API
This page documents the public API surface for ChartSpire, including constructor options, runtime methods, and integration callbacks.
Creating chart
Create a chart instance by passing a configuration object to new ChartSpire(...).
For most implementations, start with container, symbol, interval, dataFeed, and enabledSymbolTypes, then add optional features as needed.
new ChartSpire(
options: {
candleCloseTimerEnabled?: boolean;
container: string | HTMLElement;
dataFeed: DataFeed | string;
defaultOpenComponents?: ('watchlist' | 'orderbook' | 'papertrading' | 'trades' | 'objecttree')[];
drawingBarVisible?: boolean;
enabledSymbolTypes: SYMBOL_TYPE[];
fontFamily?: string;
fontWeight?: 'lighter' | 'normal' | 'bold' | 'bolder' | number
indicators?: string[]
interval: Interval;
intervalEnabled?: boolean;
layoutLimit?: number;
layoutsEnabled?: boolean;
layoutUseExternalStorage?: boolean;
locale?: string;
logoEnabled?: boolean;
menuPages?: MenuPage[];
menuPagesEnabled?: boolean;
menuPageClickCallback?: (page: MenuPage) => void;
multiChartDelay?: number;
multiChartLimit?: number;
objectTreeEnabled?: boolean;
orderBookDepthVisualization?: 'amount' | 'cumulative';
orderBookEnabled?: boolean;
orderBookMaxRows?: number;
paperTradingEnabled?: boolean;
paperTradingUseExternalStorage?: boolean;
paperTradingPriceTrackingInterval?: number;
paperTradingPriceTrackingLogging?: boolean;
periods?: Interval[];
styles?: DeepPartial<Styles>;
subscribedSymbolsURL?: string;
symbol: SymbolInfo;
symbolSearchOnKeyStroke?: boolean;
theme?: string;
themeCustom?: CustomTheme[];
themeGeneraterEnabled?: boolean;
themesEnabled?: boolean;
themeUseExternalStorage?: boolean;
timezone?: string;
timezoneEnabled?: boolean;
tradesEnabled?: boolean;
tradesMaxRows?: number;
tradesTimeFormat?: '12h' | '24h';
watchListAmount?: number;
watchListEnabled?: boolean;
watchListHttp?: boolean;
watchListHttpBatchSize?: number;
watchListHttpInterval?: number;
watchListHttpMaxRetries?: number;
watchListHttpRetryEnabled?: boolean;
watchListLimit?: number;
watchListUseExternalStorage?: boolean;
watermark?: string | Node;
}
) => ChartSpirecandleCloseTimerEnabledWhether to enable candle close timer on the price linechartNavigationEnabledEnable/disable chart navigation controls (zoom, move, reset) - default: truecontainerContainer id or HTML elementdataFeedData feed implementation or a registered data feed namedefaultOpenComponentsArray of component names to open by default on page load. Maximum of 3 components. Valid values: 'watchlist', 'orderbook', 'papertrading', 'trades', 'objecttree'. Components must be enabled to open (e.g., watchListEnabled: true)drawingBarVisibleWhether to display the drawing toolbarenabledSymbolTypesArray of SYMBOL_TYPE values to filter which symbol types are available in the UI. When specified, only these symbol types will appear in symbol search, watchlists, and other symbol-related features. If empty or omitted, all symbol types are available. Example: [SYMBOL_TYPE.STOCKS, SYMBOL_TYPE.CRYPTO]fontFamilyFont family for the entire chart (e.g., 'Roboto', 'Arial, sans-serif', '"Inter", system-ui, sans-serif')fontWeightFont weight for the entire chart (e.g., 'normal', 'bold', '400', '600')indicatorsDefault indicators to display on the chart (e.g., ['SAR', 'VOL'])intervalTime intervalintervalEnabledEnable/disable interval selector in bottom bar (default: true)layoutLimitMaximum number of saved layoutslayoutsEnabledEnable/disable layout selector in bottom bar (default: true)layoutUseExternalStorageWhether to use external storage for layoutslocaleLanguagelogoEnabledEnable/disable ChartSpire logomenuPagesArray of menu pages to display in the topbar dropdown menumenuPagesEnabledEnable/disable the menu dropdown in the topbar (default: false)menuPageClickCallbackCallback function called when user clicks on a menu page - receives the selected page objectmultiChartDelayDelay in milliseconds between mounting/unmounting charts during multichart switchmultiChartLimitMaximum number of charts allowed (1, 2, 3, 4, 6, 8, 10, 12, 14, 16). Defaults to 16objectTreeEnabledWhether to enable the Object Tree component that displays chart properties, indicators, and overlays (default: true)orderBookDepthVisualizationOrder book depth visualization mode: 'amount' shows individual order quantities, 'cumulative' shows cumulative market depth (default: 'cumulative')orderBookEnabledWhether to enable order book functionalityorderBookMaxRowsMaximum number of rows to display in the order book (default: 10)paperTradingEnabledWhether to enable paper trading functionalitypaperTradingUseExternalStorageWhether to use external storage for paper trading dataperiodsAll available time intervalspaperTradingPriceTrackingIntervalPrice tracking update interval in milliseconds for paper trading (default: 30000 = 30 seconds, minimum: 1000)paperTradingPriceTrackingLoggingWhether to enable debug logging for price tracking (default: true)stylesCore chart stylessubscribedSymbolsURLURL for subscribed symbolssymbolSymbol information objectsymbolSearchOnKeyStrokeEnable real-time symbol search that triggers on every keystroke (default: false). When enabled, search results update as you type. When disabled, search only triggers when Enter key is pressedthemeThemethemeGeneraterEnabledEnable/disable custom theme creation functionality (default: true)themesEnabledEnable/disable theme selector in bottom bar (default: true)themeUseExternalStorageWhether to use external storage for custom themesthemeCustomCustom chart theme, for more details refer totheme.mddoctimezoneTimezonetimezoneEnabledEnable/disable timezone selector in bottom bar (default: true)tradesEnabledWhether to enable trades (time and sales) functionalitytradesMaxRowsMaximum number of trade rows to display in the trades component (default: 50)tradesTimeFormatTime format for trade timestamps: '12h' for 12-hour format with AM/PM, '24h' for 24-hour format (default: '24h')watchListAmountNumber of watchlist items to displaywatchListEnabledWhether to enable watchlist functionalitywatchListHttpEnable HTTP polling for watchlist prices instead of WebSocket streaming (default: false)watchListHttpBatchSizeMaximum number of symbols to batch in a single HTTP request cycle (default: 10)watchListHttpIntervalInterval in milliseconds between HTTP price requests for watchlist (default: 5000, minimum: 1000)watchListHttpMaxRetriesMaximum number of retry attempts for failed HTTP requests (default: 3)watchListHttpRetryEnabledEnable retry logic for failed HTTP price requests (default: true)watchListLimitMaximum number of items in the watchlistwatchListUseExternalStorageWhether to use external storage for watchlistwatermarkWatermark
SymbolInfo Interface
Defines the symbol payload shape used when creating charts, switching symbols, and integrating data feeds.
interface SymbolInfo {
symbol: string;
type: SYMBOL_TYPE | 'UNKNOWN';
name?: string;
shortName?: string;
exchange?: string;
market?: string;
pricePrecision?: number;
volumePrecision?: number;
priceCurrency?: string;
logo?: string;
}ChartID Interface
Represents a chart instance identifier in multi-chart mode for APIs that target a specific chart.
interface ChartID {
id: string;
}Chart API
These runtime methods let you control chart state after initialization (theme, symbol, interval, active chart, and lifecycle).
setTheme(theme)
(theme: string) => voidSet theme for all charts.
getTheme()
() => stringGet current theme.
setStyles(styles)
(styles: DeepPartial<Styles>) => voidSet core chart styles for all charts.
getStyles()
() => StylesGet core chart styles from active chart.
setLocale(locale)
(locale: string) => voidSet language for all charts.
getLocale()
() => stringGet language from active chart.
setFontFamily(fontFamily)
(fontFamily: string) => voidSet font family for the entire widget. Accepts any valid CSS font-family value.
Examples:
// Set Roboto font with fallbacks
chart.setFontFamily('Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif')
// Set custom font with fallbacks
chart.setFontFamily('"Inter", "Helvetica Neue", Arial, sans-serif')
// Set system font
chart.setFontFamily('system-ui, sans-serif')getFontFamily()
() => stringGet current font family setting.
setFontWeight(fontWeight)
(fontWeight: 'lighter' | 'normal' | 'bold' | 'bolder' | number) => voidSet font weight for the entire widget. Accepts any valid CSS font-weight value.
Examples:
// Set font weight using keywords
chart.setFontWeight('normal')
chart.setFontWeight('bold')
chart.setFontWeight('lighter')
// Set font weight using numeric values
chart.setFontWeight(400) // normal
chart.setFontWeight(600) // semi-bold
chart.setFontWeight(700) // boldgetFontWeight()
() => stringGet current font weight setting.
setTimezone(timezone)
(timezone: string) => voidSet timezone for all charts.
getTimezone()
() => stringGet timezone from active chart.
setSymbol(symbol, chartId, dataFeed)
(symbol: SymbolInfo, chartId: ChartID, dataFeed: DataFeed) => voidSet symbol for a specific chart.
getSymbol(chartId)
(chartId: ChartID) => SymbolInfo | nullGet symbol for a specific chart.
setInterval(interval, chartId)
(interval: Interval, chartId: ChartID) => voidSet interval for a specific chart.
getInterval(chartId)
(chartId: ChartID) => Interval | nullGet interval for a specific chart.
getActiveChart()
() => Nullable<ChartInterface>Get active chart.
getChart(chartId)
(chartId: ChartID) => Nullable<ChartInterface>Get chart for a specific chart ID.
isActiveChart(chartId)
(chartId: ChartID) => booleanCheck if a specific chart is active.
Default Open Components
The defaultOpenComponents property allows you to specify which right-side panel components should be open by default when the chart loads. This is useful for creating a customized initial view for your users.
Basic Usage
Use this pattern when you want one or more right-side panels open as soon as the widget mounts.
const chart = new ChartSpire({
// ... other options
// Enable the components you want to use
watchListEnabled: true,
orderBookEnabled: true,
paperTradingEnabled: true,
tradesEnabled: true,
// Open watchlist and orderbook by default
defaultOpenComponents: ['watchlist', 'orderbook'],
})Available Components
These are the component keys accepted by defaultOpenComponents.
'watchlist'- Symbol watchlist panel'orderbook'- Order book panel'papertrading'- Paper trading panel'trades'- Recent trades panel
Rules and Limitations
- Maximum of 3 components can be open at once
- Only enabled components will open (e.g., requires
watchListEnabled: truefor watchlist) - Components are opened in the order specified in the array
- If more than 3 components are specified, only the first 3 will be used
Examples
The examples below show common default-open combinations and a complete configuration.
// Open just the watchlist
defaultOpenComponents: ['watchlist']
// Open watchlist and orderbook
defaultOpenComponents: ['watchlist', 'orderbook']
// Open all three panels (max limit)
defaultOpenComponents: ['watchlist', 'orderbook', 'papertrading']
// This will only open the first 3 (excess ignored)
defaultOpenComponents: ['watchlist', 'orderbook', 'papertrading', 'trades']
// Complete configuration example
const chart = new ChartSpire({
container: '#chart',
symbol: { symbol: 'BTCUSDT', type: 'crypto' },
dataFeed: new DefaultDataFeed(),
// Enable components
watchListEnabled: true,
orderBookEnabled: true,
paperTradingEnabled: true,
tradesEnabled: true,
// Open watchlist and orderbook by default
defaultOpenComponents: ['watchlist', 'orderbook'],
// ... other options
})Theme API
Use this section to configure theming behavior and integrate custom theme persistence.
Custom Theme Management
ChartSpire supports custom themes with external storage capabilities for enterprise applications.
setThemeChangeCallback(callback)
(callback: (themes: CustomTheme[]) => Promise<boolean>) => voidSets the callback function that will be called whenever custom themes are created, modified, or deleted. The callback should save the themes array to your external storage and return true if successful, false if failed.
setGetThemeDataCallback(callback)
(callback: () => Promise<CustomTheme[] | null>) => voidSets the callback function that will be called to load custom themes from external storage. Should return the themes array or null if no custom themes exist.
getThemeData()
() => Promise<CustomTheme[] | null>Utility function that calls the registered load callback to retrieve custom themes data.
Custom Theme Interfaces
These interfaces describe the required structure for storing and applying custom themes.
CustomTheme
interface CustomTheme {
name: string
displayName: string
colors: ThemeColors
}ThemeColors
interface ThemeColors {
primaryColor: string
selectedColor: string
hoverBackgroundColor: string
backgroundColor: string
popoverBackgroundColor: string
textColor: string
textSecondColor: string
borderColor: string
}Usage Examples
Use these examples to quickly wire storage callbacks and verify custom theme application.
External Storage Configuration
import { setThemeChangeCallback, setGetThemeDataCallback } from '@chartspire/chartspire'
// Enable external storage for themes
const chart = new ChartSpire({
// ... other options
themeUseExternalStorage: true, // Enable external storage
})
// Set up save callback
setThemeChangeCallback(async (themes) => {
try {
const response = await fetch('/api/themes/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(themes)
})
return response.ok
} catch (error) {
console.error('Failed to save custom themes:', error)
return false
}
})
// Set up load callback
setGetThemeDataCallback(async () => {
try {
const response = await fetch('/api/themes')
if (response.ok) {
return await response.json()
}
return null
} catch (error) {
console.error('Failed to load custom themes:', error)
return null
}
})Creating Custom Themes
// Example custom theme object
const oceanBlueTheme: CustomTheme = {
name: 'ocean-blue',
displayName: 'Ocean Blue',
colors: {
primaryColor: '#0077B6',
selectedColor: 'rgba(0, 119, 182, 0.15)',
hoverBackgroundColor: 'rgba(0, 119, 182, 0.15)',
backgroundColor: '#CAF0F8',
popoverBackgroundColor: '#EDF6F9',
textColor: '#03045E',
textSecondColor: '#0096C7',
borderColor: '#90E0EF'
}
}
// Apply the custom theme
chart.setTheme('ocean-blue')setActiveChart(chartId)
(chartId: string) => voidSet the active chart.
getMultiChart()
() => numberGet the current number of displayed charts.
getAllChartIds()
() => string[]Get an array of all chart IDs that are available based on the multiChartLimit.
getVisibleChartIds()
() => string[]Get an array of chart IDs that are currently visible based on the multiChart setting.
syncAllSymbolsToActiveChart()
() => voidSync all charts to use the symbol from the active chart. When called, all visible charts will switch to display the same symbol symbol as the currently active chart, while preserving their individual interval settings.
syncAllIntervalsToActiveChart()
() => voidSync all charts to use the interval from the active chart. When called, all visible charts will switch to use the same time interval as the currently active chart, while preserving their individual symbol symbols.
destroy()
() => voidClean up resources and remove all charts.
Paper Trading API
ChartSpire includes a comprehensive paper trading system that can be configured through the chart options and controlled programmatically.
Configuration Options
These constructor options control paper-trading availability and runtime tracking behavior.
Chart Initialization
Use this initialization pattern to enable paper trading from the first render.
new ChartSpire({
// ... other options
paperTradingEnabled: true,
paperTradingPriceTrackingInterval: 15000, // 15 seconds
paperTradingPriceTrackingLogging: true, // Enable debug logging
})Configuration Properties
Each property below explains what it controls, its default behavior, and when to tune it.
paperTradingEnabled(optional): Whether to enable paper trading functionality- Type:
boolean - Default:
false - Enables the paper trading interface in the right sidebar
- Type:
paperTradingUseExternalStorage(optional): Whether to use external storage for paper trading data- Type:
boolean - Default:
false - When
true, uses callback-based external storage instead of localStorage - Requires setting up save and load callbacks using
setPaperTradingChangeCallbackandsetGetPaperTradingDataCallback
- Type:
paperTradingPriceTrackingInterval(optional): Price tracking update interval in milliseconds- Type:
number - Default:
30000(30 seconds) - Minimum:
1000(1 second) - Controls how frequently the system checks prices for pending limit orders
- Lower values provide faster order execution but use more API calls
- Type:
paperTradingPriceTrackingLogging(optional): Whether to enable debug logging for price tracking- Type:
boolean - Default:
true - Set to
falsein production to reduce console output - Logs price fetch operations, tracking start/stop, and order executions
- Type:
Runtime Configuration
The paper trading system can be configured at runtime through the PaperTradingService API:
External Storage Callbacks
When using external storage (paperTradingUseExternalStorage: true), you must set up callback functions to handle data persistence:
setPaperTradingChangeCallback(callback)
(callback: (data: PaperTradingData) => Promise<boolean>) => voidSets the callback function that will be called whenever paper trading data changes (orders placed, positions closed, etc.). The callback should save the data to your external storage and return true if successful, false if failed.
setGetPaperTradingDataCallback(callback)
(callback: () => Promise<PaperTradingData | null>) => voidSets the callback function that will be called to load paper trading data from external storage. Should return the data object or null if no data exists.
getPaperTradingData()
() => Promise<PaperTradingData | null>Utility function that calls the registered load callback to retrieve paper trading data.
setPriceTrackingInterval(intervalMs)
(intervalMs: number) => voidSets the price tracking update interval in milliseconds. Minimum value is 1000ms (1 second).
setPriceTrackingLogging(enabled)
(enabled: boolean) => voidEnables or disables price tracking logging.
getCurrentConfig()
() => PriceTrackingConfigGets the current price tracking configuration.
updatePriceTrackingConfig(config)
(config: Partial<PriceTrackingConfig>) => voidUpdates multiple price tracking configuration options at once.
Usage Examples
These examples cover baseline, production, and external-storage paper-trading setups.
Basic Configuration
const chart = new ChartSpire({
container: 'chart-container',
symbol: { symbol: 'AAPL', type: 'stock' },
interval: { multiplier: 1, timespan: 'day', text: '1D' },
paperTradingEnabled: true,
paperTradingPriceTrackingInterval: 15000, // 15 seconds
paperTradingPriceTrackingLogging: true,
// ... other required options
})Production Configuration
const chart = new ChartSpire({
// ... other options
paperTradingEnabled: true,
paperTradingPriceTrackingInterval: 60000, // 1 minute (fewer API calls)
paperTradingPriceTrackingLogging: false, // Disable logging in production
})External Storage Configuration
import { setPaperTradingChangeCallback, setGetPaperTradingDataCallback } from '@chartspire/chartspire'
// Enable external storage
const chart = new ChartSpire({
// ... other options
paperTradingEnabled: true,
paperTradingUseExternalStorage: true, // Enable external storage
paperTradingPriceTrackingInterval: 30000,
paperTradingPriceTrackingLogging: false,
})
// Set up save callback
setPaperTradingChangeCallback(async (data) => {
try {
const response = await fetch('/api/paper-trading/save', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
})
return response.ok
} catch (error) {
console.error('Failed to save paper trading data:', error)
return false
}
})
// Set up load callback
setGetPaperTradingDataCallback(async () => {
try {
const response = await fetch('/api/paper-trading')
if (response.ok) {
return await response.json()
}
return null
} catch (error) {
console.error('Failed to load paper trading data:', error)
return null
}
})Price Tracking Configuration Interface
Defines runtime controls used by the paper-trading price tracker.
interface PriceTrackingConfig {
updateInterval: number // Interval between API calls in milliseconds
enableLogging: boolean // Whether to enable debug logging
}Paper Trading Data Interfaces
These interfaces define the persisted paper-trading state shape used by callbacks and services.
PaperTradingData
Top-level paper-trading snapshot containing orders, positions, trades, and account balance.
interface PaperTradingData {
orders: Order[] // Array of order objects
positions: Position[] // Array of position objects
trades: Trade[] // Array of trade objects
balance: number // Account balance as number
}Order
Represents a single order and its execution status over time.
interface Order {
id: string
symbol: string
side: 'buy' | 'sell'
quantity: number
type: 'MARKET' | 'LIMIT'
price: number
status: 'PENDING' | 'FILLED' | 'CANCELLED'
timestamp: number
filledAt?: number
symbolType?: string
}Position
Represents an aggregated position derived from executed trades.
interface Position {
id: string
symbol: string
side: 'buy' | 'sell'
quantity: number
averagePrice: number
unrealizedPnL: number
realizedPnL: number
timestamp: number
symbolType?: string
}Trade
Represents an individual fill event linked to an order.
interface Trade {
id: string
orderId: string
symbol: string
side: 'buy' | 'sell'
quantity: number
price: number
timestamp: number
}Important Notes
Review these constraints to avoid production surprises and unnecessary API load.
- When the update interval is changed, all existing price tracking will be restarted with the new interval
- The minimum interval is 1000ms (1 second) to prevent excessive API usage
- Changes take effect immediately for all tracked symbols
- Price tracking only occurs when the paper trading tab is open to optimize API usage
- The system supports multiple asset types (stocks, crypto, forex, futures) simultaneously
Runtime Updates
Use these calls to adjust paper-trading tracking behavior without recreating the chart instance.
// Get the paper trading service (implementation depends on your setup)
const paperTradingService = getPaperTradingService()
// Update interval to 10 seconds
paperTradingService.setPriceTrackingInterval(10000)
// Disable logging
paperTradingService.setPriceTrackingLogging(false)
// Get current configuration
const config = paperTradingService.getCurrentConfig()
console.log('Current interval:', config.updateInterval)
// Update multiple settings
paperTradingService.updatePriceTrackingConfig({
updateInterval: 20000,
enableLogging: true
})