Metadata-Version: 2.4
Name: tickwire
Version: 0.1.0
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).
Author-email: Tickwire <hello@tickwire.io>
License-Expression: MIT
Project-URL: Homepage, https://tickwire.io/
Project-URL: Documentation, https://tickwire.io/docs/sdk-python/
Project-URL: Changelog, https://tickwire.io/docs/changelog/
Keywords: metatrader,mt4,mt5,trading,api,sdk,ai-agents
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Requires-Dist: websockets<18,>=12
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Dynamic: license-file

# tickwire (Python SDK)

Typed clients for the Tickwire MT4/MT5 API: one API for both platforms,
truthful health, idempotent trading, an audit trail, agent keys with pre-trade
hooks, and signed webhooks. Sync and async.

**Not published yet.** `pip install tickwire` won't find it. Install from source, from the
repository root:

```
pip install ./sdk/python
```

Once it is published:

```
pip install tickwire
```

Python 3.11 or newer. MIT licensed. Docs: [tickwire.io/docs/sdk-python](https://tickwire.io/docs/sdk-python/).

## Quick start

A free sandbox (no sign-in, no card) against the public API, then a first trade:

```python
from tickwire import Tickwire, sandbox_signup, trade_succeeded

API = "https://api.tickwire.io"
sb = sandbox_signup(API)                     # a twsk_ key (shown once: keep it) and one simulated MT5 account
with Tickwire(API, sb["apiKey"], actor="quickstart") as tw:
    acc = tw.account(sb["account"]["id"])    # MT4 and MT5 look the same
    print(acc.health()["status"])            # healthy | stale | disconnected | down
    print(acc.price("EURUSD"))
    r = acc.market_order("EURUSD", 0.01, reason="quickstart")   # Idempotency-Key generated for you
    print(trade_succeeded(r), r["numericCode"])
```

`sandbox_signup` is anonymous and rate limited (5 sandboxes an hour per
address), so call it once and reuse the key. With your own API key, skip it:
`Tickwire("https://api.tickwire.io", "YOUR_API_KEY")`, or set
`TICKWIRE_API_URL` and `TICKWIRE_API_KEY` and call `Tickwire()`. Then
`tw.list_accounts()` lists your accounts.

`sandbox=True` reads the sandbox URL from `sandbox_url=` or
`TICKWIRE_SANDBOX_URL` (it never guesses a host) and raises `ConfigError` if
neither is set.

## 60 seconds: an AI agent with its own key

The account owner creates a scoped agent key; the agent can then trade only
through the guarded path (kill switches, the owner's pre-trade hook, audit).
This needs your own API key: the restricted key from `sandbox_signup` cannot
create agent keys.

```python
from tickwire import AgentClient, Tickwire

API = "https://api.tickwire.io"
with Tickwire(API, "YOUR_API_KEY") as owner:
    created = owner.create_agent_key("my-agent", [account_id], reason="new agent")
    agent_key = created["key"]                          # twag_…, shown once: store it now

with AgentClient(API, agent_key) as agent:
    r = agent.trade(account_id, {"actionType": "ORDER_TYPE_BUY", "symbol": "EURUSD", "volume": 0.01},
                    reason="breakout above the Asian range")
    if r.outcome == "applied":
        print("filled", r.evidence)
    elif r.outcome == "held":
        print("waiting for approval", r.hold_id)
    elif r.outcome == "rejected":
        print("not executed:", r.error, "sent:", r.sent)
    else:                                               # unknown: it MAY have executed
        print(agent.trade_status(r.idempotency_key))    # never retry with a new key
```

Async: `AsyncTickwire` and `AsyncAgentClient` have the same methods
(`async with …`, `await …`), plus resumable streams:

```python
async with AsyncTickwire(API, "YOUR_API_KEY") as tw:
    async with tw.account(account_id).stream() as s:    # stream protocol v2
        state = await s.wait_synchronized()
        s.on("positionUpdated", lambda frame, st: print(frame["position"]))
```

## What it covers

| Area | Methods |
|---|---|
| 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` |
| Control plane | `list_accounts`, `get_account`, `list_webhooks`, `get_webhook`, `create_webhook`, `delete_webhook` |
| 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` |
| 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` |
| Guarded execution | `execute_trade` (returns a `TradeResult`) |
| Sandbox, connected AI apps | `sandbox_signup()` (module function, no key needed), `sandbox_info`, `create_sandbox_key`, `list_connected_apps`, `disconnect_connected_app` |
| Dedicated IPs, billing | `dedicated_ips`, `move_accounts_to_dedicated_ip`, `billing_summary` (read-only) |
| Agent API (`AgentClient`) | `me`, `accounts`, `snapshot`, `health`, `account_information`, `positions`, `orders`, `price`, `specification`, `deals`, `trade`, `trade_status`, `audit` |

### Pagination

Native `/v1` lists (agent keys, pre-trade hooks, holds, kill switches, the
agent audit log, connected apps, `AgentClient.accounts`) return one page:
`{"data" | "entries" | "apps" | "accounts": [...], "has_more", "next_cursor"}`.
Pass `limit=` (1 to 500, default 100) and `cursor=`, or let `pages` follow the
cursor for you:

```python
for page in tw.pages(tw.list_holds, status="pending", limit=100):
    for hold in page["data"]:
        ...
# async: async for page in tw.pages(tw.list_agent_keys): ...
```

### Snapshot

`tw.account(id).snapshot()` (or `AgentClient.snapshot(account_id)`) returns
account information, positions, orders, health and server time in one read,
each section with `status` (`ok`, `stale`, `unavailable`), `read_at` and
`age_ms`. The broker's UTC offset is explicit
(`server_time["data"]["brokerUtcOffsetMinutes"]`, `None` when unknown).

Every call maps to an operation in `tickwire/_operations.py`, generated from
the public OpenAPI spec ([tickwire.io/openapi.json](https://tickwire.io/openapi.json)).

## Safety you get by default

- **Idempotency.** Every mutation sends `Idempotency-Key` (yours, or a
  generated `tw_…`), `X-Actor` and `X-Reason`. Pass `idempotency_key=` to make
  a repeat of the same decision safe across restarts.
- **Retries only when safe.** Reads retry on transport errors and
  408/429/502/503/504 with full-jitter backoff (`Retry-After` honoured up to
  the cap), within a per-client `RetryBudget` so an outage cannot become a
  retry storm. A mutation retries only when the server confirms it did not
  run it, always with the same key: connection refused; `409
  idempotency_in_flight` (the first attempt is still running, so the SDK
  waits `Retry-After` and then gets that attempt's stored result); or a
  429/5xx whose body says explicitly `sent: false` (error codes alone
  never count).
- **`unknown` is never retried.** A lost reply to a mutation (read timeout,
  reset) or any other 408/5xx raises `OutcomeUnknown` carrying the
  idempotency key; the
  guarded trades (`execute_trade`, `AgentClient.trade`) return
  `TradeResult(outcome="unknown", sent="unknown")` instead.
- **Streams resume.** `AccountStream` re-subscribes with the last `seq`; a gap
  forces a full resync, so the mirror is never silently wrong.
- **Typed errors** (`NotFound`, `Conflict`, `NotSupportedOnMt4`,
  `RateLimited`, `ConfigError`, …) keep the server envelope in `.body`.
  `health()` returns the body of a 503: "down" is an answer, not an exception.
- **Webhooks:** `verify_webhook(secret, headers, body)` checks the HMAC-SHA256
  signature and rejects replays outside a 5-minute window.
- **Clean close.** `close()` / `aclose()` release every connection and are
  idempotent. Credentials never appear in `repr()`.

A bare control plane (no gateway) serves the FxSocket routes at the root:
pass `control_prefix=""`.

## Examples

A prop-firm risk guard (flatten on daily drawdown), a trade copier, a journal
sync and a trading bot: [tickwire.io/docs/guides/examples](https://tickwire.io/docs/guides/examples/).
Demo accounts only.
