Skip to main content

Drawing Tools & Overlays

Overlays are interactive canvas elements drawn on top of the chart. They include:

  • Drawing tools: trend lines, Fibonacci retracements, shapes, wave counts, annotations.
  • Order lines: horizontal price-level lines used to visualize open orders.

Showing the Drawing Toolbar​

The drawing toolbar is hidden by default. Enable it at construction time or toggle it at runtime:

// Show on creation
const chart = new AltradyCharts({
drawingBarVisible: true,
// ...
})

// Toggle at runtime via the internal store
// (exposed via the period bar menu button in the default UI)

The drawing bar appears on the left side of the chart and contains buttons for all built-in overlay categories.


Programmatic Overlay Creation​

Use createOverlay to add overlays without user interaction.

createOverlay(
overlay: OverlayCreate & { properties?: DeepPartial<OverlayProperties> },
paneId?: string
): string | null

OverlayCreate is the klinecharts overlay creation type. The properties extension allows setting visual properties at creation time.

// Add a horizontal line at a fixed price
chart.createOverlay({
name: 'horizontalStraightLine',
points: [{ timestamp: Date.now(), value: 50000 }],
properties: {
line: { color: '#FF5252', size: 2, style: 'dashed' },
},
})

// Add a trend line
chart.createOverlay({
name: 'segment',
points: [
{ timestamp: startTs, value: 48000 },
{ timestamp: endTs, value: 52000 },
],
})

// Target a specific sub-pane
chart.createOverlay(
{ name: 'horizontalStraightLine', points: [{ timestamp: Date.now(), value: 70 }] },
'rsi_pane_id'
)

Return value​

Returns the overlay ID string on success, or null if the chart is not yet initialized.


Overlay Mode​

setOverlayMode(mode: OverlayMode): void

Controls how overlays respond to user interaction.

ModeBehavior
'normal'Overlays can be selected, moved, and resized
'lock'Overlays cannot be moved or deleted

OverlayProperties​

Styling properties available on all overlays. Part of the klinecharts OverlayProperties type.

export interface OverlayProperties {
line: {
color: string
size: number
style: 'solid' | 'dashed' | 'dotted'
dashedValue?: number[]
}
text: {
color: string
size: number
family: string
weight: string
paddingLeft?: number
paddingRight?: number
paddingTop?: number
paddingBottom?: number
borderRadius?: number
borderSize?: number
borderColor?: string
backgroundColor?: string
borderStyle?: string
}
point: {
color: string
borderColor: string
borderSize: number
radius: number
activeRadius: number
activeColor: string
activeBorderColor: string
activeBorderSize: number
}
polygon: {
color: string
borderColor: string
borderSize: number
borderStyle: string
}
arc: {
color: string
borderColor: string
borderSize: number
borderStyle: string
}
}

DEFAULT_OVERLAY_PROPERTIES​

A pre-built OverlayProperties object with default values, re-exported from klinecharts. Use it as a base for merging custom styles:

import { DEFAULT_OVERLAY_PROPERTIES } from '@altrady/charts'

const myProperties = {
...DEFAULT_OVERLAY_PROPERTIES,
line: { ...DEFAULT_OVERLAY_PROPERTIES.line, color: '#FF5252' },
}

BUILT_IN_OVERLAYS​

All 29 built-in overlay type names:

export const BUILT_IN_OVERLAYS = [
// Lines
'horizontalStraightLine', // Infinite horizontal line
'verticalStraightLine', // Infinite vertical line
'straightLine', // Infinite diagonal line through two points
'rayLine', // Ray extending from one point through another
'segment', // Finite line segment between two points
'priceLine', // Horizontal line with price label

// Channels
'parallelStraightLine', // Two parallel straight lines
'priceChannelLine', // Price channel with three defining points

// Fibonacci
'fibonacciLine', // Fibonacci retracement levels
'fibonacciSegment', // Fibonacci with segment visualization
'fibonacciCircle', // Fibonacci circle arcs
'fibonacciSpiral', // Fibonacci spiral
'fibonacciSpeedResistanceFan', // Speed/resistance fan lines
'fibonacciExtension', // Fibonacci extension levels

// Shapes
'rect', // Rectangle
'circle', // Circle
'triangle', // Triangle
'parallelogram', // Parallelogram
'arc', // Arc
'arrow', // Arrow
'brush', // Freehand brush stroke

// Annotations
'simpleAnnotation', // Text annotation
'simpleTag', // Price tag

// Waves
'threeWaves', // Elliott 3-wave count
'fiveWaves', // Elliott 5-wave count
'eightWaves', // Elliott 8-wave count
'anyWaves', // Flexible wave count
'abcd', // ABCD harmonic pattern
'xabcd', // XABCD harmonic pattern

// Gann
'gannBox', // Gann square

// Order line
'orderLine', // Horizontal order price line
] as const

Overlays are grouped into categories for the drawing bar UI:

CategoryOverlays
LineshorizontalStraightLine, verticalStraightLine, straightLine, rayLine, segment, priceLine
ChannelsparallelStraightLine, priceChannelLine
FibonaccifibonacciLine, fibonacciSegment, fibonacciCircle, fibonacciSpiral, fibonacciSpeedResistanceFan, fibonacciExtension
Shapesrect, circle, triangle, parallelogram, arc, arrow, brush
AnnotationssimpleAnnotation, simpleTag
WavesthreeWaves, fiveWaves, eightWaves, anyWaves, abcd, xabcd
GanngannBox

Order Lines​

Order lines are horizontal price-level overlays for visualizing open orders, positions, and alerts. createOrderLine returns a handle with get() and set(patch), the same shape as createPriceAlert, createSmartPosition and createTradeDraft.

Creating an Order Line​

import { createOrderLine } from '@altrady/charts'
import type { Chart } from '@altrady/charts'

const chart: Chart = superchart.getChart()!
const orderId = '123'

const orderLine = createOrderLine(chart, {
price: 49500,
text: 'Buy 0.5 BTC',
quantity: '0.5 BTC',
lineColor: '#4caf50',
lineStyle: 'dashed',
bodyBackgroundColor: '#4caf50',
bodyTextColor: '#FFFFFF',
editable: true, // can be dragged to new price (default: true)
onCancel: () => cancelOrder(orderId),
onModify: (event) => modifyOrder(orderId, event?.overlay.points[0].value),
})

// later
orderLine.set({ price: 49750, quantity: '0.6 BTC' })
orderLine.get().price // where the line is now, mid-drag included
orderLine.set({ onModify: undefined }) // a key set to undefined clears it

OrderLine (handle)​

export interface OrderLine {
readonly id: string
readonly paneId: string

/** The line's properties, `price` being where it is now, mid-drag included; `null` once removed. */
get(): OrderLineProperties | null
/** Patch the line's properties. Only a `price` in the patch moves the line,
* so a text or quantity update during a drag doesn't pull it back. A key
* set to `undefined` clears it, callbacks included. */
set(patch: Partial<OrderLineProperties>): OrderLine
remove(): void
}

Sections​

Each order line renders three sections (left to right): body, quantity, cancelButton.

SectionInteractionUse case
bodyDraggable (when editable: true), click does nothingLabel text (e.g. "Buy 0.5 BTC")
quantityClick calls onModifySize/price display
cancelButtonClick calls onCancelX icon to cancel order

All sections are independently toggle-able via isBodyVisible, isQuantityVisible and isCancelButtonVisible (in the options or through set()). Hidden sections leave no gap.

The line is drawn in the trade overlay's handle style: one rounded pill 40px from the price scale, the body tinted in lineColor, the quantity as a value, the ✕ behind a divider, on a dashed track. The look is fixed: only lineColor tones it (defaulting to brand-default), and the neutral colours are design tokens on the chart root, so both themes resolve. The TradingView-style colour, font, padding, border, line-style and y-axis label options are accepted for compatibility but ignored.

Alignment​

// Right-aligned (default) — labels near the y-axis
createOrderLine(chart, { price: 50000, text: 'Limit Buy', align: 'right' })

// Left-aligned — labels at the left edge (e.g. "AVG ENTRY")
createOrderLine(chart, { price: 50000, text: 'AVG ENTRY', align: 'left', marginLeft: 10 })

Price Lines​

The overlay draws two dashed lines that skip the label area:

  • price-line-left: left chart edge → labels start
  • price-line-right: labels end → right chart edge

This prevents the line from showing through transparent label backgrounds.

OrderLineProperties​

export interface OrderLineProperties {
price?: number
text?: string
quantity?: number | string
tooltip?: string
modifyTooltip?: string
cancelTooltip?: string

// Layout
align?: 'left' | 'right'
marginRight?: number
marginLeft?: number

// Behavior
editable?: boolean // default: true (draggable)
extendLeft?: boolean

// Line
lineColor?: string
lineWidth?: number
lineStyle?: 'solid' | 'dashed'
lineDashedValue?: number[]
lineLength?: number

// Body label
bodyFont?: string
bodyFontSize?: number
bodyFontWeight?: number | string
bodyTextColor?: string
bodyBackgroundColor?: string
bodyBorderColor?: string
bodyPaddingLeft?: number
bodyPaddingRight?: number
bodyPaddingTop?: number
bodyPaddingBottom?: number
isBodyVisible?: boolean

// Quantity label
quantityFont?: string
quantityFontSize?: number
quantityFontWeight?: number | string
quantityTextColor?: string
quantityBackgroundColor?: string
quantityBorderColor?: string
quantityPaddingLeft?: number
quantityPaddingRight?: number
quantityPaddingTop?: number
quantityPaddingBottom?: number
isQuantityVisible?: boolean

// Cancel button
cancelButtonFontSize?: number
cancelButtonFontWeight?: number | string
cancelButtonIconColor?: string
cancelButtonBackgroundColor?: string
cancelButtonBorderColor?: string
cancelButtonPaddingLeft?: number
cancelButtonPaddingRight?: number
cancelButtonPaddingTop?: number
cancelButtonPaddingBottom?: number
isCancelButtonVisible?: boolean

// Shared border
borderStyle?: 'solid' | 'dashed'
borderSize?: number
borderDashedValue?: number[]
borderRadius?: number // ignored: the pill is fixed

// Events: the line's price is at event.overlay.points[0].value
onMoveStart?: OrderLineCallback
onMove?: OrderLineCallback
onMoveEnd?: OrderLineCallback
onCancel?: OrderLineCallback
onModify?: OrderLineCallback
}

export type OrderLineCallback = (event?: OverlayEvent<unknown>) => void

Callbacks are plain options: pass them to createOrderLine or later with set({ onCancel }). They get no params argument, so close over your own data (an order id, say) instead.


Host overlays​

createHostOverlay draws an overlay template (priceLevelLine, box, a marker of your own) from the host's data. It isn't one of the user's drawings: no default drawing style, never saved with the chart, not in the Object Tree, no undo, and removing it leaves the user's selection alone. The host keeps its own state.

import { createHostOverlay } from '@altrady/charts'

const level = createHostOverlay(sc.chart(0), { // or `sc` for the active chart
name: 'priceLevelLine',
points: [{ value: 64250 }],
lock: false, // default true
extendData: { text: 'Trigger', color: '#f7a600' },
onPressedMoveEnd: (e) => saveTrigger(e.overlay.points[0].value),
onRightClick: (e) => openMyMenu(e), // the engine's right-click delete never applies
})

level.set({ points: [{ value: 64300 }], extendData: { text: 'Moved' } }) // extendData is merged
level.get() // { name, points, lock, visible, extendData }, or null once removed
level.remove() // from the chart it was created on, whichever chart is active

For the user's own drawings, use sc.createOverlay / sc.removeOverlay, and sc.getDrawings() to list them.


Handles after remove()​

Every handle (createOrderLine, createTradeLine, createHostOverlay, createPriceAlert, createSmartPosition, createTradeDraft) behaves the same once removed: get() returns null and set() does nothing, so a stale handle can't redraw or report a state that's no longer on the chart.


Handle texts​

The texts of createSmartPosition and createPriceAlert handles (pill names, tooltips, buttons) come from the chart's locale, like the rest of the UI. They follow setLocale without the host doing anything. The keys are smart_position_* and price_alert_* in the locale packs, so loadLocale adds a language or changes a wording for every handle at once.

A handle's labels option overrides a text only where the wording really differs in that context, for example a trigger-price level whose ✕ reads "Cancel" instead of "Remove alert". Don't pass translations through labels. labels.hidden, the mask shown while hideAmounts is on, isn't translated, so a host sets it if it wants something other than ***.


Trade Draft​

The trade overlay (trade_overlay feature) shows the order being set up as one draft row: entry pill (Buy Limit | QTY | ✓ ✕), side swap, extra entries, R:R and TP/SL handles. The ✓ at the end of the entry pill places the order and the ✕ discards it, the way an alert being edited is confirmed. createTradeDraft drives that draft from the host the way createOrderLine drives a line, so a trade form and the chart edit the same order.

import { createTradeDraft } from '@altrady/charts'

const draft = createTradeDraft(superchart, {
side: 'buy',
kind: 'limit', // 'market' tracks the last price
entries: [{ id: 'o1', price: 83000, sizePct: 100 }], // primary first; more = a ladder
qty: 0.5, // base amount across all entries
takeProfits: [{ id: 'tp1', price: 85500, sizePct: 100 }],
stopLoss: { price: 81300, protection: 'none', cooldownMin: 0 },
})
.onChange((state) => form.update(state)) // the user dragged or edited it on the chart
.onPlace((state) => form.submit()) // ✓ pressed; the draft stays until remove()
.onCancel(() => form.reset()) // ✕ pressed; the draft is already gone

draft.set({ qty: 1.25 }) // any subset; never reported back through onChange
draft.get() // the current state, or null once removed
draft.remove()
  • One draft per chart: a new createTradeDraft replaces the last.
  • The ✓ is greyed out until the draft has a size. placeBlocked: 'reason' greys it out with that reason as its hover text (the host's form is invalid); set({ placeBlocked: null }) clears it. Kept across set() calls that leave it out.
  • Ids are yours (order ids) and come back unchanged; a level the user adds on the chart comes back as chart-N, and a removed one is missing, so diff by id.
  • onChange fires only when something the host can see changed; the R:R lock and risk target stay chart-local.
  • followsEntry: true on a DCA entry (not the first), a take profit or the stop marks a level nobody has priced yet, e.g. one a preset put at a distance from the first entry. While the first entry is dragged, flagged levels move with it by the same ratio in the same frame, instead of waiting for the host's set(). A take profit set as a return on the entry (PnL %) takes it too: its price is proportional to the entry, so the ratio keeps its % exactly. Dragging a flagged level clears its flag. Filled levels, running trails and a locked stop never move. Kept per level across set() calls that leave it out (false clears it), never reported back.
  • A take profit reads as the least it makes: from the first entry to fill (or the filled entries), on that part of the size, net of the entry and exit fee. The % is base × (1 + %) on a buy and base / (1 + %) on a sell, with base = entry × (1 ± 2 × feeRate). The stop reads as the most it loses: the whole ladder's average, on the whole size.
  • A draft the user starts from the + menu reaches the host through AltradyChartsOptions.onTradeDraftStart(draft), with the same handle, when no draft is bound yet.
  • Also available as superchart.createTradeDraft(state).

Editing a live position​

The same draft edits an order that is already partly or fully executed. Flag what can't change any more:

const draft = createTradeDraft(superchart, {
side: 'buy',
kind: 'limit',
qty: 0.5,
entries: [{ id: 'o1', price: 64000, sizePct: 60, filled: true }, { id: 'o2', price: 63000, sizePct: 40 }],
takeProfits: [
{ id: 't1', price: 66000, sizePct: 50, filled: true },
{ id: 't2', price: 68000, sizePct: 50, trailingPct: 1, trailingActive: true },
],
stopLoss: { price: 64000, protection: 'breakeven', cooldownMin: 0, locked: true, lockReason: 'Moved to break-even' },
labels: { place: 'Update position', cancel: 'Cancel edit' },
})
  • filled (entries and take profits): drawn with a check, never dragged, removed or resized, and left out of every split rebalance. A filled take profit is a read-out only: no axis price tag and no track across the pane. onChange echoes filled levels unchanged.
  • Once any entry is filled, the side and order type are fixed (no side flip, no reverse) and the entry ladder is sized in base amounts. A filled level keeps its amount; + adds an open level with the amount of the last level, and resizing or removing an open level changes qty by that amount. Shares are re-derived and may be fractional, so read a filled level's amount as sizePct × qty. The whole-position size can't be typed, and there's no trailing entry.
  • A filled primary entry reads as the position (labels.position, default "Position"), whether or not open entry levels follow it. Pass the filled part as one entry at the average price.
  • takeProfits[i].trailingActive: the trail is running, so the level and its distance are fixed and no target can be added beyond it.
  • stopLoss.locked / lockReason: no drag, no ✕, protection and cooldown read-only; the reason shows on hover.
  • The R:R lock is off while anything is fixed. With a filled entry, editing the stop's $ risk moves the stop instead of resizing.
  • labels (place and cancel are the ✓ / ✕ hover text; position, filled) are kept across set() calls that leave them out, and never reported back.
  • The touch order sheet doesn't enforce these locks; edit mode is for the desktop handle rows.

Order Label Parts​

What a line's pill shows besides its name is chosen by the host, per kind of line, and passed as labelParts. The host resolves its own presets; Altrady Charts has none.

import type { LabelPart, LabelParts } from '@altrady/charts'

type LabelPart = 'base' | 'quote' | 'pnl' | 'pnlPct' | 'share' | 'distancePct'
type LabelParts = { entry: LabelPart[], dca: LabelPart[], tp: LabelPart[], sl: LabelPart[], openOrder: LabelPart[] }
  • Parts always render in the order base, quote, pnl, pnlPct, share, distancePct; ones not listed are skipped. The line name (Entry 1, DCA1, TP2, SL, the open order's name) always shows.
  • base is the size via format.qty; quote is size × price via format.value; pnl goes via format.pnl; pnlPct is the return; share is the percent of the position at that level; distancePct is the distance from the current price.
  • labelParts goes on SmartPositionState and TradeDraftState. Absent, they use the "PnL" default: entry and dca base, share; tp pnl, pnlPct, share; sl pnl, pnlPct; openOrder base.
  • hideAmounts masks base, quote and pnl; pnlPct, share and distancePct stay.
  • Plain order lines take the structured fields labelKind ('openOrder' | 'tp' | 'sl'), labelName, labelParts (the list for that kind), qty, pnl, pnlPct, hideAmounts and format, with matching setters (setLabelKind, setLabelName, setLabelParts, setQty, setPnl, setPnlPct, setHideAmounts, setFormat). With labelKind set, the quantity section is built from them and quantity is ignored; the body shows labelName. distancePct is read from the last bar's close each time the line is drawn. A line without labelKind keeps the free text and quantity.
  • format is { price, qty, value, pnl, pnlPct }; a function left out falls back to the chart symbol's precisions and baseCurrency / quoteCurrency.

Extend Left / Right​

Certain line-based overlays can extend their lines to the edges of the chart viewport. This is configured via the overlay settings modal (Style tab → Extend section) or programmatically through extendData.

Supported Overlays​

OverlayDescription
segmentLine segment extends in one or both directions to the viewport edges
fibonacciSegmentFibonacci level lines extend left/right to the viewport edges
fibonacciExtensionExtension level lines extend left/right to the viewport edges

Programmatic Usage​

Set extendData when creating an overlay:

chart.createOverlay({
name: 'segment',
points: [
{ timestamp: startTs, value: 48000 },
{ timestamp: endTs, value: 52000 },
],
extendData: { extendLeft: true, extendRight: false },
})

Or update an existing overlay via the underlying chart:

const klineChart = chart.getChart()
klineChart?.overrideOverlay({
id: overlayId,
extendData: { extendLeft: true, extendRight: true },
})

The extend state is automatically persisted and restored via StorageAdapter.


Timeframe Visibility​

Overlays can be configured to show or hide based on the active timeframe. This allows, for example, showing a trend line only on hourly charts and above, or hiding detailed annotations on weekly charts.

Settings Modal​

Double-click an overlay → Visibility tab:

  • Show on All Timeframes — master toggle (default: on)
  • Per-category rules — enable/disable each period category (seconds, minutes, hours, days, weeks, months) with from/to range selectors

How It Works​

  • Visibility rules are stored per overlay and persisted to StorageAdapter
  • When the user changes the chart period, all overlays are checked against their visibility rules
  • Overlays that don't match the current period are hidden (visible: false); matching ones are shown
  • Rules are checked as: period.span >= rule.from && period.span <= rule.to within each category

TimeframeVisibility Type​

export interface TimeframeVisibility {
showOnAll: boolean
rules: Record<PeriodCategory, TimeframeVisibilityRule>
}

export interface TimeframeVisibilityRule {
enabled: boolean
from: number // minimum span value
to: number // maximum span value
}

export type PeriodCategory = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month'

Persistence — SavedOverlay​

Overlays are automatically saved to StorageAdapter when a storageKey and adapter are configured. Each overlay is serialized as:

export interface SavedOverlay {
id: string
/** Overlay type name (e.g. 'fibonacciLine') */
name: string
/** Pane ID where the overlay lives */
paneId: string
groupId?: string
/** Anchor points stored as timestamp+value pairs */
points: SavedOverlayPoint[]
properties?: DeepPartial<OverlayProperties>
lock: boolean
visible: boolean
extendLeft?: boolean
extendRight?: boolean
mode?: OverlayMode
extendData?: unknown
/** Timeframe visibility rules (omitted when showOnAll is true) */
timeframeVisibility?: TimeframeVisibility
}

export interface SavedOverlayPoint {
/** Unix milliseconds */
timestamp: number
/** Price value */
value: number
}

Points are stored as { timestamp, value } rather than { dataIndex, value } to survive gaps when new bars are added to the left.

overlayPointsToSaved​

Helper to convert klinecharts Point[] to SavedOverlayPoint[]:

function overlayPointsToSaved(points: Array<Partial<Point>>): SavedOverlayPoint[]

Used internally when serializing overlays. Only points with both timestamp and value defined are included.


ProOverlay​

ProOverlay is an extended overlay interface that adds property management methods. Created by ProOverlayTemplate factories registered in klinecharts:

export interface ProOverlay extends Overlay {
setProperties(properties: DeepPartial<OverlayProperties>, id: string): void
getProperties(id: string): DeepPartial<OverlayProperties>
}

export interface ProOverlayCreate extends OverlayCreate {
properties?: DeepPartial<OverlayProperties>
}

createOverlay accepts ProOverlayCreate, so you can set initial properties directly:

chart.createOverlay({
name: 'fibonacciLine',
points: [
{ timestamp: highTs, value: 55000 },
{ timestamp: lowTs, value: 40000 },
],
properties: {
line: { color: '#9C27B0' },
},
})

Custom Overlays​

Altrady Charts exposes registration APIs that let consumers define and register custom overlay types, figure primitives, and indicator templates.

Registration Functions​

import {
registerOverlay,
registerFigure,
registerIndicator,
} from '@altrady/charts'

// Types for defining templates
import type {
OverlayTemplate,
FigureTemplate,
IndicatorTemplate,
ProOverlayTemplate,
} from '@altrady/charts'
FunctionDescription
registerOverlay(template)Register a custom overlay type (drawing tool)
registerFigure(template)Register a custom figure primitive (canvas shape)
registerIndicator(template)Register a custom indicator template

Important: Call registration functions before creating the chart (new AltradyCharts()), or before the first createOverlay() call that uses the custom name.

Example: Simple Emoji Marker Overlay​

A minimal overlay that renders a single emoji at the clicked position:

import { registerOverlay } from '@altrady/charts'
import type { OverlayTemplate } from '@altrady/charts'

const myEmojiOverlay: OverlayTemplate = {
name: 'myEmoji',
totalStep: 2, // click once to place
needDefaultPointFigure: false,
needDefaultXAxisFigure: false,
needDefaultYAxisFigure: false,

createPointFigures: ({ coordinates, overlay }) => {
if (coordinates.length === 0) return []
const emoji = (overlay.extendData as { text?: string })?.text ?? '📌'

return [{
type: 'text',
attrs: {
x: coordinates[0].x,
y: coordinates[0].y,
text: emoji,
align: 'center',
baseline: 'middle',
},
styles: {
color: '#000000',
size: 24,
backgroundColor: 'transparent',
borderSize: 0,
paddingLeft: 0, paddingRight: 0,
paddingTop: 0, paddingBottom: 0,
},
}]
},
}

registerOverlay(myEmojiOverlay)

// Usage:
const chart = superchart.getChart()
chart?.createOverlay({
name: 'myEmoji',
points: [{ timestamp: Date.now(), value: 50000 }],
extendData: { text: '🚀' },
})

Example: Split-Line Overlay with Text Gap​

An overlay that renders a horizontal line split into two segments with label text in the gap (like orderLine or breakEvenLine):

import { registerOverlay, utils } from '@altrady/charts'

const { calcTextWidth } = utils

registerOverlay({
name: 'labeledPriceLine',
totalStep: 2,

createPointFigures: ({ coordinates, bounding, overlay }) => {
if (coordinates.length === 0) return []
const y = coordinates[0].y
const data = overlay.extendData as { text?: string; color?: string } | null
const text = data?.text ?? ''
const color = data?.color ?? '#FF5252'

if (text.length === 0) {
return [{ type: 'line', attrs: { coordinates: [{ x: 0, y }, { x: bounding.width, y }] }, styles: { color } }]
}

const textW = calcTextWidth(text, 12, 'normal')
const gap = textW + 12
const midX = bounding.width / 2

return [
// Left line
{ type: 'line', attrs: { coordinates: [{ x: 0, y }, { x: midX - gap / 2, y }] }, styles: { color }, ignoreEvent: true },
// Right line
{ type: 'line', attrs: { coordinates: [{ x: midX + gap / 2, y }, { x: bounding.width, y }] }, styles: { color }, ignoreEvent: true },
// Label
{ type: 'text', attrs: { x: midX, y, text, align: 'center', baseline: 'middle' },
styles: { color, size: 12, backgroundColor: 'transparent', borderSize: 0, paddingLeft: 0, paddingRight: 0, paddingTop: 0, paddingBottom: 0 } },
]
},
})

Example: Custom Figure Primitive​

Register a custom canvas figure that overlays can reference by name:

import { registerFigure } from '@altrady/charts'

registerFigure({
name: 'diamond',
checkEventOn: (coordinate, attrs, styles) => {
const { x, y, size = 10 } = attrs
return Math.abs(coordinate.x - x) + Math.abs(coordinate.y - y) <= size
},
draw: (ctx, attrs, styles) => {
const { x, y, size = 10 } = attrs
const { color = '#FF5252' } = styles
ctx.beginPath()
ctx.moveTo(x, y - size)
ctx.lineTo(x + size, y)
ctx.lineTo(x, y + size)
ctx.lineTo(x - size, y)
ctx.closePath()
ctx.fillStyle = color
ctx.fill()
},
})

// Use in a custom overlay:
registerOverlay({
name: 'diamondMarker',
totalStep: 2,
createPointFigures: ({ coordinates }) => [{
type: 'diamond', // references the registered figure
attrs: { x: coordinates[0].x, y: coordinates[0].y, size: 8 },
styles: { color: '#FFD700' },
}],
})

ProOverlayTemplate (Advanced)​

For overlays that need per-instance property management (like orderLine), use the ProOverlayTemplate factory pattern:

import { registerOverlay } from '@altrady/charts'
import type { ProOverlayTemplate } from '@altrady/charts'

function myOverlayFactory(): ProOverlayTemplate {
// Per-instance state via closure
let properties: Record<string, unknown> = {}

return {
name: 'myProOverlay',
totalStep: 2,

createPointFigures: ({ coordinates, overlay }) => {
const ext = overlay.extendData as Record<string, unknown> | null
const color = (ext?.color ?? properties.color ?? '#FF0000') as string
// ... render figures using merged properties
return []
},

setProperties: (newProps, id) => {
properties = { ...properties, ...newProps }
},

getProperties: (id) => ({ ...properties }),
}
}

registerOverlay(myOverlayFactory())

Built-in Overlay Types​

These custom overlays are registered by Altrady Charts and available for use:

NameDescription
orderLineHorizontal price line with body/quantity/cancel sections
emojiMarkerSingle emoji character at a point
timeAlertLineVertical line split with rotated text label
breakEvenLineHorizontal line split with text label in gap
trendlineAlertLineTwo-point segment with angle-matched rotated text