> For the complete documentation index, see [llms.txt](https://docs.outpoll.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.outpoll.com/api/futures-api/python-examples/futures-examples/live-pnl-monitor.md).

# 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: `LONG` at the best bid, `SHORT` at the best ask — the same prices the API uses for `upn`

Start with [Setup & Helpers](broken://pages/5f82d3397698cce89dbce1b8ec851e2c9aceba84) if you still need the shared prerequisites.

{% code title="live\_pnl.py" %}

```python
#!/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())
```

{% endcode %}

## Example Output

{% code title="terminal.txt" %}

```
pair        side              size             entry        uPnL    ROE %
BTCUSDT     LONG        0.01700000    83797.00000000       12.41     8.71
ETHUSDT     SHORT       0.50000000     3120.40000000       -3.05    -1.95

total uPnL 9.36   updated 14:32:05 UTC
```

{% endcode %}

{% hint style="info" %}
The account stream sends `upn` as `null`, so unrealized PnL is calculated from market data. The formula shown is for linear pairs; the script skips inverse pairs.
{% endhint %}

## Related Pages

* [Account stream](broken://pages/cedd682d52eba2750e492fcfadf9fb27ca28deb8)
* [Best Quote](broken://pages/f1d5d4ce1e41b692bc11f5d61d9c6799c0f9477e)
* [Get Open Positions](broken://pages/8a65b0267b58d7282fdacb75e81c6a9b308f8eac#get-open-positions)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.outpoll.com/api/futures-api/python-examples/futures-examples/live-pnl-monitor.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
