Risk Control System
Version: v3.3.2
Last Updated: 2025-01-27
Table of Contents
- Risk Control Overview
- Multi-Layer Risk Control
- Active Risk Control Details
- Fund Safety Checks
- Reconciliation Mechanism
- Order Cleanup
- 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 │
└─────────────────────────────────────┘
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:
-
Account Balance Sufficiency
- Verify account balance is sufficient
- Calculate maximum available margin
-
Leverage Limit
- Check if leverage exceeds limit (default max 10x)
- Prevent over-leveraging
Maximum Position Calculation
Max Available Margin = Account Balance × Leverage
Cost Per Position = Order Amount (fixed)
Max Positions = Max Available Margin / Cost Per Position
-
Fee Rate Verification
- Verify fee rate configuration
- Check profit rate vs fee rate
-
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
Layer 2: Active Risk Monitoring
Purpose: Monitor market anomalies in real-time, automatically pause trading to prevent losses from extreme markets.
Monitoring Logic:
-
Real-time monitoring of multiple mainstream coins' K-lines
- Default monitoring: BTC, ETH, SOL, XRP, DOGE
- Configurable monitoring coin list
Calculate volume moving average
Moving Average Volume = (Sum of Recent N K-line Volumes) / N
- Detect volume anomalies
Trigger Condition: Current Volume > Moving Average Volume × Multiplier Threshold
-
Trigger Risk Control
- Cancel all buy orders
- Pause new order placement
- Log risk control trigger
Recovery Condition
Recovery Condition: At least N coins return to normal
(Current Price > Moving Average AND Volume < Average × Multiplier)
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
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
Recovery Example:
[INFO] 📊 Market Recovery Check: 3/5 coins returned to normal
[INFO] ✅ Market recovered, resuming trading
[INFO] 🔄 Restarting order placement...
Layer 3: Order Cleanup
Purpose: Prevent order accumulation and release slot resources.
Cleanup Strategy:
-
Check pending order count
- Periodic check (default every 60 seconds)
- Count total pending orders
Trigger cleanup
Trigger Condition: Pending Orders > Cleanup Threshold (default 100)
-
Batch cancel oldest orders
- Cancel N orders per batch (default 10/batch)
- Prioritize oldest orders
-
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
Layer 4: Position Reconciliation
Purpose: Periodically sync local state with exchange state to ensure data consistency.
Reconciliation Content:
-
Position Reconciliation
- Exchange positions vs local positions
- Detect and fix differences
-
Order Reconciliation
- Exchange pending orders vs local orders
- Detect and fix differences
-
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:
-
Graceful Exit
- Press
Ctrl+Cto 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
- Cancel all pending orders (if
- Press
-
Emergency Stop
- Directly terminate process
- Or use
kill -9to 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
Trigger Conditions
Trigger Risk Control:
Current Volume > Moving Average Volume × volume_multiplier
Resume Trading:
At least recovery_threshold coins satisfy:
- Current Price > Moving Average Price
- Current Volume < Moving Average Volume × volume_multiplier
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
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
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
Fund Safety Checks
Check Items
Pre-startup checks include:
- Account Balance Check
Required Margin = order_quantity × (buy_window_size + sell_window_size) × Leverage
If Account Balance < Required Margin × Safety Factor:
Refuse to start
- Leverage Check
If Leverage > max_leverage (default 10):
Refuse to start
- 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
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
Order Cleanup
Cleanup Strategy
Trigger Condition:
Pending Orders > order_cleanup_threshold
Cleanup Method:
- Sort orders by creation time
- Select oldest N orders (
cleanup_batch_size) - Batch cancel these orders
- 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)
Best Practices
- Must Enable Risk Control
risk_control:
enabled: true # Must enable
-
Reasonable Parameter Settings
- Adjust
volume_multiplierbased on market conditions - Set
recovery_thresholdbased on needs - Regularly check risk control triggers
- Adjust
-
Monitor Risk Control Status
- Regularly check logs
- Pay attention to risk control triggers
- Analyze trigger causes
-
Fund Management
- Don't invest all funds
- Keep sufficient margin buffer
- Set reasonable
position_safety_check
Next Steps
Risk control system is an important mechanism to protect fund safety. It is strongly recommended to enable and configure it properly.
Top comments (0)