import os
from decimal import Decimal

from opentrade_backtest import BacktestClient, Balance, Credentials, SessionSpec

PAIR = "BTC/USDT"
VENUES = ["HUOBI", "OKEX", "BITGET"]
REST_FOR_MS = 60_000
FINISHED = {("ExecutionReport", "COMPLETED"), ("OrderUpdate", "REJECTED"), ("OrderUpdate", "CANCELLED")}

creds = Credentials(os.environ["OT_API_USERNAME"], os.environ["OT_PASSWORD"],
                    os.environ["OT_API_USERNAME"], os.environ["OT_SECRET"])
bt = BacktestClient.production(creds)
session = bt.create_session(SessionSpec(
    name="bid under the book",
    window=("2026-06-15", "2026-09-15"),
    pairs={PAIR: VENUES},
    balances=[Balance(venue, "USDT", "20000") for venue in VENUES],
    seed=7,
))
print("session", session.session_id, session.ws_url)

bids = {}
resting = None
with session.connect() as ws:
    ws.subscribe_book(PAIR)
    ws.subscribe_private(PAIR)
    session.start()
    for batch in ws.steps(until_ms=5000):
        for report in batch.private:
            if resting and report.get("clientOrderId") == resting["id"] and \
                    (report.get("class"), report.get("orderRequestStatus")) in FINISHED:
                resting = None
        for book in batch.books:
            if book["bids"]:
                bids[book["exchange"]] = Decimal(str(book["bids"][0][0]))
        now = ws.clock.now_ms()
        if resting and not resting["cancelling"] and now - resting["placed"] > REST_FOR_MS:
            ws.cancel_order(PAIR, client_order_id=resting["id"], exchange=resting["venue"])
            resting["cancelling"] = True
        if resting is None and bids:
            venue, best = max(bids.items(), key=lambda item: item[1])
            price = (best * Decimal("0.998")).quantize(Decimal("0.1"))
            order_id = ws.create_order(PAIR, "BUY", "0.01", price=price, exchange=venue)
            resting = {"id": order_id, "venue": venue, "placed": now, "cancelling": False}

report = session.result()
frames = report.frames()
print("run", report.run_id, "reproducible", report.reproducible)
print(frames["metrics"])
print(frames["fills"].tail())
