Two Stage ATR Based Trailing Stop

Two Stage ATR Based Trailing Stop

// ================trailing atr stop VIRTUAL==================
if enabletsvir then
//
once stepsvir=0
once minatrdistvir=0
once atrtrailingperiodvir    = 2  // atr parameter
once minstopvir              = 10   // minimum  distance
if barindex=tradeindex then
trailingstoplongvir    = 5  // trailing stop atr distance
trailingstopshortvir    = 5   // trailing stop atr distance
else
if longonmarket then
if newslvir>0 then
if trailingstoplongvir>minatrdistvir then
if newslvir>newslvir[1] then
trailingstoplongvir=trailingstoplongvir
else
trailingstoplongvir=trailingstoplongvirstepsvir
endif
else
trailingstoplongvir=minatrdistvir
endif
endif
endif
if shortonmarket then
if newslvir>0 then
if trailingstopshortvir>minatrdistvir then
if newslvir<newslvir[1] then
trailingstopshortvir=trailingstopshortvir
else
trailingstopshortvir=trailingstopshortvirstepsvir
endif
else
trailingstopshortvir=minatrdistvir
endif
endif
endif
endif
//
atrtrailvir=averagetruerange[atrtrailingperiodvir]((close/10)*pipsize)/1000
trailingstartlvir=round(atrtrailvir*trailingstoplongvir)
trailingstartsvir=round(atrtrailvir*trailingstopshortvir)
tglvir=trailingstartlvir
tgsvir=trailingstartsvir
//
if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
maxpricevir=0
minpricevir=close
newslvir=0
endif
//
if longonmarket then
maxpricevir=max(maxpricevir,close)
if maxpricevirtradeprice(1)>=tglvir*pointsize then
if maxpricevirtradeprice(1)>=minstopvir then
newslvir=maxpricevirtglvir*pointsize
else
newslvir=maxpricevirminstopvir*pointsize
endif
endif
endif
//
if shortonmarket then
minpricevir=min(minpricevir,close)
if tradeprice(1)minpricevir>=tgsvir*pointsize then
if tradeprice(1)minpricevir>=minstopvir then
newslvir=minpricevir+tgsvir*pointsize
else
newslvir=minpricevir+minstopvir*pointsize
endif
endif
endif
//
if longonmarket and close <newslvir and newslvir>0 then
sell at market
endif
if shortonmarket and close>newslvir and newslvir>0 then
exitshort at market
endif

Leave a Comment