HARDWARE FAILSAFE

ESP32
KILL SWITCH

A physical emergency stop for autonomous trading bots. When algorithms go rogue during a flash crash, bypass software freezes and liquidate all positions instantly over WiFi.

SYSTEM STATUS

Phase 2 COMPLETE
Integration Trade-Lab API
Target Azure VM / Local Mac
INTERACTIVE SIMULATION
ARMED Awaiting trigger
HOLD
3 SEC

In Action.

Pressing the button triggers a Webhook via WiFi directly to the Trade-Lab Flask server, bypassing the core logic loop to execute a market-order liquidation.

How it Works.

1. Hardware Interrupt

Physical Switch → GPIO 4

The physical toggle switch is thrown. The ESP32 immediately detects the state change via a hardware interrupt on GPIO 4, bypassing any software-level loops or delays.

2. Local Feedback

ESP32 → OLED & RGB LED

The ESP32 instantly updates the local SSD1306 OLED display to KILLED, transitions the RGB LED to solid red, and triggers the active buzzer for auditory confirmation.

3. Secure Webhook Payload

ESP32 → Trade-Lab Flask API (HTTP POST)

The ESP32 constructs an HTTP POST request containing a secure X-Kill-Token header. It fires this payload over WiFi directly to the Trade-Lab server endpoints (Azure VM & Local Mac).

4. Backend Validation

Trade-Lab API → Auth Middleware

The Python Flask server intercepts the webhook, verifies the secure token, and immediately pauses all algorithmic trading loops to prevent further autonomous decisions.

5. Liquidation Execution

Trade-Lab API → Broker Exchange

The backend cancels all pending limit orders and fires emergency Market Sell orders to the broker exchange, liquidating all open positions and securing the portfolio within milliseconds.

How to Build.

Want to build your own physical fail-safe? Here is the complete component list and wiring guide.

Components (BOM)

  • ESP-WROOM-32 Development Board
  • 0.96" SSD1306 I2C OLED Display
  • Slide Switch or Push Button
  • RGB LED (Common Cathode)
  • Active Buzzer
  • Resistors: 3x 220Ω, 1x 10kΩ
  • Breadboard & Jumper Wires
Estimated Cost: ~₹1,000

Pin Mapping

Component ESP32 Pin
Kill Switch GPIO 4
LED Red (220Ω) GPIO 15
LED Green (220Ω) GPIO 16
LED Blue (220Ω) GPIO 17
Buzzer (+) GPIO 18
OLED SDA GPIO 21
OLED SCL GPIO 22

Firmware & Source Code

All the C++ code required to flash the ESP32, handle the physical debouncing, and authorize the webhooks is fully open-source. (Requires the Adafruit_SSD1306 and HTTPClient Arduino libraries). Grab the latest .ino file and secrets.h template directly from the repository.

VIEW ON GITHUB →
Top-down wiring view

The Brain: ESP32

A 38-pin ESP-WROOM-32 dev board handles WiFi connectivity, physical button debouncing, and cryptographic webhook signing.

OLED display showing ARMED

Status Display

A 0.96" SSD1306 OLED provides real-time feedback on connection status and arm state.

Kill switch activated - red LED

Visual Confirmation

RGB LED transitions from blue (armed) to yellow (processing) to red (killed), backed by an active buzzer.

Interactive Simulation.

Before soldering components or buying hardware, you can test the firmware, verify the GPIO pin mapping, and trigger the webhook virtually using our Wokwi simulation.

Virtual Breadboard

Wokwi Schematic

Simulation in Action

Server Response.

When the ESP32 fires the webhook, the Trade-Lab Python server takes over. It validates the cryptographic X-Kill-Token to prevent unauthorized spam, halts algorithmic loops, and triggers an emergency liquidation of all open paper-trading positions.

kill_server.py
Terminal
# ── Kill endpoint — ESP32 calls this on button press
@app.route('/kill', methods=['POST'])
def kill():
    # ── Auth check ───────────────────────────────────────
    token = request.headers.get('X-Kill-Token', '')
    if KILL_SECRET and token != KILL_SECRET:
        logging.warning("🚫 Unauthorized /kill attempt")
        return jsonify({"error": "Unauthorized"}), 401

    # Write the persistent kill flag
    with open(KILL_FLAG, 'w') as f:
        f.write(datetime.now().isoformat())

    logging.info("🚨 KILL SIGNAL RECEIVED")

    # ── Emergency Liquidation ────────────────────────────
    broker = PaperBroker()
    if broker.positions:
        logging.warning(f"🚨 Liquidating {len(broker.positions)} open positions!")
        broker.liquidate_all()
        
    send_telegram("🚨 HARDWARE KILL SWITCH TRIGGERED")
    
    return jsonify({"status": "killed"}), 200
[2026-05-27 10:14:22] INFO Kill Switch Server starting on port 5050...
[2026-05-27 10:14:22] INFO Endpoints: /health /kill /reset /status

[2026-05-27 14:05:11] 🚨 KILL SIGNAL RECEIVED
[2026-05-27 14:05:11] WARNING Liquidating 3 open positions!
[2026-05-27 14:05:12] INFO ✅ Liquidation complete.
[2026-05-27 14:05:13] INFO Telegram alert sent. Bot stopped.
localhost:5050/dashboard
// DASHBOARD CAPABILITIES
Remote Re-arming Node Targeting (Azure/Local) Live Telemetry Telegram Webhook Test
← BACK TO TRADE-LAB VIEW ON GITHUB →