Working with positions
All script positions are accessed through the ISecurity.Positions property.
For each position, a signal name is assigned. Only one line item with the same name can be active at a time.
For example, if you created a position "LE" and did not close it, then you cannot create a second position with the same name.
Position opening
To open positions, use the methods sec.Positions.BuyXXX (...) for buying and sec.Positions.SellXXX (...) for selling.
Buy:
sec.Positions.BuyAtMarket(i + 1, 2, "LE"); // Buy two market contracts at the next bar.
sec.Positions.BuyAtPrice(i + 1, 2, 65000, "LE"); // Set a limit order for the purchase of two contracts on the next bar at a price of 65,000.
sec.Positions.BuyIfGreater(i + 1, 2, 65000, "LE"); // Place a conditional order to buy two contracts on the next bar if the price is above 65,000.
sec.Positions.BuyIfLess(i + 1, 2, 65000, "LE"); // Place a conditional order to buy two contracts on the next bar if the price is below 65,000.Sell:
sec.Positions.SellAtMarket(i + 1, 2, "LE"); // Sell two market contracts at the next bar.
sec.Positions.SellAtPrice(i + 1, 2, 65000, "LE"); // Set a limit order for the sale of two contracts at the next bar at a price of 65,000.
sec.Positions.SellIfGreater(i + 1, 2, 65000, "LE"); // Place a conditional order to sell two contracts at the next bar if the price is 65,000.
sec.Positions.SellIfLess(i + 1, 2, 65000, "LE"); // Place a conditional order to sell two contracts on the next bar if the price is below 65,000Getting position
A commonly used method to get the position of GetLastActiveForSignal (...), example:
The method searches for an active position with the name "LE" and returns it; if there are no positions, the method will return null.
There are also other methods for getting positions, they are all written like this: sec.Positions.GetXXX (...).
Position change
To change the position size, use the pos.ChangeAtXXX (...) methods, and the size of the new position is transferred.
For example, to increase a long position by 2 market contracts, you need to write pos.ChangeAtMarket (i + 1, pos.Shares + 2, "LX"); Here pos.Shares shows the current number of position contracts, and when we pass pos.Shares + 2, this means that we need to increase the position by 2 contracts.
If you pass a negative value, for example -3, then the position will turn into a short one with three contracts.
Examples:
Closing position
To close a position, use the pos.CloseAtXXX (...) methods.
Examples:
It is important to note that methods that close a position by condition (CloseAtPrice, CloseAtProfit, CloseAtStop) must be set on each bar until the position closes, otherwise TSLab will remove the closing order on the exchange.
For example, we’ll write a script that will buy after a growing candle in the market and set a stop of 200 points and a take of 400 points:

Last updated
Was this helpful?