🧠 Pillar Tutorial

ChatGPT & Claude for Trading Indicators — Complete Tutorial

By Dan Machado · 15 min read · Prompts tested

You used to need months learning Pine Script to build a custom indicator. Now you describe what you want in plain English, paste the response into TradingView, and have a working indicator in 2 minutes. This tutorial shows exactly how to do it well — including prompts that produce production-quality code on the first try.

🎯 What You’ll Learn

1. The prompt structure that produces clean Pine Script v5
2. Differences between ChatGPT and Claude for trading code
3. How to debug AI-generated code (it sometimes hallucinates)
4. Free tier vs paid plans — what’s worth it for SA traders
5. 4 ready-to-use prompts for common indicators

ChatGPT vs Claude for Pine Script

Both AI tools can produce Pine Script. After testing dozens of indicators on both:

🟢 ChatGPT (GPT-4)

  • Wider general knowledge of trading concepts
  • Better at explaining what code does
  • Sometimes uses old Pine Script v4 syntax (warn it!)
  • Free tier: GPT-3.5 (lower code quality)
  • Paid: $20/mo (~R370) for GPT-4
  • Better for “build me an indicator that combines X+Y+Z”

🟣 Claude (Anthropic)

  • Cleaner code structure, fewer bugs
  • Better at Pine Script v5 specifically
  • Longer context = paste entire scripts to debug
  • Free tier: usable for most tasks
  • Paid: $20/mo (~R370) for Pro
  • Better for “debug this code” or “convert v4 to v5”

💡 Our Recommendation

For SA traders starting out: use Claude free tier first. Code quality is consistently better and the free tier is generous. If you find you need more capacity, both Pro plans cost roughly the same (~R370/mo). For one-off indicator generation, free tier of either works.

The Anatomy of a Good Prompt

The single biggest factor in code quality is prompt structure. A bad prompt gives bad code. Here’s the formula we use:

  1. Role: “You are a Pine Script v5 expert.”
  2. Goal: “Create an indicator that…”
  3. Specifications: exact parameters (periods, thresholds, colours)
  4. Display: what should be plotted, where (overlay or separate pane)
  5. Alerts: what conditions trigger alerts
  6. Constraints: “use only built-in functions, no external libraries”
  7. Output format: “Return complete .pine file ready to paste into TradingView”

Prompt Template (Copy-Paste Ready)

▸ Universal Prompt Template COPY ↗
You are a TradingView Pine Script v5 expert.

Create an indicator with these specifications:
- Name: [DESCRIPTIVE NAME]
- Purpose: [WHAT IT DOES IN ONE SENTENCE]
- Indicators used: [LIST: RSI, EMA, Bollinger Bands, etc.]
- Parameters (inputs): [LIST WITH DEFAULTS]
- Plot location: overlay=[true/false]
- Plotted items: [WHAT LINES/SHAPES TO DISPLAY]
- Alert conditions: [WHEN TO FIRE ALERTS]

Constraints:
- Use only built-in Pine Script v5 functions
- All inputs must be configurable via input.* functions
- Add inline comments explaining each section
- Make it work on any timeframe and any asset

Return the complete .pine file, ready to paste directly
into the TradingView Pine Editor.

Example 1: RSI with Smart Alerts

Let’s build a real indicator. Here’s the prompt:

📋 PROMPT

“You are a TradingView Pine Script v5 expert. Create an indicator named ‘RSI Smart Alerts’ that displays RSI(14) with overbought (70) and oversold (30) levels. Add background colouring when overbought (red) or oversold (green). Include alert conditions when RSI crosses below 30 from above (bullish) and when RSI crosses above 70 from below (bearish). Use input.* for the period and thresholds. Return complete Pine v5 code.”

Result (paste this into TradingView’s Pine Editor):

▸ Pine Script v5 · RSI Smart Alerts COPY ↗
//@version=5
indicator("RSI Smart Alerts", overlay=false)

// === INPUTS ===
rsiLen = input.int(14, "RSI Length", minval=2)
osLevel = input.int(30, "Oversold Level")
obLevel = input.int(70, "Overbought Level")

// === CALCULATIONS ===
rsi = ta.rsi(close, rsiLen)

// === PLOTS ===
plot(rsi, "RSI", color=#E040FB, linewidth=2)
hline(obLevel, "Overbought", color=color.new(#FF5252, 50))
hline(osLevel, "Oversold", color=color.new(#00E676, 50))
hline(50, "Mid", color=color.new(color.gray, 70), linestyle=hline.style_dotted)

// === BACKGROUND COLOURING ===
bgcolor(rsi > obLevel ? color.new(#FF5252, 90) : na, title="OB Zone")
bgcolor(rsi < osLevel ? color.new(#00E676, 90) : na, title="OS Zone")

// === ALERTS ===
bullishCross = ta.crossunder(rsi, osLevel)
bearishCross = ta.crossover(rsi, obLevel)
alertcondition(bullishCross, "RSI Bullish",
  "RSI crossed below {{plot_0}} — potential BUY")
alertcondition(bearishCross, "RSI Bearish",
  "RSI crossed above {{plot_0}} — potential SELL")

Example 2: Multi-Indicator Strategy

More complex prompt for trading strategy:

📋 PROMPT

“You are a Pine Script v5 expert. Create an overlay indicator combining RSI(14) and EMA(9, 21) for use on Volatility 75 Index. Plot the EMAs. Show BUY arrow below price when: EMA9 crosses above EMA21 AND RSI < 50. Show SELL arrow above price when: EMA9 crosses below EMA21 AND RSI > 50. Add status table showing current EMA trend (bullish/bearish) and RSI value. Include alerts for both signals. Make all parameters configurable.”

▸ Pine Script v5 · EMA + RSI Combo COPY ↗
//@version=5
indicator("EMA + RSI Combo — IA Trader Pro", overlay=true)

// === INPUTS ===
emaFast = input.int(9, "EMA Fast")
emaSlow = input.int(21, "EMA Slow")
rsiLen = input.int(14, "RSI Length")
rsiMid = input.int(50, "RSI Midline")

// === CALCULATIONS ===
ef = ta.ema(close, emaFast)
es = ta.ema(close, emaSlow)
rsi = ta.rsi(close, rsiLen)

// === PLOTS ===
plot(ef, "EMA Fast", color=#00E676, linewidth=2)
plot(es, "EMA Slow", color=#FF5252, linewidth=2)

// === SIGNAL CONDITIONS ===
emaCrossUp = ta.crossover(ef, es)
emaCrossDn = ta.crossunder(ef, es)
buySignal = emaCrossUp and rsi < rsiMid
sellSignal = emaCrossDn and rsi > rsiMid

// === ARROWS ===
plotshape(buySignal, "BUY",
  location.belowbar, color=#00E676,
  style=shape.triangleup, size=size.small, text="BUY")
plotshape(sellSignal, "SELL",
  location.abovebar, color=#FF5252,
  style=shape.triangledown, size=size.small, text="SELL")

// === STATUS TABLE ===
var table dash = table.new(position.top_right, 2, 3,
  bgcolor=color.new(color.black, 20),
  border_width=1, border_color=color.gray)
if barstate.islast
    trend = ef > es ? "BULL" : "BEAR"
    trendCol = ef > es ? #00E676 : #FF5252
    table.cell(dash, 0, 0, "EMA", text_color=color.white, text_size=size.tiny)
    table.cell(dash, 1, 0, trend, text_color=trendCol, text_size=size.tiny)
    table.cell(dash, 0, 1, "RSI", text_color=color.white, text_size=size.tiny)
    table.cell(dash, 1, 1, str.tostring(rsi, "#.#"),
      text_color=color.white, text_size=size.tiny)

// === ALERTS ===
alertcondition(buySignal, "EMA+RSI BUY",
  "EMA crossover up + RSI < 50")
alertcondition(sellSignal, "EMA+RSI SELL",
  "EMA crossover down + RSI > 50")

Pitfalls of AI-Generated Code

⚠️ Watch Out For These

AI doesn’t always produce correct code. Common hallucinations:
1. v4 syntax instead of v5 — always specify “Pine Script v5” explicitly
2. Non-existent functions — AI sometimes invents ta.fakeFunction()
3. Wrong parameter types — using strings where integers are needed
4. Missing imports — some indicators need import statements
5. Look-ahead bias — using future data in calculations (rare but possible)
6. Wrong overlay setting — RSI plotted on price chart instead of separate pane

How to Debug AI Code

If the code doesn’t compile in Pine Editor (red error), do this:

  1. Copy the error message from TradingView (bottom of editor)
  2. Paste back to AI: “This code returns the following error: [paste error]. Fix it and explain what was wrong.”
  3. Iterate until it compiles
  4. If 3+ iterations fail, simplify the request and start over

Claude in particular is excellent at debugging — paste broken code and ask “what’s wrong with this?”. Usually gets it right on first try.

Backtest Before Trusting AI Indicators

⚠️ Critical Step

Code compiling cleanly ≠ profitable strategy. AI generates the indicator you asked for, but doesn’t know if it works. Always backtest:
1. Convert indicator to strategy (ask AI: “convert this indicator to a strategy script with stop-loss and take-profit”)
2. Run on TradingView Strategy Tester for 3-6 months historical data
3. Check win rate, profit factor, max drawdown
4. If profit factor < 1.5, don’t deploy live
Full process: Backtesting Guide

Common Indicators You Can Generate

AI can generate any of these in seconds with proper prompts:

  • Trend: EMA Crossover, MACD, SuperTrend, Heikin Ashi
  • Momentum: RSI, Stochastic, ROC, Awesome Oscillator
  • Volatility: Bollinger Bands, ATR Channels, Keltner Channels
  • Volume: OBV, Volume Profile, VWAP, Accumulation/Distribution
  • Levels: Pivot Points, Fibonacci, Support/Resistance Auto
  • Patterns: Engulfing detection, Doji finder, Inside Bar
  • Combos: Any of the above combined
  • Custom logic: “Buy when X AND Y AND Z” — describe it, get it

See our 10 Pine Script Indicators library for production-ready examples.

What AI CAN’T Do (Yet)

❌ AI Limitations

1. Predict markets — AI generates code, doesn’t see the future
2. Identify profitable strategies — only humans + backtesting can do this
3. Tell you when to enter — you still need market understanding
4. Replace risk management — must be added manually
5. Custom Python integrations — limited (Pine Script ≠ Python)
6. Real-time scraping — Pine Script is sandboxed, no external data calls
Treat AI as a code generator, not a strategist.

Free Tier vs Paid — SA Cost Analysis

At ~R18.50/USD, here’s what each tier costs SA traders monthly:

  • ChatGPT Free (GPT-3.5): R0 — sufficient for simple indicators
  • ChatGPT Plus (GPT-4): $20/mo ≈ R370/mo
  • Claude Free: R0 — sufficient for most Pine Script tasks
  • Claude Pro: $20/mo ≈ R370/mo
  • API access (developer): pay-per-token, ~R5-R20 per 1000 generations

If you generate 1-2 indicators per week, free tier is enough. Heavy users (10+ per week) benefit from Pro plans for higher message limits.

Iterative Prompting (Pro Technique)

Don’t try to get the perfect indicator in one prompt. Iterate:

  1. Prompt 1: “Create basic RSI indicator with alerts.”
  2. Prompt 2: “Add background colouring when overbought/oversold.”
  3. Prompt 3: “Now add a status table showing current RSI value.”
  4. Prompt 4: “Convert to strategy script with 2% position sizing and 50-pip stop loss.”
  5. Prompt 5: “Add multi-timeframe RSI (show H1 RSI on M5 chart).”

Each iteration builds on the last. AI maintains context. End result is far better than asking for everything at once.

Generate Trading Strategies, Not Just Indicators

Once comfortable with indicators, level up to strategy scripts. These actually place simulated trades and let you backtest. The key prompt:

📋 INDICATOR → STRATEGY CONVERSION

“Convert this Pine Script indicator into a strategy script. Add: (1) strategy.entry on BUY signal, strategy.exit on SELL signal. (2) Stop-loss at 1% below entry. (3) Take-profit at 2% above entry. (4) Position size = 2% of equity per trade. (5) Commission of 0.05% per trade. (6) initial_capital = 1000. Return complete Pine v5 strategy code.”

Paste your indicator first, then this prompt. AI converts it. Open in Strategy Tester to see realistic backtest results.

Privacy & Data Considerations

🔐 POPIA Note

When you paste account data, trade history, or balance info into ChatGPT/Claude, you’re transmitting personal information to US-based services. Under POPIA Section 72, this is an international transfer. Both OpenAI and Anthropic have data processing agreements that comply with major privacy regulations, but:
• Don’t paste your real Deriv account number
• Don’t paste your real balance amounts
• Don’t paste personal identifiers
For backtesting analysis, use anonymised data or placeholders.

SA-Specific Use Cases

AI prompts particularly useful for SA traders:

  • JSE stock analysis: “Analyse this Naspers price action: [paste OHLC]. Identify trend, key levels, possible setups.”
  • ZAR pair indicators: “Build indicator for USD/ZAR forex pair. Range-bound strategy with breakout filter.”
  • Tax categorisation: “Help categorise these trades for SARS: [paste list]. Income vs CGT?”
  • Education: “Explain Bollinger Bands in simple terms for a SA retail trader who knows RSI.”

Save Your Best Prompts

Build a personal prompt library. Save prompts that produce good results. We use a Google Doc with categories: Indicators, Strategies, Debugging, Conversions, Explanations. Over time, you’ll have 20-30 reusable prompts that save hours.

What’s Next

  1. Try our 5 Specific AI Prompts
  2. Build indicators with our 10 Pine Script library
  3. Backtest properly: Backtesting guide
  4. Move to Python automation: Python + Deriv API
  5. Test live: Deriv Bot setup

🚀 Test AI-generated indicators on Deriv demo (FSCA-licensed, free):

Open Free Demo Account

Related Reading

DM

Dan Machado

Founder IA Trader Pro · Built 100+ indicators with AI

⚠️ Disclaimer: AI-generated code may contain bugs. Always test on demo before live. Trading involves risk of capital loss. Deriv is FSCA-authorised (FSP 50885). This is educational content, not financial advice. Contains Deriv affiliate links. Full disclaimer.