Skip to content

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.

typescript
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;
  }
) => ChartSpire
  • candleCloseTimerEnabled Whether to enable candle close timer on the price line
  • chartNavigationEnabled Enable/disable chart navigation controls (zoom, move, reset) - default: true
  • container Container id or HTML element
  • dataFeed Data feed implementation or a registered data feed name
  • defaultOpenComponents Array 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)
  • drawingBarVisible Whether to display the drawing toolbar
  • enabledSymbolTypes Array 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]
  • fontFamily Font family for the entire chart (e.g., 'Roboto', 'Arial, sans-serif', '"Inter", system-ui, sans-serif')
  • fontWeight Font weight for the entire chart (e.g., 'normal', 'bold', '400', '600')
  • indicators Default indicators to display on the chart (e.g., ['SAR', 'VOL'])
  • interval Time interval
  • intervalEnabled Enable/disable interval selector in bottom bar (default: true)
  • layoutLimit Maximum number of saved layouts
  • layoutsEnabled Enable/disable layout selector in bottom bar (default: true)
  • layoutUseExternalStorage Whether to use external storage for layouts
  • locale Language
  • logoEnabled Enable/disable ChartSpire logo
  • menuPages Array of menu pages to display in the topbar dropdown menu
  • menuPagesEnabled Enable/disable the menu dropdown in the topbar (default: false)
  • menuPageClickCallback Callback function called when user clicks on a menu page - receives the selected page object
  • multiChartDelay Delay in milliseconds between mounting/unmounting charts during multichart switch
  • multiChartLimit Maximum number of charts allowed (1, 2, 3, 4, 6, 8, 10, 12, 14, 16). Defaults to 16
  • objectTreeEnabled Whether to enable the Object Tree component that displays chart properties, indicators, and overlays (default: true)
  • orderBookDepthVisualization Order book depth visualization mode: 'amount' shows individual order quantities, 'cumulative' shows cumulative market depth (default: 'cumulative')
  • orderBookEnabled Whether to enable order book functionality
  • orderBookMaxRows Maximum number of rows to display in the order book (default: 10)
  • paperTradingEnabled Whether to enable paper trading functionality
  • paperTradingUseExternalStorage Whether to use external storage for paper trading data
  • periods All available time intervals
  • paperTradingPriceTrackingInterval Price tracking update interval in milliseconds for paper trading (default: 30000 = 30 seconds, minimum: 1000)
  • paperTradingPriceTrackingLogging Whether to enable debug logging for price tracking (default: true)
  • styles Core chart styles
  • subscribedSymbolsURL URL for subscribed symbols
  • symbol Symbol information object
  • symbolSearchOnKeyStroke Enable 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 pressed
  • theme Theme
  • themeGeneraterEnabled Enable/disable custom theme creation functionality (default: true)
  • themesEnabled Enable/disable theme selector in bottom bar (default: true)
  • themeUseExternalStorage Whether to use external storage for custom themes
  • themeCustom Custom chart theme, for more details refer to theme.md doc
  • timezone Timezone
  • timezoneEnabled Enable/disable timezone selector in bottom bar (default: true)
  • tradesEnabled Whether to enable trades (time and sales) functionality
  • tradesMaxRows Maximum number of trade rows to display in the trades component (default: 50)
  • tradesTimeFormat Time format for trade timestamps: '12h' for 12-hour format with AM/PM, '24h' for 24-hour format (default: '24h')
  • watchListAmount Number of watchlist items to display
  • watchListEnabled Whether to enable watchlist functionality
  • watchListHttp Enable HTTP polling for watchlist prices instead of WebSocket streaming (default: false)
  • watchListHttpBatchSize Maximum number of symbols to batch in a single HTTP request cycle (default: 10)
  • watchListHttpInterval Interval in milliseconds between HTTP price requests for watchlist (default: 5000, minimum: 1000)
  • watchListHttpMaxRetries Maximum number of retry attempts for failed HTTP requests (default: 3)
  • watchListHttpRetryEnabled Enable retry logic for failed HTTP price requests (default: true)
  • watchListLimit Maximum number of items in the watchlist
  • watchListUseExternalStorage Whether to use external storage for watchlist
  • watermark Watermark

SymbolInfo Interface

Defines the symbol payload shape used when creating charts, switching symbols, and integrating data feeds.

typescript
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.

typescript
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)

typescript
(theme: string) => void

Set theme for all charts.

getTheme()

typescript
() => string

Get current theme.

setStyles(styles)

typescript
(styles: DeepPartial<Styles>) => void

Set core chart styles for all charts.

getStyles()

typescript
() => Styles

Get core chart styles from active chart.

setLocale(locale)

typescript
(locale: string) => void

Set language for all charts.

getLocale()

typescript
() => string

Get language from active chart.

setFontFamily(fontFamily)

typescript
(fontFamily: string) => void

Set font family for the entire widget. Accepts any valid CSS font-family value.

Examples:

typescript
// 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()

typescript
() => string

Get current font family setting.

setFontWeight(fontWeight)

typescript
(fontWeight: 'lighter' | 'normal' | 'bold' | 'bolder' | number) => void

Set font weight for the entire widget. Accepts any valid CSS font-weight value.

Examples:

typescript
// 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)  // bold

getFontWeight()

typescript
() => string

Get current font weight setting.

setTimezone(timezone)

typescript
(timezone: string) => void

Set timezone for all charts.

getTimezone()

typescript
() => string

Get timezone from active chart.

setSymbol(symbol, chartId, dataFeed)

typescript
(symbol: SymbolInfo, chartId: ChartID, dataFeed: DataFeed) => void

Set symbol for a specific chart.

getSymbol(chartId)

typescript
(chartId: ChartID) => SymbolInfo | null

Get symbol for a specific chart.

setInterval(interval, chartId)

typescript
(interval: Interval, chartId: ChartID) => void

Set interval for a specific chart.

getInterval(chartId)

typescript
(chartId: ChartID) => Interval | null

Get interval for a specific chart.

getActiveChart()

typescript
() => Nullable<ChartInterface>

Get active chart.

getChart(chartId)

typescript
(chartId: ChartID) => Nullable<ChartInterface>

Get chart for a specific chart ID.

isActiveChart(chartId)

typescript
(chartId: ChartID) => boolean

Check 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.

typescript
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: true for 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.

typescript
// 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)

typescript
(callback: (themes: CustomTheme[]) => Promise<boolean>) => void

Sets 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)

typescript
(callback: () => Promise<CustomTheme[] | null>) => void

Sets 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()

typescript
() => 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

typescript
interface CustomTheme {
  name: string
  displayName: string
  colors: ThemeColors
}

ThemeColors

typescript
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

typescript
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

typescript
// 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)

typescript
(chartId: string) => void

Set the active chart.

getMultiChart()

typescript
() => number

Get the current number of displayed charts.

getAllChartIds()

typescript
() => string[]

Get an array of all chart IDs that are available based on the multiChartLimit.

getVisibleChartIds()

typescript
() => string[]

Get an array of chart IDs that are currently visible based on the multiChart setting.

syncAllSymbolsToActiveChart()

typescript
() => void

Sync 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()

typescript
() => void

Sync 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()

typescript
() => void

Clean 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.

typescript
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
  • 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 setPaperTradingChangeCallback and setGetPaperTradingDataCallback
  • 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
  • paperTradingPriceTrackingLogging (optional): Whether to enable debug logging for price tracking

    • Type: boolean
    • Default: true
    • Set to false in production to reduce console output
    • Logs price fetch operations, tracking start/stop, and order executions

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)

typescript
(callback: (data: PaperTradingData) => Promise<boolean>) => void

Sets 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)

typescript
(callback: () => Promise<PaperTradingData | null>) => void

Sets 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()

typescript
() => Promise<PaperTradingData | null>

Utility function that calls the registered load callback to retrieve paper trading data.

setPriceTrackingInterval(intervalMs)

typescript
(intervalMs: number) => void

Sets the price tracking update interval in milliseconds. Minimum value is 1000ms (1 second).

setPriceTrackingLogging(enabled)

typescript
(enabled: boolean) => void

Enables or disables price tracking logging.

getCurrentConfig()

typescript
() => PriceTrackingConfig

Gets the current price tracking configuration.

updatePriceTrackingConfig(config)

typescript
(config: Partial<PriceTrackingConfig>) => void

Updates multiple price tracking configuration options at once.

Usage Examples

These examples cover baseline, production, and external-storage paper-trading setups.

Basic Configuration

typescript
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

typescript
const chart = new ChartSpire({
  // ... other options
  paperTradingEnabled: true,
  paperTradingPriceTrackingInterval: 60000, // 1 minute (fewer API calls)
  paperTradingPriceTrackingLogging: false,  // Disable logging in production
})

External Storage Configuration

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
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.

typescript
// 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
})