tickwire 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -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,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,162 @@
1
+ # tickwire (Python SDK)
2
+
3
+ Typed clients for the Tickwire MT4/MT5 API: one API for both platforms,
4
+ truthful health, idempotent trading, an audit trail, agent keys with pre-trade
5
+ hooks, and signed webhooks. Sync and async.
6
+
7
+ **Not published yet.** `pip install tickwire` won't find it. Install from source, from the
8
+ repository root:
9
+
10
+ ```
11
+ pip install ./sdk/python
12
+ ```
13
+
14
+ Once it is published:
15
+
16
+ ```
17
+ pip install tickwire
18
+ ```
19
+
20
+ Python 3.11 or newer. MIT licensed. Docs: [tickwire.io/docs/sdk-python](https://tickwire.io/docs/sdk-python/).
21
+
22
+ ## Quick start
23
+
24
+ A free sandbox (no sign-in, no card) against the public API, then a first trade:
25
+
26
+ ```python
27
+ from tickwire import Tickwire, sandbox_signup, trade_succeeded
28
+
29
+ API = "https://api.tickwire.io"
30
+ sb = sandbox_signup(API) # a twsk_ key (shown once: keep it) and one simulated MT5 account
31
+ with Tickwire(API, sb["apiKey"], actor="quickstart") as tw:
32
+ acc = tw.account(sb["account"]["id"]) # MT4 and MT5 look the same
33
+ print(acc.health()["status"]) # healthy | stale | disconnected | down
34
+ print(acc.price("EURUSD"))
35
+ r = acc.market_order("EURUSD", 0.01, reason="quickstart") # Idempotency-Key generated for you
36
+ print(trade_succeeded(r), r["numericCode"])
37
+ ```
38
+
39
+ `sandbox_signup` is anonymous and rate limited (5 sandboxes an hour per
40
+ address), so call it once and reuse the key. With your own API key, skip it:
41
+ `Tickwire("https://api.tickwire.io", "YOUR_API_KEY")`, or set
42
+ `TICKWIRE_API_URL` and `TICKWIRE_API_KEY` and call `Tickwire()`. Then
43
+ `tw.list_accounts()` lists your accounts.
44
+
45
+ `sandbox=True` reads the sandbox URL from `sandbox_url=` or
46
+ `TICKWIRE_SANDBOX_URL` (it never guesses a host) and raises `ConfigError` if
47
+ neither is set.
48
+
49
+ ## 60 seconds: an AI agent with its own key
50
+
51
+ The account owner creates a scoped agent key; the agent can then trade only
52
+ through the guarded path (kill switches, the owner's pre-trade hook, audit).
53
+ This needs your own API key: the restricted key from `sandbox_signup` cannot
54
+ create agent keys.
55
+
56
+ ```python
57
+ from tickwire import AgentClient, Tickwire
58
+
59
+ API = "https://api.tickwire.io"
60
+ with Tickwire(API, "YOUR_API_KEY") as owner:
61
+ created = owner.create_agent_key("my-agent", [account_id], reason="new agent")
62
+ agent_key = created["key"] # twag_…, shown once: store it now
63
+
64
+ with AgentClient(API, agent_key) as agent:
65
+ r = agent.trade(account_id, {"actionType": "ORDER_TYPE_BUY", "symbol": "EURUSD", "volume": 0.01},
66
+ reason="breakout above the Asian range")
67
+ if r.outcome == "applied":
68
+ print("filled", r.evidence)
69
+ elif r.outcome == "held":
70
+ print("waiting for approval", r.hold_id)
71
+ elif r.outcome == "rejected":
72
+ print("not executed:", r.error, "sent:", r.sent)
73
+ else: # unknown: it MAY have executed
74
+ print(agent.trade_status(r.idempotency_key)) # never retry with a new key
75
+ ```
76
+
77
+ Async: `AsyncTickwire` and `AsyncAgentClient` have the same methods
78
+ (`async with …`, `await …`), plus resumable streams:
79
+
80
+ ```python
81
+ async with AsyncTickwire(API, "YOUR_API_KEY") as tw:
82
+ async with tw.account(account_id).stream() as s: # stream protocol v2
83
+ state = await s.wait_synchronized()
84
+ s.on("positionUpdated", lambda frame, st: print(frame["position"]))
85
+ ```
86
+
87
+ ## What it covers
88
+
89
+ | Area | Methods |
90
+ |---|---|
91
+ | 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` |
92
+ | Control plane | `list_accounts`, `get_account`, `list_webhooks`, `get_webhook`, `create_webhook`, `delete_webhook` |
93
+ | 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` |
94
+ | 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` |
95
+ | Guarded execution | `execute_trade` (returns a `TradeResult`) |
96
+ | Sandbox, connected AI apps | `sandbox_signup()` (module function, no key needed), `sandbox_info`, `create_sandbox_key`, `list_connected_apps`, `disconnect_connected_app` |
97
+ | Dedicated IPs, billing | `dedicated_ips`, `move_accounts_to_dedicated_ip`, `billing_summary` (read-only) |
98
+ | Agent API (`AgentClient`) | `me`, `accounts`, `snapshot`, `health`, `account_information`, `positions`, `orders`, `price`, `specification`, `deals`, `trade`, `trade_status`, `audit` |
99
+
100
+ ### Pagination
101
+
102
+ Native `/v1` lists (agent keys, pre-trade hooks, holds, kill switches, the
103
+ agent audit log, connected apps, `AgentClient.accounts`) return one page:
104
+ `{"data" | "entries" | "apps" | "accounts": [...], "has_more", "next_cursor"}`.
105
+ Pass `limit=` (1 to 500, default 100) and `cursor=`, or let `pages` follow the
106
+ cursor for you:
107
+
108
+ ```python
109
+ for page in tw.pages(tw.list_holds, status="pending", limit=100):
110
+ for hold in page["data"]:
111
+ ...
112
+ # async: async for page in tw.pages(tw.list_agent_keys): ...
113
+ ```
114
+
115
+ ### Snapshot
116
+
117
+ `tw.account(id).snapshot()` (or `AgentClient.snapshot(account_id)`) returns
118
+ account information, positions, orders, health and server time in one read,
119
+ each section with `status` (`ok`, `stale`, `unavailable`), `read_at` and
120
+ `age_ms`. The broker's UTC offset is explicit
121
+ (`server_time["data"]["brokerUtcOffsetMinutes"]`, `None` when unknown).
122
+
123
+ Every call maps to an operation in `tickwire/_operations.py`, generated from
124
+ the public OpenAPI spec ([tickwire.io/openapi.json](https://tickwire.io/openapi.json)).
125
+
126
+ ## Safety you get by default
127
+
128
+ - **Idempotency.** Every mutation sends `Idempotency-Key` (yours, or a
129
+ generated `tw_…`), `X-Actor` and `X-Reason`. Pass `idempotency_key=` to make
130
+ a repeat of the same decision safe across restarts.
131
+ - **Retries only when safe.** Reads retry on transport errors and
132
+ 408/429/502/503/504 with full-jitter backoff (`Retry-After` honoured up to
133
+ the cap), within a per-client `RetryBudget` so an outage cannot become a
134
+ retry storm. A mutation retries only when the server confirms it did not
135
+ run it, always with the same key: connection refused; `409
136
+ idempotency_in_flight` (the first attempt is still running, so the SDK
137
+ waits `Retry-After` and then gets that attempt's stored result); or a
138
+ 429/5xx whose body says explicitly `sent: false` (error codes alone
139
+ never count).
140
+ - **`unknown` is never retried.** A lost reply to a mutation (read timeout,
141
+ reset) or any other 408/5xx raises `OutcomeUnknown` carrying the
142
+ idempotency key; the
143
+ guarded trades (`execute_trade`, `AgentClient.trade`) return
144
+ `TradeResult(outcome="unknown", sent="unknown")` instead.
145
+ - **Streams resume.** `AccountStream` re-subscribes with the last `seq`; a gap
146
+ forces a full resync, so the mirror is never silently wrong.
147
+ - **Typed errors** (`NotFound`, `Conflict`, `NotSupportedOnMt4`,
148
+ `RateLimited`, `ConfigError`, …) keep the server envelope in `.body`.
149
+ `health()` returns the body of a 503: "down" is an answer, not an exception.
150
+ - **Webhooks:** `verify_webhook(secret, headers, body)` checks the HMAC-SHA256
151
+ signature and rejects replays outside a 5-minute window.
152
+ - **Clean close.** `close()` / `aclose()` release every connection and are
153
+ idempotent. Credentials never appear in `repr()`.
154
+
155
+ A bare control plane (no gateway) serves the FxSocket routes at the root:
156
+ pass `control_prefix=""`.
157
+
158
+ ## Examples
159
+
160
+ A prop-firm risk guard (flatten on daily drawdown), a trade copier, a journal
161
+ sync and a trading bot: [tickwire.io/docs/guides/examples](https://tickwire.io/docs/guides/examples/).
162
+ Demo accounts only.
@@ -0,0 +1,48 @@
1
+ [project]
2
+ name = "tickwire"
3
+ version = "0.1.0"
4
+ description = "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
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ authors = [{ name = "Tickwire", email = "hello@tickwire.io" }]
10
+ keywords = ["metatrader", "mt4", "mt5", "trading", "api", "sdk", "ai-agents"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Topic :: Office/Business :: Financial :: Investment",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = [
24
+ "httpx>=0.27,<1",
25
+ "websockets>=12,<18",
26
+ ]
27
+
28
+ [project.optional-dependencies]
29
+ dev = ["pytest>=8.0"]
30
+
31
+ [project.urls]
32
+ Homepage = "https://tickwire.io/"
33
+ Documentation = "https://tickwire.io/docs/sdk-python/"
34
+ Changelog = "https://tickwire.io/docs/changelog/"
35
+
36
+ [build-system]
37
+ requires = ["setuptools>=77"]
38
+ build-backend = "setuptools.build_meta"
39
+
40
+ [tool.setuptools.packages.find]
41
+ where = ["."]
42
+ include = ["tickwire*"]
43
+
44
+ [tool.setuptools.package-data]
45
+ tickwire = ["py.typed"]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,120 @@
1
+ """The SDK against the real control plane and bridges, in-process, on fake MT4/MT5 terminals.
2
+
3
+ Skipped when ``bridge``/``controlplane`` are not installed (CI installs them via
4
+ requirements-ci.txt).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+
10
+ import httpx
11
+ import pytest
12
+
13
+ pytest.importorskip("tickwire_controlplane.app")
14
+ pytest.importorskip("tickwire_bridge.app")
15
+
16
+ from tickwire_bridge.app import create_app as create_bridge # noqa: E402
17
+ from tickwire_bridge.config import BridgeConfig # noqa: E402
18
+ from tickwire_bridge.fake_backend import FakeMt5Backend # noqa: E402
19
+ from tickwire_controlplane.agentgw.terminal import Route # noqa: E402
20
+ from tickwire_controlplane.app import create_app # noqa: E402
21
+ from tickwire_controlplane.store import InMemoryStore # noqa: E402
22
+
23
+ from tickwire import AsyncAgentClient, AsyncTickwire # noqa: E402
24
+
25
+ API = "http://api.tickwire.test"
26
+ BUY = {"actionType": "ORDER_TYPE_BUY", "symbol": "EURUSD", "volume": 0.01}
27
+
28
+
29
+ class HostRouter(httpx.AsyncBaseTransport):
30
+ def __init__(self) -> None:
31
+ self.apps: dict[str, object] = {}
32
+
33
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
34
+ app = self.apps.get(request.url.host)
35
+ if app is None:
36
+ raise httpx.ConnectError(f"no host {request.url.host}", request=request)
37
+ return await httpx.ASGITransport(app=app).handle_async_request(request)
38
+
39
+
40
+ class Stack:
41
+ def __init__(self, platform: str) -> None:
42
+ self.store = InMemoryStore()
43
+ self.tenant = self.store.create_tenant("sdk", balance_cents=100_000)
44
+ self.owner_key = self.store.issue_full_key(self.tenant.id).secret
45
+ self.app = create_app(self.store)
46
+ self.router = HostRouter()
47
+ self.router.apps["api.tickwire.test"] = self.app
48
+ self.acct = self.store.create_account(self.tenant.id, platform=platform, server="Demo1", login=9001,
49
+ password="demo-broker-pw")
50
+ self.backend = FakeMt5Backend(login=9001, platform=platform)
51
+ self.router.apps["bridge-1"] = create_bridge(self.backend, BridgeConfig(
52
+ account_id=self.acct.id, trade_connection_wait_s=0.05, trade_connection_retry_s=0.01))
53
+
54
+ async def resolve(account):
55
+ return Route("http://bridge-1", "connected") if account.id == self.acct.id else None
56
+
57
+ self.app.state.agent_route_resolver = resolve
58
+ self.app.state.agent_terminal_transport = self.router
59
+
60
+ def owner(self) -> AsyncTickwire:
61
+ # a bare control plane serves its FxSocket routes at the root (the gateway adds /v1)
62
+ return AsyncTickwire(API, self.owner_key, transport=self.router, control_prefix="")
63
+
64
+ def agent(self, key: str) -> AsyncAgentClient:
65
+ return AsyncAgentClient(API, key, transport=self.router)
66
+
67
+
68
+ @pytest.mark.parametrize("platform", ["mt5", "mt4"])
69
+ def test_agent_keys_kill_switch_execution_and_agent_api(platform):
70
+ s = Stack(platform)
71
+
72
+ async def main():
73
+ async with s.owner() as tw:
74
+ assert [a["id"] for a in await tw.list_accounts()] == [s.acct.id]
75
+ created = await tw.create_agent_key("bot", [s.acct.id], reason="sdk test")
76
+ assert created["key"].startswith("twag_")
77
+ keys = await tw.list_agent_keys()
78
+ assert any(k["id"] == created["id"] for k in keys["data"])
79
+ assert keys["has_more"] is False and keys["next_cursor"] is None
80
+
81
+ async with s.agent(created["key"]) as agent:
82
+ me = await agent.me()
83
+ assert me is not None
84
+ assert [a["account_id"] for a in (await agent.accounts())["accounts"]] == [s.acct.id]
85
+ r = await agent.trade(s.acct.id, BUY, reason="sdk test entry", idempotency_key="sdk-1")
86
+ assert r.outcome == "applied" and r.sent is True, r.body
87
+ again = await agent.trade(s.acct.id, BUY, reason="said differently", idempotency_key="sdk-1")
88
+ assert again.replayed and again.outcome == "applied"
89
+ assert len(s.backend.positions()) == 1 # one order, not two
90
+ status = await agent.trade_status("sdk-1")
91
+ assert status is not None
92
+
93
+ await tw.set_account_kill_switch(s.acct.id, True, reason="stop everything")
94
+ stopped = await agent.trade(s.acct.id, BUY, reason="after the switch")
95
+ assert stopped.outcome == "rejected" and stopped.sent is False
96
+ assert stopped.error == "kill_switch_engaged"
97
+ # the account kill switch stops agents only: the owner can still trade and flatten
98
+ ex = await tw.execute_trade(s.acct.id, BUY, reason="owner via execution")
99
+ assert ex.outcome == "applied", ex.body
100
+ assert len(s.backend.positions()) == 2
101
+
102
+ await tw.set_account_kill_switch(s.acct.id, False, reason="resume")
103
+ resumed = await agent.trade(s.acct.id, BUY, reason="after resume")
104
+ assert resumed.outcome == "applied", resumed.body
105
+ assert len(s.backend.positions()) == 3
106
+
107
+ audit = await agent.audit(limit=10)
108
+ assert audit
109
+ owner_audit = await tw.agent_audit(account_id=s.acct.id, limit=50)
110
+ assert owner_audit
111
+ assert (await tw.list_pretrade_hooks())["data"] == []
112
+ assert "ips" in await tw.dedicated_ips()
113
+ await tw.list_holds(status="pending")
114
+ await tw.list_kill_switches()
115
+ await tw.revoke_agent_key(created["id"], reason="done")
116
+ summary = await tw.billing_summary()
117
+ assert summary["status"] in ("none", "trialing", "active", "past_due", "unpaid", "expired",
118
+ "paused", "canceled", "unknown")
119
+
120
+ asyncio.run(main())
@@ -0,0 +1,113 @@
1
+ """Bounded backoff with jitter, and proof that a failing server does not get a retry storm."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import random
6
+ import statistics
7
+
8
+ import httpx
9
+ import pytest
10
+
11
+ from tickwire import AsyncTickwire, Backoff, RetryBudget, RetryBudgetExhausted, ServerError, Tickwire
12
+
13
+
14
+ def test_delay_is_bounded_and_jittered():
15
+ b = Backoff(base_s=0.25, cap_s=2.0, rng=random.Random(1))
16
+ for attempt in range(1, 30):
17
+ for _ in range(50):
18
+ d = b.delay(attempt)
19
+ assert 0 <= d <= min(2.0, 0.25 * 2 ** (attempt - 1))
20
+ samples = [b.delay(5) for _ in range(500)]
21
+ assert statistics.pstdev(samples) > 0.3 # spread, not a thundering herd
22
+ assert len({round(s, 3) for s in samples}) > 400
23
+
24
+
25
+ def test_retry_after_is_honoured_but_capped():
26
+ b = Backoff(base_s=0.1, cap_s=3.0, rng=random.Random(2))
27
+ assert b.delay(1, retry_after=2.0) >= 2.0
28
+ assert b.delay(1, retry_after=3600) == 3.0
29
+
30
+
31
+ def _always(status: int, counter: list):
32
+ def handler(request: httpx.Request) -> httpx.Response:
33
+ counter.append(request)
34
+ return httpx.Response(status, json={"error": "unavailable", "message": "down"})
35
+ return httpx.MockTransport(handler)
36
+
37
+
38
+ def test_single_call_stops_after_max_attempts():
39
+ calls: list = []
40
+ sleeps: list = []
41
+ tw = Tickwire("https://api.test", "tok", transport=_always(503, calls), sleep=sleeps.append,
42
+ backoff=Backoff(max_attempts=4, rng=random.Random(3)))
43
+ with pytest.raises(ServerError):
44
+ tw.account("a").positions()
45
+ assert len(calls) == 4 and len(sleeps) == 3
46
+ assert all(s <= tw.opts.backoff.cap_s for s in sleeps)
47
+
48
+
49
+ def test_sustained_outage_is_capped_by_the_retry_budget():
50
+ """200 calls against a dead server: without a budget that is 800 requests; with it, ~210."""
51
+ calls: list = []
52
+ budget = RetryBudget(capacity=10, refill_per_success=0.1)
53
+ tw = Tickwire("https://api.test", "tok", transport=_always(503, calls), sleep=lambda s: None,
54
+ budget=budget, backoff=Backoff(max_attempts=4, rng=random.Random(4)))
55
+ exhausted = 0
56
+ for _ in range(200):
57
+ try:
58
+ tw.account("a").positions()
59
+ except RetryBudgetExhausted:
60
+ exhausted += 1
61
+ except ServerError:
62
+ pass
63
+ assert len(calls) <= 200 + 10 # every call once, plus the budget
64
+ assert exhausted >= 190
65
+ assert budget.tokens < 1
66
+
67
+
68
+ def test_budget_refills_on_success():
69
+ budget = RetryBudget(capacity=2, refill_per_success=0.5)
70
+ assert budget.try_spend() and budget.try_spend() and not budget.try_spend()
71
+ budget.on_success()
72
+ budget.on_success()
73
+ assert budget.try_spend()
74
+
75
+
76
+ def test_concurrent_clients_do_not_retry_in_lockstep():
77
+ """50 clients fail at the same instant; their retry times must be spread out."""
78
+ attempts_at: list[float] = []
79
+
80
+ async def main():
81
+ loop = asyncio.get_running_loop()
82
+
83
+ def handler(request):
84
+ attempts_at.append(loop.time())
85
+ return httpx.Response(503, json={"error": "unavailable", "message": "down"})
86
+
87
+ async def one(i):
88
+ tw = AsyncTickwire("https://api.test", "tok", transport=httpx.MockTransport(handler),
89
+ backoff=Backoff(base_s=0.05, cap_s=0.4, max_attempts=3, rng=random.Random(i)))
90
+ async with tw:
91
+ with pytest.raises(ServerError):
92
+ await tw.account("a").positions()
93
+
94
+ t0 = loop.time()
95
+ await asyncio.gather(*(one(i) for i in range(50)))
96
+ return t0
97
+
98
+ t0 = asyncio.run(main())
99
+ assert len(attempts_at) == 150 # exactly max_attempts each, never more
100
+ retries = sorted(t - t0 for t in attempts_at if t - t0 > 0.001)
101
+ # jitter spreads the 100 retries over time instead of two synchronized spikes.
102
+ # Lockstep retries land in 2 or 3 one-millisecond buckets. A busy machine
103
+ # wakes timers in batches, so the bar is well below 100 but far above 3.
104
+ buckets = {round(t, 3) for t in retries}
105
+ assert len(buckets) > 20
106
+
107
+
108
+ def test_non_retryable_errors_are_not_retried():
109
+ calls: list = []
110
+ tw = Tickwire("https://api.test", "tok", transport=_always(400, calls), sleep=lambda s: None)
111
+ with pytest.raises(Exception):
112
+ tw.account("a").positions()
113
+ assert len(calls) == 1