Pine Script with AI: TradingView Auto Trading
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:
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 paneAI will return code that looks something like this:
//@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.
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:
| Function | Purpose | In an indicator |
|---|---|---|
| strategy.entry() | Open position (long/short) | Not available |
| strategy.exit() | Close position (stop-loss/take-profit) | Not available |
| strategy.close() | Flat the position | Not available |
| plotshape() | Draw signal markers | Available |
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.
Back to the AI prompt — change it to this:
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 paneThe output will look something like this:
//@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")// === 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)After saving, click the Strategy Tester at the top-right of the chart to see historical backtest results — net profit, win rate, max drawdown.
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.
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:
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-lossThe code for this logic:
// === 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.
| Parameter | Suggested value | Explanation |
|---|---|---|
| RSI Period | 14 | Standard value, works for most markets |
| Oversold/Overbought | 30/70 | Classic thresholds; adjustable to 20/80 in trending markets |
| ATR Multiplier | 1.5–2.5 | Larger means wider stop-loss but also lets more losses through |
| Risk Percentage | 0.5–2.0 | Not 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:
// 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:
{
"action": "{{strategy.order.action}}",
"symbol": "{{ticker}}",
"price": {{close}},
"exchange": "binance"
}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.
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.
After writing the code, go to the top-right of the TradingView chart and click the bell icon → Create Alert:
- 1Select ConditionIf it's an indicator, pick your configured alertcondition; if it's a strategy, pick "Any alert() function call".
- 2Set FrequencyFor auto-trading, strongly select <Code>Once Per Bar Close</Code> to prevent signals from disappearing before bar close and causing false signals.
- 3Switch to the Notifications tabCheck <Code>Webhook URL</Code>, paste your TVSBot webhook URL.
- 4Fill MessageIf the code uses Approach A (alert_message), leave this blank or fill <Code>{{strategy.order.alert_message}}</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 location | Pine code | TradingView Alert dialog |
| Changing strategies | Edit code only | No JSON changes, but must re-paste each time |
| Recommended use case | Fixed strategy, long-term use | Quick 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.
The specific steps:
| Step | What to do | Time |
|---|---|---|
| 1 | Register on TVSBot | 1 minute |
| 2 | Bind exchange API key (read + trade, withdrawal disabled) | 3–5 minutes |
| 3 | Create a strategy to get your webhook URL | 1 minute |
| 4 | Go back to TradingView and paste webhook URL + JSON | 1 minute |
| 5 | Test with Dry-run mode | Instant |
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.
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.
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."
During testing, check three things:
Frequently asked questions
Can free TradingView plans use webhooks?
Is there a big difference between Pine Script v5 and v6?
Can I use AI-generated code directly for live trading?
Can one strategy connect to multiple exchanges at once?
Webhook isn't responding — what should I check?
Should I use indicator or strategy?
Get started
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- Pine Script Beginner — Write Your First Strategy in 30 Minutes (v6)
- TradingView Webhook Complete Tutorial — From Zero to Auto-Execution
- Write Pine with Claude — Automated Trading Without Code
- AI Generated Your Pine Script Strategy — Now What?
- How to Spot Overfitted Backtests — Three Things to Do After Parameter Optimization