"""muniQuant Qualifier bot template. Put your rules into on_headline() and/or on_bar(); everything else is plumbing.

The two example rules below are switched OFF (USE_EXAMPLES = False). They only show the mechanics and are NOT the
effect hidden in the data: find your own in the history (files next to this one) and replace them.

Start (in the folder that also holds muniquant_client.py):
    python3 qualifier_bot_template.py https://<server> <bot key>        (Windows: py qualifier_bot_template.py ...)
The bot key comes from the trading screen: card "My bots" -> name -> "Create bot" -> "Copy key".

Timing (the same for everybody): each tick closes one hourly bar (08:00 ... 19:00, the day closes at 20:00).
A market order sent right after the tick of a bar fills at that bar's close = the open of the next bar, +- 2.5 bps.
A headline arrives with the tick just before the bar from which you can trade on it (`tradable_from_bar`).
"""
from __future__ import annotations

import sys

from muniquant_client import Client   # same folder

USE_EXAMPLES = False


def on_headline(n: dict, clock: dict) -> float | None:
    """Called for every new headline. n: category, sentiment ('positive'/'negative'), strength (0..1), window
    ('pre_open', 'intraday', 'after_close'), weekday ('Mon'..'Fri'), timestamp, tradable_from_bar ('YYYY-MM-DD HH:00').
    Return the exposure to hold from the next bar on (-1.0 = short with all capital ... +1.0 = long with all capital),
    or None to ignore the headline. The position is closed by hold_until (see run()), set in the same call."""
    if USE_EXAMPLES and n["category"] == "MACRO" and n["sentiment"] == "negative" and n["window"] == "intraday":
        return -0.5
    return None


def on_bar(clock: dict) -> float | None:
    """Called after every bar. clock: bar (just closed, 'YYYY-MM-DD HH:00'), weekday, next_bar, next_weekday.
    Return the exposure to hold from the next bar on, or None to keep what you have.
    Example (calendar rule): long on Mondays from the 08:00 open to the 20:00 close."""
    if not USE_EXAMPLES:
        return None
    if clock.get("next_weekday") == "Mon" and (clock.get("next_bar") or "").endswith("08:00"):
        return 1.0                     # the next bar is Monday 08:00: go long now, the order fills at Monday's open
    if clock.get("weekday") == "Mon" and (clock.get("bar") or "").endswith("19:00"):
        return 0.0                     # Monday's last bar just closed: flat now = at the 20:00 close
    return None


def run(url: str, key: str) -> None:
    with Client(url, key) as c:
        target = 0.0                   # exposure we want to hold
        hold_until = None              # 'YYYY-MM-DD': for headline trades, flat after that day's 19:00 bar
        pending: list[dict] = []       # headlines published before the start (tradable from the first bar)
        print("connected, waiting for the session ...")
        for msg in c.stream():         # a snapshot first, then one tick per hourly bar
            kind = msg["type"]
            if kind == "finished":
                print(f"session over, equity {c.account()['equity']:,.0f}")
                break
            if kind == "snapshot":
                if msg.get("state") == "ready":
                    pending = [n for n in msg.get("news", []) if n.get("step") == -1]
                continue
            if kind != "tick":
                continue
            clock = msg.get("qualifier") or {}
            want = None
            for n in pending + msg.get("news", []):
                x = on_headline(n, clock)
                if x is not None:
                    want = x
                    hold_until = (n.get("tradable_from_bar") or "")[:10]   # one trading day; change if you like
                    print(f"{n['timestamp']} {n['category']} {n['sentiment']} {n['strength']} -> exposure {x:+.0%}")
            pending = []
            x = on_bar(clock)
            if x is not None:
                want = x
                hold_until = None
            bar = clock.get("bar") or ""
            if want is None and hold_until and bar.startswith(hold_until) and bar.endswith("19:00"):
                want, hold_until = 0.0, None   # headline trade over: flat at the 20:00 close
            if want is not None and want != target:
                target = want
                pos = c.set_exposure(target)   # works out the lots from your equity and the price (max 100 %)
                print(f"{bar} -> exposure {target:+.0%}, position {pos} lots")
            elif target == 0 and c.position() != 0:
                c.set_exposure(0)              # an order was refused earlier (e.g. rate limit): close the rest now


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("usage: python3 qualifier_bot_template.py <server url> <bot key>")
    run(sys.argv[1], sys.argv[2])
