From c370d546b3f7474e0df095cb69da892bf68cfcbd Mon Sep 17 00:00:00 2001 From: Drew Mattick Date: Fri, 25 Sep 2026 02:37:33 -0500 Subject: [PATCH 1/2] style: format with black Applies black 26.5.1 (unpinned in CI, resolved to latest at run time) using the repo's tool.black config (line-length 100, target-version py310/py311/py312) across the exact paths CI checks: pm_bot, run_bot.py, scripts, tests. 24 files reformatted, mechanical only. Verified: AST of every changed file is identical before and after (ast.dump comparison), black --check and ruff check both pass, and the local test suite (16 tests) still passes. No behavior change. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_014ST4EyP7XFr92rgawwPJC1 --- pm_bot/config.py | 7 ++- pm_bot/exchanges/base.py | 18 ++---- pm_bot/exchanges/kalshi.py | 85 ++++++++++++++------------ pm_bot/exchanges/paper.py | 13 ++-- pm_bot/exchanges/polymarket.py | 29 +++++---- pm_bot/exchanges/polymarket_us.py | 8 +-- pm_bot/models.py | 53 +++++++++------- pm_bot/persistence/db.py | 73 +++++++++++++++++----- pm_bot/risk/manager.py | 25 ++++++-- pm_bot/signals/feeds/base.py | 5 +- pm_bot/signals/feeds/espn_injuries.py | 46 +++++++------- pm_bot/signals/nba_matcher.py | 75 +++++++++++++++++------ pm_bot/strategies/cross_market_arb.py | 68 ++++++++++++++------- pm_bot/strategies/news_signal.py | 32 +++++++--- pm_bot/strategies/sum_prob_arb.py | 48 +++++++++------ pm_bot/util/math.py | 11 ++-- pm_bot/util/signing.py | 4 +- run_bot.py | 33 ++++++---- scripts/cross_exchange_scanner.py | 88 +++++++++++++++++++++------ scripts/dashboard.py | 29 +++++---- scripts/polymarket_diagnostic.py | 7 ++- scripts/polymarket_setup_api_keys.py | 6 +- scripts/scan_diagnostic.py | 16 +++-- scripts/test_kalshi_auth.py | 2 +- 24 files changed, 509 insertions(+), 272 deletions(-) diff --git a/pm_bot/config.py b/pm_bot/config.py index df4f37e..a3d615c 100644 --- a/pm_bot/config.py +++ b/pm_bot/config.py @@ -14,6 +14,7 @@ # Load .env if present (silent no-op if dotenv not installed) try: from dotenv import load_dotenv + load_dotenv() except ImportError: pass @@ -30,7 +31,7 @@ class RuntimeConfig(BaseModel): class KalshiExchangeConfig(BaseModel): enabled: bool = True - env: str = "demo" # demo | prod + env: str = "demo" # demo | prod rate_tier: str = "basic" @@ -84,6 +85,7 @@ class ScannerConfig(BaseModel): class Secrets(BaseModel): """Values loaded from environment. Never log these.""" + kalshi_api_key_id: str = "" kalshi_private_key_path: str = "./kalshi_private.pem" kalshi_env: str = "demo" @@ -138,8 +140,7 @@ def load_config(path: str | Path = "config.yaml") -> Config: p = Path(path) if not p.exists(): raise FileNotFoundError( - f"Config file not found: {p.absolute()}. " - f"Copy config.yaml from the repo root." + f"Config file not found: {p.absolute()}. " f"Copy config.yaml from the repo root." ) with open(p, encoding="utf-8") as f: diff --git a/pm_bot/exchanges/base.py b/pm_bot/exchanges/base.py index f024508..6dd7ca0 100644 --- a/pm_bot/exchanges/base.py +++ b/pm_bot/exchanges/base.py @@ -34,35 +34,29 @@ def list_markets( status: str = "open", limit: int = 200, event_id: str | None = None, - ) -> list[Market]: - ... + ) -> list[Market]: ... @abc.abstractmethod - def get_market(self, ticker: str) -> Market | None: - ... + def get_market(self, ticker: str) -> Market | None: ... @abc.abstractmethod - def get_orderbook(self, ticker: str, depth: int = 10) -> OrderBook | None: - ... + def get_orderbook(self, ticker: str, depth: int = 10) -> OrderBook | None: ... # ----- trading path --------------------------------------------------- # Adapters that don't support trading raise ComplianceError. @abc.abstractmethod - def supports_trading(self) -> bool: - ... + def supports_trading(self) -> bool: ... @abc.abstractmethod def place_order(self, order: Order) -> Order: """Submit an order. Returns the updated Order (with exchange id + status).""" @abc.abstractmethod - def cancel_order(self, client_order_id: str) -> bool: - ... + def cancel_order(self, client_order_id: str) -> bool: ... @abc.abstractmethod - def get_positions(self) -> list[Position]: - ... + def get_positions(self) -> list[Position]: ... @abc.abstractmethod def get_balance(self) -> float: diff --git a/pm_bot/exchanges/kalshi.py b/pm_bot/exchanges/kalshi.py index 9cda8c1..f285576 100644 --- a/pm_bot/exchanges/kalshi.py +++ b/pm_bot/exchanges/kalshi.py @@ -44,10 +44,10 @@ # Per-tier rate limits (reads/sec, writes/sec) as of April 2026 RATE_LIMITS = { - "basic": (20, 10), + "basic": (20, 10), "advanced": (30, 30), - "premier": (100, 100), - "prime": (400, 400), + "premier": (100, 100), + "prime": (400, 400), } @@ -72,11 +72,13 @@ def __init__( self._last_write = 0.0 self.session = requests.Session() - self.session.headers.update({ - "Accept": "application/json", - "Content-Type": "application/json", - "User-Agent": "pm_bot/0.2.0", - }) + self.session.headers.update( + { + "Accept": "application/json", + "Content-Type": "application/json", + "User-Agent": "pm_bot/0.2.0", + } + ) # ----- internal helpers ----------------------------------------------- @@ -112,9 +114,9 @@ def _request( ) # Signing path includes the full /trade-api/v2/... portion sign_path = path if path.startswith("/trade-api") else f"/trade-api/v2{path}" - headers.update(build_auth_headers( - self.api_key_id, self.private_key_path, method, sign_path - )) + headers.update( + build_auth_headers(self.api_key_id, self.private_key_path, method, sign_path) + ) resp = self.session.request( method, url, params=params, json=body, headers=headers, timeout=15 ) @@ -153,9 +155,7 @@ def get_market(self, ticker: str) -> Market | None: def get_orderbook(self, ticker: str, depth: int = 10) -> OrderBook | None: try: - data = self._request( - "GET", f"/markets/{ticker}/orderbook", params={"depth": depth} - ) + data = self._request("GET", f"/markets/{ticker}/orderbook", params={"depth": depth}) except requests.HTTPError as e: if e.response is not None and e.response.status_code == 404: return None @@ -173,14 +173,18 @@ def parse_levels(raw: list) -> list[OrderBookLevel]: try: p_raw, s_raw = lvl[0], lvl[1] # New API: dollar strings ("0.55"); old: cents int (55) - if isinstance(p_raw, str) or (isinstance(p_raw, (int, float)) and float(p_raw) <= 1): + if isinstance(p_raw, str) or ( + isinstance(p_raw, (int, float)) and float(p_raw) <= 1 + ): price = float(p_raw) else: price = float(p_raw) / 100.0 - out.append(OrderBookLevel( - price=price, - size=int(float(s_raw)), - )) + out.append( + OrderBookLevel( + price=price, + size=int(float(s_raw)), + ) + ) except (IndexError, ValueError, TypeError): continue return out @@ -190,12 +194,8 @@ def parse_levels(raw: list) -> list[OrderBookLevel]: # Kalshi returns bid books; we synthesize asks from the other side: # the "yes ask" price = 1 - best NO bid price; the size is the NO depth - yes_asks = [ - OrderBookLevel(price=1.0 - lvl.price, size=lvl.size) for lvl in no_bids - ] - no_asks = [ - OrderBookLevel(price=1.0 - lvl.price, size=lvl.size) for lvl in yes_bids - ] + yes_asks = [OrderBookLevel(price=1.0 - lvl.price, size=lvl.size) for lvl in no_bids] + no_asks = [OrderBookLevel(price=1.0 - lvl.price, size=lvl.size) for lvl in yes_bids] return OrderBook( venue=self.venue, @@ -214,6 +214,7 @@ def _parse_market(self, raw: dict) -> Market: and *_fp float fields, and removed the old integer-cent fields. We prefer the new fields and fall back to legacy ones for compatibility. """ + def to_float(v) -> float: if v is None: return 0.0 @@ -277,8 +278,7 @@ def supports_trading(self) -> bool: def place_order(self, order: Order) -> Order: if not self.trading_enabled: raise RuntimeError( - "Kalshi trading not enabled. Set trading_enabled=True and " - "provide credentials." + "Kalshi trading not enabled. Set trading_enabled=True and " "provide credentials." ) body = { @@ -302,9 +302,14 @@ def place_order(self, order: Order) -> Order: order.exchange_order_id = o.get("order_id") order.status = OrderStatus.OPEN order.updated_at = datetime.utcnow() - log.info("Kalshi order placed: %s %s %d @ %.2f on %s", - order.action.value, order.side.value, order.size, - order.price, order.ticker) + log.info( + "Kalshi order placed: %s %s %d @ %.2f on %s", + order.action.value, + order.side.value, + order.size, + order.price, + order.ticker, + ) except requests.HTTPError as e: order.status = OrderStatus.REJECTED order.notes = f"HTTP {e.response.status_code}: {e.response.text if e.response else ''}" @@ -334,14 +339,18 @@ def get_positions(self) -> list[Position]: net = int(p.get("position", 0)) if net == 0: continue - positions.append(Position( - venue=self.venue, - ticker=p.get("ticker", ""), - side=Side.YES if net > 0 else Side.NO, - size=abs(net), - avg_entry_price=float(p.get("market_exposure", 0)) / (abs(net) * 100) if net else 0.0, - realized_pnl=float(p.get("realized_pnl", 0)) / 100.0, - )) + positions.append( + Position( + venue=self.venue, + ticker=p.get("ticker", ""), + side=Side.YES if net > 0 else Side.NO, + size=abs(net), + avg_entry_price=( + float(p.get("market_exposure", 0)) / (abs(net) * 100) if net else 0.0 + ), + realized_pnl=float(p.get("realized_pnl", 0)) / 100.0, + ) + ) return positions def get_balance(self) -> float: diff --git a/pm_bot/exchanges/paper.py b/pm_bot/exchanges/paper.py index 17e1fa7..442243d 100644 --- a/pm_bot/exchanges/paper.py +++ b/pm_bot/exchanges/paper.py @@ -179,8 +179,7 @@ def _try_match(self, order: Order, book: OrderBook) -> None: order.filled_size += fillable order.avg_fill_price = fill_price order.status = ( - OrderStatus.FILLED if order.filled_size >= order.size - else OrderStatus.PARTIAL + OrderStatus.FILLED if order.filled_size >= order.size else OrderStatus.PARTIAL ) def _apply_position(self, ticker: str, side: Side, delta: int, price: float) -> None: @@ -189,8 +188,11 @@ def _apply_position(self, ticker: str, side: Side, delta: int, price: float) -> if delta == 0: return self._positions[ticker] = Position( - venue=self.venue, ticker=ticker, side=side, - size=abs(delta), avg_entry_price=price, + venue=self.venue, + ticker=ticker, + side=side, + size=abs(delta), + avg_entry_price=price, ) return # Update weighted average entry @@ -198,7 +200,8 @@ def _apply_position(self, ticker: str, side: Side, delta: int, price: float) -> new_size = pos.size + abs(delta) pos.avg_entry_price = ( (pos.avg_entry_price * pos.size + price * abs(delta)) / new_size - if new_size > 0 else 0.0 + if new_size > 0 + else 0.0 ) pos.size = new_size else: diff --git a/pm_bot/exchanges/polymarket.py b/pm_bot/exchanges/polymarket.py index 5bed054..741699c 100644 --- a/pm_bot/exchanges/polymarket.py +++ b/pm_bot/exchanges/polymarket.py @@ -56,10 +56,12 @@ def __init__( self._compliance = compliance_acknowledged self._last_req = 0.0 self.session = requests.Session() - self.session.headers.update({ - "Accept": "application/json", - "User-Agent": "pm_bot/0.2.0", - }) + self.session.headers.update( + { + "Accept": "application/json", + "User-Agent": "pm_bot/0.2.0", + } + ) def _throttle(self) -> None: """Gamma API allows 4000/10s; we rate-limit at ~5/s to be polite.""" @@ -130,18 +132,20 @@ def to_levels(rows: list, limit: int) -> list[OrderBookLevel]: out: list[OrderBookLevel] = [] for r in (rows or [])[:limit]: try: - out.append(OrderBookLevel( - price=float(r.get("price", 0)), - size=int(float(r.get("size", 0))), - )) + out.append( + OrderBookLevel( + price=float(r.get("price", 0)), + size=int(float(r.get("size", 0))), + ) + ) except (ValueError, TypeError): continue return out - yes_bids = sorted(to_levels(data.get("bids", []), depth), - key=lambda lvl: lvl.price, reverse=True) - yes_asks = sorted(to_levels(data.get("asks", []), depth), - key=lambda lvl: lvl.price) + yes_bids = sorted( + to_levels(data.get("bids", []), depth), key=lambda lvl: lvl.price, reverse=True + ) + yes_asks = sorted(to_levels(data.get("asks", []), depth), key=lambda lvl: lvl.price) # NO side is derived: NO bid at price p <=> YES ask at (1-p) no_bids = [OrderBookLevel(price=1 - lvl.price, size=lvl.size) for lvl in yes_asks] @@ -168,6 +172,7 @@ def _parse_market(self, raw: dict) -> Market: prices = raw.get("outcomePrices") or "[]" if isinstance(prices, str): import json as _json + prices = _json.loads(prices) if prices: yes_price = float(prices[0]) diff --git a/pm_bot/exchanges/polymarket_us.py b/pm_bot/exchanges/polymarket_us.py index f95377c..13e1364 100644 --- a/pm_bot/exchanges/polymarket_us.py +++ b/pm_bot/exchanges/polymarket_us.py @@ -46,9 +46,7 @@ def __init__( self.relayer_api_key = relayer_api_key self.relayer_api_key_address = relayer_api_key_address self.relayer_host = relayer_host - self.trading_enabled = ( - trading_enabled and bool(api_key and api_secret) - ) + self.trading_enabled = trading_enabled and bool(api_key and api_secret) self.has_relayer = bool(relayer_api_key and relayer_api_key_address) if trading_enabled and not (api_key and api_secret): @@ -123,11 +121,11 @@ def _build_relayer_client(self): # Wallet private key signing — never log this import os + signer_pk = os.environ.get("POLYMARKET_PRIVATE_KEY", "") if not signer_pk: raise RuntimeError( - "Relayer requires a wallet private key. Set " - "POLYMARKET_PRIVATE_KEY in .env." + "Relayer requires a wallet private key. Set " "POLYMARKET_PRIVATE_KEY in .env." ) return RelayClient( diff --git a/pm_bot/models.py b/pm_bot/models.py index b8446bf..8a4e5de 100644 --- a/pm_bot/models.py +++ b/pm_bot/models.py @@ -29,9 +29,9 @@ class OrderType(str, Enum): class OrderStatus(str, Enum): - PENDING = "pending" # submitted, not yet accepted - OPEN = "open" # resting on book - PARTIAL = "partial" # partially filled + PENDING = "pending" # submitted, not yet accepted + OPEN = "open" # resting on book + PARTIAL = "partial" # partially filled FILLED = "filled" CANCELED = "canceled" REJECTED = "rejected" @@ -39,23 +39,26 @@ class OrderStatus(str, Enum): class Venue(str, Enum): """Which exchange a market lives on.""" + KALSHI = "kalshi" - POLYMARKET = "polymarket" # international - POLYMARKET_US = "polymarket_us" # QCX, CFTC-regulated - PAPER = "paper" # paper-trade shim + POLYMARKET = "polymarket" # international + POLYMARKET_US = "polymarket_us" # QCX, CFTC-regulated + PAPER = "paper" # paper-trade shim # ------------------------------------------------------------------------ # Market data # ------------------------------------------------------------------------ + class Market(BaseModel): """A single binary contract.""" + venue: Venue - ticker: str # exchange-native id (Kalshi ticker, Poly token_id, etc.) + ticker: str # exchange-native id (Kalshi ticker, Poly token_id, etc.) title: str subtitle: str = "" - yes_bid: float = 0.0 # best yes bid in dollars (0..1) + yes_bid: float = 0.0 # best yes bid in dollars (0..1) yes_ask: float = 1.0 no_bid: float = 0.0 no_ask: float = 1.0 @@ -63,7 +66,7 @@ class Market(BaseModel): open_interest: int = 0 category: str = "" close_time: datetime | None = None - event_id: str | None = None # groups related markets (multi-outcome events) + event_id: str | None = None # groups related markets (multi-outcome events) status: str = "open" @property @@ -87,8 +90,8 @@ def _price_range(cls, v: float) -> float: class OrderBookLevel(BaseModel): - price: float # dollars, 0..1 - size: int # contracts at this level + price: float # dollars, 0..1 + size: int # contracts at this level class OrderBook(BaseModel): @@ -121,45 +124,49 @@ def depth(self, side: Side, action: Action) -> int: # Trading # ------------------------------------------------------------------------ + class Order(BaseModel): """An order we've placed (or intend to place).""" + venue: Venue ticker: str side: Side action: Action order_type: OrderType = OrderType.LIMIT - price: float # dollars, 0..1 - size: int # number of contracts - client_order_id: str # our unique id + price: float # dollars, 0..1 + size: int # number of contracts + client_order_id: str # our unique id exchange_order_id: str | None = None status: OrderStatus = OrderStatus.PENDING filled_size: int = 0 avg_fill_price: float = 0.0 - strategy: str = "" # which strategy submitted it + strategy: str = "" # which strategy submitted it created_at: datetime = Field(default_factory=datetime.utcnow) updated_at: datetime = Field(default_factory=datetime.utcnow) - notes: str = "" # free-form, for debugging + notes: str = "" # free-form, for debugging class Fill(BaseModel): """A partial or full execution of an order.""" + venue: Venue ticker: str - order_id: str # client_order_id + order_id: str # client_order_id side: Side action: Action price: float size: int - fee: float = 0.0 # in dollars + fee: float = 0.0 # in dollars timestamp: datetime = Field(default_factory=datetime.utcnow) class Position(BaseModel): """Net position on a single market.""" + venue: Venue ticker: str side: Side - size: int # positive = long; 0 means flat + size: int # positive = long; 0 means flat avg_entry_price: float realized_pnl: float = 0.0 unrealized_pnl: float = 0.0 @@ -173,17 +180,19 @@ def notional_usd(self) -> float: # Strategy signals # ------------------------------------------------------------------------ + class TradeSignal(BaseModel): """A strategy's proposed trade. Risk manager decides whether to route it.""" + strategy: str venue: Venue ticker: str side: Side action: Action price: float - size: int # suggested size; risk mgr may reduce - edge_bps: int # estimated after-fee edge in basis points - confidence: float = 0.5 # 0..1 + size: int # suggested size; risk mgr may reduce + edge_bps: int # estimated after-fee edge in basis points + confidence: float = 0.5 # 0..1 reasoning: str = "" # For multi-leg strategies: companion legs that must all fill or none. companion_signals: list[TradeSignal] = Field(default_factory=list) diff --git a/pm_bot/persistence/db.py b/pm_bot/persistence/db.py index 5a45d77..a485673 100644 --- a/pm_bot/persistence/db.py +++ b/pm_bot/persistence/db.py @@ -191,9 +191,23 @@ def log_signal( price, size, edge_bps, confidence, reasoning, outcome, rejection_reason, companion_count, metadata_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - (_now(), strategy, venue, ticker, side, action, price, size, - edge_bps, confidence, reasoning, outcome, rejection_reason, - companion_count, json.dumps(metadata or {})), + ( + _now(), + strategy, + venue, + ticker, + side, + action, + price, + size, + edge_bps, + confidence, + reasoning, + outcome, + rejection_reason, + companion_count, + json.dumps(metadata or {}), + ), ) return int(cur.lastrowid or 0) @@ -219,9 +233,22 @@ def log_order( venue, ticker, side, action, order_type, price, size, status, strategy, paper, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - (_now(), client_order_id, exchange_order_id, venue, ticker, - side, action, order_type, price, size, status, strategy, - 1 if paper else 0, notes), + ( + _now(), + client_order_id, + exchange_order_id, + venue, + ticker, + side, + action, + order_type, + price, + size, + status, + strategy, + 1 if paper else 0, + notes, + ), ) def update_order_status( @@ -237,8 +264,7 @@ def update_order_status( """UPDATE orders SET status=?, filled_size=?, avg_fill_price=?, exchange_order_id=COALESCE(?, exchange_order_id) WHERE client_order_id=?""", - (status, filled_size, avg_fill_price, exchange_order_id, - client_order_id), + (status, filled_size, avg_fill_price, exchange_order_id, client_order_id), ) def log_fill( @@ -258,8 +284,18 @@ def log_fill( """INSERT INTO fills (ts, client_order_id, venue, ticker, side, action, price, size, fee, paper) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - (_now(), client_order_id, venue, ticker, side, action, - price, size, fee, 1 if paper else 0), + ( + _now(), + client_order_id, + venue, + ticker, + side, + action, + price, + size, + fee, + 1 if paper else 0, + ), ) def log_snapshot( @@ -279,8 +315,18 @@ def log_snapshot( """INSERT INTO snapshots (ts, venue, ticker, yes_bid, yes_ask, no_bid, no_ask, volume, open_interest, book_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - (_now(), venue, ticker, yes_bid, yes_ask, no_bid, no_ask, - volume, open_interest, json.dumps(book) if book else None), + ( + _now(), + venue, + ticker, + yes_bid, + yes_ask, + no_bid, + no_ask, + volume, + open_interest, + json.dumps(book) if book else None, + ), ) def log_event(self, kind: str, message: str, metadata: dict | None = None) -> None: @@ -310,8 +356,7 @@ def upsert_daily_pnl( unrealized_pnl=excluded.unrealized_pnl, trade_count=excluded.trade_count, fee_total=excluded.fee_total""", - (day, strategy, realized_pnl, unrealized_pnl, trade_count, - fee_total), + (day, strategy, realized_pnl, unrealized_pnl, trade_count, fee_total), ) # ----- reads ---------------------------------------------------------- diff --git a/pm_bot/risk/manager.py b/pm_bot/risk/manager.py index 4dd1116..c7ed2cf 100644 --- a/pm_bot/risk/manager.py +++ b/pm_bot/risk/manager.py @@ -100,8 +100,11 @@ def evaluate( adapter = self.adapters.get(signal.venue) if adapter is not None: current_positions = adapter.get_positions() - if (len(current_positions) >= self.cfg.max_concurrent_positions - and signal.ticker not in {p.ticker for p in current_positions}): + if len( + current_positions + ) >= self.cfg.max_concurrent_positions and signal.ticker not in { + p.ticker for p in current_positions + }: return False, "concurrent_position_limit" return True, "ok" @@ -123,7 +126,11 @@ def size(self, signal: TradeSignal) -> int: # edge_prob implied: market_price * (1 + edge_bps/10000) for BUY YES # This is a rough conversion; strategies should set confidence thoughtfully. edge_frac = signal.edge_bps / 10000.0 - edge_prob = min(1.0, signal.price + edge_frac) if signal.action == Action.BUY else max(0.0, signal.price - edge_frac) + edge_prob = ( + min(1.0, signal.price + edge_frac) + if signal.action == Action.BUY + else max(0.0, signal.price - edge_frac) + ) n = kelly_contracts( edge_prob=edge_prob, @@ -163,9 +170,14 @@ def route( rejection_reason=reason, companion_count=len(signal.companion_signals), ) - log.debug("Signal rejected (%s): %s %s %s @ %.2f", - reason, signal.strategy, signal.ticker, - signal.action.value, signal.price) + log.debug( + "Signal rejected (%s): %s %s %s @ %.2f", + reason, + signal.strategy, + signal.ticker, + signal.action.value, + signal.price, + ) return None contracts = self.size(signal) @@ -187,6 +199,7 @@ def route( return None from pm_bot.exchanges.kalshi import new_client_order_id + order = Order( venue=signal.venue, ticker=signal.ticker, diff --git a/pm_bot/signals/feeds/base.py b/pm_bot/signals/feeds/base.py index c4b188d..92aa2c8 100644 --- a/pm_bot/signals/feeds/base.py +++ b/pm_bot/signals/feeds/base.py @@ -27,13 +27,14 @@ @dataclass class NewsItem: """A single piece of news from a feed.""" + text: str timestamp: datetime source: str - severity: str = "info" # info | watch | breaking + severity: str = "info" # info | watch | breaking tags: dict[str, Any] = field(default_factory=dict) raw: dict[str, Any] = field(default_factory=dict) - item_id: str = "" # source-specific stable ID for dedup + item_id: str = "" # source-specific stable ID for dedup class NewsFeed(abc.ABC): diff --git a/pm_bot/signals/feeds/espn_injuries.py b/pm_bot/signals/feeds/espn_injuries.py index 4976a55..47a31d2 100644 --- a/pm_bot/signals/feeds/espn_injuries.py +++ b/pm_bot/signals/feeds/espn_injuries.py @@ -115,31 +115,31 @@ def poll(self) -> list[NewsItem]: ts = datetime.now(timezone.utc) if espn_date: try: - ts = datetime.fromisoformat( - espn_date.replace("Z", "+00:00") - ) + ts = datetime.fromisoformat(espn_date.replace("Z", "+00:00")) except ValueError: pass - items.append(NewsItem( - text=( - f"{player_name} ({team_abbr}) status: " - f"{prior_status or 'unknown'} -> {status}" - ), - timestamp=ts, - source=self.name, - severity=severity, - tags={ - "player_id": player_id, - "player_name": player_name, - "team_name": team_name, - "team_abbr": team_abbr, - "status_from": prior_status, - "status_to": status, - }, - raw={"description": description, "espn_inj": inj}, - item_id=f"espn-inj-{player_id}-{status}", - )) + items.append( + NewsItem( + text=( + f"{player_name} ({team_abbr}) status: " + f"{prior_status or 'unknown'} -> {status}" + ), + timestamp=ts, + source=self.name, + severity=severity, + tags={ + "player_id": player_id, + "player_name": player_name, + "team_name": team_name, + "team_abbr": team_abbr, + "status_from": prior_status, + "status_to": status, + }, + raw={"description": description, "espn_inj": inj}, + item_id=f"espn-inj-{player_id}-{status}", + ) + ) if not self._primed: log.info("ESPN injuries: primed with %d players, no items emitted", len(self._seen)) @@ -153,7 +153,7 @@ def poll(self) -> list[NewsItem]: def _extract_player_id(athlete: dict) -> str: """ESPN buries the player id in the playercard link URL. Returns empty string if not found.""" - for link in (athlete.get("links") or []): + for link in athlete.get("links") or []: href = link.get("href") or "" # e.g. https://www.espn.com/nba/player/_/id/4585618/keshon-gilbert if "/id/" in href: diff --git a/pm_bot/signals/nba_matcher.py b/pm_bot/signals/nba_matcher.py index 959f560..e9c8bcd 100644 --- a/pm_bot/signals/nba_matcher.py +++ b/pm_bot/signals/nba_matcher.py @@ -29,28 +29,64 @@ # Hand-curated NBA stars whose absence materially moves win prob. # Update when superstars retire / get traded. NBA_STARS_2026 = { - "Nikola Jokic", "Shai Gilgeous-Alexander", "Luka Doncic", - "Giannis Antetokounmpo", "Jayson Tatum", "Stephen Curry", - "LeBron James", "Anthony Edwards", "Joel Embiid", - "Donovan Mitchell", "Damian Lillard", "Kawhi Leonard", - "Devin Booker", "Kevin Durant", "Anthony Davis", - "Tyrese Haliburton", "Victor Wembanyama", "Paolo Banchero", - "Jalen Brunson", "Trae Young", "Karl-Anthony Towns", - "De'Aaron Fox", "Pascal Siakam", "Jaylen Brown", + "Nikola Jokic", + "Shai Gilgeous-Alexander", + "Luka Doncic", + "Giannis Antetokounmpo", + "Jayson Tatum", + "Stephen Curry", + "LeBron James", + "Anthony Edwards", + "Joel Embiid", + "Donovan Mitchell", + "Damian Lillard", + "Kawhi Leonard", + "Devin Booker", + "Kevin Durant", + "Anthony Davis", + "Tyrese Haliburton", + "Victor Wembanyama", + "Paolo Banchero", + "Jalen Brunson", + "Trae Young", + "Karl-Anthony Towns", + "De'Aaron Fox", + "Pascal Siakam", + "Jaylen Brown", } # Map team display name to Kalshi 3-letter code TEAM_TO_KALSHI = { - "Atlanta Hawks": "ATL", "Boston Celtics": "BOS", "Brooklyn Nets": "BKN", - "Charlotte Hornets": "CHA", "Chicago Bulls": "CHI", "Cleveland Cavaliers": "CLE", - "Dallas Mavericks": "DAL", "Denver Nuggets": "DEN", "Detroit Pistons": "DET", - "Golden State Warriors": "GSW", "Houston Rockets": "HOU", "Indiana Pacers": "IND", - "LA Clippers": "LAC", "Los Angeles Lakers": "LAL", "Memphis Grizzlies": "MEM", - "Miami Heat": "MIA", "Milwaukee Bucks": "MIL", "Minnesota Timberwolves": "MIN", - "New Orleans Pelicans": "NOP", "New York Knicks": "NYK", "Oklahoma City Thunder": "OKC", - "Orlando Magic": "ORL", "Philadelphia 76ers": "PHI", "Phoenix Suns": "PHX", - "Portland Trail Blazers": "POR", "Sacramento Kings": "SAC", "San Antonio Spurs": "SAS", - "Toronto Raptors": "TOR", "Utah Jazz": "UTA", "Washington Wizards": "WAS", + "Atlanta Hawks": "ATL", + "Boston Celtics": "BOS", + "Brooklyn Nets": "BKN", + "Charlotte Hornets": "CHA", + "Chicago Bulls": "CHI", + "Cleveland Cavaliers": "CLE", + "Dallas Mavericks": "DAL", + "Denver Nuggets": "DEN", + "Detroit Pistons": "DET", + "Golden State Warriors": "GSW", + "Houston Rockets": "HOU", + "Indiana Pacers": "IND", + "LA Clippers": "LAC", + "Los Angeles Lakers": "LAL", + "Memphis Grizzlies": "MEM", + "Miami Heat": "MIA", + "Milwaukee Bucks": "MIL", + "Minnesota Timberwolves": "MIN", + "New Orleans Pelicans": "NOP", + "New York Knicks": "NYK", + "Oklahoma City Thunder": "OKC", + "Orlando Magic": "ORL", + "Philadelphia 76ers": "PHI", + "Phoenix Suns": "PHX", + "Portland Trail Blazers": "POR", + "Sacramento Kings": "SAC", + "San Antonio Spurs": "SAS", + "Toronto Raptors": "TOR", + "Utah Jazz": "UTA", + "Washington Wizards": "WAS", } @@ -95,7 +131,8 @@ def find_team_next_game( # Pull list of NBA game events try: data = kalshi._request( - "GET", "/events", + "GET", + "/events", params={"series_ticker": "KXNBAGAME", "status": "open", "limit": 50}, ) except Exception as e: diff --git a/pm_bot/strategies/cross_market_arb.py b/pm_bot/strategies/cross_market_arb.py index a395f5c..4626860 100644 --- a/pm_bot/strategies/cross_market_arb.py +++ b/pm_bot/strategies/cross_market_arb.py @@ -118,10 +118,12 @@ def _do_full_scan(self) -> list[TradeSignal]: elif "kalshi_ticker" in pair: signals.extend(self._scan_legacy_single(pair)) except Exception as e: - log.warning("pair scan failed (%s): %s", - pair.get("name", "?"), e) - log.info("cross_market_arb scanned %d pairs, emitted %d signals", - len(self._event_map), len(signals)) + log.warning("pair scan failed (%s): %s", pair.get("name", "?"), e) + log.info( + "cross_market_arb scanned %d pairs, emitted %d signals", + len(self._event_map), + len(signals), + ) return signals # ------------------------------------------------------------------ @@ -189,22 +191,32 @@ def _scan_multi_leg(self, pair: dict) -> list[TradeSignal]: cost_a = match["ask"] + (1 - kv["yes_bid"]) edge_a_cents = (1 - cost_a) * 100 if edge_a_cents >= self.min_gap_cents: - signals.extend(self._make_pair_signals( - pair_name, kv, match, match_name, - direction="P_YES+K_NO", - edge_cents=edge_a_cents, - )) + signals.extend( + self._make_pair_signals( + pair_name, + kv, + match, + match_name, + direction="P_YES+K_NO", + edge_cents=edge_a_cents, + ) + ) # Direction B: BUY K_YES + BUY P_NO if kv["yes_ask"] > 0 and kv["yes_ask"] < 1 and match["bid"] > 0: cost_b = kv["yes_ask"] + (1 - match["bid"]) edge_b_cents = (1 - cost_b) * 100 if edge_b_cents >= self.min_gap_cents: - signals.extend(self._make_pair_signals( - pair_name, kv, match, match_name, - direction="K_YES+P_NO", - edge_cents=edge_b_cents, - )) + signals.extend( + self._make_pair_signals( + pair_name, + kv, + match, + match_name, + direction="K_YES+P_NO", + edge_cents=edge_b_cents, + ) + ) return signals @@ -386,17 +398,29 @@ def _scan_legacy_single(self, pair: dict) -> list[TradeSignal]: cost = match["ask"] + (1 - kv["yes_bid"]) edge = (1 - cost) * 100 if edge >= self.min_gap_cents: - signals.extend(self._make_pair_signals( - pair.get("name", k_ticker), kv, match, p_token, - direction="P_YES+K_NO", edge_cents=edge, - )) + signals.extend( + self._make_pair_signals( + pair.get("name", k_ticker), + kv, + match, + p_token, + direction="P_YES+K_NO", + edge_cents=edge, + ) + ) # Direction B if kv["yes_ask"] > 0 and kv["yes_ask"] < 1 and match["bid"] > 0: cost = kv["yes_ask"] + (1 - match["bid"]) edge = (1 - cost) * 100 if edge >= self.min_gap_cents: - signals.extend(self._make_pair_signals( - pair.get("name", k_ticker), kv, match, p_token, - direction="K_YES+P_NO", edge_cents=edge, - )) + signals.extend( + self._make_pair_signals( + pair.get("name", k_ticker), + kv, + match, + p_token, + direction="K_YES+P_NO", + edge_cents=edge, + ) + ) return signals diff --git a/pm_bot/strategies/news_signal.py b/pm_bot/strategies/news_signal.py index cb9e504..a410318 100644 --- a/pm_bot/strategies/news_signal.py +++ b/pm_bot/strategies/news_signal.py @@ -56,11 +56,13 @@ def __init__(self, config: dict[str, Any], adapters: dict[Venue, ExchangeAdapter # Build active feed list based on config espn_cfg = self.sources.get("espn_nba_injuries", {}) or {} if espn_cfg.get("enabled"): - self._feeds.append({ - "feed": ESPNInjuriesFeed(), - "interval": float(espn_cfg.get("poll_interval_sec", 60)), - "matcher": "nba_injury", - }) + self._feeds.append( + { + "feed": ESPNInjuriesFeed(), + "interval": float(espn_cfg.get("poll_interval_sec", 60)), + "matcher": "nba_injury", + } + ) log.info("news_signal: ESPN NBA injuries feed enabled") def scan(self) -> list[TradeSignal]: @@ -118,7 +120,11 @@ def _react_to_nba_injury(self, item) -> TradeSignal | None: if abs(impact) < self.min_edge_cents: log.debug( "news_signal: %s status %s->%s impact=%.1fc (below threshold %.1fc)", - player_name, status_from, status_to, impact, self.min_edge_cents, + player_name, + status_from, + status_to, + impact, + self.min_edge_cents, ) return None @@ -141,7 +147,10 @@ def _react_to_nba_injury(self, item) -> TradeSignal | None: if actionable_gap_cents < self.min_edge_cents: log.debug( "news_signal: %s gap %.1fc below threshold (current_bid=%.3f implied=%.3f)", - game["ticker"], actionable_gap_cents, current_yes_bid, implied_new_yes, + game["ticker"], + actionable_gap_cents, + current_yes_bid, + implied_new_yes, ) return None @@ -167,7 +176,12 @@ def _react_to_nba_injury(self, item) -> TradeSignal | None: ) log.info( "news_signal SIGNAL: %s | %s %s->%s | gap=%.1fc | %s @ %.3f", - game["ticker"], player_name, status_from, status_to, - actionable_gap_cents, "BUY NO", sig_price, + game["ticker"], + player_name, + status_from, + status_to, + actionable_gap_cents, + "BUY NO", + sig_price, ) return sig diff --git a/pm_bot/strategies/sum_prob_arb.py b/pm_bot/strategies/sum_prob_arb.py index 6a1045a..a3794cd 100644 --- a/pm_bot/strategies/sum_prob_arb.py +++ b/pm_bot/strategies/sum_prob_arb.py @@ -90,8 +90,9 @@ def scan(self) -> list[TradeSignal]: continue # Size: fewest available NO contracts at best ask, capped - basket_size = min(self.max_contracts_per_leg, - min(max(1, m.volume // 100) for m in legs)) + basket_size = min( + self.max_contracts_per_leg, min(max(1, m.volume // 100) for m in legs) + ) total_cost = sum(m.no_ask for m in legs) * basket_size edge_pct = (edge_per_basket * basket_size) / max(total_cost, 0.01) @@ -99,22 +100,24 @@ def scan(self) -> list[TradeSignal]: # Generate companion signals (must all fill or cancel all) companions: list[TradeSignal] = [] for leg in legs: - companions.append(TradeSignal( - strategy=self.name, - venue=Venue.KALSHI, - ticker=leg.ticker, - side=Side.NO, - action=Action.BUY, - price=leg.no_ask, - size=basket_size, - edge_bps=bps(edge_pct), - confidence=0.99, # pure-math arb once confirmed - reasoning=( - f"sum-prob arb: event {event_id}, " - f"sum(YES)={sum_yes:.3f}, " - f"edge=${edge_per_basket:.3f}/basket" - ), - )) + companions.append( + TradeSignal( + strategy=self.name, + venue=Venue.KALSHI, + ticker=leg.ticker, + side=Side.NO, + action=Action.BUY, + price=leg.no_ask, + size=basket_size, + edge_bps=bps(edge_pct), + confidence=0.99, # pure-math arb once confirmed + reasoning=( + f"sum-prob arb: event {event_id}, " + f"sum(YES)={sum_yes:.3f}, " + f"edge=${edge_per_basket:.3f}/basket" + ), + ) + ) # Head signal carries companions; caller should route all or none head = companions[0] @@ -123,11 +126,16 @@ def scan(self) -> list[TradeSignal]: log.info( "Sum-prob arb candidate: event=%s N=%d sum_yes=%.3f edge=$%.3f/basket", - event_id, len(legs), sum_yes, edge_per_basket, + event_id, + len(legs), + sum_yes, + edge_per_basket, ) log.info( "sum_prob_arb scanned %d markets, %d multi-outcome events, %d candidates", - len(markets), len(groups), len(signals), + len(markets), + len(groups), + len(signals), ) return signals diff --git a/pm_bot/util/math.py b/pm_bot/util/math.py index df9bb33..e0e1029 100644 --- a/pm_bot/util/math.py +++ b/pm_bot/util/math.py @@ -16,8 +16,8 @@ # Kalshi fees # ------------------------------------------------------------------------ -KALSHI_TAKER_FEE_COEFF = 0.07 # fee = 0.07 * p * (1-p) in dollars per contract -KALSHI_MAKER_FEE_MULT = 0.25 # maker pays 25% of what taker would pay +KALSHI_TAKER_FEE_COEFF = 0.07 # fee = 0.07 * p * (1-p) in dollars per contract +KALSHI_MAKER_FEE_MULT = 0.25 # maker pays 25% of what taker would pay def kalshi_taker_fee(price: float, contracts: int) -> float: @@ -48,6 +48,7 @@ def polymarket_fee(price: float, contracts: int, bps: int = 100) -> float: # Kelly sizing # ------------------------------------------------------------------------ + def kelly_fraction_of_bankroll( edge_prob: float, market_price: float, @@ -93,6 +94,7 @@ def kelly_contracts( # Probability / price # ------------------------------------------------------------------------ + def price_to_implied_prob(price: float) -> float: """YES price in dollars = implied prob. Trivially the identity, but we keep the function because it makes calling code self-documenting.""" @@ -112,6 +114,7 @@ def bps(edge: float) -> int: # Arbitrage math # ------------------------------------------------------------------------ + def sum_prob_arb_edge( yes_prices: Iterable[float], fee_per_leg_fn=kalshi_taker_fee, @@ -138,8 +141,8 @@ def sum_prob_arb_edge( def cross_market_arb_edge( - leg_a_price: float, # e.g. YES on Kalshi - leg_b_price: float, # e.g. NO on Polymarket (same event) + leg_a_price: float, # e.g. YES on Kalshi + leg_b_price: float, # e.g. NO on Polymarket (same event) contracts: int = 1, fee_fn_a=kalshi_taker_fee, fee_fn_b=polymarket_fee, diff --git a/pm_bot/util/signing.py b/pm_bot/util/signing.py index 30fdf32..8518102 100644 --- a/pm_bot/util/signing.py +++ b/pm_bot/util/signing.py @@ -37,9 +37,7 @@ def load_private_key(path: str) -> rsa.RSAPrivateKey: key = serialization.load_pem_private_key(f.read(), password=None) if not isinstance(key, rsa.RSAPrivateKey): - raise ValueError( - f"Expected RSA private key in {path}, got {type(key).__name__}" - ) + raise ValueError(f"Expected RSA private key in {path}, got {type(key).__name__}") return key diff --git a/run_bot.py b/run_bot.py index 6bdcbd2..d30763f 100644 --- a/run_bot.py +++ b/run_bot.py @@ -208,17 +208,23 @@ def check_paper_fills(adapters: dict[Venue, ExchangeAdapter], db: Database) -> N fee=f.fee, paper=True, ) - log.info("[paper fill] %s %s %d @ %.3f (fee $%.3f)", - f.action.value, f.side.value, f.size, f.price, f.fee) + log.info( + "[paper fill] %s %s %d @ %.3f (fee $%.3f)", + f.action.value, + f.side.value, + f.size, + f.price, + f.fee, + ) def main() -> int: parser = argparse.ArgumentParser(description="pm_bot prediction market bot") parser.add_argument("--config", default="config.yaml") - parser.add_argument("--once", action="store_true", - help="run one scan cycle and exit") - parser.add_argument("--dry", action="store_true", - help="scan + risk evaluate, but never place orders") + parser.add_argument("--once", action="store_true", help="run one scan cycle and exit") + parser.add_argument( + "--dry", action="store_true", help="scan + risk evaluate, but never place orders" + ) args = parser.parse_args() cfg = load_config(args.config) @@ -244,13 +250,16 @@ def main() -> int: risk = RiskManager(cfg.risk, db, adapters) if not strategies: - log.warning("No strategies enabled. Edit config.yaml and set " - "strategies..enabled: true.") + log.warning( + "No strategies enabled. Edit config.yaml and set " "strategies..enabled: true." + ) - log.info("Starting pm_bot | paper=%s | strategies=%s | adapters=%s", - cfg.runtime.paper_trading, - [s.name for s in strategies], - [v.value for v in adapters.keys()]) + log.info( + "Starting pm_bot | paper=%s | strategies=%s | adapters=%s", + cfg.runtime.paper_trading, + [s.name for s in strategies], + [v.value for v in adapters.keys()], + ) exit_code = 0 try: diff --git a/scripts/cross_exchange_scanner.py b/scripts/cross_exchange_scanner.py index 0a2b345..7293453 100644 --- a/scripts/cross_exchange_scanner.py +++ b/scripts/cross_exchange_scanner.py @@ -40,10 +40,18 @@ GAMMA = "https://gamma-api.polymarket.com" CLOB = "https://clob.polymarket.com" -DB_PATH = Path(os.environ.get("CROSS_SCAN_DB", str(Path(__file__).resolve().parents[1] / "data" / "cross_scan.db"))) +DB_PATH = Path( + os.environ.get( + "CROSS_SCAN_DB", str(Path(__file__).resolve().parents[1] / "data" / "cross_scan.db") + ) +) DB_PATH.parent.mkdir(parents=True, exist_ok=True) -EVENT_MAP_PATH = Path(__import__("os").environ.get("EVENT_MAP_PATH", str(Path(__file__).resolve().parents[1] / "config" / "event_map.yaml"))) +EVENT_MAP_PATH = Path( + __import__("os").environ.get( + "EVENT_MAP_PATH", str(Path(__file__).resolve().parents[1] / "config" / "event_map.yaml") + ) +) THROTTLE = 0.4 # 2.5 req/sec, well under both exchanges' limits @@ -95,7 +103,9 @@ def now_iso() -> str: def fetch_polymarket_event(keywords: list[str]) -> dict | None: - r = requests.get(f"{GAMMA}/events", params={"limit": 500, "active": "true", "closed": "false"}, timeout=10) + r = requests.get( + f"{GAMMA}/events", params={"limit": 500, "active": "true", "closed": "false"}, timeout=10 + ) if not r.ok: return None events = r.json() if isinstance(r.json(), list) else [] @@ -124,8 +134,9 @@ def words(s: str) -> set[str]: return {w.lower() for w in (s or "").split() if len(w) > 3} -def scan_pair(k: KalshiAdapter, pair: dict, conn: sqlite3.Connection, - edge_threshold_cents: float = 1.0) -> int: +def scan_pair( + k: KalshiAdapter, pair: dict, conn: sqlite3.Connection, edge_threshold_cents: float = 1.0 +) -> int: """Scan one pair, log to DB, return number of candidates found.""" ts = now_iso() pair_name = pair["name"] @@ -217,8 +228,18 @@ def scan_pair(k: KalshiAdapter, pair: dict, conn: sqlite3.Connection, kalshi_bid, kalshi_ask, kalshi_ticker, edge_PYK_NO_cents, edge_KYP_NO_cents) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", - (ts, pair_name, match_name or k_team, match["bid"], match["ask"], - kv["bid"], kv["ask"], kv["ticker"], edge_A, edge_B), + ( + ts, + pair_name, + match_name or k_team, + match["bid"], + match["ask"], + kv["bid"], + kv["ask"], + kv["ticker"], + edge_A, + edge_B, + ), ) n_compared += 1 @@ -228,20 +249,42 @@ def scan_pair(k: KalshiAdapter, pair: dict, conn: sqlite3.Connection, """INSERT INTO candidates (ts, pair_name, leg_name, direction, edge_cents, poly_price, kalshi_price, kalshi_ticker) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", - (ts, pair_name, match_name or k_team, "P_YES+K_NO", edge_A, - match["ask"], kv["bid"], kv["ticker"]), + ( + ts, + pair_name, + match_name or k_team, + "P_YES+K_NO", + edge_A, + match["ask"], + kv["bid"], + kv["ticker"], + ), + ) + print( + f" *** {match_name or k_team}: EDGE={edge_A:.2f}c (P_YES@{match['ask']:.3f} + K_NO@{1-kv['bid']:.3f})", + flush=True, ) - print(f" *** {match_name or k_team}: EDGE={edge_A:.2f}c (P_YES@{match['ask']:.3f} + K_NO@{1-kv['bid']:.3f})", flush=True) n_candidates += 1 if edge_B >= edge_threshold_cents: conn.execute( """INSERT INTO candidates (ts, pair_name, leg_name, direction, edge_cents, poly_price, kalshi_price, kalshi_ticker) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", - (ts, pair_name, match_name or k_team, "K_YES+P_NO", edge_B, - match["bid"], kv["ask"], kv["ticker"]), + ( + ts, + pair_name, + match_name or k_team, + "K_YES+P_NO", + edge_B, + match["bid"], + kv["ask"], + kv["ticker"], + ), + ) + print( + f" *** {match_name or k_team}: EDGE={edge_B:.2f}c (K_YES@{kv['ask']:.3f} + P_NO@{1-match['bid']:.3f})", + flush=True, ) - print(f" *** {match_name or k_team}: EDGE={edge_B:.2f}c (K_YES@{kv['ask']:.3f} + P_NO@{1-match['bid']:.3f})", flush=True) n_candidates += 1 elapsed = time.time() - start @@ -251,17 +294,21 @@ def scan_pair(k: KalshiAdapter, pair: dict, conn: sqlite3.Connection, (ts, pair_name, pe.get("id"), n_compared, elapsed), ) conn.commit() - print(f" -> {n_compared} legs compared, {n_candidates} candidates ({elapsed:.1f}s)", flush=True) + print( + f" -> {n_compared} legs compared, {n_candidates} candidates ({elapsed:.1f}s)", flush=True + ) return n_candidates def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--once", action="store_true", help="run one full sweep and exit") - parser.add_argument("--interval", type=int, default=120, - help="seconds between sweeps (default 120)") - parser.add_argument("--threshold", type=float, default=1.0, - help="minimum edge in cents to flag as candidate") + parser.add_argument( + "--interval", type=int, default=120, help="seconds between sweeps (default 120)" + ) + parser.add_argument( + "--threshold", type=float, default=1.0, help="minimum edge in cents to flag as candidate" + ) args = parser.parse_args() init_db() @@ -286,7 +333,10 @@ def main() -> int: print(f" pair scan error: {e}", flush=True) elapsed = time.time() - cycle_start - print(f"\n=== sweep complete: {total_candidates} total candidates, {elapsed:.0f}s ===", flush=True) + print( + f"\n=== sweep complete: {total_candidates} total candidates, {elapsed:.0f}s ===", + flush=True, + ) if args.once: break diff --git a/scripts/dashboard.py b/scripts/dashboard.py index 7ad0c05..1ce3a4d 100644 --- a/scripts/dashboard.py +++ b/scripts/dashboard.py @@ -61,7 +61,7 @@ def file_age_seconds(p: Path) -> float | None: """Seconds since file was last modified, or None if missing.""" if not p.exists(): return None - return (datetime.now().timestamp() - p.stat().st_mtime) + return datetime.now().timestamp() - p.stat().st_mtime # Header ---------------------------------------------------------------- @@ -102,19 +102,23 @@ def file_age_seconds(p: Path) -> float | None: status_cols[2].metric("signals today", n_sig) # Total candidates today (cross scanner) -cand_today = query(CROSS_SCAN_DB, "SELECT COUNT(*) AS n FROM candidates WHERE ts LIKE ?", (f"{today}%",)) +cand_today = query( + CROSS_SCAN_DB, "SELECT COUNT(*) AS n FROM candidates WHERE ts LIKE ?", (f"{today}%",) +) n_cand = int(cand_today["n"].iloc[0]) if not cand_today.empty else 0 status_cols[3].metric("candidates today", n_cand) # Tabs ------------------------------------------------------------------ -tab_cross, tab_bot, tab_pnl, tab_raw = st.tabs([ - "🔀 Cross-exchange", - "🤖 Bot signals", - "💰 P&L", - "🗃 Raw data", -]) +tab_cross, tab_bot, tab_pnl, tab_raw = st.tabs( + [ + "🔀 Cross-exchange", + "🤖 Bot signals", + "💰 P&L", + "🗃 Raw data", + ] +) # ----- Cross-exchange tab --------------------------------------------- @@ -130,7 +134,9 @@ def file_age_seconds(p: Path) -> float | None: LIMIT 100""", ) if candidates.empty: - st.info("No candidates logged yet. Run `python scripts/cross_exchange_scanner.py` to start collecting.") + st.info( + "No candidates logged yet. Run `python scripts/cross_exchange_scanner.py` to start collecting." + ) else: candidates["ts"] = pd.to_datetime(candidates["ts"]) st.dataframe(candidates, use_container_width=True, hide_index=True) @@ -258,8 +264,9 @@ def file_age_seconds(p: Path) -> float | None: .groupby("strategy")["realized_pnl"] .cumsum() .reset_index() - .merge(pnl[["day", "strategy"]].reset_index(), left_on="index", right_index=True) - [["day", "strategy", "realized_pnl"]] + .merge(pnl[["day", "strategy"]].reset_index(), left_on="index", right_index=True)[ + ["day", "strategy", "realized_pnl"] + ] .pivot(index="day", columns="strategy", values="realized_pnl") ) st.line_chart(cumulative, height=350) diff --git a/scripts/polymarket_diagnostic.py b/scripts/polymarket_diagnostic.py index f0998cc..775ba4e 100644 --- a/scripts/polymarket_diagnostic.py +++ b/scripts/polymarket_diagnostic.py @@ -136,6 +136,7 @@ def main() -> int: if isinstance(tokens, str): # Sometimes returned as JSON string import json as _json + try: tokens = _json.loads(tokens) except Exception: @@ -172,8 +173,10 @@ def main() -> int: print(f"\n=== {len(arb_candidates)} POLYMARKET ARB CANDIDATE(S) ===") for title, total, n, vol in arb_candidates: edge = (total - 1) * 100 - print(f" ${edge:5.2f} per 100-basket sum(YES)={total:.3f} " - f"{n} legs vol=${vol:,.0f} {title}") + print( + f" ${edge:5.2f} per 100-basket sum(YES)={total:.3f} " + f"{n} legs vol=${vol:,.0f} {title}" + ) else: print("\nNo arb candidates with sum > 1.03 in this sample.") print("Polymarket's documented arb opportunities are typically in") diff --git a/scripts/polymarket_setup_api_keys.py b/scripts/polymarket_setup_api_keys.py index 05c5652..5822668 100644 --- a/scripts/polymarket_setup_api_keys.py +++ b/scripts/polymarket_setup_api_keys.py @@ -61,7 +61,9 @@ def main() -> int: private_key = "0x" + private_key if len(private_key) != 66: - print(f"ERROR: private key looks wrong (got {len(private_key)} chars, expected 66 incl. '0x')") + print( + f"ERROR: private key looks wrong (got {len(private_key)} chars, expected 66 incl. '0x')" + ) return 1 print("=" * 64) @@ -85,7 +87,7 @@ def main() -> int: print("[1/2] Connecting to Polymarket CLOB...") client = ClobClient( host="https://clob.polymarket.com", - chain_id=137, # Polygon mainnet + chain_id=137, # Polygon mainnet key=private_key, ) try: diff --git a/scripts/scan_diagnostic.py b/scripts/scan_diagnostic.py index 3b25090..7b85473 100644 --- a/scripts/scan_diagnostic.py +++ b/scripts/scan_diagnostic.py @@ -24,9 +24,9 @@ from pm_bot.exchanges.kalshi import KalshiAdapter -EVENT_PAGES = 5 # 5 pages * 200 = 1000 events sampled -EVENT_SCAN_CAP = 50 # cap orderbook scans at this many events -THROTTLE_SEC = 1.0 # 1 req/sec — very polite, no 429s +EVENT_PAGES = 5 # 5 pages * 200 = 1000 events sampled +EVENT_SCAN_CAP = 50 # cap orderbook scans at this many events +THROTTLE_SEC = 1.0 # 1 req/sec — very polite, no 429s def fetch_events_page(k: KalshiAdapter, cursor: str | None) -> tuple[list[dict], str | None]: @@ -90,7 +90,9 @@ def main() -> int: print("[3/4] Pulling orderbooks for each leg (slowest step, ~1 req/sec)...") total_books = sum(len(m) for _, m in candidates) - print(f" will pull ~{total_books} orderbooks ({total_books * THROTTLE_SEC:.0f}s estimated)\n") + print( + f" will pull ~{total_books} orderbooks ({total_books * THROTTLE_SEC:.0f}s estimated)\n" + ) print(f"{'sum(ASK)':>9} {'sum(BID)':>9} {'covg':>7} {'event':<28} title") print("-" * 110) @@ -138,8 +140,10 @@ def main() -> int: print(f"\n=== {len(arb_candidates)} ARB CANDIDATE(S) (sum > 1.03, full coverage) ===") for ticker, total, n, title in arb_candidates: edge_per_basket = (total - 1) * 100 - print(f" ${edge_per_basket:5.2f} per 100-basket sum(YES)={total:.3f} " - f"{n} legs {ticker} ({title})") + print( + f" ${edge_per_basket:5.2f} per 100-basket sum(YES)={total:.3f} " + f"{n} legs {ticker} ({title})" + ) else: print("\nNo arb candidates with sum > 1.03 in this sample.") print("Try re-running — the sort by recency rotates which events get scanned.") diff --git a/scripts/test_kalshi_auth.py b/scripts/test_kalshi_auth.py index 749143f..4b17416 100644 --- a/scripts/test_kalshi_auth.py +++ b/scripts/test_kalshi_auth.py @@ -39,7 +39,7 @@ def main() -> int: api_key_id=secrets.kalshi_api_key_id, private_key_path=str(key_path), env=env, - trading_enabled=True, # we want auth turned on for this smoke test + trading_enabled=True, # we want auth turned on for this smoke test ) # Unauthenticated read From bae04440327175ac9e8fd31c2721839a8d522946 Mon Sep 17 00:00:00 2001 From: Drew Mattick Date: Fri, 25 Sep 2026 02:38:25 -0500 Subject: [PATCH 2/2] chore: ignore the formatting commit in git blame Adds .git-blame-ignore-revs listing the black reformat commit (c370d546b3f7474e0df095cb69da892bf68cfcbd) so `git blame` and GitHub's web blame skip past it to the line's real authorship commit. The file alone does nothing locally: it only takes effect after running `git config blame.ignoreRevsFile .git-blame-ignore-revs` (a one-time per-clone setting), or by passing --ignore-revs-file explicitly. A note to that effect is added next to [tool.black] in pyproject.toml. Verified with `git blame -L` on a line the reformat commit touched: without the config it attributes to the reformat commit, with it the attribution falls back to the original commit. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_014ST4EyP7XFr92rgawwPJC1 --- .git-blame-ignore-revs | 15 +++++++++++++++ pyproject.toml | 4 ++++ 2 files changed, 19 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..9e73bf4 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,15 @@ +# git-blame ignore list +# +# This file lists commits that should be ignored by `git blame` because +# they are pure, mechanical reformatting and not meaningful content +# changes. Ignoring them keeps blame pointing at the commit that +# actually introduced a line's logic, instead of the reformat commit. +# +# This file alone does nothing: git only reads it when you tell it to, +# either per-invocation with `git blame --ignore-revs-file +# .git-blame-ignore-revs`, or persistently with: +# git config blame.ignoreRevsFile .git-blame-ignore-revs +# GitHub's web blame view also honors this file automatically. + +# style: format with black (24 files, pm_bot/run_bot.py/scripts/tests) +c370d546b3f7474e0df095cb69da892bf68cfcbd diff --git a/pyproject.toml b/pyproject.toml index 3743f78..302e4d2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -93,6 +93,10 @@ ignore = [ [tool.ruff.lint.per-file-ignores] "tests/*" = ["E402"] +# .git-blame-ignore-revs at the repo root lists mechanical reformat +# commits (e.g. the black formatting pass) so `git blame` skips them. +# Run `git config blame.ignoreRevsFile .git-blame-ignore-revs` once +# locally to make it take effect; the file alone does nothing. [tool.black] line-length = 100 target-version = ["py310", "py311", "py312"]