π 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.
π― 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;
};
/**
* 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;
/** 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;
};
/**
* Chart theme
*/
type ChartTheme = "light" | "dark";
/**
* Chart configuration object for createChart function
*/
type ChartConfig = {
// ========================================================================
// Required Properties
// ========================================================================
/** Datafeed object with required methods for fetching chart data */
datafeed: Datafeed;
/** Initial symbol to display (e.g., "AAPL", "BYBIT:FUTURE:BTCUSDT") */
symbol: string;
/** Initial time interval (e.g., "1m", "5m", "1D") */
interval: string;
/** Your SDK license key */
licenseKey: string;
// ========================================================================
// Display Options
// ========================================================================
/** Chart theme - 'light' or 'dark' (default: "light") */
theme?: ChartTheme;
/** Theme color for chart background (e.g., "dark", "#1a1a1a") */
themeColor?: string;
/** Enable automatic resizing (default: true) */
autosize?: boolean;
/** Chart width - number in pixels or string with units (default: "100%") */
width?: number | string;
/** Chart height - number in pixels or string with units (default: "100%") */
height?: number | string;
/** Locale for internationalization (e.g., "en-US", "en") (default: "en-US") */
locale?: string;
// ========================================================================
// Feature Flags
// ========================================================================
/** Enable debug logging to console (default: false) */
debugLog?: boolean;
/** Hide search bar in top bar (default: false) */
disableSearch?: boolean;
/** Hide compare button in top bar (default: false) */
disableCompare?: boolean;
/** Hide drawing toolbar in top bar (default: false) */
hideDrawingToolBar?: boolean;
/** Enable always draw mode (default: false) */
alwaysDrawMode?: boolean;
// ========================================================================
// Configuration Overrides
// ========================================================================
/** Override default initial chart configuration */
defaultInitialChartConfig?: DefaultInitialChartConfig;
/** Trading configuration overrides */
trading?: TradingConfig;
/** Context menu configuration (New in v1.0.47) */
contextMenu?: ContextMenuOptions;
/** Popup display preferences */
popups?: PopupsConfig;
/** Favorite symbols configuration */
favourite?: FavouriteConfig;
// ========================================================================
// UI Customization
// ========================================================================
/** Object to exclude specific UI elements or features */
exclude?: ExcludeOptions;
// ========================================================================
// Event Callbacks
// ========================================================================
/** Callback for trading events and application-level events */
appCallback?: AppCallbackEventHandler;
/** Callback when chart is ready and initialized */
onReady?: OnReadyEventHandler;
/** Callback for errors during chart initialization or operation */
onError?: OnErrorEventHandler;
};
/**
* UI element exclusion options
*/
type ExcludeOptions = {
/** Hide left panel */
leftPanel?: boolean;
/** Hide right panel */
rightPanel?: boolean;
/** Hide top bar */
topBar?: boolean;
/** Hide bottom bar */
bottomBar?: boolean;
/**
* Array of indicator types to exclude from the indicators menu
* @example ["SMA", "EMA", "RSI", "MACD"]
*/
indicators?: string[];
};
/**
* Trading configuration options
*/
type TradingConfig = {
// ========================================================================
// Core Trading Settings
// ========================================================================
/** Enable trading features (default: false) */
enableTrading?: boolean;
// ========================================================================
// UI Display Options
// ========================================================================
/** Show reverse button in trading panel (default: true) */
showReverseButton?: boolean;
/** Show open orders panel (default: true) */
showOpenOrders?: boolean;
/** Show positions panel (default: true) */
showPositions?: boolean;
/** Show executions/trades panel (default: true) */
showExecutions?: boolean;
/** Show notifications panel (default: true) */
showNotifications?: boolean;
// ========================================================================
// Trading Behavior
// ========================================================================
/** Enable beep sound on order execution (default: true) */
beep?: boolean;
/** Enable quick trade mode (default: false) */
quickTradeMode?: boolean;
/** Enable Stop order options in context menus (default: false) */
supportStopOrders?: boolean;
/** Enable Stop-Limit order options in context menus (default: false) */
supportStopLimitOrders?: boolean;
// ========================================================================
// Take Profit Settings
// ========================================================================
/** Enable take profit defaults (default: false) */
enableTakeProfitDefaults?: boolean;
/** Default take profit spread (default: 1) */
defaultTakeProfitSpread?: number;
/** Default take profit spread type: "tick" | "price" | "percent" (default: "tick") */
defaultTakeProfitSpreadType?: "tick" | "price" | "percent";
// ========================================================================
// Stop Loss Settings
// ========================================================================
/** Enable stop loss defaults (default: false) */
enableStopLossDefaults?: boolean;
/** Default stop loss spread (default: 1) */
defaultStopLossSpread?: number;
/** Default stop loss spread type: "tick" | "price" | "percent" (default: "tick") */
defaultStopLossSpreadType?: "tick" | "price" | "percent";
// ========================================================================
// Position Display Settings
// ========================================================================
/** Trading box alignment: "left" | "right" (default: "right") */
boxAlignment?: "left" | "right";
/** Order/position line category: "extended" | "compact" (default: "extended") */
lineCategory?: "extended" | "compact";
};
/**
* Context menu configuration options (New in v1.0.47)
*/
type ContextMenuOptions = {
/** Show trading options (Buy/Sell buttons) in context menu (default: true) */
showTradingOptions?: boolean;
};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?: string;
};
/**
* 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
* This is the TradingView-compatible 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, subscribeTicks, unsubscribeTicks, getMarks, getTimescaleMarks, destroy
*/
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
// ========================================================================
/**
* 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) => 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;
/**
* 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- Valid - β
BTC/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") */
symbol: string;
/** Full symbol name with exchange (e.g., "BYBIT:FUTURE:BTCUSDT") */
full_name: string;
/** Human-readable description/name (e.g., "BTC / USDT PERPETUAL FUTURES") */
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;
};
/**
* 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
Available Configuration Options
// β
IMPLEMENTED - Current ChartConfig interface
// This is the actual interface used by createChart()
interface ChartConfig {
// Required
symbol: string; // Trading symbol
interval: string; // Chart interval
datafeed: Datafeed; // Your datafeed implementation
licenseKey: string; // Your license key
// Optional - Display
theme?: ChartTheme; // Chart theme (default: "light")
autosize?: boolean; // Enable automatic resizing (default: true)
width?: number | string; // Chart width (default: "100%")
height?: number | string; // Chart height (default: "100%")
// Optional - Features
enableTrading?: boolean; // Enable trading features (default: false)
debugLog?: boolean; // Enable debug logging (default: false)
skipLicenseValidation?: boolean; // Skip license validation (for demos)
// Optional - UI Customization
exclude?: ExcludeOptions; // Exclude specific UI elements
// Event callbacks (type-safe - message type narrows based on eventType)
appCallback?: AppCallbackEventHandler; // Trading and app events
onReady?: (chartInstance: ChartInstance) => void; // Chart ready callback
onError?: (error: Error | ChartError | string) => void; // Error callback
}π 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)
| "STOP_LOSS" // Modify existing stop loss price
| "NEW_STOP_LOSS" // Add new stop loss (first time)
| "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 | string | null; // Take profit price
stopLoss?: number | string | 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)
// 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
| "PLACE_ORDER"
| "PLACE_BASKET_ORDER"
| "EDIT_ORDER"
| "PLACE_ORDER_DIRECT"
| "MODIFY_POSITION"
| "MODIFY_ORDER_DIRECT"
| "MODIFY_ORDER"
| "CANCEL_ORDER"
| "EXIT_ALL_POSITIONS"
| "CANCEL_ALL_ORDERS"
| "GET_ACCOUNT_SUMMARY"
| "CONNECT_BROKER"
// Alert events
| "CREATE_ALERT"
| "DELETE_ALERT"
| "MODIFY_ALERT"
// Data events
| "DOWNLOAD_MORE_DATA_BY_DATE"
| "DOWNLOAD_MORE_DATA"
// UI events
| "OPEN_SETTINGS"
| "OPEN_LAYERS"
| "OPEN_OBJECT_PROPERTIES"
| "OPEN_INDICATORS_MODAL"
// Chart events
| "CHART_SELECTED"
| "CHART_MODE_CHANGED"
// Allow any string for extensibility
| (string & {});
/**
* 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: UIEventMessage;
}
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
// Low-level chart widget instance (returned by getChartInstance())
interface ChartWidgetInstance {
container: HTMLElement; // Chart container element
// Additional methods available on the underlying chart instance
// (This is the TradingView chart widget instance)
}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
interface Resolution {
scale: number; // Scale value (e.g., 1, 5, 15)
unit: "S" | "D" | "W" | "M"; // Time unit: Second, Day, Week, Month
text: string; // Display text (e.g., "1m", "5m", "1D")
}π§ 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?: any;
}
// 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
- React + TypeScript Integration - Complete implementation guide
- Vanilla JavaScript Example - Basic integration
- Time Marks Example - Custom time marks
- CodePen Examples - Live interactive demos