This code snippet demonstrates how to implement a trailing stop mechanism in percentage terms rather than fixed points or pips. A trailing stop is a dynamic stop-loss order that adjusts as the price of an asset moves in favor of the trade, helping to protect gains or limit losses.
trailingPercent = 0.5 //trailing stop function
if onmarket then
trailingstart = tradeprice(1)*(trailingpercent/100) //trailing will start @trailinstart points profit
trailingstep = tradeprice(1)*(trailingpercent/100) //trailing step to move the "stoploss"
endif
//reset the stoploss value
IF NOT ONMARKET THEN
newSL=0
ENDIF
//manage long positions
IF LONGONMARKET THEN
//first move (breakeven)
IF newSL=0 AND close-tradeprice(1)>=trailingstart THEN
newSL = tradeprice(1)+trailingstep
ENDIF
//next moves
IF newSL>0 AND close-newSL>trailingstep THEN
newSL = newSL+trailingstep
ENDIF
ENDIF
//manage short positions
IF SHORTONMARKET THEN
//first move (breakeven)
IF newSL=0 AND tradeprice(1)-close>=trailingstart THEN
newSL = tradeprice(1)-trailingstep
ENDIF
//next moves
IF newSL>0 AND newSL-close>trailingstep THEN
newSL = newSL-trailingstep
ENDIF
ENDIF
//stop order to exit the positions
IF newSL>0 THEN
SELL AT newSL STOP
EXITSHORT AT newSL STOP
ENDIF
//put the first stoploss if onmarket and newSL=0 and activatestoploss then
set stop loss trailingstart endif
The code snippet above is structured to manage both long and short positions using a trailing stop calculated as a percentage of the trade price. Here’s a step-by-step breakdown:
This approach helps in managing trades more dynamically, adjusting protections based on market movements and thus potentially locking in profits while limiting losses.
Check out this related content for more information:
https://www.prorealcode.com/topic/cannot-set-trailing-stop-as-through-ig/#post-83701
Visit Link