Binance adapter
Decides which Binance an order goes to, the practice testnet or the real one. Unedited, from build 579b29d3.
// Binance and Binance.US, over the WebSocket API.
//
// The transport lives in binanceWs.ts and the reason it exists is there too:
// Binance's REST preflight allows neither POST nor the api-key header, so a
// browser cannot place an order over REST at all. This file is the mapping
// layer on top, and it inherits one hard constraint from that transport. An
// unrecognised key gets the socket closed with no error frame, so a failed
// auth and a resting order are indistinguishable, and every ambiguous failure
// arrives as UnknownOutcomeError rather than as a failure. Callers must
// reconcile those with findByClientOrderId instead of reporting a loss.
//
// Symbols are the awkward part. Binance concatenates with no separator, so
// BTCUSDT is unambiguous going out and genuinely ambiguous coming back: it
// could be BTC/USDT or BTCU/SDT if such a pair existed. The reverse mapping
// therefore matches against a known quote list, longest first, rather than
// guessing at a split point.
import { BinanceWsClient, BinanceWsError, SocketOpenError, UnknownOutcomeError, type BinanceOrder } from '../binanceWs';
import { requiredSandbox } from '../rollout';
import { restFallback } from './relayBridge';
import type { SigningCredential } from '../keystore';
import { VENUES } from '../venues';
import {
ExchangeError,
type AdapterOptions,
type Balance,
type Fill,
type Order,
type OrderRequest,
type PermissionReport,
type TradingAdapter,
} from './types';
// Longest first, so USDT wins over USD and FDUSD is not read as USD.
const QUOTES = ['FDUSD', 'TUSD', 'USDT', 'USDC', 'BUSD', 'USD', 'EUR', 'TRY', 'BTC', 'ETH', 'BNB'];
const TESTNET_WS = 'wss://ws-api.testnet.binance.vision/ws-api/v3';
/**
* One socket per credential and environment, reused across calls.
*
* Opening a WebSocket costs a round trip and Binance rate-limits connections
* far more tightly than requests, so a client per order would hit the
* connection limit long before the request weight limit.
*/
const clients = new Map<string, BinanceWsClient>();
function clientFor(id: string, cred: SigningCredential, opts?: AdapterOptions): BinanceWsClient {
if (!cred.key) {
throw new ExchangeError(id, 401, 'no_credential', `this ${id} key is not unlocked`);
}
// Which endpoint this adapter is allowed to open, decided here and nowhere
// else. Every call in this file goes through clientFor, so pinning the URL
// at this one point is what makes "paper only" a property of the transport
// rather than a rule each caller has to remember. While the gate says paper,
// ws-api.binance.com is not reachable from this adapter at all: not by an
// order, not by a cancel, not by a balance read, and not by a caller that
// passed the wrong options or none.
//
// requiredSandbox() answers undefined where the gate has no opinion, and only
// then does the caller's own choice decide.
const sandbox = requiredSandbox(id) ?? opts?.sandbox ?? false;
const url = sandbox ? TESTNET_WS : VENUES[id]?.wsUrl;
if (!url) {
throw new ExchangeError(id, 500, 'no_endpoint', `no WebSocket endpoint is configured for ${id}`);
}
const cacheKey = `${id}:${cred.keyId}:${sandbox ? 'test' : 'live'}`;
let client = clients.get(cacheKey);
if (!client) {
client = new BinanceWsClient({ url, cred: { keyId: cred.keyId, key: cred.key } });
clients.set(cacheKey, client);
}
return client;
}
/** Drop every cached socket. Called when the vault locks. */
export function closeBinanceClients(): void {
for (const c of clients.values()) c.close();
clients.clear();
}
function mapStatus(s: string): Order['status'] {
switch (s) {
case 'FILLED':
return 'filled';
case 'CANCELED':
case 'EXPIRED':
case 'EXPIRED_IN_MATCH':
return 'cancelled';
case 'REJECTED':
return 'rejected';
case 'NEW':
case 'PARTIALLY_FILLED':
case 'PENDING_CANCEL':
return 'open';
default:
return 'pending';
}
}
/** One execution, as `myTrades` reports it. */
interface BinanceTrade {
id: number;
orderId: number;
symbol: string;
price: string;
qty: string;
quoteQty?: string;
commission?: string;
commissionAsset?: string;
time: number;
isBuyer: boolean;
}
/** Binance's own cap on a myTrades call. */
const MAX_TRADES = 1000;
/**
* A commission in the quote currency, which is the only unit the P&L matcher
* adds up, or nothing at all.
*
* Binance charges in whatever asset it likes. On a spot buy that is the asset
* you received, so a BTC/USDT buy is charged in BTC and reading the number as
* dollars would be wrong by five orders of magnitude. It is still exactly
* convertible: a commission denominated in the base asset is worth
* commission x price of the quote, at this fill's own price, which is an
* identity rather than an estimate. Without it every entry fee on Binance
* reports as zero, since buys are charged in base and only sells in quote.
*
* A commission in BNB (which is what the fee discount does) has no such
* identity, because nothing in the fill says what BNB was worth. Those are
* dropped, which understates fees, and understating is the safe direction: it
* never invents a profit that was not there.
*/
function quoteFee(t: BinanceTrade, base: string, quote: string): string | undefined {
if (!t.commission || Number(t.commission) === 0) return undefined;
if (t.commissionAsset === quote) return t.commission;
if (t.commissionAsset === base) return String(Number(t.commission) * Number(t.price));
return undefined;
}
/**
* Binance's -1121 ("Invalid symbol.") in words that say why.
*
* On the testnet it is almost always a market the testnet does not list:
* the live exchange has 3,698 spot pairs and the testnet 1,363, and the chart
* offers every one of the live ones. Binance's own two words leave the reader
* thinking the app spelt the symbol wrong. On the live exchange it is the
* rarer case of a pair that has been delisted since the market list was read.
*/
function describeUnknownMarket(e: unknown, id: string, symbol: string, sandbox: boolean): unknown {
if (e instanceof BinanceWsError && e.code === -1121) {
// Named for the exchange the key is on. Binance.US is a separate exchange
// with its own list, and a message naming Binance sent people to look on
// the wrong one.
const venue = id === 'binanceus' ? 'Binance.US' : 'Binance';
return new ExchangeError(
id,
400,
'unknown_market',
sandbox
? `${symbol} is not on Binance's testnet, which lists fewer markets than the live exchange. `
+ 'Practice orders can only be placed on markets the testnet has, so there is nothing to '
+ 'show for this one here. The chart and the book still work.'
: `${venue} has no ${symbol} market any more, so there is nothing to show for it here.`,
);
}
return e;
}
/** Order states under which the order is still on the book and can be cancelled. */
const RESTING = new Set(['NEW', 'PARTIALLY_FILLED', 'PENDING_NEW', 'PENDING_CANCEL']);
/**
* Binance's -2011 ("Unknown order sent.") on a cancel, looked into.
*
* Binance gives the same two words for an order that filled, one already
* cancelled (from its own app, or by this one a moment ago) and an id it never
* had. In every one of those cases there is nothing resting to take off, which
* is the thing the person asking needs to know, so the order is looked up and
* the answer says which it was. A market order is the usual case: it fills the
* moment it lands and was never open to cancel.
*/
async function explainUnknownCancel(
e: unknown,
id: string,
client: BinanceWsClient,
marketSymbol: string,
orderId: string,
): Promise<unknown> {
if (!(e instanceof BinanceWsError) || e.code !== -2011) return e;
const found = await client.findByClientOrderId(marketSymbol, orderId).catch(() => null);
// Still resting by the exchange's own account: the refusal stands as it is.
if (found && RESTING.has(found.status)) return e;
const why =
found?.status === 'FILLED'
? 'That order already filled, so there was nothing left to cancel.'
: found?.status === 'CANCELED'
? 'That order was already cancelled.'
: 'That order is no longer open.';
// A lookup that failed (null) or found nothing still leaves -2011 itself,
// which is the exchange saying nothing rests under this id.
return new ExchangeError(id, 404, 'not_open', why);
}
/**
* How long Binance may take to act on an order after it was signed. Sent with
* every order, so an order still in flight after this is one Binance refuses
* on arrival, and "no such order" past it is final rather than "not yet".
*/
const RECV_WINDOW_MS = 5_000;
/** Clock drift and the time the lookup itself spends in flight. */
const RECV_MARGIN_MS = 2_000;
const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
/**
* The order was sent and the answer was lost: look it up and report what
* Binance holds.
*
* Until November 2026 the ticket said "Sent, but the exchange did not
* confirm" and left it there, 85 times in a month, and a market order that
* filled is in no open orders list to check. The lookup goes down a socket
* that answers (the client drops one that let a request go unanswered), and
* a lookup that fails leaves the outcome unknown, as before: "I could not
* tell" never becomes "it is not there".
*/
async function reconcilePlaced(
id: string,
client: BinanceWsClient,
marketSymbol: string,
clientOrderId: string,
sentAt: number,
lost: UnknownOutcomeError,
): Promise<BinanceOrder> {
// The vault locked with the order in flight. Nothing may reopen the socket.
if (client.closedLocally) throw lost;
for (;;) {
let found: BinanceOrder | undefined;
try {
found = await client.findByClientOrderId(marketSymbol, clientOrderId);
} catch {
throw lost;
}
if (found) return found;
const wait = sentAt + RECV_WINDOW_MS + RECV_MARGIN_MS - Date.now();
if (wait <= 0) {
throw new ExchangeError(
id,
404,
'not_placed',
'The connection to Binance dropped before the order reached it, so nothing was placed. You can send it again.',
);
}
// Too soon for "not there" to mean "never will be": the order may still
// be on its way. Asked again once it can no longer arrive.
await sleep(wait);
}
}
function makeAdapter(id: 'binance' | 'binanceus'): TradingAdapter {
const adapter: TradingAdapter = {
id,
// Nothing reads this today, so it is documentation. Kept honest anyway: it
// lists what clientFor above will actually open, which while the gate says
// paper is the testnet and nothing else.
hosts: requiredSandbox(id) === true
? [new URL(TESTNET_WS).hostname]
: [new URL(VENUES[id]?.wsUrl ?? TESTNET_WS).hostname, new URL(TESTNET_WS).hostname],
// Binance's spot testnet is a real matching engine with virtual funds, so
// an order genuinely rests, fills and cancels. Note it is unreachable from
// a geo-blocked network, which includes this project's dev machine: see
// TRADING_TESTING.md.
//
// Binance.US has no testnet. This testnet belongs to Binance.com, takes
// Binance.com testnet keys and refuses US addresses, which is everyone who
// can hold a Binance.US account, so a practice switch there would lead
// nowhere.
sandbox: id === 'binance' ? 'paper' : 'none',
// ws-api.binance.com is the spot API. Futures live on a different host
// with a different API, and nothing here speaks it.
spotOnly: true,
// Every trade-history call Binance offers takes a symbol and rejects the
// request without one: myTrades needs it, allOrders needs it, and there is
// no account-wide equivalent of either. So this venue can answer "what did
// I do on BTC/USDT" and cannot answer "what did I do", and saying so here
// is what stops the reports screen reporting a silent nothing.
fillHistory: 'symbol',
// Binance spot exposes post-only as the GTX time in force, and lists no
// dated mode at all, so there is no gtd here to offer.
supports: { postOnly: true, timeInForce: ['gtc', 'ioc', 'fok'], bracket: false },
// Spot only. The exchange listing this app draws from carries Binance's
// perpetuals and dated futures under the same id, spelled BTC/USD:BTC and
// BTC/USDT:USDT-250926 in ccxt's notation, and the spot API takes none of
// them: it answers "Illegal characters found in parameter 'symbol'" to the
// colon, which reads as a bug in this app rather than the fact that the
// market is on a different Binance. Refused here, since every call in
// this file spells the market through this one function.
toMarketSymbol: (symbol) => {
if (symbol.includes(':')) {
const base = symbol.split('/')[0].toUpperCase();
throw new ExchangeError(
id,
400,
'not_spot',
`${symbol} is a futures market, and this connection trades Binance spot only. `
+ `Pick a spot market such as ${base}/USDT.`,
);
}
// Every separator goes, not just the slash. The chart spells a
// Binance.US market BTC-USD (its own ids are dashed, like Coinbase's),
// and BTC-USD sent as it was is a market Binance has never heard of:
// the open orders and fills for it failed on every load, which left an
// order placed a minute ago stuck on screen and nothing at all after a
// restart.
return symbol.toUpperCase().replace(/[-/_]/g, '');
},
fromMarketSymbol(symbol) {
const s = symbol.toUpperCase();
const quote = QUOTES.find((q) => s.endsWith(q) && s.length > q.length);
return quote ? `${s.slice(0, -quote.length)}/${quote}` : s;
},
async validate(cred, opts): Promise<PermissionReport> {
const client = clientFor(id, cred, opts);
const notes: string[] = [];
try {
// account.status also returns canWithdraw, and it is not read here on
// purpose. That flag is the account's, not the key's: a verified
// account reads true whatever restrictions the key was created with,
// so it said every live key could withdraw, including ones made by
// the guide's own steps. The key's restrictions are on a REST-only
// endpoint (sapi apiRestrictions) the WebSocket API does not offer,
// so the report leaves canWithdraw unknown and the key form's copy
// carries the ask instead.
const account = await client.request<{
canTrade?: boolean;
accountType?: string;
}>('account.status', {}, { signed: true });
const canTrade = Boolean(account.canTrade);
if (!canTrade) notes.push('this key cannot trade: enable Spot Trading on Binance');
if (opts?.sandbox) notes.push('connected to the spot testnet, so no real money is at risk');
if (id === 'binance' && !opts?.sandbox) {
notes.push(
'Binance expires a trade-enabled key 90 days after creation unless it is '
+ 'restricted to an IP address, and this app connects from your own device. '
+ 'Expect to recreate it.',
);
}
return {
ok: canTrade,
canRead: true,
canTrade,
notes,
};
} catch (e) {
// A socket that never opened carried no key, so Binance has said
// nothing about it, though until November 2026 the connect sheet
// told the user Binance had refused the key.
if (e instanceof SocketOpenError) {
return { ok: false, canRead: false, canTrade: false, unreachable: true, notes: [e.message] };
}
// A socket that closed once open, with the request in flight, is
// almost always a key Binance does not recognise, since that is
// exactly how it reports one.
const message =
e instanceof UnknownOutcomeError
? 'Binance closed the connection without answering, which usually means it does not recognise this key'
: (e as Error).message;
return { ok: false, canRead: false, canTrade: false, notes: [message] };
}
},
async getBalances(cred, opts): Promise<Balance[]> {
const client = clientFor(id, cred, opts);
const account = await client.request<{ balances?: { asset: string; free: string; locked: string }[] }>(
'account.status',
{},
{ signed: true },
);
return (account.balances ?? [])
.filter((b) => Number(b.free) > 0 || Number(b.locked) > 0)
.map((b) => ({ asset: b.asset, free: b.free, locked: b.locked }));
},
async getFills(cred, symbol, limit = 100, opts): Promise<Fill[]> {
if (!symbol) {
throw new ExchangeError(
id,
400,
'symbol_required',
'Binance reports trades one market at a time, so it needs the market',
);
}
const client = clientFor(id, cred, opts);
const trades = await client
.request<BinanceTrade[]>(
'myTrades',
{ symbol: adapter.toMarketSymbol(symbol), limit: Math.min(limit, MAX_TRADES) },
{ signed: true },
)
.catch((e) => {
throw describeUnknownMarket(e, id, symbol, Boolean(opts?.sandbox));
});
return trades
.map((t) => {
const canonical = adapter.fromMarketSymbol(t.symbol);
const [base, quote] = canonical.split('/');
return {
id: String(t.id),
symbol: canonical,
side: t.isBuyer ? 'buy' : 'sell',
price: t.price,
quantity: t.qty,
fee: quoteFee(t, base, quote),
time: new Date(t.time).toISOString(),
} satisfies Fill;
})
// Binance answers oldest first, and every other venue here is newest
// first. The matcher sorts for itself; the caller's slice does not.
.reverse();
},
async getOpenOrders(cred, symbol, opts): Promise<Order[]> {
const client = clientFor(id, cred, opts);
const orders = await client
.request<BinanceOrder[]>(
'openOrders.status',
{ symbol: symbol ? adapter.toMarketSymbol(symbol) : undefined },
{ signed: true },
)
.catch((e) => {
throw describeUnknownMarket(e, id, symbol ?? '', Boolean(opts?.sandbox));
});
return orders.map((o) => toOrder(o, adapter));
},
async createOrder(cred, order, opts): Promise<Order> {
if (order.type === 'limit' && !order.price) {
throw new ExchangeError(id, 400, 'missing_price', 'a limit order needs a price');
}
const client = clientFor(id, cred, opts);
// Binance spells post-only as its own order type, LIMIT_MAKER, which
// takes no time in force at all.
const maker = order.type === 'limit' && order.postOnly === true;
const market = adapter.toMarketSymbol(order.symbol);
const sentAt = Date.now();
const placed = await client
.placeOrder({
symbol: market,
side: order.side.toUpperCase() as 'BUY' | 'SELL',
type: maker ? 'LIMIT_MAKER' : (order.type.toUpperCase() as 'LIMIT' | 'MARKET'),
newClientOrderId: order.clientOrderId,
quantity: order.quantity,
quoteOrderQty: order.quoteQuantity,
price: order.price,
// Binance requires a time in force on a limit order and rejects one
// on a market order, so it is set only where it belongs.
timeInForce:
order.type === 'limit' && !maker ? ((order.timeInForce ?? 'gtc').toUpperCase() as 'GTC') : undefined,
recvWindow: RECV_WINDOW_MS,
})
.catch((e) => {
if (e instanceof UnknownOutcomeError) {
return reconcilePlaced(id, client, market, order.clientOrderId, sentAt, e);
}
throw describeUnknownMarket(e, id, order.symbol, Boolean(opts?.sandbox));
});
return toOrder(placed, adapter);
},
async cancelOrder(cred, orderId, symbol, opts) {
if (!symbol) {
throw new ExchangeError(id, 400, 'symbol_required', 'Binance needs the market to cancel an order');
}
const client = clientFor(id, cred, opts);
const market = adapter.toMarketSymbol(symbol);
// Cancelled by client order id, not exchange id: it is the identifier
// this app generated and the one it can always reproduce.
try {
await client.cancelOrder(market, orderId);
} catch (e) {
throw await explainUnknownCancel(e, id, client, market, orderId);
}
return { id: orderId, cancelled: true };
},
async findByClientOrderId(cred, clientOrderId, symbol, opts): Promise<Order | undefined> {
if (!symbol) {
throw new ExchangeError(id, 400, 'symbol_required', 'Binance needs the market to look an order up');
}
const client = clientFor(id, cred, opts);
const found = await client.findByClientOrderId(adapter.toMarketSymbol(symbol), clientOrderId);
return found ? toOrder(found, adapter) : undefined;
},
};
return withRestFallback(id, adapter);
}
/**
* The same adapter, going over REST from the phone when its socket will not open.
*
* A socket that never opened sent nothing, not a balance read and not an
* order, so the same call over REST cannot be a second copy of anything. On
* a phone that can send it (restFallback says where), the call is made there;
* anywhere else, or on the testnet, the socket's own error stands as before.
* Orders are named by this app's client id either way: the REST adapter's
* answer is put back in that shape, and a cancel looks the order up first,
* since REST cancels by Binance's own id.
*/
function withRestFallback(id: 'binance' | 'binanceus', ws: TradingAdapter): TradingAdapter {
const rest = (opts: AdapterOptions | undefined) => restFallback(id, Boolean(requiredSandbox(id) ?? opts?.sandbox));
// The REST adapter takes and gives Binance's own spelling (BTCUSDT), as the
// relay hands it over; the app's is BTC/USDT.
const market = (symbol: string | undefined) => (symbol ? ws.toMarketSymbol(symbol) : undefined);
const inAppShape = (o: Order): Order => ({
...o,
id: o.clientOrderId ?? o.id,
symbol: o.symbol.includes('/') ? o.symbol : ws.fromMarketSymbol(o.symbol),
status: o.status in STATUS_WORDS ? o.status : mapStatus(o.status),
rawStatus: o.rawStatus ?? o.status,
});
async function either<T>(
opts: AdapterOptions | undefined,
viaSocket: () => Promise<T>,
viaRest: (r: TradingAdapter) => Promise<T>,
): Promise<T> {
try {
return await viaSocket();
} catch (e) {
const r = e instanceof SocketOpenError ? rest(opts) : undefined;
if (!r) throw e;
return viaRest(r);
}
}
return {
...ws,
async validate(cred, opts) {
const report = await ws.validate(cred, opts);
const r = report.unreachable ? rest(opts) : undefined;
return r ? r.validate(cred, opts) : report;
},
getBalances: (cred, opts) => either(opts, () => ws.getBalances(cred, opts), (r) => r.getBalances(cred, opts)),
getOpenOrders: (cred, symbol, opts) =>
either(
opts,
() => ws.getOpenOrders(cred, symbol, opts),
async (r) => (await r.getOpenOrders(cred, market(symbol), opts)).map(inAppShape),
),
getFills: (cred, symbol, limit, opts) =>
either(
opts,
() => ws.getFills!(cred, symbol, limit, opts),
async (r) =>
(r.getFills ? await r.getFills(cred, market(symbol), limit, opts) : []).map((f) => ({
...f,
symbol: f.symbol.includes('/') ? f.symbol : ws.fromMarketSymbol(f.symbol),
})),
),
createOrder: (cred, order, opts) =>
either(
opts,
() => ws.createOrder(cred, order, opts),
async (r) => inAppShape(await r.createOrder(cred, { ...order, symbol: ws.toMarketSymbol(order.symbol) }, opts)),
),
findByClientOrderId: (cred, clientOrderId, symbol, opts) =>
either(
opts,
() => ws.findByClientOrderId(cred, clientOrderId, symbol, opts),
async (r) => {
const o = await r.findByClientOrderId(cred, clientOrderId, market(symbol), opts);
return o ? inAppShape(o) : undefined;
},
),
cancelOrder: (cred, orderId, symbol, opts) =>
either(
opts,
() => ws.cancelOrder(cred, orderId, symbol, opts),
async (r) => {
// Cancelled by this app's client id over the socket; REST cancels by
// Binance's own, so the order is looked up for it.
const o = await r.findByClientOrderId(cred, orderId, market(symbol), opts);
if (!o) throw new ExchangeError(id, 404, 'not_open', 'That order is no longer open.');
await r.cancelOrder(cred, o.id, market(symbol), opts);
return { id: orderId, cancelled: true };
},
),
};
}
/** The app's own order states, which an answer already in them keeps. */
const STATUS_WORDS: Record<string, true> = { open: true, filled: true, cancelled: true, rejected: true, pending: true };
function toOrder(o: BinanceOrder, adapter: TradingAdapter): Order {
return {
id: o.clientOrderId ?? String(o.orderId),
clientOrderId: o.clientOrderId,
symbol: adapter.fromMarketSymbol(o.symbol),
side: o.side?.toLowerCase() === 'sell' ? 'sell' : 'buy',
// LIMIT_MAKER is a limit order that refuses to take, and reads as one.
type: o.type === 'LIMIT' || o.type === 'LIMIT_MAKER' ? 'limit' : 'market',
status: mapStatus(o.status),
rawStatus: o.status,
price: o.price,
quantity: o.origQty,
filledQuantity: o.executedQty,
createdAt: o.transactTime ? new Date(o.transactTime).toISOString() : undefined,
};
}
export const binance = makeAdapter('binance');
export const binanceus = makeAdapter('binanceus');