This code snippet demonstrates how to implement a dynamic trailing stop strategy for both long and short positions using the Average True Range (ATR) in ProBuilder. The trailing stop adjusts based on the ATR, which measures market volatility.
// trailing stop atr [adjusted reset]
once enablets=1
once displayts=1
if enablets then
// once steps=0.05
once minatrdist=3
once atrtrailingperiod = 14 // atr parameter value
once minstop = 10 // minimum trailing stop distance
if barindex=tradeindex then
trailingstoplong = 5 // trailing stop atr relative distance
trailingstopshort = 5 // trailing stop atr relative distance
elsif prezzouscita>0 then
if longonmarket then
if trailingstoplong>minatrdist then
if prezzouscita>prezzouscita[1] then
trailingstoplong=trailingstoplong
else
trailingstoplong=trailingstoplong-steps
endif
else
trailingstoplong=minatrdist
endif
endif
if shortonmarket then
if trailingstopshort>minatrdist then
if prezzouscita=tgl*pointsize then
if maxprice-tradeprice(1)>=minstop then
prezzouscita=maxprice-tgl*pointsize
else
prezzouscita=maxprice-minstop*pointsize
endif
endif
// if shortonmarket then
minprice=min(minprice,close)
if tradeprice(1)-minprice>=tgs*pointsize then
if tradeprice(1)-minprice>=minstop then
prezzouscita=minprice+tgs*pointsize
else
prezzouscita=minprice+minstop*pointsize
endif
endif
// if onmarket and prezzouscita>0 then
exitshort at prezzouscita stop
sell at prezzouscita stop
endif
if displayts then
graphonprice prezzouscita coloured(0,0,255,255) as "trailingstop atr"
endif
endif
Explanation of the Code:
This implementation helps in managing risk by dynamically adjusting the stop loss levels based on market conditions, providing a more flexible and potentially more effective risk management tool.
Check out this related content for more information:
https://www.prorealcode.com/topic/vectorial-dax-m5/page/39/#post-114921
Visit Link