# Bulk labs Docs > This file is very large and may be truncated. For an index of this content, please refer to https://docs.bulk.trade/llms.txt instead. # API Changelog Source: https://docs.bulk.trade/api-reference/changelog API updates and version history ## v1.0.20 (4th October 2026) > [!NOTE] > > **Scheduled upgrade — Sunday, 4 October 2026.** The changes below take effect > after the upgrade; they are not an announcement that deployment has completed. > All maintenance times are UTC. ### Maintenance Schedule | Time (UTC) | Availability | | - | - | | **12:00–13:00** | Scheduled downtime. Trading will be unavailable; API and WebSocket connections will be interrupted. | | **13:00–13:30** | Markets reopen in **post-only / reduce-only mode**. Post-only orders or orders that reduce existing positions will be permitted. | | **13:30** | Normal trading is scheduled to resume, subject to final checks. | Only resting **ALO / post-only orders will be cleared**. GTC and already-placed conditional orders remain untouched by the clearing process. Untriggered on-fill actions attached to a cleared post-only order are removed with that parent order. After reconnecting, reconcile open orders and refresh account and market-data snapshots before resuming normal order submission. ### Breaking Changes #### Market Size Metadata [`GET /exchangeInfo`](/api-reference/getExchangeInfo) replaces `sizePrecision` and `lotSize` with `sizeDecimals` and `sizeIncrement`. Illustrative partial response; read the actual values for each market: ```json theme={null} [ { "symbol": "BTC-USD", "pricePrecision": 1, "tickSize": 0.1, "sizeDecimals": 8, "sizeIncrement": 0.00000001, "timeInForces": ["GTC", "IOC", "ALO", "ALO_SLIDE", "ALO_JOIN"] } ] ``` `sizeDecimals` is the maximum order-size decimal width, capped at eight wire decimal places. `sizeIncrement` is the smallest representable quantity step, not the minimum trade value; `minNotional` remains a separate requirement. #### Account-Local and Aggregate Margin Public account responses retain the **`margin` object**. Unprefixed fields describe the queried account only. Optional `agg*` fields report that account plus its attached isolated accounts, not separate sub-accounts. Selected fields from a [`POST /account`](/api-reference/getAccount) response: ```json theme={null} [ { "fullAccount": { "margin": { "totalMargin": 1000.0, "availableMargin": 900.0, "marginUsed": 100.0, "aggTotalMargin": 1250.0, "aggAvailableMargin": 1125.0, "aggMarginUsed": 125.0 } } } ] ``` Do not add local and aggregate values together: the aggregate already includes the parent. The `agg*` fields are omitted when no isolated owners are attached. Positions and open orders remain a combined parent-plus-isolated view, with isolated rows identified by `iso` and `isoPubkey`. WebSocket account snapshots use the same margin object: ```json theme={null} { "type": "account", "data": { "type": "accountSnapshot", "margin": { "totalMargin": 1000.0, "marginUsed": 100.0, "aggTotalMargin": 1250.0, "aggMarginUsed": 125.0 } }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` These are partial examples. For parents with attached isolated accounts, the API suppresses incremental parent `marginUpdate` messages; consume account snapshots for the combined margin view. See [Account Stream](/api-reference/ws-account) for the complete field reference. #### Conditional-Order Signing Update the signing encoder for new conditional orders and batches containing conditional actions. The new optional slippage fields participate in the upgraded signing schema even when an override is omitted. An older conditional encoder is not made compatible merely by leaving those fields out of JSON. Use the updated SDK signing implementation. This requirement concerns **new signed submissions**; existing conditional orders are preserved through the upgrade. See [Transaction Signing](/api-reference/signing). ### New Features #### ALO Slide and ALO Join * **`ALO_SLIDE`** moves a crossing post-only order to the nearest non-crossing display tick. * **`ALO_JOIN`** moves a crossing post-only order to the best quote on its own side of the book. If no same-side quote exists, it falls back to Slide. Non-crossing orders retain their tick-aligned submitted price. Both modes remain subject to the usual risk and order-validity checks. Use these action objects inside a signed transaction's `actions` array, over either HTTP or WebSocket: ```json ALO Slide theme={null} { "l": { "c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "ALO_SLIDE", "r": false, "i": false } } ``` ```json ALO Join theme={null} { "l": { "c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "ALO_JOIN", "r": false, "i": false } } ``` | JSON request TIF | Account/order response TIF | Binary signing enum index | | - | - | -: | | `ALO_SLIDE` | `postOnlySlide` | `3` | | `ALO_JOIN` | `postOnlyJoin` | `4` | JSON requests use the names, not the numeric indices. Existing signing indices remain `GTC = 0`, `IOC = 1`, and `ALO = 2`. `GET /exchangeInfo` advertises uppercase names in `timeInForces`. Read the reported working price rather than assuming it equals the submitted price. See [Place & Cancel Orders](/api-reference/placeOrder#alo-slide-and-alo-join) and [Trading via WebSocket](/api-reference/ws-trading). #### Configurable Conditional Slippage Market-executing stop, take-profit, and trailing orders accept optional `slippage` overrides in basis points. Range orders support independent `slSlippage` and `tpSlippage` values for their stop-loss and take-profit legs. When omitted, the applicable market default is used. Explicit limit-executing legs retain their limit price. Slippage controls do not guarantee a fill. ### Improvements #### Resting-Order Price Alignment Orders capable of resting, including GTC and the ALO family, align to the market's `pricePrecision` / `tickSize`: buys round down and sells round up. IOC orders retain native fixed-point price precision. #### Performance and Correctness * Order-processing performance and efficiency improvements. * More accurate account, leverage, and isolated-margin reporting. * Funding and liquidation precision fixes. * Improved liquidation-related market-data reporting. *** ## v1.0.19 (2nd September 2026) ### Improvements #### Primary Mainnet Endpoints New integrations should use the dedicated mainnet endpoints: ```text theme={null} HTTP: https://mainnet-api1.bulk.trade/api/v1 WebSocket: wss://mainnet-ws1.bulk.trade ``` Testnet continues to use `exchange-api.bulk.trade` and `exchange-ws1.bulk.trade`. Request paths, transaction payloads, subscriptions, and response schemas are unchanged; signed transactions must use the signature domain for the target network. #### Atomic L2 Delta Batches Deployed to Mainnet at 20:00 UTC. The `l2Delta` WebSocket stream now publishes all changed price levels for an instrument update together in one atomic message. Previously, each changed price level was published as a separate message. The subscription topic and JSON schema are unchanged. `levels` remains a two-element array of `[bids, asks]`, but either side may now contain multiple changed levels in the same message. Clients should apply the complete message as one order-book transition before exposing the updated local book. Clients that are disconnected or fall behind as slow consumers must not continue applying deltas to a stale book. Reconnect, request a fresh `l2Snapshot`, rebuild the local book, and then resume `l2Delta` processing. No API-breaking change is expected for clients that already process every level in both sides of each delta message. *** ## v1.0.18 (21st August 2026) ### Breaking Changes #### Risk-Surface Response Risk REST and WebSocket responses now contain: * `liveRegime`, identifying the active risk regime * a `leverage` object with `min`, `max`, `margin_0`, and `margin_half` * `surfaces[]`, containing every regime's `regime`, `leverage[]`, `notionals[]`, `buy[][]`, and `sell[][]` * the existing correlation data This replaces the previous WebSocket shape where `regime`, `leverage[]`, `notionals[]`, `buy[][]`, and `sell[][]` were top-level fields. ### New Features #### Size-Impact API [`GET /impact`](/api-reference/getImpact) returns the latest cached size-impact curve for the requested market. The `market` query parameter is required. The response contains: * `symbol` * millisecond `timestamp` * `minSize` * `sellBps` and `buyBps`, each containing `logMin`, `logRange`, and exactly 250 impact values at log-uniform size knots The endpoint returns `404` until the first curve is available for that market. The WebSocket `impact` subscription accepts a market symbol, publishes on `impact.`, sends the cached curve immediately when one is available, and then sends future updates. It sends no initial event before the first curve is available. #### Account Data * Position snapshots, history rows, and WebSocket position updates may expose `averageEntryTime`, the average entry time in nanoseconds. * Full account snapshots may include `lockedAmounts[]` while a transfer or withdrawal is in progress. Each lock contains the action `hash`, `symbol`, `amount`, and nanosecond `lockedAt` time. Account WebSockets emit `lockedAmountsUpdate`; an empty array means all locks have cleared. ### Improvements #### Order-Size Corrections Order responses now report the current remaining quantity after partial fills: * `working.remainingSz` reports the remaining quantity and is clamped at zero * `fullAccount.openOrders[].size` and account WebSocket snapshot order `size` report signed remaining quantity * regular and conditional WebSocket `orderUpdate.sz` report signed remaining quantity The original size remains available separately as `originalSize` or `origSz`, and filled quantity remains available as `filledSz` or `fillSz`. #### Upgrade Response During an upgrade, transaction admission may temporarily return `503` with: ```json theme={null} { "error": { "code": "UPGRADE_IN_PROGRESS", "message": "transaction admission is paused during executor upgrade" } } ``` The response may include `Retry-After`. Clients should retry with bounded backoff. *** ## v1.0.17 (31st July 2026) > [!WARNING] > > **Breaking signing change.** Upgrade to a network-domain-aware SDK or client before submitting transactions. Clients using the previous signature preimage will receive a `bad signature` response after the network cutover. ### Breaking Changes #### Network-Bound Transaction Signatures Every signed transaction is now bound to one Bulk network: | Network | Signature domain byte | | - | -: | | Mainnet | `1` | | Testnet | `2` | | Devnet | `3` | For raw Ed25519 signing, append the configured byte to the canonical preimage: ```text theme={null} wincode_serialize(commission_signable_actions) || nonce_le_u64 || account_pubkey_32_bytes || signature_domain_u8 ``` The domain is trusted client configuration. It is **not** included as a transaction JSON field or supplied through an HTTP or WebSocket header. The receiving network reconstructs the preimage with its configured domain, so a transaction signed for one network is rejected by the others. Only the signature preimage changes; the transaction JSON shape and order IDs are unchanged. Offchain/Ledger signing now binds the same domain in two places: * `app_domain = signature_domain_u8 || 31 zero bytes` * the clear-sign payload includes `Network: ` and hashes the domain-bound canonical preimage See [Transaction Signing](/api-reference/signing) for raw and offchain examples. #### Trigger and OnFill Actions Trigger baskets no longer carry a top-level `i` field or append an isolated-routing byte to the canonical signing payload. Each nested order or conditional action still carries its own `i`. OnFill now uses one action with an embedded market or limit order: ```json theme={null} { "of": { "trigger": {"l": {"c": "BTC-USD", "b": true, "px": 100000, "sz": 0.1, "tif": "GTC", "r": false, "i": false}}, "actions": [{"st": {"c": "BTC-USD", "d": false, "sz": 0.1, "tr": 98000, "lim": null, "i": false}}] } } ``` The former parent sequence field is no longer part of the JSON or signing payload. See [Place & Cancel Orders](/api-reference/placeOrder#on-fill-of). #### Paginated Account History The unsigned `POST /account` endpoint now supports bounded pagination for `fills`, `positions`, `fundingHistory`, `orderHistory`, `activityHistory`, and `riskHistory`. ```json theme={null} { "type": "fills", "user": "...", "limit": 500, "startSlot": 12000, "endSlot": 13000 } ``` `limit` defaults to 5000 and accepts 1–5000. First-page `startSlot` and `endSlot` bounds are inclusive. Continue with the same `type` and `user`, the opaque `cursor`, and an optional new `limit`; do not include slot bounds with a cursor. Every history response contains typed rows in `data` and frozen traversal, coverage, and retention metadata in `page`. Rows are ordered newest-first by slot and server sequence. Use `nextCursor` for continuation rather than timestamps or payload fields. A direct physical-account query reads that account's history. A parent query returns the parent's own rows plus rows assigned to it when an isolated account event was written. Detaching or reparenting an isolated account does not move earlier history. See [Query Account](/api-reference/getAccount#history-queries). ### Improvements #### Account Fill `tradeId` REST account-fill history and account WebSocket fill updates now expose `tradeId` as a lossless `":"` string. Maker, taker, and isolated-account views of the same execution share the same value. Treat `tradeId` as an opaque, network-local reconciliation key. It is not portable across forks or networks, and sequence gaps in one account's view are expected. This field applies to account fill surfaces; it does not add an ID to the public market-trades stream. See [Query Account](/api-reference/getAccount#history-queries) and [Account WebSocket Events](/api-reference/ws-account#fill-update). *** ## v1.0.16 (10th July 2026) > [!NOTE] > > **Client update required.** [`bulk-client`](https://github.com/Bulk-trade/bulk-client) has been bumped to **0.1.2** for builder-code support. Update before exercising the `builderCode`, `abc`, and `rbc` fields below. ### New Features #### Builder Codes (live) Builder codes are now live on BULK's exchange endpoints for routed-order-flow attribution. A user first approves a builder-code recipient with `abc`, routed `m`/`l` orders may include `builderCode: { "to": "...", "fee": 5 }`, and approval can be revoked with `rbc`. > [!WARNING] > > `abc` and `rbc` are master-account-only actions. Agent wallets cannot approve or revoke builder-code recipients. ```bash HTTP REST theme={null} https://mainnet-api1.bulk.trade/api/v1 ``` ```bash WebSocket theme={null} wss://mainnet-ws1.bulk.trade ``` See [Builder Codes](/bulk-exchange/builder-codes), [Place & Cancel Orders](/api-reference/placeOrder#builder-codes), and [Transaction Signing](/api-reference/signing) for payload and signing details. *** ## v1.0.15 (20th May 2026) > [!NOTE] > > **Client updates required.** [`bulk-client`](https://github.com/Bulk-trade/bulk-client) and [`bulk-cli`](https://github.com/Bulk-trade/bulk-cli) have been bumped to **0.1.1** to enable the changes in this release. Update both before exercising the new endpoints / fields below. ### New Features #### Offchain Signing Mode (any transaction shape) Transactions can now be signed via the **Solana v0 offchain-message envelope** in addition to the default raw canonical-binary path. The signed bytes are the full offchain envelope wrapping a deterministic clear-sign text payload (`Bulk Exchange Transaction`, `Account`, `Nonce`, `Actions`, `Signable-Hash`, plus per-action lines). `format = 0x00` for ASCII payloads and `format = 0x01` for UTF-8. | Surface | Header | Allowed values | | - | - | - | | `POST /order` | `x-bulk-sig-mode` | `raw` \| `offchain` \| `base58` | | WebSocket handshake | `x-bulk-sig-mode` | `raw` \| `offchain` \| `base58` | Header is hint only; signature validity still decides accept/reject. See [Offchain Signing Mode](/api-reference/signing#offchain-signing-mode) and [Optional Handshake Headers](/api-reference/ws-connection#optional-handshake-headers). The legacy compatibility path for **owner-signed `agentWalletCreation`** (signature over `bs58_encode(canonical_binary_message).as_bytes()`) is retained for older wallet UIs. #### `POST /account` Query Type: `riskHistory` New unsigned query returning the last 5000 liquidation, ADL, and risk-vault events for a master or sub-account. For master/sub queries, results include both base-account rows and per-instrument isolated-account rows (`iso = true`). | Field | Description | | - | - | | `eventType` | `liquidation`, `adl`, or `risk_vault` | | `marginPrior` / `marginAfter` | Margin balance snapshot around the event | | `reason` | Optional human-readable reason (e.g. shortfall, underfill tagging) | This query now supports bounded pagination through optional `limit`, `cursor`, `startSlot`, and `endSlot` body fields. See [Query Account](/api-reference/getAccount#history-queries). ### Improvements #### `feeTier` Query Response Simplified (Account-Only) `POST /account` with `type: "feeTier"` now returns just the account fee-tier quote (`scopeInstrument`, `rollingVolume`, `tierIndex`, `tierThreshold`, `makerBps`, `takerBps`, `windowDays`). Global fee-state fields (`globalPolicyActive`, `scopes`, `settledFills`, totals, etc.) live on [`GET /feeState`](/api-reference/getFeeState). #### `liquidation_sweep` Reason Code A new `3 = liquidation_sweep` value joins the fill `reasonCode` set (`0 = normal`, `1 = liquidation`, `2 = adl`, `3 = liquidation_sweep`) and the closed-position `closeReason` enum. Affected surfaces: * Trades stream (`reason` label) * Account stream fill rows (`reasonCode`) * `POST /account` `fills` / `positions` history responses #### ADL Account-Stream Event: `adl` (lowercase) + `reason` The `data.type` value on the account stream ADL event changed from `"ADL"` to `"adl"` to match the rest of the stream's casing convention. The liquidation and ADL events now also carry an optional human-readable `reason` field. The historical POST form introduced in this release now supports bounded pagination through `type: "riskHistory"`. See [Query Account](/api-reference/getAccount#history-queries). #### `subAccounts[]` on Master Snapshots, `name` on Sub-Account Snapshots The `subAccounts` array on a master's `fullAccount` snapshot (both HTTP `POST /account` and the WS account stream) returns rows containing only `{pubkey}`. To resolve a sub-account's display name, query/subscribe to that sub-account directly; its snapshot carries a top-level `name` field when `kind: "SubAccount"`. #### `marginAmount` Must Be JSON Numbers `createSubAccount.marginAmount` and `transfer.marginAmount` must be unquoted JSON numbers (e.g. `100.0`, not `"100.0"`). Strings are rejected. *** ## v1.0.14 (28th April 2026) ### New Features #### Sub-Accounts (`createSubAccount`, `removeSubAccount`, `renameSubAccount`) Master accounts can now create, rename, and remove sub-accounts via the unified `POST /order` endpoint. Sub-accounts are off-curve, protocol-derived accounts under a master with their own margin, positions, and risk profile. | Action | Description | | - | - | | `createSubAccount` | Create a named sub-account, optionally seeded with margin atomically | | `removeSubAccount` | Remove a flat sub-account (or auto-created isolated account) and sweep margin back to master | | `renameSubAccount` | Rename an existing sub-account (`{a, n}`); pubkey is preserved | See [Sub-Accounts API](/api-reference/manageSubAccounts). #### Native Margin Transfers (`transfer`) Move margin between accounts directly inside the protocol, with no external bridge or wrapper. | Kind | Scope | | - | - | | `internal` | Master and its sub-accounts, including topping up a per-instrument isolated account via `isoPubkey` | | `external` | Any account on the network | External transfers to off-curve addresses that are not protocol accounts are rejected; no implicit account creation. See [Transfer API](/api-reference/transfer). #### Isolated Account Routing (`i` flag on `l`, `m`, `st`, `tp`, `rng`, `trig`, `trl`) Order actions that produce a position now carry a **required** `i` boolean. Setting `i = true` routes the order into a per-instrument **isolated account** (`IsoAccount`) auto-derived from the signing account and the instrument. Isolated-account positions and history rows are flagged with `iso = true` and expose an `isoPubkey` for direct margin top-up via `transfer`. Isolated accounts are torn down via `removeSubAccount` against the isolated-account pubkey. > [!WARNING] > > `i` is part of the canonical signed binary message. Always include it in the JSON (`true` or `false`); omitting it will produce a `bad signature` error. See [Isolated Margin](/bulk-exchange/isolated-margin) and [Place & Cancel Orders](/api-reference/placeOrder#isolated-account-routing-i). #### Trading From a Sub-Account Every signed action (orders, modify, cancel, conditional baskets, on-fill, transfers, user settings) now works on a sub-account by setting the transaction `account` field to the sub-account pubkey while the master, the sub-account itself, or an [agent wallet](/api-reference/manageAgentWallet) registered on either signs. There is no separate sub-account endpoint or action variant. Agents registered on a master are automatically authorized for that master's sub-accounts; sub-accounts can additionally register their own agents independently. See [Sub-Accounts: Trading From a Sub-Account](/api-reference/manageSubAccounts#trading-from-a-sub-account). ### Improvements #### `fullAccount` Top-Level Fields The full-account snapshot now exposes account hierarchy and authorization state: | Field | Description | | - | - | | `kind` | `MasterEOA` or `SubAccount` (the account kinds that `POST /account` can return) | | `parent` | Parent master pubkey for sub-accounts, `null` for masters | | `subAccounts` | List of `{pubkey, name?}` children of a master | | `authorizedAgentWallets` | Agent wallets registered on this account | See [Query Account](/api-reference/getAccount). #### `iso` Flag on Account Rows Positions, open orders, fills, closed positions, funding payments, and order history rows all carry an `iso` boolean. When `iso=true`, position rows additionally expose `isoPubkey`, the per-instrument isolated account's pubkey. Master/sub `POST /account` history queries return both base-account and per-instrument isolated-account rows. In v1.0.17, `isoPubkey` also became valid as `user` with the paginated history types for direct physical history across that pubkey's account lifecycle. It remains invalid with current-state query types and as transaction `account`. #### New Response Status Types `POST /order` now emits dedicated status rows for the new actions: | Status | Source action | | - | - | | `transfer` / `transferFailed` | `transfer` | | `createSubAccount` / `createSubAccountFailed` | `createSubAccount` | | `removeSubAccount` / `removeSubAccountFailed` | `removeSubAccount` | | `renameSubAccount` / `renameSubAccountFailed` | `renameSubAccount` | See [Place & Cancel Orders](/api-reference/placeOrder) for the full status table. *** ## v1.0.13 (16th April 2026) ### New Features #### Conditional Order Types (`st`, `tp`, `rng`, `trig`, `trl`, `of`) Six conditional order types are now fully documented with request/response examples across HTTP and WebSocket: | Action | Type | Description | | - | - | - | | `st` | Stop | Trigger when price crosses against position | | `tp` | Take Profit | Trigger when price moves in favor | | `rng` | Range / OCO | Two-leg stop + take-profit pair (one-cancels-other) | | `trig` | Trigger Basket | Arbitrary nested actions on threshold cross | | `trl` | Trailing Stop | Stop that follows favorable price movement | | `of` | On-Fill | One-shot follow-up actions on parent fill | See [Place & Cancel Orders](/api-reference/placeOrder) and [Trading via WebSocket](/api-reference/ws-trading) for full examples. #### Conditional Response Statuses New status types for conditional order lifecycle: | Status | Description | | - | - | | `triggered` | Conditional root fired (non-terminal) | | `siblingCancelled` | OCO sibling auto-cancelled when other leg fires | | `triggerFailed` | Trigger execution failed (e.g. no counterparty) | | `depositFailed` | Faucet deposit failed | | `agentWalletFailed` | Agent wallet operation failed | ### Breaking Changes > [!WARNING] > > These changes affect response parsing. #### Signed Sizes in Order Responses Size fields in order responses are now **signed**: negative values indicate sell-side intent. Affected fields: * `totalSz` in `filled` / `partiallyFilled` statuses * `filledSz` / `remainingSz` in `working` status * `filledSz` in `cancelledIoc` status * `origSz` / `sz` in WebSocket `orderUpdate` messages **Example:** ```json theme={null} {"filled": {"oid": "...", "totalSz": -0.1, "avgPx": 100025.5}} ``` A `totalSz` of `-0.1` means 0.1 BTC was sold. Previously all sizes were positive with direction inferred from `isBuy`. #### WebSocket `orderUpdate` Compact Format The `orderUpdate` message uses compact field names and includes trigger metadata for conditional orders: | Old Field | New Field | | - | - | | `symbol` | `sym` | | `orderId` | `oid` | | `originalSize` | `origSz` | | `size` | `sz` | | `filledSize` | `fillSz` | | `isBuy` | *(removed; use signed `origSz`)* | New fields: `ot` (order type), `mk` (maker flag), `trigger` (trigger metadata object with `isAbove`, `px`, `lim`, `oco`, `pxHi`, `limHi`, `trb`, `stb`), `pendingOnFill`. See [Account Stream](/api-reference/ws-account) for the full `orderUpdate` reference. *** ## v1.0.12 (March 2026) ### Breaking Changes > [!WARNING] > > These changes require updates to your integration. #### Unified Transaction Envelope (POST /order and WebSocket trading) All signed requests now use a single envelope. The previous nested `action` / `orders` structure is no longer used. **Before:** ```json theme={null} { "action": { "type": "order", "orders": [...], "nonce": 1704067200000000000 }, "account": "...", "signer": "...", "signature": "..." } ``` **After:** ```json theme={null} { "actions": [{"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false}}], "nonce": 1704067200000000000, "account": "...", "signer": "...", "signature": "..." } ``` **Action tags:** `l` (limit), `m` (market), `mod` (modify), `cx` (cancel one), `cxa` (cancel all). Other actions (faucet, updateUserSettings, agentWalletCreation) use the same envelope. Affected: `POST /order`, WebSocket `post` requests for trading. #### Signed Message Format (signer excluded) The bytes that get signed no longer include the signer public key. **Message to sign:** ``` bincode_serialize(actions) + nonce_le_u64 + account_pubkey_bytes ``` **Do not include** `signer` or `signature` in the signed message. `signer` remains in the JSON payload for authorization. See [Transaction Signing](/api-reference/signing) for the full specification. #### WebSocket: Ping-Pong Keepalive Required The server sends a WebSocket **ping** frame every **30 seconds**. The client **must** reply with a **pong** frame. If no pong is received within **10 seconds**, the server closes the connection. Ping and pong are transport-level WebSocket frames, not JSON application messages. Clients that do not respond to ping will be disconnected. #### WebSocket: Risk Metrics Stream Structure The risk stream payload has changed to the **asset risk** format. **New structure:** * `leverage` - Knot list (e.g. 1.0 … 50.0) * `notionals` - Notional knot points * `buy` / `sell` - 2D arrays indexed by `[notional_idx][leverage_idx]`, each cell `{ mmrO, mmrE, p }` * `corrs` - Array of `[pair, correlation]` * `regime` - Integer -12 to 12 Previous power-law style fields (`lambdaBuy`, `lambdaSell`, `buyCoefA/B`, `sellCoefA/B`) are no longer used. #### POST /account: fullAccount Response Shape The `fullAccount` response now returns: * `margin` - Object with `totalBalance`, `availableBalance`, `marginUsed`, `notional`, `realizedPnl`, `unrealizedPnl`, `fees`, `funding` * `positions` - Array with full position fields (e.g. `fairPrice`, `notional`, `liquidationPrice`, `maintenanceMargin`, `lambda`, `riskAllocation`, `allocMargin`) * `openOrders` - Array of order state objects * `leverageSettings` - Array of `{ symbol, leverage }` Previous `marginSummary` / `settings.maxLeverage` shape is no longer used. Response body is an array of single-key objects (e.g. `[{ "fullAccount": { ... } }]`). *** ### New Features #### GET /stats (Market Data) New endpoint for exchange statistics. **Endpoint:** `GET /stats` **Query parameters:** `period` (1d, 7d, 30d, 90d, 1y, all), `symbol` (optional filter) Returns aggregate volume, open interest, funding rates, and per-market stats. See [Get Exchange Statistics](/api-reference/getStats). #### Deterministic Order IDs Order IDs are derived from the transaction (action, account, nonce, action index). No client order ID is required. You can compute the order ID before or after sending; use [bulk-keychain](https://github.com/Bulk-trade/bulk-keychain) (Node, browser, Python, Rust) to compute them. See [Order IDs](/api-reference/orderIds). #### WebSocket Ticker: Regime and Fair Price Fields Ticker stream now includes: | Field | Description | | - | - | | `regime` | Market regime indicator | | `regimeDt` | Regime duration (10s intervals) | | `regimeVol` | Regime-adjusted volatility | | `regimeMv` | Regime mean value | | `fairBookPx` | Fair price from order book | | `fairVol` | Fair volatility estimate | | `fairBias` | Fair price bias | Timestamp is in nanoseconds. #### WebSocket Candles: Additional Intervals Candle stream supports additional intervals: `3m`, `30m`, `2h`, `6h`, `8h`, `12h`, `3d`, `1w`, `1M`. #### WebSocket Trades: reason Field Trade messages may include optional `reason` when not a normal trade: e.g. `"liquidation"`, `"adl"`. #### WebSocket Account Stream: allocMargin and New Events * **Position field:** `allocMargin` (allocated margin for the position) added to snapshot and position updates. * **New event types:** `liquidation`, `ADL`, `cancelOneRejected`, `cancelAllRejected` with full payloads. See [Account stream](/api-reference/ws-account). Legacy `order` messages with `status: "placed"` or `"cancelled"` may still be sent; new integrations should use `orderUpdate` only. #### WebSocket Trading: deposit and agentWallet Status Types Response status types for faucet and agent-wallet flows: `deposit`, `agentWallet`. #### Official Signing Library: bulk-keychain [bulk-keychain](https://github.com/Bulk-trade/bulk-keychain) is the official signing library for Node.js, browser (WASM), Python, and Rust. It produces the correct canonical encoding and supports order ID computation. See [Transaction Signing](/api-reference/signing) and [Order IDs](/api-reference/orderIds). *** ### Improvements #### Wincode and Bincode Compatibility On the wire, wincode and bincode are the same (bincode-compatible encoding). See [wincode](https://docs.rs/wincode/latest/wincode/) for the Rust crate. #### POST /account: Open Orders and Fills Response Examples At the time, documentation added response examples and field descriptions for the `openOrders` and `fills` query types. `fills` now returns a paginated `{data, page}` object; `openOrders` retains its existing array shape. *** ## v1.0.11 (January 2026) ### Breaking Changes > [!WARNING] > > This is a **critical signing update**. Existing signing implementations must be updated. #### Signing Implementation Update (wincode format) The transaction signing has been updated with the correct **wincode** serialization format: **Key Changes:** * Action types now use **u32 enum discriminants** (not length-prefixed strings) * Order items (`order`, `cancel`, `cancelAll`) use u32 discriminants * Pubkeys and Hashes are serialized as **raw 32 bytes** (decoded from base58) * Added support for `cloid` (client order ID) as `Option` * Faucet user field is now raw 32-byte pubkey (not string) **Action Discriminants:** ```typescript theme={null} const ACTION_CODES = { order: 0, oracle: 1, faucet: 2, updateUserSettings: 3, agentWalletCreation: 4, }; ``` **Order Item Discriminants:** ```typescript theme={null} const ORDER_ITEM_CODES = { order: 0, cancel: 1, cancelAll: 2, }; ``` See [Transaction Signing](/api-reference/signing) for the complete implementation with binary layout reference. *** ## v1.0.10 (January 2026) ### Breaking Changes > [!WARNING] > > These changes require updates to your integration. #### Nonce Requirement for Signed Transactions All signed transactions now require a `nonce` field (u64) for replay protection. **Before:** ```json theme={null} { "action": { "type": "order", "orders": [...] }, "account": "...", "signer": "...", "signature": "..." } ``` **After:** ```json theme={null} { "action": { "type": "order", "orders": [...], "nonce": 1704067200000000000 }, "account": "...", "signer": "...", "signature": "..." } ``` **Recommendation:** Use nanosecond timestamps: `BigInt(Date.now()) * 1_000_000n` Affected endpoints: * `POST /order` - Place/cancel orders * `POST /agent-wallet` - Manage agent wallets * `POST /user-settings` - Update user settings * `POST /private/faucet` - Request testnet funds *** ### New Features #### WebSocket: Subscription Response Format Subscription confirmations now return topic strings instead of numeric IDs. **New Format:** ```json theme={null} { "type": "subscriptionResponse", "topics": ["ticker.BTC-USD", "trades.BTC-USD"] } ``` #### WebSocket: Unsubscription via Topic String ```json theme={null} { "method": "unsubscribe", "topic": "ticker.BTC-USD" } ``` #### WebSocket: Batched Account Subscriptions Subscribe to multiple accounts in a single request: ```json theme={null} { "method": "subscribe", "subscription": [{ "type": "account", "user": ["pubkey1", "pubkey2", "pubkey3"] }] } ``` #### WebSocket: Unified `orderUpdate` Message All order state changes now use a single `orderUpdate` message type with comprehensive state information. ```json theme={null} { "type": "account", "data": { "type": "orderUpdate", "status": "filled", "symbol": "BTC-USD", "orderId": "...", "price": 100000.0, "originalSize": 0.1, "size": 0.0, "filledSize": 0.1, "vwap": 100025.5, "isBuy": true, "maker": false, "timestamp": 1763316177219383423, "reason": null }, "topic": "account.pubkey" } ``` #### Account Query: New Query Types Three history query types were added to `POST /account` in this release. They now accept optional pagination and inclusive slot-bound body fields: * `positions` - Closed position history (last 5000) * `fundingHistory` - Funding payment history (last 5000) * `orderHistory` - Terminal order history (last 5000) ```json theme={null} {"type": "positions", "user": "..."} {"type": "fundingHistory", "user": "..."} {"type": "orderHistory", "user": "..."} ``` #### WebSocket: Frontend Context Stream New stream for aggregated market data across all symbols: ```json theme={null} { "method": "subscribe", "subscription": [{"type": "frontendContext"}] } ``` Returns summary data for all markets every 2 seconds. #### WebSocket: Risk Metrics Stream Subscribe to coin-based risk metrics: ```json theme={null} { "method": "subscribe", "subscription": [{ "type": "risk", "symbol": "BTC-USD" }] } ``` *** ### Improvements #### Expanded Order Status Types Added granular status types for better order tracking: | Status | Description | | - | - | | `placed` | Order placed and resting on book | | `working` | Partial fills, still resting | | `filled` | Fully filled | | `partiallyFilled` | Partially filled and terminal | | `cancelled` | Cancelled by user | | `cancelledRiskLimit` | Cancelled - risk limit exceeded | | `cancelledSelfCrossing` | Cancelled - self-trade prevention | | `cancelledReduceOnly` | Cancelled - would increase position | | `cancelledIOC` | IOC expired without full fill | | `rejectedCrossing` | Post-only rejected for crossing | | `rejectedDuplicate` | Duplicate order ID | | `rejectedRiskLimit` | Rejected - risk limit on submission | | `rejectedInvalid` | Invalid order parameters | #### L2 Delta Stream Behavior L2 Delta provides an initial snapshot (latest cached book state) on subscription, followed by real-time delta updates for every price level change. #### Enhanced Account Snapshot Account snapshot now includes additional fields: * `originalSize` - Original order size * `vwap` - Volume-weighted average fill price * `maker` - Maker/taker indicator * `reduceOnly` - Reduce-only flag * `tif` - Time in force *** ## Migration Guide ### 1. Add Nonce to Signed Transactions ```typescript theme={null} const nonce = BigInt(Date.now()) * 1_000_000n; const action = { type: "order", orders: [...], nonce: nonce // Required }; ``` Update your bincode serialization to include nonce. ### 2. Update WebSocket Subscription Handling ```javascript theme={null} // Old way (deprecated) ws.on('message', (data) => { const msg = JSON.parse(data); if (msg.channel === 'subscriptionResponse') { // Handle numeric IDs } }); // New way ws.on('message', (data) => { const msg = JSON.parse(data); if (msg.type === 'subscriptionResponse') { console.log('Subscribed to:', msg.topics); } }); ``` ### 3. Handle New Order Status Types ```javascript theme={null} switch(orderUpdate.status) { case 'placed': case 'working': // Non-terminal - order is active break; case 'filled': case 'partiallyFilled': case 'cancelled': case 'cancelledRiskLimit': case 'cancelledSelfCrossing': case 'cancelledReduceOnly': case 'cancelledIOC': case 'rejectedCrossing': case 'rejectedDuplicate': case 'rejectedRiskLimit': case 'rejectedInvalid': // Terminal - order is complete break; } ``` *** ## Previous Versions ### v1.0.0 * Initial public API release * HTTP REST API * WebSocket streaming * Ed25519 transaction signing # Query Account (Unsigned) Source: https://docs.bulk.trade/api-reference/getAccount POST /account Query account information. **No signature required** - read-only operation. Accepts a JSON body with POST request. **Query types**: | `type` | Returns | |---|---| | `fullAccount` | Complete state (margin + positions + orders + leverage settings) | | `openOrders` | Resting live orders (includes conditional orders parked in conditional books) | | `feeTier` | Account-only fee-tier quote snapshot (`symbol` optional). For global fee state use `GET /feeState`. | | `fills` | Paginated trade fills | | `positions` | Paginated closed positions | | `fundingHistory` | Paginated funding payments | | `orderHistory` | Paginated terminal order states | | `activityHistory` | Paginated account activity | | `riskHistory` | Paginated liquidation, ADL, and risk-vault events | History queries return a plain typed `{data, page}` object; current-state queries retain their existing array response. History `limit` defaults to 5000 and is bounded to 1–5000. A first page may include inclusive `startSlot` and `endSlot` bounds. A continuation includes the same `type` and `user`, `cursor`, and an optional changed `limit`; it cannot include slot bounds. > [!NOTE] > > **4 October 2026 upgrade:** the account-local and aggregate margin guidance below > applies after the scheduled upgrade. Public responses retain the `margin` > object; they do not expose the SDK's internal `metrics` and `aggregate` objects. ## Query Targets `POST /account` is unsigned. Current-state query types accept a **master** or **sub-account** pubkey as `user`. History queries use the same endpoint and may also query a physical isolated-account pubkey directly. | Pubkey passed in `user` | What you get back | | - | - | | **Master** | Master snapshot. `fullAccount` and `openOrders` include the master's own rows **plus** rows from any per-instrument isolated accounts attached to it (each isolated row carries `iso = true` and `isoPubkey`). | | **Sub-account** | Snapshot scoped to that sub-account. `kind = "SubAccount"` and `parent` is the master pubkey. Current-state views also include any per-instrument isolated-account rows attached to that sub-account. | Isolated accounts are not current-state query targets. An isolated `isoPubkey` is supported only by the paginated history types. Isolated accounts are managed via the `i` flag on order actions (see [Isolated Margin](/bulk-exchange/isolated-margin)); their pubkeys also appear inline on parent rows and can be used as `to` in margin [`transfer`](/api-reference/transfer) top-ups. To enumerate sub-accounts on a master, read `subAccounts[]` from its `fullAccount` response. *** ## Request Examples ```json Full Account theme={null} { "type": "fullAccount", "user": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Open Orders theme={null} { "type": "openOrders", "user": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Fee Tier theme={null} { "type": "feeTier", "user": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "symbol": "BTC-USD" } ``` ```json Sub-Account theme={null} { "type": "fullAccount", "user": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR" } ``` ```json History First Page theme={null} { "type": "fills", "user": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "limit": 500, "startSlot": 12000, "endSlot": 13000 } ``` ```json History Continuation theme={null} { "type": "fills", "user": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "limit": 1000, "cursor": "opaque-base64url-cursor" } ``` *** ## Response Schemas Current-state responses are an **array** of externally tagged objects with `fullAccount`, `openOrder`, or `feeTier`. History types return a plain typed `{data, page}` object. ## History Queries Use `fills`, `positions`, `fundingHistory`, `orderHistory`, `activityHistory`, or `riskHistory` as the request `type`. * `limit` is optional, defaults to 5000, and accepts 1–5000. * `startSlot` and `endSlot` are optional inclusive bounds on the first page. * Continue with the returned `cursor`. A cursor request may change `limit` but cannot include slot bounds. History responses use this envelope: ```json theme={null} { "data": [], "page": { "nextCursor": "opaque-base64url-cursor", "hasMore": true, "asOfSlot": 13000, "startSlot": 12000, "endSlot": 13000, "coverage": "complete", "minAvailableSlot": 12000 } } ``` Rows are ordered newest-first by slot and sequence. Always continue with `nextCursor`; do not construct cursors from timestamps or row fields. Fill rows include `tradeId` in `":"` form. REST history and account WebSocket views of the same execution share the same value. Treat it as an opaque network-local reconciliation key. `positions` history rows may include `averageEntryTime` when available. ### Full Account Response For `type: "fullAccount"`. Returns account state including margin, positions, open orders, and leverage settings. The example below shows selected fields. ```json theme={null} [ { "fullAccount": { "kind": "MasterEOA", "subAccounts": [ {"pubkey": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR"} ], "authorizedAgentWallets": [ "6pJ8vnrWofWgrn9doYBBRjijV5e6YJ2yN1U2EMRk4cLQ" ], "builderCodeApprovals": [ { "recipient": "5Am6JkEHAjYG1itNWRMGpQrxvY8AaqkXCo1TZvenqVux", "maxFee": 5 } ], "margin": { "totalMargin": 100000.0, "availableMargin": 95000.0, "executionImpact": 0.0, "transferableBalance": 94750.0, "marginUsed": 5000.0, "marginBufferRate": 0.05, "bufferedMargin": 5250.0, "notional": 50000.0, "realizedPnl": 1234.0, "unrealizedPnl": 500.0, "fees": 12.5, "funding": -5.0 }, "positions": [ { "symbol": "BTC-USD", "size": 0.5, "price": 100000.0, "fairPrice": 100050.0, "notional": 50000.0, "realizedPnl": 1234.0, "unrealizedPnl": 500.0, "leverage": 5.0, "liquidationPrice": 80000.0, "fees": 12.5, "funding": -5.0, "maintenanceMargin": 2500.0, "averageEntryTime": 1775550000000000000, "lambda": 0.05, "riskAllocation": 0.8, "iso": false, "protection": { "orders": [ { "orderId": "9fJdDgS8eYq9Dj8YkXTY32tRAb4gk58wEAg2a5kzCL5P", "orderType": "stop", "trigger": { "px": 98000.0, "lim": 97950.0, "oco": null } } ] } } ], "openOrders": [ { "symbol": "BTC-USD", "orderId": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "price": 100000.0, "originalSize": 0.1, "size": 0.1, "filledSize": 0.0, "vwap": 0.0, "maker": true, "reduceOnly": false, "orderType": "limit", "trigger": null, "tif": "gtc", "status": "resting", "timestamp": 1704067200000000000, "iso": false } ], "feeTiers": [ { "symbol": "global", "rollingVolume": 1200000.0, "tierIndex": 1, "tierThreshold": 1000000.0, "makerBps": 1.8, "takerBps": 3.3, "windowDays": 14 } ], "leverageSettings": [ { "symbol": "BTC-USD", "leverage": 5.0 }, { "symbol": "ETH-USD", "leverage": 3.0 } ], "lockedAmounts": [ { "hash": "uQ8yioSC6fYLWwWS2XAi97vMJXKur3GKr7DEp1tdMqs", "symbol": "USDC", "amount": 500.0, "lockedAt": 1700000000000000000 } ] } } ] ``` **Account top-level fields:** * `kind` - Account kind string. Current-state query responses use `MasterEOA` or `SubAccount`. * `parent` - Parent master pubkey for sub-accounts; omitted when no parent exists * `name` - Sub-account display name. Present on responses where `kind: "SubAccount"` (i.e. when you passed the sub-account pubkey as `user`); omitted on master responses. * `subAccounts` - Children of the master, each `{pubkey}`. The list contains pubkeys only; query a sub-account directly with `type: "fullAccount"` to see its `name`. See [Sub-Accounts](/api-reference/manageSubAccounts) * `authorizedAgentWallets` - Agent wallets registered on this account that may sign on its behalf. See [Manage Agent Wallets](/api-reference/manageAgentWallet) * `builderCodeApprovals` - Approved builder-code recipients as `{recipient, maxFee}`. Builder codes are builder-code fees on the wire; use `abc`/`rbc` to manage this list. * `lockedAmounts` - Margin locked while a transfer or withdrawal is in progress, omitted when empty. Each row contains the action `hash`, `symbol`, `amount`, and nanosecond `lockedAt` timestamp. Locks clear when the operation completes or is no longer pending. ### Account-local and aggregate margin The unprefixed fields inside `margin` describe the queried account only. When that account has attached isolated accounts, optional `agg*` fields in the same object describe the account **plus those isolated accounts**. These totals do not include separate sub-accounts. Do not add the unprefixed values to the `agg*` values: that would count the parent twice. Illustrative partial response for an account with isolated collateral: ```json theme={null} [ { "fullAccount": { "margin": { "totalMargin": 1000.0, "availableMargin": 900.0, "marginUsed": 100.0, "aggTotalMargin": 1250.0, "aggAvailableMargin": 1125.0, "aggMarginUsed": 125.0 } } } ] ``` | Field in `margin` | Meaning | | - | - | | `totalMargin` | Account-local margin balance | | `availableMargin` | `totalMargin - marginUsed`; not the withdrawable balance | | `executionImpact` | Non-positive difference between impacted and unrealized P\&L | | `transferableBalance` | Balance currently eligible for transfer under the account's risk constraints | | `marginUsed` | Account-local maintenance margin | | `marginBufferRate` | Buffer rate applied to maintenance margin | | `bufferedMargin` | `marginUsed * (1 + marginBufferRate)` | | `notional`, `realizedPnl`, `unrealizedPnl`, `fees`, `funding` | Account-local reported values | | `aggTotalMargin`, `aggAvailableMargin`, `aggExecutionImpact`, `aggTransferableBalance`, `aggMarginUsed`, `aggBufferedMargin`, `aggNotional`, `aggRealizedPnl`, `aggUnrealizedPnl`, `aggFees`, `aggFunding` | Corresponding parent-plus-isolated totals; omitted when no isolated owners are attached | `positions` and `openOrders` remain the combined parent-plus-isolated view, with isolated rows identified by `iso` and `isoPubkey`. Public margin fields are `totalMargin` and `availableMargin`, not `totalBalance` and `availableBalance`. **Position fields:** `symbol`, `size`, `price`, `fairPrice`, `notional`, `realizedPnl`, `unrealizedPnl`, `leverage`, `liquidationPrice`, `fees`, `funding`, `maintenanceMargin`, `averageEntryTime`, `lambda`, `riskAllocation`, `iso` * `averageEntryTime` - Average entry time in nanoseconds. * `iso` - `true` if the position belongs to a per-instrument [isolated account](/bulk-exchange/isolated-margin) attached to this master/sub-account; otherwise `false` * `isoPubkey` - Present only when `iso=true`; pubkey of the isolated account. Use as `to` in [`transfer`](/api-reference/transfer) to top up isolated-account margin. It is valid as `user` for history queries, but not for current-state queries. * `protection` - Optional attached reduce-only protective orders for this symbol ### Open Orders Response For `type: "openOrders"`. Returns up to 5000 resting orders; each item is an object with key `openOrder`. ```json theme={null} [ { "openOrder": { "symbol": "BTC-USD", "orderId": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "price": 99000.0, "originalSize": 0.1, "size": 0.1, "filledSize": 0.0, "vwap": 0.0, "maker": true, "reduceOnly": false, "orderType": "limit", "trigger": null, "tif": "gtc", "status": "resting", "timestamp": 1699564800000000000, "iso": false } } ] ``` For master/sub accounts, the response also includes per-instrument isolated-account rows (`iso=true`) belonging to that account tree. Order-state `tif` values are `gtc`, `ioc`, `postOnly`, `postOnlySlide`, and `postOnlyJoin`. The last two correspond to the JSON request values `ALO_SLIDE` and `ALO_JOIN`; see [Place & Cancel Orders](/api-reference/placeOrder). ### Fee Tier Response For `type: "feeTier"`. Returns the account-only fee-tier quote snapshot. For global fee-state (policy, schedules, settlement totals) use [`GET /feeState`](/api-reference/getFeeState). ```json theme={null} [ { "feeTier": { "scopeInstrument": "BTC-USD", "rollingVolume": 1200000.0, "tierIndex": 1, "tierThreshold": 1000000.0, "makerBps": 1.8, "takerBps": 3.3, "windowDays": 14 } } ] ``` **Fee Tier Fields:** * `scopeInstrument` - Instrument scope resolved for this quote * `rollingVolume` - Account rolling volume in resolved scope window * `tierIndex` - Active tier index (0-based) * `tierThreshold` - Threshold volume of the active tier row * `makerBps` / `takerBps` - Effective bps at current tier * `windowDays` - Rolling window length in days *** ## Real-time Updates For real-time account updates, use the [WebSocket account stream](/api-reference/ws-account). ```json theme={null} { "method": "subscribe", "subscription": [{ "type": "account", "user": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" }] } ``` # Get Exchange Info Source: https://docs.bulk.trade/api-reference/getExchangeInfo GET /exchangeInfo Returns information about all available markets. Returns information about all available markets including trading rules, precision, leverage limits, and supported order types. > [!NOTE] > > **4 October 2026 upgrade:** `sizeDecimals` and `sizeIncrement` replace > `sizePrecision` and `lotSize` after the scheduled upgrade. The new post-only > variants also appear in `timeInForces` for markets that support them. Illustrative partial response; always read the actual values for your market: ```json theme={null} [ { "symbol": "BTC-USD", "pricePrecision": 1, "tickSize": 0.1, "sizeDecimals": 8, "sizeIncrement": 0.00000001, "timeInForces": ["GTC", "IOC", "ALO", "ALO_SLIDE", "ALO_JOIN"] } ] ``` * `sizeDecimals` is the maximum decimal width accepted for order sizes, capped at the wire's eight decimal places. * `sizeIncrement` is the smallest representable order-size increment, `10^(-sizeDecimals)`. It is **not** a minimum trade value; `minNotional` is a separate constraint. * `pricePrecision` and `tickSize` describe the resting-order display grid. Resting buys round down and sells round up; IOC retains native precision. * `timeInForces` uses uppercase request names. Account/order responses instead use `gtc`, `ioc`, `postOnly`, `postOnlySlide`, and `postOnlyJoin`. See [Place & Cancel Orders](/api-reference/placeOrder#alo-slide-and-alo-join) for Slide/Join behavior and [Conditional Orders](/bulk-exchange/conditional-orders) for stop and take-profit actions. # Get Fee State Source: https://docs.bulk.trade/api-reference/getFeeState GET /feeState Returns active fee policy/schedule state for protocol/global scopes. This endpoint is read-only and unsigned. Returns the active protocol fee policy, per-instrument overrides, and any scheduled future changes. For account-specific fee tier quotes, use `POST /account` with `type: "feeTier"`. See [Query Account](/api-reference/getAccount) for details. # Get Size-Impact Curve Source: https://docs.bulk.trade/api-reference/getImpact GET /impact Returns the latest executor-published liquidation-size impact curve cached for one market. Returns `404` until the first curve has been published for the requested symbol. Returns the latest executor-published liquidation-size impact curve for one market. * `market` is required and uses the exact market symbol, such as `BTC-USD`. * `timestamp` is Unix time in milliseconds. * `sellBps` and `buyBps` each contain 250 impact values at log-uniform size knots. * `minSize` is the first size knot. For a curve with `n` values, knot `i` is `exp(logMin + i / (n - 1) * logRange)`. * The endpoint returns `404` until the executor publishes the first curve for that market. For live updates, subscribe to the [`impact` WebSocket stream](/api-reference/ws-market-data#impact-curve-stream). # Get Candles (OHLCV) Source: https://docs.bulk.trade/api-reference/getKlines GET /klines Returns historical candlestick data for charting. **Supported intervals**: 10s, 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M Returns historical candlestick data for charting. Supports multiple timeframes from 10 seconds to 1 month. **Supported intervals**: `10s`, `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `6h`, `8h`, `12h`, `1d`, `3d`, `1w`, `1M` For real-time candle updates, use the WebSocket candle stream. # Get L2 Order Book Source: https://docs.bulk.trade/api-reference/getL2Book GET /l2book Returns current order book snapshot with optional filtering. Returns current order book snapshot with optional filtering by price levels and aggregation. For real-time order book data: * Use **L2 Snapshot** stream for periodic full snapshots (every 200ms) * Use **L2 Delta** stream for real-time incremental updates (\< 1ms) # Get Risk Surfaces Source: https://docs.bulk.trade/api-reference/getRiskSurfaces GET /riskSurfaces Returns the complete risk configuration surface set for one market across all regimes. This is a read-only snapshot endpoint and does not mutate state. Returns the full risk-surface configuration for a market across all regimes, including margin requirements at different leverage levels and notional sizes. * `market` accepts both coin and perp alias (`BTC` and `BTC-USD` are both valid) * `liveRegime` identifies the currently active regime * `leverage` contains the market's maximum-leverage curve (`min`, `max`, `margin_0`, and `margin_half`) * `surfaces` are sorted by `regime` ascending * `corrs` are sorted by pair key for deterministic output **Margin cell fields**: `mmrO` (maintenance margin ratio for opening), `mmrE` (for existing), `p` (portfolio margining penalty factor). # Get Exchange Statistics Source: https://docs.bulk.trade/api-reference/getStats GET /stats Returns exchange statistics with optional symbol filtering. Returns 24-hour rolling stats. The supported period is `1d` (one day), with `24h` as an alias. Aggregate queries (`symbol` omitted) are cached with 600s TTL; symbol-specific queries bypass cache. The markets array is sorted by `quoteVolume` descending. Returns 24-hour rolling exchange statistics with optional symbol filtering. Use for aggregate volume, open interest, funding rates, and per-market stats. **Notes:** * The supported period is `1d` (one day), with `24h` as an alias * Aggregate queries (no `symbol`) are cached with 600s TTL * Symbol-specific queries bypass cache # Get Market Ticker Source: https://docs.bulk.trade/api-reference/getTicker GET /ticker/{symbol} Returns 24-hour statistics for a specific symbol. Returns 24-hour statistics for a specific symbol including price changes, volume, mark price, and funding rate. For real-time ticker updates, use the WebSocket ticker stream which updates every 200ms. # API Overview Source: https://docs.bulk.trade/api-reference/introduction HTTP & WebSocket API > [card] [Download OpenAPI Spec](/api-reference/openapi.yaml) > > Complete OpenAPI 3.0 specification. Import into Postman, generate client SDKs, or browse the schema directly. ## API Structure Is divided into three main sections: > [card] Market Data > > **Public, Read-only** > > Real-time and historical market data. No authentication required. > [card] Account Queries > > **Public, Unsigned** > > Query account state without signatures. > [card] Trading > > **Authenticated, Signed** > > State-mutating operations requiring Ed25519 signatures. Use **[bulk-keychain](https://github.com/Bulk-trade/bulk-keychain)** (Node, browser, Python, Rust) for signing. ## Base URLs ```bash Mainnet HTTP (Primary) theme={null} https://mainnet-api1.bulk.trade/api/v1 ``` ```bash Mainnet WebSocket (Primary) theme={null} wss://mainnet-ws1.bulk.trade ``` ```bash Testnet HTTP theme={null} https://exchange-api.bulk.trade/api/v1 ``` ```bash Testnet WebSocket theme={null} wss://exchange-ws1.bulk.trade ``` > [!NOTE] > > Mainnet and testnet are separate networks. Signed transactions must use the matching [signature domain](/api-reference/signing#what-gets-signed). ## Quick Start **1. Query Market Data** No authentication required - start exploring immediately. ```bash theme={null} curl https://mainnet-api1.bulk.trade/api/v1/exchangeInfo ``` **2. Check Your Account** Query your positions and orders (no signature needed). ```bash theme={null} curl -X POST https://mainnet-api1.bulk.trade/api/v1/account \ -H "Content-Type: application/json" \ -d '{"type":"fullAccount","user":"FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7"}' ``` **3. Get Testnet Funds** Request testnet funds through the testnet endpoint. The faucet is not available on mainnet. See [Request Faucet](/api-reference/requestFaucet) for details. **4. Place Your First Order** Sign and submit a transaction with the official **[bulk-keychain](https://github.com/Bulk-trade/bulk-keychain)** library (Node, browser, Python, Rust) or see [Transaction Signing](/api-reference/signing) for the protocol details. ## Field Notation Bulk uses compact field names to minimize bandwidth : | Short | Full Name | Description | | - | - | - | | `s` | symbol | Market symbol (e.g., BTC-USD) | | `c` | coin | Market symbol in orders | | `px` | price | Price level | | `sz` | size | Order/position size | | `b` | is_buy | Buy/sell direction (true=buy) | | `r` | reduce_only | Order only reduces position | | `t` | type | Order type object | | `oid` | order_id | Order identifier | | `tif` | time_in_force | Order lifetime (GTC/IOC/ALO) | | `d` | direction | Trigger direction (true=above) | | `tr` | trigger | Trigger threshold price | | `lim` | limit | Post-trigger limit price | | `mk` | maker | Maker/resting flag | | `of` | on_fill | On-fill consequent actions | ## Order Types | Type | Tag | Description | Use Case | | - | - | - | - | | **Limit** | `l` | Resting limit order | Standard GTC/IOC/ALO order | | **Market** | `m` | Immediate execution | Market order at best price | | **Stop** | `st` | Conditional stop | Trigger sell/buy on price break | | **Take Profit** | `tp` | Conditional take-profit | Exit position at target price | | **Range / OCO** | `rng` | One-cancels-other pair | Combined stop + take-profit | | **Trigger Basket** | `trig` | Conditional action list | Execute multiple actions on trigger | | **Trailing Stop** | `trl` | Trailing conditional | Adjusts with favorable price | | **On-Fill** | `of` | Fill-triggered actions | Attach stop/TP after entry fills | ## Timestamp Format All timestamps are in **milliseconds since Unix epoch** (int64) for both HTTP and WebSocket APIs. > [!NOTE] > > **Nonce for Signed Transactions**: Use nanoseconds for the `nonce` field: `BigInt(Date.now()) * 1_000_000n` *** ## Resources See [Public API Rate Limits](/api-reference/rate-limits) for mainnet request, trading-action, and WebSocket connection budgets. > [card] [API Changelog](/api-reference/changelog) > > View API updates and version history > [card] [bulk-keychain](https://github.com/Bulk-trade/bulk-keychain) > > Official signing library for Node.js, browser, Python, and Rust # Manage Agent Wallet (Signed) Source: https://docs.bulk.trade/api-reference/manageAgentWallet api-reference/openapi-agent-wallet.yaml POST /order Register or remove an agent wallet via the unified transaction endpoint Agent wallet management uses the **unified** `POST /order` endpoint. Send a transaction with an `agentWalletCreation` action in the `actions` array. > [!WARNING] > > If `signer != account`, the signer must be pre-authorized. Agent wallets allow the agent to trade on behalf of the account; register the agent with this action before the agent submits orders. > [!NOTE] > > **Scope:** agent wallets are registered on the `account` field of this transaction. An agent registered on a **master** can sign for that master **and for any of its [sub-accounts](/api-reference/manageSubAccounts)**. Sub-accounts can also register their own agent wallets independently (set `account` to the sub-account pubkey when registering). To use an agent on a sub-account, set the transaction `account` to the sub-account pubkey and `signer` to the agent wallet's pubkey. > > Isolated accounts are managed entirely through the `i` flag on order actions and are never set as `account` for any transaction (including `agentWalletCreation`). See [Isolated Margin](/bulk-exchange/isolated-margin). *** ## Transaction Envelope Every request to `POST /order` has this shape: ```json theme={null} { "actions": [Action, ...], "nonce": 1704067200000, "account": "base58_pubkey", "signer": "base58_pubkey", "signature": "base58_signature" } ``` For agent wallet, the action is a single `agentWalletCreation` object. *** ## Agent Wallet Action | Field | Type | Description | | - | - | - | | `a` | string | Agent public key to authorize (base58). | | `d` | boolean | `false` = add/register agent, `true` = remove agent. | *** ## Request Examples ### Register an agent ```json theme={null} { "actions": [ {"agentWalletCreation": {"a": "5Am6JkEHAjYG1itNWRMGpQrxvY8AaqkXCo1TZvenqVux", "d": false}} ], "nonce": 1704067200000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5JXWgp1fW6px2Gjhw6YHhQ4..." } ``` ### Remove an agent ```json theme={null} {"agentWalletCreation": {"a": "5Am6JkEHAjYG1itNWRMGpQrxvY8AaqkXCo1TZvenqVux", "d": true}} ``` *** ## Signing the Transaction The canonical signing path is the raw wincode binary message described in [Transaction Signing](/api-reference/signing). Two extra signing modes are accepted on this endpoint: * **General offchain mode**: any transaction (including `agentWalletCreation`) can be signed using the v0 Solana offchain-message envelope. Set `x-bulk-sig-mode: offchain` on the request. See [Offchain Signing Mode](/api-reference/signing#offchain-signing-mode). * **Legacy wallet-compatibility path** (owner-signed `agentWalletCreation` only): when `signer == account` and the transaction contains exactly one `agentWalletCreation` action, the server also accepts a signature over `bs58_encode(canonical_binary_message).as_bytes()` for older wallet UIs that cannot produce raw binary signatures. See [Legacy Wallet-Compatibility Path](/api-reference/signing#legacy-wallet-compatibility-path-owner-signed-agentwalletcreation-only). *** ## Response Same `OrderResponse` format as other actions. Success may return `agentWallet` status: ```json theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"agentWallet": {"agent_wallet": "5Am6JkEHAjYG1itNWRMGpQrxvY8AaqkXCo1TZvenqVux"}}] } } } ``` Failure returns `agentWalletFailed`: ```json theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"agentWalletFailed": {"message": "Unauthorized"}}] } } } ``` *** ## Before You Start > [!NOTE] > > See the [Transaction Signing](/api-reference/signing) guide for how to sign your requests. > > **Nonce**: Use a unique value (e.g. timestamp in nanoseconds): `BigInt(Date.now()) * 1_000_000n` # Sub-Accounts (Signed) Source: https://docs.bulk.trade/api-reference/manageSubAccounts api-reference/openapi-sub-accounts.yaml POST /order Create, rename, and remove sub-accounts via the unified transaction endpoint Sub-account management uses the **unified** `POST /order` endpoint. Send a transaction with a single `createSubAccount`, `renameSubAccount`, or `removeSubAccount` action. Conceptual background lives on the [Sub-Accounts](/bulk-exchange/sub-accounts) page. > [!NOTE] > > Sub-accounts are **off-curve** accounts. Their pubkeys are derived from the master and have no private key. Only the parent master can manage them. *** ## Transaction Envelope ```json theme={null} { "actions": [Action], "nonce": 1704067200000, "account": "master_pubkey_base58", "signer": "master_pubkey_base58", "signature": "base58_signature" } ``` The `account` and `signer` must both be the master account that owns (or will own) the sub-account. *** ## Create Sub-Account (`createSubAccount`) Create a named sub-account under the signing master. Optionally seed it with margin in the same atomic action. Minimal (no initial margin): ```json theme={null} {"createSubAccount": {"name": "desk-1"}} ``` With initial margin transfer: ```json theme={null} { "actions": [ {"createSubAccount": {"name": "desk-1", "marginSymbol": "USDC", "marginAmount": 1000.0}} ], "nonce": 1704067200000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `name` | string | Sub-account display name. 1-32 chars, `A-Z a-z 0-9 - _`. Must be unique within the master's account tree. | | `marginSymbol` | string? | Optional margin asset (e.g. `"USDC"`). Must be present when `marginAmount` is non-zero. | | `marginAmount` | number? | Optional initial margin transferred from master at creation. Default `0.0`. **Must be a JSON number (unquoted)**, e.g. `0` or `1000.0`, not `"0"` or `"1000.0"`. | When both `marginSymbol` and `marginAmount` are provided, the protocol creates the sub-account and transfers margin from the master atomically. The master's withdrawable balance is checked before the transfer. > [!NOTE] > > The newly generated sub-account pubkey is returned in the `createSubAccount` status row (see [Response](#response)), so clients can use it immediately without waiting for an account refresh. *** ## Remove Sub-Account (`removeSubAccount`) Remove a sub-account and sweep any remaining margin back to the master. The sub-account must have no open positions and no open orders. ```json theme={null} { "actions": [ {"removeSubAccount": {"toRemove": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR"}} ], "nonce": 1704067200001, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `toRemove` | string | Sub-account pubkey to remove (base58). Must belong to the signing master. | The same action also removes auto-created [isolated accounts](/bulk-exchange/isolated-margin) once they are flat (no open positions / orders). *** ## Rename Sub-Account (`renameSubAccount`) Update the display name of an existing sub-account owned by the signing master. The pubkey is unchanged, so cached references and isolated-account links keep working. ```json theme={null} { "actions": [ {"renameSubAccount": {"a": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR", "n": "desk-2"}} ], "nonce": 1704067200002, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `a` | string | Sub-account pubkey to rename (base58). Must belong to the signing master. | | `n` | string | New display name. Same charset and length rules as `createSubAccount.name` (1-32 chars, `A-Z a-z 0-9 - _`). Must be unique within the master's account tree. | The signing master can also rename its sub-accounts via an authorized agent wallet, following the same envelope rules as other account-management actions. *** ## Constraints | Constraint | Value | | - | - | | Max sub-accounts per master | 64 | | Max name length | 32 characters | | Allowed name characters | `A-Z`, `a-z`, `0-9`, `-`, `_` | | Sub-accounts can create children | No (master-only) | *** ## Response Same `OrderResponse` envelope as other actions. Sub-account actions emit dedicated status rows: ```json Created theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [ {"createSubAccount": { "master": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "sub": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR", "name": "desk-1", "margin": 1000.0 }} ] } } } ``` ```json Removed theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [ {"removeSubAccount": { "account": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR", "marginMoved": 1000.0 }} ] } } } ``` ```json Renamed theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [ {"renameSubAccount": { "master": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "account": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR", "name": "desk-2" }} ] } } } ``` ```json Failed theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [ {"createSubAccountFailed": {"message": "duplicate name"}} ] } } } ``` | Status | Terminal | Fields | | - | - | - | | `createSubAccount` | Yes | `{master, sub, name, margin}` | | `createSubAccountFailed` | Yes | `{message}` | | `removeSubAccount` | Yes | `{account, marginMoved}` | | `removeSubAccountFailed` | Yes | `{message}` | | `renameSubAccount` | Yes | `{master, account, name}` | | `renameSubAccountFailed` | Yes | `{message}` | > [!NOTE] > > The newly generated sub-account `pubkey` is returned in the `createSubAccount` status, so clients can use it immediately without waiting for an account refresh. *** ## Listing Sub-Accounts A master account's `fullAccount` snapshot includes a `subAccounts` array of `{pubkey, name?}` rows. See [Query Account](/api-reference/getAccount) for the full response shape. *** ## Trading From a Sub-Account Sub-accounts can submit **any** signed action (orders, modify, cancel, on-fill, conditional baskets, transfers, agent wallets, user settings) the same way a master does. There is **no separate endpoint** and **no special action variant**. To act on a sub-account, just set the transaction `account` field to the sub-account's pubkey while the master signs: ```json theme={null} { "actions": [ {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false, "i": false}} ], "nonce": 1704067200000, "account": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Value | | - | - | | `account` | Sub-account pubkey (the account being traded). | | `signer` | One of: the parent master, the sub-account itself, an [agent wallet](/api-reference/manageAgentWallet) registered on the parent master, or an agent wallet registered directly on the sub-account. Agents registered on a master automatically also work for that master's sub-accounts; sub-accounts can additionally register their own agents independently. | | `signature` | Ed25519 over the canonical wincode binary. The signed bytes already include `account`, so the signature binds this transaction to the sub-account. See [Transaction Signing](/api-reference/signing). | Notes: * Margin, positions, open orders, fills, and risk for that transaction are evaluated on the **sub-account's** balance sheet, not the master's. * All conditional and on-fill follow-ups attached to a sub-account order stay on that sub-account. * Any other `signer` (not the master, not the sub-account itself, and not an authorized agent on either) returns `unauthorized signer`. * To route a sub-account order into a per-instrument [isolated account](/bulk-exchange/isolated-margin) attached **to that sub-account**, set `i = true` on the order action. The isolated-account pubkey is never set as `account`. *** ## Before You Start > [!NOTE] > > See [Transaction Signing](/api-reference/signing) for how to sign requests. > > **Nonce**: use a unique value (e.g. timestamp in nanoseconds): `BigInt(Date.now()) * 1_000_000n`. # Order IDs Source: https://docs.bulk.trade/api-reference/orderIds Deterministic order IDs - no client order ID required; compute on the fly or use bulk-keychain Order IDs on BULK are **deterministic**: they are derived from the signed transaction (action, account, nonce, and action index). You do **not** need to supply a client order ID. You can compute the order ID before or after sending the request, and use the official library to do it for you. ## Why deterministic? * **No client order ID required** - The exchange assigns a unique ID from the transaction contents. * **Know the ID before the node responds** - Useful for optimistic UI and local tracking. * **Reproducible** - Same action + account + nonce + index always yields the same order ID. ## Computing order IDs You can compute order IDs yourself from the protocol formula, or use **[bulk-keychain](https://github.com/Bulk-trade/bulk-keychain)** so you don’t have to implement the binary encoding. ### Option 1: Use bulk-keychain (recommended) The official signing library **bulk-keychain** can compute order IDs for you in **Node.js**, **browser (WASM)**, **Rust**, and **Python**. Single-order and batch (group) transactions are supported. | Environment | Package | Install | | - | - | - | | **Node.js** | `bulk-keychain` | `npm install bulk-keychain` | | **Browser (Web)** | `bulk-keychain-wasm` | `npm install bulk-keychain-wasm` | | **Python** | `bulk-keychain` | `pip install bulk-keychain` | | **Rust** | `bulk-keychain` | `cargo add bulk-keychain` | After signing, the returned object includes the order ID(s): **TypeScript (Node.js):** ```typescript theme={null} const signed = signer.sign(order); console.log(signed.orderId); // Pre-computed order ID ``` **Python:** ```python theme={null} signed = signer.sign(order) print(signed.get("order_id")) ``` **Rust:** ```rust theme={null} let signed = signer.sign(order.into(), None)?; println!("Order ID: {:?}", signed.order_id); ``` For **multi-order (grouped)** transactions, enable batch order ID computation so you get an ID per order. See the [bulk-keychain README](https://github.com/Bulk-trade/bulk-keychain) for `signGroup`, `prepareGroup`, and batch order ID options. You can also compute an order ID **without signing** (e.g. for display or lookup) using the library’s `compute_order_id` / `computeOrderId` helpers with order fields, nonce, and account. ### Option 2: Compute from the protocol Order IDs are the base58-encoded SHA-256 hash of: ``` order_id = bs58_encode( sha256(seqno_le_u32 + bincode_serialize(single_action) + account_pubkey_bytes + nonce_le_u64) ) ``` * `seqno`: Zero-based index of the order-producing action in the `actions` array (0 for a single-order tx). * `single_action`: Canonical bincode of that one action (same encoding used for signing). * For limit/market actions, `px` and `sz` use fixed-point: `round(value * 1e8)` as u64. Implementing this requires the same canonical action encoding as the rest of the protocol; using bulk-keychain avoids that. ## Order IDs versus trade IDs An `orderId` identifies one order action. One order can produce multiple fills, and each fill is a separate execution. Authenticated account fill surfaces identify an execution with `tradeId`, a lossless `":"` string. Maker, taker, and isolated-account views of the same execution share the value. Treat it as opaque and network-local: gaps are normal in one account's view, and the value is not portable across forks or networks. `tradeId` is available on paginated account fill history and account WebSocket fill updates. Public `trades.` market-data updates do not currently include it. ## Summary | Need | Approach | | - | - | | Sign and send orders | Use [bulk-keychain](https://github.com/Bulk-trade/bulk-keychain) (Node, Web, Rust, Python). | | Know order ID before response | Use bulk-keychain’s pre-computed order ID after signing (or after prepare, with external wallet). | | Order ID without private key | Use bulk-keychain’s `compute_order_id` / `computeOrderId` with order + nonce + account. | | Reconcile one account fill | Use `tradeId` from account history or account WebSocket fills. | # Place & Cancel Orders (Signed) Source: https://docs.bulk.trade/api-reference/placeOrder api-reference/openapi.yaml POST /order Place limit/market orders, cancel, and modify via the unified transaction endpoint > [!NOTE] > > **4 October 2026 upgrade:** the new `ALO_SLIDE` / `ALO_JOIN` modes, resting-price > alignment, and conditional slippage options below apply after the scheduled upgrade. > Only resting ALO/post-only orders are scheduled to be cleared. GTC and > already-placed conditional orders remain. Untriggered on-fill actions attached > to a cleared ALO order are removed with that parent order. All order operations use the **unified** `POST /order` endpoint. Send a transaction with an `actions` array; each action is a tagged object (e.g. `{"l": {...}}` for a limit order). > [!NOTE] > > See [Transaction Signing](/api-reference/signing) for how to sign requests. Use a unique **nonce** (e.g. nanoseconds): `BigInt(Date.now()) * 1_000_000n`. *** ## Transaction Envelope Every request to `POST /order` has this shape: ```json theme={null} { "actions": [Action, ...], "nonce": 1704067200000, "account": "base58_pubkey", "signer": "base58_pubkey", "signature": "base58_signature" } ``` | Field | Description | | - | - | | `actions` | Array of action objects (see below). Order/cancel/modify use `l`, `m`, `mod`, `cx`, `cxa`, `st`, `tp`, `rng`, `trig`, `trl`, `of`; builder-code approval uses `abc`/`rbc`. | | `nonce` | Unique value for replay protection (e.g. timestamp in nanoseconds). | | `account` | Account public key (base58); whose account is traded. Set this to a [sub-account](/api-reference/manageSubAccounts) pubkey to trade on a sub-account, with its master (or an agent wallet authorized on either) as `signer`. | | `signer` | Signer public key (base58); who is signing. Either the `account` itself, or an authorized [agent wallet](/api-reference/manageAgentWallet) registered on the `account` (or on the parent master when `account` is a sub-account). | | `signature` | Ed25519 signature (base58). | ### Optional Request Header `POST /order` accepts an optional `x-bulk-sig-mode: raw | offchain | base58` header that hints which signature verifier path to try first. The header is a hint only; signature validity still decides accept/reject. Omit it for the default raw canonical-binary path. See [Offchain Signing Mode](/api-reference/signing#offchain-signing-mode). > [!TIP] > > **Trading on a sub-account**: every action on this page (orders, modify, cancel, conditional baskets, on-fill) works on a sub-account exactly the same way. Just set `account` to the sub-account pubkey while its master (or an authorized agent wallet) signs. See [Sub-Accounts: Trading From a Sub-Account](/api-reference/manageSubAccounts#trading-from-a-sub-account). *** ## Isolated Account Routing (`i`) Order actions that produce a position (`l`, `m`, `st`, `tp`, `rng`, `trl`) carry a required `i` boolean. When `i = true`, the order is routed into a per-instrument **isolated account** under the signing `account` instead of its base account. A `trig` basket has no top-level `i`; each nested action controls its own routing. Isolated accounts are managed entirely through this flag; they are never set as `account` on a transaction. ```json theme={null} {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false, "i": true}} ``` Behaviour: * The isolated account is auto-derived from the signing `account` and the instrument; no separate "create" call is required. The protocol attaches it under the signing master/sub-account on first use. * Resulting fills, positions, fees, and risk live on the isolated account, not the base account. Isolated-account rows in account snapshots and history carry `iso = true` and expose the isolated account's pubkey as `isoPubkey`. * A liquidation on the isolated account only touches that account's margin. The signing master/sub-account is unaffected. * Top up isolated-account margin by sending a `transfer` action with `to = isoPubkey`. This is the **only** place an isolated-account pubkey is used directly. See [Transfer](/api-reference/transfer). * Set `i = false` to keep base-account routing. For full conceptual background and lifecycle, see [Isolated Margin](/bulk-exchange/isolated-margin). *** ## Builder Codes Builder codes are optional routed-order fees and only belong on the routed `m` or `l` order. Use `abc` once to approve a recipient, then include the `builderCode` payload on the order sent through that builder. ```json theme={null} {"abc": {"to": "recipient_pubkey_base58", "fee": 5}} ``` ```json theme={null} {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false, "builderCode": {"to": "recipient_pubkey_base58", "fee": 5}}} ``` Rules: * `fee` is basis points and must be `1..=15`. * Each master account can approve at most 10 recipients. A recipient must be an existing canonical root payout account and cannot be the signer, its root, or another account in the same account tree. * Orders without a builder code omit the field entirely. `"builderCode": null` is rejected by the JSON API. * In canonical signing bytes, an absent `builderCode` contributes no bytes; a present value contributes the `Some` tag (`1`), recipient pubkey, and fee. * The builder-code fee applies only to the side whose order carried `builderCode`, whether that side later fills as maker or taker. * `abc` and `rbc` must be signed by the master account. Agent wallets cannot approve or revoke builder-code recipients. Account snapshots expose approved builder-code recipients as `builderCodeApprovals: [{ "recipient": "...", "maxFee": 5 }]`. * Revoking with `rbc` prevents later builder-code fee settlement for resting orders that have not filled yet. ```json theme={null} {"rbc": {"to": "recipient_pubkey_base58"}} ``` See [Builder Codes](/bulk-exchange/builder-codes) for builder-facing behavior and [Transaction Signing](/api-reference/signing) for binary encoding. *** ## Place Limit Order (`l`) ### GTC (Good Till Cancel) Standard limit order that rests on the book. ```json theme={null} { "actions": [ {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false, "i": false}} ], "nonce": 1704067200000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7sVt3k2YxPqH4w..." } ``` ### IOC (Immediate or Cancel) Fills immediately or cancels the unfilled portion. ```json theme={null} {"l": {"c": "BTC-USD", "b": true, "px": 105000.0, "sz": 0.1, "tif": "IOC", "r": false, "i": false}} ``` ### ALO (Add Liquidity Only / Post-Only) Maker only; rejected if it would cross the spread. ```json theme={null} {"l": {"c": "BTC-USD", "b": true, "px": 99000.0, "sz": 0.1, "tif": "ALO", "r": false, "i": false}} ``` ### ALO Slide and ALO Join `ALO_SLIDE` moves a crossing order to the most aggressive non-crossing display tick. `ALO_JOIN` moves a crossing order to the same-side best quote; if there is no same-side quote, it falls back to Slide. A non-crossing order keeps its tick-aligned submitted price. Both modes remain post-only and are still subject to the usual risk and order-validity checks. ```json theme={null} {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "ALO_SLIDE", "r": false, "i": false}} ``` ```json theme={null} {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "ALO_JOIN", "r": false, "i": false}} ``` Use these action objects inside the signed transaction's `actions` array for HTTP or WebSocket submissions. JSON uses the uppercase names; `3` and `4` are their binary signing enum indices, not JSON request values. Existing indices remain `GTC = 0`, `IOC = 1`, and `ALO = 2`. Account/order updates use `postOnlySlide` and `postOnlyJoin` respectively. `GET /exchangeInfo` advertises uppercase names in `timeInForces`. ### Resting Price Alignment Orders capable of resting (`GTC` and the ALO family) align to the market's `pricePrecision` / `tickSize`: buy prices round down and sell prices round up. IOC prices retain native fixed-point precision. For Slide/Join, read the order's reported working price rather than assuming it equals the submitted price. Read `sizeDecimals` and `sizeIncrement` from [`GET /exchangeInfo`](/api-reference/getExchangeInfo) for quantity precision. The increment is not a minimum trade notional; `minNotional` still applies. ### With Builder Code ```json theme={null} {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false, "i": false, "builderCode": {"to": "recipient_pubkey_base58", "fee": 5}}} ``` ### Limit Order Fields | Field | Type | Description | | - | - | - | | `c` | string | Symbol (e.g. "BTC-USD") | | `b` | boolean | `true` = buy, `false` = sell | | `px` | number | Limit price | | `sz` | number | Size/quantity | | `tif` | string | Time in force: `"GTC"`, `"IOC"`, `"ALO"`, `"ALO_SLIDE"`, `"ALO_JOIN"` | | `r` | boolean | Reduce-only | | `i` | boolean | Required. `true` routes the order into the per-instrument [isolated account](/bulk-exchange/isolated-margin) under the signing account; `false` keeps base-account routing. | | `builderCode` | object | Optional builder-code fee payload `{to, fee}`. `fee` is 1..15 bps and must be approved with `abc`. Omit when absent; do not send `null`. | *** ## Place Market Order (`m`) Executes at best available price immediately. An optional `slippage` override is expressed in **basis points**. When omitted, the market's configured default applies. This bounds permitted execution; it does not guarantee a fill. ```json theme={null} { "actions": [ {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false}} ], "nonce": 1704067200001, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7sVt3k2YxPqH4w..." } ``` With builder code: ```json theme={null} {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false, "builderCode": {"to": "recipient_pubkey_base58", "fee": 5}}} ``` | Field | Type | Description | | - | - | - | | `c` | string | Symbol | | `b` | boolean | `true` = buy, `false` = sell | | `sz` | number | Size/quantity | | `r` | boolean | Reduce-only | | `i` | boolean | Required. `true` routes the order into the per-instrument [isolated account](/bulk-exchange/isolated-margin) under the signing account; `false` keeps base-account routing. | | `builderCode` | object | Optional builder-code fee payload `{to, fee}`. `fee` is 1..15 bps and must be approved with `abc`. Omit when absent; do not send `null`. | *** ## Conditional Slippage Overrides Market-executing stop (`st`), take-profit (`tp`), and trailing (`trl`) actions accept an optional `slippage` value in basis points. Range (`rng`) actions use independent `slSlippage` and `tpSlippage` values for their stop-loss and take-profit legs. When absent, the applicable security default is used. A limit-executing leg continues to use its explicit limit price. Use the updated SDK's signing implementation for conditional actions and batches that contain them: the conditional slippage fields participate in canonical signing even when an override is omitted. Do not merely append a JSON field to a transaction signed with an older conditional-action encoder. ## Modify Order (`mod`) Change the size of an existing resting order. ```json theme={null} { "actions": [ {"mod": {"oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "symbol": "BTC-USD", "amount": 0.05}} ], "nonce": 1704067200008, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `oid` | string | Order ID (base58 hash) | | `symbol` | string | Symbol | | `amount` | number | New order size | *** ## Cancel Single Order (`cx`) Cancel a specific order by ID. ```json theme={null} { "actions": [ {"cx": {"c": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F"}} ], "nonce": 1704067200002, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Description | | - | - | | `c` | Symbol | | `oid` | Order ID to cancel (base58) | *** ## Cancel All Orders (`cxa`) ### Cancel all in one symbol ```json theme={null} {"cxa": {"c": ["BTC-USD"]}} ``` ### Cancel all across all symbols ```json theme={null} {"cxa": {"c": []}} ``` | Field | Description | | - | - | | `c` | Array of symbols; use `[]` to cancel all symbols. | *** ## Batch Actions Send multiple actions in one transaction (e.g. cancel + place). ```json theme={null} { "actions": [ {"cx": {"c": "BTC-USD", "oid": "old_order_hash_base58"}}, {"l": {"c": "BTC-USD", "b": true, "px": 99000.0, "sz": 0.05, "tif": "GTC", "r": false, "i": false}}, {"l": {"c": "BTC-USD", "b": false, "px": 101000.0, "sz": 0.05, "tif": "GTC", "r": false, "i": false}} ], "nonce": 1704067200007, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` *** ## Stop Order (`st`) Place a conditional stop order that triggers when price crosses a threshold. ```json theme={null} { "actions": [ {"st": {"c": "BTC-USD", "d": false, "sz": 0.25, "tr": 98000.0, "lim": 97950.0, "i": false}} ], "nonce": 1704067200011, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `c` | string | Symbol | | `d` | boolean | Trigger direction (`true` = above/equal, `false` = below/equal) | | `sz` | number | Size to execute on trigger | | `tr` | number | Trigger threshold price | | `lim` | number? | Optional limit price after trigger. Omit for market-style | | `i` | boolean | Required. `true` routes the triggered order into the per-instrument [isolated account](/bulk-exchange/isolated-margin) under the signing account; `false` keeps base-account routing. | *** ## Take Profit Order (`tp`) Place a conditional take-profit order. ```json theme={null} { "actions": [ {"tp": {"c": "BTC-USD", "d": true, "sz": 0.25, "tr": 104000.0, "lim": 103950.0, "i": false}} ], "nonce": 1704067200012, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` Same fields as Stop Order (`st`). *** ## Range / OCO Order (`rng`) Place a range collar (one-cancels-the-other stop + take-profit pair). ```json theme={null} { "actions": [ {"rng": {"c": "BTC-USD", "d": true, "sz": 0.5, "pmin": 96000.0, "pmax": 106000.0, "lmin": 95950.0, "lmax": 105950.0, "i": false}} ], "nonce": 1704067200013, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `c` | string | Symbol | | `d` | boolean | Position direction (`true` = long collar, `false` = short) | | `sz` | number | Size to protect/exit | | `pmin` | number | Lower trigger threshold | | `pmax` | number | Upper trigger threshold | | `lmin` | number? | Optional limit for lower trigger leg | | `lmax` | number? | Optional limit for upper trigger leg | | `i` | boolean | Required. `true` routes the triggered legs into the per-instrument [isolated account](/bulk-exchange/isolated-margin) under the signing account; `false` keeps base-account routing. | *** ## Trigger Basket (`trig`) Place a trigger that executes a list of actions when threshold is crossed. ```json theme={null} { "actions": [ {"trig": {"c": "BTC-USD", "d": true, "tr": 105000.0, "actions": [ {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false}}, {"cx": {"c": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F"}} ]}} ], "nonce": 1704067200014, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `c` | string | Symbol | | `d` | boolean | Trigger direction (`true` = above/equal, `false` = below/equal) | | `tr` | number | Trigger threshold | | `actions` | Action\[] | Actions executed when trigger fires | The trigger basket itself has no `i`; each nested order or conditional action controls its own isolated routing. Nested actions support: `m`, `l`, `mod`, `cx`, `cxa`, `st`, `tp`, `rng`, `trl`. *** ## Trailing Stop (`trl`) Place a trailing conditional that adjusts with favorable price movement. ```json theme={null} { "actions": [ {"trl": {"c": "BTC-USD", "b": true, "sz": 0.25, "trb": 100, "stb": 10, "lim": null, "i": false}} ], "nonce": 1704067200015, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `c` | string | Symbol | | `b` | boolean | Protected position direction (`true` = long, `false` = short) | | `sz` | number | Size to protect/exit | | `trb` | integer | Trailing distance in bps | | `stb` | integer | Favorable reset step in bps | | `lim` | number? | Optional limit price. `null` for market-style trigger | | `i` | boolean | Required. `true` routes trailing execution into the per-instrument [isolated account](/bulk-exchange/isolated-margin) under the signing account; `false` keeps base-account routing. | *** ## On-Fill (`of`) Register one-shot follow-up actions that execute on the first fill of an embedded trigger action. ```json theme={null} { "actions": [ {"of": { "trigger": { "l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.25, "tif": "GTC", "r": false, "i": false} }, "actions": [ {"st": {"c": "BTC-USD", "d": false, "sz": 0.25, "tr": 98000.0, "lim": null, "i": false}} ] }} ], "nonce": 1704067200016, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `trigger` | Action | Embedded parent action whose first fill activates the plan | | `actions` | Action\[] | One-shot consequents executed on the trigger action's first fill | `trigger` must contain exactly one `m` or `l` action. Builder codes work on an embedded trigger or consequent `m` / `l` exactly as they do on a top-level order. Nested actions support: `m`, `l`, `mod`, `cx`, `cxa`, `st`, `tp`, `rng`, `trig`, `trl`. > [!NOTE] > > **Cancelling conditional orders**: Use `cx` with the conditional order ID or `cxa` to cancel all orders including conditionals. *** ## Response Format All submissions return an `OrderResponse` with one status per execution event: ```json theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [Status, ...] } } } ``` > [!TIP] > > Size fields in responses (`totalSz`, `filledSz`, `remainingSz`) are **signed**: negative values indicate sell-side. For example, a fully-filled sell of 0.1 BTC returns `totalSz: -0.1`. Authentication failures are returned as HTTP 200 with `status: "error"` and `statuses: [{"error":{"message":"bad signature"}}]` or `statuses: [{"error":{"message":"unauthorized signer"}}]`. ### Non-Terminal (order still active) | Status | Description | Fields | | - | - | - | | `resting` | Order placed and resting on book | `{oid}` | | `working` | Partial fills, still resting | `{oid, filledSz, remainingSz, vwap}` | | `triggered` | Conditional root fired | `{oid}` | ### Terminal (order complete) | Status | Description | Fields | | - | - | - | | `filled` | Order fully filled | `{oid, totalSz, avgPx}` | | `partiallyFilled` | Partially filled and terminal | `{oid, totalSz, avgPx}` | | `cancelled` | Cancelled by user | `{oid}` | | `cancelledRiskLimit` | Cancelled - risk limit | `{oid, reason?}` | | `cancelledSelfCrossing` | Cancelled - self-crossing (STP) | `{oid}` | | `cancelledReduceOnly` | Cancelled - would not reduce position | `{oid}` | | `cancelledIoc` | IOC expired without full fill | `{oid, filledSz}` | | `rejectedCrossing` | Post-only rejected for crossing | `{oid}` | | `rejectedDuplicate` | Duplicate order ID | `{oid}` | | `rejectedRiskLimit` | Rejected - risk limit | `{oid, reason?}` | | `rejectedInvalid` | Invalid parameters | `{oid, reason?}` | | `siblingCancelled` | OCO sibling auto-cancelled | `{oid}` | | `triggerFailed` | Trigger execution failed | `{oid, reason?}` | | `deposit` | Faucet deposit succeeded | `{amount}` | | `depositFailed` | Faucet deposit failed | `{message}` | | `agentWallet` | Agent wallet registered | `{agentWallet}` | | `agentWalletFailed` | Agent wallet failed | `{message}` | | `transfer` | Margin transfer succeeded. See [Transfer](/api-reference/transfer) | `{from, to, symbol, amount}` | | `transferFailed` | Margin transfer failed | `{message}` | | `createSubAccount` | Sub-account created. See [Sub-Accounts](/api-reference/manageSubAccounts) | `{master, sub, name, margin}` | | `createSubAccountFailed` | Sub-account creation failed | `{message}` | | `removeSubAccount` | Sub-account removed | `{account, marginMoved}` | | `removeSubAccountFailed` | Sub-account removal failed | `{message}` | | `cancelOneRejected` | Cancel rejected | `{oid, reason}` | | `cancelAllRejected` | Cancel all rejected | `{reason}` | | `error` | Generic error | `{message}` | *** ## Response Examples ```json Resting theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"resting": {"oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F"}}] } } } ``` ```json Working (sell side, signed) theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "working": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "filledSz": -0.05, "remainingSz": -0.05, "vwap": 100000.0 } }] } } } ``` ```json Filled (buy side) theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "filled": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "totalSz": 0.1, "avgPx": 100025.5 } }] } } } ``` ```json Filled (sell side, signed) theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "filled": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "totalSz": -0.1, "avgPx": 100025.5 } }] } } } ``` ```json Triggered (conditional) theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"triggered": {"oid": "9nU4oRhHQkIGY8wOrBTiypn1irpd07GiWeBC7Go6RSj9"}}] } } } ``` ```json Sibling Cancelled (OCO) theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"siblingCancelled": {"oid": "DEF..."}}] } } } ``` ```json Trigger Failed theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"triggerFailed": {"oid": "GHI...", "reason": "conditional execution failed: no counterparty"}}] } } } ``` ```json Cancelled theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"cancelled": {"oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F"}}] } } } ``` ```json Error theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"error": {"message": "Insufficient margin"}}] } } } ``` # Public API Rate Limits Source: https://docs.bulk.trade/api-reference/rate-limits Mainnet public HTTP and WebSocket limits, burst budgets, and retry behavior. These limits apply to the public mainnet endpoints: * HTTP: `https://mainnet-api1.bulk.trade` * WebSocket: `wss://mainnet-ws1.bulk.trade` ## HTTP | Budget | Sustained rate per client IP | Burst capacity | | - | - | - | | API requests | 5 requests/second | 150 requests | | Order actions submitted through `/api/v1/order` | 5 actions/second | 64 actions | Order submissions must satisfy both budgets. A transaction with 20 top-level actions consumes one HTTP request and 20 action tokens. Batching does not bypass the action limit; cancellations also consume action tokens. ## WebSocket | Budget | Public limit | | - | - | | Trading actions | 32 actions/second per connection | | Trading-action burst capacity | 96 actions per connection | | Concurrent connections | 15 per client IP | | New connection attempts | 45/minute per client IP | The trading-action budget counts actions inside submitted transactions, not outbound ticker, order-book, or account updates. It is not a promise of a fixed market-data message rate. Each connection has its own action bucket; concurrent connections and connection attempts remain limited per IP. ## How Bursts Work HTTP request and trading-action budgets use token buckets. Tokens refill at the sustained rate, up to the burst capacity. A burst of 150 HTTP requests is **not** an additional allowance every second or minute. Once that bucket is empty, it refills at five tokens per second. Clients sharing a public IP share HTTP request/action budgets and WebSocket connection limits. WebSocket trading-action buckets are per connection. Pace traffic to the applicable budget rather than treating a burst as a sustained rate. ## Handling Rate Limits * **HTTP:** handle status `429`. The response may come from the API or gateway and is not guaranteed to be JSON. Honor `Retry-After` when supplied; otherwise use bounded exponential backoff with jitter. * **WebSocket trading:** a rate-limited submission can return a negative acknowledgement containing `rate limited: too many actions`. Treat it as a rejected submission, not execution confirmation. * **Connections:** limit simultaneous connections and stagger reconnects with backoff. Reconnecting repeatedly does not reset a per-IP budget. * Prefer WebSocket subscriptions over repeated HTTP polling for market and account updates. Rate limits and protective controls may change. Clients should handle rejection even when operating below the published sustained rates. # Request Testnet Faucet (Signed) Source: https://docs.bulk.trade/api-reference/requestFaucet api-reference/openapi-faucet.yaml POST /order Request testnet funds via the unified transaction endpoint > [!NOTE] > > This action is only available on paper / testnet environments. You can claim once every 24 hours per account. > > Use the testnet endpoint, `https://exchange-api.bulk.trade/api/v1`, for the faucet. It is not available through the primary mainnet endpoint. Faucet requests use the **unified** `POST /order` endpoint. Send a transaction with a `faucet` action in the `actions` array. *** ## Transaction Envelope Every request to `POST /order` has this shape: ```json theme={null} { "actions": [Action, ...], "nonce": 1704067200000, "account": "base58_pubkey", "signer": "base58_pubkey", "signature": "base58_signature" } ``` For faucet, the action is a single `faucet` object. *** ## Faucet Action | Field | Type | Description | | - | - | - | | `u` | string | Recipient public key (base58). | *** ## Request Example ```json theme={null} { "actions": [ {"faucet": {"u": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7"}} ], "nonce": 1704067200000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7sVt3k2YxPqH4w..." } ``` *** ## Response Same `OrderResponse` format as other actions. Success returns a `deposit` status: ```json theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"deposit": {"amount": 10000.0}}] } } } ``` Failure returns `depositFailed`: ```json theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"depositFailed": {"message": "Rate limit exceeded"}}] } } } ``` *** ## Before You Start > [!NOTE] > > See the [Transaction Signing](/api-reference/signing) guide for how to sign your requests. > > **Nonce**: Use a unique value (e.g. timestamp in nanoseconds): `BigInt(Date.now()) * 1_000_000n` # Transaction Signing Source: https://docs.bulk.trade/api-reference/signing All state-mutating operations require network-bound Ed25519 signatures over the canonical wincode binary message All transactions submitted to `POST /order` require **Ed25519 signatures** for authentication. > [!WARNING] > > **4 October 2026 upgrade:** `ALO_SLIDE` and `ALO_JOIN` add TIF indices `3` and `4`; > existing indices remain unchanged. JSON requests use the uppercase names. > Use the updated SDK signing encoder for conditional orders, slippage overrides, > and batches containing conditional actions. The handwritten examples below do > not implement the upgraded conditional-action signing schema and must not be > used to sign those transactions. Omitting a slippage override does not make an > older conditional-action encoder compatible. ## JSON vs Binary Formats The API accepts transactions as **JSON** where all cryptographic fields are **base58-encoded strings**: | Field | JSON Format | Example | | - | - | - | | `account` | base58 string | `"9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt"` | | `signer` | base58 string | `"9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt"` | | `signature` | base58 string | `"5j7sVt3k2YxPqH4w..."` | | Order IDs (`oid`) | base58 string | `"Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F"` | | Pubkeys (`u`, `a`, `target`) | base58 string | `"8DmyR3yJhpQHBqgSGua4c69PZ9ZMeaJddTumUdmTx7a"` | For **signing**, construct the **canonical wincode binary representation** of the transaction (the action list plus the trailing `nonce`, `account`, and one-byte network signature domain), sign those bytes with Ed25519, then base58-encode the 64-byte signature for the JSON payload. **The `signer` field is NOT part of the signed bytes.** ### JSON wire: input tolerance vs. canonical output | Field class | Adapter | Node emits (in responses) | Node accepts (on input) | | - | - | - | - | | Scaled price/size (`sz`, `px`, `tr`, `pmin`, `pmax`) | `serde_safe_f64` | JSON string (e.g. `"0.1"`, `"100000"`) | string **or** JSON number | | Scaled optional (`lim`, `lmin`, `lmax`) | `serde_opt_f64` | string or `null` | string, number, or `null`/absent | | `nonce` | `serde_u64` | JSON string | string or JSON integer | | `Pubkey` / `Hash` / `signature` | `serde_pubkey` / `serde_hash` / `serde_signature` | base58 string | base58 string | | `tif` | derived | `"GTC"` / `"IOC"` / `"ALO"` / `"ALO_SLIDE"` / `"ALO_JOIN"` | same | | Plain `f64` (`mod.sz`, `px.px`, `faucet.amount`, `updateUserSettings.m` values) | default | JSON number | JSON number | | `PythOracle` `t`/`fi`/`px`/`e`, `of.p`, `trl.trb`/`trl.stb` | default | JSON integer | JSON integer | *** ## What Gets Signed The signature is computed over the canonical **wincode** binary serialization of the transaction, excluding `signer` and `signature`: ``` binary_message = wincode_serialize(commission_signable_actions) || nonce_le_u64 // 8 bytes little-endian || account_pubkey_32_bytes // bs58.decode(account) || signature_domain_u8 // mainnet=1, testnet=2, devnet=3 signature = ed25519_sign(binary_message, signer_secret_key) json_signature = bs58_encode(signature) // 64 raw bytes → base58 string ``` **Notes:** * `signer` is required in the JSON payload but is **not** part of the signed bytes. * If `signer != account`, the signer must be an authorized agent for that account. * `account_pubkey_bytes` is raw 32 bytes (`bs58.decode(account)`). * `signature_domain_u8` is selected from trusted client configuration. It is not a JSON transaction field and a server never accepts a client-selected domain header. * The `signature` field itself is not included in what gets signed. > [!NOTE] > > **Nonce**: Use a unique value for replay protection (timestamp in milliseconds or an incrementing counter). On the wire it is `u64` little-endian. *** ## Transaction Structure All signed requests to `POST /order` use this **unified envelope**: ```json theme={null} { "actions": [Action, ...], "nonce": 1704067200000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7sVt3k2YxPqH4w..." } ``` | Field | Description | | - | - | | `actions` | Array of actions to execute atomically (see [Place Order](/api-reference/placeOrder) and related pages). | | `nonce` | Unique integer for replay protection. | | `account` | Account public key (base58); the account performing the action. | | `signer` | Signer public key (base58); who is signing (usually same as account, or authorized agent). | | `signature` | Ed25519 signature (base58) over the wincode binary message. | *** ## Binary Serialization Format (wincode) This describes how each type is encoded in the **binary message** used for signing, **not** the JSON format. The binary wire is **bincode-compatible**: fixed-width little-endian integers, u32 enum tags, u64 length prefixes. | Type | Binary Encoding | | - | - | | Action enum tag (outer `m`/`l`/`mod`/...) | **u32 LE** (4 bytes) discriminant | | `bool` | 1 byte (0 or 1) | | `u8` | 1 byte | | `i16` | 2 bytes LE | | `u32` | 4 bytes LE | | `u64` | 8 bytes LE | | Plain `f64` | 8 bytes LE (raw IEEE-754) | | `String` | u64 length (LE) + UTF-8 bytes | | `Vec` | u64 count (LE) + elements | | `HashMap` | u64 count (LE) + key/value pairs | | `Pubkey` | 32 raw bytes (`bs58.decode` of the base58 string) | | `Hash` (order IDs) | 32 raw bytes (`bs58.decode` of the base58 string) | | `TimeInForce` (`tif`) | **u32 LE** (4 bytes) variant index: `0=GTC`, `1=IOC`, `2=ALO`, `3=ALO_SLIDE`, `4=ALO_JOIN` | | "scaled f64" *(see below)* | **u64 LE** of `round(value * 1e8)` (8 bytes) | | `Option` | 1 byte tag (0=None, 1=Some) + (if Some) u64 LE scaled | | `Option` | 1 byte tag (0=None, 1=Some) + (if Some) raw IEEE-754 f64 | | Optional `builderCode` on `m` / `l` | Absent: no bytes. Present: 1 byte `Some` tag (`1`) + recipient pubkey (32 bytes) + fee bps (`u8`) | > [!NOTE] > > `TimeInForce` is a serde-derived enum, so bincode writes its variant index as a **u32**, the same treatment as the outer action discriminants. ### Scaled vs plain `f64` The exchange uses a **fixed-point-over-bincode** convention for price- and size-like fields: multiply the `f64` value by `1e8`, round to the nearest integer, and serialize it as a **`u64` little-endian (8 bytes)**. **Scaled `f64` fields** (encode as `u64 LE` of `round(x * 1e8)`): | Action | JSON key | Rust field | | - | - | - | | `m` MarketOrder | `sz` | `size` | | `l` LimitOrder | `px`, `sz` | `price`, `size` | | `st` Stop, `tp` TakeProfit | `sz`, `tr` | `size`, `threshold` | | `rng` Range / OCO | `sz`, `pmin`, `pmax` | `size`, `collar_min`, `collar_max` | | `trig` TriggerBasket | `tr` | `threshold` | | `trl` Trailing | `sz` | `size` | **Scaled `Option` fields** (1-byte tag + optional `u64 LE` of `round(x * 1e8)`; encode **absent** as `0x00` tag with no payload): | Action | JSON key | Rust field | | - | - | - | | `st` Stop, `tp` TakeProfit | `lim` | `limit` | | `rng` Range / OCO | `lmin`, `lmax` | `limit_min`, `limit_max` | | `trl` Trailing | `lim` | `limit` | > [!WARNING] > > The old `NaN means market-style trigger` convention is no longer supported. A market-style trigger is now encoded as `Option::None` (`0x00`), not as a NaN-valued `f64`. **Plain `f64` fields** (raw IEEE-754, 8 bytes LE, **no** `1e8` scaling): | Action | JSON key | Rust field | | - | - | - | | `mod` ModifyOrder | `sz` | `amount` | | `px` Price (admin) | `px` | `price` | | `faucet` Faucet | `amount` | `amount` (`Option`, plain: tag + raw f64) | | `updateUserSettings` | values of `m` map | `max_leverage` values (raw f64 per entry) | | `createSubAccount` | `marginAmount` | `margin_amount` (`Option`, plain: tag + raw f64) | | `transfer` | `marginAmount` | `margin_amount` (raw f64) | *** ## Action Discriminants The following values cover the actions documented on this page. Discriminant values are fixed; gaps must not be renumbered. ```typescript theme={null} const ACTION_CODES = { m: 0, // market order l: 1, // limit order mod: 2, // modify order cx: 3, // cancel cxa: 4, // cancel all st: 5, // stop tp: 6, // take profit rng: 7, // range / OCO trig: 8, // trigger basket trl: 9, // trailing of: 10, // on-fill px: 11, // price (admin) // 12 is corrs (admin) o: 13, // pyth oracle (admin) // 14, 15 are beacon/join (admin) faucet: 16, agentWalletCreation: 17, updateUserSettings: 18, whitelistFaucet: 19, // admin // 20-26 are admin (addMarket, configFairPrice, configVolatility, // configSecurity, configRegime, configRisk, cfgf) createSubAccount: 27, removeSubAccount: 28, transfer: 29, rsa: 37, // rename sub-account abc: 40, // approve builder-code fee rbc: 41, // revoke builder-code fee }; const TIME_IN_FORCE_CODES = { GTC: 0, IOC: 1, ALO: 2, }; const TRANSFER_KIND_CODES = { internal: 0, external: 1, }; ``` > [!WARNING] > > `abc` and `rbc` are master-account-only actions. Agent wallets cannot approve or revoke builder-code recipients, even when they are otherwise authorized to sign orders for the account. *** ## Official Signing Library (bulk-keychain) The recommended way to sign transactions is the official **bulk-keychain** library. One Rust core with bindings for: | Environment | Package | Install | | - | - | - | | **Node.js** | `bulk-keychain` | `npm install bulk-keychain` | | **Browser (Web)** | `bulk-keychain-wasm` | `npm install bulk-keychain-wasm` | | **Python** | `bulk-keychain` | `pip install bulk-keychain` | | **Rust** | `bulk-keychain` | `cargo add bulk-keychain` | Repository: **[github.com/Bulk-trade/bulk-keychain](https://github.com/Bulk-trade/bulk-keychain)** It handles the canonical wincode encoding, scaled-f64 convention, single/batch/grouped signing, agent wallet, faucet, and external wallet (prepare/finalize) flows. For deterministic order ID computation, see [Order IDs](/api-reference/orderIds). *** ## Binary Layout All `Pubkey` and `Hash` fields are 32 raw bytes from `bs58.decode()` on the base58 string. `scaled u64` means `writeU64(round(value * 1e8))`. ### Transaction (signed message) ``` [8 bytes] Actions count (u64, LE) For each action: [4 bytes] Action discriminant (u32, LE) [...] Action-specific fields (see below) [8 bytes] Nonce (u64, LE) [32 bytes] Account pubkey (bs58.decode) -- signer pubkey and signature are NOT included in the signed message -- ``` ### MarketOrder (discriminant 0) ``` [8 bytes + N] Symbol string (u64 length + UTF-8) [1 byte] is_buy (bool) [8 bytes] size (scaled u64, round(sz * 1e8)) [1 byte] reduce_only (bool) [1 byte] iso (bool; true routes via the per-instrument isolated account) If builderCode is present: [1 byte] Some tag (1) [32 bytes] recipient pubkey (bs58.decode) [1 byte] fee bps (u8) If builderCode is absent: no bytes ``` ### LimitOrder (discriminant 1) ``` [8 bytes + N] Symbol string (u64 length + UTF-8) [1 byte] is_buy (bool) [8 bytes] price (scaled u64, round(px * 1e8)) [8 bytes] size (scaled u64, round(sz * 1e8)) [4 bytes] tif (u32 LE variant index: 0=GTC, 1=IOC, 2=ALO, 3=ALO_SLIDE, 4=ALO_JOIN) [1 byte] reduce_only (bool) [1 byte] iso (bool; true routes via the per-instrument isolated account) If builderCode is present: [1 byte] Some tag (1) [32 bytes] recipient pubkey (bs58.decode) [1 byte] fee bps (u8) If builderCode is absent: no bytes ``` ### ModifyOrder (discriminant 2) ``` [32 bytes] Order ID (bs58.decode) [8 bytes + N] Symbol string (u64 length + UTF-8) [8 bytes] Amount (plain f64 LE, NOT scaled) ``` ### Cancel (discriminant 3) ``` [8 bytes + N] Symbol string (u64 length + UTF-8) [32 bytes] Order ID (bs58.decode) ``` ### CancelAll (discriminant 4) ``` [8 bytes] Symbols count (u64, LE) For each symbol: [8 bytes + N] Symbol string ``` ### Stop (discriminant 5) and TakeProfit (discriminant 6) ``` [8 bytes + N] Symbol string (u64 length + UTF-8) [1 byte] Trigger direction (bool; true=above/equal, false=below/equal) [8 bytes] Size (scaled u64) [8 bytes] Threshold (scaled u64) [1 byte] Limit tag (0=None, 1=Some) If Some: [8 bytes] Limit (scaled u64) [1 byte] iso (bool; true routes via the per-instrument isolated account) ``` ### Range / OCO (discriminant 7) ``` [8 bytes + N] Symbol string (u64 length + UTF-8) [1 byte] Position direction (bool; true=buy/long collar, false=sell/short collar) [8 bytes] Size (scaled u64) [8 bytes] Collar min (scaled u64) [8 bytes] Collar max (scaled u64) [1 byte] Limit min tag (0=None, 1=Some) If Some: [8 bytes] Limit min (scaled u64) [1 byte] Limit max tag (0=None, 1=Some) If Some: [8 bytes] Limit max (scaled u64) [1 byte] iso (bool; true routes via the per-instrument isolated account) ``` ### Trigger Basket (discriminant 8) ``` [8 bytes + N] Symbol string (u64 length + UTF-8) [1 byte] Trigger direction (bool; true=above/equal, false=below/equal) [8 bytes] Threshold (scaled u64) [8 bytes] Nested action count (u64, LE) For each nested action: [4 bytes] Action discriminant (u32, LE) [...] Action payload ``` Trigger baskets have no top-level `i`; each nested order or conditional action carries its own isolated-routing field. ### Trailing (discriminant 9) ``` [8 bytes + N] Symbol string (u64 length + UTF-8) [1 byte] Position direction (bool; true=long protection, false=short protection) [8 bytes] Size (scaled u64) [4 bytes] Trail bps (u32, LE) [4 bytes] Step bps (u32, LE) [1 byte] Limit tag (0=None, 1=Some) If Some: [8 bytes] Limit (scaled u64) [1 byte] iso (bool; true routes via the per-instrument isolated account) ``` ### OnFill (discriminant 10) ``` [4 bytes] Trigger action discriminant (u32, LE) [...] Trigger action payload [8 bytes] Consequent action count (u64, LE) For each consequent action: [4 bytes] Action discriminant (u32, LE) [...] Action payload ``` The trigger action is embedded in `of.trigger`; on-fill does not serialize a parent action index or sequence number. ### Price (discriminant 11): admin ``` [8 bytes] Timestamp (u64, LE) [8 bytes + N] Asset string (u64 length + UTF-8) [8 bytes] Price (plain f64 LE, NOT scaled) ``` ### PythOracle (discriminant 13): admin ``` [8 bytes] Oracles count (u64, LE) For each oracle: [8 bytes] Timestamp (u64, LE) [8 bytes] Feed ID (u64, LE) [8 bytes] Price (u64, LE; raw integer price from Pyth, NOT scaled) [2 bytes] Exponent (i16, LE) ``` ### Faucet (discriminant 16) ``` [32 bytes] User pubkey (bs58.decode) [1 byte] Amount tag (0=None, 1=Some) If Some: [8 bytes] Amount (plain f64 LE, NOT scaled) ``` ### AgentWalletCreation (discriminant 17) ``` [32 bytes] Agent pubkey (bs58.decode) [1 byte] Delete flag (bool) ``` ### UpdateUserSettings (discriminant 18) ``` [8 bytes] Entry count (u64, LE) For each entry: [8 bytes + N] Symbol string [8 bytes] Max leverage (plain f64 LE, NOT scaled) ``` ### WhitelistFaucet (discriminant 19): admin ``` [32 bytes] Target pubkey (bs58.decode) [1 byte] Whitelist flag (bool) ``` ### ApproveBuilderCode (discriminant 40) ``` [32 bytes] Recipient pubkey (bs58.decode) [1 byte] Max fee bps (u8, 1..15) ``` ### RevokeBuilderCode (discriminant 41) ``` [32 bytes] Recipient pubkey (bs58.decode) ``` ### CreateSubAccount (discriminant 27) ``` [8 bytes + N] Name string (u64 length + UTF-8) [1 byte] margin_symbol tag (0=None, 1=Some) If Some: [8 bytes + M] margin_symbol string (u64 length + UTF-8) [1 byte] margin_amount tag (0=None, 1=Some) If Some: [8 bytes] margin_amount (plain f64 LE, NOT scaled) ``` ### RemoveSubAccount (discriminant 28) ``` [32 bytes] toRemove pubkey (bs58.decode; sub-account or per-instrument isolated-account pubkey to remove) ``` ### Transfer (discriminant 29) ``` [4 bytes] kind (u32 LE variant index: 0=internal, 1=external) [32 bytes] from pubkey (bs58.decode) [32 bytes] to pubkey (bs58.decode) [8 bytes + N] marginSymbol string (u64 length + UTF-8) [8 bytes] marginAmount (plain f64 LE, NOT scaled) ``` ### RenameSubAccount (discriminant 37, tag `rsa`) ``` [32 bytes] Sub-account pubkey (bs58.decode; the sub-account to rename) [8 bytes + N] New name string (u64 length + UTF-8) ``` *** ## Signing Example (JavaScript/TypeScript) > [!WARNING] > > **Reference only.** Serialization must match the canonical BULK wincode encoding exactly. For production, prefer the official [bulk-keychain](https://github.com/Bulk-trade/bulk-keychain) library. ### Install Dependencies ```bash theme={null} pnpm install tweetnacl bs58 # or yarn add tweetnacl bs58 ``` ### Implementation ```typescript Writers & scaled-f64 convention theme={null} import * as nacl from 'tweetnacl'; import bs58 from 'bs58'; // --- Primitive writers (little-endian, fixed-width, bincode-compatible) --- function writeU8(value: number): Uint8Array { return new Uint8Array([value & 0xff]); } function writeU32(value: number): Uint8Array { const buf = new Uint8Array(4); new DataView(buf.buffer).setUint32(0, value, true); return buf; } function writeI16(value: number): Uint8Array { const buf = new Uint8Array(2); new DataView(buf.buffer).setInt16(0, value, true); return buf; } function writeU64(value: number | bigint): Uint8Array { const buf = new Uint8Array(8); new DataView(buf.buffer).setBigUint64(0, BigInt(value), true); return buf; } function writeF64(value: number): Uint8Array { const buf = new Uint8Array(8); new DataView(buf.buffer).setFloat64(0, value, true); return buf; } function writeBool(value: boolean): Uint8Array { return new Uint8Array([value ? 1 : 0]); } function writeString(str: string): Uint8Array { const bytes = new TextEncoder().encode(str); return concatBytes(writeU64(bytes.length), bytes); } function concatBytes(...arrays: Uint8Array[]): Uint8Array { const total = arrays.reduce((s, a) => s + a.length, 0); const out = new Uint8Array(total); let off = 0; for (const a of arrays) { out.set(a, off); off += a.length; } return out; } // --- Exchange fixed-point convention --- const SCALE = 1e8; /** Scaled f64: encoded as u64 LE of round(x * 1e8). */ function writeScaled(value: number): Uint8Array { const fixed = Math.round(value * SCALE); if (!Number.isFinite(fixed) || fixed < 0) { throw new Error(`scaled value must be a finite non-negative number (got ${value})`); } return writeU64(BigInt(fixed)); } /** Option: 1-byte tag + (if Some) u64 LE scaled. */ function writeOptScaled(value: number | null | undefined): Uint8Array { if (value === null || value === undefined) return writeU8(0); return concatBytes(writeU8(1), writeScaled(value)); } /** Option: 1-byte tag + (if Some) raw IEEE-754 f64 LE. */ function writeOptF64(value: number | null | undefined): Uint8Array { if (value === null || value === undefined) return writeU8(0); return concatBytes(writeU8(1), writeF64(value)); } /** * CommissionSignableActions omits builderCode completely when absent. When * present, it encodes Option::Some as tag(1) + recipient pubkey + fee bps. */ function writeBuilderCode(value: {to: string, fee: number} | null | undefined): Uint8Array { if (value === null || value === undefined) return new Uint8Array(); return concatBytes(writeU8(1), bs58.decode(value.to), writeU8(value.fee)); } ``` ```typescript Action bodies theme={null} // Each action body starts with a u32 LE discriminant. const TIF_CODES: Record = { GTC: 0, IOC: 1, ALO: 2, ALO_SLIDE: 3, ALO_JOIN: 4 }; function serializeMarketOrder(o: any): Uint8Array { return concatBytes( writeU32(0), // discriminant writeString(o.c), // symbol writeBool(o.b), // is_buy writeScaled(o.sz), // size (scaled u64) writeBool(o.r), // reduce_only writeBool(!!o.i), // iso (default false) writeBuilderCode(o.builderCode), // optional builder-code fee ); } function serializeLimitOrder(o: any): Uint8Array { return concatBytes( writeU32(1), // discriminant writeString(o.c), // symbol writeBool(o.b), // is_buy writeScaled(o.px), // price (scaled u64) writeScaled(o.sz), // size (scaled u64) writeU32(TIF_CODES[o.tif] ?? 0),// tif (u32 LE variant index) writeBool(o.r), // reduce_only writeBool(!!o.i), // iso (default false) writeBuilderCode(o.builderCode), // optional builder-code fee ); } function serializeModifyOrder(d: any): Uint8Array { return concatBytes( writeU32(2), // discriminant bs58.decode(d.oid), // order ID (32 bytes) writeString(d.c), // symbol writeF64(d.sz), // amount (plain f64, NOT scaled) ); } function serializeCancel(d: any): Uint8Array { return concatBytes( writeU32(3), // discriminant writeString(d.c), // symbol bs58.decode(d.oid), // order ID (32 bytes) ); } function serializeCancelAll(d: any): Uint8Array { const parts: Uint8Array[] = [writeU32(4), writeU64(d.c.length)]; for (const sym of d.c) parts.push(writeString(sym)); return concatBytes(...parts); } // Stop (5) and TakeProfit (6) share the same body layout. function serializeStopOrTP(disc: 5 | 6, d: any): Uint8Array { return concatBytes( writeU32(disc), // discriminant writeString(d.c), // symbol writeBool(d.d), // trigger direction (is_above) writeScaled(d.sz), // size (scaled u64) writeScaled(d.tr), // threshold (scaled u64) writeOptScaled(d.lim), // limit (Option) writeBool(!!d.i), // iso (default false) ); } function serializeRange(d: any): Uint8Array { return concatBytes( writeU32(7), // discriminant writeString(d.c), // symbol writeBool(d.d), // position direction writeScaled(d.sz), // size (scaled u64) writeScaled(d.pmin), // collar_min (scaled u64) writeScaled(d.pmax), // collar_max (scaled u64) writeOptScaled(d.lmin), // limit_min (Option) writeOptScaled(d.lmax), // limit_max (Option) writeBool(!!d.i), // iso (default false) ); } function serializeTriggerBasket(d: any): Uint8Array { const nested = d.actions || []; const parts: Uint8Array[] = [ writeU32(8), // discriminant writeString(d.c), // symbol writeBool(d.d), // trigger direction writeScaled(d.tr), // threshold (scaled u64) writeU64(nested.length), // nested action count ]; for (const n of nested) parts.push(serializeAction(n)); return concatBytes(...parts); } function serializeTrailing(d: any): Uint8Array { return concatBytes( writeU32(9), // discriminant writeString(d.c), // symbol writeBool(d.b), // position direction (is_buy) writeScaled(d.sz), // size (scaled u64) writeU32(d.trb), // trail_bps (u32) writeU32(d.stb), // step_bps (u32) writeOptScaled(d.lim), // limit (Option) writeBool(!!d.i), // iso (default false) ); } function serializeOnFill(d: any): Uint8Array { const nested = d.actions || []; const parts: Uint8Array[] = [ writeU32(10), // discriminant serializeAction(d.trigger), // action that triggers on its first fill writeU64(nested.length), // consequent action count ]; for (const n of nested) parts.push(serializeAction(n)); return concatBytes(...parts); } function serializePrice(d: any): Uint8Array { return concatBytes( writeU32(11), // discriminant writeU64(d.t), // timestamp writeString(d.c), // asset writeF64(d.px), // price (plain f64, NOT scaled) ); } function serializePythOracle(d: any): Uint8Array { const oracles = d.oracles || []; const parts: Uint8Array[] = [writeU32(13), writeU64(oracles.length)]; for (const o of oracles) { parts.push( writeU64(o.t), // timestamp writeU64(o.fi), // feed id writeU64(o.px), // price (raw u64) writeI16(o.e), // exponent ); } return concatBytes(...parts); } function serializeFaucet(d: any): Uint8Array { return concatBytes( writeU32(16), // discriminant bs58.decode(d.u), // user pubkey writeOptF64(d.amount), // amount (Option) ); } function serializeAgentWalletCreation(d: any): Uint8Array { return concatBytes( writeU32(17), // discriminant bs58.decode(d.a), // agent pubkey writeBool(d.d), // delete flag ); } function serializeUpdateUserSettings(d: any): Uint8Array { const entries = Object.entries(d.m || {}) as [string, number][]; // NOTE: server deserializes into HashMap. If you sign more than one // entry you MUST use the same iteration order as the server would on re-serialize. // Today the safest path is to submit a single-entry map at a time. const parts: Uint8Array[] = [writeU32(18), writeU64(entries.length)]; for (const [sym, lev] of entries) { parts.push(writeString(sym), writeF64(lev)); // leverage is plain f64 } return concatBytes(...parts); } function serializeWhitelistFaucet(d: any): Uint8Array { return concatBytes( writeU32(19), // discriminant bs58.decode(d.target), // target pubkey writeBool(d.whitelist), // whitelist flag ); } function serializeApproveBuilderCode(d: any): Uint8Array { return concatBytes( writeU32(40), // discriminant bs58.decode(d.to), // recipient pubkey writeU8(d.fee), // max fee bps ); } function serializeRevokeBuilderCode(d: any): Uint8Array { return concatBytes( writeU32(41), // discriminant bs58.decode(d.to), // recipient pubkey ); } function serializeAction(action: any): Uint8Array { const [type, data] = Object.entries(action)[0] as [string, any]; switch (type) { case 'm': return serializeMarketOrder(data); case 'l': return serializeLimitOrder(data); case 'mod': return serializeModifyOrder(data); case 'cx': return serializeCancel(data); case 'cxa': return serializeCancelAll(data); case 'st': return serializeStopOrTP(5, data); case 'tp': return serializeStopOrTP(6, data); case 'rng': return serializeRange(data); case 'trig': return serializeTriggerBasket(data); case 'trl': return serializeTrailing(data); case 'of': return serializeOnFill(data); case 'px': return serializePrice(data); case 'o': return serializePythOracle(data); case 'faucet': return serializeFaucet(data); case 'agentWalletCreation': return serializeAgentWalletCreation(data); case 'abc': return serializeApproveBuilderCode(data); case 'rbc': return serializeRevokeBuilderCode(data); case 'updateUserSettings': return serializeUpdateUserSettings(data); case 'whitelistFaucet': return serializeWhitelistFaucet(data); default: throw new Error(`Unknown action: ${type}`); } } ``` ```typescript Sign & send theme={null} function serializeTransaction( actions: any[], nonce: number | bigint, account: string, signatureDomain: 1 | 2 | 3, ): Uint8Array { const parts: Uint8Array[] = [writeU64(actions.length)]; for (const action of actions) parts.push(serializeAction(action)); parts.push(writeU64(nonce)); parts.push(bs58.decode(account)); // 32 bytes parts.push(Uint8Array.of(signatureDomain)); return concatBytes(...parts); } function signTransaction( secretKey: Uint8Array, actions: any[], nonce: number | bigint, account: string, signatureDomain: 1 | 2 | 3, ): string { const message = serializeTransaction(actions, nonce, account, signatureDomain); const signature = nacl.sign.detached(message, secretKey); return bs58.encode(signature); } // --- Usage --- const account = "9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt"; const signer = account; const secretKey = bs58.decode("YOUR_SECRET_KEY_BASE58"); // 64 bytes const nonce = Date.now(); const signatureDomain = 1; // mainnet=1, testnet=2, devnet=3 const actions = [ { l: { c: "BTC-USD", b: true, px: 100000.0, sz: 0.1, tif: "GTC", r: false, i: false } }, ]; const signature = signTransaction(secretKey, actions, nonce, account, signatureDomain); const tx = { actions, nonce, account, signer, signature }; await fetch('https://mainnet-api1.bulk.trade/api/v1/order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(tx), }); ``` *** ## Account vs Signer The transaction includes two separate public key fields: * **`account`**: The account being traded (whose positions/orders are affected). * **`signer`**: Who is signing the transaction (usually same as account, or an authorized agent). ### Same Account and Signer Most common case, you're trading your own account: ```javascript theme={null} const transaction = { actions: [{ l: { c: "BTC-USD", b: true, px: 100000.0, sz: 0.1, tif: "GTC", r: false, i: false } }], nonce: Date.now(), account: myPublicKey, signer: myPublicKey, signature: "..." }; ``` ### Agent Wallet (Different Signer) Agent wallet trading on behalf of user: ```javascript theme={null} const transaction = { actions: [{ l: { c: "BTC-USD", b: true, px: 100000.0, sz: 0.1, tif: "GTC", r: false, i: false } }], nonce: Date.now(), account: userPublicKey, // User's account being traded signer: agentPublicKey, // Agent signing (must be pre-authorized) signature: "..." }; ``` Requirements: 1. Agent must be pre-authorized via an `agentWalletCreation` action (see [Manage Agent Wallet](/api-reference/manageAgentWallet)). 2. Agent signs with their own private key. 3. Order executes against the user's account. > [!WARNING] > > **Agent Wallets**: If `signer != account`, the signer must be pre-authorized via [Manage Agent Wallet](/api-reference/manageAgentWallet) first. *** ## Offchain Signing Mode The default and preferred signing path is the raw canonical-binary form documented above. The server additionally accepts an **offchain signing mode** for any transaction shape. This exists so that wallets/devices that can only sign clear-text messages (Phantom, Ledger, hardware signers) can still produce valid transactions. ### Signature Mode Hint Header When you use offchain signing, set this hint header so the verifier tries the matching path first: | Surface | Header | Allowed values | | - | - | - | | `POST /order` (HTTP) | `x-bulk-sig-mode` | `raw` \| `offchain` \| `base58` | | WebSocket upgrade (handshake) | `x-bulk-sig-mode` | `raw` \| `offchain` \| `base58` | Semantics: * Missing header: server uses the default raw canonical-binary verification path. * Invalid value: ignored safely (falls back to the default raw path). * Valid value: used **only as an attempt-order hint**. Signature validity still decides accept/reject. * The header is never trusted for authentication by itself. * Offchain-signed payloads should set `x-bulk-sig-mode: offchain`. ### Offchain Envelope The signed bytes are the full Solana v0 offchain-message envelope: ```text theme={null} 0xff "solana offchain" || version(0x00) || app_domain(signature_domain_u8 || 31 zero bytes) || format(1 byte) || signer_count(1 byte = 0x01) || signer_pubkey(32 bytes) || payload_len(u16 LE) || payload ``` * `format = 0x00` -> printable ASCII payload. * `format = 0x01` -> UTF-8 payload. * The server verifies the **exact full envelope bytes**; nothing is chunked or truncated. Practical signability is limited by the wallet/device. ### Offchain Payload (Clear-Sign Text) The `payload` is deterministic clear-sign text built from the transaction fields. Action lines are emitted in transaction order: ```text theme={null} Bulk Exchange Transaction Network: Account: Nonce: Actions: Signable-Hash: [0] [1] ... ``` Optional debug/verbose line (off by default for cleaner Ledger UX): ```text theme={null} Signable-Schema: bincode(commission_signable_actions)||nonce_le_u64||account_bytes||signature_domain_u8 ``` Submission rules: * HTTP: send the standard transaction JSON to `POST /order` with `x-bulk-sig-mode: offchain`. `signature` is base58 of the 64-byte Ed25519 signature over the envelope above. * WebSocket: set the handshake header `x-bulk-sig-mode: offchain` on the upgrade, then post transactions normally via the `post` method. * The raw canonical-binary path remains the default for any connection that does not opt in. ### Legacy Wallet-Compatibility Path (Owner-Signed `agentWalletCreation` Only) For a **single owner-signed `agentWalletCreation` action** (`signer == account` and exactly one action), the server additionally accepts two legacy compatibility signatures, intended to support older wallet UIs that cannot use the general offchain mode above: 1. Signature over `bs58_encode(canonical_binary_message).as_bytes()`. 2. Signature over the same v0 Solana offchain-message envelope described above, wrapping the canonical binary message as the payload (`format = 0x00`). These paths exist only for owner registration / removal of agent wallets. Use the canonical binary path or the general offchain mode for everything else. *** ## Implementation Notes > [!TIP] > > **Official signing library**: [bulk-keychain](https://github.com/Bulk-trade/bulk-keychain) provides signing for Node.js, browser (WASM), Python, and Rust with the correct protocol encoding (scaled-f64 convention, discriminants, and order-ID hashing). For production use, prefer bulk-keychain over manual implementation. ### Common Issues > [accordion] Invalid signature > > The binary message must match the server's wincode serialization exactly: > > * Use `bs58.decode()` to convert base58 `Pubkey`/`Hash` strings into raw 32-byte arrays. > * All enum variant tags (outer action types **and** `tif`) are `u32` LE. > * `Vec`/`String` lengths are `u64` LE. > * Price/size/threshold/limit `f64` fields are **fixed-point scaled** (`round(x * 1e8)` as `u64` LE), not raw `f64`. The plain-`f64` fields are listed in the encoding table above. > * The `signature` itself is NOT part of the signed message. Sign the binary, then `bs58.encode()` the 64-byte Ed25519 signature for the JSON payload. > * Order actions `l`, `m`, `st`, `tp`, `rng`, and `trl` always serialise the trailing `i` (isolated routing) byte. Always include `i` in those JSON payloads (`true` or `false`); omitting it produces a `bad signature`. > * A `trig` basket has no top-level `i`. Each nested order or conditional action carries its own `i`. > [accordion] Unauthorized signer > > If `signer != account`, the signer must be pre-authorized for `account`: > > * The `account` itself is always allowed to sign for itself. > * [Agent wallets](/api-reference/manageAgentWallet) registered on a master can sign for that master **and for any of its [sub-accounts](/api-reference/manageSubAccounts)**. Sub-accounts can also register their own agent wallets. > * For sub-accounts, set `account` to the sub-account pubkey and `signer` to the master, the sub-account itself, or any agent wallet registered on either. > * Isolated accounts are never set as `account` directly; orders routed there use the `i` flag on the master/sub-account transaction. See [Isolated Margin](/bulk-exchange/isolated-margin). > [accordion] Account not found > > Account must be funded first via a faucet action (see [Request Faucet](/api-reference/requestFaucet) on testnet). > [accordion] Replay attack / duplicate nonce > > Each nonce can only be used once. Use timestamps or incrementing counters. > [accordion] Round-tripping server responses into signatures > > Scaled fields (`sz`, `px`, `tr`, `pmin`, `pmax`, `lim`, `lmin`, `lmax`) are returned as **JSON strings** in responses but must be signed from their numeric value (`parseFloat` → `round(x * 1e8)`). # Transfer (Signed) Source: https://docs.bulk.trade/api-reference/transfer api-reference/openapi-transfer.yaml POST /order Move margin between accounts (internal, external, isolated-account top-up) via the unified transaction endpoint Transfers use the **unified** `POST /order` endpoint. Send a transaction with a single `transfer` action. Conceptual background lives on the [Protocol Native Asset Transfer](/architecture/transfers) page. > [!NOTE] > > A transfer is rejected if it would push the source account into liquidation territory. The protocol bounds withdrawable amount by `min(equity − 1.05 × MM, marginPnl)`. *** ## Transaction Envelope ```json theme={null} { "actions": [Action], "nonce": 1704067200000, "account": "authorizing_pubkey_base58", "signer": "authorizing_pubkey_base58", "signature": "base58_signature" } ``` The `account` and `signer` must be the authorizing account: * `internal`: must be the master account that owns both `from` and `to`. * `external`: must be the account that owns the source. *** ## Transfer Action (`transfer`) ```json theme={null} { "actions": [ {"transfer": { "k": "internal", "from": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "to": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR", "marginSymbol": "USDC", "marginAmount": 100.0 }} ], "nonce": 1704067200000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` | Field | Type | Description | | - | - | - | | `k` | string | Transfer kind: `"internal"` (default) or `"external"`. | | `from` | string | Source account pubkey (base58). | | `to` | string | Destination account pubkey (base58). For per-instrument isolated-account top-ups, use the `isoPubkey` of an `iso=true` position row. | | `marginSymbol` | string | Margin asset symbol (e.g. `"USDC"`). | | `marginAmount` | number | Margin amount to transfer. **Must be a JSON number (unquoted)**, e.g. `100.0` not `"100.0"`. | *** ## Transfer Kinds ### Internal Move margin between accounts that share the same master (master to sub-account, sub-account to sub-account, master to a per-instrument isolated account, and back). No minimum amount. ```json theme={null} {"transfer": { "k": "internal", "from": "MASTER_PUBKEY", "to": "SUB_OR_ISO_PUBKEY", "marginSymbol": "USDC", "marginAmount": 100.0 }} ``` ### Isolated-account top-up To add margin to a per-instrument [isolated account](/bulk-exchange/isolated-margin), set `to` to the `isoPubkey` returned on `iso=true` rows in the `fullAccount`/`positions` snapshot. ```json theme={null} {"transfer": { "k": "internal", "from": "MASTER_OR_SUB_PUBKEY", "to": "ISO_ACCOUNT_PUBKEY", "marginSymbol": "USDC", "marginAmount": 100.0 }} ``` ### External Move margin to any account on the network. Subject to a per-symbol minimum amount. ```json theme={null} {"transfer": { "k": "external", "from": "MASTER_PUBKEY", "to": "ANY_OTHER_PUBKEY", "marginSymbol": "USDC", "marginAmount": 50.0 }} ``` Notes: * `external` supports recipient auto-create only when the destination is on-curve (a real Solana wallet). * Unknown off-curve recipients are rejected; no implicit account creation. *** ## Response Same `OrderResponse` envelope. Successful transfers emit a `transfer` status row; failures emit `transferFailed`. ```json Success theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [ {"transfer": { "from": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "to": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR", "symbol": "USDC", "amount": 100.0 }} ] } } } ``` ```json Failed theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"transferFailed": {"message": "below minimum"}}] } } } ``` | Status | Terminal | Fields | | - | - | - | | `transfer` | Yes | `{from, to, symbol, amount}` | | `transferFailed` | Yes | `{message}` | *** ## Common Error Messages | Message | Cause | | - | - | | `no margin symbol` | The specified token symbol does not exist | | `unknown margin symbol` | The symbol exists but is not a recognized security | | `below minimum` | External transfer amount is below the per-symbol minimum | | `off-curve and does not exist` | External transfer to an off-curve address with no protocol account | | `not permissioned for internal transfer` | `from` or `to` is not in the signer's account tree | | `source account not found` | `from` does not exist | Failed transfers do not modify any account state. *** ## Margin-only Refresh `transfer` (along with `createSubAccount` with margin move and `removeSubAccount`) triggers a same-tick margin/risk refresh on the touched accounts. The `OrderResponse` is returned synchronously, so the response may arrive before the corresponding [account stream](/api-reference/ws-account) delta. *** ## Before You Start > [!NOTE] > > See [Transaction Signing](/api-reference/signing) for how to sign requests. > > **Nonce**: use a unique value (e.g. timestamp in nanoseconds): `BigInt(Date.now()) * 1_000_000n`. # Update User Settings (Signed) Source: https://docs.bulk.trade/api-reference/updateUserSettings api-reference/openapi-update-settings.yaml POST /order Set per-symbol max leverage via the unified transaction endpoint Leverage settings are updated via the **unified** `POST /order` endpoint. Send a transaction with an `updateUserSettings` action in the `actions` array. *** ## Transaction Envelope Every request to `POST /order` has this shape: ```json theme={null} { "actions": [Action, ...], "nonce": 1704067200000, "account": "base58_pubkey", "signer": "base58_pubkey", "signature": "base58_signature" } ``` For user settings, the action is a single `updateUserSettings` object. *** ## Settings Fields ### Max Leverage (`m`) Object mapping symbol to maximum leverage (1.0–50.0). Cannot exceed the market’s configured maximum. | Field | Type | Description | | - | - | - | | `m` | object | Map of symbol → max_leverage (e.g. `{"BTC-USD": 5.0, "ETH-USD": 3.0}`). | **Constraints:** * Leverage is clamped between `1.0` and `50.0` * Cannot exceed the market’s configured maximum leverage * Lower leverage reduces liquidation risk *** ## Request Example ```json theme={null} { "actions": [ {"updateUserSettings": {"m": {"BTC-USD": 5.0, "ETH-USD": 3.0}}} ], "nonce": 1704067200000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5JXWgp1fW6px2Gjhw6YHhQ4wEqb6FqMam6m4yg4uRcCksH9WxSv9dVjizGfD4StGtv1z9gR71unZY6tQ6dNDdJ3K" } ``` *** ## Response Same `OrderResponse` format as other actions. For update user settings, success returns an empty or applied status; settings are applied to the account. ```json theme={null} { "status": "ok", "response": { "type": "order", "data": { "statuses": [] } } } ``` *** ## Before You Start > [!NOTE] > > See the [Transaction Signing](/api-reference/signing) guide for how to sign your requests. > > **Nonce**: Use a unique value (e.g. timestamp in nanoseconds): `BigInt(Date.now()) * 1_000_000n` # WebSocket Overview Source: https://docs.bulk.trade/api-reference/websocket-intro Real-time market data and trading via WebSocket ## Connection ```javascript Production theme={null} const ws = new WebSocket('wss://mainnet-ws1.bulk.trade'); ``` **Primary Mainnet WebSocket URL**: `wss://mainnet-ws1.bulk.trade` **Testnet WebSocket URL**: `wss://exchange-ws1.bulk.trade` ### Ping-Pong Keepalive The server sends a WebSocket **ping** frame every **30 seconds**. The client **must** reply with a **pong** frame; if no pong is received within **10 seconds**, the server disconnects the connection. Ping/pong are transport-level frames, not application (JSON) messages. Many client libraries respond to ping automatically. See [Connection Management](/api-reference/ws-connection#ping-pong-keepalive-required) for details. *** ## Stream Types > [card] [Market Data](/api-reference/ws-market-data) > > Real-time price feeds, order books, and trades > [card] [Account Updates](/api-reference/ws-account) > > Live position and order updates > [card] [Trading](/api-reference/ws-trading) > > Submit orders via WebSocket for lowest latency > [card] [Connection Management](/api-reference/ws-connection) > > Subscriptions, reconnection, and best practices *** ## Quick Example ```javascript Node.js theme={null} const WebSocket = require('ws'); const ws = new WebSocket('wss://mainnet-ws1.bulk.trade'); ws.on('open', () => { // Subscribe to ticker ws.send(JSON.stringify({ method: 'subscribe', subscription: [{ type: 'ticker', symbol: 'BTC-USD' }] })); }); ws.on('message', (data) => { const message = JSON.parse(data); // Handle subscription confirmation if (message.type === 'subscriptionResponse') { console.log('Subscribed to:', message.topics); return; } // Handle ticker updates if (message.type === 'ticker') { console.log('Ticker:', message.data.ticker); } }); ``` ```python Python theme={null} import websocket import json def on_message(ws, message): data = json.loads(message) # Handle subscription confirmation if data.get('type') == 'subscriptionResponse': print(f"Subscribed to: {data['topics']}") return # Handle ticker updates if data.get('type') == 'ticker': print(f"Ticker: {data['data']['ticker']}") def on_open(ws): ws.send(json.dumps({ 'method': 'subscribe', 'subscription': [{ 'type': 'ticker', 'symbol': 'BTC-USD' }] })) ws = websocket.WebSocketApp( 'wss://mainnet-ws1.bulk.trade', on_message=on_message, on_open=on_open ) ws.run_forever() ``` *** ## Subscription Response Format All subscriptions return a confirmation with topic strings: ```json theme={null} // Request { "method": "subscribe", "subscription": [ {"type": "ticker", "symbol": "BTC-USD"}, {"type": "trades", "symbol": "BTC-USD"} ] } // Response { "type": "subscriptionResponse", "topics": [ "ticker.BTC-USD", "trades.BTC-USD" ] } ``` Use the topic strings to unsubscribe later. *** ## Unsubscribe ```json theme={null} { "method": "unsubscribe", "topic": "ticker.BTC-USD" } ``` *** ## Rate Limits The public mainnet endpoint allows **32 trading actions/second per connection**, with a **96-action burst per connection**, **15 concurrent connections per IP**, and **45 new connection attempts/minute per IP**. Trading-action limits are not outbound market-data message limits. See [Public API Rate Limits](/api-reference/rate-limits) for shared-IP budgets and retry behavior. *** ## Next Steps > [card] [Market Data Streams](/api-reference/ws-market-data) > > Ticker, Candles, Trades, Order Book > [card] [Account Stream](/api-reference/ws-account) > > Real-time positions and orders # Account Stream Source: https://docs.bulk.trade/api-reference/ws-account Real-time account updates including positions, orders, margin, and comprehensive risk metrics. No signature required for subscribing (public data) > [!NOTE] > > **4 October 2026 upgrade:** account-local and optional aggregate margin fields, > plus the new post-only TIF response names below, apply after the scheduled upgrade. > Account snapshots retain `margin`; they do not expose internal SDK `metrics` > or `aggregate` objects. ## Subscribe ### Single Account ```json theme={null} { "method": "subscribe", "subscription": [{ "type": "account", "user": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" }] } ``` ### Multiple Accounts (Batched) Subscribe to multiple accounts in a single request: ```json theme={null} { "method": "subscribe", "subscription": [{ "type": "account", "user": [ "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "5Am6JkEHAjYG1itNWRMGpQrxvY8AaqkXCo1TZvenqVux", "9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" ] }] } ``` ### Response ```json theme={null} { "type": "subscriptionResponse", "topics": [ "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "account.5Am6JkEHAjYG1itNWRMGpQrxvY8AaqkXCo1TZvenqVux", "account.9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" ] } ``` **Parameters:** * `user` (String or Array): User public key(s) in base58 format * Single: `"user": "9J8T..."` * Multiple: `"user": ["9J8T...", "5Am6...", "ABC..."]` *** ## Initial Snapshot On subscription, you receive a unified `accountSnapshot` message. The example below shows selected fields. For master and sub accounts, `positions` and `openOrders` include implicit per-instrument isolated-account rows tagged by `iso=true`: ```json theme={null} { "type": "account", "data": { "type": "accountSnapshot", "kind": "MasterEOA", "subAccounts": [ { "pubkey": "8x7iUti9m6L6Y9yQPXkXj4zD2uP1Qx5Eo9W4vYm6cGmR" } ], "authorizedAgentWallets": [ "6pJ8vnrWofWgrn9doYBBRjijV5e6YJ2yN1U2EMRk4cLQ" ], "builderCodeApprovals": [ { "recipient": "5Am6JkEHAjYG1itNWRMGpQrxvY8AaqkXCo1TZvenqVux", "maxFee": 5 } ], "margin": { "totalMargin": 100000.0, "availableMargin": 95000.0, "marginUsed": 5000.0, "notional": 50000.0, "realizedPnl": 1234.5, "unrealizedPnl": 567.8, "fees": 12.34, "funding": 5.67 }, "positions": [ { "symbol": "BTC-USD", "size": 0.5, "price": 100000.0, "fairPrice": 101000.0, "notional": 50500.0, "realizedPnl": 500.0, "unrealizedPnl": 500.0, "leverage": 5.0, "liquidationPrice": 95000.0, "fees": 10.0, "funding": 2.5, "maintenanceMargin": 1000.0, "averageEntryTime": 1775550000000000000, "lambda": 0.05, "riskAllocation": 5000.0, "iso": false, "protection": { "orders": [ { "orderId": "6v8h8LC7eXv8W2af5nYvXn1Wuk3KdAy8pwkE2fFvR8w4", "orderType": "stop", "trigger": { "px": 98000.0, "lim": 97950.0, "oco": null } } ] } }, { "symbol": "ETH-USD", "size": 2.0, "price": 3500.0, "fairPrice": 3505.0, "notional": 7010.0, "realizedPnl": 0.0, "unrealizedPnl": 10.0, "leverage": 5.0, "liquidationPrice": 3000.0, "fees": 1.0, "funding": 0.0, "maintenanceMargin": 350.0, "lambda": 0.04, "riskAllocation": 350.0, "iso": true, "isoPubkey": "C7vR3xC5vR7n6Qx2mY5s9wH1rJ4cE8pV2kB3dL6tP9fU", "protection": null } ], "openOrders": [ { "symbol": "BTC-USD", "orderId": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "price": 102000.0, "originalSize": 0.1, "size": 0.1, "filledSize": 0.0, "vwap": 0.0, "maker": true, "reduceOnly": false, "orderType": "limit", "trigger": null, "tif": "gtc", "status": "placed", "timestamp": 1763316177219383423, "iso": false } ], "feeTiers": [ { "symbol": "global", "rollingVolume": 1200000.0, "tierIndex": 1, "tierThreshold": 1000000.0, "makerBps": 1.8, "takerBps": 3.3, "windowDays": 14 } ], "leverageSettings": [ { "symbol": "BTC-USD", "leverage": 5.0 }, { "symbol": "ETH-USD", "leverage": 3.0 } ], "lockedAmounts": [ { "hash": "uQ8yioSC6fYLWwWS2XAi97vMJXKur3GKr7DEp1tdMqs", "symbol": "USDC", "amount": 500.0, "lockedAt": 1700000000000000000 } ] }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ### Account Snapshot Fields **Top-level:** | Field | Description | | - | - | | `kind` | Account kind; documented kinds include `MasterEOA`, `SubAccount`, and `IsoAccount`. Current-state `POST /account` types resolve only master and sub-accounts; the paginated history types also accept an isolated pubkey for direct physical history. | | `parent` | Parent account pubkey for sub/iso rows; omitted when no parent exists | | `name` | Sub-account display name (present on snapshots where `kind: "SubAccount"`, i.e. when you subscribed with the sub-account pubkey as `user`). Omitted on master snapshots. | | `subAccounts` | Child sub-accounts as `{pubkey}`. The list under a master contains pubkeys only; subscribe to a sub-account directly (or query it via [`POST /account`](/api-reference/getAccount) with `type: "fullAccount"`) to see its `name`. | | `authorizedAgentWallets` | Agent wallets directly registered on this account. Agents registered on a master can sign for the master and any of its sub-accounts and isolated accounts; sub-accounts may register their own agents too. | | `builderCodeApprovals` | Approved builder-code recipients as `{recipient, maxFee}`. Builder codes are builder-code fees on the wire; use `abc`/`rbc` to manage this list. | | `lockedAmounts` | Margin locks while a transfer or withdrawal is in progress. Omitted when empty; each row contains `hash`, `symbol`, `amount`, and nanosecond `lockedAt`. | **Margin:** | Field | Description | | - | - | | `totalMargin` | Account-local margin balance | | `availableMargin` | Account-local margin minus maintenance margin; not the transferable balance | | `executionImpact` | Non-positive difference between impacted and unrealized P\&L | | `transferableBalance` | Account-local balance eligible for transfer under risk constraints | | `marginUsed` | Maintenance margin used | | `marginBufferRate` | Maintenance-margin buffer rate | | `bufferedMargin` | `marginUsed * (1 + marginBufferRate)` | | `notional` | Total notional value of all positions | | `realizedPnl` | Realized profit/loss | | `unrealizedPnl` | Unrealized profit/loss | | `fees` | Total fees paid | | `funding` | Total funding paid/received | Unprefixed margin fields describe the subscribed account only. When it has attached isolated accounts, `aggTotalMargin`, `aggAvailableMargin`, `aggExecutionImpact`, `aggTransferableBalance`, `aggMarginUsed`, `aggBufferedMargin`, `aggNotional`, `aggRealizedPnl`, `aggUnrealizedPnl`, `aggFees`, and `aggFunding` report the account-plus-isolated totals. They are omitted when no isolated owners are attached. Separate sub-accounts are not included. Do not add local values to aggregate values. Positions and orders continue to include isolated rows. See the [HTTP account examples](/api-reference/getAccount#account-local-and-aggregate-margin) for the same margin object in a `fullAccount` response. **Positions:** | Field | Description | | - | - | | `symbol` | Market symbol | | `size` | Position size (positive=long, negative=short) | | `price` | VWAP entry price | | `fairPrice` | Current fair/mark price | | `notional` | Notional value (size × fair_price) | | `realizedPnl` | Realized P\&L for this position | | `unrealizedPnl` | Unrealized P\&L for this position | | `leverage` | Position leverage | | `liquidationPrice` | Liquidation price | | `fees` | Fees paid for this position | | `funding` | Funding paid/received | | `maintenanceMargin` | Required maintenance margin | | `averageEntryTime` | Average entry time in nanoseconds. | | `lambda` | Lambda (risk parameter) | | `riskAllocation` | Risk allocation (C_i) | | `iso` | `true` when the row belongs to an implicit per-instrument isolated account, otherwise `false` | | `isoPubkey` | Present only when `iso=true`; base58 pubkey of the implicit isolated account. Use as `to` in a `transfer` to top up its margin or as `user` with a paginated history type on `POST /account`. It cannot be used as transaction `account` or with a current-state account query type. | | `protection` | Optional attached reduce-only protective orders | **Open Orders:** | Field | Description | | - | - | | `symbol` | Market symbol | | `orderId` | Order ID (base58, use for cancellation) | | `price` | Order price | | `originalSize` | Original order size | | `size` | Current remaining size | | `filledSize` | Filled size | | `vwap` | VWAP fill price (0 if no fills) | | `maker` | `true` if maker order | | `reduceOnly` | `true` if reduce-only | | `orderType` | Order type: `limit`, `market`, `stop`, `takeProfit`, `range`, `trigger`, `trailing` | | `trigger` | Trigger metadata for conditional orders, otherwise `null` | | `tif` | Time in force (`gtc`, `ioc`, `postOnly`, `postOnlySlide`, `postOnlyJoin`) | | `status` | Order status (`placed`, `working`, etc.) | | `timestamp` | Order placement time (nanoseconds) | | `iso` | `true` when the row belongs to an implicit per-instrument isolated account, otherwise `false` | **Leverage Settings** (included in initial snapshot only): | Field | Description | | - | - | | `symbol` | Market symbol | | `leverage` | Maximum leverage (1.0 to 50.0) | **Fee Tiers** (included in initial snapshot only): | Field | Description | | - | - | | `symbol` | `"global"` for global scope, market symbol for per-instrument scope | | `rollingVolume` | Current rolling volume in that scope window | | `tierIndex` | Active tier index (0-based) | | `tierThreshold` | Threshold volume of the active tier row | | `makerBps` | Active maker bps for that scope | | `takerBps` | Active taker bps for that scope | | `windowDays` | Rolling window length in days | **Pending OnFill** (included in initial snapshot only): | Field | Description | | - | - | | `parentOrderId` | Resting parent order that activates on first fill | | `actions` | Consequent actions executed when the parent first fills | *** ## Real-time Delta Updates After the initial snapshot, you receive delta updates for changes: ### Margin Update ```json theme={null} { "type": "account", "data": { "type": "marginUpdate", "totalMargin": 100500.0, "availableMargin": 95500.0, "marginUsed": 5000.0, "notional": 50500.0, "realizedPnl": 1234.5, "unrealizedPnl": 567.8, "fees": 12.34, "funding": 5.67 }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` > [!NOTE] > > `transfer`, `createSubAccount` (when seeded with margin), and `removeSubAccount` trigger same-tick margin recompute on touched accounts. WS delivery is asynchronous, so the `post` acknowledgment can arrive before the `marginUpdate` is broadcast. `marginUpdate` carries account-local margin fields directly in `data`, unlike the initial snapshot's nested `data.margin`. For a parent with attached isolated accounts, the current API suppresses incremental parent `marginUpdate` messages; read the combined local and `agg*` values from `accountSnapshot.margin` or `POST /account` instead. Do not depend on a parent margin delta after every ISO fill. Illustrative partial **account snapshot**, not a margin delta: ```json theme={null} { "type": "account", "data": { "type": "accountSnapshot", "margin": { "totalMargin": 1000.0, "availableMargin": 900.0, "marginUsed": 100.0, "aggTotalMargin": 1250.0, "aggAvailableMargin": 1125.0, "aggMarginUsed": 125.0 } }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` This example omits the other account snapshot fields for brevity. ### Position Update ```json theme={null} { "type": "account", "data": { "type": "positionUpdate", "symbol": "BTC-USD", "size": 0.5, "price": 100000.0, "realizedPnl": 500.0, "unrealizedPnl": 500.0, "leverage": 5.0, "liquidationPrice": 95000.0, "fairPrice": 101000.0, "notional": 50500.0, "fees": 10.0, "funding": 2.5, "maintenanceMargin": 1000.0, "averageEntryTime": 1775550000000000000, "lambda": 0.05, "riskAllocation": 5000.0, "protection": null }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` *** ### Locked Amounts Update Emitted when transfer or withdrawal margin locks change. An empty array means all locks have cleared. ```json theme={null} { "type": "account", "data": { "type": "lockedAmountsUpdate", "lockedAmounts": [ { "hash": "uQ8yioSC6fYLWwWS2XAi97vMJXKur3GKr7DEp1tdMqs", "symbol": "USDC", "amount": 500.0, "lockedAt": 1700000000000000000 } ] }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` *** ## Order Update > [!NOTE] > > All order state changes are delivered via unified `orderUpdate` messages with full state information. > [!WARNING] > > `origSz` and `sz` are **signed**: negative values indicate sell-side intent. For example, a sell order for 0.25 BTC has `origSz: -0.25`. > For `ot: "trigger"` baskets, `origSz` and `sz` are `0` (trigger baskets carry nested actions, not a direct sized order). ```json theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "resting", "sym": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "px": 102000.0, "origSz": 0.1, "sz": 0.1, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": true, "trigger": null, "ts": 1763316177219383423, "reason": null }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ### Order Update Fields | Field | Description | | - | - | | `ot` | Order type (`limit`, `market`, `stop`, `takeProfit`, `range`, `trigger`, `trailing`) | | `status` | Order status (see table below) | | `sym` | Market symbol | | `oid` | Order ID (base58) | | `px` | Order price (or trigger reference price) | | `origSz` | **Signed** original order size (negative = sell) | | `sz` | **Signed** current remaining size (negative = sell) | | `fillSz` | Amount filled | | `vwap` | VWAP fill price | | `tif` | Time in force (`gtc`, `ioc`, `postOnly`, `postOnlySlide`, `postOnlyJoin`) | | `r` | Reduce-only flag | | `mk` | Maker/resting flag | | `trigger` | Trigger metadata for conditional orders, otherwise `null` (see below) | | `pendingOnFill` | On-fill registration attached to parent while awaiting first fill, or absent | | `ts` | Event timestamp (nanoseconds) | | `reason` | Rejection/cancellation reason (optional) | ### Trigger Metadata When `trigger` is present (conditional orders): | Field | Description | | - | - | | `isAbove` | Trigger direction (`true` = above/equal, `false` = below/equal, `null` if not encoded) | | `px` | Trigger threshold price | | `lim` | Post-trigger limit price (`null` = market) | | `oco` | Linked OCO order ID (if any) | | `pxHi` | Upper trigger threshold (range upper band / trailing sentinel) | | `limHi` | Upper post-trigger limit (range upper leg) | | `trb` | Trailing distance in bps (trailing only) | | `stb` | Favorable reset step in bps (trailing only) | ### Order Status Values | Status | Terminal | Description | | - | - | - | | `pending` | No | Accepted but not yet placed | | `placed` | No | Order placed and resting on book | | `resting` | No | Resting on book / conditional book | | `working` | No | Order has partial fills, still resting | | `modified` | No | Order was modified | | `filled` | Yes | Order fully filled | | `partiallyFilled` | Yes | Order partially filled and terminal | | `cancelled` | Yes | Order cancelled by user | | `cancelledRiskLimit` | Yes | Cancelled due to risk limit | | `cancelledSelfCrossing` | Yes | Cancelled due to self-crossing (STP) | | `cancelledReduceOnly` | Yes | Cancelled - would not reduce position | | `cancelledIoc` | Yes | IOC expired without full fill | | `rejectedCrossing` | Yes | Post-only rejected for crossing | | `rejectedDuplicate` | Yes | Duplicate order ID | | `rejectedRiskLimit` | Yes | Rejected due to risk limit | | `rejectedInvalid` | Yes | Invalid order parameters | | `triggered` | No | Conditional root fired | | `siblingCancelled` | Yes | OCO sibling auto-cancelled | | `triggerFailed` | Yes | Trigger execution failed | ### Order Update Examples ```json Buy Limit Placed theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "placed", "sym": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "px": 100000.0, "origSz": 0.1, "sz": 0.1, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": true, "trigger": null, "ts": 1763316177219383423, "reason": null }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Sell Limit Resting (signed) theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "resting", "sym": "BTC-USD", "oid": "7kR2mQfENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "px": 105000.0, "origSz": -0.25, "sz": -0.25, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": true, "trigger": null, "ts": 1763316177219383423, "reason": null }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Working (partial fill) theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "working", "sym": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "px": 100000.0, "origSz": 0.1, "sz": 0.05, "fillSz": 0.05, "vwap": 100000.0, "tif": "gtc", "r": false, "mk": true, "trigger": null, "ts": 1763316177219383423, "reason": null }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Order Filled theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "filled", "sym": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "px": 100000.0, "origSz": 0.1, "sz": 0.0, "fillSz": 0.1, "vwap": 100025.5, "tif": "gtc", "r": false, "mk": false, "trigger": null, "ts": 1763316177219383423, "reason": null }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Cancelled Risk Limit theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "cancelledRiskLimit", "sym": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "px": 100000.0, "origSz": 0.1, "sz": 0.05, "fillSz": 0.05, "vwap": 100000.0, "tif": "gtc", "r": false, "mk": false, "trigger": null, "ts": 1763316177219383423, "reason": "Position would exceed max leverage" }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Stop Resting (with trigger) theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "stop", "status": "resting", "sym": "BTC-USD", "oid": "8mT3nQgGPjHFX7vNrAShxnk0hqoc96FhVdAb6Fn5QRi8", "px": 0.0, "origSz": -0.25, "sz": -0.25, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": false, "trigger": { "isAbove": false, "px": 98000.0, "lim": 97950.0, "oco": null, "pxHi": null, "limHi": null, "trb": null, "stb": null }, "ts": 1763316177219383423, "reason": null }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Range/OCO Triggered theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "range", "status": "triggered", "sym": "BTC-USD", "oid": "ABC...", "px": 0.0, "origSz": 0.0, "sz": 0.0, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": true, "mk": false, "trigger": null, "ts": 1763316177219383423 }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json OCO Sibling Cancelled theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "range", "status": "siblingCancelled", "sym": "BTC-USD", "oid": "DEF...", "px": 0.0, "origSz": 0.0, "sz": 0.0, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": false, "trigger": null, "ts": 1763316177219383423, "reason": "oco sibling cancelled" }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` ```json Trigger Failed theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "stop", "status": "triggerFailed", "sym": "BTC-USD", "oid": "GHI...", "px": 0.0, "origSz": 0.0, "sz": 0.0, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": true, "mk": false, "trigger": null, "ts": 1763316177219383423, "reason": "conditional execution failed: no counterparty" }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` > [!NOTE] > > **Legacy order messages:** For backwards compatibility, `order` messages with `status: "placed"` or `status: "cancelled"` may still be emitted alongside `orderUpdate`. New integrations should use `orderUpdate` messages exclusively. *** ## Fill Update Emitted on each trade execution (in addition to `orderUpdate`): ```json theme={null} { "type": "account", "data": { "type": "fill", "tradeId": "34554078:127", "symbol": "BTC-USD", "orderId": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "price": 102000.0, "size": 0.05, "fee": 0.35, "isBuy": true, "reasonCode": 0, "counterpartyHint": "5Am6..nVux", "timestamp": 1763316177219383423, "maker": false }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` **Fill Fields:** * `tradeId` - Opaque network-local execution ID (`:`). Maker, taker, isolated-account, and REST account-history views of the same execution share it. Gaps are normal in one account's view; it is not portable across forks or networks. * `symbol` - Market symbol * `orderId` - Your order ID for this row * `price` - Execution price * `size` - Executed size * `fee` - Effective fee for this row * `isBuy` - `true` if taker bought, `false` if taker sold * `reasonCode` - Fill reason code (`0=normal`, `1=liquidation`, `2=adl`, `3=liquidation_sweep`) * `reason` - Optional reason label (non-normal only; `liquidation`, `adl`, or `liquidation_sweep`) * `counterpartyHint` - Short counterparty key hint (`xxxx..yyyy`) * `timestamp` - Fill timestamp (nanoseconds) * `maker` - `true` if this row is the maker side *** ## Liquidation Event Emitted when the account is liquidated: ```json theme={null} { "type": "account", "data": { "type": "liquidation", "symbol": "BTC-USD", "price": 95000.0, "size": 0.5, "isBuy": false, "marginPrior": 5000.0, "marginAfter": 0.0, "reason": "margin shortfall", "timestamp": 1763316177219383423 }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` | Field | Description | | - | - | | `symbol` | Market symbol | | `price` | Liquidation price | | `size` | Position size that was liquidated | | `isBuy` | Direction of the liquidation fill | | `marginPrior` | Margin balance before liquidation | | `marginAfter` | Margin balance after liquidation | | `reason` | Optional human-readable liquidation reason | | `timestamp` | Timestamp (nanoseconds) | *** ## ADL (Auto-Deleveraging) Event Emitted when the account is auto-deleveraged: ```json theme={null} { "type": "account", "data": { "type": "adl", "symbol": "BTC-USD", "price": 95000.0, "size": 0.5, "isBuy": false, "reason": "underfill residual", "timestamp": 1763316177219383423 }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` | Field | Description | | - | - | | `symbol` | Market symbol | | `price` | ADL price | | `size` | Position size that was auto-deleveraged | | `isBuy` | Direction of the ADL fill | | `reason` | Optional human-readable ADL reason | | `timestamp` | Timestamp (nanoseconds) | > [!TIP] > > For historical liquidation / ADL analysis, query > [`POST /account` with `type: "riskHistory"`](/api-reference/getAccount#history-queries). *** ## Cancel Rejected Emitted when a single-order cancel is rejected (e.g. order not found): ```json theme={null} { "type": "account", "data": { "type": "cancelOneRejected", "symbol": "BTC-USD", "orderId": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "reason": "Order not found", "timestamp": 1763316177219383423 }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` *** ## Cancel All Rejected Emitted when cancel-all is rejected (e.g. no open orders): ```json theme={null} { "type": "account", "data": { "type": "cancelAllRejected", "symbol": "BTC-USD", "reason": "No open orders", "timestamp": 1763316177219383423 }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` *** ## Leverage Update ```json theme={null} { "type": "account", "data": { "type": "leverageUpdate", "leverage": [ { "symbol": "BTC-USD", "leverage": 5.0 } ] }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` *** ## Fee Tier Update Emitted when the account's fee tier changes: ```json theme={null} { "type": "account", "data": { "type": "feeTierUpdate", "feeTiers": [ { "symbol": "global", "rollingVolume": 1260000.0, "tierIndex": 1, "tierThreshold": 1000000.0, "makerBps": 1.8, "takerBps": 3.3, "windowDays": 14 } ], "ts": 1775550000123456789 }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` *** ## Update Frequency * **Initial Snapshot**: Sent immediately on subscription (single unified `accountSnapshot` message). * **Event-driven**: Margin, positions, and leverage settings are sent when they change. * **Real-time**: Immediately on all order state changes (`orderUpdate`), including: * Order placement (placed, resting) * Partial fills (working) * Full fills (filled) * Cancellations (cancelled, cancelledRiskLimit, cancelledIoc, etc.) * Rejections (rejectedCrossing, rejectedRiskLimit, etc.) *** ## Example: Monitor Account ```javascript Node.js theme={null} const WebSocket = require('ws'); const PUBLIC_KEY = 'FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7'; const ws = new WebSocket('wss://mainnet-ws1.bulk.trade'); ws.on('open', () => { console.log('Connected'); // Subscribe to account updates ws.send(JSON.stringify({ method: 'subscribe', subscription: [{ type: 'account', user: PUBLIC_KEY }] })); }); ws.on('message', (data) => { const message = JSON.parse(data); if (message.type === 'subscriptionResponse') { console.log('Subscribed to:', message.topics); return; } if (message.type === 'account') { const { type, ...details } = message.data; switch(type) { case 'accountSnapshot': console.log('Account snapshot:', details); console.log('Positions:', details.positions); console.log('Open orders:', details.openOrders); break; case 'marginUpdate': console.log('Margin update:', details); break; case 'positionUpdate': console.log('Position update:', details); break; case 'orderUpdate': console.log(`Order ${details.status}:`, details); break; case 'fill': console.log('Fill:', details); break; case 'leverageUpdate': console.log('Leverage updated:', details); break; case 'feeTierUpdate': console.log('Fee tier updated:', details); break; case 'liquidation': console.log('Liquidation:', details); break; case 'adl': console.log('ADL:', details); break; case 'cancelOneRejected': console.log('Cancel rejected:', details); break; case 'cancelAllRejected': console.log('Cancel all rejected:', details); break; } } }); ``` ```python Python theme={null} import websocket import json PUBLIC_KEY = 'FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7' def on_message(ws, message): data = json.loads(message) if data.get('type') == 'subscriptionResponse': print(f"Subscribed to: {data['topics']}") return if data.get('type') == 'account': msg_type = data['data']['type'] if msg_type == 'accountSnapshot': print(f"Account snapshot: {data['data']}") print(f"Positions: {data['data']['positions']}") print(f"Open orders: {data['data']['openOrders']}") elif msg_type == 'marginUpdate': print(f"Margin update: {data['data']}") elif msg_type == 'positionUpdate': print(f"Position update: {data['data']}") elif msg_type == 'orderUpdate': print(f"Order {data['data']['status']}: {data['data']}") elif msg_type == 'fill': print(f"Fill: {data['data']}") elif msg_type == 'leverageUpdate': print(f"Leverage updated: {data['data']}") elif msg_type == 'feeTierUpdate': print(f"Fee tier updated: {data['data']}") elif msg_type == 'liquidation': print(f"Liquidation: {data['data']}") elif msg_type == 'adl': print(f"ADL: {data['data']}") elif msg_type == 'cancelOneRejected': print(f"Cancel rejected: {data['data']}") elif msg_type == 'cancelAllRejected': print(f"Cancel all rejected: {data['data']}") def on_open(ws): print('Connected') ws.send(json.dumps({ 'method': 'subscribe', 'subscription': [{ 'type': 'account', 'user': PUBLIC_KEY }] })) ws = websocket.WebSocketApp( 'wss://mainnet-ws1.bulk.trade', on_message=on_message, on_open=on_open ) ws.run_forever() ``` *** ## Unsubscribe ```json theme={null} { "method": "unsubscribe", "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` # Connection Management Source: https://docs.bulk.trade/api-reference/ws-connection Subscriptions, reconnection, and best practices # Connection Management Best practices for maintaining reliable WebSocket connections. *** ## Optional Handshake Headers Sockets that will be used to submit signed transactions via the [`post`](/api-reference/ws-trading) method can opt into an alternative signature verifier on the WebSocket upgrade: | Header | Allowed values | Purpose | | - | - | - | | `x-bulk-sig-mode` | `raw` \| `offchain` \| `base58` | Hint for the verifier attempt-order on every `post` action sent over this socket. | Semantics: * Missing header: server uses the default raw canonical-binary verification path. * Invalid value: ignored safely (falls back to default raw verification). * Valid value: used **only as an attempt-order hint**. Signature validity still decides accept/reject. * The header is never trusted for authentication by itself. * Sockets posting transactions signed with the [v0 Solana offchain envelope](/api-reference/signing#offchain-signing-mode) should set `x-bulk-sig-mode: offchain`. The header has no effect on subscription-only sockets. *** ## Subscription Management ### Subscribe Subscribe to one or multiple streams: ```json theme={null} { "method": "subscribe", "subscription": [ {"type": "ticker", "symbol": "BTC-USD"}, {"type": "trades", "symbol": "ETH-USD"}, {"type": "account", "user": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7"} ] } ``` **Response**: ```json theme={null} { "type": "subscriptionResponse", "topics": [ "ticker.BTC-USD", "trades.ETH-USD", "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" ] } ``` Save the topic strings for unsubscription. ### Unsubscribe Unsubscribe using the topic string: ```json theme={null} { "method": "unsubscribe", "topic": "ticker.BTC-USD" } ``` **Response**: ```json theme={null} { "type": "unsubscribeResponse", "topic": "ticker.BTC-USD" } ``` *** ## Reconnection Strategy WebSocket connections can drop due to network issues. Always implement reconnection logic. ```javascript Node.js with Exponential Backoff theme={null} class BulkWebSocket { constructor(url) { this.url = url; this.ws = null; this.reconnectDelay = 1000; this.maxReconnectDelay = 30000; this.subscriptions = []; this.topics = []; } connect() { this.ws = new WebSocket(this.url); this.ws.on('open', () => { console.log('Connected'); this.reconnectDelay = 1000; // Reset delay this.resubscribe(); }); this.ws.on('message', (data) => { const message = JSON.parse(data); this.handleMessage(message); }); this.ws.on('close', () => { console.log('Disconnected. Reconnecting...'); this.reconnect(); }); this.ws.on('error', (error) => { console.error('WebSocket error:', error); }); } reconnect() { setTimeout(() => { console.log(`Reconnecting in ${this.reconnectDelay}ms...`); this.connect(); // Exponential backoff this.reconnectDelay = Math.min( this.reconnectDelay * 2, this.maxReconnectDelay ); }, this.reconnectDelay); } subscribe(subscription) { this.subscriptions.push(subscription); if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify({ method: 'subscribe', subscription: [subscription] })); } } resubscribe() { if (this.subscriptions.length > 0) { this.ws.send(JSON.stringify({ method: 'subscribe', subscription: this.subscriptions })); } } handleMessage(message) { if (message.type === 'subscriptionResponse') { this.topics = message.topics; console.log('Subscribed to:', this.topics); return; } // Handle data messages console.log('Received:', message); } } // Usage const ws = new BulkWebSocket('wss://mainnet-ws1.bulk.trade'); ws.connect(); ws.subscribe({ type: 'ticker', symbol: 'BTC-USD' }); ``` ```python Python with Reconnection theme={null} import websocket import json import time import threading class BulkWebSocket: def __init__(self, url): self.url = url self.ws = None self.reconnect_delay = 1 self.max_reconnect_delay = 30 self.subscriptions = [] self.topics = [] self.running = True def connect(self): def on_open(ws): print('Connected') self.reconnect_delay = 1 # Reset delay self.resubscribe() def on_message(ws, message): data = json.loads(message) self.handle_message(data) def on_close(ws, close_status_code, close_msg): if self.running: print('Disconnected. Reconnecting...') self.reconnect() def on_error(ws, error): print(f'Error: {error}') self.ws = websocket.WebSocketApp( self.url, on_open=on_open, on_message=on_message, on_close=on_close, on_error=on_error ) # Run in thread thread = threading.Thread(target=self.ws.run_forever) thread.daemon = True thread.start() def reconnect(self): time.sleep(self.reconnect_delay) print(f'Reconnecting...') self.connect() # Exponential backoff self.reconnect_delay = min( self.reconnect_delay * 2, self.max_reconnect_delay ) def subscribe(self, subscription): self.subscriptions.append(subscription) if self.ws: self.ws.send(json.dumps({ 'method': 'subscribe', 'subscription': [subscription] })) def resubscribe(self): if self.subscriptions: self.ws.send(json.dumps({ 'method': 'subscribe', 'subscription': self.subscriptions })) def handle_message(self, message): if message.get('type') == 'subscriptionResponse': self.topics = message['topics'] print(f'Subscribed to: {self.topics}') return print(f'Received: {message}') def close(self): self.running = False if self.ws: self.ws.close() # Usage ws = BulkWebSocket('wss://mainnet-ws1.bulk.trade') ws.connect() ws.subscribe({'type': 'ticker', 'symbol': 'BTC-USD'}) ``` *** ## Ping-Pong Keepalive (Required) The server uses an explicit WebSocket ping/pong liveness check. You **must** respond to server pings with pongs or the connection will be closed. | Behavior | Detail | | - | - | | **Ping interval** | Server sends a WebSocket `ping` frame every **30 seconds** | | **Pong requirement** | Client must reply with a WebSocket `pong` frame | | **Timeout** | If a pong is still missing **10 seconds** after a ping, the server disconnects the connection | | **Frame type** | Ping/pong are **transport-level** WebSocket frames, not application (JSON) messages | **Client recommendations:** * Respond immediately to ping frames with pong. Many WebSocket client libraries (e.g. Node.js `ws`) do this automatically; if yours does not, handle the `ping` event and send a pong. * Do not treat ping/pong as application messages -they are separate from `subscribe`, `post`, and data messages. * If you are disconnected due to a missed pong, reconnect and [resubscribe](#resubscribe) to your topics. ```javascript Node.js (ws) theme={null} const WebSocket = require('ws'); const ws = new WebSocket('wss://mainnet-ws1.bulk.trade'); // Node.js 'ws' automatically replies to ping with pong by default. // To handle explicitly (e.g. for logging or custom behavior): ws.on('ping', () => { ws.pong(); // optional: library often does this automatically }); ws.on('pong', () => { // Server may send pong in response to client ping; keepalive is server-initiated }); ``` ```javascript Browser theme={null} // Browser WebSocket API automatically responds to server ping with pong. // No extra code needed for keepalive; ensure you don't ignore or close on ping. const ws = new WebSocket('wss://mainnet-ws1.bulk.trade'); ``` *** ## Rate Limits The public mainnet endpoint permits **15 concurrent connections per client IP** and **45 new connection attempts/minute per IP**. Each connection has a **32-action/second** trading budget with a **96-action burst**. Use reconnect backoff and prefer reusing connections. See [Public API Rate Limits](/api-reference/rate-limits) for full HTTP/WS limits and rejection handling. *** ## Best Practices > [accordion] Always implement reconnection logic > > Network issues are inevitable. Your application should automatically reconnect with exponential backoff. > [accordion] Store subscriptions for resubscription > > After reconnecting, you must resubscribe to all channels. Store your subscription list. > [accordion] Handle message ordering > > Messages may arrive out of order during high load. Use timestamps and sequence numbers. > [accordion] Respond to server ping with pong > > The server sends a ping every 30 seconds. If the client does not reply with a pong within 10 seconds, the server disconnects. Use a client that responds to ping (or handle it explicitly) and always implement reconnection. > [accordion] Implement timeouts > > If no application message is received for a long period, consider the connection stale and reconnect. Note: the server will already disconnect if pong is not sent within 10 seconds of a ping. > [accordion] Use compression > > Enable per-message deflate for bandwidth savings on high-frequency streams. > [accordion] Separate connections for trading > > Use one connection for market data and another for trading to avoid mixing concerns. *** ## Connection States Monitor connection state to handle different scenarios: | State | Description | Action | | - | - | - | | `CONNECTING` | Initial connection | Wait for open event | | `OPEN` | Connected and ready | Can send/receive messages | | `CLOSING` | Connection closing | Stop sending messages | | `CLOSED` | Connection closed | Reconnect if needed | *** ## Error Codes Common WebSocket close codes: | Code | Reason | Action | | - | - | - | | 1000 | Normal closure | No action needed | | 1001 | Going away | Reconnect | | 1002 | Protocol error | Check message format | | 1003 | Unsupported data | Check message content | | 1006 | Abnormal closure | Reconnect | | 1008 | Policy violation | Check rate limits | | 1011 | Server error | Retry with backoff | *** ## Monitoring Connection Health Implement health checks to detect stale connections: ```javascript theme={null} class ConnectionMonitor { constructor(ws, timeout = 60000) { this.ws = ws; this.timeout = timeout; this.lastMessage = Date.now(); this.checkInterval = null; } start() { // Update timestamp on every message this.ws.on('message', () => { this.lastMessage = Date.now(); }); // Check health every 10 seconds this.checkInterval = setInterval(() => { const timeSinceLastMessage = Date.now() - this.lastMessage; if (timeSinceLastMessage > this.timeout) { console.warn('Connection stale, reconnecting...'); this.ws.close(); } }, 10000); } stop() { if (this.checkInterval) { clearInterval(this.checkInterval); } } } // Usage const monitor = new ConnectionMonitor(ws); monitor.start(); ``` *** ## Multiple Connections For high-throughput applications, consider using multiple connections: ```javascript theme={null} // Connection 1: Market data const marketDataWs = new WebSocket('wss://mainnet-ws1.bulk.trade'); marketDataWs.on('open', () => { marketDataWs.send(JSON.stringify({ method: 'subscribe', subscription: [ { type: 'ticker', symbol: 'BTC-USD' }, { type: 'trades', symbol: 'BTC-USD' } ] })); }); // Connection 2: Account updates const accountWs = new WebSocket('wss://mainnet-ws1.bulk.trade'); accountWs.on('open', () => { accountWs.send(JSON.stringify({ method: 'subscribe', subscription: [ { type: 'account', user: PUBLIC_KEY } ] })); }); // Connection 3: Trading const tradingWs = new WebSocket('wss://mainnet-ws1.bulk.trade'); // Use this for order placement/cancellation ``` *** ## Testing Connection Test your WebSocket connection with a simple script: ```javascript theme={null} const WebSocket = require('ws'); const ws = new WebSocket('wss://mainnet-ws1.bulk.trade'); ws.on('open', () => { console.log('✓ Connected successfully'); // Test subscription ws.send(JSON.stringify({ method: 'subscribe', subscription: [{ type: 'ticker', symbol: 'BTC-USD' }] })); setTimeout(() => { console.log('Test complete'); ws.close(); }, 5000); }); ws.on('message', (data) => { const message = JSON.parse(data); if (message.type === 'subscriptionResponse') { console.log('✓ Subscribed to:', message.topics); } else { console.log('✓ Received update:', message.type); } }); ws.on('error', (error) => { console.error('✗ Error:', error); }); ws.on('close', () => { console.log('✓ Connection closed'); }); ``` # Market Data Streams Source: https://docs.bulk.trade/api-reference/ws-market-data Real-time price feeds, candles, trades, and order books ## Ticker Stream Get 24-hour statistics updated every 200ms. ```json Subscribe theme={null} { "method": "subscribe", "subscription": [{ "type": "ticker", "symbol": "BTC-USD" }] } ``` ```json Response theme={null} { "type": "subscriptionResponse", "topics": ["ticker.BTC-USD"] } ``` ```json Update theme={null} { "type": "ticker", "data": { "ticker": { "symbol": "BTC-USD", "priceChange": 2777.5, "priceChangePercent": 2.77, "lastPrice": 102777.5, "highPrice": 103500.0, "lowPrice": 101000.0, "volume": 1234.56, "quoteVolume": 126543210.0, "markPrice": 102780.0, "oraclePrice": 102775.0, "openInterest": 5432.1, "fundingRate": 0.0001, "regime": 1, "regimeDt": 93, "regimeVol": 0.35, "regimeMv": 0.02, "fairBookPx": 102779.0, "fairVol": 0.28, "fairBias": 0.001, "timestamp": 1704067200000000000 } }, "topic": "ticker.BTC-USD" } ``` **Update Frequency**: Every 200ms **Ticker Fields**: | Field | Description | | - | - | | `priceChange` | Absolute price change over 24h | | `priceChangePercent` | Percentage price change over 24h | | `lastPrice` | Last traded price | | `highPrice` | 24h high | | `lowPrice` | 24h low | | `volume` | 24h base asset volume | | `quoteVolume` | 24h quote asset volume | | `markPrice` | Current fair/mark price | | `oraclePrice` | Oracle-reported price | | `openInterest` | Total open interest | | `fundingRate` | Current funding rate | | `regime` | Market regime indicator. Values from set representing direction (negative=bearish, 0=neutral, positive=bullish) crossed with volatility tier | | `regimeDt` | Regime duration in 10s intervals | | `regimeVol` | Regime-adjusted volatility | | `regimeMv` | Regime mean value | | `fairBookPx` | Fair price derived from order book | | `fairVol` | Fair volatility estimate | | `fairBias` | Fair price bias | | `timestamp` | Timestamp (nanoseconds) | *** ## Candles Stream Real-time candlestick data with historical backfill. ```json Subscribe theme={null} { "method": "subscribe", "subscription": [{ "type": "candle", "symbol": "BTC-USD", "interval": "1m" }] } ``` ```json Response theme={null} { "type": "subscriptionResponse", "topics": ["candle.BTC-USD.1m"] } ``` ```json Update theme={null} { "type": "candle", "data": { "candles": [ { "t": 1699564800000, "T": 1699564860000, "o": 102000.0, "h": 102100.0, "l": 101900.0, "c": 101950.0, "v": 1.6, "n": 3 } ] }, "topic": "candle.BTC-USD.1m" } ``` **Supported Intervals**: `10s`, `1m`, `3m`, `5m`, `15m`, `30m`, `1h`, `2h`, `4h`, `6h`, `8h`, `12h`, `1d`, `3d`, `1w`, `1M` **Initial Response**: Up to 5000 historical candles **Updates**: Real-time (10s instant; larger intervals aggregated \~10–20s) **Candle Fields**: | Field | Description | | - | - | | `t` | Open timestamp (milliseconds) | | `T` | Close timestamp (milliseconds) | | `o` | Open price | | `h` | High price | | `l` | Low price | | `c` | Close price | | `v` | Volume | | `n` | Number of trades | *** ## Trades Stream Real-time trades feed ```json Subscribe theme={null} { "method": "subscribe", "subscription": [{ "type": "trades", "symbol": "BTC-USD" }] } ``` ```json Response theme={null} { "type": "subscriptionResponse", "topics": ["trades.BTC-USD"] } ``` ```json Update theme={null} { "type": "trades", "data": { "trades": [ { "s": "BTC-USD", "px": 102500.0, "sz": 0.15, "time": 1699564800000, "side": true, "maker": "9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt", "taker": "5Am6JkEHAjYG1itNWRMGpQrxvY8AaqkXCo1TZvenqVux" } ] }, "topic": "trades.BTC-USD" } ``` **Initial Response**: None (stateless) **Updates**: Real-time on every fill **Trade Fields**: | Field | Description | | - | - | | `s` | Symbol (market) | | `px` | Execution price | | `sz` | Size traded | | `time` | Timestamp (milliseconds) | | `side` | `true` if taker bought, `false` if taker sold | | `maker` | Maker public key (base58) | | `taker` | Taker public key (base58) | | `reason` | Fill reason (optional; only present if not a normal trade, e.g. `"liquidation"`, `"adl"`, `"liquidation_sweep"`) | | `liq` | Liquidation flag (optional; only present if true) | This public market-data message does not include the account `tradeId`. Use [`POST /account` fill history](/api-reference/getAccount#history-queries) or authenticated [account fill updates](/api-reference/ws-account#fill) when you need to reconcile one execution across account views. *** ## L2 Snapshot Stream Periodic full order book snapshots. ```json Subscribe theme={null} { "method": "subscribe", "subscription": [{ "type": "l2Snapshot", "symbol": "BTC-USD", "nlevels": 10, "aggregation": 0.5 }] } ``` ```json Response theme={null} { "type": "subscriptionResponse", "topics": ["l2snapshot.BTC-USD"] } ``` ```json Update theme={null} { "type": "l2Snapshot", "data": { "book": { "updateType": "snapshot", "symbol": "BTC-USD", "levels": [ [ {"px": 102777.0, "sz": 1.5, "n": 3}, {"px": 102776.5, "sz": 2.3, "n": 5}, {"px": 102776.0, "sz": 0.8, "n": 2} ], [ {"px": 102780.0, "sz": 2.0, "n": 4}, {"px": 102780.5, "sz": 1.2, "n": 3}, {"px": 102781.0, "sz": 1.8, "n": 2} ] ], "timestamp": 1699564800000 } }, "topic": "l2snapshot.BTC-USD" } ``` **Parameters**: * `nlevels` (optional): Number of price levels per side * `aggregation` (optional): Price bucket size in quote currency **Update Frequency**: Every 200ms **Structure**: `levels[0]` = bids (descending), `levels[1]` = asks (ascending) *** ## L2 Delta Stream Real-time incremental order book updates with initial snapshot. > [!NOTE] > > L2 Delta sends an initial snapshot (latest cached book state) on subscription, > then publishes every changed price level for an instrument update together in > one atomic delta message. ```json Subscribe theme={null} { "method": "subscribe", "subscription": [{ "type": "l2Delta", "symbol": "BTC-USD" }] } ``` ```json Response theme={null} { "type": "subscriptionResponse", "topics": ["l2delta.BTC-USD"] } ``` ```json Atomic Delta Batch theme={null} { "type": "l2Delta", "data": { "book": { "updateType": "delta", "symbol": "BTC-USD", "levels": [ [ {"px": 102777.0, "sz": 2.0, "n": 0}, {"px": 102776.0, "sz": 0.0, "n": 0} ], [{"px": 102780.0, "sz": 1.5, "n": 0}] ], "timestamp": 1699564800000 } }, "topic": "l2delta.BTC-USD" } ``` **Initial Response**: Latest cached book state (if available) **Updates**: Real-time, one message per instrument update batch **Delta Format**: * Each delta message contains every changed price level in the instrument's update batch * A message may contain multiple bid and ask changes; either side may be empty * `levels[0]` = bids (highest to lowest) * `levels[1]` = asks (lowest to highest) * Each level: `{px, sz, n}` where `n` is always `0` for deltas * `sz: 0` means remove the level Apply all levels in a delta message atomically before exposing the updated local book. If the connection drops or the client falls behind as a slow consumer, reconnect and rebuild from a fresh `l2Snapshot` before resuming `l2Delta` processing. *** ## Risk Metrics Stream Subscribe to the complete risk-surface set for a symbol, including the live regime, maximum-leverage curve, per-regime maintenance-margin grids, and asset correlations. ```json Subscribe theme={null} { "method": "subscribe", "subscription": [{ "type": "risk", "symbol": "BTC-USD" }] } ``` ```json Response theme={null} { "type": "subscriptionResponse", "topics": ["risk.BTC-USD"] } ``` ```json Update theme={null} { "type": "risk", "data": { "risk": { "symbol": "BTC-USD", "liveRegime": 1, "leverage": { "min": 2.0, "max": 50.0, "margin_0": 250000.0, "margin_half": 2500000.0 }, "surfaces": [{ "regime": 1, "leverage": [1.0, 2.0, 5.0], "notionals": [50000.0, 100000.0, 250000.0], "buy": [[{ "mmrO": 0.01, "mmrE": 0.008, "p": 0.9987 }]], "sell": [[{ "mmrO": 0.01, "mmrE": 0.008, "p": 0.9987 }]] }], "corrs": [ ["BTC:ETH", 0.7099833416646828], ["BTC:SOL", 0.7295520206661339], ["ETH:SOL", 0.7198669330795061] ] } }, "topic": "risk.BTC-USD" } ``` **Initial Response**: Latest cached risk metrics (if available) **Updates**: Event-driven (only when asset risk changes) **Risk Metrics Fields**: | Field | Description | | - | - | | `symbol` | Market symbol | | `liveRegime` | Currently active risk-regime index | | `leverage` | Maximum-leverage curve with `min`, `max`, `margin_0`, and `margin_half` | | `surfaces` | Risk surfaces for all regimes, sorted by regime | | `surfaces[].leverage` | Leverage knot points for one regime | | `surfaces[].notionals` | Notional knot points for one regime | | `surfaces[].buy` | 2D risk-point array `[notional_idx][leverage_idx]` for buy side | | `surfaces[].sell` | 2D risk-point array `[notional_idx][leverage_idx]` for sell side | | `corrs` | Array of `[pair, correlation]` tuples (e.g. `["BTC:ETH", 0.71]`) | **Buy/sell point fields** (each cell in the grid): | Field | Description | | - | - | | `mmrO` | Start-of-regime maintenance margin ratio | | `mmrE` | End-of-regime maintenance margin ratio | | `p` | Probability of remaining in the regime | **Surface indexing**: Select the desired `surfaces[]` regime, find the notional and leverage brackets, then use `buy[notional_idx][leverage_idx]` or `sell[notional_idx][leverage_idx]`. Interpolate between surrounding grid points if needed. *** ## Impact Curve Stream Subscribe to the latest liquidation-size impact curve for one market. The server sends the cached curve immediately when available, followed by executor-published updates. ```json Subscribe theme={null} { "method": "subscribe", "subscription": [{ "type": "impact", "symbol": "BTC-USD" }] } ``` ```json Update theme={null} { "type": "impact", "topic": "impact.BTC-USD", "data": { "symbol": "BTC-USD", "timestamp": 1720000000000, "minSize": 0.01, "sellBps": { "logMin": -4.605, "logRange": 10.127, "bps": [1.2, 1.4, 1.7] }, "buyBps": { "logMin": -4.605, "logRange": 10.127, "bps": [1.1, 1.3, 1.6] } } } ``` * `timestamp` is Unix time in milliseconds. * Each curve contains 250 basis-point values at log-uniform size knots. * `minSize` is the size represented by the first knot. Knot `i` represents `exp(logMin + i / (n - 1) * logRange)`. * No initial event is sent before the executor publishes the first curve for that symbol. The same cached value is available through [`GET /impact`](/api-reference/getImpact). *** ## Frontend Context Stream Aggregated market context for all symbols. Ideal for dashboard views. ```json Subscribe theme={null} { "method": "subscribe", "subscription": [{ "type": "frontendContext" }] } ``` ```json Response theme={null} { "type": "subscriptionResponse", "topics": ["frontendContext"] } ``` ```json Update theme={null} { "type": "frontendContext", "data": { "ctx": [ { "symbol": "BTC-USD", "volume": 1234.56, "funding": 0.0001, "oi": 5432.1, "lastPrice": 102777.5, "priceChange": 2777.5, "priceChangePercent": 2.77 }, { "symbol": "ETH-USD", "volume": 5678.90, "funding": 0.00015, "oi": 12345.6, "lastPrice": 3500.0, "priceChange": 150.0, "priceChangePercent": 4.48 } ] }, "topic": "frontendContext" } ``` **Initial Response**: Latest cached ticker data for all symbols **Updates**: Every 2 seconds **Context Fields**: | Field | Description | | - | - | | `symbol` | Market symbol | | `volume` | 24h trading volume (base currency) | | `funding` | Current funding rate | | `oi` | Open interest (base currency) | | `lastPrice` | Last traded price | | `priceChange` | 24h price change (absolute) | | `priceChangePercent` | 24h price change (percentage) | *** ## Multiple Subscriptions Subscribe to multiple streams at once: ```json theme={null} { "method": "subscribe", "subscription": [ {"type": "ticker", "symbol": "BTC-USD"}, {"type": "trades", "symbol": "BTC-USD"}, {"type": "candle", "symbol": "BTC-USD", "interval": "1m"}, {"type": "l2Snapshot", "symbol": "BTC-USD", "nlevels": 20}, {"type": "l2Delta", "symbol": "BTC-USD"}, {"type": "risk", "symbol": "BTC-USD"}, {"type": "impact", "symbol": "BTC-USD"}, {"type": "frontendContext"} ] } ``` **Response**: ```json theme={null} { "type": "subscriptionResponse", "topics": [ "ticker.BTC-USD", "trades.BTC-USD", "candle.BTC-USD.1m", "l2snapshot.BTC-USD", "l2delta.BTC-USD", "risk.BTC-USD", "impact.BTC-USD", "frontendContext" ] } ``` *** ## Example Implementation ```javascript Node.js theme={null} const WebSocket = require('ws'); const ws = new WebSocket('wss://mainnet-ws1.bulk.trade'); ws.on('open', () => { console.log('Connected to Bulk Exchange'); // Subscribe to multiple streams ws.send(JSON.stringify({ method: 'subscribe', subscription: [ { type: 'ticker', symbol: 'BTC-USD' }, { type: 'trades', symbol: 'BTC-USD' }, { type: 'frontendContext' } ] })); }); ws.on('message', (data) => { const message = JSON.parse(data); if (message.type === 'subscriptionResponse') { console.log('Subscribed to:', message.topics); return; } switch(message.type) { case 'ticker': console.log('Ticker:', message.data.ticker); break; case 'trades': console.log('Trade:', message.data.trades); break; case 'frontendContext': console.log('Context:', message.data.ctx); break; } }); ws.on('error', (error) => { console.error('WebSocket error:', error); }); ``` ```python Python theme={null} import websocket import json def on_message(ws, message): data = json.loads(message) if data.get('type') == 'subscriptionResponse': print(f"Subscribed to: {data['topics']}") return msg_type = data.get('type') if msg_type == 'ticker': print(f"Ticker: {data['data']['ticker']}") elif msg_type == 'trades': print(f"Trade: {data['data']['trades']}") elif msg_type == 'frontendContext': print(f"Context: {data['data']['ctx']}") def on_open(ws): print('Connected to Bulk Exchange') # Subscribe to multiple streams ws.send(json.dumps({ 'method': 'subscribe', 'subscription': [ {'type': 'ticker', 'symbol': 'BTC-USD'}, {'type': 'trades', 'symbol': 'BTC-USD'}, {'type': 'frontendContext'} ] })) def on_error(ws, error): print(f'Error: {error}') ws = websocket.WebSocketApp( 'wss://mainnet-ws1.bulk.trade', on_message=on_message, on_open=on_open, on_error=on_error ) ws.run_forever() ``` # Trading via WebSocket Source: https://docs.bulk.trade/api-reference/ws-trading Submit orders and other actions through WebSocket using the unified transaction format > [!NOTE] > > **4 October 2026 upgrade:** the new post-only modes and conditional slippage > options documented below apply after the scheduled upgrade. WebSocket `post` > uses the same signed action schema as `POST /order`. > [!NOTE] > > All trading operations require Ed25519 signatures and a unique `nonce` for replay protection. See [Transaction Signing](/api-reference/signing) for the canonical message format and [Place & Cancel Orders](/api-reference/placeOrder) for the full transaction envelope. ## Post Request Format All order and trading-related operations use the `post` method with the **unified transaction** payload: ```json theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [Action, ...], "nonce": 1704067200000000000, "account": "base58_pubkey", "signer": "base58_pubkey", "signature": "base58_signature" } }, "id": 1 } ``` **Transaction fields:** | Field | Description | | - | - | | `actions` | Array of actions to execute atomically (see [Action types](#action-types) below) | | `nonce` | Unique integer (u64) for replay protection (e.g. timestamp in nanoseconds) | | `account` | Account public key (base58) - whose account is being traded | | `signer` | Signer public key (base58) - who is signing (usually same as account, or authorized agent) | | `signature` | Ed25519 signature (base58) over the signed message | **Signing:** The signed message is `bincode_serialize(commission_signable_actions) + nonce_le_u64 + account_pubkey_bytes + signature_domain_u8`, where the domain is `1 = mainnet`, `2 = testnet`, or `3 = devnet`. Signer is not part of the signed message. See [Transaction Signing](/api-reference/signing) for details. **Offchain signing (optional):** the server also accepts transactions signed with the [v0 Solana offchain envelope](/api-reference/signing#offchain-signing-mode) for any action shape. Set the WebSocket handshake header `x-bulk-sig-mode: offchain` on the upgrade and then send `post` actions normally - the `payload` JSON shape is unchanged, only the `signature` bytes differ. See [Optional Handshake Headers](/api-reference/ws-connection#optional-handshake-headers). *** ## Action Types Each action in the `actions` array is a single-key object. The key is the action tag, the value is the action payload. **Order and conditional actions:** | Action | Description | Example | | - | - | - | | `l` | Limit order | `{"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false, "i": false}}` | | `m` | Market order | `{"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false}}` | | `mod` | Modify order size | `{"mod": {"oid": "base58_hash", "symbol": "BTC-USD", "amount": 0.05}}` | | `cx` | Cancel one order | `{"cx": {"c": "BTC-USD", "oid": "base58_hash"}}` | | `cxa` | Cancel all orders | `{"cxa": {"c": ["BTC-USD"]}}` or `{"cxa": {"c": []}}` for all symbols | | `st` | Stop order | `{"st": {"c": "BTC-USD", "d": false, "sz": 0.25, "tr": 98000.0, "lim": 97950.0, "i": false}}` | | `tp` | Take profit | `{"tp": {"c": "BTC-USD", "d": true, "sz": 0.25, "tr": 104000.0, "lim": 103950.0, "i": false}}` | | `rng` | Range / OCO | `{"rng": {"c": "BTC-USD", "d": true, "sz": 0.5, "pmin": 96000.0, "pmax": 106000.0, "lmin": 95950.0, "lmax": 105950.0, "i": false}}` | | `trig` | Trigger basket | `{"trig": {"c": "BTC-USD", "d": true, "tr": 105000.0, "actions": [...]}}` | | `trl` | Trailing stop | `{"trl": {"c": "BTC-USD", "b": true, "sz": 0.25, "trb": 100, "stb": 10, "lim": null, "i": false}}` | | `of` | On-fill | `{"of": {"trigger": {"l": {...}}, "actions": [...]}}` | The `i` flag is part of the canonical wincode message for `l`, `m`, `st`, `tp`, `rng`, and `trl`, and must be included explicitly. `i=true` routes the action via the implicit per-instrument isolated account; `i=false` trades from cross margin on the transaction's `account`. A `trig` basket has no top-level `i`; each nested action controls its own routing. Builder codes are optional builder-code fees on `m` and `l` only. Encode them with `builderCode: { "to": "recipient_pubkey_base58", "fee": 5 }`, where `fee` is `1..=15` bps and must be pre-approved with `abc`. Submit orders without builder codes by omitting `builderCode`; `"builderCode": null` is rejected by the JSON API. > [!WARNING] > > `abc` and `rbc` are master-account-only actions. Agent wallets cannot approve or revoke builder-code recipients. **Account management actions:** | Action | Description | Example | | - | - | - | | `createSubAccount` | Create a sub-account (optional initial margin transfer) | `{"createSubAccount": {"name": "desk-1", "marginSymbol": "USDC", "marginAmount": 1000.0}}` | | `removeSubAccount` | Remove a sub-account (or auto-created isolated account) by pubkey | `{"removeSubAccount": {"toRemove": "base58_pubkey"}}` | | `renameSubAccount` | Rename a sub-account | `{"renameSubAccount": {"a": "base58_pubkey", "n": "desk-1"}}` | | `transfer` | Move margin between accounts (internal/external/iso top-up) | `{"transfer": {"k": "internal", "from": "base58_pubkey", "to": "base58_pubkey", "marginSymbol": "USDC", "marginAmount": 100.0}}` | | `agentWalletCreation` | Register or revoke an agent wallet | `{"agentWalletCreation": {"a": "agent_pubkey", "d": false}}` | | `abc` | Approve builder-code recipient | `{"abc": {"to": "recipient_pubkey_base58", "fee": 5}}` | | `rbc` | Revoke builder-code recipient | `{"rbc": {"to": "recipient_pubkey_base58"}}` | | `updateUserSettings` | Update per-symbol max leverage | `{"updateUserSettings": {"m": {"BTC-USD": 5.0}}}` | | `faucet` | Request testnet quote (paper environments only) | `{"faucet": {"u": "base58_pubkey"}}` | For per-instrument isolated-account top-ups, set `transfer.to` to the `isoPubkey` from an `iso=true` open-position row on the [Account Stream](/api-reference/ws-account): ```json theme={null} {"transfer": {"k": "internal", "from": "master_or_sub_pubkey", "to": "iso_pubkey", "marginSymbol": "USDC", "marginAmount": 100.0}} ``` `k="external"` recipient auto-create applies only to on-curve pubkeys; unknown off-curve recipients are rejected. > [!NOTE] > > * `createSubAccount.marginAmount` and `transfer.marginAmount` must be JSON numbers (unquoted), e.g. `0` or `100.0`, not `"0"` or `"100.0"`. See [Manage Sub-Accounts](/api-reference/manageSubAccounts) and [Transfer](/api-reference/transfer) for full envelope and result-row references; [Manage Agent Wallet](/api-reference/manageAgentWallet), [Update User Settings](/api-reference/updateUserSettings), and [Request Faucet](/api-reference/requestFaucet) cover the other shared envelopes. `updateUserSettings` uses `m` as an object map (e.g. `"m": {"BTC-USD": 10.0}`). *** ## Place Limit Order ```json Request theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false, "i": false}} ], "nonce": 1704067200000000000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 1 } ``` ```json Response (Resting) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "resting": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F" } }] } } } } } ``` ```json Response (Filled) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "filled": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "totalSz": 0.1, "avgPx": 102500.0 } }] } } } } } ``` ```json Response (Partially Filled) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "partiallyFilled": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "totalSz": 0.05, "avgPx": 102500.0 } }] } } } } } ``` ```json Response (Error) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "error": { "message": "Insufficient margin" } }] } } } } } ``` **Limit order (`l`) fields:** `c` (symbol), `b` (true = buy), `px` (limit price), `sz` (size), `tif` (time in force), `r` (reduce-only), `i` (isolated routing flag, required), optional builder-code fee in `builderCode` (`{to, fee}`; omit when absent). With builder code: ```json theme={null} {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false, "i": false, "builderCode": {"to": "recipient_pubkey_base58", "fee": 5}}} ``` **Time in force:** `GTC` (good till cancel), `IOC` (immediate or cancel), `ALO` (strict post-only; rejects if crossing), `ALO_SLIDE` (crossing price slides to the nearest non-crossing display tick), and `ALO_JOIN` (crossing price joins the same-side best quote, falling back to Slide if that side is empty). For example, the signed `payload.actions` may contain: ```json theme={null} [ {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "ALO_SLIDE", "r": false, "i": false}} ] ``` Use `"ALO_JOIN"` to choose Join. JSON requests use these names, not numeric enum indices. Account/order update responses use `postOnlySlide` and `postOnlyJoin`. Resting buy prices round down and sell prices round up to the display tick; IOC retains native precision. Market-executing conditional legs support basis-point slippage overrides: `slippage` on `st`, `tp`, and `trl`; `slSlippage` / `tpSlippage` on `rng`. Use the updated SDK signing encoder for conditional actions, including mixed batches. See [Place & Cancel Orders](/api-reference/placeOrder#conditional-slippage-overrides). *** ## Place Market Order ```json theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false}} ], "nonce": 1704067200000000000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 2 } ``` **Market order (`m`) fields:** `c` (symbol), `b` (true = buy), `sz` (size), `r` (reduce-only), `i` (isolated routing flag, required), optional builder-code fee in `builderCode` (`{to, fee}`; omit when absent). With builder code: ```json theme={null} {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false, "builderCode": {"to": "recipient_pubkey_base58", "fee": 5}}} ``` *** ## Modify Order Change the size of an existing order: ```json theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"mod": {"oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "symbol": "BTC-USD", "amount": 0.05}} ], "nonce": 1704067200000000000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 3 } ``` **Modify (`mod`) fields:** `oid` (order ID, base58), `symbol`, `amount` (new size). *** ## Cancel Order ```json Request theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"cx": {"c": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F"}} ], "nonce": 1704067200000000000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 4 } ``` ```json Response theme={null} { "type": "post", "id": 4, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "cancelled": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F" } }] } } } } } ``` *** ## Cancel All Orders **Cancel all in one or more symbols:** use `cxa` with `c` = array of symbols. **Cancel all across all symbols:** use `cxa` with `c` = `[]`. ```json Cancel all in symbol(s) theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [{"cxa": {"c": ["BTC-USD"]}}], "nonce": 1704067200000000000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 5 } ``` ```json Cancel all across all symbols theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [{"cxa": {"c": []}}], "nonce": 1704067200000000001, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 6 } ``` *** ## Stop Order (`st`) ```json Request theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"st": {"c": "BTC-USD", "d": false, "sz": 0.25, "tr": 98000.0, "lim": 97950.0}} ], "nonce": 1704067200000000011, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 11 } ``` ```json Response (Resting) theme={null} { "type": "post", "id": 11, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"resting": {"oid": "7kR2mQfENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7"}}] } } } } } ``` **Stop order (`st`) fields:** `c` (symbol), `d` (trigger direction: `true` = above/equal, `false` = below/equal), `sz` (size), `tr` (trigger price), `lim` (optional limit after trigger; omit for market-style). *** ## Take Profit (`tp`) ```json Request theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"tp": {"c": "BTC-USD", "d": true, "sz": 0.25, "tr": 104000.0, "lim": 103950.0}} ], "nonce": 1704067200000000012, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 12 } ``` ```json Response (Resting) theme={null} { "type": "post", "id": 12, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"resting": {"oid": "8mT3nQgGPjHFX7vNrAShxnk0hqoc96FhVdAb6Fn5QRi8"}}] } } } } } ``` Same fields as Stop Order (`st`). *** ## Range / OCO (`rng`) ```json Request theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"rng": {"c": "BTC-USD", "d": true, "sz": 0.5, "pmin": 96000.0, "pmax": 106000.0, "lmin": 95950.0, "lmax": 105950.0}} ], "nonce": 1704067200000000013, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 13 } ``` ```json Response (Resting) theme={null} { "type": "post", "id": 13, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"resting": {"oid": "9nU4oRhHQkIGY8wOrBTiypn1irpd07GiWeBC7Go6RSj9"}}] } } } } } ``` ```json Response (Triggered) theme={null} { "type": "post", "id": 13, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"triggered": {"oid": "9nU4oRhHQkIGY8wOrBTiypn1irpd07GiWeBC7Go6RSj9"}}] } } } } } ``` ```json Response (Sibling Cancelled) theme={null} { "type": "post", "id": 13, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"siblingCancelled": {"oid": "ABC123..."}}] } } } } } ``` **Range/OCO (`rng`) fields:** `c` (symbol), `d` (position direction: `true` = long collar, `false` = short), `sz` (size), `pmin`/`pmax` (lower/upper trigger), `lmin`/`lmax` (optional limits for each leg). When one leg triggers, the sibling leg is auto-cancelled with status `siblingCancelled`. *** ## Trigger Basket (`trig`) ```json Request theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"trig": {"c": "BTC-USD", "d": true, "tr": 105000.0, "actions": [ {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false}}, {"cx": {"c": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F"}} ]}} ], "nonce": 1704067200000000014, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 14 } ``` ```json Response (Resting) theme={null} { "type": "post", "id": 14, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"resting": {"oid": "AoV5pSiIRlJHZ9xPsCUjzqo2jsqe18HjXfCD8Hp7STk0"}}] } } } } } ``` ```json Response (Triggered) theme={null} { "type": "post", "id": 14, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"triggered": {"oid": "AoV5pSiIRlJHZ9xPsCUjzqo2jsqe18HjXfCD8Hp7STk0"}}] } } } } } ``` ```json Response (Trigger Failed) theme={null} { "type": "post", "id": 14, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"triggerFailed": {"oid": "AoV5pSiIRlJHZ9xPsCUjzqo2jsqe18HjXfCD8Hp7STk0", "reason": "conditional execution failed: no counterparty"}}] } } } } } ``` **Trigger basket (`trig`) fields:** `c` (symbol), `d` (trigger direction: `true` = above/equal), `tr` (trigger threshold), `actions` (nested actions executed when trigger fires). Nested actions support: `m`, `l`, `mod`, `cx`, `cxa`, `st`, `tp`, `rng`, `trl`. *** ## Trailing Stop (`trl`) ```json Request theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"trl": {"c": "BTC-USD", "b": true, "sz": 0.25, "trb": 100, "stb": 10, "lim": null}} ], "nonce": 1704067200000000015, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 15 } ``` ```json Response (Resting) theme={null} { "type": "post", "id": 15, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"resting": {"oid": "BpW6qTjJSkKIA0yQtDVkAro3ktrf29IkYgED9Iq8UUl1"}}] } } } } } ``` **Trailing stop (`trl`) fields:** `c` (symbol), `b` (protected direction: `true` = long), `sz` (size), `trb` (trailing distance in bps), `stb` (favorable reset step in bps), `lim` (optional limit; `null` for market-style). *** ## On-Fill (`of`) ```json Request (Limit + On-Fill Stop) theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"of": { "trigger": { "l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.25, "tif": "GTC", "r": false, "i": false} }, "actions": [ {"st": {"c": "BTC-USD", "d": false, "sz": 0.25, "tr": 98000.0, "lim": null, "i": false}} ] }} ], "nonce": 1704067200000000016, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 16 } ``` ```json Response (Resting + On-Fill Registered) theme={null} { "type": "post", "id": 16, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [ {"resting": {"oid": "CqX7rUkKTmLJB1zRuEWlBsp4lusg30JlZhFE0Jr9VVm2"}}, {"resting": {"oid": "DrY8sVlLUnMKC2ASvFXmCtp5mvth41KmaiGF1Ks0WWn3"}} ] } } } } } ``` **On-fill (`of`) fields:** `trigger` (an embedded `m` or `l` action), `actions` (one-shot consequents executed on the trigger's first fill). An embedded trigger or consequent `m` / `l` may carry `builderCode` under the normal order rules. Nested actions support: `m`, `l`, `mod`, `cx`, `cxa`, `st`, `tp`, `rng`, `trig`, `trl`. > [!NOTE] > > **Cancelling conditional orders**: Use `cx` with the conditional order ID or `cxa` to cancel all orders including conditionals. *** ## Batch Actions Multiple actions can be combined in a single transaction (same `nonce`, `account`, `signer`, `signature`). One status is returned per action/event. **Example: cancel one order and place two new limit orders** ```json theme={null} { "method": "post", "request": { "type": "action", "payload": { "actions": [ {"cx": {"c": "BTC-USD", "oid": "old_order_id_base58"}}, {"l": {"c": "BTC-USD", "b": true, "px": 99900.0, "sz": 0.05, "tif": "GTC", "r": false}}, {"l": {"c": "BTC-USD", "b": false, "px": 100100.0, "sz": 0.05, "tif": "GTC", "r": false}} ], "nonce": 1704067200000000000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s...base58..." } }, "id": 7 } ``` *** ## Response Format | Field | Description | | - | - | | `type` | Always `"post"` for trading responses | | `id` | Request ID (matches the request) | | `data.type` | Always `"action"` | | `data.payload.status` | `"ok"` or `"error"` | | `data.payload.response.type` | Response type (e.g., `"order"`) | | `data.payload.response.data.statuses` | Array of status objects (one per execution event) | > [!TIP] > > Size fields in responses (`totalSz`, `filledSz`, `remainingSz`) are **signed**: negative values indicate sell-side. For example, a fully-filled sell of 0.1 BTC returns `totalSz: -0.1`. *** ## Status Types ### Non-Terminal (Order Still Active) | Status | Description | Fields | | - | - | - | | `resting` | Order placed and resting on book | `{oid}` | | `working` | Partial fills, still resting | `{oid, filledSz, remainingSz, vwap}` | | `triggered` | Conditional root fired | `{oid}` | ### Terminal (Order Complete) | Status | Description | Fields | | - | - | - | | `filled` | Order fully filled | `{oid, totalSz, avgPx}` | | `partiallyFilled` | Partially filled and terminal | `{oid, totalSz, avgPx}` | | `cancelled` | Cancelled by user | `{oid}` | | `cancelledRiskLimit` | Cancelled - risk limit | `{oid, reason?}` | | `cancelledSelfCrossing` | Cancelled - self-crossing (STP) | `{oid}` | | `cancelledReduceOnly` | Cancelled - would increase position | `{oid}` | | `cancelledIoc` | IOC expired without full fill | `{oid, filledSz}` | | `rejectedCrossing` | Post-only rejected for crossing | `{oid}` | | `rejectedDuplicate` | Duplicate order ID | `{oid}` | | `rejectedRiskLimit` | Rejected - risk limit | `{oid, reason?}` | | `rejectedInvalid` | Invalid parameters | `{oid, reason?}` | | `siblingCancelled` | OCO sibling auto-cancelled | `{oid}` | | `triggerFailed` | Trigger execution failed | `{oid, reason?}` | | `deposit` | Faucet deposit succeeded | `{amount}` | | `depositFailed` | Faucet deposit failed | `{message}` | | `agentWallet` | Agent wallet registered | `{agentWallet}` | | `agentWalletFailed` | Agent wallet failed | `{message}` | | `cancelOneRejected` | Cancel rejected | `{oid, reason}` | | `cancelAllRejected` | Cancel all rejected | `{reason}` | | `error` | Generic error | `{message}` | *** ## Response Examples ```json Working (partial fill, sell side) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "working": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "filledSz": -0.05, "remainingSz": -0.05, "vwap": 100000.0 } }] } } } } } ``` ```json Filled (buy side) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "filled": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "totalSz": 0.1, "avgPx": 100025.5 } }] } } } } } ``` ```json Triggered (conditional) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"triggered": {"oid": "9nU4oRhHQkIGY8wOrBTiypn1irpd07GiWeBC7Go6RSj9"}}] } } } } } ``` ```json Cancelled Risk Limit theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "cancelledRiskLimit": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "reason": "Position would exceed max leverage" } }] } } } } } ``` ```json IOC Cancelled (partial fill) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "cancelledIoc": { "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "filledSz": 0.03 } }] } } } } } ``` ```json Sibling Cancelled (OCO) theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"siblingCancelled": {"oid": "DEF..."}}] } } } } } ``` ```json Trigger Failed theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"triggerFailed": {"oid": "GHI...", "reason": "conditional execution failed: no counterparty"}}] } } } } } ``` ```json Error theme={null} { "type": "post", "id": 1, "data": { "type": "action", "payload": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{"error": {"message": "Insufficient margin"}}] } } } } } ``` *** ## Order Updates (Account Stream) In addition to the inline `post` response, all order state changes are delivered as `orderUpdate` messages on the [Account Stream](/api-reference/ws-account). These carry the full order state with signed sizes. > [!WARNING] > > `origSz` and `sz` are **signed**: negative values indicate sell-side intent. For example, a sell order for 0.25 BTC has `origSz: -0.25`. > For `ot: "trigger"` baskets, `origSz` and `sz` are `0` (trigger baskets carry nested actions, not a direct sized order). ```json theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "resting", "sym": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "px": 102000.0, "origSz": 0.1, "sz": 0.1, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": true, "trigger": null, "ts": 1763316177219383423, "reason": null }, "topic": "account.9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" } ``` ### orderUpdate Fields | Field | Description | | - | - | | `ot` | Order type: `limit`, `market`, `stop`, `takeProfit`, `range`, `trigger`, `trailing` | | `status` | Order status (see [Status Types](#status-types)) | | `sym` | Market symbol | | `oid` | Order ID (base58) | | `px` | Order price (or trigger reference price) | | `origSz` | **Signed** original order size (negative = sell) | | `sz` | **Signed** current remaining size (negative = sell) | | `fillSz` | Amount filled | | `vwap` | Volume-weighted average fill price | | `tif` | Time in force: `gtc`, `ioc`, `postOnly`, `postOnlySlide`, `postOnlyJoin` | | `r` | Reduce-only flag | | `mk` | Maker/resting flag | | `trigger` | Trigger metadata for conditionals (see below), or `null` | | `pendingOnFill` | On-fill registration attached to parent while awaiting first fill, or absent | | `ts` | Event timestamp (nanoseconds) | | `reason` | Rejection/cancellation reason (optional) | ### Trigger Metadata When `trigger` is present (conditional orders): | Field | Description | | - | - | | `isAbove` | Trigger direction (`true` = above/equal, `false` = below/equal, `null` if not encoded) | | `px` | Trigger threshold price | | `lim` | Post-trigger limit price (`null` = market) | | `oco` | Linked OCO order ID (if any) | | `pxHi` | Upper trigger threshold (range upper band / trailing sentinel) | | `limHi` | Upper post-trigger limit (range upper leg) | | `trb` | Trailing distance in bps (trailing only) | | `stb` | Favorable reset step in bps (trailing only) | ### orderUpdate Examples ```json Sell Limit Resting (signed size) theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "resting", "sym": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "px": 105000.0, "origSz": -0.25, "sz": -0.25, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": true, "trigger": null, "ts": 1763316177219383423, "reason": null }, "topic": "account.9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" } ``` ```json Filled (buy side) theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "limit", "status": "filled", "sym": "BTC-USD", "oid": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "px": 100000.0, "origSz": 0.1, "sz": 0.0, "fillSz": 0.1, "vwap": 100025.5, "tif": "gtc", "r": false, "mk": false, "trigger": null, "ts": 1763316177219383423, "reason": null }, "topic": "account.9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" } ``` ```json Stop Resting (with trigger metadata) theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "stop", "status": "resting", "sym": "BTC-USD", "oid": "7kR2mQfENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "px": 0.0, "origSz": -0.25, "sz": -0.25, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": false, "trigger": { "isAbove": false, "px": 98000.0, "lim": 97950.0, "oco": null, "pxHi": null, "limHi": null, "trb": null, "stb": null }, "ts": 1763316177219383423, "reason": null }, "topic": "account.9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" } ``` ```json Range/OCO Triggered theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "range", "status": "triggered", "sym": "BTC-USD", "oid": "9nU4oRhHQkIGY8wOrBTiypn1irpd07GiWeBC7Go6RSj9", "px": 0.0, "origSz": 0.0, "sz": 0.0, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": true, "mk": false, "trigger": null, "ts": 1763316177219383423 }, "topic": "account.9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" } ``` ```json Sibling Cancelled (OCO) theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "range", "status": "siblingCancelled", "sym": "BTC-USD", "oid": "DEF...", "px": 0.0, "origSz": 0.0, "sz": 0.0, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": false, "mk": false, "trigger": null, "ts": 1763316177219383423, "reason": "oco sibling cancelled" }, "topic": "account.9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" } ``` ```json Trigger Failed theme={null} { "type": "account", "data": { "type": "orderUpdate", "ot": "stop", "status": "triggerFailed", "sym": "BTC-USD", "oid": "GHI...", "px": 0.0, "origSz": 0.0, "sz": 0.0, "fillSz": 0.0, "vwap": 0.0, "tif": "gtc", "r": true, "mk": false, "trigger": null, "ts": 1763316177219383423, "reason": "conditional execution failed: no counterparty" }, "topic": "account.9J8TUdEWrrcADK913r1Cs7DdqX63VdVU88imfDzT1ypt" } ``` ### Fill Event Emitted separately on each trade execution (in addition to `orderUpdate`): ```json theme={null} { "type": "account", "data": { "type": "fill", "symbol": "BTC-USD", "orderId": "Fpa3oVuL3UzjNANAMZZdmrn6D1Zhk83GmBuJpuAWG51F", "price": 102000.0, "size": 0.05, "isBuy": true, "timestamp": 1763316177219383423, "maker": false }, "topic": "account.FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7" } ``` See [Account Stream](/api-reference/ws-account) for the full account stream reference. *** ## Error Handling > [accordion] Invalid signature > > Ensure you're using the correct serialization format including `nonce`. Use official SDKs when possible. > [accordion] Unauthorized signer > > `signer` must be one of: the `account` itself, an agent wallet registered on `account`, or (when `account` is a sub-account) an agent wallet registered on the parent master. Agents registered on a master can sign for the master and for any of its sub-accounts and per-instrument isolated accounts. Sub-accounts can also register their own agents. Isolated accounts are never used as `account`; their margin and orders are reached via `i=true` on order actions and the `to` field of a `transfer`. See [Manage Agent Wallet](/api-reference/manageAgentWallet). > [accordion] Insufficient margin > > Check your available balance before placing orders. Consider position size and leverage. > [accordion] Duplicate nonce > > Each nonce can only be used once. Use nanosecond timestamps: `BigInt(Date.now()) * 1_000_000n`. > [accordion] Order rejected > > Verify order parameters meet market requirements (min size, tick size, etc). # Audits Source: https://docs.bulk.trade/architecture/audits The BULK Program on Solana was independently audited by Zellic in July 2026. > [card] [Download Zellic Audit Report](https://github.com/Bulk-trade/audits/releases/download/bulk-program-zellic-2026/bulk-program-zellic-security-assessment.pdf) > > Read full Security Assessment. # BULKBFT Consensus Source: https://docs.bulk.trade/architecture/consensus Leaderless Byzantine fault-tolerant consensus for the BULK Network. ## Overview BULKBFT is a leaderless Byzantine fault-tolerant consensus protocol optimized for low-latency agreement on transaction sets. It achieves consensus in a single vote-commit round under partial synchrony, with no block proposer and no leader election. ## System Model We consider a set of $n$ validators $V = \lbrace v_1, v_2, \ldots, v_n \rbrace$, of which at most $f$ may be Byzantine, where: $$ f = \left\lfloor \frac{n - 1}{3} \right\rfloor $$ Each validator $v_i$ has a stake weight $w_i$ inherited from Solana. A set $S \subseteq V$ forms a **supermajority** if: $$ \sum_{v_i \in S} w_i > \frac{2}{3} \sum_{v_i \in V} w_i $$ We assume partial synchrony: there exists an unknown Global Stabilization Time (GST) after which all messages between honest validators are delivered within a known bound $\delta$. ## Transaction Ingress When a signed transaction $tx$ arrives at validator $v_i$, the ingress pipeline: 1. Computes a compact hash $h(tx)$ for deduplication 2. Stores the full transaction body in a local cache 3. Broadcasts $h(tx)$ to all validators in $V$ via authenticated channels Validators only exchange hashes during consensus. Full transaction bodies are fetched from the local cache after commitment. ## Authenticated Transport Validator-to-validator communication uses the **Noise Protocol Framework** (IK handshake, AEGIS-128L encryption). Each validator's Noise keypair is derived from their Solana Ed25519 identity key (converted to X25519 for Diffie-Hellman). This binds transport authentication to Solana stake - impersonation requires the validator's private key. ## Minisketch Set Reconciliation Rather than exchanging full hash lists, validators use **minisketch** for efficient set reconciliation. Each validator $v_i$ maintains a sketch $S_i$ - a compact probabilistic data structure representing their pending transaction set $T_i$. Given sketches from two validators, the symmetric difference $T_i \oplus T_j$ can be computed in $O(d)$ where $d = |T_i \oplus T_j|$ is the number of differing elements. This is a significant reduction from the naive $O(|T_i| + |T_j|)$ approach. ## Protocol ### Round Structure Each consensus round $r$ proceeds in two phases. **Phase 1 - Vote.** Each validator $v_i$ computes a digest $D_i^r$ of its proposed transaction set for round $r$: $$ D_i^r = H\left(T_i^r\right) $$ where $H$ is a collision-resistant hash function and $T_i^r$ is the set of pending transactions at $v_i$ after minisketch reconciliation. Validator $v_i$ broadcasts a signed vote $\langle \text{VOTE}, r, D_i^r \rangle_{\sigma_i}$ to all validators. **Phase 2 - Commit.** Upon receiving votes from a supermajority, each validator computes the intersection digest - the set of transactions present in the proposed sets of all supermajority voters: $$ T_{\text{committed}}^r = \bigcap_{v_i \in S} T_i^r \quad \text{where } S \text{ is a supermajority} $$ Validator $v_i$ broadcasts a signed commit $\langle \text{COMMIT}, r, H(T_{\text{committed}}^r) \rangle_{\sigma_i}$. **Commitment.** When a validator collects a supermajority of matching commit messages for round $r$, the batch is committed: $$ \text{CommittedBatch}(r) = \left(T_{\text{committed}}^r,\; r,\; \tau(r),\; \Sigma_r\right) $$ where $\tau(r)$ is the deterministic timestamp for round $r$ (see [Deterministic Clock](/architecture/timestamps)) and $\Sigma_r$ is the set of supermajority signatures. ### Fast Path Under partial synchrony (after GST), the protocol completes in one vote exchange plus one commit - two message delays total: $$ \text{latency}_{\text{fast}} = 2\delta $$ This is the theoretical minimum for BFT agreement and the common case during normal operation. ### Slow Path When synchrony breaks (network partitions, delayed messages, Byzantine validators), the protocol falls back to additional rounds for recovery. Safety is never compromised; only liveness may be temporarily affected until synchrony is restored. ## Safety and Liveness **Safety.** For any round $r$, if two honest validators commit batches $B$ and $B'$, then $B = B'$. This holds under asynchrony (no timing assumptions required). *Proof sketch.* Commitment requires a supermajority of matching commit messages. Two distinct supermajorities must overlap in at least one honest validator (since $2 \times \frac{2}{3}n > n + f$). An honest validator sends at most one commit message per round, so both supermajorities must have committed the same digest. **Liveness.** After GST, every round eventually produces a committed batch, provided at most $f$ validators are Byzantine. ## Fault Tolerance The protocol tolerates up to $f = \lfloor(n-1)/3\rfloor$ Byzantine validators. With the current validator set of 20+ independent operators, safety holds even if multiple validators are compromised or offline. This is the same fault tolerance bound as PBFT, Tendermint, and HotStuff - the fundamental limit for Byzantine agreement. ## CommittedBatch Output The output of each consensus round is a `CommittedBatch` containing: * $T_{\text{committed}}^r$ - the agreed transaction set (hashes, with bodies fetched from local cache) * $r$ - the round number * $\tau(r)$ - the batch timestamp * $\Sigma_r$ - supermajority signatures attesting to the commitment Every validator that participated in consensus holds the same `CommittedBatch`. From this point, execution is fully deterministic - no further communication is needed for validators to independently produce the same output state. # Fair Ordering Source: https://docs.bulk.trade/architecture/fair-ordering How BULK prevents transaction reordering, censorship, and MEV extraction through multi-layered fairness. ## Overview Fair ordering is one of the hardest problems in decentralized exchange design. In most systems, a single sequencer or block proposer controls transaction ordering, creating opportunities for front-running, sandwich attacks, and censorship. BULK eliminates these vectors through a multi-layered approach where no single participant controls any aspect of ordering. ```mermaid theme={null} %%{init: {'theme': 'default', 'themeVariables': {'fontSize': '16px', 'primaryColor': '#FFB457', 'primaryTextColor': '#1b1a14', 'lineColor': '#FFB457'}, 'flowchart': {'nodeSpacing': 30, 'rankSpacing': 40, 'padding': 15}}}%% flowchart TD A["Committed Batch from BULKBFT"] B["Layer 1: Quorum Admission"] C["Layer 2: Deterministic Shuffle"] D["Layer 3: Priority Queues"] E["Cancels"] F["Post-Only / ALO"] G["Regular Orders"] H["Layer 4: Price-Time Priority on Book"] A -->|"Tx in more than 2/3 validator sets"| B B -->|"Fisher-Yates seeded by batch timestamp"| C C --> D D --> E D --> F D --> G E --> H F --> H G --> H ``` ## Layer 1: Quorum-Controlled Batch Admission The transaction set in each consensus batch is not determined by any single validator. Instead, it is the **intersection of pending sets across a supermajority** of validators, computed via minisketch reconciliation. To include a transaction in a batch, the transaction must be present in the pending sets of more than 2/3 of validators. To *exclude* a transaction, an attacker would need to prevent it from reaching more than 1/3 of validators - which requires controlling a significant portion of the network. This means: * No single validator controls what transactions enter the batch * Censorship requires corrupting a supermajority, not a single sequencer * Inclusion is determined by quorum agreement, not by a proposer's choice ## Taker Speed Bump Before deterministic ordering, transactions that may take liquidity receive a uniform 25 ms delay. ALO maker-only order flow remains immediately eligible, giving liquidity providers a brief opportunity to establish or update the book before taker flow can interact with it. The same rule applies to every participant and ingress path. See [Taker Speed Bump](/architecture/taker-speed-bump) for classification and cancel behavior. ## Layer 2: Deterministic Shuffle After a batch is committed by consensus, the transactions within it are **shuffled** using the Fisher-Yates algorithm with a WyRand PRNG seeded by the batch timestamp. The batch timestamp is a **consensus output** derived from the committed batch data (see [Deterministic Clock](/architecture/timestamps)). To exploit the shuffle, an adversary would need to: 1. Know the exact final transaction set before commitment - impossible, since it depends on quorum intersection 2. Find a seed value that produces favorable ordering for their specific transaction 3. Get the quorum to agree on that seed Even if an adversary could somehow influence the seed, the impact is bounded because the transaction set is already fixed by the time the seed is committed. You cannot insert a front-running transaction after seeing the batch contents. ## Layer 3: Structural Priority Queues After the shuffle, transactions are separated into priority queues by type: 1. **Cancels** execute first 2. **Post-only (ALO) maker orders** execute second 3. **Regular orders** (market, limit, IOC) execute third This priority structure provides fairness guarantees that are **independent of ordering**: * **Traders can always cancel before being filled.** If a cancel and a matching order are in the same batch, the cancel executes first regardless of shuffle position. * **Makers always seed the book before takers cross it.** Post-only orders establish liquidity before aggressive orders can take it. * **No front-running within a batch.** Since the transaction set is fixed by consensus and the shuffle is deterministic, there is no mechanism to insert a transaction after observing the batch contents. ## Layer 4: Price-Time Priority on the Book The order book itself uses standard **price-time priority** for matching. At a given price level, orders that arrived in earlier batches are filled before orders from later batches. Within the same batch, the shuffled-then-prioritized order determines execution sequence. ## Combined Guarantee The four layers compose to provide strong fairness: | Attack Vector | Mitigation | | - | - | | Front-running (insert tx after seeing target) | Impossible - batch set is fixed by quorum before ordering | | Censorship (exclude a transaction) | Requires corrupting more than 1/3 of validators | | Ordering manipulation (reorder within batch) | Shuffle seed is consensus-derived, not controllable by any single party | | Maker disadvantage (takers cross before book is set) | Post-only orders execute before regular orders by protocol rule | | Cancel race (can't cancel before being filled) | Cancels execute before all other order types | No single layer provides complete fairness on its own. The combination of quorum-controlled admission, consensus-derived shuffle, structural priority, and price-time book matching creates a system where extracting MEV requires coordinating attacks across multiple independent mechanisms simultaneously. # Matching and Execution Source: https://docs.bulk.trade/architecture/matching How the BULK executor processes committed batches through the matching engine. ## Overview After consensus produces a `CommittedBatch`, every validator independently applies the same eligibility and execution pipeline. No further communication is needed - identical committed inputs and scheduler state produce identical outputs across every validator. ## Executor Pipeline The executor processes each committed batch through the following stages: ### 1. Receive TickProcess The consensus output is packaged as a `TickProcess` containing: * The committed transactions * The round number (slot) * The batch timestamp (used as the shuffle seed) ### 2. Taker Speed Bump Transactions are classified as complete signed packages before ordering: * Transactions without a taker-capable action, including ALO-only order flow, remain immediately eligible. * Transactions containing a market, GTC, IOC, modify, or conditional order action are held for 25 ms. * A cancel referencing an order still in the delay pool is also held. * If any action requires the delay, the entire transaction is held. Once the delay completes, held transactions join the immediately eligible transactions for the next execution batch. See [Taker Speed Bump](/architecture/taker-speed-bump) for the complete behavior. ### 3. Deterministic Shuffle and Queue Separation The `SlotQueue` receives the transactions and: 1. **Reseeds** the deterministic shuffler with the batch timestamp 2. **Shuffles** all eligible transactions in the batch 3. **Separates** transactions into priority queues: * **Config/data** actions (oracle updates, settings changes) * **Liquidation** orders (from the risk engine) * **Cancels** (cancel-one and cancel-all) * **Post-only (ALO)** maker orders * **Regular orders** (market, limit GTC, IOC) ### 4. Execution Order Actions are dequeued and executed in strict priority order: 1. Config and data updates 2. Liquidations (if any accounts breached maintenance margin) 3. Cancels 4. Post-only maker orders 5. Regular orders Within each queue, execution follows the shuffled order from step 3. ### 5. Pre-Flight Margin Check Before any order touches the book, the executor runs a `precheck_order` validation: * Verifies the account has sufficient available equity for the new position * Checks leverage limits * Validates order parameters (size, price, side) * For reduce-only orders, verifies the order would actually reduce the position Orders that fail pre-flight checks are rejected with a specific reason code (e.g., `rejectedRiskLimit`, `rejectedInvalid`). ### 6. Book Matching Orders that pass pre-flight are submitted to the matching engine, which operates as a standard central limit order book (CLOB) with price-time priority: * **Aggressive orders** (market, or limit orders that cross the spread) are matched immediately against resting liquidity at the best available prices * **Passive orders** (limit orders that don't cross) are placed on the book and wait for a counterparty * **Post-only orders** that would cross the spread are rejected (`rejectedCrossing`) instead of filling During matching, the risk engine is called back at each fill to verify that the resulting position remains within margin limits. If a fill would cause a margin breach, the remainder of the order is cancelled (`cancelledRiskLimit`). ### 7. State Updates After each fill, the executor updates: * Position sizes and entry prices * Account collateral and PnL * Order status (working, filled, partially filled) * Book state (remove filled levels, update partial fills) All updates are applied atomically per fill event. ## Deterministic Execution The entire pipeline - speed-bump classification, [deterministic shuffle](/architecture/fair-ordering#layer-2-deterministic-shuffle), queue separation, margin checks, book matching, and state updates - is deterministic. Given the same committed batches and prior state, every validator produces: * The same fills at the same prices * The same order statuses * The same position and margin state * The same book state Any validator that produces a different output is immediately detectable by comparing state hashes. This property is what makes BULK's execution verifiable without requiring re-execution by an observer - you only need to compare the output digest. ## Self-Trade Prevention When an incoming order reaches a resting order from the same account, BULK's [Self-Trade Prevention](/bulk-exchange/Self-Trade-Prevention) mechanism skips that resting order and continues searching for eligible external liquidity. The resting order remains unchanged on the book. # Architecture Overview Source: https://docs.bulk.trade/architecture/overview BULK - a specialized execution layer running natively alongside Solana. ## What is BULK BULK is an L0 - a specialized execution layer that runs sophisticated risk, order book, and matching systems natively. Each BULK validator operates a dedicated binary (`bulk-agave`) alongside the standard Solana/Agave validator on the same machine, sharing the same identity keys. Stake weight is proportional to the validator's Solana stake. Solana handles what it does best: decentralized asset custody, deposits, and withdrawals. BULK handles what requires purpose-built infrastructure: low-latency order matching, BULKBFT consensus on transaction ordering, and real-time risk management. ## Stake Inheritance BULK validators inherit their identity and stake weight from the Solana validator they run alongside. This means: * **Day-one economic security.** BULK's initial validator cohort represents \~5% of Solana's total stake, operated by 20+ independent entities. * **Aligned incentives.** Validators earn a share of exchange revenues (12.5%). Misbehavior in BULK Net results in protocol penalties (jailing), creating direct economic consequences. ## Architecture The core architecture separates pure protocol logic from I/O. Protocol crates (`bulk-consensus-proto`, `bulk-core-proto`) contain deterministic state machines - decision algorithms, type definitions, risk calculations. No network calls, no disk I/O, no Solana dependencies. I/O layers (`bulk-consensus`, `bulk-relay`, `bulk-core`) wrap these and handle network transport, database persistence, and Solana integration. This means the consensus and execution logic can be verified, simulated, and tested independently of any specific network implementation. ## Order Lifecycle ```mermaid theme={null} %%{init: {'theme': 'default', 'themeVariables': {'fontSize': '18px', 'primaryColor': '#FFB457', 'primaryTextColor': '#1b1a14', 'lineColor': '#FFB457'}, 'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'padding': 20}}}%% flowchart LR A["Trader submits order"] B["Ingress + Dedup"] C["BULKBFT Consensus"] D["Taker Speed Bump"] E["Deterministic Ordering"] F["Matching + Risk"] G["State Update"] A --> B --> C --> D --> E --> F --> G ``` ### 1. Order Ingress Traders submit signed transactions via the HTTP API or WebSocket. The ingress layer hashes each transaction for deduplication and broadcasts it to the validator set via authenticated Noise-protocol channels. ### 2. Consensus Validators exchange compact transaction sketches (minisketch) and reconcile to agree on the transaction set for each round. BULKBFT consensus produces a `CommittedBatch` - the canonical set of transactions for that round, agreed upon by a supermajority. See [BULKBFT Consensus](/architecture/consensus) for protocol details. ### 3. Taker Speed Bump Transactions containing an action that may take liquidity are held for 25 ms. Transactions without a taker-capable action, including ALO-only order flow, remain immediately eligible. When the delay completes, held transactions join the next eligible execution batch. See [Taker Speed Bump](/architecture/taker-speed-bump) for classification and cancel behavior. ### 4. Deterministic Ordering Eligible transactions pass through a [deterministic shuffle](/architecture/fair-ordering#layer-2-deterministic-shuffle) seeded by the consensus-derived batch timestamp, then separate into priority queues (cancels, then post-only, then regular orders). See [Fair Ordering](/architecture/fair-ordering) for the full design. ### 5. Execution Every validator processes the ordered batch through the identical matching engine. Pre-flight margin checks, book matching, risk callbacks, and state updates are all deterministic. Any validator that produces a different output state is immediately detectable. See [Matching and Execution](/architecture/matching) for the executor pipeline. ### 6. Settlement Deposits and withdrawals settle on Solana. # Real-Time Risk Engine Source: https://docs.bulk.trade/architecture/risk-engine Regime detection, lambda surfaces, portfolio margin, and cascade adjustment in BULK's real-time risk engine. ## Overview BULK's risk engine runs inline with the matching engine, evaluating every order and position change in real time. It is not a batch process or a background job - risk is assessed at the point of execution, before fills are confirmed. The engine is built on four interconnected systems: regime detection, lambda surfaces, portfolio margin, and cascade adjustment. ## Regime Detection BULK classifies the current market environment into one of **9 regimes** using a Hidden Markov Model. Each regime encodes direction and volatility: | Regime | Direction | Volatility | | - | - | - | | -12 | Bearish | High | | -11 | Bearish | Medium | | -10 | Bearish | Low | | 0 | Neutral | Low | | 1 | Neutral | Medium | | 2 | Neutral | High | | 10 | Bullish | Low | | 11 | Bullish | Medium | | 12 | Bullish | High | Regime classification is continuous and real-time. The engine also tracks regime duration, which feeds into the time-decay function for margin transitions. ## Lambda Surfaces Lambda ($\lambda$) is BULK's generalized risk parameter. Instead of static margin tiers, BULK uses **lambda surfaces** - continuous 3D functions that map to a maintenance margin rate: $$ \lambda_i = f(\text{leverage},\; \text{impact},\; \text{regime}) $$ Each asset has its own lambda surface. The surface is interpolated bilinearly, meaning margin requirements change continuously as position size, leverage, or market conditions change - no discrete jumps at tier boundaries. ### Time Decay When a regime change is detected, margin requirements don't jump instantaneously. They follow a time-decay curve: $$ \lambda(t) = \lambda_{\text{origin}} \cdot p^t + \lambda_{\text{end}} \cdot (1 - p^t) $$ Where $\lambda_{\text{origin}}$ is the rate at the time of the regime transition, $\lambda_{\text{end}}$ is the new regime's target, $p$ is the decay factor, and $t$ is time elapsed. This prevents unnecessary liquidation cascades from brief regime flickers. See [Margin](/bulk-exchange/Margin) for the full regime table and how time decay works in practice. ## Portfolio Margin For accounts with multiple positions, BULK computes a **correlation-adjusted effective notional** that captures diversification and hedging benefits. ### Effective Portfolio Notional For each position $i$, the signed notional is $sN_i = \text{sign}(Q_i) \cdot |Q_i| \cdot P_i$. The effective portfolio notional accounts for correlations: $$ N_{\text{eff}}^2 = \sum_i sN_i^2 + 2 \sum_{i \lt j} sN_i \cdot sN_j \cdot \rho_{ij} $$ Where $\rho_{ij}$ is the real-time correlation coefficient between assets $i$ and $j$. When positions hedge each other (correlated assets, opposing directions), the cross terms become negative and $N_{\text{eff}}$ shrinks well below the sum of individual notionals. Hedging discounts of up to 70% are achievable on correlated pairs. ### Portfolio Maintenance Margin For each position, the signed margin component is: $$ M_i = \text{sign}(Q_i) \cdot \lambda_i \cdot |Q_i| \cdot P_i $$ The correlation component uses the same correlation structure: $$ M_{\text{correlated}} = \sqrt{\max\left(0,\; \sum_i M_i^2 + 2\sum_{i \lt j} M_i \cdot M_j \cdot \rho_{ij}\right)} $$ The final maintenance margin adds a per-position reserve for liquidation cost not already represented by impact: $$ M_p = M_{\text{correlated}} + \sum_i N_i \cdot \text{Residual Reserve}_{i,\text{bps}} \cdot 10^{-4} $$ The reserve has a market-specific floor and scales with closeout impact. See [Margin](/bulk-exchange/Margin) for the complete calculation. ### Marginal Contributions For each position, the engine computes partial derivatives: $$ \frac{\partial M_p}{\partial M_i} \propto \frac{\sum_j M_j \cdot \rho_{ij}}{M_p} $$ This tells the liquidation optimizer how much each position contributes to overall portfolio risk. Candidate reductions also include their change in liquidation reserve, so correlation benefit and closeout cost both affect selection. See [Liquidations](/bulk-exchange/Liquidations) for the full optimizer algorithm. ## Cascade Adjustment The system incorporates **liquidation impact feedback** into margin and equity. It maintains size-indexed curves for: * Current cost of sweeping the closing side of the book * Additional cost if the resulting move triggers nearby liquidation levels Impact-adjusted PnL includes the full current sweep cost plus a configured fraction of positive incremental cascade cost. If a current sweep observation is unavailable, the full cascade estimate is used. The remaining all-in closeout reserve is added to maintenance margin. This prevents a thin or concentrated market from appearing safe merely because mark-price PnL has not yet realized its execution cost. ## Background Risk Recomputation In addition to inline risk checks at execution time, BULK runs background risk recomputation cycles that: * Update portfolio margins as mark prices change (even without new orders) * Detect accounts approaching maintenance margin thresholds * Trigger liquidation when impact-adjusted closeout equity falls below $M_p$ while mark-price position PnL is negative This ensures that risk is managed continuously, not just at the moment of order submission. See [Price Indices](/bulk-exchange/Price-Indices) for how the mark price is computed. ## Comparison to Existing Systems | Feature | Static Tiers (most DEXs) | BULK Risk Engine | CME SPAN | | - | - | - | - | | Margin model | Fixed per-notional brackets | Continuous lambda surfaces | Scenario-based (16 scenarios) | | Correlation | None | Full real-time matrix | Explicit inter-commodity spreads | | Market regime | Ignored | 9 regimes, real-time HMM | Implied via stress scenarios | | Margin transitions | Instant jumps | Smooth time-decay | Batch recomputation | | Liquidation | Close biggest loser | Impact-ratio optimizer | Clearing house default management | | Computation | Per-position | Portfolio-level | Portfolio-level | | Latency | N/A (batch) | Inline with matching | Batch (typically overnight/intraday) | See [Margin](/bulk-exchange/Margin), [Liquidations](/bulk-exchange/Liquidations), and [Portfolio Margining](/bulk-exchange/portfolio-margining) for detailed specifications. # Security Practices Source: https://docs.bulk.trade/architecture/security How BULK secures user funds, network consensus, and on-chain settlement. ## Self-Custodial Architecture BULK is self-custodial. All assets are held in a Solana program. Deposits and withdrawals natively settle on Solana. The BULK network handles the order book and risk engine, while the on-chain program is the custodian. Each user's funds are held in a per-user PDA (a program-derived account that is self-custodial and can only be accessed by the user). No operator, validator, or third party can move funds without the user initiating a transaction. Deposits and withdrawals are special transactions on the BULK network: * **Deposits**: A user sends tokens to the Solana program. A plugin forwards the confirmed event to the BULK network. The user's balance is credited only after Solana has finalized the transaction (approximately 12 seconds). * **Withdrawals**: A user requests a withdrawal through the BULK network. The request passes through consensus, all validators agree on the amount and recipient, and the validator set produces a FROST threshold signature to authorize the on-chain settlement. No single validator can unilaterally release funds. ## Consensus-Secured Settlement Deposits and withdrawals are special transactions on the BULK network that must pass through BULKBFT consensus before any state change occurs. **Deposit confirmation** - When a user deposits to the Solana program, a plugin transfers the state message to the BULK network. A deposit is only confirmed after Solana has finalized the slot. Until finalization, the balance is not available. **Withdrawal consensus** - When a user requests a withdrawal, the network verifies the account has sufficient available balance (accounting for open positions and margin requirements). The withdrawal is included in a consensus block voted on by the validators. Only after commit do the validators produce valid threshold signatures needed to execute the on-chain instruction. **Withdrawal safety** - Before any tokens leave an account: $$ \text{available} = \text{balance} - \text{required margin} - \text{unrealized losses} $$ If the withdrawal amount exceeds available balance, the request is rejected. ```mermaid theme={null} %%{init: {'theme': 'default', 'themeVariables': {'primaryColor': '#FFB457', 'primaryTextColor': '#1b1a14', 'lineColor': '#555', 'fontSize': '13px'}}}%% flowchart TD A[User submits deposit on Solana] --> B[Solana finalizes transaction] B --> C[Plugin forwards event to BULK network] C --> D[BULKBFT consensus confirms deposit] D --> E[Balance credited] F[User requests withdrawal] --> G[BULKBFT consensus block] G --> H{Sufficient available balance?} H -- Yes --> I[Validators produce FROST threshold signature] I --> J[On-chain withdrawal executed on Solana] H -- No --> K[Withdrawal rejected] ``` ## Threshold Signatures (FROST) Withdrawals from the Solana program require a threshold signature using FROST (Flexible Round-Optimized Schnorr Threshold signatures). The validator set collectively holds a group signing key - no single validator possesses the full private key. * The FROST group key is registered in the on-chain program state during initialization * To sign a withdrawal, a threshold of validators must participate in the signing ceremony * If a validator goes offline, the remaining validators can still produce valid signatures as long as the threshold is met * A compromised or malicious validator cannot steal funds - an attacker would need to compromise a threshold number of validators simultaneously ## On-Chain Program This program essentially acts as a bridge for deposits and withdrawals. All margining, order matching, liquidation, and other critical lifecycle operations are handled by the BULK network's deterministic execution layer - they do not depend on this on-chain program. ## Transaction Authentication Every transaction submitted to the BULK network is cryptographically signed using Ed25519. Before a transaction enters the execution pipeline, it passes through a multi-layer authentication process: **Signature verification** - At the network ingress layer, each transaction's Ed25519 signature is verified against the declared signer. Transactions with invalid signatures are immediately rejected and never reach consensus. **Authorization check** - Beyond signature validity, the system checks whether the signer is authorized to act on the target account: * The account owner is always authorized * Registered agent wallets (keychains) are authorized for the owner's account * A parent account's owner or agents are authorized for its sub-accounts Unauthorized signers are rejected even if their Ed25519 signature is valid. ## Validator-to-Validator Communication All inter-validator communication is secured by WireAuth - authenticated Noise protocol channels that provide encryption and identity binding between every pair of validators. Each validator performs a Noise handshake with every peer at startup, establishing encrypted sessions. Messages are authenticated such that a validator cannot forge messages from another peer. # Taker Speed Bump Source: https://docs.bulk.trade/architecture/taker-speed-bump How BULK gives maker liquidity a 25 ms window before taker-capable transactions become eligible for execution. ## Overview BULK applies a **25 millisecond speed bump** to transactions that may take liquidity. Transactions containing only provably maker-only orders can proceed immediately, while taker-capable transactions wait in the delay pool before becoming eligible for execution. The speed bump runs after consensus acceptance and before [deterministic shuffle](/architecture/fair-ordering#layer-2-deterministic-shuffle). It changes when a transaction becomes eligible for execution, not how the transaction is submitted. ## Temporary Maker Protection The speed bump is a temporary launch mechanism, limited to the first **90–120 days** while market makers become comfortable quoting consistently on BULK. It provides a simple, predictable protection window while liquidity and trading behavior mature. After this transition, BULK will introduce a novel protective order type that provides more targeted protection without delaying all taker flow. The design direction is an order that can cancel or constrain its resting exposure when deterministic short-horizon flow signals indicate elevated adverse-selection risk. ```mermaid theme={null} %%{init: {'theme': 'default', 'themeVariables': {'fontSize': '16px', 'primaryColor': '#FFB457', 'primaryTextColor': '#1b1a14', 'lineColor': '#FFB457'}, 'flowchart': {'nodeSpacing': 35, 'rankSpacing': 45, 'padding': 15}}}%% flowchart TD A["Consensus-accepted transactions"] B{"Transaction classification"} C["Immediate
maker-only transactions"] D["25 ms delay pool
taker-capable transactions"] E["Eligible execution batch"] F["Deterministic shuffle"] G["Structural priority queues"] H["Matching and execution"] A --> B B -->|"Maker-only"| C B -->|"Taker-capable"| D C --> E D -->|"Delay completed"| E E --> F --> G --> H ``` ## What Is Held Classification applies to the complete signed transaction. If any action in the transaction is taker-capable, the entire transaction receives the speed bump. | Action in the transaction | Scheduling behavior | | - | - | | ALO limit order | Immediate | | Market order | Held for 25 ms | | GTC or IOC limit order | Held for 25 ms | | Modify order | Held for 25 ms | | Stop or take-profit | Held for 25 ms | | Range or trigger | Held for 25 ms | | Trailing order | Held for 25 ms | | On-fill action | Held for 25 ms | | Cancel referencing an order ID still in the delay pool | Held for 25 ms | | Cancel referencing an order ID not in the delay pool | Immediate | | Cancel-all | Immediate | | Other non-order actions | Immediate | Only ALO guarantees maker behavior before execution. A GTC order is held even when it would currently rest, because the classification does not depend on mutable order-book state. ## Mixed Transactions A transaction is the scheduling boundary. If an ALO order, transfer, or cancel is packaged with a taker-capable action, every action in that transaction is held together. The speed bump does not split, rewrite, or merge signed transactions. This preserves signature integrity and action ordering, but does not make execution all-or-none. Individual actions may still be rejected, partially filled, or cancelled under their normal execution rules. ## How the Delay Pool Works The delay pool holds complete signed transactions until they become eligible. When the 25 ms window has passed, a transaction is released into the first available execution batch together with newly accepted maker-only transactions. ```mermaid theme={null} %%{init: {'theme': 'default', 'themeVariables': {'fontSize': '15px', 'primaryColor': '#FFB457', 'primaryTextColor': '#1b1a14', 'lineColor': '#FFB457'}, 'sequence': {'actorMargin': 45, 'messageMargin': 35}}}%% sequenceDiagram participant C as Consensus participant P as Delay Pool participant O as Deterministic Ordering participant E as Executor C->>O: Maker-only transaction C->>P: Taker-capable transaction O->>E: Maker becomes immediately eligible P-->>P: Hold for 25 ms P->>O: Release into first eligible batch O->>E: Execute after deterministic ordering ``` The 25 ms value is a minimum eligibility delay rather than an exact execution-time promise. Execution occurs in the first available batch after the delay, so normal consensus, batching, and processing time may make the observed interval slightly longer. ## Cancels During the Delay ### Cancel While an Order Is Still Delayed If a cancel references an order ID still in the delay pool, the cancel transaction also enters the delay pool. It does not remove or modify the original placement transaction. The placement may therefore be placed, filled, rejected, or partially filled before the cancel becomes eligible. When released, the cancel applies to whatever live order state remains. ### Cancel at the Release Boundary A cancel arriving as its placement leaves the delay pool may become eligible in the same execution batch. Normal cancel-first priority still applies. If the placement is not live when the cancel executes, the cancel can be rejected and the placement can proceed afterward. ### Cancel-All Cancel-all remains immediate and applies to orders already live in the executor. It does not remove transactions waiting in the delay pool. ## Deterministic Ordering Transactions released from the delay pool join the maker-only transactions eligible for that execution batch. The combined batch then passes through BULK's [deterministic shuffle](/architecture/fair-ordering#layer-2-deterministic-shuffle) and existing structural priority queues before matching. The speed bump does not create a client-selected fast lane. Every account, API connection, and ingress path receives the same classification and ordering rules. ## API Compatibility The speed bump requires no trading API changes: * action payloads and signatures are unchanged; * nonces, transaction IDs, and order IDs are unchanged; and * clients do not opt in or select an execution priority. The lifecycle distinction is operational: a transaction can be **accepted by consensus** before its actions become **eligible for execution**. # Deterministic Clock Source: https://docs.bulk.trade/architecture/timestamps Anti-entropy maintenance on the BULK Network. ## Overview BULK requires every validator to independently derive the **same timestamp** for each consensus round, without a central clock. This timestamp is used as the seed for the deterministic shuffle and is embedded in the committed batch. The system achieves this through a formula-based approach with a Phase-Locked Loop (PLL) correction mechanism. ## The Timestamp Formula Each batch timestamp is computed deterministically: $$ T_{\text{batch}} = T_{\text{anchor}} + (R - R_{\text{anchor}}) \times \Delta t $$ Where $T_{\text{anchor}}$ is a known reference timestamp, $R_{\text{anchor}}$ is the round number at the anchor point, $R$ is the current round, and $\Delta t$ is the nanoseconds per consensus round (the tick rate). Given the same anchor parameters and rate, every validator computes the same timestamp for any given round. No communication is needed for timestamp agreement - it falls directly out of the consensus round number. ## Beacon PLL (Phase-Locked Loop) Over time, the formula's rate will drift from real wall-clock time due to variance in consensus round duration. The PLL corrects this using **beacons** - wall-clock timestamps embedded in committed transactions. ### How Beacons Work 1. **Beacon collection.** Committed transactions include wall-clock timestamps from the validators that processed them. 2. **Median extraction.** For each round with beacons, the system takes the **median** of all beacon timestamps. The median is robust to outliers and Byzantine actors - even if some validators report incorrect times, the median reflects the honest majority. 3. **Drift computation.** The system compares the median beacon time against the formula's predicted time for that round, computing a drift value. 4. **Rate correction.** If drift accumulates beyond a threshold, the PLL adjusts $\Delta t$ to bring the formula back into alignment with real time. The anchor point is also updated to prevent accumulated error. ### Byzantine Resistance The median-based approach is inherently resistant to Byzantine clocks. The system tolerates up to $\lfloor(n-1)/2\rfloor$ faulty clocks when computing the median. Rogue validators reporting wildly incorrect times are neutralized without any explicit detection mechanism - the median naturally converges on the honest majority. ### Drift and Phase Correction The PLL operates in two modes: * **Rate correction** adjusts $\Delta t$ when consensus rounds consistently take longer or shorter than expected. This handles systematic drift (e.g., network conditions changing average round time). * **Phase correction** adjusts the anchor point when the formula has accumulated a large offset from wall-clock time. This handles step changes (e.g., after a period of network instability). Both corrections are applied deterministically based on committed data, so every validator applies the same correction at the same round. # Protocol Native Asset Transfer Source: https://docs.bulk.trade/architecture/transfers Internal and external token transfers between accounts and sub-accounts - all executed natively inside the BULK protocol. Token transfers on BULK are protocol-native operations. You can transfer any supported token (USDC, USDT, and others as listed) between any accounts on the network. > [!NOTE] > > All transfers are gasless and carry zero fees - there is no cost to move tokens between accounts. For the full request/response shape, response statuses, and signing rules, see [Transfer (Signed)](/api-reference/transfer). ## Transfer Types BULK supports two kinds of transfers, distinguished by scope and recipient handling. ### Internal Transfer Moves tokens between accounts that share the same owner. The signer must be the master account, and both the source and destination must be within the signer's account tree (the master itself or any of its sub-accounts). Typical flows: * Master to sub-account (fund a sub-account) * Sub-account to master (sweep profits back) * Sub-account to sub-account (rebalance between sub-accounts) Internal transfers do not have a minimum amount requirement. ### External Transfer Moves tokens from one account to any other account on the network, regardless of ownership. This is how you send funds to another trader or move tokens to a completely separate wallet. External transfers have a minimum amount threshold to prevent dust spam. If the destination account does not exist, the protocol auto-creates it as a new master account - but only if the destination public key is on-curve (a valid Solana wallet). Off-curve addresses that do not already exist as protocol accounts are rejected. ## Transfer Action A transfer is submitted as a single `transfer` action with the following fields: | Field | Description | | - | - | | `k` | `"internal"` (default) or `"external"` | | `from` | Source account public key | | `to` | Destination account public key. For per-instrument [isolated-account](/bulk-exchange/isolated-margin) top-ups, set this to an `isoPubkey` surfaced by [`POST /account`](/api-reference/getAccount), its [history queries](/api-reference/getAccount#history-queries), or the [account stream](/api-reference/ws-account) | | `marginSymbol` | Token to transfer (e.g. `USDC`, `USDT`) | | `marginAmount` | Amount to transfer | The transaction signer is the authorizing account. For internal transfers, this must be the master account that owns both `from` and `to`, or any [agent wallet](/api-reference/manageAgentWallet) registered on it. For external transfers, this is the account that owns the source. See [Transaction Signing](/api-reference/signing) for the canonical wincode message. For full request/response shape and signing details, see [Transfer (Signed)](/api-reference/transfer). ## Withdrawal Safety Before executing a transfer, the protocol checks whether the source account can safely release the requested tokens. The withdrawable amount is bounded by: $$ \text{max\_withdraw} = \min(\text{equity} - 1.05 \times MM, \text{margin\_pnl}) $$ Where: * **equity** = position PnL + margin PnL (total account value) * **MM** = maintenance margin (current risk requirement) * The 1.05 multiplier provides a 5% safety buffer above maintenance If the requested amount exceeds the withdrawable maximum, the transfer is rejected. This prevents transfers from pushing an account into liquidation territory. ## Sub-Accounts Sub-accounts are the primary mechanism for internal transfers. Each master can have up to 64 sub-accounts, and tokens can be moved freely between them. See the [Sub-Accounts](/bulk-exchange/sub-accounts) page for full details on creating, managing, and removing sub-accounts. ## Error Handling | Error | Cause | | - | - | | `no margin symbol` | The specified token symbol does not exist | | `unknown margin symbol` | The symbol exists but is not a recognized security | | `below minimum` | External transfer amount is below the minimum threshold | | `off-curve and does not exist` | External transfer to an off-curve address that is not a known account | | `not permissioned for internal transfer` | Source or destination is not in the signer's account tree | | `source account not found` | The `from` account does not exist | All error responses include the specific reason for rejection. Failed transfers do not modify any account state. # BIP-1: Deployer-Owned Perpetual Contracts Source: https://docs.bulk.trade/bips/bip-1 Deploy various markets on BULK. > [!TIP] > > **Status: In development.** BIP-1 is currently being built. ## Overview Most industry-standard perpetual exchanges margin each market independently. A new market can launch with a static oracle and maintenance-margin configuration because its risk is not calibrated against the rest of a trader's portfolio. BULK works differently. It margins the trader's entire portfolio using the variance of the signed position notionals and a live correlation matrix. A long position in one asset can offset a short position in a correlated asset, reducing the capital required for the combined portfolio. Depending on the hedge, this can produce margin reductions of up to 70%. BULK also uses a maintenance-margin surface calibrated across leverage, market regime, and position side. A fixed per-market MMR is often too conservative in calm markets and too permissive during tail events. BULK's regime-aware model adjusts the requirement as market conditions change. This is why a standard deployer model cannot map directly to BULK. A new market does not yet have the tick-level history, cross-market correlations, nine-regime calibration, or session-gap data required to join the [portfolio-margin system](/bulk-exchange/Margin). BIP-1 gives the market time to produce that evidence before its risk is netted against other positions. Phase 1 allows rapid experimentation. Phase 2 enables robust risk management and greater capital efficiency. ## Deployer-Owned Market Lifecycle ```mermaid theme={null} %%{init: {'theme': 'default', 'themeVariables': {'fontSize': '16px', 'primaryColor': '#FFB457', 'primaryTextColor': '#1b1a14', 'lineColor': '#FFB457'}, 'flowchart': {'nodeSpacing': 35, 'rankSpacing': 45, 'padding': 15}}}%% flowchart TD A["Deployer submits
ticker request"] B["BULK configures
base-level MMR"] C["Phase 1
isolated-only market"] D{"PMF reached?
Volume + OI growth"} E["Phase 2
maturation"] F["Nine-regime calibration
correlations + native oracle"] G["Stake 2M USDC bond
at the network"] H["Full portfolio margining
up to 70% margin reduction"] A --> B --> C --> D D -->|"Not yet"| C D -->|"Yes"| E --> F --> G --> H ``` ### Phase 1: Rapid Experimentation Phase 1 launches the market in isolated-only mode so the deployer can find product-market fit without placing uncalibrated risk inside the wider portfolio. A deployer may launch up to **30 active Phase 1 tickers** with **no deployment fee or Dutch auction**. The deployer selects each symbol using its prefix and cannot deploy an asset already listed by the protocol. The deployer pushes the oracle or index price used to keep funding tethered to the underlying market. BULK performs vanilla asset-risk calibration and configures a base-level MMR before launch. The deployer is responsible for maintaining liquidity. BULK does not offer any private MM arrangements. Phase 1 markets do not receive a liquidation backstop. Validators may vote to delist a market, and a deployer that manipulates its index feed or prices a contract to harm users can be banned. ### Phase 2: Maturation Phase 2 begins when the market reaches product-market fit: growth in volume and open interest, supported by the tick-level history needed to calibrate the asset across all nine market regimes. BULK and the deployer then recalibrate the market, allocate correlations against existing markets, and keep its risk parameters current. The protocol also provides the oracle price natively, so a deployer-pushed oracle is no longer required. The final step in maturation, before the market converts to the full portfolio-margin system, is a **2 million USDC bond** staked at the network. The protocol uses this bond to backstop liquidations. The bond is forfeited if validators delist the market for a policy violation. Otherwise, it is returned after five years or when the deployer chooses to settle the market. The bond requirement may be updated for future deployers as the protocol evolves. After maturation, the market enters full portfolio margining. Regime-aware models and wider correlation discounts can reduce margin requirements by up to 70%, providing robust risk management and greater capital efficiency for hedged portfolios. ## Deployer Economics The deployer may add a variable fee of up to 100% of the applicable [base protocol fee](/bulk-exchange/fees), making the maximum total fee twice the base fee. For example, a 3.5 bps base taker fee with a 50% deployer add-on produces a 1.75 bps deployer fee and a 5.25 bps total fee. At the 100% maximum, the same base fee produces a 3.5 bps deployer fee and a 7 bps total fee. The deployer fee accrues to the deployer's wallet on every fill and is distributed every 14 days. The same fee model continues through Phase 2. ## Become a Deployer If you are interested in becoming a deployer, [**reach out**](https://form.typeform.com/to/VIYMwIt4). ## Related Documentation > [card] [Introduction to BULK](/) > > Learn how BULK combines execution, risk, and settlement. > [card] [Portfolio Margin](/bulk-exchange/Margin) > > Understand correlation-aware margining and regime-calibrated risk. > [card] [Builder Codes](/bulk-exchange/builder-codes) > > Build custom trading experiences and attribute order flow. > [card] [API Documentation](/api-reference/introduction) > > Integrate market data, account queries, and trading APIs. # Auto-Deleveraging Source: https://docs.bulk.trade/bulk-exchange/ADL Last-resort shortfall and underfill handling on BULK. Auto-Deleveraging (ADL) is the final deterministic fallback when a liquidation creates bad debt or when its planned position reduction cannot be fully accepted within protocol capacity. ## When ADL Activates ADL handles two separate conditions: 1. **Shortfall:** realized liquidation losses exceed the account's remaining collateral. 2. **Underfill:** some planned liquidation quantity cannot be accepted within protocol capacity. These paths are separate. Underfill can activate ADL even when the liquidated account has no collateral shortfall. ## Ranking Eligible profitable accounts on the required side of the market are ranked using profit and leverage: $$ \text{score}_i = \max\left(\text{PnL}_i,\; \epsilon\right)^w \cdot \text{leverage}_i^{1-w} $$ $w$ is the configured profit-versus-leverage weight. Higher-scored accounts receive priority. Accounts without a position in the required direction or without positive PnL receive no allocation. ## Allocation ADL quantity is distributed pro-rata by score and rounded deterministically in instrument tick space. Allocations are capped by each position's remaining size, so ADL cannot reverse a position through zero. Very small allocations are concentrated on the highest-ranked eligible accounts rather than creating dust across a large candidate set. ## Execution Price The execution price depends on why ADL was required: * **Underfill ADL** reduces eligible positions at the current mark price. * **Shortfall ADL** closes selected profitable positions at their entry price while the corresponding offsetting position reductions are recorded at mark. The realized difference covers the shortfall. Every ADL event reports its executed price, size, side, and reason. ## Risk Vault For shortfall, a market-specific configured share may be assigned directly to the protocol risk vault. ADL covers the remaining eligible amount. If candidate capacity is insufficient, the unresolved shortfall is absorbed by the risk vault. For underfill, any quantity that cannot be allocated across eligible accounts returns to protected execution rather than being silently dropped. ## Safety Properties * Liquidated accounts and protocol-owned accounts are excluded from the ADL candidate set. * Candidate ordering and rounding are deterministic across validators. * Allocations cannot cross a position through zero. * Shortfall and underfill are reported separately. * Requested, executed, residual quantity, participant count, and average price are summarized for each ADL operation. ## Full Safety Stack 1. **Impact-aware margin** reserves for expected closeout cost before bad debt develops. 2. **Portfolio optimizer** selects the reductions that restore margin most efficiently. 3. **Protected execution** uses available market liquidity within deterministic fair- and oracle-anchored price limits. 4. **Risk vault and ADL** resolve shortfall or unprocessed quantity. # Contract Specifications Source: https://docs.bulk.trade/bulk-exchange/Contract-Specifications Perpetual contract parameters on BULK Exchange. ## Contract Type USDC-margined perpetual contracts. No expiration. Funding payments every hour to anchor price to spot. ## Parameters | Parameter | Value | | - | - | | **Settlement** | USDC | | **Contract size** | Quantity in base asset. Positive = long, negative = short. Scaled by 10^4. | | **Max leverage** | Up to 100x (per instrument, check [`/exchangeInfo`](/api-reference/getExchangeInfo)) | | **Margin mode** | Cross margin (default). Use sub-accounts for isolated risk. | | **Margin model** | Portfolio margin with correlation-adjusted effective notional. See [Margin](/bulk-exchange/Margin). | | **Maintenance margin** | Dynamic lambda surfaces plus a size-dependent liquidation reserve, varying by leverage, closeout impact, and market regime. No static tiers. | | **Mark price** | Median of: premium-adjusted oracle, order book median, smoothed local price. See [Price Indices](/bulk-exchange/Price-Indices). | | **Funding** | Hourly. See [Funding](/bulk-exchange/funding). | | **Liquidation** | Impact-aware portfolio reduction with reserve-adjusted, protected execution. See [Liquidations](/bulk-exchange/Liquidations). | | **ADL** | Last-resort handling for collateral shortfall or planned liquidation quantity not accepted within protocol capacity. See [Auto-Deleveraging](/bulk-exchange/ADL). | ## Available Markets Markets and their specific parameters (tick size, lot size, max leverage) are available via the [`/exchangeInfo`](/api-reference/getExchangeInfo) endpoint. ## Fees See [Fees](/bulk-exchange/fees) for the full fee and rebate schedule. # Liquidations Source: https://docs.bulk.trade/bulk-exchange/Liquidations How BULK prices closeout risk and selectively restores account margin. BULK liquidations are portfolio-aware. The system prices the cost of closing the account, cancels its open orders, and reduces the positions that restore margin health most efficiently. It does not automatically flatten the largest position or submit the entire portfolio as one unrestricted market order. ## Trigger Condition Liquidation is triggered when both conditions are met: $$ E_{\text{close}} \lt M_p \quad \text{and} \quad \text{PnL}_{\text{mark}} \lt 0 $$ Where $M_p$ is reserve-adjusted portfolio maintenance margin and closeout equity is: $$ E_{\text{close}} = C + \text{PnL}_{\text{impacted}} $$ $C$ is collateral. $\text{PnL}_{\text{impacted}}$ values each position at an adverse estimated closeout price rather than assuming the full position can exit at the mark. ### Closeout Impact For each position, BULK measures the current cost of sweeping its closing side of the book and the additional impact of nearby liquidation cascades: $$ I_{\text{close}} = I_{\text{sweep}} + c \cdot \max\left(I_{\text{cascade}} - I_{\text{sweep}},\; 0\right) $$ $c$ is the configured cascade factor. If a current sweep observation is unavailable, the full cascade-impact estimate is used. Thin books, larger positions, and concentrated liquidation levels therefore reduce closeout equity before an account reaches bad debt. ## Reserve-Adjusted Maintenance Margin Maintenance margin also reserves for liquidation cost not already represented by impacted PnL. This calculation uses the full cascade-impact estimate: $$ I_{\text{all-in}} = \max\left(I_{\text{cascade}} \cdot (1 + r),\; R\right) $$ Where $R$ is the market-specific reserve floor and $r$ is its impact reserve factor. Only the residual $I_{\text{all-in}} - I_{\text{cascade}}$ is added to maintenance margin: $$ M_p = M_{\text{correlated}} + \sum_i N_i \cdot \left(I_{\text{all-in},i} - I_{\text{cascade},i}\right) \cdot 10^{-4} $$ This is a deterministic risk reserve, not a separate liquidation fee. ## Liquidation Lifecycle ### Step 1: Cancel Open Orders All resting orders belonging to the account are cancelled before its positions are changed. This prevents open orders from increasing exposure during liquidation. ### Step 2: Compute the Recovery Target The optimizer computes how much maintenance margin must be removed: $$ \text{target} = \max\left(0,\; E_{\text{close}} \cdot (1 - \text{buffer})\right) $$ $$ \text{gap} = M_p - \text{target} $$ The buffer leaves the account below its available closeout equity after the planned reduction. ### Step 3: Size Candidate Reductions The optimizer tests incremental reductions for every non-zero position. The step size increases with the severity of the margin gap: | Condition | Reduction Fraction | | - | -: | | Gap above 30% of $M_p$ | 25% of original size | | Gap above 10% of $M_p$ | 10% of original size | | Gap at or below 10% of $M_p$ | 5% of original size | Each reduction is capped by the position's remaining size. ### Step 4: Measure Portfolio Change For every candidate, BULK recomputes: * The position's lambda at its hypothetical smaller size * The change in correlation-adjusted portfolio margin * The change in its size-dependent liquidation reserve * The expected cost of executing the reduction through current depth Hedging and correlation benefit are evaluated as part of the whole portfolio rather than treating each leg independently. ### Step 5: Rank by Efficiency Candidates are ranked by signed maintenance-margin change per dollar of expected execution cost: $$ \text{Impact Ratio}_i = \frac{-\Delta M_{p,i}}{\text{Expected Execution Cost}_i} $$ Greater estimated margin relief ranks first. The optimizer applies the highest-ranked reduction, recomputes the account, and repeats. Near-zero margin changes are skipped. ### Step 6: Stop When Margin Is Restored The optimizer runs for up to 100 iterations. If selective reductions cannot restore the target within that limit, it falls back to closing all remaining positions. ## Protected Execution The account's selected position reduction is applied during the liquidation tick at a reserve-adjusted price. Protected market execution begins after that state change; it does not delay or condition the account's liquidation. From the next executor tick, BULK may use available opposing liquidity within deterministic price limits. More aggressive execution is allowed only after an execution window has completed with a remaining shortfall, and only up to the largest quantity supported by calibrated depth. Every aggressive order has a limit independently anchored to both fair price and oracle price. If depth or either reference is unavailable or outside the configured limits, execution is postponed rather than crossing an unbounded price. Protected execution applies to quantity already accepted by the protocol. Price or depth constraints postpone that execution; they do not create a new ADL underfill. ## Shortfall and ADL ADL is evaluated for two distinct conditions: 1. **Shortfall:** liquidation losses exceed the account's collateral. 2. **Underfill:** part of the planned reduction cannot be accepted within protocol capacity. The protocol risk vault covers its configured share of shortfall and any residual that ADL cannot allocate. Underfill ADL reduces eligible opposing positions; any remaining quantity returns to protected execution. See [Auto-Deleveraging](/bulk-exchange/ADL) for ranking and allocation. ## Full Lifecycle ```mermaid theme={null} flowchart TD A["Impact-aware margin breach"] --> B["Cancel account orders"] B --> C["Optimize portfolio reduction"] C --> D["Reserve-adjusted reduction within protocol capacity"] D --> F["Price-protected execution of accepted quantity"] D --> E{"Shortfall or underfill?"} E -->|No| J["Margin restored"] E -->|Shortfall| G["ADL and risk-vault allocation"] E -->|Underfill| H["Underfill ADL"] H --> I{"Residual quantity?"} I -->|No| J["Margin restored"] I -->|Yes| F G --> J F --> J ``` # Margin Source: https://docs.bulk.trade/bulk-exchange/Margin Portfolio margin, correlation-adjusted risk, and dynamic lambda surfaces on BULK Exchange. ## Portfolio Margin BULK runs a portfolio margin system. Instead of computing margin for each position independently and summing them up, BULK evaluates the risk of your entire portfolio as a single unit, accounting for correlations between assets and the hedging benefits of opposing positions. This is the same philosophy behind CME SPAN, the gold standard for institutional derivatives margining. SPAN evaluates portfolio risk across scenarios. BULK takes the concept further: instead of a fixed set of 16 scenarios run in batch, BULK uses continuous lambda surfaces that adapt in real time to leverage, position size, market regime, and cross-asset correlations. The result is up to 70% margin efficiency on hedged portfolios. A long BTC / short ETH position requires far less margin than the sum of the two individual margins, because the system understands these assets are correlated and the short hedges the long. ## How It Works ### Step 1: Effective Portfolio Notional For each position $i$ in your portfolio, the system computes a signed notional: $$ sN_i = \text{sign}(Q_i) \cdot |Q_i| \cdot P_i $$ Where $Q_i$ is the signed position size (positive for long, negative for short) and $P_i$ is the mark price. The effective portfolio notional accounts for correlations between all position pairs: $$ N_{\text{eff}}^2 = \sum_i sN_i^2 + 2 \sum_{i \lt j} sN_i \cdot sN_j \cdot \rho_{ij} $$ Where $\rho_{ij}$ is the real-time correlation coefficient between assets $i$ and $j$, ranging from $-1$ (perfect negative correlation) to $+1$ (perfect positive correlation). Then: $$ N_{\text{eff}} = \sqrt{\max(0,\; N_{\text{eff}}^2)} $$ When positions hedge each other (correlated assets, opposing directions), the cross terms become negative and $N_{\text{eff}}$ shrinks well below the sum of individual notionals. ### Step 2: Portfolio Leverage $$ L_{\text{portfolio}} = \frac{N_{\text{eff}}}{C} $$ Where $C$ is your total collateral (USDC). This portfolio-level leverage, not per-position leverage, drives the lambda lookup. ### Step 3: Per-Position Lambda from Risk Surfaces Each asset has a lambda surface, a continuous 3D function: $$ \lambda_i = f(\text{leverage},\; \text{impact},\; \text{regime}) $$ * **Leverage** - the portfolio leverage $L_{\text{portfolio}}$ * **Impact** - estimated market impact of liquidating this position, in basis points, derived from order book depth * **Regime** - the current market regime (see below) The surface is interpolated bilinearly across grid knot points, producing a smooth maintenance margin rate with no discrete jumps at tier boundaries. #### Cascade Adjustment The executor builds size-indexed impact curves from current book depth and nearby liquidation levels. Each position queries the curve for its closing side and size, and the system iterates up to two rounds when recalibrating lambda. This prevents a position from appearing well-margined when closing it could move the book far enough to trigger additional liquidations. Closeout PnL uses both current sweep cost and a configured fraction of any larger cascade estimate: $$ I_{\text{close}} = I_{\text{sweep}} + c \cdot \max\left(I_{\text{cascade}} - I_{\text{sweep}},\; 0\right) $$ If the current sweep observation is unavailable, the full cascade-impact estimate is used. ### Step 4: Portfolio Maintenance Margin For each position, the signed margin component is: $$ M_i = \text{sign}(Q_i) \cdot \lambda_i \cdot N_i $$ Where $N_i = |Q_i| \cdot P_i$ is the unsigned notional. The correlation component of portfolio maintenance margin is: $$ M_{\text{correlated}} = \sqrt{\max\left(0,\; \sum_i M_i^2 + 2\sum_{i \lt j} M_i \cdot M_j \cdot \rho_{ij}\right)} $$ This captures the combined portfolio risk rather than summing independent position margins. ### Step 5: Liquidation Reserve Each market has a minimum reserve floor $R_i$ and impact reserve factor $r_i$. This reserve calculation uses the full cascade-impact estimate: $$ I_{\text{all-in},i} = \max\left(I_{\text{cascade},i} \cdot (1 + r_i),\; R_i\right) $$ Only the part not already represented by impact is added to maintenance margin: $$ M_p = M_{\text{correlated}} + \sum_i N_i \cdot \left(I_{\text{all-in},i} - I_{\text{cascade},i}\right) \cdot 10^{-4} $$ The reserve rises with position size and closeout impact. It is part of deterministic risk pricing, not a separate liquidation fee. ### Step 6: Marginal Contributions For each position, the system computes partial derivatives: $$ \frac{\partial M_p}{\partial M_i} \propto \frac{\sum_j M_j \cdot \rho_{ij}}{M_p} $$ This tells the liquidation optimizer how much each position contributes to overall portfolio risk. Candidate reductions also include the change in liquidation reserve, so selection accounts for both correlation benefit and closeout cost. ## Regime Detection BULK classifies the current market environment into one of 9 regimes using a Hidden Markov Model. Each regime encodes direction and volatility: | Regime | Direction | Volatility | | - | - | - | | -12 | Bearish | High | | -11 | Bearish | Medium | | -10 | Bearish | Low | | 0 | Neutral | Low | | 1 | Neutral | Medium | | 2 | Neutral | High | | 10 | Bullish | Low | | 11 | Bullish | Medium | | 12 | Bullish | High | When the regime shifts, for example from neutral-low-vol (0) to bearish-high-vol (-12), lambda values increase across the surface, raising margin requirements in real time before losses materialize. ### Time Decay Between Regimes Margin requirements don't jump instantaneously on a regime change. They follow a decay curve: $$ \lambda(t) = \lambda_{\text{origin}} \cdot p^t + \lambda_{\text{end}} \cdot (1 - p^t) $$ Where $\lambda_{\text{origin}}$ is the rate at time of transition, $\lambda_{\text{end}}$ is the new regime's target, $p$ is the decay factor, and $t$ is time elapsed. This smooths transitions and prevents unnecessary liquidation cascades from brief regime flickers. ## Collateral and Equity All collateral is denominated in USDC. Mark equity is: $$ E_{\text{mark}} = C + \text{PnL}_{\text{mark}} $$ Liquidation uses impact-adjusted closeout equity: $$ E_{\text{close}} = C + \text{PnL}_{\text{impacted}} $$ $\text{PnL}_{\text{impacted}}$ applies the estimated adverse cost of closing each position. This prevents the risk engine from assuming that a large position can exit entirely at the mark. ## Order Validation Before any order is accepted, a pre-flight check verifies: 1. **Available margin**: Your available equity (equity minus maintenance margin in use) must support the new order's notional 2. **Max leverage**: The implied leverage of the order (and cumulative leverage including open orders) must not exceed the per-instrument maximum 3. **Reducing trades**: Orders that reduce or close an existing position always pass, regardless of margin state This is not a simple "initial margin" formula. The validation uses the same portfolio margin model, checking whether the new exposure would remain within risk limits given your current portfolio state. ## Isolated Risk via Sub-Accounts BULK uses cross margin by default, where all collateral is shared across positions in your account. If you want to isolate risk for a specific trade, create a sub-account. Each sub-account has its own collateral pool and positions, completely independent from your main account. A liquidation in a sub-account does not affect your main account or other sub-accounts. Sub-account volume rolls up to your main account for fee tier calculation. ## Liquidation Trigger Liquidation is triggered when both conditions are met: $$ E_{\text{close}} \lt M_p \quad \text{and} \quad \text{PnL}_{\text{mark}} \lt 0 $$ See [Liquidations](/bulk-exchange/Liquidations) for closeout pricing, selective reduction, and protected execution. # Order Types Source: https://docs.bulk.trade/bulk-exchange/Order-Types Order types, time-in-force options, and execution modifiers on BULK Exchange. ## Market Order Executes immediately at the best available price. Walks the book until fully filled or risk limits are reached. ## Limit Order Rests on the book at a specified price or better. A buy limit fills at the limit price or lower. A sell limit fills at the limit price or higher. ## Time-in-Force | TIF | Name | Behavior | | - | - | - | | `GTC` | Good-Til-Cancelled | Rests on the book until filled or cancelled. Default for limit orders. | | `IOC` | Immediate-or-Cancel | Fills what it can immediately. Unfilled remainder is cancelled. No resting. | | `ALO` | Add-Liquidity-Only (Post-Only) | Must rest on the book as a maker order. If it would cross the spread and take liquidity, it is rejected (`rejectedCrossing`). Guarantees maker fee or no execution. | > [!NOTE] > > The internal enum uses `ALO`. The WebSocket account stream emits `"postOnly"` on the wire. The HTTP API accepts both. ## Reduce-Only A modifier that ensures the order can only decrease or close an existing position, never open a new one or increase size. If the order would flip the position direction, its size is clamped to close only. Used by the liquidation engine internally and available on any order type. ## Modify Order Amend the size of a resting limit order. Submitted as a `ModifyOrder` action referencing the original order ID. * **Size reduction**: Order stays at the same position in the queue. If the new size is less than or equal to the already-filled amount, the order is effectively cancelled. * **Size increase**: Order is moved to the back of the queue at its price level. Modify does not change the order's price. To change price, cancel and resubmit. ## Conditional Orders See [Conditional Orders](/bulk-exchange/conditional-orders) for Stop, Take-Profit, Range, Trigger, Trailing, and On-Fill order types. ## Execution Priority Within each consensus batch, transactions are deterministically shuffled then separated into priority queues: 1. **Cancels** execute first 2. **Post-only (ALO) orders** execute second 3. **Regular orders** (market, limit GTC/IOC) execute third This structural priority is independent of shuffle ordering and provides protocol-level fairness guarantees. See [Fair Ordering](/architecture/fair-ordering) for the full design. # Order Book Source: https://docs.bulk.trade/bulk-exchange/Orderbook Central limit order book architecture on BULK Exchange. ## Overview BULK runs a central limit order book (CLOB) for each perpetual contract market. Orders are matched using price-time priority, the same model used by traditional exchanges. ## Structure Each instrument has a `Book` with two sides: * **Bid levels** - buy orders sorted by price (highest first) * **Ask levels** - sell orders sorted by price (lowest first) Within each price level, orders form a FIFO queue. Earlier orders at the same price fill before later ones. ## Matching When an aggressive order enters: 1. **Price check** - buy orders cross if `price >= best_ask`, sell orders cross if `price <= best_bid` 2. **Walk the book** - the order matches against resting levels at successively worse prices until filled, the limit price is breached, or the book is exhausted 3. **Risk callback** - after each fill, the risk engine verifies the resulting position is within margin limits. If a fill would cause a margin breach, the remainder is cancelled 4. **Rest or expire** - unfilled GTC remainder rests on the book. IOC remainder is cancelled. ALO orders that would have crossed are rejected before matching. ## Pre-Flight Margin Check Before any order touches the book, the executor validates: * Sufficient available equity for the new position * Leverage within configured limits * Valid order parameters (size, price, side) * Reduce-only orders actually reduce the position Orders that fail are rejected with a specific reason code. ## Self-Trade Prevention When an incoming order would match against a resting order from the same account, the match is skipped. See [Self-Trade Prevention](/bulk-exchange/Self-Trade-Prevention). ## Deterministic Execution Every validator processes the same committed batch through the same matching engine and produces the same fills, the same order statuses, and the same book state. Any divergence is immediately detectable by comparing output state hashes. ## Integration with Risk The order book and the portfolio risk engine operate as a tightly coupled system. They share state on every tick: * **Mark price** - The book's bid, ask, and last traded price feed directly into the mark price model. The depth-weighted mid-price is one of the three core components of the mark price calculation. See [Price Indices](/bulk-exchange/Price-Indices). * **Lambda surfaces** - Order book depth is used to estimate the market impact of unwinding a position. This impact estimate feeds into the lambda surface lookup, which determines maintenance margin rates. Thin books produce higher lambdas and higher margin requirements. * **Liquidation execution** - Order-book depth determines closeout impact, reserve-adjusted margin, and the size of protected execution. Planned reductions are not submitted as one unrestricted market order: BULK uses available market liquidity only within limits independently anchored to fair price and oracle price. Planned quantity that cannot be accepted within protocol capacity becomes an ADL underfill candidate. See [Liquidations](/bulk-exchange/Liquidations). # Price Indices Source: https://docs.bulk.trade/bulk-exchange/Price-Indices Oracle price, mark price computation, and PnL calculation on BULK Exchange. ## Oracle Price The oracle price is the external spot reference for each asset, sourced from Pyth. Pyth pushes low-latency, real-time prices in a distributed manner directly to the BULK Network, providing a manipulation-resistant benchmark decoupled from BULK's internal order book. Oracle price updates flow into the executor via `PythOracle` actions, where they pass through a price filter (volatility guard against stale or spurious updates) before being accepted. ## Mark Price The mark price is the reference price used for PnL, liquidation triggers, and conditional order activation. BULK computes it using a robust model, a composite of three components that adapts to market conditions. ### Component 1: Premium-Adjusted Oracle Price $$ P_{\text{oracle-adj}} = P_{\text{oracle}} - \text{EMA}_{150s}(P_{\text{oracle}} - P_{\text{book}}) $$ Starts with the Pyth oracle price and subtracts a 150-second EMA of the premium between the oracle and the depth-weighted order book mid-price. This allows the mark price to track persistent premiums or discounts on BULK without being swayed by temporary noise. ### Component 2: Depth-Weighted Book Price (Denoised) $$ P_{\text{book}} = \text{median}\left(\text{SizeWeightedMid}_{t-2},\ \text{SizeWeightedMid}_{t-1},\ \text{SizeWeightedMid}_{t}\right) $$ A depth-weighted mid-price from BULK's order book, passed through a rolling median filter to remove outlier ticks. The size-weighted mid accounts for the actual liquidity at each level rather than just the top-of-book. ### Component 3: Smoothed Book Price $$ P_{\text{smooth}} = \text{EMA}_{30s}(P_{\text{book}}) $$ A 30-second EMA of the denoised book price. Acts as a stabilizing factor that dampens short-term fluctuations. ### Final Calculation In normal conditions, the three components are sorted and the median is selected: $$ P_{\text{mark}} = \text{median}(P_{\text{oracle-adj}},\ P_{\text{book}},\ P_{\text{smooth}}) $$ **Volatility override**: When instantaneous volatility (measured via Hawkes IRV or stdev, whichever is larger) exceeds a configurable threshold, the model bypasses the median smoothing and uses the raw depth-weighted book price directly. This ensures the mark price stays reactive during fast-moving markets. ### Stale-Book Oracle Bias If the order book has not been updated for an extended period, the mark price biases toward the oracle price on a sigmoid curve: $$ P_{\text{final}} = (1 - b) \cdot P_{\text{computed}} + b \cdot P_{\text{oracle}} $$ Where the bias factor $b$ is 0 when book age is under 1 (fresh book), and when age reaches or exceeds 1: $$ b = \tanh\left((\text{age} - 0.5) \cdot 10\right) \cdot 0.5 + 0.5 $$ And `age` is the book staleness relative to the decay window (in minutes). As the book grows stale, $b$ rises from 0 toward 1 on a sigmoid curve, and the mark price converges smoothly to the oracle, ensuring fair pricing even in low-liquidity conditions. > [!NOTE] > > **Margin calculations** use the mark price for notional values and PnL, but maintenance margin requirements are driven by lambda surfaces that depend on the **volatility regime**, not the mark price directly. See [Margin](/bulk-exchange/Margin) for how regimes affect margin requirements. ## Entry Price The entry price represents the volume-weighted average price (VWAP) at which your current position was established. It is computed and stored by the clearing engine on every fill: * **Position increase**: VWAP is updated to blend the existing entry price with the new fill price, weighted by size * **Position decrease**: Entry price stays the same (only realized PnL is booked) * **Position flip** (e.g. long to short): Entry price resets to the fill price of the new direction Entry price is stored as a scaled integer (`u64`) internally to avoid floating-point drift. ## Unrealized PnL Unrealized PnL is always computed against the mark price: $$ \text{PnL}_{\text{unrealized}} = Q \times (P_{\text{mark}} - P_{\text{entry}}) $$ Where $Q$ is the signed position size (positive for long, negative for short) and $P_{\text{entry}}$ is the VWAP entry price. This ensures PnL reflects fair value, not last traded price. Your mark equity is: $$ E_{\text{mark}} = C + \sum_i \text{PnL}_{\text{unrealized},i} $$ Where $C$ is your USDC collateral. For liquidation, BULK also computes closeout equity by applying the estimated adverse cost of closing every position through current depth and nearby cascade risk. Liquidation requires closeout equity below reserve-adjusted portfolio maintenance margin and negative mark-price position PnL. See [Liquidations](/bulk-exchange/Liquidations). # Self-Trade Prevention Source: https://docs.bulk.trade/bulk-exchange/Self-Trade-Prevention How BULK prevents users from matching orders against themselves. ## Overview BULK implements Self-Trade Prevention (STP) in the matching engine. When an incoming aggressive order reaches a resting order from the same account, the resting order is skipped and the aggressor continues searching for eligible external liquidity. ## How It Works 1. An aggressive order enters the book and begins matching 2. Before each potential fill, the engine checks if the incoming order's owner matches the resting order's owner 3. If they are the same account, the engine bypasses that resting order and leaves it unchanged on the book 4. The aggressive order continues through the book and fills against eligible external liquidity within its price limit The resting maker order remains unchanged on the book. If the aggressor finds enough external liquidity, it is filled normally. If it finds some but not enough, it finishes as `partiallyFilled`. If it finds no external liquidity, it finishes as `cancelledSelfCrossing`. Any unfilled remainder does not rest on the book after a self-cross is encountered. ## Why This Matters * **No self-trade fees.** You never pay fees for matching against yourself. * **Market maker friendly.** Makers quoting on both sides of the book can submit aggressive orders without worrying about filling their own resting liquidity. * **No wash trading.** Self-trades do not appear in the public trade feed. * **Sub-accounts are independent.** STP applies per account. Orders from different sub-accounts under the same main account can trade against each other. # Affiliate Program Source: https://docs.bulk.trade/bulk-exchange/affiliate-program An invite-only program for those who shape the BULK ecosystem. To join the Affiliate Program, [submit an application](https://form.typeform.com/to/gYELB5np). BULK reviews each application individually, taking into account trading activity on BULK, audience reach and social media presence. Affiliates receive higher rates than in [Referral Rewards](/bulk-exchange/referral-rewards) and choose one of two commission paths. ## Commission Paths | | Influencer Path | Trader Path | | - | - | - | | **Rebate on your own fees** | — | 10% | | **Direct referrals' fees** | 15–20% | 10–15% | | **Indirect referrals' fees** | 2% | 1–2% | | **Trading AURA boost for your referrals** | +10–17.5% | +10–17.5% | * **Influencer Path** is built for creators with an active audience and pays a higher share of your referrals' fees. * **Trader Path** is built for high-volume traders and returns 10% of the fees on your own trades, in addition to a share of your referrals' fees. Commissions and rebates are calculated on net fees: the taker fee minus the maker rebate. ## Levels Your level is based on the combined trading volume of you and your referrals. Higher levels increase your fee share and your referrals' Trading AURA boost. Level thresholds are shared during onboarding. A new level applies from the next weekly settlement. ## Kickback You can pass up to 50% of your fee share to your referrals to lower their fees. Higher kickbacks are available by arrangement with the BULK team. ## Affiliate Perks * Official BULK Traders affiliate badge on X for top-tier affiliates * Direct line to the BULK team, with dedicated support * Early access to new markets, features and campaigns * Intro call with the team, including the founders * Unlimited referral links ## Program Rules * You can be on one path at a time. * You can switch paths once per month. The switch applies from the next weekly settlement. * BULK may review affiliate participation and modify the Affiliate Program at any time. # The Challenger Series Source: https://docs.bulk.trade/bulk-exchange/aura A seasonal ranked league for BULK traders. The Challenger Series is BULK's seasonal trading competition with weekly leagues: **trade → climb leagues → earn rewards → qualify for the Playoffs.** Season 1 started on **October 10, 2026** and runs for **8 weeks**. Each week runs Saturday to Saturday. ## Who can participate All BULK traders with Trading AURA are automatically entered. No sign-up is needed. Market makers are not eligible. Eligibility is determined by the BULK team. ## Leagues Every week, traders are ranked by Trading AURA and placed into a league: | League | Who's in it | Prize pool | | - | - | - | | **Challenger** | Top 25 traders | 45% of the pool + Playoffs qualification | | **Diamond** | Ranks 26–100 | 25% of the pool | | **Platinum** | Rank 101 down to the top 10% | Share of 30% (2× Gold) | | **Gold** | Down to the top 25% | Share of 30% | | **Silver** | Top 25–50% | — | | **Bronze** | Everyone else with Trading AURA | — | | **Unranked** | No Trading AURA this week | — | The league you finish the week in determines your rewards for that week. No spot is safe. Don't get too comfortable. ## Weekly prize pool Each week, **12.5% of BULK's net revenue** (trading fees minus maker rebates) goes into the prize pool, paid in USDC: * **Challenger:** 45% * **Diamond:** 25% * **Platinum and Gold:** 30%, shared so that Platinum traders earn on average 2× what Gold traders earn Within each league, rewards are split pro-rata by Trading AURA. The minimum claimable reward is **\$5**. Smaller rewards stay on your balance and add up until you reach it. ## Weekly Gauntlets Each week brings a new Gauntlet: a challenge with its own goal and a **50,000 AURA** reward. The new Gauntlet is announced every Saturday in the Challenger Series tab in the BULK app. You take part automatically. The 50,000 AURA is split among participants in proportion to their results. *For example, if this week's Gauntlet is taker volume and you traded \$5M out of \$500M in total, you get 1% of the reward: 500 AURA.* Gauntlet AURA counts toward your league. The Gauntlet reward comes from the weekly 1,000,000 AURA. No extra AURA is minted. ## Fair play All rewards are subject to wash-trading and Sybil checks. Flagged accounts are excluded. ## Playoffs The top traders of the regular season qualify for the Playoffs, the final stage of the Challenger Series, with a separate prize pool. The regular season ends on **December 5, 2026**. Full qualification rules and the Playoff format will be announced before then. ## FAQ > [accordion] Who can join? > > All traders on BULK with Trading AURA, regardless of their maker rebate tier. No sign-up is needed. Market makers are not eligible. > [accordion] How do I move up a league? > > Trade more. The more Trading AURA you earn in a week, the higher your league. > [accordion] Can I drop to a lower league? > > Yes. Leagues are recalculated every week based on Trading AURA, so you can move up or down. > [accordion] Which AURA counts toward my league? > > Only Trading AURA earned during the current week, including Gauntlet rewards. AURA from referrals and other sources doesn't count. > [accordion] How do I qualify for the Playoffs? > > Full qualification rules and the Playoff format will be announced before the regular season ends on December 5. # AURA Source: https://docs.bulk.trade/bulk-exchange/aura-points How AURA points are earned and distributed on BULK. AURA is BULK's points program, designed to recognize each participant's contribution to the growth of the ecosystem. ## Weekly Distribution Every week, from Saturday to Saturday, BULK distributes **1,000,000 AURA**. Points are earned through: * **Trading:** your own trades earn Trading AURA * **Providing liquidity** * **Referrals:** see [Referral Rewards](/bulk-exchange/referral-rewards) * **Weekly Gauntlets:** see [The Challenger Series](/bulk-exchange/aura) The weekly supply is fixed, so no extra AURA is minted. ## How AURA Is Calculated AURA is distributed based on genuine market participation, not raw volume alone. Allocations take multiple factors into account, including but not limited to trading volume, fees, open interest, and the quality and consistency of activity. Taking part in eligible activity does not guarantee a specific allocation. ## Fair Play AURA is reserved for organic activity. Wash trading, self-matching and other attempts to game the system can lead to a reduced allocation or full exclusion from AURA distribution. All accounts are subject to Sybil checks. # Builder Codes Source: https://docs.bulk.trade/bulk-exchange/builder-codes Builder Codes on BULK Exchange. ## Overview Builder codes are BULK's routed-order-flow attribution mechanism. They can carry a transparent builder fee on top of BULK's base trading fees using the `builderCode`, `abc`, `rbc`, and `builderCodeApprovals` fields. > [!NOTE] > > Builder codes are now live on BULK's exchange endpoints. > > ```bash HTTP REST (Primary) theme={null} > https://mainnet-api1.bulk.trade/api/v1 > ``` > > ```bash WebSocket (Primary) theme={null} > wss://mainnet-ws1.bulk.trade > ``` This is sometimes compared to Payment for Order Flow (PFOF), but BULK's model is fundamentally different from traditional PFOF. ## How It Works A builder attaches a builder-code fee to the specific order they route. The fee is transparent in the signed order payload, capped by user approval, and settled in addition to the user's standard BULK fee tier. The key distinction: **these are not spread-charged fees.** The integrator does not internalize flow, route to a private market maker, or degrade execution quality. Every order - regardless of which frontend submitted it - is routed to the BULK Network and executed on the same deterministic order book. All participants receive the same BULK Best Bid and Offer. ## User Approval Before an order can pay a builder-code fee, the account owner approves the recipient with `abc`: ```json theme={null} {"abc": {"to": "recipient_pubkey_base58", "fee": 5}} ``` * `fee` is basis points and must be `1..=15`. * Each master account can approve at most 10 builder-code recipients. * The recipient must be an existing canonical root payout account. An account cannot approve itself or another account in its own master/sub-account tree. * Approvals are master-account scoped. `abc` must be signed by the master account; agent wallets cannot approve builder-code recipients. Account snapshots expose builder-code recipients as `builderCodeApprovals: [{ "recipient": "...", "maxFee": 5 }]`. * Users can revoke approval with `rbc`. `rbc` must also be signed by the master account; agent wallets cannot revoke builder-code recipients. Revocation prevents builder-code fee settlement for resting orders that have not filled yet. ```json theme={null} {"rbc": {"to": "recipient_pubkey_base58"}} ``` ## Routed Orders Include the `builderCode` payload only on `m` or `l` orders routed through the builder: ```json theme={null} {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false, "builderCode": {"to": "recipient_pubkey_base58", "fee": 5}}} ``` Orders without a builder code omit the field entirely: ```json theme={null} {"m": {"c": "BTC-USD", "b": true, "sz": 0.1, "r": false, "i": false}} ``` `"builderCode": null` is rejected by the JSON API. A builder-code fee applies only to the order side carrying the field, whether that order fills as maker or taker. The same rule applies to nested market and limit orders, including an OnFill trigger or consequent. In canonical signing bytes, an absent `builderCode` contributes no bytes. A present value contributes the `Some` tag (`1`), the 32-byte recipient pubkey, and the one-byte fee. ## For Builders * Use `abc`/`rbc` for user authorization and show the active `builderCodeApprovals` state before routing * Attach `builderCode: {to, fee}` only to orders actually routed through your builder code * The builder-code fee is applied on top of the user's standard BULK fee tier and credited to the recipient account * All orders are routed to the network and matched fairly - no internalization, no dark pools, no preferential routing ## Why This Matters Traditional PFOF creates a conflict of interest: the broker sells your order to a market maker who profits from the spread. On BULK, there is no such conflict. The builder earns a transparent fee, the user gets the best available price from the full order book, and the network treats every order identically. ## API Reference * [Place & Cancel Orders](/api-reference/placeOrder) * [Trading via WebSocket](/api-reference/ws-trading) * [Transaction Signing](/api-reference/signing) * [Query Account](/api-reference/getAccount) # Conditional Orders (TP/SL) Source: https://docs.bulk.trade/bulk-exchange/conditional-orders Stop, Take-Profit, Range, Trigger, Trailing, and On-Fill orders on BULK Exchange. ## Overview Conditional orders activate when the mark price crosses a specified trigger price. BULK supports six conditional order types, all triggered by the fair/mark price (not last traded price) and all reduce-only by default. ## Stop Order Triggers when the mark price moves against your position. Used for stop-loss protection. * **Trigger direction**: Below for longs, above for shorts * **On trigger**: Submits a reduce-only market order (if no limit price set) or a reduce-only GTC limit order at the specified limit price * **Reduce-only**: Always. Cannot open new positions. ## Take-Profit Order Triggers when the mark price moves in favor of your position. Used to lock in gains. * **Trigger direction**: Above for longs, below for shorts * **On trigger**: Same as Stop, either market or limit depending on whether a limit price is specified ## Range Order A two-leg conditional that places both a stop and a take-profit simultaneously with a single action. Internally creates two linked orders (OCO). * **Lower trigger**: Stop-loss level with optional limit price * **Upper trigger**: Take-profit level with optional limit price * When one leg triggers, the other is automatically cancelled (One-Cancels-Other) ## Trigger Order A general-purpose conditional that holds a set of arbitrary actions. When the mark price crosses the trigger threshold, all embedded actions are submitted to the executor. * **Trigger direction**: `Above` (fires when price is at or above threshold) or `Below` (fires when price is at or below threshold) * **Actions**: Any valid action list (limit orders, cancels, etc.) * More flexible than Stop/TP since it is not restricted to reduce-only or a single instrument ## Trailing Stop A stop order that follows the market price. As the market moves in your favor, the stop level adjusts automatically. When the market reverses by the specified trail amount, the stop triggers. * **trail_bps**: Distance in basis points from the current price * **step_bps**: Minimum price movement before the trail resets * Internally implemented as a Stop order with a companion Trigger sentinel that resets the stop level on each step ## On-Fill Orders Conditional orders that attach to a parent order and activate only when the parent fills. Used to place Stop/TP orders that are linked to a specific entry. * **Before parent fills**: The On-Fill children are dormant, not on the conditional book * **Parent fully fills**: All On-Fill children are activated and placed on the conditional book * **Parent cancelled before fill**: Children are cancelled too * **Parent partially fills then cancelled by margin**: Children are placed for the filled size * Up to 32 On-Fill rounds per tick can fire (batched processing) ## Conditional Book All conditional orders live on a separate trigger book, not the main order book. The trigger book maintains two sorted maps: * **Above book**: Orders that fire when price reaches or exceeds the threshold * **Below book**: Orders that fire when price reaches or falls below the threshold Each tick, the executor checks the current fair price against the book and drains all triggered levels in a single pass. OCO partners are cancelled after the drain. ## Parameters | Field | Description | | - | - | | `trigger_price` | Price at which the order activates | | `limit_price` | Optional. If set, places a limit order on trigger. If zero/unset, places a market order. | | `is_above` | Trigger direction. `true` for above-threshold trigger, `false` for below-threshold trigger | | `oco_order_id` | Optional linked order ID for One-Cancels-Other behavior | | `trail_bps` | For trailing stops: trail distance in basis points | | `step_bps` | For trailing stops: minimum step size before trail resets | ## Example: Limit Entry with TP/SL Place a limit buy with attached take-profit and stop-loss using On-Fill: 1. Submit a limit buy for 1 BTC at 95,000 2. Attach an On-Fill take-profit at trigger 105,000 (market) 3. Attach an On-Fill stop-loss at trigger 90,000 with limit 89,500 If the limit buy fills, both conditional orders activate. If BTC hits 105,000 first, the TP fires and the SL is cancelled via OCO. ## API Reference For full request/response examples and implementation details, see: * **HTTP**: [Place & Cancel Orders](/api-reference/placeOrder) for `st`, `tp`, `rng`, `trig`, `trl`, `of` action types * **WebSocket**: [Trading via WebSocket](/api-reference/ws-trading) for conditional order examples with request/response payloads and `orderUpdate` lifecycle events # Fees Source: https://docs.bulk.trade/bulk-exchange/fees Fee tiers, maker rebates, and the BULK Alpha Program. ## Overview Fees and rebates settle per fill in USDC. Maker and taker fees are determined by the account's 14-day trading-volume tier. Maker rebates are calculated separately, based on the account's share of maker volume in each market. For tier qualification, volume from the main account and all of its sub-accounts is combined. The resulting fee tier applies across the whole account tree, while each fee or rebate is posted to the account that executed the fill. BULK is fundamentally transparent. There is no separate liquidation fee. Liquidation pricing includes deterministic market-impact and reserve adjustments that are part of risk management rather than the trading-fee schedule. Every node runs the same execution logic, and validators earn 12.5% of trading fees for running the network. ## Growth Mode BULK is currently operating in Growth Mode. During this period, maker fees are set to 0 bps across all markets, and a reduced taker fee applies to TradFi markets. ### Crypto Markets Taker fees depend on your 14-day volume. | Tier | 14-Day Volume | Maker | Taker | | - | - | - | - | | 1 | \<\$1M | 0 bps | 3.5 bps | | 2 | ≥\$1M | 0 bps | 3.3 bps | | 3 | ≥\$10M | 0 bps | 3.0 bps | | 4 | ≥\$50M | 0 bps | 2.8 bps | | 5 | ≥\$150M | 0 bps | 2.6 bps | | 6 | ≥\$500M | 0 bps | 2.4 bps | | 7 | ≥\$1.5B | 0 bps | 2.3 bps | | 8 | ≥\$4.0B | 0 bps | 2.2 bps | #### Maker Rebates Makers can also earn a rebate in each market based on their share of that market's 14-day maker volume. | Tier | Share of 14-Day Market Maker Volume | Maker Rebate | | - | - | - | | 1 | ≥0.50% | -0.2 bps | | 2 | ≥2.50% | -1.0 bps | | 3 | ≥5.00% | -1.5 bps | ### TradFi Markets TradFi markets use a single flat fee tier, regardless of your 14-day volume. | Tier | 14-Day Volume | Maker | Taker | | - | - | - | - | | 1 | ≥\$0 | 0 bps | 1.5 bps | #### Maker Rebates | Share of 14-Day Market Maker Volume | Maker Rebate | | - | - | | ≥5.00% | -0.5 bps | ### How Rebates Apply Because maker fees are 0 bps, a qualifying maker receives the full rebate. For example, a maker with a 5.00% share of a crypto market's maker volume earns 1.5 bps on every maker fill in that market, or 0.5 bps in a TradFi market. ## How the Rolling Window Works Fee qualification uses executed USD notional from the trailing 14 completed UTC days. * The current UTC day's activity is recorded immediately but does not affect that day's tier. It becomes eligible after the next 00:00 UTC cutoff. * A fill uses the tier established by volume completed before that fill. A fill cannot move itself into a lower-fee tier. * Volume from the main account and all sub-accounts is aggregated for qualification. Self-trades between accounts under the same main account do not create qualifying volume. * Volume thresholds are inclusive. The highest threshold reached determines the base maker and taker rates. * Maker share is calculated separately for each market: $$ \text{Maker Share} = \frac{\text{Account Tree's Maker Notional}}{\text{Total Maker Notional in the Market}} $$ Both values in the maker-share calculation use the same trailing 14 completed UTC days. The calculation is a direct volume share; it is not time-weighted or exponentially decayed. Maker rebates are requested at the rates above and funded by each market's rebate pool. The realized rebate on a fill cannot exceed the available pool balance plus the taker fee collected on that fill. ## The BULK Alpha Program > [!NOTE] > > The BULK Alpha Program has not launched yet. Follow official BULK channels for launch updates. A performance-based rewards program on top of fee rebates, designed to accelerate market liquidity starting with makers. **Reward pool:** 7.5% of taker fee revenue per epoch (one epoch = 30 days). ### Quality Score Each market maker is scored per market: $$ QS = 0.40 \cdot \text{OI} + 0.30 \cdot \text{TightnessDepth} + 0.20 \cdot \text{Uptime} + 0.10 \cdot \text{Volume} $$ | Component | Weight | What It Rewards | | - | - | - | | Open Interest Share | 40% | Maintaining a large share of the exchange's open interest | | Spread and Depth | 30% | Tight spreads and deep order books | | Uptime | 20% | Quoting consistently | | Trading Volume Share | 10% | Both maker and taker volume | Distribution is market-weighted (larger markets allocate more rewards), then market-maker-weighted by $QS$ within each market. Rewards are paid out every epoch. No KYC or special requirements beyond the criteria above. # Funding Source: https://docs.bulk.trade/bulk-exchange/funding Hourly funding rate mechanism on BULK Exchange. ## Overview Funding payments anchor perpetual contract prices to spot. They are exchanged hourly, directly between long and short holders. The exchange does not take a cut. If the perp trades at a premium to spot, longs pay shorts. If at a discount, shorts pay longs. ## Funding Rate Formula Each funding period, the rate is computed from sampled premiums: $$ F = \text{clamp}\left(P_\mu + \text{clamp}(r - P_\mu, -d, d), -f_{\text{cap}}, f_{\text{cap}}\right) $$ Where: | Variable | Description | | - | - | | `P_mu` | Simple moving average of premium samples over the funding period | | `r` | Interest rate (configurable, in bps) | | `d` | Deviation cap (configurable, in bps) - limits how much the interest rate component can deviate from the premium | | `f_cap` | Funding rate cap (configurable, in bps) - absolute clamp on the final rate | ### Premium Sampling Each sample interval (configurable, typically every few seconds): 1. Compute the depth-weighted bid and ask prices by sweeping a fixed notional amount through the book: * `P_bid = sweep(sell, size)` * `P_ask = sweep(buy, size)` * where `size = notional / mid` 2. Get the oracle price `P_o` 3. Compute the premium: $$ \Delta D = \max(P_{\text{bid}} - P_o, 0) - \max(P_o - P_{\text{ask}}, 0) $$ $$ \Pi = \frac{\Delta D}{P_o} $$ 4. `P_mu = SMA(Pi)` over the configured window This depth-weighted premium is more robust than a simple mid-price comparison because it accounts for actual executable prices at meaningful size. ## Funding Payment For each position at funding time: $$ \text{payment} = \text{notional}_{\text{USD}} \times F \times (-\text{sign}(Q)) $$ * Long (`Q > 0`) with positive `F`: pays funding (payment deducted from margin) * Short (`Q < 0`) with positive `F`: receives funding (payment added to margin) * Signs reverse when `F` is negative Payments are applied directly to your margin balance. No separate funding wallet. ## Schedule Funding is calculated and settled every hour, aligned to the top of the hour. The rate is applied to positions open at the funding timestamp. # High Frequency Market Making Source: https://docs.bulk.trade/bulk-exchange/hf-market-making Open market making on BULK with deterministic ordering and a uniform maker window. ## Open Access Anyone can make markets on the BULK Network. There are no private feeds, VIP queues, or negotiated latency tiers. Every participant uses the same order types and passes through the same consensus, speed-bump classification, deterministic ordering, and matching engine. ## Uniform Maker Window BULK's [Taker Speed Bump](/architecture/taker-speed-bump) gives maker-only transactions a 25 ms window before taker-capable transactions become eligible for execution. ALO orders are immediately eligible because they either add liquidity or are rejected. Market, GTC, IOC, modify, and conditional order transactions receive the same 25 ms delay for every participant and ingress path. After the delay, eligible transactions enter the same [deterministic shuffle](/architecture/fair-ordering#layer-2-deterministic-shuffle) and matching pipeline. The maker window is a public protocol rule, not preferential access for selected firms. ## Signing at High Frequency For high-frequency order submission, use a **keychain** (agent wallet) for signing transactions. Agent wallets are authorized sub-keys that can sign on behalf of your main account without exposing your primary private key. They support the full order lifecycle: place, modify, cancel. See [Signing](/api-reference/signing) and [Agent Wallets](/api-reference/manageAgentWallet) for setup. ## SDKs SDKs for high-frequency market making are in active development. Check back for updates or join the Discord for early access. ## Rate Limits and Validator Mode If you find the default API rate limits too restrictive for your strategy, consider running a BULK validator in **follower mode**. A follower node replicates the full network state locally, allowing you to read and write without participating in consensus. This gives you: * Direct local state reads with zero network latency * Higher throughput for order submission * Full order book and account state without API polling ## Latency and Co-location The majority of BULK Network nodes are currently based in Europe. For the best latency today, co-locate with the European cluster. When regional books go live, co-locate with the market flow: * **Crypto** - Asia * **Commodities** - United States Regional books are designed so that liquidity follows the trading population. The matching engine runs locally in each region, with cross-region settlement handled by the consensus layer. ## Questions If you have technical questions about market making on BULK, start in the Discord: [discord.gg/bulk](https://discord.gg/bulk) # Isolated Margin Source: https://docs.bulk.trade/bulk-exchange/isolated-margin Isolate risk per instrument with auto-created isolated accounts, or manually via sub-accounts. BULK does not have a special "isolated mode" toggle. Instead, isolated margin is achieved through the account structure itself. There are two ways to isolate risk: 1. **Automatically (per instrument)**: submit an order with the `i` (iso) flag set and the protocol routes it into a per-instrument **isolated account** (`IsoAccount`) attached to your master/sub-account. 2. **Manually (per book)**: create a [sub-account](/bulk-exchange/sub-accounts), fund it, and trade from it. The risk engine evaluates it independently. ## Isolated Accounts (Implicit, Per Instrument) Order actions that produce a position (`l`, `m`, `st`, `tp`, `rng`, `trig`, `trl`) carry a required `i` boolean. When `i = true`, the order is routed into a per-instrument `IsoAccount` attached to the signing master/sub-account. ```json theme={null} {"l": {"c": "BTC-USD", "b": true, "px": 100000.0, "sz": 0.1, "tif": "GTC", "r": false, "i": true}} ``` > [!NOTE] > > **Isolated accounts are entirely flag-managed.** You never set the `IsoAccount` > pubkey as `account` on a transaction, register agents on it, or query it via > current-state `POST /account` query. It is created, traded, and torn down > through ordinary signed actions on the parent master/sub-account. Its pubkey > appears on read-only rows (`isoPubkey`), can be queried directly through the > [history query types](/api-reference/getAccount#history-queries) on `POST /account`, > and is accepted as the `to` of an > internal [`transfer`](/api-reference/transfer). Properties: * One instrument per isolated account (e.g. the BTC-USD isolated account only holds BTC-USD positions). * The isolated account is **auto-derived** from the signing account and the instrument. No separate "create" action is required; the first `i = true` order materialises it. * It is **off-curve**: the pubkey is deterministically derived from the parent and the instrument, and has no private key. Only the parent account (or its registered [agent wallets](/api-reference/manageAgentWallet)) can manage it. * It has its own balances, positions, and margin. The same [portfolio margining](/bulk-exchange/portfolio-margining) engine applies, but since the account is limited to a single instrument, the margin calculation reduces to a single-position evaluation with no cross-asset correlation benefit. * Before an `i = true` order executes, BULK funds the isolated account to a buffered target covering leverage-based margin and the position's size-dependent liquidation reserve. If the account already has sufficient collateral, no additional margin is moved. * A liquidation on the isolated account only touches that account's margin. The signing master/sub-account is unaffected. ## Account and History Surfaces Current account snapshots follow the current account tree: isolated-account rows appear alongside base-account rows on the attached parent master or sub-account. Each isolated-account row carries: | Field | Meaning | | - | - | | `iso` | `true` for isolated-account rows. `false` for base-account rows. | | `isoPubkey` | Present only when `iso = true`. Base58 pubkey of the isolated account. Use it as the `to` target for margin top-ups or as the `user` body field for a direct physical-history query. | Aggregated `fullAccount` queries on a master or sub-account return both base-account rows and isolated-account rows in one response. Group on `iso` and `isoPubkey` to render per-instrument PnL/risk. Current-state `POST /account` types accept only master and sub-account pubkeys, while the history types on that endpoint accept an isolated pubkey for its full physical history. Paginated history uses immutable row-time ownership rather than the current account tree. A parent query merges only its own primary rows and sparse alias rows that stored that parent when they were written. A direct `isoPubkey` query reads that pubkey's entire physical primary history across isolated and base lifecycle states. Detaching or reparenting never rewrites history: the former parent keeps its earlier rows, and the new parent sees only rows written after the new row-time relationship was recorded. The query cost does not grow with the parent's current or historical lane count. A direct request reads one stream; a parent request merges at most its primary and row-time alias streams. These streams have independent hot retention, so aggregate and direct queries can report different `minAvailableSlot` values. See [Query Account](/api-reference/getAccount#history-queries) for the request and cursor shape. ## Top-Up and Settlement To add margin, send an internal [`transfer`](/api-reference/transfer) with `to = isoPubkey`. The other direct read-only use is a physical-history query for that pubkey: ```json theme={null} { "actions": [ {"transfer": {"k": "internal", "from": "master_or_sub_pubkey", "to": "iso_account_pubkey", "marginSymbol": "USDC", "marginAmount": 100.0}} ], "nonce": 1704067200000, "account": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signer": "FuueqefENiGEW6uMqZQgmwjzgpnb85EgUcZa5Em4PQh7", "signature": "5j7s..." } ``` `transfer`, `createSubAccount`, and `removeSubAccount` trigger a same-tick PnL/risk refresh on touched accounts (including isolated accounts), so margin headroom updates immediately without waiting for the next snapshot tick. ## Removing an Isolated Account Isolated accounts are removed via the [`removeSubAccount`](/api-reference/manageSubAccounts) action submitted by the parent master/sub-account, with `toRemove` set to the isolated account's pubkey. The isolated account must have: * No open positions * No open orders On removal, remaining margin is swept back to the parent automatically. Removal affects current account state only. Historical rows keep the parent recorded when each row was written; they are not moved, relabelled, or deleted because the isolated account was removed. ## Isolated Margin via Sub-Accounts For more flexibility, you can isolate manually using [sub-accounts](/bulk-exchange/sub-accounts). Create a sub-account, transfer in the exact amount of tokens you are willing to risk, and trade from it (set the transaction `account` to the sub-account pubkey; the master, the sub-account itself, or an authorized agent wallet signs): * The risk engine evaluates the sub-account independently. * If the sub-account hits its maintenance margin threshold, only that sub-account is liquidated. * The master account's equity and other sub-accounts remain untouched. * Unlike auto-created isolated accounts, sub-accounts can hold positions across multiple instruments and benefit from full [portfolio margining](/bulk-exchange/portfolio-margining); cross-asset correlations and hedging discounts apply. This gives you granular capital allocation with the full power of portfolio margin applied to a smaller, separate account. # Portfolio Margining Source: https://docs.bulk.trade/bulk-exchange/portfolio-margining True portfolio margining on-chain - capital efficiency, multi-asset collateral, and the future of risk management. ## The State of Risk Management An exchange is only as good as its risk engine. Every major derivatives venue in traditional finance - CME, Eurex, ICE - has converged on the same conclusion: portfolio margining is the gold standard. Evaluating risk at the portfolio level, accounting for correlations and hedges, is the only way to provide capital-efficient margin without compromising safety. Until now, this has been a TradFi-only capability. Crypto exchanges either run isolated margin (each position margined independently) or a rudimentary cross-margin that still sums individual position requirements. BULK brings true portfolio margining on-chain for the first time. ## What Makes It "True" Portfolio Margining Portfolio margining is not just cross-margin with a different name. The defining characteristics: 1. **Correlation-adjusted notionals** - A long BTC / short ETH portfolio is recognized as partially hedged. The effective notional is computed using real-time cross-asset correlations, not the sum of individual notionals. 2. **Dynamic risk surfaces** - Margin rates adapt continuously to leverage, position size, market impact, and volatility regime. No static tiers. No cliff edges. 3. **Marginal risk contributions** - The system computes how much each position contributes to total portfolio risk. Adding a hedge reduces your margin. Adding a correlated directional bet increases it. 4. **Portfolio-aware liquidation** - The optimizer recomputes whole-portfolio margin for each candidate reduction. Correlation benefit, liquidation reserve, and expected execution cost all affect which positions are reduced instead of mechanically closing the largest losing leg. ```mermaid theme={null} flowchart LR A[Isolated Margin] -->|"Sum of individual margins"| D[High capital requirement] B[Cross Margin] -->|"Shared collateral, still summed"| D C[Portfolio Margin] -->|"Correlation-adjusted, hedge-aware"| E[Optimal capital efficiency] ``` ## Capital Efficiency The difference is material. Consider a portfolio with a long BTC perpetual and a short ETH perpetual at 10x: | Margin Model | Margin Required | | - | - | | Isolated | 10% BTC notional + 10% ETH notional | | Cross (sum) | 10% of (BTC + ETH notional) | | Portfolio (BULK) | 10% of correlation-adjusted effective notional | With BTC-ETH correlation around 0.85, the portfolio margin requirement can be 30-70% lower than the isolated equivalent. The more hedged the portfolio, the larger the savings. ## How CME and Eurex Do It CME SPAN runs 16 predefined scenarios per product, scanning price and volatility shifts to find the worst-case loss. Eurex Prisma uses a filtered historical simulation with full revaluation. Both are batch processes - risk is recomputed on a schedule, not tick-by-tick. BULK computes portfolio margin continuously. Lambda surfaces update in real time with regime shifts. Correlations are live. There is no batch window, no stale risk between scans. ## The Road Ahead Portfolio margining is a foundation, not a ceiling. The same correlation-aware risk model that handles perpetual futures can be extended to: **Multi-asset collateral** - Use BTC, ETH, SOL, or other assets as margin deposits. Each collateral asset is haircut based on its volatility and correlation to the position set. A BTC deposit collateralizing a BTC-perp position gets a smaller haircut than one collateralizing a SOL-perp position. **Lending and borrowing** - Borrow against your portfolio's excess margin. The risk engine already knows your true risk, so it can compute safe borrowing limits without requiring separate collateral pools. **Multi-instrument portfolios** - Options, spot, structured products, and perpetuals in a single margined account. The correlation model extends naturally to any instrument with a price feed. A covered call (long spot + short call) would be recognized as a defined-risk position and margined accordingly. **Cross-exchange netting** - Positions across regional books and multiple venues netted into a single risk profile. The goal is a single account where your entire portfolio - across instruments, collateral types, and strategies - is evaluated as one unit. Maximum capital efficiency, minimum unnecessary liquidation risk. See [Margin](/bulk-exchange/Margin) for the full technical breakdown of how portfolio margin is computed today. # Referral Rewards Source: https://docs.bulk.trade/bulk-exchange/referral-rewards Earn a share of trading fees from the traders you refer to BULK. In addition to USDC rewards, you earn 1 AURA for every 4 Trading AURA your referrals earn. ## Tiers | Tier | Eligibility | Referrer rewards | Referred trader benefit | | - | - | - | - | | **Base** | Default for all referrers | 10% of net fees from direct referrals and 1% from indirect referrals | +5% Trading AURA boost | | **Top Partner** | \$1B lifetime volume (personal + direct referrals) | 15% of net fees from direct referrals and 2% from indirect referrals | +10% Trading AURA boost | Your rates depend only on your own tier, not on the tier of the traders you refer. ## Referral Levels **Direct referrals** are traders who sign up through your referral link. **Indirect referrals** are traders who sign up through the link of one of your direct referrals. Example rewards when a referral pays \$10,000 in net fees: | Referral | Base | Top Partner | | - | - | - | | Direct | \$1,000 | \$1,500 | | Indirect | \$100 | \$200 | ## Net Fees Net fees are the trading fees paid by your referrals after rebates and discounts. The following fees and volume are not counted: * Fees and volume from accounts that qualify for maker rewards or are whitelisted market makers * Trades executed through builder codes ## Trading AURA Boost The boost increases a referred trader's share of the fixed weekly AURA supply. No additional AURA is minted. ## Referral Link and Invite Slots Access codes have been replaced by a single referral link per trader, and each remaining access code has been converted into one invite slot. * Each new trader who signs up through your link uses one invite slot. * When you have no slots left, new traders cannot sign up through your link until you earn more. * Traders who joined with your access codes remain your direct referrals. * You earn **1 invite slot** for every **\$100,000** of your personal trading volume. ## Payouts * Rewards are paid weekly in USDC. * Each payout week runs from Saturday 12:00 UTC to the following Saturday 12:00 UTC. * A new tier applies from the start of the next payout week. Previous weeks are not recalculated. * Amounts below \$1 roll over to the following week. ## Who Can Participate All BULK traders can participate, except: * Users in restricted jurisdictions under the [BULK Terms of Service](https://www.bulk.trade/terms) * Accounts flagged for wash trading, self-referral or other abuse. Pending rewards for these accounts may be withheld. ## Additional Information * There is currently no cap on referral rewards. * Referral activity, invite slots, tier progress and rewards can be tracked on the referrals page. * Referral link names are case sensitive. ## FAQ > [accordion] Where do I find my referral link? > > On the referrals page in the BULK app. You can also track your referrals, invite slots, tier progress and rewards there. > [accordion] Do my existing referrals still count? > > Yes. Everyone who joined with your access codes is now your direct referral, and you earn from their trades starting October 20, 2026. > [accordion] When and how do I get paid? > > Rewards are paid weekly in USDC for each payout week, which ends on Saturday at 12:00 UTC. Amounts below \$1 roll over to the next week. > [accordion] How do I become a Top Partner? > > Reach \$1B in lifetime volume, counting your own trading and your direct referrals' trading. Top Partner rates apply from the start of the next payout week. > [accordion] What do the traders I invite get? > > A Trading AURA boost: +5% if you're a Base referrer, +10% if you're a Top Partner. The boost applies to everyone who joins through your link. More perks for referred traders may be added in the future. > [accordion] What happens when I run out of invite slots? > > New traders can't sign up through your link until you earn more slots. You get 1 slot for every \$100,000 of your own trading volume. > [accordion] Does referral AURA count toward the Challenger Series? > > No. Only your own Trading AURA counts toward your league. > [accordion] Can I refer my own accounts? > > No. Self-referral is treated as abuse, and flagged accounts are excluded from the program. # Sub-Accounts Source: https://docs.bulk.trade/bulk-exchange/sub-accounts Partition a single master account into independent sub-accounts, each with its own margin, positions, and risk profile. Sub-accounts let you partition a single master account into independent accounts. Each sub-account holds its own token balances, positions, and orders, with its own risk profile evaluated independently by the portfolio margin engine. Every sub-account benefits from the same [portfolio margining](/bulk-exchange/portfolio-margining) as the master - cross-asset correlations, hedging discounts, and dynamic lambda surfaces all apply within each sub-account's portfolio. Sub-accounts are also the foundation for [isolated margin](/bulk-exchange/isolated-margin) on BULK. Fund a sub-account with the exact amount you are willing to risk, and if it is liquidated, the master account and other sub-accounts are unaffected. ## Account Hierarchy Every wallet that connects to BULK is a **MasterEOA** - a master externally owned account with a Solana keypair. The master can create sub-accounts beneath it, forming a tree: ``` MasterEOA (your wallet) ├── Sub-Account: "portfolio-a" ├── Sub-Account: "portfolio-b" └── Sub-Account: "hedges" ``` The master account is always the root. Sub-accounts cannot create children of their own. > [!NOTE] > > Sub-accounts are **off-curve accounts**. Their public keys are deterministically derived from the master's public key and do not correspond to any private key. Ownership is enforced by the protocol - only the parent MasterEOA can manage them. ## Creating a Sub-Account Submit a [`CreateSubAccount`](/api-reference/manageSubAccounts) action with the following fields: | Field | Description | | - | - | | `name` | Display name for the sub-account (1-32 characters, alphanumeric, `-`, `_`) | | `margin_symbol` | (Optional) Token to seed the account with (e.g. `USDC`) | | `margin_amount` | (Optional) Amount of tokens to transfer from master on creation | If both `margin_symbol` and `margin_amount` are provided, the protocol atomically creates the sub-account and transfers tokens from the master in a single operation. The master's withdrawable balance is checked before the transfer. Names must be unique within the master's account tree. The protocol rejects duplicate names. ## Constraints | Constraint | Value | | - | - | | Max sub-accounts per master | 64 | | Max name length | 32 characters | | Allowed name characters | `A-Z`, `a-z`, `0-9`, `-`, `_` | | Can create child sub-accounts | No (only master can create) | ## Managing Sub-Accounts ### Transfer Tokens Use the [Transfer](/architecture/transfers) action to move tokens between master and sub-accounts (internal transfer) or between sibling sub-accounts. See the [Protocol Native Asset Transfer](/architecture/transfers) page for full details. ### Remove Submit a [`RemoveSubAccount`](/api-reference/manageSubAccounts) action referencing the sub-account to remove. The sub-account must have: * No open positions * No open orders On removal, all remaining token balances are swept back to the master account automatically. The master's token balance is credited and the sub-account is deleted. Only the owning master account can remove a sub-account. ### Rename Submit a [`RenameSubAccount`](/api-reference/manageSubAccounts) action with the new name. The same naming rules apply (1-32 characters, alphanumeric plus `-` and `_`). The new name must not duplicate any existing sub-account name under the same master. Only the owning master account can rename. ## Settings Inheritance When a sub-account is created, it inherits the master's user settings (leverage allocations per instrument). These settings are copied at creation time. If the master changes its settings afterward, existing sub-accounts are not updated - each sub-account maintains its own independent configuration from that point forward. # SNDK Stock Split Source: https://docs.bulk.trade/corporate-actions/sndk Trading and settlement schedule for Sandisk's 8-for-1 stock split on 19–20 November 2026. Sandisk has [announced an 8-for-1 stock split](https://investor.sandisk.com/news-releases/news-release-details/sandisk-reports-fiscal-first-quarter-2027-financial-results), with additional shares issued after the market closes on **19 November 2026** and split-adjusted trading beginning on **20 November 2026**. BULK plans to close and cash-settle the **SNDK-USD** perpetual market before the transition, then reopen with post-split prices and quantities. All existing positions will be closed and all outstanding orders cancelled. Positions will not automatically reopen. ## Schedule All times below are **UTC**. | Date and time (UTC) | Stage | What happens | | - | - | - | | **19 Nov 2026, 15:00** | Restricted trading | SNDK-USD enters suspended mode. Orders must be reduce-only or post-only. Traders have six hours to wind down exposure before the pre-split regular session closes. | | **19 Nov 2026, shortly after 21:00** | Closure and settlement | Trading closes. All remaining positions are cash-settled using the official 19 November Nasdaq closing-auction price, once available. All outstanding SNDK-USD orders, including take-profit and stop-loss orders, are cancelled. | | **20 Nov 2026, 15:00 — target** | Reopening | Trading resumes in post-split units, subject to final pricing and risk checks. This is 30 minutes after the Nasdaq regular session opens. | > [!NOTE] > > Reopening is a target, not a guaranteed time. SNDK-USD will remain closed if the final checks are incomplete. Any timing changes will be communicated before trading resumes. ## Settlement Remaining positions will be cash-settled in **USDC** using the official **19 November 2026 Nasdaq closing-auction price**. This is the final regular-session closing price before the split, in pre-split units. Settlement will take place once that price is available, shortly after **21:00 UTC**. Settlement realizes the profit or loss on each remaining position. The market will stay closed through the split transition. All traders will start flat when it reopens, and cancelled orders will not be reinstated. ## Reopening in post-split units When trading resumes, prices and order quantities will reflect the 8-for-1 split. Traders who want exposure must submit fresh orders in post-split units. For example, a hypothetical **\$800** pre-split share price corresponds to **\$100** after an 8-for-1 split. **Eight post-split units** represent the same share exposure as **one pre-split unit**. This is an illustration of the split ratio; actual prices will depend on the market. Existing BULK positions are settled before this change. They are not carried across the split or automatically replaced with new positions. ## What traders should do * Review SNDK-USD exposure and wind down positions ahead of settlement if you prefer to close them yourself. * Account for the closure when managing hedges or strategies that trade SNDK-USD. * After reopening, submit fresh orders using post-split prices and quantities. # Design Philosophy Source: https://docs.bulk.trade/design-panorama The architectural principles and design goals behind BULK Exchange. ## Mission BULK Exchange is designed to close the performance gap between centralized and decentralized trading venues. The goal is not incremental improvement but a fundamentally different execution environment - one that delivers colocation-grade speed with cryptographic guarantees that no centralized venue can offer. ## Design Goals **Low-Latency Matching and Propagation.** Achieve matching plus propagation latency in the 5-20ms range within regional validator sets. **Leaderless Decentralization.** No single point of failure, no leader-based block production, no centralized sequencer. Every consensus round is leaderless - no single validator can censor or reorder transactions. **Verifiable and Permissionless.** The entire system state is cryptographically verifiable. Validator participation is open and secured by economic stake inherited from Solana. **High-Performance Order Book.** Infrastructure for internet-scale capital markets, with throughput far beyond current on-chain systems. ## Core Architecture BULK is an L0 - a specialized execution layer that runs natively alongside Solana. Each BULK validator runs a dedicated binary (`bulk-agave`) alongside the standard Solana/Agave validator, inheriting its identity keys with proportional stake weight. BULK validators form their own consensus network while Solana handles deposits, withdrawals, and asset custody. The architecture separates concerns cleanly: * **BULK Net** - Authenticated transport layer for validator-to-validator communication. Transactions are broadcast, deduplicated, and disseminated across the validator set. * **BULKBFT Consensus** - Leaderless Byzantine fault-tolerant consensus with a fast path that completes in a single vote-commit round under partial synchrony. Validators exchange compact sketches, reconcile transaction sets via minisketch, and commit batches that a supermajority agrees on. * **Executor** - Deterministic execution engine. Every validator processes the identical committed batch through the identical matching engine and produces the identical output state. * **Solana Ledger** - Settlement layer. Deposits and withdrawals are settled on Solana. Assets remain in Solana custody throughout. ## Fair Ordering BULK does not use FIFO ordering. Instead, it employs a multi-layered fairness design that prevents any single participant from controlling transaction ordering: 1. **Quorum-controlled batch admission.** The transaction set in each batch is the intersection of pending sets across a supermajority of validators, computed via minisketch reconciliation. No single validator controls what enters the batch. 2. **Deterministic shuffle.** After commitment, transactions are shuffled using a Fisher-Yates algorithm seeded by the consensus-derived batch timestamp. The seed is a consensus output that no single validator can unilaterally determine. 3. **Structural priority queues.** After the shuffle, transactions are separated by type: cancels execute first, then post-only maker orders, then regular orders. This guarantees that traders can always cancel before being filled and makers always seed the book before takers cross it. 4. **Price-time priority on the book.** The order book itself uses standard price-time priority for matching. The combination of quorum-controlled admission, consensus-derived shuffle, and structural priority provides fairness guarantees that no ordering manipulation can circumvent. ## Regional Books BULK uses regional validator subsets to achieve low latency - the same architecture used by TradFi venues that process trillions in derivatives volume. Each region runs BULKBFT consensus among geographically close validators where sub-20ms round trips are achievable. When local liquidity is insufficient, orders route cross-region at higher latency. See BIP-2 (coming soon) for the full regional books specification. ## Censorship Resistance Censorship resistance is the most critical property a decentralized application must offer. Without it, the system is self-custody with centralized execution. BULK's architecture ensures censorship resistance through: * **Leaderless consensus** - No single validator proposes blocks or controls ordering. * **Quorum inclusion** - Transaction inclusion requires supermajority agreement, not a single sequencer's decision. * **Deterministic execution** - Every validator produces the same output from the same input. Any attempt to alter execution is immediately detectable by any observer. * **No bridges, no sequencers** - Eliminates entire categories of centralization risks that affect L2 and cross-chain systems. ## Risk Infrastructure BULK integrates a real-time risk engine directly into the execution pipeline. Portfolio margin combines correlation-aware risk, regime-adaptive lambda surfaces, closeout-impact reserves, and portfolio-level liquidation optimization. See the [Margin](/bulk-exchange/Margin), [Liquidations](/bulk-exchange/Liquidations), and [Real-Time Risk Engine](/architecture/risk-engine) pages for details. # Introduction Source: https://docs.bulk.trade/index ![Bulk Exchange](https://mintcdn.com/bulklabs/9fBmpzP5LCYGXyLN/images/stock.png?fit=max\&auto=format\&n=9fBmpzP5LCYGXyLN\&q=85\&s=415fbd00375a83a4d779221e786aecc9) The evolution of decentralized finance (DeFi) has reached a critical inflection point. While the core primitives of lending, swapping, and asset custody have matured, the performance frontier of on-chain trading remains significantly behind its centralized counterparts.\ \ This performance deficit, particularly in the realm of high-frequency orderbook trading, represents the single largest barrier to onboarding the full scale of internet capital markets into the decentralized ecosystem.\ \ BULK Exchange is engineered from first principles to solve this challenge, delivering a novel execution architecture capable of 5-20ms matching and propagation latency within regional validator sets, without compromising the foundational tenets of decentralization, censorship resistance, and permissionless access. # Portfolio Margin Calculator Source: https://docs.bulk.trade/misc/margin-calculator Interactive portfolio margin calculator with real risk surfaces across all regimes. | > [!TIP] > > Collateral (USDC) > [!TIP] > > Regime > [!TIP] > > Positions Market Side Size Mark Price Value * Add Position *** ## How It Works Calculator implements the portfolio margin formulas from [Margin](/bulk-exchange/Margin) using risk surface data fetched live from the APIs. **Risk surfaces**: Fetches the full risk surface for every listed market via [`GET /riskSurfaces`](https://docs.bulk.trade/api-reference/getRiskSurfaces). Each response contains all 9 regime surfaces (the complete 2D lambda grid of notional x leverage knots with `mmrO`, `mmrE`, `p` triplets), plus pair correlations and the asset's current live regime. You can query this endpoint directly to build your own margin tooling. **Time decay**: Each grid point contains three values. The effective lambda at time $t$ into the current regime is: $$ \lambda(t) = \lambda_E + (\lambda_O - \lambda_E) \cdot p^t $$ Where $\lambda_O$ is the start-of-regime value, $\lambda_E$ is the equilibrium value, and $p$ is the transition probability. The calculator uses the live `regimeDt` from the WebSocket ticker stream for time decay. **Live prices**: Mark prices stream via WebSocket from the `ticker` and `frontendContext` subscriptions. **Correlation matrix**: Pair correlations are returned by the risk surfaces endpoint. The correlation between assets $i$ and $j$ is $\rho_{ij}$, used in both the effective notional and portfolio margin calculations. **Regime sensitivity**: The risk surfaces have a 2% floor for small positions. Regime differentiation in lambda values becomes visible at higher notional values (roughly \$750k+ for BTC) and portfolio leverage (4-5x+). At these sizes, bear and bull regimes can produce significantly different margin requirements. The margin calculation pipeline: 1. **Signed notional** - $sN_i = \text{sign}(Q_i) \cdot |Q_i| \cdot P_i$ 2. **Effective notional** - $N_{\text{eff}} = \sqrt{\sum_i sN_i^2 + 2\sum_{i \lt j} sN_i \cdot sN_j \cdot \rho_{ij}}$ 3. **Portfolio leverage** - $L = N_{\text{eff}} / C$ 4. **Lambda lookup** - bilinear interpolation on the 2D surface (notional x leverage knots) with time decay 5. **Portfolio margin** - $M_p = \sqrt{\sum_i M_i^2 + 2\sum_{i \lt j} M_i \cdot M_j \cdot \rho_{ij}}$ # Paper Trading Competition Source: https://docs.bulk.trade/misc/paper-trading-comp The first ever BULK Trading Competition. $50,000 paper-trading prize pool, ranked by Skill Score. > [!NOTE] > > **The first ever BULK Trading Competition is live.** Paper trading only. \$50,000 prize pool. Free and open to all. Trade from [early.bulk.trade](https://early.bulk.trade). ## At a Glance > [card] Prize Pool > > **\$50,000** total, paid to the **Top 50** finishers. > [card] Metric > > **Skill Score** = Realized PnL × √(Effective Capital). > [card] Window > > **19 May 2026** to **28 May 2026 13:00 UTC** snapshot. > [card] Cost > > Free. Paper trading. Just claim the faucet and trade. ## How to Enter **1. Connect** Head to [early.bulk.trade](https://early.bulk.trade) and connect your wallet. **2. Claim the faucet (master account only)** Your **master account** can claim **1,000** of paper quote currency every **72 hours**. **Sub-accounts cannot claim the faucet directly**. Fund them by transferring margin from your master. **3. Trade across your 10 accounts** You get **1 main account + up to 9 sub-accounts** = 10 leaderboard slots per wallet. Spin them up from the app. **4. Realize your PnL** Only realized PnL counts. Open positions update unrealized PnL but do not move you on the leaderboard until you close. ## How Ranking Works Each account is ranked by **Skill Score**, defined as: ``` Skill Score = Realized PnL × sqrt(Effective Capital) ``` The score rewards two things at once: **how much you actually earned** (Realized PnL) and **the size you were trading at** (Effective Capital). The square root softens the size component so a trader at one tenth the bankroll is not crushed. ### Realized PnL The numerator is your **net realized PnL** since competition start. | Included | Excluded | | - | - | | Voluntary position closes | Unrealized PnL on open positions | | Liquidation fills (typically negative) | Funding payments (settle on account, ignored by leaderboard) | | ADL fills (positive on the winning side, negative on the deleveraged side) | Faucet claims and account transfers (these are not trading PnL) | | **Trading fees actually paid** are subtracted from PnL | | In other words: only what came from closing positions counts, with the actual fees you paid deducted. Funding sits outside the metric. ### Effective Capital The multiplier is the **size you were actually trading at**, not the size of your bankroll. It is defined as the smaller of two numbers: ``` Effective Capital = min( p95(notional in open positions), peak equity ) ``` | Term | What it captures | | | | - | - | - | - | | **Notional in open positions** | The sum of \` | qty | × price\` across all your open positions, sampled every minute while you have at least one position open, plus one sample at every position close. We then take the **95th percentile** of those samples. This is the position size you sustained, not a brief spike. | | **Peak equity** | The highest your account value (`margin balance + unrealized PnL`) ever reached during the comp. This is what your account was actually worth at its best moment. | | | The `min()` is the important part. Whichever of the two is smaller is the one that counts. > [!TIP] > > **Why two caps.** The 95th-percentile of notional rejects "I leveraged to 50x for 30 seconds to inflate my multiplier" stunts. The peak-equity cap rejects "I claimed faucet 4 times to inflate my Capital Deposited" stunts and also bounds how much leverage can carry a small bankroll. Together they make the metric robust without filtering anyone off the board. ### Why this design | Behaviour | Score outcome | | - | - | | Trade $1k bankroll into $10k peak position size, book \$25k PnL | **Effective Capital = \$10k** (the deployed size). Score = 25,000 × √10,000 = \~2.5M. Compounding your own winnings into bigger size is rewarded. | | Hold a $10 sub-account, scalp it sustained, book $490 PnL | **Effective Capital = \$10**. Score = 490 × √10 = \~1,549. Visible on the leaderboard, ranked honestly for what it is. | | Claim faucet 4 times, never open a position | **Effective Capital = 0** (no positions = no notional samples). Score = 0. Faucet stacking does nothing. | | $1k bankroll, open a $50k notional spike for 30 seconds, no real PnL | **Effective Capital ≤ \$1k** (peak equity caps the multiplier at the bankroll you actually had). Score collapses on its own. | | $50k bankroll, deploy $40k notional, book \$25k PnL | **Effective Capital = \$40k**. Score = 25,000 × √40,000 = \~5M. Bigger real capital deployed beats smaller real capital deployed for the same PnL. | ### Worked example: compounding from a small seed A trader deposits **$1,000** of faucet, trades it into open profits that grow the account to **$26,000** in equity over the comp, with **\$10,000** of notional in open positions at peak. ``` Realized PnL = $25,000 (after subtracting fees actually paid) p95 of notional-while-positioned = $10,000 (sustained peak size) Peak equity = $26,000 Effective Capital = min($10k, $26k) = $10,000 Skill Score = 25,000 × sqrt(10,000) = 2,500,000 ``` The seed of \$1k does not bound the score. The trader compounded their own winnings back into risk and the metric credits them for the size they actually traded at. ## Leaderboard Rules ### What counts * Only **closed positions** contribute to your Skill Score. Unrealized PnL on open positions does not move you on the leaderboard. * **Trading fees actually paid are deducted** from your Realized PnL. **Funding payments are excluded** from the metric (they still settle on your account). * **Liquidation and ADL fills count** as realized PnL. The deleveraged side takes the loss; the winning counterparty books the realised gain. * Each **sub-account is ranked independently** during the competition. You can see all of your accounts on the live leaderboard. * **Every wallet is ranked.** There is no minimum-activity floor. Wallets with no realized fills land at Skill Score = 0 at the bottom. * Updates run on a **15-minute delay** and only refresh after a realized fill on the account. ### Top-50 dedup (applied at snapshot) Only the **single highest-ranked account per wallet** counts toward final rankings. Your other accounts are removed from the snapshot, and lower-ranked traders move up to fill the freed slots. **Example 1.** You finish with 3 accounts inside the live Top 50. Your highest placement stays; the other 2 are removed. Two traders below the cut move into the Top 50. **Example 2.** You finish 60th on the live board. 13 duplicate accounts ahead of you get removed during dedup. You move up to 47th, inside the prize-paying Top 50. ### Snapshot * **Snapshot time**: **28 May 2026, 13:00 UTC**. * Positions are **not** auto-closed at snapshot. * The leaderboard runs on a 15-minute delay, so **close any trades you want counted by 12:30 UTC** to be safe. * Final, deduped rankings are posted to Discord and Telegram after the snapshot. ### Fair play We have not found evidence of exploits so far, but any account caught gaming loopholes will be **removed from the leaderboard** at our discretion. Wash trading, collusion, and manipulation of the realized-PnL metric all qualify for removal. ## Prize Breakdown Total prize pool: **\$50,000**. | Place | Prize | Place | Prize | | - | - | - | - | | 1st | \$15,000 | 11th to 19th | \$500 each | | 2nd | \$10,000 | 20th to 29th | \$300 each | | 3rd | \$5,000 | 30th to 39th | \$150 each | | 4th | \$2,500 | 40th to 50th | \$100 each | | 5th | \$2,000 | | | | 6th | \$1,500 | | | | 7th | \$1,200 | | | | 8th | \$1,000 | | | | 9th | \$900 | | | | 10th | \$800 | | | ## Eligibility * **Open to everyone.** No KYC, no entry fee. * **One wallet, ten accounts, one final placement** (after dedup). * Accounts created after the snapshot do not qualify. ## Useful Links > [card] [Trade Now](https://early.bulk.trade) > > The competition runs on [early.bulk.trade](https://early.bulk.trade). > [card] [Announcement](https://x.com/bulktrade/status/2054959833032380418) > > Original BULK X (Twitter) announcement. # Getting Started Source: https://docs.bulk.trade/validators/getting-started How to run a BULK Network validator. > [!NOTE] > > Coming soon. # Rewards Source: https://docs.bulk.trade/validators/rewards How validators earn a share of exchange fees on the BULK Network. ## Overview Validators earn **12.5% of all trading fees**. Each settled fee credits that share to the validator reward pool, and the pool is distributed every consensus epoch - roughly 5 seconds of consensus rounds. Each validator's share is set by a consensus-agreed weight with three components: | Component | Weight | What It Rewards | | - | - | - | | Origination | 50% | Sourcing fee-generating order flow - being the first to deliver fills that add value to the validator reward pool | | Participation | 40% | Doing the consensus work - voting with the committed quorum, round after round | | Stake | 10% | Solana stake backing the validator | ## The Weight Vector Each epoch assigns every validator $v_j$ in the epoch's active set of $n$ validators a reward weight $w_j \in [0, 1]$. The weight is a direct share of the pool: $$ \text{reward}_j = \text{pool} \times w_j $$ The weight vector has two properties: * **Deterministic.** Weights are computed from committed ledger data only, using integer fixed-point arithmetic in parts-per-million (ppm). Every validator derives byte-identical weights, so any mismatch is immediately detectable, like any other execution divergence. * **Conservative.** Weights sum to at most 1. Credit that cannot be attributed cleanly - unknown source, self-reports, validators outside the active set - is burned, never redistributed to other validators. The undistributed remainder of the pool stays in the pool account and carries into later epochs. ## Origination Origination rewards the validator that *sourced* fee-generating order flow. When a transaction first arrives at the network - via a validator's HTTP or WebSocket ingress - downstream validators remember which peer first delivered it to them. If that transaction later produces a fill that adds value to the validator reward pool, the exact positive pool contribution is attributed to that peer. **Origination credit is earned only for the exact positive atoms the fill added to the validator reward pool.** A fill that adds zero atoms - because it paid no fee, its fee funded a maker rebate, or it otherwise did not fund the pool - earns no origination credit. Attribution is **peer-witnessed**. Each validator $v_i$ reports, once per epoch in a signed record, how many positive reward-pool atoms came from fills whose transactions it first heard from each peer: $$ f_i[j] = \frac{A_i[j]}{T_i} $$ where $A_i[j]$ is the exact number of positive reward-pool atoms validator $i$ attributes to transactions first heard from validator $j$, and $T_i$ is the total positive reward-pool contribution validator $i$ observed that epoch, including unattributed atoms. The origination weight averages these rows across all $n$ validators: $$ w_j^{\text{orig}} = \frac{1}{n} \sum_{i \neq j} f_i[j] $$ Self-reports are burned: a validator's claims about its own volume never count - only what its peers witnessed. A dishonest reporter cannot raise its own weight, and can shift any peer's weight by at most $1/n$. A validator that reports nothing contributes an all-zero row while the divisor stays $n$, so a missing report shrinks total credit rather than shifting it. Positive pool atoms with no attributable source remain in $T_i$ but are assigned to nobody, preventing unknown flow from being redistributed to named peers. ## Participation Participation rewards consensus liveness. For each committed round, validator $i$ credits every peer whose commit vote matched a digest $i$ itself committed. Per epoch: $$ w_j^{\text{part}} = \frac{1}{n(n-1)} \sum_{i \neq j} \frac{P_i[j]}{Q_i} $$ where $P_i[j]$ counts the rounds in which validator $i$ observed $j$ voting with the committed quorum, out of the $Q_i$ rounds $i$ committed that epoch. A fully live validator set splits the participation share equally; a validator that is slow, frequently in the minority, or offline loses exactly the fraction of rounds it missed. ## Stake The stake component is a linear share of Solana stake: $$ w_j^{\text{stake}} = \frac{s_j}{\sum_{k} s_k} $$ where $s_j$ is validator $j$'s Solana stake, read at finalized commitment from the co-located Agave validator (see [Stake Inheritance](/architecture/overview#stake-inheritance)), and the sum runs over the epoch's pinned active set. Stake is pinned once per epoch, so mid-epoch stake changes take effect at the next epoch boundary. ## Blending The final weight sums the three components in their protocol-fixed proportions: $$ w_j = 0.50 \cdot w_j^{\text{orig}} + 0.40 \cdot w_j^{\text{part}} + 0.10 \cdot w_j^{\text{stake}} $$ The blend constants are protocol parameters, identical on every validator. ## Epochs and Settlement * **Epoch length:** \~5 seconds of consensus rounds. * **Reporting:** each validator's origination and participation rows are included in its signed epoch [beacon transaction](/architecture/timestamps#beacon-pll-phase-locked-loop) - the same per-epoch transaction that carries the validator's clock beacon - so the raw inputs are themselves committed, tamper-evident ledger data. * **Settlement lag:** epoch $N$ settles two epochs later (\~10 seconds), giving every beacon time to commit and propagate. Settlement uses the validator set and stake pinned at epoch $N$, not the live set. * **Payout:** a system settlement transaction anchors the payout point in committed order. On applying it, every validator derives the same weights from the same committed rows and credits the same amounts from the pool into each validator's exchange account. There is no claim transaction. Rewards land automatically in the validator's exchange account at settlement, in USDC - a regular balance, transferable via [native transfer](/architecture/transfers) or withdrawable to Solana. Each epoch settles independently: rewards are earned for what a validator did that epoch, not accrued against a running total. ## Auditability The entire reward computation is reproducible from the committed ledger alone: attribution rows are committed in beacon transactions, the validator set and stake are committed state, and the weight computation is a pure function of that data. An external observer can re-derive every credit. Validators can inspect reward state live via the `/status` endpoint: | Field | Meaning | | - | - | | `settled_weights` | The consensus-agreed weight vector `(pubkey, ppm)` for the last settled epoch - identical bytes on every validator | | `settled_weight_epoch` | Which epoch the weights describe | | `epoch_attributed` | Positive reward-pool atoms this validator attributed to peers in the current epoch | | `epoch_unattributed` | Positive reward-pool atoms with no attributable source (burned; should sit near zero) | Comparing `settled_weights` across validators is the standing health check for reward accounting.