or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

account-management.mderror-handling.mdexchange-management.mdfunding-operations.mdindex.mdmarket-data.mdorder-management.mdtrading-operations.mdutility-functions.mdwebsocket-operations.md
tile.json

market-data.mddocs/

Market Data

Market data functionality provides access to real-time and historical market information including tickers, order books, trades, OHLCV candlestick data, and market metadata across all supported exchanges.

Capabilities

Market Information

Retrieve comprehensive information about available trading pairs, including trading rules, precision settings, and limits.

/**
 * Fetch all available markets from the exchange
 * @param params - Additional exchange-specific parameters
 * @returns Array of market objects with trading information
 */
fetchMarkets(params?: Dict): Promise<Market[]>;

interface Market {
  id: string;           // Exchange-specific market identifier
  symbol: string;       // Unified symbol (e.g., 'BTC/USDT')
  base: string;         // Base currency (e.g., 'BTC')
  quote: string;        // Quote currency (e.g., 'USDT')
  baseId: string;       // Exchange-specific base currency identifier
  quoteId: string;      // Exchange-specific quote currency identifier
  active: boolean;      // Whether market is currently active for trading
  type: MarketType;     // Market type: 'spot', 'margin', 'swap', 'future', 'option'
  subType?: 'linear' | 'inverse';  // Derivatives subtype
  spot: boolean;        // Whether this is a spot market
  margin: boolean;      // Whether margin trading is available
  swap: boolean;        // Whether this is a perpetual swap
  future: boolean;      // Whether this is a dated future
  option: boolean;      // Whether this is an options contract
  contract: boolean;    // Whether this is any type of derivative contract
  settle?: string;      // Settlement currency for derivatives
  settleId?: string;    // Exchange-specific settlement currency ID
  contractSize?: number; // Contract size for derivatives
  linear?: boolean;     // Whether derivative is linear (settled in quote currency)
  inverse?: boolean;    // Whether derivative is inverse (settled in base currency)
  expiry?: number;      // Expiration timestamp for futures/options
  expiryDatetime?: string; // Expiration datetime string
  strike?: number;      // Strike price for options
  optionType?: 'call' | 'put'; // Option type
  precision: {
    amount: number;     // Decimal places for order amounts
    price: number;      // Decimal places for prices
    cost?: number;      // Decimal places for cost calculations
  };
  limits: {
    amount?: {          // Minimum and maximum order amounts
      min: number;
      max: number;
    };
    price?: {           // Minimum and maximum prices
      min: number;
      max: number;
    };
    cost?: {            // Minimum and maximum order costs
      min: number;
      max: number;
    };
    leverage?: {        // Leverage limits for margin/derivatives
      min: number;
      max: number;
    };
  };
  maker?: number;       // Maker fee rate
  taker?: number;       // Taker fee rate
  percentage?: boolean; // Whether fees are percentage-based
  tierBased?: boolean;  // Whether fees are tier-based
  info: any;           // Raw exchange-specific market data
}

type MarketType = 'spot' | 'margin' | 'swap' | 'future' | 'option' | 'delivery' | 'index';

Usage Examples:

// Fetch all markets
const markets = await exchange.fetchMarkets();
console.log(`Found ${markets.length} markets`);

// Filter spot markets
const spotMarkets = markets.filter(market => market.spot);

// Filter futures markets
const futuresMarkets = markets.filter(market => market.future);

// Find specific market
const btcUsdtMarket = markets.find(market => market.symbol === 'BTC/USDT');
if (btcUsdtMarket) {
  console.log('Min order amount:', btcUsdtMarket.limits.amount?.min);
  console.log('Price precision:', btcUsdtMarket.precision.price);
  console.log('Maker fee:', btcUsdtMarket.maker);
}

// Group markets by base currency
const marketsByBase = markets.reduce((acc, market) => {
  const base = market.base;
  if (!acc[base]) acc[base] = [];
  acc[base].push(market);
  return acc;
}, {} as { [base: string]: Market[] });

Price Tickers

Get current price information including best bid/ask, 24-hour volume, and price changes.

/**
 * Fetch ticker data for a specific trading pair
 * @param symbol - Trading pair symbol (e.g., 'BTC/USDT')
 * @param params - Additional exchange-specific parameters
 * @returns Ticker object with current price information
 */
fetchTicker(symbol: string, params?: Dict): Promise<Ticker>;

/**
 * Fetch ticker data for multiple trading pairs
 * @param symbols - Array of trading pair symbols (optional, fetches all if not provided)
 * @param params - Additional exchange-specific parameters
 * @returns Dictionary of ticker objects indexed by symbol
 */
fetchTickers(symbols?: string[], params?: Dict): Promise<Tickers>;

interface Ticker {
  symbol: string;       // Trading pair symbol
  timestamp: number;    // Ticker timestamp in milliseconds
  datetime: string;     // Ticker datetime in ISO format
  high: number;         // Highest price in 24h period
  low: number;          // Lowest price in 24h period
  bid: number;          // Best bid price
  bidVolume?: number;   // Volume at best bid
  ask: number;          // Best ask price
  askVolume?: number;   // Volume at best ask
  vwap?: number;        // Volume-weighted average price
  open: number;         // Opening price (24h ago)
  close: number;        // Closing price (current)
  last: number;         // Last trade price
  previousClose?: number; // Previous closing price
  change?: number;      // Absolute price change (24h)
  percentage?: number;  // Percentage price change (24h)
  average?: number;     // Average of bid and ask
  baseVolume: number;   // 24h trading volume in base currency
  quoteVolume: number;  // 24h trading volume in quote currency
  info: any;           // Raw exchange-specific ticker data
}

type Tickers = { [symbol: string]: Ticker };

Usage Examples:

// Fetch single ticker
const ticker = await exchange.fetchTicker('BTC/USDT');
console.log(`BTC/USDT: $${ticker.last} (${ticker.percentage?.toFixed(2)}%)`);
console.log(`Bid: $${ticker.bid}, Ask: $${ticker.ask}`);
console.log(`24h Volume: ${ticker.baseVolume} BTC`);

// Fetch multiple tickers
const tickers = await exchange.fetchTickers(['BTC/USDT', 'ETH/USDT', 'ADA/USDT']);
Object.entries(tickers).forEach(([symbol, ticker]) => {
  console.log(`${symbol}: $${ticker.last} (${ticker.percentage?.toFixed(2)}%)`);
});

// Fetch all tickers
const allTickers = await exchange.fetchTickers();
const sortedByVolume = Object.values(allTickers)
  .sort((a, b) => b.quoteVolume - a.quoteVolume)
  .slice(0, 10);
console.log('Top 10 by volume:', sortedByVolume.map(t => t.symbol));

// Calculate spread
const spread = ticker.ask - ticker.bid;
const spreadPercentage = (spread / ticker.ask) * 100;
console.log(`Spread: $${spread.toFixed(2)} (${spreadPercentage.toFixed(3)}%)`);

Order Book Data

Access real-time order book information showing current buy and sell orders at different price levels.

/**
 * Fetch order book (market depth) for a trading pair
 * @param symbol - Trading pair symbol (e.g., 'BTC/USDT')
 * @param limit - Number of order book entries to fetch per side (optional)
 * @param params - Additional exchange-specific parameters
 * @returns Order book object with bids and asks
 */
fetchOrderBook(symbol: string, limit?: number, params?: Dict): Promise<OrderBook>;

interface OrderBook {
  symbol: string;           // Trading pair symbol
  bids: [number, number][]; // Buy orders as [price, amount] pairs, sorted by price desc
  asks: [number, number][]; // Sell orders as [price, amount] pairs, sorted by price asc
  timestamp: number;        // Order book timestamp in milliseconds
  datetime: string;         // Order book datetime in ISO format
  nonce?: number;           // Exchange-specific sequence number
  info: any;               // Raw exchange-specific order book data
}

Usage Examples:

// Fetch full order book
const orderBook = await exchange.fetchOrderBook('BTC/USDT');
console.log(`Order book for ${orderBook.symbol}:`);
console.log(`Best bid: $${orderBook.bids[0][0]} (${orderBook.bids[0][1]} BTC)`);
console.log(`Best ask: $${orderBook.asks[0][0]} (${orderBook.asks[0][1]} BTC)`);

// Fetch limited order book (top 10 levels)
const limitedOrderBook = await exchange.fetchOrderBook('BTC/USDT', 10);
console.log(`Fetched ${limitedOrderBook.bids.length} bid levels`);

// Calculate order book metrics
const bestBid = orderBook.bids[0][0];
const bestAsk = orderBook.asks[0][0];
const spread = bestAsk - bestBid;
const midPrice = (bestBid + bestAsk) / 2;

console.log(`Mid price: $${midPrice}`);
console.log(`Spread: $${spread} (${(spread/midPrice * 100).toFixed(3)}%)`);

// Calculate total volume at different levels
const bidVolume = orderBook.bids.slice(0, 5).reduce((sum, [price, amount]) => sum + amount, 0);
const askVolume = orderBook.asks.slice(0, 5).reduce((sum, [price, amount]) => sum + amount, 0);
console.log(`Top 5 levels - Bid volume: ${bidVolume}, Ask volume: ${askVolume}`);

// Find price level with specific volume
function findVolumeLevel(orders: [number, number][], targetVolume: number): number {
  let cumulativeVolume = 0;
  for (const [price, amount] of orders) {
    cumulativeVolume += amount;
    if (cumulativeVolume >= targetVolume) {
      return price;
    }
  }
  return orders[orders.length - 1][0]; // Return last price if target not reached
}

const priceFor1BTC = findVolumeLevel(orderBook.asks, 1.0);
console.log(`Price to buy 1 BTC: $${priceFor1BTC}`);

Trade History

Access public trade history showing recent executed trades with prices, volumes, and timestamps.

/**
 * Fetch recent public trades for a trading pair
 * @param symbol - Trading pair symbol (e.g., 'BTC/USDT')
 * @param since - Timestamp in milliseconds to fetch trades from (optional)
 * @param limit - Maximum number of trades to fetch (optional)
 * @param params - Additional exchange-specific parameters
 * @returns Array of trade objects
 */
fetchTrades(symbol: string, since?: number, limit?: number, params?: Dict): Promise<Trade[]>;

interface Trade {
  id: string;           // Exchange-specific trade identifier
  order?: string;       // Order ID that generated this trade (if available)
  timestamp: number;    // Trade timestamp in milliseconds
  datetime: string;     // Trade datetime in ISO format
  symbol: string;       // Trading pair symbol
  type?: OrderType;     // Order type that generated the trade
  side: OrderSide;      // Trade side: 'buy' or 'sell'
  amount: number;       // Trade amount in base currency
  price: number;        // Trade price in quote currency
  cost: number;         // Trade cost (amount * price)
  fee?: {               // Trade fee information
    currency: string;   // Fee currency
    cost: number;       // Fee amount
    rate?: number;      // Fee rate
  };
  info: any;           // Raw exchange-specific trade data
}

type OrderSide = 'buy' | 'sell';
type OrderType = 'limit' | 'market' | 'stop' | 'stop_limit';

Usage Examples:

// Fetch recent trades
const trades = await exchange.fetchTrades('BTC/USDT', undefined, 50);
console.log(`Fetched ${trades.length} recent trades`);

// Analyze recent trade activity
const buyTrades = trades.filter(trade => trade.side === 'buy');
const sellTrades = trades.filter(trade => trade.side === 'sell');
const buyVolume = buyTrades.reduce((sum, trade) => sum + trade.amount, 0);
const sellVolume = sellTrades.reduce((sum, trade) => sum + trade.amount, 0);

console.log(`Buy volume: ${buyVolume} BTC, Sell volume: ${sellVolume} BTC`);
console.log(`Buy/Sell ratio: ${(buyVolume / sellVolume).toFixed(2)}`);

// Calculate volume-weighted average price (VWAP)
const totalCost = trades.reduce((sum, trade) => sum + trade.cost, 0);
const totalVolume = trades.reduce((sum, trade) => sum + trade.amount, 0);
const vwap = totalCost / totalVolume;
console.log(`VWAP: $${vwap.toFixed(2)}`);

// Fetch trades since specific time
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
const dayTrades = await exchange.fetchTrades('BTC/USDT', oneDayAgo);
console.log(`Trades in last 24h: ${dayTrades.length}`);

// Find largest trades
const sortedByAmount = trades.sort((a, b) => b.amount - a.amount);
console.log('Largest trade:', sortedByAmount[0]);

OHLCV Candlestick Data

Access historical candlestick (OHLCV) data for technical analysis and charting.

/**
 * Fetch OHLCV (candlestick) data for a trading pair
 * @param symbol - Trading pair symbol (e.g., 'BTC/USDT')
 * @param timeframe - Timeframe string (e.g., '1m', '1h', '1d')
 * @param since - Timestamp in milliseconds to fetch data from (optional)
 * @param limit - Maximum number of candles to fetch (optional)
 * @param params - Additional exchange-specific parameters
 * @returns Array of OHLCV candles
 */
fetchOHLCV(symbol: string, timeframe?: string, since?: number, limit?: number, params?: Dict): Promise<OHLCV[]>;

// OHLCV candle structure: [timestamp, open, high, low, close, volume]
type OHLCV = [number, number, number, number, number, number];

/** Available timeframes (varies by exchange) */
readonly timeframes: { [key: string]: string };
// Common timeframes: '1m', '3m', '5m', '15m', '30m', '1h', '2h', '4h', '6h', '8h', '12h', '1d', '3d', '1w', '1M'

Usage Examples:

// Check available timeframes
console.log('Available timeframes:', exchange.timeframes);

// Fetch 1-hour candles
const candles = await exchange.fetchOHLCV('BTC/USDT', '1h', undefined, 100);
console.log(`Fetched ${candles.length} hourly candles`);

// Process candle data
candles.forEach(([timestamp, open, high, low, close, volume]) => {
  const date = new Date(timestamp);
  console.log(`${date.toISOString()}: O:${open} H:${high} L:${low} C:${close} V:${volume}`);
});

// Calculate simple moving average
function calculateSMA(candles: OHLCV[], period: number): number[] {
  const sma: number[] = [];
  for (let i = period - 1; i < candles.length; i++) {
    const sum = candles.slice(i - period + 1, i + 1)
      .reduce((acc, candle) => acc + candle[4], 0); // Sum closing prices
    sma.push(sum / period);
  }
  return sma;
}

const sma20 = calculateSMA(candles, 20);
console.log(`Latest 20-period SMA: ${sma20[sma20.length - 1]}`);

// Fetch data since specific date
const weekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
const weeklyCandles = await exchange.fetchOHLCV('BTC/USDT', '1d', weekAgo);

// Calculate price change
if (weeklyCandles.length >= 2) {
  const firstCandle = weeklyCandles[0];
  const lastCandle = weeklyCandles[weeklyCandles.length - 1];
  const priceChange = ((lastCandle[4] - firstCandle[1]) / firstCandle[1]) * 100;
  console.log(`7-day price change: ${priceChange.toFixed(2)}%`);
}

// Find highest and lowest prices
const highs = candles.map(candle => candle[2]);
const lows = candles.map(candle => candle[3]);
const highestPrice = Math.max(...highs);
const lowestPrice = Math.min(...lows);
console.log(`Period high: $${highestPrice}, Period low: $${lowestPrice}`);

Currency Information

Get information about supported currencies including deposit/withdrawal status and networks.

/**
 * Fetch information about all supported currencies
 * @param params - Additional exchange-specific parameters
 * @returns Dictionary of currency objects indexed by currency code
 */
fetchCurrencies(params?: Dict): Promise<{ [code: string]: Currency }>;

interface Currency {
  id: string;           // Exchange-specific currency identifier
  code: string;         // Unified currency code (e.g., 'BTC', 'ETH')
  name: string;         // Full currency name
  active: boolean;      // Whether currency is active for trading
  deposit: boolean;     // Whether deposits are enabled
  withdraw: boolean;    // Whether withdrawals are enabled
  fee?: number;         // Withdrawal fee amount
  fees?: {              // Network-specific fees
    [network: string]: number;
  };
  precision: number;    // Decimal precision for amounts
  limits: {
    amount?: {          // Min/max transaction amounts
      min: number;
      max: number;
    };
    withdraw?: {        // Min/max withdrawal amounts
      min: number;
      max: number;
    };
  };
  networks?: {          // Supported networks for deposits/withdrawals
    [network: string]: {
      id: string;
      network: string;
      name: string;
      active: boolean;
      deposit: boolean;
      withdraw: boolean;
      fee: number;
      precision: number;
      limits: {
        amount?: { min: number; max: number };
        withdraw?: { min: number; max: number };
      };
    };
  };
  info: any;           // Raw exchange-specific currency data
}

Usage Examples:

// Fetch all currencies
const currencies = await exchange.fetchCurrencies();
console.log(`Exchange supports ${Object.keys(currencies).length} currencies`);

// Check specific currency
const btc = currencies['BTC'];
if (btc) {
  console.log(`BTC deposits: ${btc.deposit}, withdrawals: ${btc.withdraw}`);
  console.log(`BTC withdrawal fee: ${btc.fee}`);
  console.log(`BTC networks:`, Object.keys(btc.networks || {}));
}

// Filter active currencies
const activeCurrencies = Object.entries(currencies)
  .filter(([code, currency]) => currency.active)
  .map(([code, currency]) => code);
console.log('Active currencies:', activeCurrencies);

// Find currencies with lowest withdrawal fees
const currenciesWithFees = Object.entries(currencies)
  .filter(([code, currency]) => currency.fee !== undefined)
  .sort(([, a], [, b]) => (a.fee || 0) - (b.fee || 0));
console.log('Lowest withdrawal fees:', currenciesWithFees.slice(0, 5));

// Check multi-network support
const multiNetworkCurrencies = Object.entries(currencies)
  .filter(([code, currency]) => currency.networks && Object.keys(currency.networks).length > 1)
  .map(([code, currency]) => ({ code, networks: Object.keys(currency.networks!) }));
console.log('Multi-network currencies:', multiNetworkCurrencies);