Safety Mechanisms in Trading Bots

한국어로 읽기

TECH INSIGHT / EXPLAINED

Safety controls must describe what the bot knows, what it is allowed to do, and how it recovers when a request has an uncertain result. A strategy can lose substantially even with these controls; they reduce specific failure modes rather than guarantee a loss limit.

Three adult colleagues explain bot safety
AI-generated teaching illustration, not an actual operating screen or performance record.

Local execution of the actual project

These captures show the existing project UI or functions executed locally with non-private sample inputs. Each caption states the scope of the execution.

The actual project settings dialog opened locally, showing monitor_only, maximum positions and automatic entry/exit fields. Values are samples; nothing was saved or traded. The screen alone does not verify backend safeguards.
The actual project settings dialog opened locally, showing monitor_only, maximum positions and automatic entry/exit fields. Values are samples; nothing was saved or traded. The screen alone does not verify backend safeguards.
The original check_caps() branches executed with synthetic quantities. This version disables daily, total-exposure and account-percentage guards and has a single-share exception, so it is not a complete implementation of the article’s aggregate risk budget. No reconciliation, reservation or actual order was performed.
The original check_caps() branches executed with synthetic quantities. This version disables daily, total-exposure and account-percentage guards and has a single-share exception, so it is not a complete implementation of the article’s aggregate risk budget. No reconciliation, reservation or actual order was performed.

Separate intent, acknowledgement and fill

A submitted entry is pending, not an open filled position. Persist an intent ID before submission; reserve its risk budget so another signal cannot spend it. Record the broker order ID after acknowledgement, then update quantity from reconciled fills. If an acknowledgement is lost, query before retrying. A mutex and 30-second debounce cannot deduplicate across process restarts or a delayed response.

FLAT -> ENTRY_PENDING -> PARTIAL/OPEN
ENTRY_PENDING + timeout -> UNKNOWN -> RECONCILE
OPEN -> EXIT_PENDING -> PARTIAL/FLAT
Any unresolved discrepancy -> HALT_NEW_ENTRIES

Close-out is a monitored workflow

Stop new entries before the configured session cutoff, reconcile current orders/positions, submit the intended reduction and verify actual remaining quantity. Market orders can slip, reject or remain unfilled during a halt. Blindly retrying three times can create duplicate or reverse positions; use the existing order identity and venue-specific reduce-only rules where supported. The cutoff must follow the instrument’s exchange calendar and session, not a universal 15:20 timer.

Replace magic thresholds with budgets

A hypothetical account risk budget may cap pending plus open notional at 1,000 units. If open exposure is 700 and pending is 250, a new 100-unit order must fail even though no position flag is set for it. Check spread, depth for the whole intended size, quote age and price collars. Numerical thresholds require instrument-specific calibration; half the required displayed depth is not a general safety condition.

Recovery and secrets

On restart read a durable checkpoint, then reconcile the venue’s open orders, fills and balances before enabling entries. Store market timezone and trading session with baselines. Protect stored credentials with an OS credential store or properly managed encryption keys; encryption with a key stored beside ciphertext offers limited protection. AES-GCM also requires checked errors and nonce uniqueness. Never log credentials. A paused bot should continue reconciliation and urgent alerts rather than simply kill every worker.

Rehearse cancellation during a partial fill

Suppose an illustrative buy order requests 10 units and fills 4 before cancellation begins. Another 2 can fill while the cancel request travels, leaving a final holding of 6 and a canceled remainder of 4. Freezing the position at 4 when the cancel button is pressed, or releasing the entire reservation, gives later orders an incorrect risk budget. Treat cancel-request acceptance and final order status as separate transitions.

Deduplicate confirmed executions by their unique fill identifiers. Transfer the filled portion of the reservation into actual exposure while retaining the reservation for any still-active remainder. Release only the canceled portion once cancellation is established. Fees and the asset in which they are charged also affect usable balances; summing requested quantities alone cannot establish what is available.

Specify actions that remain permitted while halted

ActionIllustrative halt policy
Increase exposureBlocked
Read orders and fillsContinue when authentication and the read path work
Cancel an existing orderPermit within policy after establishing its identity
Request a position reductionEvaluate confirmed quantity and instrument rules

Labeling a request “risk reduction” does not make every sell safe. An existing exit or another process's order can make an additional sell excessive or create a reverse position. If state is uncertain, gather available evidence first and escalate discrepancies outside the automated policy. Persist the halt reason, start time, and conditions required for resumption.

One order response does not explain an account

The Bithumb individual-order endpoint provides an identity-based lookup useful for reconciling a particular order. That result cannot explain an entire account containing manual orders, other bots, deposits, or withdrawals. Collect order listings, unique executions, and balances with their observation times, then separate explained differences from unresolved ones.

Responses obtained at different times do not automatically form an atomic snapshot. If an execution occurs between reads, revisit the relevant interval and converge without counting the same fill twice. Use versions, request start times, and documented ordering information where available so a delayed older response cannot overwrite newer execution knowledge. When ordering is insufficient, retain uncertainty instead of inventing a definitive total.

A successful recovery test can refuse to resume

An offline rehearsal should include termination immediately after submission, another fill during cancellation, duplicate execution notifications, out-of-order reads, and a balance change from a manual order. Inspect submission count, confirmed holdings, active reservations, and unresolved intents after each step. Repeated restarts with an unknown order must not increase the submission count.

Resumption requires more than resetting an error counter. Recheck quote freshness, agreement between orders and balances, the risk-configuration version, and required dependency health. Record the evidence used to resume. If a discrepancy remains unresolved, continuing to block new entries can be the correct passing result. This is a design exercise for synthetic failures, not a claim of live execution performance, profitability, or a guaranteed maximum loss.

Documentation and next steps

Content and examples reviewed: 2026-10-01

댓글