Docs / Reference / Python library

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.

Updated 16 Nov 2026·Version 0.x
Beta. Version 1.5.0b2 is a beta. Like the Trading API, it trades MetaTrader 5 live and demo accounts; run it on a demo account first.

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

pip install --pre "perkbridge-connect>=1.5.0b2" pip install --pre "perkbridge-connect[direct]>=1.5.0b2" # with the DirectConnect client

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:

VERSIONWHAT IT ADDED
1.5Bar cache (off by default since 1.5.0b2), bars() above 1000 bars, schedule offset for platform events
1.4Strategies run by the PerkBridge platform: version label on orders, typed ctx.params, events connected under Events (section 8)
1.3Several accounts in one configuration (section 4), connection.token_file
1.2The DirectConnect client (section 10)
1.1Back-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

  1. 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.
  2. 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.
  3. 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.
  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 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.

mkdir -p ~/.perkbridge printf '%s' 'paste-your-token-here' > ~/.perkbridge/token chmod 600 ~/.perkbridge/token

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.

connection.url = https://connect.example.com/api connection.account = tac-xxxxxxxx order.default_volume = 0.01

The token stays out of the file: PERKBRIDGE_CONNECTION_TOKEN_FILE points the library at the token file. Check everything before you trade:

export PERKBRIDGE_CONNECTION_TOKEN_FILE=~/.perkbridge/token perkbridge-run --check

A first script:

from perkbridge import Config, Connect with Connect(Config.load()) as pb: # checks the URL, the token and the account acct = pb.account() print(acct.balance, acct.currency) q = pb.quote("EURUSD") print("bid", q.bid, "ask", q.ask) order = pb.buy("EURUSD", then_stops=("1.0800", None)) # market buy, then a stop loss print(order.status) # filled, or unknown; a refusal or rejection raises pos = pb.position("EURUSD") if pos is not None: pb.close(pos)

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.

"""Breakout: buy when the last closed H1 bar closes above the highest high of the 20 bars before it; close when it closes below their lowest low.""" from perkbridge import Context, Event, Strategy class Breakout(Strategy): name = "breakout" # the strategy tag on every order config = { # defaults; the properties file overrides them "schedule.mode": "interval", "schedule.every": "1h", "schedule.market_hours": "Mon-Fri 08:00-20:00", "schedule.timezone": "Europe/London", } events = ("order.filled", "halt.updated") symbol = "EURUSD" lookback = 20 def on_run(self, ctx: Context) -> None: bars = ctx.bars(self.symbol, "H1", limit=self.lookback + 1) if len(bars) <= self.lookback: ctx.log.info("only %d bars of %s; waiting for more", len(bars), self.symbol) return last, window = bars[-1], bars[:-1] high = max(b.high for b in window if b.high is not None) low = min(b.low for b in window if b.low is not None) pos = ctx.position(self.symbol) # only this strategy's position if pos is None and last.close is not None and last.close > high: ctx.buy(self.symbol, then_stops=(low, None)) elif pos is not None and last.close is not None and last.close < low: ctx.close(pos) ctx.state["last_bar"] = last.time # saved between runs def on_event(self, ctx: Context, ev: Event) -> None: if ev.name == "order.filled": ctx.log.info("filled %s %s at %s", ev.order.side, ev.order.symbol, ev.order.average_price) elif ev.halted: ctx.log.warning("trading is halted; new orders are refused until it is lifted")

Its properties file, examples/breakout.properties. The token is not in it.

connection.url = https://connect.example.com/api connection.account = tac-xxxxxxxx order.default_volume = 0.01 # Local envelope, checked before anything is sent. order.max_open_positions = 1 order.max_volume = 0.05 order.allowed_symbols = EURUSD state.dir = ~/.perkbridge/state log.level = info [strategy.breakout] schedule.every = 1h

What to do with it, in this order:

  1. Check the configuration, the token and the account: perkbridge-run examples/breakout.py:Breakout -c examples/breakout.properties --check.
  2. 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).
  3. Run once on the demo account and look at the log and the dashboard: ... --once.
  4. 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:

from perkbridge import Config, Connect conf = Config.load().update({"order.max_volume": "0.02"}) # file + env, then code conf = Config.from_file("live.properties") # one file only conf = Config({"connection.url": "https://connect.example.com/api", "connection.account": "tac-xxxxxxxx"}) # everything in code pb = Connect(conf)
GROUPKEYS 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. envelopemax_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)
Keep state.dir. The journal in state.dir is what makes a restart safe. Back it up with the program, keep it on a volume in a container, and never share one directory between two machines.

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.

connection.url = https://connect.example.com/api 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
pb = Connect(conf) # the default account, "main" pb.buy("EURUSD", "0.10") pb.accounts["hedge"].sell("EURUSD", "0.10") # a Connect for the hedge account class Pair(Strategy): def on_run(self, ctx): ctx.buy("EURUSD", "0.10") # main ctx.accounts["hedge"].sell("EURUSD", "0.10") # same run and strategy label, hedge

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.

bars = ctx.bars("EURUSD", "M15", 4000, cache=True) # one small request per run after the first pb.bar_cache.stats # hits, full loads, reloads # or for every read: bars.cache = true in the properties file

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

pb.buy("EURUSD") # market, volume = order.default_volume pb.sell("EURUSD", "0.02") # market, explicit volume pb.buy("EURUSD", "0.01", stop_loss="1.0800", take_profit="1.0950") # market with stops (1.2.0-beta) pb.buy("EURUSD", then_stops=("1.0800", "1.0950")) # market, then stops on the position pb.buy("EURUSD", comment="breakout v2") # up to 64 characters, shown at the broker
Stops on market orders. Since PerkBridge Connect 1.2.0-beta, MetaTrader 5 market orders take a stop loss and take profit. With an older release, or a symbol whose broker refuses them, pb.buy("EURUSD", stop_loss="1.08") is refused before it is sent, with StopsNotSupported. then_stops=(sl, tp) works everywhere: the library places the order, then sets the stops on the position (below). None leaves one of them out.

Pending orders

from datetime import timedelta pb.buy_limit("EURUSD", "1.0800", stop_loss="1.0770", take_profit="1.0860") pb.sell_stop("EURUSD", "1.0750", "0.01", time_in_force="day") pb.buy_stop_limit("EURUSD", price="1.0900", limit_price="1.0895") pb.sell_limit("GBPUSD", "1.2900", time_in_force="gtd", good_until=pb.in_hours(4))

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

from perkbridge import KEEP pos = pb.position("EURUSD") pb.modify_position(pos, stop_loss="1.0820") # take profit kept pb.modify_position(pos, take_profit=None) # take profit removed o = pb.buy_limit("EURUSD", "1.0800") pb.modify_order(o, price="1.0790", stop_loss="1.0760") pb.cancel_order(o) pb.close(pos) # the whole position report = pb.close_all(symbol="EURUSD") # one by one, largest first print(report.ok, report.stopped_early)

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

STATUSMEANINGWHAT TO DO
filled, partially_filledExecuted by the broker.Nothing. order.average_price and filled_volume tell the details.
placedA pending order rests at the broker.Wait for a fill, or modify or cancel it.
doneA modify or cancel was applied.Nothing.
refusedPerkBridge's checks refused it; it was never sent.Raised as OrderRefused with .code (for example a risk limit).
rejectedThe broker rejected it.Raised as OrderRejected with the MT5 .retcode.
expiredIt could not be sent within order.expires_in_ms.Raised as OrderExpired. Decide again with fresh prices.
cancelledA pending order left the broker unfilled.Nothing.
queued, sendingStill on its way when the wait ended.pb.wait(order) or an event follows it.
checking, unknown, answer_lostThe 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.
from perkbridge import OrderRefused, OrderRejected, InFlight, EnvelopeRefused try: o = pb.buy("EURUSD", "0.01") except EnvelopeRefused as e: # your own order.* limits, nothing was sent print("refused locally:", e) except OrderRefused as e: # platform checks, nothing was sent print("refused:", e.code) # e.g. daily_loss_limit, outside_trading_hours except OrderRejected as e: # the broker said no print("rejected, retcode", e.retcode) except InFlight: # another order of the account is still on its way pass else: if o.unknown: o = pb.wait(o, timeout=120) # never buy() again: it may have filled print(o.status)

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.

from perkbridge import StopsNotSet try: o = pb.buy("EURUSD", then_stops=("1.0800", "1.0950")) except StopsNotSet as e: # e.order WAS placed: do not buy again print("position open without stops:", e.order.position_id) pb.pending_stops() # stops still being set pb.stops_status() # every intent and its state pb.stops_needing_attention() # open positions whose stops failed

6. Strategies

A strategy is a class with up to four methods. Only on_run is required.

METHODCALLED
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).
from perkbridge import Strategy class EmaCross(Strategy): config = {"schedule.mode": "interval", "schedule.every": "15m"} def on_start(self, ctx): ctx.state.setdefault("trades_today", 0) def on_run(self, ctx): closes = [b.close for b in ctx.bars("EURUSD", "M15", limit=27)] fast, slow = ema(closes, 12), ema(closes, 26) # your own function pos = ctx.position("EURUSD") if fast > slow and pos is None: ctx.buy("EURUSD", then_stops=(closes[-1] - ctx.symbol("EURUSD").point * 300, None)) elif fast < slow and pos is not None: ctx.close(pos)

7. Running strategies

From the command line

perkbridge-run TARGET [--config FILE] [--set KEY=VALUE ...] [--check | --show-config | --once | --time-machine ... | --reset-state --yes]
COMMANDWHAT IT DOES
perkbridge-run my.py:EmaCrossRuns the strategy on its schedule until Ctrl-C or SIGTERM. TARGET is file.py:Class or module:Class.
... my.py:EmaCross,BreakoutRuns several strategies in one process, each on its own schedule. Names must differ.
... --checkValidates the config, the token and the account, then exits.
... --show-configPrints the merged settings with their sources, token masked.
... --onceRuns each strategy once now and exits. Events waiting in the feed are delivered first.
... --set schedule.every=5mOverrides one key; repeatable.
... --time-machine from=... to=...Replays a past window (section 9).
... --reset-state --yesDeletes 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

from perkbridge import Config, run, run_once run(EmaCross) # until Ctrl-C or SIGTERM run([EmaCross, Breakout], Config.load()) # several strategies ctx = run_once(EmaCross) # one run now; returns its context print(ctx.orders_placed)

Schedules

SCHEDULEPROPERTIES
Every 15 minutes, on the clock (:00, :15, ...)schedule.mode = interval
schedule.every = 15m
At fixed timesschedule.mode = at
schedule.at = 08:05, 12:00, 16:30
Cron (five fields): weekdays at 07:30schedule.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 hoursschedule.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

services: breakout: image: python:3.12-slim command: sh -c "pip install --pre perkbridge-connect && 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 restart: unless-stopped volumes: {state: {}} secrets: {perkbridge_token: {file: ./token}}

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.NAMEWHENUSEFUL 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.updatedThe open positions changed (opened, closed, stops hit, changed at the broker).ev.positions
account.updatedBalance, status or readiness changed.ev.account, ev.halted
halt.updatedTrading was halted or resumed (emergency stop or a risk rule).ev.halted
route.updatedAn order route changed.ev.route_id, ev.data
sync.resumedThe saved cursor was older than the feed keeps (30 days); the runner started again from now.Reload what you need.
unknownA 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.

from perkbridge import Strategy class Guard(Strategy): events = ("order.filled", "order.rejected", "positions.updated", "halt.updated") def on_run(self, ctx): if ctx.state.get("halted"): return # wait until trading resumes ... def on_event(self, ctx, ev): if ev.name == "order.filled" and ev.strategy == self.strategy_name(): ctx.log.info("filled %s at %s", ev.order.symbol, ev.order.average_price) elif ev.name == "order.rejected": ctx.log.warning("rejected by the broker: %s", ev.order.client_order_id) elif ev.name == "positions.updated": ctx.state["open"] = len([p for p in ev.positions if p.strategy == self.strategy_name()]) elif ev.name == "halt.updated": ctx.state["halted"] = ev.halted

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.

SOURCEFIRED BYWITH HANDLER ON_EVENT
scheduleThe 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 hoursev.source == "schedule"; with handler on_run it is a normal run
tradingThe library, from the account's event feedev.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 handlerev.json(), ev.text
manualRun now in the dashboard, or POST /v1/strategies/{id}/run with an optional payloadev.data is the payload

A strategy that handles all four:

from perkbridge import Context, Strategy, run class SignalTrader(Strategy): def on_run(self, ctx: Context) -> None: # Connected schedule "every-15m" with handler on_run: a normal run. if ctx.position(ctx.params.symbol) and ctx.now.hour >= 21: ctx.close_all(symbol=ctx.params.symbol) # flat before the evening def on_event(self, ctx: Context, ev) -> None: if ev.source == "ingress": # TradingView or your own system msg = ev.json() or {} side, symbol = msg.get("action"), msg.get("symbol", ctx.params.symbol) if side == "buy" and not ctx.position(symbol): ctx.buy(symbol, ctx.params.lots, stop_loss=msg.get("sl"), take_profit=msg.get("tp")) elif side == "close": ctx.close_all(symbol=symbol) elif ev.source == "trading" and ev.trading.name == "order.filled": ctx.log.info("filled %s", ev.trading.order.client_order_id) elif ev.source == "manual": # Run now, with an optional payload if ev.data.get("flatten"): ctx.close_all() elif ev.source == "schedule" and ev.name == "daily-report": ctx.log.info("balance %s", ctx.account().balance) run(SignalTrader)
  • 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
WhereIn your process, with the live account's bars.A separate PerkBridge service, nile-timemachine, with your own MT5 data.
FillsA 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 forA quick check that the logic does what you think.Results you compare, with a fingerprint that is equal for equal inputs.
OrdersNever sent to any account.Only to virtual accounts of the service; it has no broker.

Local Time Machine

perkbridge-run examples/breakout.py:Breakout -c examples/breakout.properties \ --time-machine from=2026-10-01 to=2026-10-31 step=1h
  • 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:

strategy breakout account tac-xxxxxxxx window 2026-10-01T00:00:00Z .. 2026-10-31T00:00:00Z schedule interval 1h ticks 720 runs 264 errors 0 orders 9 (mode journal) fills 9 closed trades 4 open positions 0 balance 10000.00 -> 10023.40 USD equity 10023.40 closed symbol side volume open close profit why ...

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:

from perkbridge import Config, TimeMachine, run run(Breakout, Config.load(), time_machine=TimeMachine.parse("from=2026-10-01 to=2026-10-31 step=1h"))

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:

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"])
  • 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.

from perkbridge.direct import AccountView, DirectConnect dc = DirectConnect( ["wss://direct-1.example.com:8444/v1/direct", "wss://direct-2.example.com:8444/v1/direct"], open("/etc/myapp/dc-token").read().strip(), # nile_tdc_… ca_file="directconnect-ca.crt", # Download CA on DirectConnect → Proxies 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): # snapshot, order, position, account view.apply(ev) # rebuilds itself after a gap or reconnect print(ev.event, sorted(view.positions))

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 fillAbout 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
Tokennile_tat_ (REST)nile_tdc_ (DirectConnect)
Account setupAny accountA deployment prepared for DirectConnect and the Order path set to DirectConnect
Ids, journal, resendsDone by the libraryDone by the library
Scheduler, Strategy, events, back-testsIncludedNot 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().

METHODRETURNS
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.
apiThe 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

PerkBridgeError every error: .message, .code, .request_id, .status ├─ ConfigError bad or missing setting (exit code 2) ├─ AuthError token missing, wrong or expired ├─ PermissionRefused the token may not do this (read-only, other route) ├─ NotFound ├─ RateLimited too many requests; retried with back-off first ├─ ConnectionLost the dashboard could not be reached ├─ ApiError any other error answer │ ├─ Conflict │ └─ CursorExpired └─ OrderError ├─ EnvelopeRefused your own order.* limits; nothing sent ├─ StopsNotSupported stops on a market order; use then_stops ├─ StopsNotSet the order was placed, its stops were not (.order) ├─ InFlight another order of the account is on its way ├─ OrderRefused PerkBridge's checks (.code); nothing sent ├─ OrderRejected the broker (.retcode) ├─ OrderExpired not sent in time ├─ IdempotencyConflict a key reused for a different order └─ OutcomeUnknown only with order.strict = true

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.

Without the library. To call the API with plain HTTP, see Python examples, which uses the requests library.
Was this page helpful?