# ChartLabs CodeLab: brief for AI agents CodeLab is the TypeScript indicator editor inside ChartLabs (chartlabs.co/charts). This file tells an AI agent (Claude, Grok, Cursor, ...) how to write a custom indicator for a user and put it on their chart. Every fact and example below was checked against the real CodeLab compiler and SDK (@chartlabs/script-sdk 0.2.29). Do not rely on Pine Script habits or on other docs where they differ. ## Connect first You act through Agent Connect. If you are not paired yet, read /marketplace/api/agent/llms.txt (the user gives you a code from the "Connect an Agent" button on their chart). is the scheme and host you read this file from, e.g. https://chartlabs.co. You work on the chart the user paired you from, or on any open chart when you pass its chartId (list_charts lists them). If the paired chart is closed, calls without a chartId fail with CHART_GONE: call list_charts and pass a chartId. The open script belongs to the browser tab holding the chart, so pass the same chartId on every call of a sequence. ## The contract - ONE custom indicator = ONE CodeLab script. A change to an indicator is a change to its script, never a second script. - New indicator: codelab_new {"name": "My Indicator"} codelab_set_source {"code": ""} codelab_compile -> fix every error, compile again codelab_run -> puts it on the chart, reports what it drew codelab_save - Calling codelab_set_source again replaces YOUR script in place. The user's own scripts are never overwritten unless you pass replace:true, which runs without asking unless the user chose Ask for script edits. Only pass it when the user asked you to change that script. - After the user reloads the page, or once you codelab_open a saved script, CodeLab treats it as the user's: change it with replace:true, otherwise your code goes into a NEW script (a duplicate). - Follow-up changes: codelab_modify_indicator {"instructions": "plain English"} (ChartLabs' code writer edits, compiles and re-runs it; it spends the user's AI credits, within your daily limit, and you get one change at a time). Or codelab_read_source, edit, and codelab_set_source the corrected code. - Replacing, inserting into or renaming the user's own script runs without asking, unless the user chose Ask for script edits. If they say No, the result says the script was not changed. That is FINAL: stop, do not retry or work around it, ask the user what they want. - Not available to agents (refused if called): publishing to the community or marketplace, converting an indicator to a strategy, changing a saved script by name. The user does those in CodeLab themselves. - Limits: a script is at most 40,000 characters; 20 CodeLab changes per minute. ## Fixing without screenshots - codelab_compile -> {ok, errors: [{line, column, message}], warnings}. Syntax errors carry the line in YOUR code. - codelab_run -> {ok, stage: "compile" | "mount" | "ok", console, drawn}. stage "ok" with nothing drawn means the logic never fired; read "drawn". Runtime errors ("ta.kama is not a function", "alma is not defined") arrive here, not at compile time. - codelab_read_source pages long scripts: follow "more" and "next". - codelab_list_scripts -> scripts [{id, name, kind}], templates, the open one. ## Script shape import { indicator, input, ta, plot, close } from '@chartlabs/script-sdk'; export default indicator('Name', { placement: 'overlay' }, () => { // runs once per bar }); - placement: 'overlay' (on the price chart), 'subpane' (its own pane below, e.g. RSI) or 'widget'. Anything else fails to compile. - `export default` is required. - The body runs once per bar. Call plot(), plotShape(), hline() etc. UNCONDITIONALLY and in the same order on every bar. `if (...) plot(...)` breaks at run time. Put the condition in the value instead (plotShape(cond, ...), or colors rules on plot). - Do not redeclare SDK names at the top level (`const close = ...` fails). - Only `@chartlabs/script-sdk` can be imported, and only these names exist at run time (importing any other name compiles but throws "X is not defined"): indicator input ta plot plotHist plotShape plotChar plotCandle hline bgColor barColor fill label line box table security alpha mix makeSeries open high low close volume hl2 hlc3 ohlc4 barTime (and, for the class form: Lab compute bars barstate strategy time state persist config draw feed emit ui createBarsView) Prefer ta.* for indicators: ta.ema(...), not a top-level ema import. - No network, storage, DOM or timers-with-strings: scripts run in a locked sandbox worker. fetch, XMLHttpRequest, WebSocket, eval and Function are gone. ## Series close, high, ... and every ta.* result are Series: a per-bar value with history. - Current-first history: s[0] or s.value is this bar, s[1] the previous bar, s.offset(n) is the whole Series shifted n bars back. - JavaScript has no operator overloading, so use methods, which return Series: add sub mul div mod neg abs gt lt gte lte eq ne and or not offset iff e.g. close.gt(upper).and(isUp), bull.and(bull.offset(1).not()), cond.iff(a, b) ## ta.* (the full list) ad adx alma anchoredVwap atr barssince bbands cci change cmo cog correlation cross crossover crossunder cum dailyVwap dayOfWeek dema dev ema falling highest highestbars hma hour keltner linreg lowest lowestbars macd median mfi minuteOfDay mom newDay obv percentRank pivotHigh pivotLow rising rma roc rsi sar session sessionEnd sessionHigh sessionLow sessionStart sma stdev stoch sum supertrend swma tema tr tsi valueWhen variance vwap vwma wma wpr Multi-value results destructure: const { upper, middle, lower } = ta.bbands(close, 20, 2); const { value, direction } = ta.supertrend(high, low, close, 10, 3); // direction > 0 = up ## Inputs (settings the user can change) input.int input.float input.bool input.string input.color input.source input.timeframe input.session input.time input.text input.int('Length', 14, { min: 1, max: 200, group: 'Main', tooltip: '...' }) input.float('Factor', 3, { min: 0.5, max: 10, step: 0.1 }) ## Drawing options (exact names) plot(series, { title, color, width, style: 'solid' | 'dashed' | 'dotted', plotStyle: 'line' | 'linebr' | 'stepline' | 'histogram' | 'columns' | 'area' | 'areabr' | 'circles' | 'cross', fillColor, baseValue, offset, trackPrice, colors: [{ when: seriesCond, color }] }) Use width, not linewidth. plotShape(cond, { title, shape, color, size, location: 'above' | 'below' | 'absolute', price, text, textColor }) shape: arrowup arrowdown triangleup triangledown circle square diamond cross xcross plus flag labelup labeldown ... location is 'above' / 'below' (not 'abovebar' / 'belowbar'). hline(value, { title, color, style: 'solid' | 'dashed' | 'dotted' }) ## Complete examples (each compiles, runs and draws) ### 1. EMA cross with arrows (overlay) import { indicator, input, ta, plot, plotShape, close } from '@chartlabs/script-sdk'; export default indicator('EMA Cross Arrows', { placement: 'overlay' }, () => { const fastLen = input.int('Fast length', 9, { min: 1, max: 200 }); const slowLen = input.int('Slow length', 21, { min: 2, max: 400 }); const fast = ta.ema(close, fastLen); const slow = ta.ema(close, slowLen); plot(fast, { title: 'Fast EMA', color: '#2962FF', width: 2 }); plot(slow, { title: 'Slow EMA', color: '#FF9800', width: 2 }); plotShape(ta.crossover(fast, slow), { title: 'Bull cross', shape: 'arrowup', location: 'below', color: '#089981', size: 'small' }); plotShape(ta.crossunder(fast, slow), { title: 'Bear cross', shape: 'arrowdown', location: 'above', color: '#F23645', size: 'small' }); }); ### 2. RSI with bands (own pane) import { indicator, input, ta, plot, hline, close } from '@chartlabs/script-sdk'; export default indicator('RSI Bands', { placement: 'subpane' }, () => { const length = input.int('RSI length', 14, { min: 2, max: 200 }); const overbought = input.float('Overbought', 70, { min: 50, max: 100, step: 1 }); const oversold = input.float('Oversold', 30, { min: 0, max: 50, step: 1 }); plot(ta.rsi(close, length), { title: 'RSI', color: '#7E57C2', width: 2 }); hline(overbought, { title: 'Overbought', color: '#F23645', style: 'dashed' }); hline(50, { title: 'Midline', color: '#787B86', style: 'dotted' }); hline(oversold, { title: 'Oversold', color: '#089981', style: 'dashed' }); }); ### 3. Bollinger Bands + SuperTrend breakouts (Series math, colour rules) import { indicator, input, ta, plot, plotShape, close, high, low } from '@chartlabs/script-sdk'; export default indicator('BB + SuperTrend', { placement: 'overlay' }, () => { const bbLen = input.int('BB length', 20, { min: 2, max: 500, group: 'Bollinger Bands' }); const bbMult = input.float('BB multiplier', 2, { min: 0.1, max: 10, step: 0.1, group: 'Bollinger Bands' }); const stLen = input.int('ATR length', 10, { min: 1, max: 200, group: 'SuperTrend' }); const stFactor = input.float('Factor', 3, { min: 0.5, max: 10, step: 0.1, group: 'SuperTrend' }); const firstOnly = input.bool('Only first bar outside the band', true, { group: 'Signals' }); const { upper, middle, lower } = ta.bbands(close, bbLen, bbMult); const { value: stLine, direction } = ta.supertrend(high, low, close, stLen, stFactor); plot(upper, { title: 'BB Upper', color: '#2962FF', width: 1 }); plot(middle, { title: 'BB Basis', color: '#787B86', width: 1 }); plot(lower, { title: 'BB Lower', color: '#2962FF', width: 1 }); const isUp = direction.gt(0); const isDown = direction.lt(0); plot(stLine, { title: 'SuperTrend', color: '#FFB74D', width: 2, colors: [{ when: isUp, color: '#089981' }, { when: isDown, color: '#F23645' }], }); const bullRaw = close.gt(upper).and(isUp); const bearRaw = close.lt(lower).and(isDown); const bull = firstOnly ? bullRaw.and(bullRaw.offset(1).not()) : bullRaw; const bear = firstOnly ? bearRaw.and(bearRaw.offset(1).not()) : bearRaw; plotShape(bull, { title: 'Bull breakout', shape: 'triangleup', location: 'below', color: '#089981', size: 'small' }); plotShape(bear, { title: 'Bear breakout', shape: 'triangledown', location: 'above', color: '#F23645', size: 'small' }); }); ## More - Human docs: /docs (CodeLab SDK reference and tutorial) - Product page: /codelabs - Agent Connect (pairing and every tool): /marketplace/api/agent/llms.txt