Search code examples
pine-scriptpine-script-v5tradingview-apipine-script-v4

Single strategy that can buy/sell two symbols


New to Pine script, but reasonably experienced with trading and programming in other areas.

I’m wanting to test an arbitrage strategy which switches between two tickers - vis

Indicator Case 1 sell all, buy XXX

Indicator Case 2 Sell all, buy YYY

NB the indicator is always based on XXX

Seems hard to do either in v4 or v5 - strategy.entry doesn’t support the symbol parameter in v5, and v4 errors out when passing the symbol parameter into the strategy.entry function.

My chart does have both tickers and the indicator plotting.

Am I missing something? A working example would be awesome ;-)

I tried various suggestions made by ChatGPT, which ended up being less than helpful, and also direct entry of the ticker symbol in the v4 version vs using a declared variable and calling that.

Seems the symbol parameter in v4 strategy.entry won’t take a value. Is it broken?

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DJ_Papastanley

//@version=4
strategy(title="AAPL MSFT Arbitrage strategy", shorttitle="AAPL MSFT Arb")
// Define the ticker symbol for the stock
//ticker = "AAPL"
// Chart base ticker is AAPL 

// Define the Parabolic SAR indicator
sar = sar(0.02, 0.03, 0.2)

// Define the MSFT symbol
// MSFT = ticker + ":MSFT"
// ticker2 = "MSFT"

// Buy signal: SAR turns negative
sell_signal = crossover(close, sar) and sar < close

// Sell signal: SAR turns positive
buy_signal = crossunder(close, sar) and sar > close

// Plot the Parabolic SAR indicator on the chart
plot(sar, color=color.blue)

// Execute the trade when the buy or sell signal is generated
// NB relative to AAPL as primary chart ticker
if buy_signal //close the MSFT position and buy AAPL
    strategy.close_all(comment="Sell MSFT")
    strategy.entry("Buy AAPL", strategy.long, qty=100, comment="Buy AAPL")

if sell_signal //close the AAPL position and buy MSFT
    strategy.close_all(comment="Sell AAPL")
    strategy.entry("Buy MSFT", strategy.long, symbol="MSFT", qty=100, comment="Buy MSFT")


Solution

  • Not possible, Pine Script strategies can only execute orders on the currently selected symbol on the chart. Note that there is no symbol= parameter in the Pine syntax in the entry/exit/close commands of a strategy.

    You can access the data from another symbol using the request.security() function, but not to execute the orders on a second symbol.

    Check out the Pine Script Strategy guide in the User Manual: https://www.tradingview.com/pine-script-docs/en/v5/concepts/Strategies.html