π 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
| Parameter | Type | Required | Description |
|---|---|---|---|
container | HTMLElement | string | β | DOM element or CSS selector for chart container |
config | ChartConfig | β | Chart configuration object |
ChartConfig Properties
| Property | Type | Required | Description |
|---|---|---|---|
datafeed | Datafeed | β | Datafeed implementation for market data |
symbol | string | β | Initial symbol (e.g., βAAPLβ, βBYBIT:FUTURE:BTCUSDTβ) |
interval | string | β | Initial interval (e.g., β1mβ, β5mβ, β1Hβ, β1Dβ) |
licenseKey | string | β | Your SDK license key |
theme | "light" | "dark" | β | Chart theme (default: βlightβ) |
themeColor | string | β | Theme color (e.g., βdarkβ, β#1a1a1aβ) |
autosize | boolean | β | Enable automatic resizing (default: true) |
width | number | string | β | Chart width (default: β100%β) |
height | number | string | β | Chart height (default: β100%β) |
locale | string | β | Locale (e.g., βen-USβ, βenβ) (default: βen-USβ) |
debugLog | boolean | β | Enable debug logging (default: false) |
trading | TradingConfig | β | Trading configuration |
exclude | ExcludeOptions | β | Exclude UI elements |
appCallback | AppCallbackEventHandler | β | Trading and app event handler |
onReady | OnReadyEventHandler | β | Callback when chart is ready |
onError | OnErrorEventHandler | β | Error callback |
| β¦ | β¦ | β | See Configuration for all options |
Returns: ChartWrapper
Returns a ChartWrapper object with lifecycle management methods:
| Method | Return Type | Description |
|---|---|---|
destroy() | void | Destroy chart and clean up resources |
isDestroyed() | boolean | Check if chart is destroyed |
getChartInstance() | ChartInstance | Get the underlying ChartInstance component |
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
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
useEffectcleanup
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 trueReturns: 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
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
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: [...] });
},
};π Related Documentation
- Chart Widget API - ChartInstance methods for chart control
- Datafeed API - Implement custom data sources
- Configuration - Complete ChartConfig options
- Events - All available event types
- TypeScript Types - Type definitions
- React + TypeScript Example - Complete implementation
For complete working examples, see the Examples section.