Skip to content

MCP Integration

chartgen speaks the Model Context Protocol over both stdio (Claude Desktop) and HTTP (Claude.ai). Both transports share the same tool definitions.

The HTTP transport implements MCP Streamable HTTP, spec 2025-03-26. See ADR-0002 for the migration rationale.

Time units. t and fields ending in _t are unix seconds (chart coordinates). Fields ending in _time or _at are unix milliseconds. The one exception is server alerts’ bar_time, which is in seconds and stays so for webhook compatibility.

Add chartgen to claude_desktop_config.json:

{
"mcpServers": {
"chartgen": {
"command": "/path/to/chartgen",
"args": ["--mcp"]
}
}
}

Claude.ai — Streamable HTTP (2025-03-26) + OAuth 2.1 PKCE

Section titled “Claude.ai — Streamable HTTP (2025-03-26) + OAuth 2.1 PKCE”

Run chartgen --serve behind a TLS-terminating reverse proxy and add https://<your-domain>/mcp (for example https://chartgen.example.com/mcp) as a remote MCP connector. OAuth is handled by chartgen — see the OAuth reference for the endpoint catalog and token lifetime.

The connector uses a single endpoint — /mcp — in two modes:

  • POST /mcp — JSON-RPC 2.0 request/response. The server negotiates Content-Type based on the client’s Accept header. Streamable HTTP clients send Accept: application/json, text/event-stream; chartgen’s synchronous tool calls return Content-Type: application/json with the JSON-RPC response in the body. A client that explicitly excludes JSON (e.g. Accept: text/plain) receives 406 Not Acceptable. A missing Accept header is tolerated and treated as application/json.
  • GET /mcp — optional server-initiated SSE stream. Used to deliver push notifications such as notifications/alert_triggered and notifications/chart_tick as raw JSON-RPC notification frames — see push notifications and subscribe_chart. Requires the Bearer token in the Authorization header.

Mcp-Session-Id is supported: if a client sends the header on a POST /mcp request, the server echoes it back unchanged. An initialize request without one gets a freshly minted id, which spec-compliant clients then send on every request, including GET /mcp. chartgen’s tool calls are stateless (auth is per-request via the Bearer token). The state keyed on the session is chart push, subscribe_chart pushing over the SSE stream opened with the same token and session id, and which sessions the server gave out since it started (below). A POST made only of notifications or responses (one, or a batch), such as notifications/initialized or notifications/cancelled, is answered with 202 Accepted and no body.

After a restart, a client hears that the tools may have changed (ADR-0074). initialize advertises capabilities.tools.listChanged: true. The server keeps the session ids it gave out since it started. The first POST with an id it did not give out, which was given out before a restart (by a build with other tools, maybe), is answered as an event stream when its Accept takes text/event-stream (not with q=0): first {"jsonrpc":"2.0","method":"notifications/tools/list_changed"}, then the answer itself, each as an event: message. Once per session; the next POSTs get JSON again. A client then reads tools/list again. An initialize, an answer that is not 200, and a client that takes only JSON are answered as before. A script that sends a session id should send Accept: application/json only, or read every event of a stream: after a restart, one answer of its session comes as two events, the notice first.

POST / and POST /message are retained as deprecated aliases of POST /mcp, and GET /sse is retained as an alias of GET /mcp, for backwards compatibility with existing Claude.ai connector deployments that predate Streamable HTTP or were added with the root URL. GET / is not MCP: it serves the web app to browsers and the health JSON to everyone else (ADR-0027).

prompts/list and prompts/get serve one prompt, draw-on-chart (ADR-0054): the workflow for drawing on a chart — inspect_chart, anchor points to its swing highs and lows with snap, generate_chart with drawings, check the image and warnings, then give the user open_url — with three worked examples: a trend line between two swing lows, a support zone with cgRect, and a fib retracement from a swing high to a swing low. initialize announces the prompts capability. An unknown prompt name is a -32602 error.

23 tools. The 12 trading tools require --trade; attempting to call them without it returns an error. With CHARTGEN_SCRIPTING=1 the server also lists the 5 scripted-indicator tools, and with CHARTGEN_SERVER_ALERTS=1 the 4 server alert tools. With CHARTGEN_SETUPS=1, or on a replay server, it lists the 5 setup tools.

Render a chart for a symbol. Accepts ticker/symbol, timeframe/interval, indicators (string names or objects with overrides), bars (default 200), width, height, format, end_time, warmup, profile_intrabars, chart_style, chart_params and drawings.

ParameterMeaning
width, heightIntegers, default 1920 and 1080. For png and both. Not clamped: bars × (indicators + 1) + width × height / 512 must fit the 32,000 one call may hold, or the call is refused with -32602.
barsInteger, default 200. Capped at 5000 in every format (png, summary, both, series); larger values are silently clamped. On Binance each 1000 bars is one upstream request.
end_timeInteger, ms since epoch, between -2208988800000 (1900-01-01; index histories predate 1970) and one year from now. Only bars whose open time is strictly before end_time are returned. To load the page before the oldest bar you have, pass that bar’s t × 1000. Omit it (or send null) to get the newest bars, including the candle that is still forming. Applies to every format. A string, a float or an out-of-range value is a tool error.
warmupInteger, default 0, max 1000. format=series only. Fetches this many extra older bars and feeds them to the indicators, then trims them from the response, so the first returned bars have warmed-up values instead of null. png, summary, and both ignore it: with indicators and a ticker they always read what those need to converge, at least 300 bars (the web chart’s warmup) and at most 1000, and still show exactly bars; the demo series without a ticker reads none (ADR-0056).
profile_intrabarsBoolean, default false. format=series only. Computes volume_profile, fixed_range_vp and anchored_vp from lower-timeframe bars, for up to 6 more Binance requests (ADR-0048). Meant for a chart’s full load: pages and tails keep the load’s profile, so leave it off on those.
chart_stylecandles (default) or heikin_ashi. heikin_ashi replaces the price bars with Heikin Ashi bars in every format: haClose = (o+h+l+c)/4, haOpen = (prev haOpen + prev haClose)/2 (the first bar is seeded with (o+c)/2), haHigh = max(h, haOpen, haClose), haLow = min(l, haOpen, haClose); volume and timestamps are unchanged. Like TradingView, indicators are computed on the Heikin Ashi values, not the raw bars. The transform runs over bars + warmup before trimming, and because each haOpen is an exponentially decaying average, pages and tail polls with the same warmup agree after a few bars. format=series echoes the applied style as chart_style. renko, kagi, point_figure, line_break and range are price-based. Any other value is an error.
chart_paramsInputs of a price-based style, and an error with any other style.
drawingsUp to 50 drawings on the price chart, in the web app’s drawing tools. See Drawings.

timeframe is a number and a unit: s seconds, m minutes, h hours, d or D days, w, W or wk weeks, and M or mo months (5s, 7m, 45m, 90m, 8h, 2D, 2W, 3M). Lowercase m is minutes and uppercase M months; the other units take either case. Anything else is a tool error that says what is wrong. ADR-0038 explains the limits:

  • Upper bounds, after normalization: under 60 seconds, under 1440 minutes, then 168h, 365D, 52W and 12M. Not every length below a bound parses, as the next rule says. 60s is 1m and 1440m is 1d.
  • Seconds need a Binance spot symbol: 1s is its own kline, and the rest are resampled from it. Yahoo has no seconds data, so a stock returns an error saying so.
  • A minute or hour interval may take at most 60 native bars per bar, counted on Binance’s klines for every symbol. Every length up to 60 minutes qualifies; 61m needs 61 1m klines and is rejected, while 65m needs 13 5m klines and is fine, and 1439m is rejected. Days, weeks and months have no such rule: 365D takes 365 1d klines.

The response’s interval is the canonical form, and the same bars have one name: 120m is 2h, 24h is 1d, 7d is 1wk, 2W is 2wk, 1M is 1mo.

Where a source has the interval, its own bars are served. Otherwise bars come from the coarsest native interval that divides it and are resampled:

SourceNativeBuilt from
Binance1m 3m 5m 15m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w 1M7m from 1m, 45m from 15m, 90m from 30m, 10h from 2h, 6d from 3d, 2W from 1w, 3M from 1M
Yahoo1m 2m 5m 15m 30m 1h 90m 1d 1wk 1mo7m from 1m, 6m from 2m, 45m from 15m, 8h from 1h, 2D from 1d, 2W from 1wk, 2M and 3M from 1mo

Bars land on a stable grid, so a reload gives the same bars:

  • 24/7 symbols, minutes and hours. A grid counted from the unix epoch. It agrees with Binance’s klines at every interval Binance has.
  • Exchange-traded symbols, minutes and hours. Buckets start at each session’s open, and a session’s last bucket may be shorter, as on TradingView.
  • Days. Calendar days counted from epoch day 1, where Binance’s 3d klines open. A stock’s 2D bucket with no trading day in it has no bar, and one with a single trading day holds that day alone.
  • Weeks. Counted from Monday 1970-01-05, so 2W opens every second Monday.
  • Months. Counted from January 1970, so 3M is a calendar quarter and 12M a calendar year.

A custom interval on Binance reads at most 20 requests’ worth of native bars per call (20,000). That caps the bars fetched, which also supply warmup; the response returns at most bars of them. A 59m call fetches about 338 bars, so one asking for bars: 2 returns 2, computed over those 338, and one asking for bars: 500 returns the 338 with has_more: true, though it asked for more, and older bars come from paging. Warmup past the cap is simply shorter, and paging does not restore it: a page, a poll and a push each compute over their own capped read. With warmup: 1000 on 59m, an indicator with a very long window stays null or unconverged on every one of them. Calls for the newest bars share native klines read in the last 2 minutes, so after the first, polling a tail costs one request whatever its warmup.

The server holds one budget for all its Binance requests. After Binance answers 429, 418 or 403 nothing is sent until its Retry-After has passed, and nothing starts once 80% of the weight for the minute is used. Such a call is a tool error starting Binance rate limit: that names the wait. Retry after it.

With a ticker, a failed upstream fetch (network error, unknown symbol, rate limit) is a tool error in every format. Only a call without a ticker renders the synthetic demo series.

format values:

ValueOutput
png (default)Base64-encoded PNG of the rendered chart.
summaryCompact JSON: OHLCV stats, last indicator values, signal dots, divergences, and horizontal reference levels. Typically 10–50× fewer tokens than a PNG — ideal for automated analysis without vision.
bothPNG plus the JSON summary.
seriesFull per-bar time-series JSON: every OHLCV bar plus indicator value arrays aligned 1:1 with bars (NaN → JSON null for pre-warmup), signals with bar timestamps, hlines, and y_range. Useful for downstream numeric computation that needs raw arrays rather than last values.

In the image:

  • The price pane’s range fits the candles, as the web chart’s does. An overlay value past it (a far pivot level, an envelope band) is cut off where it leaves the pane, never drawn on its edge.
  • A panel’s range is its indicator’s own (CCI ±250, RSI 0–100, which keeps its reference lines in place), grown when the values go past it, or with none, its values’.
  • The last price is tagged right of the plot, and there is a bar of room before the first candle and after the last.
  • Values plotted past the last bar (the Ichimoku cloud, the series’ future) are drawn there.
  • A fixed range or anchored volume profile sits over the bars it was read from, with its POC, VAH and VAL across them alone and its edges dashed.
  • A legend shows — for a line with a single value: nothing of it is drawn, and it is not warmed up. A panel with a histogram and no line shows the histogram’s last value (Funding: 0.0100).

Example request:

{
"name": "generate_chart",
"arguments": {
"ticker": "BTCUSDT",
"timeframe": "1h",
"indicators": [
"ema_stack",
{ "name": "rsi", "length": 21 },
{ "name": "vpvr", "bins": 32, "split_up_down": true }
],
"bars": 200,
"format": "summary"
}
}

Summary payload shape (for format=summary or format=both):

{
"symbol": "BTCUSDT",
"interval": "1h",
"price": {
"bars": 200,
"first": { "date": "...", "open": 66900.1, "close": 66950.2 },
"last": { "date": "...", "open": 67400.0, "high": 67500.0,
"low": 67320.0, "close": 67432.5, "volume": 128.4 },
"range": { "high": 67980.0, "low": 65010.5 },
"total_volume": 18342.7,
"change_pct": 0.79
},
"indicators": {
"rsi": {
"label": "RSI(21)",
"is_overlay": false,
"y_range": [0.0, 100.0],
"lines": [{ "index": 0, "label": "RSI", "last_value": 62.4 }],
"signals": [{ "x": 197, "y": 72.1, "label": "rsi_overbought" }],
"hlines": [{ "y": 30.0 }, { "y": 70.0 }]
}
}
}

Fields are keyed by the name each indicator was requested with, so {"name": "rsi", "length": 21} comes back as indicators.rsi. A line’s last_value is its last finite value. Lines that break at a trend flip (Supertrend’s and Parabolic SAR’s up and down lines) report their value at the last bar instead, null when they have none there: only the active one has a value. In format=series those lines carry "breaks": true, which the web legend uses the same way.

chart_patterns adds patterns: key, name, bias, status, tooltip, optional target, invalidation and confirmed_x (a bar index), and the times and height of each.

renko, kagi, point_figure, line_break and range are built on the server from the bars of timeframe, and indicators run on them (ADR-0047). They are built from candles, not ticks, so they only approximate what the same types show on tick data: within one source bar the order of moves is unknown.

chart_params keyForDefaultMeaning
boxall but line_breakatratr, fixed or percent. The box of renko and point_figure, the reversal amount of kagi, the size of range.
atr_lengthbox: atr141 to 500, over closed source bars.
percentbox: percent1Of the last price, above 0 and at most 100.
box_sizebox: fixed, or to keep a boxA fixed box’s size, required. With atr or percent, the size to use instead of resolving one.
reversalpoint_figure3Boxes to start a new column, 1 to 20.
linesline_break3Lines a close must pass to reverse, 1 to 20.

Unknown keys are errors. atr and percent round to two significant digits. format=series and summary echo chart_params with the box_size used. Send that box_size back on later polls, pages and subscriptions, or each call may resolve another box and the bars will not line up. subscribe_chart refuses an atr or percent box without one, so load first.

  • Times are when a bar opened: the first source bar after the last confirmed one. Bars from one source bar take the next free second, so times always increase and are not evenly spaced. end_time works as for candles.
  • profile_intrabars plans its read on the time the bars cover, not on how many there are. A profile whose bars cover too long a time for finer bars stays computed from its own bars, with no profile_interval.
  • The last bar is open. Only closed source bars confirm a bar. The open bar keeps its t when confirmed, so overwrite by t. On kagi and point_figure it is the current line or column. The newest bar of any live build closes on the last price, so its close can read past a level until the next call.
  • anchor in format=series is the time of the first source bar the build used. A later one is a new build, whose bars need not line up with an earlier call’s: replace yours from the tail’s first bar on. This happens every 1000 source bars on Binance, and sooner on Yahoo.
  • Reads take a fixed window of source bars, up to 5000, within the 20,000 native bar limit, from a start on a fixed grid of time. warmup does nothing here: every bar of the window warms the indicators. A window may hold fewer bars than bars, with has_more: true.
  • Tails: ask for more than 2 bars, as one source bar can confirm several. subscribe_chart pushes 64 bars first, then the bars since its last push plus one of overlap, never more than 64. More new bars than that, or joining a subscription already running, can give a tail that starts past your newest bar. Bars are then missing: call generate_chart again rather than merging it.
  • Refused: a box under a millionth of the last price, one that would make over 20,000 bars, and any of these styles without a ticker on the demo series.
  • Indicators that project past the last bar return no future. The PNG draws these bars as candles, including kagi and point_figure, and its title names the type and box.

The same indicator may be requested more than once, with different parameters (ADR-0028). Each entry gets its own key in indicators and indicator_errors (every format), so results map back to their entries whatever the order:

  • An object entry with an id (a string of 1 to 64 characters) is keyed by its id. The id only names the result and is not a parameter.
  • An entry without an id is keyed by its name. A name that is already taken gets name#2, name#3, and so on. Explicit ids are reserved first, so an automatic key never takes one.
  • A repeated id, or an id that is not a 1 to 64 character string, is a tool error (Duplicate indicator id: …, Invalid indicator id: …).
  • An id equal to the name of an entry without an id is a tool error, since both would get that key (Indicator id macd is also the name of an entry without an id; give that entry an id too).
  • generate_chart asks for at most 32,000 bars × (indicators + 1), which is 5000 bars with 5 indicators or 627 with 50. Some indicators count as more than one, for what they draw: cipher_b as 4, candlestick_patterns as 3, and kalman_volume, rsi_mfi_stoch, ichimoku, wavetrend and fear_greed as 2, under any of their names. A price-based chart_style counts as 1200 bars more, as its indicators run on every brick it builds, up to 20,000: 500 bars of it take at most 17 indicators. With format png or both, an image adds width × height / 512: 4050 at the default 1920 × 1080, and 31,250 at 4000 × 4000, which leaves room for 750 bars × (indicators + 1). A 5000-bar image takes at most 4 indicators at the default size. A larger call gets a -32602 error saying so, as it would take too much memory at once (ADR-0051, ADR-0052). Calls share that amount while they are built; then each keeps only its answer, a unit a KiB, until that has gone out. One that waits 20 s for its turn gets 503 with Retry-After: nothing has run, so ask again.
  • generate_chart takes at most 50 entries (At most 50 indicators per chart.); subscribe_chart at most 10.
"indicators": [
{ "name": "rsi", "length": 14 },
{ "name": "rsi", "length": 21, "id": "rsi#2" },
{ "name": "ma", "type": "ema", "length": 20 },
{ "name": "ma", "type": "ema", "length": 50 }
]

comes back keyed rsi, rsi#2, ma and ma#2. The web app sends <name>#<n> ids for every instance after the first. Push tails (subscribe_chart) use the same keys.

Series payload shape (for format=series):

{
"symbol": "BTCUSDT",
"interval": "1h",
"bars": [
{ "t": 1713420000, "o": 66900.1, "h": 67100.0, "l": 66850.0, "c": 67050.5, "v": 128.4 },
{ "t": 1713423600, "o": 67050.5, "h": 67220.0, "l": 67010.0, "c": 67180.0, "v": 96.2 },
{ "t": 1713427200, "o": 67180.0, "h": 67340.0, "l": 67120.0, "c": 67290.5, "v": 104.8 },
{ "t": 1713430800, "o": 67290.5, "h": 67500.0, "l": 67240.0, "c": 67432.5, "v": 128.4 }
],
"indicators": {
"rsi": {
"label": "RSI(21)",
"is_overlay": false,
"y_range": [0.0, 100.0],
"lines": [
{ "index": 0, "label": "RSI", "values": [null, null, 68.2, 72.1], "color": "rgba(195,62,225,0.8)", "width": 2 }
],
"signals": [
{ "x": 3, "t": 1713430800, "y": 72.1, "label": "rsi_overbought", "color": "rgba(225,62,62,1)" }
],
"hlines": [
{ "y": 30.0, "color": "rgba(62,225,69,0.3)" },
{ "y": 70.0, "color": "rgba(225,62,62,0.3)" }
]
},
"volume": {
"label": "Volume",
"is_overlay": false,
"lines": [
{ "index": 0, "label": "Volume MA", "values": [null, null, null, 114.5], "color": "rgba(41,98,255,1)", "width": 1 }
],
"histogram": [
{
"index": 0,
"label": "Volume",
"values": [128.4, 96.2, 104.8, 128.4],
"palette": ["rgba(38,166,154,0.5)", "rgba(239,83,80,0.5)"],
"color_idx": [0, 0, 0, 0]
}
]
},
"bbands": {
"label": "BB",
"is_overlay": true,
"lines": [
{ "index": 0, "label": "upper", "values": [null, null, 67400.5, 67511.7] },
{ "index": 1, "label": "middle", "values": [null, null, 67051.3, 67163.1] },
{ "index": 2, "label": "lower", "values": [null, null, 66702.1, 66814.5] }
],
"fills": [
{ "y1": [null, null, 67300.1, 67410.9], "y2": [null, null, 66802.4, 66915.3], "color": "rgba(33,150,243,0.1)" }
]
},
"vpvr": {
"label": "VPVR",
"is_overlay": true,
"hbars": [
{ "y": 67432.5, "height": 12.1, "width": 0.82, "offset": 0.0, "left": true, "color": "rgba(41,98,255,0.4)" }
]
},
"cipher_b": {
"label": "Cipher B",
"is_overlay": false,
"divlines": [
{ "x1": 12, "t1": 1713427200, "y1": 30.2, "x2": 48, "t2": 1713556800, "y2": 18.7, "dashed": true, "color": "rgba(255,0,0,0.8)" }
]
}
},
"has_more": true
}

bars[i] aligns 1:1 with every indicators.*.lines[*].values[i] (and indicators.*.histogram[*].values[i] when an indicator emits histogram bars, e.g. MACD). Pre-warmup indicator values are null (not truncated). Each signal carries both x (bar index) and t (unix seconds from the source feed, or null for synthetic sample data). format=series is exclusive — no PNG companion, a single text content item.

Three additional channels round out the payload so the full set of PanelResult data an indicator emits is renderable on the wire — see ADR-0007:

  • fills — shaded regions between two y-series (Bollinger Bands, Keltner Channels, Ichimoku cloud, VWAP bands). y1 and y2 are arrays aligned 1:1 with bars[]; pre-warmup values are null.
  • profile_interval — on a profile that read lower-timeframe bars because profile_intrabars asked (volume_profile, fixed_range_vp, anchored_vp), which ones. Absent means it spread the chart’s own bars (ADR-0048).
  • level_lines — true when the lines hold levels (session_vp): a change of value is a jump from one to the next, not a slope, and is not drawn. So a session of one bar draws nothing: with the default daily session, that is 1d and above.
  • hbars — horizontal bars at price levels, used by volume-profile indicators (VPVR, Session VP, HVN/LVN, Naked POC, TPO). Each bar has a price-space y and height, axis-relative width and offset (0.0–1.0 as a fraction of chart width), and a boolean left that tells the renderer which edge of the chart to anchor against.
  • divlines — two-point diagonal segments for divergences (WaveTrend/RSI divergences in Cipher B, for example). Each endpoint carries both x (bar index) and t (unix seconds, or null for synthetic sample data), mirroring the signal shape, plus dashed.
  • labels — text labels on bars (candlestick_patterns): x, t, y (the bar’s high or low), above, text, key, name, bias, color and tooltip. tentative: true marks one on the forming bar, which can change or vanish until the bar closes.
  • patterns — detected shapes (chart_patterns, the swing of auto_fib): key, name, bias, status (forming, confirmed or failed), strokes (two-point segments as in divlines), label, tooltip, and optional target, invalidation and confirmed_t. A chart_patterns one also carries its times and height.
  • levels — lines[line] is flat at y from bar x on (auto_fib).
  • events — what an alert can wait for: key, name and t, the bar time of the newest occurrence on a closed bar, or null.

patterns, levels and events are re-detected as a whole (ADR-0046), so every response holds all of them, tails included: an index before the response’s first bar is negative, and t still names the bar. Take them from your newest response and ignore those on older history pages. A new swing moves a level on every bar, so rewrite that plot from levels instead of merging its values. These indicators raise warmup to their lookback. signals only hold detections on the newest closed bar, for indicator_signal alerts (see the conditions that needs). As the 600-bar window slides, chart_patterns’ older patterns can change, and an event’s t can fall back to an older bar or to null and return. To tell a new detection, take a t newer than any you saw and no older than the newest bar of your previous response. format=summary and png take no warmup, so chart_patterns and auto_fib read only the bars you ask for: ask for 600 to match the web chart.

Each chart_patterns pattern, in format=series and in format=summary (so also get_indicators), says when it happened, as bar open times in ms since epoch (unlike t, which is in seconds):

FieldMeaning
start_time, end_timeFirst and last bar of the pattern before any breakout: its first and last pivot.
known_timeFirst bar with its last pivot known, depth bars after it. Only closes from here on can confirm or fail it.
confirmed_timeThe bar whose close broke its line, or null.
failed_timeThe bar that failed it, or null. A pattern that failed after a confirmation has both.
heightIts height in price, as the measured move uses it: target is the broken line’s value on the confirming bar, plus or minus height. For a triangle, wedge, channel or rectangle, the distance between its lines at its first pivot; for a flag or pennant, the pole; for a head and shoulders, the head over the neckline; for a double or triple top or bottom, the extreme past the neck.

target and invalidation are there as before. A series without bar times (the demo series) has no time fields. A descending triangle that failed, abridged:

{
"key": "descending_triangle", "name": "Descending Triangle", "bias": "bearish", "status": "failed",
"start_time": 1762200000000, "end_time": 1762632000000, "known_time": 1762704000000,
"confirmed_time": null, "failed_time": 1762790400000,
"height": 142.6
}

Key a pattern by (key, start_time) to follow it across calls, attach drawings to it, or score it later. Patterns are re-detected on each call from the last lookback (600) closed bars, and that window’s start moves its first swings: in the newer half of the window a confirmed pattern stays, but in the older half patterns can appear and disappear as the window slides (ADR-0046). So a pattern missing from a later response is not proof that it failed; only failed_time says that. To score the detector, record each pattern while it is in the newer half.

An indicator that plots past the last bar also carries a future block (ADR-0033). Today that is ichimoku: TradingView draws its cloud displacement - 1 bars ahead of price.

"future": {
"bars": 25,
"t": [1713571200, 1713585600, ...],
"lines": [{ "index": 2, "values": [67120.4, ...] }, { "index": 3, "values": [66410.0, ...] }],
"fills": [{ "index": 0, "y1": [67120.4, ...], "y2": [66410.0, ...] }]
}
  • bars is the number of bars after the last one, at most 500. Value j of every array belongs to the j-th of them.
  • lines[k].index and fills[k].index name the line or fill the values continue: Senkou A (line 2), Senkou B (line 3) and the cloud (fill 0).
  • t is those bars’ open times: the last bar’s time plus j + 1 intervals, on 24/7 symbols. Month-based bars (1M, 3M, 2mo) step by calendar months. Exchange-traded symbols follow the exchange’s regular session, from Yahoo’s metadata, in its time zone: intraday bars stay between open and close and restart at the next open, and day bars stay on trading days. Saturday and Sunday each count as closed when no loaded bar falls on them, and a Sunday with neither a Friday nor a Saturday means a Friday and Saturday weekend. Without a session, as for crypto, a day closes only if the bars could have shown otherwise: 7 days of 1d bars, or 5 cycles of 7 longer ones. US-listed equities, ETFs, indices and mutual funds also skip the holidays of the NYSE’s published calendar, for 2026 to 2028, on intraday and day bars. Weekly and monthly bars stay on their calendar grid, so one can fall on a holiday. An early-close day is not skipped: its bars stop at the 13:00 New York close. Other exchanges’ holidays, US indices quoted from Chicago (^VIX, ^TNX), and US dates past 2028 are not skipped. Futures step through their breaks. See ADR-0038. t is absent when the bars have no timestamps.
  • The per-bar arrays are unchanged, so clients that ignore future keep working. Every series response carries the block, tails and pushes included: the forming bar moves the newest projected values. Take it from your newest response and ignore the one on older history pages.

Every item of fills, hbars, divlines and hlines also carries a color: a CSS "rgba(r,g,b,a)" string with the color the PNG renderer uses, so clients can match the PNG exactly (ADR-0012). A fill may also carry color_below, used where y1 < y2 (color applies where y1 >= y2); it is omitted when the fill has one color. Older servers omit color; clients should fall back to their own theme.

Plots carry their colors too (ADR-0026):

  • Each item of lines has color (same CSS form) and width, the stroke width in px.
  • Each item of histogram has a label for legends. It is the indicator’s label ("Volume", "AO"), or "Histogram" when a line already has that name (MACD), numbered when there are several.
  • Each histogram also has per-bar colors in compact form: palette lists each distinct color once, in order of first appearance, and color_idx[i] is the index into palette of bar i’s color, aligned 1:1 with values. It is null where the value is null or the bar has no color. Palettes are per response, so a client joining two responses (a history page, a tail) remaps the indices rather than concatenating them.
  • Each signal has the color of its dot.

All of these are omitted by older servers.

All three channels are omitted from the per-indicator object when the indicator emits none — matching the existing convention for lines, histogram, signals, and hlines.

See ADR-0009. For Binance symbols over HTTP, subscribe_chart pushes the same tail instead of you polling for it.

  • Live tail. Poll { "format": "series", "bars": 2, "warmup": 200 } every few seconds. The last bar is the candle still forming, and the one before it is the last closed bar. Merge both into your arrays by t. Yahoo stamps its live bar with the last trade time; chartgen snaps it back onto its period start, so t always lands on the bar grid.
  • Older history. Request { "format": "series", "bars": 500, "warmup": 200, "end_time": <bars[0].t of your oldest page × 1000> }. The new page ends right before end_time, so pages join without gaps or duplicates.
  • has_more (boolean, always present in format=series) is true when older history may exist before bars[0]. For Binance and the sample source that means the read got all it asked for: the full bars + warmup count or, for an interval built from finer bars, the 20,000-kline cap. So a capped page can be shorter than bars and still report true. For Yahoo it means the request window was not cut off by Yahoo’s lookback limit or the symbol’s first trade date, so a short page (for example 2000 1m bars when one 7-day window only holds about 1950) still reports true. It is false when history ran out (the page can be shorter or empty) and for the no-ticker demo series, which has no timestamps.
  • Volume profiles on partial responses. vpvr, fixed_range_vp, anchored_vp, hvn_lvn, and tpo are computed over the bars of the response they arrive in. Keep their hbars and profile-derived hlines (POC/VAH/VAL, HVN/LVN nodes) from the initial full load, and ignore them on tail-poll and history-page responses, which cover only a slice of the chart.

How warmup trims the channels: bars[], lines, histogram (with its color_idx), and fills keep only their last bars entries. Signal x values are shifted to the trimmed window, and signals inside the warmup are dropped. Divlines that end at or before the first returned bar are dropped. Divlines that cross into the window are clipped to start at bar 0, with y1 interpolated. For windowed profiles (vpvr, fixed_range_vp, anchored_vp, hvn_lvn, tpo), hbars and hlines are recomputed over the returned bars only. y_range and the hlines of every other indicator don’t change.

A non-zero warmup is raised to what the requested indicators need to converge, up to 1000 (ADR-0032). ema_stack needs 891 bars, so its EMA 200 is computed over at least that many and matches one long request to within 0.01% at a page seam or on a tail. The exception is a Binance interval built from finer bars when the 20,000-kline cap leaves fewer than that: a 59m read holds about 338 bars, so these guarantees do not hold there. The other EMA/RMA-based built-ins (ma, ma_ribbon, envelopes, keltner, rsi, atr, adx, supertrend, macd, stoch_rsi, trix, ppo, tsi, smi_ergodic, elder_force_index, volume_oscillator, connors_rsi, kalman_volume) declare it from their parameters. The community composites (cipher_b, wavetrend, rsi_mfi_stoch) and user scripts keep the warmup you send. ichimoku declares its longest window plus displacement - 1 (77 bars at the defaults), so a tail’s leading spans and future block match one long request. warmup: 0 is never raised. Smoothings beyond the cap (an EMA longer than 224, an RMA longer than 126) can still differ slightly at a seam, running sums (OBV, CVD, A/D line) by a constant offset, and VWAP until its next session reset. Finite-window indicators (SMA, Bollinger Bands, Donchian) match exactly once warmup covers their lookback. When history runs out, has_more stays true as long as the response fetched more bars than it returned, so the next page brings the trimmed warmup bars. has_more is never true with an empty bars: if trimming would leave no bar (bars: 0), the fetched bars come back instead, with indicator values null where they have not converged, and has_more is false.

Upstream limits: Binance requests are paginated at 1000 bars per call. Yahoo intraday history ends after about 30 days for 1m, 60 days for other sub-hour intervals, and 730 days for 1h, and an interval built from one of them ends with it: 7m has 30 days of history on a stock, 45m 60 and 8h 730. Each upstream request times out after 10 s, and a paginated Binance fetch gives up after 20 s.

Daily and longer Yahoo bars (1d, 3d, 5d, 1wk, 1mo, 3mo) are stamped at 00:00 UTC of the exchange-local date, using the exchange’s gmtoffset. Yahoo itself stamps them at the session open, which for ASX in AEDT or NZX falls on the previous UTC day, so a UTC date read from the stamp would be one day early. Binance date bars already open at 00:00 UTC. A history page’s end_time is compared against these stamps.

Yahoo has no native 3m, 2h, 4h, 6h, 12h or 3d, so chartgen builds them from 1m, 1h and 1d bars (Binance serves all of them natively):

  • 2h, 4h, 6h, 12h are anchored at each session’s open, like TradingView: a US stock gets 09:30–13:30 and 13:30–16:00 ET at 4h, the second one shorter; at 12h each session is one bar. A session ends where two consecutive source bars are more than an hour apart, so the overnight gap, a futures daily break (ES=F trades 18:00–17:00 ET and restarts its buckets at 18:00) and a lunch break that leaves a gap in Yahoo’s rows each start a new session, so such a market anchors its afternoon separately. Tokyo, Shanghai and Hong Kong keep null rows through lunch, so theirs stays on the morning’s grid. Each bucket’s t is its slot on the session’s grid. Crypto (BTC-USD) and FX (EURUSD=X) trade around the clock and use the UTC grid instead, with t at the grid start.
  • 3m uses the UTC grid for every symbol (exchanges open on 15-minute boundaries, so it matches the session grid). It inherits the 1m limits: about 30 days of history and 7 days per request, so the first load of a stock covers roughly 4 to 5 sessions.
  • 3d groups three calendar days counted from the Unix epoch, on the same grid as Binance’s 3d klines (epoch days with day % 3 == 1). For stocks this means calendar-day buckets that can hold fewer than three trading days. TradingView likely buckets by trading sessions, a known divergence.
  • A zero-volume 1m or 1h print outside the regular session (Yahoo’s phantom print at the close) is merged into the previous bar instead of becoming a bar of its own.

A built-in never fails, but a scripted indicator can, for example by hitting its time limit. A failing indicator is left out of indicators, the rest of the chart renders, and the payload (summary, series, both) gets a top-level map keyed like indicators:

"indicator_errors": {
"my_osc": { "step": "runtime", "line": 7, "message": "time limit exceeded" }
}

line is 1-based, or null when unknown. With format=png the map comes as a second text content item, {"indicator_errors": {...}}. The field is absent when every indicator computed (ADR-0025).

An agent draws on the chart with the web app’s own 18 drawing tools, and the result opens in the web app as normal drawings (ADR-0054). Each drawing is {tool, points, style?, text?}:

FieldMeaning
toolOne of the names list_drawing_tools lists: segment, rayLine, straightLine, horizontalStraightLine, horizontalRayLine, verticalStraightLine, parallelStraightLine, fibonacciLine, cgRect, cgText, simpleTag, cgFibExt, cgPitchfork, cgPriceRange, cgDateRange, cgDatePriceRange, cgLong, cgShort.
pointsExactly the tool’s points, in its order (1 to 3). A point is {"time": T, "price": P}, or an anchor {"time": T, "snap": "open" | "high" | "low" | "close"} that takes that bar’s value. T is unix seconds (below 1e11), unix ms, or ISO 8601 (2026-10-12, 2026-10-12T14:00:00Z; UTC unless it has an offset). It resolves to the bar containing it; past the last bar, to that bar’s grid, rounded to a bar. A snap needs a loaded bar.
styleThe web app’s style bar fields for the tool: color, width (1-4) and dash (solid, dashed, dotted) on lines and shapes, fill on cgRect and the three ranges, color and fontSize (10, 12, 14, 18, 24) on cgText. Colors are #rgb, #rrggbb, #rrggbbaa or rgba(r, g, b, a). Absent fields take the tool’s own look. A field that does not apply is an error.
textcgText’s text, required there, on one line: 1 to 200 characters, counted in UTF-16 units as the web app counts them (an emoji counts 2). No other tool takes text.

What the points of each tool mean: fibonacciLine is the 100% level then the 0% level; cgFibExt is A, B and C, with levels C + (B − A) × level; parallelStraightLine is two points of the base line and one the parallel passes through; cgPitchfork is P1, P2 and P3; cgLong and cgShort are entry, target and stop, where the target and the stop share one time, the box’s right edge, and must be on the profit and the loss side of the entry. The horizontal tools use only the price, verticalStraightLine only the time.

All drawings are checked together, and the call draws all of them or none. The shapes are checked before any bars are read, the times once they are in. A problem fails the call with a tool error whose text is JSON:

{
"error": "1 problem(s) with drawings; nothing was drawn. Fix them and send the call again.",
"drawing_errors": [
{
"index": 1,
"tool": "segment",
"message": "points[0]: time 2026-10-01T00:00:00Z is before the first bar of the chart, 2026-10-12T00:00:00Z",
"hint": "load more history (a larger bars, up to 5000) or pick a time at or after 2026-10-12T00:00:00Z"
}
]
}

Drawings need bar times, so a call without a ticker (the demo series) cannot take them. On success the answer adds a JSON text item after the image (and after the summary or series):

{
"drawings": [
{
"tool": "rayLine",
"points": [
{ "time": "2026-10-28T08:00:00Z", "timestamp": 1793174400000, "price": 236.30, "bar": 32, "snap": "low" },
{ "time": "2026-10-29T20:00:00Z", "timestamp": 1793304000000, "price": 223.06, "bar": 68, "snap": "low" }
],
"style": { "color": "#089981", "width": 2 }
}
],
"warnings": [],
"open_url": "https://chartgen.example.com/?symbol=BTCUSDT&interval=1h&draw=rayLine(1793174400:236.3;1793304000:223.06;color:%2523089981;width:2)"
}

bar counts from the first bar the chart shows. warnings says what the image cuts off: a price outside the visible price range, or a point more bars past the last bar than the image shows (half the bars shown). open_url is a share link with symbol, interval, type (candles or Heikin Ashi only), ind when the call named at least one indicator, and draw. Without ind the receiver keeps their own indicators: a link never clears them. It is there only when the server has CHARTGEN_BASE_URL, and is left out with a warning when the drawings take more than the 8192 characters a link carries. The PNG draws every tool in the web app’s dark-theme colors: fib levels with their prices, zones and ranges with translucent fills and labels, long and short positions with their target, stop and risk/reward ratio. Drawings add nothing to a call’s cost.

The drawing tools drawings takes, from the one table in src/drawings.rs: for each its name, label (as in the web app’s toolbar), summary, points (what each point is), style (the fields that apply) and text (whether it takes text), plus max_drawings, max_text and the style and point forms. No arguments; read-only. The web app’s copy of the table is web/src/generated/drawing-tools.json.

Read-only facts of a chart, to anchor drawings on real bars instead of guessing prices. Takes ticker/symbol (required), timeframe/interval (default 4h), bars (default 200, 1 to 1000), end_time and swing_depth (default 5, 1 to 50). Use the same ticker, timeframe, bars and end time as the generate_chart call that will draw, so the bars match.

{
"symbol": "BTCUSDT",
"interval": "1h",
"bars": 120,
"first_bar": { "time": "2026-10-27T00:00:00Z", "timestamp": 1793059200000, "bar": 0, "open": 216.12, "high": 219.07, "low": 216.06, "close": 218.22 },
"last_bar": { "time": "2026-10-31T23:00:00Z", "timestamp": 1793487600000, "bar": 119, "open": 257.74, "high": 263.11, "low": 257.15, "close": 262.61 },
"last_close": 262.61,
"high": { "price": 263.11, "time": "2026-10-31T23:00:00Z", "timestamp": 1793487600000, "bar": 119 },
"low": { "price": 216.06, "time": "2026-10-27T00:00:00Z", "timestamp": 1793059200000, "bar": 0 },
"visible_price_range": { "low": 213.70, "high": 265.46 },
"max_bars_past_last": 60,
"swing_depth": 5,
"swings": [
{ "kind": "high", "snap": "high", "price": 256.72, "time": "2026-10-27T19:00:00Z", "timestamp": 1793127600000, "bar": 19 },
{ "kind": "low", "snap": "low", "price": 236.30, "time": "2026-10-28T08:00:00Z", "timestamp": 1793174400000, "bar": 32 }
]
}

swings are the newest 12 swing highs and lows, oldest first, alternating: zigzag pivots with swing_depth bars on each side. A larger depth finds fewer, bigger swings; the newest swing_depth bars cannot hold one yet. visible_price_range is the price range the PNG shows (the bars’ range plus 5% each side); max_bars_past_last is how far past the last bar the image reaches for drawings. It costs bars × 2 of the call budget, at least 1000 (ADR-0052).

Return the full indicator catalog with descriptions, aliases, and configurable parameters. Call before generate_chart to discover valid names. With scripting on, the caller’s own scripts are included, tagged "source": "user"; a script replaces the entry of the built-in it shadows.

Compute indicators and return raw numeric values as JSON. Fetches OHLCV (or uses cached engine data under --trade) and reports each indicator’s last line values, dot presence (signals), and horizontal reference levels.

Required: symbol, indicators (array of names). Optional: interval (default 4h).

Response shape:

{
"symbol": "BTCUSDT",
"interval": "4h",
"source": "engine_cache",
"bars": 200,
"indicators": {
"rsi": { "label": "RSI(14)", "lines": [...], "signals": [...], "hlines": [...] },
"macd": { "label": "MACD", "lines": [...], "histogram": [...] }
}
}

source is engine_cache when hitting the running trading engine’s rolling window, fetched when the tool fell back to fresh OHLCV. The per-indicator object is the same shape generate_chart returns under format=summary.

Last price and change for many symbols in one call. The web watchlist polls it every 5 s.

Required: symbols (array of at most 50 strings). Symbols are trimmed, uppercased and deduplicated. A valid symbol is 1–32 characters of A-Z 0-9 . ^ = - _ with at least one letter or digit. These are tool errors: an array of more than 50 entries (checked before any entry is read, so duplicates count too), a missing symbols and a non-string entry.

Response shape: one entry per distinct symbol, in request order:

{
"quotes": [
{
"symbol": "AAPL",
"last": 349.51,
"change": 17.61,
"change_pct": 5.3058,
"prev_close": 331.9,
"high": 354.47,
"low": 340.99,
"volume": 88958176.0,
"source": "yahoo"
},
{ "symbol": "NOPEUSDT", "error": "Binance: Invalid symbol." }
]
}

A symbol that fails gets {symbol, error} and never fails the call. That covers a malformed ticker ("invalid symbol"), an unknown ticker and an unreachable upstream. change = last - prev_close and change_pct = change / prev_close × 100. high, low and volume are null when upstream omits them. Numbers that are not finite are null.

A stale quote is one its market has not updated for longer than the limit below. That is usually a symbol that stopped trading, such as a delisted coin: Binance still answers XMRUSDT with its last price and a change of 0. A closure longer than the limit, such as a week-long exchange holiday, makes a quote stale too, so stale says the quote is old, not why. It keeps last, but change and change_pct are null, and it adds "stale": true and last_bar_at, the ISO 8601 UTC time of its last update (ADR-0076):

{ "symbol": "XMRUSDT", "last": 118.7, "change": null, "change_pct": null,
"prev_close": 118.7, "high": 118.7, "low": 118.7, "volume": 0.0,
"source": "binance", "stale": true, "last_bar_at": "2026-11-13T03:09:00Z" }
MarketLast updateStale after
Binance; Yahoo crypto (instrumentType CRYPTOCURRENCY)the 24 h ticker’s closeTime; regularMarketTime2 hours
Yahoo FX (CURRENCY)regularMarketTime3 days
Yahoo stocks, ETFs, indices and anything elseregularMarketTime4 days

Staleness is judged when the call is answered. A fresh quote, a sample quote and one whose update time upstream did not give have neither field.

What prev_close means depends on source (see ADR-0011):

sourceSymbolslast / prev_closehigh / low / volume
yahoostocks, ETFs, indices, FXregularMarketPrice / previous session close (chartPreviousClose, v8 chart range=1d)regular-session day values
binancetickers ending in USDT, BTC, ETH, …lastPrice / openPrice of the rolling 24 h tickerrolling 24 h; volume in the base asset
sampleany (CHARTGEN_DATA_SOURCE=sample)forming daily bar’s close / previous daily closeforming daily bar

Live quotes are cached per symbol for 3 s, and the cache is shared by all clients, so tabs polling the same symbols share one upstream fetch per symbol at most every 3 s. Per-symbol errors are cached the same way. The Binance and Yahoo fetches for one call run at the same time.

  • Binance symbols are fetched with one batched /api/v3/ticker/24hr request. Binance rejects the whole batch with HTTP 400 if any symbol is unknown (-1121) or malformed (-1100). Only then is each symbol requested on its own, so only the bad one fails. The bad symbol is remembered for 5 minutes: it gets its error from memory and stays out of the batch. Other failures, including rate limits (429/418), fail every Binance symbol of that call and are never retried per symbol.
  • Yahoo symbols cost one request each, run by a queue of at most 8 workers. The symbol is percent-encoded as a single URL path segment.

Each request times out after 10 s.

A symbol’s market at a glance: the same context a wake-up carries (ADR-0072).

Required: symbols, 1 to 10 strings, trimmed, uppercased and deduplicated as get_quotes takes them. One entry per distinct symbol, in request order:

{
"contexts": [
{
"symbol": "BTCUSDT", "at": 1794700800000, "price": 91234.5,
"trend": { "4h": "down", "1d": "down" },
"funding_pct": 0.006,
"long_short": { "long": 0.764, "ratio": 3.24 },
"fear_greed": { "value": 13, "label": "extreme fear" },
"line": "BTCUSDT 91234.5 | trend 4h down, 1d down | funding 0.006% | longs 76.4% (L/S 3.24) | F&G 13 extreme fear"
},
{ "symbol": "NOPEUSDT", "error": "Binance: Invalid symbol." }
]
}
  • price: the close of the forming 4h bar, so the last price.
  • trend per interval, of 150 bars with the forming one: up when the price is above the 20-bar EMA and that EMA is above the 50-bar EMA, down when both are the other way round, mixed otherwise.
  • funding_pct: the latest funding rate, in percent, as the funding_rate indicator reads it on 1h bars.
  • long_short: the share of Binance accounts that are long, and ratio long/short, as the long_short indicator reads them (4h period).
  • fear_greed: today’s crypto Fear & Greed index (alternative.me) and its band: extreme fear below 25, fear below 45, neutral below 55, greed below 75, else extreme greed.
  • line: all of it in one line, for a template.

Funding, long/short and the index are for Binance symbols only; a stock has its price and trends. A part that could not be read is absent. A symbol whose bars cannot be read gets {symbol, error} and never fails the call. So does one that is not trading (ADR-0073): Binance still serves a delisted symbol’s last bars, which are no price now. A Binance symbol whose newest 4h bar opened more than 8 hours ago, or a stock, ETF or index whose newest bar is more than 7 days old, answers {"symbol": "XMRUSDT", "error": "no bar since 2024-02-20T00:00:00Z: not trading"}, and a wake-up about it goes without context. Each symbol is read at most once a minute, the index once in ten minutes; within that, every caller gets the held answer, and callers that come during a read wait for it. There is no macro calendar here, so whether a macro blackout is on is not part of it. A replay server refuses the tool.

Search tickers and names across all Binance spot pairs and Yahoo Finance instruments, like TradingView’s symbol search. The web symbol search dialog calls it.

Required: query (string). Optional: limit (integer 1–50, default 30), types (array of crypto, stock, etf, fund, index, forex, future; omitted or empty means all). The query is trimmed and must be 1–40 characters without control characters. A bad query, limit or types is a tool error.

{
"results": [
{
"symbol": "SPY",
"name": "State Street SPDR S&P 500 ETF Trust",
"exchange": "NYSEArca",
"type": "etf",
"source": "yahoo"
},
{
"symbol": "BTCUSDT",
"name": "BTC / USDT",
"exchange": "Binance",
"type": "crypto",
"source": "binance"
}
],
"warnings": ["yahoo: Yahoo API returned status 429 Too Many Requests"]
}

warnings is present only when a source failed. Results are ranked: exact match first, then symbol prefix, then symbol contains, then name match. An exact match is the symbol itself or its root: the base of a crypto pair (BTC for BTCUSDT), the base currency of EURUSD=X, the ES of ES=F and the GSPC of ^GSPC. Among exact matches the order is coins (crypto with a non-fiat base), futures, forex (USD quote first), indices, crypto pairs with a fiat base (EURUSDT), then stocks, ETFs and funds, so btc gives BTCUSDT, BTC=F, then the Grayscale ETF BTC. After that USDT/USD quotes come first, then shorter symbols. Remaining ties keep Binance before Yahoo and Yahoo’s own order. Duplicate symbols are dropped. symbol can be passed straight to generate_chart or get_quotes.

sourceWhereNotes
binance/api/v3/exchangeInfo, TRADING spot pairs only (about 3000)fetched once and cached in memory for 6 h, searched locally; type is crypto, name is "BASE / QUOTE"
yahoo/v1/finance/search, 20 quotescached per query for 60 s; type from quoteType (EQUITY → stock, ETF → etf, INDEX → index, CURRENCY → forex, FUTURE → future, MUTUALFUND → fund), exchange from exchDisp
samplebuilt-in list of 30 symbols (CHARTGEN_DATA_SOURCE=sample)no network

Yahoo results of other kinds (including crypto such as BTC-USD, which Binance covers) are dropped, and so are symbols outside A-Z 0-9 . ^ = - _ (the symbols are uppercased first).

Binance and Yahoo run at the same time, and a types filter skips a source that cannot match (for example, ["crypto"] never calls Yahoo). When one source fails, the other’s results are returned and warnings names the failure ("binance: …" or "yahoo: …"). The call is an error only when every queried source fails.

Upstream protection:

  • Concurrent identical lookups share one upstream request, so a cold cache costs one exchangeInfo download however many searches arrive.
  • A failed lookup is remembered for 60 s instead of retried on every keystroke.
  • After the 6 h TTL the Binance list is still served while it refreshes in the background; a failed refresh keeps the old list and retries after 60 s.
  • Yahoo search is limited to 2 requests per second (burst 2) for the whole server, since it shares a host with chart and quote requests. Over the limit the call returns the Binance results plus a yahoo: rate limited warning, and the rejection is not remembered. Cache hits cost no token.
  • Each source has a 4 s deadline. A source that misses it is reported as "<source>: timed out", its late answer still fills the cache, and the other source’s results are not held back.

The Yahoo cache holds at most 500 queries and drops the oldest first. Its key is the query lowercased with inner whitespace collapsed. Each upstream request times out after 10 s.

Server push of the live tail, so a chart updates as the market trades instead of once per poll. See ADR-0021. HTTP transport only (stdio returns an error); works without --trade.

subscribe_chart takes the chart’s generate_chart arguments: ticker (required, 2-20 letters or digits), timeframe (default 4h), indicators (at most 10, with instance ids as for generate_chart), chart_style, chart_params and warmup (default 0, max 1000). Validation and error messages are otherwise the same as for generate_chart, except that a chart using your scripts (CHARTGEN_SCRIPTING=1) answers not pushable, because pushed tails run without a user. Poll generate_chart for those. An interval Binance has no stream for follows the coarsest stream that divides it (7m follows 1m), and each tail is resampled from that stream’s bars as a fetch would be, so a live bar is the bar a reload shows. The exception is a reconnect short enough to fit inside one native kline whose REST backfill fails, as during a rate-limit cooldown: that kline’s last updates are lost, and the bar stays wrong until it leaves the window (ADR-0038). It returns:

{ "subscription_id": "cs-0b7f…" }

From then on the SSE stream (GET /mcp) opened with the same Bearer token and Mcp-Session-Id receives:

{
"jsonrpc": "2.0",
"method": "notifications/chart_tick",
"params": { "subscription_id": "cs-0b7f…", "series": { "…": "…" } }
}

series is exactly what generate_chart(format=series, bars=2, warmup) returns for the same arguments at that moment: the last closed bar and the forming bar, with every indicator recomputed. Merge it like a polled tail.

  • Pushable symbols. Binance symbols only. Any other symbol fails with an error that starts with not pushable: poll generate_chart instead. With CHARTGEN_DATA_SOURCE=sample the same symbols are pushable and a synthetic feed ticks every ~500 ms.
  • Cadence. The server follows Binance’s kline stream (every 2 s) and its aggTrade stream (each trade), and pushes at most 4 tails per second per chart (2 per second when warmup is above 300, or when an interval with no stream of its own holds more than 302 native bars). The first tail is pushed right after subscribing.
  • Sharing. Subscriptions with equal arguments share one rolling window and one recompute. Every chart of a symbol and feed interval shares one Binance WebSocket, so 1m and 7m of a symbol use the same one.
  • Limits. At most 4 subscriptions per token, 32 per client address (the TCP peer; behind a reverse proxy that is the proxy, unless a header is named) or with sign-in per user, and 64 per server, and 10 subscribe_chart calls per token per minute. Over a limit the call fails with an error starting with push limit reached; poll that chart instead. Without an open SSE stream for the session it fails too, and can be retried once the stream is open. An error starting with feeds busy means too many feeds are starting across the server (40 new ones a minute, 96 at once): it passes within a minute, so poll meanwhile and try again.
  • Lifetime. A subscription ends with unsubscribe_chart, when its SSE stream closes, or when the stream falls 256 frames behind (the stream is then unlinked). A WebSocket closes 30 s after its last chart goes.

unsubscribe_chart takes subscription_id and returns { "unsubscribed": true }, or false if the subscription was already gone (or belongs to another token).

Both are built from klines, not trades (ADR-0048): a row’s volume is always an estimate, each kline’s volume spread over its high-low range. Compact JSON. Their forming bar or period repaints as data arrives.

Buy and sell volume per price row of each chart bar.

ArgumentDefaultMeaning
tickerrequiredAs generate_chart.
timeframe1hChart interval.
bars60Newest bars, up to 200.
end_timeExclusive bound on bar open time, ms.
row_sizeRow height in price. Raised to a tick, lowered to the highest price, and widened if a bar would have over 200 rows; row_widened says so.
row_ticksRow height in ticks. Without either: auto, 0.2 x ATR on round numbers.
atr_length14ATR length of the auto row size.
value_area70Percent of the volume.
imbalance300Percent. Buy against the sell one row below, sell against the buy one row above. A row with nothing to compare with is none.
stacked3Imbalances in a row that make a stack. A level counts only where at least 2 klines with volume traded, on it and on the level it is compared with: one kline has one split, so its rows would all agree.
intrabar_intervalFor a poll of a chart already loaded: the intrabar_interval its load returned, or none if that was null, so the newest bars read as the load’s did. Bars that cannot afford it read what they can.
{
"symbol": "BTCUSDT", "interval": "1h",
"intrabar_interval": "1m", "side": "taker_volume",
"row_size": 5, "row_auto": true, "row_widened": false, "tick": 0.01,
"bars_without_data": 0, "has_more": true,
"footprints": [{
"t": 1762466400, "row": 5, "buy": 512.3, "sell": 488.1,
"min_delta": -40.2, "max_delta": 61.5,
"poc": 100000, "vah": 100015, "val": 99990,
"rows": [[99990, 12.5, 9.1], [99995, 31.0, 40.2]],
"buy_imbalances": [], "sell_imbalances": [99990],
"stacked": [{ "side": "buy", "low": 100000, "high": 100015, "count": 3 }]
}]
}

intrabar_interval is what the bars were read from; null means nothing finer exists, and the bar is its own only intrabar. side is taker_volume (Binance’s measured taker buy volume per kline) or close_vs_open (no aggressor data: each kline goes to one side, a doji by the previous close). A row is [bottom price, buy, sell], as high as the bar’s row. vah is a row’s top, val and poc a row’s bottom. bars_without_data counts bars with nothing in them, whose rows are empty.

Time Price Opportunity (market profile): which blocks traded at each price row. Up to 3 Binance requests for a block Binance has (5m, 15m, 30m, 1h, 2h, 4h). Any other is built from finer klines, as a chart of that interval is, and can cost up to 20.

ArgumentDefaultMeaning
tickerrequiredAs generate_chart.
period1DA count and D, W or M: 1D, 2D, 1W, 1M.
block30mBlock length, from 5m to 4h. If 3000 of them cannot hold a whole period, the next that can: the reply’s block is that one, and block_widened says so. A period that 4h blocks cannot cover is refused.
periods10Newest periods, up to 60. Whole periods within 3000 blocks; periods_cut says if that left some out.
end_timeExclusive bound on block open time, ms.
row_size, row_ticksAs get_footprint. Auto: a 24th of the median period range.
value_area70Percent of the blocks.
ib_blocks2Blocks of the initial balance.
sessionsUp to 5 HH:MM-HH:MM in the exchange’s time (UTC for crypto): one profile per session of each period.

Each profile has t (its period’s start, plus its session’s: what identifies it between replies), end, row, block_times (the first is where it starts), open, close, high, low, mid, poc, vah, val, poor_high, poor_low (more than one block at the extreme), single_prints ([low, high] runs of one block inside the profile, tails excluded), ib_high, ib_low, total_blocks, blocks_above_poc, blocks_below_poc, rotation_factor, volume, and rows of { p, letters, blocks, v }: bottom price, letters (A-Z, a-z, then around again), block indices, and volume, spread over each block’s range.

Alerts that run on the server with no browser open, and can call a webhook (guide, ADR-0042). They watch the price, or an indicator’s line at bar closes (ADR-0067). These tools are listed only when the server runs with CHARTGEN_SERVER_ALERTS=1 and answer only on the HTTP transport: an alert belongs to the OAuth client of the bearer token, or with sign-in to its user, and another client or user cannot see or change it. They are unrelated to the --trade alert tools above. On a server without them list_server_alerts returns {enabled: false, alerts: []} and the others an error. The operator decides who may use them (CHARTGEN_SERVER_ALERT_CLIENTS): by default anyone may create alerts and nobody gets webhooks. can_create, webhooks and push in the list say what your client may do.

ToolArgumentsResult
create_server_alertsymbol, condition, trigger, and level unless compare: "close" or condition: "bar_close"; optional interval (default 1m), evaluate_on, indicator, params, line, compare, message, webhook_url, sign, push, notify_agent, setup_idThe alert; webhook_secret too, once, with sign: true
list_server_alerts—{enabled, can_create, webhooks, push, limits, alerts: [...]}
update_server_alertalert_id; optional active, condition, level, trigger, message, webhook_url, sign, push, notify_agent, setup_idThe alert; a new webhook_secret, once, with sign: true
delete_server_alertalert_id{deleted}, with any delivery still pending
subscribe_pushendpoint, p256dh, auth{devices}: registers this browser’s push subscription
unsubscribe_pushendpoint{removed, devices}
  • symbol: a Binance symbol. A stock is refused. Drawing alerts cannot run here; indicator alerts can, at bar closes.
  • condition: crossing, crossing_up, crossing_down, greater, less. A crossing needs a previous reading, so the first price after creating, resuming, editing or a server restart never fires one. greater and less can fire on it. bar_close fires at every close of the interval, whatever the price: see an alert at a bar’s close.
  • trigger: once switches off after firing. every stays on; greater and less wait until the price is back on the other side.
  • evaluate_on: live (default) reads every price update, and interval only labels the alert, so it can be any interval. close reads only the closes of interval’s bars, which must have a Binance kline stream, so a custom interval is refused.
  • A symbol new to the server is checked with one request, so create_server_alert can fail with Binance rate limit: like any fetch. Nothing is stored; retry after the wait it names.
  • update_server_alert: a new condition, level or trigger switches the alert on and re-arms it. A new message or webhook leaves its state alone, so a spent alert stays spent. active: false pauses, active: true resumes re-armed. webhook_url: "" removes the webhook, and a new URL drops the signing secret unless sign: true is sent with it. sign: false stops signing. Symbol, interval and evaluate_on cannot change, nor can an indicator alert’s indicator, params, line and compare.

An alert in a list:

{
"id": "61c779cc-a2f2-418c-8965-95f1241994f2",
"symbol": "BTCUSDT",
"interval": "1h",
"evaluate_on": "live",
"condition": "crossing",
"level": 65000.0,
"trigger": "every",
"message": "breakout",
"active": true,
"disarmed": false,
"created_at": 1793965350122,
"last_triggered_at": 1793965351000,
"fire_count": 1,
"webhook": { "host": "hooks.example.com", "signed": true },
"last_delivery_at": 1793965351131,
"last_status": 200,
"last_error": null,
"feed": "live",
"last_price": 65012.5
}

Times are unix milliseconds. webhook shows the host only, never the URL or the secret. An alert that wakes your agent also has "notify_agent": true, and "setup_id" if it is about a setup; other alerts have neither field. An indicator alert also has "indicator", and its level is null when it compares the close with the line. feed is waiting when no price arrived for two minutes. last_status is the webhook’s HTTP status, and nothing else of its response is kept. last_error is why the last delivery failed or was skipped, or that fires are being limited.

Limits, per user where there is sign-in: 20 alerts per client and 200 not yet spent in total, 16 symbol and interval pairs watched and 2 per client, 10 creates or updates per client per minute, 6 fires per every alert per minute, 30 webhooks per client and 120 in total per minute. A delivery over those waits its turn, up to 50 per client and for up to an hour, with the client that waited longest going first; past that the fire still counts and last_error says the webhook was skipped.

An alert can watch an indicator’s line instead of the price (ADR-0067). At each close of its interval the server computes the indicator over that symbol’s bars, as a chart of it would, and compares:

  • with compare: "level" (the default), the line with level: RSI 14 under 25 on 4h,
  • with compare: "close", the bar’s close with the line, and no level: the 1d close crossing EMA 50.
{ "symbol": "BTCUSDT", "interval": "4h", "evaluate_on": "close",
"indicator": "rsi", "params": { "length": 14 },
"condition": "crossing_down", "level": 25, "trigger": "every", "notify_agent": true }
{ "symbol": "ETHUSDT", "interval": "1d", "evaluate_on": "close",
"indicator": "ma", "params": { "type": "ema", "length": 50 }, "compare": "close",
"condition": "crossing_up", "trigger": "once" }
  • indicator: one of rsi, ma, macd, stoch, cci, mfi, williams_r, roc, atr, adx. An EMA or SMA of a length is ma with type and length (ema is the fixed 8/21/50/200 stack). Your own scripts and indicators that fetch other data (funding, open interest) are refused.
  • params: as list_indicators gives them. A name the indicator does not take is refused. The alert keeps every param it takes, with the defaults filled in, and shows and sends them so. The indicator must settle within the 999 closed bars the server reads: EMA 200 and RSI up to about 120 do. stoch, cci, mfi, williams_r and roc take at most 200 for each param. offset is refused.
  • line: the line’s legend label, any case, e.g. Signal of macd or %D of stoch. Default: the first line.
  • evaluate_on must be close, and interval 1h or longer.
  • level: any number, negative too. Absent with compare: "close"; sending one there is refused.
  • A crossing compares two closes: the line, or the close and the line, at the bar that closed and at the bar before it, both from the bars. So unlike a price alert, the first close after creating it, or after a restart, can fire a crossing. A close is read once: one the alert fired on does not fire again after a restart.
  • When the alert is created, or after a restart, the server reads the symbol’s last 1000 bars once, through the same Binance budget as a chart; feed is waiting until it has them. If a close goes missing (a reconnect, a lag) it reads them again and then reads that close, at most once a minute per symbol and interval.
  • The alert in a list has "indicator": {"name", "params", "line", "compare", "value"}, where value is the line at the last close read, or null before the first.
  • update_server_alert changes its condition, level and trigger like a price alert’s.

The webhook payload and the wake-up carry the same "indicator" object, with value at the close that fired. level there is the level the alert compares with, or with compare: "close" the line’s value that the close crossed. A price alert’s payload has no indicator and is unchanged.

condition: "bar_close" fires when a bar of the alert’s interval closes, whatever the price: a wake-up at every 4h close, say (ADR-0069).

{ "symbol": "BTCUSDT", "interval": "4h", "condition": "bar_close",
"trigger": "every", "notify_agent": true }
  • interval is required, 1h or longer, with a Binance kline stream. evaluate_on is close; leave it out or send close.
  • It takes no level, indicator, params, line or compare; each is refused. Its level is null in a list, in the webhook payload and in the wake-up, and price there is the bar’s close.
  • trigger: "once" fires at the next close and switches off; every fires at each close.
  • A close the server did not see is not fired afterwards: after a restart or an outage it fires at the next close it sees, with that bar’s time. It never fires twice for one bar, also when the feed sends a bar again after a restart, and never for a bar that closed before the alert was made.
  • update_server_alert changes its trigger, message and delivery like any alert’s. Its condition cannot change to another, nor can another alert’s change to bar_close.
  • It counts in the same limits as any alert. The web app lists it and can pause, resume and delete it, but does not edit it.

A spent alert is deleted 7 days after it fired. An alert is deleted once its owner has had no token for 30 days, unless the operator listed that client.

Refused when creating, and checked again before every attempt:

  • anything but https on port 443, or a URL with a user or password, or over 512 bytes;
  • an address that is loopback, private, link-local, CGNAT, multicast, reserved, documentation or a cloud metadata address, on IPv4 or IPv6, in any spelling (2130706433, [::ffff:127.0.0.1]), IPv6 outside global unicast or in the 6to4, Teredo and NAT64 ranges, or in a prefix the operator blocked;
  • a name with no dot, or under a private suffix such as .internal or .docker;
  • a host this server fetches from (Binance, Yahoo, alternative.me) or its own host;
  • a name with any refused address among its answers. That reads the same as a name that does not resolve: webhook host does not resolve to a public address.

The connection is pinned to the addresses checked, unless the operator sends webhooks through a proxy, which then resolves and connects itself. Redirects are not followed: a 3xx is a failure. Each attempt has 5 s; a timeout, connection failure, 5xx or 429 is retried twice, after 2 s and 8 s; other answers are final.

POST with Content-Type: application/json:

{
"id": "d99a10e1-d742-4b79-9ccc-f75169944c6a",
"type": "alert.fired",
"alert_id": "61c779cc-a2f2-418c-8965-95f1241994f2",
"symbol": "BTCUSDT",
"interval": "1h",
"evaluate_on": "live",
"condition": "crossing",
"level": 65000.0,
"price": 65010.5,
"trigger": "every",
"message": "breakout",
"bar_time": 1793962800,
"fired_at": 1793965351000,
"fire_count": 3
}

bar_time is the bar’s open in unix seconds, fired_at unix milliseconds, message may be null. Delivery is at least once: a restart resumes an unfinished delivery for up to an hour, so deduplicate on id. Any 2xx counts as received; the body of the response is never read.

HeaderValue
X-Chartgen-EventThe event id
X-Chartgen-TimestampUnix seconds of this attempt
X-Chartgen-Signaturesha256=<hex>, only with sign: true
webhook-idThe event id, the same on every attempt
webhook-timestampUnix seconds of this attempt
webhook-signaturev1,<base64>, only with sign: true
User-Agentchartgen-webhook/1

The last three are the Standard Webhooks headers (ADR-0061). A receiver built for that convention verifies a delivery with no code for this server: the signature is the base64 HMAC-SHA256 over <webhook-id>.<webhook-timestamp>.<raw body>, keyed with the bytes of the alert’s secret. Either pair of headers proves the same thing; verify one.

The signature is HMAC-SHA256 with the alert’s secret over <timestamp>.<raw body>. To verify, compute it over the bytes you received, compare in constant time, and refuse an old timestamp to stop replays:

import hashlib, hmac
def verify(secret: str, timestamp: str, body: bytes, signature: str) -> bool:
signed = timestamp.encode() + b"." + body
mac = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(f"sha256={mac}", signature)

The secret is shown once and is never logged or returned again; sign: true on update_server_alert replaces it.

notify_agent: true delivers the alert to your own agent, at a receiver this server’s operator configured for your account (ADR-0061). There is no URL and no secret in the call: both are the operator’s. Where no receiver is configured for you the call is refused, with the same words as any webhook the server does not send for you.

  • It takes the place of webhook_url: an alert has one or the other. push may go with it.
  • setup_id names one of your open setups. It needs notify_agent. The wake-up then carries that setup as it stands when it is sent.
  • The alert changes nothing on the setup, and deleting it leaves the setup alone.

The delivery is signed with the operator’s secret and has the headers above. Its body is its own, in this order:

{
"id": "d99a10e1-d742-4b79-9ccc-f75169944c6a",
"type": "alert.fired",
"at": 1793965351000,
"alert": {
"id": "61c779cc-a2f2-418c-8965-95f1241994f2",
"symbol": "BTCUSDT", "interval": "1m", "evaluate_on": "live",
"condition": "crossing", "level": 65000.0, "price": 65010.5,
"trigger": "once", "bar_time": 1793965320, "fire_count": 1
},
"note": "the alert's message",
"context": {
"symbol": "BTCUSDT", "at": 1793965352000, "price": 65012.0,
"trend": { "4h": "up", "1d": "mixed" }, "funding_pct": 0.01,
"long_short": { "long": 0.52, "ratio": 1.08 },
"fear_greed": { "value": 61, "label": "greed" },
"line": "BTCUSDT 65012.0 | trend 4h up, 1d mixed | funding 0.01% | longs 52.0% (L/S 1.08) | F&G 61 greed"
},
"setup": {
"id": "0b6f6f0e-6f0e-4a3e-9d43-0d6c1f6a2a11",
"status": "watching",
"symbol": "BTCUSDT", "interval": "1h", "direction": "long", "decision": "take",
"levels": { "entry": { "low": 64000.0, "high": 64200.0 }, "invalidation": 63000.0,
"targets": [66000.0], "expires_at": 1794051751000 },
"fill": null, "exit": null, "result_r": null,
"mae_r": null, "mfe_r": null, "mae_at": null, "mfe_at": null, "closest_approach_r": 0.42,
"bars_to_fill": null, "bars_to_exit": null, "bars_to_mae": null, "bars_to_mfe": null,
"shadow_results": null,
"tags": ["strategy:breakout"], "gap": false,
"thesis": "the setup's thesis, as you wrote it"
}
}

note is absent without a message, and setup without a setup_id or once the setup is gone. context is the symbol’s market when the body is made, as get_market_context answers it (ADR-0072). A wake-up waits at most 5 s for it, and goes without it when it is not held from the last minute and not read in time, or when the symbol’s bars cannot be read. Whether a macro blackout is on is not in it. The order is fixed: what says which event this is and where the setup stands comes first, the thesis last, so a receiver that shows only the beginning of a body still shows the levels. The setup has no drawings and no log here; get_setup answers those. A body is at most 8 KiB: a thesis that would exceed it is cut, and "thesis_cut": true says so.

A status the server gives one of your setups wakes your agent too, with no flag on the setup: triggered, won, invalidated and expired of a setup whose decision is take. The body then has "type": "setup.status" and, where an alert’s body has alert,

"change": { "from": "watching", "to": "triggered", "gap": false }

with result_r once there is one, followed by the setup. at is the time of the bar that decided it. Your own cancellation, and every change of a skip setup, are logged and wake nobody.

change says what happened; setup is the setup as it is when the body is sent. A wake-up that reaches you late can say triggered about a setup that already shows won.

A take that went 0.8 R against it wakes your agent once, before the stop (ADR-0072). It is the first 1m bar whose low (long) or high (short) takes mae_r to −0.8 or below while the setup stays triggered: R from the fill price to the invalidation, before costs, as mae_r counts it. The body has "type": "setup.near_stop", at the time of that bar, and

"change": { "mae_r": -0.83, "gap": false }

followed by context and the setup, which shows near_stop_at. It is said once per setup, however often the price comes back and goes out again. A bar that stops the take out says so with its status instead, and the bar that fills it can be the one. After the server was away, a warning written together with the stop that followed it is logged and not sent. A skip is not warned about.

Wake-ups have limits of their own, apart from the ones above: 50 waiting, 30 a minute, 2 at once. Delivery is tried three times within about fifteen seconds. With no answer, a 5xx or a 429 it is tried once more after 1, 5, 15 and 30 minutes, while the event is younger than an hour; a restart of the server continues that. An alert shows the newest outcome (last_status, last_error). The same webhook-id can arrive twice: drop the second.

ToolArgumentsReturns
list_eventsoptional after (a cursor, default 0), limit (default 50, at most 100){events: [...], cursor, more, truncated}, oldest first

Every event that could wake your agent is logged first, and stays whether or not a wake-up was sent or arrived. An agent that was away asks list_events with the last cursor it kept, and repeats while more is true.

{
"events": [
{ "seq": 41, "id": "d99a10e1-d742-4b79-9ccc-f75169944c6a", "type": "alert.fired",
"at": 1793965351000, "alert_id": "61c779cc-…", "setup_id": "0b6f6f0e-…",
"what": { "symbol": "BTCUSDT", "interval": "1h", "evaluate_on": "live",
"trigger": "once", "price": 65010.5, "level": 65000.0,
"condition": "crossing", "bar_time": 1793965320, "fire_count": 1 },
"delivery": "delivered" },
{ "seq": 42, "id": "7a0c1d0e-…", "type": "setup.status",
"at": 1793965380000, "setup_id": "0b6f6f0e-…",
"what": { "from": "watching", "to": "triggered", "gap": false },
"delivery": "delivered" },
{ "seq": 43, "id": "c1f4e2b7-…", "type": "setup.near_stop",
"at": 1793967180000, "setup_id": "0b6f6f0e-…",
"what": { "mae_r": -0.83, "gap": false },
"delivery": "waiting" }
],
"cursor": 43, "more": false, "truncated": false
}
  • seq counts your events from 1 and is never used twice. id is the webhook-id of the wake-up, so what you were sent and what you read back can be matched.
  • delivery: none (logged only), waiting, delivered, failed (given up, or refused by the receiver), dropped (too many were waiting).
  • An event holds no thesis and no note. Read the setup or the alert for those.
  • An alert.fired event says what the fire saw: level is the level it compared with (null for an alert that has none), and an indicator alert’s also has indicator with the line’s value at that close, and with compare: "close" that value as level. It also holds the alert’s symbol, interval, evaluate_on, condition and trigger at the fire. The wake-up’s alert is made from the event, so it says the same even if the alert changed or was deleted meanwhile; only its note comes from the alert, and is absent once the alert is gone.
  • A wake-up that a build from before the event log left waiting goes into the log at the next start, under its own id and with the time of its fire, and is sent from there.
  • The newest 1000 events are kept, for 7 days. truncated: true means events after your cursor are gone: read your setups and alerts as they are instead of relying on the log.
  • Listed where server alerts or setups run. A replay server has no log and refuses the call.

Push (ADR-0045). push: true on an alert, with or without a webhook, sends the same JSON to each of your devices through Web Push, encrypted under RFC 8291. push in list_server_alerts is null where the server will not notify for your client, else {public_key, devices}: subscribe in the browser with that key as applicationServerKey, then pass the subscription to subscribe_push. The endpoint must be https at a known push service (fcm.googleapis.com, updates.push.services.mozilla.com, *.push.apple.com, *.notify.windows.com), p256dh at most 88 characters and auth at most 24. Registering the same endpoint again updates its keys. You may have 5 devices, and a new one over that replaces the oldest; at most 30 pushes per minute. On a server whose 2000 devices are full, a new one replaces another client’s, and a client’s alerts only notify that client’s devices: with sign-in those are all of its user’s, on every client. subscribe_push answers devices, the count, and device, this one’s id. An endpoint has one owner, whoever subscribed it last: registering one that someone else holds removes their row, and fails with registered with other keys, changing nothing, unless both keys match. A 404 or 410 from the push service removes the device. Delivery is at least once, so deduplicate on id; the app’s worker uses it as the notification’s tag. Each alert also returns push, last_push_at, last_push_status and last_push_error, the last outcome across your devices, and last_push_devices: the devices its last fire went to, by id, each with {at, status, error}, or null while its outcome is not known. A device not there was not sent that fire.

Trading setups an agent stores and the server scores on paper (guide, ADR-0059). No order is sent. These tools are listed only when the server runs with CHARTGEN_SETUPS=1, or as a replay server, and answer only on the HTTP transport: a setup belongs to the OAuth client of the bearer token, or with sign-in to its user, and a setup of another owner reads as one that does not exist. On a server without them list_setups returns {enabled: false, setups: []} and the others an error. Where the operator listed accounts in CHARTGEN_SERVER_ALERT_CLIENTS, only those may create setups; can_create in the list says so.

ToolArgumentsResult
create_setupsymbol, interval, direction, thesis; for a setup entry, invalidation, targets, expires_at; optional drawings, decision, tags, features, probability, playbook_versionThe setup with its log
revise_setupid, reason; any of thesis, drawings, tags, entry, invalidation, targets, expires_atThe setup with its log
get_setupidThe setup with its log
list_setupsoptional status, symbol, tags (only setups that have all of them), limit (default 50, at most 500){enabled, can_create, replay, total, limits, setups: [...]}, newest first, without logs
cancel_setupid, reasonThe setup with its log
get_track_recordoptional symbol, direction, decision, playbook_version, from, to, group_by, feature{replay, closed, open, truncated, group_by, feature, total, groups: [...], shadows}
  • symbol: a Binance symbol, or a stock or ETF listed in the US (Nasdaq, NYSE, NYSE American, NYSE Arca or Cboe BZX) as Yahoo reports it, such as NVDA or SPY. An index (^GSPC), an OTC stock, a stock listed elsewhere and Yahoo’s crypto, FX and futures are refused, each with a hint. A stock setup has its own costs and session rules; see stock setups.
  • direction: long or short. decision: take (default), or skip for a decision not to trade, which takes no levels and is scored with the server’s bracket.
  • entry: {low, high}. invalidation: below the entry zone of a long, above that of a short, and at least 42 bps of the price from it (24 bps on a stock). targets: 1 to 4 prices beyond the zone, nearest first; the first decides a win. expires_at: unix seconds, unix ms or ISO 8601, ahead and at most 90 days, and on a stock not past 2028, the last year the exchange calendar here holds.
  • thesis: at most 2000 characters. reason: at most 500.
  • drawings: as generate_chart’s, at most 50, on the bars of the setup’s symbol and interval.
  • tags: at most 10 labels, each 1 to 64 characters of lowercase letters, digits and : - _ . /, starting with a letter or digit, such as strategy:breakout or trigger:rsi-oversold. A tag given twice is kept once. On revise_setup the list replaces the old one ([] clears it), and it can change after the fill too. A closed setup, or one being cancelled, takes a revision with tags alone.
  • status, result_r, the excursion and duration fields, closest_approach_r, near_stop_at, shadow_results, fill, exit and costs are set by the server. Sending one is an error.
  • features, probability, playbook_version (ADR-0064): what you state when you make the setup, all optional. features is a flat object of at most 16 entries, names of a-z, 0-9 and _ up to 32 characters, values a number, true or false, or a string of at most 32 characters. probability is your own estimate from 0 to 1 that the setup reaches its first target. playbook_version is a label of at most 32 characters. The server gives them no meaning. They are fixed once the setup is made: revise_setup and cancel_setup refuse them. A setup made without probability or playbook_version answers without them.
  • The server adds three features to every setup it makes (ADR-0077): ctx_trend_4h and ctx_trend_1d (up, down or mixed) and ctx_fear_greed (extreme fear, fear, neutral, greed or extreme greed), the symbol’s market context when the setup was made. Each is unknown where the context has none: on a replay server, a symbol that is not trading, a read that failed or took over 10 seconds, and for ctx_fear_greed a symbol that is not on Binance. They are fixed as your features are. A feature name of yours that starts with ctx_ is refused. They do not count against the 16 features you may state. A setup made before this has none of them.
  • as_of: replay servers only, where every call needs it. generate_chart, inspect_chart, get_indicators and get_quotes take it there too.

A setup answers with id, the fields above, bracket (agent, or for a skip atr or floor: which rule set its levels), status (watching, triggered, won, invalidated, expired, cancelled), created_at, costs, fill and exit (each {price, bar_time} or null), result_r (in R; null while open, and for a setup that expired filled while its owner was off the operator’s list), mae_r, mfe_r, mae_at, mfe_at, bars_to_fill, bars_to_exit, bars_to_mae, bars_to_mfe and closest_approach_r (see excursions), shadow_results (from the fill on, the setup scored with three fixed exit variants for comparison, v1_half_t1_be, v2_be_at_1r and v3_time_stop, each with status, result_r, stop, exits, exited_at and time_stop_at; null before the fill; see shadow results), tags, scored_through (still moving after the close while a shadow result is open), gap (true if bars were missed and could not be read afterwards, so the result is incomplete), pending (changes that count from the next 1m bar), revisions and agent_revisions. A stock setup also has market (us_equity), last_close (its newest 1m close scored, {price, bar_time}) and adjustments once a split or a dividend applied ({kind: "split", at, ratio} or {kind: "dividend", at, amount}); a Binance setup has none of the three. A take that went 0.8 R against it while open has near_stop_at, the open time of that 1m bar (near the stop); until then it is absent. log holds every entry: seq, at, by (agent or server), kind (created, revised, cancelled, status, voided, gap, adjusted, near_stop), reason and changes ({field: {from, to}}). Times are in ms.

A call that fails a check answers with an error whose text is JSON: {error, setup_errors: [{field, message, hint}]}, one entry per problem, and stores nothing.

get_track_record counts your closed setups. Open ones are not counted; open says how many match the filters.

  • Filters: symbol, direction, decision, playbook_version, and from and to (unix seconds, unix ms or ISO 8601) on the time the setup was made.
  • group_by: playbook_version, feature (with feature, the name of one, the server’s ctx_trend_4h, ctx_trend_1d and ctx_fear_greed included), probability (in tenths: 0.0, 0.1 … 0.9, with 1 in the last), symbol or direction. A setup that stated none is in the group whose key is null. Groups come in the order of their keys. More than 50 groups are refused: group by something that takes fewer values.
{
"replay": false, "closed": 3, "open": 1, "truncated": false,
"group_by": "playbook_version", "feature": null,
"total": {
"count": 3, "won": 2, "invalidated": 1, "expired": 0, "cancelled": 0,
"with_result": 3, "total_r": 2.1, "mean_r": 0.7,
"entered": 3, "mean_r_entered": 0.7, "gaps": 0,
"probability": { "stated": 2, "mean": 0.425, "won": 1, "observed": 0.5,
"stated_entered": 2, "won_entered": 1, "observed_entered": 0.5 }
},
"groups": [
{ "key": null, "count": 1, "won": 1, "invalidated": 0, "expired": 0, "cancelled": 0,
"with_result": 1, "total_r": 1.6, "mean_r": 1.6,
"entered": 1, "mean_r_entered": 1.6, "gaps": 0,
"probability": { "stated": 0, "mean": null, "won": 0, "observed": null,
"stated_entered": 0, "won_entered": 0, "observed_entered": null } },
{ "key": "v1", "count": 2, "won": 1, "invalidated": 1, "expired": 0, "cancelled": 0,
"with_result": 2, "total_r": 0.5, "mean_r": 0.25,
"entered": 2, "mean_r_entered": 0.25, "gaps": 0,
"probability": { "stated": 2, "mean": 0.425, "won": 1, "observed": 0.5,
"stated_entered": 2, "won_entered": 1, "observed_entered": 0.5 } }
],
"shadows": {
"v1_half_t1_be": { "closed": 2, "with_result": 2, "total_r": -0.4, "mean_r": -0.2,
"canonical_total_r": -0.5, "canonical_mean_r": -0.25, "open": 1 },
"v2_be_at_1r": { "closed": 3, "with_result": 3, "total_r": 1.1, "mean_r": 0.37,
"canonical_total_r": 2.1, "canonical_mean_r": 0.7, "open": 0 },
"v3_time_stop": { "closed": 3, "with_result": 3, "total_r": 1.8, "mean_r": 0.6,
"canonical_total_r": 2.1, "canonical_mean_r": 0.7, "open": 0 }
}
}
  • with_result is how many have a result in R; mean_r is over those and null when there are none. A setup that expired filled while nobody scored it has no result and is not given one. gaps counts results that do not cover bars the server missed.
  • A setup that was cancelled, expired or invalidated before its entry was reached has a result of 0 R, and is in mean_r and in the observed share. It never traded, and it pulls the mean towards 0. entered is how many setups had their entry reached, and mean_r_entered is the mean over those of them that have a result: it leaves the ones that never traded out. Read both: mean_r is what following every setup gave, mean_r_entered what the trades gave.
  • probability: of the setups that stated one, how many (stated), its mean, how many of them won, and that share (observed). The share is over all of them, the ones that never traded included, so it mixes in the chance of a fill. stated_entered, won_entered and observed_entered are the same over those whose entry was reached.
  • shadows: each fixed exit variant (ADR-0066) over the filled setups among those counted, in all and not per group: how many of its positions closed, how many of those have a result, their total_r and mean_r, and how many are still open, which a closed setup’s variant can be for a while. A setup that never traded has no variants, so these are over fewer setups than total. Compare a variant only with its own canonical_total_r and canonical_mean_r, the setups’ own results over the very setups the variant has a result for. The open ones are not a random part: an open v1_half_t1_be is a runner after T1, a winner, so v1’s closed ones lean to losers until those end, and v1 beside total would look worse than it is.
  • A feature’s number is one value however it was written: 1 and 1.0 are one group, and a number key is written as a decimal (1.0). The string "1" is another group.
  • It counts and judges nothing. There is no significance and no ranking. A group of a few setups says little, and setups that overlap in time or share a cause are not independent trials.
  • The newest 500 closed setups are read; truncated is true if older ones were left out.
  • On a replay server it needs as_of and is the same on every run.

Scripted indicators (CHARTGEN_SCRIPTING=1)

Section titled “Scripted indicators (CHARTGEN_SCRIPTING=1)”

User-authored Starlark indicators (guide, ADR-0024, ADR-0025). These tools are listed and served only when the server runs with CHARTGEN_SCRIPTING=1. Scripts belong to the OAuth client of the bearer token, or with sign-in to its user, so the tools that store or read scripts need the HTTP transport (stdio has no user). Once registered, a script’s name works in generate_chart (resolved before built-ins, so it can shadow one for its owner) and shows up in list_indicators. The generated TypeScript input types do not include these tools.

ToolArgumentsResult
register_indicatorname (^[a-z][a-z0-9_]{0,47}$), source (≤ 64 KiB), create_only (default false){ok: true, name, title, overlay, configurable_params, replaced, shadows_builtin}
fork_indicatorbuiltin_name{name, source, configurable_params} for a built-in with a reference implementation (wavetrend); otherwise an error listing the forkable ones
list_my_indicators—{total, indicators: [{name, title, description, type, overlay, configurable_params?, source: "user", created_at, updated_at}]}
get_my_indicatorname{name, source, updated_at}: the stored Starlark source. With no such script: isError: true with {ok: false, error: "not_found", message}, which a failed read never has
delete_indicatorname{ok: true, name}; an error if you have no such script

register_indicator validates in four steps: parse, static, presence, and dry_run (100 synthetic bars, 200 ms). A failure returns isError: true with:

{ "ok": false, "errors": [{ "step": "static", "line": 3, "message": "`len` shadows a builtin; pick another name" }] }

Registering an existing name replaces the script ("replaced": true), unless create_only is true: then the store’s insert refuses it, and the error has "step": "exists". Each user may store 50 scripts. Scripts are stored in SQLite at CHARTGEN_DB (default ~/.chartgen/chartgen.db), see the persistence reference.

A generate_chart call computes at most 3 scripted indicators, sharing one 1 s budget; further ones fail with an indicator_errors entry. At most 4 script evaluations run on the server at once and one per user; a caller waits for a slot until its deadline, then gets “server busy”. subscribe_chart pushes compute built-ins only.

Scripting is meant for trusted or single-user deployments: without sign-in a script’s owner is an OAuth client registration and /authorize approves automatically, and with it anyone with an account can run scripts in the server process (threat model in ADR-0025 and ADR-0044).

ToolPurposeRequired args
place_orderSubmit a market or limit order.symbol, side (buy/sell), type (market/limit), quantity; price for limits.
cancel_orderCancel an open order.order_id.
get_ordersList tracked orders.Optional filter: open or all (default).
get_positionsOpen positions with unrealized PnL.—
get_balanceStub. Always returns an error; use get_positions.—
ToolPurposeRequired args
set_alertRegister a one-shot alert. Fires once, then is removed.symbol, condition (see below).
list_alertsList all active alerts.—
cancel_alertRemove an alert before it fires.alert_id.
get_notificationsDrain the triggered-alert queue (polling).—

Alert conditions:

{ "price_above": 50000 }
{ "price_below": 45000 }
{ "indicator_signal": { "indicator": "cipher_b", "signal": "gold_buy" } }

Signal labels come from a fixed registry in src/trading/signals.rs — see the trading guide for the full list. candlestick_patterns and chart_patterns use their own: a pattern’s key such as hammer, or double_top_confirmed, on the newest closed bar.

indicator_signal is not checked when set. It only fires if the indicator is in the server’s --panels under that exact name, since the engine computes nothing else; any other name is accepted and never fires. The engine’s window starts empty and holds at most 200 bars, with no history loaded, so an indicator needing more bars stays silent until they have closed, and chart_patterns reads those 200 rather than the web chart’s 600.

Instead of polling get_notifications, subscribe for JSON-RPC pushes over SSE:

ToolPurposeRequired args
subscribe_notificationsRegister filters for push notifications.Optional symbols (array), alert_types (price_above/price_below/indicator_signal).
unsubscribe_notificationsRemove the current subscription.—
list_subscriptionsActive filters and offline queue size.—

Subscriptions persist to ~/.chartgen/subscriptions.json; queued alerts are kept for up to one hour. See push notifications.