I coded a portion of my EA to close half my position when I get to TP1 and move my stop to breakeven + a certain amount of pips. And it does...over and over again! It closes half my position, then on the next tick, it closes half, and half, until it gets down to 0.01 lot size. And I'm not sure why. As part of my if hierarchy, i have it stop if the Stop Loss has been moved. It should close half the position, move the stop loss (which it does), and then stop. Here's the code:
(I didn't include the Sell side, but you see what it would be.) So as it's executing, first it closes half, then it modifies the remaining order to move the SL, then the next time it does the loop, it should find that the OrderPrice is no longer > OrderStopLoss, so it should stop. Yet in reality it seems like it closes all my positions by half, then moves the SL. Though it could just be my human perception of what's going on, being too slow to see what's actually happening in real time.
The only thing that I can think of is that the server is executing the OrderClose faster than the OrderModify, so that it's looping through before my Stop Loss can be moved by the server. Maybe I should put a sleep() statement at the end?
Anyway, can anyone see if I'm missing something simple & obvious?
Thanks,
Pepper...
Inserted Code
void CloseHalfTrade() { double tp2 = MathAbs(OrderTakeProfit() - OrderOpenPrice()); double tp1 = NormalizeDouble(tp2 * 0.5, Digits); double breakevenPips = PipsToAddToBreakeven / GetPipValue(); //---- for(int b=OrdersTotal()-1; b>=0; b--) { if(OrderSelect(b, SELECT_BY_POS, MODE_TRADES)) if(OrderSymbol()==ChartSymbol()) if(OrderType()==OP_BUY) if(Bid-OrderOpenPrice()>=tp1) if(OrderOpenPrice()>OrderStopLoss()) { OrderClose(OrderTicket(), OrderLots()/2, Bid, 3, clrNONE); OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice() + breakevenPips, OrderTakeProfit(), 0,clrNONE); Alert(OrderSymbol() + " TP1 Hit, closing half trade & moving stop to BE+ 2 pips"); SendNotification(OrderSymbol() + " TP1 Hit, closing half trade & moving stop to BE+ 2 pips"); } }
The only thing that I can think of is that the server is executing the OrderClose faster than the OrderModify, so that it's looping through before my Stop Loss can be moved by the server. Maybe I should put a sleep() statement at the end?
Anyway, can anyone see if I'm missing something simple & obvious?
Thanks,
Pepper...