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.
🏗️ How It Works
Section titled “🏗️ How It Works”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
📦 balances (Object)
Section titled “📦 balances (Object)”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.
📦 candle (Object)
Section titled “📦 candle (Object)”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.
Functions:
Section titled “Functions:”candle.prev(amount = 1)→ Returns past candle(s) offset byamount.candle.last(amount = 14)→ Returns the lastamountcandles as an array.
📦 ta Technical Analysis
Section titled “📦 ta Technical Analysis”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)
ReturnstrueiffirstSeriescrosses upward oversecondSeries. -
ta.crossdown(firstSeries, secondSeries)
ReturnstrueiffirstSeriescrosses downward belowsecondSeries. -
ta.crossany(firstSeries, secondSeries)
Returnstrueif 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, useind.addorUI Indicator Sectioninstead—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 }). -
ta.getVolatility(period = 14)
Calculates price volatility as the standard deviation of closing prices over the specified period.
📦 ob Order Book
Section titled “📦 ob Order Book”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).
Order Book Levels:
Section titled “Order Book Levels:”ob.asks→ List of ask levels:[[price, amount], ...].ob.bids→ List of bid levels:[[price, amount], ...].
📦 ind Indicators
Section titled “📦 ind Indicators”Manage and retrieve custom indicator data.
ind.get(name, prevAmount = 0)→ Get current or historical value of an indicator.ind.prev(name, prevAmount = 1)→ Get indicator value fromprevAmountsteps back.ind.last(name, amount = 14)→ Get an array of the lastamountvalues.ind.add(indicator)→ Add a new indicator for use in scripts.
📦 config
Section titled “📦 config”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 }).
📦 trader Context & Utilities
Section titled “📦 trader Context & Utilities”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.liveMode→trueif using live exchange data,falseif 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.001for 0.1%).trader.totalProfit→ Cumulative profit earned during the current trading session.trader.totalFee→ Total trading fees paid during the current session.
Utility Functions:
Section titled “Utility Functions:”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.
📦 order
Section titled “📦 order”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.order.getUnrealizedProfits()→ Calculate unrealized PnL across orders.order.getUnrealizedProfit(orderId)→ Get unrealized PnL for a single order.
📦 utils Helper functions
Section titled “📦 utils Helper functions”utils.baseToQuote(price?)
Calculates the maximum quote currency amount obtainable by selling your free base asset balance at the given price, or uses the current best bid (or candle close in backtests) if omitted (basically your max sellable amount).utils.quoteToBase(price?)
Calculates the maximum base asset amount purchasable with your free quote currency balance at the given price, or uses the current best ask (or candle close in backtests) if omitted (basically your max buyable amount).utils.round(number)
Roundsnumberto the current market precision; returnsnullif input is invalid.utils.roundToDecimals(number, decimal = 2)
Roundsnumbertodecimalplaces; returnsnullif inputs are invalid ordecimalis negative.
🔧 Global Utility Functions
Section titled “🔧 Global Utility Functions”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.
🛡️ Notes
Section titled “🛡️ Notes”- All functions are available globally within your trading scripts.
- Scripts run on every new candle (or tick, depending on your settings).
- Use
simulation modeto test scripts safely before live trading.