tickwire 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tickwire/config.py ADDED
@@ -0,0 +1,53 @@
1
+ """Where a client points: live or sandbox, from arguments or the environment.
2
+
3
+ No host is hard-coded. The live API URL comes from ``base_url`` or
4
+ ``TICKWIRE_API_URL``; the sandbox URL from ``sandbox_url`` or
5
+ ``TICKWIRE_SANDBOX_URL``. A client asked for the sandbox with no sandbox URL
6
+ configured refuses to start instead of silently trading live.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from collections.abc import Mapping
12
+
13
+ from .errors import ConfigError
14
+
15
+ ENV_API_URL = "TICKWIRE_API_URL"
16
+ ENV_SANDBOX_URL = "TICKWIRE_SANDBOX_URL"
17
+ ENV_API_KEY = "TICKWIRE_API_KEY"
18
+ ENV_AGENT_KEY = "TICKWIRE_AGENT_KEY"
19
+
20
+
21
+ def resolve_base_url(base_url: str | None = None, *, sandbox: bool = False, sandbox_url: str | None = None,
22
+ env: Mapping[str, str] | None = None) -> str:
23
+ """The API base URL, without a trailing slash.
24
+
25
+ * ``base_url`` given: used as is (live or sandbox, the caller knows).
26
+ * ``sandbox=True``: ``sandbox_url``, else ``$TICKWIRE_SANDBOX_URL``.
27
+ * otherwise: ``$TICKWIRE_API_URL``.
28
+ """
29
+ env = os.environ if env is None else env
30
+ if base_url and sandbox:
31
+ raise ConfigError("pass either base_url or sandbox=True, not both (use sandbox_url= to "
32
+ "override the sandbox URL)")
33
+ if sandbox:
34
+ url = sandbox_url or env.get(ENV_SANDBOX_URL, "")
35
+ if not url.strip():
36
+ raise ConfigError(f"sandbox=True but no sandbox URL is configured: pass sandbox_url= or set "
37
+ f"{ENV_SANDBOX_URL}")
38
+ else:
39
+ url = base_url or env.get(ENV_API_URL, "")
40
+ if not url.strip():
41
+ raise ConfigError(f"no API URL: pass base_url= or set {ENV_API_URL} (or sandbox=True)")
42
+ url = url.strip().rstrip("/")
43
+ if not url.startswith(("https://", "http://")):
44
+ raise ConfigError(f"the API URL must start with https:// (got {url!r})")
45
+ return url
46
+
47
+
48
+ def resolve_token(token: str | None, env_name: str, *, env: Mapping[str, str] | None = None) -> str:
49
+ env = os.environ if env is None else env
50
+ tok = (token or env.get(env_name, "")).strip()
51
+ if not tok:
52
+ raise ConfigError(f"no credential: pass it or set {env_name}")
53
+ return tok
tickwire/errors.py ADDED
@@ -0,0 +1,107 @@
1
+ """Error types. Every API error carries the server's ``{"error", "message", …}`` envelope."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+
7
+ class TickwireError(Exception):
8
+ """Base class. ``code`` is the envelope's ``error`` field (e.g. ``not_supported_on_mt4``)."""
9
+
10
+ def __init__(self, message: str, *, status: int | None = None, code: str | None = None,
11
+ body: Any = None) -> None:
12
+ super().__init__(message)
13
+ self.message = message
14
+ self.status = status
15
+ self.code = code
16
+ self.body = body
17
+
18
+ def __repr__(self) -> str:
19
+ return f"{type(self).__name__}(status={self.status!r}, code={self.code!r}, message={self.message!r})"
20
+
21
+
22
+ class ConfigError(TickwireError):
23
+ """The client is misconfigured (no URL, no credential, sandbox without a sandbox URL)."""
24
+
25
+
26
+ class TransportError(TickwireError):
27
+ """No usable HTTP response (connection refused, reset, timeout).
28
+
29
+ For a read this is only a failed read. A mutation that fails this way was
30
+ either never sent (the connection could not be opened: the SDK retried it
31
+ with the same idempotency key) or raises :class:`OutcomeUnknown`.
32
+ """
33
+
34
+
35
+ class OutcomeUnknown(TransportError):
36
+ """A mutation reached the server, or may have, and no answer came back
37
+ (read timeout, reset, a 408 or 5xx without ``sent: false``, or a 409
38
+ ``idempotency_in_flight`` that outlasted the retries). It MAY have executed. The SDK never retries
39
+ it on its own: check the account (positions, orders, or the agent API's
40
+ request status) and, to retry, reuse ``idempotency_key`` so the server can
41
+ refuse a second execution."""
42
+
43
+ def __init__(self, message: str, *, idempotency_key: str | None = None, **kw) -> None:
44
+ super().__init__(message, **kw)
45
+ self.idempotency_key = idempotency_key
46
+
47
+
48
+ class BadRequest(TickwireError):
49
+ pass
50
+
51
+
52
+ class Unauthorized(TickwireError):
53
+ pass
54
+
55
+
56
+ class Forbidden(TickwireError):
57
+ pass
58
+
59
+
60
+ class SandboxKeyRestricted(Forbidden):
61
+ """403 ``sandbox_key_restricted``: a key from anonymous sandbox sign-up may only manage its
62
+ sandbox accounts, trade, stream and read. For webhooks, hooks, agent keys or more keys, sign
63
+ in and get a sandbox key from your live key (``create_sandbox_key``)."""
64
+
65
+
66
+ class NotFound(TickwireError):
67
+ pass
68
+
69
+
70
+ class Conflict(TickwireError):
71
+ """E.g. an Idempotency-Key reused with a different body."""
72
+
73
+
74
+ class NotSupportedOnMt4(TickwireError):
75
+ """The account is MT4 and the platform cannot do this (market depth, tick history…)."""
76
+
77
+
78
+ class RateLimited(TickwireError):
79
+ def __init__(self, message: str, *, retry_after: float | None = None, **kw) -> None:
80
+ super().__init__(message, **kw)
81
+ self.retry_after = retry_after
82
+
83
+
84
+ class ServerError(TickwireError):
85
+ pass
86
+
87
+
88
+ class RetryBudgetExhausted(TickwireError):
89
+ """Retries are paused because too many recent calls failed (anti-retry-storm guard)."""
90
+
91
+
92
+ def from_response(status: int, body: Any, *, retry_after: float | None = None) -> TickwireError:
93
+ code = message = None
94
+ if isinstance(body, dict):
95
+ code = body.get("error") or body.get("stringCode")
96
+ message = body.get("message") or body.get("detail")
97
+ message = str(message or f"HTTP {status}")
98
+ if code == "not_supported_on_mt4":
99
+ return NotSupportedOnMt4(message, status=status, code=code, body=body)
100
+ if code == "sandbox_key_restricted":
101
+ return SandboxKeyRestricted(message, status=status, code=code, body=body)
102
+ cls = {400: BadRequest, 401: Unauthorized, 403: Forbidden, 404: NotFound, 409: Conflict}.get(status)
103
+ if status == 429:
104
+ return RateLimited(message, status=status, code=code, body=body, retry_after=retry_after)
105
+ if cls is None:
106
+ cls = ServerError if status >= 500 else TickwireError
107
+ return cls(message, status=status, code=code, body=body)
tickwire/models.py ADDED
@@ -0,0 +1,167 @@
1
+ """Typed shapes (``TypedDict``) of the public API. ``total=False``: servers may add fields.
2
+
3
+ MetaApi-compatible models follow docs/research/metaapi-mt5-parity-spec.md §2;
4
+ Tickwire extras follow the bridge (health, audit) and control plane (webhooks).
5
+ Times are ISO-8601 UTC strings; ``brokerTime`` fields are broker-local strings
6
+ and are never labelled UTC.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from typing import Any, Literal, TypedDict
11
+
12
+ # "stale" is only sent by older engines; a quiet market is now "healthy" with
13
+ # prices_live False.
14
+ HealthStatus = Literal["healthy", "stale", "disconnected", "down"]
15
+
16
+
17
+ class Health(TypedDict, total=False):
18
+ status: HealthStatus
19
+ connected: bool
20
+ trading_enabled: bool
21
+ reasons: list[str]
22
+ last_tick_age_s: float | None
23
+ # Price movement across the Market Watch: False = no price moving (market
24
+ # likely closed; not a failure), None = not known yet.
25
+ prices_live: bool | None
26
+ prices_reason: str | None
27
+ last_price_at: str | None
28
+ last_price_symbol: str | None
29
+ last_price_age_s: float | None
30
+ symbols_checked: int
31
+ broker_time: str | None
32
+ checked_at: str
33
+ fx_status: str
34
+
35
+
36
+ class AuditEntry(TypedDict, total=False):
37
+ seq: int
38
+ ts_utc: str
39
+ actor: str
40
+ reason: str
41
+ action: str
42
+ request: dict
43
+ result: dict
44
+ idempotency_key: str | None
45
+ replayed: bool
46
+ broker_time: str | None
47
+
48
+
49
+ class AccountInformation(TypedDict, total=False):
50
+ platform: Literal["mt4", "mt5"]
51
+ broker: str
52
+ currency: str
53
+ server: str
54
+ balance: float
55
+ equity: float
56
+ margin: float
57
+ freeMargin: float
58
+ leverage: float
59
+ marginLevel: float
60
+ tradeAllowed: bool
61
+ marginMode: str
62
+ name: str
63
+ login: int
64
+ credit: float
65
+ type: str
66
+
67
+
68
+ class Position(TypedDict, total=False):
69
+ id: str
70
+ type: Literal["POSITION_TYPE_BUY", "POSITION_TYPE_SELL"]
71
+ symbol: str
72
+ magic: int
73
+ time: str
74
+ updateTime: str
75
+ brokerTime: str
76
+ openPrice: float
77
+ currentPrice: float
78
+ volume: float
79
+ profit: float
80
+ swap: float
81
+ commission: float
82
+ stopLoss: float
83
+ takeProfit: float
84
+ comment: str
85
+ clientId: str
86
+
87
+
88
+ class Order(TypedDict, total=False):
89
+ id: str
90
+ type: str
91
+ state: str
92
+ symbol: str
93
+ magic: int
94
+ time: str
95
+ brokerTime: str
96
+ openPrice: float
97
+ volume: float
98
+ currentVolume: float
99
+ positionId: str
100
+ stopLoss: float
101
+ takeProfit: float
102
+ clientId: str
103
+
104
+
105
+ class Deal(TypedDict, total=False):
106
+ id: str
107
+ type: str
108
+ entryType: str
109
+ symbol: str
110
+ time: str
111
+ brokerTime: str
112
+ volume: float
113
+ price: float
114
+ profit: float
115
+ commission: float
116
+ swap: float
117
+ positionId: str
118
+ orderId: str
119
+ clientId: str
120
+
121
+
122
+ class SymbolPrice(TypedDict, total=False):
123
+ symbol: str
124
+ bid: float
125
+ ask: float
126
+ time: str
127
+ brokerTime: str
128
+
129
+
130
+ class Trade(TypedDict, total=False):
131
+ actionType: str
132
+ symbol: str
133
+ volume: float
134
+ openPrice: float
135
+ stopLoss: float
136
+ takeProfit: float
137
+ positionId: str
138
+ orderId: str
139
+ comment: str
140
+ clientId: str
141
+ magic: int
142
+ slippage: float
143
+ expiration: dict[str, Any]
144
+
145
+
146
+ class TradeResponse(TypedDict, total=False):
147
+ numericCode: int
148
+ stringCode: str
149
+ message: str
150
+ orderId: str
151
+ positionId: str
152
+
153
+
154
+ TRADE_SUCCESS_CODES = frozenset({0, 10008, 10009, 10010, 10025})
155
+
156
+
157
+ def trade_succeeded(resp: TradeResponse) -> bool:
158
+ """MetaApi success set (spec §2.4). Anything else, including ambiguous codes, is not success."""
159
+ return resp.get("numericCode") in TRADE_SUCCESS_CODES
160
+
161
+
162
+ class Webhook(TypedDict, total=False):
163
+ id: str
164
+ url: str
165
+ secret: str
166
+ active: bool
167
+ created_at: str
tickwire/py.typed ADDED
File without changes
tickwire/results.py ADDED
@@ -0,0 +1,81 @@
1
+ """Typed trade outcomes for the guarded APIs (``/v1/execution`` and ``/v1/agent``).
2
+
3
+ The server answers every guarded trade with an ``outcome``:
4
+
5
+ ============= =================================================== ===========
6
+ ``outcome`` meaning ``sent``
7
+ ============= =================================================== ===========
8
+ ``applied`` the terminal confirmed the effect (``evidence``) ``True``
9
+ ``no_change`` nothing needed doing (e.g. already closed) ``True``
10
+ ``rejected`` not executed; with ``sent=False`` it never left ``True``/``False``
11
+ ``held`` a pre-trade hook holds it for approval (HTTP 202) ``False``
12
+ ``unknown`` it MAY have executed: never retry with a new key ``"unknown"``
13
+ ============= =================================================== ===========
14
+
15
+ :class:`TradeResult` carries that answer. An error envelope that says
16
+ ``outcome: rejected`` becomes a result too, and so does a lost reply (the SDK
17
+ reports ``unknown`` with the idempotency key it used and never retries it).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Literal
23
+
24
+ Outcome = Literal["applied", "no_change", "rejected", "held", "unknown"]
25
+ OUTCOMES = ("applied", "no_change", "rejected", "held", "unknown")
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class TradeResult:
30
+ outcome: Outcome
31
+ sent: bool | Literal["unknown"]
32
+ idempotency_key: str
33
+ status: int | None = None
34
+ body: dict[str, Any] = field(default_factory=dict)
35
+
36
+ @property
37
+ def ok(self) -> bool:
38
+ """The terminal confirmed it (``applied``) or nothing was needed (``no_change``)."""
39
+ return self.outcome in ("applied", "no_change")
40
+
41
+ @property
42
+ def is_unknown(self) -> bool:
43
+ return self.outcome == "unknown"
44
+
45
+ @property
46
+ def error(self) -> str | None:
47
+ """The error code of a refusal (``hook_denied``, ``kill_switch_engaged``, …)."""
48
+ return self.body.get("error")
49
+
50
+ @property
51
+ def message(self) -> str | None:
52
+ return self.body.get("message")
53
+
54
+ @property
55
+ def evidence(self) -> dict[str, Any] | None:
56
+ return self.body.get("evidence")
57
+
58
+ @property
59
+ def hold_id(self) -> str | None:
60
+ return self.body.get("hold_id")
61
+
62
+ @property
63
+ def replayed(self) -> bool:
64
+ return bool(self.body.get("replayed"))
65
+
66
+ @classmethod
67
+ def from_body(cls, status: int | None, body: Any, idempotency_key: str) -> "TradeResult":
68
+ b = body if isinstance(body, dict) else {"raw": body}
69
+ outcome = b.get("outcome")
70
+ if outcome not in OUTCOMES:
71
+ # never infer success: an answer without a known outcome is unknown
72
+ outcome = "held" if status == 202 else "unknown"
73
+ sent = b.get("sent")
74
+ if sent not in (True, False, "unknown"):
75
+ sent = {"held": False, "unknown": "unknown"}.get(outcome, "unknown")
76
+ return cls(outcome=outcome, sent=sent, idempotency_key=idempotency_key, status=status, body=b)
77
+
78
+ @classmethod
79
+ def unknown(cls, idempotency_key: str, message: str, status: int | None = None) -> "TradeResult":
80
+ return cls(outcome="unknown", sent="unknown", idempotency_key=idempotency_key, status=status,
81
+ body={"error": "no_reply", "message": message})
tickwire/stream.py ADDED
@@ -0,0 +1,281 @@
1
+ """Streaming client for Tickwire stream protocol v2 (parallel-build §1.4).
2
+
3
+ ``AccountStream`` keeps one WebSocket to ``/users/current/accounts/{id}/ws``,
4
+ mirrors the terminal state locally (:class:`TerminalState`) and survives
5
+ disconnects:
6
+
7
+ * **Resume.** Every frame carries a monotonic ``seq``. On reconnect the client
8
+ re-subscribes with ``sync.lastSeq`` = the last applied ``seq``; the server
9
+ replays from its ring buffer or runs a full sync (``synchronizationStarted``
10
+ resets the mirror). A gap in ``seq`` or a ``warning`` about dropped frames
11
+ forces a fresh full sync.
12
+ * **Bounded reconnects** with full-jitter backoff (:class:`~tickwire.backoff.Backoff`,
13
+ unlimited attempts but capped delay; the delay resets after a healthy session).
14
+ * **Clean close.** ``await stream.close()`` stops reconnecting, closes the socket
15
+ with code 1000 and cancels every task it started. It is idempotent.
16
+
17
+ Listeners: ``stream.on("positionUpdated", fn)`` (or ``"*"`` for every frame);
18
+ ``fn(frame, state)`` may be sync or async. ``await stream.wait_synchronized()``
19
+ resolves after the ``synchronized`` frame of the current sync.
20
+
21
+ Frame payloads are read from the frame itself or from its ``data`` member, so
22
+ the client tolerates either envelope style.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import contextlib
28
+ import json
29
+ import random
30
+ from dataclasses import dataclass, field
31
+ from typing import Any, Awaitable, Callable
32
+ from urllib.parse import quote
33
+
34
+ import websockets
35
+
36
+ from .backoff import Backoff
37
+
38
+ Listener = Callable[[dict, "TerminalState"], Any]
39
+
40
+
41
+ def _payload(frame: dict) -> dict:
42
+ data = frame.get("data")
43
+ return data if isinstance(data, dict) else frame
44
+
45
+
46
+ def _id(obj: Any) -> str | None:
47
+ if isinstance(obj, dict):
48
+ v = obj.get("id", obj.get("ticket"))
49
+ return None if v is None else str(v)
50
+ return None if obj is None else str(obj)
51
+
52
+
53
+ @dataclass
54
+ class TerminalState:
55
+ """Local mirror of one account, built only from server frames."""
56
+ account_information: dict | None = None
57
+ positions: dict[str, dict] = field(default_factory=dict)
58
+ orders: dict[str, dict] = field(default_factory=dict)
59
+ deals: dict[str, dict] = field(default_factory=dict)
60
+ history_orders: dict[str, dict] = field(default_factory=dict)
61
+ prices: dict[str, dict] = field(default_factory=dict)
62
+ health: dict | None = None
63
+ connected_to_broker: bool | None = None
64
+ synchronized: bool = False
65
+ last_seq: int | None = None
66
+
67
+ def apply(self, frame: dict) -> None:
68
+ t = frame.get("type")
69
+ p = _payload(frame)
70
+ if t == "synchronizationStarted":
71
+ self.account_information = None
72
+ self.positions.clear()
73
+ self.orders.clear()
74
+ self.deals.clear()
75
+ self.history_orders.clear()
76
+ self.synchronized = False
77
+ elif t in ("accountInformation",):
78
+ self.account_information = dict(p.get("accountInformation") or {})
79
+ elif t == "accountInformationUpdated":
80
+ self.account_information = {**(self.account_information or {}), **(p.get("accountInformation") or {})}
81
+ elif t == "positions":
82
+ self.positions = {k: v for v in p.get("positions") or [] if (k := _id(v))}
83
+ elif t == "orders":
84
+ self.orders = {k: v for v in p.get("orders") or [] if (k := _id(v))}
85
+ elif t in ("historyOrders", "deals"):
86
+ target = self.history_orders if t == "historyOrders" else self.deals
87
+ for v in p.get(t) or []:
88
+ if (k := _id(v)):
89
+ target[k] = v
90
+ elif t == "positionUpdated":
91
+ pos = p.get("position") or {}
92
+ if (k := _id(pos)):
93
+ self.positions[k] = pos
94
+ elif t == "positionRemoved":
95
+ self.positions.pop(_id(p.get("positionId", p.get("position"))) or "", None)
96
+ elif t == "orderUpdated":
97
+ order = p.get("order") or {}
98
+ if (k := _id(order)):
99
+ self.orders[k] = order
100
+ elif t == "orderCompleted":
101
+ self.orders.pop(_id(p.get("orderId", p.get("order"))) or "", None)
102
+ elif t == "historyOrderAdded":
103
+ ho = p.get("historyOrder") or p.get("order") or {}
104
+ if (k := _id(ho)):
105
+ self.history_orders[k] = ho
106
+ elif t == "dealAdded":
107
+ d = p.get("deal") or {}
108
+ if (k := _id(d)):
109
+ self.deals[k] = d
110
+ elif t == "prices":
111
+ for price in p.get("prices") or []:
112
+ if isinstance(price, dict) and price.get("symbol"):
113
+ self.prices[price["symbol"]] = price
114
+ elif t == "health":
115
+ self.health = dict(p.get("health") or p)
116
+ elif t == "brokerConnectionStatus":
117
+ self.connected_to_broker = bool(p.get("connected"))
118
+ elif t == "synchronized":
119
+ self.synchronized = True
120
+
121
+
122
+ class AccountStream:
123
+ def __init__(self, base_url: str, token: str, account_id: str, *,
124
+ market_data: list[dict] | None = None, starting_history_time: str | None = None,
125
+ backoff: Backoff | None = None, ping_interval_s: float = 20.0,
126
+ connect: Callable[..., Awaitable[Any]] | None = None) -> None:
127
+ scheme_url = base_url.replace("https://", "wss://").replace("http://", "ws://").rstrip("/")
128
+ self.url = f"{scheme_url}/users/current/accounts/{account_id}/ws?auth-token={quote(token, safe='')}"
129
+ self.account_id = account_id
130
+ self.market_data = market_data or []
131
+ self.starting_history_time = starting_history_time
132
+ self.backoff = backoff or Backoff(base_s=0.5, cap_s=15.0, max_attempts=10**9, rng=random.Random())
133
+ self.ping_interval_s = ping_interval_s
134
+ self._connect = connect or (lambda url: websockets.connect(url, max_size=None, open_timeout=10))
135
+ self.state = TerminalState()
136
+ self._listeners: dict[str, list[Listener]] = {}
137
+ self._task: asyncio.Task | None = None
138
+ self._ws = None
139
+ self._closing = False
140
+ self._synced = asyncio.Event()
141
+ self._force_full_sync = False
142
+ self.connections = 0 # observable for tests/metrics
143
+ self.reconnect_delays: list[float] = []
144
+
145
+ # ------------------------------------------------------------ listeners
146
+ def on(self, frame_type: str, fn: Listener) -> Callable[[], None]:
147
+ self._listeners.setdefault(frame_type, []).append(fn)
148
+
149
+ def off() -> None:
150
+ with contextlib.suppress(ValueError):
151
+ self._listeners[frame_type].remove(fn)
152
+ return off
153
+
154
+ async def _emit(self, frame: dict) -> None:
155
+ for fn in list(self._listeners.get(frame.get("type", ""), [])) + list(self._listeners.get("*", [])):
156
+ try:
157
+ r = fn(frame, self.state)
158
+ if asyncio.iscoroutine(r):
159
+ await r
160
+ except Exception: # a listener must never kill the stream
161
+ pass
162
+
163
+ # ------------------------------------------------------------ lifecycle
164
+ async def start(self) -> "AccountStream":
165
+ if self._task is None:
166
+ self._closing = False
167
+ self._task = asyncio.create_task(self._run(), name=f"tickwire-stream-{self.account_id}")
168
+ return self
169
+
170
+ async def __aenter__(self) -> "AccountStream":
171
+ return await self.start()
172
+
173
+ async def __aexit__(self, *exc) -> None:
174
+ await self.close()
175
+
176
+ async def wait_synchronized(self, timeout_s: float = 60.0) -> TerminalState:
177
+ await self.start()
178
+ await asyncio.wait_for(self._synced.wait(), timeout_s)
179
+ return self.state
180
+
181
+ async def subscribe_market_data(self, symbol: str, subscriptions: list[dict] | None = None) -> None:
182
+ entry = {"symbol": symbol, "subscriptions": subscriptions or [{"type": "quotes"}]}
183
+ self.market_data = [m for m in self.market_data if m.get("symbol") != symbol] + [entry]
184
+ if self._ws is not None:
185
+ await self._send({"type": "subscribe", "marketData": [entry]})
186
+
187
+ async def close(self) -> None:
188
+ self._closing = True
189
+ ws, task = self._ws, self._task
190
+ self._task = None
191
+ if ws is not None:
192
+ with contextlib.suppress(Exception):
193
+ await ws.close(code=1000)
194
+ if task is not None:
195
+ task.cancel()
196
+ with contextlib.suppress(asyncio.CancelledError, Exception):
197
+ await task
198
+ self._ws = None
199
+
200
+ @property
201
+ def closed(self) -> bool:
202
+ return self._closing and self._task is None
203
+
204
+ # ------------------------------------------------------------ internals
205
+ async def _send(self, msg: dict) -> None:
206
+ if self._ws is not None:
207
+ await self._ws.send(json.dumps(msg))
208
+
209
+ def _subscribe_msg(self) -> dict:
210
+ if self._force_full_sync:
211
+ self.state.last_seq = None # a full sync starts a new seq lineage
212
+ last = self.state.last_seq
213
+ msg: dict = {"type": "subscribe", "sync": {"startingHistoryTime": self.starting_history_time,
214
+ "lastSeq": last}}
215
+ if self.market_data:
216
+ msg["marketData"] = self.market_data
217
+ return msg
218
+
219
+ async def _run(self) -> None:
220
+ attempt = 0
221
+ while not self._closing:
222
+ healthy = False
223
+ try:
224
+ async with self._connect(self.url) as ws:
225
+ self._ws = ws
226
+ self.connections += 1
227
+ await self._send(self._subscribe_msg())
228
+ self._force_full_sync = False
229
+ pinger = asyncio.create_task(self._pinger())
230
+ try:
231
+ async for raw in ws:
232
+ healthy = True
233
+ await self._handle(json.loads(raw))
234
+ if self._force_full_sync:
235
+ break # drop and resubscribe from scratch
236
+ finally:
237
+ pinger.cancel()
238
+ with contextlib.suppress(asyncio.CancelledError, Exception):
239
+ await pinger
240
+ except asyncio.CancelledError:
241
+ raise
242
+ except Exception:
243
+ pass
244
+ finally:
245
+ self._ws = None
246
+ if self._closing:
247
+ break
248
+ attempt = 1 if healthy else attempt + 1
249
+ delay = self.backoff.delay(attempt)
250
+ self.reconnect_delays.append(delay)
251
+ await asyncio.sleep(delay)
252
+
253
+ async def _pinger(self) -> None:
254
+ while True:
255
+ await asyncio.sleep(self.ping_interval_s)
256
+ await self._send({"type": "ping"})
257
+
258
+ async def _handle(self, frame: dict) -> None:
259
+ seq = frame.get("seq")
260
+ t = frame.get("type")
261
+ if isinstance(seq, int):
262
+ last = self.state.last_seq
263
+ if last is not None and seq <= last and t != "synchronizationStarted":
264
+ return # duplicate from a replay
265
+ if last is not None and seq > last + 1 and t != "synchronizationStarted":
266
+ self._force_full_sync = True # gap: our mirror can no longer be trusted
267
+ self._synced.clear()
268
+ self.state.synchronized = False
269
+ return
270
+ self.state.last_seq = seq
271
+ if t == "warning":
272
+ p = _payload(frame)
273
+ if p.get("firstMissingSeq") is not None or p.get("code") in ("slow_consumer", "frames_dropped"):
274
+ self._force_full_sync = True
275
+ self._synced.clear()
276
+ if t == "synchronizationStarted":
277
+ self._synced.clear()
278
+ self.state.apply(frame)
279
+ if t == "synchronized":
280
+ self._synced.set()
281
+ await self._emit(frame)