Hey traders! Let’s dive into how a trailing stop can really boost your trading game by moving the stop loss into profit territory, ensuring we keep our gains secured automatically.
We’ll kick things off by setting the input parameters for our trailing stop in the code:
input bool isTrailingStop = true; // Enable Trailing Stopinput int trailingStart = 15; // Trailing Start (pips)input int trailingStep = 5; // Trailing Step (pips)input int MagicNumber = 0; // Magic Number
Now, let’s set up a global variable:
// Global Variabledouble myPoint = 0.0;
When we run this Expert Advisor (EA), the OnInit() function will be executed for the first time, where we will validate and initialize our input variables:
intOnInit() { if (isTrailingStop && trailingStart <= 0){ Alert ("Parameters incorrect"); return(INIT_PARAMETERS_INCORRECT); } myPoint = GetPipPoint(Symbol()); return(INIT_SUCCEEDED); }
Every time there’s a price movement (tick) on the chart where this EA is active, the OnTick() function will be executed. Inside this function, we’ll call setTrailingStop():
voidOnTick() { //--- setTrailingStop(MagicNumber); }
Now, let’s look at the setTrailingStop() function:
void setTrailingStop(int magicNumber=0){ if (isTrailingStop==false) return; int tOrder = 0; string pair = ""; double sl = 0.0, tp = 0.0; pair = Symbol(); tOrder = OrdersTotal(); for (int i=tOrder-1; i>=0; i--){ bool hrsSelect = OrderSelect(i, SELECT_BY_POS, MODE_TRADES); if (OrderMagicNumber() == magicNumber && StringFind(OrderSymbol(), pair, 0) == 0 ){ if (OrderType() == OP_BUY){ if ( (Bid - (trailingStart * myPoint)) >= OrderOpenPrice() && (Bid - ((trailingStart+trailingStep) * myPoint) >= OrderStopLoss() ) ){ sl = NormalizeDouble(Bid - (trailingStart * myPoint), Digits()); if (!OrderModify(OrderTicket(), OrderOpenPrice(), sl, OrderTakeProfit(), 0, clrBlue)){ Print ("#", OrderTicket(), " failed to update SL"); } } } if (OrderType() == OP_SELL){ if ( (Ask + (trailingStart * myPoint)) <= OrderOpenPrice() && ( (Ask + ((trailingStart+trailingStep) * myPoint) <= OrderStopLoss() ) || OrderStopLoss() == 0.0) ) { sl = NormalizeDouble(Ask + (trailingStart * myPoint), Digits() ); if (!OrderModify(OrderTicket(), OrderOpenPrice(), sl, OrderTakeProfit(), 0, clrBlue)){ Print ("#", OrderTicket(), " failed to update SL"); } } } } //end if magicNumber }//end for }
Another essential function you’ll need is GetPipPoint():
// Function GetPipPointdouble GetPipPoint(string pair) { double point= 0.0; int digits = (int) MarketInfo(pair, MODE_DIGITS); if(digits == 2 || digits== 3) point= 0.01; elseif(digits== 4 || digits== 5) point= 0.0001; return(point); }
Got questions? Feel free to drop them in the comments below! You can also join our trading group for more insights. Check it out here: t.me/codeMQL
Don’t forget to check out our SignalForex App too!
Your support means a lot, so download the app and enhance your trading experience! You can find it here: SignalForex App

Comments 0