-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolymarket_trader.py
More file actions
825 lines (729 loc) · 32 KB
/
Copy pathpolymarket_trader.py
File metadata and controls
825 lines (729 loc) · 32 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
"""
polymarket_trader.py — Consumes ArbitrageSignal objects and executes trades.
Flow:
1. Receive signal from BinanceFeed
2. Validate signal age (discard if stale)
3. Fetch current Polymarket odds for matching market
4. Calculate edge = |fair_prob - market_prob|
5. Size bet via Kelly Criterion
6. Place order (paper or live)
7. Monitor outcome and close position
Polymarket CLOB docs: https://docs.polymarket.com/#clob
"""
import asyncio
from collections import Counter
import json
import logging
import time
import uuid
from datetime import datetime, timedelta, timezone
from typing import Dict, Optional, List
import aiohttp
from binance_feed import ArbitrageSignal
from config import BotConfig
from logger import TradeLogger
from risk_manager import RiskManager
from state import BotState, Position
# ── Polymarket CLOB endpoints ──────────────────────────────────────────────────
CLOB_BASE = "https://clob.polymarket.com"
GAMMA_BASE = "https://gamma-api.polymarket.com"
class PolymarketClient:
"""
Thin async wrapper around the Polymarket CLOB REST API.
Uses aiohttp for async HTTP with connection pooling.
For production, consider using the official py-clob-client:
pip install py-clob-client
This class mirrors that interface but works asynchronously.
"""
def __init__(self, config: BotConfig, logger: logging.Logger):
self.config = config
self.logger = logger
self._session: Optional[aiohttp.ClientSession] = None
self._live_client = None
self._live_client_init_attempted = False
self._max_retries = 3
self._retry_base_delay_s = 0.25
async def _get_session(self) -> aiohttp.ClientSession:
if self._session is None or self._session.closed:
timeout = aiohttp.ClientTimeout(total=5, connect=2)
self._session = aiohttp.ClientSession(
timeout=timeout,
headers={
"POLY_ADDRESS": self.config.POLYMARKET_API_KEY,
"POLY_SIGNATURE": "", # set per-request
"POLY_TIMESTAMP": "",
"POLY_NONCE": "",
"Content-Type": "application/json",
},
)
return self._session
async def get_market(self, condition_id: str) -> Optional[dict]:
"""Fetch market metadata and current best bid/ask."""
url = f"{CLOB_BASE}/markets/{condition_id}"
return await self._get_json_with_retry(
url=url,
params=None,
request_name=f"get_market({condition_id})",
)
async def get_market_resolution(self, condition_id: str) -> Optional[dict]:
"""
Best-effort resolution fetch for a market by condition id.
Returns:
{"resolved": bool, "winning_outcome": "YES"|"NO"|None}
"""
market = await self.get_market(condition_id)
if market is None:
return None
# Closed checks across possible schemas.
resolved = bool(
market.get("closed")
or market.get("resolved")
or market.get("ended")
or market.get("isResolved")
)
winning_outcome = self._extract_winning_outcome(market)
if winning_outcome:
resolved = True
return {"resolved": resolved, "winning_outcome": winning_outcome}
async def get_orderbook(self, token_id: str) -> Optional[dict]:
"""Fetch live orderbook for a specific outcome token."""
url = f"{CLOB_BASE}/book"
return await self._get_json_with_retry(
url=url,
params={"token_id": token_id},
request_name=f"get_orderbook({token_id})",
)
async def get_active_btc_eth_markets(self) -> List[dict]:
"""
Discover active BTC/ETH **5-minute** Up/Down markets via Gamma public-search.
Rolling intraday markets use slugs like ``btc-updown-5m-<epoch>`` /
``eth-updown-5m-<epoch>``. The legacy ``/markets?tag_slug=crypto`` feed
often omits these or only returns unrelated long-dated crypto markets.
"""
seen: set = set()
out: List[dict] = []
async def pull(query: str, slug_prefix: str) -> None:
url = f"{GAMMA_BASE}/public-search"
params = {
"q": query,
"limit_per_type": 80,
"events_status": "active",
}
data = await self._get_json_with_retry(
url=url,
params=params,
request_name=f"public_search({query[:24]}...)",
)
if not isinstance(data, dict):
return
for event in data.get("events") or []:
eslug = str(event.get("slug") or "")
if not eslug.startswith(slug_prefix):
continue
for m in event.get("markets") or []:
if m.get("closed"):
continue
cid = m.get("conditionId") or m.get("condition_id")
if not cid:
continue
key = str(cid)
if key in seen:
continue
seen.add(key)
out.append(m)
await pull(self.config.POLYMARKET_SEARCH_BTC_5M, self.config.POLYMARKET_SLUG_PREFIX_BTC_5M)
await pull(self.config.POLYMARKET_SEARCH_ETH_5M, self.config.POLYMARKET_SLUG_PREFIX_ETH_5M)
return out
async def place_market_order(
self,
token_id: str,
side: str, # "BUY" or "SELL"
size_usd: float,
price: float, # limit price (probability 0-1)
) -> Optional[object]:
"""
Place a market order on the CLOB.
In production this requires proper EIP-712 signing.
See: https://docs.polymarket.com/#signing-orders
"""
if self.config.PAPER_TRADING:
return {
"order_id": f"PAPER-{uuid.uuid4().hex[:8]}",
"status": "MATCHED",
"size_matched": size_usd,
"price": price,
}
# Live order path uses official py-clob-client signing flow.
try:
client = await self._get_live_client()
if client is None:
return None
result = await asyncio.to_thread(
self._create_and_post_order_sync,
client,
token_id,
side,
size_usd,
price,
)
if result:
return result
except Exception as e:
self.logger.error(f"place_market_order error: {e}", exc_info=True)
return None
async def close(self):
if self._session and not self._session.closed:
await self._session.close()
async def _get_live_client(self):
"""Lazily initialize official py-clob-client instance for live trading."""
if self._live_client is not None:
return self._live_client
if self._live_client_init_attempted:
return None
self._live_client_init_attempted = True
try:
self._live_client = await asyncio.to_thread(self._build_live_client_sync)
return self._live_client
except Exception as e:
self.logger.error(f"Failed to initialize py-clob-client: {e}", exc_info=True)
self._live_client = None
return None
def _build_live_client_sync(self):
from py_clob_client.client import ClobClient
host = CLOB_BASE
chain_id = 137
creds = {
"key": self.config.POLYMARKET_API_KEY,
"secret": self.config.POLYMARKET_API_SECRET,
"passphrase": self.config.POLYMARKET_API_PASSPHRASE,
}
client = ClobClient(
host,
key=self.config.POLYMARKET_PRIVATE_KEY,
chain_id=chain_id,
creds=creds,
signature_type=self.config.POLYMARKET_SIGNATURE_TYPE,
funder=self.config.POLYMARKET_FUNDER,
)
return client
def _create_and_post_order_sync(
self,
client,
token_id: str,
side: str,
size_usd: float,
price: float,
) -> Optional[dict]:
from py_clob_client.clob_types import OrderArgs, OrderType
from py_clob_client.order_builder.constants import BUY, SELL
# Polymarket order size is number of shares; cost ~= shares * price.
shares = round(size_usd / max(price, 0.01), 4)
side_const = BUY if side.upper() == "BUY" else SELL
response = client.create_and_post_order(
OrderArgs(
token_id=str(token_id),
price=round(price, 4),
size=shares,
side=side_const,
),
options={
"tick_size": "0.01",
"neg_risk": False,
},
order_type=OrderType.FAK,
)
if not isinstance(response, dict):
return None
return {
"order_id": response.get("orderID") or response.get("id") or str(uuid.uuid4()),
"status": response.get("status", "SUBMITTED"),
"raw": response,
}
def _extract_winning_outcome(self, market: dict) -> Optional[str]:
"""
Extract resolved winner from varying Polymarket schemas.
Returns canonical YES/NO/UP/DOWN when determinable.
"""
winner = market.get("winner") or market.get("winningOutcome")
if isinstance(winner, str):
upper = winner.strip().upper()
if upper in ("YES", "NO", "UP", "DOWN"):
return upper
def _parse_list(val):
if val is None:
return None
if isinstance(val, list):
return val
if isinstance(val, str):
try:
return json.loads(val)
except (json.JSONDecodeError, TypeError):
return None
return None
outcomes = _parse_list(market.get("outcomes"))
outcome_prices = _parse_list(market.get("outcomePrices"))
if isinstance(outcomes, list) and isinstance(outcome_prices, list) and len(outcomes) == len(outcome_prices):
try:
idx = max(range(len(outcome_prices)), key=lambda i: float(outcome_prices[i]))
maybe = str(outcomes[idx]).strip().upper()
if maybe in ("YES", "NO", "UP", "DOWN") and float(outcome_prices[idx]) >= 0.99:
return maybe
except (TypeError, ValueError):
pass
tokens = market.get("tokens")
if isinstance(tokens, list):
for token in tokens:
try:
if token.get("winner") is True or str(token.get("result", "")).upper() == "WIN":
out = str(token.get("outcome", "")).strip().upper()
if out in ("YES", "NO", "UP", "DOWN"):
return out
except AttributeError:
continue
return None
async def _get_json_with_retry(
self,
url: str,
params: Optional[dict],
request_name: str,
) -> Optional[dict]:
"""
GET JSON with bounded exponential backoff.
Retries transient errors (timeouts, 5xx, 429) and returns None on exhaustion.
"""
last_error: Optional[str] = None
for attempt in range(1, self._max_retries + 1):
try:
session = await self._get_session()
async with session.get(url, params=params) as resp:
if resp.status == 200:
return await resp.json()
body = await resp.text()
last_error = f"status={resp.status} body={body[:300]}"
# Retry only on transient statuses.
if resp.status in (429, 500, 502, 503, 504):
if attempt < self._max_retries:
delay = self._retry_base_delay_s * (2 ** (attempt - 1))
await asyncio.sleep(delay)
continue
break
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
last_error = str(e)
if attempt < self._max_retries:
delay = self._retry_base_delay_s * (2 ** (attempt - 1))
await asyncio.sleep(delay)
continue
except Exception as e:
last_error = str(e)
break
self.logger.warning(f"{request_name} failed after retries: {last_error}")
return None
def extract_best_price(orderbook: dict, side: str) -> Optional[float]:
"""
Parse CLOB orderbook for the price you would cross if you take liquidity.
BUY -> best (lowest) ask (what you pay to buy outcome tokens)
SELL -> best (highest) bid (what you receive when selling)
Prices are probabilities in [0, 1].
"""
try:
if side == "BUY":
asks = orderbook.get("asks", [])
if asks:
return float(min(asks, key=lambda x: float(x["price"]))["price"])
else:
bids = orderbook.get("bids", [])
if bids:
return float(max(bids, key=lambda x: float(x["price"]))["price"])
except (KeyError, ValueError, TypeError):
pass
return None
class PolymarketTrader:
"""
Main trading loop.
Consumes signals, validates edge, sizes and places bets.
"""
def __init__(
self,
config: BotConfig,
state: BotState,
risk: RiskManager,
trade_log: TradeLogger,
logger: logging.Logger,
):
self.config = config
self.state = state
self.risk = risk
self.trade_log = trade_log
self.logger = logger
self.client = PolymarketClient(config, logger)
# Cache of known markets: asset → list of market dicts
self._market_cache: Dict[str, List[dict]] = {}
self._cache_ttl: float = 0 # perf_counter timestamp
self._skip_counts: Counter = Counter()
self._skip_summary_every_s: float = 60.0
self._last_skip_summary_at: float = time.perf_counter()
async def run(self, signal_queue: asyncio.Queue):
"""Main consumer loop."""
self.logger.info("PolymarketTrader started.")
self.state.update_heartbeat("trader")
try:
await self._refresh_market_cache()
while self.state.running:
try:
self.state.update_heartbeat("trader")
signal: ArbitrageSignal = await asyncio.wait_for(
signal_queue.get(), timeout=5.0
)
await self._handle_signal(signal)
self._emit_skip_summary_if_due()
except asyncio.TimeoutError:
# Periodic tasks
await self._refresh_market_cache_if_needed()
await self._check_open_positions()
self._emit_skip_summary_if_due()
except Exception as e:
self.logger.error(f"Trader error: {e}", exc_info=True)
finally:
await self.client.close()
self.logger.info("PolymarketTrader stopped.")
async def _handle_signal(self, signal: ArbitrageSignal):
"""Process one arbitrage signal end-to-end."""
self.state.update_heartbeat("trader")
t0 = time.perf_counter()
# ── 1. Age check ─────────────────────────────────────────────────────
age_ms = signal.age_ms()
max_signal_age_ms = min(self.config.MAX_ENTRY_LATENCY_MS, self.config.STALE_SIGNAL_MS)
if age_ms > max_signal_age_ms:
self.logger.debug(f"Signal too old ({age_ms:.0f}ms) — skipping")
self._record_skip("signal_too_old")
return
# ── 2. Kill switch / pause check ──────────────────────────────────────
if self.state.killed or self.state.paused:
self._record_skip("killed_or_paused")
return
# ── 3. Position limit ─────────────────────────────────────────────────
if len(self.state.open_positions) >= self.config.MAX_OPEN_POSITIONS:
self.logger.debug("Max open positions reached — skipping signal")
self._record_skip("max_open_positions")
return
# ── 4. Find matching Polymarket market ────────────────────────────────
market = await self._find_matching_market(signal.asset)
if market is None:
self.logger.debug(f"No active market found for {signal.asset}")
self._record_skip("no_active_market")
return
condition_id = market.get("conditionId") or market.get("condition_id", "")
token_id = self._get_token_id(market, signal.direction)
if not token_id:
self._record_skip("missing_token_id")
return
target_outcome = self._position_outcome_label(market, signal.direction)
# ── 5. Fetch live orderbook ────────────────────────────────────────────
book = await self.client.get_orderbook(token_id)
if book is None:
self._record_skip("orderbook_fetch_failed")
return
# Current best ask (what we'd pay to BUY YES/NO)
market_price = extract_best_price(book, "BUY")
if market_price is None:
self._record_skip("missing_market_price")
return
# ── 6. Calculate edge ─────────────────────────────────────────────────
# After a confirmed price move, the outcome probability should be high.
# We estimate fair value based on move magnitude.
fair_prob = self._estimate_fair_prob(signal)
edge = fair_prob - market_price
self.logger.debug(
f"{signal.asset} {signal.direction}: "
f"market={market_price:.3f} fair={fair_prob:.3f} edge={edge:.3f}"
)
if edge < self.config.MIN_EDGE:
self.logger.debug(f"Insufficient edge ({edge:.3f}) — skipping")
self._record_skip("edge_too_low")
return
if fair_prob < self.config.MIN_WIN_PROB:
self.logger.debug(f"Win prob too low ({fair_prob:.3f}) — skipping")
self._record_skip("win_prob_too_low")
return
# ── 7. Size via fractional Kelly ──────────────────────────────────────
size_usd = self.risk.kelly_size(
win_prob=fair_prob,
market_price=market_price,
balance=self.state.balance,
)
if size_usd < self.config.MIN_BET_SIZE:
self.logger.debug(f"Bet too small (${size_usd:.2f}) — skipping")
self._record_skip("bet_too_small")
return
# Enforce hard per-trade safety cap from risk manager rule.
size_usd = min(size_usd, round(self.state.balance * 0.05, 2))
# ── 8. Final risk check ────────────────────────────────────────────────
if not self.risk.pre_trade_check(size_usd):
self._record_skip("risk_pre_trade_block")
return
# ── 9. Place order ────────────────────────────────────────────────────
order = await self.client.place_market_order(
token_id=token_id,
side="BUY",
size_usd=size_usd,
price=market_price,
)
total_ms = (time.perf_counter() - t0) * 1000
self.state.record_latency(total_ms)
if order is None:
self.logger.warning("Order placement failed")
self._record_skip("order_placement_failed")
return
# ── 10. Record position ───────────────────────────────────────────────
self._record_skip("entered_trade")
trade_id = order.get("order_id", str(uuid.uuid4()))
pos = Position(
trade_id=trade_id,
market_id=condition_id,
token_id=token_id,
outcome=target_outcome,
asset=signal.asset,
direction=signal.direction,
size_usd=size_usd,
entry_price=market_price,
entry_time=datetime.utcnow(),
signal_latency_ms=total_ms,
paper=self.config.PAPER_TRADING,
binance_entry_price=signal.price_after,
)
await self.state.open_position(pos)
await self._apply_scaling()
mode = "PAPER" if self.config.PAPER_TRADING else "LIVE"
self.logger.info(
f"{mode} | {signal.asset} {signal.direction} | "
f"${size_usd:.2f} @ {market_price:.3f} | "
f"edge={edge:.3f} | latency={total_ms:.0f}ms"
)
self.trade_log.log_entry(pos, signal, fair_prob, edge)
def _record_skip(self, reason: str) -> None:
self._skip_counts[reason] += 1
def _emit_skip_summary_if_due(self) -> None:
now = time.perf_counter()
if (now - self._last_skip_summary_at) < self._skip_summary_every_s:
return
self._last_skip_summary_at = now
if not self._skip_counts:
return
parts = [f"{k}={v}" for k, v in sorted(self._skip_counts.items())]
self.logger.info("Signal decision summary (last ~60s): " + ", ".join(parts))
self._skip_counts.clear()
def _estimate_fair_prob(self, signal: ArbitrageSignal) -> float:
"""
Conservative estimate of the true outcome probability given a
confirmed Binance price move.
For a 5-min "Will BTC be higher?" market:
- A 0.15% move (threshold) → ~65% confidence it resolves in direction
- A 0.50% move → ~80% confidence
- Caps at 0.90 to be conservative
This is a simplification; in production, calibrate this against
your actual win rate from paper trading.
"""
move = signal.move_pct
# Linear interpolation: 0.15% → 0.65, 1.0% → 0.90
prob = 0.65 + (move - 0.15) / (1.0 - 0.15) * 0.25
return round(min(max(prob, 0.60), 0.90), 4)
def _get_token_id(self, market: dict, direction: str) -> Optional[str]:
"""
Token id for the outcome we want to buy (same side as Binance move).
Gamma may use Yes/No or Up/Down; map signal UP -> YES or UP, DOWN -> NO or DOWN.
"""
def _parse_json_list(val):
if val is None:
return None
if isinstance(val, list):
return val
if isinstance(val, str):
try:
return json.loads(val)
except (json.JSONDecodeError, TypeError):
return None
return None
def _pick_token(outcome_map: Dict[str, str]) -> Optional[str]:
if direction == "UP":
for key in ("UP", "YES"):
if key in outcome_map:
return outcome_map[key]
else:
for key in ("DOWN", "NO"):
if key in outcome_map:
return outcome_map[key]
return None
try:
raw_tokens = market.get("tokens")
if isinstance(raw_tokens, list) and raw_tokens:
outcome_map = {
str(t["outcome"]).strip().upper(): str(t["token_id"])
for t in raw_tokens
}
return _pick_token(outcome_map)
outcomes = _parse_json_list(market.get("outcomes"))
clob_ids = _parse_json_list(market.get("clobTokenIds"))
if (
isinstance(outcomes, list)
and isinstance(clob_ids, list)
and len(outcomes) == len(clob_ids)
and outcomes
):
outcome_map = {
str(o).strip().upper(): str(cid)
for o, cid in zip(outcomes, clob_ids)
}
return _pick_token(outcome_map)
except (KeyError, TypeError, ValueError):
return None
return None
def _position_outcome_label(self, market: dict, direction: str) -> str:
"""Stored on Position.outcome for settlement comparison (UP/DOWN vs YES/NO)."""
def _parse_json_list(val):
if val is None:
return None
if isinstance(val, list):
return val
if isinstance(val, str):
try:
return json.loads(val)
except (json.JSONDecodeError, TypeError):
return None
return None
outcomes = _parse_json_list(market.get("outcomes"))
if isinstance(outcomes, list) and outcomes:
labels = {str(o).strip().upper() for o in outcomes}
if "UP" in labels or "DOWN" in labels:
return "UP" if direction == "UP" else "DOWN"
return "YES" if direction == "UP" else "NO"
async def _find_matching_market(self, asset: str) -> Optional[dict]:
"""Return best matching active market for this asset."""
markets = self._market_cache.get(asset, [])
if not markets:
return None
# Prefer markets closest to configured short duration and not expired.
now = datetime.now(timezone.utc)
target_min = self.config.MARKET_DURATION_MINUTES
candidates = []
for market in markets:
end_time = self._market_end_time(market)
if end_time is None or end_time <= now:
continue
mins_to_expiry = (end_time - now).total_seconds() / 60.0
duration_error = abs(mins_to_expiry - target_min)
candidates.append((duration_error, mins_to_expiry, market))
if not candidates:
return None
candidates.sort(key=lambda x: (x[0], x[1]))
return candidates[0][2]
async def _refresh_market_cache(self):
"""Discover and cache active Polymarket markets."""
all_markets = await self.client.get_active_btc_eth_markets()
cache: Dict[str, List[dict]] = {"BTCUSDT": [], "ETHUSDT": []}
for m in all_markets:
q = m.get("question", "").upper()
if "BTC" in q or "BITCOIN" in q:
cache["BTCUSDT"].append(m)
if "ETH" in q or "ETHEREUM" in q:
cache["ETHUSDT"].append(m)
for asset in cache:
cache[asset].sort(
key=lambda m: self._market_end_time(m) or datetime.max.replace(tzinfo=timezone.utc)
)
self._market_cache = cache
self._cache_ttl = time.perf_counter()
total = sum(len(v) for v in cache.values())
self.logger.info(f"Market cache refreshed: {total} markets found")
async def _refresh_market_cache_if_needed(self):
age_s = time.perf_counter() - self._cache_ttl
if age_s > 60: # refresh every minute
await self._refresh_market_cache()
async def _check_open_positions(self):
"""
Poll open positions and close resolved ones.
In production, use Polymarket webhooks or polling the settlement API.
This simplified version closes positions after market expiry.
"""
if not self.state.open_positions:
return
close_after = timedelta(minutes=self.config.MARKET_DURATION_MINUTES)
now = datetime.utcnow()
to_close: List[Position] = []
async with self.state.lock:
for pos in self.state.open_positions.values():
to_close.append(pos)
for pos in to_close:
resolution = await self.client.get_market_resolution(pos.market_id)
won: Optional[bool] = None
exit_price: Optional[float] = None
pnl: Optional[float] = None
if resolution and resolution.get("resolved"):
winning_outcome = resolution.get("winning_outcome")
if winning_outcome in ("YES", "NO", "UP", "DOWN"):
w = str(winning_outcome).strip().upper()
po = str(pos.outcome).strip().upper()
won = w == po
exit_price = 1.0 if won else 0.0
pnl = pos.size_usd * (1 / pos.entry_price - 1) if won else -pos.size_usd
else:
# Market appears closed but no deterministic winner yet.
continue
elif self.config.PAPER_TRADING and (now - pos.entry_time >= close_after):
# Paper-mode fallback so simulations keep flowing when no resolution exists.
current_price = self.state.last_prices.get(pos.asset)
if current_price is None:
continue
won = current_price > pos.binance_entry_price if pos.direction == "UP" else current_price < pos.binance_entry_price
exit_price = 1.0 if won else 0.0
pnl = pos.size_usd * (1 / pos.entry_price - 1) if won else -pos.size_usd
else:
continue
await self.state.close_position(
trade_id=pos.trade_id,
pnl=round(pnl, 4), # type: ignore[arg-type]
won=bool(won),
exit_price=float(exit_price),
)
closed = next((p for p in self.state.closed_positions if p.trade_id == pos.trade_id), None)
if closed:
self.trade_log.log_exit(closed)
self.logger.info(
f"CLOSE | {pos.asset} {pos.direction} | trade={pos.trade_id} | "
f"{'WON' if won else 'LOST'} | pnl=${pnl:.2f}"
)
def _market_end_time(self, market: dict) -> Optional[datetime]:
"""Parse market expiry from known Gamma fields."""
for key in ("endDate", "end_date", "endTime", "end_time", "expiration"):
value = market.get(key)
if not value:
continue
if isinstance(value, (int, float)):
return datetime.fromtimestamp(value, tz=timezone.utc)
if isinstance(value, str):
text = value.strip()
if text.endswith("Z"):
text = text.replace("Z", "+00:00")
try:
dt = datetime.fromisoformat(text)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt
except ValueError:
continue
return None
async def _apply_scaling(self):
"""Gradually increase max bet size after win threshold."""
async with self.state.lock:
if (
self.state.wins_since_last_scale >= self.config.SCALING_WIN_THRESHOLD
and self.state.current_max_bet < self.config.MAX_BET_SIZE
):
old = self.state.current_max_bet
self.state.current_max_bet = min(
self.state.current_max_bet + self.config.SCALE_STEP_USD,
self.config.MAX_BET_SIZE,
)
self.state.wins_since_last_scale = 0
self.logger.info(
f"Scaled max bet: ${old:.2f} -> ${self.state.current_max_bet:.2f}"
)