Skip to content

Instantly share code, notes, and snippets.

@ego008
Forked from matthewkastor/mql Modify Open Order.mq4
Created October 21, 2021 02:22
Show Gist options
  • Save ego008/c4b5815bbd44aceaf4ca85dd3878ca85 to your computer and use it in GitHub Desktop.
Save ego008/c4b5815bbd44aceaf4ca85dd3878ca85 to your computer and use it in GitHub Desktop.
function that moves the stop loss and take profit levels if it is favorable to the open position on metatrader 4
// select the order http://docs.mql4.com/trading/orderselect
// OrderSelect(......
// then this method will work on the order selected
// bool result = ModifyOpenOrder(0.00300, 0.00900);
// returns true if the order was modified successfully
// returns false if the order didn't need modification or if modification failed
bool ModifyOpenOrder(double stopLossPips, double pipsProfit){
bool modify = false;
double takeProfit;
double stopLoss;
int orderType = OrderType();
if(orderType == OP_BUY) {
takeProfit = NormalizeDouble(Bid + pipsProfit, Digits);
stopLoss = NormalizeDouble(Bid - stopLossPips, Digits);
if(OrderStopLoss() < stopLoss) modify = true;
}
if(orderType == OP_SELL) {
takeProfit = NormalizeDouble(Ask - pipsProfit, Digits);
stopLoss = NormalizeDouble(Ask + stopLossPips, Digits);
if(OrderStopLoss() > stopLoss) modify = true;
}
if(modify == true) {
if(OrderProfit() < 0) {
takeProfit = OrderTakeProfit();
}
bool result = OrderModify(OrderTicket(),OrderOpenPrice(),stopLoss,takeProfit,0,clrNONE);
if(!result) {
Print("Error in OrderModify. Error code=",GetLastError());
}
return result;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment