Skip to content

A deterministic agent that evaluates trade execution discipline against a defined trading plan and market regime.

Notifications You must be signed in to change notification settings

QuantTradingOS/Execution-Discipline-Agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧭 Execution Discipline Agent (v1)

A deterministic agent that evaluates whether trades were executed according to a predefined trading plan β€” conditioned on the current market regime.

⚠️ Important: This agent measures process compliance, not PnL. Built to diagnose behavior, not generate signals.


πŸ“‹ Table of Contents


✨ Features

  • βœ… Rule-based evaluation β€” No AI/ML, deterministic compliance checking
  • πŸ“Š Regime-aware analysis β€” Validates trades against market regime constraints
  • πŸ›‘οΈ Stop-loss validation β€” Ensures stop-loss orders are properly set
  • πŸ’Ύ Persistent memory β€” Tracks compliance history over time
  • 🚫 No external APIs β€” Fully offline, no OpenAI or external dependencies
  • 🎯 Process-focused β€” Measures discipline, not performance

πŸš€ Installation

Prerequisites

  • Python 3.7+
  • pip

Setup

  1. Clone the repository

    git clone <repository-url>
    cd Execution-Discipline-Agent
  2. Install dependencies

    pip install -r requirements.txt
  3. Run the Streamlit app

    streamlit run app.py
  4. Open your browser

    • The app will automatically open at http://localhost:8501
    • If not, navigate to the URL shown in the terminal

🎯 Quick Start

  1. Prepare your files:

    • πŸ“„ Trades CSV β€” Your trade execution log (see format below)
    • πŸ“‹ Trading Plan JSON β€” Your trading rules (see format below)
  2. Launch the app:

    streamlit run app.py
  3. Upload files:

    • Upload your trades CSV file
    • Upload your trading plan JSON file
    • Enter the current market regime label (e.g., "Risk-On", "Risk-Off")
  4. View results:

    • Compliance score (0.0 to 1.0)
    • Regime mismatch rate
    • Detailed violation list

πŸ“₯ Input Formats

πŸ“„ Trades CSV Format

Your trades CSV must include the following columns:

Column Description Example Required
date Trade date 2025-08-01 βœ…
symbol Trading symbol SPY βœ…
side Trade direction LONG or SHORT βœ…
entry_price Entry price 530.00 βœ…
exit_price Exit price 535.00 βœ…
shares Number of shares 100 βœ…
stop_price Stop-loss price 525.00 ⚠️ (if stop_required: true)

Example:

date,symbol,side,entry_price,exit_price,shares,stop_price
2025-08-01,SPY,LONG,530,535,100,525
2025-08-02,QQQ,LONG,470,465,120,

πŸ“‹ Trading Plan JSON Format

Your trading plan JSON must include:

{
  "risk_per_trade_pct": 0.5,
  "max_position_pct": 10,
  "allowed_regimes": ["Risk-On", "Risk-Off"],
  "stop_required": true,
  "max_stop_pct": 2.0,
  "account_size": 100000,
  "position_limits_by_regime": {
    "Risk-On": 10,
    "Risk-Off": 3
  }
}

Required Fields:

  • allowed_regimes (array): List of market regimes where trading is allowed
  • stop_required (boolean): Whether stop-loss orders are mandatory

Optional Fields:

  • risk_per_trade_pct: Maximum risk per trade percentage
  • max_position_pct: Maximum position size percentage
  • max_stop_pct: Maximum stop-loss percentage
  • account_size (number): Total account size in dollars (required for position sizing checks)
  • position_limits_by_regime (object): Dictionary mapping regime names to maximum position size as percentage of account (e.g., {"Risk-On": 10} means max 10% of account per position in Risk-On regime)

Example:

{
  "risk_per_trade_pct": 0.5,
  "max_position_pct": 10,
  "allowed_regimes": ["Risk-On", "Risk-Off"],
  "stop_required": true,
  "max_stop_pct": 2.0,
  "account_size": 100000,
  "position_limits_by_regime": {
    "Risk-On": 10,
    "Risk-Off": 3
  }
}

Position Sizing Rule:

  • Position size is calculated as shares Γ— entry_price
  • If position_limits_by_regime and account_size are provided, the agent will check each trade against the regime-specific limit
  • Violations are flagged when position size exceeds the allowed percentage for the current regime

🏷️ Market Regime Label

Enter the current market regime as a text string. Common values:

  • Risk-On
  • Risk-Off
  • Neutral
  • Volatile

πŸ“€ Output

The agent generates a Discipline Report containing:

πŸ“Š Metrics

  • Compliance Score (0.0 - 1.0)

    • 1.0 = Perfect compliance (no violations)
    • 0.0 = Complete non-compliance
    • Calculated as: 1.0 - (violations / total_trades)
  • Regime Mismatch Rate (0.0 - 1.0)

    • Percentage of trades executed in non-allowed regimes

🚨 Violations

Each violation includes:

  • Trade Index: Which trade violated the rule
  • Violation Type:
    • Regime Mismatch β€” Trade executed in non-allowed regime
    • Missing Stop β€” Required stop-loss not provided
    • Oversized for Regime β€” Position size exceeds regime-specific limit
    • Early Exit β€” Exited trade with R < 0.5 (didn't let trade run to target)
    • Late Exit β€” Hit stop loss after trade likely had >= 1R unrealized gain (should have exited earlier)
  • Detail: Human-readable explanation

R-Multiple Calculation:

  • R-multiple measures trade performance relative to risk: R = (exit_price - entry_price) / (entry_price - stop_price)
  • Only calculated for trades with valid stop_price
  • Supports both LONG and SHORT positions

πŸ—οΈ Architecture

Execution-Discipline-Agent/
β”œβ”€β”€ app.py                 # Streamlit web interface
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ agent.py          # Main agent logic
β”‚   β”œβ”€β”€ rules.py          # Compliance rule checkers
β”‚   β”œβ”€β”€ schemas.py        # Data models
β”‚   └── memory.py         # Persistent state management
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ trades.example.csv    # Example trades file
β”‚   └── plan.example.json     # Example plan file
β”œβ”€β”€ state/
β”‚   └── memory.json       # Persistent compliance history
└── requirements.txt      # Python dependencies

πŸ” Key Components

  • ExecutionDisciplineAgent: Main agent class that orchestrates compliance checking
  • check_regime_allowed(): Validates trades against allowed regimes
  • check_missing_stops(): Ensures stop-loss orders are present when required
  • check_position_sizing(): Validates position sizes against regime-specific limits
  • check_r_multiple(): Calculates R-multiples and flags Early Exit and Late Exit violations
  • Memory System: Tracks compliance history in state/memory.json

πŸ’‘ Usage Examples

Example 1: Command Line Testing

import pandas as pd
import json
from src.agent import ExecutionDisciplineAgent

# Load data
trades = pd.read_csv("data/trades.example.csv")
plan = json.load(open("data/plan.example.json"))

# Run agent
agent = ExecutionDisciplineAgent()
report = agent.run(trades, plan, regime_label="Risk-Off")

# View results
print(f"Compliance Score: {report.compliance_score}")
for v in report.violations:
    print(f"Trade #{v.trade_index}: {v.violation_type} - {v.detail}")

Example 2: Web Interface

  1. Run streamlit run app.py
  2. Upload data/trades.example.csv
  3. Upload data/plan.example.json
  4. Enter regime: Risk-Off
  5. View the compliance report

πŸ”§ Troubleshooting

❌ File Upload 403 Error

If you see AxiosError: Request failed with status code 403:

  1. Restart Streamlit β€” Stop the server (Ctrl+C) and restart:

    streamlit run app.py
  2. Clear browser cache β€” Hard refresh: Cmd+Shift+R (Mac) or Ctrl+Shift+R (Windows)

  3. Check config β€” Ensure .streamlit/config.toml has enableXsrfProtection = false

❌ CSV Parsing Errors

  • Missing columns: Ensure your CSV has all required columns (see Input Formats)
  • Invalid data types: Check that prices and shares are numeric
  • Empty file: Ensure the CSV has at least one data row (not just headers)

❌ JSON Parsing Errors

  • Invalid JSON: Validate your JSON using a JSON validator
  • Missing fields: Ensure allowed_regimes is present in your plan
  • Wrong data types: allowed_regimes must be an array, stop_required must be boolean

❌ Memory File Errors

If you see errors about state/memory.json:

  • The file is created automatically on first run
  • Ensure the state/ directory exists or is writable
  • Delete state/memory.json to reset history

πŸ“ Notes

  • Offline Only: This agent does not connect to external APIs or services
  • Deterministic: Same inputs always produce the same outputs
  • Process Focus: Measures trading discipline, not profitability
  • Memory Persistence: Compliance history is saved to state/memory.json

πŸ“„ License

[Add your license information here]


🀝 Contributing

[Add contribution guidelines here]


Built to diagnose behavior, not generate signals. 🎯

Releases

No releases published

Packages

No packages published

Languages