Skip to main content
Glama
dushaorighthere

RiskPilot

README.md
# RiskPilot

**Risk-controlled crypto trading agent built with Binance Agent OS and Binance MCP.**

**Risk before execution.** A risk-controlled crypto agent workflow designed for Binance Agent OS.

RiskPilot turns market snapshots and structured agent proposals into `LONG`, `SHORT` or `NO_TRADE` decisions. A deterministic engine checks every candidate before a local paper fill. Refusals are first-class outputs, with specific reasons and a verifiable audit trail.

**Status: final release candidate verified on 2026-09-05; PAPER execution only.** Official OAuth, four real read-only tools, concrete schema binding, CLI/UI decisions and risk-refusal audit evidence are complete. Codex owns the credentials. The earlier unauthenticated HTTP 401 probe is historical. Public GitHub, video, X publication and the final survey remain participant actions. See [integration verification](evidence/official-integration-verification.json) and [security audit](SECURITY_AUDIT.md).

## Problem and approach

An AI-generated trade idea can be wrong, oversized or explicitly unsafe. RiskPilot separates proposal from authority: market data and an agent may propose an action, while an independent deterministic engine decides whether it is allowed. This makes refusals, position sizing and the exact policy visible and auditable.

> **AI can propose a trade, but it cannot override deterministic risk controls.**

RiskPilot is not a conventional auto-trading bot. It has no exchange execution adapter. The implemented workflow ends in a local PAPER decision and, when approved, a simulated entry recorded in SQLite.

## Start in under a minute

Offline/public REST modes require Python **3.11+**, with no runtime pip dependencies or build step. Agent OS mode additionally requires an installed, authenticated Codex CLI (verified with 0.149.1); no API key is entered into RiskPilot.

On Windows, double-click **`START_DEMO.cmd`**. It detects an available Python runtime and opens the page. Keep the server window open.

Portable command, from this repository:

```sh
python -m riskpilot serve
```

Open **http://127.0.0.1:8765**. If the port is occupied, use `python -m riskpilot serve --port 8766` and the URL printed by the server. All servers bind to `127.0.0.1` only. `Ctrl+C` stops the process. No system security settings need to change.

Optional isolated environment:

```sh
python -m venv .venv
# Windows (activation is not required):
.venv\Scripts\python -m riskpilot serve
# macOS/Linux:
.venv/bin/python -m riskpilot serve
```

## The 90-second demonstration

Click **New paper session** to start with an empty simulated portfolio while retaining history.

1. Select **Agent OS MCP · read only**, ETH/USDT, then **Analyze & check**. Confirm `AGENT_OS_HOST_BRIDGE`, the current market snapshot and a natural `LONG`, `SHORT` or `NO_TRADE` result. Do not force a trade.
2. Switch to **Synthetic demo · offline**, select **02 · Valid long**, then analyze. Expect `APPROVED`, about **2.60:1 net R:R**, **0.9933 ETH**, **$44.94 modeled stop risk**, and `SIMULATED_FILL`.
3. Select **03 · Unsafe request**, then analyze. The request asks for 50x leverage and more size. Expect `REJECTED`, including `RISK_LIMIT_EXCEEDED`, `LEVERAGE_LIMIT_EXCEEDED` and `POSITION_LIMIT_EXCEEDED`; no new fill.
4. Inspect **Audit trail**, expand the full decision and show the verified chain.

`01 · No setup` and `04 · Valid short` provide reproducible `NO_TRADE` and `SHORT` results. The short is a local directional simulation; it does not short spot ETH or open a derivatives account. Synthetic prices are illustrative. Live market prices and decisions will differ.

See [the script](SUBMISSION/DEMO_SCRIPT.md), [shot list](SUBMISSION/VIDEO_SHOT_LIST.md) and [replication guide](SUBMISSION/REPLICATION_GUIDE.md).

## Binance Agent OS / MCP and system architecture

| Mode | Implementation | Evidence / limitations |
|---|---|---|
| Synthetic demo | Deterministic generated hourly candles and a demo command router | Offline, explicitly labeled; no LLM used inside the page |
| Binance public data | Three fixed public GET routes: exchangeInfo, klines, bookTicker | No credentials; no fallback on errors; unfinished candle excluded |
| Local MCP tools | `riskpilot_policy`, `riskpilot_analyze`, `riskpilot_audit` over stdio | AI hosts can supply structured proposals; every candidate enters the same engine |
| Agent OS host bridge | Codex app-server uses its stored OAuth; verified `spot.exchangeInfo`, `spot.klines` and `spot.depth` feed the same engine | Authenticated CLI/UI reads, PAPER fill, rejection and audit verified; no LLM turn is required for acquisition |
| Execution | SQLite paper entry simulation only | No LIVE adapter, environment switch, order endpoint or funds-transfer operation |

The page is a reliable demonstration surface, not an LLM chat service. Connect a compatible AI host to the local MCP server to give natural-language reasoning access to the guarded tools. Use [the host prompt](agent/SYSTEM_PROMPT.md) and [connection guide](agent/CONNECT.md). The model may propose price levels and quantities; it cannot set policy, approve its own trade, or access exchange writes through RiskPilot.

Select **Agent OS MCP · read only** in the UI to use the authenticated bridge. The CLI binds `CodexMarketBridge` through `AgentOSAdapter`; library users can inject the same bridge. Codex must expose exactly `spot.ticker24hr`, `spot.exchangeInfo`, `spot.klines` and `spot.depth`. `tool_execute`, account reads and exchange writes are excluded. The bridge rejects unsupported tools and symbols before transport and rejects mismatched schemas/data. Authentication errors never switch silently to REST or fixtures. See [setup](agent/CONNECT.md) and [actual tool schemas](evidence/official-market-tool-schemas.json).

The implemented flow is:

```text
Binance MCP read-only market data
        ↓
validated normalized snapshot
        ↓
strategy or untrusted agent proposal
        ↓
deterministic risk engine
        ↓
NO_TRADE / REJECTED / approved local PAPER fill
        ↓
hash-linked audit trail
```

See [the detailed architecture](SUBMISSION/ARCHITECTURE.md).

## Hard rules and calculations

Immutable policy: $10,000 paper equity, default requested risk 0.5%, maximum risk 1%, minimum **net** R:R 2, leverage 1–3x, one position ≤30% of equity in notional, ≤3 open positions, total notional ≤100% of equity and aggregate modeled stop risk ≤2%.

Stop loss and take profit are required. Direction, price tick, quantity step, minimum notional, spread ≤20 bps, quote age ≤90 seconds, market/proposal symbol match and entry within 0.3% of midpoint are checked. Public symbol filters are fetched; fixtures use declared paper filters.

Quote age is measured from the public request start, not an exchange event timestamp: `bookTicker` does not provide one. The last closed hourly bar must end within 3,700 seconds. This is a data validation boundary, not a guarantee that an upstream quote was never delayed.

For entry `E`, stop `S`, target `T` and combined per-side fee/slippage rate `c = 0.001 + 0.0005`:

```text
loss_per_unit   = abs(E - S) + (E + S) * c
reward_per_unit = abs(T - E) - (E + T) * c
net_rr          = reward_per_unit / loss_per_unit
risk_budget     = equity * min(requested_risk_pct, 0.01)
auto_quantity   = floor_to_step(min(risk_budget / loss_per_unit,
                                   equity * 0.30 / E,
                                   available_margin * leverage / E))
```

Oversized explicit quantities and excessive requested risk are rejected, never silently approved after capping. Leverage changes margin, not the calculation of loss at the stop. Costs are illustrative conservative assumptions, not a representation of a specific Binance fee tier. Stop gaps, liquidity, funding, liquidation, partial fills, stop/target order placement, exits and mark-to-market P&L are **not** modeled. Actual losses are not bounded by these estimates.

The illustrative strategy uses SMA8/SMA21 separation greater than 0.3%, slow-SMA slope and the last closed price relative to SMA8. Stop distance is the larger of 1.5×ATR14 or 1.2% of price. Target distance is 3.5×stop distance before tick rounding. There is no trained prediction model, optimized backtest or profitability claim.

## Audit and duplicate protection

- Full market snapshots, policy hash/version, proposal, checks, portfolio before/after, decision and execution outcome are logged.
- SQLite `BEGIN IMMEDIATE` commits paper fill, exposure, result and audit events atomically. Audit-write failure rolls back the fill.
- A request ID is persistent across restarts. Reusing it returns the stored result; changing its inputs returns `IDEMPOTENCY_CONFLICT`.
- A second request ID for an identical proposal on the same closed candle is blocked as `DUPLICATE_ACTION` within the paper session.
- Each audit event hashes its exact payload, sequence and previous hash. Startup and transactions verify the chain.
- New paper sessions retain previous positions and events; they do not claim realized P&L or settlement.
- Hashes detect accidental or partial changes. There is no external anchor: someone controlling files can rewrite a whole chain, truncate its tail, modify other tables or change code. This is **not tamper-proof storage**.
- Free-form prompts and raw rejected model text are not persisted. Never paste secrets into the demo.

## Reproduce the tests

```sh
python -m pip install -r requirements-dev.txt
python -m pytest -q
python -m compileall -q riskpilot tests scripts
```

Optional independent SDK and lint gates, in a project environment:

```sh
python -m pip install -r requirements-dev.txt
python -m ruff check .
python -m ruff format --check .
python scripts/verify_sdk.py
```

The SDK check starts a real subprocess and tests initialization, tool discovery, paper fill, rejection, retry and audit retrieval. It connects only to local RiskPilot. It does **not** prove Binance OAuth or a real LLM session. Saved results are in `evidence/`.

CLI examples:

```sh
python -m riskpilot analyze --scenario danger
python -m riskpilot analyze --scenario short
python -m riskpilot analyze --source binance_public --symbol ETHUSDT
python -m riskpilot audit
python -m riskpilot new-session
python -m riskpilot --db runtime/agent.sqlite3 mcp
```

Database arguments come **before** the subcommand. All runtime files are excluded from Git. The sample `.env.example` is a placeholder; this release reads no credentials and does not load `.env`. `RISKPILOT_MODE=LIVE` in the process environment is refused. There is no need to create a Binance API secret.

## Binance OAuth and human authorization

RiskPilot never asks for or reads an OAuth token. Configure the official endpoint and four-tool allowlist in a supported Codex client, then run `codex mcp login binance-mcp-server`. The participant must personally complete Binance login, OAuth consent and any 2FA. Keep optional account, trading, borrowing and transfer permissions disabled. Exact configuration and verification steps are in [agent/CONNECT.md](agent/CONNECT.md).

The participant must also personally confirm eligibility, publish the GitHub repository and video, post on X, and submit the Binance survey. Those public or account-bound actions are listed in [HUMAN_ACTION_REQUIRED.md](SUBMISSION/HUMAN_ACTION_REQUIRED.md).

## Project map

```text
riskpilot/        domain, market, strategy, risk, paper execution, audit, HTTP and MCP
riskpilot/static/ local HTML/CSS/JS demo
tests/            deterministic risk, data, concurrency, persistence, HTTP, MCP tests
agent/            host prompt, connection template and Agent OS handoff
scripts/          independent MCP SDK check and verification utilities
SUBMISSION/       English project copy, demo script, architecture and human checklist
evidence/         test logs, structured demo results, screenshots, integration status
START_DEMO.cmd    Windows launcher
```

## Open source and submission

Original implementation, MIT license. Runtime: Python standard library (including bundled SQLite) and browser standards; zero third-party runtime packages or copied trading projects. Optional QA dependencies: Ruff (MIT), official Python MCP SDK (MIT) and its dependencies. See [THIRD_PARTY.md](THIRD_PARTY.md). The project is independent and not endorsed by Binance.

Track A material is prepared under `SUBMISSION/`. Official entry requires the participant's own eligible account and public entry steps. The current source repository is local: no remote repository, X post, public demo video or contest submission has been created. Official rules and exact sources: [COMPETITION_RESEARCH.md](SUBMISSION/COMPETITION_RESEARCH.md).

## Limitations and disclaimer

RiskPilot is a hackathon prototype for local PAPER analysis. It does not model real fills, exits, liquidation, funding, slippage under stress, tax, custody or guaranteed stop execution. Market data and software can fail, and historical or simulated behavior does not predict future results.

This project is for technical demonstration and education. It is not financial advice, an offer to trade or a promise of profit. Use of Binance services remains subject to Binance terms, eligibility restrictions and the participant's own judgment.

TDQS

A4.2/5.0

Scored across 3 tools

Disambiguation5/5

Each tool has a distinct responsibility: policy reads immutable limits, analyze executes validated paper trades under guardrails, and audit verifies hash-linked events. There is no overlap or ambiguity between them.

Naming Consistency5/5

All tool names follow a consistent pattern of 'riskpilot_' prefix followed by a clear verb-like noun (policy, analyze, audit). The uniform lowercase and consistent structure make the set predictable.

Tool Count5/5

Three tools is well-scoped for a focused risk management and paper trading server. Each tool addresses a core function—reading policies, executing validated paper trades, and auditing—without unnecessary bloat or missing essentials.

Completeness4/5

The tool set covers the primary lifecycle: policy reading, trade analysis/execution with hard guardrails, and audit verification. It is missing optional capabilities like manual ledger management or limit updates, but these are intentionally immutable or out of scope, so no critical gaps exist.

Maintenance

ActivityMaintained
ResponsivenessNo issues