I build a breakout strategy in Pine Script:
- If the close of the current bar is higher than the highest high of the last 100 bars, go long
- If the close of the current bar is lower than the lowest low of the last 50 bars, go short
- I added a take profit of 25 ticks
- No two trades in a row in the same direction
So if it hits the take profit of a long position it closes and waits for a short signal. If it doesn’t hit the take profit the trade is reversed in the event of a short signal. Vice versa for a short trade. It works well, except when the strategy is entered and closed at the same bar due to a take profit. It then opens a new trade in the same direction if the long/short condition is valid (see screenshot below).
I cannot figure out how to avoid this. I’ve tried several combinations with strategy.opentrades.*, *profit, bar_index variables etc. trying to check if the last bar was a take profit or how many bars are between the last take profit and the new entry, but I cannot figure out the right combination. Or maybe there’s an easier way.
Here’s the code:
//@version=5
strategy(title="Breakout", overlay = true, process_orders_on_close = false)
periodhh = input(100)
periodll = input(50)
reverse = input(false, title="Trade reverse")
hh = ta.highest(periodhh)
ll = ta.lowest(periodll)
pos=0
pos := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(pos[1], 0)
if (pos==1 and pos[2]!=1)
strategy.entry("Long", strategy.long)
strategy.exit("Take Profit", profit=25)
if (pos==-1 and pos[2]!=-1)
strategy.entry("Short", strategy.short)
strategy.exit("Take Profit", profit=25)
the number of bars back to pos, should be 1
if (pos==1 and pos[1]!=1)
Try:
//@version=5
strategy(title="Breakout", overlay = true, process_orders_on_close = false)
periodhh = input(100)
periodll = input(50)
reverse = input(false, title="Trade reverse")
hh = ta.highest(periodhh)
ll = ta.lowest(periodll)
pos=0
pos := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(pos[1], 0)
if (pos==1 and pos[1]!=1)
strategy.entry("Long", strategy.long)
strategy.exit("Take Profit", profit=25)
if (pos==-1 and pos[1]!=-1)
strategy.entry("Short", strategy.short)
strategy.exit("Take Profit", profit=25)
plot (
hh,
'hh',
linewidth = 2,
color = color.new(color.gray, 0),
style = plot.style_line)
plot (
ll,
'll',
linewidth = 2,
color = color.new(color.silver, 0),
style = plot.style_line)
plot(
pos,
"pos",
editable = false, display = display.data_window)
1