# What happens if my trading bot crashes with a position open?

A kill switch inside the bot dies with the bot; its orders and position stay at the venue. A venue timer can cancel the protective stop with the entries, and a closing order can be throttled while cancels pass. Persist a halt that blocks new risk across restarts, allow only verified exits, and drill a crash on paper.

Canonical: <https://pitofficer.com/blog/trading-bot-crashed-open-position/>
Author: Eugene Palchukovsky <https://github.com/palchukovsky>
Description: A kill switch inside your bot dies with it while the venue keeps its orders and position: what venue timers cancel, a halt that survives a restart, a drill.
Published: 2026-10-15T22:15:19+03:00
Updated: 2026-10-15T22:15:19+03:00
Tags: risk-controls, kill-switch, trading-bots

Your bot is long 2 BTC with a stop at the venue when its process dies. Its
orders can keep working without it, and what decides the loss is what can still
act while the bot is down.

:::stat
**Up to 6.2 BTC**

What the bot can hold a minute after the crash below, against a stop for 2 BTC
or none. The times and quantities are illustrative.
:::

:::timeline

1. **12:00:00 The bot refreshes a 60-second venue cancel timer.** Long 2 BTC,
   a stop for 2 at the venue, a buy for 3 working.
2. **12:00:07 The process dies.** Its loss check dies with it.
3. **12:00:58 The buy fills 1.2.** Nothing resizes the stop: long 3.2, a stop
   for 2.
4. **12:01:00 The timer fires.** It cancels the rest of the buy, and the stop
   too if the venue counts it as an open order.
5. **12:01:05 A supervisor restarts the bot.** Its memory says the buy is
   working; the venue shows none, so it sends a new buy for 3.
6. **12:01:06 The bot tries to place a full-size stop.** If a crash loop spent
   the request budget, the venue can throttle or reject it.

:::

:::cards

- **The venue keeps what it accepted.** Entries can fill, stops can trigger,
  and the position stays exposed; only what ran inside the bot stops.
- **A venue cancel timer can take your stop with it.** Kraken Spot's timer
  cancels all client orders; others say "open orders" without saying whether
  conditional orders count.
- **Cancels and closes can have different budgets.** On Hyperliquid a
  rate-limited address can still cancel while its cancel allowance lasts, but
  closes and new stops share one request per 10 seconds.
- **A halt is stored durably before it acts.** It is read at start-up before any order
  goes out, and cleared only by a verified check or a person.
- **A switch that fires on bad data is a failure too.** An unverified input
  should block entries, not flatten the position.

:::

## What keeps running at the venue when your bot dies?

**Everything the venue accepted and has not removed; what stops is everything
that lived in the process.**

:::outcomes

- **Working orders.** Entries can still fill, and stops can still trigger.
- **The position.** It stays exposed to fills, margin, funding and, on
  derivatives, liquidation.
- **How working orders end.** A fill, an expiry, a cancel-on-disconnect or timer, or a
  cancel sent by another client.
- **What dies with the bot.** The loss check, the logic that resizes the stop
  after a fill, the refresh of any venue timer, and the stop button that calls
  into the bot.

:::

The restart at 12:01:05 failed because it trusted the bot's memory over the
venue;
[rebuilding the position from the venue](/blog/trading-bot-position-out-of-sync-with-broker/)
before the first order is its own subject.

:::more[What a kill switch is, and the other terms this article uses]
A **kill switch** is a control that, once activated, disables a trading
system's trading: no new orders, and its working orders canceled; it may still
allow orders that reduce risk
([FIA, *Best Practices for Automated Trading Risk Controls and System Safeguards*](https://www.fia.org/sites/default/files/2024-07/FIA_WP_AUTOMATED%20TRADING%20RISK%20CONTROLS_FINAL_0.pdf),
July 2024, section 1.5).

**Cancel-on-disconnect** is a venue service that makes a best-effort attempt to
cancel a session's resting orders when the venue detects that the session's
connection is lost; the venue decides what counts as a disconnect, a network
error or missed application heartbeats (FIA, section 1.4). A **dead man's
switch** is a venue timer that cancels orders when the client stops refreshing
it before its deadline.

A **halt** is a persisted block on new risk: it lives outside the process, so a
restarted bot comes back halted. **Reduce-only** is an order flag, offered by
some venues, that lets an order only decrease an existing position; each
venue's name for it is in [the venue notes](#what-does-each-venue-document).
:::

:::more[Why no switch inside the bot could catch any of it]
The crash above is the one a perpetual futures bot typically sets up: a
fixed-size stop-market sell for 2 BTC resting at the venue, an entry buy limit
for 3 BTC working with nothing filled, and a venue cancel timer of 60 seconds
that the bot refreshes every 15. At 12:00:07 the process is killed, out of
memory. At 12:01:05 its persisted state says long 2, stop in place, entry
working, so the strategy, still sized on long 2, sends a new buy for 3: up to
6.2 BTC.

- **12:00:58**: a partial fill two seconds before the cancel enlarged the
  position the stop was sized for, with no one there to resize it.
- **12:01:00**: the control meant to remove unattended orders may have removed
  the one order that protected the position.
- **12:01:05 to 12:01:06**: the restart trusted the bot's memory instead of the
  venue, and the bot's ability to repair the position depended on a budget it
  had already spent. The new stop protects nothing until the venue has accepted
  it.

:::

## Which switches live at the venue?

**Two kinds: cancel-on-disconnect fires when the connection drops; a dead man's
timer also fires when the connection stays up and the bot goes silent.**

:::matrix

| Venue switch | Fires on a silent bot | Cancels the stop |
| --- | --- | --- |
| Deribit cancel-on-disconnect | ~ [1] | ~ [2] |
| Binance USDⓈ-M countdown | ✓ [3] | ? [4] |
| Kraken Spot timer | ✓ [5] | ✓ [5] |
| Hyperliquid scheduled cancel | ✓ [6] | ? [6] |

1. When the connection closes, including Deribit's close after 10 minutes
   with no activity; an explicit logout does not trigger it
   ([Deribit](https://docs.deribit.com/api-reference/session-management/private-enable_cancel_on_disconnect)).
2. Only orders sent through the connection that dropped.
3. One timer per symbol; a symbol never armed has none
   ([Binance](https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Auto-Cancel-All-Open-Orders)).
4. "All open orders" of the symbol; USDⓈ-M stops now live in a separate
   service, and Binance does not say whether the countdown reaches them.
5. All client orders; once fired, it stays off until armed again
   ([Kraken](https://docs.kraken.com/api-reference/trading/cancel-all-orders-after-x)).
6. All open orders, conditional orders not mentioned; at most 10 triggers per
   UTC day
   ([Hyperliquid](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint)).

:::

A timer measures whatever refreshes it: refreshed from a background thread, it
keeps a deadlocked strategy's orders alive. Refresh it from the decision loop,
at the cost that a long pause or a slow computation there now cancels your
orders.

FIA recommends keeping cancel-on-disconnect optional, since canceling
every working order can add risk (section 1.4); on your venue, it can take the
stop.

:::more[A clean logout switches Deribit's protection off]
An explicit logout does not trigger Deribit's cancel-on-disconnect, so a
shutdown handler that logs out cleanly switches the protection off exactly when
the bot is leaving. A killed process closes its socket, which does trigger it.
:::

:::more[Heartbeats find a Deribit host crash sooner]
On Deribit, a host crash or a network cut leaves no closed socket behind;
heartbeats can detect the loss before the inactivity timeout. Without
heartbeats set on the connection, its orders can stay live until the 10-minute
inactivity close.
:::

:::more[A Kraken timer that fired stays off]
After Kraken Spot's timer fires, it stays disabled until the client sends a new
timeout, so the restarted bot must arm it again before it places anything. A
bot that assumes it is still armed trades without it.
:::

:::more[A crash loop can use up Hyperliquid's timer]
Hyperliquid caps scheduled-cancel triggers at 10 per UTC day. The documentation
does not say what happens to an 11th deadline, so a crash loop that arms and
dies repeatedly can leave you without a timer you think you have. Check the
response to every arm, and treat a rejected or unconfirmed one as no timer.
:::

## What should a watchdog outside the bot do?

**Run a watchdog that is not the bot: another process, on another host and
network, with its own key that can read and cancel.**

FIA describes a kill switch that may sit outside the trading application
(section 1.5) and an order cancellation route independent of the trading
connection (section 1.6). When the bot's heartbeat goes quiet, the watchdog:

1. writes the halt;
2. cancels entries;
3. checks the protection against the venue's position;
4. pages a person.

:::more[One call to go flat is for a verified breach]
Some brokers give such a process one call that cancels all open orders, stops
included, and one that submits a closing order for each open position; Alpaca's
are in [the venue notes](#what-does-each-venue-document). That route belongs to
the verified-breach exit, not to a heartbeat that went quiet. If the close
first cancels all open orders and that takes the stop, the position has none
until the close fills. Each call answers with a separate status for each order
or position, so the watchdog has to read every element, not the status line,
and then track each closing order through its fills to a reconciled position.
:::

:::more[A network failure on your side can cut this route too]
A major network failure on your side can cut the independent route as well.
FIA then names the venue's cancel-on-disconnect as the only mechanical means
left (section 1.6); a timer you armed also runs at the venue and can still
fire. A watchdog on the same host or uplink as the bot shares its failures.
:::

:::more[The watchdog shares the account with the bot]
The watchdog is a second client of the same account. Its cancels race the
bot's orders if the bot is alive and merely slow, and where the venue counts
limits per account or address, its trading requests spend the bot's budget. On
Hyperliquid, actions from the same address share the address limit; info
requests do not count against it, and IP limits apply separately.
:::

## What does the timer cancel that you wanted to keep?

**The protective stop, on any venue whose cancel-all counts it as an open
order.** Where your venue's documentation is silent, as Binance's is, find out
in [the drill](#how-do-you-drill-it).

:::outcomes

- **It leaves a whole-position stop.** Sized at trigger time, it targets the
  larger position; Hyperliquid's
  [position stop](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/take-profit-and-stop-loss-orders-tp-sl)
  placed without a fixed size works this way.
- **It leaves a fixed-size stop.** It covers the size it was placed for: 2 BTC
  of 3.2.
- **It takes the stop.** The position has no protection at the venue.

:::

Three ways out:

- **Place protection where the timer does not reach**, such as a Deribit stop
  sent through a connection without cancel-on-disconnect. The cost: two
  connections to reconcile, with the stop tracked across both.
- **Let the watchdog restore it** with a reduce-only stop for the venue's whole
  position. The cost: the watchdog now places orders and needs the bot's
  sizing checks.
- **Accept the bare position**, with the timer and the alerting sized so a
  person looks before it matters.
  The cost is the move during those minutes.

:::more[A fill during cancel-all is position, not a canceled order]
A cancel is a request; the order can fill until the venue applies it. A
quantity that filled a millisecond before the timer is position, not a canceled
order. After any cancel-all, read the fills, not only the order statuses.
:::

:::more[A cancel-all from the restarted bot removes the stops too]
A start-up routine that cancels everything to begin clean removes surviving
stops as well. Cancel by order type or by your own client-ID prefix if you mean
entries only.
:::

## Can the bot still close a position after it spent its request budget?

**Not always: on some venues, Hyperliquid among them, canceling and closing are
counted separately.**

:::outcomes

- **Cancels.** A larger allowance: a rate-limited address can still cancel
  while it lasts.
- **Closing orders and new stops.** Once rate limited, the address gets one
  request every 10 seconds for everything but cancels, and an order protects
  nothing until the venue accepts it.

:::

Hyperliquid's allowance grows with the volume the address has traded, so a
crash loop that cancels and re-places orders on every start spends it without
trading ([the numbers](#what-does-each-venue-document)).

- **Make restarts cheap**: a
  [persisted halt](#how-does-a-halt-survive-the-restart) keeps a restart from
  re-placing entries. The cost: no new exposure until the halt is cleared.
- **Keep a reserve** for closing the position and re-placing its stops. The
  cost is idle capacity in normal trading.
- **Close in one reduce-only order**: one request, not one per rung of a
  ladder. The cost: on a thin book, it can pay more slippage than smaller
  orders.

:::more[What closing in one order costs]
One reduce-only order for the whole position spends one request against the
address-based limit; a ladder of small exits spends one per rung. On a thin
book, one immediate order can pay more slippage than smaller ones that give
liquidity time to return, and a remainder that is canceled unfilled needs
another request.
:::

## How does a halt survive the restart?

**Write it to storage before it acts, read it at start-up before any order can
go out, and clear it only through an explicit check or a person.**

```d2 title="Start-up with a stored halt: the bot trades only when nothing is left to explain"
grid-rows: 4
grid-columns: 2
horizontal-gap: 100
vertical-gap: 80
start: "Start\nclosed"
gap: " " {style.opacity: 0}
read: "Read the\nstored halt"
stuck: "Stay closed,\nalert a person"
recon: "Rebuild orders,\nfills and position\nfrom the venue;\narm timers"
halted: "Stay halted:\ncancel entries,\nalert a person"
open: "Open for\nnew orders"
trip: "Write a halt:\ncancel entries,\nalert a person"
start -> read
read -> stuck: "unreadable"
read -> recon: "read"
recon -> halted: "a halt\nwas stored"
recon -> trip: "no halt,\nunexplained\ndifferences"
recon -> open: "no halt,\nclean"
```

While halted, every order is checked against the venue's position, not the
bot's memory: the memory is what the crash corrupted.

:::outcomes

- **Cancels.** They pass, unless the order is a stop whose replacement the
  venue has not accepted.
- **Protective orders and exits.** They pass only if they shrink that position
  without flipping it: reduce-only where the venue has the flag, otherwise
  sized within what working stops and exits leave uncovered.
- **Everything else.** Rejected until reconciliation is clean and the cause is
  resolved, confirmed by a person or a check named in advance.

:::

A supervisor restart is safe only with this in place: the bot comes back
halted, to reconcile, not to trade. Several restarts in a few minutes are a
cause for a halt in themselves, at the cost of halting on a harmless burst too.
The gate is in [pseudocode](#where-is-the-halt-in-pseudocode) at the end.

:::more[Why each step is where it is]

- **The gate starts closed.** A bot that starts open and then reads the halt
  has a window in which the strategy can send an order. In the crash above,
  that window is 12:01:05.
- **An unreadable store keeps the gate closed.** The cost: a corrupt file or a
  storage outage keeps the bot down until a person looks.
- **The halt is written before the cancel.** If the process dies between the
  two, the next start is halted and cancels again; in the other order, it
  starts open.
- **A halted bot keeps refreshing its timers.** The loop that refreshes them
  stays alive while halted, or the timer fires one timeout after the halted
  start and, on Kraken Spot, cancels the stop the halt was keeping. The
  alternative is to leave unarmed any timer that would take the stop, and rely
  on the watchdog.
- **The store lives where the replacement starts.** A file on a host that died
  with the bot is not there when the bot restarts on another one.
- **Clearing is an explicit act.** A halt that expires on a timer or clears on
  a successful start-up is not a halt.

:::

:::more[Exits on a venue without a reduce-only flag]
Where the venue does not support reduce-only, also size each exit within what
the stops and exits already working leave uncovered, or a stop and an exit that
each pass alone can fill together and flip the position. Binance USDⓈ-M does
not accept the flag in Hedge Mode; there an exit is an order in the opposite
direction on the position's own leg, a sell on the long leg or a buy on the
short ([the venue notes](#what-does-each-venue-document) have the fields). A
protective order is canceled only after its replacement is accepted; where no
replacement fits, amend the stop in place if the venue allows it, or a person
decides.
:::

:::more[With the OpenPit SDK 0.9.0]
If your bot checks its orders with the OpenPit SDK, its
[account block](https://github.com/openpitkit/pit/wiki/Account-Blocking/3b8287bad7149800524316e0908331afdb52b7aa)
rejects every new pre-trade request for the account, exits included, before
any policy runs; Spot Funds P&L kill switches, set per currency since
[0.8.0](https://github.com/openpitkit/pit/releases/tag/v0.8.0), raise it too.
Since [0.8.1](https://github.com/openpitkit/pit/releases/tag/v0.8.1), your
application restores a cause it persisted with `block_with_cause` on a newly
built engine, and waits for it to return before starting any operation that
can record a block for that account; the engine does not store the cause for
you, and `unblock` clears it. The verified exit path above stays your code.
:::

## When should the kill switch not fire?

**When the input that would trip it cannot be trusted.**

:::outcomes

- **The input is unverified.** A stale mark, a missing fill, an unfinished
  reconciliation: halt, keep the stops, alert a person.
- **The breach is verified.** The venue confirms the position, prices are
  fresh, the loss is over the limit: flatten through the exit path, if your
  strategy decided that in advance.

:::

Flattening on a stale price pays the spread and the slippage to close a
position on a number nobody verified, and FIA treats a kill switch as a last
resort (section 1.5). Halting costs too: the position stays exposed while you verify,
so time-limit the verification and page someone when it runs out. Loss limits
that pass on a stale price are the subject of
[stale market data in a trading bot's loss limits](/blog/stale-market-data-trading-bot/).

:::more[Why a forced exit on a stale input is a loss of its own]
A switch that flattens on a stale price or an unknown P&L acts on a number
nobody has verified: the forced exit realizes P&L at whatever price it
executes, pays the spread and the slippage, and removes a position the
strategy meant to hold. A P&L that depends on a price that stopped updating is
unverified too, and the stale input established neither the direction nor the
size of that P&L. FIA treats a kill switch as a last resort, for when other
actions have failed or are not feasible (section 1.5), not as the first
reaction to an alert. A stale input is a reason to stop adding risk, not proof
that the risk you hold is wrong.
:::

## How do you drill it?

**Kill the process on a paper or test account and watch the venue from a
second client.** A graceful stop runs your shutdown handlers and tests them,
not the crash.

1. **Set up the crash above**: a small position, its stop, a resting entry,
   every venue timer armed.
2. **Watch from a second view**: the venue's web interface or a read-only key
   on another host.
3. **Kill the bot with SIGKILL**, and note the time.
4. **Record what the venue does**: when the timer fires, what it cancels,
   whether the stop survives, how long cancel-on-disconnect takes.
5. **Cut the network instead**, with the process alive, and record the same.
6. **Restart the bot**: it starts halted, reconciles, sends no entry, and the
   position is still protected one timer timeout later.
7. **Clear the halt by hand**, and check the log names who did it.

:::more[What to look for at each step]

1. The stop is a stop-market for the position; the entry is far enough from
   the market that it rests. On Hyperliquid, include a position stop already
   resting before the timer fires: its documentation does not say whether a
   scheduled cancel removes one.
2. The second view shows open orders, conditional orders and the position.
3. A handler that cancels orders or logs out tests the handler, not the crash.
4. Deribit documents what detects a disconnect, not how fast it acts, so that
   number is yours to measure.
5. Block the bot host's outbound traffic. The bot can no longer refresh its
   timers or reach the venue. What can still act is an armed venue timer,
   cancel-on-disconnect once the venue detects the drop (on Deribit, time how
   long its heartbeat takes), and a watchdog on another host, which this block
   does not cut. A watchdog on the same host or uplink fails with the bot.
6. Each timer is left in the state you chose for that venue.

:::

:::more[What the drill does not cover]

- **Budgets.** A test account rarely has the trading history or the request
  usage of the live one; work out the live address's remaining budget
  separately before you rely on closing after a crash loop.
- **Trigger caps.** On Hyperliquid every scheduled cancel that actually fires
  counts against the address's 10 daily triggers, so a drill that lets it fire
  uses one; drill on a separate address, after confirming that it can arm.
- **Venue maintenance.** Kraken advises disabling the timer before scheduled
  engine maintenance, because orders are canceled when the engine returns if
  it is still enabled. Put that in the runbook, not in the drill.

:::

## What should you verify before the next crash?

- No part of the kill switch lives only inside the bot's process.
- Per venue, you know which timer or cancel-on-disconnect you use, its scope,
  and whether it cancels your stops; where the documentation is silent, the
  drill answered it.
- Timers are refreshed from the decision loop, armed for every symbol, and on a
  halted start refreshed or deliberately left off.
- Shutdown handlers do not log out in a way that disables cancel-on-disconnect.
- The halt is written durably before it acts, read before any order, and
  cleared only by a named check or a person.
- Start-up cancels entries, not everything.
- A halted bot can still cancel and send exits checked against the venue's
  position, reduce-only where supported.
- An unverified input blocks entries; it does not flatten.
- A watchdog runs on another host and network.
- You have killed the bot on paper, cut its network, restarted it, and recorded
  what the venue did.

## What does each venue document?

**The calls, fields, limits and dates behind everything above, venue by
venue.**

:::more[Deribit]

- **Cancel-on-disconnect.**
  [`private/enable_cancel_on_disconnect`](https://docs.deribit.com/api-reference/session-management/private-enable_cancel_on_disconnect)
  fires when the TCP connection is terminated, heartbeats detect a
  disconnection, or 10 minutes pass with no activity. `scope=connection` (the
  default, WebSocket only) cancels the orders created through the disconnected
  connection, and orders from other connections stay; `scope=account` makes it
  the default for new connections, so it applies again to the next one.
  Documented by
  [2021-10-19](https://insights.deribit.com/dev-hub/how-to-maintain-and-authenticate-a-websocket-connection-to-deribit-python/).
- **Heartbeats.** Without `public/set_heartbeat`, a host crash or a network cut
  can leave the connection's orders live until the 10-minute inactivity close.
- **Logout.** An explicit `private/logout` does not trigger
  cancel-on-disconnect.

:::

:::more[Binance USDⓈ-M Futures]

- **Countdown.**
  [`POST /fapi/v1/countdownCancelAll`](https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Auto-Cancel-All-Open-Orders)
  cancels "all open orders of the specified symbol" when the countdown for that
  symbol ends; the venue checks about every 10 ms. One symbol per timer. Call
  it again as a heartbeat; `countdownTime=0` stops it. Available since
  [2020-05-11](https://developers.binance.com/docs/derivatives/usds-margined-futures/change-log#2020-05-11).
- **Stops.** Conditional orders, stops included, moved to a separate Algo
  Service on
  [2025-12-09](https://developers.binance.com/docs/derivatives/usds-margined-futures/change-log),
  with their own cancel-all endpoint; the countdown documentation still speaks
  only of open orders and does not say whether algo orders are included.
- **Reduce-only.** `reduceOnly` on
  [new orders](https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api);
  not accepted in Hedge Mode, where an exit takes the opposite `side` on the
  position's own `positionSide`: `SELL` with `LONG`, `BUY` with `SHORT`.

:::

:::more[Kraken Spot]

- **Timer.**
  [`CancelAllOrdersAfter`](https://docs.kraken.com/api-reference/trading/cancel-all-orders-after-x)
  cancels all client orders when the timeout passes without a new call; the
  timeout is below 86,400 s, and the scope is not stated. After it fires it
  stays disabled until the client sends a new non-zero timeout. Available since
  [2021-01-13](https://docs-legacy.kraken.com/api/docs/change-log/).
- **Refresh.** Kraken recommends a call every 15 to 30 seconds with a
  60-second timeout.
- **Maintenance.** Kraken advises disabling the timer before scheduled engine
  maintenance: if it is still enabled, orders are canceled when the engine
  returns.

:::

:::more[Hyperliquid]

- **Scheduled cancel.**
  [`scheduleCancel`](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint)
  cancels all open orders when the scheduled time arrives, which must be at
  least 5 s ahead; the scope is not stated. At most 10 triggers per UTC day,
  reset at 00:00 UTC; omitting `time` removes the schedule. Documented by
  [2024-10-15](https://github.com/hyperliquid-dex/hyperliquid-python-sdk/blob/ddc400cde75b7ecee4bf25df9912b820df96d61c/hyperliquid/exchange.py).
- **Request budget.** The
  [rate limits](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/rate-limits-and-user-limits),
  as
  [archived on 2026-09-25](https://web.archive.org/web/20260925161623/https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/rate-limits-and-user-limits),
  allow an address 1 request per 1 USDC traded since the address was created,
  plus an initial buffer of 10,000. Cancels have a larger cumulative limit,
  `min(limit + 100000, limit * 2)`. Once rate limited, the address gets one
  request every 10 seconds for everything else. When an address has at least
  1,000 other open orders, a new reduce-only or trigger order is rejected.
  Actions from the same address share the address limit; info requests do not
  count against it, and IP limits apply separately.
- **Reduce-only.** The `r` field on an order
  ([exchange endpoint](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint)).
- **Position stop.** A
  [position TP/SL](https://hyperliquid.gitbook.io/hyperliquid-docs/trading/take-profit-and-stop-loss-orders-tp-sl)
  placed without a fixed size targets the whole position at trigger time.

:::

:::more[Alpaca]
The [Trading API](https://forum.alpaca.markets/t/new-product-update-7-29-2019/91)
cancels all open orders, stops included, with `DELETE /v2/orders`, and submits
a closing order for each open position with `DELETE /v2/positions`, both since
2019-07-29. With `cancel_orders=true`, the second call cancels all open orders
before liquidating. Both return HTTP 207 with a separate status for each order
or position; track each
[closing order](https://docs.alpaca.markets/us/reference/deleteallopenpositions-1)
through its fills.
:::

## Where is the halt in pseudocode?

:::more[The start-up, the exit gate, the trip and the clear]

```text
# Pseudocode.

on_start():
    gate.set(HALTED, cause="starting")          # closed until proven otherwise
    halt = store.read("halt")
    if halt.read_failed:
        alert("halt state unreadable"); return  # stays closed
    venue = reconcile()                         # orders, fills, position from the venue
    arm_venue_timers()                          # a fired Kraken timer stays off;
                                                # refreshed while halted too
    if halt.present:
        gate.set(HALTED, cause=halt.cause)      # the stored cause, not "starting"
        cancel_entries()                        # idempotent: finishes a trip cut short by the crash
        alert("started halted: " + halt.cause)
        return
    if venue.unexplained_differences:
        trip("reconciliation break at start-up")
        return
    gate.open()

submit(order):
    if gate.open:
        return send(order)
    position = venue.position(order.instrument) # confirmed by the venue, not memory
    if order.is_cancel:
        if order.target.protective and not replacement_accepted(order.target):
            alert("stop needs replacing: amend it in place or decide by hand")
            return reject("protective order without an accepted replacement")
        return send(order)
    if not reduces(position, order.signed_qty): # direction from the confirmed position
        return reject(gate.cause)
    if not venue.supports_reduce_only:
        left = position + venue.working_reducing_qty(order.instrument)
                                                # signed; resting and in-flight exits
        if not reduces(left, order.signed_qty): # size within what they leave uncovered
            return reject(gate.cause)
    return send(as_exit(order))                 # reduce-only flag where the venue has one

reduces(position, qty):                         # decimals: a float residue rejects a full close
    after = position + qty
    return abs(after) < abs(position) and (after == 0 or sign(after) == sign(position))
                                                # smaller, and never flipped

trip(cause):
    store.write_durably("halt", {cause, time, source})  # before anything else
    gate.set(HALTED, cause)
    cancel_entries()                            # by type or client-ID prefix, not the stops
    alert(cause)

clear(by):                                      # a person, or a check you named in advance
    require(reconcile().clean and cause_resolved(by))
    store.delete("halt")
    log("halt cleared by " + by)
    gate.open()
```

:::

## What else do people ask?

:::more[If my bot crashes with an open position, what happens next?]
The position stays open and exposed to margin, funding and liquidation, and
orders the venue accepted can keep working: entries can still fill and stops
can still trigger. A fixed-size stop is not resized after a fill, and nothing
in the bot can close the position until it restarts. A venue cancel timer or
cancel-on-disconnect, if armed, removes working orders, possibly the stop too.
:::

:::more[What should a bot do when it comes back online with a position already open?]
Start halted, rebuild orders, fills and the position from the venue, and send
nothing new until every difference is explained. While halted it may cancel and
place reduce-only protective orders for the position the venue reports.
:::

:::more[Can I still cancel orders when Hyperliquid rate limits my bot?]
Yes, within the larger cancel allowance the venue documents. Closing orders and
new stops fall under the ordinary limit, which drops to one request every 10
seconds once the address is rate limited.
:::

:::more[Is cancel-on-disconnect enough?]
It tries to cancel orders when the venue detects the connection is lost; it
does not close a position, it may remove your stop, and on Deribit an explicit
logout bypasses it. It also does not fire while a hung bot keeps its connection
alive; a dead man's timer refreshed by the decision loop covers that case.
:::

:::more[Should a kill switch close all positions?]
Only on a verified breach, and only if your strategy decided that in advance.
On bad or missing data, block new entries and keep the protection; a forced
exit on a stale input realizes P&L at the execution price, spread and slippage
included, on a number nobody verified.
:::

## Where should I read next?

- [Why your trading bot's position drifts from the broker's](/blog/trading-bot-position-out-of-sync-with-broker/):
  rebuilding the position after a restart.
- [Duplicate orders after a timeout](/blog/duplicate-orders-after-timeout/):
  orders whose outcome was unknown at the crash.
- [Stale market data in a trading bot's loss limits](/blog/stale-market-data-trading-bot/):
  loss limits that pass on a stale price.
- [OpenPit v0.9.0 release](https://github.com/openpitkit/pit/releases/tag/v0.9.0):
  account blocks your application restores from a persisted cause after a
  restart.
- [FIA, Best Practices for Automated Trading Risk Controls and System Safeguards](https://www.fia.org/sites/default/files/2024-07/FIA_WP_AUTOMATED%20TRADING%20RISK%20CONTROLS_FINAL_0.pdf),
  sections 1.4 to 1.6.
