Skip to Content
API ReferenceChart API

πŸ“Š Chart Creation API

The GoCharting SDK provides a simple createChart() function for creating professional trading charts with built-in AutoFit and real-time capabilities.

πŸš€ Quick Start

import { createChart } from "@gocharting/chart-sdk"; const chart = createChart("#chart-container", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_LICENSE_KEY", });

πŸ“– API Reference

createChart(container, config)

Creates a new chart instance with the specified configuration.

Syntax

function createChart( container: HTMLElement | string, config: ChartConfig ): ChartWrapper;

Parameters

ParameterTypeRequiredDescription
containerHTMLElement | stringβœ…DOM element or CSS selector for chart container
configChartConfigβœ…Chart configuration object

ChartConfig Properties

PropertyTypeRequiredDescription
datafeedDatafeedβœ…Datafeed implementation for market data
symbolstringβœ…Initial symbol (e.g., β€œAAPL”, β€œBYBIT:FUTURE:BTCUSDT”)
intervalstringβœ…Initial interval (e.g., β€œ1m”, β€œ5m”, β€œ1H”, β€œ1D”)
licenseKeystringβœ…Your SDK license key
theme"light" | "dark"❌Chart theme (default: β€œlight”)
themeColorstring❌Theme color (e.g., β€œdark”, β€œ#1a1a1a”)
autosizeboolean❌Enable automatic resizing (default: true)
widthnumber | string❌Chart width (default: β€œ100%β€œ)
heightnumber | string❌Chart height (default: β€œ100%β€œ)
localestring❌Locale (e.g., β€œen-US”, β€œen”) (default: β€œen-US”)
debugLogboolean❌Enable debug logging (default: false)
tradingTradingConfig❌Trading configuration
excludeExcludeOptions❌Exclude UI elements
appCallbackAppCallbackEventHandler❌Trading and app event handler
onReadyOnReadyEventHandler❌Callback when chart is ready
onErrorOnErrorEventHandler❌Error callback
β€¦β€¦βŒSee Configuration for all options

Returns: ChartWrapper

Returns a ChartWrapper object with lifecycle management methods:

MethodReturn TypeDescription
destroy()voidDestroy chart and clean up resources
isDestroyed()booleanCheck if chart is destroyed
getChartInstance()ChartInstanceGet the underlying ChartInstance component
Note

The ChartWrapper provides lifecycle management. For chart control methods (setSymbol, setInterval, etc.), use getChartInstance() or the onReady callback.

πŸ’‘ Usage Examples

Example 1: Basic Chart

import { createChart } from "@gocharting/chart-sdk"; // Create your datafeed object (no class inheritance needed!) const myDatafeed = { async getBars(symbolInfo, resolution, periodParams) { // Fetch historical bars from your API const response = await fetch(`/api/bars?symbol=${symbolInfo.symbol}`); const data = await response.json(); return { bars: data }; }, resolveSymbol(symbolName, onResolve, onError) { // Resolve symbol information const symbolInfo = { symbol: symbolName, full_name: symbolName, description: symbolName, exchange: "EXCHANGE", type: "stock", session: "0930-1600", timezone: "America/New_York", ticker: symbolName, has_intraday: true, supported_resolutions: ["1", "5", "15", "30", "60", "1D"], }; onResolve(symbolInfo); }, }; // πŸš€ Create chart with one simple call! const chart = createChart("#chart-container", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_LICENSE_KEY", theme: "light", onReady: (chartInstance) => { console.log("Chart ready!"); // chartInstance is the ChartInstance component }, onError: (error) => { console.error("Chart error:", error); }, }); // Always clean up when done chart.destroy();

Example 2: Chart with Trading Features

import { createChart } from "@gocharting/chart-sdk"; const tradingChart = createChart("#trading-chart", { symbol: "BYBIT:FUTURE:BTCUSDT", interval: "1m", datafeed: myDatafeed, licenseKey: "YOUR_LICENSE_KEY", theme: "dark", trading: { enableTrading: true, }, appCallback: ({ eventType, message, onClose }) => { console.log("Trading event:", eventType, message); switch (eventType) { case "PLACE_ORDER": // Handle order placement console.log("Place order:", message.order); // Call your API to place the order if (onClose) onClose(); break; case "MODIFY_ORDER": // Handle order modification console.log("Modify order:", message.orderId, message.order); if (onClose) onClose(); break; case "CANCEL_ORDER": // Handle order cancellation console.log("Cancel order:", message); if (onClose) onClose(); break; } }, onReady: (chartInstance) => { // Set broker accounts when chart is ready chartInstance.setBrokerAccounts({ accountList: [ { id: "123", name: "Trading Account", balance: 10000, currency: "USD", }, ], orderBook: [], tradeBook: [], positions: [], }); }, });

Example 3: Using ChartInstance Methods

import { createChart } from "@gocharting/chart-sdk"; const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_LICENSE_KEY", onReady: (chartInstance) => { // ChartInstance methods are available here chartInstance.setSymbol("MSFT"); chartInstance.setInterval("1H"); chartInstance.setTheme("dark"); // Update settings chartInstance.updateSettings({ zone: "America/New_York", showGrid: true, }); // Get chart state const state = chartInstance.getChartState(); console.log("Chart state:", state); }, }); // ChartWrapper methods console.log("Is destroyed?", chart.isDestroyed()); // false // Get ChartInstance from wrapper const chartInstance = chart.getChartInstance(); chartInstance.setSymbol("GOOGL"); // Clean up chart.destroy(); console.log("Is destroyed?", chart.isDestroyed()); // true

πŸ“‹ ChartWrapper Methods

The ChartWrapper object returned by createChart() provides lifecycle management methods:

destroy()

Destroys the chart and cleans up all resources including active subscriptions.

chart.destroy();

What it cleans up:

  • βœ… Active tick subscriptions - Unsubscribes from all WebSocket streams
  • βœ… Event listeners - Removes all DOM event listeners
  • βœ… ResizeObserver - Disconnects resize monitoring
  • βœ… Keyboard shortcuts - Clears all key bindings
  • βœ… Memory references - Prevents memory leaks
Caution

Always call destroy() when removing the chart from the DOM to prevent memory leaks:

  • Required for proper cleanup when recreating charts
  • Prevents WebSocket subscription leaks
  • Should be called in React useEffect cleanup

Example with React:

useEffect(() => { const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_KEY", }); return () => { // Cleanup when component unmounts chart.destroy(); }; }, []);

isDestroyed()

Checks if the chart has been destroyed.

const destroyed = chart.isDestroyed(); console.log("Is destroyed?", destroyed); // false or true

Returns: boolean - true if chart is destroyed, false otherwise

getChartInstance()

Gets the underlying ChartInstance component for programmatic control.

const chartInstance = chart.getChartInstance(); // Now you can use ChartInstance methods chartInstance.setSymbol("MSFT"); chartInstance.setInterval("1H"); chartInstance.setTheme("dark");

Returns: ChartInstance - The underlying React component with chart control methods

Note

For all chart control methods (setSymbol, setInterval, setBrokerAccounts, etc.), see the Chart Widget API documentation.

πŸ“‹ ChartInstance Methods

For chart control methods like setSymbol(), setInterval(), setBrokerAccounts(), etc., you need to access the ChartInstance:

// Method 1: Use onReady callback (recommended) const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_KEY", onReady: (chartInstance) => { // chartInstance has all control methods chartInstance.setSymbol("MSFT"); chartInstance.setBrokerAccounts(data); }, }); // Method 2: Get from wrapper const chartInstance = chart.getChartInstance(); chartInstance.setSymbol("GOOGL");

Available ChartInstance Methods:

  • Basic Control: setSymbol(), setInterval(), setTheme(), resize(), destroy()
  • Trading: setBrokerAccounts()
  • Multichart: setChartSymbolAtIndex(), setIntervalAtIndex(), getAllCharts() πŸ†•
  • Indicators & Drawings: addIndicator(), addDrawing(), deleteObject()
  • Settings & State: updateSettings(), getChartState(), setChartState()
  • Resubscription: resubscribeAll()

For complete documentation of all ChartInstance methods, see the Chart Widget API page.

getAllCharts() - New in v1.0.47 πŸŽ‰

Get information about all charts when multicharting is enabled.

const chart = createChart("#chart", { symbol: "BTCUSDT", interval: "1H", datafeed: myDatafeed, licenseKey: "YOUR_KEY", onReady: (chartInstance) => { // Get all charts info const chartInfo = chartInstance.getAllCharts(); if (chartInfo.isMultichartingEnabled) { console.log(`Found ${chartInfo.charts.length} charts`); chartInfo.charts.forEach((chart) => { console.log( `Chart ${chart.idx}: ${chart.symbol} @ ${chart.interval}` ); }); } }, });

Returns: MultiChartInfo

type MultiChartInfo = { isMultichartingEnabled: boolean; // true if layout !== "1" charts: ChartSelectedMessage[]; // Array of chart details }; type ChartSelectedMessage = { id: string; // Chart ID (e.g., "CHART_1") chartId: string; // Same as id idx: number; // Chart index (0-based) symbol: string; // Current symbol interval: string; // Current interval };

Use Cases:

  • Programmatically access all chart states in multi-chart layouts
  • Synchronize data across multiple charts
  • Build custom multi-chart management UIs
  • Export/save multi-chart workspace configurations

🎯 Event Callbacks

Event callbacks are configured in the ChartConfig object passed to createChart().

onReady Callback

Fired when the chart is fully loaded and ready. Receives the ChartInstance as a parameter.

const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_KEY", onReady: (chartInstance) => { console.log("Chart is ready!"); // chartInstance has all control methods chartInstance.setSymbol("MSFT"); }, });

Signature:

onReady?: (chartInstance: ChartInstance) => void;

onError Callback

Fired when an error occurs during chart initialization or operation.

const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_KEY", onError: (error) => { console.error("Chart error:", error); // Handle error appropriately }, });

Signature:

onError?: (error: ChartError) => void;

appCallback - Trading and UI Events

Handles all trading events (order placement, position changes, etc.) and UI events.

const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_KEY", trading: { enableTrading: true, }, appCallback: ({ eventType, message, onClose }) => { console.log("Event:", eventType, "Message:", message); switch (eventType) { case "PLACE_ORDER": console.log("User wants to place order:", message.order); // Call your API to place the order if (onClose) onClose(); break; case "MODIFY_ORDER": console.log("User wants to modify order:", message); // Call your API to modify the order if (onClose) onClose(); break; case "CANCEL_ORDER": console.log("User wants to cancel order:", message); // Call your API to cancel the order if (onClose) onClose(); break; case "MODIFY_POSITION": console.log("User wants to modify position:", message.position); // Handle position modification (SL/TP) if (onClose) onClose(); break; case "CLOSE_POSITION": console.log("User wants to close position:", message); // Call your API to close the position if (onClose) onClose(); break; case "ALERT_TRIGGERED": console.log("Alert triggered:", message.alert); break; default: console.log("Other event:", eventType); } }, });

Signature:

appCallback?: (event: { eventType: AppCallbackEventType, message: AppCallbackMessage, onClose?: () => void }) => void;

Available Event Types:

  • Trading Events: PLACE_ORDER, MODIFY_ORDER, CANCEL_ORDER, MODIFY_POSITION, CLOSE_POSITION, REVERSE_POSITION
  • Alert Events: ALERT_TRIGGERED, CREATE_ALERT, MODIFY_ALERT, DELETE_ALERT
  • Data Events: DOWNLOAD_DATA
  • UI Events: TAKE_SCREENSHOT, SHARE_CHART, PRINT_CHART, FULLSCREEN_TOGGLE, THEME_CHANGE, INTERVAL_CHANGE, SYMBOL_CHANGE

For complete details on all event types and message formats, see the Events API documentation.

🎯 Best Practices

Tip

Always Use onReady Callback

Use the onReady callback to access ChartInstance methods safely:

const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_KEY", onReady: (chartInstance) => { // Chart is ready - safe to call methods chartInstance.setSymbol("MSFT"); chartInstance.setBrokerAccounts(data); }, });

2. Handle Errors Gracefully

Always provide an onError callback:

const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_KEY", onError: (error) => { console.error("Chart error:", error); // Show user-friendly error message // Log to error tracking service }, });

3. Clean Up Resources (Critical!)

Always call destroy() when removing the chart:

// React component cleanup useEffect(() => { const chart = createChart("#chart", config); return () => { // Cleanup when component unmounts chart.destroy(); }; }, []);

Why this is critical:

  • βœ… Prevents WebSocket subscription leaks
  • βœ… Avoids receiving data for destroyed charts
  • βœ… Prevents memory leaks and performance issues
  • βœ… Required when recreating charts

4. Use Trading Events Properly

Handle trading events through appCallback and always call onClose():

const chart = createChart("#chart", { // ... config appCallback: ({ eventType, message, onClose }) => { switch (eventType) { case "PLACE_ORDER": // Call your API placeOrderAPI(message.order) .then(() => { // Close the dialog on success if (onClose) onClose(); }) .catch((error) => { console.error("Order failed:", error); // Don't close dialog on error }); break; } }, });

5. Implement Datafeed Correctly

Ensure your datafeed implements all required methods:

const myDatafeed = { // Required: Fetch historical bars async getBars(symbolInfo, resolution, periodParams) { const { from, to, firstDataRequest } = periodParams; // Fetch and return bars return { bars: [...] }; }, // Required: Resolve symbol information resolveSymbol(symbolName, onResolve, onError) { // Fetch symbol info and call onResolve onResolve(symbolInfo); }, // Optional but recommended: Search symbols searchSymbols(userInput, exchange, symbolType, onResultReadyCallback) { // Search and return results onResultReadyCallback({ searchInProgress: false, items: [...] }); }, };

For complete working examples, see the Examples section.

Last updated on