Skip to content

Script API

TradeHub includes a built-in JavaScript-based scripting API that allows you to create highly customized trading bots. Whether you are new to coding or already familiar with algorithmic trading, this API is designed to be easy to use, while still powerful enough for advanced users.

This page introduces the key global objects and functions available in your trading scripts.


Your script runs in a secure JavaScript environment with several global objects already available. These globals provide access to market data, trading actions, indicators, account balances, and more.

You can write scripts that:

  • Monitor price data and indicators
  • Automatically place, cancel, or manage orders
  • Log and visualize data directly on the chart
  • React to custom events during trading

Represents your account balances for the current trading pair.

  • balances.base.free → Free amount of base currency (e.g., BTC in BTC/USDT).
  • balances.base.locked → Amount of base currency locked in orders.
  • balances.quote.free → Free amount of quote currency (e.g., USDT in BTC/USDT).
  • balances.quote.locked → Amount of quote currency locked in orders.

Provides access to current and historical candle data.

  • candle.open → Current candle’s open price.
  • candle.high → Current candle’s high price.
  • candle.low → Current candle’s low price.
  • candle.close → Current candle’s close price.
  • candle.volume → Current candle’s volume.
  • candle.prev(amount = 1) → Returns past candle(s) offset by amount.
  • candle.last(amount = 14) → Returns the last amount candles as an array.

Built-in tools for plotting and detecting indicator events.

  • ta.plot(name, value, settings = {}, stepBack = 0)
    Plot data on the chart.

  • ta.clearPlot(name, stepBack = 0)
    Remove a specific plot.

  • ta.crossUp(firstSeries, secondSeries)
    Returns true if firstSeries crosses upward over secondSeries.

  • ta.crossDown(firstSeries, secondSeries)
    Returns true if firstSeries crosses downward below secondSeries.

  • ta.crossAny(firstSeries, secondSeries)
    Returns true if any cross occurs in either direction.

  • ta.calc(metaKey, name, inputs, options = {})
    Calculates a built-in indicator with the given input. You can create indicators that use other indicators or your custom-calculated values as inputs, also known as Meta Indicators.
    If you need standard indicators with OHLCV (candlestick) data as input, use ind.add or UI Indicator Section instead—for both better performance and ease of use.
    If the indicator requires a single input, provide it directly. If it requires multiple inputs, pass them as an array—in the correct order.
    Example: ta.calc("unique-name", "sma", candle.close, { period: 20 }).
    Example: ta.calc("unique-name2", "adx", [candle.high,candle.close], { period: 20 }).


Access live order book data. For backtest candle.close will be returned.

  • ob.bestAsk → Best ask (lowest sell price).
  • ob.bestBid → Best bid (highest buy price).
  • ob.asks → List of ask levels: [[price, amount], ...].
  • ob.bids → List of bid levels: [[price, amount], ...].

Manage and retrieve custom indicator data.

  • ind.ref(alias, outputName?) → Returns a reference to an indicator output for use in indicator releated functions.
  • ind.get(aliasOrRef, prevAmount = 0) → Get current or historical value of an indicator.
  • ind.prev(aliasaliasOrRef, prevAmount = 1) → Get indicator value from prevAmount steps back.
  • ind.last(aliasOrRef, amount = 14) → Get an array of the last amount values.
  • ind.add(indicator) → Add a new indicator for use in scripts.

Note: Functions that accept an indicator alias also accept an ind.ref(name, output) reference. This allows you to work with specific outputs of multi-output indicators.

// Get the last 10 values of BBANDS lower band
ind.get(ind.ref('bbands', 'lower'), 10);

This is especially useful for helpers like crossUp. For example, a simple MACD strategy can be written as:

// Buy when MACD crosses above its signal line
if (ta.crossUp(ind.ref('macd', 'macd'), ind.ref('macd', 'signal'))) {
await order.buy();
}

Read and modify bot configuration at runtime.

  • config.get(key) → Retrieve a configuration value.
  • config.set(configs) → Update configuration with an object.
    Example: config.set({ mySetting: true }).

Provides trading session context and utility methods.

  • trader.timeframe → Active bot timeframe (e.g., "1m", "15m").
  • trader.market → Current trading market (e.g., "BTC/USDT").
  • trader.exchange → Exchange name (e.g., "Binance").
  • trader.liveModetrue if using live exchange data, false if using historical backtest data. (Data source indicator)
  • trader.orderMode"simulated" (Backtest/Paper) or "live" (real orders). (Order execution mode)
  • trader.exchangeFee → Current exchange fee rate (e.g., 0.001 for 0.1%).
  • trader.positions – Returns all open positions (bought base awaiting sell) with unrealized PnL.
  • trader.trades.last(n = 10) – Returns the last n closed trades (realized positions).
  • trader.trades.count() – Returns the total number of closed trades.
  • trader.updateLog(...msgs) → Updates recent log message.
  • trader.clearLogs(amount) → Clear recent log entries.
  • trader.addHook(type, callback, once = false) → Register event hooks (e.g., on candle updates). (Check Usage)
  • trader.abort(msg) → Safely stop bot execution with a message.
  • trader.require(pluginName, pluginOptions = {}) → Load a plugin with options.

Place, cancel, and manage orders.

  • async order.buy(price, amount, timeInForce = "GTC", params = {}) → Place a buy order.
  • async order.sell(price, amount, timeInForce = "GTC", params = {}) → Place a sell order.
  • async order.placeOrder(type, side, amount, price, timeInForce, params) → General order function.
  • async order.cancel(orderId) → Cancel a specific order.
  • async order.cancelAll() → Cancel all open orders.
  • order.get(orderId) → Retrieve details of a specific order.
  • order.last(amount = 10) → Get a list of recent orders.
  • order.openOrders → Retrieve all open orders.

  • metrics.startTime
    Backtest or trading start timestamp (ms).

  • metrics.endTime
    Backtest or trading end timestamp (ms).

  • metrics.roi
    Total return on investment (ROI).

  • metrics.holdRoi
    Buy-and-hold ROI for the same period.

  • metrics.annualizedRoi
    Annualized return on investment.

  • metrics.positiveTrades
    Number of profitable trades.

  • metrics.negativeTrades
    Number of losing trades.

  • metrics.breakevenTrades
    Number of break-even trades.

  • metrics.pnl
    Net realized PnL after fees (quote currency).

  • metrics.totalFee
    Total fees paid (quote currency).

  • metrics.profitFactor
    Gross profit divided by gross loss.

  • metrics.winLossRatio
    Average winning trade divided by average losing trade.

  • metrics.winRatio
    Percentage of winning trades (0–100).

  • metrics.lossRatio
    Percentage of losing trades (0–100).

  • metrics.avgProfitPercentage
    Average profit percentage per trade.

  • metrics.avgDrawdownPercentage
    Average drawdown percentage per trade.

  • metrics.riskRewardRatio
    Average reward divided by average risk.

  • metrics.expectancy
    Expected profit per trade.

  • metrics.breakEvenPercentage
    Break-even win rate percentage.

  • metrics.maxProfitPercentage
    Maximum profit percentage achieved in a single trade.

  • metrics.maxProfitDuration
    Duration of the most profitable trade.

  • metrics.maxDrawdownPercentage
    Maximum drawdown percentage observed.

  • metrics.maxDrawdownDuration
    Duration of the maximum drawdown.

  • metrics.maxTradeDuration
    Longest trade duration.

  • metrics.minTradeDuration
    Shortest trade duration.

  • metrics.minBalance
    Lowest account equity reached.

  • metrics.maxBalance
    Highest account equity reached.


  • utils.maxBuyAmount(price?) – Returns the maximum buyable amount at the given price (or current best bid if omitted), with the estimated fee already deducted.
  • utils.round(number)
    Rounds number to the current market precision; returns null if input is invalid.
  • utils.roundToDecimals(number, decimal = 2)
    Rounds number to decimal places; returns null if inputs are invalid or decimal is negative.

Global utility functions for logging and storage.

  • log(...args) → Log any values to log table.
  • set(key, value) → Store a custom variable.
  • get(key) → Retrieve a stored variable.

  • All functions are available globally within your trading scripts.
  • Scripts run on every new candle (or tick, depending on your settings).
  • Use simulation mode to test scripts safely before live trading.