pine-scriptpine-script-v5tradingview-apialgorithmic-tradingpine-script-v4

I am merging the RSI and VWAP codes to create a AI bot. The error is - The 'strategy.exit' function does not have an argument with the name 'when'


I am new to pinescript/ coding/ AI/ trading and am using chatGPT to sort of gain an understanding of things.

I am merging the VWAP and RSI code to create an AI strategy. I come to the same error constantly which is "The 'strategy.exit' function does not have an argument with the name 'when'", chatGPT would change it to condition and I would get this error message "The 'strategy.exit' function does not have an argument with the name 'condition'". ChatGPT would go vice versa and not be able to solve this. Does anyone know of a solution.

The aim of my strategy is

Buy Condition: The price crosses over VWAP and RSI reaches 25. Close Buy: The trade closes when RSI reaches 30. Short Condition: The price crosses below VWAP and RSI reaches 65. Close Short: The trade closes when RSI reaches 70.

I will back test and adjust this as I go. These parameters are not definitive or thought to give even a 1% gain, but a 100% loss until tested and seen otherwise.

RSI and VWAP strategy code

//@version=6
indicator(title="VWAP and RSI Strategy", shorttitle="VWAP RSI Strategy", overlay=true)

// --- VWAP Code ---
cumulativePeriod = input.int(30, title="VWAP Period") 

typicalPrice = (high + low + close) / 3
typicalPriceVolume = typicalPrice * volume
cumulativeTypicalPriceVolume = ta.cum(typicalPriceVolume) // Cumulative typical price volume
cumulativeVolume = ta.cum(volume) // Cumulative volume
vwapValue = cumulativeTypicalPriceVolume / cumulativeVolume

plot(vwapValue, title="VWAP", color=color.blue, linewidth=2)

// --- RSI Code ---
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
rsi = ta.rsi(rsiSourceInput, rsiLengthInput)

// Plot RSI on the main chart as well (if desired)
rsiPlot = plot(rsi, "RSI", color=color.purple)
rsiUpperBand = hline(70, "RSI Upper Band", color=color.red)
rsiLowerBand = hline(30, "RSI Lower Band", color=color.green)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")

// --- Strategy Conditions ---

// Buy Condition: Price crosses over VWAP and RSI reaches 25
longCondition = ta.crossover(close, vwapValue) and rsi <= 25
if longCondition
    strategy.entry("Long", strategy.long)

// Short Condition: Price crosses below VWAP and RSI reaches 65
shortCondition = ta.crossunder(close, vwapValue) and rsi >= 65
if shortCondition
    strategy.entry("Short", strategy.short)

// --- Strategy Exits ---
strategy.exit("Close Long", from_entry="Long", when=rsi >= 30)
strategy.exit("Close Short", from_entry="Short", when=rsi >= 70)

// --- Additional Plots and Strategy Settings ---
plotshape(longCondition, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
plotshape(shortCondition, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")

VWAP code used

//@version=3
study("VWAP", overlay=true)

// There are five steps in calculating VWAP:
//
// 1. Calculate the Typical Price for the period. [(High + Low + Close)/3)]
// 2. Multiply the Typical Price by the period Volume (Typical Price x Volume)
// 3. Create a Cumulative Total of Typical Price. Cumulative(Typical Price x Volume)
// 4. Create a Cumulative Total of Volume. Cumulative(Volume)
// 5. Divide the Cumulative Totals. 
//
// VWAP = Cumulative(Typical Price x Volume) / Cumulative(Volume)

cumulativePeriod = input(30, "Period")

typicalPrice = (high + low + close) / 3
typicalPriceVolume = typicalPrice * volume
cumulativeTypicalPriceVolume = sum(typicalPriceVolume, cumulativePeriod)
cumulativeVolume = sum(volume, cumulativePeriod)
vwapValue = cumulativeTypicalPriceVolume / cumulativeVolume

plot(vwapValue)

RSI code used

//@version=6
indicator(title="Relative Strength Index", shorttitle="RSI", format=format.price, precision=2, timeframe="", timeframe_gaps=true)

rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
calculateDivergence = input.bool(false, title="Calculate Divergence", group="RSI Settings", display = display.data_window, tooltip = "Calculating divergences is needed in order for divergence alerts to fire.")

change = ta.change(rsiSourceInput)
up = ta.rma(math.max(change, 0), rsiLengthInput)
down = ta.rma(-math.min(change, 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))

rsiPlot = plot(rsi, "RSI", color=#7E57C2)
rsiUpperBand = hline(70, "RSI Upper Band", color=#787B86)
midline = hline(50, "RSI Middle Band", color=color.new(#787B86, 50))
rsiLowerBand = hline(30, "RSI Lower Band", color=#787B86)
fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
midLinePlot = plot(50, color = na, editable = false, display = display.none)
fill(rsiPlot, midLinePlot, 100, 70, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100),  title = "Overbought Gradient Fill")
fill(rsiPlot, midLinePlot, 30,  0,  top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0),      title = "Oversold Gradient Fill")

// Smoothing MA inputs
GRP = "Moving Average"
TT_BB = "Only applies when 'SMA + Bollinger Bands' is selected. Determines the distance between the SMA and the bands."
maTypeInput = input.string("SMA", "Type", options = ["None", "SMA", "SMA + Bollinger Bands", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = GRP, display = display.data_window)
maLengthInput = input.int(14, "Length", group = GRP, display = display.data_window)
bbMultInput = input.float(2.0, "BB StdDev", minval = 0.001, maxval = 50, step = 0.5, tooltip = TT_BB, group = GRP, display = display.data_window)
var enableMA = maTypeInput != "None"
var isBB = maTypeInput == "SMA + Bollinger Bands"

// Smoothing MA Calculation
ma(source, length, MAtype) =>
    switch MAtype
        "SMA"                   => ta.sma(source, length)
        "SMA + Bollinger Bands" => ta.sma(source, length)
        "EMA"                   => ta.ema(source, length)
        "SMMA (RMA)"            => ta.rma(source, length)
        "WMA"                   => ta.wma(source, length)
        "VWMA"                  => ta.vwma(source, length)

// Smoothing MA plots
smoothingMA = enableMA ? ma(rsi, maLengthInput, maTypeInput) : na
smoothingStDev = isBB ? ta.stdev(rsi, maLengthInput) * bbMultInput : na
plot(smoothingMA, "RSI-based MA", color=color.yellow, display = enableMA ? display.all : display.none)
bbUpperBand = plot(smoothingMA + smoothingStDev, title = "Upper Bollinger Band", color=color.green, display = isBB ? display.all : display.none)
bbLowerBand = plot(smoothingMA - smoothingStDev, title = "Lower Bollinger Band", color=color.green, display = isBB ? display.all : display.none)
fill(bbUpperBand, bbLowerBand, color= isBB ? color.new(color.green, 90) : na, title="Bollinger Bands Background Fill", display = isBB ? display.all : display.none)

// Divergence
lookbackRight = 5
lookbackLeft = 5
rangeUpper = 60
rangeLower = 5
bearColor = color.red
bullColor = color.green
textColor = color.white
noneColor = color.new(color.white, 100)

_inRange(bool cond) =>
    bars = ta.barssince(cond)
    rangeLower <= bars and bars <= rangeUpper

plFound = false
phFound = false

bullCond = false
bearCond = false

rsiLBR = rsi[lookbackRight]

if calculateDivergence
    //------------------------------------------------------------------------------
    // Regular Bullish
    // rsi: Higher Low
    plFound := not na(ta.pivotlow(rsi, lookbackLeft, lookbackRight))    
    rsiHL = rsiLBR > ta.valuewhen(plFound, rsiLBR, 1) and _inRange(plFound[1])
    // Price: Lower Low
    lowLBR = low[lookbackRight]
    priceLL = lowLBR < ta.valuewhen(plFound, lowLBR, 1)
    bullCond := priceLL and rsiHL and plFound

    //------------------------------------------------------------------------------
    // Regular Bearish
    // rsi: Lower High
    phFound := not na(ta.pivothigh(rsi, lookbackLeft, lookbackRight))
    rsiLH = rsiLBR < ta.valuewhen(phFound, rsiLBR, 1) and _inRange(phFound[1])
    // Price: Higher High
    highLBR = high[lookbackRight]
    priceHH = highLBR > ta.valuewhen(phFound, highLBR, 1)
    bearCond := priceHH and rsiLH and phFound


plot(
     plFound ? rsiLBR : na,
     offset=-lookbackRight,
     title="Regular Bullish",
     linewidth=2,
     color=(bullCond ? bullColor : noneColor),
     display = display.pane
     )

plotshape(
     bullCond ? rsiLBR : na,
     offset=-lookbackRight,
     title="Regular Bullish Label",
     text=" Bull ",
     style=shape.labelup,
     location=location.absolute,
     color=bullColor,
     textcolor=textColor
     )

plot(
     phFound ? rsiLBR : na,
     offset=-lookbackRight,
     title="Regular Bearish",
     linewidth=2,
     color=(bearCond ? bearColor : noneColor),
     display = display.pane
     )

plotshape(
     bearCond ? rsiLBR : na,
     offset=-lookbackRight,
     title="Regular Bearish Label",
     text=" Bear ",
     style=shape.labeldown,
     location=location.absolute,
     color=bearColor,
     textcolor=textColor
     )

alertcondition(bullCond, title='Regular Bullish Divergence', message="Found a new Regular Bullish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar.")
alertcondition(bearCond, title='Regular Bearish Divergence', message='Found a new Regular Bearish Divergence, `Pivot Lookback Right` number of bars to the left of the current bar.')

Solution

  • //@version=6
    strategy("VWAP and RSI Strategy", shorttitle="VWAP RSI Strategy", overlay=true)
    
    // --- VWAP Code ---
    cumulativePeriod = input.int(30, title="VWAP Period") 
    typicalPrice = (high + low + close) / 3
    typicalPriceVolume = typicalPrice * volume
    cumulativeTypicalPriceVolume = ta.cum(typicalPriceVolume)  // Cumulative typical price volume
    cumulativeVolume = ta.cum(volume)  // Cumulative volume
    vwapValue = cumulativeTypicalPriceVolume / cumulativeVolume  // VWAP calculation
    plot(vwapValue, title="VWAP", color=color.blue, linewidth=2)
    
    // --- RSI Code ---
    // To plot the RSI in a separate window, we must set overlay=false for the strategy script
    rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
    rsiSourceInput = input.source(close, "Source", group="RSI Settings")
    rsi = ta.rsi(rsiSourceInput, rsiLengthInput)
    
    // Plot RSI in a **separate sub-window** below the main chart
    plot(rsi, "RSI", color=color.purple, linewidth=2)
    rsiUpperBand = hline(70, "RSI Upper Band", color=color.red, linestyle=hline.style_dashed)
    rsiLowerBand = hline(30, "RSI Lower Band", color=color.green, linestyle=hline.style_dashed)
    fill(rsiUpperBand, rsiLowerBand, color=color.rgb(126, 87, 194, 90), title="RSI Background Fill")
    
    // --- Strategy Conditions ---
    // Buy when price crosses **below** VWAP and RSI is **<= 25**
    longCondition = ta.crossunder(close, vwapValue) and rsi <= 25
    if longCondition
        strategy.entry("Long", strategy.long)
    
    // Short when price crosses **above** VWAP and RSI is **>= 65**
    shortCondition = ta.crossover(close, vwapValue) and rsi >= 65
    if shortCondition
        strategy.entry("Short", strategy.short)
    
    // --- Exit Conditions ---
    // Close the long trade if RSI reaches **30**
    if (rsi >= 30)
        strategy.close("Long")
    
    // Close the short trade if RSI reaches **70**
    if (rsi >= 70)
        strategy.close("Short")
    
    // --- Risk Management (Optional) ---
    longStopLossPercent = input.float(2.0, title="Long Stop Loss %", minval=0.1, step=0.1) / 100
    longTakeProfitPercent = input.float(5.0, title="Long Take Profit %", minval=0.1, step=0.1) / 100
    shortStopLossPercent = input.float(2.0, title="Short Stop Loss %", minval=0.1, step=0.1) / 100
    shortTakeProfitPercent = input.float(5.0, title="Short Take Profit %", minval=0.1, step=0.1) / 100
    
    longStopLossPrice = strategy.position_avg_price * (1 - longStopLossPercent)
    longTakeProfitPrice = strategy.position_avg_price * (1 + longTakeProfitPercent)
    shortStopLossPrice = strategy.position_avg_price * (1 + shortStopLossPercent)
    shortTakeProfitPrice = strategy.position_avg_price * (1 - shortTakeProfitPercent)
    
    strategy.exit("Long TP/SL", from_entry="Long", stop=longStopLossPrice, limit=longTakeProfitPrice)
    strategy.exit("Short TP/SL", from_entry="Short", stop=shortStopLossPrice, limit=shortTakeProfitPrice)
    
    plotshape(longCondition, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
    plotshape(shortCondition, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")