"""Cross-exchange arbitrage between Polymarket and Kalshi (paper mode).

Monitors the same underlying event on both exchanges and arbs price differences.
"""

import horizon as hz


def fair_value(ctx: hz.Context) -> float:
    """Use the average of both exchange book prices as fair value."""
    poly_price = ctx.feeds.get("poly", hz.context.FeedData()).price or 0.5
    kalshi_price = ctx.feeds.get("kalshi", hz.context.FeedData()).price or 0.5
    return (poly_price + kalshi_price) / 2


def quoter(ctx: hz.Context, fair: float) -> list[hz.Quote]:
    """Tight spread when exchanges agree, wider when they diverge."""
    poly_price = ctx.feeds.get("poly", hz.context.FeedData()).price or fair
    kalshi_price = ctx.feeds.get("kalshi", hz.context.FeedData()).price or fair
    divergence = abs(poly_price - kalshi_price)

    base_spread = 0.02
    spread = base_spread + divergence * 0.5

    return hz.quotes(fair, spread, size=5)


if __name__ == "__main__":
    hz.run(
        name="cross_exchange_arb",
        markets=["will-btc-hit-100k-by-end-of-2025"],
        feeds={
            "poly": hz.PolymarketBook("will-btc-hit-100k-by-end-of-2025"),
            "kalshi": hz.KalshiBook("KXBTC-25FEB16"),
        },
        pipeline=[fair_value, quoter],
        risk=hz.Risk(max_position=50, max_drawdown_pct=3),
        interval=0.5,
        mode="paper",
    )
