Account Information (Python)
Fetch user account data including balances, positions, and open orders.
Fetching User Info
The user info endpoint returns balances, positions, and orders for an account.
import requests
from base58 import b58encode
API_URL = "https://zo-devnet.n1.xyz"
def get_user_info(user_pubkey: bytes):
"""
Fetch user account information.
Args:
user_pubkey: 32-byte user public key
"""
pubkey_b58 = b58encode(user_pubkey).decode()
resp = requests.get(f"{API_URL}/user/{pubkey_b58}")
if resp.status_code != 200:
raise Exception(f"Failed to fetch user info: {resp.status_code}")
return resp.json()
# Example usage
user_pubkey = user_key.public_key().public_bytes_raw()
info = get_user_info(user_pubkey)
print("Balances:", info.get("balances", []))
print("Positions:", info.get("positions", []))
print("Open Orders:", info.get("orders", []))Understanding the Response
Balances
{
"tokenId": 1,
"available": 10000.0, # Available for trading
"locked": 500.0, # Locked in open orders
"total": 10500.0 # Total balance
}Positions
{
"marketId": 0,
"size": 0.5, # Position size (+ long, - short)
"entryPrice": 92000.0, # Average entry price
"unrealizedPnl": 250.0, # Current unrealized PnL
"liquidationPrice": 75000.0 # Estimated liquidation price
}Orders
{
"orderId": 12345,
"marketId": 0,
"side": "bid", # "bid" or "ask"
"price": 90000.0,
"size": 0.1,
"filledSize": 0.0,
"status": "open"
}Monitoring Positions
def monitor_positions(user_pubkey, interval=5):
"""Monitor positions and PnL in real-time."""
import time
pubkey_b58 = b58encode(user_pubkey).decode()
while True:
try:
resp = requests.get(f"{API_URL}/user/{pubkey_b58}")
info = resp.json()
print(f"\n{'='*50}")
print(f"Time: {time.strftime('%H:%M:%S')}")
for pos in info.get("positions", []):
if pos["size"] != 0:
print(f"Market {pos['marketId']}: "
f"Size={pos['size']:+.4f} "
f"Entry=${pos['entryPrice']:,.2f} "
f"PnL=${pos['unrealizedPnl']:+,.2f}")
time.sleep(interval)
except KeyboardInterrupt:
break
# monitor_positions(user_pubkey)Checking Available Margin
def get_available_margin(user_pubkey):
"""Calculate available margin for new trades."""
info = get_user_info(user_pubkey)
# Sum available balances (simplified)
total_available = sum(
b["available"] for b in info.get("balances", [])
if b["tokenId"] == 1 # USDC
)
# Account for unrealized PnL
unrealized_pnl = sum(
p["unrealizedPnl"] for p in info.get("positions", [])
)
return total_available + unrealized_pnl
margin = get_available_margin(user_pubkey)
print(f"Available margin: ${margin:,.2f}")Listing Open Orders
def get_open_orders(user_pubkey, market_id=None):
"""Get open orders, optionally filtered by market."""
info = get_user_info(user_pubkey)
orders = info.get("orders", [])
if market_id is not None:
orders = [o for o in orders if o["marketId"] == market_id]
for order in orders:
side = "BUY" if order["side"] == "bid" else "SELL"
print(f"Order {order['orderId']}: {side} "
f"{order['size']:.4f} @ ${order['price']:,.2f}")
return orders
# Get all BTC orders
btc_orders = get_open_orders(user_pubkey, market_id=0)Last updated on