Skip to main content

AI assistant integration

This article shows how to let an AI assistant change DXcharts React from a chat, with Devexa, the Devexperts AI assistant, as the example. Users can ask, in a free text format, to:

  • change the symbol: "show AAPL", "show me Apple"
  • change the timeframe: "switch to 5m", "1 hour", "daily"
  • change the chart type: "make it a line chart", "candles"
  • change the layout: "2x2 layout", "put AVGO and AAPL side by side"
  • add and remove indicators: "add RSI", "remove RSI"
  • add and remove comparisons: "compare with MSFT", "remove the MSFT comparison"
  • change one chart of a multi-chart layout: "switch the 1st chart to MSFT", "add RSI to chart 3"
  • change settings: "switch theme to classic light", the price type, volume and time zone
  • draw on the chart: "draw support and resistance", "a Fibonacci retracement over the last drop", "trend line from the March low to the June low", "long position with a 5% stop and a 10% target"
  • remove drawings: "remove it", "remove the trend line", "remove all drawings"

The integration uses only the public Supported APIs, so no changes to the chart are needed. See it in the DXcharts demo: open Chart Assistant in the chart toolbar.

How it works​

  1. Devexa's Chart Control tool tells the assistant which chart commands exist. With every message, the page tells it what the chart shows right now.
  2. The user asks for a change, for example "show TSLA on 5m with RSI".
  3. Devexa's Chart Control tool sends the commands to the page in a chartCommands widget event. Nothing is shown in the chat.
  4. The page checks the commands, applies them with ChartReactAPI and shows what changed in a chart notification.
  5. The page reports back what it applied and what it skipped, with the reason. Devexa answers the user from that report.

The page does not run the code it receives. The commands are plain JSON: every value is checked, and only known ChartReactAPI methods are called.

Requirements​

  • DXcharts React 5.16.5 or later. Drawing from the chat needs 5.20.0 or later (addDrawing and removeDrawing).
  • The Devexa widget, @dx-private/devexa-widget-platform 5.0.1 or later.
  • From the Devexa team: the widget token for your channel, and the Chart Control tool enabled for your organization. Without the tool, the assistant doesn't know the chart commands and can't change the chart.

Command format​

Commands are a JSON object with a commands array. They run in the following order:

{
"commands": [
{ "action": "changeSymbol", "symbol": "TSLA" },
{ "action": "setTimeframe", "timeframe": "5m" },
{ "action": "addIndicator", "indicator": "RSI" }
]
}
ActionFieldsChartReactAPI
changeSymbolsymbol, chartchangeInstrument
setTimeframetimeframe (5m, 1h, 1d, ...), chartchangePeriod
setChartTypechartType (candle, bar, line, area, ...)changeChartType
setLayoutlayout (1x1, 2x1, 1x2, 2x2, 3x1, 1x3, 2x4)generateLayout + syncLayoutParts
addIndicatorindicator (RSI, MACD, Bollinger Bands, ...), chartgetChartInfo + setStudies
removeIndicatorindicator, chartgetChartInfo + setStudies
removeAllIndicatorschartsetStudies
compareSymbolsymbol, chartaddCompareInstrument
removeComparisonsymbol, chartremoveCompareInstrument
setThemetheme (dark, light, cloudDancer, oud, solar, still)changeTheme
setPriceTypepriceType (last, bid, ask, mark), chartsetPriceType
setVolumevisible (true or false), chartsetVolumesVisible
setTimezonetimezone (IANA name, for example America/New_York)setCurrentTimezone
addDrawingdrawing, points, role, label, color, stop, target, icon, chartaddDrawing
removeDrawingswhich (last, chat, all), drawing, chartremoveDrawing

chart is optional. It is the chart number users see, starting from 1, or "all". Without it, the command changes the selected chart. The chart type and the layout always change all charts.

Layout names are rows × columns: 1x2 is two charts side by side, 2x1 is two charts stacked.

Drawings​

addDrawing draws one drawing per command. drawing is one of 47 supported drawings, from trend_line, horizontal_line and fib_retracement to long_position, elliott_impulse and icon; the full list is in the Chart Control tool's description.

  • points are only the places the user named, each { "time": ..., "price": ... }. time is a date (2026-03-15), a month (2026-03), a moment (2026-03-15 14:30) or latest. price is a number, or high, low, open or close of the candles at that time. "From the March low to the June low" is [{ "time": "2026-03", "price": "low" }, { "time": "2026-06", "price": "low" }].
  • What the user leaves out is placed on the chart's candles: a trend line along the swings, a price line at the nearest level, a Fibonacci retracement over the last swing, a box around the recent range. role: "support" or "resistance" picks a level below or above the price.
  • A long or short position takes stop and target as fields. Each is a price, or a distance from the entry in percent ("5%"). Its entry is the latest close unless the user names one. A stop or target on the wrong side of the entry is moved, and the report says so.
  • removeDrawings with which: "last" removes what the chat drew last ("remove it"), "chat" everything the chat drew, "all" every drawing on the chart. drawing narrows it to one kind ("remove the trend line").

The report says where and when each drawing was placed, for example "Drew a Fib retracement over the last drop, 430.00 on 10 Aug to 295.00 on 5 Nov".

Step 1. Show the Devexa widget​

Load the Devexa widget script and create the widget with useCustomButton: true, so it opens from a button in the chart toolbar. Add the button with addCustomToolbarButtons.

Create the widget in the component that renders the chart, not in the toolbar button. The chart toolbar is rebuilt when the multi-chart layout changes, so a widget created inside the button would close every time the layout changes. The button only opens and closes the widget.

The complete component is in Step 4.

Step 2. Give the assistant the context​

The Chart Control tool already tells the assistant which commands exist, how to write them and how to answer (see below). The page adds what the chart shows right now.

The widget sends the last value passed to addMessageContext with every user message. Pass the current chart state: today's date, the layout, the selected chart, and for each chart its symbol, timeframe, chart type, indicators, comparisons, drawings, the time range of its candles and the latest price. Add the list of indicators the chart offers, so the assistant uses their names.

The date, the candle range and the latest price let the assistant turn "the March low" into a date, and "a 5% stop" into a price.

Update the context right before the user sends a message. To do this, listen to keydown and pointerdown on the document in the capture phase. The chat panel is rendered outside the widget container, so listeners on the container do not see the user typing. Also update the context after the commands are applied.

/**
* Context for Devexa: what the chart shows right now. The widget sends the latest value passed to
* `addMessageContext` with every user message. Which chart commands exist and how to answer is part of
* Devexa's Chart Control tool; its description is in `chart-control-tool-description.txt`, so send the
* Devexa team any change to it.
*/
import { ContextItem } from '@dx-private/devexa-widget-platform';
import { getChartsAmount } from '@dx-private/dxchart5-react/dist/chart/model/multichart.model';
import { TStudySettings } from '@dx-private/dxchart5-react/dist/chart/model/studies.model';
import { ChartReactAPI } from '@dx-private/dxchart5-react/dist/chart/view-models/api/chart-react-api.view-model';
import { formatTimeframe } from './chart-command-values';
import { CHAT_DRAWING_ID_PREFIX, drawingNameOfType } from './chart-drawings';
const CONTEXT_ROLE = 'system';
const describeStudies = (studies: TStudySettings[]) =>
studies.length > 0 ? `indicators: ${studies.map(study => study.title).join(', ')}` : 'no indicators';
const isoDay = (timestamp: number) => new Date(timestamp).toISOString().slice(0, 10);
const isoMinute = (timestamp: number) => new Date(timestamp).toISOString().slice(0, 16).replace('T', ' ');
const MONTHS = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
/** Today, and how a month named without a year reads today: its latest occurrence up to today. */
const describeToday = (now: number) => {
const today = new Date(now);
const year = today.getUTCFullYear();
const month = today.getUTCMonth();
const asked = (index: number) =>
`"${MONTHS[index]}" → ${index > month ? year - 1 : year}-${String(index + 1).padStart(2, '0')}`;
return `Today: ${isoDay(now)} (${asked((month + 11) % 12)}, ${asked((month + 1) % 12)}).`;
};
const FLAT_DRAWING_TYPES = ['horizontal_line', 'horizontal_ray', 'price_label'];
/** "price line at 191.83 (from the chat)": its kind, the price of a flat one, and who added it. */
const describeDrawing = (drawing: { id: string; type: string; keyPoints: { value: number }[] }) => {
const price = FLAT_DRAWING_TYPES.includes(drawing.type) ? drawing.keyPoints[0]?.value : undefined;
return [
drawingNameOfType(drawing.type),
price === undefined ? '' : ` at ${Number(price.toPrecision(6))}`,
drawing.id.startsWith(CHAT_DRAWING_ID_PREFIX) ? ' (from the chat)' : '',
].join('');
};
/** The candles a drawing can be placed on (times in UTC), and the drawings already there. */
const describeCandlesAndDrawings = (info: ReturnType<ChartReactAPI['getChartInfo']>) => {
const candles = info.chart?.chartModel.mainCandleSeries.dataPoints.filter(candle => !candle.expansion) ?? [];
const first = candles[0];
const last = candles[candles.length - 1];
const daily = ['d', 'w', 'mo', 'y'].includes(info.period.durationType);
const time = daily ? isoDay : isoMinute;
const drawings = (info.instrument ? info.drawings[info.instrument] : undefined) ?? [];
const shapes = drawings.filter(drawing => !drawing.id.endsWith('-label'));
return [
first && last
? `candles from ${time(first.timestamp)} to ${time(last.timestamp)}${daily ? '' : ' UTC'}, last price ${last.close}`
: '',
shapes.length > 0 ? `drawings: ${shapes.map(describeDrawing).join(', ')}` : '',
];
};
/** One line per chart of the current layout, numbered the way the user sees them. */
export const describeChartState = (api: ChartReactAPI, now = Date.now()) => {
const layout = api.getMultiChartLayout();
const chartCount = getChartsAmount(layout);
const selectedChart = Number(api.getSelectedChartId()) + 1;
const charts = Array.from({ length: chartCount }, (_, index) => {
const info = api.getChartInfo(String(index));
const comparisons = info.compareInstruments.map(item => item.symbol);
const parts = [
info.instrument ?? 'no symbol',
formatTimeframe(info.period),
info.chartType,
describeStudies(info.studies),
comparisons.length > 0 ? `compared with: ${comparisons.join(', ')}` : '',
...describeCandlesAndDrawings(info),
];
return `Chart ${index + 1}: ${parts.filter(part => part.length > 0).join('; ')}`;
});
return [
'Current chart state:',
describeToday(now),
`Layout ${layout} (${chartCount} ${chartCount === 1 ? 'chart' : 'charts'}), selected chart: ${selectedChart}.`,
...charts,
].join('\n');
};
export const describeAvailableIndicators = (studies: TStudySettings[]) =>
`Indicators the chart offers: ${studies.map(study => study.title).join(', ')}.`;
/** The chart state, and the indicators the chart offers; call it again whenever the chart changes. */
export const buildDevexaContext = (api: ChartReactAPI | undefined, studies: TStudySettings[]): ContextItem[] =>
api
? [{ role: CONTEXT_ROLE, content: [describeChartState(api), describeAvailableIndicators(studies)].join('\n') }]
: [];
note

Don't send the command instructions from the page as well. The assistant would get them even when the Chart Control tool is off, and would say it changed the chart when nothing happened.

What the Chart Control tool tells the assistant​

For reference, this is the tool's description. It matches the commands of the code on this page: if you add or change commands, ask the Devexa team to update it.

You can change the DXcharts chart on this page. Use this tool when the user asks to change the chart or to draw on it. Send the commands in the order they should run, for example: {"commands":[{"action":"changeSymbol","symbol":"AAPL"},{"action":"setTimeframe","timeframe":"5m"}]} The page runs them and reports back what it applied and what it skipped, with the reason. Answer from that report in one or two short sentences: say what changed, and say plainly what was skipped and why. Never say a change was made unless the report lists it as applied. If part of a request is something you won't do (for example a price forecast), still send the chart changes you can do and say which part you left out. With every message the page sends the current chart state: today's date, the layout and the selected chart, and for each chart its symbol, timeframe, chart type, indicators, comparisons, candle range, latest price and drawings, and the indicators the chart offers. Actions and their fields ([chart] is optional): - changeSymbol: symbol, [chart]. Use a ticker, not a company name: Apple → AAPL, Tesla → TSLA. - setTimeframe: timeframe, [chart]. For example 1m, 5m, 15m, 30m, 1h, 4h, 1d, 1w, 1mo. - setChartType: chartType. One of candle, bar, line, area, hollow, heikinAshi, baseline, histogram, renko. Changes all charts. - setLayout: layout. One of 1x1, 2x1, 1x2, 2x2, 3x1, 1x3, 2x4 (rows x columns: 1x2 is two charts side by side, 2x1 is two charts stacked). There is no 4x4 layout. - addIndicator: indicator, [chart]. Indicator name, for example RSI, MACD, SMA, EMA, Bollinger Bands. - removeIndicator: indicator, [chart]. - removeAllIndicators: [chart]. - compareSymbol: symbol, [chart]. Adds another instrument to the chart for comparison. - removeComparison: symbol, [chart]. - setTheme: theme. One of dark (Classic Dark), light (Classic Light), cloudDancer, oud, solar, still. - setPriceType: priceType, [chart]. One of last, bid, ask, mark. - setVolume: visible (true or false), [chart]. - setTimezone: timezone. IANA name, for example America/New_York or Europe/London. - addDrawing: drawing, [points], [role], [label], [color], [stop], [target], [icon], [chart]. Draws on the chart, one command per drawing ("draw support and resistance" → two commands, role support and role resistance). drawing is one of trend_line, ray, extended_line, horizontal_line (a price line across the chart), horizontal_ray, vertical_line (marks a time), rectangle, fib_retracement, fib_extension, trend_channel, price_range, date_range, date_price_range, text (a note), callout, arrow_up, arrow_down, arrow, price_label, info_line, regression_trend, volume_profile, anchored_volume_profile, long_position, short_position, oval, curve, arc, path, cycle_brackets, icon, brush, highlighter, pitchfork, fib_rays, fib_arcs, fib_circles, fib_channel, fib_time_zones, fib_time_extension, fib_time_ratios, fib_spiral, gann_square, gann_box, gann_fan, elliott_impulse, elliott_correction. points: only the places the user named, in order, each {"time": ..., "price": ...}. Leave out what the user did not say, or the whole list: the chart places the drawing where it fits best (a trend line along the swings, a price line at the nearest level, a Fib over the last swing, a box around the recent range). time is YYYY-MM-DD, YYYY-MM-DD HH:mm, YYYY-MM for a whole month, or latest; a month or day without a year is its latest occurrence up to today. price is a number, or high, low, open or close of the candles at that time ("from the March low to the June low" → [{"time":"YYYY-03","price":"low"},{"time":"YYYY-06","price":"low"}]). role: support or resistance, for a drawing the chart places. label: the text of a note or callout, or a label next to a line or box. color: red, green, blue, orange, yellow, purple, pink, white, gray or black. stop and target: a long_position's or short_position's stop and target, as fields, not points; each is a price, or a distance from the entry in percent ("5%"). Its only point is the entry, left out for the latest close ("long with stop at 140 and target 230" → {"action":"addDrawing","drawing":"long_position","stop":140,"target":230}; "long with a 5% stop and a 10% target" → {"action":"addDrawing","drawing":"long_position","stop":"5%","target":"10%"}). A long's stop is below the entry and its target above, a short's the other way round; the latest price of each chart is in the chart state. Order size (quantity) can't be set. icon: the icon's name, for example bell, heart, check, thumbs-up, dollar-sign. - removeDrawings: which, [drawing], [chart]. which is last (what the chat added last: "remove it"), chat (all drawings added from the chat) or all (every drawing on the chart). drawing narrows it to one kind, as named in addDrawing, or "support line" / "resistance line"; with last it takes off the latest drawing of that kind ("remove the trend line" → {"action":"removeDrawings","which":"last","drawing":"trend_line"}). The drawings on each chart are listed in the chart state. "chart" is the chart number the user sees, starting from 1 ("the 2nd chart" → 2), or "all". Leave it out to change the selected chart. Put all commands for one request into one call; they run in order. To change a chart of a new layout, put setLayout first. Custom indicators written in JavaScript are not chart commands: they still go in a __CHART_REACT_API.addCustomStudy(...) code block. If the request is not about these actions, don't use this tool.

Step 3. Apply the commands and report back​

Listen to widget events with addEventListener. When a chartCommands event arrives:

  1. Pass event.commands to parseChartCommandList. It drops commands with unknown actions or missing fields, and says why.
  2. Apply the rest with executeChartCommands. A command that cannot be applied is skipped with a reason, for example "there is no chart 3 in the 1x2 layout". The other commands still run.
  3. Show the result with sendNotification.
  4. Report the result with reportChartCommandResult(event.commandId, { applied, skipped }). Devexa waits about 20 seconds for it, so report within that time even if the chart is slow, for example after 12 seconds with "the chart took too long".
import { ContextItem } from '@dx-private/devexa-widget-platform';
import { ChartReactAPI } from '@dx-private/dxchart5-react/dist/chart/view-models/api/chart-react-api.view-model';
import { ParsedChartCommands } from './chart-commands';
import {
ChartCommandExecutorOptions,
ChartCommandReport,
executeChartCommands,
summarizeChartCommandReport,
} from './chart-command-executor';
import { buildDevexaContext } from './devexa-context';
/** What the Devexa widget needs from the chart page. */
export interface DevexaChartControl extends ChartCommandExecutorOptions {
/** The API from `onApiCreated`; `undefined` until the chart is ready. */
readonly getApi: () => ChartReactAPI | undefined;
}
export const getDevexaChartContext = (control: DevexaChartControl): ContextItem[] =>
buildDevexaContext(control.getApi(), control.getStudies());
const NOTIFICATION_MIN_TIME_MS = 4000;
const NOTIFICATION_MAX_TIME_MS = 10000;
const NOTIFICATION_TIME_PER_CHAR_MS = 60;
const CHART_API_NOT_READY = 'Chart API is not initialized yet';
/** Applies chart commands and shows what happened on top of the chart. */
export const applyDevexaChartCommands = async (
control: DevexaChartControl,
parsed: ParsedChartCommands,
): Promise<ChartCommandReport> => {
const api = control.getApi();
if (!api) {
console.error(CHART_API_NOT_READY);
return {
applied: [],
skipped: [...parsed.rejected, CHART_API_NOT_READY],
};
}
const report = await executeChartCommands(api, parsed.commands, control);
const result: ChartCommandReport = {
applied: report.applied,
skipped: [...parsed.rejected, ...report.skipped],
};
const summary = summarizeChartCommandReport(result);
if (summary.length > 0) {
try {
const displayTime = Math.min(
NOTIFICATION_MAX_TIME_MS,
Math.max(NOTIFICATION_MIN_TIME_MS, summary.length * NOTIFICATION_TIME_PER_CHAR_MS),
);
api.sendNotification(summary, { displayTime });
} catch (error) {
console.error('[Devexa chart control]: sendNotification failed', error);
}
}
return result;
};

The parser:

/**
* Chart commands that Devexa sends to the page.
*
* Devexa answers a chart request with a JSON code block, for example:
* {"commands":[{"action":"changeSymbol","symbol":"AAPL"},{"action":"setTimeframe","timeframe":"5m"}]}
* When the user clicks "Add to Chart" under that block, the Devexa widget emits a `customizeChart`
* event whose payload is the text of the block. `parseChartCommands` turns that text into commands.
*/
/** 1-based chart number as the user sees it, or every chart of the current layout. */
export type ChartTarget = number | 'all';
/** A point of a drawing as written; what is left out is placed by the chart. */
export interface DrawingPointText {
readonly time?: string;
readonly price?: string;
}
/** The last drawing added from the chat, all drawings added from the chat, or every drawing. */
export type DrawingsToRemove = 'last' | 'chat' | 'all';
export type ChartCommand =
| { readonly action: 'changeSymbol'; readonly symbol: string; readonly chart?: ChartTarget }
| { readonly action: 'setTimeframe'; readonly timeframe: string; readonly chart?: ChartTarget }
| { readonly action: 'setChartType'; readonly chartType: string }
| { readonly action: 'setLayout'; readonly layout: string }
| { readonly action: 'addIndicator'; readonly indicator: string; readonly chart?: ChartTarget }
| { readonly action: 'removeIndicator'; readonly indicator: string; readonly chart?: ChartTarget }
| { readonly action: 'removeAllIndicators'; readonly chart?: ChartTarget }
| { readonly action: 'compareSymbol'; readonly symbol: string; readonly chart?: ChartTarget }
| { readonly action: 'removeComparison'; readonly symbol: string; readonly chart?: ChartTarget }
| { readonly action: 'setTheme'; readonly theme: string }
| { readonly action: 'setPriceType'; readonly priceType: string; readonly chart?: ChartTarget }
| { readonly action: 'setVolume'; readonly visible: boolean; readonly chart?: ChartTarget }
| { readonly action: 'setTimezone'; readonly timezone: string }
| {
readonly action: 'addDrawing';
readonly drawing: string;
readonly points?: DrawingPointText[];
readonly role?: 'support' | 'resistance';
readonly label?: string;
readonly color?: string;
readonly stop?: string;
readonly target?: string;
readonly icon?: string;
readonly chart?: ChartTarget;
}
| {
readonly action: 'removeDrawings';
readonly which: DrawingsToRemove;
/** Only drawings of this kind, e.g. "trend_line" or "support line". */
readonly drawing?: string;
readonly chart?: ChartTarget;
};
export type ChartCommandAction = ChartCommand['action'];
export interface ParsedChartCommands {
readonly commands: ChartCommand[];
/** Why some of the received commands were dropped, in a form that can be shown to the user. */
readonly rejected: string[];
}
interface CommandSpec {
readonly text?:
'symbol' | 'timeframe' | 'chartType' | 'layout' | 'indicator' | 'theme' | 'priceType' | 'timezone' | 'drawing';
readonly flag?: 'visible';
readonly perChart: boolean;
/** Reads the other fields of the command, or says why they can't be read. */
readonly fields?: (raw: Record<string, unknown>) => Record<string, unknown> | string;
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null && !Array.isArray(value);
const readText = (value: unknown): string | undefined => {
if (typeof value === 'number' && Number.isFinite(value)) {
return String(value);
}
if (typeof value === 'string' && value.trim().length > 0) {
return value.trim();
}
return undefined;
};
const withoutEmpty = (fields: Record<string, unknown>) =>
Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
/** `{"time": "2026-03", "price": "low"}`, "2026-03@low" or a price; a point left out stays in its place, empty. */
const readDrawingPoint = (value: unknown): DrawingPointText => {
if (isRecord(value)) {
return withoutEmpty({ time: readText(value.time), price: readText(value.price) });
}
if (typeof value === 'number') {
return withoutEmpty({ price: readText(value) });
}
const [time, price] = (readText(value) ?? '').split('@');
return withoutEmpty({ time: readText(time), price: readText(price) });
};
const readDrawingFields = (raw: Record<string, unknown>) => {
const listed = typeof raw.points === 'string' ? raw.points.split(/[;|]/) : raw.points;
if (listed !== undefined && !Array.isArray(listed)) {
return 'addDrawing has "points" that are not a list';
}
const single = readDrawingPoint({ time: raw.time, price: raw.price });
const points = listed ? listed.map(readDrawingPoint) : Object.keys(single).length > 0 ? [single] : undefined;
const role = readText(raw.role)?.toLowerCase();
return withoutEmpty({
points,
role: role === 'support' || role === 'resistance' ? role : undefined,
label: readText(raw.label),
color: readText(raw.color),
stop: readText(raw.stop),
target: readText(raw.target),
icon: readText(raw.icon),
});
};
const DRAWINGS_TO_REMOVE: Record<string, DrawingsToRemove> = {
last: 'last',
latest: 'last',
it: 'last',
that: 'last',
chat: 'chat',
mine: 'chat',
yours: 'chat',
added: 'chat',
all: 'all',
every: 'all',
everything: 'all',
};
const readDrawingsToRemove = (raw: Record<string, unknown>) => {
const text = readText(raw.which)?.toLowerCase();
const which = text === undefined ? 'last' : DRAWINGS_TO_REMOVE[text];
return which
? withoutEmpty({ which, drawing: readText(raw.drawing) })
: `removeDrawings has an unknown "which" "${text}"`;
};
const COMMAND_SPECS: Record<ChartCommandAction, CommandSpec> = {
changeSymbol: { text: 'symbol', perChart: true },
setTimeframe: { text: 'timeframe', perChart: true },
setChartType: { text: 'chartType', perChart: false },
setLayout: { text: 'layout', perChart: false },
addIndicator: { text: 'indicator', perChart: true },
removeIndicator: { text: 'indicator', perChart: true },
removeAllIndicators: { perChart: true },
compareSymbol: { text: 'symbol', perChart: true },
removeComparison: { text: 'symbol', perChart: true },
setTheme: { text: 'theme', perChart: false },
setPriceType: { text: 'priceType', perChart: true },
setVolume: { flag: 'visible', perChart: true },
setTimezone: { text: 'timezone', perChart: false },
addDrawing: { text: 'drawing', perChart: true, fields: readDrawingFields },
removeDrawings: { perChart: true, fields: readDrawingsToRemove },
};
const ORDINALS: Record<string, number> = {
first: 1,
second: 2,
third: 3,
fourth: 4,
fifth: 5,
sixth: 6,
seventh: 7,
eighth: 8,
one: 1,
two: 2,
three: 3,
four: 4,
five: 5,
six: 6,
seven: 7,
eight: 8,
};
const isChartCommandAction = (value: unknown): value is ChartCommandAction =>
typeof value === 'string' && Object.prototype.hasOwnProperty.call(COMMAND_SPECS, value);
const stripCodeFence = (text: string) =>
text
.trim()
.replace(/^```[\w-]*\s*/, '')
.replace(/```$/, '')
.trim();
const parseJson = (text: string): unknown => {
if (!text.startsWith('{') && !text.startsWith('[')) {
return undefined;
}
try {
return JSON.parse(text);
} catch {
return undefined;
}
};
const readFlag = (value: unknown): boolean | undefined => {
if (typeof value === 'boolean') {
return value;
}
const text = readText(value)?.toLowerCase();
if (text === undefined) {
return undefined;
}
if (['true', 'show', 'on', 'yes', 'visible', 'enable', 'enabled'].includes(text)) {
return true;
}
if (['false', 'hide', 'off', 'no', 'hidden', 'disable', 'disabled'].includes(text)) {
return false;
}
return undefined;
};
/**
* Accepts 2, "2", "2nd", "chart 2", "second" and "all". Returns `null` for a value that is present
* but cannot be understood, so the command is dropped instead of changing the wrong chart.
*/
export const readChartTarget = (value: unknown): ChartTarget | undefined | null => {
if (value === undefined || value === null || value === '') {
return undefined;
}
if (typeof value === 'number') {
return Number.isInteger(value) && value >= 1 ? value : null;
}
if (typeof value !== 'string') {
return null;
}
const text = value.trim().toLowerCase();
if (text === 'all' || text === 'all charts' || text === 'every chart') {
return 'all';
}
const ordinal = ORDINALS[text.replace(/^(the\s+)?(chart\s+)?/, '').replace(/\s+chart$/, '')];
if (ordinal !== undefined) {
return ordinal;
}
const digits = text.match(/^(?:chart\s*#?\s*)?(\d+)(?:st|nd|rd|th)?$/);
const chartNumber = digits ? Number(digits[1]) : NaN;
return chartNumber >= 1 ? chartNumber : null;
};
const toCommand = (raw: unknown): ChartCommand | string => {
if (!isRecord(raw)) {
return 'a command is not an object';
}
const action = raw.action;
if (!isChartCommandAction(action)) {
return `unknown action "${String(action)}"`;
}
const spec = COMMAND_SPECS[action];
const command: Record<string, unknown> = { action };
if (spec.text) {
const text = readText(raw[spec.text]);
if (text === undefined) {
return `${action} has no "${spec.text}"`;
}
command[spec.text] = text;
}
if (spec.flag) {
const flag = readFlag(raw[spec.flag]);
if (flag === undefined) {
return `${action} needs "${spec.flag}": true or false`;
}
command[spec.flag] = flag;
}
if (spec.perChart) {
const chart = readChartTarget(raw.chart);
if (chart === null) {
return `${action} has an unknown chart "${String(raw.chart)}"`;
}
if (chart !== undefined) {
command.chart = chart;
}
}
if (spec.fields) {
const fields = spec.fields(raw);
if (typeof fields === 'string') {
return fields;
}
Object.assign(command, fields);
}
return command as ChartCommand;
};
const toCommandList = (json: unknown): unknown[] | undefined => {
if (Array.isArray(json)) {
return json;
}
if (isRecord(json) && Array.isArray(json.commands)) {
return json.commands;
}
if (isRecord(json) && 'action' in json) {
return [json];
}
return undefined;
};
/** Validates a list of raw command objects into applied-ready commands and rejection reasons. */
export const parseChartCommandList = (items: unknown[]): ParsedChartCommands => {
const commands: ChartCommand[] = [];
const rejected: string[] = [];
items.forEach(item => {
const result = toCommand(item);
if (typeof result === 'string') {
rejected.push(result);
} else {
commands.push(result);
}
});
return { commands, rejected };
};
/**
* Parses a `customizeChart` payload. Returns `null` when the payload is not a chart command message
* (for example, a custom indicator written in JavaScript), so the caller can handle it another way.
*
* Accepted shapes: `{"commands": [...]}`, a bare array of commands, or a single command object.
*/
export const parseChartCommands = (payload: string): ParsedChartCommands | null => {
const items = toCommandList(parseJson(stripCodeFence(payload)));
return items === undefined ? null : parseChartCommandList(items);
};

The executor applies the commands with ChartReactAPI:

/**
* Applies chart commands with the public ChartReactAPI. Commands run in order; a command that
* cannot be applied is reported and skipped, the rest still run.
*/
import { AggregationPeriod } from '@dx-private/dxchart5-react/dist/chart/model/aggregation.model';
import {
MultiChartLayoutType,
getChartsAmount,
layouts,
} from '@dx-private/dxchart5-react/dist/chart/model/multichart.model';
import { TStudySettings } from '@dx-private/dxchart5-react/dist/chart/model/studies.model';
import { ChartReactAPI } from '@dx-private/dxchart5-react/dist/chart/view-models/api/chart-react-api.view-model';
import { ChartCommand, ChartTarget, DrawingsToRemove } from './chart-commands';
import {
CHAT_DRAWING_ID_PREFIX,
DRAWINGS,
DrawingAsk,
DrawingKind,
DrawingPlan,
drawingNameOfType,
parsePositionLevel,
parsePriceAsk,
parseTimeAsk,
planDrawing,
resolveDrawingKind,
} from './chart-drawings';
import {
describeChartIds,
formatTimeframe,
isVolumeIndicator,
resolveChartTarget,
resolveChartType,
resolveIndicator,
resolveLayout,
resolvePriceType,
resolveTheme,
resolveTimeframe,
resolveTimezone,
studyMatches,
suggestIndicators,
toKey,
} from './chart-command-values';
export interface ChartCommandExecutorOptions {
/** Built-in indicators the chart offers, usually `dxStudiesProvider.getStudies()`. */
readonly getStudies: () => TStudySettings[];
/**
* Turns what the assistant wrote ("AAPL", "BTC/USD") into a symbol your data provider knows,
* for example the first result of `symbolSuggestProvider.searchInstruments`.
* Resolve `undefined` when nothing matches. Without this option the symbol is used as written.
*/
readonly searchSymbol?: (query: string) => Promise<string | undefined>;
}
export interface ChartCommandReport {
/** Short descriptions of the changes that were made, e.g. "Timeframe 5m". */
readonly applied: string[];
/** Why some commands were not applied, e.g. "there is no chart 3 in the 1x2 layout". */
readonly skipped: string[];
}
interface ExecutionContext {
readonly api: ChartReactAPI;
readonly options: ChartCommandExecutorOptions;
/** Indicators and comparisons changed during this run, so later commands build on earlier ones. */
readonly studies: Map<string, TStudySettings[]>;
readonly comparisons: Map<string, string[]>;
/** Ids for the drawings of this run; they share a stem, so "remove it" takes them off together. */
readonly newDrawingId: () => string;
/**
* Charts that load new candles after a change in this run, with their candles as they were before
* ('' for a new chart); a drawing on them waits for the new candles.
*/
readonly candlesBefore: Map<string, string>;
}
type AddDrawingCommand = Extract<ChartCommand, { action: 'addDrawing' }>;
type RemoveDrawingsCommand = Extract<ChartCommand, { action: 'removeDrawings' }>;
class SkippedCommandError extends Error {}
const skip = (reason: string): never => {
throw new SkippedCommandError(reason);
};
const LAYOUT_READY_TIMEOUT_MS = 3000;
const LAYOUT_READY_POLL_MS = 50;
const CANDLES_READY_TIMEOUT_MS = 5000;
const CANDLES_READY_POLL_MS = 100;
const createUuid = () =>
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
? crypto.randomUUID()
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
const targetChartIds = (api: ChartReactAPI, target: ChartTarget | undefined) => {
const resolution = resolveChartTarget(api, target);
return 'error' in resolution ? skip(resolution.error) : resolution.chartIds;
};
const getStudies = (context: ExecutionContext, chartId: string) =>
context.studies.get(chartId) ?? context.api.getChartInfo(chartId).studies;
const setStudies = (context: ExecutionContext, chartId: string, studies: TStudySettings[]) => {
context.api.setStudies(studies, chartId);
context.studies.set(chartId, studies);
};
const getComparisons = (context: ExecutionContext, chartId: string) =>
context.comparisons.get(chartId) ?? context.api.getChartInfo(chartId).compareInstruments.map(item => item.symbol);
const findComparison = (symbols: string[], query: string) => {
const key = toKey(query);
return symbols.find(symbol => toKey(symbol) === key || toKey(symbol.split(':')[0]) === key);
};
const resolveSymbol = async (context: ExecutionContext, query: string) => {
const typed = query.trim().toUpperCase();
const { searchSymbol } = context.options;
if (!searchSymbol) {
return typed;
}
let found: string | undefined;
try {
found = await searchSymbol(query.trim());
} catch (error) {
console.warn('[Devexa chart control]: symbol search failed, using the symbol as written', error);
return typed;
}
return found ?? skip(`no symbol found for "${query}"`);
};
/**
* There is no public setter for the multi-chart grid, but `syncLayoutParts` applies the grid
* of a layout object, so the current layout is generated and sent back with another grid.
*/
const applyLayout = (api: ChartReactAPI, layout: MultiChartLayoutType) => {
const current = api.generateLayout();
api.syncLayoutParts(
{
...current,
multiChart: { ...current.multiChart, layout },
id: 'devexa-chart-control',
name: 'Devexa chart control',
lastUpdateTimeStamp: Date.now(),
},
{ multiChartLayout: true },
);
};
/** New charts of a bigger grid are created asynchronously; commands for them must wait. */
const waitForCharts = (api: ChartReactAPI, chartCount: number) =>
new Promise<void>(resolve => {
const startedAt = Date.now();
const check = () => {
const ready = Array.from({ length: chartCount }, (_, index) => String(index)).every(chartId => {
const info = api.getChartInfo(chartId);
return info.id === chartId && info.chart !== undefined;
});
if (ready || Date.now() - startedAt > LAYOUT_READY_TIMEOUT_MS) {
resolve();
return;
}
setTimeout(check, LAYOUT_READY_POLL_MS);
};
check();
});
const mainCandles = (api: ChartReactAPI, chartId: string) =>
api.getChartInfo(chartId).chart?.chartModel.mainCandleSeries.dataPoints.filter(candle => !candle.expansion) ?? [];
/** What the chart's candles are now, to tell when new ones have come. */
const candlesFingerprint = (api: ChartReactAPI, chartId: string) => {
const candles = mainCandles(api, chartId);
const last = candles[candles.length - 1];
return [candles.length, candles[0]?.timestamp, last?.timestamp, last?.close].join(':');
};
const expectNewCandles = (context: ExecutionContext, chartIds: string[], fingerprint = candlesFingerprint) =>
chartIds
.filter(chartId => !context.candlesBefore.has(chartId))
.forEach(chartId => context.candlesBefore.set(chartId, fingerprint(context.api, chartId)));
/** Candles of another symbol or timeframe, or of a new chart, come asynchronously; a drawing waits for them. */
const waitForNewCandles = (context: ExecutionContext, chartId: string) =>
new Promise<void>(resolve => {
// with no candles yet, any that come will do
const before =
context.candlesBefore.get(chartId) ?? (mainCandles(context.api, chartId).length === 0 ? '' : undefined);
context.candlesBefore.delete(chartId);
const startedAt = Date.now();
const check = () => {
const arrived =
mainCandles(context.api, chartId).length > 0 &&
(before === '' || candlesFingerprint(context.api, chartId) !== before);
if (before === undefined || arrived || Date.now() - startedAt > CANDLES_READY_TIMEOUT_MS) {
resolve();
return;
}
setTimeout(check, CANDLES_READY_POLL_MS);
};
check();
});
const unknownIndicator = (name: string, studies: TStudySettings[]) => {
const suggestions = suggestIndicators(name, studies);
return suggestions.length > 0
? `"${name}" matches several indicators: ${suggestions.join(', ')}`
: `there is no "${name}" indicator`;
};
const addIndicator = (context: ExecutionContext, indicator: string, chart: ChartTarget | undefined) => {
const { api, options } = context;
const chartIds = targetChartIds(api, chart);
if (isVolumeIndicator(indicator)) {
chartIds.forEach(chartId => api.setVolumesVisible(true, chartId));
return `Volume shown${describeChartIds(api, chartIds)}`;
}
const available = options.getStudies();
const study = resolveIndicator(indicator, available) ?? skip(unknownIndicator(indicator, available));
const addedTo = chartIds.filter(chartId => {
const current = getStudies(context, chartId);
if (current.some(item => item.id === study.id)) {
return false;
}
setStudies(context, chartId, [...current, { ...study, uuid: createUuid() }]);
return true;
});
if (addedTo.length === 0) {
skip(`${study.title} is already on the chart`);
}
return `Added ${study.title}${describeChartIds(api, addedTo)}`;
};
const removeIndicator = (context: ExecutionContext, indicator: string, chart: ChartTarget | undefined) => {
const { api, options } = context;
const chartIds = targetChartIds(api, chart);
if (isVolumeIndicator(indicator)) {
chartIds.forEach(chartId => api.setVolumesVisible(false, chartId));
return `Volume hidden${describeChartIds(api, chartIds)}`;
}
// Built-in indicators are matched by id; anything else (e.g. a custom indicator) by its name.
const builtIn = resolveIndicator(indicator, options.getStudies());
const matches = (study: TStudySettings) => (builtIn ? study.id === builtIn.id : studyMatches(study, indicator));
const title = builtIn?.title ?? indicator;
const removedFrom = chartIds.filter(chartId => {
const current = getStudies(context, chartId);
const remaining = current.filter(study => !matches(study));
if (remaining.length === current.length) {
return false;
}
setStudies(context, chartId, remaining);
return true;
});
if (removedFrom.length === 0) {
skip(`${title} is not on the chart`);
}
return `Removed ${title}${describeChartIds(api, removedFrom)}`;
};
const removeAllIndicators = (context: ExecutionContext, chart: ChartTarget | undefined) => {
const chartIds = targetChartIds(context.api, chart).filter(chartId => getStudies(context, chartId).length > 0);
if (chartIds.length === 0) {
skip('there are no indicators on the chart');
}
chartIds.forEach(chartId => setStudies(context, chartId, []));
return `Removed all indicators${describeChartIds(context.api, chartIds)}`;
};
const compareSymbol = async (context: ExecutionContext, symbol: string, chart: ChartTarget | undefined) => {
const { api } = context;
const chartIds = targetChartIds(api, chart);
const resolved = await resolveSymbol(context, symbol);
const addedTo = chartIds.filter(chartId => {
const comparisons = getComparisons(context, chartId);
if (api.getChartInfo(chartId).instrument === resolved || comparisons.includes(resolved)) {
return false;
}
api.addCompareInstrument(resolved, chartId);
context.comparisons.set(chartId, [...comparisons, resolved]);
return true;
});
if (addedTo.length === 0) {
skip(`${resolved} is already on the chart`);
}
return `Comparing with ${resolved}${describeChartIds(api, addedTo)}`;
};
const removeComparison = (context: ExecutionContext, symbol: string, chart: ChartTarget | undefined) => {
const { api } = context;
const removed = targetChartIds(api, chart).flatMap(chartId => {
const comparisons = getComparisons(context, chartId);
const match = findComparison(comparisons, symbol);
if (match === undefined) {
return [];
}
api.removeCompareInstrument(match, chartId);
context.comparisons.set(
chartId,
comparisons.filter(item => item !== match),
);
return [{ chartId, symbol: match }];
});
if (removed.length === 0) {
skip(`${symbol.toUpperCase()} is not compared on the chart`);
}
const chartIds = removed.map(item => item.chartId);
return `Removed comparison with ${removed[0].symbol}${describeChartIds(api, chartIds)}`;
};
const DAILY_DURATION_TYPES = ['d', 'w', 'mo', 'y'];
const timeFormatter = (period: AggregationPeriod, timezone: string | undefined) => {
const intraday = !DAILY_DURATION_TYPES.includes(period.durationType);
return (timestamp: number) => {
const date = new Date(timestamp);
const sameYear = date.getUTCFullYear() === new Date().getUTCFullYear();
// daily candles stand at midnight UTC: read in another zone they would land a day early
return new Intl.DateTimeFormat('en-GB', {
day: 'numeric',
month: 'short',
...(sameYear ? {} : { year: 'numeric' }),
...(intraday ? { hour: '2-digit', minute: '2-digit', timeZone: timezone } : { timeZone: 'UTC' }),
}).format(date);
};
};
const withoutPeriod = (sentence: string) => sentence.replace(/\.$/, '');
/** Places the drawing on one chart and adds it; says why when it can't. */
const drawOnChart = async (
context: ExecutionContext,
chartId: string,
ask: DrawingAsk,
): Promise<DrawingPlan | string> => {
const { api } = context;
await waitForNewCandles(context, chartId);
const info = api.getChartInfo(chartId);
const { chart, instrument } = info;
if (!chart || !instrument) {
return 'the chart is not ready yet';
}
const series = chart.chartModel.mainCandleSeries;
const candles = mainCandles(api, chartId);
if (candles.length === 0) {
return 'the chart has no candles yet';
}
const view = { from: Math.max(0, series.dataIdxStart), to: Math.min(candles.length - 1, series.dataIdxEnd) };
const plan = planDrawing(ask, candles, {
view,
formatPrice: price => chart.chartModel.pane.valueFormatter(price),
formatTime: timeFormatter(info.period, info.timezone),
newId: context.newDrawingId,
});
if (!plan) {
return "I couldn't work out what to draw";
}
// only on the chart it was asked for: removing a synced drawing from a chart that isn't selected
// keeps it in the saved layout, so it would come back after a reload
plan.drawings.forEach(drawing => api.addDrawing({ ...drawing, synced: false }, chartId));
const onChart = api.getChartInfo(chartId).drawings[instrument] ?? [];
if (!onChart.some(drawing => drawing.id === plan.drawings[0].id)) {
return 'the chart has as many drawings as it can hold; remove some first';
}
// a drawing placed where the user said may start before what is on screen: bring it in
const earliest = Math.min(...plan.drawings.flatMap(drawing => drawing.keyPoints.map(p => p.timestamp)));
const earliestIndex = Math.max(
0,
candles.findIndex(candle => candle.timestamp >= earliest),
);
if (earliestIndex >= view.from) {
return plan;
}
const pad = Math.max(3, Math.round((view.to - earliestIndex) * 0.05));
chart.scale.setXScale(Math.max(0, earliestIndex - pad), chart.scale.xEnd);
return { ...plan, notes: [...plan.notes, 'I moved the chart back so it is in view.'] };
};
/** A drawing kind, and the side it marks, from what the assistant wrote: "trend_line", "box", "support line". */
const readDrawingName = (text: string) => {
const key = toKey(text);
const role: DrawingAsk['role'] = key.includes('support')
? 'support'
: key.includes('resistance')
? 'resistance'
: undefined;
const kind: DrawingKind | undefined = resolveDrawingKind(text) ?? (role ? 'horizontal_line' : undefined);
return { kind, role };
};
const addDrawing = async (context: ExecutionContext, command: AddDrawingCommand) => {
const { api } = context;
const named = readDrawingName(command.drawing);
const kind = named.kind ?? skip(`there is no "${command.drawing}" drawing`);
const role = command.role ?? named.role;
const ask: DrawingAsk = {
kind,
points: (command.points ?? []).map(point => ({
time: parseTimeAsk(point.time),
price: parsePriceAsk(point.price),
})),
role,
label: command.label,
color: command.color,
stop: parsePositionLevel(command.stop),
target: parsePositionLevel(command.target),
icon: command.icon,
};
const results: { chartId: string; result: DrawingPlan | string }[] = [];
for (const chartId of targetChartIds(api, command.chart)) {
results.push({ chartId, result: await drawOnChart(context, chartId, ask) });
}
const drawn = results.flatMap(({ chartId, result }) =>
typeof result === 'string' ? [] : [{ chartId, plan: result }],
);
if (drawn.length === 0) {
const reason = results.find(({ result }) => typeof result === 'string')?.result;
skip(typeof reason === 'string' ? reason : `couldn't draw the ${DRAWINGS[kind].name}`);
}
const chartIds = drawn.map(item => item.chartId);
if (drawn.length > 1) {
return `Drew the ${DRAWINGS[kind].name}${describeChartIds(api, chartIds)}`;
}
const { summary, notes } = drawn[0].plan;
const caveats = notes.length > 0 ? ` (${notes.map(withoutPeriod).join('; ')})` : '';
return `${withoutPeriod(summary)}${describeChartIds(api, chartIds)}${caveats}`;
};
const LABEL_SUFFIX = '-label';
/** Drawings added from the chat have ids "chat-<run>-<n>": the run they came in, and their place in it. */
const drawingOrder = (drawingId: string) => {
const [, run = '', index = ''] = drawingId.split('-');
return { run, time: parseInt(run, 36) || 0, index: parseInt(index, 36) || 0 };
};
const newestFirst = (a: { id: string }, b: { id: string }) => {
const x = drawingOrder(a.id);
const y = drawingOrder(b.id);
return y.time - x.time || y.index - x.index;
};
/** A drawing of the kind named; for a support or resistance line, also on that side of the latest close. */
const isNamedDrawing = (
drawing: { type: string; keyPoints: { value: number }[] },
named: ReturnType<typeof readDrawingName>,
latestClose: number | undefined,
) => {
if (named.kind === undefined || drawing.type !== DRAWINGS[named.kind].type) {
return false;
}
const value = drawing.keyPoints[0]?.value;
if (named.role === undefined || latestClose === undefined || value === undefined) {
return true;
}
return named.role === 'support' ? value <= latestClose : value >= latestClose;
};
/**
* Of the drawings on a chart (labels left out): every one, those added from the chat, or those the
* chat added last — all of its latest run, or with a kind named, only the latest drawing of it.
*/
const pickDrawings = <T extends { id: string }>(shapes: T[], which: DrawingsToRemove, ofOneKind: boolean) => {
const fromChat = shapes.filter(drawing => drawing.id.startsWith(CHAT_DRAWING_ID_PREFIX));
if (which === 'all') {
return shapes;
}
if (which === 'chat') {
return fromChat;
}
const latest = [...fromChat].sort(newestFirst);
if (ofOneKind) {
return latest.slice(0, 1);
}
return fromChat.filter(drawing => drawingOrder(drawing.id).run === drawingOrder(latest[0]?.id ?? '').run);
};
const removeDrawings = (context: ExecutionContext, command: RemoveDrawingsCommand) => {
const { api } = context;
const named = command.drawing === undefined ? undefined : readDrawingName(command.drawing);
if (named && named.kind === undefined) {
skip(`there is no "${command.drawing}" drawing`);
}
const removed = targetChartIds(api, command.chart).flatMap(chartId => {
const { instrument, drawings } = api.getChartInfo(chartId);
const onChart = instrument ? (drawings[instrument] ?? []) : [];
const latestClose = mainCandles(api, chartId).slice(-1)[0]?.close;
const shapes = onChart.filter(
drawing =>
!drawing.id.endsWith(LABEL_SUFFIX) &&
(named === undefined || isNamedDrawing(drawing, named, latestClose)),
);
const picked = pickDrawings(shapes, command.which, named !== undefined);
const ids = new Set(picked.flatMap(drawing => [drawing.id, `${drawing.id}${LABEL_SUFFIX}`]));
onChart.filter(drawing => ids.has(drawing.id)).forEach(drawing => api.removeDrawing(drawing.id));
return picked.map(drawing => ({ chartId, drawing }));
});
if (removed.length === 0) {
const what = named?.kind ? `is no ${DRAWINGS[named.kind].name}` : 'are no drawings';
skip(command.which === 'all' ? `there ${what} on the chart` : `there ${what} from the chat on the chart`);
}
const chartIds = [...new Set(removed.map(item => item.chartId))];
const name = named?.role ? `${named.role} line` : drawingNameOfType(removed[0].drawing.type);
return removed.length === 1
? `Removed the ${name}${describeChartIds(api, chartIds)}`
: `Removed ${removed.length} drawings${describeChartIds(api, chartIds)}`;
};
const runCommand = async (command: ChartCommand, context: ExecutionContext): Promise<string> => {
const { api } = context;
switch (command.action) {
case 'changeSymbol': {
const chartIds = targetChartIds(api, command.chart);
const symbol = await resolveSymbol(context, command.symbol);
expectNewCandles(
context,
chartIds.filter(chartId => api.getChartInfo(chartId).instrument !== symbol),
);
chartIds.forEach(chartId => api.changeInstrument(symbol, chartId));
return `Symbol ${symbol}${describeChartIds(api, chartIds)}`;
}
case 'setTimeframe': {
const period = resolveTimeframe(command.timeframe) ?? skip(`unknown timeframe "${command.timeframe}"`);
const chartIds = targetChartIds(api, command.chart);
expectNewCandles(
context,
chartIds.filter(
chartId => formatTimeframe(api.getChartInfo(chartId).period) !== formatTimeframe(period),
),
);
chartIds.forEach(chartId => api.changePeriod(period, chartId));
return `Timeframe ${formatTimeframe(period)}${describeChartIds(api, chartIds)}`;
}
case 'setChartType': {
const chartType = resolveChartType(command.chartType) ?? skip(`unknown chart type "${command.chartType}"`);
api.changeChartType(chartType);
return `Chart type ${chartType}`;
}
case 'setLayout': {
const layout =
resolveLayout(command.layout) ??
skip(`there is no "${command.layout}" layout, available: ${layouts.join(', ')}`);
const chartCountBefore = getChartsAmount(api.getMultiChartLayout());
const chartCount = getChartsAmount(layout);
applyLayout(api, layout);
const newChartIds = Array.from({ length: Math.max(0, chartCount - chartCountBefore) }, (_, index) =>
String(chartCountBefore + index),
);
expectNewCandles(context, newChartIds, () => '');
await waitForCharts(api, chartCount);
return `Layout ${layout}`;
}
case 'addIndicator':
return addIndicator(context, command.indicator, command.chart);
case 'removeIndicator':
return removeIndicator(context, command.indicator, command.chart);
case 'removeAllIndicators':
return removeAllIndicators(context, command.chart);
case 'compareSymbol':
return compareSymbol(context, command.symbol, command.chart);
case 'removeComparison':
return removeComparison(context, command.symbol, command.chart);
case 'setTheme': {
const themeNames = api.getLocalization().themes.types;
const theme = resolveTheme(command.theme, themeNames) ?? skip(`unknown theme "${command.theme}"`);
api.changeTheme(theme);
return `Theme ${themeNames[theme] ?? theme}`;
}
case 'setPriceType': {
const priceType = resolvePriceType(command.priceType) ?? skip(`unknown price type "${command.priceType}"`);
const chartIds = targetChartIds(api, command.chart);
chartIds.forEach(chartId => api.setPriceType(priceType, chartId));
return `Price type ${priceType}${describeChartIds(api, chartIds)}`;
}
case 'setVolume': {
const chartIds = targetChartIds(api, command.chart);
chartIds.forEach(chartId => api.setVolumesVisible(command.visible, chartId));
return `Volume ${command.visible ? 'shown' : 'hidden'}${describeChartIds(api, chartIds)}`;
}
case 'setTimezone': {
const timezone = resolveTimezone(command.timezone) ?? skip(`unknown time zone "${command.timezone}"`);
api.setCurrentTimezone(timezone);
return `Time zone ${timezone}`;
}
case 'addDrawing':
return addDrawing(context, command);
case 'removeDrawings':
return removeDrawings(context, command);
}
};
export const executeChartCommands = async (
api: ChartReactAPI,
commands: ChartCommand[],
options: ChartCommandExecutorOptions,
): Promise<ChartCommandReport> => {
const drawingBatch = `${CHAT_DRAWING_ID_PREFIX}${Date.now().toString(36)}`;
let drawingCount = 0;
const context: ExecutionContext = {
api,
options,
studies: new Map(),
comparisons: new Map(),
newDrawingId: () => `${drawingBatch}-${(drawingCount++).toString(36)}`,
candlesBefore: new Map(),
};
const applied: string[] = [];
const skipped: string[] = [];
for (const command of commands) {
try {
applied.push(await runCommand(command, context));
} catch (error) {
if (error instanceof SkippedCommandError) {
skipped.push(error.message);
} else {
console.error(`[Devexa chart control]: "${command.action}" failed`, error);
skipped.push(`${command.action} failed`);
}
}
}
return { applied, skipped };
};
/** One line for the chart notification, e.g. "Symbol AAPL · Timeframe 5m. Not applied: ...". */
export const summarizeChartCommandReport = ({ applied, skipped }: ChartCommandReport) => {
const done = applied.join(' · ');
const notDone = skipped.length > 0 ? `Not applied: ${skipped.join('; ')}` : '';
return [done, notDone].filter(part => part.length > 0).join('. ');
};

An AI assistant does not always write exact values, so they are matched before they reach the chart. For example, "daily" becomes 1d, "candles" becomes candle, "Classic Light" becomes light, and "RSI" becomes the RelativeStrengthIndex indicator:

/**
* Turns the loose values an AI assistant writes ("daily", "candles", "classic light", "RSI")
* into the exact values ChartReactAPI accepts. Every resolver returns `undefined` for a value
* it does not understand, so nothing unexpected reaches the chart.
*/
import { AggregationPeriod } from '@dx-private/dxchart5-react/dist/chart/model/aggregation.model';
import { ChartType, defaultChartTypes } from '@dx-private/dxchart5-react/dist/chart/model/chart.model';
import {
MultiChartLayoutType,
getChartsAmount,
layouts,
} from '@dx-private/dxchart5-react/dist/chart/model/multichart.model';
import { TStudySettings } from '@dx-private/dxchart5-react/dist/chart/model/studies.model';
import { ThemeType, themeTypes } from '@dx-private/dxchart5-react/dist/chart/model/theme.model';
import { ChartReactAPI } from '@dx-private/dxchart5-react/dist/chart/view-models/api/chart-react-api.view-model';
import { PriceType, priceType } from '@dx-private/dxchart5-react/dist/providers/chart-data-provider';
import { ChartTarget } from './chart-commands';
/** Lower-cases and drops everything except letters and digits: "Bollinger Bands" → "bollingerbands". */
export const toKey = (text: string) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
const TIMEFRAME_UNITS: Record<string, AggregationPeriod['durationType']> = {
s: 's',
sec: 's',
secs: 's',
second: 's',
seconds: 's',
m: 'm',
min: 'm',
mins: 'm',
minute: 'm',
minutes: 'm',
h: 'h',
hr: 'h',
hrs: 'h',
hour: 'h',
hours: 'h',
hourly: 'h',
d: 'd',
day: 'd',
days: 'd',
daily: 'd',
w: 'w',
wk: 'w',
week: 'w',
weeks: 'w',
weekly: 'w',
mo: 'mo',
mon: 'mo',
month: 'mo',
months: 'mo',
monthly: 'mo',
y: 'y',
yr: 'y',
year: 'y',
years: 'y',
yearly: 'y',
};
/** "5m", "5 min", "1 hour", "4H", "daily", "1W", "1M" (month) → AggregationPeriod. */
export const resolveTimeframe = (text: string): AggregationPeriod | undefined => {
const match = text.trim().match(/^(\d+)?\s*([a-zA-Z]+)$/);
if (!match) {
return undefined;
}
const duration = match[1] === undefined ? 1 : Number(match[1]);
// A capital M is the usual trading shorthand for a month; a lowercase m is a minute.
const durationType = match[2] === 'M' ? 'mo' : TIMEFRAME_UNITS[match[2].toLowerCase()];
return durationType && duration > 0 ? { duration, durationType } : undefined;
};
export const formatTimeframe = (period: AggregationPeriod) => `${period.duration}${period.durationType}`;
const CHART_TYPE_ALIASES: Record<string, ChartType> = {
candles: 'candle',
candlestick: 'candle',
candlesticks: 'candle',
japanese: 'candle',
bars: 'bar',
ohlc: 'bar',
mountain: 'area',
hollowcandle: 'hollow',
hollowcandles: 'hollow',
heikinashi: 'heikinAshi',
ha: 'heikinAshi',
columns: 'histogram',
column: 'histogram',
scatter: 'scatterPlot',
scatterplot: 'scatterPlot',
};
export const resolveChartType = (text: string): ChartType | undefined => {
const key = toKey(text.replace(/chart$/i, ''));
return defaultChartTypes.find(type => toKey(type) === key) ?? CHART_TYPE_ALIASES[key];
};
const LAYOUT_ALIASES: Record<string, MultiChartLayoutType> = {
single: '1x1',
singlechart: '1x1',
one: '1x1',
onechart: '1x1',
full: '1x1',
sidebyside: '1x2',
stacked: '2x1',
four: '2x2',
fourcharts: '2x2',
quad: '2x2',
grid: '2x2',
eight: '2x4',
eightcharts: '2x4',
};
/** Layout names are rows × columns: 1x2 is two charts side by side, 2x1 is two charts stacked. */
export const resolveLayout = (text: string): MultiChartLayoutType | undefined => {
const grid = text.toLowerCase().match(/(\d)\s*(?:x|×|by|\*)\s*(\d)/);
if (grid) {
return layouts.find(layout => layout === `${grid[1]}x${grid[2]}`);
}
return LAYOUT_ALIASES[toKey(text.replace(/layout$/i, ''))];
};
const THEME_ALIASES: Record<string, ThemeType> = {
night: 'dark',
black: 'dark',
day: 'light',
white: 'light',
};
/** Understands theme ids ("light") and the names users see in the chart settings ("Classic Light"). */
export const resolveTheme = (
text: string,
themeNames: Partial<Record<ThemeType, string>> = {},
): ThemeType | undefined => {
const key = toKey(text.replace(/theme$/i, ''));
const byName = themeTypes.find(theme => {
const name = themeNames[theme];
return name !== undefined && toKey(name) === key;
});
const plainKey = key.replace(/^classic/, '');
return byName ?? themeTypes.find(theme => toKey(theme) === plainKey) ?? THEME_ALIASES[plainKey];
};
const PRICE_TYPE_ALIASES: Record<string, PriceType> = {
close: 'last',
trade: 'last',
lasttrade: 'last',
markprice: 'mark',
};
export const resolvePriceType = (text: string): PriceType | undefined => {
const key = toKey(text);
return priceType.find(type => type === key) ?? PRICE_TYPE_ALIASES[key];
};
const TIMEZONE_ALIASES: Record<string, string> = {
utc: 'UTC',
gmt: 'UTC',
newyork: 'America/New_York',
nyc: 'America/New_York',
est: 'America/New_York',
edt: 'America/New_York',
et: 'America/New_York',
chicago: 'America/Chicago',
cst: 'America/Chicago',
losangeles: 'America/Los_Angeles',
pst: 'America/Los_Angeles',
london: 'Europe/London',
frankfurt: 'Europe/Berlin',
berlin: 'Europe/Berlin',
tokyo: 'Asia/Tokyo',
hongkong: 'Asia/Hong_Kong',
singapore: 'Asia/Singapore',
sydney: 'Australia/Sydney',
};
/** IANA time zone names ("Europe/London") and a few common abbreviations and cities. */
export const resolveTimezone = (text: string): string | undefined => {
const candidate = TIMEZONE_ALIASES[toKey(text)] ?? text.trim();
try {
return new Intl.DateTimeFormat('en-US', { timeZone: candidate }).resolvedOptions().timeZone;
} catch {
return undefined;
}
};
const INDICATOR_ALIASES: Record<string, string> = {
rsi: 'RelativeStrengthIndex',
ma: 'SMA',
movingaverage: 'SMA',
bb: 'BollingerBands',
bollinger: 'BollingerBands',
bollingerband: 'BollingerBands',
atr: 'AverageTrueRange',
obv: 'OnBalanceVolume',
sar: 'ParabolicSAR',
psar: 'ParabolicSAR',
parabolic: 'ParabolicSAR',
mfi: 'MoneyFlowIndex',
stoch: 'FullStochastic',
stochastic: 'FullStochastic',
stochrsi: 'StochasticRSI',
williamsr: 'WilliamsPercentRange',
hma: 'HullMovingAverage',
hull: 'HullMovingAverage',
pivots: 'PivotPoints',
keltner: 'KeltnerChannels',
donchian: 'DonchianChannel',
alligator: 'WilliamsAlligator',
ao: 'AwesomeOscillator',
tsi: 'TrueStrengthIndex',
cmf: 'ChaikinMoneyFlow',
ttm: 'TTMSqueeze',
ichimokucloud: 'Ichimoku',
};
/** Matches a study by its id, a common abbreviation or its title. */
export const studyMatches = (study: TStudySettings, name: string) => {
const key = toKey(name);
return toKey(study.id) === key || toKey(study.title) === key || INDICATOR_ALIASES[key] === study.id;
};
const findByTitlePart = (name: string, studies: TStudySettings[]) => {
const key = toKey(name);
return key.length >= 4 ? studies.filter(study => toKey(study.title).includes(key)) : [];
};
/** Finds a built-in indicator by id ("RelativeStrengthIndex"), abbreviation ("RSI") or title ("Bollinger Bands"). */
export const resolveIndicator = (name: string, studies: TStudySettings[]): TStudySettings | undefined => {
const exact = studies.find(study => studyMatches(study, name));
if (exact) {
return exact;
}
const partial = findByTitlePart(name, studies);
return partial.length === 1 ? partial[0] : undefined;
};
/** Titles that contain the requested name, for a "did you mean" hint when the name is ambiguous. */
export const suggestIndicators = (name: string, studies: TStudySettings[], limit = 3) =>
findByTitlePart(name, studies)
.slice(0, limit)
.map(study => study.title);
export const isVolumeIndicator = (name: string) => ['volume', 'volumes'].includes(toKey(name));
export type ChartTargetResolution = { readonly chartIds: string[] } | { readonly error: string };
/**
* Chart ids are 0-based strings ("0", "1", ...), chart numbers the user says are 1-based.
* No target means the chart the user selected last; "all" means every chart of the current layout.
*/
export const resolveChartTarget = (api: ChartReactAPI, target: ChartTarget | undefined): ChartTargetResolution => {
const layout = api.getMultiChartLayout();
const chartCount = getChartsAmount(layout);
if (target === undefined) {
return { chartIds: [api.getSelectedChartId()] };
}
if (target === 'all') {
return { chartIds: Array.from({ length: chartCount }, (_, index) => String(index)) };
}
if (target > chartCount) {
return { error: `there is no chart ${target} in the ${layout} layout` };
}
return { chartIds: [String(target - 1)] };
};
/** "chart 2" when the layout has several charts, nothing for a single chart. */
export const describeChartIds = (api: ChartReactAPI, chartIds: string[]) => {
if (getChartsAmount(api.getMultiChartLayout()) === 1) {
return '';
}
const numbers = chartIds.map(id => Number(id) + 1);
return numbers.length === 1 ? ` on chart ${numbers[0]}` : ` on charts ${numbers.join(', ')}`;
};

Drawings are placed on the candles of their respective chart:

/**
* Drawings asked for in the chat: what the user asked for, placed where they said, or — for
* whatever they left out — where it fits the chart best: a trend line along the swings it rests
* on, a price line at the level price keeps coming back to, a Fibonacci over the last big swing,
* a box around the range price is stuck in. Pure: candles in, drawings and a sentence on where
* they went out. The page adds the drawings with `ChartReactAPI.addDrawing`.
*/
import { Drawing, DrawingKeyPoint } from '@dx-private/dxchart5-modules/dist/drawings/drawings.config';
import { DrawingType } from '@dx-private/dxchart5-react/dist/chart/model/drawing.model';
export type DrawingKind =
| 'trend_line'
| 'ray'
| 'extended_line'
| 'horizontal_line'
| 'horizontal_ray'
| 'vertical_line'
| 'rectangle'
| 'fib_retracement'
| 'fib_extension'
| 'trend_channel'
| 'price_range'
| 'date_range'
| 'text'
| 'callout'
| 'arrow_up'
| 'arrow_down'
| 'price_label'
| 'arrow'
| 'info_line'
| 'date_price_range'
| 'regression_trend'
| 'volume_profile'
| 'anchored_volume_profile'
| 'long_position'
| 'short_position'
| 'oval'
| 'curve'
| 'arc'
| 'path'
| 'cycle_brackets'
| 'icon'
| 'brush'
| 'highlighter'
| 'pitchfork'
| 'fib_rays'
| 'fib_arcs'
| 'fib_circles'
| 'fib_channel'
| 'fib_time_zones'
| 'fib_time_extension'
| 'fib_time_ratios'
| 'fib_spiral'
| 'gann_square'
| 'gann_box'
| 'gann_fan'
| 'elliott_impulse'
| 'elliott_correction';
interface KindSpec {
readonly type: DrawingType;
/** How many points it takes; 'any' for a path or a stroke, as many as it has. */
readonly points: number | 'any';
readonly name: string;
}
export const DRAWINGS: Record<DrawingKind, KindSpec> = {
trend_line: { type: 'line', points: 2, name: 'trend line' },
ray: { type: 'ray', points: 2, name: 'ray' },
extended_line: { type: 'extended_line', points: 2, name: 'extended line' },
horizontal_line: { type: 'horizontal_line', points: 1, name: 'price line' },
horizontal_ray: { type: 'horizontal_ray', points: 1, name: 'horizontal ray' },
vertical_line: { type: 'vertical_line', points: 1, name: 'time line' },
rectangle: { type: 'rectangle', points: 2, name: 'rectangle' },
fib_retracement: { type: 'fibonacci_retracements', points: 2, name: 'Fib retracement' },
fib_extension: { type: 'fibonacci_projection', points: 3, name: 'Fib extension' },
trend_channel: { type: 'trend_channel', points: 3, name: 'trend channel' },
price_range: { type: 'price_range', points: 2, name: 'price range' },
date_range: { type: 'date_range', points: 2, name: 'date range' },
text: { type: 'text', points: 1, name: 'note' },
callout: { type: 'callout', points: 2, name: 'callout' },
arrow_up: { type: 'vertical_arrow_up', points: 1, name: 'up arrow' },
arrow_down: { type: 'vertical_arrow_down', points: 1, name: 'down arrow' },
price_label: { type: 'price_label', points: 1, name: 'price label' },
arrow: { type: 'arrow', points: 2, name: 'arrow' },
info_line: { type: 'info_line', points: 2, name: 'info line' },
date_price_range: { type: 'date_price_range', points: 2, name: 'date and price range' },
regression_trend: { type: 'regression_trend', points: 2, name: 'regression trend' },
volume_profile: { type: 'range_volume_by_price', points: 2, name: 'volume profile' },
anchored_volume_profile: { type: 'anchored_volume_by_price', points: 1, name: 'anchored volume profile' },
long_position: { type: 'risk_reward_long', points: 4, name: 'long position' },
short_position: { type: 'risk_reward_short', points: 4, name: 'short position' },
oval: { type: 'ellipse', points: 3, name: 'oval' },
curve: { type: 'curve', points: 3, name: 'curve' },
arc: { type: 'arc', points: 3, name: 'arc' },
path: { type: 'path', points: 'any', name: 'path' },
cycle_brackets: { type: 'cycle_brackets', points: 2, name: 'cycle brackets' },
icon: { type: 'icon', points: 1, name: 'icon' },
brush: { type: 'brush', points: 'any', name: 'brush stroke' },
highlighter: { type: 'highlighter', points: 'any', name: 'highlight' },
pitchfork: { type: 'pitchfork', points: 3, name: 'pitchfork' },
fib_rays: { type: 'fibonacci_rays', points: 2, name: 'Fib rays' },
fib_arcs: { type: 'fibonacci_ark', points: 2, name: 'Fib arcs' },
fib_circles: { type: 'fibonacci_circles', points: 2, name: 'Fib circles' },
fib_channel: { type: 'fibonacci_channel', points: 3, name: 'Fib channel' },
fib_time_zones: { type: 'fibonacci_time_zones', points: 2, name: 'Fib time zones' },
fib_time_extension: { type: 'fibonacci_time_extension', points: 3, name: 'Fib time extension' },
fib_time_ratios: { type: 'fibonacci_time_ratios', points: 2, name: 'Fib time ratios' },
fib_spiral: { type: 'fibonacci_spiral', points: 2, name: 'Fib spiral' },
gann_square: { type: 'gann_square', points: 2, name: 'Gann square' },
gann_box: { type: 'gann_box', points: 2, name: 'Gann box' },
gann_fan: { type: 'gann_fan', points: 2, name: 'Gann fan' },
elliott_impulse: { type: 'elliott_wave', points: 6, name: 'Elliott impulse wave' },
elliott_correction: { type: 'elliott_correction_wave', points: 4, name: 'Elliott correction wave' },
};
export const DRAWING_KINDS = Object.keys(DRAWINGS) as DrawingKind[];
/** What a drawing on the chart is called, by its type: "trend line" for `line`. */
export const drawingNameOfType = (type: string) =>
DRAWING_KINDS.map(kind => DRAWINGS[kind]).find(spec => spec.type === type)?.name ?? type.replace(/_/g, ' ');
const toKey = (text: string) => text.toLowerCase().replace(/[^a-z0-9]/g, '');
const DRAWING_ALIASES: Record<string, DrawingKind> = {
line: 'trend_line',
trend: 'trend_line',
priceline: 'horizontal_line',
horizontal: 'horizontal_line',
level: 'horizontal_line',
timeline: 'vertical_line',
vertical: 'vertical_line',
box: 'rectangle',
fib: 'fib_retracement',
fibonacci: 'fib_retracement',
retracement: 'fib_retracement',
fibonacciretracement: 'fib_retracement',
fibprojection: 'fib_extension',
fibonacciextension: 'fib_extension',
fibonacciprojection: 'fib_extension',
channel: 'trend_channel',
parallelchannel: 'trend_channel',
note: 'text',
comment: 'text',
uparrow: 'arrow_up',
downarrow: 'arrow_down',
ellipse: 'oval',
circle: 'oval',
long: 'long_position',
riskreward: 'long_position',
short: 'short_position',
volumebyprice: 'volume_profile',
fixedrangevolumeprofile: 'volume_profile',
elliottwave: 'elliott_impulse',
impulsewave: 'elliott_impulse',
abccorrection: 'elliott_correction',
gann: 'gann_square',
};
/** A drawing kind from what the assistant wrote: "trend_line", "Trend line", "fib", "box". */
export const resolveDrawingKind = (text: string): DrawingKind | undefined => {
const key = toKey(text);
return DRAWING_KINDS.find(kind => toKey(kind) === key) ?? DRAWING_ALIASES[key];
};
/** A stretch of time the user named: a day, a month, a moment; `latest` is the last candle. */
export type TimeAsk = { readonly from: number; readonly to: number } | 'latest';
/** A price the user named, or which price of the candle(s) at the time they named. */
export type PriceAsk = number | 'high' | 'low' | 'open' | 'close';
export interface AskPoint {
readonly time?: TimeAsk;
readonly price?: PriceAsk;
}
/** A position's stop or target: a price, or how far from the entry in percent ("5%"). */
export type PositionLevel = number | { readonly percent: number };
/** What to draw, as the user put it; what they left out is found on the chart. */
export interface DrawingAsk {
readonly kind: DrawingKind;
readonly points: ReadonlyArray<AskPoint>;
/** What it should mark when placed by itself: support below price, resistance above. */
readonly role?: 'support' | 'resistance';
readonly label?: string;
readonly color?: string;
/** A long or short position's stop and target. */
readonly stop?: PositionLevel;
readonly target?: PositionLevel;
/** An icon's name, from the chart's icons (bell, heart, check…). */
readonly icon?: string;
}
/** The candle fields the placing reads. */
export interface DrawingCandle {
readonly timestamp: number;
readonly open: number;
readonly hi: number;
readonly lo: number;
readonly close: number;
}
export interface PlaceOptions {
/** The candles on screen, as indices into the candles; placed by itself, a drawing goes here. */
readonly view?: { readonly from: number; readonly to: number };
readonly formatPrice?: (price: number) => string;
readonly formatTime?: (timestamp: number) => string;
/** Makes the ids; drawings added from the chat all start with CHAT_DRAWING_ID_PREFIX. */
readonly newId?: () => string;
}
export interface DrawingPlan {
/** The drawing, and its label when one was asked for on a kind that can't carry text. */
readonly drawings: Drawing<DrawingType>[];
/** Where it went and why. */
readonly summary: string;
/** What could not be done as asked, and what was done instead. */
readonly notes: string[];
}
export const CHAT_DRAWING_ID_PREFIX = 'chat-';
let made = 0;
const defaultId = () => `${CHAT_DRAWING_ID_PREFIX}${Date.now().toString(36)}-${(made++).toString(36)}`;
const COLORS: Record<string, string> = {
red: 'rgba(242,54,69,1)',
green: 'rgba(38,166,91,1)',
blue: 'rgba(41,98,255,1)',
orange: 'rgba(255,152,0,1)',
yellow: 'rgba(255,214,0,1)',
purple: 'rgba(156,39,176,1)',
pink: 'rgba(233,30,99,1)',
white: 'rgba(255,255,255,1)',
gray: 'rgba(158,158,158,1)',
grey: 'rgba(158,158,158,1)',
black: 'rgba(0,0,0,1)',
};
/** A colour as the chart takes it, from a name or anything CSS-like; undefined when unknown. */
export const drawingColor = (color: string | undefined): string | undefined => {
if (!color) {
return undefined;
}
const c = color.trim().toLowerCase();
return COLORS[c] ?? (/^(#[0-9a-f]{3,8}|rgba?\(.+\))$/.test(c) ? c : undefined);
};
// ============================================================================
// Reading the candles
// ============================================================================
interface Swing {
readonly index: number;
readonly price: number;
readonly high: boolean;
}
/**
* Swing highs and lows: a bar whose high (low) no bar within `w` either side tops (undercuts).
* `provisional` also takes the latest ones, with fewer than `w` bars after them yet — the peak
* price just made is the resistance that matters, even before it is confirmed.
*/
const swingsOf = (
candles: ReadonlyArray<DrawingCandle>,
from: number,
to: number,
w: number,
provisional = false,
): Swing[] => {
const swings: Swing[] = [];
for (let i = from; i <= to; i++) {
let isHigh = true;
let isLow = true;
for (let k = Math.max(from, i - w); k <= Math.min(to, i + w); k++) {
if (k === i) {
continue;
}
isHigh = isHigh && candles[k].hi < candles[i].hi;
isLow = isLow && candles[k].lo > candles[i].lo;
}
// a swing needs bars on both sides, except at the window's start
const roomAfter = i + w <= to || provisional;
if (isHigh && roomAfter) {
swings.push({ index: i, price: candles[i].hi, high: true });
}
if (isLow && roomAfter) {
swings.push({ index: i, price: candles[i].lo, high: false });
}
}
return swings;
};
const averageRange = (candles: ReadonlyArray<DrawingCandle>, from: number, to: number) => {
let sum = 0;
for (let i = from; i <= to; i++) {
sum += candles[i].hi - candles[i].lo;
}
return sum / Math.max(1, to - from + 1);
};
/** Up when closes rise across the window (least squares), down otherwise. */
const trendOf = (candles: ReadonlyArray<DrawingCandle>, from: number, to: number): 'up' | 'down' => {
const n = to - from + 1;
let sx = 0;
let sy = 0;
let sxy = 0;
let sxx = 0;
for (let i = 0; i < n; i++) {
const y = candles[from + i].close;
sx += i;
sy += y;
sxy += i * y;
sxx += i * i;
}
const slope = (n * sxy - sx * sy) / Math.max(1, n * sxx - sx * sx);
return slope >= 0 ? 'up' : 'down';
};
const point = (candles: ReadonlyArray<DrawingCandle>, index: number, value: number): DrawingKeyPoint => ({
timestamp: candles[index].timestamp,
value,
});
interface Line {
readonly a: Swing;
readonly b: Swing;
readonly touches: number;
}
const lineAt = (line: { a: Swing; b: Swing }, index: number) =>
line.a.price + ((line.b.price - line.a.price) * (index - line.a.index)) / (line.b.index - line.a.index);
/**
* The trend line price rests on now: through two swing lows (support) or highs (resistance),
* the one the most swings touch and the fewest bars cross from its first point to the latest
* bar, that is still near price at the latest bar; the more recent and the longer, the better.
* A line far from today's price — the floor of a range price long since left — is history.
*/
const restingLine = (
candles: ReadonlyArray<DrawingCandle>,
from: number,
to: number,
support: boolean,
swings: ReadonlyArray<Swing>,
): Line | undefined => {
const side = swings.filter(s => s.high !== support);
const avg = averageRange(candles, from, to);
const tol = avg * 0.25;
const span = to - from + 1;
let best: { line: Line; score: number } | undefined;
for (let j = side.length - 1; j >= 1; j--) {
for (let i = 0; i < j; i++) {
const line = { a: side[i], b: side[j] };
let crossed = 0;
for (let k = line.a.index; k <= to; k++) {
const at = lineAt(line, k);
crossed += (support ? candles[k].lo < at - tol : candles[k].hi > at + tol) ? 1 : 0;
}
const touches = side.filter(
s => s.index >= line.a.index && Math.abs(s.price - lineAt(line, s.index)) <= tol,
).length;
// how far the line ends from the latest close, in average candles
const away = Math.min(20, Math.abs(candles[to].close - lineAt(line, to)) / avg);
const score =
touches * 6 +
((line.b.index - line.a.index) / span) * 6 +
((line.b.index - from) / span) * 6 -
crossed * 4 -
away * 1.2;
if (!best || score > best.score) {
best = { line: { ...line, touches }, score };
}
}
}
return best?.line;
};
/** The last big swing on screen: from the extreme before the latest one to the latest one. */
const lastSwing = (candles: ReadonlyArray<DrawingCandle>, from: number, to: number) => {
let hiIdx = from;
let loIdx = from;
for (let i = from; i <= to; i++) {
hiIdx = candles[i].hi > candles[hiIdx].hi ? i : hiIdx;
loIdx = candles[i].lo < candles[loIdx].lo ? i : loIdx;
}
const up = hiIdx > loIdx;
return up
? { start: { index: loIdx, price: candles[loIdx].lo }, end: { index: hiIdx, price: candles[hiIdx].hi }, up }
: { start: { index: hiIdx, price: candles[hiIdx].hi }, end: { index: loIdx, price: candles[loIdx].lo }, up };
};
/** The latest stretch price has been boxed in: grown back from the last bar while the range stays tight. */
const recentRange = (candles: ReadonlyArray<DrawingCandle>, from: number, to: number) => {
const limit = averageRange(candles, from, to) * 4;
let hi = candles[to].hi;
let lo = candles[to].lo;
let start = to;
for (let i = to - 1; i >= Math.max(from, to - 80); i--) {
const nextHi = Math.max(hi, candles[i].hi);
const nextLo = Math.min(lo, candles[i].lo);
if (nextHi - nextLo > limit && to - i >= 8) {
break;
}
hi = nextHi;
lo = nextLo;
start = i;
}
if (to - start < 7) {
start = Math.max(from, to - 19);
hi = Math.max(...candles.slice(start, to + 1).map(c => c.hi));
lo = Math.min(...candles.slice(start, to + 1).map(c => c.lo));
}
return { start, end: to, hi, lo };
};
interface Level {
readonly kind: 'support' | 'resistance';
readonly price: number;
readonly since: number;
readonly touches: number;
}
/**
* The levels price keeps coming back to: swing highs and lows within a zone's width of each
* other, touched three times, or twice when price came back from the other side (a high there,
* then a low, or the reverse); each support or resistance by where it sits against the latest close.
*/
const levelsOf = (
candles: ReadonlyArray<DrawingCandle>,
from: number,
to: number,
swings: ReadonlyArray<Swing>,
): Level[] => {
const close = candles[to].close;
const halfWidth = Math.max(averageRange(candles, from, to) * 0.5, close * 0.0015);
const clusters: Swing[][] = [];
for (const s of [...swings].sort((a, b) => a.price - b.price)) {
const current = clusters[clusters.length - 1];
if (current && s.price - current[0].price <= 2 * halfWidth) {
current.push(s);
} else {
clusters.push([s]);
}
}
return clusters
.filter(cluster => {
const flipped = cluster.some(s => s.high) && cluster.some(s => !s.high);
return cluster.length >= (flipped ? 2 : 3);
})
.map(cluster => {
const prices = cluster.map(s => s.price);
const price = (Math.min(...prices) + Math.max(...prices)) / 2;
return {
kind: price <= close ? 'support' : 'resistance',
price,
since: candles[Math.min(...cluster.map(s => s.index))].timestamp,
touches: cluster.length,
};
});
};
/** The support or resistance level nearest the latest close. */
const nearestLevel = (
candles: ReadonlyArray<DrawingCandle>,
from: number,
to: number,
role: 'support' | 'resistance' | undefined,
swings: ReadonlyArray<Swing>,
) => {
const close = candles[to].close;
const levels = levelsOf(candles, from, to, swings).filter(level => role === undefined || level.kind === role);
levels.sort((a, b) => Math.abs(a.price - close) - Math.abs(b.price - close));
return levels[0];
};
/** Highs and lows taking turns: of two in a row on one side, the more extreme stays. */
const zigzag = (swings: ReadonlyArray<Swing>): Swing[] => {
const out: Swing[] = [];
for (const s of [...swings].sort((a, b) => a.index - b.index)) {
const prev = out[out.length - 1];
if (prev && prev.high === s.high) {
if (s.high ? s.price > prev.price : s.price < prev.price) {
out[out.length - 1] = s;
}
} else if (!prev || prev.index !== s.index) {
out.push(s);
}
}
return out;
};
/** The latest `count` turns of the zigzag that end on a high (or a low); undefined with too few. */
const lastTurns = (turns: ReadonlyArray<Swing>, count: number, endsHigh?: boolean): Swing[] | undefined => {
for (let j = turns.length - 1; j >= count - 1; j--) {
if (endsHigh === undefined || turns[j].high === endsHigh) {
return turns.slice(j - count + 1, j + 1);
}
}
return undefined;
};
/** With too few clear swings: `count` points spread over the candles on screen, taking turns at highs and lows. */
const spreadTurns = (
candles: ReadonlyArray<DrawingCandle>,
from: number,
to: number,
count: number,
endsHigh: boolean,
): Swing[] =>
Array.from({ length: count }, (_, i) => {
const index = Math.round(from + ((to - from) * i) / Math.max(1, count - 1));
const high = (count - 1 - i) % 2 === 0 ? endsHigh : !endsHigh;
return { index, price: high ? candles[index].hi : candles[index].lo, high };
});
// ============================================================================
// Reading what the user said
// ============================================================================
/** The candles at a time the user named, or the nearest one before it; undefined before the history. */
const candlesAt = (candles: ReadonlyArray<DrawingCandle>, time: TimeAsk): { from: number; to: number } | undefined => {
const last = candles.length - 1;
if (time === 'latest') {
return { from: last, to: last };
}
let from = -1;
let to = -1;
for (let i = 0; i <= last; i++) {
if (candles[i].timestamp >= time.from && candles[i].timestamp < time.to) {
from = from < 0 ? i : from;
to = i;
}
}
if (from >= 0) {
return { from, to };
}
// a weekend, a holiday, the future: the nearest candle before it
for (let i = last; i >= 0; i--) {
if (candles[i].timestamp < time.from) {
return { from: i, to: i };
}
}
return undefined;
};
const extremeIn = (candles: ReadonlyArray<DrawingCandle>, span: { from: number; to: number }, high: boolean) => {
let at = span.from;
for (let i = span.from; i <= span.to; i++) {
at = (high ? candles[i].hi > candles[at].hi : candles[i].lo < candles[at].lo) ? i : at;
}
return { index: at, price: high ? candles[at].hi : candles[at].lo };
};
/** Where a point the user named lands: on its candle, at the price they named or the one asked of that candle. */
const resolvePoint = (
candles: ReadonlyArray<DrawingCandle>,
ask: AskPoint,
fallback: DrawingKeyPoint,
otherwise: 'high' | 'low' | 'close',
notes: string[],
formatTime: (ts: number) => string,
): DrawingKeyPoint => {
if (!ask.time) {
return typeof ask.price === 'number' ? { timestamp: fallback.timestamp, value: ask.price } : fallback;
}
const span = candlesAt(candles, ask.time);
if (!span) {
notes.push(
`That time is before the loaded history, which starts ${formatTime(candles[0].timestamp)}; I used the first candle.`,
);
}
const at = span ?? { from: 0, to: 0 };
const wanted = ask.price ?? otherwise;
if (typeof wanted === 'number') {
return { timestamp: candles[at.from].timestamp, value: wanted };
}
if (wanted === 'high' || wanted === 'low') {
const e = extremeIn(candles, at, wanted === 'high');
return point(candles, e.index, e.price);
}
return wanted === 'open'
? point(candles, at.from, candles[at.from].open)
: point(candles, at.to, candles[at.to].close);
};
// ============================================================================
// Placing
// ============================================================================
interface Auto {
readonly points: DrawingKeyPoint[];
readonly why: string;
/** For points the user gives a time but no price: which price of the candle. */
readonly priceAt: 'high' | 'low' | 'close';
}
const autoPlace = (
ask: DrawingAsk,
candles: ReadonlyArray<DrawingCandle>,
from: number,
to: number,
fmtP: (p: number) => string,
fmtT: (ts: number) => string,
): Auto => {
const last = to;
const avg = averageRange(candles, from, to);
const latestClose = candles[last].close;
const w = Math.max(2, Math.min(8, Math.round((to - from + 1) / 30)));
const swings = swingsOf(candles, from, to, w);
const latestSwings = swingsOf(candles, from, to, w, true);
const trend = trendOf(candles, from, to);
const support = ask.role ? ask.role === 'support' : trend === 'up';
switch (ask.kind) {
case 'trend_line':
case 'ray':
case 'extended_line':
case 'trend_channel':
case 'fib_channel': {
const channel = ask.kind === 'trend_channel' || ask.kind === 'fib_channel';
const line = restingLine(candles, from, to, support, swings);
if (!line) {
const s = lastSwing(candles, from, to);
const ends = [point(candles, s.start.index, s.start.price), point(candles, s.end.index, s.end.price)];
return {
points: channel ? [...ends, point(candles, last, latestClose)] : ends,
why: `along the last swing, ${fmtP(s.start.price)} to ${fmtP(s.end.price)}`,
priceAt: support ? 'low' : 'high',
};
}
const pts = [point(candles, line.a.index, line.a.price), point(candles, line.b.index, line.b.price)];
const rising = line.b.price >= line.a.price;
const what = `${rising ? 'rising' : 'falling'} swing ${support ? 'lows' : 'highs'}`;
const where = `from ${fmtP(line.a.price)} on ${fmtT(pts[0].timestamp)} to ${fmtP(line.b.price)} on ${fmtT(pts[1].timestamp)}`;
const touches = line.touches > 2 ? ` (${line.touches} touches)` : '';
if (!channel) {
return { points: pts, why: `along the ${what}, ${where}${touches}`, priceAt: support ? 'low' : 'high' };
}
// the other side runs through the farthest bar from the base line since its start
let far = line.a.index;
let farBy = -Infinity;
for (let k = line.a.index; k <= to; k++) {
const by = support ? candles[k].hi - lineAt(line, k) : lineAt(line, k) - candles[k].lo;
if (by > farBy) {
farBy = by;
far = k;
}
}
return {
points: [...pts, point(candles, far, support ? candles[far].hi : candles[far].lo)],
why: `on the ${what}, ${where}, with its other side through ${fmtP(support ? candles[far].hi : candles[far].lo)} on ${fmtT(candles[far].timestamp)}`,
priceAt: support ? 'low' : 'high',
};
}
case 'horizontal_line':
case 'horizontal_ray':
case 'price_label': {
if (ask.kind === 'price_label' && !ask.role) {
return {
points: [point(candles, last, latestClose)],
why: `at the latest close, ${fmtP(latestClose)}`,
priceAt: 'close',
};
}
const level = nearestLevel(candles, from, to, ask.role, swings);
if (level) {
const at = candles.findIndex(c => c.timestamp >= level.since);
return {
points: [point(candles, ask.kind === 'horizontal_ray' ? Math.max(0, at) : last, level.price)],
why: `at ${fmtP(level.price)}, the ${level.kind} price has come back to ${level.touches} times since ${fmtT(level.since)}`,
priceAt: 'close',
};
}
// no level found: the nearest swing on the side asked for, clear of the price itself
const gap = avg * 0.3;
const side = latestSwings.filter(s =>
ask.role === 'support'
? !s.high && s.price <= latestClose - gap
: ask.role === 'resistance'
? s.high && s.price >= latestClose + gap
: true,
);
side.sort((a, b) => Math.abs(a.price - latestClose) - Math.abs(b.price - latestClose));
const s = side[0];
return s
? {
points: [point(candles, ask.kind === 'horizontal_ray' ? s.index : last, s.price)],
why: `at ${fmtP(s.price)}, the nearest swing ${s.high ? 'high' : 'low'} (${fmtT(candles[s.index].timestamp)})`,
priceAt: 'close',
}
: {
points: [point(candles, last, latestClose)],
why: `at the latest close, ${fmtP(latestClose)}`,
priceAt: 'close',
};
}
case 'vertical_line':
return {
points: [point(candles, last, latestClose)],
why: `at the latest candle, ${fmtT(candles[last].timestamp)}`,
priceAt: 'close',
};
case 'rectangle': {
const r = recentRange(candles, from, to);
return {
points: [point(candles, r.start, r.hi), point(candles, r.end, r.lo)],
why: `around the range of the last ${r.end - r.start + 1} candles, ${fmtP(r.lo)}–${fmtP(r.hi)}`,
priceAt: 'high',
};
}
case 'fib_retracement':
case 'price_range':
case 'date_range':
case 'date_price_range':
case 'info_line':
case 'arrow':
case 'fib_rays':
case 'fib_arcs':
case 'fib_circles':
case 'fib_spiral':
case 'fib_time_zones':
case 'fib_time_ratios':
case 'gann_square':
case 'gann_box':
case 'gann_fan':
case 'fib_extension': {
const s = lastSwing(candles, from, to);
const pts = [point(candles, s.start.index, s.start.price), point(candles, s.end.index, s.end.price)];
const why = `over the last ${s.up ? 'rise' : 'drop'}, ${fmtP(s.start.price)} on ${fmtT(pts[0].timestamp)} to ${fmtP(s.end.price)} on ${fmtT(pts[1].timestamp)}`;
if (ask.kind !== 'fib_extension') {
return { points: pts, why, priceAt: 'close' };
}
// the pullback since: its extreme against the swing, or the latest close
const after = s.end.index < to ? extremeIn(candles, { from: s.end.index + 1, to }, !s.up) : undefined;
const c = after ? point(candles, after.index, after.price) : point(candles, last, latestClose);
return { points: [...pts, c], why: `${why}, from the pullback to ${fmtP(c.value)}`, priceAt: 'close' };
}
case 'text':
return {
points: [point(candles, last, candles[last].hi + avg * 1.5)],
why: 'above the latest candle',
priceAt: 'high',
};
case 'callout': {
const at = Math.max(from, last - Math.max(3, Math.round((to - from) / 8)));
return {
points: [point(candles, last, candles[last].hi), point(candles, at, candles[last].hi + avg * 3)],
why: 'pointing at the latest candle',
priceAt: 'high',
};
}
case 'arrow_up':
case 'arrow_down': {
const up = ask.kind === 'arrow_up';
const s = [...latestSwings].reverse().find(x => x.high !== up);
const index = s?.index ?? last;
return {
points: [point(candles, index, up ? candles[index].lo - avg * 0.3 : candles[index].hi + avg * 0.3)],
why: s
? `at the last swing ${up ? 'low' : 'high'}, ${fmtP(s.price)} on ${fmtT(candles[index].timestamp)}`
: 'at the latest candle',
priceAt: up ? 'low' : 'high',
};
}
case 'regression_trend': {
const s = lastSwing(candles, from, to);
return {
points: [point(candles, s.start.index, s.start.price), point(candles, last, latestClose)],
why: `over the move since the ${s.up ? 'low' : 'high'} on ${fmtT(candles[s.start.index].timestamp)}, ${to - s.start.index + 1} candles`,
priceAt: 'close',
};
}
case 'volume_profile':
case 'oval': {
const r = recentRange(candles, from, to);
const why = `${ask.kind === 'oval' ? 'around' : 'over'} the range of the last ${r.end - r.start + 1} candles, ${fmtP(r.lo)}–${fmtP(r.hi)}`;
if (ask.kind === 'volume_profile') {
return { points: [point(candles, r.start, r.hi), point(candles, r.end, r.lo)], why, priceAt: 'high' };
}
// an oval is drawn on its long axis (the first two points) and reaches out to the third
const mid = (r.hi + r.lo) / 2;
return {
points: [
point(candles, r.start, mid),
point(candles, r.end, mid),
point(candles, Math.round((r.start + r.end) / 2), r.hi),
],
why,
priceAt: 'close',
};
}
case 'anchored_volume_profile': {
const s = lastSwing(candles, from, to);
return {
points: [point(candles, s.start.index, s.start.price)],
why: `anchored at the start of the last ${s.up ? 'rise' : 'drop'}, ${fmtP(s.start.price)} on ${fmtT(candles[s.start.index].timestamp)}`,
priceAt: s.up ? 'low' : 'high',
};
}
case 'long_position':
case 'short_position': {
const long = ask.kind === 'long_position';
const gap = avg * 0.3;
// the stop goes just beyond the latest swing against the trade, clear of the entry
const guard = [...latestSwings]
.reverse()
.find(x => (long ? !x.high && x.price < latestClose - gap : x.high && x.price > latestClose + gap));
const stop = guard ? guard.price + (long ? -1 : 1) * avg * 0.2 : latestClose + (long ? -2 : 2) * avg;
const target = latestClose + (latestClose - stop) * 2;
const period = (candles[to].timestamp - candles[from].timestamp) / Math.max(1, to - from);
const end = candles[last].timestamp + Math.max(5, Math.round((to - from) * 0.2)) * period;
return {
points: [
point(candles, last, latestClose),
point(candles, last, target),
point(candles, last, stop),
{ timestamp: end, value: latestClose },
],
why: guard
? `the stop just beyond the last swing ${long ? 'low' : 'high'} (${fmtT(candles[guard.index].timestamp)})`
: 'the stop two candles’ range away',
priceAt: 'close',
};
}
case 'curve':
case 'arc':
case 'pitchfork':
case 'fib_time_extension': {
const turns = lastTurns(zigzag(latestSwings), 3) ?? spreadTurns(candles, from, to, 3, trend === 'up');
const [a, b, c] = turns;
const why = `through the last three swings: ${fmtP(a.price)} on ${fmtT(candles[a.index].timestamp)}, ${fmtP(b.price)} on ${fmtT(candles[b.index].timestamp)} and ${fmtP(c.price)} on ${fmtT(candles[c.index].timestamp)}`;
if (ask.kind === 'arc') {
// the arc spans the outer two and rises to the middle one
return {
points: [
point(candles, a.index, a.price),
point(candles, c.index, c.price),
point(candles, b.index, b.price),
],
why,
priceAt: 'close',
};
}
if (ask.kind === 'curve') {
// a curve bends towards its third point; for it to pass through the middle swing,
// that point sits twice as far out from the chord's middle
const control = Math.max(from, Math.min(to, Math.round(2 * b.index - (a.index + c.index) / 2)));
return {
points: [
point(candles, a.index, a.price),
point(candles, c.index, c.price),
point(candles, control, 2 * b.price - (a.price + c.price) / 2),
],
why,
priceAt: 'close',
};
}
return { points: turns.map(t => point(candles, t.index, t.price)), why, priceAt: 'close' };
}
case 'elliott_impulse':
case 'elliott_correction': {
const impulse = ask.kind === 'elliott_impulse';
const count = impulse ? 6 : 4;
// an impulse ends with the trend, a correction against it
const endsHigh = impulse === (trend === 'up');
const turns =
lastTurns(zigzag(latestSwings), count, endsHigh) ?? spreadTurns(candles, from, to, count, endsHigh);
const first = turns[0];
const end = turns[turns.length - 1];
return {
points: turns.map(t => point(candles, t.index, t.price)),
why: `on the last ${count} swings, from ${fmtP(first.price)} on ${fmtT(candles[first.index].timestamp)} to ${fmtP(end.price)} on ${fmtT(candles[end.index].timestamp)}`,
priceAt: 'close',
};
}
case 'cycle_brackets': {
const lows = zigzag(latestSwings).filter(x => x.high !== support);
const pair = lows.length >= 2 ? lows.slice(-2) : spreadTurns(candles, from, to, 2, !support);
return {
points: pair.map(t => point(candles, t.index, t.price)),
why: `one cycle, from the swing ${support ? 'low' : 'high'} on ${fmtT(candles[pair[0].index].timestamp)} to the next on ${fmtT(candles[pair[1].index].timestamp)}`,
priceAt: support ? 'low' : 'high',
};
}
case 'path': {
const turns = zigzag(latestSwings).slice(-6);
const pts = turns.length >= 2 ? turns : spreadTurns(candles, from, to, 4, trend === 'up');
return {
points: pts.map(t => point(candles, t.index, t.price)),
why: `through the last ${pts.length} swings`,
priceAt: 'close',
};
}
case 'brush':
case 'highlighter': {
const s = lastSwing(candles, from, to);
const step = Math.max(1, Math.ceil((to - s.start.index + 1) / 60));
const pts: DrawingKeyPoint[] = [];
for (let i = s.start.index; i <= to; i += step) {
pts.push(point(candles, i, candles[i].close));
}
if (pts[pts.length - 1].timestamp !== candles[to].timestamp) {
pts.push(point(candles, to, latestClose));
}
return {
points: pts,
why: `along the price since ${fmtT(candles[s.start.index].timestamp)}`,
priceAt: 'close',
};
}
case 'icon':
return {
points: [point(candles, last, candles[last].hi + avg * 1.5)],
why: 'above the latest candle',
priceAt: 'high',
};
}
};
const propertiesOf = (kind: DrawingKind, color: string | undefined, label: string | undefined): object => {
const text = label !== undefined && (kind === 'text' || kind === 'callout') ? { textValue: label } : {};
if (!color) {
return text;
}
if (kind === 'text' || kind === 'callout' || kind === 'price_label') {
return { ...text, text: { textBg: color, bgBorder: color } };
}
if (kind === 'rectangle') {
return { line: { lineColor: color }, background: { fillStyle: color } };
}
if (kind === 'icon') {
return { iconStyle: { fillStyle: color } };
}
return { line: { lineColor: color } };
};
/** The chart's icons, by name; an icon asked for by another name gets the bell. */
export const ICON_NAMES = [
'bell',
'heart',
'check',
'check-circle',
'thumbs-up',
'thumbs-down',
'arrow-up',
'arrow-down',
'arrow-left',
'arrow-right',
'dollar-sign',
'euro-sign',
'pound-sign',
'coins',
'money-bill',
'wallet',
'briefcase',
'calendar-alt',
'hourglass',
'eye',
'search',
'comment',
'lock',
'lock-open',
'anchor',
'compass',
'flask',
'coffee',
'handshake',
'infinity',
'percent',
'plus',
'minus',
'level-up-alt',
'level-down-alt',
'camera',
'phone',
'envelope',
] as const;
const ICON_WORDS: Record<string, string> = {
tick: 'check',
checkmark: 'check',
like: 'thumbs-up',
dislike: 'thumbs-down',
dollar: 'dollar-sign',
euro: 'euro-sign',
pound: 'pound-sign',
money: 'money-bill',
calendar: 'calendar-alt',
clock: 'hourglass',
timer: 'hourglass',
chat: 'comment',
message: 'comment',
alarm: 'bell',
love: 'heart',
};
export const iconName = (name: string | undefined): string => {
const n = (name ?? '').trim().toLowerCase().replace(/\s+/g, '-');
return (ICON_NAMES as ReadonlyArray<string>).includes(n) ? n : (ICON_WORDS[n] ?? 'bell');
};
/**
* A long or short position's points — entry, target, stop, and where its box ends — from the
* entry the user named (or the latest close), the stop and target they named or found.
*/
const positionPoints = (
ask: DrawingAsk,
resolved: ReadonlyArray<DrawingKeyPoint>,
auto: Auto,
candles: ReadonlyArray<DrawingCandle>,
from: number,
to: number,
notes: string[],
): DrawingKeyPoint[] => {
const long = ask.kind === 'long_position';
const entry = resolved[0];
const avg = averageRange(candles, from, to);
// a percent is a distance from the entry: against the trade for the stop, with it for the target
const priceOf = (level: PositionLevel | undefined, towardsProfit: boolean) =>
level === undefined || typeof level === 'number'
? level
: entry.value * (1 + ((long === towardsProfit ? 1 : -1) * Math.abs(level.percent)) / 100);
const onSide = (stop: number) => (long ? stop < entry.value : stop > entry.value);
const found = auto.points[2].value;
let stop = priceOf(ask.stop, false) ?? (onSide(found) ? found : entry.value + (long ? -2 : 2) * avg);
if (!onSide(stop)) {
notes.push(
`A ${long ? 'long' : 'short'} position's stop goes ${long ? 'below' : 'above'} the entry, so I put it there.`,
);
stop = entry.value + (long ? -2 : 2) * avg;
}
let target = priceOf(ask.target, true) ?? entry.value + (entry.value - stop) * 2;
if (onSide(target) || target === entry.value) {
notes.push(
`A ${long ? 'long' : 'short'} position's target goes ${long ? 'above' : 'below'} the entry, so I put it at twice the risk.`,
);
target = entry.value + (entry.value - stop) * 2;
}
// the box runs as far past the entry as the one found runs past the latest candle
const end = entry.timestamp + (auto.points[3].timestamp - candles[to].timestamp);
return [
entry,
{ timestamp: entry.timestamp, value: target },
{ timestamp: entry.timestamp, value: stop },
{ timestamp: end, value: entry.value },
];
};
const describePosition = (long: boolean, points: ReadonlyArray<DrawingKeyPoint>, fmtP: (p: number) => string) => {
const [entry, target, stop] = points.map(p => p.value);
const ratio = Math.abs(target - entry) / Math.max(1e-9, Math.abs(entry - stop));
return `with entry ${fmtP(entry)}, stop ${fmtP(stop)} and target ${fmtP(target)} (${ratio.toFixed(1)} to 1)`;
};
const namesAPlace = (ask: DrawingAsk) => ask.points.some(p => p.time !== undefined || p.price !== undefined);
const withArticle = (name: string) => `${/^[aeiou]/i.test(name) ? 'an' : 'a'} ${name}`;
/**
* The drawing to put on the chart for what the user asked: every point they named where they
* named it, the rest where it fits the chart best (within the candles on screen), with a
* sentence on where it went. A label on a kind that can't carry text comes as a note next to
* it. Undefined with no candles.
*/
export const planDrawing = (
ask: DrawingAsk,
candles: ReadonlyArray<DrawingCandle>,
options: PlaceOptions = {},
): DrawingPlan | undefined => {
if (candles.length === 0) {
return undefined;
}
const fmtP = options.formatPrice ?? ((p: number) => p.toFixed(2));
const fmtT = options.formatTime ?? ((ts: number) => new Date(ts).toISOString().slice(0, 10));
const newId = options.newId ?? defaultId;
const lastIndex = candles.length - 1;
// at least 30 candles to read, or there is nothing to fit to
const to = Math.min(lastIndex, Math.max(0, options.view?.to ?? lastIndex));
const from = Math.max(0, Math.min(options.view?.from ?? to - 149, to - 29));
const spec = DRAWINGS[ask.kind];
const notes: string[] = [];
const auto = autoPlace(ask, candles, from, to, fmtP, fmtT);
// a path or a stroke takes as many points as the user named, at least two, or those found
const count =
spec.points === 'any' ? (ask.points.length >= 2 ? ask.points.length : auto.points.length) : spec.points;
const resolved = Array.from({ length: count }, (_, i) => {
const fallback = auto.points[Math.min(i, auto.points.length - 1)];
return ask.points[i] ? resolvePoint(candles, ask.points[i], fallback, auto.priceAt, notes, fmtT) : fallback;
});
const position = ask.kind === 'long_position' || ask.kind === 'short_position';
const keyPoints = position ? positionPoints(ask, resolved, auto, candles, from, to, notes) : resolved;
const flat = ask.kind === 'horizontal_line' || ask.kind === 'horizontal_ray';
const at = keyPoints.map(p => (flat ? fmtP(p.value) : `${fmtP(p.value)} on ${fmtT(p.timestamp)}`));
const placed = position
? describePosition(ask.kind === 'long_position', keyPoints, fmtP)
: at.length === 1
? `at ${at[0]}`
: at.length === 2
? `from ${at[0]} to ${at[1]}`
: spec.points === 'any'
? `through ${at.length} points, from ${at[0]} to ${at[at.length - 1]}`
: `through ${at.slice(0, -1).join(', ')} and ${at[at.length - 1]}`;
const color = drawingColor(ask.color);
if (ask.color && !color) {
notes.push(`I don't know the colour "${ask.color}", so it has the usual one.`);
}
const main: Drawing<DrawingType> = {
id: newId(),
type: spec.type,
keyPoints,
properties: {
...propertiesOf(
ask.kind,
color,
ask.kind === 'text' || ask.kind === 'callout' ? (ask.label ?? 'Note') : undefined,
),
// a trend line found on the chart runs on to today, where it matters
...(ask.kind === 'trend_line' && !namesAPlace(ask) ? { style: { extendRight: true } } : {}),
// the icon's picture is filled in from the chart's icons by name
...(ask.kind === 'icon' ? { icon: { name: iconName(ask.icon) } } : {}),
} as never,
visible: true,
locked: false,
};
const drawings: Drawing<DrawingType>[] = [main];
if (ask.label && ask.kind !== 'text' && ask.kind !== 'callout') {
// a line or box carries no text: the label goes just above its latest point, and far
// enough left of the latest candle that the text, which runs right, isn't cut off
const end = keyPoints.reduce((a, b) => (b.timestamp >= a.timestamp ? b : a));
const avg = averageRange(candles, from, to);
const endIndex = Math.max(
0,
candles.findIndex(c => c.timestamp >= end.timestamp),
);
const labelIndex = Math.max(from, Math.min(endIndex, to - Math.round((to - from) * 0.18)));
drawings.push({
id: `${main.id}-label`,
type: 'text',
keyPoints: [{ timestamp: candles[labelIndex].timestamp, value: end.value + avg * 0.8 }],
properties: propertiesOf('text', color, ask.label) as never,
visible: true,
locked: false,
});
}
const what =
ask.kind === 'text' || ask.kind === 'callout'
? `Added ${withArticle(spec.name)} "${ask.label ?? 'Note'}"`
: `Drew ${withArticle(spec.name)}`;
const labelled = ask.label && ask.kind !== 'text' && ask.kind !== 'callout' ? `, labelled "${ask.label}"` : '';
const where = position
? `${placed}${namesAPlace(ask) || ask.stop !== undefined ? '' : `, ${auto.why}`}`
: namesAPlace(ask)
? placed
: auto.why;
const summary = `${what} ${where}${labelled}.`;
return { drawings, summary, notes };
};
// ============================================================================
// Times and prices the way the assistant writes them
// ============================================================================
const DAY = 86_400_000;
/**
* A time as the assistant writes it — "2026-03-12", "2026-03-12 14:30", "2026-03" for the month,
* "2026" for the year, "latest" (or now/today/last) for the latest candle — as a stretch of
* time (UTC). Undefined when it can't be read.
*/
export const parseTimeAsk = (text: string | undefined): TimeAsk | undefined => {
const s = (text ?? '').trim().toLowerCase();
if (!s) {
return undefined;
}
if (/^(latest|now|today|last|current|last candle|latest candle)$/.test(s)) {
return 'latest';
}
let m = /^(\d{4})-(\d{1,2})-(\d{1,2})[ t](\d{1,2}):(\d{2})/.exec(s);
if (m) {
const at = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5]);
return { from: at, to: at + 60_000 };
}
m = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(s);
if (m) {
const at = Date.UTC(+m[1], +m[2] - 1, +m[3]);
return { from: at, to: at + DAY };
}
m = /^(\d{4})-(\d{1,2})$/.exec(s);
if (m) {
return { from: Date.UTC(+m[1], +m[2] - 1, 1), to: Date.UTC(+m[1], +m[2], 1) };
}
m = /^(\d{4})$/.exec(s);
if (m) {
return { from: Date.UTC(+m[1], 0, 1), to: Date.UTC(+m[1] + 1, 0, 1) };
}
return undefined;
};
/** A price as the assistant writes it: a number ("$1,250.5" too), or high/low/open/close of the candle. */
export const parsePriceAsk = (text: string | undefined): PriceAsk | undefined => {
const s = (text ?? '').trim().toLowerCase();
if (s === 'high' || s === 'low' || s === 'open' || s === 'close') {
return s;
}
// "5%" is not the price 5
if (s.includes('%') || s.includes('percent')) {
return undefined;
}
const n = parseFloat(s.replace(/[$,\s]/g, ''));
return s !== '' && Number.isFinite(n) ? n : undefined;
};
/** A position's stop or target as the assistant writes it: a price, or a percent of the entry ("5%", "-5%"). */
export const parsePositionLevel = (text: string | undefined): PositionLevel | undefined => {
const s = (text ?? '').trim().toLowerCase();
const percent = /^[-+]?\s*(\d+(?:\.\d+)?)\s*(?:%|percent)$/.exec(s);
if (percent) {
return { percent: parseFloat(percent[1]) };
}
const price = parsePriceAsk(s);
return typeof price === 'number' ? price : undefined;
};

Notes on the API calls:

  • setStudiesByIds resets the settings of the indicators that are already on the chart. To add or remove one indicator, read the current list with getChartInfo(chartId).studies and pass the new list to setStudies.
  • There is no separate method to change the multi-chart layout. syncLayoutParts with { multiChartLayout: true } applies the grid of a layout object, so the example generates the current layout with generateLayout and changes its grid.
  • The charts added by a bigger layout are created asynchronously. Wait until getChartInfo(chartId).chart is available before you send commands to them. After a symbol or timeframe change, wait for the new candles before you place a drawing.
  • With drawing sync on, addDrawing marks a drawing as synced by default, and removeDrawing on a chart that is not selected does not remove it from the synced drawings, so it comes back on the other charts and after a reload. Add the drawings from the chat with synced: false. See Custom Drawings for addDrawing.
  • To accept company names and exchange-specific symbols, pass searchSymbol and look the symbol up with your Symbol Suggest Provider.

Add to Chart​

Under a code block in a reply, the widget shows Add to Chart. A click sends the text of the block to the page in a customizeChart event. The assistant uses it for custom indicators written in JavaScript: parseChartCommands returns null for those, so handle them as described in Custom Studies. A block of chart commands is parsed and applied the same way as a chartCommands event.

Step 4. Put it together​

import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import {
DevexaWidgetPlatformConstructorParameters,
DevexaWidgetPlatformInterface,
DevexaWidgetPlatformState,
WidgetEvent,
} from '@dx-private/devexa-widget-platform';
import { ChartReactApp } from '@dx-private/dxchart5-react/dist/chart/chart-react-app';
import { fromRawStudiesSettings } from '@dx-private/dxchart5-react/dist/chart/model/studies.model';
import { addCustomToolbarButtons } from '@dx-private/dxchart5-react/dist/chart/ui-overrides/toolbar';
import { ChartReactAPI } from '@dx-private/dxchart5-react/dist/chart/view-models/api/chart-react-api.view-model';
import { DEFAULT_LOCALIZATION } from '@dx-private/dxchart5-react/dist/config/localization/localization';
import { DEFAULT_STUDIES_LIST } from '@dx-private/dxchart5-react/dist/config/studies-list';
import { createDxStudiesProvider } from '@dx-private/dxchart5-react/dist/providers/studies/dx-studies-provider';
import { CREATE_MOCK_PROVIDERS } from '@dx-private/dxchart5-react-mock-providers/dist';
import { parseChartCommandList, parseChartCommands } from './chart-commands';
import { ChartCommandReport } from './chart-command-executor';
import { DevexaChartControl, applyDevexaChartCommands, getDevexaChartContext } from './devexa-chart-control';
declare global {
interface Window {
DevexaWidgetCompact: (params: DevexaWidgetPlatformConstructorParameters) => DevexaWidgetPlatformInterface;
}
}
// The Devexa team provides the widget URLs and a token for your channel.
const DEVEXA_APP_URL = 'https://devexa.devexperts.com';
const DEVEXA_SCRIPT_URL = 'https://devexa.devexperts.com/widget/platform/devexa-widget-platform.js';
const DEVEXA_WIDGET_CONTAINER_ID = 'devexa-widget';
// Devexa waits about 20 seconds for the result; report sooner so the reply is not lost.
const CHART_COMMANDS_BUDGET_MS = 12_000;
/** Applies the commands, or reports a timeout when they take longer than the budget. */
const applyWithinBudget = (chartControl: DevexaChartControl, commands: unknown[]): Promise<ChartCommandReport> => {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<ChartCommandReport>(resolve => {
timer = setTimeout(
() => resolve({ applied: [], skipped: ['the chart took too long to apply the commands'] }),
CHART_COMMANDS_BUDGET_MS,
);
});
return Promise.race([applyDevexaChartCommands(chartControl, parseChartCommandList(commands)), timeout]).finally(
() => clearTimeout(timer),
);
};
/**
* The widget script first returns a loader that accepts any call; the result has to reach the
* widget it loads, which the loader exposes once it is ready.
*/
type WidgetLoader = DevexaWidgetPlatformInterface & {
readonly __devexaWidgetInstance?: DevexaWidgetPlatformInterface | null;
};
const reportResult = (widget: WidgetLoader, commandId: string, report: ChartCommandReport) =>
(widget.__devexaWidgetInstance ?? widget).reportChartCommandResult(commandId, report);
const loadDevexaScript = () =>
new Promise<void>((resolve, reject) => {
const script = document.createElement('script');
script.src = DEVEXA_SCRIPT_URL;
script.type = 'module';
script.onload = () => resolve();
script.onerror = () => reject(new Error('Devexa widget script failed to load'));
document.head.appendChild(script);
});
/**
* Creates the Devexa widget and returns a function that opens or closes it.
* Call it in the page component: the chart toolbar is rebuilt when the multi-chart layout changes,
* so a widget created inside a toolbar button would close on every layout change.
*/
const useDevexaWidget = (chartControl: DevexaChartControl, token: string, userId: string) => {
const widget = useRef<DevexaWidgetPlatformInterface | null>(null);
const isOpen = useRef(false);
useEffect(() => {
const container = document.getElementById(DEVEXA_WIDGET_CONTAINER_ID);
let unsubscribe = () => {};
let disposed = false;
loadDevexaScript().then(() => {
if (disposed || container === null) {
return;
}
const instance = window.DevexaWidgetCompact({
element: container,
config: { appUrl: DEVEXA_APP_URL, token, userId, useCustomButton: true, inline: false },
state: { activeWidgetTab: 'SUPPORT', toggledOn: false },
theme: 'dxcharts-dark',
});
widget.current = instance;
// Devexa sends the context with every message, so keep it fresh right before the user sends one.
// The chat panel is rendered outside the container, so listen on the whole document.
const refreshContext = () => instance.addMessageContext(getDevexaChartContext(chartControl));
const onStateChange = (state: DevexaWidgetPlatformState) => {
isOpen.current = state.toggledOn;
};
const onEvent = async (event: WidgetEvent) => {
// the Chart Control tool sends the commands of a reply; Devexa answers from the report
if (event.type === 'chartCommands') {
let report: ChartCommandReport = {
applied: [],
skipped: ['the chart could not apply the commands'],
};
try {
report = await applyWithinBudget(chartControl, event.commands ?? []);
} finally {
reportResult(instance, event.commandId, report);
refreshContext();
}
return;
}
// "Add to Chart" under a code block: a custom indicator in JavaScript, or a block of chart commands
if (event.type === 'customizeChart') {
const commands = parseChartCommands(event.payload);
if (commands) {
await applyDevexaChartCommands(chartControl, commands);
refreshContext();
}
// Otherwise the payload is a custom indicator in JavaScript, see the Custom Studies article.
}
};
refreshContext();
instance.addEventListener(onEvent);
instance.addStateListener(onStateChange);
document.addEventListener('keydown', refreshContext, true);
document.addEventListener('pointerdown', refreshContext, true);
unsubscribe = () => {
document.removeEventListener('keydown', refreshContext, true);
document.removeEventListener('pointerdown', refreshContext, true);
instance.removeEventListener(onEvent);
instance.removeStateListener(onStateChange);
instance.unmount();
widget.current = null;
};
});
return () => {
disposed = true;
unsubscribe();
};
}, [chartControl, token, userId]);
return useCallback(() => {
isOpen.current = !isOpen.current;
widget.current?.updateState({ toggledOn: isOpen.current });
}, []);
};
interface DevexaChartAssistantExampleProps {
/** Devexa channel token. */
readonly token: string;
/** A stable id of the current user. */
readonly userId: string;
}
export const DevexaChartAssistantExample = ({ token, userId }: DevexaChartAssistantExampleProps) => {
const apiRef = useRef<ChartReactAPI | undefined>(undefined);
const dxStudiesProvider = useMemo(
() => createDxStudiesProvider(DEFAULT_STUDIES_LIST(DEFAULT_LOCALIZATION.studies).map(fromRawStudiesSettings)),
[],
);
const chartControl = useMemo<DevexaChartControl>(
() => ({
getApi: () => apiRef.current,
getStudies: () => dxStudiesProvider.getStudies(),
// Optional: let your symbol search turn "BTC/USD" into the symbol your data provider uses.
// searchSymbol: query => symbolSuggestProvider.searchInstruments(query).then(found => found[0]?.symbol),
}),
[dxStudiesProvider],
);
const toggleChartAssistant = useDevexaWidget(chartControl, token, userId);
const toolbarButtons = useMemo(
() =>
addCustomToolbarButtons({
button: () => <button onClick={toggleChartAssistant}>Chart Assistant</button>,
}),
[toggleChartAssistant],
);
return (
<>
<div id={DEVEXA_WIDGET_CONTAINER_ID} style={{ position: 'absolute' }} />
<ChartReactApp
uiOverrides={{ Toolbar: { ToolbarButtons: toolbarButtons } }}
dependencies={{
...CREATE_MOCK_PROVIDERS(),
dxStudiesProvider,
onApiCreated: api => {
apiRef.current = api;
},
}}
/>
</>
);
};

Troubleshooting​

The assistant says it can't change the chart, or the chart doesn't change. The Chart Control tool is not enabled for your organization, so no chartCommands event reaches the page. Ask the Devexa team to enable it. To check, turn on the widget's debug log with localStorage.setItem('devexaWidgetLoaderDebug', '1') and reload the page: the widget logs what it receives from Devexa, and no chart commands arrive.

The assistant says "Done", but nothing changed. The page also sends the command instructions in its context. Send only the chart state (see the note in Step 2).

A drawing comes back after it was removed. It was added with drawing sync on; add it with synced: false (see the notes in Step 3).