Trade operations (Positions.Close)

Here is a description of methods and properties intended for managing and obtaining information about positions, orders, and deals.

Position - an uncompleted trading operation (unfinished deal). When changing the quotation of a financial instrument, the position keeps a record of the client’s funds (for write-off and crediting). 

This section describes properties and methods for working with positions

 

We send a request to close an existing open position.

Input parameters

Parameters Type Description
positionId int Position identifier positionId
Volume double Position volume we want to close in lots
isAsync bool Asynchronous mode (enabled or disabled).
Disabled by default

 

Return value

If isAsync = false (synchronous mode by default), it returns the result code of the operation:

0 Position is successfully closed
Error code If an error occurs, it returns the server error code

 

If isAsync = true (asynchronous mode)

0 The request to close the position was successfully sent to the server. It does not mean that the position has already been closed or will definitely be closed.
Error code

If an error occurs, it returns the error code received on the client. The codes match the server error codes.

 

//------------------------------------
// Close all positions on the account
//------------------------------------
private void CloseAllPos()
{
 string line = "";
 int err = 0;
 line = line + "Positions Count = " + GetPositionCount().ToString() + Environment.NewLine;
 if (GetPositionCount() > 0)
 for (var i = Positions.Count - 1; i >= 0; i--) {
 Position pos = Positions.Find(Positions[i].PositionId);
 if (pos != null) {
 err = Positions.Close(pos.PositionId, pos.Volume);
 if (err == 0) {
 line = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss:fff") + " Closed Success, PositionId = " + pos.PositionId.ToString() + " CurrentProfit:" + pos.Profit.ToString() + Environment.NewLine;
 Print(mCommonLog, line);
 } else {
 line = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss:fff") + " Closed Failed, ServerErrorCode = " + err.ToString() + Environment.NewLine;
 Print(mCommonLog, line);
 }
 }
 }
 } else {
 line = DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss:fff") + " Positions not found! ";
 Print(mCommonLog, line);
 }
}
//-------------------------------------------
// Count the number of open positions
//-------------------------------------------
private int GetPositionCount()

 int poc = 0;
 for (var i = Positions.Count - 1; i >= 0; i--) {
 Position pos = Positions.Find(Positions[i].PositionId);
 if (pos != null) {
 if ((pos.PositionType == (int)PositionType.Buy || pos.PositionType == (int)PositionType.Sell)) {
 poc++;
 }
 }
 }
 return(poc);
}