Positions.Close
We send a request to close an existing open position.
int err = Positions.Close(int PositionId, int Volume, bool isAsync=false);
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 |
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. |
If an error occurs, it returns the error code received on the client. The codes match the server error codes. |
Example:
//------------------------------------
// 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);
}