'Pine Script Strategy Not Showing Short Position Closes; Only Closing Long Positions
I'm trying to get each trade to close two bars after being opened. I'm using this to backtest some binary option strategies. I can't figure out why the Long positions are working, but the Short positions are not showing any closes.
Also, I want "calc_on_every_tick" to be active, but when I add "and strategy.opentrades==0" to my buy and sell signal variables, to prevent multiple Longs and Shorts on the same candle, all Long and Short signals disappear from the chart. My best guess is that this is happening because the Short positions are not being closed, but I'm not sure.
Any help is appreciated. Thanks.
barsTillClose = input.int(2, minval=1, title="Amount of Bars Till Close Position")
buy_signal = crossUp// and strategy.opentrades==0
sel_signal = crossDo// and strategy.opentrades==0
strategy.entry("Long", strategy.long, qty=1, when=buy_signal)
strategy.entry("Short", strategy.short, qty=1, when=sel_signal)
// Track the Entry Bar
entryTime = float(na)
timeClose = bool(na)
entryTime := timeClose[1] ? na : strategy.position_size[0] > strategy.position_size[1] ? bar_index : entryTime[1]
// See if we need to close
timeClose := bar_index >= entryTime+(barsTillClose-1)
strategy.close('Long', when=timeClose)
strategy.close('Short', when=timeClose)
Solution 1:[1]
You can use the strategy.opentrades.entry_bar_index() built-in to find the entry bar. There is one for time as well, among other useful values. 0 is the first open trade. I substituted some variables to make the script complete.
//@version=5
strategy("My strategy", overlay=true, margin_long=100, margin_short=100)
barsTillClose = input.int(2, minval=1, title="Amount of Bars Till Close Position")
sma1 = ta.sma(close, 21)
sma2 = ta.sma(close, 50)
crossUp = ta.crossover(sma1, sma2)
crossDo = ta.crossunder(sma1, sma2)
buy_signal = crossUp// and strategy.opentrades==0
sel_signal = crossDo// and strategy.opentrades==0
strategy.entry("Long", strategy.long, qty=1, when=buy_signal)
strategy.entry("Short", strategy.short, qty=1, when=sel_signal)
// Track the Entry Bar
entryTime = strategy.opentrades.entry_bar_index(0)
// See if we need to close
timeClose = bar_index >= entryTime+(barsTillClose-1)
strategy.close('Long', when=timeClose)
strategy.close('Short', when=timeClose)
Cheers and all the best
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bjorgum |
