Skip to content

Instantly share code, notes, and snippets.

@matthewkastor
Last active October 21, 2021 02:22
Show Gist options
  • Save matthewkastor/dc8a3fea18cf26119287 to your computer and use it in GitHub Desktop.
Save matthewkastor/dc8a3fea18cf26119287 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;
}
@WinstonN
Copy link

WinstonN commented Mar 4, 2018

Nice one! Thanks for posting this!
Are you still coding for forex?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment