|
| 1 | +import json |
| 2 | +import os |
| 3 | +import time |
| 4 | +from threading import Lock |
| 5 | +from typing import Any, Dict, Optional, Tuple |
| 6 | + |
| 7 | + |
| 8 | +class ConfirmationStore: |
| 9 | + def __init__(self, path: str): |
| 10 | + self.path = path |
| 11 | + self.lock = Lock() |
| 12 | + self._data: Dict[str, Dict[str, Any]] = {} |
| 13 | + self._load() |
| 14 | + |
| 15 | + def _load(self): |
| 16 | + try: |
| 17 | + if os.path.exists(self.path): |
| 18 | + with open(self.path, "r", encoding="utf-8") as f: |
| 19 | + self._data = json.load(f) |
| 20 | + except Exception: |
| 21 | + self._data = {} |
| 22 | + |
| 23 | + def _save(self): |
| 24 | + tmp = f"{self.path}.tmp" |
| 25 | + with open(tmp, "w", encoding="utf-8") as f: |
| 26 | + json.dump(self._data, f) |
| 27 | + os.replace(tmp, self.path) |
| 28 | + |
| 29 | + def mark_pending(self, key: str, payload: Dict[str, Any]) -> None: |
| 30 | + with self.lock: |
| 31 | + self._data[key] = {"first_seen": time.time(), "payload": payload} |
| 32 | + try: |
| 33 | + self._save() |
| 34 | + except Exception: |
| 35 | + pass |
| 36 | + |
| 37 | + def pop_if_confirmed(self, key: str, delay: int, ttl: int) -> Tuple[bool, Optional[Dict[str, Any]]]: |
| 38 | + """ |
| 39 | + Returns (confirmed, payload). If confirmed is True, pending entry is removed. |
| 40 | + """ |
| 41 | + with self.lock: |
| 42 | + entry = self._data.get(key) |
| 43 | + if not entry: |
| 44 | + return False, None |
| 45 | + now = time.time() |
| 46 | + first = entry.get("first_seen", now) |
| 47 | + if now - first > ttl: |
| 48 | + # expired |
| 49 | + del self._data[key] |
| 50 | + try: |
| 51 | + self._save() |
| 52 | + except Exception: |
| 53 | + pass |
| 54 | + return False, None |
| 55 | + if now - first >= delay: |
| 56 | + payload = entry.get("payload") |
| 57 | + del self._data[key] |
| 58 | + try: |
| 59 | + self._save() |
| 60 | + except Exception: |
| 61 | + pass |
| 62 | + return True, payload |
| 63 | + return False, None |
| 64 | + |
| 65 | + def expire_all_older_than(self, ttl: int) -> int: |
| 66 | + removed = 0 |
| 67 | + now = time.time() |
| 68 | + with self.lock: |
| 69 | + keys = list(self._data.keys()) |
| 70 | + for k in keys: |
| 71 | + if now - self._data[k].get("first_seen", now) > ttl: |
| 72 | + del self._data[k] |
| 73 | + removed += 1 |
| 74 | + if removed: |
| 75 | + try: |
| 76 | + self._save() |
| 77 | + except Exception: |
| 78 | + pass |
| 79 | + return removed |
| 80 | + |
| 81 | + |
| 82 | +def check_market_quality_for_entry(best_bid: Optional[float], best_ask: Optional[float], ask_size: Optional[float], settings) -> Tuple[bool, str, Dict[str, Any]]: |
| 83 | + """ |
| 84 | + Return (ok, reason, details) |
| 85 | + """ |
| 86 | + details = { |
| 87 | + "best_bid": best_bid, |
| 88 | + "best_ask": best_ask, |
| 89 | + "ask_size": ask_size, |
| 90 | + } |
| 91 | + if best_ask is None: |
| 92 | + return False, "no_entry_price", details |
| 93 | + if best_bid is None: |
| 94 | + return False, "no_best_bid", details |
| 95 | + spread = best_ask - best_bid |
| 96 | + details["spread"] = spread |
| 97 | + if spread > settings.MAX_SPREAD_ENTRY: |
| 98 | + return False, "spread_too_wide", details |
| 99 | + if settings.ENFORCE_DEPTH: |
| 100 | + if ask_size is None: |
| 101 | + return False, "ask_size_unavailable", details |
| 102 | + try: |
| 103 | + if float(ask_size) < float(settings.MIN_ASK_SIZE): |
| 104 | + return False, "ask_size_too_small", details |
| 105 | + except Exception: |
| 106 | + return False, "ask_size_unavailable", details |
| 107 | + return True, "ok", details |
| 108 | + |
| 109 | + |
| 110 | +def compute_time_to_market_end(market: Optional[Dict[str, Any]]) -> Tuple[Optional[int], str]: |
| 111 | + """ |
| 112 | + Returns (seconds_to_end or None, reason) |
| 113 | + """ |
| 114 | + if not market: |
| 115 | + return None, "end_time_unavailable" |
| 116 | + end_ts = market.get("end_time") or market.get("close_time") or market.get("end") |
| 117 | + if not end_ts: |
| 118 | + return None, "end_time_unavailable" |
| 119 | + try: |
| 120 | + # Expect ISO format; if numeric epoch, handle |
| 121 | + from datetime import datetime, timezone |
| 122 | + |
| 123 | + if isinstance(end_ts, (int, float)): |
| 124 | + end = datetime.fromtimestamp(float(end_ts), tz=timezone.utc) |
| 125 | + else: |
| 126 | + end = datetime.fromisoformat(str(end_ts).replace("Z", "+00:00")) |
| 127 | + now = datetime.now(timezone.utc) |
| 128 | + seconds = int((end - now).total_seconds()) |
| 129 | + return seconds, "ok" |
| 130 | + except Exception: |
| 131 | + return None, "end_time_unavailable" |
| 132 | + |
0 commit comments