# How the CloddsBot Risk Engine Is Structured: A Modular Pipeline Architecture

> Discover the CloddsBot risk engine's modular pipeline architecture. Understand how its Unified Risk Engine orchestrates VaR, volatility, safety, and Kelly sizing for robust risk checks.

- Repository: [AL/CloddsBot](https://github.com/alsk1992/CloddsBot)
- Tags: architecture
- Published: 2026-09-13

---

**The CloddsBot risk engine is a modular, layered system centered around a Unified Risk Engine that orchestrates specialized sub-components—including VaR calculation, volatility detection, safety management, and Kelly sizing—to enforce pre-trade and portfolio-level risk checks through a sequential validation pipeline.**

The risk management system in the `alsk1992/CloddsBot` repository implements a centralized **Unified Risk Engine** that validates every trade through a configurable pipeline of specialized checks. Written in TypeScript, the engine combines statistical risk metrics with circuit-breaker protections to ensure trading activities remain within predefined safety thresholds while maintaining high extensibility.

## Unified Risk Engine Core ([`src/risk/engine.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/risk/engine.ts))

The architecture centers on the `createRiskEngine` factory function (lines 44-56) in [`src/risk/engine.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/risk/engine.ts), which instantiates the main orchestrator with a `RiskConfig` object and dependency injections. According to the CloddsBot source code, this factory creates two critical internal subsystems: a **VaR calculator** (`createVaRCalculator`, lines 17-20) that tracks historical profit-and-loss to compute Value-at-Risk (VaR) and Conditional VaR (CVaR), and a **Volatility detector** (`createVolatilityDetector`, lines 21-24) that monitors realized P&L volatility to classify market regimes as low, medium, or high.

## Pre-Trade Validation Pipeline

The engine processes every trade through a sequential pipeline where each stage can abort execution early while logging specific warnings. This design isolates individual risk concerns into distinct validation layers.

### Safety Manager and Circuit Breakers

The **Safety Manager** ([`src/trading/safety.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/safety.ts)) provides circuit-breaker style protections including daily loss limits, drawdown caps, concentration limits, correlation checks, and a manual kill-switch. It is queried early in the validation sequence (lines 73-88) to ensure global trading permissions and threshold compliance. Following the safety check, the **Execution Circuit-Breaker** ([`src/execution/circuit-breaker.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/execution/circuit-breaker.ts)) validates execution-engine health (lines 92-104) by monitoring rate limits and order-flow anomalies.

### Trading-Level and Arbitrage Risk Checks

The engine delegates instrument-specific validations to specialized modules. In [`src/trading/risk.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/risk.ts), the `enforceMaxOrderSize` function (lines 13-29) validates that proposed orders do not exceed maximum size constraints, while `enforceExposureLimits` (lines 31-84) checks per-user position caps and stop-loss thresholds. For arbitrage strategies, the system additionally references [`src/opportunity/risk.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/opportunity/risk.ts) to model execution-specific hazards.

### VaR and Volatility Regime Validation

If configured with a `varLimit`, the engine compares the current 95% confidence VaR against the threshold (lines 88-99) and blocks trades that would exceed the limit. Simultaneously, the volatility detector returns a regime classification (`low`, `medium`, `high`). High volatility triggers warnings, while extreme volatility causes immediate trade abortion (lines 119-128).

### Kelly Sizing Integration

When a `DynamicKellyCalculator` is supplied from [`src/trading/kelly.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/kelly.ts), the engine computes Kelly-optimal position sizing based on estimated edge and confidence parameters, then scales the result by the volatility-regime multiplier (lines 141-176). If no Kelly calculator is present, only the regime multiplier applies to position sizing.

## Risk Decision and Portfolio APIs

Upon completion of the pipeline, the engine returns a `RiskDecision` object (lines 65-84) containing an `approved` boolean flag, optional `adjustedSize`, warning arrays, a detailed `checks` list with pass/fail status, and the current `regime` classification.

For portfolio oversight, `getPortfolioRisk()` (lines 90-108) returns a comprehensive snapshot including total value, position count, VaR95/99, CVaR, drawdown, and daily P&L. The `getDashboard()` method (lines 54-67) aggregates VaR, volatility, safety, circuit-breaker, Kelly, and concentration data into a UI-friendly format. External systems can invoke `runStressTest()` (lines 48-55) to simulate scenarios or `recordPnL()` (lines 70-74) to feed realized profits back into the VaR and volatility models.

## HTTP API Gateway ([`src/gateway/risk-routes.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/risk-routes.ts))

The risk engine exposes its functionality through an Express router defined in [`src/gateway/risk-routes.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/risk-routes.ts) (lines 20-124), wrapping the engine with REST endpoints for portfolio snapshots, regime queries, trade validation, stress-testing, and P&L recording.

## Implementation Example

*Creating the engine with all dependencies:*

```typescript
import { createRiskEngine } from './risk/engine';
import { createSafetyManager } from './trading/safety';
import { createVaRCalculator } from './risk/var';
import { createVolatilityDetector } from './risk/volatility';
import { createCircuitBreaker } from './execution/circuit-breaker';
import { createKellyCalculator } from './trading/kelly';
import db from './db';

const safety = createSafetyManager(db);
const engine = createRiskEngine(
  { varLimit: 2000, volatilityConfig: { windowSize: 200 } },
  {
    riskContext: {
      db: {
        getUser: id => db.getUser(id),
        getPositions: id => db.getPositions(id),
      },
    },
    safetyManager: safety,
    circuitBreaker: createCircuitBreaker(),
    kellyCalculator: createKellyCalculator(),
    getPositions: () => db.getOpenPositions(),
    getPositionValues: () => db.getOpenPositions().map(p => p.value),
  }
);

```

*Validating a trade via the engine:*

```typescript
const decision = engine.validateTrade({
  userId: 'u123',
  platform: 'polymarket',
  marketId: 'xyz',
  outcomeId: 'yes',
  side: 'buy',
  size: 150,
  price: 0.45,
  estimatedEdge: 0.07,
  confidence: 0.8,
  category: 'sports',
});

if (decision.approved) {
  console.log('Trade approved, size =', decision.adjustedSize);
} else {
  console.warn('Trade rejected:', decision.reason);
}

```

*Calling the REST endpoint:*

```bash
curl -X POST https://bot.example.com/api/risk/validate-trade \
     -H "Content-Type: application/json" \
     -d '{
           "userId":"u123",
           "platform":"polymarket",
           "marketId":"xyz",
           "outcomeId":"yes",
           "side":"buy",
           "size":150,
           "price":0.45,
           "estimatedEdge":0.07,
           "confidence":0.8,
           "category":"sports"
         }'

```

## Summary

- The **Unified Risk Engine** ([`src/risk/engine.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/risk/engine.ts)) serves as the central orchestrator, instantiated via `createRiskEngine` (lines 44-56) with configurable `RiskConfig` parameters.
- The validation pipeline follows a **sequential architecture** that aborts early on critical failures while accumulating warnings, involving the Safety Manager, Execution Circuit-Breaker, and trading-level risk checks.
- **Statistical risk components** include a VaR calculator (lines 17-20) for 95% confidence historical risk metrics and a volatility detector (lines 21-24) for regime classification (low/medium/high/extreme).
- **Position sizing** integrates Kelly criterion calculations (lines 141-176) when `DynamicKellyCalculator` is provided, scaled by volatility regime multipliers.
- The engine exposes **portfolio-level insights** through `getPortfolioRisk()`, `getDashboard()`, and stress-testing APIs, all accessible via REST endpoints in [`src/gateway/risk-routes.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/risk-routes.ts).

## Frequently Asked Questions

### What is the entry point for initializing the CloddsBot risk engine?

The entry point is the `createRiskEngine` factory function in [`src/risk/engine.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/risk/engine.ts) (lines 44-56). This function accepts a `RiskConfig` configuration object and a dependencies object containing the safety manager, circuit breaker, Kelly calculator, and database accessors, then returns an initialized engine instance ready to process trades.

### How does the risk engine handle high volatility market conditions?

The engine's `createVolatilityDetector` monitors realized P&L to classify the current regime as `low`, `medium`, `high`, or `extreme` (lines 21-24). When the detector returns `high` volatility, the engine attaches a warning to the trade decision (lines 119-128); when it detects `extreme` volatility, the engine immediately aborts the trade before execution, preventing entries during unstable market conditions.

### What information does the RiskDecision object contain after validation?

The `RiskDecision` object includes an `approved` boolean indicating whether the trade passed all checks, an optional `adjustedSize` number representing the Kelly-optimal or regime-scaled position size, an array of `warnings` describing non-fatal issues, a detailed `checks` array listing each validation step with pass/fail status and messages, and a `regime` string indicating the current volatility classification (lines 65-84).

### Which file contains the trading-specific risk limits like maximum order size?

Trading-specific risk limits are enforced in [`src/trading/risk.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/risk.ts), which exports `enforceMaxOrderSize` (lines 13-29) for validating order size constraints and `enforceExposureLimits` (lines 31-84) for checking per-user position caps and stop-loss thresholds against current portfolio state.