Metadata-Version: 2.5
Name: perkbridge-connect
Version: 1.0.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'
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.0.0b1, beta.** It has been tested against a real Control Plane with
simulator accounts. It has not yet been run against a real MT5 terminal.
Use demo accounts.

```
pip install perkbridge-connect      # once published; 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.

## 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`, `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` |
| `log.` | `level`, `format` (text, json) |

## 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. 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.

## 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`.

## 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
