Skip to Content
While25SDK docs
ExamplesApps and panels

Account overview: every figure the broker states, and the day's P&L

An HTML page of the account as the broker reports it: day, realised and unrealised P&L, each funds figure under the broker's own label (with the money it lets you put into a new trade marked), per-asset balances where the venue has them, and a small inline SVG bar per position's P&L. Any figure the broker did not state says so in words, never as 0.

An HTML page of the account as the broker reports it: day, realised and unrealised P&L, each funds figure under the broker's own label (with the money it lets you put into a new trade marked), per-asset balances where the venue has them, and a small inline SVG bar per position's P&L. Any figure the broker did not state says so in words, never as 0.

Shows: App, ui.html, portfolio.funds() figures / roles / assets, funds_unavailable_reason(), day_pnl() / realised_pnl() / unrealised_pnl(), Money, inline built in Python, brand classes.

View on GitHub

apps/account_overview.py
"""Account overview: every figure the broker states, and the day's P&L

An HTML page of the account as the broker reports it: day, realised and
unrealised P&L, each funds figure under the broker's own label (with the
money it lets you put into a new trade marked), per-asset balances where
the venue has them, and a small inline SVG bar per position's P&L. Any figure
the broker did not state says so in words, never as 0.

Shows: App, ui.html, portfolio.funds() figures / roles / assets, funds_unavailable_reason(), day_pnl() / realised_pnl() / unrealised_pnl(), Money, inline <svg> built in Python, brand classes.
"""
import html

import while25
from while25 import App, on, ui

ui.panel("account_overview", "Account overview")
ui.layout(ui.html("view"))


def money_text(m):
    """(text, tone class) for a Money or None."""
    if m is None:
        return "not stated", "c-dim"
    return f"{m.value:,.2f} {m.currency}", ("c-profit" if m.value >= 0 else "c-loss")


def figure_text(fig):
    """One funds figure as the broker labels it, in its own kind."""
    if fig["kind"] == "text":
        return fig["text"] or "—"
    if fig["value"] is None:
        return "not stated"
    if fig["kind"] == "percent":
        return f"{fig['value']:.2f}%"
    if fig["kind"] == "money":
        return f"{fig['value']:,.2f} {fig['currency'] or ''}".strip()
    return f"{fig['value']:,}"


def pnl_bars(positions, width=360, row_h=18):
    """An inline SVG with one horizontal bar per position's P&L, centred on
    zero. Positions whose P&L is not known are listed without a bar."""
    vals = [(p["symbol"], float(p["pnl"].value) if p.get("pnl") else None) for p in positions]
    scale = max((abs(v) for _, v in vals if v is not None), default=0) or 1
    mid, half = width // 2 + 40, width // 2 - 50
    parts = [f'<svg width="{width + 80}" height="{row_h * len(vals) + 4}" role="img">']
    for i, (sym, v) in enumerate(vals):
        y = i * row_h + 2
        parts.append(f'<text x="0" y="{y + 12}" font-size="11" fill="var(--color-text-dim)">'
                     f'{html.escape(sym)}</text>')
        if v is None:
            parts.append(f'<text x="{mid + 4}" y="{y + 12}" font-size="11" '
                         f'fill="var(--color-text-dim)">P&amp;L not known</text>')
            continue
        w = abs(v) / scale * half
        x = mid if v >= 0 else mid - w
        colour = "var(--color-profit)" if v >= 0 else "var(--color-loss)"
        parts.append(f'<rect x="{x:.1f}" y="{y + 3}" width="{w:.1f}" height="{row_h - 6}" fill="{colour}"/>')
    parts.append(f'<line x1="{mid}" x2="{mid}" y1="0" y2="{row_h * len(vals) + 4}" '
                 f'stroke="var(--color-text-dim)" stroke-width="1"/></svg>')
    return "".join(parts)


def page(funds, why, pnl, positions):
    tiles = "".join(
        f'<div class="tile"><div class="k">{k}</div><div class="v t-num {c}">{t}</div></div>'
        for k, (t, c) in pnl.items())
    if funds is None:
        figures = f'<p class="c-dim">The broker has not stated its funds: {html.escape(why or "no reason given")}</p>'
    else:
        rows = "".join(
            f'<tr><td>{html.escape(f["section"])}</td><td>{html.escape(f["label"])}'
            f'{" <span class=badge-amber badge>available</span>" if "available" in f["roles"] else ""}</td>'
            f'<td>{html.escape(f["column"])}</td><td class="num">{html.escape(figure_text(f))}</td></tr>'
            for f in funds["figures"])
        assets = "".join(
            f'<tr><td>{html.escape(a["asset"])}</td>'
            + "".join(f'<td class="num">{"—" if a[k] is None else a[k]}</td>' for k in ("free", "locked", "total"))
            + "</tr>" for a in funds["assets"])
        figures = (f'<table class="dense"><thead><tr><th>Section</th><th>Figure</th><th>Column</th>'
                   f'<th class="num">Value</th></tr></thead><tbody>{rows or "<tr><td colspan=4 class=c-dim>No figures sent</td></tr>"}</tbody></table>'
                   + (f'<h3>Balances</h3><table class="dense"><thead><tr><th>Asset</th><th class="num">Free</th>'
                      f'<th class="num">Locked</th><th class="num">Total</th></tr></thead><tbody>{assets}</tbody></table>'
                      if assets else ""))
    chart = pnl_bars(positions) if positions else '<p class="c-dim">No open positions</p>'
    return (f'<div class="page stack"><div class="header"><h3>Account</h3>'
            f'<span class="stamp">every 10s</span></div><div class="tiles">{tiles}</div>'
            f'<div class="card"><div class="card-h">Funds, as the broker states them</div>'
            f'<div class="card-b">{figures}</div></div>'
            f'<div class="card"><div class="card-h">Open P&amp;L by position</div>'
            f'<div class="card-b">{chart}</div></div></div>')


class AccountOverview(App):
    id = "account_overview"
    label = "Account overview"

    @on.schedule(every="10s")
    def draw(self, ctx):
        pf = while25.portfolio
        funds = pf.funds()
        why = pf.funds_unavailable_reason() if funds is None else None
        pnl = {"Day P&L": money_text(pf.day_pnl()),
               "Realised": money_text(pf.realised_pnl()),
               "Unrealised": money_text(pf.unrealised_pnl())}
        while25.ui.push("view", page(funds, why, pnl, pf.positions() or []))