Utility functions provide common helpers for data manipulation, formatting, authentication, cryptographic operations, and time handling. These functions are essential for building robust cryptocurrency trading applications.
Common utilities for working with objects, arrays, and data structures.
/**
* Generic utility functions
*/
declare const keys: (object: object) => string[];
declare const values: (object: object) => any[];
declare const extend: (...objects: object[]) => object;
declare const clone: (object: any) => any;
declare const ordered: (object: object) => object;
declare const unique: (array: any[]) => any[];
declare const arrayConcat: (a: any[], b: any[]) => any[];
declare const inArray: (needle: any, haystack: any[]) => boolean;
declare const toArray: (object: any) => any[];
declare const isEmpty: (object: any) => boolean;
declare const keysort: (object: object) => object;
declare const sort: (array: any[]) => any[];
declare const groupBy: (array: any[], key: string) => object;
declare const indexBy: (array: any[], key: string) => object;
declare const filterBy: (array: any[], key: string, value?: any) => any[];
declare const sortBy: (array: any[], key: string, descending?: boolean) => any[];
declare const flatten: (array: any[]) => any[];
declare const pluck: (array: any[], key: string) => any[];
declare const omit: (object: object, ...keys: string[]) => object;
declare const sum: (...values: number[]) => number;
declare const deepExtend: (...objects: object[]) => object;
declare const merge: (target: object, ...sources: object[]) => object;Usage Examples:
import { keys, values, extend, clone, unique, groupBy, sortBy } from 'ccxt';
// Object utilities
const market = { symbol: 'BTC/USDT', base: 'BTC', quote: 'USDT' };
console.log(keys(market)); // ['symbol', 'base', 'quote']
console.log(values(market)); // ['BTC/USDT', 'BTC', 'USDT']
// Object merging
const config = extend({}, { apiKey: 'key1' }, { secret: 'secret1' });
console.log(config); // { apiKey: 'key1', secret: 'secret1' }
// Deep cloning
const originalOrder = { id: '123', symbol: 'BTC/USDT', nested: { fee: 0.1 } };
const clonedOrder = clone(originalOrder);
clonedOrder.nested.fee = 0.2; // Won't affect original
// Array utilities
const prices = [100, 200, 100, 300, 200];
const uniquePrices = unique(prices); // [100, 200, 300]
// Data grouping
const trades = [
{ symbol: 'BTC/USDT', side: 'buy', amount: 1 },
{ symbol: 'ETH/USDT', side: 'buy', amount: 10 },
{ symbol: 'BTC/USDT', side: 'sell', amount: 0.5 },
];
const tradesBySymbol = groupBy(trades, 'symbol');
// { 'BTC/USDT': [...], 'ETH/USDT': [...] }
const sortedByAmount = sortBy(trades, 'amount', true); // DescendingString manipulation functions for text processing and formatting.
/**
* String utility functions
*/
declare const capitalize: (string: string) => string;
declare const strip: (string: string) => string;
declare const numberToString: (number: number) => string;Usage Examples:
import { capitalize, strip } from 'ccxt';
// String formatting
const exchangeName = capitalize('binance'); // 'Binance'
const cleanSymbol = strip(' BTC/USDT '); // 'BTC/USDT'
// Format exchange names for display
function formatExchangeName(name) {
return capitalize(name.replace(/([a-z])([A-Z])/g, '$1 $2'));
}
console.log(formatExchangeName('coinbasepro')); // 'Coinbasepro'
console.log(formatExchangeName('binanceus')); // 'Binanceus'Number formatting and precision handling functions.
/**
* Number utility functions
*/
declare const precisionFromString: (string: string) => number;
declare const decimalToPrecision: (
number: number,
roundingMode: number,
precision: number
) => string;
declare const numberToString: (number: number) => string;Usage Examples:
import { precisionFromString, decimalToPrecision } from 'ccxt';
// Determine precision from string
const precision1 = precisionFromString('123.456'); // 3
const precision2 = precisionFromString('0.00001'); // 5
// Format numbers to specific precision
const formatted = decimalToPrecision(123.456789, 0, 2); // '123.46'
const price = decimalToPrecision(0.123456, 0, 6); // '0.123456'
// Format trading amounts
function formatAmount(amount, symbol) {
const precision = symbol.includes('BTC') ? 8 : 2;
return decimalToPrecision(amount, 0, precision);
}
console.log(formatAmount(0.12345678, 'BTC/USDT')); // '0.12345678'
console.log(formatAmount(123.456, 'ETH/USDT')); // '123.46'Time formatting, parsing, and manipulation functions.
/**
* Time utility functions
*/
declare const timeout: (ms: number, promise: Promise<any>) => Promise<any>;
declare const sleep: (ms: number) => Promise<void>;
declare const iso8601: (timestamp: number) => string;
declare const parse8601: (string: string) => number;
declare const rfc2616: (timestamp: number) => string;
declare const yyyymmdd: (timestamp: number, separator?: string) => string;
declare const ymdhms: (timestamp: number, separator?: string) => string;
declare const yymmdd: (timestamp: number, separator?: string) => string;
declare const mdy: (timestamp: number, separator?: string) => string;
declare const ymd: (timestamp: number, separator?: string) => string;Usage Examples:
import { timeout, sleep, iso8601, parse8601, yyyymmdd } from 'ccxt';
// Add timeout to promises
async function fetchWithTimeout(exchange, symbol) {
try {
return await timeout(5000, exchange.fetchTicker(symbol));
} catch (error) {
console.log('Request timed out after 5 seconds');
throw error;
}
}
// Delay between requests
async function rateLimitedRequests(exchange, symbols) {
const results = [];
for (const symbol of symbols) {
const ticker = await exchange.fetchTicker(symbol);
results.push(ticker);
await sleep(1000); // Wait 1 second between requests
}
return results;
}
// Time formatting
const now = Date.now();
console.log(iso8601(now)); // '2024-01-15T10:30:45.123Z'
console.log(yyyymmdd(now)); // '20240115'
console.log(yyyymmdd(now, '-')); // '2024-01-15'
// Parse time strings
const timestamp = parse8601('2024-01-15T10:30:45.123Z');
console.log(timestamp); // 1705315845123
// Format trade timestamps
function formatTradeTime(trade) {
return {
...trade,
datetime: iso8601(trade.timestamp),
date: yyyymmdd(trade.timestamp, '-'),
};
}Cryptographic functions for authentication and data integrity.
/**
* Cryptographic utility functions
*/
declare const hash: (message: string, algorithm: string, digest?: string) => string;
declare const hmac: (message: string, secret: string, algorithm: string, digest?: string) => string;
declare const jwt: (request: object, secret: string, algorithm?: string, isRSA?: boolean) => string;
declare const crc32: (string: string, signed?: boolean) => number;
declare const ecdsa: (message: string, secret: string, algorithm: string, hash?: string, fixedLength?: boolean) => any;
declare const eddsa: (message: string, secret: string, curve?: string) => string;
declare const rsa: (message: string, secret: string, hash?: string) => string;
declare const oath: (secret: string, timestamp?: number, window?: number) => string;Usage Examples:
import { hash, hmac, jwt } from 'ccxt';
// HMAC signatures for API authentication
function signRequest(message, secret) {
return hmac(message, secret, 'sha256', 'hex');
}
const signature = signRequest('GET/api/v1/account', 'my-secret-key');
console.log(signature); // HMAC-SHA256 signature
// JWT token generation
const payload = {
sub: 'user123',
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 3600, // 1 hour
};
const token = jwt(payload, 'jwt-secret', 'HS256');
console.log(token); // JWT token
// Hash functions
const messageHash = hash('sensitive-data', 'sha256', 'hex');
console.log(messageHash); // SHA-256 hash
// Custom authentication helper
function createAuthHeaders(apiKey, secret, timestamp, method, path, body = '') {
const message = timestamp + method + path + body;
const signature = hmac(message, secret, 'sha256', 'base64');
return {
'X-API-KEY': apiKey,
'X-TIMESTAMP': timestamp,
'X-SIGNATURE': signature,
};
}Encoding and decoding functions for various data formats.
/**
* Encoding utility functions
*/
declare const urlencodeBase64: (payload: string | Uint8Array) => string;
declare const base64ToString: (string: string) => string;
declare const stringToBase64: (string: string) => string;
declare const base16ToString: (string: string) => string;
declare const stringToBase16: (string: string) => string;
declare const base58ToString: (string: string) => string;
declare const stringToBase58: (string: string) => string;
declare const utf16ToString: (string: string) => string;
declare const stringToUtf16: (string: string) => string;Usage Examples:
import { base64ToString, stringToBase64, stringToBase16 } from 'ccxt';
// Base64 encoding/decoding
const originalData = 'Hello, CCXT!';
const encoded = stringToBase64(originalData);
const decoded = base64ToString(encoded);
console.log(encoded); // 'SGVsbG8sIENDWFQh'
console.log(decoded); // 'Hello, CCXT!'
// Hex encoding
const hexEncoded = stringToBase16('Binary data');
console.log(hexEncoded); // Hex representation
// URL-safe base64 encoding
const urlSafeEncoded = urlencodeBase64('data with special chars +/=');
console.log(urlSafeEncoded); // URL-safe base64Type checking and validation functions.
/**
* Type checking utility functions
*/
declare const isNumber: (value: any) => boolean;
declare const isInteger: (value: any) => boolean;
declare const isString: (value: any) => boolean;
declare const isObject: (value: any) => boolean;
declare const isArray: (value: any) => boolean;
declare const isDictionary: (value: any) => boolean;
declare const hasProps: (object: any) => boolean;Usage Examples:
import { isNumber, isString, isArray, isDictionary } from 'ccxt';
// Input validation
function validateOrderParams(symbol, type, side, amount, price) {
if (!isString(symbol)) throw new Error('Symbol must be a string');
if (!isString(type)) throw new Error('Type must be a string');
if (!isString(side)) throw new Error('Side must be a string');
if (!isNumber(amount)) throw new Error('Amount must be a number');
if (price !== undefined && !isNumber(price)) throw new Error('Price must be a number');
}
// Data structure validation
function validateMarketData(data) {
if (!isDictionary(data)) throw new Error('Market data must be an object');
if (!isArray(data.bids)) throw new Error('Bids must be an array');
if (!isArray(data.asks)) throw new Error('Asks must be an array');
}
// Safe property access
function safeGetProperty(obj, path) {
if (!isDictionary(obj)) return undefined;
const keys = path.split('.');
let current = obj;
for (const key of keys) {
if (!isDictionary(current) || !(key in current)) {
return undefined;
}
current = current[key];
}
return current;
}
const ticker = { symbol: 'BTC/USDT', last: 50000 };
console.log(safeGetProperty(ticker, 'symbol')); // 'BTC/USDT'
console.log(safeGetProperty(ticker, 'nonexistent.property')); // undefinedAdditional utility functions for specialized tasks.
/**
* Miscellaneous utility functions
*/
declare const aggregate: (bidasks: any[]) => any[];
declare const uuid: () => string;
declare const unCamelCase: (string: string) => string;
declare const packb: (object: any) => any;Usage Examples:
import { uuid, unCamelCase, aggregate } from 'ccxt';
// Generate unique identifiers
const orderId = uuid();
console.log(orderId); // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
// Convert camelCase to snake_case
const snakeCase = unCamelCase('fetchOpenOrders'); // 'fetch_open_orders'
const normalized = unCamelCase('createLimitOrder'); // 'create_limit_order'
// Aggregate order book data
const rawBids = [[100, 1], [100, 2], [99, 3]]; // [price, amount] pairs
const aggregatedBids = aggregate(rawBids);
console.log(aggregatedBids); // [[100, 3], [99, 3]] - amounts summed by price
// Create API method mapping
function createMethodMap(methods) {
const map = {};
methods.forEach(method => {
const snake = unCamelCase(method);
map[snake] = method;
});
return map;
}
const methodMap = createMethodMap(['fetchTicker', 'createOrder', 'cancelOrder']);
// { 'fetch_ticker': 'fetchTicker', 'create_order': 'createOrder', ... }