I think there’s an error in above code, lines 14 and 18 appear to set newSL with none zero value, however, lines 35 and 36 look for a none zero newSL and exits.
Similar scenario for the short.
I played around with some code to display the trailing stop (TS) to see what’s what using a out of thin air entry condition.
I added in a default TS value , TSdefaultAmt, because zero messes with the charts auto scale with graphonprice.
When the yellow line is horizontal, it represents the TS start threshold level above the entry price , TSstartLvl.
When price closes above, the TS is active, TSactive = 1, which triggers the TS.
After entry but before TS triggered, The horizontal orange line represent the default TS.
After being triggered, TS jumps to the startprice + step amount.
Subsequent bars increment the TS ‘TSL’ by the step amount.
If close triggers the exit condition, the trade is exited.
If low hits the default stop level it is also exited.
As I worked through I graphed some variables.
Some are true/false and some are number values.
Using cursor values…
The values are scaled within a ‘1’ range and +n value offset then to the ‘y’ scale.
The *0.75 are the booleans where the integer value is false and value+0.75 is true.
The*0.00001 are values, just look at decimal portion and crop off last digit.
see what you think.
entryCondition = date = 20241016 and opentime >= 000000
TSdefaultAmt = 30 // TS default stop level
TSstartAmt = 15 // TS threshold setting amount
TSstepAmt = 1 // TS step amount per step
// difference between Current price and last Trade entry
CTdiff = close-tradePrice[1]
// get the TS threshold level
TSstartLvl = tradeprice[1] + TSstartAmt
// set a default TS stop
TSdefaultL = close - TSdefaultAmt
// new TS step
CmTSL = Close - TSL
// not on market
if not LongonMarket then
LONG = 0
TSactive = 0
// enter Market
if entryCondition then
buy 1 contract at market
// set a default TS
TSL = TSdefaultL
endif
endif
// on Market
if LongonMarket then
LONG = 1
if close >= TSstartLvl and TSactive = 0 then
TSactive = 1
TSL = tradePrice[1] + TSstepAmt
endif
if TSactive =1 and CmTSL >= TSstepAmt then
TSL = TSL + TSstepAmt
endif
// if close below TSL
if close <= TSL then
sell at market
endif
// exit if low hits default stop level
if low <= tradePrice[1] - TSdefaultAmt then
sell at market
endif
endif
// display
if onmarket then
graphonprice TSstartLvl as"TSstartLvl" coloured("yellow")
graphonprice TSL as"TSL" coloured("orange")
endif
graph TSactive * 0.75 + 5 as"TSactive"
graph TSstartLvl * 0.00001 + 4 as"TSstepLvl"
graph TSstepAmt * 0.00001 + 3 as"TSstepAmt"
graph TSstartAmt * 0.00001 + 2 as"TSstartAmt"
graph TSdefaultAmt * 0.00001 + 1 as"TSdefaultAmt"
graph LONG * 0.75 + 0 as"LONG"