DEV Community

ghostsworm
ghostsworm

Posted on

Risk Control System of quantmesh

Risk Control System

Version: v3.3.2

Last Updated: 2025-01-27


Table of Contents

  1. Risk Control Overview
  2. Multi-Layer Risk Control
  3. Active Risk Control Details
  4. Fund Safety Checks
  5. Reconciliation Mechanism
  6. Order Cleanup
  7. Risk Control Configuration

Risk Control Overview

QuantMesh adopts a multi-layer risk control mechanism to comprehensively protect fund safety and trading stability.

Risk Control Layers

┌─────────────────────────────────────┐
│  Layer 1: Pre-startup Safety Check │
│  - Balance Sufficiency Check        │
│  - Leverage Limit                   │
│  - Max Position Calculation         │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│  Layer 2: Active Risk Monitoring    │
│  - K-line Volume Anomaly Detection  │
│  - Multi-coin Correlation Monitor   │
│  - Auto Trading Pause                │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│  Layer 3: Order Cleanup             │
│  - Pending Order Limit               │
│  - Periodic Old Order Cleanup       │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│  Layer 4: Position Reconciliation  │
│  - Local vs Exchange Reconciliation  │
│  - Slot Status Repair                │
└─────────────────────────────────────┘
           ↓
┌─────────────────────────────────────┐
│  Layer 5: Manual Intervention       │
│  - Graceful Exit                     │
│  - Emergency Stop                    │
└─────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Multi-Layer Risk Control

Layer 1: Pre-startup Safety Check

Purpose: Verify account status before system startup to prevent issues caused by insufficient funds.

Check Items:

  1. Account Balance Sufficiency

    • Verify account balance is sufficient
    • Calculate maximum available margin
  2. Leverage Limit

    • Check if leverage exceeds limit (default max 10x)
    • Prevent over-leveraging
  3. Maximum Position Calculation

   Max Available Margin = Account Balance × Leverage
   Cost Per Position = Order Amount (fixed)
   Max Positions = Max Available Margin / Cost Per Position
Enter fullscreen mode Exit fullscreen mode
  1. Fee Rate Verification

    • Verify fee rate configuration
    • Check profit rate vs fee rate
  2. Position Safety Verification

    • Verify if can safely hold at least N positions (default 100)
    • Ensure sufficient buffer for price fluctuations

Failure Handling:

If checks fail, the system will:

  • ❌ Refuse to start
  • 📝 Output detailed error messages
  • 💡 Provide solution suggestions

Configuration Example:

trading:
  position_safety_check: 100  # Minimum positions to hold downward
Enter fullscreen mode Exit fullscreen mode

Layer 2: Active Risk Monitoring

Purpose: Monitor market anomalies in real-time, automatically pause trading to prevent losses from extreme markets.

Monitoring Logic:

  1. Real-time monitoring of multiple mainstream coins' K-lines

    • Default monitoring: BTC, ETH, SOL, XRP, DOGE
    • Configurable monitoring coin list
  2. Calculate volume moving average

   Moving Average Volume = (Sum of Recent N K-line Volumes) / N
Enter fullscreen mode Exit fullscreen mode
  1. Detect volume anomalies
   Trigger Condition: Current Volume > Moving Average Volume × Multiplier Threshold
Enter fullscreen mode Exit fullscreen mode
  1. Trigger Risk Control

    • Cancel all buy orders
    • Pause new order placement
    • Log risk control trigger
  2. Recovery Condition

   Recovery Condition: At least N coins return to normal
   (Current Price > Moving Average AND Volume < Average × Multiplier)
Enter fullscreen mode Exit fullscreen mode

Configuration Example:

risk_control:
  enabled: true               # Enable risk control
  monitor_symbols:            # Mainstream coins to monitor
    - "BTCUSDT"
    - "ETHUSDT"
    - "SOLUSDT"
    - "XRPUSDT"
    - "DOGEUSDT"
  interval: "1m"              # K-line period: 1m / 3m / 5m
  volume_multiplier: 3.0      # Volume multiplier: Current > Average×3x is abnormal
  average_window: 20          # Moving average window: 20 K-lines
  recovery_threshold: 3       # Number of normal coins required for recovery
Enter fullscreen mode Exit fullscreen mode

Risk Control Trigger Example:

[WARN] 🚨 Market Anomaly Detected: BTCUSDT volume abnormal (Current: 1000, Average: 200, Multiplier: 5.0)
[WARN] 🚨 Market Anomaly Detected: ETHUSDT volume abnormal (Current: 800, Average: 250, Multiplier: 3.2)
[WARN] 🛡️ Active Risk Control Triggered, Trading Paused
[INFO] 🔄 Canceling all buy orders...
[INFO] ✅ Canceled 15 buy orders
[INFO] ⏸️ Trading paused, waiting for market recovery
Enter fullscreen mode Exit fullscreen mode

Recovery Example:

[INFO] 📊 Market Recovery Check: 3/5 coins returned to normal
[INFO] ✅ Market recovered, resuming trading
[INFO] 🔄 Restarting order placement...
Enter fullscreen mode Exit fullscreen mode

Layer 3: Order Cleanup

Purpose: Prevent order accumulation and release slot resources.

Cleanup Strategy:

  1. Check pending order count

    • Periodic check (default every 60 seconds)
    • Count total pending orders
  2. Trigger cleanup

   Trigger Condition: Pending Orders > Cleanup Threshold (default 100)
Enter fullscreen mode Exit fullscreen mode
  1. Batch cancel oldest orders

    • Cancel N orders per batch (default 10/batch)
    • Prioritize oldest orders
  2. Reset slot status

    • Reset slots corresponding to canceled orders to FREE
    • Allow re-ordering

Configuration Example:

trading:
  order_cleanup_threshold: 100      # Order cleanup limit
  cleanup_batch_size: 20            # Cleanup batch size
Enter fullscreen mode Exit fullscreen mode

Layer 4: Position Reconciliation

Purpose: Periodically sync local state with exchange state to ensure data consistency.

Reconciliation Content:

  1. Position Reconciliation

    • Exchange positions vs local positions
    • Detect and fix differences
  2. Order Reconciliation

    • Exchange pending orders vs local orders
    • Detect and fix differences
  3. Slot Status Repair

    • Repair slots based on exchange actual state
    • Ensure slot status is correct

Reconciliation Cycle:

  • Default every 5 minutes (configurable)
  • Pause reconciliation logs when risk control is triggered (to avoid excessive logs)

Layer 5: Manual Intervention

Purpose: Provide manual intervention mechanisms for emergencies.

Intervention Methods:

  1. Graceful Exit

    • Press Ctrl+C to send SIGINT signal
    • System will:
      • Cancel all pending orders (if cancel_on_exit: true)
      • Close all positions (if close_positions_on_exit: true)
      • Stop all goroutines
      • Save data
      • Close connections
  2. Emergency Stop

    • Directly terminate process
    • Or use kill -9 to force terminate

Active Risk Control Details

How It Works

Active risk control monitors K-line volumes of multiple mainstream coins to detect market anomalies.

Monitoring Flow:

1. Start K-line stream
   ↓
2. Receive K-line data
   ↓
3. Update K-line cache (keep recent N)
   ↓
4. Calculate moving average volume
   ↓
5. Detect if current volume is abnormal
   ↓
6. Trigger risk control or recovery
Enter fullscreen mode Exit fullscreen mode

Trigger Conditions

Trigger Risk Control:

Current Volume > Moving Average Volume × volume_multiplier
Enter fullscreen mode Exit fullscreen mode

Resume Trading:

At least recovery_threshold coins satisfy:
- Current Price > Moving Average Price
- Current Volume < Moving Average Volume × volume_multiplier
Enter fullscreen mode Exit fullscreen mode

Configuration Recommendations

Conservative Configuration (More Sensitive):

risk_control:
  volume_multiplier: 2.0      # Trigger at 2x
  average_window: 10           # Use recent 10 K-lines
  recovery_threshold: 4        # Need 4 coins to recover
Enter fullscreen mode Exit fullscreen mode

Aggressive Configuration (More Relaxed):

risk_control:
  volume_multiplier: 5.0      # Trigger at 5x
  average_window: 30           # Use recent 30 K-lines
  recovery_threshold: 2        # Only need 2 coins to recover
Enter fullscreen mode Exit fullscreen mode

Default Configuration (Recommended):

risk_control:
  volume_multiplier: 3.0      # Trigger at 3x
  average_window: 20           # Use recent 20 K-lines
  recovery_threshold: 3        # Need 3 coins to recover
Enter fullscreen mode Exit fullscreen mode

Fund Safety Checks

Check Items

Pre-startup checks include:

  1. Account Balance Check
   Required Margin = order_quantity × (buy_window_size + sell_window_size) × Leverage

   If Account Balance < Required Margin × Safety Factor:
       Refuse to start
Enter fullscreen mode Exit fullscreen mode
  1. Leverage Check
   If Leverage > max_leverage (default 10):
       Refuse to start
Enter fullscreen mode Exit fullscreen mode
  1. Maximum Position Calculation
   Max Available Margin = Account Balance × Leverage
   Cost Per Position = order_quantity
   Max Positions = Max Available Margin / Cost Per Position

   If Max Positions < position_safety_check (default 100):
       Refuse to start
Enter fullscreen mode Exit fullscreen mode

Reconciliation Mechanism

Reconciliation Flow

1. Get exchange positions
   ↓
2. Get local positions
   ↓
3. Compare differences
   ↓
4. Fix inconsistencies
   ↓
5. Get exchange pending orders
   ↓
6. Get local pending orders
   ↓
7. Compare differences
   ↓
8. Fix inconsistencies
Enter fullscreen mode Exit fullscreen mode

Order Cleanup

Cleanup Strategy

Trigger Condition:

Pending Orders > order_cleanup_threshold
Enter fullscreen mode Exit fullscreen mode

Cleanup Method:

  1. Sort orders by creation time
  2. Select oldest N orders (cleanup_batch_size)
  3. Batch cancel these orders
  4. Reset corresponding slot status

Cleanup Frequency:

  • Default check every 60 seconds
  • Execute immediately if triggered

Risk Control Configuration

Complete Configuration Example

# Active Risk Control Configuration
risk_control:
  enabled: true               # Enable risk control (strongly recommended)

  # Mainstream coins to monitor (for overall market sentiment)
  monitor_symbols:
    - "BTCUSDT"
    - "ETHUSDT"
    - "SOLUSDT"
    - "XRPUSDT"
    - "DOGEUSDT"

  interval: "1m"              # K-line period: 1m / 3m / 5m
  volume_multiplier: 3.0      # Volume multiplier: Current > Average×3x is abnormal
  average_window: 20          # Moving average window: 20 K-lines
  recovery_threshold: 3       # Number of normal coins required for recovery
  max_leverage: 10            # Max allowed leverage (default 10, 0 = unlimited)

# Risk control related parameters in trading config
trading:
  position_safety_check: 100        # Position safety check (minimum positions to hold downward)
  order_cleanup_threshold: 100      # Order cleanup limit
  cleanup_batch_size: 20            # Cleanup batch size
  reconcile_interval: 60            # Reconciliation interval (seconds)

# System configuration
system:
  cancel_on_exit: true              # Cancel all orders on exit
  close_positions_on_exit: false    # Close positions on exit (default disabled)
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Must Enable Risk Control
   risk_control:
     enabled: true  # Must enable
Enter fullscreen mode Exit fullscreen mode
  1. Reasonable Parameter Settings

    • Adjust volume_multiplier based on market conditions
    • Set recovery_threshold based on needs
    • Regularly check risk control triggers
  2. Monitor Risk Control Status

    • Regularly check logs
    • Pay attention to risk control triggers
    • Analyze trigger causes
  3. Fund Management

    • Don't invest all funds
    • Keep sufficient margin buffer
    • Set reasonable position_safety_check

Next Steps

  • 💡 Use Cases - View practical application scenarios
  • FAQ - Answer common questions

Risk control system is an important mechanism to protect fund safety. It is strongly recommended to enable and configure it properly.

Top comments (0)