Pine Editor Help - Sell One Security When Another Rallies

Viewed 20

I am trying to write a Pine script that will do the following:

  1. Start 100% long AAPL
  2. If SPY rallies 5% in a week, then sell 100% long in AAPL
  3. 2 weeks later, go long 100% AAPL (end of bar)

This is what I have so far, but when I go to "List of trades" there's nothing there:

//@version=5
strategy("Sell AAPL when SPY rally", initial_capital =1000)

strategy.entry("long", strategy.long, 1000)

SPY_close = request.security("SPY", "W", close)
SPY_open = request.security("SPY", "W", open)

price_change = SPY_close / SPY_open

if price_change > 1.10
    strategy.close("sell", qty=1000)
    
twobarsback = price_change[2]
if twobarsback >1.10
    strategy.entry("long", strategy.long, 1000)
    
plot(price_change)
1 Answers

That's because a trade is made of an entry and exit You did the entry, now you need to add an exit/close logic using either the strategy.exit() or strategy.close() function Once you'll do that, you'll see trades in the "List of Trades"

Related