Metadata-Version: 2.5
Name: perkbridge-connect
Version: 1.9.0b1
Summary: Python client for the PerkBridge Connect Trading API: idempotent orders, strategies on a schedule, events.
Project-URL: Homepage, https://perkbridge.eu
Project-URL: Source, https://github.com/perkbridge/connect-python-client
Author: PerkBridge
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: api-client,metatrader,mt5,perkbridge,trading
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
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.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: tzdata; sys_platform == 'win32'
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: pyyaml>=6; extra == 'dev'
Requires-Dist: ruff==0.17.3; extra == 'dev'
Requires-Dist: websockets>=13; extra == 'dev'
Provides-Extra: direct
Requires-Dist: websockets>=13; extra == 'direct'
Description-Content-Type: text/markdown

# perkbridge-connect

The Python library for the PerkBridge Connect Trading API (`/v1/trading`).
Write a strategy as a small class, keep the connection in a properties file,
and run it. The library takes care of authentication, idempotency, duplicate
prevention, scheduling, reconnects, events and errors.

Status: **1.3.0b1, beta.** It has been tested against a real Control Plane with
simulator accounts, and its smoke test ran against a real MT5 demo terminal
(orders, replays, limit and cancel, close). Changing a position's stops on MT5
needs a Control Plane with perkbridge/nile#530. The DirectConnect client was
tested against nile's real proxy and trading server with a fake terminal, not
yet with a real MT5 terminal. Several accounts in one configuration (1.3.0b1)
are covered by unit tests, not yet by a run on a real Control Plane. Use demo
accounts.

```
pip install --pre perkbridge-connect   # import name: perkbridge
```

Python 3.10 to 3.13. The only runtime dependency is `httpx` (plus `tzdata` on Windows).

## Five rules the library never breaks

1. **Every order is idempotent.** The library generates the `client_order_id` and
   fsyncs it to a local journal before the request leaves the process. Any retry,
   including one after a crash and restart, reuses that key, so the same order is
   never placed twice.
2. **No invented outcomes.** An order ends in the state the API reports. When an
   answer is lost, the order is reported as `unknown` while the platform checks
   with the broker. It is never re-sent under a new key.
3. **Config is data, code is strategy.** The connection, the account, the local
   risk envelope and the schedule come from a properties file or environment
   variables. Tokens are never logged.
4. **One run at a time.** `on_run` is never called twice at once for the same
   strategy.
5. **Closing always works.** `close()` and `cancel_order()` are sent during a
   halt and after a risk rule trips, exactly as the API allows. The library adds
   no block of its own.

## Quick start

```python
from perkbridge import Config, Connect

conf = Config.load()          # ./perkbridge.properties, $PERKBRIDGE_CONFIG, env
pb = Connect(conf)            # checks the token and the account

print(pb.account().balance, pb.quote("EURUSD").ask)
order = pb.buy("EURUSD", volume="0.01", then_stops=("1.0800", None))
print(order.status)           # filled, placed, refused, rejected, ... or unknown
pb.close(pb.position("EURUSD"))
```

A strategy:

```python
from perkbridge import Context, Strategy, run

class Breakout(Strategy):
    config = {"schedule.mode": "interval", "schedule.every": "1h",
              "schedule.market_hours": "Mon-Fri 08:00-20:00"}

    def on_run(self, ctx: Context) -> None:
        bars = ctx.bars("EURUSD", "H1", limit=21)
        if ctx.position("EURUSD") is None and bars[-1].close > max(b.high for b in bars[:-1]):
            ctx.buy("EURUSD")

run(Breakout)
```

or from the command line:

```
perkbridge-run examples/breakout.py:Breakout --config examples/breakout.properties
```

See [examples/breakout.py](examples/breakout.py) for a complete strategy.

## Smoke test against your server

[scripts/smoke_test.py](scripts/smoke_test.py) checks a server and account
end to end from your own machine:

```
export PERKBRIDGE_CONNECTION_URL=https://connect.example.com/api
export PERKBRIDGE_CONNECTION_ACCOUNT=tac-xxxxxxxx
export PERKBRIDGE_CONNECTION_TOKEN_FILE=~/.perkbridge/token   # chmod 600
python scripts/smoke_test.py                  # read-only: account, symbols, quotes, bars, ...
python scripts/smoke_test.py --trade EURUSD   # plus a minimum-volume round trip, demo accounts only
```

`--trade` buys the minimum volume with `then_stops`, replays the same
`client_order_id`, moves the take profit, places and cancels a far buy limit,
and closes the position. It refuses a non-demo account and touches only what
it opened; if a step fails it closes and cancels its own position and order.
Each step prints PASS, FAIL or SKIP; the exit code is 0 only when nothing failed.

## Configuration

Settings are layered: the strategy's `config` defaults, then the file, then
`[strategy.<name>]` sections, then environment variables. Values set in code
with `Config.update()` win over all of these. Unknown keys and invalid values
are all reported at start, with a hint.

```properties
connection.url     = https://connect.example.com
connection.account = tac-7f3k2m9q
# connection.token: prefer PERKBRIDGE_CONNECTION_TOKEN or ..._TOKEN_FILE
order.default_volume     = 0.01
order.max_open_positions = 3        # local envelope, refused before sending
order.max_volume         = 0.10
order.allowed_symbols    = EURUSD, GBPUSD
state.dir = ~/.perkbridge/state

[strategy.breakout]
schedule.mode  = interval
schedule.every = 1h
```

- **Environment variables.** Every key has one: `connection.token` becomes
  `PERKBRIDGE_CONNECTION_TOKEN`. A `_FILE` suffix reads the value from a file,
  which suits Docker secrets. A value written `${env:NAME}` in the file reads
  the variable `NAME`.
- **File permissions.** A file that holds a token must not be readable by other
  users; the library refuses it and suggests `chmod 600`.
- **Plain HTTP.** Accepted only for `localhost`.
- **Checking a config.** `perkbridge-run --show-config` prints the merged
  settings and where each one came from, with the token masked.

| Group | Keys |
|---|---|
| `connection.` | `url`, `token`, `token_file`, `account`, `timeout_s`, `verify_tls`, `ca_file` |
| `order.` | `default_volume`, `expires_in_ms`, `wait_for_outcome`, `wait_timeout_s`, `strict`, `stops_watch_s`, `max_open_positions`, `max_volume`, `allowed_symbols`, `max_orders_per_run`, `duplicate_check`, `replay_window_s` |
| `state.` | `dir` |
| `schedule.` | `mode` (manual, interval, at, cron), `every`, `at`, `cron`, `timezone`, `align`, `market_hours`, `skip_if_running`, `catch_up`, `jitter_s`, `max_consecutive_errors` |
| `events.` | `enabled`, `poll_interval_s` |
| `bars.` | `cache` (default false; or `bars(..., cache=True)`), `cache_max_bars` (default 20000) |
| `log.` | `level`, `format` (text, json) |
| `account.` | `default` (the default account's alias, with several accounts) |
| `accounts.<alias>.` | `id`, `token`, `token_file`, `token_mode` |

### Several accounts

One configuration can hold several trading accounts. Each one has an alias, an
account id and its own token; `account.default` names the one that
`connection.account` stands for. A configuration without `accounts.*` keys is
the single account of `connection.*`, exactly as before.

```properties
connection.url = https://connect.example.com
account.default = main
accounts.main.id = tac-7f3k2m9q
accounts.main.token_file = ~/.perkbridge/token-main
accounts.hedge.id = tac-2h8d5k1x
accounts.hedge.token_file = ~/.perkbridge/token-hedge
```

```python
pb = Connect(conf)                      # the default account, as before
pb.buy("EURUSD", 0.1)
pb.accounts["hedge"].sell("EURUSD", 0.1)

class Pair(Strategy):
    def on_run(self, ctx):
        ctx.buy("EURUSD", 0.1)                        # the default account
        ctx.accounts["hedge"].sell("EURUSD", 0.1)     # same strategy tag, the hedge account
```

- `pb.accounts["hedge"]` is a `Connect` for that account; `pb.accounts["main"]`
  (the default) is `pb` itself. Each account keeps its own journal and state
  under `state.dir/<account id>`, so idempotency and recovery work per account.
  `pb.accounts.open_all()` checks every account at once; `perkbridge-run` does
  it at start, so a wrong token fails before the first run, by name.
- `ctx.accounts["hedge"]` is the same run on that account: same strategy tag and
  `ctx.state`, keys from that account's journal.
- Environment: `PERKBRIDGE_ACCOUNT_DEFAULT`, `PERKBRIDGE_ACCOUNTS_<ALIAS>_ID`,
  `_TOKEN`, `_TOKEN_FILE`, `_TOKEN_MODE` (`PERKBRIDGE_ACCOUNTS_HEDGE_TOKEN_FILE`).
- In a PerkBridge strategy container you set the accounts in the strategy
  editor; the library reads them from the platform file
  (`PERKBRIDGE_PLATFORM_CONFIG`). `connection.account` there is the default
  account, so the library 1.2 still runs the default one. When that variable
  names a file that is missing, the library refuses to start instead of
  running on the default account alone.
- A token or token file from a higher-precedence source (the environment, a
  later layer) replaces the other form from a lower one; both in one source is
  an error.
- `order.max_orders_per_run` counts the orders of one run on every account.
- The event feed (`on_event`) and the Time Machine use the default account.

### Bars and the bar cache

`bars(symbol, timeframe, limit)` returns the last `limit` completed bars,
oldest first. A `limit` above 1000 (the API's largest answer) is read in pages.

The bar cache is **off by default**. Turn it on for every read with
`bars.cache = true`, or for one read with `bars(..., cache=True)`
(`ctx.bars("EURUSD", "M15", 4000, cache=True)`). Cached reads (without `since`
and `until`) use a cache kept for the life of the client. The first read loads the bars; every later read
fetches only the newest 10 bars and joins them to the cached ones. A strategy
that reads 4000 M15 bars every minute then sends one small request instead of
four large ones. The join is checked before it is used:

- the new bars must reach back to the cache's last bar (more pages are read
  when many bars were missed), so no bar between the two can be missing;
- in that overlap the bar times must be the same one for one, so a bar the
  server added, dropped or moved since shows up;
- the times must rise strictly.

If a check fails, the cache for that symbol and timeframe is dropped, the bars
are read again in full and a warning is logged. The bars in the overlap are
always taken from the new answer, so a corrected last bar replaces the cached
one. A larger `limit` than before reads the history again; a smaller one is
served from the cache. `pb.bar_cache.stats` counts hits, full loads, reloads and
requests, and `pb.bar_cache.clear()` forgets the bars. A Time Machine run never
uses the cache.

### The forming bar

`bars(symbol, timeframe, limit, forming=True)` (also `ctx.bars(...)`) reads the
bar that is still forming, like the original MT5 read from position 0. It
returns one list: at most `limit` bars, oldest first, the forming bar last with
`Bar.forming = True` and `Bar.observed_until` (the time of the last tick it
holds), and `limit - 1` closed bars before it. When the terminal has no bar in
the current period (no tick yet, a weekend) the list is the `limit` closed
bars and none has `forming` set, so test `bars[-1].forming`.

```python
bars = ctx.bars("XAUUSD", "M30", limit=100, forming=True)
now_bar = bars[-1]            # forming: its values change on the next read
closed = [b for b in bars if not b.forming]
```

- It asks the API for `include_forming=true` and never sends `to`, so it
  cannot take `until` (`ValueError`); `since` filters the closed bars only. For
  a `limit` above 1000 only the newest page asks for the forming bar.
- It never uses the bar cache.
- A Control Plane that does not answer the forming bar (its answer has no
  `forming` key) raises `NotSupported`; closed bars are never returned as if
  they were current. A `forming` value that is not valid (not an object, no
  time or prices, `observed_until` before the open time, an open time not after
  the newest closed bar) raises `PerkBridgeError` with code `bad_forming_bar`.
- The Control Plane's refusals: `409 not_supported_by_terminal` (the account's
  terminal lacks the feature) raises `NotSupportedByTerminal`, which is both a
  `NotSupported` and a `Conflict`. `409 invalid_state` (an account that is not
  an MT5 account) stays a plain `Conflict`.
- `since` with `forming=True` reads one page, so `limit` must be at most 1000.
- `DirectConnect.bars(..., forming=True)` raises `NotSupported`: DirectConnect
  does not offer the forming bar yet.
- In a Time Machine run the forming bar of `ctx.now` is built from the M1 bars
  that closed before `ctx.now` inside the current period of the timeframe
  (open of the first, highest high, lowest low, last close, summed tick volume,
  `observed_until` the close of the last M1 bar). The period is taken from the
  bar series itself, so broker-aligned H4 and D1 bars work. This is an
  approximation that **misses the current minute**: its high, low and close lag
  a live forming bar. With no such M1 bar the list holds closed bars only. An
  M1 read therefore **never** has a forming bar in the local Time Machine
  (the current minute has no closed M1 bar), although live MT5 serves one.
  In a long replay, `forming=True` loads the M1 history of the whole replay
  window for the symbol, once.
- Service back-tests (`run_service_backtest`, the nile-timemachine service)
  with `forming=True` need a nile release that includes the run-route change
  of nile#1110 (ADR-030 Amendment 6, F8: `"forming": null` when asked and there
  is none). Before it, a run with no forming bar answers without the key and
  the read raises `NotSupported`.

## Orders and outcomes

- **Order calls.** `buy`, `sell`, `buy_limit`, `sell_limit`, `buy_stop`,
  `sell_stop`, `buy_stop_limit` and `sell_stop_limit` return an `Order`. By
  default the call waits until the order is final, placed or `unknown`.
  `close`, `close_all`, `modify_position`, `modify_order` and `cancel_order`
  work the same way. For modifies, `KEEP` leaves a value unchanged and `None`
  removes it.
- **Refusals and rejections.** The platform refusing an order raises
  `OrderRefused`, with `.code` and a hint. The broker rejecting it raises
  `OrderRejected`, with `.retcode`. Both carry the stored order.
- **Stops on market orders.** When a symbol does not support stops on a market
  order, the order is refused before it is sent (`StopsNotSupported`). Use
  `then_stops=(sl, tp)` instead: it places the order, then modifies the
  position. The stops are journaled with the order. If the order has not
  filled when the call returns, they are set once it fills, and exactly once,
  with the key `<key>-s`. This is checked on start, after `wait()`, on order
  events, before each strategy run, and by `pb.apply_pending_stops()`. An order
  that ends without a fill drops its stops.

  While stops are waiting, a background watcher thread (a daemon) retries
  every `order.stops_watch_s` (2 s by default), so a direct `Connect` user
  needs no further call. The watcher stops when nothing is pending or on
  `close_session()`. Closing, or the process ending, with stops still pending
  logs a warning: those positions are not protected until a `Connect` for the
  same account and `state.dir` starts again and resumes them. With
  `order.stops_watch_s = 0`, the caller must call `apply_pending_stops()` or
  `wait()` itself.

  If the stops fail during the `buy()` call itself, the call raises
  `StopsNotSet`, whose `.order` is the order that WAS placed. Do not place it
  again. Inside a strategy, the same intent returns that order instead of
  opening a second position. Stop intents that are not resolved, and orders
  that are not final yet, are never pruned from the journal, however old they
  are.

  The stops count as set only when the platform reports the modify as
  `done`. While the modify is queued, sending or unknown, it stays pending
  and is followed up with the same key. These cases are handled as follows:

  - **Nothing sent.** Another order was in flight, or the platform rate
    limited the request. The modify is retried later.
  - **Refused, rejected or expired.** The modify was definitely not applied. It
    is retried with a fresh key (`<key>-s2`, `-s3`, ...), waiting 5 s, 15 s,
    60 s, then 300 s between attempts.
  - **Permanent refusal.** For example `stops_invalid` or
    `position_not_found`. The library gives up and logs an error saying the
    position is open without its stops.
  - **Too many attempts.** After 20 attempts it also gives up with that error.
  - **Position already closed.** The stops are dropped.

  - `pb.pending_stops()` lists the stops that are still being worked on.
  - `pb.stops_status()` lists every intent with its state: `pending`,
    `failed`, `set`, `dropped` or `resolved`.
  - `pb.stops_needing_attention()` lists positions left open without the
    stops the library gave up setting. Each one stays listed, across restarts
    and journal pruning, until its position is seen closed. Each one is also
    logged as an error on start and before every strategy run.
  Reusing a `client_order_id` with different `then_stops` raises
  `IdempotencyConflict`.
- **Unknown outcomes.** An `unknown` outcome is returned as an order with
  `.unknown` true, or raised as `OutcomeUnknown` when `order.strict = true`. The
  platform settles it, and `pb.wait(order)` or the events follow it.
- **Duplicate intents.** Inside one strategy run, the same intent made twice
  returns the first order (`order.duplicate_check`). If the first call ended
  without a known outcome (`ConnectionLost`, `OutcomeUnknown`), the same intent
  reuses the first call's key, so the platform answers with that order instead
  of placing a second one. Only a definite "not placed" (refused, rejected,
  never sent) frees the intent for a new order.
- **Local envelope.** The envelope is checked inside the account's submission
  lock, so two threads cannot both pass `order.max_open_positions`. It applies
  only to a new intent: a replay of a `client_order_id` that is already
  journaled returns the stored order even when the limit has been reached.
- **One order in flight.** While an order of the account is still `sending`
  or `queued`, the next order raises `InFlight` instead of queueing. This also
  applies after `wait()` times out and after a restart, because the journal
  remembers the order. An `unknown` outcome is left to the platform, which
  refuses new orders with `reconciliation_pending` while it checks.
- **`close_all`.** It closes positions one by one and stops at the first
  close whose outcome is not known (a lost answer, or `unknown`). That close
  stays journaled and is resolved with its key before anything else is sent.
- **Keys that are never reused.** A journaled key whose request never got an
  answer follows the restart rules even when it is reused at once: it is
  looked up by key, replayed only while it is younger than
  `order.replay_window_s`, and abandoned otherwise. An abandoned key raises
  `OrderError` (`intent_abandoned`) and is never sent again; a new order needs
  a new key. Derived keys, such as `<key>-s` for stops, stay unique for keys
  near the 128-character limit, because they include a digest of the whole
  key.
- **Restarts.** On start, `Connect` reads the journal. An entry that never got
  an answer is looked up by its key first. It is replayed with the same key only
  if it is younger than `order.replay_window_s` (120 s by default); otherwise it
  is reported and abandoned.

## Strategies and the scheduler

`Strategy` has four callbacks: `on_start`, `on_run`, `on_event(ev)` and
`on_stop`.

- **The context.** `ctx` exposes the reads and orders, scoped to the
  strategy's own positions unless `all=True`. It also has `ctx.state`, a dict
  persisted between runs, plus `ctx.run_number`, `ctx.now` and `ctx.log`.
- **Schedules.** `interval` (aligned to the clock by default), `at` (fixed
  times), `cron` (five fields) and `manual`. All of them honour
  `schedule.timezone` and daylight saving time, and can be limited with
  `schedule.market_hours`.
- **Missed and failing ticks.** A tick that overruns is skipped, not stacked.
  Missed ticks after a sleep run once at most, or are skipped. After
  `schedule.max_consecutive_errors` errors in a row, the strategy pauses with a
  clear log line.
- **Control Plane unreachable.** The tick is skipped with one log line. Nothing
  is closed or retried blindly.
- **Events.** They come from the account's event feed, with a saved cursor, so
  none are lost across restarts. A cursor that is too old resynchronises and
  delivers a `sync.resumed` event.

## Time Machine

Replay a strategy over a past window with `ctx.now` set to each past tick:

```
perkbridge-run examples/breakout.py:Breakout -c examples/breakout.properties \
    --time-machine from=2026-10-01 to=2026-10-31 step=1h
```

- **Data.** Bars come from the API, and only bars closed before `ctx.now` are
  visible (`forming=True` adds an approximate forming bar, see "The forming bar"). Quotes are synthetic, built from the last M1 close plus the live
  spread.
- **Fills.** A local simulator fills market, limit, stop and stop-limit orders
  and SL/TP on M1, M15 or H1 bars, depending on the window length.
- **No real orders.** Nothing is sent to the platform. `orders=none` only logs
  the intents.
- **Output.** The report is written to
  `state/<account>/strategies/<name>/time-machine/<from>_<to>/report.json`.

It is a sanity replay, not a backtester: there are no swaps, commissions or
slippage model.

## Back-tests on a TimeMachine service

`nile-timemachine` is a separate PerkBridge service (Docker image and Compose
example in the nile repository, `deployments/timemachine`). It serves the same
Trading API on virtual accounts in historical time: fills from recorded ticks
on both price sides, pending orders, SL/TP, margin and stop-out, commission and
swap, the risk policy, and a run report with a reproducible fingerprint. The
same strategy class runs there unchanged:

```python
from datetime import datetime, timezone
from perkbridge import Config, ServiceRun, TimeMachineService, run_service_backtest
from breakout import Breakout

svc = TimeMachineService("https://127.0.0.1:8443", open("secrets/admin-token").read().strip(),
                         ca_file="secrets/tls.crt")
spec = ServiceRun(dataset_id="tmd-...", profile_id="tmp-demo-fx", profile_version=1, symbols=("EURUSD",),
                  start=datetime(2025, 3, 11, tzinfo=timezone.utc), end=datetime(2025, 3, 14, 20, tzinfo=timezone.utc),
                  balance="10000.00", currency="USD", leverage=100, margin_mode="hedging", seed=7)
settings = Config.load().resolve("breakout", strategy_defaults=Breakout.config)
result = run_service_backtest(Breakout(), settings, svc, spec, step=3600)
print(result["report"]["fingerprint"])
```

- **Time.** The service creates a run with its own account (`tma-…`) and run
  token (`nile_tmt_…`, never written to disk). Each schedule tick sends every
  request with `X-TimeMachine-At` = the tick; a later tick processes everything
  in between (fills, stops, swap at rollover). After `on_stop` the clock is
  advanced to the run's end, so the report covers the whole requested range,
  also when the last tick is earlier or the strategy paused. If that advance fails,
  `run_service_backtest` raises `BacktestIncomplete` instead of returning: no
  report or fingerprint is returned, `result.json` says `"complete": false`,
  and the run is kept on the service (also with `delete_run=True`). A returned
  result always has `"complete": true`.
- **Determinism.** Order keys do not depend on the run id and pending
  `then_stops` are applied at every tick (also when `on_run` raised), never by
  a background thread, so equal inputs give an equal fingerprint.
- **Output.** The service's report (costs kept apart, orders by outcome,
  trades, balance curve, fingerprint) is returned and written to
  `state/<tma-account>/strategies/<name>/timemachine-service/<run>/result.json`.
  The run is kept on the service unless `delete_run=True`, which deletes it
  also when the back-test fails (the original error is raised).
- **Transport.** `https://` to any host; plain `http://` only to a loopback
  host itself (`localhost`, `127.0.0.0/8`, `::1`). A URL with a user name or
  password is refused.
- **Isolation.** The service has no broker and no credentials. The Control
  Plane refuses a run token and the `X-TimeMachine-At` header.

`tests/timemachine` runs the breakout example twice against a real service
(`tests/timemachine/nile-timemachine.sh start DIR`, from a nile checkout) and
checks the fingerprints are equal.

## Command line

```
perkbridge-run TARGET [--config FILE] [--set KEY=VALUE ...]
               [--check | --show-config | --once | --time-machine ... | --reset-state --yes]
```

- **Target.** `TARGET` is `module:Class` or `file.py:Class`, with
  `Class1,Class2` for several strategies.
- **Exit codes.** 0 means OK, 1 an error, 2 a configuration error and 130
  interrupted.
- **Logs.** They are JSON when stdout is not a terminal.
- **Tokens.** `--set connection.token=...` is refused: tokens do not belong on
  command lines.

## Running in a container

The library is built to run in a container later, with no code change:

```yaml
services:
  breakout:
    image: python:3.12-slim          # an official image will follow
    command: perkbridge-run /app/breakout.py:Breakout
    environment:
      PERKBRIDGE_CONFIG: /app/perkbridge.properties
      PERKBRIDGE_CONNECTION_TOKEN_FILE: /run/secrets/perkbridge_token
      PERKBRIDGE_STATE_DIR: /state
    volumes: ["./app:/app:ro", "state:/state"]
    secrets: [perkbridge_token]
    stop_grace_period: 30s
volumes: {state: {}}
secrets: {perkbridge_token: {file: ./token}}
```

Keep `state.dir` on a volume: the idempotency journal is what makes a restart
safe. The library warns when it runs in a container with the default `state.dir`.

## On the PerkBridge platform (1.4)

In a strategy deployed from the dashboard (Strategies), the platform mounts
`platform.properties` and sets `PERKBRIDGE_PLATFORM_CONFIG`. With it the
library:

- tags every order with the platform label `<name>_v<version>` (the Trading
  API refuses any other tag for a strategy token), and reads (`ctx.positions()`,
  `ctx.position()`, `ctx.orders()`, `ctx.history()`, `ctx.close_all()`,
  `order.max_open_positions`) include the positions and orders of every
  version of the strategy, so version 4 sees what version 3 opened;
- gives the parameters of the strategy's Spec as `ctx.params`, with their
  types (`ctx.params.fast` is an `int`, `0.01` a `Decimal`, booleans are
  `bool`); secret parameters are read from their files at start and never
  shown by `repr`;
- fires the events connected in Workspace > Events:

| Source | Fired by | `on_run` | `on_event` |
|---|---|---|---|
| `schedule` | the library, on the server (`every`, `at` + `weekdays`, `cron`, `timezone`, `align`, `catch_up`, `market_hours`, `offset`: fire each tick that much later, such as `15s`) | a run, as a scheduled tick | `PlatformEvent(source="schedule")` |
| `trading` | the library, from the account's event feed (`events: order.filled,...`) | a run | `PlatformEvent(source="trading")`, `ev.trading` is the feed `Event` |
| `ingress` (webhook) | polled from the Control Plane, acknowledged after the handler | a run | `PlatformEvent(source="ingress")`, `ev.json()` / `ev.text` |
| `manual` (Run now) | the same | a run | `PlatformEvent(source="manual")` |

```python
class SmaCross(Strategy):
    def on_run(self, ctx):                 # schedule events with handler on_run
        ...
    def on_event(self, ctx, ev):
        if ev.source == "ingress":         # a webhook
            signal = ev.json() or {}
```

Webhook and Run now deliveries are at least once. Orders placed while one is
handled get the key `<strategy id>-d<delivery id>-<n>`, the same on every
redelivery, so a redelivered event never places a second order. A handler that
raises is tried four times (1, 2, 4 s apart), then the delivery is acknowledged
as `failed: ...` and shows as failed on the event's page, where it can be
replayed. A lost connection leaves it unacknowledged: it is delivered again.
Events listed in `<state.dir>/control/events.disabled` (Pause now) are skipped.
With events connected, the account feed's own events reach `on_event` only when
the class lists them in `Strategy.events`.

### Trading mode (1.7)

A strategy on the platform runs in practice (`dry`) or with real trades
(`live`). `ctx.trading_mode()` reads it from the Control Plane on every call,
so a switch made in the dashboard is seen at once. It has three states:

| Value | Meaning | What to do |
|---|---|---|
| `None` | not on the platform (plain `run()`, the Time Machine) | trade normally |
| `"live"` | real trades | trade |
| `"dry"`, or anything else | practice | record what you would do |

```python
def on_event(self, ctx, ev):
    mode = ctx.trading_mode()
    if mode is not None and mode != "live":    # practice on the platform
        ctx.log.info("practice: would buy EURUSD 0.10")
        return
    ctx.buy("EURUSD", "0.10")
```

In `dry` the Control Plane itself refuses, with `409 strategy_dry_mode`, every
order that opens exposure and every change of a resting pending order. It
does **not** stop the rest: closing a position, cancelling an order and
changing a position's stop loss or take profit still reach the broker, and
pending orders left from live mode stay at the broker. Do not call them as
"practice". A refused open is raised as `Conflict` with
`.code == "strategy_dry_mode"` (not `OrderRefused`).

Each call is one GET to the Control Plane and counts towards rate limits:
read it once per run or event, not in a loop.

`ctx.strategy_self()` gives the whole answer (`desired_state`, `label`, ...);
on `ctx.accounts["hedge"]` it reads through the default account's strategy
token, so its `account_id` is the default account. A failed read raises like
any other read. A Control Plane before `strategy-self` (nile#803) answers
`NotFound`, as it does for a strategy being removed.

Quotes carry `tick_value_profit` and `tick_value_loss` (runtime NileTrade
1.7.0 or later, else `None`): what a move of one `tick_size` is worth for one
lot in the account currency. The money at risk of a stop is
`distance / symbol.tick_size * quote.tick_value_loss * volume`.

### Risk protection, sizing from risk and dry run (1.8)

Each account of a platform strategy has a **risk protection**, set in the
dashboard (strategy › Accounts › Risk protection) and read with `ctx.risk`:

| `ctx.risk.mode` | Who decides volume and stops | What to call |
|---|---|---|
| `custom` (default, every existing strategy) | your code, as before | `ctx.buy` / `ctx.sell` / `place_order`; `ctx.size_for` helps |
| `embedded` | the values set in the dashboard | `ctx.trade` |

`ctx.risk` is `None` off the platform. Its values (`per_position`,
`reward_risk`, `entry_types`, `max_volume`, `protection`) are those of the
spec revision the strategy was started with; a change applies at the next
restart.

```python
def on_event(self, ctx, ev):
    # Embedded: say what to trade; the platform's values decide how much.
    ctx.trade("EURUSD", "buy", stop_loss="1.08250")                         # market
    ctx.trade("EURUSD", "sell", entry="limit", price="1.09000", stop_loss="1.09200")
```

`ctx.trade(symbol, side, stop_loss=..., entry="market"|"limit"|"stop", price=...)`:

- **Volume** risks `risk.per_position` (money, or a percent of the balance or
  equity read fresh) at the stop. `E` is the ask (buy) or bid (sell) of a fresh
  quote for a market entry, or `price` for a pending one:
  `loss_per_lot = |E - SL| / tick_size * tick_value_loss` (from the same
  quote), `volume = risk / loss_per_lot` rounded **down** on the broker's grid
  (`volume_min + n * volume_step`), capped by `max_volume` and the symbol's
  `volume_max`. Below `volume_min` it does not trade (`RiskRefused`
  `size_below_minimum`); it never rounds up to the minimum.
- **Take profit** `TP = E ± reward_risk * |E - SL|` (none without
  `reward_risk`), the distance rounded down to the tick.
- The account's **protection** (break-even, trailing ...) travels with the
  order as a bracket.
- The inputs and the computed volume and take profit are **journaled** under
  the order's key before the first send. The same key again (a redelivered
  event, a retry after a crash) sends the journaled request: it never resizes
  on a moved quote or a new risk revision. Other inputs under the same key (a
  stop computed from the live quote) raise `IdempotencyConflict`; keep a
  signal's stop in the event or in `ctx.state`.
- It raises `RiskRefused` (nothing sent) with `risk_mode_custom` (the account
  is Custom, or not on the platform), `entry_type_not_allowed`, `stale_quote`
  (no tick value, or the quote is older than 5 s), `volume_unit_unsupported`
  (volumes not in lots), `symbol_spec_incomplete`, `stop_loss_wrong_side` or
  `size_below_minimum`.

The loss at the stop is **about** the risk, not at most: slippage, gaps,
commissions and exchange-rate moves can make it larger.

`ctx.size_for(symbol, entry, stop_loss, risk=...)` computes the same volume
without sending anything, in either mode: `risk` is money, `{"value": 1,
"unit": "percent_balance"}` (or `percent_equity`), or `None` for the account's
Embedded risk per position. It returns a `Sizing` (`volume`, `loss_per_lot`,
`risk_money`, `risk_at_volume`, `capped_by` ...). `size_position()` and
`take_profit()` are the pure functions behind them. In a Time Machine run the
simulated quotes carry no tick value, so sizing raises `stale_quote` there.

**Dry run.** `ctx.dry_run` is `True` while the strategy is in dry run on the
platform (any trading mode but `live`), read from the Control Plane and
reused for at most 2 seconds; `False` off the platform. In dry run:

- `ctx.trade` sends nothing and returns a `WouldPlace` (`key`, `body`,
  `volume`, `reason`, `sizing`): what it would have sent. It is not an order:
  no order id, no position. It is journaled under the order's key and is final
  for it: the same event delivered again after a switch to live still sends
  nothing.
- Any other order call that the Control Plane refuses as dry
  (`409 strategy_dry_mode`) raises `DryRunRefused` (a `Conflict`, with
  `.would_place`), journaled the same way and never sent later. Raised out of
  `on_run` or `on_event` it ends the run or the delivery normally: the delivery
  is acknowledged, not retried and not marked failed. The same call again in
  that run or delivery raises it again without a send, even after a switch to
  live (`allow_duplicate=True` sends a new order).
- The `accounts.<alias>.risk.*` keys are checked at start: an unknown key or
  an empty value stops the strategy instead of trading on a guess.

### Metrics (1.6)

`run()` writes `<state.dir>/metrics.json` (schema `perkbridge.metrics/v1`)
after every run and every 30 seconds; the strategy's Metrics tab shows it.
Nothing to add to your code. The numbers cover the whole process over the last
hour:

| Field | Meaning |
|---|---|
| `run_number` | the last `on_run` number |
| `last_run_ms` | how long the last `on_run` took |
| `busy_ratio_1h` | share of the last hour spent in `on_run` and `on_event` (0 to 1) |
| `api_calls_per_min` | HTTP requests to the Control Plane per minute, retries included |
| `api_errors_1h` | requests that failed: no connection, or an answer of 400 or above other than 429 |
| `rate_limited_1h` | requests answered 429 |
| `last_error` | the last exception of a callback in the hour, at most 300 characters |
| `reported_at` | when the file was written (UTC) |

The file is replaced atomically; a write failure is logged once and never stops
the strategy.

## DirectConnect

DirectConnect is the low-latency channel to the account's trading server.
It is a WebSocket to the organization's DirectConnect proxies instead of the
Control Plane's REST API. It needs the `direct` extra and a DirectConnect
token (`nile_tdc_…`, from *API tokens* in the dashboard). REST tokens do not
work on DirectConnect.

```bash
pip install --pre "perkbridge-connect[direct]"
```

```python
from perkbridge.direct import AccountView, DirectConnect

dc = DirectConnect(
    ["wss://direct-1.example.com:8444/v1/direct", "wss://direct-2.example.com:8444/v1/direct"],
    token,                                   # nile_tdc_…
    ca_file="directconnect-ca.crt",          # "Download CA" in the dashboard, when needed
    state_dir="~/.perkbridge/direct",        # the order journal: keep it
)
with dc:
    order = dc.buy("EURUSD", "0.01", stop_loss="1.0500")
    print(order.state, order.ticket, order.elapsed_ms)
    dc.modify_position(str(order.ticket), take_profit="1.0900")
    dc.close_position(str(order.ticket))

    view = AccountView()
    for ev in dc.events(timeout=30):         # subscribes on first use
        view.apply(ev)                       # rebuilds itself on a gap or reconnect
        print(ev.event, sorted(view.positions))
```

[`examples/directconnect.py`](examples/directconnect.py) is a complete example. It reads the account, symbols, bars, positions and deals, then shows the live events. With `--trade` it also buys the minimum volume and closes it again (demo accounts):

```bash
python examples/directconnect.py --symbol EURUSD --timeframe H1 --bars 24 --events 60 --trade
```

[`examples/directconnect_settings.py`](examples/directconnect_settings.py) is the same example with its settings written in the file instead: fill in the block at the top (proxy URL, token, CA file, symbol, timeframe, how long to show events, `TRADE`) and run `python examples/directconnect_settings.py`. Keep a file with a token in it private.

`DirectConnect.from_env()` reads `PERKBRIDGE_DIRECT_URLS` (a comma-separated
list), `PERKBRIDGE_DIRECT_TOKEN`, and optionally `PERKBRIDGE_DIRECT_CA` and
`PERKBRIDGE_DIRECT_STATE_DIR`.

What the client does for you:

- **Proxies.** It connects to the first proxy that answers. On a lost
  connection it reconnects to the next one, and subscribes again if you
  were subscribed.
- **Order IDs and resends.** Each order gets a UUIDv7 `client_order_id`.
  The order is resent with the SAME ID until it is final when:
  - the connection is lost,
  - there is no answer,
  - the server sends a retryable error such as `server_unavailable` or
    `rate_limited` (resent after `retry_after_ms`);
  - an answer is lost on a live connection (each send waits at most
    `answer_timeout`, 5 s by default).

  The trading server never executes an ID twice. IDs the server will never
  execute raise `OrderIdUnusable` and are not resent:
  `stale_client_order_id`, `id_used_order_not_held`, and an invalid or
  future ID.
- **Journal.** With `state_dir`, the ID and body are fsynced to a journal
  before they are sent. `connect()` settles orders that an earlier run left
  without a final state, and asks the server about each one first:
  - **Final:** recorded as it is.
  - **Held by the server:** resent with its ID.
  - **Never received:** sent with its ID only while its `expires_in_ms` has
    not passed. After that it is recorded `not_received`.

  New orders raise `InFlight` while an earlier one is still unresolved.
  Without `state_dir` the same bookkeeping is kept in memory: unresolved
  orders still block new ones, but a restart forgets them.
- **Outcomes.** Outcomes raise the same errors as REST: `OrderRejected`,
  `OrderRefused` and `OrderExpired`. If no final state arrives within
  `order_timeout`, `OrderUnresolved` is raised. It carries the
  `client_order_id`: resend it with `resend()` or `recover()`, and never place
  the same order under a new ID.
- **Status without sending.** `order_status(client_order_id)` reads the
  ledger without sending the order. It returns `None` when the server never
  received the ID.
- **Reads.** These come from the terminal: `account()`, `positions()`,
  `resting_orders()`, `symbols()`, `bars()` (closed bars; `forming=True` raises
  `NotSupported`) and `deals()`. Positions and
  orders may be a few seconds behind the broker. `read(what, params)` returns
  the raw answer.
- **Events.** `events()` yields `snapshot`, `order`, `position`, `account`
  and `interrupted`. An event with `rebuild=True` (a gap, a new stream, an
  interruption or a reconnect) means: discard what you built and wait for the
  next snapshot. `AccountView` does this for you.

Positions are named by their broker ticket (`position_id`), and pending
orders by the platform's `order_id`. There are no quotes, exposure or risk
reads on DirectConnect; use `Connect` (REST) for those. `Strategy` and
`run()` still trade through REST. DirectConnect needs nile's DirectConnect
feature and a proxy deployed from the dashboard.

## Low-level API

`pb.api` is a thin typed client with one method per public operation of the
Trading API, for example `pb.api.list_orders(...)` and
`pb.api.place_order(body)`. It handles authentication and retries but adds no
journal.

## Development

```
python -m venv .venv && . .venv/bin/activate
pip install -e '.[dev]'
ruff check . && ruff format --check . && mypy src && pytest
```

- **Unit tests** (`tests/unit`) use an in-process fake API and run anywhere.
- **Contract tests** (`tests/contract`) run against a real Control Plane with
  simulator accounts, built from the private `perkbridge/nile` source with
  `tests/contract/nile-sim.sh`. They are skipped unless `PB_CONTRACT_URL` is
  set.
- **Specification.** See [docs/SPEC.md](docs/SPEC.md).

## Licence

Apache-2.0
