TypeScript Definitions
Complete TypeScript type definitions for the GoCharting SDK.
This page documents the most commonly-used types from the SDK (~58% coverage).
For the complete type definitions including advanced configuration options (80+ types total),
check your node_modules/@gocharting/chart-sdk/dist/index.d.ts file after installation, or explore the types directly in your IDE with IntelliSense.
Enums & literal unions
Quick index of exported string/object unions. Summary catalog: Enums & literal unions.
Chart / widget
- ChartActionId
- Chart type strings
- VisibilityType
- ChartTheme
- ChartFeatureId
- MarketStatusInfo
- TimeFrameInput
Trading
Events
ChartActionId
Used by activeChart().executeActionById(). See Enums hub and Chart API.
type ChartActionId =
| "chartReset"
| "zoomIn"
| "zoomOut"
| "undo"
| "redo"
| "invertScale"
| "logScale"
| "magnet";Chart type strings
No fixed TS enum — use runtime ids from supportedChartTypes() / setChartType. See Enums hub.
VisibilityType
type VisibilityType =
| "alwaysOn"
| "alwaysOff"
| "visibleOnMouseOver";Also used (same members) as CurrencyUnitVisibility for price-scale currency/unit visibility.
ChartTheme
type ChartTheme = "light" | "dark";ChartFeatureId
type ChartFeatureId =
| "topBar"
| "bottomBar"
| "drawingToolbar"
| "leftPanel"
| "rightPanel"
| "symbolSearch"
| "compare";MarketStatusInfo
type MarketStatusInfo = {
isOpen?: boolean;
statusText?: string;
dataStatus?: string;
delaySeconds?: number;
};TimeFrameInput
type TimeFrameInput =
| string
| { from: number; to: number }
| { type: "period-back"; value: string }
| { type: "time-range"; from: number; to: number };OrderType
type OrderType = "market" | "limit" | "stop" | "stop_limit";OrderSide
type OrderSide = "buy" | "sell";OrderStatus
type OrderStatus =
| "open"
| "pending"
| "filled"
| "cancelled"
| "rejected"
| "expired";TimeInForce
type TimeInForce = "GTC" | "IOC" | "FOK" | "DAY";ExecutionDirection
type ExecutionDirection = "buy" | "sell";TradingEventType
type TradingEventType =
| "CREATE_ORDER"
| "PLACE_ORDER"
| "MODIFY_ORDER"
| "CANCEL_ORDER";AppCallbackEventType
type AppCallbackEventType =
| "CREATE_ORDER"
| "PLACE_ORDER"
| "EDIT_ORDER"
| "PLACE_ORDER_DIRECT"
| "MODIFY_POSITION"
| "MODIFY_ORDER_DIRECT"
| "MODIFY_ORDER"
| "CANCEL_ORDER"
| "CLOSE_POSITION"
| "EXIT_ALL_POSITIONS"
| "CANCEL_ALL_ORDERS"
| "DOWNLOAD_MORE_DATA_BY_DATE"
| "DOWNLOAD_MORE_DATA"
| "OPEN_SETTINGS"
| "OPEN_TRADING_WIDGET"
| "OPEN_CONTEXT_MENU"
| "CHART_SELECTED"
| "CHART_MODE_CHANGED";Core Types
Chart Types
/**
* ProfessionalChart React component instance
* This is the raw React component instance passed to the onReady callback
* and returned by chartWrapper.getChartInstance()
*/
type ChartInstance = {
/** Destroy the chart and clean up all resources */
destroy(): void;
/** Set broker account data for trading features */
setBrokerAccounts(data: BrokerAccountData): void;
/** Change the symbol */
setSymbol(newSymbol: string): void;
/** Change the interval */
setInterval(newInterval: string): void;
/** Change the theme ('light' or 'dark') */
setTheme(newTheme: "light" | "dark"): void;
/** Resize the chart */
resize(width: number | string, height: number | string): void;
/** Change symbol of a specific chart by index in multichart mode */
setChartSymbolAtIndex(newSymbol: string, chartIdx: number): void;
/** Change interval of a specific chart by index in multichart mode */
setIntervalAtIndex(newInterval: string, chartIdx: number): void;
/** Add an indicator to the currently selected chart */
addIndicator(indicator: { type?: string; id?: string }): void;
/** Add an indicator to a specific chart by index in multichart mode */
addIndicatorAtIndex(
indicator: { type?: string; id?: string },
chartIdx: number
): void;
/** Add a drawing to the currently selected chart */
addDrawing(
drawing: {
type?: string;
name?: string;
options?: DrawingOptions;
appearance?: DrawingAppearance;
},
chartId?: string
): void;
/** Add a drawing to a specific chart by index in multichart mode */
addDrawingAtIndex(
drawing: {
type?: string;
name?: string;
options?: DrawingOptions;
appearance?: DrawingAppearance;
},
chartIdx: number,
chartId?: string
): void;
/** Delete an object (drawing or indicator) from the currently selected chart */
deleteObject(objectId: string, chartId?: string): void;
/** Delete an object (drawing or indicator) from a specific chart by index in multichart mode */
deleteObjectAtIndex(
objectId: string,
chartIdx: number,
chartId?: string
): void;
/** Update chart settings for the currently selected chart */
updateSettings(settings: Partial<ChartSettings>): void;
/** Update chart settings for a specific chart by index in multichart mode */
updateSettingsAtIndex(
settings: Partial<ChartSettings>,
chartIdx: number
): void;
/** Get the complete chart state for the currently selected chart */
getChartState(): ChartState | null;
/** Get the complete chart state for a specific chart by index in multichart mode */
getChartStateAtIndex(chartIdx: number): ChartState | null;
/** Set the complete chart state for the currently selected chart */
setChartState(newState: ChartState): void;
/** Set the complete chart state for a specific chart by index in multichart mode */
setChartStateAtIndex(newState: ChartState, chartIdx: number): void;
/** Resubscribe to all active subscriptions after reconnection */
resubscribeAll(idToken?: string): void;
/** Get information about all charts in multichart mode (New in v1.0.47) */
getAllCharts(): MultiChartInfo;
// Widget façade — also on ChartWrapper from createChart()
activeChart(): IChartApi;
chart(index: number): IChartApi;
chartsCount(): number;
activeChartIndex(): number;
setActiveChart(index: number): void;
layout(): string;
setLayout(layout: string): void;
setLayoutSizes(sizes: LayoutSizes, disableUndo?: boolean): void;
resetLayoutSizes(disableUndo?: boolean): void;
unloadUnusedCharts(): void;
applyOverrides(overrides: ApplyOverridesInput): void;
applyStudiesOverrides(overrides: StudiesOverridesMap): void;
applyTradingCustomization(overrides: TradingCustomization): void;
setCSSCustomProperty(name: string, value: string): void;
getCSSCustomPropertyValue(name: string): string;
addCustomCSSFile(url: string): void;
customThemes(): Promise<ICustomThemesApi>;
features(): IFeaturesApi;
setFeatureEnabled(id: ChartFeatureId | string, enabled: boolean): void;
getFeatureEnabled(id: ChartFeatureId | string): boolean;
getFeatures(): FeatureFlags;
headerReady(): Promise<void>;
createButton(options?: CreateButtonOptions): HTMLButtonElement;
createDropdown(options: CreateDropdownOptions): Promise<IDropdownApi>;
removeButton(button: HTMLElement | string): void;
onShortcut(shortcut: ShortcutInput, callback: () => void): () => void;
onContextMenu(callback: ContextMenuCallback): void;
closePopupsAndDialogs(): void;
showConfirmDialog(
titleOrParams: string | ConfirmDialogParams,
content?: string | string[] | ((confirmed: boolean) => void),
callbackOrOk?: ((confirmed: boolean) => void) | string,
optionsOrCancel?: { okText?: string; cancelText?: string } | string,
): Promise<boolean>;
showNoticeDialog(
titleOrParams: string | NoticeDialogParams,
content?: string | string[],
callback?: () => void,
): Promise<void>;
selectLineTool(linetool: string): void;
selectedLineTool(): string;
hideAllDrawingTools(): ISyncApi;
lockAllDrawingTools(): ISyncApi;
magnetEnabled(): ISyncApi;
magnetMode(): INumberSyncApi;
takeClientScreenshot(options?: ClientSnapshotOptions): Promise<HTMLCanvasElement>;
takeScreenshot(): Promise<string>;
clearUndoHistory(): void;
undoRedoState(): UndoRedoState;
resetCache(): void;
getStudiesList(): string[];
getStudyInputs(studyName: string): StudyInputInformation[];
getStudyStyles(studyName: string): StudyStyleInfo;
supportedChartTypes(): string[];
getIntervals(): string[];
symbolInterval(): SymbolIntervalResult | null;
mainSeriesPriceFormatter(): PriceFormatter;
currencyAndUnitVisibility(): IVisibilityApi;
customSymbolStatus(): ICustomSymbolStatusApi;
navigationButtonsVisibility(): IVisibilityWatchedValue;
paneButtonsVisibility(): IVisibilityWatchedValue;
dateFormat(): IStringWatchedValue;
timeHoursFormat(): IStringWatchedValue;
symbolSync(): ISyncApi;
intervalSync(): ISyncApi;
drawOnAllChartsEnabled(): ISyncApi;
crosshairSync(): ISyncApi;
dateRangeSync(): ISyncApi;
timeSync(): ISyncApi;
subscribe(event: WidgetSubscribeEvent, callback: WidgetSubscribeCallback): void;
unsubscribe(event: WidgetSubscribeEvent, callback: WidgetSubscribeCallback): void;
};
/**
* Multichart information (New in v1.0.47)
* Contains information about all charts when multicharting is enabled
*/
type MultiChartInfo = {
/** Whether multicharting is enabled (layout !== "1") */
isMultichartingEnabled: boolean;
/** GoCharting layout id when emitted from CHART_MODE_CHANGED / setLayout */
layout?: string;
/** Array of chart details for all charts */
charts: ChartSelectedMessage[];
};
/**
* Chart selection message (New in v1.0.47)
* Contains details about a specific chart in multichart mode
*/
type ChartSelectedMessage = {
/** Chart ID (e.g., "CHART_1") */
id: string;
/** Chart ID (same as id) */
chartId: string;
/** Chart index (0-based) */
idx: number;
/** Current symbol */
symbol: string;
/** Current interval */
interval: string;
};
/**
* Chart wrapper instance returned by createChart()
* This is the wrapper object with lifecycle management methods
*/
type ChartWrapper = {
/** Destroy the chart and clean up all resources */
destroy(): void;
/** Check if chart is destroyed */
isDestroyed(): boolean;
/** Get the underlying ProfessionalChart React component instance */
getChartInstance(): ChartInstance | null;
/** Widget façade — prefer over getChartInstance() / Redux */
activeChart(): IChartApi;
chart(index: number): IChartApi;
chartsCount(): number;
activeChartIndex(): number;
setActiveChart(index: number): void;
layout(): string;
setLayout(layout: string): void;
setLayoutSizes(sizes: LayoutSizes, disableUndo?: boolean): void;
resetLayoutSizes(disableUndo?: boolean): void;
unloadUnusedCharts(): void;
applyOverrides(overrides: ApplyOverridesInput): void;
applyStudiesOverrides(overrides: StudiesOverridesMap): void;
applyTradingCustomization(overrides: TradingCustomization): void;
setCSSCustomProperty(name: string, value: string): void;
getCSSCustomPropertyValue(name: string): string;
addCustomCSSFile(url: string): void;
customThemes(): Promise<ICustomThemesApi>;
features(): IFeaturesApi;
setFeatureEnabled(id: ChartFeatureId | string, enabled: boolean): void;
getFeatureEnabled(id: ChartFeatureId | string): boolean;
getFeatures(): FeatureFlags;
headerReady(): Promise<void>;
createButton(options?: CreateButtonOptions): HTMLButtonElement;
createDropdown(options: CreateDropdownOptions): Promise<IDropdownApi>;
removeButton(button: HTMLElement | string): void;
onShortcut(shortcut: ShortcutInput, callback: () => void): () => void;
onContextMenu(callback: ContextMenuCallback): void;
closePopupsAndDialogs(): void;
showConfirmDialog(
titleOrParams: string | ConfirmDialogParams,
content?: string | string[] | ((confirmed: boolean) => void),
callbackOrOk?: ((confirmed: boolean) => void) | string,
optionsOrCancel?: { okText?: string; cancelText?: string } | string,
): Promise<boolean>;
showNoticeDialog(
titleOrParams: string | NoticeDialogParams,
content?: string | string[],
callback?: () => void,
): Promise<void>;
selectLineTool(linetool: string): void;
selectedLineTool(): string;
hideAllDrawingTools(): ISyncApi;
lockAllDrawingTools(): ISyncApi;
magnetEnabled(): ISyncApi;
magnetMode(): INumberSyncApi;
takeClientScreenshot(options?: ClientSnapshotOptions): Promise<HTMLCanvasElement>;
takeScreenshot(): Promise<string>;
clearUndoHistory(): void;
undoRedoState(): UndoRedoState;
resetCache(): void;
getStudiesList(): string[];
getStudyInputs(studyName: string): StudyInputInformation[];
getStudyStyles(studyName: string): StudyStyleInfo;
supportedChartTypes(): string[];
getIntervals(): string[];
symbolInterval(): SymbolIntervalResult | null;
mainSeriesPriceFormatter(): PriceFormatter;
currencyAndUnitVisibility(): IVisibilityApi;
customSymbolStatus(): ICustomSymbolStatusApi;
navigationButtonsVisibility(): IVisibilityWatchedValue;
paneButtonsVisibility(): IVisibilityWatchedValue;
dateFormat(): IStringWatchedValue;
timeHoursFormat(): IStringWatchedValue;
symbolSync(): ISyncApi;
intervalSync(): ISyncApi;
drawOnAllChartsEnabled(): ISyncApi;
crosshairSync(): ISyncApi;
dateRangeSync(): ISyncApi;
timeSync(): ISyncApi;
subscribe(event: WidgetSubscribeEvent, callback: WidgetSubscribeCallback): void;
unsubscribe(event: WidgetSubscribeEvent, callback: WidgetSubscribeCallback): void;
getAllCharts(): MultiChartInfo;
};Widget / IChartApi types (Phase 0–1E)
Types for activeChart() / chart(index) and related façade payloads. Fields use GoCharting shapes. See the Chart API — Widget façade.
type WidgetSubscribeEvent =
| "activeChartChanged"
| "layout"
| "onTick"
| string;
type WidgetSubscribeCallback = (payload: any) => void;
/** Cross-chart sync controller — `symbolSync()` / `intervalSync()` / `drawOnAllChartsEnabled()` / `crosshairSync()` / `dateRangeSync()` / `timeSync()` */
type ISyncApi = {
value(): boolean;
setValue(value: boolean): void;
subscribe(callback: (value: boolean) => void): () => void;
};
/** Multi-chart pane sizes as percentages (P2-2) */
type LayoutSizes = {
rows?: number[];
columns?: number[];
};
/** Chart appearance override (P3-1) — bare appearance or `{ appearance }` */
type ApplyOverridesInput =
| Record<string, any>
| { appearance: Record<string, any>; [key: string]: any };
/** Studies overrides keyed by indicator type (P3-1) */
type StudiesOverridesMap = Record<
string,
| Record<string, any>
| { appearance?: Record<string, any>; options?: Record<string, any> }
>;
/** Root `trading` prefs merge (P3-1) */
type TradingCustomization = Record<string, any>;
/** CSS custom property token map (P3-2) */
type CustomThemeTokens = Record<string, string>;
type CustomThemesInput =
| CustomThemeTokens
| { light?: CustomThemeTokens; dark?: CustomThemeTokens };
type ICustomThemesApi = {
applyCustomThemes(themes: CustomThemesInput): void;
resetCustomThemes(): void;
getCustomThemes(): CustomThemesInput | null;
};
/** Runtime chrome feature ids (P3-3) */
type ChartFeatureId =
| "topBar"
| "bottomBar"
| "drawingToolbar"
| "leftPanel"
| "rightPanel"
| "symbolSearch"
| "compare";
type FeatureFlags = Record<ChartFeatureId, boolean>;
type IFeaturesApi = {
value(): FeatureFlags;
setValue(partial: Partial<FeatureFlags>): void;
subscribe(callback: (value: FeatureFlags) => void): () => void;
};
/** Header custom controls (P3-4) */
type HeaderAlign = "left" | "right";
type CreateButtonOptions = {
align?: HeaderAlign;
useCompactStyle?: boolean;
/** @deprecated Use `useCompactStyle` */
useTradingViewStyle?: boolean;
text?: string;
title?: string;
onClick?: () => void;
};
type DropdownItem = { title: string; onSelect: () => void };
type CreateDropdownOptions = {
title: string;
tooltip?: string;
icon?: string;
items: DropdownItem[];
align?: HeaderAlign;
};
type IDropdownApi = {
applyOptions(options: Partial<CreateDropdownOptions>): void;
remove(): void;
};
/** Keyboard / context menu (P3-5) */
type ShortcutInput = string | Array<string | number>;
type ContextMenuItemPosition = "top" | "bottom";
type ContextMenuItem = {
position?: ContextMenuItemPosition;
/** `"-"` separator; `"-Label"` hide matching built-in */
text: string;
click?: () => void;
};
type ContextMenuCallback = (
unixtime: number,
price: number,
) => ContextMenuItem[] | void;
/** Dialogs (P3-6) */
type NoticeDialogParams = {
title: string;
body?: string;
callback?: () => void;
};
type ConfirmDialogParams = {
title: string;
body?: string;
callback?: (confirmed: boolean) => void;
okText?: string;
cancelText?: string;
};
/** Numeric watched value (P3-7 magnetMode: 0 off / 1 on) */
type INumberSyncApi = {
value(): number;
setValue(value: number): void;
subscribe(callback: (value: number) => void): () => void;
};
/** Options for takeClientScreenshot (P3-8) */
type ClientSnapshotOptions = {
backgroundColor?: string;
includeCrosshair?: boolean;
hideStudiesFromLegend?: boolean;
};
/** Undo/redo snapshot (P3-9 / TV UndoRedoState) */
type UndoRedoState = {
enableUndo: boolean;
enableRedo: boolean;
undoText: string;
redoText: string;
originalUndoText: string;
originalRedoText: string;
};
/** Study input descriptor (P3-10 / TV StudyInputInformation) */
type StudyInputInformation = {
id: string;
name: string;
type: string;
localizedName: string;
};
/** Study style metadata (P3-10 / TV StudyStyleInfo subset) */
type StudyStyleInfo = {
plots?: { id: string; type: string }[];
styles?: Record<string, { title: string }>;
defaults?: { styles?: Record<string, any> };
};
/** Active symbol + interval (P3-11 / TV SymbolIntervalResult) */
type SymbolIntervalResult = {
symbol: string;
interval: string;
};
/** Number formatter (P3-12 / TV INumberFormatter) */
type PriceFormatter = {
format: (price: number) => string;
};
/** Price-scale currency/unit visibility (P3-12) */
type CurrencyUnitVisibility =
| "alwaysOn"
| "alwaysOff"
| "visibleOnMouseOver";
type IVisibilityApi = {
value(): CurrencyUnitVisibility;
setValue(value: CurrencyUnitVisibility): void;
subscribe(callback: (value: CurrencyUnitVisibility) => void): () => void;
};
type ICustomSymbolStatusApi = {
symbol(symbolId: string): ICustomSymbolStatusAdapter;
hideAll(): void;
getAll(): Record<string, CustomSymbolStatusState>;
};
/** Watched visibility (P3-13 nav/pane buttons) */
type IVisibilityWatchedValue = {
value(): CurrencyUnitVisibility;
setValue(value: CurrencyUnitVisibility): void;
subscribe(callback: (value: CurrencyUnitVisibility) => void): () => void;
};
/** Watched string (P3-13 dateFormat / timeHoursFormat) */
type IStringWatchedValue = {
value(): string;
setValue(value: string): void;
subscribe(callback: (value: string) => void): () => void;
};
type MarketStatusInfo = {
isOpen?: boolean;
statusText?: string;
dataStatus?: string;
delaySeconds?: number;
};
/** Visible time range in Unix seconds. */
type VisibleTimeRange = { from: number; to: number };
/** Visible bar indices in loaded data. */
type VisibleBarsRange = { from: number; to: number };
/** Extended symbol info — prefer max_tick_precision / tick_size (not TV pricescale / minmov). */
type SymbolExtInfo = {
symbol: string;
full_name?: string;
name?: string;
exchange?: string;
segment?: string;
tick_size?: number;
display_tick_size?: number;
max_tick_precision?: number;
max_volume_precision?: number;
data_status?: string;
delay_seconds?: number;
supported_resolutions?: string[];
[key: string]: unknown;
};
/** Pane from config.charts / chartOrder — GC id/idx (not TV paneIndex). */
type ChartPaneInfo = {
idx: number;
id: string;
heightFraction: number;
label?: string;
type?: string;
visible?: boolean;
};
type ExportedSeriesData = {
schema: Array<{ name: string; type: string }>;
data: Array<Record<string, number | string | null>>;
};
type TimeFrameInput =
| string
| { from: number; to: number }
| { type: "period-back"; value: string }
| { type: "time-range"; from: number; to: number };
/** Create/input payload for drawings — GoCharting fields only. */
type CreateShapeInput = {
type?: string;
name?: string;
shape?: Record<string, any>;
options?: DrawingOptions;
appearance?: DrawingAppearance;
chartId?: string;
visible?: boolean;
[key: string]: unknown;
};
type ShapeInfo = {
id: string;
chartId: string;
kind: string;
type?: string;
name?: string;
shape?: Record<string, any>;
options?: DrawingOptions;
appearance?: DrawingAppearance;
visible?: boolean;
zIndex?: number;
groupId?: string | null;
[key: string]: unknown;
};
type ObjectGroupInfo = {
id: string;
objectIds: string[];
zIndex?: number;
visible?: boolean;
lock?: boolean;
label?: string;
[key: string]: unknown;
};
type LineToolsPaneState = {
objects: Record<string, ShapeInfo>;
objectGroups?: Record<string, ObjectGroupInfo>;
};
type LineToolsState = {
charts: Record<string, LineToolsPaneState>;
};
type ZOrderOperations = {
bringToFront: boolean;
bringForward: boolean;
sendToBack: boolean;
sendBackward: boolean;
};
type ShapeSelection = {
chartId: string;
objectId: string;
selectedPart?: unknown;
} | null;
type ShapesGroupController = {
createGroup(objectIds: string[], chartId?: string): string;
ungroup(groupId: string, chartId?: string): void;
getGroups(chartId?: string): ObjectGroupInfo[];
};
/** Per-chart API from widget.activeChart() / widget.chart(index). */
type IChartApi = {
// Phase 0
chartIndex(): number;
symbol(): string | null;
symbolExt(): SymbolExtInfo | null;
interval(): string | null;
resolution(): string | null;
chartType(): string | null;
symbolInterval(): { symbol: string; interval: string } | null;
setSymbol(symbol: string): void;
setInterval(interval: string): void;
setResolution(interval: string): void;
setChartType(chartType: string): void;
addIndicator(indicator: { type?: string; id?: string }): void;
addDrawing(drawing: CreateShapeInput, chartId?: string): void;
deleteObject(objectId: string, chartId?: string): void;
updateSettings(settings: Partial<ChartSettings>): void;
getChartState(): ChartState | null;
setChartState(newState: ChartState): void;
// Phase 1A
getVisibleRange(): VisibleTimeRange | null;
setVisibleRange(range: VisibleTimeRange): void;
getVisibleBarsRange(): VisibleBarsRange | null;
goToDate(date: string | Date | { date1: any; date2: any }): void;
setTimeFrame(timeframe: TimeFrameInput): void;
zoomOut(): void;
canZoomOut(): boolean;
resetData(): void; // viewport/scale reset — not a datafeed refetch
exportData(options?: {
includeVolume?: boolean;
useFullData?: boolean;
}): ExportedSeriesData | null;
getPanes(): ChartPaneInfo[];
getAllPanesHeight(): number[];
getTimeScale(): {
getVisibleRange: () => VisibleTimeRange | null;
barSpacing: () => number | null;
};
getSeries(): { id: string; type: string; title?: string } | null;
priceFormatter(): { format: (price: number) => string };
maximizeChart(): void;
isMaximized(): boolean;
marketStatus(): MarketStatusInfo | null;
inactivityGaps(): boolean;
// Phase 1B
createShape(drawing: CreateShapeInput): string;
createMultipointShape(drawing: CreateShapeInput): string;
createAnchoredShape(drawing: CreateShapeInput): string;
getAllShapes(chartId?: string): ShapeInfo[];
getShapeById(objectId: string, chartId?: string): ShapeInfo | null;
removeEntity(objectId: string, chartId?: string): void;
removeAllShapes(chartId?: string): void;
getLineToolsState(): LineToolsState;
applyLineToolsState(state: LineToolsState): void;
reloadLineToolsFromServer(): void; // stub until Phase 5 — throws
bringToFront(objectId: string, chartId?: string): void;
bringForward(objectId: string, chartId?: string): void;
sendToBack(objectId: string, chartId?: string): void;
sendBackward(objectId: string, chartId?: string): void;
availableZOrderOperations(objectId: string, chartId?: string): ZOrderOperations;
selection(): ShapeSelection;
showPropertiesDialog(objectId?: string, chartId?: string): void;
shapesGroupController(): ShapesGroupController;
// Phase 1C — studies
getAllStudies(chartId?: string): StudyInfo[];
getStudyById(objectId: string, chartId?: string): StudyInfo | null;
removeAllStudies(): void;
createStudyTemplate(nameOrOptions?: string | { name?: string; save?: boolean }): StudyTemplate;
applyStudyTemplate(template: StudyTemplate | { indicators?: StudyTemplateItem[] }): void;
loadChartTemplate(
template: string | StudyTemplate | ChartState | Record<string, any>,
): void;
// Phase 1D — library-native trading lines (not Broker API)
createOrderLine(): IOrderLineApi;
createPositionLine(): IPositionLineApi;
createExecutionShape(): IExecutionShapeApi;
// Phase 1E — chart events + actions
onSymbolChanged(): ISubscription<void>;
onIntervalChanged(): ISubscription<void>;
onChartTypeChanged(): ISubscription<void>;
onDataLoaded(): ISubscription<void>;
onVisibleRangeChanged(): ISubscription<{ from: number; to: number }>;
crossHairMoved(): ISubscription<CrossHairMovedEvent>;
onHoveredSourceChanged(): ISubscription<HoveredSourceEvent>;
dataReady(callback: () => void): void;
executeActionById(actionId: ChartActionId | string): void;
requestSelectBar(): Promise<SelectBarResult>;
cancelSelectBar(): void;
};
type ISubscription<T = void> = {
subscribe(callback: (value: T) => void): () => void;
unsubscribe(callback?: (value: T) => void): void;
};
type CrossHairMovedEvent = {
time: number | null;
price: number | null;
};
type HoveredSourceEvent = {
entityId: string | null;
chartId?: string;
type?: string;
} | null;
type SelectBarResult = {
index: number;
time: number;
};
type ChartActionId =
| "chartReset"
| "zoomIn"
| "zoomOut"
| "undo"
| "redo"
| "invertScale"
| "logScale"
| "magnet";
type ExecutionDirection = "buy" | "sell";
/** Fluent order-line stub — see Chart API Phase 1D */
type IOrderLineApi = {
remove(): void;
getPrice(): number;
setPrice(price: number): IOrderLineApi;
getText(): string;
setText(text: string): IOrderLineApi;
getQuantity(): string;
setQuantity(value: string | number): IOrderLineApi;
getTooltip(): string;
setTooltip(text: string): IOrderLineApi;
onModify(callback: () => void): IOrderLineApi;
onMove(callback: () => void): IOrderLineApi;
onCancel(callback: () => void): IOrderLineApi;
};
/** Fluent position-line stub — see Chart API Phase 1D */
type IPositionLineApi = {
remove(): void;
getPrice(): number;
setPrice(price: number): IPositionLineApi;
getText(): string;
setText(text: string): IPositionLineApi;
getQuantity(): string;
setQuantity(value: string | number): IPositionLineApi;
getTooltip(): string;
setTooltip(text: string): IPositionLineApi;
onClose(callback: () => void): IPositionLineApi;
onReverse(callback: () => void): IPositionLineApi;
onModify(callback: () => void): IPositionLineApi;
};
/** Fluent execution-shape stub — see Chart API Phase 1D */
type IExecutionShapeApi = {
remove(): void;
getPrice(): number;
setPrice(price: number): IExecutionShapeApi;
getTime(): number;
setTime(time: number): IExecutionShapeApi;
getDirection(): ExecutionDirection;
setDirection(direction: ExecutionDirection): IExecutionShapeApi;
getText(): string;
setText(text: string): IExecutionShapeApi;
getTooltip(): string;
setTooltip(text: string): IExecutionShapeApi;
};
type StudyInfo = {
id: string;
chartId: string;
kind: string;
type?: string;
name?: string;
options?: Record<string, any>;
appearance?: Record<string, any>;
visible?: boolean;
zIndex?: number;
};
type StudyTemplateItem = {
type: string;
name?: string;
options?: Record<string, any>;
appearance?: Record<string, any>;
};
type StudyTemplate = {
id?: string | number;
name?: string;
indicators: StudyTemplateItem[];
createdAt?: string;
};
### ChartTheme
```typescript
type ChartTheme = "light" | "dark";ChartConfig
Options for createChart() / <GoCharting />. See also Configuration API.
type ChartConfig = {
// Required
datafeed: Datafeed;
symbol: string;
interval: string;
licenseKey: string;
// Display
theme?: ChartTheme;
/** Hex background (e.g. "#22292f"); not "light"/"dark" */
themeColor?: string;
autosize?: boolean;
width?: number | string;
height?: number | string;
locale?: string;
// Chrome flags
debugLog?: boolean;
skipLicenseValidation?: boolean;
disableSearch?: boolean;
disableCompare?: boolean;
hideDrawingToolBar?: boolean;
alwaysDrawMode?: boolean;
showCrosshairPlusIcon?: boolean;
touchMode?: boolean;
isNativeApp?: boolean;
// Construct-time features (Phase 4)
disabled_features?: string[];
enabled_features?: string[];
overrides?: Record<string, any>;
studies_overrides?: Record<string, any>;
settings_overrides?: Record<string, any>;
custom_css_url?: string;
custom_themes?: Record<string, any>;
timezone?: string;
toolbar_bg?: string;
time_frames?: Array<string | Record<string, any>>;
timeframe?: string | Record<string, any>;
favorites?: Record<string, any>;
// Persistence (Phase 5)
autoSave?: boolean;
auto_save_delay?: number;
save_load_adapter?: Record<string, any>;
image_storage_adapter?: Record<string, any>;
load_last_chart?: boolean;
saved_data?: Record<string, any> | string;
snapshot_url?: string;
client_id?: string;
user_id?: string;
// Nested configs
defaultInitialChartConfig?: DefaultInitialChartConfig;
trading?: TradingConfig;
contextMenu?: ContextMenuOptions;
context_menu?: ContextMenuOptions;
popups?: PopupsConfig;
favourite?: FavouriteConfig;
exclude?: ExcludeOptions;
// Callbacks
appCallback?: AppCallbackEventHandler;
onReady?: OnReadyEventHandler;
onError?: OnErrorEventHandler;
};ExcludeOptions
type ExcludeOptions = {
leftPanel?: boolean;
rightPanel?: boolean;
topBar?: boolean;
bottomBar?: boolean;
/** Same effect as `hideDrawingToolBar` */
drawingToolbar?: boolean;
/** e.g. `["SMA", "EMA", "RSI"]` */
indicators?: string[];
};TradingConfig
type TradingConfig = {
enableTrading?: boolean;
showReverseButton?: boolean;
showOpenOrders?: boolean;
showPositions?: boolean;
showExecutions?: boolean;
showNotifications?: boolean;
beep?: boolean;
quickTradeMode?: boolean;
supportStopOrders?: boolean;
supportStopLimitOrders?: boolean;
enableTakeProfitDefaults?: boolean;
defaultTakeProfitSpread?: number;
defaultTakeProfitSpreadType?: "tick" | "price" | "percent";
enableStopLossDefaults?: boolean;
defaultStopLossSpread?: number;
defaultStopLossSpreadType?: "tick" | "price" | "percent";
boxAlignment?: "left" | "right";
lineCategory?: "extended" | "compact";
};DefaultInitialChartConfig
type DefaultInitialChartConfig = {
settings?: ChartSettingsConfig;
appearance?: ChartAppearanceConfig;
};ContextMenuOptions
type ContextMenuOptions = {
showTradingOptions?: boolean;
};PopupsConfig
Panel state overrides keyed by panel id (TradingPanel, Settings, Layers, …). Not welcome/tutorial dialogs.
type PopupPanelState = {
visible?: boolean;
x?: number;
y?: number;
height?: number;
width?: number;
title?: string;
[key: string]: any;
};
type PopupsConfig = Record<string, PopupPanelState>;FavouriteConfig
type FavouriteConfig = {
INTERVALS?: string[];
DRAWINGS?: string[];
INDICATOR?: string[];
CHARTTYPES?: string[];
TEMPLATES?: Array<{
id: number;
name: string;
indicators: IndicatorTemplateItem[];
}>;
[key: string]: any;
};Datafeed Types
/**
* Period parameters for historical data requests
* Note: At runtime, the SDK passes Date objects for from/to, not numbers
*/
type PeriodParams = {
/** Start time (Date object) */
from: Date;
/** End time (Date object) */
to: Date;
/** Whether this is the first data request */
firstDataRequest: boolean;
/** Number of bars to fetch (optional) */
countBack?: number;
/** Number of rows to fetch (optional) */
rows?: number;
/**
* Duration string when duration buttons are clicked (optional)
* When provided, from/to dates are calculated based on this duration.
* Use this to identify which duration button was clicked.
*/
duration?: DurationString;
};
/**
* Result from getBars method (simple format with bars array)
*/
type BarsResult = {
/** Array of bar data */
bars: Bar[];
/** Optional metadata */
meta?: {
/** Indicates no data available */
noData?: boolean;
/** Next available data time */
nextTime?: number;
};
};
/**
* UDF (Universal Data Feed) format response
* UDF-compatible response format used by many datafeeds
*/
type UDFResponse = {
/** Status: "ok", "error", or "no_data" */
s: "ok" | "error" | "no_data";
/** Error message (when s === "error") */
errmsg?: string;
/** Next available time (when s === "no_data") */
nextTime?: number | null;
/** Time array (Unix timestamps in seconds) */
t?: number[];
/** Open prices array */
o?: number[];
/** High prices array */
h?: number[];
/** Low prices array */
l?: number[];
/** Close prices array */
c?: number[];
/** Volume array */
v?: number[];
};
/**
* Resolution/Interval object
*/
type Resolution = {
/** Scale value (e.g., 1, 5, 15) */
scale: number;
/** Time unit (e.g., "m", "h", "D", "W", "M") */
units: string;
/** Original interval string (e.g., "1m", "5m", "15m", "30m", "1h", "4h", "1D", "1W", "1M") - set internally by SDK */
type?: string;
};
/**
* Datafeed type - implement this to provide data to the chart
* This is a simple object type, no class inheritance required
*
* REQUIRED METHODS: getBars, resolveSymbol
* OPTIONAL METHODS: searchSymbols, searchSymbolsPaginated, subscribeTicks, unsubscribeTicks,
* subscribeBars, unsubscribeBars, getMarks, getTimescaleMarks, destroy
*
* Realtime exclusivity: implement either subscribeTicks/unsubscribeTicks OR
* subscribeBars/unsubscribeBars — not both. If both are present, the SDK prefers
* ticks, warns, and ignores bars.
*/
type DatafeedConfiguration = {
exchanges?: Array<{ value: string; name: string; desc?: string }>;
symbols_types?: Array<{ name: string; value: string }>;
supported_resolutions?: string[];
supports_search?: boolean;
supports_group_request?: boolean;
supports_marks?: boolean;
supports_timescale_marks?: boolean;
supports_time?: boolean;
currency_codes?: string[];
units?: Array<{ id: string; name: string; description?: string }>;
};
type Datafeed = {
// ========================================================================
// REQUIRED METHODS
// ========================================================================
/**
* Fetch historical bar data (REQUIRED)
*
* Can return either:
* - BarsResult format: { bars: Bar[], meta?: {...} }
* - UDF format: { s: "ok", t: [...], o: [...], h: [...], l: [...], c: [...], v: [...] }
*
* @param symbolInfo - Symbol information
* @param resolution - Time interval (can be string or Resolution object)
* @param periodParams - Time period parameters
* @returns Promise resolving to bars result in either BarsResult or UDF format
*/
getBars(
symbolInfo: SymbolInfo,
resolution: string | Resolution,
periodParams: PeriodParams
): Promise<BarsResult | UDFResponse>;
/**
* Resolve symbol information (REQUIRED)
* @param symbolName - Symbol name to resolve
* @param onResolve - Callback with resolved symbol info
* @param onError - Error callback
*/
resolveSymbol(
symbolName: string,
onResolve: (symbolInfo: SymbolInfo) => void,
onError: (error: string) => void
): void;
// ========================================================================
// OPTIONAL METHODS
// ========================================================================
/**
* Datafeed configuration handshake (OPTIONAL, TV onReady).
* Pass DatafeedConfiguration to the callback (prefer asynchronously).
*/
onReady?(callback: (configuration: DatafeedConfiguration) => void): void;
/**
* Search for symbols (OPTIONAL)
* Implement this to enable symbol search functionality in the chart
* If not implemented, symbol search will be disabled
*
* @param userInput - User search query
* @param exchange - Exchange filter (can be empty string)
* @param symbolType - Symbol type filter (can be empty string)
* @param onResultReadyCallback - Callback with search results
*/
searchSymbols?(
userInput: string,
exchange: string,
symbolType: string,
onResultReadyCallback: (result: {
searchInProgress: boolean;
items: SearchResult[];
}) => void
): void;
/**
* Subscribe to real-time ticks (OPTIONAL)
* Implement this to provide real-time data updates to the chart
*
* The callback can receive:
* - Bar objects (OHLCV data)
* - Tick objects (Bar with change/changePercent)
*
* @param symbolInfo - Symbol information
* @param resolution - Time interval
* @param onRealtimeCallback - Callback to receive real-time updates (Bar or Tick)
* @param subscriberUID - Unique identifier for this subscription
* @param onResetCacheNeededCallback - Callback when cache needs to be reset
*/
subscribeTicks?(
symbolInfo: SymbolInfo,
resolution: string | Resolution,
onRealtimeCallback: (data: Bar | Tick | TradeMessage) => void,
subscriberUID: string,
onResetCacheNeededCallback?: () => void
): void;
/**
* Unsubscribe from real-time ticks (OPTIONAL)
* @param subscriberUID - Unique identifier of the subscription to cancel
*/
unsubscribeTicks?(subscriberUID: string): void;
searchSymbolsPaginated?(
options: {
userInput: string;
exchange: string;
symbolType: string;
limit: number;
offset: number;
},
onResult: (
result:
| SearchResult[]
| { searchInProgress: boolean; items: SearchResult[] }
) => void
): void;
/**
* Subscribe to real-time bars (OPTIONAL)
* Host pushes complete OHLCV; SDK does not aggregate ticks.
* Mutually exclusive with subscribeTicks — if both exist, ticks win.
*/
subscribeBars?(
symbolInfo: SymbolInfo,
resolution: string | Resolution,
onRealtimeCallback: (bar: Bar) => void,
subscriberUID: string,
onResetCacheNeededCallback?: () => void
): void;
unsubscribeBars?(subscriberUID: string): void;
/**
* Cleanup method called when chart is destroyed (OPTIONAL)
* Use this to clean up resources like:
* - Active WebSocket connections
* - Pending HTTP requests (AbortController)
* - Intervals and timeouts
* - Cached data
*/
destroy?(): void;
};Symbol and Market Data Types
Symbol Naming Convention
Symbol names must NOT contain special characters such as /, \, :, *, ?, ", <, >, or |.
Examples:
EUR/USD- Invalid (contains/)EURUSD- ValidBTC/USDT- Invalid (contains/)
BTCUSDT- Valid
The symbol field should contain only alphanumeric characters. Use the name or description field for human-readable display names that may include special characters.
/**
* Symbol information object
* Contains all metadata about a trading symbol.
* This is returned from the datafeed's resolveSymbol method.
*/
type SymbolInfo = {
// ========================================================================
// Required Symbol Information
// ========================================================================
/** Trading symbol (e.g., "BTCUSDT", "AAPL") — avoid `/`, `:`, and other path-unsafe chars */
symbol: string;
/** Full symbol name with exchange (e.g., "BYBIT:FUTURE:BTCUSDT") */
full_name: string;
/** Display name (e.g., "BTC / USDT PERPETUAL FUTURES") — preferred UI title */
name?: string;
/** Human-readable description (often same as `name`) */
description: string;
/** Exchange name (e.g., "BYBIT", "NASDAQ") */
exchange: string;
/** Symbol type (e.g., "crypto", "stock", "futures") */
type: string;
/** Trading session (e.g., "24x7", "0930-1600") */
session: string;
/** Timezone (e.g., "Etc/UTC", "America/New_York") */
timezone: string;
/** Ticker symbol (usually same as symbol) */
ticker: string;
/** Supports intraday data */
has_intraday: boolean;
/** Supported time intervals/resolutions (e.g., ["1", "5", "15", "60", "1D"]) */
supported_resolutions: string[];
// ========================================================================
// Optional Symbol Information
// ========================================================================
/** Market segment (e.g., "FUTURE", "SPOT", "OPTION") */
segment?: string;
/** Asset type classification (e.g., "CRYPTO", "EQUITY") */
asset_type?: string;
/** Trading session label */
session_label?: string;
// ========================================================================
// Symbol Pair Information (for crypto/forex)
// ========================================================================
/** Currency pair information */
pair?: SymbolPair;
// ========================================================================
// Trading Information
// ========================================================================
/** Whether symbol is tradeable */
tradeable?: boolean;
/** Whether symbol is an index */
is_index?: boolean;
/** Whether symbol is a formula/calculated */
is_formula?: boolean;
// ========================================================================
// Data Feed Information
// ========================================================================
/** Data delay in seconds (0 for real-time) */
delay_seconds?: number;
/** Data streaming status */
data_status?: DataStatus;
/** Data source location/datacenter */
data_source_location?: string;
// ========================================================================
// Display Information
// ========================================================================
/** Industry classification */
industry?: string;
/** Symbol logo URLs */
symbol_logo_urls?: string[];
// ========================================================================
// Price & Volume Precision
// ========================================================================
/** Contract size (for futures/options) */
contract_size?: number;
/** Minimum price movement (tick size) */
tick_size?: number;
/** Display tick size */
display_tick_size?: number;
/** Minimum volume increment */
volume_size_increment?: number;
/** Maximum decimal places for price */
max_tick_precision?: number;
/** Maximum decimal places for volume */
max_volume_precision?: number;
/** Quote currency */
quote_currency: string;
// ========================================================================
// Futures-specific (if applicable)
// ========================================================================
/** 'PERP' for perpetual, or expiry date for dated futures */
future_type?: string;
// ========================================================================
// Exchange Information
// ========================================================================
/** Exchange information object */
exchange_info?: ExchangeInfo;
// ========================================================================
// Additional Optional Fields
// ========================================================================
/** Supports daily data */
has_daily?: boolean;
/** Intraday multipliers (e.g., ["1", "5", "15", "30", "60", "240"]) */
intraday_multipliers?: string[];
/** Volume decimal places */
volume_precision?: number;
/** Source identifier from exchange */
source_id?: string;
/** Feature flags for this symbol (e.g. footprint eligibility) */
supports?: {
footprint?: boolean;
[key: string]: boolean | undefined;
};
};
/**
* Symbol type classification (legacy compatibility)
*/
type SymbolType =
| "stock"
| "forex"
| "crypto"
| "futures"
| "options"
| "index"
| "bond";
/**
* Asset type classification (modern API format)
*/
type AssetType = "CRYPTO" | "EQUITY" | "FOREX" | "COMMODITY" | "INDEX" | "BOND";
/**
* Data streaming status
*/
type DataStatus = "streaming" | "endofday" | "pulsed" | "delayed_streaming";
/**
* Exchange information object
* Contains metadata about the exchange
*/
type ExchangeInfo = {
/** Exchange name (lowercase) */
name: string;
/** Exchange code (uppercase) */
code: string;
/** Country code */
country_cd?: string;
/** Timezone */
zone: string;
/** Whether exchange provides unique trade IDs */
has_unique_trade_id?: boolean;
/** Exchange logo URL */
logo_url?: string;
/** Array of holiday dates (null if 24/7) */
holidays?: string[] | null;
/** Trading hours for each day (0=Sunday, 6=Saturday) */
hours?: Array<{ open: boolean }>;
/** Whether exchange has ambiguous symbol names */
contains_ambiguous_symbols?: boolean;
/** Supported timeframes */
valid_intervals?: string[];
};
/**
* Symbol pair information (for crypto/forex)
*/
type SymbolPair = {
/** Base currency (e.g., "BTC") */
from: string;
/** Quote currency (e.g., "USDT") */
to: string;
};
/**
* Bar/Candle data structure (OHLCV)
*/
type Bar = {
/** Unix timestamp in milliseconds */
time: number;
/** Opening price */
open: number;
/** Highest price */
high: number;
/** Lowest price */
low: number;
/** Closing price */
close: number;
/** Volume */
volume: number;
};
/**
* Real-time tick data (extends Bar with additional fields)
*/
type Tick = Bar & {
/** Price change from previous close */
change?: number;
/** Price change percentage */
changePercent?: number;
};
/**
* Search result for symbol search
*/
type SearchResult = {
/** Symbol name */
symbol: string;
/** Full symbol name with exchange */
full_name: string;
/** Human-readable description */
description: string;
/** Exchange name */
exchange: string;
/** Ticker symbol */
ticker: string;
/** Symbol type */
type: SymbolType;
};Configuration Types
Canonical shapes for createChart options live above under ChartConfig, TradingConfig, ExcludeOptions, PopupsConfig, and FavouriteConfig.
See also the Configuration API guide.
Trading Types
IMPLEMENTED Trading Features
// IMPLEMENTED - Trading events through appCallback
type TradingEventType =
| "CREATE_ORDER" // User initiated order creation
| "PLACE_ORDER" // User confirmed order placement
| "MODIFY_ORDER" // User requested order modification
| "CANCEL_ORDER"; // User requested order cancellation
// IMPLEMENTED - Chart method for updating broker data
interface ChartInstance {
setBrokerAccounts(data: BrokerAccountData): void;
// ... other chart methods
}Trading Data Types
/**
* Order type
*/
type OrderType = "market" | "limit" | "stop" | "stop_limit";
/**
* Order side (buy/sell)
*/
type OrderSide = "buy" | "sell";
/**
* Order status
*/
type OrderStatus =
| "open"
| "pending"
| "filled"
| "cancelled"
| "rejected"
| "expired";
/**
* Time in force
*/
type TimeInForce = "GTC" | "IOC" | "FOK" | "DAY";
/**
* Order task type - distinguishes between order placement and modification
*/
type OrderTask = "placement" | "modify";
/**
* Order update type - specifies the type of modification operation
*/
type OrderUpdateType =
| "DELETE_SL" // Delete stop loss from order
| "DELETE_TP" // Delete take profit from order
| "SHAPE_MODIFY" // Modify order shape (price, TP, SL)
| "STANDARD"; // Standard price/quantity modifications
/**
* Order shape update type - specifies what aspect is being modified
*/
type OrderShapeUpdateType =
| "TAKE_PROFIT" // Modify existing take profit price
| "NEW_TAKE_PROFIT" // Add new take profit (first time)
| "DELETE_TAKE_PROFIT" // Delete take profit from order
| "STOP_LOSS" // Modify existing stop loss price
| "NEW_STOP_LOSS" // Add new stop loss (first time)
| "DELETE_STOP_LOSS" // Delete stop loss from order
| "STOP_PRICE" // Modify stop trigger price
| "LIMIT_PRICE"; // Modify order limit price
/**
* Position update type - specifies the type of position modification
*/
type PositionUpdateType = "SHAPE_MODIFY";
/**
* Position shape update type - specifies what aspect is being modified
*/
type PositionShapeUpdateType =
| "DELETE_STOP_LOSS" // Delete stop loss from position
| "DELETE_TAKE_PROFIT" // Delete take profit from position
| "STOP_LOSS" // Modify existing stop loss price
| "NEW_STOP_LOSS" // Add new stop loss (first time)
| "TAKE_PROFIT" // Modify existing take profit price
| "NEW_TAKE_PROFIT"; // Add new take profit (first time)
/**
* Security information object
*/
type SecurityInfo = {
/** Symbol name */
symbol: string;
/** Exchange name */
exchange: string;
/** Market segment */
segment: string;
/** Minimum price increment */
tick_size: number;
/** Minimum quantity increment */
lot_size: number;
/** Quote currency */
quote_currency: string;
};
/**
* Order interface
*/
type Order = {
// Core Fields
orderId: string; // Unique order ID
symbol: string; // Trading symbol (base symbol name)
side: OrderSide; // Order side (buy/sell)
orderType: OrderType; // Order type
price: number; // Order price
size: number; // Order size/quantity
status: OrderStatus; // Order status
// Additional Required Fields
productId: string; // Full symbol identifier (EXCHANGE:SEGMENT:SYMBOL)
broker: string; // Broker identifier
productType: string; // Product type: "FUTURE" | "SPOT" | "OPTION"
exchange: string; // Exchange name
segment: string; // Market segment
currency: string; // Order currency
key: string; // Unique key (broker-productId-orderId)
isGC: boolean; // GoCharting flag
security: SymbolInfo | SecurityInfo; // Security information
// Optional Fields
timeInForce?: TimeInForce; // Time in force
timestamp?: string; // Order timestamp (ISO string)
datetime?: Date; // Order creation date
timeStamp?: number; // Order timestamp in milliseconds
fillPrice?: number | null; // Fill price (if filled)
avgFillPrice?: number | null; // Average fill price
fillSize?: number; // Filled size
filledSize?: number; // Filled size (alias)
remainingSize?: number; // Remaining unfilled quantity
commission?: number; // Commission/fees
commissions?: number; // Commission amount
lastTradeTimestamp?: number | null; // Last trade timestamp
cost?: number | null; // Order cost
trades?: Trade[]; // Associated trades
fee?: {
// Fee information
currency: string;
cost: number;
rate: number;
};
info?: Record<string, unknown>; // Additional broker-specific information
modifiedAt?: number | null; // Last modification timestamp
takeProfit?: number | null; // Take profit price
stopLoss?: number | null; // Stop loss price
stopPrice?: number | null; // Stop trigger price (for stop orders)
pnlMultiplier?: number; // PnL calculation multiplier (for TP/SL USD calculations)
paperTraderKey?: string | null; // Paper trading key
validity?: string; // Order validity: "DAY", "GTC", etc.
rejReason?: string | null; // Rejection reason
userTag?: string | null; // User-defined tag
showStopLossButton?: boolean; // Whether to show stop loss button in UI
showTakeProfitButton?: boolean; // Whether to show take profit button in UI
// Runtime Modification Fields
task?: OrderTask; // Operation type: "placement" for new orders, "modify" for modifications
update?: OrderUpdateType; // Modification type indicator
updateType?: OrderShapeUpdateType; // Specific update type when update is "SHAPE_MODIFY"
defaultTradeSettings?: TradingConfig; // Default trade settings applied to this order (TP/SL/trailing settings)
exitPosition?: boolean; // Flag indicating this order is closing/exiting an existing position
};
/**
* Trade interface
*/
type Trade = {
/** Unique trade ID */
tradeId: string;
/** Associated order ID */
orderId?: string;
/** Trading symbol */
symbol: string;
/** Trade side */
side: OrderSide;
/** Execution price */
price: number;
/** Trade size (quantity) */
size: number;
/** Trade size (alias for size, used in some contexts) */
tradeSize?: number;
/** Trade value */
value?: number;
/** Commission/fees */
commission?: number;
/** Trade timestamp (ISO string) */
timestamp?: string;
/** Trade creation date */
datetime?: Date;
/** Trade timestamp in milliseconds */
timeStamp?: number;
/** Full symbol identifier (EXCHANGE:SEGMENT:SYMBOL) */
productId?: string;
/** Exchange name */
exchange?: string;
/** Broker identifier */
broker?: string;
/** Product type: "FUTURE" | "SPOT" | "OPTION" */
productType?: string;
/** Trade status */
status?: string;
/** Trade cost (price × quantity) */
cost?: number;
/** Fee information */
fee?: {
currency: string;
cost: number;
rate: number;
};
/** Security information */
security?: SymbolInfo | SecurityInfo;
/** Unique key (broker-productId-tradeId) */
key?: string;
};
/**
* Position interface
*/
type Position = {
// Core Fields
size: number; // Net position size (positive = long, negative = short)
size_currency: number; // Position quantity in base currency
price: number; // Average entry price
amount: number; // Position value (price × quantity)
side: OrderSide; // Position side (buy/sell)
// Identifiers
productId: string; // Full symbol identifier (EXCHANGE:SEGMENT:SYMBOL)
broker: string; // Broker identifier
productType: string; // Product type: "FUTURE" | "SPOT" | "OPTION"
currency: string; // Position currency
id: string; // Position identifier
underlying: string; // Underlying asset identifier
symbol: string; // Base symbol name
segment: string; // Market segment
exchange: string; // Exchange name
key: string; // Unique key (broker-productId-positionId)
isGC: boolean; // GoCharting flag
// P&L Fields
unPnl: number; // Unrealized profit/loss
rPnl: number; // Realized profit/loss
pnl: number; // Total profit/loss
security: SymbolInfo | SecurityInfo; // Security information
// Optional Fields
pnlMultiplier?: number; // PnL calculation multiplier
openPosVal?: number; // Open position value
closedPosVal?: number; // Closed position value
paperTraderKey?: string | null; // Paper trading key
positions?: Record<string, Position>; // Detailed position breakdown (keyed by position ID or symbol)
takeProfit?: number | null; // Take profit level
stopLoss?: number | null; // Stop loss level
trailingSLSpread?: number | null; // Trailing stop loss spread
trailingStopHighestPnL?: number | null; // Highest PnL for trailing stop
showStopLossButton?: boolean; // Whether to show stop loss button in UI
showTakeProfitButton?: boolean; // Whether to show take profit button in UI
// Runtime Modification Fields
update?: PositionUpdateType; // Modification type indicator (always "SHAPE_MODIFY" for positions)
updateType?: PositionShapeUpdateType; // Specific update type when modifying position TP/SL
};
/**
* Account interface
*/
type Account = {
/** Account ID */
id: string;
/** Account name */
name: string;
/** Account balance */
balance: number;
/** Currency */
currency: string;
/** Broker name */
broker?: string;
/** Leverage */
leverage?: number;
/** Margin used */
marginUsed?: number;
/** Available margin */
marginAvailable?: number;
};
/**
* Broker account data structure
*/
type BrokerAccountData = {
/** List of accounts */
accountList: Account[];
/** Order book */
orderBook: Order[];
/** Trade book */
tradeBook: Trade[];
/** Open positions */
positions: Position[];
};App Callback Types
Event Types
/**
* Application callback event types
* Includes trading events, data events, and UI events
*/
type AppCallbackEventType =
// Trading events
| "CREATE_ORDER"
| "PLACE_ORDER"
| "EDIT_ORDER"
| "PLACE_ORDER_DIRECT"
| "MODIFY_POSITION"
| "MODIFY_ORDER_DIRECT"
| "MODIFY_ORDER"
| "CANCEL_ORDER"
| "CLOSE_POSITION"
| "EXIT_ALL_POSITIONS"
| "CANCEL_ALL_ORDERS"
// Data events
| "DOWNLOAD_MORE_DATA_BY_DATE"
| "DOWNLOAD_MORE_DATA"
// UI events
| "OPEN_SETTINGS"
| "OPEN_TRADING_WIDGET"
| "OPEN_CONTEXT_MENU"
// Chart events
| "CHART_SELECTED"
| "CHART_MODE_CHANGED";
/**
* Event handler types
*/
/**
* Single event object for appCallback
* Combines eventType, message, and onClose into a discriminated union
*/
type AppCallbackEvent = {
[K in AppCallbackEventType]: {
eventType: K;
message: AppCallbackEventMap[K];
onClose?: () => void;
};
}[AppCallbackEventType];
/**
* App callback handler type - receives single event object
* Use this type when you need to handle events in a switch statement.
* The message type is automatically narrowed based on eventType in switch cases.
*/
type AppCallbackEventHandler = (event: AppCallbackEvent) => void;
/**
* Maps each AppCallbackEventType to its corresponding message type
* Used for type-safe event handling in appCallback
*/
interface AppCallbackEventMap {
// Trading events
CREATE_ORDER: CreateOrderMessage;
PLACE_ORDER: PlaceOrderMessage;
PLACE_BASKET_ORDER: PlaceOrderMessage;
EDIT_ORDER: ModifyOrderMessage;
PLACE_ORDER_DIRECT: PlaceOrderMessage;
MODIFY_POSITION: ModifyPositionMessage;
MODIFY_ORDER_DIRECT: ModifyOrderMessage;
MODIFY_ORDER: ModifyOrderMessage;
CANCEL_ORDER: CancelOrderMessage;
CLOSE_POSITION: ClosePositionMessage;
EXIT_ALL_POSITIONS: Position;
CANCEL_ALL_ORDERS: Order;
GET_ACCOUNT_SUMMARY: Account;
CONNECT_BROKER: Account;
// Alert events
CREATE_ALERT: AlertMessage;
DELETE_ALERT: AlertMessage;
MODIFY_ALERT: AlertMessage;
// Data events
DOWNLOAD_MORE_DATA_BY_DATE: DownloadDataMessage;
DOWNLOAD_MORE_DATA: DownloadDataMessage;
// UI events
OPEN_SETTINGS: UIEventMessage;
OPEN_LAYERS: UIEventMessage;
OPEN_OBJECT_PROPERTIES: UIEventMessage;
OPEN_INDICATORS_MODAL: UIEventMessage;
OPEN_TRADING_WIDGET: UIEventMessage;
// Chart events
CHART_SELECTED: ChartSelectedMessage;
CHART_MODE_CHANGED: MultiChartInfo;
}
type OnReadyEventHandler = (chartInstance: ChartInstance) => void;
type OnErrorEventHandler = (error: Error | ChartError | string) => void;
type OnSymbolChangeEventHandler = (symbolInfo: SymbolInfo) => void;
type OnIntervalChangeEventHandler = (interval: string) => void;Message Types
Each event type has a corresponding message type. The AppCallbackEventHandler automatically narrows the message type based on the eventType parameter.
/**
* Order placement message (PLACE_ORDER, PLACE_BASKET_ORDER, PLACE_ORDER_DIRECT)
* @example
* {
* order: { side: "buy", orderType: "limit", price: 50000, size: 0.1 },
* security: { symbol: "BTCUSDT", exchange: "BYBIT", segment: "FUTURE" },
* ltp: 50100
* }
*/
type PlaceOrderMessage = {
order: Partial<Order>;
security?: SymbolInfo | SecurityInfo;
ltp?: number;
stateParams?: Record<string, unknown>;
};
/**
* Order modification message (MODIFY_ORDER, EDIT_ORDER, MODIFY_ORDER_DIRECT)
* @example
* {
* orderId: "ORDER_001",
* order: { price: 51000, stopLoss: 49500, task: "modify", update: "SHAPE_MODIFY" },
* security: { symbol: "BTCUSDT", exchange: "BYBIT", segment: "FUTURE" }
* }
*/
type ModifyOrderMessage = {
orderId: string;
order: Partial<Order>;
security?: SymbolInfo | SecurityInfo;
};
/**
* Cancel order message (CANCEL_ORDER)
* @example
* { order: { orderId: "ORDER_001", symbol: "BTCUSDT" } }
*/
type CancelOrderMessage = {
order: Partial<Order>;
};
/**
* Position modification message (MODIFY_POSITION)
* The position object contains both the position data and modification details
* via the update/updateType fields.
* @example
* {
* position: {
* id: "POS_001",
* symbol: "BTCUSDT",
* size: 0.5,
* stopLoss: 47000,
* update: "SHAPE_MODIFY",
* updateType: "NEW_STOP_LOSS"
* }
* }
*/
type ModifyPositionMessage = {
position: Position;
id?: string;
};
/**
* Alert message (CREATE_ALERT, DELETE_ALERT, MODIFY_ALERT)
* @example
* { alert: { symbol: "BTCUSDT", price: 55000, condition: "above", message: "BTC above 55k!" } }
*/
type AlertMessage = {
alert: {
symbol: string;
price: number;
condition: "above" | "below" | "cross";
message?: string;
};
};
/**
* Download data message (DOWNLOAD_MORE_DATA, DOWNLOAD_MORE_DATA_BY_DATE)
* @example
* { params: [1704067200, 1704153600], store: { getState: () => ({ security, interval }) } }
*/
type DownloadDataMessage = {
params: [number, number] | [number, number, unknown];
store?: { getState: () => Record<string, unknown> };
};
/**
* UI event message (OPEN_SETTINGS, OPEN_LAYERS, OPEN_OBJECT_PROPERTIES, OPEN_INDICATORS_MODAL, OPEN_TRADING_WIDGET)
* @example
* { chartId: "MAIN_CHART", objectId: "drawing_123", defaultTab: "style" }
*/
type UIEventMessage = {
chartId?: string;
objectId?: string;
defaultTab?: string;
};
/**
* Create order message (CREATE_ORDER)
* Received when user initiates order creation from chart UI
* @example
* { side: "buy", quantity: 1, price: 50000, symbol: "BTCUSDT" }
*/
type CreateOrderMessage = {
side?: OrderSide;
quantity?: number;
price?: number;
symbol?: string;
security?: SymbolInfo | SecurityInfo;
ltp?: number;
};
/**
* Close position message (CLOSE_POSITION)
* Received when user requests to close a position
* @example
* { position: { id: "POS_123", symbol: "BTCUSDT" }, id: "POS_123" }
*/
type ClosePositionMessage = {
position?: Position;
id?: string;
positionId?: string;
};Type-Safe Event Handling Example
The appCallback receives a single event object (AppCallbackEvent) with eventType, message, and optional onClose.
The message type is automatically narrowed based on eventType in switch/case statements.
appCallback: (event) => {
switch (event.eventType) {
case "PLACE_ORDER":
// event.message is PlaceOrderMessage
console.log("Order:", event.message.order);
console.log("Security:", event.message.security);
break;
case "MODIFY_ORDER":
// event.message is ModifyOrderMessage
console.log("Order ID:", event.message.orderId);
break;
case "CREATE_ORDER":
// event.message is CreateOrderMessage
console.log("Side:", event.message.side);
break;
case "CLOSE_POSITION":
// event.message is ClosePositionMessage
console.log("Position:", event.message.position);
break;
case "CANCEL_ORDER":
// event.message is Order
console.log("Cancelling:", event.message.orderId);
break;
}
};Advanced Types
Chart Widget Instance
// Deprecated alias of ChartInstance — kept for backward compatibility.
type ChartWidgetInstance = ChartInstance;Timescale Marks
// Timescale mark for marking important events on the chart
interface TimescaleMark {
id: string; // Unique mark ID
time: number; // Time coordinate (Unix timestamp)
color: string; // Mark color
label: string; // Mark label text
tooltip?: string; // Tooltip text
shape?: "circle" | "square" | "arrowUp" | "arrowDown"; // Mark shape
}UDF Response Format
// Universal Data Feed (UDF) response format
interface UDFResponse {
s: "ok" | "error" | "no_data"; // Status
t?: number[]; // Time array (Unix timestamps)
o?: number[]; // Open prices
h?: number[]; // High prices
l?: number[]; // Low prices
c?: number[]; // Close prices
v?: number[]; // Volume
errmsg?: string; // Error message (if s === "error")
nextTime?: number; // Next available data time
}Resolution
// Chart resolution/interval configuration
type Resolution = {
scale: number; // Scale value (e.g., 1, 5, 15)
units: string; // Time unit (e.g., "m", "h", "D", "W", "M")
type?: string; // Original interval string (e.g., "1m", "1D") — set internally by the SDK
};Event Types
Event Interfaces
// Chart events
interface ChartClickEvent {
x: number;
y: number;
price: number;
time: number;
ctrlKey?: boolean;
shiftKey?: boolean;
altKey?: boolean;
}
interface CrosshairMoveEvent {
price: number;
time: number;
x: number;
y: number;
}
// Error types
interface ChartError {
type: "license" | "data" | "network" | "general";
message: string;
code?: string;
details?: Record<string, unknown> | Error | string;
}
// Drawing events
interface DrawingObject {
id: string;
type: string;
points: DrawingPoint[];
style: DrawingStyle;
}
interface DrawingPoint {
time: number;
price: number;
}
interface DrawingStyle {
color?: string;
width?: number;
style?: "solid" | "dashed" | "dotted";
}Usage & Implementation
For complete implementation examples with these types, see:
React + TypeScript Integration - Complete guide with:
- Type-safe chart components
- Custom datafeed implementation
- Trading integration with typed callbacks
- Real-world production examples
- Best practices and common patterns
GitHub Demo Repository - Full working examples with:
- ChartSDKAdvanced2.tsx - Complete trading implementation
- Custom datafeed with TypeScript
- Order and position management
- Real-time price updates
Related Documentation
- Enums & literal unions - Catalog of real GoCharting union types
- React + TypeScript Integration - Complete implementation guide
- Vanilla JavaScript Example - Basic integration
- Time Marks Example - Custom time marks
- CodePen Examples - Live interactive demos