Skip to Content

Market Data (Python)

Fetching public market data using Python’s requests library.

Markets and Tokens

import requests API_URL = "https://zo-mainnet.n1.xyz" def get_markets(): """Fetch all available markets.""" resp = requests.get(f"{API_URL}/info") data = resp.json() for market in data["markets"]: print(f"{market['marketId']}: {market['symbol']} " f"(price_dec={market['priceDecimals']}, size_dec={market['sizeDecimals']})") return data["markets"] def get_tokens(): """Fetch all available tokens.""" resp = requests.get(f"{API_URL}/info") data = resp.json() for token in data["tokens"]: print(f"{token['tokenId']}: {token['symbol']} ({token['decimals']} decimals)") return data["tokens"] markets = get_markets() # Output: # 0: BTCUSD (price_dec=1, size_dec=4) # 1: ETHUSD (price_dec=2, size_dec=3) # ...

Market Statistics

def get_market_stats(market_id: int): """Fetch detailed statistics for a market.""" resp = requests.get(f"{API_URL}/market/{market_id}/stats") stats = resp.json() print(f"Market {market_id} Stats:") print(f" Index Price: ${stats['indexPrice']:,.2f}") print(f" Mark Price: ${stats['perpStats']['mark_price']:,.2f}") print(f" Funding Rate: {stats['perpStats']['funding_rate']:.4%}") print(f" Open Interest: {stats['perpStats']['open_interest']:,.2f}") print(f" 24h Volume: ${stats['volumeQuote24h']:,.0f}") print(f" 24h High: ${stats['high24h']:,.2f}") print(f" 24h Low: ${stats['low24h']:,.2f}") return stats stats = get_market_stats(0) # BTC

Orderbook

def get_orderbook(market_id: int, depth: int = 10): """Fetch orderbook for a market.""" resp = requests.get(f"{API_URL}/orderbook", params={"marketId": market_id}) book = resp.json() print(f"\n{'BIDS':^25} | {'ASKS':^25}") print("-" * 53) for i in range(min(depth, max(len(book["bids"]), len(book["asks"])))): bid = book["bids"][i] if i < len(book["bids"]) else ["-", "-"] ask = book["asks"][i] if i < len(book["asks"]) else ["-", "-"] bid_str = f"{bid[1]:.4f} @ ${bid[0]:,.1f}" if bid[0] != "-" else "" ask_str = f"${ask[0]:,.1f} @ {ask[1]:.4f}" if ask[0] != "-" else "" print(f"{bid_str:>25} | {ask_str:<25}") return book orderbook = get_orderbook(0) # BTC

Recent Trades

from datetime import datetime def get_recent_trades(market_id: int, limit: int = 20): """Fetch recent trades for a market.""" resp = requests.get( f"{API_URL}/trades", params={"marketId": market_id, "pageSize": limit} ) data = resp.json() print(f"\nRecent Trades (Market {market_id}):") print(f"{'Time':^12} | {'Side':^4} | {'Price':^12} | {'Size':^10}") print("-" * 45) for trade in data["trades"]: time = datetime.fromtimestamp(trade["timestamp"] / 1000) side = "BUY" if trade["side"] == "bid" else "SELL" print(f"{time:%H:%M:%S} | {side:^4} | ${trade['price']:>10,.1f} | {trade['size']:>10.4f}") return data["trades"] trades = get_recent_trades(0)

Funding Rate Monitoring

import time from concurrent.futures import ThreadPoolExecutor def monitor_funding_rates(market_ids: list, interval: int = 60): """Monitor funding rates for multiple markets.""" def fetch_stats(market_id): resp = requests.get(f"{API_URL}/market/{market_id}/stats") return resp.json() print("Monitoring funding rates (Ctrl+C to stop)...") try: while True: with ThreadPoolExecutor(max_workers=5) as executor: all_stats = list(executor.map(fetch_stats, market_ids)) print(f"\n{datetime.now():%Y-%m-%d %H:%M:%S}") for stats in all_stats: market_id = stats["marketId"] funding = stats["perpStats"]["funding_rate"] mark = stats["perpStats"]["mark_price"] print(f" Market {market_id}: {funding:+.4%} @ ${mark:,.2f}") time.sleep(interval) except KeyboardInterrupt: print("\nStopped.") # Monitor BTC, ETH, SOL # monitor_funding_rates([0, 1, 2], interval=60)

WebSocket Streaming

For real-time data, use WebSockets:

import asyncio import websockets import json async def stream_candles(symbol: str, resolution: str = "1"): """Stream real-time candle data.""" uri = f"wss://zo-mainnet.n1.xyz/ws/candle@{symbol}:{resolution}" async with websockets.connect(uri) as ws: print(f"Connected to {symbol} {resolution}m candles") async for message in ws: candle = json.loads(message) print(f"O: {candle['o']:.1f} H: {candle['h']:.1f} " f"L: {candle['l']:.1f} C: {candle['c']:.1f}") # Run with: asyncio.run(stream_candles("BTCUSD", "1"))

Full Market Dashboard

def market_dashboard(market_id: int = 0): """Display a comprehensive market dashboard.""" # Fetch all data info = requests.get(f"{API_URL}/info").json() stats = requests.get(f"{API_URL}/market/{market_id}/stats").json() book = requests.get(f"{API_URL}/orderbook", params={"marketId": market_id}).json() market = next(m for m in info["markets"] if m["marketId"] == market_id) print(f"\n{'='*50}") print(f"{market['symbol']} Market Dashboard") print(f"{'='*50}") print(f"\nPRICES") print(f"Index: ${stats['indexPrice']:,.2f}") print(f"Mark: ${stats['perpStats']['mark_price']:,.2f}") spread = book['asks'][0][0] - book['bids'][0][0] if book['bids'] and book['asks'] else 0 print(f"Spread: ${spread:.1f}") print(f"\n24H STATS") print(f"Volume: ${stats['volumeQuote24h']:,.0f}") print(f"High: ${stats['high24h']:,.2f}") print(f"Low: ${stats['low24h']:,.2f}") print(f"\nFUNDING") print(f"Rate: {stats['perpStats']['funding_rate']:+.4%}") print(f"Next: {stats['perpStats']['next_funding_time']}") print(f"\nORDERBOOK (Top 5)") print(f"{'BIDS':^20} | {'ASKS':^20}") for i in range(5): bid = book['bids'][i] if i < len(book['bids']) else [0, 0] ask = book['asks'][i] if i < len(book['asks']) else [0, 0] print(f"{bid[1]:.4f} @ ${bid[0]:,.1f} | ${ask[0]:,.1f} @ {ask[1]:.4f}") market_dashboard(0)
Last updated on