WebSocket API

Overview

The Public WebSocket API provides real-time data subscription functionality, supporting subscriptions for order books, K-lines, instrument information, portfolios, and more.

Connection URL

wss://api.monday.trade/v4/public/ws

Heartbeat Mechanism

Clients can send a "ping" string to keep the connection alive. The server will reply with "pong".


Message Format

Request Message Format

All request messages follow this format:

{
  "id": <number>,           // Request ID for matching responses
  "method": "SUBSCRIBE" | "UNSUBSCRIBE",
  "params": {
    // Specific parameters vary by subscription type
  }
}

Response Message Format

Subscribe/Unsubscribe Response

Data Stream Message Format


Subscription Types

1. K-line Data Subscription (kline)

Subscribe to K-line data updates for a specific instrument and interval.

Subscribe Request

Unsubscribe Request

Parameter Description

  • chainId (required): Chain ID

  • instrument (required): Instrument address (lowercase)

  • expiry (required): Expiry timestamp

  • interval (required): K-line interval. Supported values:

    • 1m - 1 minute

    • 5m - 5 minutes

    • 15m - 15 minutes

    • 30m - 30 minutes

    • 1h - 1 hour

    • 4h - 4 hours

    • 8h - 8 hours

    • 12h - 12 hours

    • 1d - 1 day

    • 1w - 1 week

    • 1M - 1 month

  • type (required): Must be "kline"

Data Stream Message


2. Order Book Subscription (orderBook)

Subscribe to order book data updates for a specific instrument.

Subscribe Request

Unsubscribe Request

Parameter Description

  • chainId (required): Chain ID

  • instrument (required): Instrument address (lowercase)

  • expiry (required): Expiry timestamp

  • type (required): Must be "orderBook"

Data Stream Message

Order Book Data Structure:

  • chainId (top-level): Chain ID of the order book update

  • instrument (top-level): Instrument address corresponding to the update

  • expiry (top-level): Expiry timestamp

  • data: Map of order book entries, keyed by tick ID (string). Each entry contains:

    • blockInfo: Block information

      • height: Block height

      • timestamp: Block timestamp

    • bids: Buy order list (sorted by price from high to low)

    • asks: Sell order list (sorted by price from low to high)

    • Each order item contains:

      • tick: Price tick

      • price: Price (string format)

      • baseSize: Base asset quantity

      • quoteSize: Quote asset quantity

      • baseSum: Cumulative base asset quantity

      • quoteSum: Cumulative quote asset quantity


3. Instrument Information Subscription (instrument)

Subscribe to detailed instrument information updates.

Subscribe Request

Unsubscribe Request

Parameter Description

  • chainId (required): Chain ID

  • instrument (required): Instrument address (lowercase)

  • expiry (required): Expiry timestamp

  • type (required): Must be "instrument"

Data Stream Messages

When subscribing to instrument, you will receive two types of messages:

3.1 Instrument Information (instrument)

Complete instrument information update:

Instrument Information Data Structure

  • instrumentAddr: Instrument address

  • symbol: Trading pair symbol

  • market: Market information

    • info: Market basic information (address, type, beacon)

    • config: Market configuration (daily interest rate, feeder sources)

    • feeder: Market feeder information (aggregators, heartbeats)

  • condition: Instrument condition status

  • setting: Instrument settings

    • initialMarginRatio: Initial margin ratio

    • maintenanceMarginRatio: Maintenance margin ratio

    • quoteParam: Quote parameters (min margin amount, fee ratios, etc.)

  • spotPrice: Spot price

  • amms: Array of AMM states, containing:

    • expiry: Expiry timestamp

    • timestamp: Timestamp

    • status: AMM status

    • tick: Current tick

    • sqrtPX96: Square root price in X96 format

    • liquidity: Current liquidity

    • totalLiquidity: Total liquidity

    • totalShort: Total short positions

    • openInterests: Open interest

    • totalLong: Total long positions

    • involvedFund: Involved fund amount

    • feeIndex: Fee index

    • protocolFee: Protocol fee

    • longSocialLossIndex: Long social loss index

    • shortSocialLossIndex: Short social loss index

    • longFundingIndex: Long funding index

    • shortFundingIndex: Short funding index

    • insuranceFund: Insurance fund amount

    • settlementPrice: Settlement price

    • markPrice: Mark price

    • fairPrice: Fair price

    • blockInfo: Block information (height, timestamp)

  • base: Base token information (symbol, address, decimals, name)

  • quote: Quote token information (symbol, address, decimals, name)

  • blockInfo: Block information (height, timestamp)

  • placePaused: Whether placing orders is paused

  • fundingHour: Funding hour

  • disableOrderRebate: Whether order rebate is disabled

  • instrumentType: Instrument type

  • marketType: Market type (e.g., "perp")

  • minTradeValue: Minimum trade value

  • minOrderValue: Minimum order value

  • minRangeValue: Minimum range value

  • displayBase: Display base token information

  • displayQuote: Display quote token information

  • minTickDelta: Minimum tick delta

3.2 Market Pair Info Changed (marketPairInfoChanged)

Market pair information update (prices, volumes, etc.):

Note: This message is sent when market pair information (prices, volumes, etc.) changes. It provides a lightweight update focused on market data, while the instrument message provides complete instrument state information.

Market Pair Info Changed Data Structure

  • instrumentAddr: Instrument address

  • expiry: Expiry timestamp

  • symbol: Trading pair symbol (e.g., "ETH/USD")

  • fullSymbol: Full trading pair symbol with expiry (e.g., "ETH/USD-PERP")

  • baseToken: Base token information

    • symbol: Token symbol

    • address: Token address

    • decimals: Token decimals

    • price: Current token price

    • image: Token image URL

  • quoteToken: Quote token information

    • symbol: Token symbol

    • address: Token address

    • decimals: Token decimals

    • price: Current token price

    • image: Token image URL

  • markPrice: Mark price (string)

  • fairPrice: Fair price (string)

  • spotPrice: Spot price (string)

  • fairPriceChange24h: Fair price change percentage over 24 hours (string)

  • baseVolume24h: Base token volume over 24 hours (string)

  • quoteVolume24h: Quote token volume over 24 hours (string)

  • volume24hUsd: Total volume in USD over 24 hours (string)

  • openInterests: Open interest amount (string)

  • openInterestsUsd: Open interest in USD (string)

  • tvl: Total value locked (string)

  • tvlUsd: Total value locked in USD (string)

  • longOi: Long open interest (string)

  • shortOi: Short open interest (string)

  • periods1hFunding: 1-hour periods funding rate

    • long: Long funding rate

    • short: Short funding rate

  • last1hFunding: Last 1-hour funding rate

    • long: Long funding rate

    • short: Short funding rate

  • fundingRatePerHour: Funding rate per hour (string)

  • poolFee24h: Pool fee over 24 hours (string)

  • maxLeverage: Maximum leverage (number)

  • updateTime: Last update timestamp (number)

  • marketType: Market type (e.g., "perp")

  • condition: Instrument condition status (number)

  • ammStatus: AMM status (number)


4. Portfolio Subscription (portfolio)

Subscribe to portfolio update notifications for a specific user address.

Subscribe Request

Unsubscribe Request

Parameter Description

  • chainId (required): Chain ID

  • userAddress (required): User address (lowercase)

  • type (required): Must be "portfolio"

Data Stream Message

Portfolio Update Description:

  • This message is pushed when a user's orders, range orders, positions, or gates change

  • The type field indicates the change type:

    • order: Order change

    • range: Range order change

    • position: Position change

    • gate: Gate change

  • After receiving this message, clients should call the corresponding REST API to fetch the latest portfolio details


5. Common Subscription (common)

Subscribe to chain-level common events, including block number changes and market list changes.

Subscribe Request

Unsubscribe Request

Parameter Description

  • chainId (required): Chain ID

  • type (required): Must be "common"

Data Stream Message Types

5.1 Block Number Changed (blockNumChanged)

5.2 Market List Changed (marketListChanged)

Note: To receive individual market pair information updates (marketPairInfoChanged), you need to subscribe to the instrument type instead. The common subscription only provides blockNumChanged and marketListChanged messages.


6. Instrument Basic Info Subscription (instrumentBasicInfo)

Subscribe to basic instrument information updates.

Subscribe Request

Unsubscribe Request

Parameter Description

  • chainId (required): Chain ID

  • instrument (required): Instrument address (lowercase)

  • expiry (required): Expiry timestamp

  • type (required): Must be "instrumentBasicInfo"

Note: This subscription type is defined in the code, but the current implementation returns immediately without sending data stream messages.


Error Handling

Connection Errors

If the connection fails, the WebSocket will trigger an error event. Clients should implement a reconnection mechanism.

Common connection issues:

  1. Connection Timeout:

    • Check your network connection and firewall settings

    • Verify the WebSocket URL is correct

  2. Unexpected Server Response:

    • Ensure you're using the correct protocol (wss:// for secure connections)

    • Verify the server endpoint is accessible

Message Format Errors

If the message format is incorrect, the server may not respond or return an error. Please ensure:

  • JSON format is correct

  • All required parameters are provided

  • Parameter types are correct (e.g., chainId is a number, instrument is a string)


Best Practices

  1. Connection Management

    • Implement automatic reconnection mechanism

    • Use heartbeat to keep connection alive

    • Handle network interruptions

  2. Subscription Management

    • Subscribe to required data streams immediately after connection is established

    • Unsubscribe from all subscriptions before disconnecting

    • Use unique request IDs to track subscription status

  3. Data Processing

    • Validate received data format

    • Handle data update frequency to avoid excessive UI refreshes

    • For portfolio subscriptions, actively fetch the latest data after receiving notifications

  4. Performance Optimization

    • Only subscribe to needed data streams

    • Unsubscribe from unnecessary subscriptions promptly

    • Use data caching appropriately


Example Code

Browser JavaScript Example

Node.js TypeScript Example


Changelog

  • Support for K-line, order book, instrument information, portfolio, and common event subscriptions

  • Heartbeat mechanism support

  • Multi-chain subscription support

Last updated