INDUSEURO
All case studies
Capital MarketsFinancial ServicesMiFID IIGDPR

Real-Time Anomaly Detection for Algorithmic Trading

Client: Proprietary Trading Firm, Germany

Built a millisecond-latency anomaly detection system for a German algo trading firm that monitors live order flow, flags risk events in real time, and prevents runaway trades before they execute.

<5msDetection latency
<0.3%False positive rate
50K+Orders monitored/sec
Dozens/monthIncidents prevented

Overview

Algorithmic trading systems can generate thousands of orders per second. When something goes wrong—a parameter misconfiguration, a market data spike, a runaway strategy—the damage compounds in milliseconds. Manual monitoring is not an option. The detection and response system has to be faster than the problem it's preventing.

This case study describes the design and delivery of a real-time anomaly detection system for a proprietary trading firm operating in German and European equity markets. The system processes live order flow, detects anomalous patterns using both rule-based and statistical methods, and triggers circuit breakers before problematic orders reach the exchange.


The Problem

The firm's existing risk controls were embedded in the trading system itself—pre-trade checks that evaluated each order individually against static limits. These were effective for simple limit breaches but blind to:

  • Behavioural anomalies: A strategy sending orders within individual limits but at an abnormal rate or pattern
  • Cross-instrument correlation anomalies: Unusual clustering of correlated positions across instruments
  • Market data anomalies: Strategies reacting unusually to stale or erroneous market data
  • Execution anomalies: Fill rates, slippage, or partial fill patterns that indicate exchange-side issues

The firm needed a layer of intelligence that could see across the entire order flow—not individual orders in isolation—and detect emergent patterns that indicate something is wrong before damage accumulates.


System Architecture

MARKET DATA & ORDER FLOW
         │
         ▼
┌─────────────────────────────────────────────────────────────┐
│                     Kafka Event Bus                         │
│   Topics: orders, fills, positions, market-data-ticks       │
└────────┬─────────────────┬──────────────────┬───────────────┘
         │                 │                  │
         ▼                 ▼                  ▼
┌────────────────┐ ┌───────────────┐ ┌──────────────────────┐
│  Rule Engine   │ │  Statistical  │ │  Market Data         │
│  (hard limits, │ │  Detector     │ │  Anomaly Detector    │
│  rate limits,  │ │  (z-score,    │ │  (stale data,        │
│  position      │ │  EWMA,        │ │  erroneous ticks,    │
│  thresholds)   │ │  isolation    │ │  spread anomalies)   │
│                │ │  forest)      │ │                      │
└───────┬────────┘ └───────┬───────┘ └──────────┬───────────┘
        │                 │                     │
        └─────────┬───────┘─────────────────────┘
                  │
                  ▼
         ┌────────────────┐
         │  Risk Aggregator│
         │  & Scorer       │
         │  (Redis, <1ms) │
         └───────┬────────┘
                 │
         ┌───────▼────────┐         ┌─────────────────────┐
         │  Circuit Breaker│────────▶│  Alert & Dashboard  │
         │  (halt / throttle│        │  (Grafana + webhook)│
         │  / notify)      │        └─────────────────────┘
         └─────────────────┘

Approach

Event Streaming Foundation

The system is built on Apache Kafka as the central event bus. Every order event, fill confirmation, position update, and market data tick is published to Kafka topics. This decouples the detection layer completely from the trading system—the trading infrastructure publishes events; the anomaly detection system consumes them independently with no impact on trading latency.

Consumer groups allow multiple detection modules to process the same event stream independently at their own pace.

Three Detection Layers

Rule Engine: Fast, deterministic checks run first. These evaluate rate limits (orders per second per strategy), position thresholds, order size anomalies, and time-of-day constraints. The rule engine uses pre-compiled decision trees stored in Redis for sub-millisecond evaluation.

Statistical Detector: A sliding-window statistical model builds a real-time baseline of each strategy's normal behaviour—order rate distribution, average size, instrument spread, fill rate, slippage. Exponentially Weighted Moving Averages (EWMA) track the evolving baseline. Deviations beyond configurable z-score thresholds trigger anomaly signals. An Isolation Forest model provides a second opinion on multivariate anomalies that simple z-score misses.

Market Data Anomaly Detector: Separate from order analysis, this module monitors the data the trading strategies are consuming. It flags stale timestamps, bid-ask spread anomalies, tick rate anomalies, and price discontinuities. A strategy reacting to bad market data is as dangerous as a strategy behaving incorrectly, and this module catches that at the source.

Risk Aggregation & Circuit Breakers

Signals from all three layers feed into a Risk Aggregator that scores the current situation per strategy and per portfolio. Scores are maintained in Redis for constant-time lookup. When a score exceeds configurable thresholds, the Circuit Breaker triggers one of three responses:

  1. Notify: Log and alert the risk desk (low-confidence or informational anomalies)
  2. Throttle: Rate-limit the affected strategy's order submission
  3. Halt: Immediately stop a strategy's order flow and alert for manual review

The response level is determined by anomaly type, confidence score, and position risk.

Feedback Loop & Model Improvement

Every triggered alert is logged with full context. Risk desk operators confirm, modify, or dismiss each alert. This feedback trains the statistical models over time, reducing false positives and improving sensitivity to genuine anomalies.


Key Technical Challenges

Latency budget: The total detection-to-action latency budget was under 5 milliseconds. Achieving this required careful profiling, Redis for in-memory state, compiled rule evaluation, and avoiding any synchronous database writes on the critical path.

Baseline cold start: A new strategy has no historical baseline. The system uses a conservative warm-up period with stricter rule-based thresholds until the statistical model has accumulated enough data to establish a reliable baseline.

Alert fatigue: Early tuning produced too many low-confidence alerts, leading risk desk operators to tune them out. We implemented a tiered confidence scoring system and a daily alert quality report, and worked with the risk desk to calibrate thresholds until the false positive rate dropped below 0.3%.

Kafka consumer group coordination: Multiple detection modules consuming the same Kafka topics required careful partition assignment and offset management to ensure no events are dropped or double-processed, especially during module restarts.


Outcomes

  • Detection latency consistently under 5ms from event publication to circuit breaker response.
  • Monitoring capacity of 50,000+ orders per second without performance degradation.
  • False positive rate below 0.3% after two months of threshold calibration.
  • Dozens of genuine risk events prevented monthly—including two incidents that would have resulted in significant financial loss.
  • Risk desk reports full confidence in the system's signal quality; alert dismissal rate has dropped from 60% to under 10%.

Technology Stack

  • Event streaming: Apache Kafka
  • In-memory state: Redis
  • Statistical models: Python (scikit-learn), custom EWMA implementation
  • API layer: FastAPI (configuration and alert management)
  • Database: PostgreSQL (historical events, model feedback)
  • Monitoring: Grafana dashboards with custom alert panels
  • Deployment: Docker Compose on on-premise servers (firm security requirement)

Compliance & Governance

  • MiFID II algorithmic trading risk controls satisfied by the circuit breaker framework.
  • Full audit trail of every anomaly event, alert, and circuit breaker action.
  • GDPR: no personal data processed—all data is market and order data.
  • Quarterly model review with risk desk to recalibrate thresholds and validate baseline assumptions.

Technology stack

PythonApache KafkaRedisPostgreSQLScikit-learnFastAPIGrafana

Services delivered

Software EngineeringData Engineering for AI

Discuss a similar project

If this case study is relevant to a challenge you're facing, we'd welcome the conversation.

Book a consultation