# How CloddsBot's Risk Engine Automatically Tightens Risk Bounds

> Discover how CloddsBot's risk engine automatically tightens risk bounds by reducing active parameters like maxOrderSize and exposure limits when breaches are detected.

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

---

**CloddsBot automatically tightens risk bounds by reducing active risk parameters—such as `maxOrderSize` and exposure limits—whenever `enforceExposureLimits` or `enforceMaxOrderSize` detect a breach, creating a self-correcting feedback loop that protects users from runaway exposure without manual intervention.**

The **CloddsBot** trading system, available in the `alsk1992/CloddsBot` repository, implements a defensive risk architecture that dynamically constrains trading capacity when market conditions or user settings would otherwise permit dangerous leverage. Written in TypeScript, the **CloddsBot risk engine automatically tightens risk bounds** through pure-function utilities invoked during every order-placement request, ensuring that a single breach triggers immediate parameter reduction for the remainder of the session.

## Core Risk Validation Functions

The engine’s guardrails reside in [`src/trading/risk.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/risk.ts), which exports deterministic validation functions consumed by the order-building pipeline. These utilities inspect the trading context and user settings before any order reaches the market.

### Portfolio Exposure Limits

The `enforceExposureLimits` function queries the user’s current positions via `context.db.getPositions` and compares them against three configurable thresholds stored in user settings:

- **`maxPositionValue`** – Caps exposure for a single market or outcome.
- **`maxTotalExposure`** – Limits aggregate notional value across all positions.
- **`stopLossPct`** – Defines the price threshold below which new orders are rejected.

If adding a new order would violate any of these constraints, `enforceExposureLimits` returns a JSON-encoded error object containing a detailed message and a `hint` field (e.g., “Reduce size or update maxOrderSize in user settings”). The builder intercepts this error to trigger the tightening sequence.

### Per-Order Size Constraints

Before exposure checks run, `enforceMaxOrderSize` validates the requested notional against `context.tradingContext?.maxOrderSize`. If the order exceeds this cap, the function returns an error immediately. This check prevents individual trades from consuming excessive capital before portfolio-level limits are even considered.

## Automatic Tightening Mechanism in builder.ts

When [`src/trading/builder.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/builder.ts) receives an error from the risk utilities, it does not merely block the order—it recalibrates the session’s active risk parameters. This automatic tightening ensures that subsequent requests face stricter scrutiny without requiring manual configuration changes.

### Dynamic Parameter Reduction

Upon detecting a `riskError`, the builder reduces the `maxOrderSize` (or `maxPortfolioPct`) by twenty percent:

```typescript
// Inside src/trading/builder.ts
if (riskError) {
  // Reduce the maximum order size for the rest of the session
  params.risk.maxOrderSize = Math.max(0, params.risk.maxOrderSize * 0.8);
}

```

This multiplication by `0.8` effectively tightens the bound, preventing large-size orders until the user explicitly raises the limit in their settings. The `Math.max(0, ...)` guard ensures the parameter never drops below zero.

### Session Cool-Down and Rate Limits

Beyond size reduction, the engine applies a temporary suspension and daily volume caps:

- **Cool-down**: The builder reads `params.risk.cooldownSec` (defaulting to 60 seconds) and sets a timer to throttle further order attempts.
- **Daily limits**: The `maxTradesPerDay` limit is enforced automatically, capping total execution count regardless of individual order size.

```typescript
// Apply a cool-down to throttle further orders
const cooldownMs = (params.risk.cooldownSec || 60) * 1000;
setTimeout(() => { /* resume trading */ }, cooldownMs);

```

## Pre-Trade Integration and Feedback Loops

The risk checks are wired into the order lifecycle via [`src/trading/pre-trade.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/pre-trade.ts), which invokes the validation functions before finalizing any trade. When a breach occurs, the error object’s `hint` field surfaces actionable guidance to the user interface. Although users can manually raise limits in their configuration, the engine continues to enforce the tightened bounds until the offending condition clears—for example, until a stop-loss breach is resolved or the cool-down period expires.

## Implementation Example

The following integration demonstrates how the validation functions are invoked and how the builder responds to breaches:

```typescript
// Example: order creation – the engine automatically validates risk
import { enforceMaxOrderSize, enforceExposureLimits } from '../../src/trading/risk';

function tryPlaceOrder(context, userId, notional, label) {
  // 1️⃣ Check max-order-size cap
  const sizeError = enforceMaxOrderSize(context, notional, label);
  if (sizeError) return JSON.parse(sizeError); // engine will tighten maxOrderSize

  // 2️⃣ Check exposure limits (max total exposure, per-market caps, stop-loss)
  const expError = enforceExposureLimits(context, userId, {
    platform: 'somePlatform',
    marketId: 'mkt-123',
    notional,
    label,
  });
  if (expError) return JSON.parse(expError); // engine will tighten exposure bounds
}

```

## Summary

- **Validation layer**: [`src/trading/risk.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/risk.ts) provides `enforceExposureLimits` and `enforceMaxOrderSize` to check `maxTotalExposure`, `maxPositionValue`, `stopLossPct`, and `maxOrderSize` against real-time positions.
- **Tightening logic**: [`src/trading/builder.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/builder.ts) captures validation errors and automatically reduces `maxOrderSize` by 20%, applies a configurable `cooldownSec` timer, and enforces `maxTradesPerDay`.
- **Integration**: [`src/trading/pre-trade.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/pre-trade.ts) hooks the risk checks into every order request, ensuring the self-correcting loop runs automatically without manual intervention.

## Frequently Asked Questions

### What triggers automatic risk tightening in CloddsBot?

The tightening mechanism triggers when `enforceExposureLimits` or `enforceMaxOrderSize` in [`src/trading/risk.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/risk.ts) return a validation error. This occurs when a new order would exceed `maxTotalExposure`, `maxPositionValue`, `stopLossPct`, or the per-order size cap defined in `context.tradingContext.maxOrderSize`.

### How does the builder.ts file reduce risk parameters?

When [`src/trading/builder.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/builder.ts) detects a risk error, it multiplies the current `params.risk.maxOrderSize` by `0.8`, reducing the allowable order size by twenty percent for the remainder of the session. It also initiates a cool-down timer based on `params.risk.cooldownSec` to throttle subsequent requests.

### Can users override tightened risk bounds manually?

Users can manually adjust their risk settings (such as raising `maxOrderSize` or `maxTotalExposure`) through the bot’s configuration interface. However, the engine continues to enforce the tightened bounds until the specific breach condition clears—such as the cool-down period expiring or the stop-loss threshold being satisfied.

### Which files contain the core risk management logic?

The primary risk enforcement logic resides in three key locations:
- [`src/trading/risk.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/risk.ts) – Contains the pure validation functions `enforceExposureLimits` and `enforceMaxOrderSize`.
- [`src/trading/builder.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/builder.ts) – Implements the automatic tightening logic and parameter reduction.
- [`src/trading/pre-trade.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/trading/pre-trade.ts) – Provides the hooks that invoke risk checks before order execution.