Live PnL Monitor
Unrealized PnL of every open position, updated from the account stream and best bid/ask
Use this script to watch your positions without polling the REST API.
What This Script Does
Loads open positions once over REST
Keeps them current from the account stream: opened, changed, closed and liquidated positions
Follows the best bid and ask of every pair
Recalculates unrealized PnL and ROE every second:
LONGat the best bid,SHORTat the best ask — the same prices the API uses forupn
Start with Setup & Helpers if you still need the shared prerequisites.
#!/usr/bin/env python3
"""Live unrealized PnL of your open positions: account stream + best bid/ask."""
import asyncio
import json
import time
from decimal import Decimal
import websockets
from futures_helpers import (MARKET_DATA_WS, FuturesClient, connect_private, get_pairs,
keepalive)
API_KEY = "your-api-key"
API_SECRET = "your-api-secret"
pairs = {p["gid"]: p for p in get_pairs().values()}
positions = {} # position id -> position object
quotes = {} # pair id -> (bid, ask)
def is_linear(pos):
return pairs[pos["pi"]]["ct"] == "LINEAR_PERPETUAL"
def upnl(pos):
"""Linear pairs: LONG closes at the bid, SHORT at the ask (same price the API uses)."""
bid, ask = quotes.get(pos["pi"], (None, None))
if pos["s"] == "LONG" and bid is not None:
return (bid - pos["e"]) * pos["sz"]
if pos["s"] == "SHORT" and ask is not None:
return (pos["e"] - ask) * pos["sz"]
return None
def draw():
print("\033[H\033[J", end="")
print(f"{'pair':<12}{'side':<6}{'size':>16}{'entry':>18}{'uPnL':>12}{'ROE %':>9}")
total = Decimal(0)
for pos in positions.values():
pnl = upnl(pos)
if pnl is None:
print(f"{pairs[pos['pi']]['nm']:<12}{pos['s']:<6}{pos['sz']:>16}{pos['e']:>18}{'—':>12}")
continue
total += pnl
roe = pnl / pos["im"] * 100 if pos["im"] else Decimal(0)
print(f"{pairs[pos['pi']]['nm']:<12}{pos['s']:<6}{pos['sz']:>16}{pos['e']:>18}"
f"{pnl:>12.2f}{roe:>9.2f}")
print(f"\ntotal uPnL {total:.2f} updated {time.strftime('%H:%M:%S', time.gmtime())} UTC")
async def watch_account():
ws = await connect_private(API_KEY, API_SECRET, "/ws/account")
ping = asyncio.create_task(keepalive(ws))
try:
async for raw in ws:
if raw == "pong":
continue
msg = json.loads(raw, parse_float=Decimal)
if msg.get("e") != "POSITION":
continue
if not is_linear(msg["d"]):
continue
if msg["a"] in ("CLOSED", "LIQUIDATED"):
positions.pop(msg["d"]["id"], None)
else:
positions[msg["d"]["id"]] = msg["d"]
finally:
ping.cancel()
async def watch_quotes():
async with websockets.connect(MARKET_DATA_WS + "/ws/book/best") as ws:
# By ID: the current quote of each held pair arrives at once.
# all: covers pairs you open later (their quotes arrive on the next change).
held = sorted({pos["pi"] for pos in positions.values()})
if held:
await ws.send(json.dumps({"act": "subscribe", "ps": held}))
await ws.send(json.dumps({"act": "subscribe", "all": True}))
ping = asyncio.create_task(keepalive(ws))
try:
async for raw in ws:
if raw == "pong":
continue
msg = json.loads(raw, parse_float=Decimal)
if "er" not in msg:
quotes[int(msg["pi"])] = (msg["b"][0], msg["a"][0])
finally:
ping.cancel()
async def redraw():
while True:
draw()
await asyncio.sleep(1)
async def main():
# Snapshot over REST, then keep it current from the streams
client = FuturesClient(API_KEY, API_SECRET)
for pos in client.get("/api/v1/positions"):
if is_linear(pos):
positions[pos["id"]] = pos
await asyncio.gather(watch_account(), watch_quotes(), redraw())
asyncio.run(main())Example Output
Related Pages
Account stream
Best Quote
Get Open Positions
Was this helpful?

