Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

CapitalGuard

A risk-controlled trading dashboard for the Capital.com API with integrated market analysis, signal backtesting, and position sizing — all in one Streamlit application.

Warning: Trading CFDs and leveraged products involves significant risk of loss. Always test in demo mode first. This project is not financial advice.


What it does

CapitalGuard combines two tools into a single professional workflow:

  1. Market analysis — fetches historical data from Yahoo Finance, classifies the current market regime, generates rule-based signals, calculates ATR-based stop/take-profit levels, and backtests those signals historically.
  2. Risk-controlled execution — connects to the Capital.com API with multiple hard safety gates before any order is sent: kill switch, daily loss limit, drawdown limit, spread filter, and more.

The two sides are connected: the Analysis tab pre-fills the Manual Order tab with the symbol, direction, and ATR-calculated levels, so the workflow is Analyze → Size → Preview → Send without switching applications.


Features

Market Analysis (Yahoo Finance data)

  • Technical indicators: SMA 20/50, EMA 20, RSI 14, ATR 14, 20-day volatility
  • Market state classification: Uptrend, Downtrend, Ranging
  • Regime detection: Trending Up/Down, Volatile, Range Bound, Breakout, Breakdown
  • Support and resistance levels with price location label
  • Rule-based signals: Bullish trend, Bearish trend, Oversold rebound, Overbought risk, Neutral
  • Plain-English signal explanation generated from live stats
  • ATR-based stop-loss and take-profit for both long and short
  • Risk/reward ratio calculator
  • Position sizing from account balance and risk percentage
  • Signal backtesting: hit rate, average return, Sharpe ratio, max drawdown, win/loss ratio
  • Walk-forward out-of-sample evaluation (sequential date splits)
  • Monte Carlo simulation (1 000 resampled equity curves)
  • Watchlist scanner with composite score ranking
  • Portfolio correlation matrix and diversification score
  • Market data cache with manual clear control

Risk-Controlled Execution (Capital.com API)

  • Demo / live mode hard separation — four config flags required to go live
  • Pre-trade preview checks every risk gate before touching the API
  • Kill switch (file-based, survives restarts) with auto-activation on limit breach
  • Emergency close all open positions + instant kill switch activation
  • Hard limits enforced before every order:
    • Max daily loss (auto-activates kill switch on breach)
    • Max account drawdown % (auto-activates kill switch on breach)
    • Max trades per day
    • Max open positions
    • Max position size (absolute units)
    • Max position size as % of available balance (optional)
    • Max spread %
    • Stop-loss required
    • Take-profit required
    • Minimum deal size validation
    • Market must be TRADEABLE status
  • Full SQLite audit log: every order attempt including blocked ones
  • Risk event log: every kill switch activation and drawdown breach
  • Capital.com history: transactions and activity viewer
  • Performance dashboard: local logs + Capital.com history combined
  • Database backups with configurable retention
  • Reconnect button for session recovery without restarting Streamlit

Workflow Integration

  • Analysis tab calculates ATR-based levels from live Yahoo Finance data
  • "Pre-fill Order Form" button sends epic, direction, stop, and take-profit to the Manual Order tab
  • Manual Order tab shows a pre-fill banner and populates all fields automatically
  • Position sizing uses the live Capital.com available balance

Dashboard Tabs

Tab Description
Account Live Capital.com balance, drawdown %, risk snapshot
Analysis Full market analysis, regime, signal, risk calculator, backtest, Monte Carlo, order bridge
Scanner Composite-scored watchlist across multiple symbols
Portfolio Equal-weight correlation matrix and diversification analysis
Market Search Find Capital.com epics by keyword
Open Positions Live positions, single close, emergency close all
Manual Order Preview → confirm → send with analysis pre-fill support
Trade Logs Every order attempt with status, deal ID, and raw API response
Risk Events Kill switch activations, drawdown and loss limit breaches
History Capital.com transactions and activity log
Performance Charts of local logs and Capital.com history combined

Tech Stack

Layer Library
Dashboard Streamlit
Capital.com API Requests
Market data yfinance (Yahoo Finance)
Charts Plotly
Data wrangling Pandas
Trade database SQLite + SQLAlchemy
Configuration Pydantic Settings

Quickstart

git clone <your-repo-url>
cd capitalguard
python -m venv venv
source venv/bin/activate      # Windows: venv\Scripts\activate
pip install -r requirements.txt
cp .env.example .env
# edit .env with your Capital.com API key
python init_db.py
streamlit run dashboard.py

Configuration

All settings live in .env. Copy .env.example to get started.

Capital.com connection

CAPITAL_MODE=DEMO                   # DEMO or LIVE
CAPITAL_API_KEY=your_api_key
CAPITAL_IDENTIFIER=your_email
CAPITAL_PASSWORD=your_api_password

Safety flags (all must be set to trade live)

LIVE_TRADING_ENABLED=false          # set true only after demo testing
ENABLE_ORDER_EXECUTION=false        # set true to allow orders
I_UNDERSTAND_TRADING_RISK=no        # set yes to unlock Send Order button

Risk limits

MAX_DAILY_LOSS=25                   # max realized loss per day before kill switch
MAX_TRADES_PER_DAY=3
MAX_OPEN_POSITIONS=1
MAX_POSITION_SIZE=1.0               # max size in units
MAX_POSITION_SIZE_PCT=0             # max size as % of available balance (0 = disabled)
MAX_SPREAD_PERCENT=1.0              # block orders when spread exceeds this
MAX_ACCOUNT_DRAWDOWN_PERCENT=5.0    # kill switch threshold
REQUIRE_STOP_LOSS=true
REQUIRE_TAKE_PROFIT=true

Checklist to go live

  1. Test all features thoroughly in CAPITAL_MODE=DEMO
  2. Set conservative risk limits for your account size
  3. Set MAX_POSITION_SIZE_PCT to cap each trade (e.g. 2 = max 2% of available balance)
  4. Set CAPITAL_MODE=LIVE
  5. Set LIVE_TRADING_ENABLED=true
  6. Set ENABLE_ORDER_EXECUTION=true
  7. Set I_UNDERSTAND_TRADING_RISK=yes
  8. Restart Streamlit and verify the sidebar shows LIVE MODE ACTIVE in red

Recommended Workflow

1. Analysis tab
   └── Enter Yahoo Finance symbol (e.g. BTC-USD)
   └── Click Analyze → review regime, signal, RSI, S/R levels
   └── Review ATR-based stop and take-profit levels
   └── Check historical hit rate and Sharpe in Backtest section
   └── Set position size using risk % of your account balance

2. Market Search tab
   └── Search the Capital.com epic (e.g. "bitcoin")
   └── Copy the epic string (e.g. BITCOIN)

3. Analysis tab → Send to Order Form
   └── Paste the Capital.com epic
   └── Click "Pre-fill Order Form"

4. Manual Order tab
   └── Confirm pre-filled epic, direction, stop, take-profit
   └── Adjust size to match your position sizing output
   └── Click Preview Order → review all risk checks
   └── Tick confirmation checkbox → click Send Order

Project Structure

capitalguard/
├── analysis/                   ← market analysis engine (Yahoo Finance)
│   ├── config.py               ← indicator and regime constants
│   ├── indicators.py           ← SMA, EMA, RSI, ATR, volatility
│   ├── market_state.py         ← trend, momentum, volatility classification
│   ├── regime.py               ← regime detection (trending, volatile, breakout...)
│   ├── signals.py              ← rule-based signal generation
│   ├── structure.py            ← support and resistance levels
│   ├── risk_calc.py            ← ATR stops, R:R ratio, position sizing
│   ├── confidence.py           ← sample confidence labelling
│   ├── explanations.py         ← plain-English signal narrative
│   ├── charts.py               ← candlestick, RSI, equity curve charts
│   ├── scanner.py              ← watchlist composite scoring
│   └── portfolio.py            ← correlation and diversification analysis
│
├── backtesting/                ← statistical testing
│   ├── engine.py               ← signal backtest, Sharpe, max drawdown, trade log
│   ├── walk_forward.py         ← out-of-sample date-split evaluation
│   └── monte_carlo.py          ← 1 000-simulation equity curve resampling
│
├── app/                        ← Capital.com trading engine
│   ├── capital_client.py       ← API client with session management
│   ├── config.py               ← Pydantic settings from .env
│   ├── trading_service.py      ← preview and execution orchestration
│   ├── risk_manager.py         ← kill switch, daily loss, position limits
│   ├── account_guard.py        ← balance and drawdown validation
│   ├── market_guard.py         ← spread, size, stop/profit level validation
│   ├── models.py               ← SQLAlchemy ORM models
│   ├── repository.py           ← trade log and risk event queries
│   ├── database.py             ← SQLite engine setup
│   └── maintenance.py          ← database integrity utilities
│
├── data/
│   ├── providers.py            ← yfinance downloader with CSV cache
│   ├── capitalguard.db         ← SQLite trade and risk event database
│   └── market_cache/           ← cached Yahoo Finance CSV files
│
├── scripts/
│   ├── backup_db.py            ← database backup with retention policy
│   └── health_check.py         ← connectivity and kill switch check
│
├── backups/                    ← automated database backups
├── dashboard.py                ← Streamlit application entry point
├── init_db.py                  ← create database tables
├── requirements.txt
├── .env.example
└── README.md

Methodology Notes

  • Market state uses rule-based indicators only: moving averages, RSI, ATR, volatility, and recent price range.
  • Backtests find historical occurrences of the same signal and simulate a fixed holding-period or ATR-exit result.
  • Confidence labels reflect sample count only: low confidence below 10 trades, medium below 30.
  • Walk-forward testing is a sequential date split with fixed rules — it is not parameter optimization.
  • Monte Carlo resamples historical trade returns. It does not predict future prices.
  • Yahoo Finance data and Capital.com prices may differ due to data source differences and instrument specifications.

Scripts

# Database backup
python scripts/backup_db.py

# Health check (API connectivity + kill switch status)
python scripts/health_check.py

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages