Back to where your exchange keys go

Binance connection

The direct line from your device to Binance that orders travel on. Unedited, from build 579b29d3.

lib/trading/binanceWs.ts lines 1-493
// Binance order entry over the WebSocket API.
//
// This exists because Binance's REST preflight allows neither POST nor the
// x-mbx-apikey header, so a browser cannot place an order over REST however
// correct the request is. WebSockets are not subject to CORS, and the WS API
// exposes the same operations. Measured from tabmira.com's origin on
// 2026-09-04: the handshake returns 101, `time` answers 200, and `order.place`
// with empty params answers -1102 naming the missing symbol, which is the
// method existing and validating rather than a method that is not there.
//
// The signing key is a non-extractable CryptoKey from the keystore, so the
// signature is produced here and the secret is never a string this file could
// leak. Nothing in the order path touches a TabMira server.
//
// One behaviour drove most of the design below. **Binance closes the
// connection outright on a signed request it cannot authenticate.** No error
// frame, no close reason, just a 1006. Verified against ws-api.binance.us with
// a well-formed but unknown API key. So an auth failure and an order that may
// already be resting are indistinguishable from the socket alone, and every
// submission has to be recoverable by client order id rather than trusted to
// report its own outcome.

import { toHex } from './keys';
import type { SigningKey } from './sign';

const enc = new TextEncoder();

export interface BinanceWsOptions {
  url: string;
  cred: SigningKey;
  /** Injectable so tests can drive a fake socket. Defaults to the platform WebSocket. */
  socketFactory?: (url: string) => WebSocket;
  /** How long to wait for a reply before giving up on a request. */
  timeoutMs?: number;
  /**
   * How long the socket may go without a word from Binance before the next
   * request first checks it is still there. See checkAlive.
   */
  idleCheckMs?: number;
}

/** A ping that takes longer than this is a socket not worth sending an order down. */
const ALIVE_CHECK_TIMEOUT_MS = 3_000;

/**
 * How far this device's clock is from Binance's, per host, in milliseconds.
 *
 * Binance refuses a signed request stamped more than a second ahead of its
 * clock, or further behind than the receive window, with -1021. A phone whose
 * clock is off could not connect a key at all: five keys were turned away
 * like that in a month, and balance reads failed the same way. Zero until
 * Binance refuses a timestamp, then learned from its own `time` and kept for
 * every socket to that host. Per host because live and testnet are separate
 * machines with separate clocks.
 */
const clockOffsets = new Map<string, number>();

/**
 * Where the corrected stamp lands. Binance takes up to a second ahead and the
 * whole receive window behind, so aim a little behind: the estimate is off by
 * up to half a round trip either way.
 */
const CLOCK_MARGIN_MS = 500;

/** Forget learned clock offsets. For tests. */
export function resetBinanceClock(): void {
  clockOffsets.clear();
}

/** The exchange answered and said no. The order did not happen. */
/**
 * Our words for a refusal, where Binance's give nobody a next step.
 *
 * -2015 is one code for three things: a key Binance does not know, a key it
 * knows but whose permission is off, and a key restricted to addresses this
 * device is not on. Its own "Invalid API-key, IP, or permissions for action."
 * is accurate and useless. Every direct call passes through here, so orders,
 * balances and the connect screen all get the same sentence.
 */
function describeRefusal(code: number): string | undefined {
  if (code === -2015) {
    return (
      'Binance rejected the key, the address it came from, or its permissions. Check the key was '
      + 'pasted whole and into the right box, that it still has Spot Trading enabled, and, if you '
      + 'restricted it to an IP address, that this device is on the list.'
    );
  }
  return undefined;
}

export class BinanceWsError extends Error {
  readonly code: number;
  readonly status: number;
  constructor(status: number, code: number, message: string) {
    super(message);
    this.name = 'BinanceWsError';
    this.status = status;
    this.code = code;
  }
}

/**
 * The socket died with the request in flight, so the outcome is genuinely
 * unknown: it may have been rejected on auth, or it may be resting on the book.
 *
 * Never present this to a user as a failure. Reconcile it with
 * `findByClientOrderId` and report what the exchange actually says.
 */
export class UnknownOutcomeError extends Error {
  readonly clientOrderId?: string;
  constructor(message: string, clientOrderId?: string) {
    super(message);
    this.name = 'UnknownOutcomeError';
    this.clientOrderId = clientOrderId;
  }
}

/**
 * The socket closed before it ever opened, so nothing was sent: no key, no
 * order. A network that dropped, or a host that turned the connection away
 * (Binance refuses the handshake from countries it does not serve). Whatever
 * the cause, it says nothing about the key.
 */
export class SocketOpenError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'SocketOpenError';
  }
}

interface Pending {
  resolve: (v: unknown) => void;
  reject: (e: Error) => void;
  timer: ReturnType<typeof setTimeout>;
  /** Set for order submissions, so a dropped socket can name what to go looking for. */
  clientOrderId?: string;
}

interface WsReply {
  id?: string;
  status?: number;
  result?: unknown;
  error?: { code?: number; msg?: string };
  rateLimits?: { rateLimitType: string; interval: string; limit: number; count: number }[];
}

export interface BinanceOrder {
  symbol: string;
  orderId: number;
  clientOrderId: string;
  status: string;
  side: string;
  type: string;
  price?: string;
  origQty?: string;
  executedQty?: string;
  transactTime?: number;
}

export class BinanceWsClient {
  private ws: WebSocket | undefined;
  private opening: Promise<void> | undefined;
  private readonly pending = new Map<string, Pending>();
  private seq = 0;
  private closedByUs = false;
  /** When Binance last said anything on this socket, or when it opened. */
  private lastHeard = 0;
  /** The liveness check in flight, shared by the requests that wait on it. */
  private checking: Promise<void> | undefined;

  /** Most recent rate-limit snapshot the exchange volunteered. */
  lastRateLimits: WsReply['rateLimits'];

  // A plain field rather than a parameter property, matching the relay
  // adapters: parameter properties are the one TypeScript feature Node's
  // strip-only mode refuses, and keeping them out means these modules load
  // under plain node with no build step.
  private readonly opts: BinanceWsOptions;

  constructor(opts: BinanceWsOptions) {
    this.opts = opts;
  }

  private get timeout(): number {
    return this.opts.timeoutMs ?? 10_000;
  }

  /** Whether close() was called, which is the vault locking: nothing should reopen this client. */
  get closedLocally(): boolean {
    return this.closedByUs;
  }

  async connect(): Promise<void> {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) return;
    if (this.opening) return this.opening;

    this.closedByUs = false;
    this.opening = new Promise<void>((resolve, reject) => {
      const make = this.opts.socketFactory ?? ((u: string) => new WebSocket(u));
      const ws = make(this.opts.url);
      this.ws = ws;

      const settleOpen = () => {
        this.opening = undefined;
        this.lastHeard = Date.now();
        resolve();
      };

      ws.onopen = settleOpen;
      ws.onmessage = (ev: MessageEvent) => this.onMessage(String(ev.data));
      ws.onclose = () => {
        this.opening = undefined;
        // Fail every request that was in flight. Rejecting them is not
        // optional: leaving them pending means a UI that spins forever on an
        // order that may well have been placed.
        this.failAllPending();
        if (ws.readyState !== WebSocket.OPEN) reject(new SocketOpenError('binance ws closed before opening'));
      };
      ws.onerror = () => {
        // Browsers deliberately give no detail here, so there is nothing worth
        // reporting beyond the close that follows.
      };
    });

    return this.opening;
  }

  private failAllPending(reason?: string): void {
    for (const [id, p] of this.pending) {
      clearTimeout(p.timer);
      p.reject(
        reason
          ? new UnknownOutcomeError(reason, p.clientOrderId)
          : this.closedByUs
          ? new UnknownOutcomeError('the connection was closed locally with this request in flight', p.clientOrderId)
          : new UnknownOutcomeError(
              'Binance closed the connection without answering. This is what an unknown API key looks like, '
              + 'and also what a dropped network looks like, so the order may or may not exist.',
              p.clientOrderId,
            ),
      );
      this.pending.delete(id);
    }
  }

  /**
   * Let go of a socket that stopped answering, so the next request opens a
   * new one.
   *
   * A socket can stay OPEN to the browser long after the network under it
   * went: a phone that slept, a laptop that changed Wi-Fi. Every request sent
   * down it waits out the timeout, and an order comes back unknown. Until
   * November 2026 the client kept the socket after a timeout too, so the next
   * order went down the same dead line, which is how one evening of trading
   * on Binance saw 59 orders end unknown.
   *
   * Its handlers are detached first: the pending map is shared with the
   * socket that replaces it, and a late close from this one must not fail
   * requests the new one is carrying.
   */
  private abandon(): void {
    const ws = this.ws;
    if (!ws) return;
    ws.onopen = null;
    ws.onmessage = null;
    ws.onclose = null;
    ws.onerror = null;
    this.ws = undefined;
    this.opening = undefined;
    this.failAllPending('Binance stopped answering on this connection, so it was dropped with this request in flight');
    try {
      ws.close();
    } catch {
      // Already closing, or never opened. Either way it is gone.
    }
  }

  /**
   * Before a request on a socket that has been quiet a while, a ping, so a
   * dead line is found in a few seconds with nothing riding on it, rather
   * than in ten with an order on it.
   *
   * Binance's WS API says nothing unprompted (its keepalive pings are control
   * frames the browser answers without telling the page), so silence alone
   * cannot tell a dead socket from an idle one. Weight 1, and only after a
   * quiet spell, so an active ticket pays nothing.
   */
  private checkAlive(): Promise<void> | undefined {
    const idle = this.opts.idleCheckMs ?? 15_000;
    // Not while one is opening, which has not had the chance to be quiet.
    if (!this.ws || this.opening || this.ws.readyState !== WebSocket.OPEN || Date.now() - this.lastHeard < idle) {
      return this.checking;
    }
    if (!this.checking) {
      this.checking = this.send('ping', {}, {}, Math.min(ALIVE_CHECK_TIMEOUT_MS, this.timeout))
        .then(
          () => undefined,
          () => this.abandon(),
        )
        .finally(() => {
          this.checking = undefined;
        });
    }
    return this.checking;
  }

  private onMessage(raw: string): void {
    this.lastHeard = Date.now();
    let reply: WsReply;
    try {
      reply = JSON.parse(raw) as WsReply;
    } catch {
      return;
    }
    if (reply.rateLimits) this.lastRateLimits = reply.rateLimits;
    if (!reply.id) return;

    const p = this.pending.get(reply.id);
    if (!p) return;
    clearTimeout(p.timer);
    this.pending.delete(reply.id);

    if (reply.status !== undefined && reply.status >= 400) {
      const code = reply.error?.code ?? 0;
      p.reject(
        new BinanceWsError(reply.status, code, describeRefusal(code) ?? reply.error?.msg ?? `binance returned ${reply.status}`),
      );
      return;
    }
    p.resolve(reply.result);
  }

  /**
   * Sign the parameters the way the WS API expects.
   *
   * Sorted by key, joined as k=v&k=v, HMAC-SHA256, hex. Note the sort: the
   * REST API signs the query string in the order it was written, the WS API
   * signs it alphabetically. Using the REST rule here produces a -1022 that
   * looks nothing like an ordering problem.
   */
  private async sign(params: Record<string, string | number>): Promise<string> {
    const payload = Object.keys(params)
      .sort()
      .map((k) => `${k}=${params[k]}`)
      .join('&');
    const sig = await crypto.subtle.sign('HMAC', this.opts.cred.key, enc.encode(payload));
    return toHex(new Uint8Array(sig));
  }

  async request<T>(
    method: string,
    params: Record<string, string | number | undefined> = {},
    opts: { signed?: boolean; clientOrderId?: string } = {},
  ): Promise<T> {
    // Awaited only when there is a check to wait for: a request on a fresh
    // or busy socket goes out in the same tick it was made, as it always has.
    const check = this.checkAlive();
    if (check) await check;
    try {
      return await this.send<T>(method, params, opts, this.timeout);
    } catch (e) {
      // A stamp outside Binance's window. Nothing was done on a -1021, an
      // order included, so learn the offset and go again, once. A second
      // -1021 stands: the clock is moving, or the answer to `time` was slow.
      if (!(opts.signed && e instanceof BinanceWsError && e.code === -1021)) throw e;
      if (!(await this.learnClock())) throw e;
      return this.send<T>(method, params, opts, this.timeout);
    }
  }

  /**
   * Ask Binance the time and keep how far this device is from it.
   *
   * Taken at the middle of the round trip, which is where the server read its
   * clock if the two legs took the same time. False if it could not be asked.
   */
  private async learnClock(): Promise<boolean> {
    try {
      const before = Date.now();
      const r = await this.send<{ serverTime?: number }>('time', {}, {}, Math.min(ALIVE_CHECK_TIMEOUT_MS, this.timeout));
      const after = Date.now();
      if (typeof r?.serverTime !== 'number') return false;
      clockOffsets.set(this.opts.url, r.serverTime - (before + after) / 2 - CLOCK_MARGIN_MS);
      return true;
    } catch {
      return false;
    }
  }

  private async send<T>(
    method: string,
    params: Record<string, string | number | undefined>,
    opts: { signed?: boolean; clientOrderId?: string },
    timeoutMs: number,
  ): Promise<T> {
    await this.connect();
    const ws = this.ws;
    if (!ws || ws.readyState !== WebSocket.OPEN) throw new SocketOpenError('binance ws is not open');

    const clean: Record<string, string | number> = {};
    for (const [k, v] of Object.entries(params)) if (v !== undefined) clean[k] = v;

    if (opts.signed) {
      clean.apiKey = this.opts.cred.keyId;
      clean.timestamp = Date.now() + Math.round(clockOffsets.get(this.opts.url) ?? 0);
      clean.signature = await this.sign(clean);
    }

    const id = `t${++this.seq}`;
    const frame = JSON.stringify({ id, method, params: clean });

    return new Promise<T>((resolve, reject) => {
      const timer = setTimeout(() => {
        this.pending.delete(id);
        reject(
          new UnknownOutcomeError(
            `Binance did not answer ${method} within ${timeoutMs}ms`,
            opts.clientOrderId,
          ),
        );
        // A socket that let a request go unanswered this long is not one to
        // send the next order down. See abandon.
        if (this.ws === ws) this.abandon();
      }, timeoutMs);

      this.pending.set(id, {
        resolve: resolve as (v: unknown) => void,
        reject,
        timer,
        clientOrderId: opts.clientOrderId,
      });
      ws.send(frame);
    });
  }

  /**
   * Place an order.
   *
   * `newClientOrderId` is not optional here, and that is the point. Binance
   * rejects a duplicate client id, which makes a retry safe, and it is the
   * only handle that survives a dropped socket. An order placed without one
   * cannot be reconciled afterwards.
   */
  placeOrder(params: {
    symbol: string;
    side: 'BUY' | 'SELL';
    type: 'LIMIT' | 'LIMIT_MAKER' | 'MARKET';
    newClientOrderId: string;
    quantity?: string;
    quoteOrderQty?: string;
    price?: string;
    timeInForce?: 'GTC' | 'IOC' | 'FOK';
    /** Milliseconds after its timestamp that Binance may still act on it. */
    recvWindow?: number;
  }): Promise<BinanceOrder> {
    return this.request<BinanceOrder>('order.place', params, {
      signed: true,
      clientOrderId: params.newClientOrderId,
    });
  }

  cancelOrder(symbol: string, origClientOrderId: string): Promise<BinanceOrder> {
    return this.request<BinanceOrder>('order.cancel', { symbol, origClientOrderId }, { signed: true });
  }

  /**
   * The recovery path. Call this whenever a submission ends in an
   * UnknownOutcomeError: it answers whether the order actually exists.
   *
   * Returns undefined only when Binance positively reports no such order
   * (-2013), never when the lookup itself failed, because "I could not tell"
   * and "it is not there" must not collapse into the same answer.
   */
  async findByClientOrderId(symbol: string, origClientOrderId: string): Promise<BinanceOrder | undefined> {
    try {
      return await this.request<BinanceOrder>('order.status', { symbol, origClientOrderId }, { signed: true });
    } catch (e) {
      if (e instanceof BinanceWsError && e.code === -2013) return undefined;
      throw e;
    }
  }

  accountStatus(): Promise<unknown> {
    return this.request('account.status', {}, { signed: true });
  }

  close(): void {
    this.closedByUs = true;
    this.ws?.close();
    this.ws = undefined;
  }
}