Reputation: 41
Should be the easiest strategy in the world to code, yet I can't seem to figure it out. I just want a simple swing trade tester, where I buy at close, and sell at open the next morning. Here's what I've got.
//@version=4
strategy(title = "Buy the Close, Sell the Open", default_qty_value=100, overlay=true)
strategy.entry(id = "Entry at Close", when = close, long = true)
strategy.close(id = "Exit at Open", when = open)
I've also tried this
//@version=4
strategy(title = "Buy the Close, Sell the Open", shorttitle = "BtCStO", default_qty_value=100, overlay=true)
timeResolution = input("D", type=input.resolution)
priceClose = security(syminfo.tickerid, timeResolution, close[1])
priceOpen = security(syminfo.tickerid, timeResolution, open[1])
strategy.entry(id = "Entry at Close", when = priceClose, long = true)
strategy.close(id = "Exit at Open", when = priceOpen)
Edit: I've gone in and added some if statements and simplified it a bit I think, and added a plot line to make sure the data is actually being pulled. I went all the way back on the chart and found that it did actually enter a position, although it appears to be entering at open, not close, and then it just never exits the position. I suspect it's confused because it's trying to do both on the same day, rather than buying the close on day 1, and selling on day 2, then repeating the buy the close on day 2, and selling the open on day 3 and so on.
Updated code example:
//@version=4
strategy(title = "Buy the Close, Sell the Open", shorttitle = "BtCStO", default_qty_value=100, overlay=true)
if close
strategy.entry(id = "Entry at Close", long = true)
if open
strategy.close(id = "Exit at Open")
plot(close)
plot(open)
Here's a quick screen grab of what I'm seeing.
Upvotes: 1
Views: 1416
Reputation: 1
Not sure if this was answered, but I too searched a lot and finally found the solution. You need to do the following:
strategy.close("Buy", immediately = true)
setting immediately = true
does the trick
Here's my reference implementation if interested:
https://in.tradingview.com/script/3ssgkN7R-Open-Close-Strategy/
Upvotes: 0
Reputation: 41
It only took me all day to figure it out, but indeed the answer was pretty simple, I failed to match the id's, as the close needs to match the open. Since I had the wrong id, it never closed the initial position, and thus never opened a new one.
strategy(title = "Buy the Close, Sell the Open", shorttitle = "BtCStO", default_qty_value=100, overlay=true)
if close
strategy.entry(id = "BtCStO", long = true
if open
strategy.close(id = "BtCStO")
Upvotes: 2