Search code examples
pine-scriptpine-script-v5

Pinescript compilation error of version5 If variables


compilation error line 27 no viable alternative at input 'if'. Try to add line "//@version2 to the top of your script.

I have exhausted my means to correct this script. Any suggestions?

//@version=5
// This script is an example of a simple strategy that buys on a long entry signal
// and sells on a short entry signal. It uses the built-in long_entry and short_entry
// signals provided by TradingView.


// Load data for the S&P 500 ETF and apply the strategy
symbol("SPY", daily)
strategy("SPY Daily Trade")

// Define input variables
emaLength = input(title="EMA Length:", type=integer, defval=50)
stopLoss = input(title="Stop Loss:", type=float, defval=0.05)
takeProfit = input(title="Take Profit:", type=float, defval=0.1)

// Calculate the exponential moving average
ema = ema(close, emaLength)

// Plot the exponential moving average
plot(ema, color=blue)

// Buy when the stock price crosses above the EMA
buyCondition = crossover(close, ema)

// Sell when the stock price crosses below the EMA
sellCondition = crossunder(close, ema) 

// Set stop loss and take profit levels
stopLossLevel = close * (1 - stopLoss)
takeProfitLevel = close * (1 + takeProfit)

// Enter a long position if the buy condition is met
if buyCondition 
    strategy.entry("Long", strategy.long, stop=stopLossLevel, limit=takeProfitLevel)

// Enter a short position if the sell condition is met
if sellCondition
    strategy.entry("Short", strategy.short, stop=takeProfitLevel, limit=stopLossLevel)

// Close the position if the opposite condition is met
if strategy.position_size != 0 and (buyCondition or sellCondition)
    strategy.close()

I tried correcting the if with supporting than statements. I also removed the declared variable and wrote it out with no success.


Solution

  • You were close buddy -

    A few points:

    • I've changed some code to meet Pine v5 specs
    • You don't need to include symbol info, just use the ticker and timeframe you want
    • I've changed your SL/TP inputs so you can enter a % value rather than decimal value
    • You need a SL/TP for both Long and Short trades (that's 4 values in total)
    • These SL/TP values should be calculated from strategy.position_avg_price rather than close - The problem with close is it will get updated on every new bar!
    • Updated your strategy.exit functions to suit

    I hope this all helps

    For more info on Stop Loss and Take Profits check out some code I've written on Tradingview..

    https://www.tradingview.com/script/00WHGEoc-Fixed-Percent-Stop-Loss-Take-Profit/ https://www.tradingview.com/script/bVkqAx0s-Percent-Trailing-Stop/

    I've also written some code for creating SL/TP & Trailing tops within Study scripts (now called Indicator scripts) :)

    //@version=5
    
    //JUST ADD THIS STRATEGY TO YOUR CHART LAYOUT WITH APPROPRIATE TICKER AND TIMEFRAME
    //symbol("SPY", daily)??
    strategy("SPY Daily Trade", overlay=true)
    
    // Define input variables
    emaLength = input.int(title="EMA Length:", defval=50)
    stopLoss = input.float(title="Stop Loss %:", defval=5) / 100
    takeProfit = input.float(title="Take Profit %:", defval=5) / 100
    
    // Calculate the exponential moving average
    ema = ta.ema(close, emaLength)
    
    // Plot the exponential moving average
    plot(ema, color=color.blue)
    
    // Buy when the stock price crosses above the EMA
    buyCondition = ta.crossover(close, ema)
    
    // Sell when the stock price crosses below the EMA
    sellCondition = ta.crossunder(close, ema) 
    
    // Set stop loss and take profit levels
    longStop = strategy.position_avg_price * (1 - stopLoss)
    shortStop = strategy.position_avg_price * (1 + stopLoss)
    shortTake = strategy.position_avg_price * (1 - takeProfit)
    longTake = strategy.position_avg_price * (1 + takeProfit)
    
    // Enter a long position if the buy condition is met
    if buyCondition 
        strategy.entry("Long", strategy.long)
    
    // Enter a short position if the sell condition is met
    if sellCondition
        strategy.entry("Short", strategy.short)
    
    // Close the position if the opposite condition is met
    if strategy.position_size > 0 
        strategy.exit(id="Close Long", stop=longStop, limit=longTake)
    if strategy.position_size < 0 
        strategy.exit(id="Close Short", stop=shortStop, limit=shortTake)