Docs / Reference / DirectConnect

DirectConnect

Send orders from your own strategy straight to the trading server over one TLS WebSocket, with PerkBridge adding only about 20 to 45 ms, with the same risk checks, and read the account on the same connection.

Updated 16 Nov 2026·Version 0.x
Live and demo accounts. DirectConnect, like the rest of PerkBridge in early access, trades MetaTrader 5 live and demo accounts. Test on a demo account first. It needs a licence that includes DirectConnect, and the permissions in What you need.

1. What DirectConnect is

With the classic order path, an order from the Trading API goes through the control plane to the trading server. From request to fill that takes about 0.5 to 0.7 seconds (an estimate; 1.32 s was measured before orders were dispatched at once). With DirectConnect, your strategy keeps one connection open to a DirectConnect proxy, and the proxy hands each order to the account's trading server over a link the server keeps open. PerkBridge's own part takes about 20 to 45 ms (an estimate). The broker's fill comes on top and is the same on every path: 160 to 180 ms measured on one broker's demo server, so about 200 to 230 ms from request to fill with everything in the broker's datacenter.

How DirectConnect works. Your program keeps one TLS WebSocket open to a DirectConnect proxy on port 8444. The trading server opens a mutual TLS link to the proxy on port 8445. The proxy hands each order over that link to the trading server, which checks the risk rules, writes the order to disk and passes it to the MetaTrader 5 terminal, which sends it to the broker. The control plane is not in the order path: it sends the proxies the tokens, the allowed addresses and the certificates.Your programyour strategytoken nile_tdc_client_order_idProxy2 or more,on your serverschecks token, IPTrading serverrisk checksorder on disknever twiceMT5 terminalNileTrade EAin yourdeploymentBrokerdemo accountexecutesthe orderTLS :8444mTLS :8445opened by the serverack: the order is on the server's diskresult: filled, placed, refused, ...Both on the same WebSocket. PerkBridge's part: 20 to 45 ms.Control plane (dashboard)not in the order path:proxies, tokens, allowed addresses,certificates, risk rules, the order path tab
Your program talks only to a proxy. The trading server connects out to the proxies, so it opens no inbound port. The control plane configures everything but never carries an order.

What stays the same:

  • Orders have the same kinds, fields and statuses as the Trading API. See How orders work.
  • The account's risk limits and time rules are checked on the trading server before every order.
  • The dashboard, the REST API and the emergency stop keep working on a DirectConnect account. Closing positions is always possible, also during a halt.
  • Failover to the standby server needs no change in your program.

Every order carries an id that your program makes. The trading server writes each order to disk before it sends it, and never executes the same id twice, so a program that resends an order after a lost connection cannot place it twice (section 5).

One order, step by step. Your program sends the order with its client_order_id. The proxy checks the token and the address and forwards it. The trading server checks the risk rules and writes the order to disk, then answers ack. It sends the order through the terminal to the broker. The broker fills it and the trading server answers result. If the connection is lost, your program reconnects and sends the same order with the same id again; the server answers with the stored order and never executes it twice.Your programProxyTrading serverBrokerorder + client_order_idtoken and address checkedrisk rules checked,order written to diskack: on diskthrough the MT5 terminalfilledresult: filled (20 to 45 ms + broker fill)If the connection drops before the resultreconnect, same order, same client_order_idthe stored order and its status: never a second fill
Send the next order only when the previous one has its result. Resending with the same id is always safe; a new id is a new order.

2. Set it up in the dashboard

You do this once per server and once per account.

What you need

A licence with DirectConnect. DirectConnect works only when your licence includes the DirectConnect feature. The licence also sets how many proxies your installation can run. Check it, or upload a new licence, in Settings → License.
YOU NEEDWHY
A licence that includes DirectConnectTurns DirectConnect on and sets the number of proxies.
A trading server added with Allow risk modeOrders are checked by the risk service on the server, which is the only process that may send them to the terminal.
A deployment created with Run in risk mode and Prepare for DirectConnect, on the nile-mt5-runtime-direct imageThe terminal must take orders from the server's DirectConnect service.
An MT5 account, live or demoDirectConnect, like the rest of PerkBridge, trades live and demo accounts. Real accounts need the runtime image NileTrade 1.4.0 and a current Fleet Agent.
At least one proxy, better two, on your serversYour program connects to a proxy; with two it can switch when one is down.

The people who set it up need these permissions (capabilities). An administrator has all of them.

STEPPERMISSION
Install DirectConnect on a serverserver:provision on that server, and a recent sign-in
Add or remove a proxytrading:configure on the organization and server:provision on the proxy's server, and a recent sign-in
Turn DirectConnect on for an account (Order path tab)trading:direct on the account
Create a DirectConnect tokentrading:tokens on the organization or the account, and a recent sign-in
Your programA DirectConnect token with Full access to send orders, or Read only

Install DirectConnect on the trading server

Open DirectConnect → Servers and press Install next to the server. The server's updater installs the DirectConnect service and checks it. Running deployments keep running. The service is then updated with the server's other software. The server opens no new inbound port: it connects out to the proxies.

The DirectConnect, Servers page with Install next to each server
DirectConnect → Servers: install the DirectConnect service on each trading server.

Add a proxy

Open DirectConnect → Proxies, choose Add proxy, pick one of your servers and give the proxy a name. Any managed server can run a proxy, also one that trades. The proxy uses the server's own address and is ready when the page shows it as connected. Add at least two proxies on different servers, so your program can switch when one is unreachable. Your licence sets how many proxies you can run.

The proxies use certificates from your installation's own DirectConnect authority. Press Download CA on the same page and give that file to your program, which uses it to check the proxies (section 4). In your provider's firewall, open port 8444 on the proxy's server to your program's address, and port 8445 to your trading servers, which connect to the proxy there.

The DirectConnect, Proxies page with two connected proxies
DirectConnect → Proxies: two proxies on different servers, both connected.

Create the account's deployment for DirectConnect

DirectConnect is chosen when the deployment is created and cannot be added to a running one. In Deploy a trading account, tick Run in risk mode and Prepare for DirectConnect, and choose the DirectConnect runtime image, nile-mt5-runtime-direct.

Turn DirectConnect on for the account

  1. Open the trading account and its Order path tab.
  2. Choose DirectConnect: file channel. The tab can also offer DirectConnect: named pipe, when your installation offers it; it is off by default. The options are greyed out, with the reason, until the licence, your trading:direct permission, DirectConnect on the server and a proxy are all in place.
  3. Under Allowed client addresses, enter the public IP addresses or CIDR ranges your program connects from, one per line. At most 32. 0.0.0.0/0 is not allowed. A proxy drops every other address before it answers.
  4. Press Save. The server takes the account over within a few seconds. The tab then lists the proxy addresses to use.
The Order path tab of a trading account with DirectConnect chosen and allowed client addresses
The account's Order path tab: DirectConnect chosen, with the allowed client addresses and the proxy addresses to use.
The lower part of the Order path tab with allowed client addresses, proxy addresses and execution time
Further down the same tab: the allowed client addresses, the proxy addresses and account id for your program, and the measured execution time.

DirectConnect → Accounts lists every account and whether DirectConnect is on for it.

The DirectConnect, Accounts page listing accounts with their transport and status
DirectConnect → Accounts.

Open positions stay open when you change the order path. You can switch back to Classic at any time.

Create a DirectConnect token

Open API tokens, pick the account, and under Used with choose DirectConnect. Choose Full access to send orders, or Read only, and a lifetime of 1 to 365 days. The token starts with nile_tdc_ and is shown once. Keep it like a password and never put it in source code. A REST token (nile_tat_) does not open a DirectConnect connection, and a DirectConnect token does not work on the REST API. See API tokens.

A new or revoked token reaches the proxies within seconds. Until then the token list shows Pending delivery.

The Create a token form with Used with set to DirectConnect and Full access
Create a token: Used with DirectConnect, Access Full.
The new API token dialog with Used with set to DirectConnect
The new token is shown once, with Copy connection settings for your program: account id, token and proxy addresses.

After an upgrade

Created a DirectConnect deployment before 1.1.9-beta? Re-create it once. Before 1.1.9-beta the server's risk service did not start at the deployment's active placement, so every read answered server_unavailable and the account could not bind. Close the account's positions, remove the deployment (Removing) and create it again with Prepare for DirectConnect. Deployments created with 1.1.9-beta or later need nothing.
  • Bring each trading server up to date after you upgrade the control plane: Servers → your server → Setup → Run setup again (1.2.0-beta) updates the agent, watchdog, vault, updater and the installed DirectConnect component, even from several releases back, and leaves running terminals running.
  • The DirectConnect menu and the Prepare for DirectConnect option appear only when your licence includes DirectConnect (since 1.1.6-beta). After you upload such a licence they appear without a new sign-in. Without the feature, turning DirectConnect on for an account through the API is refused with 409 feature_not_licensed and audited (since 1.2.7-beta; before, it answered an error 500).
  • Bars reads without an end time read up to now (since 1.1.10-beta; before, they answered status_unavailable). When a read fails, the trading server's log says why.
  • Stop loss and take profit on market orders are accepted since 1.2.0-beta, and so are the units and protections of Position protections, on the runtime image main-213a8d4 or later (DirectConnect File-channel image).
  • After a failover that promotes the standby in place, DirectConnect stays closed for the account until its deployment is re-created. Try failover on a demo account first.

3. Orders, with examples

Every message is one JSON object, sent as one WebSocket text message; the examples are spread over several lines only to be read. Each order carries a client_order_id: a UUIDv7 your program makes for each new order. It names the order for its whole life. Its time may not be more than a minute ahead of the server's clock, so keep your clock in sync. expires_in_ms, at most 60000, is how long the order may wait for the terminal; after that it is not sent.

A market order

{ "type": "order", "client_order_id": "0190f5c2-7b1e-7c3a-9f2d-4c1e8b7a6d5f", "kind": "open", "order_type": "market", "symbol": "EURUSD", "side": "buy", "volume": "0.01", "expires_in_ms": 5000 }

The answers, in order. First the ack: the order is on the trading server's disk. Then the result with its final status. elapsed_ms is the time on the proxy from reading your order to the answer.

{ "type": "ack", "request_id": "r-01", "client_order_id": "0190f5c2-7b1e-7c3a-9f2d-4c1e8b7a6d5f", "order": { "order_id": "ord-7f3a…", "account_seq": 42, "magic": 7310482211, "state": "pending" }, "elapsed_ms": 4 } { "type": "result", "request_id": "r-01", "client_order_id": "0190f5c2-7b1e-7c3a-9f2d-4c1e8b7a6d5f", "order": { "order_id": "ord-7f3a…", "state": "filled", "ticket": 100001, "filled_volume": "0.01" }, "elapsed_ms": 41 }

The values above are an example. Since 1.2.0-beta a market order can also carry stop_loss and take_profit; on an older release, set them on the position afterwards (below), or use a pending order.

A limit order with stop loss and take profit

{ "type": "order", "client_order_id": "0190f5c2-8a01-7d44-b1e2-0c9a5e6f7a11", "kind": "open", "order_type": "limit", "symbol": "EURUSD", "side": "buy", "volume": "0.01", "price": "1.08000", "stop_loss": "1.07700", "take_profit": "1.08600", "time_in_force": "gtc", "expires_in_ms": 5000 }

Its result has the status placed: the order waits at the broker for its price. order_type can also be stop or stop_limit (with stop_limit_price). time_in_force is gtc, day, gtd (with good_until) or gtd_day (with good_until_date).

Change, cancel and close

Change a pending order's price or stops. target_order_id is the order_id from its answer:

{ "type": "order", "client_order_id": "0190f5c2-9b12-7e55-82f3-1dab6f708b22", "kind": "modify", "target_order_id": "ord-81c2…", "price": "1.07950", "stop_loss": "1.07650", "take_profit": "1.08550" }

Set or change the stop loss and take profit of an open position. position_id is the position's broker ticket:

{ "type": "order", "client_order_id": "0190f5c2-a023-7f66-93a4-2ebc70819c33", "kind": "modify", "position_id": "100001", "stop_loss": "1.08100", "take_profit": "1.08900" }

Cancel a pending order:

{ "type": "order", "client_order_id": "0190f5c2-b134-7077-a4b5-3fcd8192ad44", "kind": "cancel", "target_order_id": "ord-81c2…" }

Close a position, or part of it with volume:

{ "type": "order", "client_order_id": "0190f5c2-c245-7188-b5c6-40de92a3be55", "kind": "close", "position_id": "100001", "volume": "0.01" }

Each of these is a new order with its own new client_order_id. route_id, strategy and comment (up to 64 characters) work as in the Trading API.

The answers

TYPEMEANING
ackThe order is stored on the trading server, with its order_id. It is still in flight: the result follows.
resultThe order's status in order.state: final (filled, placed, rejected, refused, expired, not_executed, …) or unknown. A result that answers a resend has stored: true and shows the order as it is now.
refusedRefused before anything was sent, for example by a risk rule. The id is used up.
errorAbout the connection or the moment, not the order: nothing was recorded for this message. code says what to do (section 5).

Every answer carries the request_id of the message it answers and the order's client_order_id. The exception is rate_limited: the proxy answers it before it reads your message, so it has no client_order_id. Treat it as an answer to the message you just sent, and resend that message with the same id after a short wait.

One order may be in flight per account. Send the next order only after the previous one has a final result or a refused. For a pending order, its placed result is enough. An ack is not: the order is stored, but it is still in flight, and a new order sent then gets in_flight_limit.

4. Connecting

  • Address: the proxy addresses listed on the account's Order path tab, for example wss://direct-1.example.com:8444/v1/direct. TLS 1.3 only.
  • WebSocket subprotocol nile.direct.v1 and the header Authorization: Bearer nile_tdc_….
  • Trust the CA file from Download CA, and connect to the proxy exactly by the address listed: its certificate names that address.
  • A wrong, expired or revoked token gets a plain HTTP 401. An address that is not allowed gets no answer at all.
  • Keep one long-lived connection. Send {"type":"ping"} at least every 60 seconds; WebSocket pings also keep it open.
  • When a proxy cannot be reached, connect to the next one. Every proxy serves every account of your organization.
  • Limits: 50 messages per second (bursts of 100), 4 connections per token, 16 per account, one order in flight per account.

5. When to resend

The one rule: if you do not know an order's fate, send it again with the same client_order_id. That is always safe, because the trading server answers a known id from its records and never executes it twice. Make a new id only after a final status, when you still want the order.

WHAT YOU GOTWHAT TO DO
The connection dropped, no answer, a timeoutReconnect, to any proxy, and resend the same id.
error server_unavailable, account_paused, in_flight_limit, failover_in_progress, rate_limited and the other temporary codesWait briefly and resend the same id. Back off up to a few seconds.
error target_not_yet_importedResend the same id after retry_after_ms.
error server_lost_in_flightThe order may be at the broker. Do not make a new id: resend the same one until it is final.
A stored result that is not final, or unknownResend the same id after a second. An unknown order is settled from the broker's history within about a minute.
error stale_client_order_id or id_used_order_not_heldNever resend this id. Check the account's orders in the dashboard, then make a new id if you still want the order.
error invalid_client_order_id or client_order_id_in_futureFix the id, or your machine's clock.
refused, or a final resultDone. Resending gets the same answer.

While an order is unknown, the account is paused for new orders and the dashboard shows Paused: order unknown. Closing positions from the dashboard still works. A dropped connection never cancels an order the server already has: it runs to its end, and your resend after reconnecting returns it.

6. Order status, reads and events

Ask about an order without sending it

{ "type": "order_status", "client_order_id": "0190f5c2-7b1e-7c3a-9f2d-4c1e8b7a6d5f" }

The answer holds the order as the server has it, or the error order_not_known when the server never received this id, in which case sending the order with it is safe. Use it after your program restarts, before you resend an order whose fate you did not record.

Read the account

{ "type": "read", "read_id": "pos-1", "what": "positions", "params": {} } { "type": "read", "read_id": "bars-1", "what": "bars", "params": { "symbol": "EURUSD", "timeframe": "M1", "count": 100 } }

what is account, positions, orders, symbols, bars or history (the last 7 days), with the Trading API's parameters. The answer is read_result with data, or an error. Reads come from the trading server's terminal. When it cannot answer you get status_unavailable, never old data. Positions and orders may be a few seconds behind the broker; an order's own result is not.

The same reads work over plain HTTPS on the proxy, for example from a shell:

curl --cacert perkbridge-directconnect-ca.pem \ -H "Authorization: Bearer $NILE_DIRECT_TOKEN" \ "https://direct-1.example.com:8444/v1/direct/positions" curl --cacert perkbridge-directconnect-ca.pem \ -H "Authorization: Bearer $NILE_DIRECT_TOKEN" \ "https://direct-1.example.com:8444/v1/direct/order_status?client_order_id=0190f5c2-7b1e-7c3a-9f2d-4c1e8b7a6d5f"

Follow the account

Send {"type":"subscribe"}. The proxy answers subscribed and then streams the account's events:

{ "type": "event", "event": "position", "stream": "st-5a1c…", "seq": 3, "at": "2026-11-06T08:25:24.92Z", "data": { "change": "opened", "position": { "position_id": "100001", "symbol": "EURUSD", "side": "buy", "volume": "0.01" } } }
EVENTDATA
snapshotThe account, its positions and its open orders. Always the first event of a stream.
orderAn order that was accepted or changed, also one placed from the dashboard. Sent at once.
positionA position was opened, changed (volume, prices or stops) or closed. Up to a second late.
accountBalance, equity or margin changed. Up to a second late.
interruptedThe stream stopped, for example while the account switches server.

Within a stream, seq goes up by one. A gap, a new stream or interrupted means: throw away what you built and wait for the next snapshot. Prices are not sent as events. A program that does not read its events loses the connection.

7. A complete Python example

This program connects to the first proxy that answers, places one market order and follows the rules of section 5: it resends the same id after a lost connection or a temporary error, also a rate_limited answer without an id, and stops only at a final status.

Before it sends the order for the first time, it writes the order's id and exact body to a file, NILE_DIRECT_STATE (by default directconnect-order.json), and removes the file once the order is final. When the program is killed, crashes or gives up waiting (exit code 2), run it again from the same directory: it finds the file, asks the order's status, and resends that order with the same id and body when it is not final. It never makes a new id for an order whose fate it does not know, so a restart cannot open a second position. With NILE_DIRECT_EVENTS_SECONDS=10 it also prints the account's events after the order.

pip install websockets export NILE_DIRECT_URLS=wss://direct-1.example.com:8444/v1/direct,wss://direct-2.example.com:8444/v1/direct export NILE_DIRECT_TOKEN=nile_tdc_... # from the dashboard, never in source code export NILE_DIRECT_CA=perkbridge-directconnect-ca.pem python3 directconnect_client.py

directconnect_client.py:

# directconnect_client.py: place one market order over DirectConnect and # follow the resend rules. Python 3.10+, pip install websockets. # Try it on a demo account first. import asyncio import json import os import secrets import ssl import sys import time import websockets SUBPROTOCOL = "nile.direct.v1" FINAL = {"filled", "partially_filled", "rejected", "refused", "expired", "not_executed", "placed", "cancelled", "done", "recovered_from_broker"} # Errors after which the same client_order_id is resent (nothing was # recorded). RESEND = {"server_unavailable", "account_paused", "in_flight_limit", "failover_in_progress", "failover_blocked", "direct_channel_unavailable", "ledger_unavailable", "stale_epoch", "target_not_yet_imported", "history_unavailable", "rate_limited"} # Never resend these IDs: the order never executes on this host. NEVER = {"stale_client_order_id", "id_used_order_not_held"} class StatusUnavailable(Exception): """The server could not tell an order's state now; ask again.""" class OrderUnresolved(Exception): """No final state within the timeout. The order may have executed: the caller must resend the SAME client_order_id (order(body, client_order_id=e.client_order_id)) until it is final, and must not send a new order for the same intent meanwhile.""" def __init__(self, client_order_id): super().__init__(f"{client_order_id}: no final state yet; resend the same client_order_id") self.client_order_id = client_order_id def uuid7() -> str: """A client_order_id: UUIDv7 (time ordered), as the host requires.""" ms = int(time.time() * 1000) b = bytearray(ms.to_bytes(6, "big") + secrets.token_bytes(10)) b[6] = 0x70 | (b[6] & 0x0F) b[8] = 0x80 | (b[8] & 0x3F) h = b.hex() return f"{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:]}" class DirectConnect: def __init__(self, urls, token, ca=None): self.urls, self.token = urls, token self.tls = ssl.create_default_context(cafile=ca) if ca else ssl.create_default_context() self.tls.minimum_version = ssl.TLSVersion.TLSv1_3 self.ws = None # The last final result's elapsed_ms: the proxy's time from reading # the order to its result. self.last_elapsed_ms = None async def connect(self): """Connect to the first proxy that answers; any proxy serves the account.""" last = None for url in self.urls: try: self.ws = await websockets.connect(url, ssl=self.tls, subprotocols=[SUBPROTOCOL], additional_headers={"Authorization": "Bearer " + self.token}, open_timeout=5, ping_interval=20) return url except (OSError, websockets.WebSocketException) as e: last = e raise ConnectionError(f"no DirectConnect proxy reachable: {last}") async def close(self): if self.ws is not None: await self.ws.close() async def _answer(self, match, timeout): """Next message for which match() is true, within timeout seconds.""" end = time.monotonic() + timeout while True: left = end - time.monotonic() if left <= 0: raise TimeoutError m = json.loads(await asyncio.wait_for(self.ws.recv(), left)) if match(m): return m async def order(self, body, client_order_id=None, timeout=150.0): """Send an order and return its final state. body is the REST order body without client_order_id. client_order_id is None for a new order, or the ID of an order whose fate is not known yet (from OrderUnresolved) to resend it. The same ID is resent after a reconnect or a retryable error until the order is final; a result that is not final yet (a stored, pending order) is asked for again. After timeout seconds without a final state it raises OrderUnresolved carrying the ID. """ coid = client_order_id or uuid7() msg = dict(body, type="order", client_order_id=coid) end = time.monotonic() + timeout delay = 0.2 while time.monotonic() < end: try: if self.ws is None: await self.connect() await self.ws.send(json.dumps(msg)) while True: # rate_limited is answered before the proxy reads the # message, so it carries no client_order_id. This # example has one request open at a time, so take it. a = await self._answer(lambda m: m.get("client_order_id") == coid or (m.get("type") == "error" and m.get("code") == "rate_limited" and "client_order_id" not in m), max(0.1, end - time.monotonic())) # Every answer names the request it answers. print(f" {a['type']:7} request_id={a.get('request_id')} code={a.get('code', '')} " f"state={(a.get('order') or {}).get('state', a.get('order_state', ''))}", file=sys.stderr) order = a.get("order") or {} if a["type"] == "ack": continue # durable on the host; the result follows if a["type"] in ("result", "refused") and order.get("state") in FINAL: self.last_elapsed_ms = None if a.get("stored") else a.get("elapsed_ms") return dict(order, client_order_id=coid) if a["type"] == "error": code = a.get("code", "") if code in NEVER: raise RuntimeError(f"{coid}: {code}: check the account's history before trading again") if code == "server_lost_in_flight" or code in RESEND: break # resend the same ID (it is never executed twice) raise RuntimeError(f"{coid}: {code}") break # stored and not final yet: ask again except (OSError, TimeoutError, websockets.WebSocketException): # Connection lost or no answer: the order may exist. Reconnect # (to any proxy) and resend the same ID. await self.close() self.ws = None await asyncio.sleep(delay) delay = min(delay * 2, 2.0) raise OrderUnresolved(coid) async def status(self, client_order_id, timeout=10.0): """An order's state from the server's ledger, without sending anything. Returns the order, or None when the server never received this ID (sending the order with it is safe). Raises for an ID that must never be resent, and StatusUnavailable when the server cannot answer now (ask again). """ await self.ws.send(json.dumps({"type": "order_status", "client_order_id": client_order_id})) a = await self._answer(lambda m: m.get("type") in ("order_status", "error") and m.get("client_order_id") == client_order_id, timeout) if a["type"] == "order_status": return a["order"] code = a.get("code", "") if code == "order_not_known": return None if code in NEVER: raise RuntimeError(f"{client_order_id}: {code}: check the account's history before trading again") raise StatusUnavailable(code) async def subscribe(self, timeout=10.0): """Ask for the account's events; returns the subscription's request_id.""" await self.ws.send(json.dumps({"type": "subscribe"})) return (await self._answer(lambda m: m.get("type") == "subscribed", timeout))["request_id"] async def events(self, seconds): """The account's events for this many seconds. A real program reads the socket in one task and hands answers and events to whoever waits for them; this example reads events only while it sends nothing. Within a stream seq rises by one: a gap, a new stream or an "interrupted" event means wait for the next snapshot and rebuild from it. """ end = time.monotonic() + seconds while True: try: yield await self._answer(lambda m: m.get("type") == "event", end - time.monotonic()) except (TimeoutError, asyncio.TimeoutError): return async def read(self, what, params=None, timeout=10.0): """A trading read (account, positions, orders, symbols, bars, history).""" rid = uuid7() await self.ws.send(json.dumps({"type": "read", "read_id": rid, "what": what, "params": params or {}})) a = await self._answer(lambda m: m.get("read_id") == rid, timeout) if a["type"] == "error": raise RuntimeError(f"read {what}: {a.get('code')}: {a.get('message', '')}") return a.get("data") def load_state(path): """The order this program sent last and did not see final, if any.""" try: with open(path) as f: return json.load(f) except FileNotFoundError: return None def save_state(path, client_order_id, body): """Write the ID and the exact body to disk BEFORE the first send, so a restart after a crash resends this same order instead of a new one.""" tmp = path + ".tmp" with open(tmp, "w") as f: json.dump({"client_order_id": client_order_id, "body": body}, f) f.flush() os.fsync(f.fileno()) os.replace(tmp, path) async def main(): urls = [u.strip() for u in os.environ["NILE_DIRECT_URLS"].split(",") if u.strip()] state_path = os.environ.get("NILE_DIRECT_STATE", "directconnect-order.json") dc = DirectConnect(urls, os.environ["NILE_DIRECT_TOKEN"], os.environ.get("NILE_DIRECT_CA")) print("connected to", await dc.connect(), file=sys.stderr) try: saved = load_state(state_path) order = None if saved: # An earlier run stopped before this order was final: finish # that order first, with its own ID and body, never a new one. coid, body = saved["client_order_id"], saved["body"] known = await dc.status(coid) state = known.get("state") if known else "never received" print(f"resuming {coid}: {state}", file=sys.stderr) if known and known.get("state") in FINAL: order = known else: coid = uuid7() body = {"kind": "open", "order_type": "market", "symbol": os.environ.get("NILE_DIRECT_SYMBOL", "EURUSD"), "side": "buy", "volume": os.environ.get("NILE_DIRECT_VOLUME", "0.01"), "expires_in_ms": 5000} save_state(state_path, coid, body) try: if order is None: order = await dc.order(body, client_order_id=coid) except OrderUnresolved as e: # Never place the order again under a new ID: it may have filled. # The state file stays, so the next run resends this order. print(f"unresolved: {e.client_order_id}; run again to resend it", file=sys.stderr) return 2 os.remove(state_path) # final: the next run places a new order print(json.dumps({"order_id": order.get("order_id"), "state": order.get("state"), "reason": order.get("reason", ""), "magic": order.get("magic")})) seconds = float(os.environ.get("NILE_DIRECT_EVENTS_SECONDS") or 0) if seconds > 0: print("subscribed", await dc.subscribe(), file=sys.stderr) async for ev in dc.events(seconds): print(f" event {ev['event']} stream={ev.get('stream', '')} seq={ev.get('seq', '')}", file=sys.stderr) finally: await dc.close() return 0 if __name__ == "__main__": sys.exit(asyncio.run(main()))

In your own program, read the connection in one task and hand answers and events to whoever waits for them. The example reads events only while it sends nothing, to stay short.

8. Where to run your program

  • Run your program close to a proxy, in the same datacenter or region, and the proxies close to the trading server. Each network hop between continents adds tens of milliseconds per order.
  • Use at least two proxies on different servers, and list all of them in your program. On a connection error, connect to the next one and resend. A load balancer in front of them may pass TLS through but must not end it.
  • Keep the allowed addresses tight: your program's fixed public addresses only. A program behind a changing address should use a fixed exit, such as a NAT gateway or a VPN.
  • Keep the clock in sync with NTP on the machine that makes the ids.
  • The account's Order path tab shows the measured execution time, median and 99th percentile of the last 24 hours, once the account trades over DirectConnect.

9. What PerkBridge guarantees

Every change to DirectConnect runs a fault-injection test suite. It runs the real proxy and trading-server services against a simulated terminal and broker. It kills the proxy and the server's services at each step of an order's way, crashes the simulated terminal before and after sending, cuts the network and drops the client. In those tests, a program that follows section 5 gets no duplicate order and no lost order: every order ends in a final status that agrees with the simulated broker. The switch to a standby server is tested the same way, with two servers and two proxies and a simulated control plane. During a switch, a new order gets failover_in_progress and is not sent; after it, only the new server sends orders.

What these tests do not cover yet:

  • A real MetaTrader 5 terminal and a real broker. A soak test that runs the same checks for an hour or more on a broker's demo server, with faults made by hand, is written but has not been run on a real server yet. Until it has, treat the results above as tested on the simulated broker only.
  • Two limits of the standby switch. An order that the old server answered but never reported before it stopped is not seen by the new server. A change or cancel of an order the new server was never told about is refused there. Check the account's orders in the dashboard after a switch.

Turning DirectConnect off for an account in its Order path tab takes it off the proxies at once. Orders still pending on the server finish first, and the account then goes back to the classic path.

Was this page helpful?