Python library
perkbridge-connect is the official Python library for the PerkBridge Trading API. Write a strategy as a small class, keep the connection in a properties file, and run it on a schedule. The library handles authentication, safe order keys, duplicate prevention, reconnects, events and back-tests.
1. Introduction
perkbridge-connect talks to the same Trading API as your own HTTP code would, but it takes care of the parts that are easy to get wrong in a trading program: every order gets a key that is saved to disk before it is sent, a lost answer is never turned into a second order, and a restart picks up exactly where the program stopped. You write the trading idea; the library runs it.
You can use it in two ways:
- As a client. Connect gives you the account, prices, bars, positions and orders, and methods such as buy() and close(). Good for scripts, notebooks and your own programs.
- As a strategy runner. You subclass Strategy and implement on_run. The library calls it on a schedule (every hour, at fixed times, or by cron), delivers account events to on_event, keeps your state between runs, and can replay the strategy over the past.
Install
The package name is perkbridge-connect and the import name is perkbridge. --pre is needed while the library is in beta. This page describes 1.5.0b2 (published 10 Nov 2026); check your version with pip show perkbridge-connect. What came in which version:
| VERSION | WHAT IT ADDED |
|---|---|
| 1.5 | Bar cache (off by default since 1.5.0b2), bars() above 1000 bars, schedule offset for platform events |
| 1.4 | Strategies run by the PerkBridge platform: version label on orders, typed ctx.params, events connected under Events (section 8) |
| 1.3 | Several accounts in one configuration (section 4), connection.token_file |
| 1.2 | The DirectConnect client (section 10) |
| 1.1 | Back-tests on a TimeMachine service (section 9) |
It works with Python 3.10 to 3.13 on Linux, macOS and Windows. Its only dependency is httpx (and tzdata on Windows). The licence is Apache-2.0. The package is on PyPI.
Five rules the library never breaks
- Every order is idempotent. The library makes the client_order_id and writes it to a local journal on disk before the request leaves the process. Any retry, also after a crash and restart, uses the same key, so the same order is never placed twice.
- No invented outcomes. An order ends in the state the platform reports. When an answer is lost, the order is reported as unknown while the platform checks with the broker. It is never sent again under a new key.
- Config is data, code is strategy. The connection, the account, a local risk envelope and the schedule come from a properties file or environment variables. Tokens are never logged.
- One run at a time. on_run is never called twice at once for the same strategy.
- Closing always works. close() and cancel_order() are sent during a halt and after a risk rule trips, exactly as the platform allows. The library adds no block of its own.
2. Quick start
You need an API token for one trading account, with Full access if the program places orders. Create it on the API tokens page of the dashboard (see API tokens). Keep the token out of your code: put it in a file only you can read.
Then write perkbridge.properties in your project directory. The API is served under /api on your dashboard address; the account id starts with tac- and is shown on the account's page.
The token stays out of the file: PERKBRIDGE_CONNECTION_TOKEN_FILE points the library at the token file. Check everything before you trade:
A first script:
Config.load() reads ./perkbridge.properties (or the file named in $PERKBRIDGE_CONFIG) and the environment. Prices and volumes can be strings, Decimal or numbers; the library sends them as exact decimal strings and returns Decimal values.
3. A real example: a breakout strategy
This is the example shipped with the library, examples/breakout.py. Once an hour, during London trading hours, it looks at the last 21 closed H1 bars of EURUSD. When the last bar closes above the highest high of the 20 bars before it, it buys and puts the stop loss at the bottom of that range. When a bar closes below the range, it closes the position.
Its properties file, examples/breakout.properties. The token is not in it.
What to do with it, in this order:
- Check the configuration, the token and the account: perkbridge-run examples/breakout.py:Breakout -c examples/breakout.properties --check.
- Replay last month in the Time Machine. Nothing is sent to the account: ... --time-machine from=2026-10-01 to=2026-10-31 step=1h. Read the report (section 9).
- Run once on the demo account and look at the log and the dashboard: ... --once.
- Run it on its schedule: perkbridge-run examples/breakout.py:Breakout -c examples/breakout.properties. Stop it with Ctrl-C or SIGTERM; it finishes the current run first.
What the library adds without a line of code: each order carries strategy = breakout and a key such as breakout-k3f9-r412-1 (strategy, state id, run number, order number), so a restart in the middle of run 412 cannot buy a second time. ctx.position() sees only positions this strategy opened. The local envelope refuses a second position or a bigger volume before anything is sent. The stop loss is set as soon as the market order fills, and retried until it is set.
4. Configuration
Settings are layered, each layer overriding the one before: the strategy class's config, the properties file, the file's [strategy.<name>] section, environment variables, and finally values set in code with Config.update(). Unknown keys and invalid values are all reported at start, each with a hint.
- Environment variables. Every key has one: connection.token is PERKBRIDGE_CONNECTION_TOKEN, schedule.every is PERKBRIDGE_SCHEDULE_EVERY. A _FILE suffix reads the value from a file, which suits Docker secrets. In the file, ${env:NAME} reads the variable NAME.
- Tokens. A file that holds a token must not be readable by other users; the library refuses it and suggests chmod 600. --set connection.token=... on the command line is refused.
- HTTPS. Plain http:// is accepted only for localhost. For a private certificate authority, set connection.ca_file.
- See the result. perkbridge-run --show-config prints every setting, where it came from, and the token masked.
In code:
| GROUP | KEYS AND DEFAULTS |
|---|---|
| connection. | url, account, token, token_file, timeout_s, verify_tls (true), ca_file |
| order. | default_volume; expires_in_ms (30000: how long the platform may hold an order unsent); wait_for_outcome (true); wait_timeout_s (60); strict (false: raise on unknown); stops_watch_s (2); duplicate_check (true); replay_window_s (120) |
| order. envelope | max_open_positions, max_volume, allowed_symbols, max_orders_per_run: checked locally before an order is sent |
| state. | dir (~/.perkbridge/state): the order journal, run numbers, ctx.state and the event cursor |
| schedule. | mode (manual, interval, at, cron), every, at, cron, timezone (UTC), align (true), market_hours, skip_if_running (true), catch_up (false), jitter_s (0), max_consecutive_errors (5) |
| events. | enabled (true), poll_interval_s (2) |
| account., accounts. | account.default; accounts.<alias>.id, .token, .token_file, .token_mode (below) |
| bars. | cache (false), cache_max_bars (20000) (below) |
| log. | level (info), format (text or json; json when the output is not a terminal) |
Several accounts
One configuration can hold several trading accounts (1.3 and later). Each has an alias, an account id and its own token; account.default names the one that pb and ctx trade by default. A configuration without accounts.* keys is the single account of connection.*, as before.
Each account keeps its own journal under state.dir/<account id>, so duplicate prevention and recovery work per account. perkbridge-run checks every account at start, so a wrong token fails before the first run, by name. order.max_orders_per_run counts the orders of one run on all accounts; events and the Time Machine use the default account. In the environment: PERKBRIDGE_ACCOUNTS_HEDGE_TOKEN_FILE and so on.
Bars and the bar cache
bars(symbol, timeframe, limit) returns the last limit completed bars, oldest first; a limit above 1000 is read in pages. A strategy that reads thousands of bars every minute can turn on the bar cache (1.5): the first read loads the history, and each later read fetches only the newest 10 bars and joins them, after checking that the bar times overlap exactly. If they don't, the history is read again in full, with a warning.
5. Orders
Every order call returns an Order. By default the call waits until the order has an outcome: final, resting at the broker (placed), or unknown. The same calls exist on Connect (pb) and inside a strategy on ctx.
Open a position
Pending orders
A pending order returns with the status placed: it rests at the broker until its price is reached. Pending orders may carry their stop loss and take profit directly. time_in_force is gtc, day, gtd (with good_until) or gtd_day (with good_until_date).
Change, cancel and close
An argument you leave out keeps its value (KEEP); None removes it. close(), close_all() and cancel_order() work during a halt and after a risk limit is hit. close_all() stops at the first close whose outcome is not known, so it never closes blind.
Outcomes
| STATUS | MEANING | WHAT TO DO |
|---|---|---|
| filled, partially_filled | Executed by the broker. | Nothing. order.average_price and filled_volume tell the details. |
| placed | A pending order rests at the broker. | Wait for a fill, or modify or cancel it. |
| done | A modify or cancel was applied. | Nothing. |
| refused | PerkBridge's checks refused it; it was never sent. | Raised as OrderRefused with .code (for example a risk limit). |
| rejected | The broker rejected it. | Raised as OrderRejected with the MT5 .retcode. |
| expired | It could not be sent within order.expires_in_ms. | Raised as OrderExpired. Decide again with fresh prices. |
| cancelled | A pending order left the broker unfilled. | Nothing. |
| queued, sending | Still on its way when the wait ended. | pb.wait(order) or an event follows it. |
| checking, unknown, answer_lost | The broker's answer was lost; the platform is checking. | Do not send it again. order.unknown is true; pb.wait() or the events bring the result. |
How duplicates are prevented
- One key per order. Before sending, the key and the order are written to state.dir. On restart, Connect looks up every order that never got an answer, by its key. It is sent again with the same key only while it is younger than order.replay_window_s (120 s); older ones are reported and never sent.
- Same intent, same order. Inside one strategy run, asking for the same order twice returns the first one (order.duplicate_check). Your own key: pb.buy(..., client_order_id="my-key-1"); sending it again returns the stored order.
- One order in flight. While an order of the account is queued or sending, the next one raises InFlight instead of queueing behind it.
- Unknown is not "no". While an outcome is being checked, the platform refuses new opens with reconciliation_pending; closing still works.
Stops after a market order
With then_stops, the stops are saved in the journal with the order. As soon as the order fills, they are set on the position, exactly once. While they wait, a background thread retries every order.stops_watch_s; they are also checked on start, after wait(), on order events and before each strategy run. A refused modify is retried with a fresh key (after 5 s, 15 s, 60 s, then 300 s); a permanent refusal such as stops_invalid, or 20 failed attempts, is given up and logged as an error. Until the stops are set, the position has no stop loss or take profit at the broker, and when the program stops (or close_session() is called) with stops still pending, nothing sets them until a Connect with the same account and state.dir starts again; a warning is logged.
6. Strategies
A strategy is a class with up to four methods. Only on_run is required.
| METHOD | CALLED |
|---|---|
| on_start(ctx) | Once per process, before the first run. |
| on_run(ctx) | Once per schedule tick. |
| on_event(ctx, ev) | For each account event the strategy subscribes to (section 8). |
| on_stop(ctx) | On Ctrl-C or SIGTERM. It closes nothing on its own. |
Class attributes: name (the strategy tag; default: the class name in kebab case, EmaCross is ema-cross), config (the strategy's defaults) and events (the event names it wants; None for all).
The context ctx is the client bound to the strategy and the run:
- Reads: ctx.account(), ctx.quote(symbol), ctx.bars(symbol, timeframe, limit), ctx.positions(), ctx.position(symbol), ctx.orders(), ctx.history(), ctx.exposure(). Positions, orders and history are only the strategy's own; pass all=True for the whole account.
- Orders: the same calls as Connect, tagged with the strategy and keyed by run.
- ctx.state: a dict saved after every run and event, for anything that must survive a restart. Values must be JSON-serialisable.
- ctx.run_number (a counter saved per strategy), ctx.run_id, ctx.now (the tick's time, also in the Time Machine), ctx.log (a logger that adds the strategy and run) and ctx.hours(n), ctx.minutes(n).
7. Running strategies
From the command line
| COMMAND | WHAT IT DOES |
|---|---|
| perkbridge-run my.py:EmaCross | Runs the strategy on its schedule until Ctrl-C or SIGTERM. TARGET is file.py:Class or module:Class. |
| ... my.py:EmaCross,Breakout | Runs several strategies in one process, each on its own schedule. Names must differ. |
| ... --check | Validates the config, the token and the account, then exits. |
| ... --show-config | Prints the merged settings with their sources, token masked. |
| ... --once | Runs each strategy once now and exits. Events waiting in the feed are delivered first. |
| ... --set schedule.every=5m | Overrides one key; repeatable. |
| ... --time-machine from=... to=... | Replays a past window (section 9). |
| ... --reset-state --yes | Deletes the strategy's run number, ctx.state and event cursor. The order journal is kept. |
Exit codes: 0 OK, 1 an error, 2 a configuration error, 130 interrupted.
From Python
Schedules
| SCHEDULE | PROPERTIES |
|---|---|
| Every 15 minutes, on the clock (:00, :15, ...) | schedule.mode = interval schedule.every = 15m |
| At fixed times | schedule.mode = at schedule.at = 08:05, 12:00, 16:30 |
| Cron (five fields): weekdays at 07:30 | schedule.mode = cron schedule.cron = 30 7 * * 1-5 |
| Only when you call it (--once, run_once) | schedule.mode = manual (the default) |
| Limit any schedule to trading hours | schedule.market_hours = Mon-Fri 08:00-20:00 schedule.timezone = Europe/London |
- Every schedule follows schedule.timezone, daylight saving time included.
- A run that takes longer than the interval makes the next tick be skipped, not stacked (skip_if_running). Ticks missed while the computer slept are skipped, or run once with catch_up = true.
- After max_consecutive_errors failing runs in a row the strategy pauses with a clear log line.
- When the dashboard cannot be reached, the tick is skipped with one log line. Nothing is closed or retried blindly.
- Stopping the program closes nothing: open positions stay open. Stops that are at the broker stay there, but stops the library has not set yet (then_stops still pending) or gave up on are not at the broker: those positions are unprotected until the program starts again with the same state.dir. Before you stop it, check pb.stops_status() and pb.stops_needing_attention(), and set any missing stops yourself or in the dashboard.
In a container
Keep state.dir on a volume; the library warns when it runs in a container with the default one. For a real setup, build your own image with the library installed instead of installing it at every start. An official image is planned.
8. Events
The account has one event feed. When a strategy implements on_event, the runner polls the feed every events.poll_interval_s and calls it for each event the strategy subscribes to. The cursor is saved in state.dir, so events raised while the program was stopped are delivered when it starts, before the first run. Duplicates are dropped. on_event never runs at the same time as the same strategy's on_run, so ctx.state needs no locking. Keep it short: anything slow belongs in the next run.
| EV.NAME | WHEN | USEFUL FIELDS |
|---|---|---|
| order.filled, order.placed, order.refused, order.rejected, order.cancelled, order.unknown, ... (type order.updated) | An order changed status. The name is order. plus the new status. | ev.order (an Order), ev.step, ev.strategy |
| positions.updated | The open positions changed (opened, closed, stops hit, changed at the broker). | ev.positions |
| account.updated | Balance, status or readiness changed. | ev.account, ev.halted |
| halt.updated | Trading was halted or resumed (emergency stop or a risk rule). | ev.halted |
| route.updated | An order route changed. | ev.route_id, ev.data |
| sync.resumed | The saved cursor was older than the feed keeps (30 days); the runner started again from now. | Reload what you need. |
| unknown | A type this version does not know. Delivered, never dropped. | ev.type, ev.data |
Every event also has ev.type (the API's type), ev.event_id, ev.occurred_at and ev.data. Strategy.events filters on either the name or the type.
Outside a strategy, pb.api.list_events(after=cursor) reads the feed directly; keep the returned next_cursor.
Events of a strategy run by PerkBridge
When PerkBridge runs your strategy for you (Python strategies), the library (1.4 and later) also fires the events you connect to it under Events, and passes them as a PlatformEvent: ev.source, ev.name (the event's name), ev.time, ev.attempt, ev.delivery_id, and the body as ev.json(), ev.data or ev.text.
| SOURCE | FIRED BY | WITH HANDLER ON_EVENT |
|---|---|---|
| schedule | The library, on the server, on its own clock: every (with an optional offset), at and weekdays, or cron, in a time zone, optionally in market hours | ev.source == "schedule"; with handler on_run it is a normal run |
| trading | The library, from the account's event feed | ev.trading is the feed event (ev.trading.name, .order, …) |
| ingress (webhook) | A POST to the event's address, fetched from the control plane and acknowledged after the handler | ev.json(), ev.text |
| manual | Run now in the dashboard, or POST /v1/strategies/{id}/run with an optional payload | ev.data is the payload |
A strategy that handles all four:
- At least once. Webhooks and Run now can be delivered again after a crash. Orders placed while one delivery is handled get the key <strategy id>-d<delivery id>-<n>, the same on every redelivery, so the second delivery returns the first order instead of placing another. Keep the order of the calls in a handler the same on every run.
- Errors. A handler that raises is tried four times (1, 2 and 4 s apart), then the delivery is marked failed on the event's page, where it can be replayed. A lost connection leaves it unacknowledged, so it comes again.
- Pause now in the dashboard skips the event at once, in the running container.
- The account feed still reaches on_event only for the names listed in Strategy.events, when platform events are connected.
- Parameters. ctx.params.lots is the typed value from the strategy's Spec (Decimal, int, bool or str); secret parameters are read from their files and hidden by repr.
- The label. Every order carries <name>_v<version>, and reads such as ctx.positions() include the positions every version opened, so version 4 sees what version 3 opened.
9. Back-tests
The same strategy class runs live and in the past, unchanged. There are two ways to run it in the past.
| TIME MACHINE (LOCAL) | TIMEMACHINE SERVICE | |
|---|---|---|
| Where | In your process, with the live account's bars. | A separate PerkBridge service, nile-timemachine, with your own MT5 data. |
| Fills | A simple simulator on closed bars: market, limit, stop, stop limit, SL and TP. | Recorded ticks on both price sides, pending orders, SL and TP, margin and stop-out, commission and swap, the risk policy. |
| Good for | A quick check that the logic does what you think. | Results you compare, with a fingerprint that is equal for equal inputs. |
| Orders | Never sent to any account. | Only to virtual accounts of the service; it has no broker. |
Local Time Machine
- from and to are a past window; dates are UTC. step replaces the schedule with an aligned interval; without it the strategy's own schedule is replayed.
- orders=journal (the default) simulates fills; orders=none only logs what the strategy wanted to do.
- Each tick sets ctx.now to the past time. ctx.bars() returns only bars closed before it, and quotes are built from the last M1 close plus the live spread.
- The state is kept apart from the live one, so a replay never changes the live run number, ctx.state or journal.
The report is printed and written to state/<account>/strategies/<name>/time-machine/<from>_<to>/report.json:
The figures above are an example. There is no swap, commission or slippage model, and profit is in the symbol's quote currency: it is a sanity replay, not a back-tester. From Python:
Back-tests on a TimeMachine service
nile-timemachine serves the same Trading API on virtual accounts in historical time. It is not part of the Connect installation; you run it on your own computer from its Docker image, with datasets imported from your MT5 exports and a venue profile (symbol specs, costs). With its operator token:
- The service creates a run with its own account (tma-) and run token. Each tick sends every request at the tick's time; the time between ticks is processed by the service (fills, stops, swap at rollover).
- After on_stop the clock is moved to the end of the range, so the report covers the whole range. If that fails, BacktestIncomplete is raised and no report is returned.
- The report (costs, 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.
- A busy service (answer 503 run_busy) is asked again after its Retry-After, at most busy_retries times in a row (8 by default, set in TimeMachineService(..., busy_retries=8)). A refused run creation writes nothing, so repeating it is safe.
- A run token is refused by your Connect installation, and the installation refuses simulated times, so a back-test cannot reach a real account.
10. DirectConnect
The library talks to the REST Trading API: about half a second from request to fill, which suits strategies that run on minutes or hours. For the lowest latency it has a DirectConnect client too (1.2 and later): perkbridge.direct.DirectConnect keeps one WebSocket open to your DirectConnect proxies. Install the direct extra and use a DirectConnect token (nile_tdc_…); a REST token does not work there.
What the client does for you, following the rules of the DirectConnect page:
- Ids and resends. Each order gets a UUIDv7 id. After a lost connection, no answer within answer_timeout (5 s) or a retryable error such as rate_limited, it is resent with the same id until it is final; the trading server never executes an id twice.
- Proxies. It connects to the first proxy that answers and moves to the next on a lost connection, subscribing again.
- Journal. With state_dir, the id and the order are written to disk before sending, and connect() settles what an earlier run left open. A new order raises InFlight while an earlier one is unresolved.
- Outcomes raise the same errors as REST: OrderRejected, OrderRefused, OrderExpired, and OrderUnresolved (resend it with resend(), never under a new id).
- Reads from the terminal: account(), positions(), resting_orders(), symbols(), bars(), deals(). Quotes and risk reads are REST only.
- DirectConnect.from_env() reads PERKBRIDGE_DIRECT_URLS, PERKBRIDGE_DIRECT_TOKEN, PERKBRIDGE_DIRECT_CA and PERKBRIDGE_DIRECT_STATE_DIR.
| CONNECT (REST) | DIRECTCONNECT CLIENT | |
|---|---|---|
| Request to fill | About 0.5 to 0.7 s (estimate) | About 200 to 230 ms on one broker's demo server, of which PerkBridge about 20 to 45 ms |
| Token | nile_tat_ (REST) | nile_tdc_ (DirectConnect) |
| Account setup | Any account | A deployment prepared for DirectConnect and the Order path set to DirectConnect |
| Ids, journal, resends | Done by the library | Done by the library |
| Scheduler, Strategy, events, back-tests | Included | Not yet: Strategy and run() trade through REST |
Both paths go through the same risk checks, and the dashboard, the REST API and the emergency stop keep working on a DirectConnect account. The DirectConnect client has been tested against PerkBridge's real proxy and trading server with a simulated terminal, not yet with a real MetaTrader 5 terminal.
11. API reference
Connect
Connect(conf=None, *, strategy=None, check=True, recover=True) opens the client for one account: it validates the config, checks the URL, token and account (check), and resolves journaled orders that never got an answer (recover). Use it in a with block, or call close_session().
| METHOD | RETURNS |
|---|---|
| check(), account(), halted() | The Account (balance, equity, currency, status), or whether trading is halted. |
| symbols(refresh=False), symbol(name) | Symbol: digits, point, volume limits, stop levels. |
| quote(symbol), quotes(symbols=None) | Quote: bid, ask, time. |
| bars(symbol, timeframe="M1", limit=100, *, since=None, until=None) | Completed Bars, oldest first (bid prices; time is the open time). |
| positions(symbol=None, strategy=None), position(symbol, strategy=None) | Positions; position() returns one or None. |
| orders(status=None, symbol=None, strategy=None, limit=50), order(ref) | Orders, newest first; order() takes an order_id or a client_order_id. |
| timeline(order) | The OrderSteps of an order, from accepted to final. |
| history(since=None, until=None, *, symbol=None, strategy=None, limit=100) | Closed trades (ClosedTrade). |
| exposure(strategy=None), risk() | Exposure by symbol, and the account's RiskLimits. |
| buy, sell (symbol, volume=None, **kw) | A market order. kw: stop_loss, take_profit, then_stops, comment, client_order_id, strategy, route_id. |
| buy_limit, sell_limit, buy_stop, sell_stop (symbol, price, volume=None, **kw) | A pending order. Also stop_loss, take_profit, time_in_force, good_until, good_until_date. |
| buy_stop_limit, sell_stop_limit (symbol, price, limit_price, volume=None, **kw) | A stop limit order. |
| modify_position(position, *, stop_loss=KEEP, take_profit=KEEP) | Sets, keeps or removes (None) a position's stops. |
| modify_order(order, *, price=KEEP, stop_loss=KEEP, take_profit=KEEP, good_until=KEEP, ...) | Changes a pending order. |
| cancel_order(order), close(position), close_all(symbol=None, strategy=None) | Cancel, close one, close many (CloseReport: .ok, .results, .stopped_early). |
| wait(order, timeout=None) | Follows an order until it is settled or the timeout passes. |
| pending_stops(), stops_status(), stops_needing_attention(), apply_pending_stops() | The then_stops intents (section 5). |
| in_minutes(n), in_hours(n), new_key(prefix) | A time for good_until; a new client_order_id. |
| api | The low-level client (below). |
Order
An Order has the API's fields: order_id, client_order_id, status, kind, type, symbol, side, volume, price, stop_loss, take_profit, filled_volume, average_price, position_id, strategy, refused_reason, created_at and more. Helpers: final, settled, pending, unknown. Money, prices and volumes are Decimal; times are UTC datetimes. Fields a newer server adds are kept in .extra.
Errors
Low-level API
pb.api has one method per operation of the Trading API, for example pb.api.list_orders(...), pb.api.get_order_timeline(order_id) or pb.api.list_events(after=cursor). It returns the JSON bodies, handles authentication and retries, but keeps no journal: an order sent through it gets none of the protections above. For every field, see the Trading API reference.