Blog
Algorithmic tradingTrading botsRisk controlsBinance

Pre-Trade Checks and Kill Switches for Trading Bots

Pre-trade checks and kill switches for trading bots, with Binance Futures examples for reserving order capacity, cancelling orders, and recovery.

Siebly.io10 min readMarkdown

Checking Orders Before Submission

Two strategies share an account with a $1,000 limit on outstanding buy orders. Each prepares a $600 order. Both read the same available capacity, both pass their checks, and together they submit $1,200. Neither order is too large on its own. The failure is between checking the limit and reserving capacity.

A kill switch has a similar timing problem. Stopping the strategy doesn't remove orders already waiting in a request queue. Closing its connection doesn't cancel orders at the exchange. Those orders can still fill after the bot appears to have stopped.

The examples below reserve the value of a prepared Binance USD-M Futures limit buy and block queued submissions when a halt starts. They use synthetic prices and mock SDK methods, so the demonstration needs no API credentials or exchange connection. Instrument validation is covered by the separate Binance order-filter example.

The checks belong on the submission path shared by every strategy and retry. A strategy-side check can explain why a signal was rejected, but a separate caller mustn't be able to skip the account's limits by calling the exchange client directly.

Start with a Prepared Order

The order-filter example loads instrument metadata and converts a USDT allocation into a price and quantity that satisfy the supported rules. The capacity checks below run after that preparation step.

This example starts after that boundary with a hypothetical 0.010 BTC limit buy at 60,000 USDT, worth 600 USDT. Those are fixture values, not current market data or a claim that the order passes today's Binance filters. The admission and halt checks below answer whether the application may dispatch an already prepared request.

Install decimal.js, save the following as halt-and-reserve.mjs, and append the next two JavaScript blocks in order:

Code example

sh
npm install decimal.js
node halt-and-reserve.mjs

halt-and-reserve.mjs

JavaScript
import { randomUUID } from 'node:crypto';
import Decimal from 'decimal.js';

function positive(value) {
  const result = new Decimal(value);
  if (!result.isFinite() || result.lte(0)) throw new Error('Invalid amount');
  return result;
}

const prepared = Object.freeze({
  symbol: 'BTCUSDT', side: 'BUY', type: 'LIMIT', timeInForce: 'GTC',
  positionSide: 'BOTH', price: 60_000, quantity: 0.010,
  newClientOrderId: randomUUID(),
});
const symbol = prepared.symbol;

A running dispatcher obtains this request from its instrument-specific preparation path and checks the account's supported mode. The example's outstanding-buy budget measures order notional, not the margin required to hold a leveraged position.

Reserving Order Capacity

A valid Binance request can still exceed the bot's limits. Append this function to reserve the final order value before submission. The 800 USDT per-order limit and 1,000 USDT outstanding-buy limit are example application settings.

Reserving the final order value

JavaScript
const reservations = new Map();
const maxOrderUsdt = new Decimal('800');
const maxOpenBuyUsdt = new Decimal('1000');

function reserveBuy(order) {
  const id = order.newClientOrderId;
  if (reservations.has(id)) throw new Error('Order already reserved');
  const notional = positive(order.price).mul(positive(order.quantity));
  if (notional.gt(maxOrderUsdt)) throw new Error('Per-order limit exceeded');
  const committed = [...reservations.values()]
    .reduce((sum, value) => sum.plus(value), new Decimal(0));
  if (committed.plus(notional).gt(maxOpenBuyUsdt)) {
    throw new Error('Outstanding buy limit exceeded');
  }
  // No asynchronous work between the capacity check and reservation.
  reservations.set(id, notional);
}

The reservation runs synchronously. If two prepared orders are each worth 600 USDT, the first reservation succeeds and the second fails. Another task on this JavaScript event loop can't reserve the same capacity between the check and the write. Multiple processes need a shared coordinator or an atomic transaction; giving each worker its own map would recreate the original problem.

This example limits outstanding buy notional. It doesn't calculate portfolio exposure, available funds, fees, or margin. Those need their own checks using the correct account and product fields. A position limit must include the position already held and the possible effect of working orders, including requests whose outcomes are unknown. Opposing buy and sell orders shouldn't simply cancel each other out in that calculation: one side can fill while the other remains open.

A reservation remains until the application can account for the outcome. A confirmed rejection can release it. A fill moves the relevant amount into executed purchases or position exposure; it doesn't restore spending capacity. Partial fills leave the unfilled portion committed. A timeout alone releases nothing, because the exchange may have accepted the order. The unknown-order workflow covers that case.

The client order ID stays with the candidate throughout submission and recovery. The small example retains its reservations and demonstrates admission only. An application needs an order ledger that updates them from accepted order state, plus a separate record of used client IDs so removing a completed reservation doesn't permit an accidental resubmission.

Checking State at Dispatch

The fixture above has no live price reference. A running bot needs a current price appropriate to its strategy at dispatch. A price collar can reject orders too far from a reference, but comparing against an old or incorrect reference can approve the wrong value. Quote age, book integrity, and the choice of price source depend on the calculation.

An unchanged balance or position is different. It doesn't become invalid merely because no private update arrived for thirty seconds. Healthy private events maintain Account State; missing initialization, known stream gaps, and conflicting observations are reasons to recover it. Reconnect and backfill handling explains that distinction.

A request queue introduces another delay. An order that passed its checks before waiting may be obsolete by the time capacity becomes available. The dispatch path checks its deadline, current halt state, price assumptions, and account capacity again. Rate-limit scheduling decides when a request may leave; it doesn't establish that the order is still wanted.

The SDK's submitNewOrder() method sends the prepared Binance request; the application controls whether it reaches that method. The same application checks apply whether submission uses REST or a WebSocket API. If the transport wrapper queues or retries internally, it needs to preserve the halt and deadline rules at its actual dispatch point too.

Implementing a Kill Switch

A halt first blocks further submissions in its scope. A strategy halt may leave other strategies running; an account halt must reach every process that can send orders for that account. The cancellation policy then determines which working orders to cancel. Removing protective orders as a side effect of an account-wide cancel can leave an existing position without those orders.

For a bot that owns all regular orders on a symbol, Binance's cancelAllOpenOrders({ symbol }) provides the cancellation call. A bot sharing that symbol with other strategies needs to select its own orders instead. Conditional orders have a separate algo-order cancellation endpoint, exposed as cancelAllAlgoOpenOrders() in the SDK. Neither call should accidentally remove another strategy's protection.

Append this block to the same file. The injected client has the Binance SDK's method names, but the runnable example uses mocks. The queued buy reaches the dispatcher after the halt starts.

Halting submissions and cancelling Binance orders

JavaScript
let haltReason = null;
let newOrdersSent = 0;

function dispatchBuy(order, client) {
  if (haltReason !== null) throw new Error(`Halted: ${haltReason}`);
  reserveBuy(order);
  // Pass a copy because the SDK may add request fields.
  return client.submitNewOrder({ ...order });
}

async function haltAndCancel(reason, symbols, client) {
  haltReason ??= reason;
  return Promise.allSettled(symbols.map((symbol) =>
    Promise.resolve().then(() => client.cancelAllOpenOrders({ symbol })),
  ));
}

const mockClient = {
  async submitNewOrder(order) {
    newOrdersSent += 1;
    return { clientOrderId: order.newClientOrderId };
  },
  async cancelAllOpenOrders({ symbol }) {
    console.log('Cancel requested:', symbol);
    return { code: 200, msg: 'Mock cancellation completed' };
  },
};
const queuedResult = Promise.resolve()
  .then(() => dispatchBuy(prepared, mockClient))
  .catch((error) => error.message);
const cancellations = haltAndCancel('manual stop', [symbol], mockClient);

console.log(await queuedResult);
console.log('New orders sent:', newOrdersSent);
console.log('Cancel request results:', await cancellations);

The halt takes effect before the first await. The queued order fails with Halted: manual stop, and New orders sent remains zero. Cancellation runs separately, so a blocked submission path doesn't also block attempts to remove existing orders. The halt remains set even if every cancel request fails. An authenticated USDMClient would send these operations to Binance; the fixture must first be replaced by the actual instrument and account validation path.

In an actual dispatcher, validation, capacity reservation, and the start of submission need coordinated ordering with the halt. An order already handed to the transport can still reach the exchange. For example, the first scan may find no working orders while a submission response is still pending. If that response later identifies an accepted order, the cancellation policy still applies to it. The initial scan hasn't completed the halt.

The example handles one process and a supplied list of symbols. A larger system must persist the halt, have every sender observe it, and discover all affected working and unresolved orders. Cancellation requests still need bounded timeouts and their own available rate-limit capacity. A large account may require pagination or several cancellation batches.

Handling Fills During Cancellation

A cancel-all response doesn't describe fills that happened before cancellation. The order manager still needs to account for those executions. On Binance, private order updates and targeted getOrder({ symbol, origClientOrderId }) lookups can resolve individual orders. Other exchanges have different response semantics: Bybit cancellation is asynchronous, so its initial response only acknowledges the request.

Consider a 0.010 BTC buy order with 0.004 BTC filled when the halt starts:

EventAccount state
Halt blocks new submissions0.004 BTC bought; 0.006 BTC may still fill.
Cancel request is in flightRemaining quantity is still unresolved.
Another 0.002 BTC fills before cancellation0.006 BTC bought; 0.004 BTC remains.
Order becomes cancelled0.006 BTC bought; no remaining quantity on this order.

The position doesn't return to zero when the remaining order is cancelled. Closing it requires another trade, with a separate decision about sizing, price, and execution. A kill switch that stops new orders or cancels working orders should report that outcome precisely. It shouldn't claim the account is flat.

Bybit's order-stream documentation also describes repeated Filled messages when a fill races with cancellation. The deduplication article covers applying repeated observations without counting execution twice.

Surviving a Process Failure

A local halt function can't send cancellation requests after its process crashes or loses network access. Binance USD-M Futures provides countdown cancellation per symbol. The SDK call is:

Renewing Binance's cancellation timer

JavaScript
function renewCancelTimer(client) {
  return client.setCancelOrdersOnTimeout({
    symbol: 'BTCUSDT',
    countdownTime: 120_000,
  });
}

Binance documents renewing a 120-second timer every 30 seconds. If renewal stops, expiry triggers cancellation. A timeout of zero disables the timer; it doesn't request immediate cancellation. This function belongs in the authenticated execution service and isn't called by the runnable example.

Renewal should depend on the trading workflow being healthy enough to keep its orders working. A separate heartbeat process that continues renewing while the order manager is broken can defeat the intended behaviour. The timer's scope and treatment of protective orders also need to match the account's cancellation policy. This mechanism doesn't close positions created by earlier fills.

Submission ownership matters here too. Code elsewhere with the same trading credentials can bypass an in-process gate. Keeping trading credentials at the execution service and separating unrelated accounts makes the scope enforceable. Credential storage and permissions are covered in the security guidance.

Restarting After a Halt

A restart mustn't clear the halt just because a Boolean returned to its default value. Startup loads the recorded halt and order state before enabling submissions. A missing or unreadable record leaves the sender paused until the state is established.

Recovery checks unresolved submissions, cancellation outcomes, remaining working orders, and the resulting balances or positions. An empty open-order response alone can't explain an order that filled during the outage. The account-recovery procedure covers the necessary lookups and stream handling.

Once those facts are known, resuming is a separate action. Old queued signals may no longer apply and should expire rather than drain automatically on restart. Useful halt records identify the account or strategy, the cause, unresolved order IDs, and which cancellations failed. That gives the operator something more actionable than a green connection indicator.

A brief check through the bot's actual submission path can exercise an oversized order, concurrent reservations, a halt with queued work, and a fill racing with cancellation. A mock adapter or the exchange's supported demo environment is enough to start; a separate script that bypasses the dispatcher won't check the same behaviour.

Related articles

Continue from here

Related Siebly resources

All articles

Subscribe on Substack

Complete the Substack form below to join our newsletter. Substack handles all subscriber data directly.