For the complete documentation index, see llms.txt. This page is also available as Markdown.

websocket

Perpl provides two WebSocket endpoints for real-time data.

Endpoints

Endpoint
Purpose
Authentication

/ws/v1/market-data

Public market data

None

/ws/v1/trading

Trading & account data

Required

URLs (configurable via PERPL_WS_URL, default: wss://app.perpl.xyz):

  • Market Data: ${PERPL_WS_URL}/ws/v1/market-data

  • Trading: ${PERPL_WS_URL}/ws/v1/trading

Message Format

All messages are JSON with a common header:

interface MessageHeader {
  mt: number;       // Message type
  sid?: number;     // Subscription ID
  sn?: number;      // Sequence number
  cid?: number;     // Correlation ID
  ses?: string;     // Session ID
}

Message Types

Value
Name
Direction

1

Ping

Client → Server

2

Pong

Server → Client

3

StatusResponse

Server → Client

5

SubscriptionRequest

Client → Server

6

SubscriptionResponse

Server → Client

7

GasPriceUpdate

Server → Client

8

MarketConfigUpdate

Server → Client

9

MarketStateUpdate

Server → Client

10

MarketFundingUpdate

Server → Client

11

CandlesSnapshot

Server → Client

12

CandlesUpdate

Server → Client

15

L2BookSnapshot

Server → Client

16

L2BookUpdate

Server → Client

17

TradesSnapshot

Server → Client

18

TradesUpdate

Server → Client

19

WalletSnapshot

Server → Client

20

WalletUpdate

Server → Client

21

AccountUpdate

Server → Client

22

OrderRequest

Client → Server

23

OrdersSnapshot

Server → Client

24

OrdersUpdate

Server → Client

25

FillsUpdate

Server → Client

26

PositionsSnapshot

Server → Client

27

PositionsUpdate

Server → Client

28

AccountStatsUpdate

Server → Client

29

ApiKeySignIn

Client → Server

30

BatchOrderRequest

HTTP only

31

BatchStatusResponse

HTTP only

100

Heartbeat

Server → Client

30 / 31 are allocated across both transports, but the WebSocket connection does not currently accept a batch frame: it is the body and answer of POST /v1/trading/orders. Over this connection, submit orders one OrderRequest (mt: 22) at a time — a socket already pipelines them without paying a round trip each.


Market Data WebSocket

Connecting

Available Streams

Stream
Format
Description

heartbeat

heartbeat@<chain_id>

Block sync heartbeat

gas-stats

gas-stats@<chain_id>

Gas price updates

market-config

market-config@<chain_id>

Market configuration

market-state

market-state@<chain_id>

Prices, volume, OI

funding

funding@<chain_id>

Funding rate updates (see FundingEvent: two messages per interval, keyed by feb)

candles

candles@<market_id>*<resolution>

OHLCV candles

order-book

order-book@<market_id>

L2 order book

trades

trades@<market_id>

Recent trades

Chain ID: Configurable via PERPL_CHAIN_ID (default: 143 for Monad Mainnet)

Candle Resolutions (seconds): 60, 300, 900, 1800, 3600, 7200, 14400, 28800, 43200, 86400

Subscribing

The market-data server allows 16 subscriptions and 10 requests/min per connection — lower than the trading server, and the same on testnet and mainnet. Batch multiple streams into one mt: 5 frame rather than sending one per stream.

Subscription Response

Failures here are per-subscription, not per-connection — the socket stays open and the other entries in the same request still succeed. Check status.code on every element rather than assuming the whole batch applied:

code

error

Recovery

429

too many subscriptions

Subscription cap reached; unsubscribe from a stream and retry

404

unknown stream

Bad stream name or market ID; fix the identifier

Order Book Messages

Snapshot (mt: 15):

Update (mt: 16):

Same structure. Price levels with o: 0 should be removed.

The opening snapshot is also served over HTTP — see GET /v1/market-data/:market_id/book. Subscribe here if you are tracking the book; call the endpoint if you want it once.

Trade Messages

Snapshot (mt: 17):

Update (mt: 18):

Same structure, contains new trades.

Candle Messages

Snapshot (mt: 11):

Update (mt: 12):

Contains up to 2 candles: previous (closed) and current (updated).

Market State Update (mt: 9)

The same state is served over HTTP, keyed the same way — see GET /v1/market-data/:market_id/ticker for one market and GET /v1/market-data/ticker for all of them.

Heartbeat (mt: 100)


Trading WebSocket

Connecting & Authenticating

The primary way to authenticate the trading WebSocket is API-key sign-in (mt: 29). API keys are Ed25519 key pairs created at the web UI (https://app.perpl.xyz/apikeys for mainnet, https://testnet.perpl.xyz/apikeys for testnet) or programmatically (see Integrations). Placing orders requires a trade-scoped key — a read-scoped key still receives snapshots/updates, but its OrderRequest frames are rejected with 403.

API-key sign-in (mt: 29)

Send an ApiKeySignIn frame as the first message after the socket opens, and send it promptly — the sign-in frame must arrive within the server's idle timeout (5s on mainnet, 10s on testnet) or the connection is closed with 1008 (idle timeout).

The Ed25519 signature covers the WS canonical string — four fields joined by \n (newline):

Frame shape:

Initial Snapshots

After authentication, you receive snapshots:

1

WalletSnapshot (mt: 19)

Wallet and account balances.

2

OrdersSnapshot (mt: 23)

Open orders.

3

PositionsSnapshot (mt: 26)

Open positions.

The WalletSnapshot includes a sequence number (sn from MessageHeader) that serves as the starting point for sequence tracking. Store this value and use it to validate subsequent heartbeat sequence numbers (see Heartbeat).

Each of these three snapshots is also served over HTTP, in the identical shape, for a client that wants the state once rather than following it — see Trading State Endpoints. Opening a connection purely to read a snapshot and closing it is the pattern those endpoints replace.

Placing Orders

bf is only valid on a builder-bound API key, and only up to the ceiling that key was enrolled with; the builder code itself comes from the key, never from the request. See Integrations → Builder codes.

The fields above the message header — everything from rq down — are an OrderSpec, which is also what POST /v1/trading/orders accepts for a client whose flow does not justify holding a connection open. Everything in this section — the delivery semantics, request-ID rules, retries and trigger-order behaviour — applies identically on that transport; the exchange cannot tell the two apart.

Delivery Semantics & Idempotency

rq (Request ID) is an idempotency key scoped per account. The server guarantees at-most-once execution per rq.

The Request ID is equivalent to a client order id on non-dex exchanges (applicable only for orders sent via API, not for direct on-chain transactions).

Multiple requests via the API with the same Request ID only results in a single execution.

For smart contract / SDK users placing non API orders the value maybe set to anything to identify the order and is non-unique.

Request ID generation

rq must be strictly increasing. The server tracks the last processed ID as lfr on the Account object (in WalletSnapshot mt: 19 and AccountUpdate mt: 21).

1

Seed the local counter

Seed local counter from account.lfr on connect to trading websocket.

2

Generate each request ID

For each order: rq = max(localCounter, account.lfr) + 1

Submitting rq <= lfr fails with sr: 32 (OrderDescIdTooLow).

Retries

Client side is responsible for retries and should follow the following rules:

1

Retry with the original RequestID

Retry with original RequestID:

  • Before receiving any status update for the original request

  • Before LastExecBlock expiration

2

Retry with a new RequestID

Retry with new RequestID only when:

  • Failure status received for the original request

  • Current known block (eg. Heartbeat.h) is greater or equal to LastExecBlock of the original request and no status updates were received - only if all block updates / heartbeats after order posting were observed (i.e. there were no reconnections)

For each RequestID, multiple Order messages with status updates can be received. Client side is responsible for deduplication of these messages, processing only:

  • The first failure message if all received messages are failures (OrderStatusFailed)

  • The first non-failure message received (OrderStatusOpen, OrderStatusPartiallyFilled, OrderStatusFilled, OrderStatusCanceled, OrderStatusUntriggered, OrderStatusTriggered, OrderStatusExecuted)

Scenario
Action

No status received yet, lb not expired

Retry with same rq

sr: 32 (OrderDescIdTooLow)

Retry once with new rq (common with multiple clients/tabs)

Head block ≥ lb, no status received, no reconnections since posting

Retry with new rq

Client-side deduplication

Multiple updates may arrive for a single rq:

  • First non-failure status (st: 2–5, 8, 9, 10) is definitive — ignore everything after, including later failures

  • If only failures (st: 7) arrive, process the first one only

  • After retrying with a new rq, ignore late failures from the old rq

Trigger Orders

  • Set lb: 0 on trigger orders. A non-zero lb is ignored after admission — each execution attempt gets a server-assigned window — but a stale value (lb <= head) is still rejected with last exec block already expired. Trigger lifetime is governed by tif, the trigger condition, and the tr/lp links.

  • tp + tpc: The order will not be posted until the market last price crosses the trigger price according to the condition (GTE or LTE).

  • tr: Links this trigger order to another request. When the linked request results in a trade, the trigger activates; when it fails, the trigger is cancelled. If the linked request places an order, this trigger links to that order — activating when it fills, cancelling when it is cancelled.

  • lp: Links the trigger order to a position. The trigger is cancelled when the position is closed or inverted.

Order Types

Value
Name

1

OpenLong

2

OpenShort

3

CloseLong

4

CloseShort

5

Cancel

6

IncreasePositionCollateral

7

Change

Order Flags

Value
Name

0

GoodTillCancel

1

PostOnly

2

FillOrKill

4

ImmediateOrCancel

Last execution block (lb)

  • lb: 0 is legal on any order type, not just triggers. The server substitutes the market's maximum window.

  • A non-zero lb must be > head, on every order type — 0 < lb <= head is rejected with last exec block already expired.

  • The ceiling is head + market.order_ttl_blocks (see the rejection table below for the exact condition).

  • The server also clamps lb down to that ceiling — you cannot buy a longer validity window than the market allows, and a value that passed admission can still be shortened.

  • order_ttl_blocks is per-market and subject to change — read it from /api/v1/pub/context or mt: 8 at runtime, never hardcode it.

Negative PnL collateralization (mnp)

Filling an order can require collateralizing the unrealized negative PnL of the position it results in — the loss that position already carries against the mark price. mnp is your upper bound on that, in basis points of the resulting position's notional. A match that would need more is not filled: the order comes back on mt: 24 with fr: 8 (ExceedsMaxNegPnlCollat).

  • The limit is measured against the whole resulting position, not against this order's own size. Adding 0.5 BTC at $100,000 to an existing 2.0 BTC position gives a notional of $250,000, so mnp: 1000 (10%) allows $25,000 of negative PnL to be collateralized — not 10% of the $50,000 the order itself is worth.

  • Values above 10000 are meaningful, not errors: 10000 is 100% of the notional, 30000 is three times it. At the 65535 ceiling roughly 6.5x the position's notional can be taken from the account as collateral to fill one match — size the value deliberately rather than defaulting it upward.

  • Omitting mnp is not the same as sending 0. Omit the field to take the market default, order_max_neg_pnl_collat_bps from /api/v1/pub/context. Send an explicit 0 to refuse any fill that would collateralize negative PnL at all.

  • Range is 0..65535; a larger value is rejected with code: 400 (see the rejection table below). mnp is an unsigned field — a negative number is not a range error but an unparseable frame, and closes the connection with 1011.

  • The check only runs on a fill that creates, increases or inverts a position. A purely reducing fill — a CloseLong/CloseShort, or an opposing Open* that only shrinks the position — never collateralizes negative PnL, so it can never come back with fr: 8 regardless of mnp. Reducing realizes PnL on the closed portion at the fill price instead: it is paid out or collected there and then, and the exposure it belonged to is gone, so there is nothing left to pre-fund against the mark price. Close* orders are reduce-only and are clamped to the position size, so they can never fall through to the inverting case. A reducing fill has its own failure modes — fr: 6 (NegativePositionValue) and fr: 5 (PerpetualSolvency) — but not fr: 8.

  • order_max_neg_pnl_collat_bps is per-market and subject to change — read it from /api/v1/pub/context at runtime rather than hardcoding it. It is not carried on the mt: 8 market-config stream, which publishes MarketConfig only.

As taker

The order is one settlement against the size-weighted average of its fills, so there is one verdict for the whole order:

  • The price used is the average fill price — Σ(price × size) / Σ(size) over every match — rounded in the direction that widens the allowance slightly, so the effective limit can be marginally above the exact arithmetic.

  • Exceeding the limit fails the entire order: nothing is filled — the whole settlement is unwound, including every match it had already made — and you get one mt: 24 with st: 7 (Failed), sr: 44 (TakerOrderSettlementFailed) and fr: 8. There is no partial fill up to the limit.

As maker

A resting order is settled once per match, against its own price, using the mnp it was posted with:

  • The price used is the resting order's own limit price, exactly — there is no averaging and no rounding, because the maker fills at the price it named.

  • The limit read is the one stored on the resting order at post time. The taker's mnp has no bearing on the maker's side of the fill, and vice versa: each side is checked against its own value.

  • The check is evaluated at fill time against the current mark price, while the price the order is valued at was fixed when it was posted. A resting order is therefore far more exposed to this rejection than a taker: the longer it waits and the further the mark price drifts away from its limit price, the larger the negative PnL a fill would have to collateralize. An mnp that was comfortable at post time can be exceeded by the time the order is hit.

  • Exceeding the limit removes the whole resting order from the book, not just the matched portion. The remaining unfilled size is gone, the order lock is released, and the order-recycling fee paid when it was posted is forfeited to the taker (or to the protocol on a forwarded taker order). You get mt: 24 with st: 7 (Failed), sr: 23 (MakerOrderSettlementFailed) and fr: 8. Repost if you still want the exposure — there is no partial survivor to amend.

  • The taker that hit you is not penalized. Matching skips the cleared order and continues into the next resting order at that price level, so the taker may still fill in full from other inventory.

  • On a partial fill that does settle, the remainder stays on the book with the same mnp, and each subsequent match is checked again independently.

Cancel, IncreasePositionCollateral and Change

mnp is recorded when an order is posted and read when that order is matched. The three non-matching order types do neither, so they never read it:

  • Cancel (t: 5) removes an order. It has nothing to match and no position to value, so mnp is ignored.

  • IncreasePositionCollateral (t: 6) moves collateral from your account balance into an existing position's deposit. It never matches, so mnp is ignored. Note that it does reduce your free account balance, which is what a later fill draws on to collateralize negative PnL — so adding margin this way can make a subsequent fill fail on balance (fr: 1/2/3) rather than on fr: 8.

  • Change (t: 7) amends price, size and expiry block only. It cannot change mnp: an mnp sent alongside a change is accepted and validated for range, then ignored, and the resting order keeps the value it was originally posted with. To change the limit, cancel the order and post a new one. This matters when repricing — moving a resting order closer to the mark does not relax the limit it will be filled under.

Sending mnp on any of these three is harmless: it is range-checked like every other order type (mnp > 65535 is a code: 400) and then discarded.

Trigger orders

Trigger orders carry mnp too. The value is recorded when the trigger is placed and applied to the order the trigger forwards when it fires — which is then subject to the taker or maker rules above depending on how that order executes. It is not re-read or re-defaulted at fire time, so a trigger placed while the market default was one value keeps that value even if the market default changes in between.

Example - Open Long

Input Validation

Recommended for production:

  • size > 0 - Reject zero or negative sizes.

  • leverage within market limits - Check MarketConfig.initial_margin (e.g., 1000 = 10% = max 10x).

  • marketId is valid - Verify against /api/v1/pub/context markets.

  • price > 0 for limit orders, price = 0 for market (IOC).

  • lb is 0, or satisfies head < lb <= head + market.order_ttl_blocks where head is the latest Heartbeat.h (see Last execution block above).

  • mnp is omitted, or 0 <= mnp <= 65535 — send it only when the market default is not what you want (see Negative PnL collateralization above).

  • WebSocket is connected - Check ws.readyState === WebSocket.OPEN.

Example - Cancel Order

Command Status (mt: 3)

Every mt: 22 frame receives exactly one StatusResponse (mt: 3) on the sid: 100 command-status stream. It reports whether the gateway accepted the frame — not what happened to the order.

code: 0 means accepted for forwarding — not posted, not filled. The order's real outcome arrives later on the mt: 24 OrdersUpdate stream. A non-zero code means the gateway rejected the frame before it reached the chain, and no mt: 24 message will ever follow for it.

Correlation: cid echoes the sn from your outbound frame, not rq, and is omitted whenever it would be zero. Set a unique non-zero sn on every mt: 22 frame — without one, neither acknowledgements nor rejections can be matched to the order that caused them.

Rejection reasons (non-zero code):

error

Condition

code

order already expired

tif > 0 && tif <= head

400

last exec block already expired

lb > 0 && lb <= head

400

last exec block too high

tp == 0 && lb > head + order_ttl_blocks

400

trigger price condition is not specified

tp > 0 && tpc == 0

400

order type is not provided / invalid order type

invalid t

400

builder fee not permitted for this api key

bf above the key's ceiling, or any bf on a non-builder key

400

max negative pnl collateralization out of range

mnp > 65535

400

api key lacks trade scope

read-scoped key

403

mt: 3 reports admission only; everything after arrives on mt: 24. Note sr: 14 (ExceedsLastExecutionBlock) and sr: 34 (OrderForwardingNotAllowed) can be produced without any transaction reaching the chain — do not treat them as evidence that a transaction was submitted.

Order Updates (mt: 24)

Orders with r: true should be removed from open orders.

An order the exchange refused to post or settle carries fr next to sr, giving the reason behind the refusal — insufficient collateral, a stale reference price, and so on. See OrderFailureReason. It is omitted on every event that is not such a failure.

Fill Updates (mt: 25)

Position Updates (mt: 27)

Account Updates (mt: 21)

An mt: 21 update is how a fee-tier change reaches you: the tier is reassigned in the background from trading volume, so re-read ft on every account update rather than caching it from the snapshot. See Fees & fee tiers.

It is also the only place a change to fw shows up — there is no on-chain getter for the flag and no AccountEvent for it, so re-read fw on every account update. A toggle from any other client of the same wallet lands here, and orders are rejected for as long as it is false. See Enabling Order Forwarding (One-Click Trading).

Account Stats (mt: 28)

AccountStatsUpdate (mt: 28) carries an AccountStats body — per-account trading statistics (see AccountStats).

Account stats are also delivered in the WalletSnapshot (mt: 19) via the wallet's sts? field.

Heartbeat (Trading)

On the trading WebSocket, sequence tracking requires special initialization:

1

Initialize the sequence number

Initialize lastSn from the sn field in the WalletSnapshot (mt: 19) received after authentication.

2

Validate each heartbeat

Each subsequent heartbeat must have sn === previousSn + 1.

3

Reconnect on a gap

On sequence gap (missed heartbeat), force reconnect — the gap means messages may have been lost.

Keep-Alive

Send periodic pings to keep the trading connection alive:

Application pings count toward the request budget on both servers. At 30s that is 2/min — negligible against the trading budget, but 20% of the market-data budget.

Market-data connections do not need mt: 1 at all: data arrives every block and the server keeps the socket alive at the protocol level. Reserve the budget for subscriptions. See Rate Limits.

Error Handling

Close Code 3401: Authentication failure

Reconnect and re-send a fresh signed ApiKeySignIn frame (new timestamp + nonce, re-signed) as the first message.

Close Code 1013: The client fell behind — its send buffer stayed full for the whole server I/O timeout and the connection was dropped. Reconnect after a pause and read frames off the socket into your own queue instead of processing them inline; resubscribing to the same firehose without that change reproduces it.

See WebSocket Close Codes for the full list.

Reconnection Strategy


Sequence Numbers

  • heartbeat and gas-stats streams have continuous sequence numbers.

  • Other streams may have gaps (e.g., when no activity).

  • Track sn to detect missed messages.

  • On gap detection, resubscribe to get fresh snapshot.