I have attached the code for a function I am using to move the stop loss to break even. I do not see any issue with the code, but I am obviously missing something because it is not working. It is supposed to iterate through all open positions, and if a position is 5 pips in profit the stop loss is to be moved to breakeven. Here is the code:
bool MoveBE()
{
for (int i = 0; i < PositionsTotal(); i++)
{
ulong ticketNum = PositionGetTicket(i);
if (PositionSelectByTicket(ticketNum) && breakEven > 0)
{
Print("MoveBE() function called");
long openPositionType = PositionGetInteger(POSITION_TYPE);
double currentStop = PositionGetDouble(POSITION_SL);
double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
string symbol = PositionGetString(POSITION_SYMBOL);
//The point value for gold is set to .01 but it should be .1
//double pointValue = SymbolInfoDouble(symbol, SYMBOL_POINT);
double pointValue = 0.1 ;
double currentProfit;
if (openPositionType == POSITION_TYPE_BUY)
{
currentProfit = SymbolInfoDouble(symbol, SYMBOL_BID) - openPrice;
Print("Debug: currentProfit =", currentProfit);
if ((currentStop < openPrice || currentStop == 0) && currentProfit >= breakEven * pointValue)
{
currentStop = openPrice;
bool modified = trade.PositionModify(ulong(ticketNum), currentStop, PositionGetDouble(POSITION_TP));
if (modified)
{
modificationCount++;
Print("Stop moved to BE for ticket ", ticketNum, " Count: ", modificationCount);
return true;
}
else
{
Print("Failed to move stop to BE for ticket ", ticketNum);
return false;
}
}
}
else if (openPositionType == POSITION_TYPE_SELL)
{
currentProfit = openPrice - SymbolInfoDouble(symbol, SYMBOL_ASK);
if ((currentStop > openPrice || currentStop == 0) && currentProfit >= breakEven * pointValue)
{
currentStop = openPrice;
bool modified = trade.PositionModify(ulong(ticketNum), currentStop, PositionGetDouble(POSITION_TP));
if (modified)
{
modificationCount++;
Print("Stop moved to BE for ticket ", ticketNum, " Count: ", modificationCount);
return true;
}
else
{
Print("Failed to move stop to BE for ticket ", ticketNum);
return false;
}
}
}
}
}
return false;
}
Any help would be greatly appreciated and I can provide the rest of the code as well.
I tried to add debug codes to monitor the current profit for open positions but even that is not working properly.