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

utility-functions.mddocs/

Utility Functions

Utility functions provide essential tools for cryptocurrency operations including mathematical precision, cryptographic operations, time handling, data manipulation, and encoding/decoding functions.

Capabilities

Precision Mathematics

Handle high-precision decimal arithmetic required for cryptocurrency calculations.

/**
 * Precise decimal arithmetic class for cryptocurrency calculations
 */
class Precise {
  constructor(number: string | number);
  
  /** Convert to string representation */
  toString(): string;
  
  /** Convert to number (may lose precision) */
  valueOf(): number;
  
  /** Static method to add two precise numbers */
  static stringAdd(a: string, b: string): string;
  
  /** Static method to subtract two precise numbers */
  static stringSub(a: string, b: string): string;
  
  /** Static method to multiply two precise numbers */
  static stringMul(a: string, b: string): string;
  
  /** Static method to divide two precise numbers */
  static stringDiv(a: string, b: string): string;
  
  /** Static method to compare two precise numbers */
  static stringEquals(a: string, b: string): boolean;
  
  /** Static method to check if first number is greater than second */
  static stringGt(a: string, b: string): boolean;
  
  /** Static method to check if first number is less than second */
  static stringLt(a: string, b: string): boolean;
}

/**
 * Convert number to string with specified precision
 * @param number - Number to convert
 * @param precision - Decimal places
 * @param rounding - Rounding mode
 * @returns Formatted string
 */
function decimalToPrecision(number: string, rounding: number, precision: number): string;

/**
 * Get precision from string representation
 * @param str - Number string
 * @returns Number of decimal places
 */
function precisionFromString(str: string): number;

Usage Examples:

// High-precision calculations
const price = new Precise('50000.123456789');
const amount = new Precise('0.001234567');
const cost = Precise.stringMul(price.toString(), amount.toString());
console.log(`Cost: ${cost}`); // Precise calculation without floating point errors

// Safe arithmetic operations
const balance1 = '1000.123456789';
const balance2 = '2000.987654321';
const total = Precise.stringAdd(balance1, balance2);
console.log(`Total: ${total}`);

// Precision formatting
const formatted = decimalToPrecision('123.456789', 0, 4); // Round to 4 decimals
console.log(`Formatted: ${formatted}`); // "123.4568"

Time Functions

Handle timestamps, date formatting, and time-related operations.

/**
 * Convert timestamp to ISO8601 string
 * @param timestamp - Timestamp in milliseconds (optional, uses current time)
 * @returns ISO8601 formatted string
 */
function iso8601(timestamp?: number): string;

/**
 * Parse ISO8601 string to timestamp
 * @param timestamp - ISO8601 string
 * @returns Timestamp in milliseconds
 */
function parse8601(timestamp: string): number;

/**
 * Get current timestamp in seconds
 * @returns Current timestamp in seconds
 */
function seconds(): number;

/**
 * Get current timestamp in milliseconds
 * @returns Current timestamp in milliseconds
 */
function milliseconds(): number;

/**
 * Get current timestamp in microseconds
 * @returns Current timestamp in microseconds
 */
function microseconds(): number;

/**
 * Get current timestamp (alias for milliseconds)
 * @returns Current timestamp in milliseconds
 */
function now(): number;

/**
 * Format timestamp as YYYY-MM-DD
 * @param timestamp - Timestamp in milliseconds (optional)
 * @returns Date string in YYYY-MM-DD format
 */
function yyyymmdd(timestamp?: number): string;

/**
 * Format timestamp as YYYY-MM-DD HH:MM:SS
 * @param timestamp - Timestamp in milliseconds (optional)
 * @returns Datetime string
 */
function ymdhms(timestamp?: number): string;

Usage Examples:

// Current time operations
const currentTime = now();
const isoString = iso8601(currentTime);
const backToTimestamp = parse8601(isoString);
console.log(`Current: ${currentTime}, ISO: ${isoString}, Back: ${backToTimestamp}`);

// Date formatting
const dateStr = yyyymmdd(); // Current date
const datetimeStr = ymdhms(); // Current datetime
console.log(`Date: ${dateStr}, DateTime: ${datetimeStr}`);

// Time calculations
const oneDayAgo = now() - 24 * 60 * 60 * 1000;
const oneDayAgoStr = iso8601(oneDayAgo);
console.log(`24 hours ago: ${oneDayAgoStr}`);

Cryptographic Functions

Perform cryptographic operations required for API authentication and security.

/**
 * Calculate hash of data
 * @param request - Data to hash (string or bytes)
 * @param algorithm - Hash algorithm ('sha256', 'sha512', 'md5', etc.)
 * @returns Hex-encoded hash
 */
function hash(request: string | Uint8Array, algorithm: string): string;

/**
 * Calculate HMAC of data
 * @param request - Data to sign (string or bytes)
 * @param secret - Secret key (string or bytes)
 * @param algorithm - HMAC algorithm ('sha256', 'sha512', etc.)
 * @returns Hex-encoded HMAC
 */
function hmac(request: string | Uint8Array, secret: string | Uint8Array, algorithm: string): string;

/**
 * Calculate ECDSA signature
 * @param request - Data to sign
 * @param secret - Private key
 * @param algorithm - Signature algorithm
 * @returns Signature string
 */
function ecdsa(request: string, secret: string, algorithm: string): string;

Usage Examples:

// API signature generation (common pattern)
const apiKey = 'your-api-key';
const apiSecret = 'your-api-secret';
const timestamp = now().toString();
const method = 'POST';
const path = '/api/v1/order';
const body = JSON.stringify({ symbol: 'BTC/USDT', side: 'buy', amount: 0.001 });

// Create signature string
const signatureString = timestamp + method + path + body;
const signature = hmac(signatureString, apiSecret, 'sha256');

console.log(`Signature: ${signature}`);

// Hash data
const dataHash = hash('sensitive-data', 'sha256');
console.log(`Hash: ${dataHash}`);

Encoding Functions

Encode and decode data in various formats.

/**
 * Encode string to bytes
 * @param str - String to encode
 * @returns Byte array
 */
function encode(str: string): Uint8Array;

/**
 * Decode bytes to string
 * @param bytes - Byte array to decode
 * @returns Decoded string
 */
function decode(bytes: Uint8Array): string;

/**
 * Convert Base64 string to binary
 * @param str - Base64 string
 * @returns Byte array
 */
function base64ToBinary(str: string): Uint8Array;

/**
 * Convert binary to Base64 string
 * @param bytes - Byte array
 * @returns Base64 string
 */
function binaryToBase64(bytes: Uint8Array): string;

/**
 * Convert Base58 string to binary
 * @param str - Base58 string
 * @returns Byte array
 */
function base58ToBinary(str: string): Uint8Array;

/**
 * Convert binary to Base58 string
 * @param bytes - Byte array
 * @returns Base58 string
 */
function binaryToBase58(bytes: Uint8Array): string;

/**
 * URL encode parameters
 * @param params - Parameters object
 * @returns URL encoded string
 */
function urlencode(params: Dict): string;

Usage Examples:

// Base64 operations
const originalText = 'Hello, CCXT!';
const encoded = binaryToBase64(encode(originalText));
const decoded = decode(base64ToBinary(encoded));
console.log(`Original: ${originalText}, Encoded: ${encoded}, Decoded: ${decoded}`);

// URL encoding
const params = { symbol: 'BTC/USDT', side: 'buy', amount: 0.001 };
const urlEncoded = urlencode(params);
console.log(`URL encoded: ${urlEncoded}`);

// Base58 (common for Bitcoin addresses)
const binaryData = encode('test data');
const base58Encoded = binaryToBase58(binaryData);
const base58Decoded = decode(base58ToBinary(base58Encoded));
console.log(`Base58: ${base58Encoded}, Decoded: ${base58Decoded}`);

Generic Functions

General-purpose utility functions for data manipulation.

/**
 * Extend object with properties from another object
 * @param target - Target object
 * @param source - Source object
 * @returns Extended object
 */
function extend(target: Dict, source: Dict): Dict;

/**
 * Deep clone object
 * @param obj - Object to clone
 * @returns Cloned object
 */
function clone(obj: any): any;

/**
 * Deep extend multiple objects
 * @param objects - Objects to merge
 * @returns Merged object
 */
function deepExtend(...objects: Dict[]): Dict;

/**
 * Merge multiple objects
 * @param target - Target object
 * @param sources - Source objects
 * @returns Merged object
 */
function merge(target: Dict, ...sources: Dict[]): Dict;

/**
 * Omit specified keys from object
 * @param obj - Source object
 * @param keys - Keys to omit
 * @returns Object without specified keys
 */
function omit(obj: Dict, keys: string[]): Dict;

/**
 * Get unique elements from array
 * @param arr - Input array
 * @returns Array with unique elements
 */
function unique(arr: any[]): any[];

/**
 * Sum numeric array elements
 * @param arr - Numeric array
 * @returns Sum of elements
 */
function sum(arr: number[]): number;

/**
 * Generate UUID
 * @returns UUID string
 */
function uuid(): string;

/**
 * Generate 16-character UUID
 * @returns 16-character UUID
 */
function uuid16(): string;

/**
 * Generate 22-character UUID
 * @returns 22-character UUID
 */
function uuid22(): string;

Usage Examples:

// Object operations
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const extended = extend(obj1, obj2); // { a: 1, b: 3, c: 4 }
const cloned = clone(obj1);

// Array operations
const duplicates = [1, 2, 2, 3, 3, 3, 4];
const uniqueValues = unique(duplicates); // [1, 2, 3, 4]
const total = sum([1, 2, 3, 4, 5]); // 15

// ID generation
const orderId = uuid();
const shortId = uuid16();
console.log(`Order ID: ${orderId}, Short ID: ${shortId}`);

// Object filtering
const largeObject = { a: 1, b: 2, c: 3, d: 4, e: 5 };
const filtered = omit(largeObject, ['b', 'd']); // { a: 1, c: 3, e: 5 }