This release is a pre-release and may not be stable for production use.
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.1.0b2, 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. 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
- Every order is idempotent. The library generates the
client_order_idand 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. - No invented outcomes. An order ends in the state the API reports. When an
answer is lost, the order is reported as
unknownwhile the platform checks with the broker. It is never re-sent under a new key. - 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.
- One run at a time.
on_runis never called twice at once for the same strategy. - Closing always works.
close()andcancel_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
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:
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 for a complete strategy.
Smoke test against your server
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.
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.tokenbecomesPERKBRIDGE_CONNECTION_TOKEN. A_FILEsuffix reads the value from a file, which suits Docker secrets. A value written${env:NAME}in the file reads the variableNAME. - 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-configprints 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_limitandsell_stop_limitreturn anOrder. By default the call waits until the order is final, placed orunknown.close,close_all,modify_position,modify_orderandcancel_orderwork the same way. For modifies,KEEPleaves a value unchanged andNoneremoves it. -
Refusals and rejections. The platform refusing an order raises
OrderRefused, with.codeand a hint. The broker rejecting it raisesOrderRejected, 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). Usethen_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, afterwait(), on order events, before each strategy run, and bypb.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 directConnectuser needs no further call. The watcher stops when nothing is pending or onclose_session(). Closing, or the process ending, with stops still pending logs a warning: those positions are not protected until aConnectfor the same account andstate.dirstarts again and resumes them. Withorder.stops_watch_s = 0, the caller must callapply_pending_stops()orwait()itself.If the stops fail during the
buy()call itself, the call raisesStopsNotSet, whose.orderis 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_invalidorposition_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,droppedorresolved. -
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 aclient_order_idwith differentthen_stopsraisesIdempotencyConflict.
-
-
Unknown outcomes. An
unknownoutcome is returned as an order with.unknowntrue, or raised asOutcomeUnknownwhenorder.strict = true. The platform settles it, andpb.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 aclient_order_idthat 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
sendingorqueued, the next order raisesInFlightinstead of queueing. This also applies afterwait()times out and after a restart, because the journal remembers the order. Anunknownoutcome is left to the platform, which refuses new orders withreconciliation_pendingwhile it checks. -
close_all. It closes positions one by one and stops at the first close whose outcome is not known (a lost answer, orunknown). 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 raisesOrderError(intent_abandoned) and is never sent again; a new order needs a new key. Derived keys, such as<key>-sfor stops, stay unique for keys near the 128-character limit, because they include a digest of the whole key. -
Restarts. On start,
Connectreads 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 thanorder.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.
ctxexposes the reads and orders, scoped to the strategy's own positions unlessall=True. It also hasctx.state, a dict persisted between runs, plusctx.run_number,ctx.nowandctx.log. - Schedules.
interval(aligned to the clock by default),at(fixed times),cron(five fields) andmanual. All of them honourschedule.timezoneand daylight saving time, and can be limited withschedule.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_errorserrors 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.resumedevent.
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.noware 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=noneonly 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:
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 withX-TimeMachine-At= the tick; a later tick processes everything in between (fills, stops, swap at rollover). Afteron_stopthe 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_backtestraisesBacktestIncompleteinstead of returning: no report or fingerprint is returned,result.jsonsays"complete": false, and the run is kept on the service (also withdelete_run=True). A returned result always has"complete": true. - Determinism. Order keys do not depend on the run id and pending
then_stopsare applied at every tick (also whenon_runraised), 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 unlessdelete_run=True, which deletes it also when the back-test fails (the original error is raised). - Transport.
https://to any host; plainhttp://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-Atheader.
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.
TARGETismodule:Classorfile.py:Class, withClass1,Class2for 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:
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 privateperkbridge/nilesource withtests/contract/nile-sim.sh. They are skipped unlessPB_CONTRACT_URLis set. - Specification. See docs/SPEC.md.
Licence
Apache-2.0
Metadata
Release files for perkbridge-connect 1.1.0b2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| perkbridge_connect-1.1.0b2.tar.gz | 140.5 kB | Without provenance | Details for perkbridge_connect-1.1.0b2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| perkbridge_connect-1.1.0b2-py3-none-any.whl | Python 3 | none | any | Details for perkbridge_connect-1.1.0b2-py3-none-any.whl |
Total release size: 231.0 kB
Release files / perkbridge_connect-1.1.0b2.tar.gz
| Download URL | perkbridge_connect-1.1.0b2.tar.gz |
|---|---|
| Size | 140.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c5b2948e4e2d182b23fd88cc86a266189dc7a8e995ad3c8c36487131120bdbd3
|
|
BLAKE2b-256 checksum How to use checksums |
f0e9d6fcad25f38415b3c4f0fc442fe51f1a36f9d0efe3ffad6251e978539d4b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
Release files / perkbridge_connect-1.1.0b2-py3-none-any.whl
| Download URL | perkbridge_connect-1.1.0b2-py3-none-any.whl |
|---|---|
| Size | 90.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c482161813af40bfd156d4359c8882ed9690c6619df1ee012ab7f9fe58d4dd1c
|
|
BLAKE2b-256 checksum How to use checksums |
92f69a5ca07a86c8a234838ccb79b99b0c9b0f1303bfee2f6056d0af08cc88ab
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.18
|
Security for perkbridge-connect 1.1.0b2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.