Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/Proof-labs/trading-sdk/llms.txt

Use this file to discover all available pages before exploring further.

The Proof Trading SDK exposes a set of strongly-typed query response interfaces that mirror the engine’s MessagePack wire format. Every type documented here is defined in src/types.ts and is returned directly by client query methods such as queryOrderbook, queryAccount, and queryMarketConfig. Numeric values carried as bigint preserve full precision for on-chain integers (prices in cents, balances in microUSDC, contract quantities); fields marked number are safely bounded integers such as market IDs and basis-point rates.

Orderbook

Aggregated order book snapshot for a market. Returned by client.queryOrderbook(marketId).
interface Orderbook {
  bids: OrderbookLevel[];
  asks: OrderbookLevel[];
}
bids
OrderbookLevel[]
required
Bid (buy) levels, sorted best (highest price) first.
asks
OrderbookLevel[]
required
Ask (sell) levels, sorted best (lowest price) first.

OrderbookLevel

A single aggregated price level in the order book.
interface OrderbookLevel {
  price: bigint;
  totalQty: bigint;
  orderCount: number;
}
price
bigint
required
Price in cents with 2 decimal places (e.g., 6675234n = $66,752.34).
totalQty
bigint
required
Total resting quantity at this level in integer contracts (lots).
orderCount
number
required
Number of individual resting orders at this level.

OpenOrder

A single resting order on the book. Returned by client.queryOpenOrders(address). Wire shape is a 6-tuple [id, market, owner, side, price, quantity].
interface OpenOrder {
  id: bigint;
  market: number;
  owner: Uint8Array;
  side: "Buy" | "Sell";
  price: bigint;
  quantity: bigint;
}
id
bigint
required
Engine-assigned order ID. Monotonically increasing within a market.
market
number
required
Market identifier.
owner
Uint8Array
required
20-byte owner address derived from the Ed25519 public key.
side
"Buy" | "Sell"
required
Order side: "Buy" for long, "Sell" for short.
price
bigint
required
Limit price in cents (2 decimal places).
quantity
bigint
required
Resting quantity in integer contracts.

AccountInfo

Full account snapshot including balance, open positions, and margin state. Returned by client.queryAccount(address). Wire shape is a positional MessagePack array; index numbers are stable for backward compatibility.
interface AccountInfo {
  balance: bigint;                          // [0]
  positions: PositionInfo[];                // [1]
  equity: bigint;                           // [2]
  totalMm: bigint;                          // [3]
  totalIm: bigint;                          // [4]
  marginRatioBps: bigint;                   // [5]
  bindingScenario?: BindingScenarioEntry[]; // [6]
  feesAccrued?: bigint;                     // [7]
  volume30dMicroUsdc?: bigint;              // [8]
}
balance
bigint
required
[0] Available USDC balance in microUSDC (6 decimal places). Example: 100_000_000_000n = $100,000.
positions
PositionInfo[]
required
[1] All open positions for this account. See PositionInfo below.
equity
bigint
required
[2] Total equity in microUSDC (balance + unrealized PnL). Scenario-aware: returns the worst-case equity across all active impact-market resolution outcomes.
totalMm
bigint
required
[3] Total maintenance margin requirement in microUSDC. Scenario-aware: returns the maximum MM across all resolution outcomes.
totalIm
bigint
required
[4] Total initial margin requirement in microUSDC.
marginRatioBps
bigint
required
[5] Current margin ratio in basis points (equity / total notional × 10,000).
bindingScenario
BindingScenarioEntry[]
[6] The resolution scenario that maximises totalMm — one entry per active impact market, ascending by impactMarketId. Empty for perp-only accounts. Absent on responses from gateways older than 2026-04-24.
feesAccrued
bigint
[7] Cumulative trading fees paid (positive) or rebates received (negative) in microUSDC. Updated atomically at fill time. New accounts read 0n. Absent on gateways predating 2026-05-03.
volume30dMicroUsdc
bigint
[8] Rolling 30-day taker volume in microUSDC at the account’s last volume update. Used by the engine to select the applicable fee tier before the next fill. Absent on older gateways.

PositionInfo

Information about a single open position. Fields [0]–[5] are raw engine state; fields [6]–[12] are response-only enrichments computed at query time. Indices are stable with the msgpack wire tuple.
interface PositionInfo {
  owner: Uint8Array;           // [0]
  market: number;              // [1]
  side: "Buy" | "Sell";        // [2]
  entryPrice: bigint;          // [3]
  size: bigint;                // [4]
  lastFundingIndex: bigint;    // [5]
  upnlNow?: bigint;            // [6]
  mmNow?: bigint;              // [7]
  imNow?: bigint;              // [8]
  pnlIfFires?: bigint;         // [9]
  pnlIfDies?: bigint;          // [10]
  fundingSince?: bigint;       // [11]
  adlScore?: bigint;           // [12]
}
owner
Uint8Array
required
[0] 20-byte owner address.
market
number
required
[1] Market identifier.
side
"Buy" | "Sell"
required
[2] Position side: "Buy" = long, "Sell" = short.
entryPrice
bigint
required
[3] Weighted-average entry price in cents (2 decimal places).
size
bigint
required
[4] Absolute position size in integer contracts.
lastFundingIndex
bigint
required
[5] Cumulative funding index at the time the position was last settled.
upnlNow
bigint
[6] Unrealized P&L at the current mark price (signed), unconditional. Perp and CP positions use the oracle as the current mark; binary positions return 0 — use pnlIfFires/pnlIfDies instead.
mmNow
bigint
[7] Maintenance margin contribution of this position when its firing branch is active. Zero under the non-firing branch for CP/binary positions.
imNow
bigint
[8] Initial margin contribution. Same firing-branch semantics as mmNow.
pnlIfFires
bigint
[9] Position value if its branch fires (μ = 1): sign(side) × (settle × size − entry × size). Perpetuals always fire; CP fires when the event resolves to its branch; binary fires and settles to BINARY_PRICE_MAX × size.
pnlIfDies
bigint
[10] Position value if its branch does NOT fire (μ = 0): sign(side) × (0 − entry × size). For perpetuals this equals upnlNow (perps never die, reported for UI column symmetry).
fundingSince
bigint
[11] Funding accrued since the position’s last settled funding index, in microUSDC. Positive = credit received, negative = debit paid.
adlScore
bigint
[12] Auto-deleveraging queue score: max(0, upnlNow) × leverage_used. Higher values are closer to the front of the ADL queue. Only profitable positions have a non-zero score. UIs should rank positions by adlScore descending to compute a per-market percentile and warn above the 90th percentile.

AdlQueueEntry

One row of the auto-deleveraging queue for a market. Returned by GET /v1/adl/queue/{market}, sorted by adlScore descending (front of queue first). Wire shape is a 6-tuple [owner, market, side, size, upnlNow, adlScore].
interface AdlQueueEntry {
  owner: Uint8Array;
  market: number;
  side: "Buy" | "Sell";
  size: bigint;
  upnlNow: bigint;
  adlScore: bigint;
}
owner
Uint8Array
required
20-byte owner address.
market
number
required
Market identifier.
side
"Buy" | "Sell"
required
Position side: "Buy" = long, "Sell" = short.
size
bigint
required
Position size in integer contracts.
upnlNow
bigint
required
Unrealized PnL at the current mark price (signed). Always positive in this queue — only profitable positions are eligible for ADL.
adlScore
bigint
required
max(0, upnlNow) × leverage_bps. Higher = closer to the front of the queue. Tied with PositionInfo.adlScore for the same position.

Ticker

One-round-trip market summary for the markets-page card rail and the perp trade ticker bar. Returned by client.queryTicker(marketId).
interface Ticker {
  market: string;
  lastPrice: string;
  volume24hContracts: string;
  change24hBps: string;
  fundingMsgpackB64: string;
  orderbookMsgpackB64: string;
  openInterest: string | null;
}
market
string
required
Market ID as a decimal string.
lastPrice
string
required
Last fill price within the 24-hour window. "0" or empty if no trades have occurred.
volume24hContracts
string
required
Sum of contract quantities filled in the 24-hour window (integer contracts).
change24hBps
string
required
Signed 24-hour price change in basis points. "0" or empty if no trades have occurred.
fundingMsgpackB64
string
required
Base64-encoded msgpack blob containing the FundingInfo struct (mark EWMA, oracle price, funding rate, and interval). Decode with @msgpack/msgpack.
orderbookMsgpackB64
string
required
Base64-encoded msgpack blob containing an OrderbookSnapshot at depth 1. Empty string for fresh markets with no resting orders.
openInterest
string | null
required
Always null today — the engine does not yet track open interest. UIs should render "—" or "coming soon" for this column.

MarketConfig

Full configuration for a perpetual, conditional, or binary market. The wire form is a positional MessagePack array; indices mirror the Rust struct field order. Fields after index 7 use serde(default) so older on-chain records decode cleanly.
interface MarketConfig {
  market: number;                       // [0]
  imBps: number;                        // [1]
  mmBps: number;                        // [2]
  takerFeeBps: number;                  // [3]
  makerFeeBps: number;                  // [4]
  fundingIntervalMs: bigint;            // [5]
  maxFundingRateBps: number;            // [6]
  kind?: MarketKind;                    // [7]
  maxPositionSize?: bigint;             // [8]
  defaultTtlMs?: bigint;                // [9]
  netDeltaMargin?: boolean;             // [10]
  poolId?: number;                      // [11]
  markPriceMaxOracleAgeMs?: bigint;     // [12]
  feeTiers?: FeeTier[];                 // [13]
  tickSize?: bigint;                    // [14]
  lotSize?: bigint;                     // [15]
  primaryOracleSigner?: Address;        // [16]
  oracleStalenessMs?: bigint;           // [17]
  markSourceMode?: MarkSourceMode;      // [18]
  maxMarkSpreadBps?: number;            // [19]
  cexCompositeStalenessMs?: bigint;     // [20]
  partialLiquidationEnabled?: boolean;  // [21]
  szDecimals?: number;                  // [22]
  ticker?: string;                      // [23]
}
market
number
required
[0] Market identifier (unique integer).
imBps
number
required
[1] Initial margin requirement in basis points (e.g., 1000 = 10% = 10× max leverage).
mmBps
number
required
[2] Maintenance margin requirement in basis points (e.g., 500 = 5%).
takerFeeBps
number
required
[3] Taker fee rate in basis points (e.g., 5 = 0.05%).
makerFeeBps
number
required
[4] Maker fee rate in basis points (e.g., 2 = 0.02%).
fundingIntervalMs
bigint
required
[5] Funding payment interval in milliseconds. 0 = funding is disabled.
maxFundingRateBps
number
required
[6] Maximum absolute funding rate per interval in basis points.
kind
MarketKind
[7] Market kind discriminator. Defaults to "Perp" for legacy records. Parameterised variants are { ConditionalPerp: [impactId, "Yes" | "No"] } and { PredictionBinary: [impactId, "Yes" | "No"] }.
maxPositionSize
bigint
[8] Per-account absolute position cap in integer contracts. 0 = no limit.
defaultTtlMs
bigint
[9] Default order TTL in milliseconds. 0 = no automatic expiry. When set, resting orders older than this value are swept at the end of each block.
netDeltaMargin
boolean
[10] When true, firing legs sharing the same underlying are netted into a single position for MM/IM calculations (|Σ signed_size| × settle × weighted_bps). When false, per-leg scenario margin applies.
poolId
number
[11] Insurance-fund pool ID. Markets in different pools are insulated from each other’s liquidation cascades. 0 = shared default pool.
markPriceMaxOracleAgeMs
bigint
[12] Maximum oracle age in milliseconds before the engine refuses to use the oracle price for mark calculations. 0 = no staleness check.
feeTiers
FeeTier[]
[13] Volume-based fee tier table. Empty array = flat taker/maker fees apply.
tickSize
bigint
[14] Minimum price increment in microUSDC. 0 = no tick gate (any price accepted).
lotSize
bigint
[15] Minimum quantity increment in integer contracts. 0 = no lot gate (any quantity accepted).
primaryOracleSigner
Address
[16] 20-byte primary oracle signer address. When set, oracle updates from this signer take precedence. Pass an all-zero address to clear.
oracleStalenessMs
bigint
[17] Oracle staleness threshold in milliseconds. Only consulted when primaryOracleSigner is set. 0 = gate disabled.
markSourceMode
"OracleOnly" | "Median"
[18] Mark-price source mode. "OracleOnly" = legacy oracle-only mode; "Median" = median of oracle and book-mid. Has no effect on impact-family child markets.
maxMarkSpreadBps
number
[19] Thin-book spread cap in basis points for the "Median" mark-price guard. 0 resets to the engine default (100 bps). Ignored unless markSourceMode === "Median".
cexCompositeStalenessMs
bigint
[20] Maximum age in milliseconds for the composite-CEX price source in "Median" mode. 0 resets to the engine default (30 seconds).
partialLiquidationEnabled
boolean
[21] When true, liquidation closes one position at a time and rechecks maintenance margin before proceeding. When false, all-or-nothing liquidation applies.
szDecimals
number
[22] Published size scale: order and position quantities are in units of 10^-szDecimals of the base asset (display/metadata only — the engine never reads this field). 0 = integer-unit sizing.
ticker
string
[23] Human-readable ticker symbol (e.g., "BTC"). Display/metadata only; capped at 24 bytes. Fixed at market creation and immutable thereafter.

History Types

HistoryCashFlow

One row of the per-user deposit/withdrawal cash-flow log. Returned by GET /v1/history/deposits/{address} and GET /v1/history/withdrawals/{address}.
interface HistoryCashFlow {
  kind: "deposit_confirmed" | "withdraw_requested"
      | "withdrawal_confirmed" | "withdrawal_failed";
  owner: string;
  amount: string;
  signedDelta: string;
  newBalance: string;
  withdrawalId: string;
  solanaTxSig: string;
  solanaDestination: string;
  reason: string;
  blockHeight: number;
  timestamp: number;
}
kind
string
required
One of "deposit_confirmed", "withdraw_requested", "withdrawal_confirmed", or "withdrawal_failed".
owner
string
required
20-byte owner address as a hex string.
amount
string
required
Amount in microUSDC (always positive). May be empty for "withdrawal_confirmed" events.
signedDelta
string
required
Signed balance change for this event: +amount for deposit_confirmed and withdrawal_failed (credit); -amount for withdraw_requested (debit); "0" for withdrawal_confirmed (no balance change on acknowledgement).
newBalance
string
required
Post-event balance in microUSDC. Empty for "withdrawal_confirmed" since no balance change occurs on that event.
withdrawalId
string
required
Present on withdrawal events (withdraw_requested, withdrawal_confirmed, withdrawal_failed).
solanaTxSig
string
required
Present on deposit_confirmed and withdrawal_confirmed events.
solanaDestination
string
required
Present on withdraw_requested events only.
reason
string
required
Human-readable failure reason. Present on withdrawal_failed events only.
blockHeight
number
required
Block height at which the event landed.
timestamp
number
required
Unix timestamp in milliseconds.

HistoryResolution

One row of the per-user position-at-resolution log. Returned by GET /v1/history/resolutions/{address}.
interface HistoryResolution {
  kind: "conditional_settled" | "conditional_voided" | "prediction_settled";
  impactMarketId: string;
  market: string;
  owner: string;
  side: string;
  size: string;
  entryPrice: string;
  settlementPrice: string;
  realizedPnl: string;
  blockHeight: number;
  timestamp: number;
}
kind
string
required
One of "conditional_settled", "conditional_voided", or "prediction_settled".
impactMarketId
string
required
Impact-market family ID that the resolved position belonged to.
market
string
required
Child market ID (CPY/CPN or EBY/EBN).
owner
string
required
20-byte owner address as a hex string.
side
string
required
Position side at resolution: "Buy" = long, "Sell" = short.
size
string
required
Position size at resolution in integer contracts (stringified to preserve BIGINT precision).
entryPrice
string
required
Weighted-average entry price of the resolved position.
settlementPrice
string
required
Settlement price used for PnL calculation. conditional_settled → mark price; prediction_settled → payoff per share (BINARY_PRICE_MAX for winner, 0 for loser); conditional_voided → empty string (void path returns margin, no cash movement).
realizedPnl
string
required
Signed realized PnL in microUSDC. "0" for conditional_voided.
blockHeight
number
required
Block height at which the resolution landed.
timestamp
number
required
Unix timestamp in milliseconds.

HistoryPositionSnapshot

One row of the per-user position-history snapshot log. Each entry is a point-in-time snapshot written after every fill that changes position state (open → grow → reduce → close). A size of "0" represents a close event. Returned by GET /v1/history/positions/{address} with optional ?market=&from=&to=&limit= filters; results are newest-first.
interface HistoryPositionSnapshot {
  owner: string;
  market: string;
  side: string;
  entryPrice: string;
  size: string;
  blockHeight: number;
  timestamp: number;
}
owner
string
required
20-byte owner address as a hex string.
market
string
required
Market ID as a decimal string.
side
string
required
Position side: "Buy" = long, "Sell" = short.
entryPrice
string
required
Weighted-average entry price in microUSDC at the time of the snapshot.
size
string
required
Absolute position size in integer contracts. "0" indicates the position was closed at this block.
blockHeight
number
required
Block height at which the snapshot landed.
timestamp
number
required
Unix timestamp in milliseconds.

WithdrawalRecord

On-chain withdrawal record returned by queryWithdrawal. Mirrors exchange-core::types::WithdrawalRecord field-for-field.
type WithdrawalStatus = "Pending" | "Completed" | "Failed";

interface WithdrawalRecord {
  id: bigint;
  owner: Address;
  amount: bigint;
  solanaDestination: Uint8Array;
  status: WithdrawalStatus;
  requestHeight: bigint;
}
id
bigint
required
Engine-assigned withdrawal ID.
owner
Uint8Array
required
20-byte address that requested the withdrawal.
amount
bigint
required
Withdrawal amount in microUSDC.
solanaDestination
Uint8Array
required
Solana destination public key (Ed25519, 32 bytes).
status
"Pending" | "Completed" | "Failed"
required
Lifecycle status. Transitions are one-way: Pending → Completed or Pending → Failed; never reverses.
requestHeight
bigint
required
Block height at which the withdrawal request was admitted.

ImpactMarketInfo

On-chain info for an impact-market family (a set of 4–5 related books). Returned by the impactMarketInfo query.
type ImpactMarketStatus =
  | { kind: "Trading" }
  | { kind: "PreResolution" }
  | { kind: "Resolved"; outcome: Outcome };

interface ImpactMarketInfo {
  impactMarketId: number;
  underlyingMarket: number;
  cpyMarket: number;
  cpnMarket: number;
  ebyMarket: number;
  ebnMarket: number;
  question: string;
  deadlineMs: bigint;
  resolutionWindowMs: bigint;
  status: ImpactMarketStatus;
  createdMs: bigint;
  resolvedMs: bigint;
}
impactMarketId
number
required
Impact-market family identifier.
underlyingMarket
number
required
The underlying perpetual market this impact market is derived from.
cpyMarket
number
required
Child market ID for the Conditional Perp Yes (CPY) leg.
cpnMarket
number
required
Child market ID for the Conditional Perp No (CPN) leg.
ebyMarket
number
required
Child market ID for the Event Binary Yes (EBY) leg.
ebnMarket
number
required
Child market ID for the Event Binary No (EBN) leg.
question
string
required
Human-readable question text for the event (e.g., "Will BTC exceed $100k by Q4?").
deadlineMs
bigint
required
Unix timestamp in milliseconds at which the event’s trading window closes.
resolutionWindowMs
bigint
required
Duration in milliseconds after deadlineMs during which the resolver must submit an outcome.
status
ImpactMarketStatus
required
Current lifecycle status of the impact market.
createdMs
bigint
required
Unix timestamp in milliseconds at which the impact market was created.
resolvedMs
bigint
required
Unix timestamp in milliseconds at which the event was resolved. 0 if not yet resolved.

Build docs developers (and LLMs) love