Crisis Alerting & Black Swan Detection

Real-Time Anomaly Detection with Automatic Trading Halts

System Overview

The Black Swan Detection system continuously monitors market data for anomalies that could indicate impending crisis events. When high-severity events are detected, all live trading runs are automatically halted.

12
Event Types
4
Severity Levels
15+
Historical Patterns
5min
Detection Cycle

Automatic Trading Halt

When a black swan warning with severity HIGH or above is detected, all live trading runs are immediately halted. This is a safety measure to protect capital during extreme market conditions.

Detection Pipeline

The detection system analyzes data from the All-Seeing Eye aggregation layer, computing z-scores and correlation changes.

flowchart TB subgraph Input["All-Seeing Eye Data"] AGG[aggregateAllData
15 source categories] end subgraph Detection["Black Swan Detector"] ANOM["detectAnomalies()
Z-score analysis"] CORR["detectCorrelationRegimeChanges()
Correlation matrix diff"] TYPE["determineEventType()
Pattern classification"] SEV["calculateSeverity()
Based on z-scores"] PROB["calculateProbability()
Occurrence likelihood"] end subgraph Analysis["Deep Analysis"] WHY["generateWhyAnalysis()
Root cause"] HOW["generateHowAnalysis()
Mechanism"] WHAT["generateWhatAnalysis()
Impact assessment"] WHEN["generateWhenAnalysis()
Timeline"] WHERE["generateWhereAnalysis()
Affected sectors"] HIST["findBestHistoricalMatch()
Similar past events"] end subgraph Output["Warning Generation"] WARN["BlackSwanWarning"] ACT["suggestedActions"] HEDGE["hedgingStrategies"] end subgraph Response["Automated Response"] EXEC["Executor tickRun()
Halt live runs"] SSE["SSE Stream
Real-time alerts"] DB["Database
Warning storage"] end AGG --> ANOM AGG --> CORR ANOM --> TYPE CORR --> TYPE TYPE --> SEV SEV --> PROB PROB --> WHY PROB --> HOW PROB --> WHAT PROB --> WHEN PROB --> WHERE PROB --> HIST WHY --> WARN HOW --> WARN WHAT --> WARN WHEN --> WARN WHERE --> WARN HIST --> WARN WARN --> ACT WARN --> HEDGE WARN --> EXEC WARN --> SSE WARN --> DB style WARN fill:#f85149,color:#fff style EXEC fill:#f0883e,color:#000

Anomaly Detection

The detectAnomalies() function computes z-scores for each data source against historical means and standard deviations.

Z-Score Range Interpretation Action
|z| < 2 Normal range No action
2 ≤ |z| < 3 Unusual Monitor
3 ≤ |z| < 4 Significant anomaly Elevated warning
|z| ≥ 4 Extreme anomaly High+ severity warning

Correlation Regime Changes

The system tracks a rolling correlation matrix between data sources. Sudden changes indicate regime shifts:

Event Types

12 distinct crisis event types are detected based on triggering signal patterns.

📉 Market Crash
Flash Crash
💧 Liquidity Crisis
💱 Currency Crisis
🌍 Geopolitical
🦠 Pandemic
🏗️ Infrastructure
🔒 Cyber Attack
🌊 Natural Disaster
📜 Regulatory Shock
🔗 Contagion
🏦 Systemic Risk

Detection Signals by Event Type

Event Type Key Signals Detection Pattern
Market Crash VIX spike, volume surge, price collapse VIX > 35, S&P down > 4% intraday
Flash Crash Extreme volume, rapid price swing, quick reversal 5%+ move in < 10 min, 50%+ retracement
Liquidity Crisis Bid-ask spread widening, order book depth collapse Spread 3x normal, MOVE > 150
Currency Crisis FX volatility, rate differentials, reserve depletion 5%+ currency move, yield curve inversion
Geopolitical News sentiment, defense stocks, oil spike Sentiment collapse + energy spike
Systemic Risk Credit spreads, bank CDS, intermarket correlation Investment grade spread > 200bp

Severity Levels

Four severity levels determine the response action, from monitoring to automatic trading halt.

⚠️
ELEVATED
Unusual conditions detected. Continue trading with caution.
🔶
HIGH
Significant risk. Live runs halted.
🔴
SEVERE
Crisis conditions. All trading stopped.
🚨
EXTREME
Black swan event. Emergency protocols.

Severity Calculation

Input Elevated High Severe Extreme
Max Z-Score 2.5 - 3.0 3.0 - 4.0 4.0 - 5.0 > 5.0
Correlation Breaks 1 - 2 3 - 4 5 - 7 > 7
Signal Count 2 - 3 4 - 5 6 - 8 > 8

Executor Kill Switch Integration

The trading executor checks for active black swan warnings on every tick. Live runs are automatically halted when high+ severity warnings exist.

sequenceDiagram participant T as tickRun() participant K as AI Kill Switch participant B as Black Swan Detector participant D as Database participant L as Live Status T->>K: isAiTradingKilled() K-->>T: false T->>B: listActiveWarnings() B-->>T: [warning: {severity: 'high'}] alt severity >= high T->>D: recordKill(guardrail, L1, 'Black swan: ...') T->>D: UPDATE algorithm_runs SET ended_at, kill_reason T->>L: updateLiveStatus(killed, 'Black swan warning') T-->>T: return killed:L1:black_swan else severity < high T->>T: Continue normal tick processing end

Kill Reason Format

Black swan: {eventType} ({severity})
Example: Black swan: market_crash (high)

Paper Runs Not Affected

Black swan warnings only halt live trading runs. Paper trading continues to operate, allowing users to observe strategy behavior during crisis conditions.

Historical Pattern Matching

Each warning is matched against 15+ historical crisis events to provide context and precedent.

2008 Financial Crisis
September 2008
87%
COVID-19 Crash
March 2020
72%
2022 Rate Shock
September 2022
65%

Matching Algorithm

Historical matching uses cosine similarity on normalized feature vectors:

Warning Structure

The BlackSwanWarning object contains comprehensive analysis for each detected event.

Field Type Description
idstringUnique warning ID (blackswan_xxxxx)
titlestringHuman-readable title with emoji
eventTypestringOne of 12 event types
severitystringelevated | high | severe | extreme
probabilitynumberOccurrence probability 0-1
confidencenumberDetection confidence 0-1
anomalyScorenumberComposite anomaly score
zScoresRecordPer-source z-scores
correlationBreaksarrayPairs with correlation changes
triggeringSignalsarrayData points that triggered detection
whystringRoot cause analysis
howstringMechanism explanation
whatstringImpact assessment
whenstringTimeline prediction
wherestringAffected sectors/assets
historicalMatchIdstringBest matching past crisis
historicalSimilaritynumberSimilarity score 0-1
suggestedActionsarrayRecommended responses
hedgingStrategiesarrayPosition protection ideas
statusstringactive | resolved | monitoring
createdAtstringWarning timestamp

Hedging Strategies

Each warning includes event-type-specific hedging recommendations.

Event Type Hedging Strategies
Market Crash
  • Long VIX calls
  • Put spreads on SPY/QQQ
  • Long Treasury duration
  • Reduce equity beta
Liquidity Crisis
  • Raise cash allocation
  • Exit illiquid positions
  • Treasury bill ladder
  • Gold allocation
Currency Crisis
  • USD/safe haven FX long
  • EM exposure reduction
  • Commodity hedges
  • Local currency bonds exit
Systemic Risk
  • Credit default swaps
  • Bank sector underweight
  • Short high-yield debt
  • Quality factor tilt

API Endpoints

Endpoint Method Description
/api/predict/v1/all-seeing-eye/warnings GET List all warnings (optional status filter)
/api/predict/v1/all-seeing-eye/warnings/:id GET Get specific warning details
/api/predict/v1/all-seeing-eye/warnings/active GET Get active warnings only
/api/predict/v1/all-seeing-eye/warnings/:id/status PATCH Update warning status (admin)
/api/predict/v1/all-seeing-eye/historical-patterns GET List historical crisis patterns
/api/predict/v1/all-seeing-eye/status GET System health and warning count

Key Files

File Purpose
packages/be/src/all-seeing-eye/black-swan/detector.tsCore detection logic
packages/be/src/all-seeing-eye/black-swan/analyzer.tsWhy/How/What/When/Where analysis
packages/be/src/all-seeing-eye/black-swan/historical-patterns.tsHistorical crisis matching
packages/be/src/all-seeing-eye/black-swan/index.tsModule exports, warning storage
packages/be/src/algorithms/paper/executor.tsKill switch integration (line 1438)
packages/be/src/all-seeing-eye/orchestrator/index.ts5-minute detection cycle