Risk logo

Risk

CommunityPopular
alsk1992
risk

Unified risk engine with VaR, stress testing, volatility regimes, and automated controls

Overview

Publisheralsk1992
RepositoryCloddsBot
Skill namerisk
Stars
3K
Forks
353
Bundled files
1
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 1 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by alsk1992 on GitHub. Read the source before you install it.

Installation

Install the Risk AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/alsk1992/CloddsBot/tree/main/src/skills/bundled/risk
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/alsk1992/CloddsBot.git /tmp/CloddsBot
mkdir -p .claude/skills
cp -r /tmp/CloddsBot/src/skills/bundled/risk .claude/skills/risk
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Risk in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Risk on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Risk is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Risk - Complete API Reference

Full risk management engine: circuit breakers, loss limits, Value-at-Risk, volatility regime detection, stress testing, and kill switches.


Chat Commands

View Risk Status

/risk                               Current risk status
/risk status                        Detailed status with portfolio metrics
/risk limits                        View all limits
/risk dashboard                     Real-time risk metrics (VaR, regime, HHI, etc.)

Risk Analytics

/risk var                           Value-at-Risk and CVaR numbers
/risk regime                        Current volatility regime and size multiplier
/risk stress [scenario]             Run stress test (flash_crash, black_swan, etc.)

Available stress scenarios: flash_crash, liquidity_crunch, platform_down, correlation_spike, black_swan

Configure Limits

/risk set max-loss 1000             Max daily loss ($)
/risk set max-loss-pct 10           Max daily loss (%)
/risk set max-drawdown 20           Max drawdown (%)
/risk set max-position 25           Max single position (%)
/risk set max-trades 50             Max trades per day
/risk set consecutive-losses 5      Stop after N losses

Circuit Breaker

/risk trip "manual stop"            Manually trip breaker
/risk reset                         Reset after cooldown
/risk kill                          Emergency stop all trading
/risk check 500                     Check if a $500 trade is allowed

TypeScript API Reference

Unified Risk Engine

The risk engine is the single entry point for all pre-trade validation. It orchestrates 10 checks in order:

  1. Kill switch (SafetyManager)
  2. Circuit breaker (execution-level)
  3. Max order size
  4. Exposure limits
  5. Daily loss limit
  6. Max drawdown
  7. Position concentration
  8. VaR limit
  9. Volatility regime
  10. Kelly sizing recommendation
typescript
import { createRiskEngine } from 'clodds/risk';

const engine = createRiskEngine(
  {
    varLimit: 500,           // Reject trades if portfolio VaR > $500
    varConfidence: 0.95,
    varWindowSize: 100,
    volatilityConfig: {
      lookbackWindow: 30,
      haltOnExtreme: true,   // Stop trading in extreme volatility
    },
  },
  {
    riskContext,              // From trading/risk.ts
    safetyManager,           // From trading/safety.ts
    circuitBreaker,          // From execution/circuit-breaker.ts
    kellyCalculator,         // From trading/kelly.ts
    getPositions: () => positions,
    getPositionValues: () => positions.map(p => p.value),
  }
);

Validate a Trade

typescript
const decision = engine.validateTrade({
  userId: 'user-123',
  platform: 'polymarket',
  marketId: 'market-456',
  outcome: 'YES',
  side: 'buy',
  size: 500,
  price: 0.65,
  estimatedEdge: 0.05,    // 5% edge
  confidence: 0.8,
  category: 'politics',
});

if (decision.approved) {
  // Use adjustedSize — may be smaller than requested (Kelly + regime)
  await executeTrade(decision.adjustedSize);
  console.log(`Regime: ${decision.regime}`);
  console.log(`Warnings: ${decision.warnings}`);
} else {
  console.log(`Blocked: ${decision.reason}`);
  // Check which step failed:
  for (const check of decision.checks) {
    console.log(`  ${check.name}: ${check.passed ? 'PASS' : 'FAIL'} — ${check.message}`);
  }
}

Record Trade P&L (feeds VaR + volatility)

typescript
engine.recordPnL({
  pnlUsd: -45.20,
  pnlPct: -0.09,
  positionId: 'polymarket:market-456:YES',
  timestamp: new Date(),
});

Portfolio Risk Snapshot

typescript
const risk = engine.getPortfolioRisk();
console.log(`Total value: $${risk.totalValue}`);
console.log(`VaR (95%): $${risk.var95}`);
console.log(`VaR (99%): $${risk.var99}`);
console.log(`CVaR (95%): $${risk.cvar95}`);
console.log(`Regime: ${risk.regime}`);
console.log(`Drawdown: ${risk.drawdownPct}%`);

Value-at-Risk

typescript
import { createVaRCalculator, calculateVaR, calculateCVaR } from 'clodds/risk';

// Full calculator with rolling window
const calc = createVaRCalculator({ windowSize: 100, confidenceLevel: 0.95 });
calc.addObservation({ pnlUsd: -50, pnlPct: -0.05, timestamp: new Date() });
const result = calc.calculateAt(0.99);
console.log(`VaR (99%): $${result.historicalVaR}`);
console.log(`CVaR (99%): $${result.cvar}`);

// Quick one-liners
const var95 = calculateVaR(pnlArray, 0.95);
const cvar95 = calculateCVaR(pnlArray, 0.95);

Volatility Regime Detection

typescript
import { createVolatilityDetector, detectRegime } from 'clodds/risk';

const detector = createVolatilityDetector({
  lookbackWindow: 30,
  haltOnExtreme: false,
  regimeMultipliers: { low: 1.2, normal: 1.0, high: 0.5, extreme: 0.25 },
});

detector.addObservation(0.03);  // 3% P&L
const snapshot = detector.detect();
console.log(`Regime: ${snapshot.regime}`);          // 'low' | 'normal' | 'high' | 'extreme'
console.log(`Size multiplier: ${snapshot.sizeMultiplier}x`);
console.log(`Should halt: ${snapshot.shouldHalt}`);

// One-shot from array
const regime = detectRegime(recentPnLPcts);

Stress Testing

typescript
import { runStressTest, runAllScenarios, getAvailableScenarios } from 'clodds/risk';

const result = runStressTest(positions, 'flash_crash');
console.log(`Estimated loss: $${result.estimatedLoss} (${result.estimatedLossPct}%)`);
console.log(`Severity: ${result.severity}`);
console.log(`Recommendations: ${result.recommendations.join(', ')}`);

// Run all scenarios at once
const all = runAllScenarios(positions);  // sorted by severity

// Override scenario parameters
const custom = runStressTest(positions, 'flash_crash', {
  scenarios: { flash_crash: { lossPct: 30, description: 'Severe crash' } },
});

Risk Dashboard

typescript
import { getRiskDashboard } from 'clodds/risk';

const dashboard = engine.getDashboard();
console.log(`VaR (95%): $${dashboard.portfolioVaR95}`);
console.log(`Regime: ${dashboard.regime} (${dashboard.regimeSizeMultiplier}x)`);
console.log(`Daily P&L: $${dashboard.dailyPnL} / $${dashboard.dailyLossLimit}`);
console.log(`Drawdown: ${dashboard.currentDrawdown}% / ${dashboard.maxDrawdown}%`);
console.log(`Concentration HHI: ${dashboard.concentrationHHI}`);
console.log(`Kill switch: ${dashboard.killSwitchActive}`);
console.log(`Warnings: ${dashboard.warnings}`);

Circuit Breaker (Standalone)

typescript
import { createCircuitBreaker, MODERATE_CONFIG } from 'clodds/risk';

// Feature-engineering circuit breaker (market-condition-aware)
const breaker = createCircuitBreaker(MODERATE_CONFIG);
breaker.startMonitoring();

if (!breaker.canTrade('polymarket', marketId)) {
  return; // Trading halted
}

breaker.recordTrade({ success: true, pnl: 2.5 });

Kill Switch

typescript
// Emergency stop via SafetyManager — no auto-resume
safetyManager.killSwitch('Market anomaly detected');

// Resume manually after review
safetyManager.resumeTrading();

Risk Engine Checks

#CheckModuleBlocks Trade?
1Kill switchSafetyManagerYes
2Circuit breakerCircuitBreakerYes
3Max order sizetrading/riskYes
4Exposure limitstrading/riskYes
5Daily loss limitSafetyManagerYes
6Max drawdownSafetyManagerYes
7ConcentrationSafetyManagerYes
8VaR limitVaRCalculatorYes (if configured)
9Volatility regimeVolatilityDetectorYes (if extreme + halt)
10Kelly sizingDynamicKellyNo (adjusts size)

Circuit Breaker Triggers

TriggerDefaultDescription
Daily loss (USD)$1,000Absolute loss limit
Daily loss (%)10%Percentage of capital
Drawdown20%Peak-to-trough
Consecutive losses5Losses in a row
Error rate50%Failed order rate
Max trades50Trades per day

Volatility Regimes

RegimeSize MultiplierDescription
low1.2xCalm markets, slightly larger positions
normal1.0xBaseline conditions
high0.5xElevated volatility, half size
extreme0.25xCrisis — quarter size or halt trading

Stress Test Scenarios

ScenarioLossDescription
flash_crash20%All positions lose value instantly
liquidity_crunch10%Slippage doubles, partial fills
platform_down15%Primary platform offline
correlation_spike25%All positions move together
black_swan40%3-sigma tail event

Status Levels

StatusDescription
armedNormal, trading allowed
warningApproaching limits (80%)
trippedLimit exceeded, trading stopped
killedEmergency stop, manual reset required

Recovery Process

  1. Auto-reset: Next day at midnight (daily counters)
  2. Cooldown: Circuit breaker auto-resets after cooldown period
  3. Manual reset: /risk reset to re-arm
  4. Kill recovery: /risk reset after manual review (no auto-resume)

Best Practices

  1. Start conservative — Lower limits while learning
  2. Don't override — Respect the circuit breaker
  3. Review trips — Understand why limits were hit
  4. Monitor VaR — Use /risk var and /risk dashboard regularly
  5. Run stress tests — Use /risk stress before large position changes
  6. Watch regime — Use /risk regime to understand current volatility
  7. Adjust limits — Based on strategy performance and regime

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Risk AI skill do?

Unified risk engine with VaR, stress testing, volatility regimes, and automated controls

Why use Risk on TypingMind?

Because you install it once and use it with any model. Risk is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Risk in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/alsk1992/CloddsBot/tree/main/src/skills/bundled/risk. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Risk?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Risk?

As many as you like. As long as a model supports skills, you can use Risk with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Risk AI skill free?

Yes. It is published on GitHub by alsk1992 under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇