# AGENTS.md — AegisTrade AI Operational Directives & Security Policy

## Core Directives for Autonomous & Engineering Agents

All agents, subagents, and automated systems operating within or contributing to the **AegisTrade AI** codebase MUST adhere strictly to the following architectural, operational, and financial safety rules. Violations of these directives will invalidate any build, test, or proposed deployment.

---

### 1. Absolute Financial Safety & Risk Invariants (Non-Negotiable)

1. **Capital Preservation Above All**: The primary goal of AegisTrade AI is capital preservation and long-term positive expectancy. NO-TRADE is a valid, winning decision when expected edge after friction is negative or uncertain.
2. **Never Promise Profit**: Never claim guaranteed profits, unrealistic win rates, or zero-risk strategies in code, documentation, UI, or model outputs.
3. **No Martingale / No Averaging Down**: Martingale, grid recovery schemes, revenge trading, and increasing position sizes during drawdowns are strictly forbidden and barred in the execution logic.
4. **Independent Risk Engine**: The Risk Engine is strictly decoupled from and authoritative over the Signal & Prediction Engines. **An AI model can NEVER override a risk rejection.**
5. **No Stop-Loss Loosening**: Stops are fixed or trailing in a risk-reducing direction only. Stops can never be moved further away from the current market price to avoid realizing a loss.
6. **Small Account Protection Policy**:
   - Risk per position defaults to **0.25%** of equity (configurable up to max 1.0%).
   - Maximum simultaneous positions: **2**.
   - Maximum daily loss threshold: **1.0%** of starting-day equity.
   - Maximum portfolio drawdown: **5.0%** from peak equity.
   - Leverage: Locked to **1.0x** (No borrowed margin or high leverage).
   - If the exchange minimum notional or contract increment exceeds the calculated position risk budget, **THE TRADE MUST BE REJECTED**. Never inflate position size to satisfy minimums.

---

### 2. Operational Modes & Exchange Credentials Isolation

The system supports four distinct, strictly isolated operational modes:

| Mode | Identifier | Exchange Network | Execution Target | API Key Required |
| :--- | :--- | :--- | :--- | :--- |
| **BACKTEST** | `BACKTEST` | None (Local Fixtures/DB) | Simulated Ledger | No |
| **PAPER (Default)** | `PAPER` | Public Ticks/Candles only | Virtual Order Engine | No |
| **BYBIT_DEMO** | `BYBIT_DEMO` | Bybit Demo (`api-demo.bybit.com`) | Demo Unified Account | Demo API Keys Only |
| **LIVE** | `LIVE` | Bybit Mainnet | Live Unified Account | Live Subaccount Only |

#### Mandatory Mode Safeguards:
- **Default Mode**: Always starts in `PAPER` mode.
- **Live Trading Hard-Lock**: Live execution is disabled by default via `ENABLE_LIVE_TRADING=False`. Enabling live execution requires:
  1. Setting `ENABLE_LIVE_TRADING=true` in environment.
  2. Providing verified live subaccount API keys with read/trade permissions only (NO withdrawal permissions).
  3. Validating exchange endpoint is Bybit mainnet.
  4. Passing system pre-flight health checks and active risk limits.
  5. Explicit authenticated human approval token via the Dashboard/API.
- **Endpoint Segregation**:
  - Demo REST: `https://api-demo.bybit.com`
  - Demo Private WS: `wss://stream-demo.bybit.com/v5/private`
  - Mainnet REST: `https://api.bybit.com`
  - Demo and Live credentials must never be interchanged or stored together.

---

### 3. Machine Learning & Signal Engine Directives

1. **Zero Look-Ahead Information**:
   - Every feature must be causal—computed strictly using information available at or before the decision timestamp $t$.
   - Forward-looking rolling windows, future target leakage in feature normalization, and unembargoed time series splits are critical security bugs.
2. **Probability Calibration**:
   - Raw model scores cannot be treated as real probabilities.
   - Predictions must be calibrated using Platt scaling / Isotonic regression on validation data, evaluated via Brier score and reliability plots.
3. **Cost-Adjusted Expected Value (EV)**:
   - A trade signal is generated ONLY if:
     $$\mathbb{E}[\text{Return}] = P_{\text{win}} \times R_{\text{win}} - P_{\text{loss}} \times R_{\text{loss}} - \text{Friction} > \text{Minimum Hurdle}$$
   - Friction includes: Maker/Taker fees, bid-ask spread, estimated slippage, funding fees, and execution uncertainty buffer.
4. **Champion/Challenger Model Registry**:
   - Newly trained models are stored as *Challengers*.
   - Automatic promotion to production is strictly forbidden.
   - Promotion requires passing walk-forward validation against baseline benchmarks (Buy & Hold, EMA Trend, NO-TRADE) and deliberate administrator approval.

---

### 4. Emergency Kill Switch Specifications

1. The Kill Switch state must be **persisted to disk/database** across system restarts.
2. When triggered:
   - Immediately rejects any new order submissions.
   - Cancels all pending unfilled entry orders.
   - Position flattening is a distinct secondary action requiring explicit human confirmation.
   - Disables automatic reactivation until an authorized manual reset.
   - Emits high-priority alert events to all connected clients and notification channels.

---

### 5. Code Quality, Security, and Testing Standards

- **Precision**: Monetary, balance, and price calculations must use `Decimal` or rounded integer ticks/lots to avoid floating-point drift.
- **Secrets Management**: Never log, display, commit, or serialize API keys, secret keys, or authentication tokens. All sensitive data must be redacted in structured logs.
- **Auditing**: Every order must be immutably linked to its generating Signal ID, Model Version, Risk Check ID, and Client Order ID.
- **Test Coverage**: Critical paths (Risk checks, Kill Switch, Order lifecycle, Calibration, Look-ahead checks) must have automated tests with 100% verification pass rates.
