-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmarket_maker.py
More file actions
2132 lines (1931 loc) · 83.7 KB
/
Copy pathmarket_maker.py
File metadata and controls
2132 lines (1931 loc) · 83.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Polymarket Market Making Bot
============================
Strategy: BTC-linked binary prediction markets
- Reads BTC price from Binance websocket with multi-exchange reference fallback
- Calculates fair probability from price/strike
- Compares vs Polymarket CLOB midpoint
- Places two-sided quotes when edge >= threshold
- Captures spread, earns maker rebates
"""
import asyncio
import json
import logging
import os
import time
import math
import statistics
import re
import uuid
from datetime import datetime, timezone
from dataclasses import dataclass, asdict, field
from typing import Dict, Optional
import aiohttp
import psycopg
from pathlib import Path
from dotenv import load_dotenv
from db_schema import apply_schema
_REPO_ROOT = Path(__file__).resolve().parent
# Repo .env wins over inherited environment (systemd EnvironmentFile often sets KEY= empty,
# which would otherwise block dotenv from filling the same keys with override=False).
load_dotenv(_REPO_ROOT / ".env", override=True)
# ─── Configuration ────────────────────────────────────────────────────────────
def env_value(name: str, default, parser):
raw = os.getenv(name)
if raw is None:
return default
try:
return parser(raw)
except (TypeError, ValueError):
return default
def env_bool(name: str, default: bool) -> bool:
return env_value(name, default, lambda v: v.strip().lower() in {"1", "true", "yes", "on"})
def env_float(name: str, default: float) -> float:
return env_value(name, default, float)
def env_int(name: str, default: int) -> int:
return env_value(name, default, int)
STRATEGY_PRESETS: dict[str, dict[str, float | int]] = {
# Lower risk / slower turnover.
"conservative": {
"POLY_SPREAD_PCT": 0.05,
"POLY_MIN_EDGE": 0.02,
"POLY_ORDER_SIZE": 30.0,
"POLY_MAX_POSITION": 300.0,
"POLY_QUOTE_REFRESH_SEC": 40,
"POLY_MARKETS_WATCHED": 8,
"POLY_MARKETS_FETCH_LIMIT": 800,
"POLY_MIN_MARKET_LIQUIDITY": 2000.0,
"POLY_MAX_DAILY_LOSS": 120.0,
"POLY_MAX_OPEN_ORDERS": 30,
"POLY_INVENTORY_SOFT_LIMIT_PCT": 0.50,
"POLY_INVENTORY_HARD_LIMIT_PCT": 0.75,
"POLY_INVENTORY_SKEW_PCT": 0.015,
"POLY_PASSIVE_BUFFER_TICKS": 2,
"POLY_MIN_MID_DISTANCE_PCT": 0.008,
"POLY_MAX_MID_DISTANCE_PCT": 0.25,
"POLY_MAX_ORDERS_PER_CYCLE": 14,
},
# Current default behavior.
"balanced": {},
# Target-wallet style: broad market coverage, moderate spread, fast cadence.
"target_clone": {
"POLY_SPREAD_PCT": 0.035,
"POLY_MIN_EDGE": 0.012,
"POLY_ORDER_SIZE": 60.0,
"POLY_MAX_POSITION": 700.0,
"POLY_QUOTE_REFRESH_SEC": 20,
"POLY_MARKETS_WATCHED": 18,
"POLY_MARKETS_FETCH_LIMIT": 2000,
"POLY_MIN_MARKET_LIQUIDITY": 1000.0,
"POLY_MAX_DAILY_LOSS": 350.0,
"POLY_MAX_OPEN_ORDERS": 70,
"POLY_INVENTORY_SOFT_LIMIT_PCT": 0.65,
"POLY_INVENTORY_HARD_LIMIT_PCT": 0.92,
"POLY_INVENTORY_SKEW_PCT": 0.01,
"POLY_PASSIVE_BUFFER_TICKS": 1,
"POLY_MIN_MID_DISTANCE_PCT": 0.004,
"POLY_MAX_MID_DISTANCE_PCT": 0.30,
"POLY_MAX_ORDERS_PER_CYCLE": 28,
},
# Higher throughput / higher inventory risk.
"aggressive": {
"POLY_SPREAD_PCT": 0.03,
"POLY_MIN_EDGE": 0.01,
"POLY_ORDER_SIZE": 75.0,
"POLY_MAX_POSITION": 900.0,
"POLY_QUOTE_REFRESH_SEC": 20,
"POLY_MARKETS_WATCHED": 20,
"POLY_MARKETS_FETCH_LIMIT": 2000,
"POLY_MIN_MARKET_LIQUIDITY": 800.0,
"POLY_MAX_DAILY_LOSS": 450.0,
"POLY_MAX_OPEN_ORDERS": 80,
"POLY_INVENTORY_SOFT_LIMIT_PCT": 0.70,
"POLY_INVENTORY_HARD_LIMIT_PCT": 0.95,
"POLY_INVENTORY_SKEW_PCT": 0.008,
"POLY_PASSIVE_BUFFER_TICKS": 1,
"POLY_MIN_MID_DISTANCE_PCT": 0.003,
"POLY_MAX_MID_DISTANCE_PCT": 0.35,
"POLY_MAX_ORDERS_PER_CYCLE": 36,
},
}
def selected_profile() -> str:
raw = (os.getenv("POLY_STRATEGY_PROFILE", "balanced") or "").strip().lower()
return raw if raw in STRATEGY_PRESETS else "balanced"
def env_float_profile(name: str, default: float) -> float:
raw = os.getenv(name)
if raw is not None:
try:
return float(raw)
except (TypeError, ValueError):
return default
profile_defaults = STRATEGY_PRESETS.get(selected_profile(), {})
if name in profile_defaults:
try:
return float(profile_defaults[name])
except (TypeError, ValueError):
return default
return default
def env_int_profile(name: str, default: int) -> int:
raw = os.getenv(name)
if raw is not None:
try:
return int(raw)
except (TypeError, ValueError):
return default
profile_defaults = STRATEGY_PRESETS.get(selected_profile(), {})
if name in profile_defaults:
try:
return int(profile_defaults[name])
except (TypeError, ValueError):
return default
return default
def env_credential_any(*keys: str) -> str:
"""First non-empty env among alternate names (POLY_* vs POLYMARKET_* in .env)."""
for k in keys:
raw = os.getenv(k)
if raw is not None and str(raw).strip():
return str(raw).strip()
return ""
def normalize_private_key(raw: str) -> str:
"""Strip .env junk (quotes, whitespace) so eth_account accepts the key."""
s = (raw or "").strip()
if len(s) >= 2 and s[0] == s[-1] and s[0] in "\"'":
s = s[1:-1].strip()
for ch in ("\ufeff", "\u200b", "\u200c", "\u200d"):
s = s.replace(ch, "")
return s.strip()
def assert_valid_hex_private_key(s: str) -> None:
"""ethereum keys: 32 bytes = 64 hex chars, optional 0x prefix."""
body = s[2:] if s.startswith(("0x", "0X")) else s
if len(body) != 64:
raise RuntimeError(
"POLY_PRIVATE_KEY must be exactly 64 hex characters (or 0x + 64 hex). "
f"After trimming quotes/whitespace, got {len(body)} hex characters."
)
try:
int(body, 16)
except ValueError as e:
raise RuntimeError(
"POLY_PRIVATE_KEY contains invalid hex (wrong character or stray spaces). "
"Use only 0-9 and a-f, no spaces inside the key."
) from e
@dataclass
class Config:
STRATEGY_PROFILE: str = field(default_factory=selected_profile)
# API endpoints
GAMMA_API: str = "https://gamma-api.polymarket.com"
CLOB_API: str = "https://clob.polymarket.com"
BINANCE_API: str = "https://api.binance.com"
COINBASE_API: str = "https://api.exchange.coinbase.com"
KRAKEN_API: str = "https://api.kraken.com"
BINANCE_WS: str = "wss://stream.binance.com:9443/ws/btcusdt@ticker"
BTC_REFERENCE_REFRESH_SEC: int = field(default_factory=lambda: env_int("POLY_BTC_REFERENCE_REFRESH_SEC", 120))
# Trading parameters
SPREAD_PCT: float = field(default_factory=lambda: env_float_profile("POLY_SPREAD_PCT", 0.04)) # Quote ±2% around fair price (captures 4% spread)
MIN_EDGE: float = field(default_factory=lambda: env_float_profile("POLY_MIN_EDGE", 0.015)) # Minimum edge over midpoint to place order
ORDER_SIZE: float = field(default_factory=lambda: env_float_profile("POLY_ORDER_SIZE", 50.0)) # USDC notional per side per quote
MAX_POSITION: float = field(default_factory=lambda: env_float_profile("POLY_MAX_POSITION", 500.0)) # Max USDC in any single market
QUOTE_REFRESH_SEC: int = field(default_factory=lambda: env_int_profile("POLY_QUOTE_REFRESH_SEC", 30)) # How often to refresh quotes
MARKETS_WATCHED: int = field(default_factory=lambda: env_int_profile("POLY_MARKETS_WATCHED", 10)) # How many BTC markets to watch
MARKETS_FETCH_LIMIT: int = field(default_factory=lambda: env_int_profile("POLY_MARKETS_FETCH_LIMIT", 1000)) # Raw market fetch size before filtering
MIN_MARKET_LIQUIDITY: float = field(default_factory=lambda: env_float_profile("POLY_MIN_MARKET_LIQUIDITY", 1000.0)) # Minimum market liquidity to quote
ENABLE_LIVE_TRADING: bool = field(default_factory=lambda: env_bool("POLY_ENABLE_LIVE_TRADING", False))
MIN_ORDER_SHARES: float = field(default_factory=lambda: env_float("POLY_MIN_ORDER_SHARES", 5.0))
MAX_ORDERS_PER_CYCLE: int = field(default_factory=lambda: env_int_profile("POLY_MAX_ORDERS_PER_CYCLE", 20))
CANCEL_BEFORE_REQUOTE: bool = field(default_factory=lambda: env_bool("POLY_CANCEL_BEFORE_REQUOTE", True))
ANCHOR_EVENT_HAZARD_PER_DAY: float = field(default_factory=lambda: env_float("POLY_ANCHOR_EVENT_HAZARD_PER_DAY", 0.001))
GTA_RELEASE_HAZARD_PER_DAY: float = field(default_factory=lambda: env_float("POLY_GTA_RELEASE_HAZARD_PER_DAY", 0.0002))
# Risk
MAX_DAILY_LOSS: float = field(default_factory=lambda: env_float_profile("POLY_MAX_DAILY_LOSS", 200.0)) # Kill switch: stop if daily PnL < -$200
MAX_OPEN_ORDERS: int = field(default_factory=lambda: env_int_profile("POLY_MAX_OPEN_ORDERS", 40)) # Cancel all if exceeded
INVENTORY_SOFT_LIMIT_PCT: float = field(default_factory=lambda: env_float_profile("POLY_INVENTORY_SOFT_LIMIT_PCT", 0.60)) # One-sided quoting starts beyond this ratio
INVENTORY_HARD_LIMIT_PCT: float = field(default_factory=lambda: env_float_profile("POLY_INVENTORY_HARD_LIMIT_PCT", 0.90)) # Strictly block risk-increasing side
INVENTORY_SKEW_PCT: float = field(default_factory=lambda: env_float_profile("POLY_INVENTORY_SKEW_PCT", 0.01)) # Midpoint skew to rebalance inventory
PASSIVE_BUFFER_TICKS: int = field(default_factory=lambda: env_int_profile("POLY_PASSIVE_BUFFER_TICKS", 1)) # Keep quotes at least N ticks away from opposite top-of-book
MIN_MID_DISTANCE_PCT: float = field(default_factory=lambda: env_float_profile("POLY_MIN_MID_DISTANCE_PCT", 0.005)) # Minimum bid/ask distance from mid to avoid crossing/taking
MAX_MID_DISTANCE_PCT: float = field(default_factory=lambda: env_float_profile("POLY_MAX_MID_DISTANCE_PCT", 0.30)) # Maximum distance from mid (too far quotes are clipped)
# Auth (set via env or .env file — POLY_* or Polymarket-style POLYMARKET_*)
PRIVATE_KEY: str = field(
default_factory=lambda: env_credential_any("POLY_PRIVATE_KEY", "POLYMARKET_PRIVATE_KEY")
)
API_KEY: str = field(
default_factory=lambda: env_credential_any("POLY_API_KEY", "POLYMARKET_API_KEY")
)
API_SECRET: str = field(
default_factory=lambda: env_credential_any("POLY_API_SECRET", "POLYMARKET_API_SECRET")
)
API_PASSPHRASE: str = field(
default_factory=lambda: env_credential_any(
"POLY_PASSPHRASE", "POLYMARKET_API_PASSPHRASE", "POLYMARKET_PASSPHRASE"
)
)
# Database
DATABASE_URL: str = field(
default_factory=lambda: os.getenv(
"DATABASE_URL",
"postgresql://postgres:postgres@localhost:5432/polybot",
)
)
config = Config()
live_client = None
def is_live_mode() -> bool:
return bool(config.ENABLE_LIVE_TRADING)
def validate_runtime_config():
"""Validate runtime config for live mode. Paper mode skips CLOB credential checks."""
if not is_live_mode():
log.warning(
"Paper mode enabled (POLY_ENABLE_LIVE_TRADING=0). "
"No real Polymarket orders will be sent."
)
return
auto_derive = env_bool("POLY_CLOB_AUTO_DERIVE_API_CREDS", True)
missing = []
if not (config.PRIVATE_KEY or "").strip():
missing.append("POLY_PRIVATE_KEY (or POLYMARKET_PRIVATE_KEY)")
if not auto_derive:
for env_name, value in {
"POLY_API_KEY": config.API_KEY,
"POLY_API_SECRET": config.API_SECRET,
"POLY_PASSPHRASE": config.API_PASSPHRASE,
}.items():
if not (value or "").strip():
missing.append(env_name)
if missing:
raise RuntimeError(
f"Missing required CLOB credentials: {', '.join(missing)}. "
f"With POLY_CLOB_AUTO_DERIVE_API_CREDS=1 (default) only the wallet private key is required; "
f"otherwise set POLY_* or POLYMARKET_* API fields in {_REPO_ROOT / '.env'}."
)
config.PRIVATE_KEY = normalize_private_key(config.PRIVATE_KEY)
assert_valid_hex_private_key(config.PRIVATE_KEY)
config.API_KEY = (config.API_KEY or "").strip()
config.API_SECRET = (config.API_SECRET or "").strip()
config.API_PASSPHRASE = (config.API_PASSPHRASE or "").strip()
def notional_to_shares(notional_usdc: float, price: float) -> float:
if notional_usdc <= 0:
return 0.0
return round(notional_usdc / max(price, 0.01), 6)
# ─── Logging ──────────────────────────────────────────────────────────────────
log_dir = Path(__file__).parent / "logs"
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
handlers=[
logging.FileHandler(log_dir / f"bot_{datetime.now().strftime('%Y%m%d')}.log"),
logging.StreamHandler(),
]
)
log = logging.getLogger("polybot")
# ─── Database ─────────────────────────────────────────────────────────────────
def init_db(database_url: str):
con = psycopg.connect(database_url, autocommit=False)
apply_schema(con)
con.commit()
return con
db = init_db(config.DATABASE_URL)
SQL_UPSERT_BTC_PRICE = """
INSERT INTO btc_prices (ts, price)
VALUES (%s, %s)
ON CONFLICT (ts) DO UPDATE SET price = EXCLUDED.price
"""
SQL_INSERT_QUOTE = """INSERT INTO quotes (ts,market_id,bid,ask,fair_price,mid,edge,placed,model_type)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
SQL_INSERT_TRADE = """INSERT INTO trades
(ts,market_id,market_slug,event_slug,market_q,mode,side,price,size,notional_usdc,size_shares,order_id,status,pnl,fill_price)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
SQL_UPSERT_BOT_STATS = """INSERT INTO bot_stats
(ts,total_trades,open_positions,realized_pnl,unrealized_pnl,daily_pnl,balance,active_markets)
VALUES (%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT (ts) DO UPDATE
SET total_trades = EXCLUDED.total_trades,
open_positions = EXCLUDED.open_positions,
realized_pnl = EXCLUDED.realized_pnl,
unrealized_pnl = EXCLUDED.unrealized_pnl,
daily_pnl = EXCLUDED.daily_pnl,
balance = EXCLUDED.balance,
active_markets = EXCLUDED.active_markets"""
SQL_DAILY_PNL = "SELECT COALESCE(SUM(pnl), 0) FROM trades WHERE status='filled' AND ts > (NOW() - INTERVAL '1 day')"
SQL_UPSERT_RUNTIME_STATE = """INSERT INTO runtime_state
(id,updated_at,running,kill_switch,paper_mode,btc_price,btc_source,ws_connected,ws_tick_age_sec,cycle_latency_ms,orders_placed_cycle,cycle_latency_avg_ms,orders_placed_avg,quotes_considered_cycle,quotes_eligible_cycle,order_attempts_cycle,order_acks_cycle,fills_cycle,quote_hit_rate_cycle,ack_rate_cycle,fill_rate_cycle,avg_edge_cycle,avg_order_distance_cycle,quote_hit_rate_avg,ack_rate_avg,fill_rate_avg,avg_edge_avg,avg_order_distance_avg,last_cycle,errors)
VALUES (1,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT (id) DO UPDATE
SET updated_at = EXCLUDED.updated_at,
running = EXCLUDED.running,
kill_switch = EXCLUDED.kill_switch,
paper_mode = EXCLUDED.paper_mode,
btc_price = EXCLUDED.btc_price,
btc_source = EXCLUDED.btc_source,
ws_connected = EXCLUDED.ws_connected,
ws_tick_age_sec = EXCLUDED.ws_tick_age_sec,
cycle_latency_ms = EXCLUDED.cycle_latency_ms,
orders_placed_cycle = EXCLUDED.orders_placed_cycle,
cycle_latency_avg_ms = EXCLUDED.cycle_latency_avg_ms,
orders_placed_avg = EXCLUDED.orders_placed_avg,
quotes_considered_cycle = EXCLUDED.quotes_considered_cycle,
quotes_eligible_cycle = EXCLUDED.quotes_eligible_cycle,
order_attempts_cycle = EXCLUDED.order_attempts_cycle,
order_acks_cycle = EXCLUDED.order_acks_cycle,
fills_cycle = EXCLUDED.fills_cycle,
quote_hit_rate_cycle = EXCLUDED.quote_hit_rate_cycle,
ack_rate_cycle = EXCLUDED.ack_rate_cycle,
fill_rate_cycle = EXCLUDED.fill_rate_cycle,
avg_edge_cycle = EXCLUDED.avg_edge_cycle,
avg_order_distance_cycle = EXCLUDED.avg_order_distance_cycle,
quote_hit_rate_avg = EXCLUDED.quote_hit_rate_avg,
ack_rate_avg = EXCLUDED.ack_rate_avg,
fill_rate_avg = EXCLUDED.fill_rate_avg,
avg_edge_avg = EXCLUDED.avg_edge_avg,
avg_order_distance_avg = EXCLUDED.avg_order_distance_avg,
last_cycle = EXCLUDED.last_cycle,
errors = EXCLUDED.errors"""
def utcnow() -> datetime:
return datetime.now(timezone.utc)
def db_write(query: str, params: tuple) -> None:
db.execute(query, params)
db.commit()
# ─── Data Models ──────────────────────────────────────────────────────────────
@dataclass
class Market:
condition_id: str
slug: str
event_slug: str
question: str
yes_token: str
no_token: str
yes_price: float
no_price: float
best_bid: float
best_ask: float
volume: float
liquidity: float
end_date_iso: str
rules_text: str
active: bool
@dataclass
class Quote:
market: Market
fair_price: float # 0–1 probability
mid: float # current Polymarket midpoint
bid: float # our bid
ask: float # our ask
edge: float # how much we beat the mid
should_place: bool
@dataclass
class BotState:
running: bool = True
btc_price: float = 0.0
total_trades: int = 0
realized_pnl: float = 0.0
daily_pnl: float = 0.0
open_positions: dict = field(default_factory=dict)
active_markets: list = field(default_factory=list)
last_cycle: str = ""
kill_switch: bool = False
errors: list = field(default_factory=list)
starting_balance: float = 0.0
current_balance: float = 0.0
equity: float = 0.0
ws_btc_price: float = 0.0
ws_connected: bool = False
ws_last_tick: float = 0.0
reference_btc_price: float = 0.0
reference_last_update: float = 0.0
cycle_latency_ms: float = 0.0
orders_placed_cycle: int = 0
cycle_latency_avg_ms: float = 0.0
orders_placed_avg: float = 0.0
cycle_latency_window: list[float] = field(default_factory=list)
orders_placed_window: list[int] = field(default_factory=list)
quotes_considered_cycle: int = 0
quotes_eligible_cycle: int = 0
order_attempts_cycle: int = 0
order_acks_cycle: int = 0
fills_cycle: int = 0
quote_hit_rate_cycle: float = 0.0
ack_rate_cycle: float = 0.0
fill_rate_cycle: float = 0.0
avg_edge_cycle: float = 0.0
avg_order_distance_cycle: float = 0.0
quote_hit_rate_avg: float = 0.0
ack_rate_avg: float = 0.0
fill_rate_avg: float = 0.0
avg_edge_avg: float = 0.0
avg_order_distance_avg: float = 0.0
quote_hit_rate_window: list[float] = field(default_factory=list)
ack_rate_window: list[float] = field(default_factory=list)
fill_rate_window: list[float] = field(default_factory=list)
avg_edge_window: list[float] = field(default_factory=list)
avg_order_distance_window: list[float] = field(default_factory=list)
# Cumulative matched YES shares already applied via ledger (live partial fills).
live_matched_shares_by_order: dict[str, float] = field(default_factory=dict)
state = BotState()
class BinanceBtcWsFeed:
"""Maintains a real-time BTC ticker stream from Binance websocket."""
def __init__(self):
self._running = True
async def run(self):
backoff_sec = 1
while self._running and state.running:
try:
timeout = aiohttp.ClientTimeout(total=None, sock_read=60)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.ws_connect(config.BINANCE_WS, heartbeat=20) as ws:
state.ws_connected = True
log.info("BTC websocket connected (Binance)")
backoff_sec = 1
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
try:
payload = json.loads(msg.data)
tick = float(payload.get("c", 0.0))
if tick > 0:
state.ws_btc_price = tick
state.ws_last_tick = time.time()
except Exception:
continue
elif msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):
break
except asyncio.CancelledError:
break
except Exception as e:
log.warning(f"BTC websocket disconnected: {e}")
finally:
state.ws_connected = False
if self._running and state.running:
await asyncio.sleep(backoff_sec)
backoff_sec = min(backoff_sec * 2, 20)
def stop(self):
self._running = False
def get_total_exposure() -> float:
"""Approximate gross inventory notional in USDC."""
exposure = 0.0
for pos in state.open_positions.values():
qty = abs(float(pos.get("qty", 0.0)))
avg = max(0.01, float(pos.get("avg_price", 0.0)))
exposure += qty * avg
return round(exposure, 4)
def get_market_exposure(market_id: str) -> float:
"""Approximate per-market inventory notional in USDC."""
pos = state.open_positions.get(market_id)
if not pos:
return 0.0
qty = abs(float(pos.get("qty", 0.0)))
avg = max(0.01, float(pos.get("avg_price", 0.0)))
return round(qty * avg, 4)
def get_market_position_qty(market_id: str) -> float:
"""Signed YES share inventory for a market (+long / -short)."""
pos = state.open_positions.get(market_id)
if not pos:
return 0.0
return float(pos.get("qty", 0.0))
def refresh_account_state():
"""Equity from realized PnL ledger (starting reference balance + cumulative realized)."""
state.current_balance = round(state.starting_balance + state.realized_pnl, 4)
state.equity = state.current_balance
def update_cycle_telemetry(orders_placed: int, cycle_started: float) -> None:
"""Track instantaneous and 10-cycle average telemetry."""
state.orders_placed_cycle = int(orders_placed)
state.cycle_latency_ms = round((time.perf_counter() - cycle_started) * 1000.0, 2)
state.orders_placed_window.append(state.orders_placed_cycle)
state.cycle_latency_window.append(state.cycle_latency_ms)
if len(state.orders_placed_window) > 10:
state.orders_placed_window.pop(0)
if len(state.cycle_latency_window) > 10:
state.cycle_latency_window.pop(0)
state.orders_placed_avg = round(
sum(state.orders_placed_window) / max(1, len(state.orders_placed_window)),
2,
)
state.cycle_latency_avg_ms = round(
sum(state.cycle_latency_window) / max(1, len(state.cycle_latency_window)),
2,
)
def update_execution_telemetry(
quotes_considered: int,
quotes_eligible: int,
order_attempts: int,
order_acks: int,
fills: int,
edge_sum: float,
edge_count: int,
order_distance_sum: float,
order_distance_count: int,
) -> None:
state.quotes_considered_cycle = int(quotes_considered)
state.quotes_eligible_cycle = int(quotes_eligible)
state.order_attempts_cycle = int(order_attempts)
state.order_acks_cycle = int(order_acks)
state.fills_cycle = int(fills)
state.quote_hit_rate_cycle = round((quotes_eligible / quotes_considered), 4) if quotes_considered > 0 else 0.0
state.ack_rate_cycle = round((order_acks / order_attempts), 4) if order_attempts > 0 else 0.0
state.fill_rate_cycle = round((fills / order_acks), 4) if order_acks > 0 else 0.0
state.avg_edge_cycle = round((edge_sum / edge_count), 6) if edge_count > 0 else 0.0
state.avg_order_distance_cycle = round((order_distance_sum / order_distance_count), 6) if order_distance_count > 0 else 0.0
for window, value in (
(state.quote_hit_rate_window, state.quote_hit_rate_cycle),
(state.ack_rate_window, state.ack_rate_cycle),
(state.fill_rate_window, state.fill_rate_cycle),
(state.avg_edge_window, state.avg_edge_cycle),
(state.avg_order_distance_window, state.avg_order_distance_cycle),
):
window.append(float(value))
if len(window) > 10:
window.pop(0)
state.quote_hit_rate_avg = round(sum(state.quote_hit_rate_window) / max(1, len(state.quote_hit_rate_window)), 4)
state.ack_rate_avg = round(sum(state.ack_rate_window) / max(1, len(state.ack_rate_window)), 4)
state.fill_rate_avg = round(sum(state.fill_rate_window) / max(1, len(state.fill_rate_window)), 4)
state.avg_edge_avg = round(sum(state.avg_edge_window) / max(1, len(state.avg_edge_window)), 6)
state.avg_order_distance_avg = round(
sum(state.avg_order_distance_window) / max(1, len(state.avg_order_distance_window)),
6,
)
# ─── Market Data ──────────────────────────────────────────────────────────────
async def get_btc_price(session: aiohttp.ClientSession) -> float:
"""Use websocket BTC feed when fresh, with periodic multi-exchange reference refresh."""
async def fetch_binance() -> Optional[float]:
try:
async with session.get(
f"{config.BINANCE_API}/api/v3/ticker/price",
params={"symbol": "BTCUSDT"},
timeout=aiohttp.ClientTimeout(total=4)
) as r:
d = await r.json()
return float(d["price"])
except Exception:
return None
async def fetch_coinbase() -> Optional[float]:
try:
async with session.get(
f"{config.COINBASE_API}/products/BTC-USD/ticker",
timeout=aiohttp.ClientTimeout(total=4)
) as r:
d = await r.json()
return float(d["price"])
except Exception:
return None
async def fetch_kraken() -> Optional[float]:
try:
async with session.get(
f"{config.KRAKEN_API}/0/public/Ticker",
params={"pair": "XBTUSD"},
timeout=aiohttp.ClientTimeout(total=4)
) as r:
d = await r.json()
result = d.get("result", {})
pair_key = next(iter(result.keys()), None)
if not pair_key:
return None
last_trade = result[pair_key].get("c", [])
if not last_trade:
return None
return float(last_trade[0])
except Exception:
return None
now_ts = time.time()
ws_fresh = state.ws_btc_price > 0 and (now_ts - state.ws_last_tick) <= 15
refresh_due = (now_ts - state.reference_last_update) >= config.BTC_REFERENCE_REFRESH_SEC
if refresh_due or state.reference_btc_price <= 0:
prices = {}
binance, coinbase, kraken = await asyncio.gather(
fetch_binance(),
fetch_coinbase(),
fetch_kraken(),
)
if binance is not None:
prices["binance"] = binance
if coinbase is not None:
prices["coinbase"] = coinbase
if kraken is not None:
prices["kraken"] = kraken
if prices:
state.reference_btc_price = float(statistics.median(prices.values()))
state.reference_last_update = now_ts
sources = ",".join(sorted(prices.keys()))
log.info(f"BTC reference median from {sources}: ${state.reference_btc_price:,.2f}")
if ws_fresh:
price = state.ws_btc_price
elif state.reference_btc_price > 0:
price = state.reference_btc_price
else:
log.warning("BTC price unavailable from websocket/reference; using last known price")
price = state.btc_price or 85000.0
state.btc_price = price
db_write(
SQL_UPSERT_BTC_PRICE,
(utcnow(), price),
)
return price
async def get_btc_markets(session: aiohttp.ClientSession) -> list[Market]:
"""
Fetch active BTC prediction markets from Gamma API.
These are markets with questions like "Will BTC be above $X on date?"
"""
target_fetch = max(100, min(config.MARKETS_FETCH_LIMIT, 3000))
markets_raw: list[dict] = []
try:
# Prefer event feed scoped to Bitcoin tag; this tracks the visible BTC shelf
# better than raw /markets top-volume pages.
event_offset = 0
event_page_size = 200
while len(markets_raw) < target_fetch:
async with session.get(
f"{config.GAMMA_API}/events",
params={
"active": "true",
"closed": "false",
"tag_slug": "bitcoin",
"limit": event_page_size,
"offset": event_offset,
"_order": "volume",
},
timeout=aiohttp.ClientTimeout(total=10),
) as r:
events_page = await r.json()
if not isinstance(events_page, list) or not events_page:
break
for ev in events_page:
ev_slug = str(ev.get("slug", "") or "")
ev_title = str(ev.get("title", "") or "")
for m in (ev.get("markets") or []):
if not isinstance(m, dict):
continue
row = dict(m)
row["_event_slug"] = ev_slug
row["_event_title"] = ev_title
markets_raw.append(row)
if len(markets_raw) >= target_fetch:
break
if len(markets_raw) >= target_fetch:
break
if len(events_page) < event_page_size:
break
event_offset += len(events_page)
except Exception as e:
log.error(f"Gamma API error: {e}")
return []
# Fallback for environments where /events payload is unavailable.
if not markets_raw:
try:
offset = 0
page_size = 1000
while len(markets_raw) < target_fetch:
this_limit = min(page_size, target_fetch - len(markets_raw))
async with session.get(
f"{config.GAMMA_API}/markets",
params={
"active": "true",
"closed": "false",
"tag_slug": "bitcoin",
"limit": this_limit,
"offset": offset,
"_order": "volume",
},
timeout=aiohttp.ClientTimeout(total=10),
) as r:
page = await r.json()
if not isinstance(page, list) or not page:
break
markets_raw.extend(page)
if len(page) < this_limit:
break
offset += len(page)
except Exception as e:
log.error(f"Gamma API fallback error: {e}")
return []
results = []
skipped_unsupported = 0
for m in markets_raw:
q = m.get("question", "").lower()
# Filter for BTC price prediction markets
if "bitcoin" not in q and "btc" not in q:
continue
if not m.get("active"):
continue
if bool(m.get("closed")):
continue
rules_text = " ".join(
str(m.get(k, "") or "")
for k in ("description", "rules", "resolutionSource", "resolution")
)
if m.get("_event_title"):
rules_text = f"{rules_text} {m.get('_event_title', '')}".strip()
model_type = classify_market_model(m.get("question", ""), rules_text)
if model_type == "unsupported":
skipped_unsupported += 1
continue
# Gamma API shape changed over time. Support both:
# 1) legacy "tokens" objects
# 2) modern "clobTokenIds" + "outcomes"/"outcomePrices"
yes_token = ""
no_token = ""
yes_idx = 0
no_idx = 1
tokens = m.get("tokens", [])
if tokens and len(tokens) >= 2:
yes_tok = next((t for t in tokens if t.get("outcome", "").lower() == "yes"), tokens[0])
no_tok = next((t for t in tokens if t.get("outcome", "").lower() == "no"), tokens[1])
yes_token = yes_tok.get("token_id", "")
no_token = no_tok.get("token_id", "")
else:
clob_ids_raw = m.get("clobTokenIds")
clob_ids = []
if isinstance(clob_ids_raw, list):
clob_ids = [str(x) for x in clob_ids_raw]
elif isinstance(clob_ids_raw, str):
try:
parsed_clob_ids = json.loads(clob_ids_raw)
if isinstance(parsed_clob_ids, list):
clob_ids = [str(x) for x in parsed_clob_ids]
except Exception:
clob_ids = []
outcomes_raw = m.get("outcomes")
outcomes = []
if isinstance(outcomes_raw, list):
outcomes = [str(x).lower() for x in outcomes_raw]
elif isinstance(outcomes_raw, str):
try:
outcomes = [str(x).lower() for x in json.loads(outcomes_raw)]
except Exception:
outcomes = []
if "yes" in outcomes:
yes_idx = outcomes.index("yes")
if "no" in outcomes:
no_idx = outcomes.index("no")
elif yes_idx == 0:
no_idx = 1
else:
no_idx = 0
if len(clob_ids) >= 2:
yes_idx = max(0, min(yes_idx, len(clob_ids) - 1))
no_idx = max(0, min(no_idx, len(clob_ids) - 1))
yes_token = str(clob_ids[yes_idx])
no_token = str(clob_ids[no_idx])
if not yes_token or not no_token:
continue
# Parse prices from outcomePrices field
outcome_prices = m.get("outcomePrices", ["0.5", "0.5"])
if isinstance(outcome_prices, str):
try:
outcome_prices = json.loads(outcome_prices)
except Exception:
outcome_prices = ["0.5", "0.5"]
try:
yes_idx_price = max(0, min(yes_idx, len(outcome_prices) - 1))
no_idx_price = max(0, min(no_idx, len(outcome_prices) - 1))
yes_price = float(outcome_prices[yes_idx_price])
no_price = float(outcome_prices[no_idx_price])
except (IndexError, ValueError):
yes_price, no_price = 0.5, 0.5
results.append(Market(
condition_id=m.get("conditionId", m.get("id", "")),
slug=m.get("slug", ""),
event_slug=(
str(m.get("_event_slug", ""))
or (m.get("events")[0].get("slug", "") if isinstance(m.get("events"), list) and m.get("events") else "")
),
question=m.get("question", ""),
yes_token=yes_token,
no_token=no_token,
yes_price=yes_price,
no_price=no_price,
best_bid=float(m.get("bestBid", 0) or 0),
best_ask=float(m.get("bestAsk", 0) or 0),
volume=float(m.get("volume", 0) or 0),
liquidity=float(m.get("liquidity", 0) or 0),
end_date_iso=m.get("endDate", ""),
rules_text=rules_text,
active=True
))
def market_priority_score(market: Market) -> float:
# Favor deep/liquid markets with balanced probabilities and usable horizon.
vol_score = math.log1p(max(0.0, market.volume))
liq_score = math.log1p(max(0.0, market.liquidity))
balance_score = max(0.0, 1.0 - abs(market.yes_price - 0.5) * 2.0)
dte = get_days_to_expiry(market.end_date_iso)
horizon_score = 1.0 if 0.5 < dte <= 45 else (0.5 if dte > 45 else 0.0)
return (0.55 * vol_score) + (0.35 * liq_score) + (2.0 * balance_score) + horizon_score
# Rank by priority score (not raw volume only) to broaden actionable coverage.
results.sort(key=market_priority_score, reverse=True)
state.active_markets = results[:config.MARKETS_WATCHED]
if skipped_unsupported:
log.info(f"Skipped {skipped_unsupported} unsupported BTC market structures")
return state.active_markets
async def get_order_book_mid(session: aiohttp.ClientSession, token_id: str) -> Optional[float]:
"""Get midpoint from CLOB order book."""
try:
async with session.get(
f"{config.CLOB_API}/midpoint",
params={"token_id": token_id},
timeout=aiohttp.ClientTimeout(total=5)
) as r:
d = await r.json()
mid = d.get("mid")
if mid is not None:
return float(mid)
except Exception as e:
log.debug(f"Midpoint fetch failed for {token_id[:16]}: {e}")
return None
# ─── Fair Probability Calculator ──────────────────────────────────────────────
def extract_price_levels(text: str) -> list[float]:
"""
Extract ordered dollar-denominated levels from free text.
Supports formats like $90,000, $95k, $1m, $90000.
"""
if not text:
return []
matches = re.finditer(
r"\$([0-9]{1,3}(?:,[0-9]{3})+|[0-9]+(?:\.[0-9]+)?)([km]?)\b",
text,
re.IGNORECASE,
)
out: list[float] = []
for m in matches:
base_raw = m.group(1).replace(",", "")
suffix = (m.group(2) or "").lower()
try:
value = float(base_raw)
except ValueError:
continue
if suffix == "k":
value *= 1_000.0
elif suffix == "m":
value *= 1_000_000.0
out.append(value)
return out
def extract_strike_from_question(question: str, rules_text: str = "") -> Optional[float]:
"""
Parse strike price from questions like:
"Will Bitcoin be above $90,000 on Dec 31?"
"BTC above $95k by end of month?"
"""
levels_q = extract_price_levels(question)
if levels_q:
return levels_q[0]
levels_rules = extract_price_levels(rules_text)
if levels_rules:
return levels_rules[0]
return None
def extract_price_range(question: str, rules_text: str = "") -> Optional[tuple[float, float]]:
levels = extract_price_levels(question)
if len(levels) < 2 and rules_text:
levels = levels + extract_price_levels(rules_text)
if len(levels) < 2:
return None
a, b = levels[0], levels[1]
lo, hi = (a, b) if a <= b else (b, a)
return (lo, hi)
def has_explicit_time_cue(question: str, rules_text: str = "") -> bool:
q = f"{(question or '').lower()} {(rules_text or '').lower()}".strip()
if not q:
return False
month_names = (
"jan", "feb", "mar", "apr", "may", "jun",
"jul", "aug", "sep", "oct", "nov", "dec",
)
if any(m in q for m in month_names):
return True
if re.search(r"\b20[2-9][0-9]\b", q):
return True
time_phrases = ("by end", "end of", "this week", "this month", "this year", " by ", " on ")
return any(p in q for p in time_phrases)
def classify_market_model(question: str, rules_text: str = "") -> str:
"""
Supported models:
- terminal: price relation at expiry (above/below/close/settle)
- barrier: first-touch style (hit/reach/touch) with explicit time cue
- unsupported: everything else (including comparative-event questions)
"""
q = (question or "").strip().lower()
rules = (rules_text or "").strip().lower()
if not q:
return "unsupported"
# Up/Down binary intraday-style markets usually do not expose explicit strike.
if "up or down" in q and ("bitcoin" in q or "btc" in q):
return "up_down_binary"
strike = extract_strike_from_question(question, rules_text)
if strike is None:
return "unsupported"
if ("between" in q or "range" in q) and extract_price_range(question, rules_text):
if has_explicit_time_cue(q, rules):
return "range_terminal"
terminal_patterns = (
r"\bbe above\b",