zetaapi 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.
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
zetaapi-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alle-AI
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.
zetaapi-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,250 @@
1
+ Metadata-Version: 2.5
2
+ Name: zetaapi
3
+ Version: 0.1.0
4
+ Summary: Official Python client for the Zeta API: cloud MetaTrader 4/5 over REST, SSE and WebSocket.
5
+ Project-URL: Homepage, https://zetaapi.cloud
6
+ Project-URL: Documentation, https://zetaapi.cloud/docs
7
+ Project-URL: Changelog, https://zetaapi.cloud/docs/changelog
8
+ Author-email: Alle-AI <support@zetaapi.cloud>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: api,forex,metatrader,mt4,mt5,sdk,trading,zeta
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Office/Business :: Financial :: Investment
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.9
26
+ Requires-Dist: httpx<1,>=0.25
27
+ Requires-Dist: typing-extensions>=4.5; python_version < '3.11'
28
+ Provides-Extra: dev
29
+ Requires-Dist: mypy>=1.8; extra == 'dev'
30
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
31
+ Requires-Dist: pytest>=8; extra == 'dev'
32
+ Requires-Dist: websockets>=14; extra == 'dev'
33
+ Provides-Extra: ws
34
+ Requires-Dist: websockets>=14; extra == 'ws'
35
+ Description-Content-Type: text/markdown
36
+
37
+ <p><a href="https://zetaapi.cloud/"><img src="https://zetaapi.cloud/brand/zeta-logo-blue-96.png" width="48" height="48" alt="Zeta API logo"></a></p>
38
+
39
+ # zetaapi
40
+
41
+ Official Python client for the [Zeta API](https://zetaapi.cloud): real MetaTrader 5 (and MT4) terminals
42
+ in the cloud, read and traded over plain HTTP, Server-Sent Events and WebSocket.
43
+
44
+ - Python 3.9+, sync (`Zeta`) and asyncio (`AsyncZeta`) clients on `httpx`; typed (`py.typed`, TypedDicts).
45
+ - Safe by default: every trade carries an `Idempotency-Key` (generated for you), and only safe requests
46
+ are retried, so a retry never trades twice.
47
+ - Live data with automatic reconnect over SSE (`account.stream()`), or one WebSocket for many accounts
48
+ (`pip install "zetaapi[ws]"`).
49
+
50
+ ```bash
51
+ pip install zetaapi # REST + SSE streaming
52
+ pip install "zetaapi[ws]" # + the WebSocket client
53
+ ```
54
+
55
+ ## Quickstart: first trade in 5 minutes
56
+
57
+ You need two things:
58
+
59
+ 1. **An API key**: sign up free at [zetaapi.cloud](https://zetaapi.cloud/signup), verify your email, create
60
+ a key under **API keys** (it starts with `zk_` and is shown once), then `export ZETA_API_KEY=zk_...`
61
+ (PowerShell: `$env:ZETA_API_KEY = "zk_..."`).
62
+ 2. **A demo MetaTrader account** (login, password, server). No broker needed: the MetaTrader 5 web terminal
63
+ at [web.metatrader.app/terminal](https://web.metatrader.app/terminal) → **Open Demo account** gives you a
64
+ login on server `MetaQuotes-Demo`. Any broker's free MT5 or MT4 demo works too (for MT4 pass `platform="mt4"`).
65
+
66
+ ```python
67
+ import os
68
+ from zeta import Zeta
69
+
70
+ zeta = Zeta(api_key=os.environ["ZETA_API_KEY"])
71
+ account = zeta.accounts.create(12345678, "your-demo-password", "MetaQuotes-Demo")
72
+ zeta.accounts.wait_until_connected(account["id"]) # usually 20-55 s
73
+
74
+ acc = zeta.account(account["id"])
75
+ print(acc.info()["data"]["balance"], acc.quotes(["EURUSD"]))
76
+
77
+ order = acc.place_order("EURUSD", "buy", 0.01)
78
+ print(order["status"], order["position"], order["fillPrice"])
79
+ acc.close_position(order["position"])
80
+
81
+ for ev in acc.stream(["EURUSD"]): # tick, account, positions, orders, status; Ctrl+C to stop
82
+ print(ev.type, ev.data)
83
+ ```
84
+
85
+ Ran it before? `accounts.create` raises `ZetaError` `account_exists` with the existing id in
86
+ `err.details["accountId"]`. Forex is closed at weekends: use `BTCUSD` then. Delete the account when done
87
+ (`zeta.accounts.delete(id)`). The runnable version is `examples/quickstart.py` (in the source distribution, `pip download --no-binary :all: zetaapi`).
88
+ Guides, errors and limits: https://zetaapi.cloud/docs.
89
+
90
+ A client, an account handle, plain dicts back (keys as in the API: `fillPrice`, `brokerSymbol`, ...).
91
+
92
+ Async is the same with `await`:
93
+
94
+ ```python
95
+ from zeta import AsyncZeta
96
+
97
+ async with AsyncZeta(api_key="zk_...") as zeta:
98
+ acc = zeta.account(account_id)
99
+ order = await acc.place_order("EURUSD", "buy", 0.01)
100
+ async for ev in acc.stream(["EURUSD"]):
101
+ print(ev.type, ev.data)
102
+ ```
103
+
104
+ ## Client
105
+
106
+ ```python
107
+ Zeta(
108
+ api_key="zk_...",
109
+ base_url="https://zetaapi.cloud", # default
110
+ max_retries=3, # retries for safe requests (see "Retries")
111
+ timeout=60.0, # seconds per attempt
112
+ retry_base=0.5, retry_max=8.0, # backoff (seconds)
113
+ http_client=None, transport=None, # your own httpx.Client / transport
114
+ )
115
+ ```
116
+
117
+ `Zeta` and `AsyncZeta` are context managers (`with` / `async with`) that close their HTTP client.
118
+
119
+ ## Accounts
120
+
121
+ | Method | Returns |
122
+ |---|---|
123
+ | `zeta.accounts.create(login, password, server, *, platform=None, external_ref=None)` | `Account` (status `provisioning`) |
124
+ | `zeta.accounts.list(*, limit, cursor, external_ref)` | `{"data": [Account], "nextCursor"}` |
125
+ | `zeta.accounts.list_all(*, limit, external_ref)` | iterator (async iterator) over every account |
126
+ | `zeta.accounts.get(account_id)` | `Account` |
127
+ | `zeta.accounts.update_credentials(account_id, password, *, server=None)` | `Account` |
128
+ | `zeta.accounts.delete(account_id)` | `None` (terminal stops; positions stay open at the broker) |
129
+ | `zeta.accounts.wait_until_connected(account_id, *, timeout=600, interval=3, on_status=None)` | `Account` once `connected` |
130
+
131
+ `wait_until_connected` raises `ZetaError` with code `auth_failed` (Zeta does not retry a wrong
132
+ login/password/server), `account_stopped` (see `err.details["account"]["statusReason"]`) or `timeout`.
133
+
134
+ ## Account data and trading: `zeta.account(id)`
135
+
136
+ | Method | Returns |
137
+ |---|---|
138
+ | `get()`, `wait_until_connected(...)` | `Account` |
139
+ | `info()` | `{"asOf", "stale", "data": AccountInfo}` |
140
+ | `positions()` | `{"asOf", "stale", "data": [Position]}` |
141
+ | `orders()` | `{"asOf", "stale", "data": [PendingOrder]}` |
142
+ | `quotes(["EURUSD", "XAUUSD"])` | `[Quote]` (1-20 symbols) |
143
+ | `candles(symbol, timeframe, *, limit, from_, to)` | `{"symbol", "brokerSymbol", "timeframe", "truncated", "data": [Candle]}`, oldest first |
144
+ | `symbols(search=None)` | `[SymbolSpec]` |
145
+ | `history.deals(*, from_, to, limit)` | `{"data": [Deal], "truncated"}` |
146
+ | `place_order(symbol, side, volume, *, type="market", price, sl, tp, deviation, expiration, comment, client_ref, idempotency_key)` | `Order` |
147
+ | `close_position(ticket, *, volume, comment, idempotency_key)` | `Order` |
148
+ | `modify_position(ticket, *, sl, tp)` | `Order` (not given = keep, `None` = remove) |
149
+ | `modify_order(ticket, *, price, sl, tp, expiration)` | `Order` |
150
+ | `cancel_order(ticket)` | `Order` |
151
+ | `get_order(order_id)` | `Order` |
152
+ | `wait_for_order(order_id, *, timeout=120, interval=2)` | `Order` once its outcome is known |
153
+ | `stream(symbols=None, *, on_tick, on_account, on_positions, on_orders, on_status, on_subscribed, on_event, on_error)` | `Stream` |
154
+
155
+ Times (`from_`, `to`, `expiration`) take a `datetime` (naive = UTC), a `date` or an ISO string.
156
+ `timeframe`: `M1 M5 M15 M30 H1 H4 D1 W1 MN1`. `magic` is a decimal string (64-bit).
157
+
158
+ Also: `zeta.usage(from_=None, to=None)`, `zeta.me()`, `zeta.brokers()`.
159
+
160
+ ### Trade results
161
+
162
+ | `order["status"]` | Meaning |
163
+ |---|---|
164
+ | `filled`, `partially_filled`, `placed` | done; `order["position"]` is the ticket to close later |
165
+ | `done` | modify / cancel applied |
166
+ | `sent`, `unknown` | **outcome not known yet**: do not place it again with a new key; `acc.wait_for_order(order["id"])` |
167
+
168
+ A rejected trade raises `ZetaError`; `err.order` has Zeta's record (with `retcode`).
169
+
170
+ ## Retries and idempotency
171
+
172
+ - Reads are retried on no answer, `429` and `5xx` with exponential backoff and jitter (`Retry-After` honoured).
173
+ - Trades always send an `Idempotency-Key` (a UUID unless you pass `idempotency_key=`) and are retried
174
+ **with the same key** on no answer, `429` and `5xx`. A recorded rejection (`err.order` set) is not
175
+ retried: the same key would only replay it. A new trade gets a new key; a trade is never retried with a new key.
176
+ - `accounts.create`, `update_credentials` and `delete` are never retried.
177
+ - If a trade still fails without an answer, `err.idempotency_key` holds the key: call again with
178
+ `idempotency_key=err.idempotency_key` to learn its outcome safely.
179
+
180
+ ## Errors
181
+
182
+ ```python
183
+ from zeta import ZetaError
184
+
185
+ try:
186
+ acc.place_order("EURUSD", "buy", 0.01, sl=1.09)
187
+ except ZetaError as err:
188
+ print(err.status, err.code, err.message, err.details, err.request_id, err.order, err.retryable)
189
+ ```
190
+
191
+ `status` is the HTTP status, `0` when no answer arrived (`network_error`, `timeout`, `connection_lost`,
192
+ `closed`). The API's codes (`validation_failed`, `unauthorized`, `not_found`, `account_not_connected`,
193
+ `idempotency_key_reused`, `market_closed`, `busy`, `snapshot_pending`, ...) are listed in
194
+ [docs/API.md](../../docs/API.md#6-errors) and in the JS SDK README. SDK-side codes:
195
+ `invalid_idempotency_key`, `validation_failed` (bad ticket), `auth_failed`, `account_stopped`,
196
+ `handler_error`, `websocket_unavailable`.
197
+
198
+ ## Streaming (SSE)
199
+
200
+ ```python
201
+ stream = acc.stream(
202
+ ["EURUSD", "XAUUSD"], # up to 50 (10 on MT4); optional
203
+ on_tick=lambda t: print(t["symbol"], t["bid"], t["ask"]),
204
+ on_account=lambda e: print("equity", e["data"]["equity"]),
205
+ on_positions=lambda e: print(len(e["data"]), "positions"),
206
+ on_status=lambda e: print(e["status"], e["statusReason"]),
207
+ on_error=lambda err, will_retry: print(err.code, will_retry),
208
+ )
209
+ stream.run() # or: for ev in stream: ... (ev.type, ev.data)
210
+ stream.close() # from another thread, a callback or a loop body
211
+ ```
212
+
213
+ Reconnects by itself with backoff (and when nothing, not even the 15 s keepalive, arrives for 45 s).
214
+ After each (re)connect the first events bring you up to date. Stops for good on `400/401/403/404`
215
+ (`on_error(err, False)`). The async version: `async for ev in acc.stream(...)` or `await stream.run()`.
216
+
217
+ ## WebSocket (`pip install "zetaapi[ws]"`, asyncio)
218
+
219
+ ```python
220
+ async with AsyncZeta(api_key="zk_...") as zeta, zeta.ws() as ws:
221
+ ws.on("positions", lambda e, account_id: print(account_id, len(e["data"])))
222
+ await ws.subscribe(account_id, ["EURUSD"], on_tick=lambda t: print(t["bid"]))
223
+ order = await ws.place_order(account_id, "EURUSD", "buy", 0.01)
224
+ async for ev in ws: # Event(type, data, account_id)
225
+ ...
226
+ ```
227
+
228
+ - Methods: `subscribe(account_id, symbols=None, **handlers)`, `unsubscribe`, `place_order`, `close_position`,
229
+ `modify_position`, `modify_order`, `cancel_order` (same arguments as the REST handle with `account_id`
230
+ first), `ping`, `close`, `on(event, fn)`.
231
+ - Auth with the `Authorization` header (default) or `auth="message"`. Answers are matched by `id`.
232
+ On a drop it reconnects with backoff, subscribes again and resends unanswered requests (trades keep
233
+ their `idempotencyKey`). A wrong key stops it for good (`ZetaError` 401).
234
+ - Options: `url`, `reconnect=True`, `max_reconnect_delay=30`, `request_timeout=60`, `ping_interval=20`.
235
+ - `zeta.ws()` also exists on the sync `Zeta`, but the socket is asyncio: use it inside an event loop.
236
+
237
+ ## Examples
238
+
239
+ - [`examples/quickstart.py`](examples/quickstart.py): add an account, buy, stream, close, delete.
240
+ - [`examples/websocket.py`](examples/websocket.py): many accounts on one WebSocket.
241
+ - [`examples/candles_and_history.py`](examples/candles_and_history.py): balance, positions, candles, deals.
242
+
243
+ ## Development
244
+
245
+ ```bash
246
+ python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate
247
+ pip install -e ".[dev]"
248
+ pytest # httpx.MockTransport and a local websockets server
249
+ mypy # strict
250
+ ```
@@ -0,0 +1,214 @@
1
+ <p><a href="https://zetaapi.cloud/"><img src="https://zetaapi.cloud/brand/zeta-logo-blue-96.png" width="48" height="48" alt="Zeta API logo"></a></p>
2
+
3
+ # zetaapi
4
+
5
+ Official Python client for the [Zeta API](https://zetaapi.cloud): real MetaTrader 5 (and MT4) terminals
6
+ in the cloud, read and traded over plain HTTP, Server-Sent Events and WebSocket.
7
+
8
+ - Python 3.9+, sync (`Zeta`) and asyncio (`AsyncZeta`) clients on `httpx`; typed (`py.typed`, TypedDicts).
9
+ - Safe by default: every trade carries an `Idempotency-Key` (generated for you), and only safe requests
10
+ are retried, so a retry never trades twice.
11
+ - Live data with automatic reconnect over SSE (`account.stream()`), or one WebSocket for many accounts
12
+ (`pip install "zetaapi[ws]"`).
13
+
14
+ ```bash
15
+ pip install zetaapi # REST + SSE streaming
16
+ pip install "zetaapi[ws]" # + the WebSocket client
17
+ ```
18
+
19
+ ## Quickstart: first trade in 5 minutes
20
+
21
+ You need two things:
22
+
23
+ 1. **An API key**: sign up free at [zetaapi.cloud](https://zetaapi.cloud/signup), verify your email, create
24
+ a key under **API keys** (it starts with `zk_` and is shown once), then `export ZETA_API_KEY=zk_...`
25
+ (PowerShell: `$env:ZETA_API_KEY = "zk_..."`).
26
+ 2. **A demo MetaTrader account** (login, password, server). No broker needed: the MetaTrader 5 web terminal
27
+ at [web.metatrader.app/terminal](https://web.metatrader.app/terminal) → **Open Demo account** gives you a
28
+ login on server `MetaQuotes-Demo`. Any broker's free MT5 or MT4 demo works too (for MT4 pass `platform="mt4"`).
29
+
30
+ ```python
31
+ import os
32
+ from zeta import Zeta
33
+
34
+ zeta = Zeta(api_key=os.environ["ZETA_API_KEY"])
35
+ account = zeta.accounts.create(12345678, "your-demo-password", "MetaQuotes-Demo")
36
+ zeta.accounts.wait_until_connected(account["id"]) # usually 20-55 s
37
+
38
+ acc = zeta.account(account["id"])
39
+ print(acc.info()["data"]["balance"], acc.quotes(["EURUSD"]))
40
+
41
+ order = acc.place_order("EURUSD", "buy", 0.01)
42
+ print(order["status"], order["position"], order["fillPrice"])
43
+ acc.close_position(order["position"])
44
+
45
+ for ev in acc.stream(["EURUSD"]): # tick, account, positions, orders, status; Ctrl+C to stop
46
+ print(ev.type, ev.data)
47
+ ```
48
+
49
+ Ran it before? `accounts.create` raises `ZetaError` `account_exists` with the existing id in
50
+ `err.details["accountId"]`. Forex is closed at weekends: use `BTCUSD` then. Delete the account when done
51
+ (`zeta.accounts.delete(id)`). The runnable version is `examples/quickstart.py` (in the source distribution, `pip download --no-binary :all: zetaapi`).
52
+ Guides, errors and limits: https://zetaapi.cloud/docs.
53
+
54
+ A client, an account handle, plain dicts back (keys as in the API: `fillPrice`, `brokerSymbol`, ...).
55
+
56
+ Async is the same with `await`:
57
+
58
+ ```python
59
+ from zeta import AsyncZeta
60
+
61
+ async with AsyncZeta(api_key="zk_...") as zeta:
62
+ acc = zeta.account(account_id)
63
+ order = await acc.place_order("EURUSD", "buy", 0.01)
64
+ async for ev in acc.stream(["EURUSD"]):
65
+ print(ev.type, ev.data)
66
+ ```
67
+
68
+ ## Client
69
+
70
+ ```python
71
+ Zeta(
72
+ api_key="zk_...",
73
+ base_url="https://zetaapi.cloud", # default
74
+ max_retries=3, # retries for safe requests (see "Retries")
75
+ timeout=60.0, # seconds per attempt
76
+ retry_base=0.5, retry_max=8.0, # backoff (seconds)
77
+ http_client=None, transport=None, # your own httpx.Client / transport
78
+ )
79
+ ```
80
+
81
+ `Zeta` and `AsyncZeta` are context managers (`with` / `async with`) that close their HTTP client.
82
+
83
+ ## Accounts
84
+
85
+ | Method | Returns |
86
+ |---|---|
87
+ | `zeta.accounts.create(login, password, server, *, platform=None, external_ref=None)` | `Account` (status `provisioning`) |
88
+ | `zeta.accounts.list(*, limit, cursor, external_ref)` | `{"data": [Account], "nextCursor"}` |
89
+ | `zeta.accounts.list_all(*, limit, external_ref)` | iterator (async iterator) over every account |
90
+ | `zeta.accounts.get(account_id)` | `Account` |
91
+ | `zeta.accounts.update_credentials(account_id, password, *, server=None)` | `Account` |
92
+ | `zeta.accounts.delete(account_id)` | `None` (terminal stops; positions stay open at the broker) |
93
+ | `zeta.accounts.wait_until_connected(account_id, *, timeout=600, interval=3, on_status=None)` | `Account` once `connected` |
94
+
95
+ `wait_until_connected` raises `ZetaError` with code `auth_failed` (Zeta does not retry a wrong
96
+ login/password/server), `account_stopped` (see `err.details["account"]["statusReason"]`) or `timeout`.
97
+
98
+ ## Account data and trading: `zeta.account(id)`
99
+
100
+ | Method | Returns |
101
+ |---|---|
102
+ | `get()`, `wait_until_connected(...)` | `Account` |
103
+ | `info()` | `{"asOf", "stale", "data": AccountInfo}` |
104
+ | `positions()` | `{"asOf", "stale", "data": [Position]}` |
105
+ | `orders()` | `{"asOf", "stale", "data": [PendingOrder]}` |
106
+ | `quotes(["EURUSD", "XAUUSD"])` | `[Quote]` (1-20 symbols) |
107
+ | `candles(symbol, timeframe, *, limit, from_, to)` | `{"symbol", "brokerSymbol", "timeframe", "truncated", "data": [Candle]}`, oldest first |
108
+ | `symbols(search=None)` | `[SymbolSpec]` |
109
+ | `history.deals(*, from_, to, limit)` | `{"data": [Deal], "truncated"}` |
110
+ | `place_order(symbol, side, volume, *, type="market", price, sl, tp, deviation, expiration, comment, client_ref, idempotency_key)` | `Order` |
111
+ | `close_position(ticket, *, volume, comment, idempotency_key)` | `Order` |
112
+ | `modify_position(ticket, *, sl, tp)` | `Order` (not given = keep, `None` = remove) |
113
+ | `modify_order(ticket, *, price, sl, tp, expiration)` | `Order` |
114
+ | `cancel_order(ticket)` | `Order` |
115
+ | `get_order(order_id)` | `Order` |
116
+ | `wait_for_order(order_id, *, timeout=120, interval=2)` | `Order` once its outcome is known |
117
+ | `stream(symbols=None, *, on_tick, on_account, on_positions, on_orders, on_status, on_subscribed, on_event, on_error)` | `Stream` |
118
+
119
+ Times (`from_`, `to`, `expiration`) take a `datetime` (naive = UTC), a `date` or an ISO string.
120
+ `timeframe`: `M1 M5 M15 M30 H1 H4 D1 W1 MN1`. `magic` is a decimal string (64-bit).
121
+
122
+ Also: `zeta.usage(from_=None, to=None)`, `zeta.me()`, `zeta.brokers()`.
123
+
124
+ ### Trade results
125
+
126
+ | `order["status"]` | Meaning |
127
+ |---|---|
128
+ | `filled`, `partially_filled`, `placed` | done; `order["position"]` is the ticket to close later |
129
+ | `done` | modify / cancel applied |
130
+ | `sent`, `unknown` | **outcome not known yet**: do not place it again with a new key; `acc.wait_for_order(order["id"])` |
131
+
132
+ A rejected trade raises `ZetaError`; `err.order` has Zeta's record (with `retcode`).
133
+
134
+ ## Retries and idempotency
135
+
136
+ - Reads are retried on no answer, `429` and `5xx` with exponential backoff and jitter (`Retry-After` honoured).
137
+ - Trades always send an `Idempotency-Key` (a UUID unless you pass `idempotency_key=`) and are retried
138
+ **with the same key** on no answer, `429` and `5xx`. A recorded rejection (`err.order` set) is not
139
+ retried: the same key would only replay it. A new trade gets a new key; a trade is never retried with a new key.
140
+ - `accounts.create`, `update_credentials` and `delete` are never retried.
141
+ - If a trade still fails without an answer, `err.idempotency_key` holds the key: call again with
142
+ `idempotency_key=err.idempotency_key` to learn its outcome safely.
143
+
144
+ ## Errors
145
+
146
+ ```python
147
+ from zeta import ZetaError
148
+
149
+ try:
150
+ acc.place_order("EURUSD", "buy", 0.01, sl=1.09)
151
+ except ZetaError as err:
152
+ print(err.status, err.code, err.message, err.details, err.request_id, err.order, err.retryable)
153
+ ```
154
+
155
+ `status` is the HTTP status, `0` when no answer arrived (`network_error`, `timeout`, `connection_lost`,
156
+ `closed`). The API's codes (`validation_failed`, `unauthorized`, `not_found`, `account_not_connected`,
157
+ `idempotency_key_reused`, `market_closed`, `busy`, `snapshot_pending`, ...) are listed in
158
+ [docs/API.md](../../docs/API.md#6-errors) and in the JS SDK README. SDK-side codes:
159
+ `invalid_idempotency_key`, `validation_failed` (bad ticket), `auth_failed`, `account_stopped`,
160
+ `handler_error`, `websocket_unavailable`.
161
+
162
+ ## Streaming (SSE)
163
+
164
+ ```python
165
+ stream = acc.stream(
166
+ ["EURUSD", "XAUUSD"], # up to 50 (10 on MT4); optional
167
+ on_tick=lambda t: print(t["symbol"], t["bid"], t["ask"]),
168
+ on_account=lambda e: print("equity", e["data"]["equity"]),
169
+ on_positions=lambda e: print(len(e["data"]), "positions"),
170
+ on_status=lambda e: print(e["status"], e["statusReason"]),
171
+ on_error=lambda err, will_retry: print(err.code, will_retry),
172
+ )
173
+ stream.run() # or: for ev in stream: ... (ev.type, ev.data)
174
+ stream.close() # from another thread, a callback or a loop body
175
+ ```
176
+
177
+ Reconnects by itself with backoff (and when nothing, not even the 15 s keepalive, arrives for 45 s).
178
+ After each (re)connect the first events bring you up to date. Stops for good on `400/401/403/404`
179
+ (`on_error(err, False)`). The async version: `async for ev in acc.stream(...)` or `await stream.run()`.
180
+
181
+ ## WebSocket (`pip install "zetaapi[ws]"`, asyncio)
182
+
183
+ ```python
184
+ async with AsyncZeta(api_key="zk_...") as zeta, zeta.ws() as ws:
185
+ ws.on("positions", lambda e, account_id: print(account_id, len(e["data"])))
186
+ await ws.subscribe(account_id, ["EURUSD"], on_tick=lambda t: print(t["bid"]))
187
+ order = await ws.place_order(account_id, "EURUSD", "buy", 0.01)
188
+ async for ev in ws: # Event(type, data, account_id)
189
+ ...
190
+ ```
191
+
192
+ - Methods: `subscribe(account_id, symbols=None, **handlers)`, `unsubscribe`, `place_order`, `close_position`,
193
+ `modify_position`, `modify_order`, `cancel_order` (same arguments as the REST handle with `account_id`
194
+ first), `ping`, `close`, `on(event, fn)`.
195
+ - Auth with the `Authorization` header (default) or `auth="message"`. Answers are matched by `id`.
196
+ On a drop it reconnects with backoff, subscribes again and resends unanswered requests (trades keep
197
+ their `idempotencyKey`). A wrong key stops it for good (`ZetaError` 401).
198
+ - Options: `url`, `reconnect=True`, `max_reconnect_delay=30`, `request_timeout=60`, `ping_interval=20`.
199
+ - `zeta.ws()` also exists on the sync `Zeta`, but the socket is asyncio: use it inside an event loop.
200
+
201
+ ## Examples
202
+
203
+ - [`examples/quickstart.py`](examples/quickstart.py): add an account, buy, stream, close, delete.
204
+ - [`examples/websocket.py`](examples/websocket.py): many accounts on one WebSocket.
205
+ - [`examples/candles_and_history.py`](examples/candles_and_history.py): balance, positions, candles, deals.
206
+
207
+ ## Development
208
+
209
+ ```bash
210
+ python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate
211
+ pip install -e ".[dev]"
212
+ pytest # httpx.MockTransport and a local websockets server
213
+ mypy # strict
214
+ ```
@@ -0,0 +1,32 @@
1
+ """Read an account: balance, open positions, the last 100 H1 bars and last week's deals.
2
+
3
+ ZETA_API_KEY=zk_... ACCOUNT_ID=... python examples/candles_and_history.py
4
+ """
5
+
6
+ import os
7
+ from datetime import datetime, timedelta, timezone
8
+
9
+ from zeta import Zeta, ZetaError
10
+
11
+ zeta = Zeta(api_key=os.environ["ZETA_API_KEY"])
12
+ acc = zeta.account(os.environ["ACCOUNT_ID"])
13
+
14
+ try:
15
+ info = acc.info()
16
+ print(f"balance {info['data']['balance']} {info['data']['currency']}, equity {info['data']['equity']}"
17
+ + (" (stale)" if info["stale"] else ""))
18
+
19
+ for p in acc.positions()["data"]:
20
+ print(p["ticket"], p["side"], p["volume"], p["symbol"], "profit", p["profit"])
21
+
22
+ bars = acc.candles("EURUSD", "H1", limit=100)
23
+ last = bars["data"][-1] if bars["data"] else None
24
+ print(f"{len(bars['data'])} bars of {bars['brokerSymbol']}; last close {last and last['close']} at {last and last['time']}")
25
+
26
+ week = acc.history.deals(from_=datetime.now(timezone.utc) - timedelta(days=7))
27
+ print(f"{len(week['data'])} deals, profit {sum(d['profit'] for d in week['data']):.2f}")
28
+ except ZetaError as err:
29
+ if err.code == "account_not_connected":
30
+ print("Not connected yet:", (err.details or {}).get("status", "wait and retry")) # "waking" = waking from sleep
31
+ else:
32
+ raise
@@ -0,0 +1,86 @@
1
+ """Zero to first trade: add a demo account, wait for it, read it, buy 0.01 lot, close it, stream, clean up.
2
+
3
+ pip install zetaapi
4
+ ZETA_API_KEY=zk_... MT_LOGIN=12345678 MT_PASSWORD=... MT_SERVER=MetaQuotes-Demo python quickstart.py
5
+
6
+ Optional: MT_PLATFORM=mt4 for an MT4 account, SYMBOL=BTCUSD at weekends (forex is closed), KEEP=1 to keep the account.
7
+ (Windows PowerShell: $env:ZETA_API_KEY = "zk_..." and so on, then python quickstart.py.)
8
+ """
9
+
10
+ import os
11
+ import threading
12
+ import time
13
+
14
+ from zeta import Zeta, ZetaError
15
+
16
+
17
+ def env(name: str, default: "str | None" = None) -> str:
18
+ value = os.environ.get(name, default)
19
+ if value is None:
20
+ raise SystemExit(f"Set {name} (see the top of this file)")
21
+ return value
22
+
23
+
24
+ symbol = env("SYMBOL", "EURUSD")
25
+ zeta = Zeta(api_key=env("ZETA_API_KEY"))
26
+ t0 = time.monotonic()
27
+
28
+
29
+ def elapsed() -> str:
30
+ return f"{time.monotonic() - t0:.1f}s"
31
+
32
+
33
+ login = int(env("MT_LOGIN", os.environ.get("MT5_LOGIN")))
34
+ password = env("MT_PASSWORD", os.environ.get("MT5_PASSWORD"))
35
+ server = env("MT_SERVER", os.environ.get("MT5_SERVER", "MetaQuotes-Demo"))
36
+
37
+ # 1. Add the account, or reuse it (with the password and server given now) if this login was added before.
38
+ try:
39
+ account_id = zeta.accounts.create(login, password, server, platform=os.environ.get("MT_PLATFORM"))["id"]
40
+ except ZetaError as e:
41
+ if e.code != "account_exists":
42
+ raise
43
+ account_id = (e.details or {})["accountId"]
44
+ print("this login is already added, reusing", account_id)
45
+ # A login that failed before gets the password and server given now (this restarts its terminal).
46
+ if zeta.accounts.get(account_id)["status"] in ("auth_failed", "stopped"):
47
+ zeta.accounts.update_credentials(account_id, password, server=server)
48
+
49
+ # 2. Wait until connected (raises ZetaError auth_failed, account_stopped or timeout).
50
+ try:
51
+ zeta.accounts.wait_until_connected(account_id, on_status=lambda a: print(elapsed(), "status:", a["status"], a["statusReason"] or ""))
52
+ except ZetaError as e:
53
+ reason = ((e.details or {}).get("account") or {}).get("statusReason") or ""
54
+ print(f"\n{e} {reason}")
55
+ if e.code == "auth_failed":
56
+ print("Check MT_LOGIN, MT_PASSWORD and MT_SERVER (exactly as the broker wrote it), then run again.")
57
+ if e.code == "account_stopped":
58
+ print("See https://zetaapi.cloud/docs/accounts for what this status means.")
59
+ raise SystemExit(1)
60
+ print(elapsed(), "connected")
61
+ acc = zeta.account(account_id)
62
+
63
+ # 3. Read the account and a price.
64
+ info = acc.info()["data"]
65
+ print("balance", info["balance"], info["currency"], "equity", info["equity"], "demo", info["isDemo"])
66
+ print("quote", acc.quotes([symbol]))
67
+
68
+ # 4. Buy 0.01 lot. The SDK sends an Idempotency-Key, so its retries never trade twice.
69
+ order = acc.place_order(symbol, "buy", 0.01)
70
+ print(elapsed(), "order", order["status"], "position", order["position"], "at", order["fillPrice"])
71
+ if order["status"] in ("sent", "unknown"):
72
+ order = acc.wait_for_order(order["id"])
73
+
74
+ # 5. Close it.
75
+ if order["position"]:
76
+ close = acc.close_position(order["position"])
77
+ print(elapsed(), "closed", close["status"], "at", close["fillPrice"])
78
+
79
+ # Live events (ticks, balance, positions, status) for 10 seconds.
80
+ stream = acc.stream([symbol], on_tick=lambda t: print("tick", t["symbol"], t["bid"], t["ask"]))
81
+ threading.Timer(10, stream.close).start()
82
+ stream.run()
83
+
84
+ if not os.environ.get("KEEP"):
85
+ zeta.accounts.delete(account_id) # frees the cloud terminal; positions would stay open at the broker
86
+ print("account removed")
@@ -0,0 +1,28 @@
1
+ """One WebSocket for several accounts: prices plus trading on the same connection.
2
+
3
+ pip install "zetaapi[ws]"
4
+ ZETA_API_KEY=zk_... ACCOUNT_IDS=id1,id2 python examples/websocket.py
5
+ """
6
+
7
+ import asyncio
8
+ import os
9
+
10
+ from zeta import AsyncZeta
11
+
12
+
13
+ async def main() -> None:
14
+ async with AsyncZeta(api_key=os.environ["ZETA_API_KEY"]) as zeta, zeta.ws() as ws:
15
+ for account_id in os.environ["ACCOUNT_IDS"].split(","):
16
+ await ws.subscribe(account_id, ["EURUSD", "XAUUSD"])
17
+
18
+ # Trades answer on the same socket; the SDK adds the idempotencyKey:
19
+ # order = await ws.place_order(account_id, "EURUSD", "buy", 0.01)
20
+
21
+ async for ev in ws:
22
+ if ev.type == "tick":
23
+ print(ev.account_id[:8], ev.data["symbol"], ev.data["bid"], ev.data["ask"])
24
+ elif ev.type == "status":
25
+ print(ev.account_id[:8], "status", ev.data["status"])
26
+
27
+
28
+ asyncio.run(main())