Complete Tutorial

Pine Script with AI: TradingView Auto Trading

2026-11-21·7 min read

You don't write code, but you want to use TradingView's Pine Script — the built-in scripting language — for automated trading? You no longer need to learn syntax from scratch. With an AI prompt, you can generate backtestable scripts that send webhooks (that is, URLs that automatically transmit signals). The key isn't writing code; it's knowing how to ask.

This article walks you through the full pipeline: generate your first Pine indicator with AI → convert it to a strategy for backtesting → add alerts to emit signals → connect webhooks to TVSBot for auto-execution. Every stage includes ready-to-copy prompts; tweak a parameter and swap strategies.

Why "knowing how to prompt AI" matters more than "knowing Pine"

Pine Script (TradingView's built-in scripting language) has syntax so simple it borders on trivial: assign variables with =, draw with plot(), branch logic with if. But what really stumps beginners isn't the syntax — it's not knowing what logic to write in the first place to make money. That's where AI steps in.

The more specific your prompt to AI, the more usable the code it produces. Every prompt in this article has been tested; paste them directly into ChatGPT, Claude, or other AI tools and they run.

But let's be clear about one thing: AI won't decide trading logic for you. It can only translate your ideas into code. If your strategy is fundamentally flawed, AI will produce code that "runs but loses money" — exactly the same as traditional coding.

Step 1: Generate your first Pine indicator with an AI prompt

Open TradingView → click Pine Editor at the bottom → New → Blank Indicator. If you're not yet comfortable with Pine Script syntax, check out our Pine Script beginner tutorial first, then come back. Paste this prompt into your AI tool:

prompt
Write an RSI indicator in Pine Script v6.
        Requirements:
        1. Use input.int so users can adjust the RSI period (default 14), overbought level (default 70), oversold level (default 30)
        2. Plot the RSI line, add horizontal lines in the overbought/oversold zones
        3. overlay=false, plot in the lower pane

AI will return code that looks something like this:

pine
//@version=6
        indicator("RSI Indicator", overlay=false)

        length = input.int(14, "RSI Period")
        oversold = input.int(30, "Oversold Level")
        overbought = input.int(70, "Overbought Level")

        rsiValue = ta.rsi(close, length)

        plot(rsiValue, "RSI", color=color.purple)
        hline(overbought, "Overbought", color=color.red)
        hline(oversold, "Oversold", color=color.green)

Click Save → Add to chart, and you'll see RSI appear below the chart. This indicator can now be backtested and emit alerts — but it still can't auto-trade, because it's not a strategy.

Prompting tip: If you're unsure what to add, just ask AI "add entry signals" or "add stop-losses." Change only one thing at a time; don't overload AI with too many requests — the more it handles at once, the higher the chance of errors.
Plotting + alert
indicator (suits signal emission, pairs with external backtests)
Execution + backtest
strategy (auto-calculates net profit, win rate, max drawdown)
Latest version
Pine Script v6 (removed when= param from strategy.entry(), bool no longer accepts na)
Consistency across periods
Backtest key check (does the last 30% of the period match full-period performance?)

Step 2: Convert the indicator to a strategy (the backtestable kind)

An indicator and a strategy differ only in the first line: change indicator() to strategy(), then add a few more parameters. But more importantly, strategies gain execution functions that let TradingView auto-calculate backtest results for you.

Here are the strategy-exclusive functions and what they do:

FunctionPurposeIn an indicator
strategy.entry()Open position (long/short)Not available
strategy.exit()Close position (stop-loss/take-profit)Not available
strategy.close()Flat the positionNot available
plotshape()Draw signal markersAvailable

Pine Script v6 strategy functions cheat sheet, verified 2026-10-20

Indicators don't have these functions, so even if you add alert() to fire webhooks, you won't see performance metrics in TradingView's built-in backtesting tool. Strategies auto-calculate net profit, win rate, max drawdown, and every other metric.

Plotting + alert
indicator (can't backtest, no performance numbers)
Execution + backtest
strategy (auto-calculates net profit, win rate, max drawdown)

Back to the AI prompt — change it to this:

prompt
Write an RSI reversal strategy in Pine Script v6.
        Requirements:
        1. Declare with strategy(), initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10
        2. Go long when RSI crosses above 30 from below; close when it crosses below 70 from above
        3. Add plotshape to draw triangle markers for entry and exit
        4. commission_type = strategy.commission.percent, commission_value = 0.1 (0.1% fee per trade)
        5. overlay=true, RSI in the lower pane

The output will look something like this:

true
overlay (strategy plot layered on the price chart)
10000
initial_capital (starting capital $10,000)
percent_of_equity
default_qty_type (position sized as a percentage of equity each time)
pine
//@version=6
        strategy("RSI Reversal Strategy", overlay=true,
          initial_capital=10000,
          default_qty_type=strategy.percent_of_equity,
          default_qty_value=10,
          commission_type=strategy.commission.percent,
          commission_value=0.1)

        // === Parameters ===
        length = input.int(14, "RSI Period")
        oversold = input.int(30, "Oversold Level")
        overbought = input.int(70, "Overbought Level")
14
RSI Period (standard value, works for most markets)
30/70
Oversold/Overbought (classic thresholds; adjustable to 20/80 in trending markets)
pine
// === Calculation ===
        rsiValue = ta.rsi(close, length)

        // === Signals ===
        longCondition = ta.crossover(rsiValue, oversold)
        shortCondition = ta.crossunder(rsiValue, overbought)

        // === Execution ===
        if longCondition
            strategy.entry("Long", strategy.long)
        if shortCondition
            strategy.close("Long")

        // === Visuals ===
        plot(rsiValue, "RSI", color=color.purple, display=display.pane)
        hline(oversold, "Oversold", color=color.green)
        hline(overbought, "Overbought", color=color.red)

        plotshape(longCondition, "Entry", shape.triangleup,
          location.belowbar, color=color.green, size=size.small)
        plotshape(shortCondition, "Exit", shape.triangledown,
          location.abovebar, color=color.red, size=size.small)
14
RSI Period (standard value, works for most markets)
30/70
Oversold/Overbought (classic thresholds; adjustable to 20/80 in trending markets)

After saving, click the Strategy Tester at the top-right of the chart to see historical backtest results — net profit, win rate, max drawdown.

v6 note: Pine Script v6 removed the when= parameter from strategy.entry(). Old syntax like strategy.entry("Buy", strategy.long, when=condition) will fail to compile in v6. The correct approach wraps if condition around it (as shown in the code above).

Step 3: Add stop-losses and position sizing

The strategy above has a problem: it always uses 10% of capital regardless of volatility. Professional traders use ATR (Average True Range) to dynamically size positions — smaller positions in volatile markets, larger when calm.

10% of capital each time
Fixed percentage (position size stays the same regardless of market chaos)
High volatility → smaller position
ATR dynamic (larger ATR = more chaos = smaller position, risk controlled)

ATR is a built-in TradingView indicator function; ta.atr(14) returns the average true range over the past 14 bars. Multiply it by a factor (say 2.0), and you have your stop-loss distance.

Change the prompt to this:

prompt
Add ATR stop-loss and dynamic position sizing to the RSI strategy above:
        1. Add input.float("ATR Multiplier", minval=0.5, maxval=5.0) default 2.0
        2. Add input.float("Risk Percentage", minval=0.1, maxval=5.0) default 1.0
        3. Stop-loss distance = ATR × ATR multiplier
        4. Position size = account equity × risk percentage / stop-loss distance
        5. Add strategy.exit() to set the stop-loss

The code for this logic:

pine
// === ATR stop-loss + dynamic sizing ===
        atrLength = input.int(14, "ATR Period")
        atrMult = input.float(2.0, "ATR Multiplier", minval=0.5, maxval=5.0)
        riskPct = input.float(1.0, "Risk Percentage %", minval=0.1, maxval=5.0)

        atrValue = ta.atr(atrLength)

        if longCondition and atrValue > 0
            stopDistance = atrValue * atrMult
            riskAmount = strategy.equity * (riskPct / 100)
            qty = riskAmount / stopDistance
            strategy.entry("Long", strategy.long, qty=qty)
            strategy.exit("Long SL", "Long", stop=strategy.position_avg_price - stopDistance)

The math is intuitive: you're willing to risk riskPct of your account balance, divided by the stop-loss distance (ATR × multiplier), gives you the quantity to buy. Larger ATR (more chaotic market) → smaller position — this is a complete risk management system.

ParameterSuggested valueExplanation
RSI Period14Standard value, works for most markets
Oversold/Overbought30/70Classic thresholds; adjustable to 20/80 in trending markets
ATR Multiplier1.5–2.5Larger means wider stop-loss but also lets more losses through
Risk Percentage0.5–2.0Not exceeding 2% of account per trade is an industry common practice

RSI + ATR strategy parameter recommendations, verified 2026-10-20

Step 4: Make the strategy fire webhook signals

A pretty backtest is only the first step. To send signals to exchanges for auto-execution, you need to add alert() or the alert_message parameter of strategy.entry() in your Pine code. The key here is the API (Application Programming Interface) — TradingView uses it to pass signals to TVSBot.

Two approaches:

pine
// Approach A: strategy.entry with alert_message (recommended, fires only on entry)
        if longCondition
            strategy.entry("Long", strategy.long, qty=qty)
            strategy.exit("Long SL", "Long", stop=stopLossPrice)
            alert('{"action":"buy","symbol":"' + syminfo.ticker + '",'
                + '"exchange":"binance"}', alert.freq_once_per_bar_close)

The key here is the JSON inside alert_message — TradingView will POST this text to your webhook URL. If you use the alert_message parameter of strategy.entry(), the message content goes out automatically through the {{strategy.order.alert_message}} placeholder in the Alert settings.

Approach B instead manually fills JSON in TradingView's Alert dialog:

json
{
          "action": "{{strategy.order.action}}",
          "symbol": "{{ticker}}",
          "price": {{close}},
          "exchange": "binance"
        }
Built into code
Approach A (JSON written in Pine, changes with strategy)
Filled manually in Alert
Approach B (JSON in TradingView UI, no code changes needed)

Both approaches produce the same result. The difference: Approach A's JSON lives in the code and changes with the strategy; Approach B's JSON lives in the Alert settings screen and doesn't touch Pine at all.

Don't confuse Pine's interface with TradingView's UI: The alert() function controls frequency within code (alert.freq_once_per_bar_close), while the Alert dialog's Frequency dropdown is a separate set of labels (Once only, Once per bar, Once per bar close, Once per minute or every time). They don't share configuration — be clear about which one you're adjusting.

Step 5: Create an Alert + Webhook in TradingView

After writing the code, go to the top-right of the TradingView chart and click the bell icon → Create Alert: for more detailed webhook setup steps (including JSON format and error troubleshooting), check out our TradingView Webhook complete tutorial.

alertcondition / alert() call
Condition (indicator picks alertcondition, strategy picks alert() call)
Once Per Bar Close
Frequency (strongly recommended! Prevents signals from disappearing before bar close, causing false signals)
TVSBot-specific URL
Webhook URL (paste in the Notifications tab, JSON comes from code or manual entry)

After writing the code, go to the top-right of the TradingView chart and click the bell icon → Create Alert:

  1. 1
    Select Condition
    If it's an indicator, pick your configured alertcondition; if it's a strategy, pick "Any alert() function call".
  2. 2
    Set Frequency
    For auto-trading, strongly select <Code>Once Per Bar Close</Code> to prevent signals from disappearing before bar close and causing false signals.
  3. 3
    Switch to the Notifications tab
    Check <Code>Webhook URL</Code>, paste your TVSBot webhook URL.
  4. 4
    Fill Message
    If the code uses Approach A (alert_message), leave this blank or fill <Code>&#123;&#123;strategy.order.alert_message&#125;&#125;</Code>. If using Approach B, paste the JSON here.

Finally click Test to verify — TradingView will simulate one trigger, and you'll see the response in TVSBot's webhook log.

Approach A (code-built)Approach B (Alert manual entry)
JSON locationPine codeTradingView Alert dialog
Changing strategiesEdit code onlyNo JSON changes, but must re-paste each time
Recommended use caseFixed strategy, long-term useQuick test, unsure of strategy

Comparison of two webhook signal approaches

Step 6: Connect TVSBot for auto-execution

TVSBot's workflow is straightforward: register → paste your exchange API key (that is, the application key that lets different software communicate — only enable Trade permissions, disable Withdraw) → create a strategy to get a webhook URL → paste it into TradingView Alert. The whole process takes about 5 minutes.

7 exchanges
Supported exchanges (Binance, OKX, Bybit, Bitget, Gate.io, BingX, Hyperliquid DEX)
Fernet encryption
API key security (Withdraw disabled, keys with withdrawal capability rejected)
Free, unlimited
Dry-run (traverses real API paths, skips actual execution)

The specific steps:

StepWhat to doTime
1Register on TVSBot1 minute
2Bind exchange API key (read + trade, withdrawal disabled)3–5 minutes
3Create a strategy to get your webhook URL1 minute
4Go back to TradingView and paste webhook URL + JSON1 minute
5Test with Dry-run modeInstant

TVSBot integration flow and time estimates

API key permission settings are the most critical part of auto-trading. No matter which exchange you use, the principle is always the same:

  • ✓ Enable Trade / Spot permissions
  • ✓ Disable Withdraw
  • ✓ Enable IP whitelist (if your exchange supports it)
  • ✓ Enable 2FA

TVSBot supports Binance, OKX, Bybit, Bitget, Gate.io, BingX, and Hyperliquid DEX — all running through ccxt's unified abstraction layer. Each exchange has different API key formats, but the permission principle is identical: can execute trades but cannot withdraw funds.

TradingView's 3-second limit: After TradingView sends a webhook, if the receiver doesn't respond with 200 within 3 seconds, the request is cancelled. So your webhook receiver (or an intermediary service like TVSBot) must return 200 immediately upon receiving the signal; actual execution should be handled asynchronously in the background.

Step 7: Forward test before going live

No matter how pretty the backtest, it doesn't guarantee live profitability — historical data has latency, slippage, fee discrepancies, and other variables. The safest approach is to run TVSBot's Dry-run mode for a while first, confirm the signal chain is complete and correct, then consider going live.

Simulated fills
Dry-run (traverses real API paths but skips execution)
Fully offline
Paper trading (no exchange connection, can't verify API setup)
Real funds
Live (start with small capital after confirming Dry-run stability)

Dry-run is a built-in TVSBot feature: strategies receive TradingView webhook signals normally, run the full decision logic (including risk controls and daily limits), but actual execution is simulated — no real orders are sent to the exchange. TVSBot's official docs write "Dry-run sandbox: Validate webhook + risk wiring with virtual capital before going live."

Dry-run is not paper trading: It traverses real exchange API paths (including balance checks and limit verification), only skipping the actual order placement. So Dry-run validates whether your API key setup is correct and whether risk controls trigger properly — different from traditional paper trading's "fully offline simulation."

During testing, check three things:

1
Is the signal frequency as expected?
Yes →Move to the next check.
No →Check Pine's frequency setting and TradingView Alert's Frequency; confirm both match.
2
Are stop-loss / take-profit triggering correctly?
Yes →Strategy logic is correct, proceed to live stage.
No →Go back and check strategy.exit() parameters and the stopLossPrice calculation formula.
3
Is the Dry-run win rate acceptable?
Yes →You can switch to Live mode, but start with small capital for the first week.
No →Adjust strategy parameters or reselect signal logic, go back to Step 4 and rewrite Pine.

Frequently asked questions

Can free TradingView plans use webhooks?
No. Webhooks are only available from the Essential plan ($14.95/month) onward; Basic (free) has zero support for this feature.
Is there a big difference between Pine Script v5 and v6?
The main differences: v6 removed the when= parameter from strategy.entry() (use if blocks instead), bool types no longer accept na, and dynamic request.security() is supported. If writing new code with AI prompts, just specify v6 directly.
Can I use AI-generated code directly for live trading?
Not recommended. AI-generated code can run, but whether the trading logic is correct needs your own verification. Test with Dry-run first before considering live trading.
Can one strategy connect to multiple exchanges at once?
TradingView Alerts can only send to one webhook URL at a time. If you want to connect to multiple exchanges, use an intermediary service like TVSBot that forwards to different exchanges.
Webhook isn't responding — what should I check?
First check: 1) Is the TradingView Alert enabled? 2) Is the Webhook URL correct? 3) Is the JSON format valid? 4) Is the receiver responding with 200 within 3 seconds? TVSBot\'s webhook log will show received content and response status.
Should I use indicator or strategy?
If you only need to emit signals (e.g., for external backtesting), use indicator + alert(). If you want to see backtest results directly in TradingView, use strategy. Both can connect to webhooks.

Get started

Ready to ship what you just learned?

Bring AI-generated Pine Script strategies here — TVSBot handles the webhook-to-exchange part with your own API key, start with dry-run, set your own risk controls.

Get started for free