Developing an Emergency Close System for Trading Bot Positions

Developing an Emergency Close System for All Bot Positions "Close everything" — the simplest function in appearance and one of the most critical. In a moment of crisis, when the main engine may hang or the UI becomes unresponsive, this button must work instantly. A 30-second delay during a flash

Blockchain Development Services

Frequently Asked Questions

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1451
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1309
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    1005
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1270
  • image_logo-advance_0.webp
    B2B Advance company logo design
    719
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    1011

Developing an Emergency Close System for All Bot Positions

"Close everything" — the simplest function in appearance and one of the most critical. In a moment of crisis, when the main engine may hang or the UI becomes unresponsive, this button must work instantly. A 30-second delay during a flash crash can wipe out 5–10% of the portfolio. We have been engineering such mechanisms for years and implemented them for over 15 projects, including high-load DeFi protocols and CEX bots with hundreds of positions.

In one project, during a sharp drop of ETH, the bot's engine froze due to an error in the margin calculation script. The emergency close, implemented as a separate service on asyncio, closed 25 positions in 2 seconds via parallel orders — losses were less than 0.5% instead of a potential 12%. This case shows why isolating the code path is critical.

How We Build the Emergency Close System

Each component is designed with failure in mind. Here are the key requirements:

Speed: emergency close must complete in seconds, not minutes. Achieved by closing all positions simultaneously via asyncio.gather, not a sequential loop.

Reliability: works even if the main trading loop hangs or UI is unavailable. This is a separate, maximally simple code path with no dependencies on the main engine — only an HTTP client to the exchange.

Confirmation: each position must be confirmed closed. If the order is not filled, retry with exponential backoff. Do not stop until all positions are closed or a timeout is reached with an alert in Telegram.

Idempotency: if the button is pressed twice, do not send duplicate orders. Use Redis to store the operation state: on a repeated call, check if an active close is already in progress and return the current status.

Execution Algorithm

1. Get the list of all open positions (REST snapshot) 2. For each position in parallel: a. Place a market order of the opposite side b. Wait for confirmation fill c. If timeout — check status, retry if necessary 3. After N seconds, perform reconciliation: - Request current positions from the exchange - If anything remains open, repeat for those 4. Send final report: what was closed, at what prices, final P&L 

Liquidity Problem During Emergency Close

Emergency close usually happens during high volatility — precisely when liquidity drops. A market order for a large position can cause catastrophic slippage. Solution: for large positions — TWAP execution even during emergency (split into several orders over 30–60 seconds). For small positions — plain market order. The size threshold is configurable.

Comparison of TWAP and Direct Market Order

Parameter TWAP Execution Market Order
Time to close large position 30–60 seconds <1 second
Slippage risk Minimal (≤1%) High (up to 5–15%)
Reliability when liquidity is zero High (orders partially fill) Low (may not fill)
Recommended position size >$10k <$10k

What to Do If Liquidity Drops to Zero?

In such cases, a plain market order may execute at the worst price in the order book. We add a fallback: if the spread exceeds 5%, the system switches to a limit order with an aggressive price (best bid/ask) and retries every 2 seconds. This protects against slippage while maintaining a chance to close the position.

Comparison of Approaches to Executing Emergency Close

Parameter Sequential Closing Parallel Closing
Execution time ~10–30 seconds ~1–3 seconds
Slippage risk Higher due to delays Lower due to synchrony
Reliability Depends on sequence Higher, each order independent
Implementation complexity Low Medium (requires asynchronicity)

Parallel closing is 3–5 times faster than sequential for 10+ positions.

Why Is It Important to Test Emergency Close Regularly?

The emergency close system is a safety feature that is rarely needed but must work flawlessly when required. Test it regularly in paper trading mode with flash crash simulations. We include automated tests that use historical crisis data and emulate network issues. After our implementation, you can rest assured.

Implementation Process

Stage Duration Result
Analysis of bot architecture 1–2 days Technical specification and estimate
Code path design 1 day Algorithm and fallback document
Development in Python (asyncio) or Solidity 3–5 days Ready emergency close module
Integration with exchange and TWAP setup 1–2 days Working prototype
Testing on historical data 2 days Simulation report
Deployment and two-hour support 1 day System in production

What's Included in the Work?

  • Full architecture and code of emergency close (separate service or integrated module)
  • Implementation of parallel execution with asyncio/aiohttp or similar stack
  • TWAP execution configuration for large positions
  • Reconciliation and alerts on failures
  • Documentation (algorithm description, configuration, testing instructions)
  • Two hours of post-deployment support

Contact us to discuss your project — we will analyze your stack and propose the optimal solution within one business day.