I am trying to set an SL and TP based on the swing high/low.
`// SL Swing
swing_low = ta.lowest(close, 10)
swing_high = ta.highest(close, 10)
long_risk = close[1] - swing_low
short_risk = swing_high - close[1]
long_tp_price = close[1] + long_risk
short_tp_price = close[1] - short_risk
//Long Position
if (long_signal)
strategy.entry("Long", strategy.long)
strategy.exit("Take Profit/Stop Loss", "Long", stop=swing_low, limit=long_tp_price)
//Short Position
if (short_signal)
strategy.entry("Short", strategy.short)
strategy.exit("Take Profit/Stop Loss", "Short", stop=swing_high, limit=short_tp_price)`
I am not getting the desired results as per below, do I have a problem with my calculation? The below should have been a winning trade instead it closed immediately.
First, change swing_low & swing_high
swing_low = ta.lowest(low, 10)
swing_high = ta.highest(high, 10)
For long debug, plot lines swing_low & long_tp_price
You can set the levels with ta.valuewhen()
// SL Swing
swing_low = ta.valuewhen(long_signal, ta.lowest(low, 10), 0)
swing_high = ta.valuewhen(short_signal, ta.highest(high, 10), 0)
long_risk = close[1] - swing_low
short_risk = swing_high - close[1]
long_tp_price = ta.valuewhen(long_signal, close[1] + long_risk, 0)
short_tp_price = ta.valuewhen(short_signal, close[1] - short_risk, 0)
//Long Position
if (long_signal)
strategy.entry("Long", strategy.long)
strategy.exit("Take Profit/Stop Loss", "Long", stop=swing_low, limit=long_tp_price)
//Short Position
if (short_signal)
strategy.entry("Short", strategy.short)
strategy.exit("Take Profit/Stop Loss", "Short", stop=swing_high, limit=short_tp_price)
plot (
strategy.position_size > 0 ? swing_low : na,
'swing_low',
linewidth = 2,
color = color.new(color.maroon, 0),
style = plot.style_steplinebr)
plot (
strategy.position_size > 0 ? long_tp_price : na,
'long_tp_price',
linewidth = 2,
color = color.new(color.teal, 0),
style = plot.style_steplinebr)
plot (
strategy.position_size < 0 ? swing_high : na,
'swing_high',
linewidth = 2,
color = color.new(color.maroon, 0),
style = plot.style_steplinebr)
plot (
strategy.position_size < 0 ? short_tp_price : na,
'short_tp_price',
linewidth = 2,
color = color.new(color.teal, 0),
style = plot.style_steplinebr)