sifting/io
Forex & Crypto
9 min readSiftingIO Team

Crypto price alerts in Node.js: WebSocket ticks instead of polling

Build a crypto price alert in Node.js that listens to WebSocket ticks instead of polling REST, with crossing logic, re-arming, keepalive pings and reconnects.

Crypto price alerts in Node.js: WebSocket ticks instead of polling

A crypto price alert built on a polling loop fires late, and sometimes it never fires. If your script asks for the BTCUSD price every 30 seconds, a move through your level is noticed 15 seconds late on average and 30 seconds late in the worst case. A spike that crosses the level and comes back between two polls is never seen. The fix is to stop asking and start listening: subscribe to ticks over a WebSocket, compare each tick with the previous one, and fire when the pair straddles your level.

This post builds that alert in Node.js against the SiftingIO stream, with the parts that usually get skipped: the snapshot tick, re-arming, keepalive pings and reconnects.

Why a polled price alert is late#

The delay of a polling alert is set by the interval. With an interval of T seconds, a crossing waits T/2 on average before the next poll sees it. Shortening T helps until the request budget runs out.

The numbers on the Free tier make this concrete. The documented limits are 60 REST requests per minute and 10,000 calls per month. Five symbols polled as fast as the per-minute limit allows means one request per symbol every 5 seconds, and at 60 requests per minute the monthly 10,000 calls are gone in about 2 hours 47 minutes. To make 10,000 calls last a 30-day month (43,200 minutes) you can afford one call every 4.32 minutes, which is one look at each of five symbols every 21.6 minutes. That is a price check, and it can't work as an alert.

The same Free tier allows one WebSocket connection with five symbol subscriptions. The stream pushes each new value to you as it is published, so nothing waits for your next poll, and the WebSocket docs describe the stream as having "sub-100ms median latency". The docs publish no update rate per tier, so measure the tick frequency on your own key before you depend on one. So the stream takes the polling interval out of the detection delay: detection is bounded by how soon a published value reaches you, without spending a REST call per look.

Polling still has a place. A single REST snapshot is the right tool for a one-off check or a page that renders once:

curl -H "X-API-Key: $SIFTING_KEY" \
  "https://api.sifting.io/v1/last/quote/crypto/BTCUSD"

The documented response carries s, the best bid and ask prices b and a, their sizes B and A, and t in Unix epoch milliseconds. Prices and sizes are strings on the REST endpoints. If the snapshot is older than the staleness threshold (5 seconds by default) the endpoint returns 503 stale_snapshot with last_t and server_now in the body.

What the stream sends#

You connect to wss://stream.sifting.io/ws/v1?key=... and the server replies with an ack frame that reports your tier and its caps (tier, max_conn, max_subs). You then send a subscribe op naming a product and a list of symbols. Server frames are told apart by the f field.

A tick looks like this. The values below are a fixture chosen to be internally consistent; they are not a recorded response.

{"f":"tick","class":"cex","s":"BTCUSD","p":99987.5,"P":0.0125,"b":99987.0,"B":0.84,"a":99988.0,"A":0.61,"t":1795250000000}

p and P are the last trade price and size, b and B the best bid price and size, a and A the best ask price and size, and t is the timestamp in epoch milliseconds. The docs say to branch on f first because the rest of the keys depend on it, and they don't list which tick fields are always present, so a handler should tolerate a tick without p. The tick example in the docs shows prices as bare numbers, while the REST quote endpoint returns them as strings. Convert with Number() and the same code handles both.

Two behaviours matter for an alert. First, on subscribe the server emits one snapshot tick per symbol from its cache before the live stream starts, and in the documented sequence that snapshot arrives before the subscribe ack. Second, the price is SiftingIO's fair price: one value per instrument aggregated from multiple independent venues as a weighted median. That is useful for an alert, because a single venue printing a thin or stale price can't trip your level alone. It also sets a limit on what the alert means. The alert says the cross-venue reference price crossed your level. It does not say an order would fill there on any particular venue.

Crossing logic: compare each tick with the previous one#

The naive check is price >= level. It fires on every tick while the price sits above the level, and it fires at startup if the price is already there. A crossing check needs two prices: the alert fires when the previous price was on one side of the level and the current price is on the other.

That is also the right way to treat the snapshot tick. On a fresh start there is no previous price, so the snapshot only seeds the state. After a reconnect the previous price is the last one seen before the drop, so the snapshot from the new subscription is compared against it, and a crossing that happened while the socket was down is still detected. It is detected late, which is better than not at all.

A price that hovers at the level crosses it many times a minute. To avoid a burst of notifications, disarm the alert when it fires and re-arm it only after the price has moved back past the level by a small band.

// alerts.js
export const alerts = [
  { symbol: 'BTCUSD', level: 100000, direction: 'above', rearmPct: 0.2, armed: true },
  { symbol: 'ETHUSD', level: 3000, direction: 'below', rearmPct: 0.2, armed: true },
];

const lastPrice = new Map();

export function onPrice(symbol, price, t, notify) {
  const prev = lastPrice.get(symbol);
  lastPrice.set(symbol, price);
  if (prev === undefined) return; // first tick only seeds the state

  for (const a of alerts) {
    if (a.symbol !== symbol) continue;
    const up = a.direction === 'above';
    const crossed = up
      ? prev < a.level && price >= a.level
      : prev > a.level && price <= a.level;

    if (a.armed && crossed) {
      a.armed = false;
      notify(a, price, Date.now() - t);
      continue;
    }

    const band = (a.level * a.rearmPct) / 100;
    const movedBack = up ? price < a.level - band : price > a.level + band;
    if (!a.armed && movedBack) a.armed = true;
  }
}

The levels here are arbitrary examples for the code, and nothing in them is a view on either instrument. The third argument passed to notify is the age of the tick in milliseconds. Include it in the message: a crossing detected from a cached snapshot after a two-minute outage should read differently from one detected on a live tick. Before you rely on that age, log the first tick and confirm t is a 13-digit millisecond value.

The WebSocket client: subscribe, ping, reconnect#

The client below uses the ws package (npm install ws) and Node 18 or later.

// stream.js
import WebSocket from 'ws';
import { alerts, onPrice } from './alerts.js';

const URL = `wss://stream.sifting.io/ws/v1?key=${process.env.SIFTING_KEY}`;
const SYMBOLS = [...new Set(alerts.map((a) => a.symbol))];
const FATAL = new Set(['auth_failed', 'max_connections', 'max_subscriptions']);

let attempt = 0;

function notify(alert, price, ageMs) {
  console.log(
    `${alert.symbol} crossed ${alert.direction} ${alert.level}: ${price} (tick age ${ageMs} ms)`
  );
}

function priceOf(m) {
  if (m.p !== undefined) return Number(m.p);
  if (m.b !== undefined && m.a !== undefined) return (Number(m.b) + Number(m.a)) / 2;
  return NaN;
}

function connect() {
  const ws = new WebSocket(URL);
  let pingTimer;

  ws.on('open', () => {
    ws.send(JSON.stringify({ op: 'subscribe', product: 'cex', symbols: SYMBOLS }));
    pingTimer = setInterval(() => ws.send(JSON.stringify({ op: 'ping' })), 30_000);
  });

  ws.on('message', (raw) => {
    const m = JSON.parse(raw.toString());
    if (m.f === 'tick') {
      attempt = 0;
      const price = priceOf(m);
      if (Number.isFinite(price)) onPrice(m.s, price, m.t, notify);
    } else if (m.f === 'error') {
      console.error('stream error', m.code, m.message ?? '', m.limit ?? '');
      if (FATAL.has(m.code)) process.exit(1);
    }
  });

  ws.on('close', (code, reason) => {
    clearInterval(pingTimer);
    const delay = Math.min(30_000, 1000 * 2 ** attempt++);
    console.error(`closed ${code} ${reason}, reconnecting in ${delay} ms`);
    setTimeout(connect, delay);
  });

  ws.on('error', (err) => console.error('socket error', err.message));
}

connect();

Run it with SIFTING_KEY=sft_... node stream.js. A few choices in this file are deliberate.

The subscribe is sent on every open. The docs describe no session resume and no sequence numbers, so a new connection starts with no subscriptions and the client has to ask again. Because lastPrice lives outside connect(), the state survives the reconnect and the fresh snapshot is checked against the last price seen.

The backoff doubles from one second up to a 30 second cap and resets on the first tick, which is the only reliable sign that the stream is healthy again. Resetting it on open would let a server that accepts and immediately drops connections pull the client into a tight loop.

The priceOf helper prefers the last trade price and falls back to the mid of bid and ask. Pick one definition per alert and keep it. An alert that mixes last trade and mid can cross a level without the market moving.

Gotchas that make a streaming alert go quiet#

The ping is not optional. The server closes a connection after 90 seconds without a client frame, with close code 1000 and the reason "idle timeout", and the docs ask for a ping at least every 60 seconds. Ticks arriving from the server do not reset that timer. Only frames you send do. A client that subscribes once and then only listens works for a minute and a half and then drops, however busy the stream is.

Product names on the stream differ from venue names on REST. The REST path uses crypto, forex, stocks, commodities and dex. The subscribe op uses cex, fx, us, com and dex. Sending "product":"crypto" returns an error frame with code unknown_product.

Error frames do not close the socket. A subscribe that exceeds the tier cap returns {"f":"error","code":"max_subscriptions"} with a limit field, and the connection stays open with no ticks for the symbols that were refused. On Free the cap is five symbols on one connection, so a sixth alert symbol fails without any obvious symptom unless you log error frames. The client above treats auth_failed, max_connections and max_subscriptions as fatal, because retrying none of them helps. A common cause of max_connections is an older copy of the same script still running.

An alert that starts with the price already beyond its level stays silent until the price comes back and crosses again. That follows from the crossing rule and is usually what you want, but say so in the interface, or add a startup check that reports levels already breached.

Finally, a quiet process looks the same as a broken one. Record the time of the last tick per symbol and raise your own warning when it exceeds a limit that fits the market: a few seconds for BTCUSD at any hour, far longer for an instrument whose market is closed.

Read the docs

Keep reading

Related posts