-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.py
More file actions
2043 lines (1692 loc) · 82.7 KB
/
Copy pathmain.py
File metadata and controls
2043 lines (1692 loc) · 82.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
#!/usr/bin/env python3
"""
BTC 15-min Live Trading Bot with Real-time Dashboard
Single file that combines:
- Visual terminal dashboard (rich)
- Real order execution
- Hedge management
- Auto-redemption
- Telegram notifications
Usage:
python main.py
"""
import asyncio
import json
import time
import csv
import math
import statistics
import logging
import signal
import sys
from datetime import datetime, timezone
from collections import deque
from dataclasses import dataclass, field
from typing import Optional, Dict, List, Any
from pathlib import Path
import aiohttp
import websockets
from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.layout import Layout
# Setup logging
Path("logs").mkdir(exist_ok=True)
# Main logger
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[logging.FileHandler('logs/bot.log')]
)
logger = logging.getLogger("btc_live")
# Detailed order execution logger
order_logger = logging.getLogger("btc_live.orders")
order_handler = logging.FileHandler('logs/orders.log')
order_handler.setFormatter(logging.Formatter(
'%(asctime)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
order_logger.addHandler(order_handler)
order_logger.setLevel(logging.DEBUG)
# Detailed hedge logger
hedge_logger = logging.getLogger("btc_live.hedges")
hedge_handler = logging.FileHandler('logs/hedges.log')
hedge_handler.setFormatter(logging.Formatter(
'%(asctime)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
hedge_logger.addHandler(hedge_handler)
hedge_logger.setLevel(logging.DEBUG)
# Signals logger
signal_logger = logging.getLogger("btc_live.signals")
signal_handler = logging.FileHandler('logs/signals.log')
signal_handler.setFormatter(logging.Formatter(
'%(asctime)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
signal_logger.addHandler(signal_handler)
signal_logger.setLevel(logging.DEBUG)
# Project imports
from src.config_loader import load_config, validate_config
from src.order_executor import OrderExecutor, ExecutionConfig
from src.hedge_manager import HedgeManager, HedgeConfig as HedgeManagerConfig, HedgeResult
from src.auto_redeemer import AsyncAutoRedeemer
from src.telegram_notifier import TelegramNotifier
from src.user_websocket import UserWebSocket
# Constants
GAMMA_API = "https://gamma-api.polymarket.com"
WSS_URL = "wss://ws-subscriptions-clob.polymarket.com/ws/market"
RTDS_URL = "wss://ws-live-data.polymarket.com"
console = Console()
# =============================================================================
# DATA CLASSES
# =============================================================================
@dataclass
class Trade:
"""Single trade record"""
timestamp: float
price: float
size: float
side: str
@dataclass
class TokenData:
"""Data for a single token (Up or Down)"""
token_id: str
name: str
best_bid: float = 0.0
best_bid_size: float = 0.0
best_ask: float = 0.0
best_ask_size: float = 0.0
trades: deque = field(default_factory=lambda: deque(maxlen=5000))
last_price: float = 0.0
last_trade_time: float = 0.0
trade_count: int = 0
volume_total: float = 0.0
volume_buy: float = 0.0
volume_sell: float = 0.0
def reset(self):
self.best_bid = 0.0
self.best_bid_size = 0.0
self.best_ask = 0.0
self.best_ask_size = 0.0
self.trades.clear()
self.last_price = 0.0
self.last_trade_time = 0.0
self.trade_count = 0
self.volume_total = 0.0
self.volume_buy = 0.0
self.volume_sell = 0.0
@dataclass
class MarketState:
"""Current market state"""
market_id: str = ""
condition_id: str = ""
slug: str = ""
end_time: float = 0.0
up_token: Optional[TokenData] = None
down_token: Optional[TokenData] = None
connected: bool = False
last_update: float = 0.0
# Chainlink BTC/USD price tracking
btc_anchor_price: float = 0.0 # Price at market start
btc_current_price: float = 0.0 # Latest Chainlink price
btc_last_update: float = 0.0 # Timestamp of last price update
btc_connected: bool = False # RTDS connection status
@dataclass
class Position:
"""Current open position"""
token_name: str
token_id: str
opposite_token_id: str
entry_price: float
contracts: int
entry_time: float
market_slug: str
hedged: bool = False
hedge_contracts: int = 0
hedge_price: float = 0.0
min_price_seen: float = 0.0 # Lowest price after entry (for drawdown tracking)
@dataclass
class TradeRecord:
"""Completed trade record"""
market_slug: str
token_name: str
entry_price: float
exit_price: float
contracts: int
pnl: float
won: bool
timestamp: float
max_drawdown_abs: float = 0.0 # Max absolute price drop from entry
max_drawdown_pct: float = 0.0 # Max percentage drawdown from entry
# =============================================================================
# UTILITIES
# =============================================================================
class IndicatorCalculator:
@staticmethod
def get_trades_in_window(trades: deque, window_seconds: float) -> List[Trade]:
now = time.time()
cutoff = now - window_seconds
return [t for t in trades if t.timestamp >= cutoff]
@staticmethod
def calc_vwap(trades: List[Trade]) -> float:
if not trades:
return 0.0
total_value = sum(t.price * t.size for t in trades)
total_volume = sum(t.size for t in trades)
return total_value / total_volume if total_volume > 0 else 0.0
@staticmethod
def calc_deviation(current_price: float, vwap: float) -> float:
if vwap == 0:
return 0.0
return ((current_price - vwap) / vwap) * 100
@staticmethod
def calc_momentum(trades: deque, current_price: float, window: float = 120, avg_band: float = 1.5) -> Optional[float]:
"""
Price change vs average price ~window seconds ago.
Takes all trades in [now-window-avg_band, now-window+avg_band] (3s band),
computes arithmetic mean, returns % change from that to current_price.
Returns None if no trades found in the band (not enough history).
"""
now = time.time()
band_start = now - window - avg_band
band_end = now - window + avg_band
band_prices = [t.price for t in trades if band_start <= t.timestamp <= band_end]
if not band_prices:
return None
avg_price_ago = sum(band_prices) / len(band_prices)
if avg_price_ago == 0:
return None
return ((current_price - avg_price_ago) / avg_price_ago) * 100
@staticmethod
def calc_zscore(trades: deque, current_price: float, window: float = 5) -> float:
now = time.time()
recent = [t for t in trades if t.timestamp >= now - window]
if len(recent) < 2:
return 0.0
prices = [t.price for t in recent]
mean_price = statistics.mean(prices)
std_price = statistics.stdev(prices) if len(prices) > 1 else 0.001
return (current_price - mean_price) / std_price if std_price > 0 else 0.0
class WinRateTable:
def __init__(self, csv_path: str):
self.data = {}
self.price_ranges = []
self._load(csv_path)
def _load(self, csv_path):
try:
with open(csv_path, 'r') as f:
reader = csv.reader(f)
next(reader) # Skip header
for row in reader:
if not row or not row[0]:
continue
price_range = row[0]
self.price_ranges.append(price_range)
self.data[price_range] = {}
for i, val in enumerate(row[1:], start=0):
if val:
try:
self.data[price_range][i] = float(val)
except ValueError:
pass
except Exception as e:
logger.warning(f"Could not load win_rate.csv: {e}")
def get_winrate(self, price: float, minute: int) -> Optional[float]:
price_range = None
for pr in self.price_ranges:
try:
low, high = pr.split('-')
if float(low) <= price <= float(high):
price_range = pr
break
except:
continue
if not price_range and price > 0.99 and self.price_ranges:
price_range = self.price_ranges[-1]
if not price_range:
return None
minute = max(0, min(14, minute))
return self.data.get(price_range, {}).get(minute)
# =============================================================================
# TRADING STATS
# =============================================================================
class TradingStats:
def __init__(self, log_file: str = "logs/trading_log.json"):
self.log_file = Path(log_file)
self.position: Optional[Position] = None
self.trades: List[TradeRecord] = []
self.markets_seen: int = 0
self.current_market_slug: str = ""
self.position_closed_this_market: bool = False
self.entry_blocked: bool = False # Блокировка повторных попыток после таймаута
self._load()
def _load(self):
try:
if self.log_file.exists():
with open(self.log_file, 'r') as f:
data = json.load(f)
self.trades = [TradeRecord(**t) for t in data.get('trades', [])]
self.markets_seen = data.get('markets_seen', 0)
except Exception:
pass
def _save(self):
try:
self.log_file.parent.mkdir(parents=True, exist_ok=True)
data = {
'trades': [t.__dict__ for t in self.trades],
'markets_seen': self.markets_seen
}
with open(self.log_file, 'w') as f:
json.dump(data, f, indent=2)
except Exception:
pass
def new_market(self, slug: str):
if slug != self.current_market_slug:
self.current_market_slug = slug
self.markets_seen += 1
self.position = None
self.position_closed_this_market = False
self.entry_blocked = False # Сброс блокировки для нового рынка
self._save()
def can_enter(self) -> bool:
return self.position is None and not self.position_closed_this_market and not self.entry_blocked
def block_entry(self, reason: str = ""):
"""Блокирует повторные попытки входа на текущем рынке."""
self.entry_blocked = True
if reason:
logger.warning(f"Entry blocked: {reason}")
def record_entry(self, token_name: str, token_id: str, opposite_token_id: str,
price: float, contracts: int, market_slug: str):
self.position = Position(
token_name=token_name,
token_id=token_id,
opposite_token_id=opposite_token_id,
entry_price=price,
contracts=contracts,
entry_time=time.time(),
market_slug=market_slug,
min_price_seen=price # Start tracking from entry price
)
def record_hedge(self, contracts: int, price: float):
if self.position:
self.position.hedged = True
self.position.hedge_contracts = contracts
self.position.hedge_price = price
def update_drawdown(self, current_price: float):
"""Track minimum price seen since entry for drawdown calculation."""
if self.position and current_price > 0:
if current_price < self.position.min_price_seen:
self.position.min_price_seen = current_price
def close_position(self, final_price: float) -> Optional[TradeRecord]:
if not self.position:
return None
won = final_price >= 0.70 # Win threshold
entry_cost = self.position.contracts * self.position.entry_price
if won:
pnl = self.position.contracts - entry_cost
else:
pnl = -entry_cost
# Calculate max drawdown from entry
dd_abs = max(0, self.position.entry_price - self.position.min_price_seen)
dd_pct = (dd_abs / self.position.entry_price * 100) if self.position.entry_price > 0 else 0
record = TradeRecord(
market_slug=self.position.market_slug,
token_name=self.position.token_name,
entry_price=self.position.entry_price,
exit_price=final_price,
contracts=self.position.contracts,
pnl=pnl,
won=won,
timestamp=time.time(),
max_drawdown_abs=dd_abs,
max_drawdown_pct=dd_pct,
)
self.trades.append(record)
self.position = None
self.position_closed_this_market = True
self._save()
return record
@property
def total_pnl(self) -> float:
return sum(t.pnl for t in self.trades)
@property
def win_count(self) -> int:
return sum(1 for t in self.trades if t.won)
@property
def trade_count(self) -> int:
return len(self.trades)
@property
def win_rate(self) -> float:
if not self.trades:
return 0.0
return (self.win_count / self.trade_count) * 100
# =============================================================================
# WEBSOCKET CLIENT
# =============================================================================
class WebSocketClient:
def __init__(self, state: MarketState):
self.state = state
self.running = False
self._tokens_validated = False
self._ws: Optional[websockets.WebSocketClientProtocol] = None
def _validate_tokens(self):
"""Log token prices after first WebSocket data received.
NOTE: Token swap logic was REMOVED because it was buggy.
The API token assignment should be trusted.
"""
if self._tokens_validated:
return
up = self.state.up_token
down = self.state.down_token
if not up or not down:
return
up_price = up.best_bid or up.best_ask or up.last_price
down_price = down.best_bid or down.best_ask or down.last_price
# Only log once we have valid prices
if up_price > 0.05 and down_price > 0.05:
price_sum = up_price + down_price
logger.info(f"Tokens validated: UP={up_price:.2f}, DOWN={down_price:.2f}, sum={price_sum:.2f}")
self._tokens_validated = True
async def connect(self):
self.running = True
while self.running:
try:
async with websockets.connect(WSS_URL) as ws:
self._ws = ws
self.state.connected = True
token_ids = []
if self.state.up_token:
token_ids.append(self.state.up_token.token_id)
if self.state.down_token:
token_ids.append(self.state.down_token.token_id)
# Log exact token_ids being subscribed
logger.info(f"WebSocket subscribing to tokens:")
logger.info(f" UP: {self.state.up_token.token_id[:40]}..." if self.state.up_token else " UP: None")
logger.info(f" DOWN: {self.state.down_token.token_id[:40]}..." if self.state.down_token else " DOWN: None")
await ws.send(json.dumps({"assets_ids": token_ids, "type": "market"}))
async for message in ws:
if not self.running:
break
await self._handle_message(message)
self._ws = None
except websockets.ConnectionClosed:
self._ws = None
self.state.connected = False
if self.running:
await asyncio.sleep(1)
except Exception:
self._ws = None
self.state.connected = False
if self.running:
await asyncio.sleep(2)
async def disconnect(self):
"""Gracefully close WebSocket connection with code 1000 (normal closure)."""
self.running = False
if self._ws:
try:
await self._ws.close(code=1000, reason="Normal shutdown")
logger.info("WebSocket closed gracefully (code 1000)")
except Exception as e:
logger.warning(f"Error during WebSocket close: {e}")
finally:
self._ws = None
self.state.connected = False
async def _handle_message(self, message: str):
try:
data = json.loads(message)
if isinstance(data, list):
for item in data:
if isinstance(item, dict):
await self._process_item(item)
elif isinstance(data, dict):
await self._process_item(data)
self.state.last_update = time.time()
# Validate tokens after receiving price data
if not self._tokens_validated:
self._validate_tokens()
except Exception:
pass
async def _process_item(self, data: dict):
event_type = data.get("event_type", "")
if event_type == "last_trade_price":
asset_id = data.get("asset_id")
token = self._get_token(asset_id)
if not token and asset_id:
# Asset ID doesn't match our tokens - might indicate subscription issue
logger.warning(f"Received price for unknown asset: {asset_id[:30]}...")
logger.warning(f" Our UP token: {self.state.up_token.token_id[:30] if self.state.up_token else 'None'}...")
logger.warning(f" Our DOWN token: {self.state.down_token.token_id[:30] if self.state.down_token else 'None'}...")
if token:
price = float(data.get("price", 0))
size = float(data.get("size", 0))
side = data.get("side", "BUY")
if price > 0 and size > 0:
token.last_price = price
token.last_trade_time = time.time()
token.trades.append(Trade(time.time(), price, size, side))
token.trade_count += 1
token.volume_total += size
if side == "BUY":
token.volume_buy += size
else:
token.volume_sell += size
elif event_type == "price_change":
for change in data.get("price_changes", []):
token = self._get_token(change.get("asset_id"))
if token:
if change.get("best_bid"):
token.best_bid = float(change["best_bid"])
if change.get("best_ask"):
token.best_ask = float(change["best_ask"])
elif event_type == "book":
token = self._get_token(data.get("asset_id"))
if token:
bids = data.get("bids", [])
if bids:
bids.sort(key=lambda x: float(x["price"]), reverse=True)
token.best_bid = float(bids[0]["price"])
token.best_bid_size = float(bids[0]["size"])
asks = data.get("asks", [])
if asks:
asks.sort(key=lambda x: float(x["price"]))
token.best_ask = float(asks[0]["price"])
token.best_ask_size = float(asks[0]["size"])
def _get_token(self, asset_id: str) -> Optional[TokenData]:
if self.state.up_token and asset_id == self.state.up_token.token_id:
return self.state.up_token
elif self.state.down_token and asset_id == self.state.down_token.token_id:
return self.state.down_token
return None
def stop(self):
"""Stop WebSocket (sync version - just sets flag)."""
self.running = False
async def stop_graceful(self):
"""Stop WebSocket gracefully with proper close."""
await self.disconnect()
# =============================================================================
# CHAINLINK BTC PRICE CLIENT
# =============================================================================
class ChainlinkPriceClient:
"""
Always-on BTC/USD price stream from Polymarket RTDS (Chainlink source).
Connects to wss://ws-live-data.polymarket.com and subscribes to
crypto_prices_chainlink for btc/usd.
Autonomously tracks 15-minute market boundaries (epoch-aligned to 900s)
and snapshots the anchor price at the exact boundary crossing, independent
of the bot's market finding flow. This ensures the anchor is captured
within ~1 second of the real boundary, not 5-15s later.
"""
MARKET_DURATION = 900 # 15 minutes in seconds
def __init__(self, state: 'MarketState'):
self.state = state
self.running = False
self._ws = None
self._ping_task: Optional[asyncio.Task] = None
# Track which 15-min window the current anchor belongs to
self._current_window: int = 0
# Buffer: last price before boundary (for most accurate anchor)
self._last_price_before_boundary: float = 0.0
self._last_price_ts: float = 0.0
@staticmethod
def _get_window(ts: float) -> int:
"""Get the 15-min window start timestamp for a given time."""
return int(ts) // 900 * 900
DATA_TIMEOUT = 30 # seconds without any message → force reconnect
async def connect(self):
"""Connect to RTDS and subscribe to Chainlink BTC/USD prices. Always on."""
self.running = True
self._last_msg_time = time.time()
while self.running:
try:
async with websockets.connect(RTDS_URL) as ws:
self._ws = ws
self.state.btc_connected = True
self._last_msg_time = time.time()
logger.info("RTDS Chainlink connected")
# Subscribe to chainlink prices (all symbols, filter in code)
subscribe_msg = json.dumps({
"action": "subscribe",
"subscriptions": [{
"topic": "crypto_prices_chainlink",
"type": "*",
"filters": ""
}]
})
await ws.send(subscribe_msg)
# Start ping task and watchdog
self._ping_task = asyncio.create_task(self._ping_loop(ws))
watchdog_task = asyncio.create_task(self._watchdog(ws))
try:
async for message in ws:
if not self.running:
break
self._last_msg_time = time.time()
self._handle_message(message)
finally:
watchdog_task.cancel()
try:
await watchdog_task
except asyncio.CancelledError:
pass
self._ws = None
except websockets.ConnectionClosed:
self._ws = None
self.state.btc_connected = False
if self.running:
logger.warning("RTDS Chainlink disconnected, reconnecting in 2s...")
await asyncio.sleep(2)
except Exception as e:
self._ws = None
self.state.btc_connected = False
if self.running:
logger.warning(f"RTDS Chainlink error: {e}, reconnecting in 5s...")
await asyncio.sleep(5)
finally:
if self._ping_task and not self._ping_task.done():
self._ping_task.cancel()
try:
await self._ping_task
except:
pass
self._ping_task = None
async def _watchdog(self, ws):
"""Force-close WebSocket if no messages received for DATA_TIMEOUT seconds."""
try:
while self.running:
await asyncio.sleep(5)
silence = time.time() - self._last_msg_time
if silence > self.DATA_TIMEOUT:
logger.warning(
f"RTDS Chainlink watchdog: no data for {silence:.0f}s, forcing reconnect"
)
self.state.btc_connected = False
await ws.close()
break
except asyncio.CancelledError:
pass
def _handle_message(self, message: str):
"""Parse incoming Chainlink price message and auto-detect market boundaries."""
try:
if not isinstance(message, str) or not message.strip():
return
data = json.loads(message)
topic = data.get("topic", "")
if topic != "crypto_prices_chainlink":
return
payload = data.get("payload", {})
symbol = payload.get("symbol", "")
if symbol != "btc/usd":
return
price = float(payload.get("value", 0))
if price <= 0:
return
# Use Chainlink's own timestamp (ms) for precise boundary detection
chainlink_ts_ms = payload.get("timestamp", 0)
if chainlink_ts_ms:
price_ts = chainlink_ts_ms / 1000.0
else:
price_ts = time.time()
now = time.time()
# Update current price (always)
self.state.btc_current_price = price
self.state.btc_last_update = now
# === CALIBRATION LOG: every tick within [-15s..+5s] of any boundary ===
price_window = self._get_window(price_ts)
next_boundary = price_window + self.MARKET_DURATION
secs_to_next = next_boundary - price_ts
secs_from_prev = price_ts - price_window
# Log if within 15s before next boundary OR 5s after current boundary start
if secs_to_next <= 15.0 or secs_from_prev <= 5.0:
cl_time = datetime.fromtimestamp(price_ts, tz=timezone.utc).strftime('%H:%M:%S.%f')[:-3]
local_time = datetime.fromtimestamp(now, tz=timezone.utc).strftime('%H:%M:%S.%f')[:-3]
if secs_from_prev <= 5.0:
offset_str = f"+{secs_from_prev:.3f}s after {datetime.fromtimestamp(price_window, tz=timezone.utc).strftime('%H:%M:%S')}"
else:
offset_str = f"-{secs_to_next:.3f}s before {datetime.fromtimestamp(next_boundary, tz=timezone.utc).strftime('%H:%M:%S')}"
logger.info(
f"BTC_TICK {cl_time} (local {local_time}) ${price:,.2f} [{offset_str}]"
)
# Detect 15-minute window boundary crossing
if self._current_window == 0:
# First price ever — initialize
self._current_window = price_window
self.state.btc_anchor_price = price
logger.info(
f"BTC Chainlink init: ${price:,.2f} "
f"(window {self._current_window}, "
f"ts={datetime.fromtimestamp(price_ts, tz=timezone.utc).strftime('%H:%M:%S.%f')[:-3]})"
)
elif price_window != self._current_window:
# === NEW 15-MIN WINDOW === use FIRST tick of new window as anchor
# Calibrated: reference program uses the first tick AT or AFTER boundary
old_anchor = self.state.btc_anchor_price
old_window = self._current_window
self.state.btc_anchor_price = price # First tick of new window
self._current_window = price_window
boundary_time = datetime.fromtimestamp(price_window, tz=timezone.utc).strftime('%H:%M:%S')
price_time = datetime.fromtimestamp(price_ts, tz=timezone.utc).strftime('%H:%M:%S.%f')[:-3]
delay_ms = (price_ts - price_window) * 1000
logger.info(
f"BTC anchor reset: ${self.state.btc_anchor_price:,.2f} "
f"(boundary {boundary_time}, first tick at {price_time}, "
f"delay {delay_ms:.0f}ms, prev anchor ${old_anchor:,.2f})"
)
# Always buffer the latest price for next boundary crossing
self._last_price_before_boundary = price
self._last_price_ts = price_ts
except (json.JSONDecodeError, ValueError, KeyError):
pass
async def _ping_loop(self, ws):
"""Send ping every 5 seconds to keep connection alive."""
try:
while self.running:
await asyncio.sleep(5)
try:
await ws.ping()
except Exception:
break
except asyncio.CancelledError:
pass
async def disconnect(self):
"""Gracefully close RTDS WebSocket connection."""
self.running = False
if self._ping_task and not self._ping_task.done():
self._ping_task.cancel()
try:
await self._ping_task
except:
pass
self._ping_task = None
if self._ws:
try:
# Unsubscribe before closing
unsub_msg = json.dumps({
"action": "unsubscribe",
"subscriptions": [{
"topic": "crypto_prices_chainlink",
"type": "*",
"filters": ""
}]
})
await self._ws.send(unsub_msg)
await self._ws.close(code=1000, reason="Normal shutdown")
logger.info("RTDS Chainlink closed gracefully")
except Exception as e:
logger.warning(f"RTDS close error: {e}")
finally:
self._ws = None
self.state.btc_connected = False
# =============================================================================
# DASHBOARD
# =============================================================================
class Dashboard:
def __init__(self, state: MarketState, stats: TradingStats, config: Any):
self.state = state
self.stats = stats
self.config = config
self.calc = IndicatorCalculator()
win_rate_path = Path(__file__).parent / config.strategy.win_rate_csv
self.winrate_table = WinRateTable(str(win_rate_path))
self.last_signal = ""
self.entry_flash = False
self.hedge_flash = False
def _fmt_price(self, price: float) -> str:
if price >= 0.6:
return f"[green]{price:.3f}[/green]"
elif price <= 0.4:
return f"[red]{price:.3f}[/red]"
return f"[yellow]{price:.3f}[/yellow]"
def _fmt_dev(self, dev: float) -> str:
if dev > 5:
return f"[bold green]+{dev:.1f}%[/bold green]"
elif dev > 0:
return f"[green]+{dev:.1f}%[/green]"
elif dev < -5:
return f"[bold red]{dev:.1f}%[/bold red]"
elif dev < 0:
return f"[red]{dev:.1f}%[/red]"
return f"{dev:+.1f}%"
def _fmt_zscore(self, z: float) -> str:
if z > 2:
return f"[bold magenta]+{z:.2f}[/bold magenta] ⚡"
elif z > 1:
return f"[magenta]+{z:.2f}[/magenta]"
elif z < -2:
return f"[bold cyan]{z:.2f}[/bold cyan] ⚡"
elif z < -1:
return f"[cyan]{z:.2f}[/cyan]"
return f"{z:+.2f}"
def create_header(self) -> Panel:
now = time.time()
time_left = max(0, self.state.end_time - now)
minutes = int(time_left // 60)
seconds = int(time_left % 60)
if time_left < 60:
timer = f"[bold red]⏱️ {seconds}s[/bold red]"
elif time_left < 180:
timer = f"[yellow]⏱️ {minutes}:{seconds:02d}[/yellow]"
else:
timer = f"[green]⏱️ {minutes}:{seconds:02d}[/green]"
status = "[green]● LIVE[/green]" if self.state.connected else "[red]○ DISCONNECTED[/red]"
mode = "[bold cyan]REAL TRADING[/bold cyan]"
header = f"{timer} | {self.state.slug} | {status} | {mode}"
return Panel(header, title="[bold]BTC 15-Min Live Bot[/bold]")
def create_token_panel(self, token: TokenData, label: str) -> Panel:
if not token:
return Panel("No data", title=label)
lines = []
if token.best_ask > 0:
lines.append(f"[red]ASK {token.best_ask:.3f}[/red] | {token.best_ask_size:.0f}")
else:
lines.append(f"[red]ASK ---[/red]")
lines.append("─" * 20)
lines.append(f"[bold white]LAST {token.last_price:.3f}[/bold white]")
if token.best_ask > 0 and token.best_bid > 0:
spread = token.best_ask - token.best_bid
lines.append(f"[dim]Spread: {spread:.3f}[/dim]")
lines.append("─" * 20)
if token.best_bid > 0:
lines.append(f"[green]BID {token.best_bid:.3f}[/green] | {token.best_bid_size:.0f}")
else:
lines.append(f"[green]BID ---[/green]")
return Panel(
"\n".join(lines),
title=f"[bold]{label}[/bold] - {self._fmt_price(token.last_price)}",
border_style="green" if "Up" in label else "red"
)
def _fmt_momentum(self, m: Optional[float]) -> str:
if m is None:
return "[dim]N/A[/dim]"
if m > 0:
return f"[green]+{m:.2f}%[/green]"
elif m < 0:
return f"[red]{m:.2f}%[/red]"
return f"[cyan]0.00%[/cyan]"
def create_indicators_panel(self, token: TokenData, label: str) -> Panel:
if not token or not token.trades:
return Panel("Waiting for data...", title=f"{label} Indicators")
mom_window = self.config.strategy.momentum_window_sec
vwap_window = self.config.strategy.vwap_window_sec
vwap = self.calc.calc_vwap(self.calc.get_trades_in_window(token.trades, vwap_window))
deviation = self.calc.calc_deviation(token.last_price, vwap)
zscore = self.calc.calc_zscore(token.trades, token.last_price, window=5)
momentum = self.calc.calc_momentum(token.trades, token.last_price, window=mom_window)
def fmt_vol(v):
if v >= 1_000_000:
return f"{v/1_000_000:.1f}M"
elif v >= 1_000:
return f"{v/1_000:.1f}K"
return f"{v:.0f}"
lines = [
f"VWAP {vwap_window}s: {vwap:.4f}",
f"Deviation: {self._fmt_dev(deviation)}",
f"Z-Score 5s: {self._fmt_zscore(zscore)}",
f"Mom {mom_window}s: {self._fmt_momentum(momentum)}",
"",
f"Trades: {token.trade_count}",
f"Volume: {fmt_vol(token.volume_total)}",
f" Buy: [green]{fmt_vol(token.volume_buy)}[/green]",
f" Sell: [red]{fmt_vol(token.volume_sell)}[/red]",
]
return Panel("\n".join(lines), title=f"{label} Indicators", border_style="blue")