Skip to main content
This WebSocket API will be deprecated on July 1, 2026. See the Migration Guide to move to the Centrifuge-based API.
For optimal state updates, we recommend a combination of HTTP requests and channel subscriptions, utilizing the rewind parameter. HTTP requests provide the current state, while channel subscriptions keep the state updated. The rewind parameter ensures playback of past events, preventing any missed events between the HTTP call and subscription. See this link for an overview of the rewind parameter and more.
const Ably = require("ably");

async function getOrders(marketHash, token) {
  const response = await fetch(
    `https://api.sx.bet/orders?marketHashes=${marketHash}&baseToken=${token}`,
    {
      headers: {
        "Content-Type": "application/json",
        "X-Api-Key": this.apiKey,
      },
    }
  );
  console.log(await response.json());
}

async function orderStream(realtime, marketHash, token) {
  const channel = realtime.channels.get(`order_book:${token}:${marketHash}`, {
    params: { rewind: "10s" },
  });
  channel.subscribe((message) => {
    console.log(message.data);
  });
}

async function createTokenRequest() {
  console.log("createTokenRequest");
  const response = await fetch("https://api.sx.bet/user/token", {
    headers: {
      "X-Api-Key": this.apiKey,
      "Content-Type": "application/json",
    },
  });
  return response.json();
}

async function initialize() {
  const ablyClient = new Ably.Realtime.Promise({
    authUrl: "https://ably.com/ably-auth/token/docs",
  });
  const realtime = new Ably.Realtime.Promise({
    authCallback: async (tokenParams, callback) => {
      try {
        const tokenRequest = await createTokenRequest();
        callback(null, tokenRequest);
      } catch (error) {
        callback(error, null);
      }
    },
  });
  await ablyClient.connection.once("connected");
  return realtime;
}

async function main() {
  const realtime = await initialize();
  await getOrders(this.marketHash, this.token);
  await orderStream(realtime, this.marketHash, this.token);
}

main();