Edgoro
AI

Can ChatGPT write Pine Script? What goes wrong and how to get code that works

ChatGPT and other chatbots can write Pine Script, but often in old versions, with invented functions or look-ahead bugs. How to spot and fix each problem.

Short answer: yes, often. General-purpose chatbots such as ChatGPT, Claude and Gemini have seen a lot of Pine Script, and a simple indicator usually comes back working on the first or second try. The trouble starts with older syntax, longer scripts, strategies, and the worst category of all: code that compiles and quietly does the wrong thing.

A disclosure before we start: we make an AI Pine Script tool, so we have an interest here. The failure modes below aren't opinions, though. Each broken example was run through TradingView's own compiler to get the exact error message, and the fixes work the same whichever AI you use.

What usually works

  • Simple indicators: moving averages, RSI with levels, Bollinger Bands, crosses marked with plotshape() and an alertcondition().
  • Edits to code you already have: adding an input, changing a colour, renaming variables, adding an alert.
  • Explaining code line by line, which is useful even when you don't ask it to write anything.
  • Fixing a specific error when you paste the exact message and the line it points to.

Why chatbots make these mistakes

Three things explain most of what follows. First, a chatbot learned Pine from years of public code, and most of it predates v6, so old and new syntax sit side by side in what it has seen. Second, it predicts text that looks right; it doesn't run TradingView's compiler before answering, so an invented function looks exactly as plausible as a real one. Third, the hardest bugs in trading code aren't syntax at all. A script that peeks at future data or recalculates its stop on every bar compiles cleanly, and nothing in the chat tells either of you that the logic is wrong. That's why the checks at the end of this article matter more than the choice of chatbot.

What goes wrong, and how to spot it

1. Old Pine versions, or a mix of them

Most Pine Script on the internet was written for v4 or v5, and it shows. Chatbots regularly produce lines like these:

study("EMA with daily trend", overlay=true)
dailyClose = security(syminfo.tickerid, "D", close)
plot(ema(close, 20), color=color.orange, transp=0)

Under a //@version=6 header, each line fails: Could not find function or function reference 'study', the same for 'security' and 'ema', and The "plot" function does not have an argument with the name "transp". A mix is just as common: a //@version=5 or //@version=6 first line on top of v4 functions.

How to spot it: look at the first line, then scan for functions without a namespace. The usual replacements:

OldPine Script v6
study()indicator()
security()request.security()
ema(), rsi(), crossover()ta.ema(), ta.rsi(), ta.crossover()
tostring()str.tostring()
transp = 50color = color.new(color.red, 50)
iff(cond, a, b)cond ? a : b

Code that is already v5 needs a few more changes before it runs as v6; see how to convert Pine Script v5 to v6.

2. Functions and parameters that don't exist

Chatbots fill gaps with names that sound right. Some real examples of plausible inventions, with the messages they produce:

InventedMessageWhat exists
ta.divergence()Could not find function or function reference 'ta.divergence'Nothing built in: divergence is built from pivots
strategy.position_entry_priceUndeclared identifier "strategy.position_entry_price"strategy.position_avg_price
trail_percent in strategy.exit()The "strategy.exit" function does not have an argument with the name "trail_percent"trail_points and trail_offset, in ticks
qty_percent in strategy.entry()The "strategy.entry" function does not have an argument with the name "qty_percent"qty in strategy.entry(); qty_percent belongs to strategy.exit() and strategy.close()

How to spot it: any function you don't recognise, check in the reference manual before you debug anything else. For divergence specifically, see how to code RSI divergence in Pine Script.

3. The right function, used the wrong way

ta.supertrend() is real, but it returns two values, the line and the direction. Code that treats it as one value fails with Invalid assignment. Cannot assign a tuple to a variable "st". The fix is to unpack both:

[st, dir] = ta.supertrend(3, 10)
plot(st, "Supertrend", color = dir < 0 ? color.teal : color.red)

The same goes for argument order: ta.supertrend(factor, atrPeriod) takes the multiplier first. Swapping them compiles and draws a very different line. A reference version with explanations is on the Supertrend indicator page.

4. Other languages leaking in

Pine looks a bit like Python and a bit like JavaScript, and chatbots mix them up:

  • && and || give no viable alternative at character "&" (or "|"). Pine uses and, or and not.
  • null gives Undeclared identifier "null". Pine uses na.
  • elif gives the confusing "elif" is not a valid type qualifier. Pine uses else if.

5. Code that compiles but looks into the future

This is the dangerous one, because nothing tells you. A chatbot asked for "the daily close on an intraday chart" may write:

dailyClose = request.security(syminfo.tickerid, "D", close, lookahead = barmerge.lookahead_on)

On historical bars, lookahead_on with the current close hands every intraday bar the day's final close, hours before it happened. Signals built on it look excellent in a backtest and fall apart live. The non-repainting version requests the previous completed day:

//@version=6
indicator("EMA with daily trend", overlay = true)

len = input.int(20, "EMA length", minval = 1)

// Previous completed daily close: no future data on historical bars
dailyClose = request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on)
e = ta.ema(close, len)

plot(e, "EMA", color = color.orange)
plot(dailyClose, "Previous daily close", color = color.new(color.gray, 50))
bgcolor(close > dailyClose ? color.new(color.teal, 92) : na)

Why this works, and how to test any script for the problem, is explained in Pine Script repainting explained.

6. Strategy logic that drifts

Strategies give a chatbot more ways to be subtly wrong:

  • Stops recalculated every bar. strategy.exit("Stop", "Long", stop = close * 0.98) called on every bar moves the stop with each new close, so it trails price in both directions and rarely triggers. The stop has to be stored once, at entry.
  • States instead of events. if close > ta.ema(close, 50) is true on bar after bar, so the strategy re-enters right after every exit. Entries usually want a crossover, an event that happens once.
  • No costs. Commission and slippage are rarely included unless you ask, and leaving them out flatters every report.

A corrected version of the stop:

//@version=6
strategy("Fixed stop at entry", overlay = true,
  commission_type = strategy.commission.percent, commission_value = 0.05, slippage = 2)

fast    = ta.ema(close, 9)
slow    = ta.ema(close, 21)
crossUp = ta.crossover(fast, slow)

var float stopPrice = na
if crossUp and strategy.position_size == 0
    stopPrice := close * 0.98
    strategy.entry("Long", strategy.long)

// The stored level doesn't follow price
strategy.exit("Stop", "Long", stop = stopPrice)

plot(fast, "Fast EMA", color.teal)
plot(slow, "Slow EMA", color.orange)

7. Confident claims about performance

A chatbot may describe its strategy as "profitable" or "high win rate". It hasn't run a backtest; it can't. Treat any performance description that comes with generated code as untested, and get your numbers from TradingView's Strategy Tester, with costs set, and then from a demo account.

How to prompt for better Pine Script

  1. Name the version and the script type: "Pine Script v6 indicator" or "Pine Script v6 strategy".
  2. Give measurable rules. "RSI(14) crosses above 30", not "RSI is oversold". Our template for describing a strategy to AI covers the details.
  3. Ask for the safeguards explicitly: an input for every number, signals on closed bars only, no lookahead_on without an offset, commission and slippage in the strategy() declaration.
  4. Compile, then paste the exact error. Include the line number and the full message. "It doesn't work" gets a guess; the message gets a fix.
  5. Ask for an explanation of each block, and check that the numbers in the code are the ones you gave.
  6. Verify by hand. Pick five signals on the chart and check each against your rules before you look at any backtest.

A prompt that avoids most of the problems above:

Write a Pine Script v6 strategy (not v5, no deprecated functions).
Long only. Enter when the 20 EMA crosses above the 50 EMA and the close is above the 200 EMA.
Stop-loss at 2 x ATR(14) below the entry close, stored at entry so it doesn't move.
Take profit at 2 x the stop distance. One position at a time.
Inputs for every length and multiplier. Signals on closed bars only.
Commission 0.05% per order and slippage 2 ticks in the strategy() declaration.
Explain each block after the code.

A chatbot or a dedicated tool?

A general chatbot is flexible and often free. You're responsible for keeping it on v6, asking for inputs, alerts and costs, and pasting errors back. Dedicated Pine Script tools, Edgoro among them, fix the version, add those parts by default and keep every version of a script. Neither kind compiles inside TradingView for you, and neither replaces checking the logic on the chart and testing it.

Sources and further reading

Try it with Edgoro

The free AI Pine Script generator writes v6 indicators from a plain-English description, three scripts a month with no sign-up. If you already have code from a chatbot that won't compile, paste it with the error into the free Pine Script error fixer. Either way, check the signals on your chart before you rely on them.

AI-generated code can contain mistakes even when it compiles. Test any script before relying on it; trading involves substantial risk of loss, and nothing here is investment advice.

Build it with Edgoro

Describe your strategy in plain English and get a TradingView indicator in Pine Script v6 or a MetaTrader 5 Expert Advisor in minutes. Every first purchase is covered by a 7-day money-back guarantee.

Build your indicator with Edgoro