Edgoro
Compile error · Limits

Pine Script: Compiled code contains too many tokens (fix)

Pine Script error CE10117: the compiled script exceeds 100,256 tokens. What counts, what doesn't (comments, names), and the changes that shrink it.

Pine Editor console
Compiled code contains too many tokens

Cause

The script is too large once compiled. TradingView's compiler turns the source into a compact intermediate form made of tokens, optimizes it, and refuses to go further when an indicator, strategy or library is over 100,256 tokens (error CE10117 in TradingView's documentation). The limit applies to that compiled form, so the number of lines or characters in the editor doesn't decide it. The usual causes are code that repeats the same statement many times instead of looping, long lists of hard-coded numbers or strings, and large blocks of logic pasted several times with one value changed.

Broken code

A shortened excerpt of the pattern: these few lines compile on their own. TradingView reports the error when you save a script in which statements like these, each one adding its own tokens, are repeated until the compiled code passes the limit.

Pine Script v6
//@version=6
indicator("Up bars in the last 2000 bars")
// One statement per past bar, produced by copy and paste or by a generator
int count = 0
count += close[1] > open[1] ? 1 : 0
count += close[2] > open[2] ? 1 : 0
count += close[3] > open[3] ? 1 : 0
count += close[4] > open[4] ? 1 : 0
// ... the same line for every offset in between ...
count += close[2000] > open[2000] ? 1 : 0
plot(count, "Up bars")

Fixed code

The same script, corrected for Pine Script v6. Paste it into the Pine Editor and save.

Pine Script v6
//@version=6
indicator("Up bars in the last 2000 bars", max_bars_back = 2000)
lookback = input.int(2000, "Bars to count", minval = 1, maxval = 2000)
// One statement inside a loop replaces one statement per bar
int count = 0
for i = 1 to lookback
    count += close[i] > open[i] ? 1 : 0
plot(count, "Up bars")

Why it works

The comparison is now written once, inside a for loop, so the compiled code contains it once however many bars the loop covers. Going from 2,000 bars to 200 or back is a change of input and no longer a change of script size. max_bars_back = 2000 tells Pine how much history close[i] and open[i] need, because the offset is a variable.

Size and speed are two separate limits. A loop keeps the compiled code small but still does the work on every bar, and a long one can run into Loop is too long (> 500 ms). When a built-in function does the same job, it is both smaller and faster: see the math.sum() version below.

What the limit measures

TradingView's documentation describes three steps: the compiler translates the script into a tokenized intermediate language, optimizes it, then produces the code that runs on the chart. The limit is checked on the optimized intermediate form.

LimitValueApplies to
Compiled size of one script100,256 tokensEach indicator, strategy or library, counted separately
Imported libraries, all together1 million tokensThe total of the libraries one script imports

Three consequences follow:

  • Source length is a poor guide. Two scripts with the same number of lines can compile to very different sizes. A script full of comments and long names can be far under the limit, and a much shorter one with a huge array.from() list can be over it.
  • You can't read the size of a script that compiles. TradingView doesn't display a token count; you only learn that the limit exists when this error appears. To see what a change is worth, remove a block and save again.
  • It isn't a runtime error. The script never reaches the chart. Nothing about the symbol, the timeframe or the number of bars changes the result, unlike Memory limits exceeded or too many request.*() calls.

Changes that don't make the script smaller

The compiler already removes or simplifies the following, so editing them by hand changes little or nothing. This list comes from TradingView's page for the error:

ChangeWhy it doesn't help
Deleting commentsComments are discarded before the size is measured
Removing spaces and blank lines, or joining statements with commasLayout isn't part of the compiled code (text inside string literals is kept as written)
Shortening names of variables, functions, parameters, types and fieldsNames are replaced by internal identifiers
Removing type keywords such as float or intThe compiler infers the types anyway
Replacing 2 * 50 with 100Constant expressions are calculated at compile time
Deleting code that feeds no plot, drawing, order, alert or logCode with no effect on the outputs is already dropped; unused inputs add no tokens
Merging two identical expressions or identical functionsThe compiler already reduces most of them to one calculation

Two exceptions are worth knowing. An enum member without a title has its name stored as a string wherever it is used, so very long member names do cost tokens. And the compiler doesn't merge everything that looks identical: repeated expressions on arrays and other reference types, the same operations written in a different order, and most calls to imported library functions are each counted, so reducing those by hand does help.

Changes that do: data, strings, functions, built-ins

1. Compute long lists instead of pasting them. Every literal number, bool and string is stored in the compiled code, and a constant passed to several calls is stored at each call. A list of hundreds of values in array.from() is one of the fastest ways to reach the limit.

// Broken pattern: every value of the list is stored in the compiled code
var array<float> weights = array.from(1.0, 0.5, 0.3333, 0.25, 0.2, 0.1667, 0.1429, 0.125) // ...and hundreds more
plot(weights.size())
// Fixed: the same list built by a loop, once, on the first bar
var array<float> weights = array.new<float>()
if barstate.isfirst
    for i = 1 to 800
        weights.push(1.0 / i)
plot(weights.size())

Filling the array on the first bar only keeps the extra run time negligible. When the values follow no formula (a table of dates, a list of symbols), they can't be computed: keep the list as short as the script needs, or move it into a library function (point 5).

2. Shorten and reuse strings. Long tooltips, alert messages and table texts are stored in full, once per place they are passed. Shorten them, build repeated texts with one str.format() call inside a loop, and give long enum members a short title.

3. Write repeated logic once, in a function. A function body is compiled once; each call only adds a reference and its arguments. Four copies of the same ten lines become one definition and four short calls:

// Fixed: one definition, four calls
zScore(float src, int length) =>
    float mean = ta.sma(src, length)
    float dev = ta.stdev(src, length)
    dev == 0 ? 0.0 : (src - mean) / dev
avgZ = (zScore(close, 20) + zScore(close, 50) + zScore(close, 100) + zScore(close, 200)) / 4
plot(avgZ, "Average z-score")

Calls with many arguments cost more than calls with few, so pass what changes and leave the rest inside the function. The functions and methods example covers the syntax.

4. Use a built-in when one exists. A built-in call usually takes fewer tokens than the same calculation written by hand, and it runs faster. The up-bar count from the top of this page needs neither 2,000 statements nor a loop:

// Fixed: one built-in call replaces the repeated statements and the loop
lookback = input.int(2000, "Bars to count", minval = 1)
count = math.sum(close > open ? 1 : 0, lookback)[1]
plot(count, "Up bars")

math.sum() adds the last lookback values and [1] shifts the window back one bar, so it covers the same bars as the loop (1 to lookback bars ago). One difference: it returns na until lookback bars exist, where the loop counts the bars available.

A caution about loops. Functions that depend on past bars, such as ta.rsi() or ta.ema(), shouldn't be moved inside a loop or an if to save tokens: they must run on every bar, and TradingView warns that the function should be called on each calculation. Put that logic in a function called from the top level instead, as in point 3. The loops example shows what is safe inside a loop.

When the script is still too large: libraries and several indicators

5. Move code into a library. A library is compiled separately and its tokens don't count toward the script that imports it; only the imported libraries' total is capped, at 1 million tokens. Large calculations, and functions that return long hard-coded lists or strings, are good candidates. Exported functions are always counted in the library itself, even when two of them are identical. The library example shows export and import in v6.

6. Split the script. An indicator that draws sessions, computes a dozen oscillators and fills a dashboard is three scripts in one. Publish the independent parts as separate indicators. When one part needs the result of another, plot the intermediate value in the first indicator and read it in the second with input.source(). TradingView's documentation gives the limits of that approach: up to 24 indicator-on-indicator connections on a chart, and at most 11 indicators chained in sequence.

After any of these changes, check the result on the chart: moving work from compile time to run time (a loop instead of literals) makes the script smaller and a little slower.

Questions

How many tokens can a Pine Script contain?

According to TradingView's documentation, the compiled form of each indicator, strategy or library can contain at most 100,256 tokens, measured after the compiler's optimizations. The libraries a script imports are counted apart and can total up to 1 million tokens.

Do comments or long variable names count toward the token limit?

No. Comments are discarded and names of variables, functions, parameters, types and fields are replaced by internal identifiers before the size is measured. Removing comments, spaces or type keywords, or renaming things, doesn't fix the error.

How can I see how many tokens my Pine script uses?

You can't for a script that compiles: TradingView doesn't show the compiled size. The limit only becomes visible when the error appears. To find what weighs the most, remove one block at a time and save again.

Does deleting unused code fix Compiled code contains too many tokens?

Usually not. Code that doesn't affect a plot, drawing, order, alert or log is already dropped by the compiler. What helps is replacing repeated statements with loops or functions, computing long hard-coded lists, using built-ins and moving code into libraries.

The scripts on this page are minimal examples written to show the error and its fix, not trading systems. Trading involves substantial risk of loss and is not suitable for every investor. Edgoro is a software tool, not a broker or financial adviser: nothing it produces is investment advice, and past or backtested performance does not guarantee future results.

Still getting “Compiled code contains too many tokens”?

Paste your script and the message into the free Pine Script error fixer: it explains what went wrong and returns a corrected v6 version. Or describe the indicator in plain English and let Edgoro write the code.