This code snippet demonstrates how to implement a dynamic trailing stop mechanism for automated trading strategies. A trailing stop is used to protect gains by enabling a trade to remain open and continue to profit as long as the price is moving in the favorable direction, but closes the trade if the price changes direction by a specified amount.
// trailing stop function
trailingstart = 10 //10 trailing will start @trailinstart points profit
trailingstep = 5 //5 trailing step to move the "stoploss"
//reset the stoploss value
IF NOT ONMARKET THEN
newSL=0
ENDIF
//manage long positions
IF LONGONMARKET THEN
//first move (breakeven)
IF newSL=0 AND HIGH-tradeprice(1)>=trailingstart*pipsize THEN
//close --> HIGH
newSL = tradeprice(1)+trailingstep*pipsize
// new coding
IF newSL > close THEN
//if current closing price is < new SL then exit IMMEDIATELY!
SELL AT MARKET
ENDIF
// end new coding
ENDIF
//next moves
IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
newSL = newSL+trailingstep*pipsize
// new coding
IF newSL > close THEN
//if current closing price is < new SL then exit IMMEDIATELY!
SELL AT MARKET
ENDIF
// end new coding
ENDIF
ENDIF
//manage short positions
IF SHORTONMARKET THEN
//first move (breakeven)
IF newSL=0 AND tradeprice(1)-LOW>=trailingstart*pipsize THEN
//close --> LOW
newSL = tradeprice(1)-trailingstep*pipsize
// new coding
IF newSL < close THEN
//if current closing price is > new SL then exit IMMEDIATELY!
EXITSHORT AT MARKET
ENDIF
// end new coding
ENDIF
//next moves
IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
newSL = newSL-trailingstep*pipsize
// new coding
IF newSL < close THEN
//if current closing price is > new SL then exit IMMEDIATELY!
EXITSHORT AT MARKET
ENDIF
// end new coding
ENDIF
ENDIF
//stop order to exit the positions
IF newSL>0 THEN
SELL AT newSL STOP
EXITSHORT AT newSL STOP
ENDIF
The code is structured to manage both long and short positions in the market:
This approach ensures that the trailing stop adjusts dynamically based on price movements, aiming to protect gains while allowing profitable positions to run.
Check out this related content for more information:
https://www.prorealcode.com/topic/modified-nicolas-trailing-stop-code/#post-73306
Visit Link