Last updated: January 2026 | Reading time: 18 minutes | API version: 3.x
The Problem: Building a Crypto Portfolio Dashboard That Actually Works
Three months ago, I was contracted to build a real-time portfolio dashboard for a mid-sized crypto hedge fund. The requirement seemed straightforward: aggregate live price data from Binance, Bybit, OKX, and Deribit, calculate unrealized P&L across 47 trading pairs, and display everything on a React dashboard with sub-second refresh rates. Simple, right? Wrong.
After two weeks of wrestling with inconsistent API response formats, rate limiting errors, and malformed order book snapshots, I realized the hard way that understanding Binance's data structures isn't optional—it's the entire job. This tutorial is the guide I wish I had when I started.
By the end of this walkthrough, you'll understand every major Binance API data structure, how to parse them correctly in production code, and how to enhance your trading applications with AI-powered analysis using HolySheep AI for natural language query capabilities on your market data.
Why Binance API Data Structures Matter
Binance processes over $50 billion in daily trading volume, making it the world's largest cryptocurrency exchange by volume. Their API is the de facto standard—understanding their data schemas translates directly to Bybit, OKX, and most other CEX integrations.
Prerequisites
- Basic JavaScript/TypeScript or Python knowledge
- Node.js 18+ or Python 3.9+
- A Binance account with API key generation (no trading permissions needed for market data)
- Optional: HolySheep AI account for enhanced analytics ($1 per million tokens vs $7.30 on OpenAI)
1. Understanding the API Architecture
Binance offers three primary API endpoints:
- REST API (https://api.binance.com) — synchronous requests for order management, account data, and market snapshots
- WebSocket Streams (wss://stream.binance.com:9443) — real-time push updates for price feeds and order books
- Combined Streams — multiplexed WebSocket connections
2. Core Data Structures Explained
2.1 Klines (Candlestick Data)
Klines are the foundation of technical analysis. Each candlestick contains OHLCV data (Open, High, Low, Close, Volume) plus auxiliary fields.
// GET /api/v3/klines?symbol=BTCUSDT&interval=1h&limit=10
// Response format: Array of arrays
const binanceKlinesResponse = [
[
1706745600000, // Kline open time (Unix ms)
"43250.00", // Open price
"43500.00", // High price
"43100.00", // Low price
"43350.00", // Close price
"1250.50", // Base asset volume
1706749199999, // Kline close time
"54187500.00", // Quote asset volume
125, // Number of trades
"850.25", // Taker buy base volume
"36825000.00", // Taker buy quote volume
"0" // Unused field (ignore)
],
// ... more candles
];
// TypeScript interface for type safety
interface Kline {
openTime: number;
open: string;
high: string;
low: string;
close: string;
volume: string;
closeTime: number;
quoteVolume: string;
tradeCount: number;
takerBuyBaseVolume: string;
takerBuyQuoteVolume: string;
}
function parseKline(k: any[]): Kline {
return {
openTime: k[0],
open: k[1],
high: k[2],
low: k[3],
close: k[4],
volume: k[5],
closeTime: k[6],
quoteVolume: k[7],
tradeCount: k[8],
takerBuyBaseVolume: k[9],
takerBuyQuoteVolume: k[10],
};
}
// Usage example
const candles = binanceKlinesResponse.map(parseKline);
console.log(Latest close: $${candles[0].close} at ${new Date(candles[0].closeTime)});
2.2 Order Book (Depth Data)
The order book shows liquidity at each price level. Binance returns bids (buy orders) and asks (sell orders) with their respective quantities.
// GET /api/v3/depth?symbol=BTCUSDT&limit=100
// Real-time via WebSocket: {symbol}@depth@100ms
const orderBookResponse = {
lastUpdateId: 160, // Order book update ID (use for synchronization)
bids: [ // Buy side (price, quantity)
["43250.00", "12.50"], // Price 43250.00, Qty 12.50 BTC
["43248.50", "8.20"],
["43245.00", "25.00"],
],
asks: [ // Sell side
["43251.00", "10.00"],
["43252.50", "15.30"],
["43255.00", "5.00"],
]
};
// Class for managing order book state
class OrderBook {
bids: Map<number, number> = new Map(); // price -> quantity
asks: Map<number, number> = new Map();
lastUpdateId: number = 0;
update(orderBook: any) {
// CRITICAL: Only apply updates with higher lastUpdateId
if (orderBook.lastUpdateId <= this.lastUpdateId) {
console.warn('Stale order book update, ignoring');
return false;
}
// Clear and rebuild for full depth snapshots
if (orderBook.bids.length > 10) {
this.bids.clear();
this.asks.clear();
}
for (const [price, qty] of orderBook.bids) {
if (parseFloat(qty) === 0) {
this.bids.delete(parseFloat(price));
} else {
this.bids.set(parseFloat(price), parseFloat(qty));
}
}
for (const [price, qty] of orderBook.asks) {
if (parseFloat(qty) === 0) {
this.asks.delete(parseFloat(price));
} else {
this.asks.set(parseFloat(price), parseFloat(qty));
}
}
this.lastUpdateId = orderBook.lastUpdateId;
return true;
}
getSpread(): number {
const bestBid = Math.max(...this.bids.keys());
const bestAsk = Math.min(...this.asks.keys());
return bestAsk - bestBid;
}
getMidPrice(): number {
const bestBid = Math.max(...this.bids.keys());
const bestAsk = Math.min(...this.asks.keys());
return (bestBid + bestAsk) / 2;
}
}
const book = new OrderBook();
book.update(orderBookResponse);
console.log(Spread: $${book.getSpread().toFixed(2)}, Mid: $${book.getMidPrice().toFixed(2)});
2.3 Trade Streams (Real-time Fills)
// WebSocket: {symbol}@trade
// Push-based trade notifications
interface Trade {
e: "trade", // Event type
E: 1706745600000, // Event time
s: "BTCUSDT", // Symbol
t: 12345, // Trade ID
p: "43250.00", // Price
q: "0.500", // Quantity
b: 98765, // Buyer order ID
a: 98766, // Seller order ID
T: 1706745600000, // Trade time
m: false, // Is buyer maker?
}
// Count trades by direction for volume analysis
function analyzeTrades(trades: Trade[]) {
let buyVolume = 0;
let sellVolume = 0;
let buyCount = 0;
let sellCount = 0;
for (const trade of trades) {
const volume = parseFloat(trade.q);
if (trade.m) {
// Buyer is taker, seller is maker (sell pressure)
sellVolume += volume;
sellCount++;
} else {
// Buyer is maker, buyer initiated (buy pressure)
buyVolume += volume;
buyCount++;
}
}
const buyRatio = buyVolume / (buyVolume + sellVolume);
return {
buyVolume,
sellVolume,
buyCount,
sellCount,
buyRatio,
sentiment: buyRatio > 0.55 ? 'bullish' : buyRatio < 0.45 ? 'bearish' : 'neutral'
};
}
2.4 24-Hour Ticker Statistics
// GET /api/v3/ticker/24hr?symbol=BTCUSDT
interface Ticker24hr {
symbol: string; // "BTCUSDT"
priceChange: string; // Absolute price change
priceChangePercent: string; // Percentage change
weightedAvgPrice: string;
lastPrice: string; // Current price
lastQty: string; // Last trade quantity
bidPrice: string; // Best bid
bidQty: string; // Best bid quantity
askPrice: string; // Best ask
askQty: string; // Best ask quantity
openPrice: string; // 24h open
highPrice: string; // 24h high
lowPrice: string; // 24h low
volume: string; // Base asset volume (BTC)
quoteVolume: string; // Quote asset volume (USDT)
openTime: number; // Stats open time
closeTime: number; // Stats close time
firstId: number; // First trade ID
lastId: number; // Last trade ID
count: number; // Total trades in 24h
}
// Calculate price statistics
function getTickerSummary(ticker: Ticker24hr) {
const change = parseFloat(ticker.priceChange);
const changePercent = parseFloat(ticker.priceChangePercent);
const isPositive = change >= 0;
return {
price: $${parseFloat(ticker.lastPrice).toLocaleString()},
change: ${isPositive ? '+' : ''}${change.toFixed(2)} (${isPositive ? '+' : ''}${changePercent.toFixed(2)}%),
high24h: $${parseFloat(ticker.highPrice).toLocaleString()},
low24h: $${parseFloat(ticker.lowPrice).toLocaleString()},
volume24h: ${(parseFloat(ticker.quoteVolume) / 1e6).toFixed(2)}M USDT,
};
}
3. Building the HolySheep AI Integration
Now for the game-changer: integrating AI-powered analysis. Instead of manually parsing and interpreting all this market data, you can use HolySheep AI to query your Binance data in natural language. At $1 per million tokens, it's 85% cheaper than OpenAI's $7.30 rate.
// HolySheep AI Integration for Binance Data Analysis
// base_url: https://api.holysheep.ai/v1
// Pricing: $1/M tokens vs OpenAI's $7.30/M
const HOLYSHEEP_API_KEY = process.env.HOLYSHEEP_API_KEY;
const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';
interface HolySheepResponse {
id: string;
model: string;
created: number;
choices: Array<{
index: number;
message: {
role: string;
content: string;
};
finish_reason: string;
}>;
usage: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
}
interface MarketAnalysisRequest {
currentPrice: string;
priceChange24h: string;
volume24h: string;
orderBookDepth: { bids: [string, string][]; asks: [string, string][] };
recentTrades: Trade[];
klines: Kline[];
}
async function analyzeWithHolySheep(data: MarketAnalysisRequest): Promise<string> {
const response = await fetch(${HOLYSHEEP_BASE_URL}/chat/completions, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${HOLYSHEEP_API_KEY},
},
body: JSON.stringify({
model: 'gpt-4.1', // $8/MTok or use deepseek-v3.2 at $0.42/MTok
messages: [
{
role: 'system',
content: `You are a crypto trading analyst. Analyze the provided Binance market data
and provide actionable insights. Format your response with bullet points.`
},
{
role: 'user',
content: `Analyze this BTC/USDT market data:
Current Price: ${data.currentPrice}
24h Change: ${data.priceChange24h}
24h Volume: ${data.volume24h}
Order Book (top 5 levels):
Bids: ${data.orderBookDepth.bids.slice(0, 5).map(([p, q]) => $${p} (${q} BTC)).join(', ')}
Asks: ${data.orderBookDepth.asks.slice(0, 5).map(([p, q]) => $${p} (${q} BTC)).join(', ')}
Recent Trades: ${data.recentTrades.slice(0, 10).map(t =>
${t.m ? 'SELL' : 'BUY'} ${t.q} @ $${t.p}).join(', ')}
Provide: 1) Market sentiment, 2) Support/resistance levels, 3) Trade recommendations`
}
],
temperature: 0.3, // Lower temp for trading analysis
max_tokens: 500,
}),
});
const result: HolySheepResponse = await response.json();
return result.choices[0].message.content;
}
// Usage in your trading bot
async function runTradingAnalysis() {
// Fetch Binance data (simplified)
const [ticker, orderBook, trades] = await Promise.all([
fetch('https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT').then(r => r.json()),
fetch('https://api.binance.com/api/v3/depth?symbol=BTCUSDT&limit=100').then(r => r.json()),
// In production, use WebSocket for real-time trades
Promise.resolve([]) // Placeholder
]);
const analysis = await analyzeWithHolySheep({
currentPrice: ticker.lastPrice,
priceChange24h: ${ticker.priceChangePercent}%,
volume24h: $${(parseFloat(ticker.quoteVolume) / 1e6).toFixed(2)}M,
orderBookDepth: orderBook,
recentTrades: trades,
klines: []
});
console.log('AI Analysis:', analysis);
}
runTradingAnalysis();
4. WebSocket Real-time Architecture
// Production WebSocket manager with reconnection and heartbeat
// HolySheep API: https://api.holysheep.ai/v1
class BinanceWebSocketManager {
private streams: Map<string, WebSocket> = new Map();
private reconnectAttempts: Map<string, number> = new Map();
private maxReconnectAttempts = 5;
private heartbeatInterval: NodeJS.Timeout | null = null;
constructor(private symbols: string[], private onTrade: (trade: Trade) => void) {}
connect() {
// Build combined stream URL for multiple symbols
const streams = this.symbols.flatMap(s => [
${s.toLowerCase()}@trade,
${s.toLowerCase()}@depth@100ms,
${s.toLowerCase()}@ticker
]).join('/');
const wsUrl = wss://stream.binance.com:9443/stream?streams=${streams};
const ws = new WebSocket(wsUrl);
ws.on('open', () => {
console.log(WebSocket connected to ${this.symbols.length} streams);
this.startHeartbeat(ws);
});
ws.on('message', (data: string) => {
try {
const message = JSON.parse(data);
this.handleMessage(message);
} catch (e) {
console.error('Failed to parse WebSocket message:', e);
}
});
ws.on('close', (code, reason) => {
console.log(WebSocket closed: ${code} - ${reason});
this.scheduleReconnect(streams);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error);
});
this.streams.set(streams, ws);
return ws;
}
private handleMessage(message: any) {
const { stream, data } = message;
const eventType = stream.split('@')[1];
switch (eventType) {
case 'trade':
this.onTrade(data as Trade);
break;
case 'depth':
// Update order book state
break;
case 'ticker':
// Update 24h stats
break;
}
}
private startHeartbeat(ws: WebSocket) {
this.heartbeatInterval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping();
}
}, 30000);
}
private scheduleReconnect(streams: string) {
const attempts = this.reconnectAttempts.get(streams) || 0;
if (attempts >= this.maxReconnectAttempts) {
console.error('Max reconnect attempts reached');
return;
}
const delay = Math.min(1000 * Math.pow(2, attempts), 30000);
console.log(Reconnecting in ${delay}ms (attempt ${attempts + 1}));
setTimeout(() => {
this.reconnectAttempts.set(streams, attempts + 1);
this.connect();
}, delay);
}
disconnect() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
}
this.streams.forEach(ws => ws.close());
this.streams.clear();
}
}
// Usage with HolySheep AI batch analysis
const wsManager = new BinanceWebSocketManager(
['BTCUSDT', 'ETHUSDT', 'BNBUSDT'],
async (trade: Trade) => {
// Buffer trades for batch analysis every 5 seconds
tradeBuffer.push(trade);
}
);
wsManager.connect();
// Batch process to HolySheep every 5 seconds
setInterval(async () => {
if (tradeBuffer.length > 0) {
const batchAnalysis = await analyzeWithHolySheep({
currentPrice: '0',
priceChange24h: '0',
volume24h: '0',
orderBookDepth: { bids: [], asks: [] },
recentTrades: tradeBuffer.splice(0, 50),
klines: []
});
console.log('Batch analysis:', batchAnalysis);
}
}, 5000);
5. Error Handling and Rate Limits
Rate Limit Headers
// Binance rate limits:
// - 1200 requests/minute for weight=1 endpoints
// - 10 requests/second for order placement
// - Headers: X-MBX-USED-WEIGHT, X-MBX-ORDER-COUNT-10S
interface RateLimitConfig {
maxRequests: number;
windowMs: number;
currentWeight: number;
}
class RateLimitedClient {
private limits: Map<string, RateLimitConfig> = new Map();
private requestQueue: Array<() => Promise<any>> = [];
constructor() {
this.limits.set('weight', { maxRequests: 1200, windowMs: 60000, currentWeight: 0 });
this.limits.set('orders', { maxRequests: 10, windowMs: 10000, currentWeight: 0 });
}
async execute(endpoint: string, weight: number, request: () => Promise<any>) {
const limit = this.limits.get('weight')!;
const now = Date.now();
// Check if we need to wait
if (limit.currentWeight + weight > limit.maxRequests) {
console.log(Rate limit approaching, waiting...);
await this.sleep(1000);
return this.execute(endpoint, weight, request);
}
try {
limit.currentWeight += weight;
const result = await request();
// Reset counter after window expires
setTimeout(() => {
limit.currentWeight = Math.max(0, limit.currentWeight - weight);
}, limit.windowMs);
return result;
} catch (error: any) {
if (error.status === 429) {
console.warn('Rate limited, backing off...');
await this.sleep(5000);
return this.execute(endpoint, weight, request);
}
throw error;
}
}
private sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
6. Performance Benchmarks
| Metric | Binance | Bybit | OKX |
|---|---|---|---|
| API Latency (avg) | 12ms | 18ms | 22ms |
| Order Book Depth | 5,000 levels | 1,000 levels | 400 levels |
| WebSocket Messages/sec | 100,000+ | 50,000 | 30,000 |
| Rate Limit (REST) | 1,200/min | 600/min | 600/min |
| AI Integration Cost | HolySheep AI: $1/M tok | ||
7. Complete Integration Example
Here's a production-ready module combining everything we've learned:
// Complete Binance Market Data Service with HolySheep AI
// Using HolySheep API: https://api.holysheep.ai/v1
import WebSocket from 'ws';
import crypto from 'crypto';
const HOLYSHEEP_API = 'https://api.holysheep.ai/v1';
const HOLYSHEEP_KEY = process.env.HOLYSHEEP_API_KEY;
interface BinanceConfig {
baseUrl: string;
wsUrl: string;
symbols: string[];
apiKey?: string;
secretKey?: string;
}
class BinanceMarketDataService {
private ws: WebSocket | null = null;
private orderBooks: Map<string, OrderBook> = new Map();
private tradeBuffer: Map<string, Trade[]> = new Map();
private config: BinanceConfig;
constructor(config: BinanceConfig) {
this.config = config;
config.symbols.forEach(s => {
this.orderBooks.set(s, new OrderBook());
this.tradeBuffer.set(s, []);
});
}
async start() {
await this.connectWebSocket();
this.startProcessingLoop();
}
private async connectWebSocket() {
const streams = this.config.symbols.flatMap(s => [
${s.toLowerCase()}@depth20@100ms,
${s.toLowerCase()}@trade,
${s.toLowerCase()}@ticker
]).join('/');
const url = ${this.config.wsUrl}/stream?streams=${streams};
this.ws = new WebSocket(url);
this.ws.on('message', (data) => {
const msg = JSON.parse(data.toString());
this.processMessage(msg);
});
this.ws.on('error', (err) => console.error('WS Error:', err));
this.ws.on('close', () => {
console.log('Reconnecting...');
setTimeout(() => this.connectWebSocket(), 5000);
});
}
private processMessage(msg: any) {
const { stream, data } = msg;
const symbol = stream.split('@')[0].toUpperCase();
if (stream.includes('@depth')) {
this.orderBooks.get(symbol)?.update(data);
} else if (stream.includes('@trade')) {
this.tradeBuffer.get(symbol)?.push(data);
}
}
private startProcessingLoop() {
// Process and analyze every 10 seconds
setInterval(async () => {
for (const symbol of this.config.symbols) {
const trades = this.tradeBuffer.get(symbol) || [];
const book = this.orderBooks.get(symbol);
if (trades.length > 0 && book) {
const analysis = await this.getAIAnalysis(symbol, book, trades);
console.log(${symbol} Analysis:, analysis);
this.tradeBuffer.set(symbol, []);
}
}
}, 10000);
}
private async getAIAnalysis(symbol: string, book: OrderBook, trades: Trade[]): Promise<string> {
const response = await fetch(${HOLYSHEEP_API}/chat/completions, {
method: 'POST',
headers: {
'Authorization': Bearer ${HOLYSHEEP_KEY},
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'deepseek-v3.2', // $0.42/MTok - lowest cost option
messages: [{
role: 'user',
content: `Quick analysis for ${symbol}:
Price pressure: ${trades.filter(t => !t.m).length > trades.length / 2 ? 'BUYING' : 'SELLING'}
Volume: ${trades.reduce((sum, t) => sum + parseFloat(t.q), 0).toFixed(4)} BTC
Spread: $${book.getSpread().toFixed(2)}
Mid: $${book.getMidPrice().toFixed(2)}`
}],
max_tokens: 100,
}),
});
const result = await response.json();
return result.choices[0].message.content;
}
}
// Initialize service
const service = new BinanceMarketDataService({
baseUrl: 'https://api.binance.com',
wsUrl: 'wss://stream.binance.com:9443',
symbols: ['BTCUSDT', 'ETHUSDT'],
});
service.start();
Who It Is For / Not For
| Best For | Not Recommended For |
|---|---|
| Crypto trading bots and automation | High-frequency trading requiring sub-ms latency |
| Portfolio trackers and dashboards | Regulated financial products requiring SEC/FCA compliance |
| Algorithmic trading research | Applications requiring guaranteed uptime SLAs |
| Market analysis and backtesting | Direct trading without proper risk management |
Pricing and ROI
When building AI-powered crypto applications, token costs matter significantly. Here's the 2026 pricing comparison:
| Provider | Model | Price per 1M Tokens | Cost Efficiency |
|---|---|---|---|
| HolySheep AI | DeepSeek V3.2 | $0.42 | Best Value |
| HolySheep AI | Gemini 2.5 Flash | $2.50 | Budget |
| HolySheep AI | GPT-4.1 | $8.00 | Premium |
| HolySheep AI | Claude Sonnet 4.5 | $15.00 | High-End |
| OpenAI | GPT-4 | $30.00 | Expensive |
| Anthropic | Claude 3.5 | $15.00 | Premium |
ROI Calculation: A production crypto dashboard processing 10 million API calls per month with AI analysis can save $12,000+ annually by using HolySheep's DeepSeek V3.2 at $0.42/MTok instead of OpenAI's $30/MTok.
Why Choose HolySheep AI
- 85%+ Cost Savings: DeepSeek V3.2 at $0.42/MTok vs OpenAI's $7.30/MTok
- Multi-Exchange Support: Native integration with Binance, Bybit, OKX, and Deribit
- <50ms Latency: Optimized infrastructure for real-time market data processing
- Flexible Payments: WeChat Pay and Alipay supported for Chinese users, USD for international
- Free Credits: Sign up here and receive free tokens on registration
- Model Flexibility: Switch between GPT-4.1 ($8), Claude Sonnet 4.5 ($15), Gemini 2.5 Flash ($2.50), or DeepSeek V3.2 ($0.42)
Common Errors and Fixes
Error 1: "Invalid signature" on authenticated requests
// Problem: HMAC signature mismatch
// Cause: Incorrect timestamp, encoding, or secret key
// Solution: Double-encode the query string and use precise timestamp
function createSignedRequest(params: Record<string, string>) {
const timestamp = Date.now().toString();
const queryParams = {
...params,
timestamp,
recvWindow: '5000'
};
// Sort keys alphabetically
const sortedKeys = Object.keys(queryParams).sort();
const queryString = sortedKeys
.map(key => ${key}=${encodeURIComponent(queryParams[key])})
.join('&');
// Create HMAC SHA256 signature
const signature = crypto
.createHmac('sha256', API_SECRET)
.update(queryString)
.digest('hex');
return ${queryString}&signature=${signature};
}
// Correct request construction
const signedQuery = createSignedRequest({ symbol: 'BTCUSDT', side: 'BUY', quantity: '0.001', type: 'MARKET' });
Error 2: "Endpoint request timed out"
// Problem: Request timeout after 5000ms default
// Cause: Network latency, high server load, or missing rate limit handling
// Solution: Implement retry with exponential backoff and request timeout
async function fetchWithRetry(url: string, options: RequestInit, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000); // 10s timeout
const response = await fetch(url, {
...options,
signal: controller.signal
});
clearTimeout(timeout);
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After') || '5';
console.warn(Rate limited, waiting ${retryAfter}s...);
await new Promise(r => setTimeout(r, parseInt(retryAfter) * 1000));
continue;
}
return response;
} catch (error: any) {
if (error.name === 'AbortError') {
console.warn(Timeout, retry ${i + 1}/${retries});
} else if (i === retries - 1) {
throw error;
}
await new Promise(r => setTimeout(r, 1000 * Math.pow(2, i)));
}
}
}
Error 3: "Order book snapshot out of sync"
// Problem: Order book updates don't match snapshot
// Cause: Missing or incorrect lastUpdateId validation
// Solution: Always validate lastUpdateId before applying deltas
class ReliableOrderBook {
private bids: Map<number, number> = new Map();
private asks: Map<number, number> = new Map();
private lastUpdateId: number = 0;
private snapshotId: number = 0;
async initializeSnapshot(symbol: string) {
// Fetch a fresh snapshot
const response = await fetch(
https://api.binance.com/api/v3/depth?symbol=${symbol}&limit=1000
);
const snapshot = await response.json();
this.bids.clear();
this.asks.clear();
for (const [price, qty] of snapshot.bids) {
this.bids.set(parseFloat(price), parseFloat(qty));
}
for (const [price, qty] of snapshot.asks) {
this.asks.set(parseFloat(price), parseFloat(qty));
}
this.snapshotId = snapshot.lastUpdateId;
this.lastUpdateId = snapshot.lastUpdateId;
}
applyUpdate