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/client.py ADDED
@@ -0,0 +1,844 @@
1
+ """REST clients for the Tickwire API.
2
+
3
+ * :class:`Tickwire` / :class:`AsyncTickwire`: an API key (``tw_live_…``, or a
4
+ sandbox key). The native API (MetaApi-compatible per account, FxSocket-style
5
+ control plane), agent administration (agent keys, kill switches, pre-trade
6
+ hooks, holds, the agent audit log), guarded execution (``/v1/execution``),
7
+ dedicated IPs and the billing summary (read-only).
8
+ * :class:`AgentClient` / :class:`AsyncAgentClient` (``tickwire.agent``): an
9
+ agent key (``twag_…``) on the guarded agent API.
10
+
11
+ Every call goes through an operation of ``tickwire._operations``, generated
12
+ from the public OpenAPI spec (``sdk/openapi/generate.py``), so the SDK cannot
13
+ call a path or query parameter the spec does not have.
14
+
15
+ Safety properties:
16
+
17
+ * **Idempotent mutations.** Every POST/PUT/PATCH/DELETE carries an
18
+ ``Idempotency-Key`` (generated when the caller does not pass one), plus
19
+ ``X-Actor`` and ``X-Reason`` for the audit trail. A retry reuses the key.
20
+ * **Retries only when safe.** Reads are retried on transport errors and
21
+ 408/429/502/503/504. A mutation is retried only when the server confirms it
22
+ did not run it: the connection could not be opened; a 409
23
+ ``idempotency_in_flight`` (the first attempt is still running: the retry,
24
+ after ``Retry-After``, returns its stored result); or a 429/5xx whose body
25
+ says explicitly ``sent: false`` (or ``outcome: "not_sent"``). Error codes
26
+ alone never count. Any other 408/5xx, and
27
+ a lost reply (read timeout, reset), raises
28
+ :class:`~tickwire.errors.OutcomeUnknown` at once, or, for the guarded trade
29
+ calls, returns a :class:`~tickwire.results.TradeResult` with
30
+ ``outcome="unknown"``. It is never retried automatically.
31
+ * **Bounded.** Full-jitter backoff, at most ``max_attempts`` tries per call,
32
+ within a per-client :class:`~tickwire.backoff.RetryBudget`.
33
+ * **Clean close.** ``aclose()`` / ``close()`` (or ``async with`` / ``with``)
34
+ releases every connection; a closed client refuses further calls.
35
+ """
36
+ from __future__ import annotations
37
+
38
+ import asyncio
39
+ import time
40
+ import uuid
41
+ from dataclasses import dataclass, field
42
+ from typing import Any, Callable
43
+ from urllib.parse import quote
44
+
45
+ import httpx
46
+
47
+ from . import models
48
+ from ._operations import OPERATIONS
49
+ from ._version import __version__
50
+ from .backoff import Backoff, RetryBudget
51
+ from .config import ENV_API_KEY, resolve_base_url, resolve_token
52
+ from .errors import (OutcomeUnknown, RetryBudgetExhausted, TickwireError, TransportError,
53
+ from_response)
54
+ from .results import TradeResult
55
+
56
+ RETRYABLE_STATUS = frozenset({408, 429, 502, 503, 504})
57
+ # A mutation that got a 408/429/5xx is retried only when the body says, explicitly,
58
+ # that nothing was sent: ``sent: false`` or ``outcome: "not_sent"`` (top level or
59
+ # in ``metadata``). Error codes alone never count: a generic 503 can come from
60
+ # anywhere, including after the order reached the broker.
61
+ # 409: the first attempt with this key is still running; this one did nothing.
62
+ IN_FLIGHT_CODE = "idempotency_in_flight"
63
+ NOT_SENT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout, httpx.UnsupportedProtocol)
64
+ MUTATING = frozenset({"POST", "PUT", "PATCH", "DELETE"})
65
+ USER_AGENT = f"tickwire-python/{__version__}"
66
+ _REASON_SAFE = " ,.:;!?()-_/'\"@#$&*+=<>[]{}|~^`"
67
+
68
+
69
+ def new_idempotency_key() -> str:
70
+ return "tw_" + uuid.uuid4().hex
71
+
72
+
73
+ def _encode_reason(reason: str) -> str:
74
+ """HTTP headers are ASCII: percent-encode anything else (the server decodes it)."""
75
+ return reason if reason.isascii() and reason.isprintable() else quote(reason, safe=_REASON_SAFE)
76
+
77
+
78
+ @dataclass
79
+ class ClientOptions:
80
+ base_url: str
81
+ token: str
82
+ actor: str = "sdk"
83
+ timeout_s: float = 30.0
84
+ control_prefix: str = "/v1" # where the gateway mounts the FxSocket control plane
85
+ backoff: Backoff = field(default_factory=Backoff)
86
+ budget: RetryBudget = field(default_factory=RetryBudget)
87
+ sleep: Callable[[float], Any] | None = None # test hook
88
+ sandbox: bool = False
89
+
90
+
91
+ @dataclass
92
+ class _Req:
93
+ method: str
94
+ path: str
95
+ params: dict | None = None
96
+ json: Any = None
97
+ headers: dict = field(default_factory=dict)
98
+
99
+ @property
100
+ def mutating(self) -> bool:
101
+ return self.method in MUTATING
102
+
103
+ @property
104
+ def idempotency_key(self) -> str | None:
105
+ return self.headers.get("Idempotency-Key")
106
+
107
+
108
+ def _retry_after(resp: httpx.Response) -> float | None:
109
+ v = resp.headers.get("retry-after")
110
+ try:
111
+ return float(v) if v is not None else None
112
+ except ValueError:
113
+ return None
114
+
115
+
116
+ def _codes(body: Any) -> set:
117
+ if not isinstance(body, dict):
118
+ return set()
119
+ out = {body.get(k) for k in ("error", "code", "stringCode", "tickwireError")}
120
+ return {c for c in out if isinstance(c, str)}
121
+
122
+
123
+ def _confirmed_not_sent(body: Any) -> bool:
124
+ """Did the server say this mutation was not sent (so a same-key retry is safe)?"""
125
+ if not isinstance(body, dict):
126
+ return False
127
+ meta = body.get("metadata") if isinstance(body.get("metadata"), dict) else {}
128
+ sent = body.get("sent", meta.get("sent"))
129
+ if sent is not None: # True or "unknown": it may have run
130
+ return sent is False
131
+ return body.get("outcome", meta.get("outcome")) == "not_sent"
132
+
133
+
134
+ def _decode(resp: httpx.Response) -> Any:
135
+ if not resp.content:
136
+ return None
137
+ try:
138
+ return resp.json()
139
+ except ValueError:
140
+ return resp.text
141
+
142
+
143
+ def _trade_error(e: Exception, key: str) -> TradeResult:
144
+ """Guarded trades: a lost reply or a refusal envelope is a result, not an exception."""
145
+ if isinstance(e, OutcomeUnknown):
146
+ return TradeResult.unknown(key, e.message, e.status)
147
+ if isinstance(e, TickwireError) and isinstance(e.body, dict) and e.body.get("outcome") in (
148
+ "rejected", "unknown", "held"):
149
+ return TradeResult.from_body(e.status, e.body, key)
150
+ raise e
151
+
152
+
153
+ class _Base:
154
+ """Request building and the retry decision, shared by the sync and async clients."""
155
+
156
+ AUTH = "key" # which operations this client may call ("key" or "agent")
157
+
158
+ def __init__(self, base_url: str | None, token: str | None, *, sandbox: bool = False,
159
+ sandbox_url: str | None = None, token_env: str = ENV_API_KEY, **options: Any) -> None:
160
+ self.opts = ClientOptions(base_url=resolve_base_url(base_url, sandbox=sandbox, sandbox_url=sandbox_url),
161
+ token=resolve_token(token, token_env), sandbox=sandbox, **options)
162
+ self._closed = False
163
+
164
+ def __repr__(self) -> str: # never show the credential
165
+ return f"{type(self).__name__}({self.opts.base_url!r}, sandbox={self.opts.sandbox})"
166
+
167
+ @property
168
+ def base_url(self) -> str:
169
+ return self.opts.base_url
170
+
171
+ @property
172
+ def sandbox(self) -> bool:
173
+ return self.opts.sandbox
174
+
175
+ @property
176
+ def closed(self) -> bool:
177
+ return self._closed
178
+
179
+ def _headers(self) -> dict:
180
+ return {"auth-token": self.opts.token, "User-Agent": USER_AGENT, "Accept": "application/json"}
181
+
182
+ # ---- request building
183
+ def _prepare(self, method: str, path: str, *, params=None, json=None, idempotency_key: str | None = None,
184
+ actor: str | None = None, reason: str | None = None, control: bool = False) -> _Req:
185
+ if self._closed:
186
+ raise TickwireError("client is closed")
187
+ headers = {}
188
+ if control:
189
+ headers["X-API-Key"] = self.opts.token
190
+ path = self.opts.control_prefix.rstrip("/") + path
191
+ if method in MUTATING:
192
+ headers["Idempotency-Key"] = idempotency_key or new_idempotency_key()
193
+ headers["X-Actor"] = actor or self.opts.actor
194
+ headers["X-Reason"] = _encode_reason(reason or "")
195
+ params = {k: v for k, v in (params or {}).items() if v is not None} or None
196
+ return _Req(method, path, params=params, json=json, headers=headers)
197
+
198
+ def _op(self, key: str, *, path: dict | None = None, params: dict | None = None, json: Any = None,
199
+ idempotency_key: str | None = None, actor: str | None = None, reason: str | None = None) -> _Req:
200
+ """Build a request for a generated operation (``"METHOD /public/path"``)."""
201
+ op = OPERATIONS.get(key)
202
+ if op is None:
203
+ raise TickwireError(f"unknown operation {key!r} (not in the SDK's OpenAPI slice)")
204
+ if op["auth"] != self.AUTH:
205
+ need = "an agent key (AgentClient)" if op["auth"] == "agent" else "an API key (Tickwire)"
206
+ raise TickwireError(f"{key} needs {need}")
207
+ path = path or {}
208
+ if set(path) != set(op["pathParams"]):
209
+ raise TickwireError(f"{key}: path parameters {sorted(path)} != {op['pathParams']}")
210
+ unknown = set(k for k, v in (params or {}).items() if v is not None) - set(op["query"])
211
+ if unknown and not op["pending"]:
212
+ raise TickwireError(f"{key}: unknown query parameters {sorted(unknown)}")
213
+ url = op["path"]
214
+ for name, value in path.items():
215
+ url = url.replace("{" + name + "}", quote(str(value), safe=""))
216
+ if op["controlPrefixed"]:
217
+ url = self.opts.control_prefix.rstrip("/") + url[len("/v1"):]
218
+ req = self._prepare(op["method"], url, params=params, json=json, idempotency_key=idempotency_key,
219
+ actor=actor, reason=reason)
220
+ if url.startswith("/v1/") or op["controlPrefixed"]:
221
+ if self.AUTH == "key":
222
+ req.headers["X-API-Key"] = self.opts.token
223
+ return req
224
+
225
+ # ---- the retry decision
226
+ def _decide(self, req: _Req, attempt: int, resp: httpx.Response | None, exc: Exception | None):
227
+ """Return ``("done", (status, body))``, ``("raise", err)`` or ``("retry", delay)``."""
228
+ if resp is not None and resp.status_code < 400:
229
+ self.opts.budget.on_success()
230
+ return "done", (resp.status_code, _decode(resp))
231
+ key = req.idempotency_key
232
+ if resp is not None:
233
+ status = resp.status_code
234
+ body = _decode(resp)
235
+ err = from_response(status, body, retry_after=_retry_after(resp))
236
+ retry_after = _retry_after(resp)
237
+ if not req.mutating:
238
+ retryable = status in RETRYABLE_STATUS
239
+ elif status == 409 and IN_FLIGHT_CODE in _codes(body):
240
+ # Not run: the first attempt is still running. Same key again,
241
+ # after Retry-After, returns its result once it is done.
242
+ if attempt >= self.opts.backoff.max_attempts:
243
+ return "raise", OutcomeUnknown(
244
+ "the first attempt with this idempotency key is still running; its "
245
+ "outcome is not known yet. Repeat with the same key later (never a new "
246
+ "one) or check the account", status=status, code=err.code, body=body,
247
+ idempotency_key=key)
248
+ retryable = True
249
+ elif status == 408 or status == 429 or status >= 500:
250
+ if not _confirmed_not_sent(body):
251
+ return "raise", OutcomeUnknown(
252
+ f"HTTP {status}: the request may have executed ({err.message}); "
253
+ f"it is not retried automatically", status=status, code=err.code,
254
+ body=err.body, idempotency_key=key)
255
+ retryable = True
256
+ else:
257
+ retryable = False
258
+ else:
259
+ if req.mutating and not isinstance(exc, NOT_SENT_ERRORS):
260
+ return "raise", OutcomeUnknown(
261
+ f"{type(exc).__name__} after the request was sent: it may have executed; "
262
+ f"it is not retried automatically", idempotency_key=key)
263
+ err = TransportError(f"{type(exc).__name__}: {exc}")
264
+ retryable, retry_after = True, None
265
+ if not retryable or attempt >= self.opts.backoff.max_attempts:
266
+ return "raise", err
267
+ if not self.opts.budget.try_spend():
268
+ return "raise", RetryBudgetExhausted(f"retry budget exhausted after: {err.message}",
269
+ status=err.status, code=err.code, body=err.body)
270
+ return "retry", self.opts.backoff.delay(attempt, retry_after)
271
+
272
+ # ---- calls (the transport mixin provides _dispatch)
273
+ def _call(self, key: str, *, ok: Callable[[int, Any], Any] | None = None,
274
+ err: Callable[[Exception], Any] | None = None, **kw) -> Any:
275
+ return self._dispatch(self._op(key, **kw), ok, err)
276
+
277
+ def _trade_call(self, key: str, **kw) -> Any:
278
+ req = self._op(key, **kw)
279
+ k = req.idempotency_key
280
+ return self._dispatch(req, lambda s, b: TradeResult.from_body(s, b, k), lambda e: _trade_error(e, k))
281
+
282
+
283
+ # ---------------------------------------------------------------- transports
284
+ class _SyncTransport:
285
+ def _open(self, transport) -> None:
286
+ self._http = httpx.Client(base_url=self.opts.base_url, timeout=self.opts.timeout_s,
287
+ transport=transport, headers=self._headers())
288
+
289
+ def __enter__(self):
290
+ return self
291
+
292
+ def __exit__(self, *exc) -> None:
293
+ self.close()
294
+
295
+ def close(self) -> None:
296
+ if not self._closed:
297
+ self._closed = True
298
+ self._http.close()
299
+
300
+ def _execute(self, req: _Req) -> tuple[int, Any]:
301
+ sleep = self.opts.sleep or time.sleep
302
+ attempt = 0
303
+ while True:
304
+ attempt += 1
305
+ resp = exc = None
306
+ try:
307
+ resp = self._http.request(req.method, req.path, params=req.params, json=req.json,
308
+ headers=req.headers)
309
+ except httpx.TransportError as e:
310
+ exc = e
311
+ action, value = self._decide(req, attempt, resp, exc)
312
+ if action == "done":
313
+ return value
314
+ if action == "raise":
315
+ raise value
316
+ sleep(value)
317
+
318
+ def _dispatch(self, req: _Req, ok, err):
319
+ try:
320
+ status, body = self._execute(req)
321
+ except TickwireError as e:
322
+ if err is None:
323
+ raise
324
+ return err(e)
325
+ return ok(status, body) if ok else body
326
+
327
+ def request(self, method: str, path: str, **kw) -> Any:
328
+ """Low-level call on any path (``control=True`` for the FxSocket control plane)."""
329
+ return self._execute(self._prepare(method, path, **kw))[1]
330
+
331
+ def pages(self, list_method: Callable[..., Any], **kw):
332
+ """Every page of a cursor-paginated native list, lazily:
333
+
334
+ >>> for page in tw.pages(tw.list_agent_keys, limit=100):
335
+ ... for key in page["data"]: ...
336
+
337
+ Follows ``next_cursor`` until ``has_more`` is false; ``kw`` are the
338
+ list's own filters (kept the same on every page, as the cursor requires)."""
339
+ cursor = None
340
+ while True:
341
+ page = list_method(**kw, cursor=cursor)
342
+ yield page
343
+ if not (isinstance(page, dict) and page.get("has_more") and page.get("next_cursor")):
344
+ return
345
+ cursor = page["next_cursor"]
346
+
347
+
348
+ class _AsyncTransport:
349
+ def _open(self, transport) -> None:
350
+ self._http = httpx.AsyncClient(base_url=self.opts.base_url, timeout=self.opts.timeout_s,
351
+ transport=transport, headers=self._headers())
352
+
353
+ async def __aenter__(self):
354
+ return self
355
+
356
+ async def __aexit__(self, *exc) -> None:
357
+ await self.aclose()
358
+
359
+ async def aclose(self) -> None:
360
+ if not self._closed:
361
+ self._closed = True
362
+ await self._http.aclose()
363
+
364
+ async def _execute(self, req: _Req) -> tuple[int, Any]:
365
+ sleep = self.opts.sleep or asyncio.sleep
366
+ attempt = 0
367
+ while True:
368
+ attempt += 1
369
+ resp = exc = None
370
+ try:
371
+ resp = await self._http.request(req.method, req.path, params=req.params, json=req.json,
372
+ headers=req.headers)
373
+ except httpx.TransportError as e:
374
+ exc = e
375
+ action, value = self._decide(req, attempt, resp, exc)
376
+ if action == "done":
377
+ return value
378
+ if action == "raise":
379
+ raise value
380
+ r = sleep(value)
381
+ if asyncio.iscoroutine(r):
382
+ await r
383
+
384
+ async def _dispatch(self, req: _Req, ok, err):
385
+ try:
386
+ status, body = await self._execute(req)
387
+ except TickwireError as e:
388
+ if err is None:
389
+ raise
390
+ return err(e)
391
+ return ok(status, body) if ok else body
392
+
393
+ async def request(self, method: str, path: str, **kw) -> Any:
394
+ """Low-level call on any path (``control=True`` for the FxSocket control plane)."""
395
+ return (await self._execute(self._prepare(method, path, **kw)))[1]
396
+
397
+ async def pages(self, list_method: Callable[..., Any], **kw):
398
+ """Every page of a cursor-paginated native list (async generator):
399
+ ``async for page in tw.pages(tw.list_agent_keys): …``."""
400
+ cursor = None
401
+ while True:
402
+ page = await list_method(**kw, cursor=cursor)
403
+ yield page
404
+ if not (isinstance(page, dict) and page.get("has_more") and page.get("next_cursor")):
405
+ return
406
+ cursor = page["next_cursor"]
407
+
408
+
409
+ # ------------------------------------------------------------------ surfaces
410
+ def _entries(key: str):
411
+ def pick(_status: int, body: Any) -> Any:
412
+ return body.get(key, body) if isinstance(body, dict) else body
413
+ return pick
414
+
415
+
416
+ def _require_reason(reason: str) -> str:
417
+ if not reason or not reason.strip():
418
+ raise ValueError("reason is required: say why (it is recorded in the audit log)")
419
+ return reason
420
+
421
+
422
+ class _OwnerSurface:
423
+ """API-key operations. On the async client every method returns an awaitable."""
424
+
425
+ def account(self, account_id: str) -> "Account":
426
+ """One trading account (MT4 or MT5; the API is identical)."""
427
+ return Account(self, account_id)
428
+
429
+ # ---- native control plane (FxSocket-compatible)
430
+ def list_accounts(self) -> list[dict]:
431
+ return self._call("GET /v1/accounts")
432
+
433
+ def get_account(self, account_id: str) -> dict:
434
+ return self._call("GET /v1/accounts/{account_id}", path={"account_id": account_id})
435
+
436
+ def list_webhooks(self) -> list[models.Webhook]:
437
+ return self._call("GET /v1/webhooks")
438
+
439
+ def get_webhook(self, webhook_id: str) -> models.Webhook:
440
+ return self._call("GET /v1/webhooks/{webhook_id}", path={"webhook_id": webhook_id})
441
+
442
+ def create_webhook(self, url: str, *, secret: str | None = None, idempotency_key: str | None = None,
443
+ reason: str = "") -> models.Webhook:
444
+ body = {"url": url} if secret is None else {"url": url, "secret": secret}
445
+ return self._call("POST /v1/webhooks", json=body, idempotency_key=idempotency_key, reason=reason)
446
+
447
+ def delete_webhook(self, webhook_id: str, *, idempotency_key: str | None = None, reason: str = "") -> None:
448
+ return self._call("DELETE /v1/webhooks/{webhook_id}", path={"webhook_id": webhook_id},
449
+ ok=lambda s, b: None, idempotency_key=idempotency_key, reason=reason)
450
+
451
+ # ---- webhooks v2: settings, rotation, delivery log, resend
452
+ def webhook_event_types(self) -> Any:
453
+ """Every event type Tickwire sends, with a description and an example."""
454
+ return self._call("GET /v1/webhook-event-types")
455
+
456
+ def webhook_settings(self, webhook_id: str) -> dict:
457
+ """Status, ``disabledReason``, ``enabledEvents``, the secret preview and the rotation overlap."""
458
+ return self._call("GET /v1/webhooks/{webhook_id}/settings", path={"webhook_id": webhook_id})
459
+
460
+ def update_webhook(self, webhook_id: str, *, enabled_events: list[str] | None = None, url: str | None = None,
461
+ description: str | None = None, reason: str = "",
462
+ idempotency_key: str | None = None) -> dict:
463
+ """``enabled_events``: exact types, family wildcards (``"trade.*"``) or ``["*"]``."""
464
+ body = {k: v for k, v in (("enabledEvents", enabled_events), ("url", url), ("description", description))
465
+ if v is not None}
466
+ return self._call("PATCH /v1/webhooks/{webhook_id}", path={"webhook_id": webhook_id}, json=body,
467
+ reason=reason, idempotency_key=idempotency_key)
468
+
469
+ def enable_webhook(self, webhook_id: str, *, reason: str = "", idempotency_key: str | None = None) -> dict:
470
+ return self._call("POST /v1/webhooks/{webhook_id}/enable", path={"webhook_id": webhook_id},
471
+ reason=reason, idempotency_key=idempotency_key)
472
+
473
+ def disable_webhook(self, webhook_id: str, *, reason: str = "", idempotency_key: str | None = None) -> dict:
474
+ return self._call("POST /v1/webhooks/{webhook_id}/disable", path={"webhook_id": webhook_id},
475
+ reason=reason, idempotency_key=idempotency_key)
476
+
477
+ def rotate_webhook_secret(self, webhook_id: str, *, secret: str | None = None,
478
+ overlap_hours: float | None = None, reason: str = "",
479
+ idempotency_key: str | None = None) -> dict:
480
+ """A new secret (``secret`` and ``standardSecret``, shown once). The old one stays valid for
481
+ ``overlap_hours`` (default 24): verify with both meanwhile (``verify_webhook([old, new], …)``)."""
482
+ body = {k: v for k, v in (("secret", secret), ("overlapHours", overlap_hours)) if v is not None}
483
+ return self._call("POST /v1/webhooks/{webhook_id}/rotate-secret", path={"webhook_id": webhook_id},
484
+ json=body, reason=reason, idempotency_key=idempotency_key)
485
+
486
+ def reveal_webhook_secret(self, webhook_id: str, *, reason: str = "",
487
+ idempotency_key: str | None = None) -> dict:
488
+ return self._call("POST /v1/webhooks/{webhook_id}/reveal-secret", path={"webhook_id": webhook_id},
489
+ reason=reason, idempotency_key=idempotency_key)
490
+
491
+ def list_webhook_deliveries(self, webhook_id: str, *, status: str | None = None, event_type: str | None = None,
492
+ event_id: str | None = None, since: str | None = None, until: str | None = None,
493
+ cursor: str | None = None, limit: int | None = None) -> dict:
494
+ """Newest first: ``{data, hasMore, nextCursor}``."""
495
+ return self._call("GET /v1/webhooks/{webhook_id}/deliveries", path={"webhook_id": webhook_id},
496
+ params={"status": status, "eventType": event_type, "eventId": event_id,
497
+ "since": since, "until": until, "cursor": cursor, "limit": limit})
498
+
499
+ def get_webhook_delivery(self, webhook_id: str, delivery_id: str) -> dict:
500
+ return self._call("GET /v1/webhooks/{webhook_id}/deliveries/{delivery_id}",
501
+ path={"webhook_id": webhook_id, "delivery_id": delivery_id})
502
+
503
+ def resend_webhook_delivery(self, webhook_id: str, delivery_id: str, *, reason: str = "",
504
+ idempotency_key: str | None = None) -> dict:
505
+ """Queue the same event (same event id, fresh signature) again, as a new delivery."""
506
+ return self._call("POST /v1/webhooks/{webhook_id}/deliveries/{delivery_id}/resend",
507
+ path={"webhook_id": webhook_id, "delivery_id": delivery_id}, reason=reason,
508
+ idempotency_key=idempotency_key)
509
+
510
+ def resend_event(self, event_id: str, *, webhook_id: str | None = None, reason: str = "",
511
+ idempotency_key: str | None = None) -> Any:
512
+ """Resend an event to every endpoint that received it (or only ``webhook_id``)."""
513
+ return self._call("POST /v1/events/{event_id}/resend", path={"event_id": event_id},
514
+ params={"webhookId": webhook_id}, reason=reason, idempotency_key=idempotency_key)
515
+
516
+ # ---- sandbox and connected AI apps
517
+ def sandbox_info(self) -> dict:
518
+ """The sandbox: server name, key prefix, account limit and the magic logins."""
519
+ return self._call("GET /v1/sandbox")
520
+
521
+ def create_sandbox_key(self, name: str = "sandbox", *, reason: str = "",
522
+ idempotency_key: str | None = None) -> dict:
523
+ """An unrestricted ``twsk_`` key for your linked sandbox (``apiKey``, shown once), with full
524
+ rights inside the sandbox. Needs a live key or an unrestricted sandbox key: a key from
525
+ :func:`sandbox_signup` gets :class:`~tickwire.errors.SandboxKeyRestricted`."""
526
+ return self._call("POST /v1/sandbox/keys", json={"name": name}, reason=reason,
527
+ idempotency_key=idempotency_key)
528
+
529
+ def list_connected_apps(self, *, include_ended: bool = False, limit: int | None = None,
530
+ cursor: str | None = None) -> dict:
531
+ """AI apps connected through "Sign in with Tickwire" (OAuth grants), one page:
532
+ ``{apps, has_more, next_cursor}``. ``app_name`` is untrusted text (the app chose it)."""
533
+ return self._call("GET /v1/connected-apps", params={"include_ended": include_ended or None,
534
+ "limit": limit, "cursor": cursor})
535
+
536
+ def disconnect_connected_app(self, grant_id: str, *, reason: str = "",
537
+ idempotency_key: str | None = None) -> dict:
538
+ """Revoke the app's agent key and every token at once."""
539
+ return self._call("DELETE /v1/connected-apps/{grant_id}", path={"grant_id": grant_id}, reason=reason,
540
+ idempotency_key=idempotency_key)
541
+
542
+ # ---- dedicated IPs and billing (read-only)
543
+ def dedicated_ips(self) -> dict:
544
+ """Your dedicated egress IPs and open IP requests."""
545
+ return self._call("GET /v1/dedicated-ips")
546
+
547
+ def move_accounts_to_dedicated_ip(self, account_ids: list[str], *, reason: str,
548
+ idempotency_key: str | None = None) -> dict:
549
+ """Approve moving accounts onto their dedicated IP's host. Each move restarts the terminal."""
550
+ return self._call("POST /v1/dedicated-ips/move-accounts", json={"account_ids": list(account_ids)},
551
+ reason=_require_reason(reason), idempotency_key=idempotency_key)
552
+
553
+ def billing_summary(self) -> dict:
554
+ """Plan, status, paid access, seats and period end. Read-only: the SDK never changes billing.
555
+ ``status`` is ``unknown`` (and ``paid_access`` ``None``) when billing cannot be read."""
556
+ return self._call("GET /v1/subscription")
557
+
558
+ # ---- agent administration (owner credential)
559
+ def create_agent_key(self, name: str, account_ids: list[str], *, read_only: bool = False,
560
+ reason: str = "", idempotency_key: str | None = None) -> dict:
561
+ """A new agent key. The answer's ``key`` (``twag_…``) is shown once: store it now."""
562
+ return self._call("POST /v1/agent-keys", json={"name": name, "account_ids": list(account_ids),
563
+ "read_only": read_only},
564
+ reason=reason, idempotency_key=idempotency_key)
565
+
566
+ def list_agent_keys(self, *, limit: int | None = None, cursor: str | None = None) -> dict:
567
+ """One page of agent keys, oldest first: ``{data, has_more, next_cursor}``
568
+ (see :meth:`pages`)."""
569
+ return self._call("GET /v1/agent-keys", params={"limit": limit, "cursor": cursor})
570
+
571
+ def get_agent_key(self, key_id: str) -> dict:
572
+ return self._call("GET /v1/agent-keys/{key_id}", path={"key_id": key_id})
573
+
574
+ def update_agent_key(self, key_id: str, *, name: str | None = None, account_ids: list[str] | None = None,
575
+ read_only: bool | None = None, reason: str = "",
576
+ idempotency_key: str | None = None) -> dict:
577
+ body = {k: v for k, v in (("name", name), ("account_ids", account_ids), ("read_only", read_only))
578
+ if v is not None}
579
+ return self._call("PATCH /v1/agent-keys/{key_id}", path={"key_id": key_id}, json=body,
580
+ reason=reason, idempotency_key=idempotency_key)
581
+
582
+ def revoke_agent_key(self, key_id: str, *, reason: str = "", idempotency_key: str | None = None) -> None:
583
+ return self._call("DELETE /v1/agent-keys/{key_id}", path={"key_id": key_id}, ok=lambda s, b: None,
584
+ reason=reason, idempotency_key=idempotency_key)
585
+
586
+ def set_agent_key_kill_switch(self, key_id: str, engaged: bool, *, reason: str = "",
587
+ idempotency_key: str | None = None) -> dict:
588
+ return self._call("PUT /v1/agent-keys/{key_id}/kill-switch", path={"key_id": key_id},
589
+ json={"engaged": engaged, "reason": reason}, reason=reason,
590
+ idempotency_key=idempotency_key)
591
+
592
+ def list_kill_switches(self, *, limit: int | None = None, cursor: str | None = None) -> dict:
593
+ """Engaged account kill switches, one page: ``{accounts, has_more, next_cursor}``."""
594
+ return self._call("GET /v1/agent-kill-switches", params={"limit": limit, "cursor": cursor})
595
+
596
+ def set_account_kill_switch(self, account_id: str, engaged: bool, *, reason: str = "",
597
+ idempotency_key: str | None = None) -> dict:
598
+ """Stop (or resume) every AI agent on the account. Direct trades by the owner, including
599
+ :meth:`execute_trade`, are not blocked (so the owner can always flatten)."""
600
+ return self._call("PUT /v1/agent-kill-switches/accounts/{account_id}", path={"account_id": account_id},
601
+ json={"engaged": engaged, "reason": reason}, reason=reason,
602
+ idempotency_key=idempotency_key)
603
+
604
+ def create_pretrade_hook(self, url: str, *, account_id: str | None = None, agent_key_id: str | None = None,
605
+ reason: str = "", idempotency_key: str | None = None, **options: Any) -> dict:
606
+ """Register a pre-trade decision hook (``applies_to``, ``fail_mode``, ``timeout_ms``,
607
+ ``hold_ttl_seconds``, ``enabled`` as keyword options). ``secret`` is shown once."""
608
+ body = {"url": url, **options}
609
+ if account_id is not None:
610
+ body["account_id"] = account_id
611
+ if agent_key_id is not None:
612
+ body["agent_key_id"] = agent_key_id
613
+ return self._call("POST /v1/pretrade-hooks", json=body, reason=reason, idempotency_key=idempotency_key)
614
+
615
+ def list_pretrade_hooks(self, *, limit: int | None = None, cursor: str | None = None) -> dict:
616
+ """One page of pre-trade hooks, oldest first: ``{data, has_more, next_cursor}``."""
617
+ return self._call("GET /v1/pretrade-hooks", params={"limit": limit, "cursor": cursor})
618
+
619
+ def get_pretrade_hook(self, hook_id: str) -> dict:
620
+ return self._call("GET /v1/pretrade-hooks/{hook_id}", path={"hook_id": hook_id})
621
+
622
+ def update_pretrade_hook(self, hook_id: str, *, reason: str = "", idempotency_key: str | None = None,
623
+ **fields: Any) -> dict:
624
+ return self._call("PATCH /v1/pretrade-hooks/{hook_id}", path={"hook_id": hook_id}, json=fields,
625
+ reason=reason, idempotency_key=idempotency_key)
626
+
627
+ def delete_pretrade_hook(self, hook_id: str, *, reason: str = "", idempotency_key: str | None = None) -> None:
628
+ return self._call("DELETE /v1/pretrade-hooks/{hook_id}", path={"hook_id": hook_id},
629
+ ok=lambda s, b: None, reason=reason, idempotency_key=idempotency_key)
630
+
631
+ def rotate_pretrade_hook_secret(self, hook_id: str, *, reason: str = "",
632
+ idempotency_key: str | None = None) -> dict:
633
+ """A new hook secret, shown once; the old one stops working at once."""
634
+ return self._call("POST /v1/pretrade-hooks/{hook_id}/rotate-secret", path={"hook_id": hook_id},
635
+ reason=reason, idempotency_key=idempotency_key)
636
+
637
+ def list_holds(self, *, status: str | None = None, account_id: str | None = None,
638
+ limit: int | None = None, cursor: str | None = None) -> dict:
639
+ """One page of holds, newest first: ``{data, has_more, next_cursor}``. A cursor is
640
+ bound to the filters it was issued with."""
641
+ return self._call("GET /v1/pretrade-holds",
642
+ params={"status": status, "account_id": account_id, "limit": limit,
643
+ "cursor": cursor})
644
+
645
+ def get_hold(self, hold_id: str) -> dict:
646
+ return self._call("GET /v1/pretrade-holds/{hold_id}", path={"hold_id": hold_id})
647
+
648
+ def cancel_hold(self, hold_id: str, *, message: str | None = None, reason: str = "",
649
+ idempotency_key: str | None = None) -> dict:
650
+ """Reject a pending hold (the owner can never approve one; that belongs to the hook)."""
651
+ return self._call("POST /v1/pretrade-holds/{hold_id}/cancel", path={"hold_id": hold_id},
652
+ json={} if message is None else {"message": message}, reason=reason,
653
+ idempotency_key=idempotency_key)
654
+
655
+ def agent_audit(self, *, agent_key_id: str | None = None, account_id: str | None = None,
656
+ before: str | None = None, limit: int | None = None, cursor: str | None = None) -> dict:
657
+ """One page of the agent audit log, newest first: ``{entries, has_more, next_cursor}``."""
658
+ return self._call("GET /v1/agent-audit", params={"agent_key_id": agent_key_id, "account_id": account_id,
659
+ "before": before, "limit": limit, "cursor": cursor})
660
+
661
+ # ---- guarded execution
662
+ def execute_trade(self, account_id: str, trade: models.Trade, *, reason: str,
663
+ idempotency_key: str | None = None) -> TradeResult:
664
+ """``POST /v1/execution/accounts/{id}/trade``: the order goes through the account's
665
+ pre-trade hooks (``applies_to: all``). Always returns a :class:`TradeResult`; check
666
+ ``.outcome`` (``unknown`` means it MAY have executed: never retry with a new key)."""
667
+ return self._trade_call("POST /v1/execution/accounts/{account_id}/trade", path={"account_id": account_id},
668
+ json=dict(trade), reason=_require_reason(reason),
669
+ idempotency_key=idempotency_key)
670
+
671
+
672
+ class Account:
673
+ """One trading account on the native API (MT4 or MT5; the API is identical).
674
+
675
+ Works with both clients: on :class:`AsyncTickwire` every method returns an
676
+ awaitable.
677
+ """
678
+
679
+ def __init__(self, client: Any, account_id: str) -> None:
680
+ self.client, self.id = client, account_id
681
+
682
+ def _get(self, key: str, *, ok=None, err=None, params: dict | None = None, **path) -> Any:
683
+ return self.client._call(key, path={"account_id": self.id, **path}, params=params, ok=ok, err=err)
684
+
685
+ # ---- Tickwire extras
686
+ def health(self) -> models.Health:
687
+ """Truthful health (``healthy|stale|disconnected|down`` plus reasons). A 503 is data, not an error."""
688
+ def down(e: Exception):
689
+ if isinstance(e, TickwireError) and e.status == 503 and isinstance(e.body, dict) and "status" in e.body:
690
+ return e.body
691
+ raise e
692
+ return self._get("GET /users/current/accounts/{account_id}/health", err=down)
693
+
694
+ def capabilities(self) -> dict:
695
+ return self._get("GET /users/current/accounts/{account_id}/capabilities")
696
+
697
+ def audit(self, limit: int = 100) -> list[models.AuditEntry]:
698
+ return self.client._call("GET /users/current/accounts/{account_id}/audit",
699
+ path={"account_id": self.id}, params={"limit": limit}, ok=_entries("entries"))
700
+
701
+ # ---- MetaApi-compatible reads
702
+ def account_information(self) -> models.AccountInformation:
703
+ return self._get("GET /users/current/accounts/{account_id}/account-information")
704
+
705
+ def positions(self) -> list[models.Position]:
706
+ return self._get("GET /users/current/accounts/{account_id}/positions")
707
+
708
+ def position(self, position_id: str | int) -> models.Position:
709
+ return self._get("GET /users/current/accounts/{account_id}/positions/{position_id}",
710
+ position_id=position_id)
711
+
712
+ def orders(self) -> list[models.Order]:
713
+ return self._get("GET /users/current/accounts/{account_id}/orders")
714
+
715
+ def order(self, order_id: str | int) -> models.Order:
716
+ return self._get("GET /users/current/accounts/{account_id}/orders/{order_id}", order_id=order_id)
717
+
718
+ def deals(self, start: str, end: str, *, offset: int = 0, limit: int = 1000) -> list[models.Deal]:
719
+ """Deals in ``[start, end]`` (ISO-8601 UTC)."""
720
+ return self._get("GET /users/current/accounts/{account_id}/history-deals/time/{start_time}/{end_time}",
721
+ start_time=start, end_time=end, params={"offset": offset, "limit": limit})
722
+
723
+ def deals_by_position(self, position_id: str | int) -> list[models.Deal]:
724
+ return self._get("GET /users/current/accounts/{account_id}/history-deals/position/{position_id}",
725
+ position_id=position_id)
726
+
727
+ def history_orders(self, start: str, end: str, *, offset: int = 0, limit: int = 1000) -> list[models.Order]:
728
+ return self._get("GET /users/current/accounts/{account_id}/history-orders/time/{start_time}/{end_time}",
729
+ start_time=start, end_time=end, params={"offset": offset, "limit": limit})
730
+
731
+ def symbols(self) -> list[str]:
732
+ return self._get("GET /users/current/accounts/{account_id}/symbols")
733
+
734
+ def price(self, symbol: str) -> models.SymbolPrice:
735
+ return self._get("GET /users/current/accounts/{account_id}/symbols/{symbol}/current-price", symbol=symbol)
736
+
737
+ def tick(self, symbol: str) -> dict:
738
+ return self._get("GET /users/current/accounts/{account_id}/symbols/{symbol}/current-tick", symbol=symbol)
739
+
740
+ def specification(self, symbol: str) -> dict:
741
+ return self._get("GET /users/current/accounts/{account_id}/symbols/{symbol}/specification", symbol=symbol)
742
+
743
+ def server_time(self) -> dict:
744
+ """The broker's server clock (broker time is never assumed to be UTC)."""
745
+ return self._get("GET /users/current/accounts/{account_id}/server-time")
746
+
747
+ def snapshot(self) -> dict:
748
+ """Account information, positions, orders, health and server time in one read:
749
+ ``{as_of, complete, terminal_connected, account_information, positions, orders,
750
+ health, server_time}``; each section has ``status`` (``ok|stale|unavailable``),
751
+ ``read_at``, ``age_ms`` and ``data``. The broker's UTC offset is explicit
752
+ (``server_time.data.brokerUtcOffsetMinutes``, ``None`` when unknown)."""
753
+ return self._get("GET /users/current/accounts/{account_id}/snapshot")
754
+
755
+ # ---- trading (idempotent)
756
+ def trade(self, trade: models.Trade, *, idempotency_key: str | None = None,
757
+ reason: str = "", actor: str | None = None) -> models.TradeResponse:
758
+ """``POST /trade``. MetaApi semantics: HTTP 200 even when MT rejects; inspect ``numericCode``.
759
+
760
+ The same ``idempotency_key`` (auto-generated if omitted, and reused on
761
+ retries) guarantees one execution. A lost reply raises
762
+ :class:`~tickwire.errors.OutcomeUnknown` (with the key) and is not retried.
763
+ For the account's pre-trade hooks, use :meth:`Tickwire.execute_trade`.
764
+ """
765
+ return self.client._call("POST /users/current/accounts/{account_id}/trade", path={"account_id": self.id},
766
+ json=dict(trade), idempotency_key=idempotency_key, reason=reason, actor=actor)
767
+
768
+ def check_trade(self, trade: models.Trade) -> dict:
769
+ """``POST /trade/check``: validate an order without sending it."""
770
+ return self.client._call("POST /users/current/accounts/{account_id}/trade/check",
771
+ path={"account_id": self.id}, json=dict(trade))
772
+
773
+ def market_order(self, symbol: str, volume: float, side: str = "buy", **extra) -> models.TradeResponse:
774
+ action = "ORDER_TYPE_BUY" if side.lower() == "buy" else "ORDER_TYPE_SELL"
775
+ kw = {k: extra.pop(k) for k in ("idempotency_key", "reason", "actor") if k in extra}
776
+ return self.trade({"actionType": action, "symbol": symbol, "volume": volume, **extra}, **kw)
777
+
778
+ def close_position(self, position_id: str | int, **kw) -> models.TradeResponse:
779
+ return self.trade({"actionType": "POSITION_CLOSE_ID", "positionId": str(position_id)}, **kw)
780
+
781
+ def stream(self, **kw):
782
+ """Stream protocol v2 (async only): ``async with acc.stream() as s: …``."""
783
+ from .stream import AccountStream
784
+
785
+ return AccountStream(self.client.opts.base_url, self.client.opts.token, self.id, **kw)
786
+
787
+
788
+ AsyncAccount = Account
789
+
790
+
791
+ class AsyncTickwire(_AsyncTransport, _OwnerSurface, _Base):
792
+ """Async client. ``async with AsyncTickwire(base_url, token) as tw: …``.
793
+
794
+ ``AsyncTickwire(sandbox=True)`` targets the sandbox (``TICKWIRE_SANDBOX_URL``);
795
+ with no URL it reads ``TICKWIRE_API_URL``; with no token, ``TICKWIRE_API_KEY``.
796
+ """
797
+
798
+ def __init__(self, base_url: str | None = None, token: str | None = None, *, sandbox: bool = False,
799
+ sandbox_url: str | None = None, transport: httpx.AsyncBaseTransport | None = None,
800
+ **options: Any) -> None:
801
+ _Base.__init__(self, base_url, token, sandbox=sandbox, sandbox_url=sandbox_url, **options)
802
+ self._open(transport)
803
+
804
+
805
+ class Tickwire(_SyncTransport, _OwnerSurface, _Base):
806
+ """Blocking client with the same surface as :class:`AsyncTickwire` (no streaming)."""
807
+
808
+ def __init__(self, base_url: str | None = None, token: str | None = None, *, sandbox: bool = False,
809
+ sandbox_url: str | None = None, transport: httpx.BaseTransport | None = None,
810
+ **options: Any) -> None:
811
+ _Base.__init__(self, base_url, token, sandbox=sandbox, sandbox_url=sandbox_url, **options)
812
+ self._open(transport)
813
+
814
+
815
+ def sandbox_signup(base_url: str | None = None, *, platform: str = "mt5", sandbox_url: str | None = None,
816
+ transport: httpx.BaseTransport | None = None, timeout_s: float = 30.0) -> dict:
817
+ """Create a sandbox with no sign-in: a ``twsk_`` key (``apiKey``, shown once) and one
818
+ connected simulated account (``{sandbox, restricted: true, tenantId, apiKey, account}``).
819
+ Anonymous and rate limited per IP (and globally): 429 raises ``RateLimited``.
820
+
821
+ The key is **restricted**: it may manage its sandbox accounts, trade, stream and read.
822
+ Anything else that changes state (webhooks, pre-trade hooks, agent keys, more keys or
823
+ tokens) raises :class:`~tickwire.errors.SandboxKeyRestricted` (403
824
+ ``sandbox_key_restricted``). For those, sign in and call :meth:`Tickwire.create_sandbox_key`
825
+ with your live key.
826
+
827
+ The URL is ``base_url``, else ``sandbox_url`` / ``TICKWIRE_SANDBOX_URL``. Never retried: a
828
+ lost reply raises :class:`~tickwire.errors.OutcomeUnknown` (a retry could make a second sandbox).
829
+ """
830
+ url = base_url.rstrip("/") if base_url else resolve_base_url(sandbox=True, sandbox_url=sandbox_url)
831
+ op = OPERATIONS["POST /v1/sandbox/signup"]
832
+ headers = {"User-Agent": USER_AGENT, "Accept": "application/json", "Idempotency-Key": new_idempotency_key()}
833
+ with httpx.Client(base_url=url, timeout=timeout_s, transport=transport) as http:
834
+ try:
835
+ resp = http.post(op["path"], json={"platform": platform}, headers=headers)
836
+ except NOT_SENT_ERRORS as e:
837
+ raise TransportError(f"{type(e).__name__}: {e}") from None
838
+ except httpx.TransportError as e:
839
+ raise OutcomeUnknown(f"{type(e).__name__} after the signup was sent: a sandbox may have "
840
+ "been created") from None
841
+ body = _decode(resp)
842
+ if resp.status_code >= 400:
843
+ raise from_response(resp.status_code, body, retry_after=_retry_after(resp))
844
+ return body