Polymarket Real-Time Data Client

repository·main·Indexed 42 days ago

https://github.com/polymarket/real-time-data-client

A TypeScript/JavaScript client (v1.4.2) providing a wrapper to connect to Polymarket's real-time data streaming WebSocket service. It allows developers to subscribe to activity, comments, and price updates for crypto and equity assets. The client handles connection lifecycles, automatic heartbeats, and supports authentication via ClobApiKeyCreds and GammaAuth for protected topics.

Tokens
3.9K
Snippets
14
Records
24
Agent score
52%

What's inside Polymarket Real-Time Data Client

  1. How initial data dumps work for prices

    main
    For crypto_prices, crypto_prices_chainlink, and equity_prices topics, if you provide a filter (e.g., {"symbol":"BTCUSDT"}) during subscription, the server will automatically send an initial snapshot of recent data upon connection. This snapshot contains an array of price data objects, each with a timestamp and value.
  2. Quickstart: Connect and receive messages with RealTimeDataClient

    main

    To use the RealTimeDataClient, instantiate it with onMessage and onConnect callbacks, then call .connect(). Use the onConnect callback to perform subscriptions via client.subscribe().

    import { RealTimeDataClient } from "../src/client";
    import { Message } from "../src/model";
    
    const onMessage = (message: Message): void => {
        console.log(message.topic, message.type, message.payload);
    };
    
    const onConnect = (client: RealTimeDataClient): void => {
        // Subscribe to a topic
        client.subscribe({
            subscriptions: [
                {
                    topic: "comments",
                    type: "*", // "*" can be used to connect to all the types of the topic
                    filters: `{"parentEntityID":100,"parentEntityType":"Event"}`,
                },
            ],
        });
    };
    
    new RealTimeDataClient({ onMessage, onConnect }).connect();
  3. Initialize and use the RealTimeDataClient

    main

    To use the real-time data stream, instantiate the RealTimeDataClient class with an optional RealTimeDataClientArgs object and call .connect(). You can provide callbacks to handle connection events, incoming messages, and status changes.

    Configuration Options (RealTimeDataClientArgs)

    • onConnect?: (client: RealTimeDataClient) => void: Called when the connection is successfully established.
    • onMessage?: (client: RealTimeDataClient, message: Message) => void: Called when a message containing a payload is received.
    • onStatusChange?: (status: ConnectionStatus) => void: Called when the connection status changes (e.g., CONNECTING, CONNECTED, DISCONNECTED).
    • host?: string: The WebSocket server URL. Defaults to wss://ws-live-data.polymarket.com.
    • pingInterval?: number: Interval in milliseconds for sending pings to keep the connection alive. Defaults to 5000.
    • autoReconnect?: boolean: If true, the client will attempt to reconnect automatically if the connection is lost. Defaults to true.
    import { RealTimeDataClient } from '@polymarket/real-time-data-client';
    
    const client = new RealTimeDataClient({
      onConnect: (client) => {
        console.log('Connected!');
        // You can subscribe here
      },
      onMessage: (client, message) => {
        console.log('Received message:', message);
      },
      onStatusChange: (status) => {
        console.log('Status changed to:', status);
      }
    });
    
    client.connect();
  4. Authenticate with ClobAuth

    main

    For topics requiring authentication (like clob_user), provide clob_auth credentials within the subscription object. The clob_auth object uses the ClobApiKeyCreds interface.

    client.subscribe({
        subscriptions: [
            {
                topic: "clob_user",
                type: "*",
                clob_auth: {
                    key: "xxxxxx-xxxx-xxxxx-xxxx-xxxxxx",
                    secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                    passphrase: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                },
            },
        ],
    });
  5. Unsubscribe from message streams

    main

    To stop receiving a specific type of message within a topic, call client.subscribe() with the specific topic and type. If you previously subscribed to all types using "*", specifying a single type will unsubscribe only from that type.

    Example of unsubscribing from 'trades' in the 'activity' topic:

    client.subscribe({
        subscriptions: [
            {
                topic: "activity",
                type: "trades",
            },
        ],
    });
  6. Subscribe to message streams

    main

    Use client.subscribe() to listen to specific topics and message types. You can use the wildcard "*" for the type field to subscribe to all message types within a topic.

    To subscribe to 'trades' messages from the 'activity' topic and all 'comments' messages:

    client.subscribe({
        subscriptions: [
            {
                topic: "activity",
                type: "trades",
            },
        ],
    });
    
    client.subscribe({
        subscriptions: [
            {
                topic: "comments",
                type: "*",
            },
        ],
    });
  7. Reference: Messages hierarchy and topics

    main

    The following table defines the available topics, message types, and required filters for the real-time data stream.

    TopicTypeAuthFiltersSchema
    activitytrades-{"event_slug":"string"} OR {"market_slug":"string"}Trade
    activityorders_matched-{"event_slug":"string"} OR {"market_slug":"string"}Trade
    commentscomment_created-{"parentEntityID":number,"parentEntityType":"Event / Series"}Comment
    commentscomment_removed-{"parentEntityID":number,"parentEntityType":"Event / Series"}Comment
    commentsreaction_created-{"parentEntityID":number,"parentEntityType":"Event / Series"}Reaction
    commentsreaction_removed-{"parentEntityID":number,"parentEntityType":"Event / Series"}Reaction
    crypto_pricesupdate-{"symbol":string}CryptoPrice
    crypto_prices_chainlinkupdate-{"symbol":string}CryptoPrice
    equity_pricesupdate-{"symbol":string}EquityPrice
  8. Reference: CryptoPrice and EquityPrice schemas

    main

    Both CryptoPrice and EquityPrice use the following schema:

    NameTypeDescription
    symbolstringSymbol of the asset
    timestampnumberTimestamp in milliseconds for the update
    valuenumberValue at the time of update

    Initial data dump on connection: When a connection is established and a filter is used, the server provides an initial snapshot of recent data for CryptoPrice and EquityPrice in this format:

    NameTypeDescription
    symbolstringSymbol of the asset
    dataarrayArray of price data objects, each containing timestamp and value
  9. Reference: Comment message schema

    main

    The Comment message schema for the comments topic contains the following fields:

    NameTypeDescription
    idstringUnique identifier of comment
    bodystringContent of the comment
    parentEntityTypestringType of the parent entity (Event or Series)
    parentEntityIDnumberID of the parent entity
    parentCommentIDstringID of the parent comment
    userAddressstringAddress of the user
    replyAddressstringAddress of the reply user
    createdAtstringCreation timestamp
    updatedAtstringLast update timestamp
  10. Reference: Trade message schema

    main

    The Trade message schema for the activity topic contains the following fields:

    NameTypeDescription
    assetstringERC1155 token ID of conditional token being traded
    biostringBio of the user of the trade
    conditionIdstringId of market which is also the CTF condition ID
    eventSlugstringSlug of the event
    iconstringURL to the market icon image
    namestringName of the user of the trade
    outcomestringHuman readable outcome of the market
    outcomeIndexintegerIndex of the outcome
    pricefloatPrice of the trade
    profileImagestringURL to the user profile image
    proxyWalletstringAddress of the user proxy wallet
    pseudonymstringPseudonym of the user
    sidestringSide of the trade (BUY/SELL)
    sizeintegerSize of the trade
    slugstringSlug of the market
    timestampintegerTimestamp of the trade
    titlestringTitle of the event
    transactionHashstringHash of the transaction
  11. Reference: Reaction message schema

    main

    The Reaction message schema for the comments topic contains the following fields:

    NameTypeDescription
    idstringUnique identifier of reaction
    commentIDnumberID of the comment
    reactionTypestringType of the reaction
    iconstringIcon representing the reaction
    userAddressstringAddress of the user
    createdAtstringCreation timestamp