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/webhooks.py ADDED
@@ -0,0 +1,133 @@
1
+ """Verify Tickwire webhook deliveries, including during a secret rotation.
2
+
3
+ Every delivery carries two header sets (``docs/public/webhooks.md``):
4
+
5
+ * Tickwire: ``X-Tickwire-Timestamp`` (unix seconds),
6
+ ``X-Tickwire-Signature: sha256=<hex>`` (current secret) and
7
+ ``X-Tickwire-Signatures: sha256=<hex>[,sha256=<hex>]`` (every active secret),
8
+ each ``HMAC_SHA256(secret, "{timestamp}.{raw body}")``.
9
+ * `Standard Webhooks <https://www.standardwebhooks.com/>`_: ``webhook-id``,
10
+ ``webhook-timestamp`` and ``webhook-signature: v1,<base64> [v1,<base64>]``,
11
+ each ``HMAC_SHA256(key, "{id}.{timestamp}.{raw body}")`` where ``key`` is the
12
+ base64-decoded part of a ``whsec_…`` secret (or the secret's bytes otherwise).
13
+
14
+ :func:`verify` accepts one secret or several (pass the old and the new one while
15
+ you rotate): a delivery passes when any listed signature matches any secret.
16
+ Stale timestamps are rejected to stop replays.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import binascii
22
+ import hashlib
23
+ import hmac
24
+ import json
25
+ import re
26
+ import time
27
+ from collections.abc import Iterable, Mapping
28
+ from typing import Any
29
+
30
+ SIGNATURE_HEADER = "X-Tickwire-Signature"
31
+ SIGNATURES_HEADER = "X-Tickwire-Signatures"
32
+ TIMESTAMP_HEADER = "X-Tickwire-Timestamp"
33
+ EVENT_HEADER = "X-Tickwire-Event"
34
+ EVENT_ID_HEADER = "X-Tickwire-Event-Id"
35
+ STD_ID_HEADER = "webhook-id"
36
+ STD_TIMESTAMP_HEADER = "webhook-timestamp"
37
+ STD_SIGNATURE_HEADER = "webhook-signature"
38
+
39
+ Secrets = str | Iterable[str]
40
+
41
+
42
+ class WebhookVerificationError(Exception):
43
+ pass
44
+
45
+
46
+ def sign(secret: str, timestamp: str, body: bytes) -> str:
47
+ """The Tickwire signature (hex, without the ``sha256=`` prefix)."""
48
+ return hmac.new(secret.encode(), f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
49
+
50
+
51
+ def standard_key(secret: str) -> bytes:
52
+ """The HMAC key for the Standard Webhooks signature (as the control plane derives it)."""
53
+ if secret.startswith("whsec_"):
54
+ try:
55
+ key = base64.b64decode(secret[6:] + "==")
56
+ if key:
57
+ return key
58
+ except (binascii.Error, ValueError):
59
+ pass
60
+ return secret.encode()
61
+
62
+
63
+ def sign_standard(secret: str, msg_id: str, timestamp: str, body: bytes) -> str:
64
+ """``v1,<base64>``: the Standard Webhooks signature."""
65
+ mac = hmac.new(standard_key(secret), f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256)
66
+ return "v1," + base64.b64encode(mac.digest()).decode()
67
+
68
+
69
+ def _secrets(secrets: Secrets) -> list[str]:
70
+ out = [secrets] if isinstance(secrets, str) else [s for s in secrets]
71
+ out = [s for s in out if s]
72
+ if not out:
73
+ raise WebhookVerificationError("no secret to verify with")
74
+ return out
75
+
76
+
77
+ def _check_time(ts: str | None, tolerance_s: float, now: float | None) -> None:
78
+ if not ts:
79
+ raise WebhookVerificationError("missing timestamp header")
80
+ try:
81
+ ts_f = float(ts)
82
+ except ValueError:
83
+ raise WebhookVerificationError("bad timestamp") from None
84
+ if abs((now if now is not None else time.time()) - ts_f) > tolerance_s:
85
+ raise WebhookVerificationError("timestamp outside tolerance (possible replay)")
86
+
87
+
88
+ def _json(body: bytes) -> dict[str, Any]:
89
+ try:
90
+ return json.loads(body)
91
+ except ValueError:
92
+ raise WebhookVerificationError("body is not JSON") from None
93
+
94
+
95
+ def verify_standard(secrets: Secrets, headers: Mapping[str, str], body: bytes, *, tolerance_s: float = 300,
96
+ now: float | None = None) -> dict[str, Any]:
97
+ """Verify the Standard Webhooks headers; return the decoded event or raise."""
98
+ keys = _secrets(secrets)
99
+ lower = {k.lower(): v for k, v in headers.items()}
100
+ msg_id, ts, sig = (lower.get(STD_ID_HEADER), lower.get(STD_TIMESTAMP_HEADER),
101
+ lower.get(STD_SIGNATURE_HEADER))
102
+ if not msg_id or not sig:
103
+ raise WebhookVerificationError("missing webhook-id or webhook-signature header")
104
+ _check_time(ts, tolerance_s, now)
105
+ given = [p.split(",", 1)[1] for p in sig.split() if p.startswith("v1,")]
106
+ expected = [sign_standard(k, msg_id, ts, body).split(",", 1)[1] for k in keys]
107
+ if not any(hmac.compare_digest(e.encode(), g.encode()) for e in expected for g in given):
108
+ raise WebhookVerificationError("signature mismatch")
109
+ return _json(body)
110
+
111
+
112
+ def verify(secrets: Secrets, headers: Mapping[str, str], body: bytes, *, tolerance_s: float = 300,
113
+ now: float | None = None) -> dict[str, Any]:
114
+ """Return the decoded event, or raise :class:`WebhookVerificationError`.
115
+
116
+ ``secrets``: your secret, or several (old and new during a rotation). Reads
117
+ ``X-Tickwire-Signatures`` and ``X-Tickwire-Signature``; a delivery with only
118
+ Standard Webhooks headers is checked with :func:`verify_standard`.
119
+ """
120
+ keys = _secrets(secrets)
121
+ lower = {k.lower(): v for k, v in headers.items()}
122
+ listed = ",".join(v for v in (lower.get(SIGNATURES_HEADER.lower()), lower.get(SIGNATURE_HEADER.lower())) if v)
123
+ if not listed:
124
+ if lower.get(STD_SIGNATURE_HEADER):
125
+ return verify_standard(keys, headers, body, tolerance_s=tolerance_s, now=now)
126
+ raise WebhookVerificationError("missing signature header")
127
+ ts = lower.get(TIMESTAMP_HEADER.lower())
128
+ _check_time(ts, tolerance_s, now)
129
+ given = [p[7:] if p.startswith("sha256=") else p for p in re.split(r"[,\s]+", listed) if p]
130
+ expected = [sign(k, ts, body) for k in keys]
131
+ if not any(hmac.compare_digest(e.encode(), g.encode()) for e in expected for g in given):
132
+ raise WebhookVerificationError("signature mismatch")
133
+ return _json(body)
@@ -0,0 +1,191 @@
1
+ Metadata-Version: 2.4
2
+ Name: tickwire
3
+ Version: 0.1.0
4
+ Summary: Tickwire SDK: typed REST and streaming clients for the Tickwire MT4/MT5 cloud API (health, audit, idempotent trading, agent keys, pre-trade hooks, webhooks).
5
+ Author-email: Tickwire <hello@tickwire.io>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://tickwire.io/
8
+ Project-URL: Documentation, https://tickwire.io/docs/sdk-python/
9
+ Project-URL: Changelog, https://tickwire.io/docs/changelog/
10
+ Keywords: metatrader,mt4,mt5,trading,api,sdk,ai-agents
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Office/Business :: Financial :: Investment
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: httpx<1,>=0.27
25
+ Requires-Dist: websockets<18,>=12
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.0; extra == "dev"
28
+ Dynamic: license-file
29
+
30
+ # tickwire (Python SDK)
31
+
32
+ Typed clients for the Tickwire MT4/MT5 API: one API for both platforms,
33
+ truthful health, idempotent trading, an audit trail, agent keys with pre-trade
34
+ hooks, and signed webhooks. Sync and async.
35
+
36
+ **Not published yet.** `pip install tickwire` won't find it. Install from source, from the
37
+ repository root:
38
+
39
+ ```
40
+ pip install ./sdk/python
41
+ ```
42
+
43
+ Once it is published:
44
+
45
+ ```
46
+ pip install tickwire
47
+ ```
48
+
49
+ Python 3.11 or newer. MIT licensed. Docs: [tickwire.io/docs/sdk-python](https://tickwire.io/docs/sdk-python/).
50
+
51
+ ## Quick start
52
+
53
+ A free sandbox (no sign-in, no card) against the public API, then a first trade:
54
+
55
+ ```python
56
+ from tickwire import Tickwire, sandbox_signup, trade_succeeded
57
+
58
+ API = "https://api.tickwire.io"
59
+ sb = sandbox_signup(API) # a twsk_ key (shown once: keep it) and one simulated MT5 account
60
+ with Tickwire(API, sb["apiKey"], actor="quickstart") as tw:
61
+ acc = tw.account(sb["account"]["id"]) # MT4 and MT5 look the same
62
+ print(acc.health()["status"]) # healthy | stale | disconnected | down
63
+ print(acc.price("EURUSD"))
64
+ r = acc.market_order("EURUSD", 0.01, reason="quickstart") # Idempotency-Key generated for you
65
+ print(trade_succeeded(r), r["numericCode"])
66
+ ```
67
+
68
+ `sandbox_signup` is anonymous and rate limited (5 sandboxes an hour per
69
+ address), so call it once and reuse the key. With your own API key, skip it:
70
+ `Tickwire("https://api.tickwire.io", "YOUR_API_KEY")`, or set
71
+ `TICKWIRE_API_URL` and `TICKWIRE_API_KEY` and call `Tickwire()`. Then
72
+ `tw.list_accounts()` lists your accounts.
73
+
74
+ `sandbox=True` reads the sandbox URL from `sandbox_url=` or
75
+ `TICKWIRE_SANDBOX_URL` (it never guesses a host) and raises `ConfigError` if
76
+ neither is set.
77
+
78
+ ## 60 seconds: an AI agent with its own key
79
+
80
+ The account owner creates a scoped agent key; the agent can then trade only
81
+ through the guarded path (kill switches, the owner's pre-trade hook, audit).
82
+ This needs your own API key: the restricted key from `sandbox_signup` cannot
83
+ create agent keys.
84
+
85
+ ```python
86
+ from tickwire import AgentClient, Tickwire
87
+
88
+ API = "https://api.tickwire.io"
89
+ with Tickwire(API, "YOUR_API_KEY") as owner:
90
+ created = owner.create_agent_key("my-agent", [account_id], reason="new agent")
91
+ agent_key = created["key"] # twag_…, shown once: store it now
92
+
93
+ with AgentClient(API, agent_key) as agent:
94
+ r = agent.trade(account_id, {"actionType": "ORDER_TYPE_BUY", "symbol": "EURUSD", "volume": 0.01},
95
+ reason="breakout above the Asian range")
96
+ if r.outcome == "applied":
97
+ print("filled", r.evidence)
98
+ elif r.outcome == "held":
99
+ print("waiting for approval", r.hold_id)
100
+ elif r.outcome == "rejected":
101
+ print("not executed:", r.error, "sent:", r.sent)
102
+ else: # unknown: it MAY have executed
103
+ print(agent.trade_status(r.idempotency_key)) # never retry with a new key
104
+ ```
105
+
106
+ Async: `AsyncTickwire` and `AsyncAgentClient` have the same methods
107
+ (`async with …`, `await …`), plus resumable streams:
108
+
109
+ ```python
110
+ async with AsyncTickwire(API, "YOUR_API_KEY") as tw:
111
+ async with tw.account(account_id).stream() as s: # stream protocol v2
112
+ state = await s.wait_synchronized()
113
+ s.on("positionUpdated", lambda frame, st: print(frame["position"]))
114
+ ```
115
+
116
+ ## What it covers
117
+
118
+ | Area | Methods |
119
+ |---|---|
120
+ | Native account (MetaApi-compatible) | `account(id)`: `health`, `capabilities`, `audit`, `snapshot`, `account_information`, `positions`, `position`, `orders`, `order`, `deals`, `deals_by_position`, `history_orders`, `symbols`, `price`, `tick`, `specification`, `server_time`, `trade`, `check_trade`, `market_order`, `close_position`, `stream` |
121
+ | Control plane | `list_accounts`, `get_account`, `list_webhooks`, `get_webhook`, `create_webhook`, `delete_webhook` |
122
+ | Webhooks v2 | `webhook_event_types`, `webhook_settings`, `update_webhook`, `enable_webhook`, `disable_webhook`, `rotate_webhook_secret`, `reveal_webhook_secret`, `list_webhook_deliveries`, `get_webhook_delivery`, `resend_webhook_delivery`, `resend_event`; verify with `verify_webhook(secret_or_secrets, headers, body)` (all rotation secrets) or `verify_standard_webhook` |
123
+ | Agent administration | `create_agent_key`, `list_agent_keys`, `get_agent_key`, `update_agent_key`, `revoke_agent_key`, `set_agent_key_kill_switch`, `list_kill_switches`, `set_account_kill_switch`, `create_pretrade_hook`, `list_pretrade_hooks`, `get_pretrade_hook`, `update_pretrade_hook`, `delete_pretrade_hook`, `rotate_pretrade_hook_secret`, `list_holds`, `get_hold`, `cancel_hold`, `agent_audit` |
124
+ | Guarded execution | `execute_trade` (returns a `TradeResult`) |
125
+ | Sandbox, connected AI apps | `sandbox_signup()` (module function, no key needed), `sandbox_info`, `create_sandbox_key`, `list_connected_apps`, `disconnect_connected_app` |
126
+ | Dedicated IPs, billing | `dedicated_ips`, `move_accounts_to_dedicated_ip`, `billing_summary` (read-only) |
127
+ | Agent API (`AgentClient`) | `me`, `accounts`, `snapshot`, `health`, `account_information`, `positions`, `orders`, `price`, `specification`, `deals`, `trade`, `trade_status`, `audit` |
128
+
129
+ ### Pagination
130
+
131
+ Native `/v1` lists (agent keys, pre-trade hooks, holds, kill switches, the
132
+ agent audit log, connected apps, `AgentClient.accounts`) return one page:
133
+ `{"data" | "entries" | "apps" | "accounts": [...], "has_more", "next_cursor"}`.
134
+ Pass `limit=` (1 to 500, default 100) and `cursor=`, or let `pages` follow the
135
+ cursor for you:
136
+
137
+ ```python
138
+ for page in tw.pages(tw.list_holds, status="pending", limit=100):
139
+ for hold in page["data"]:
140
+ ...
141
+ # async: async for page in tw.pages(tw.list_agent_keys): ...
142
+ ```
143
+
144
+ ### Snapshot
145
+
146
+ `tw.account(id).snapshot()` (or `AgentClient.snapshot(account_id)`) returns
147
+ account information, positions, orders, health and server time in one read,
148
+ each section with `status` (`ok`, `stale`, `unavailable`), `read_at` and
149
+ `age_ms`. The broker's UTC offset is explicit
150
+ (`server_time["data"]["brokerUtcOffsetMinutes"]`, `None` when unknown).
151
+
152
+ Every call maps to an operation in `tickwire/_operations.py`, generated from
153
+ the public OpenAPI spec ([tickwire.io/openapi.json](https://tickwire.io/openapi.json)).
154
+
155
+ ## Safety you get by default
156
+
157
+ - **Idempotency.** Every mutation sends `Idempotency-Key` (yours, or a
158
+ generated `tw_…`), `X-Actor` and `X-Reason`. Pass `idempotency_key=` to make
159
+ a repeat of the same decision safe across restarts.
160
+ - **Retries only when safe.** Reads retry on transport errors and
161
+ 408/429/502/503/504 with full-jitter backoff (`Retry-After` honoured up to
162
+ the cap), within a per-client `RetryBudget` so an outage cannot become a
163
+ retry storm. A mutation retries only when the server confirms it did not
164
+ run it, always with the same key: connection refused; `409
165
+ idempotency_in_flight` (the first attempt is still running, so the SDK
166
+ waits `Retry-After` and then gets that attempt's stored result); or a
167
+ 429/5xx whose body says explicitly `sent: false` (error codes alone
168
+ never count).
169
+ - **`unknown` is never retried.** A lost reply to a mutation (read timeout,
170
+ reset) or any other 408/5xx raises `OutcomeUnknown` carrying the
171
+ idempotency key; the
172
+ guarded trades (`execute_trade`, `AgentClient.trade`) return
173
+ `TradeResult(outcome="unknown", sent="unknown")` instead.
174
+ - **Streams resume.** `AccountStream` re-subscribes with the last `seq`; a gap
175
+ forces a full resync, so the mirror is never silently wrong.
176
+ - **Typed errors** (`NotFound`, `Conflict`, `NotSupportedOnMt4`,
177
+ `RateLimited`, `ConfigError`, …) keep the server envelope in `.body`.
178
+ `health()` returns the body of a 503: "down" is an answer, not an exception.
179
+ - **Webhooks:** `verify_webhook(secret, headers, body)` checks the HMAC-SHA256
180
+ signature and rejects replays outside a 5-minute window.
181
+ - **Clean close.** `close()` / `aclose()` release every connection and are
182
+ idempotent. Credentials never appear in `repr()`.
183
+
184
+ A bare control plane (no gateway) serves the FxSocket routes at the root:
185
+ pass `control_prefix=""`.
186
+
187
+ ## Examples
188
+
189
+ A prop-firm risk guard (flatten on daily drawdown), a trade copier, a journal
190
+ sync and a trading bot: [tickwire.io/docs/guides/examples](https://tickwire.io/docs/guides/examples/).
191
+ Demo accounts only.
@@ -0,0 +1,18 @@
1
+ tickwire/__init__.py,sha256=WZAZIytC-_ZvowZdLDiPEvn6ypZNjHmkZ0fe_8Rt-tA,1875
2
+ tickwire/_operations.py,sha256=lv-mavBEELBQNwkySgh6dqpeElK_XrXZ9MmY2IqixKU,21337
3
+ tickwire/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
4
+ tickwire/agent.py,sha256=1mwwWwa0_UBMouHgGWq5P0hysBtthrsAE-VvzaoJgbQ,7558
5
+ tickwire/backoff.py,sha256=-lQeJN14LfM0wVVq3s3-cj8VfdXrXj0pz39ISDMzxm4,2100
6
+ tickwire/client.py,sha256=kj9UO6LmfAuOHwFZTVSM0n4nCQG5ggXPxjFWVaS5a34,44194
7
+ tickwire/config.py,sha256=3zyqUbfm2zoklzXiZ3wulFTgpUat1juvwy5CPypYlVU,2193
8
+ tickwire/errors.py,sha256=ZMv6NUJtpcjqjOIBgOWcoXgPSQ7mfOyHfAwGpans7JI,3878
9
+ tickwire/models.py,sha256=zzeg4aYO1Msbz0Ffx77XZpVZRlevlR8p-BkgJCH8MnU,3683
10
+ tickwire/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ tickwire/results.py,sha256=ChRFIMVhryKLXwOSm0OXffkofGg3ptbrr3CTBnTHjbM,3334
12
+ tickwire/stream.py,sha256=i0aW3K6YnwzUiV7wTepoT8131iiv7yU63LxrIcjL3Mc,11829
13
+ tickwire/webhooks.py,sha256=UQOArN7M_k7Cmdnlm6-6TVwpDtJNdx-ssl95W_mLXX8,5587
14
+ tickwire-0.1.0.dist-info/licenses/LICENSE,sha256=ExGtsuI2oFkv3x2tdhpsThL23NXsfHG0kE0oJK8uew0,1065
15
+ tickwire-0.1.0.dist-info/METADATA,sha256=VWxzo1nXRCSnCMKPJ9f5nBy2HNE-qSeQMk80s86y0iQ,9496
16
+ tickwire-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
17
+ tickwire-0.1.0.dist-info/top_level.txt,sha256=zGA52BuX3soydchUVC8Md6mkpzv8th5htjXPHCq3Z5Y,9
18
+ tickwire-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tickwire
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ tickwire