8000 GitHub - avmkmk/ATB: Algo bot trading for forex · GitHub
[go: up one dir, main page]

Skip to content
avmkmkPublic

About

Algo bot trading for forex

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MT5 Automated Scalping System

Status: 🟡 Core Foundation Complete - Strategies & Orchestration In Progress

Automated trading system with 5 independent scalping strategies running in parallel across Tokyo, London, and NY sessions. Trades EUR/USD and XAU/USD with fully automated execution, variable risk sizing, and 30-60 minute forced exits.


Implementation Status

✅ Phase 1: Core Infrastructure (COMPLETE)

  • ✅ mt5_connector.py - Enhanced MT5 connection with multi-timeframe fetching
  • ✅ risk_manager.py - Variable position sizing (A+/A/B grades), daily stop enforcement
  • ✅ session_manager.py - Tokyo/London/NY timing, dead zone filtering
  • ✅ trade_logger.py - JSON trade logging, performance summary generation
  • ✅ main_config.json - Master configuration with all strategy parameters

✅ Phase 2: ICT Detectors (PARTIALLY COMPLETE)

  • ✅ fvg_detector.py - Fair Value Gap 3-candle imbalance detection
  • ✅ order_block_detector.py - Institutional order block identification
  • ✅ structure_detector.py - 4H bias and 1H alignment checking
  • ⏳ volume_profile_detector.py - NEEDS IMPLEMENTATION (wrap existing VP code)
  • ⏳ liquidity_detector.py - NEEDS IMPLEMENTATION (swing level + wick rejection)

✅ Phase 3: Strategy Framework (PARTIALLY COMPLETE)

  • ✅ base_strategy.py - Abstract base class with common interface
  • ✅ strategy_2_fvg_fade.py - COMPLETE EXAMPLE (FVG imbalance trading)
  • ⏳ strategy_1_vp_retest.py - NEEDS IMPLEMENTATION (VP zone pullbacks)
  • ⏳ strategy_3_ob_bounce.py - NEEDS IMPLEMENTATION (Order Block entries)
  • ⏳ strategy_4_liq_sweep.py - NEEDS IMPLEMENTATION (Liquidity sweeps)
  • ⏳ strategy_5_ict_combined.py - NEEDS IMPLEMENTATION (Multi-concept)

⏳ Phase 4: Exit Logic (NOT STARTED)

  • ⏳ time_based_exit.py - Force close after max hold time
  • ⏳ target_based_exit.py - TP hit and break-even management
  • ⏳ trailing_stop.py - Optional momentum trailing

⏳ Phase 5: Orchestration (NOT STARTED)

  • ⏳ position_manager.py - Manage open positions, apply exit logic
  • ⏳ conflict_resolver.py - Prevent duplicate trades on same pair
  • ⏳ daily_monitor.py - Track P&L, enforce daily $200 stop
  • ⏳ strategy_orchestrator.py - Main controller (15-second scan loop)
  • ⏳ main.py - Entry point, startup sequence, crash recovery

⏳ Phase 6: Testing (NOT STARTED)

  • ⏳ test_detectors.py - Unit tests for ICT detectors
  • ⏳ test_strategy_2.py - Strategy signal generation tests
  • ⏳ 7-day paper trading validation

Quick Start (Once Complete)

Prerequisites

# Ensure MT5 terminal is running and logged in
# Verify leverage is set to 1:100 in MT5: Tools → Options → Trade → Leverage

# Install Python dependencies
pip install MetaTrader5 pandas numpy pytest

Running the Bot

cd "D:\Miscelaneous\Financials\Trading journal\Automated trading"

# Dry run (signals only, no execution)
python main.py --dry-run

# Live execution on demo account
python main.py

# Stop the bot: Ctrl+C

Configuration

Edit config/main_config.json to:

  • Enable/disable specific strategies
  • Adjust risk levels (grade_a_plus, grade_a, grade_b)
  • Change session hours
  • Modify max hold times per strategy

Architecture Overview

Automated trading/
├── core/                   # Reusable infrastructure
│   ├── mt5_connector.py   # MT5 connection, multi-timeframe data fetching
│   ├── risk_manager.py    # Position sizing, daily stop enforcement
│   ├── session_manager.py # Session timing (Tokyo/London/NY)
│   └── trade_logger.py    # JSON trade logging
│
├── detectors/              # ICT concept detection
│   ├── fvg_detector.py    # Fair Value Gaps (3-candle imbalance)
│   ├── order_block_detector.py  # Institutional entry zones
│   ├── structure_detector.py     # 4H bias, 1H alignment
│   ├── volume_profile_detector.py  # POC/VAH/VAL zones (TODO)
│   └── liquidity_detector.py       # Stop hunts (TODO)
│
├── strategies/             # 5 independent trading strategies
│   ├── base_strategy.py   # Abstract base class
│   ├── strategy_2_fvg_fade.py  # COMPLETE EXAMPLE
│   ├── strategy_1_vp_retest.py  # TODO
│   ├── strategy_3_ob_bounce.py  # TODO
│   ├── strategy_4_liq_sweep.py  # TODO
│   └── strategy_5_ict_combined.py  # TODO
│
├── exits/                  # Fast exit logic (30-60 min)
│   ├── time_based_exit.py # Force close after max hold (TODO)
│   ├── target_based_exit.py  # TP/BE management (TODO)
│   └── trailing_stop.py   # Momentum trailing (TODO)
│
├── orchestrator/           # Main bot controller
│   ├── strategy_orchestrator.py  # Runs all 5 strategies (TODO)
│   ├── conflict_resolver.py      # Prevents duplicates (TODO)
│   └── daily_monitor.py          # P&L tracking, daily stop (TODO)
│
├── config/
│   └── main_config.json   # Master configuration
│
├── logs/                   # Trade logs and bot activity
│   └── trades_YYYY-MM-DD.json
│
├── tests/                  # Unit and integration tests
│   └── test_detectors.py  # TODO
│
└── main.py                 # Entry point (TODO)

What's Working Right Now

Core Infrastructure

All core modules are fully functional:

  • MT5 connector can fetch multi-timeframe data
  • Risk manager calculates lot sizes based on grades
  • Session manager knows when to trade
  • Trade logger writes to JSON files

Detectors

  • FVG Detector: Detects 3-candle Fair Value Gaps on any timeframe
  • Order Block Detector: Identifies last candle before impulse moves
  • Structure Detector: Checks 4H bias and 1H alignment

Strategy Example

  • Strategy 2 (FVG Fade): Complete implementation showing:
    • How to use MT5 connector for multi-timeframe data
    • How to use FVG detector
    • How to grade setups (A+/A/B)
    • How to calculate entry/SL/TP

What Needs to Be Implemented

High Priority (Required for Bot to Run)

  1. Orchestrator Components

    • orchestrator/strategy_orchestrator.py - Main controller that runs scan loop
    • orchestrator/conflict_resolver.py - Prevents duplicate trades
    • orchestrator/daily_monitor.py - Tracks P&L, enforces daily stop
    • core/position_manager.py - Manages open positions, applies exit logic
  2. Exit Logic

    • exits/time_based_exit.py - Force close after 30/45/60/90 minutes
    • exits/target_based_exit.py - TP hit and break-even management
    • exits/trailing_stop.py - Optional momentum trailing (Strategies 1, 3, 5)
  3. Main Entry Point

    • main.py - Startup sequence, recovery logic, main loop

Medium Priority (Complete 5-Strategy System)

  1. Remaining Detectors

    • detectors/volume_profile_detector.py - Wrap scripts/analysis-tools/volume_profile.py
    • detectors/liquidity_detector.py - Swing level + wick rejection detection
  2. Remaining Strategies

    • strategies/strategy_1_vp_retest.py - VP zone pullbacks (use Strategy 2 as template)
    • strategies/strategy_3_ob_bounce.py - Order Block entries (use Order Block detector)
    • strategies/strategy_4_liq_sweep.py - Liquidity sweep reversals
    • strategies/strategy_5_ict_combined.py - Multi-concept high-probability

Low Priority (Testing & Validation)

  1. Unit Tests

    • tests/test_detectors.py - Test FVG, OB, liquidity detection accuracy
    • tests/test_strategy_2.py - Test Strategy 2 signal generation
    • tests/test_orchestrator.py - Integration tests
  2. 7-Day Paper Trading

    • Run on demo account for 7 consecutive days
    • Analyze performance (win rate, hold times, P&L per strategy)
    • Adjust parameters if needed

Implementation Guide

How to Implement Remaining Strategies

Use Strategy 2 (FVG Fade) as your template. All strategies follow the same pattern:

  1. Inherit from BaseStrategy

    from .base_strategy import BaseStrategy
    
    class Strategy1_VPRetest(BaseStrategy):
        def __init__(self, mt5_connector, config):
            super().__init__("strategy_1_vp_retest", mt5_connector, config)
            # Initialize detectors
  2. Implement scan_for_setups()

    • Get multi-timeframe data: data = self.mt5.get_multiple_timeframes(symbol, ["D1", "H4", "M15"], count=100)
    • Use detectors to find setups
    • Check confirmation candles
    • Return list of signal dicts
  3. Implement grade_setup()

    • A+: All timeframes aligned + ICT concept
    • A: Good alignment
    • B: Marginal setup
  4. Implement calculate_entry_sl_tp()

    • Entry: Current ask/bid
    • SL: Below/above zone + buffer
    • TP: Based on R:R target (1:1.5 to 1:2.5)

How to Implement Orchestrator

The orchestrator runs the main loop:

class StrategyOrchestrator:
    def __init__(self, config):
        self.mt5 = MT5Connector()
        self.mt5.initialize()

        # Initialize all 5 strategies
        self.strategies = [
            Strategy1_VPRetest(self.mt5, config['strategies']['strategy_1_vp_retest']),
            Strategy2_FVGFade(self.mt5, config['strategies']['strategy_2_fvg_fade']),
            # ... etc
        ]

        self.conflict_resolver = ConflictResolver()
        self.daily_monitor = DailyMonitor()
        self.position_manager = PositionManager(self.mt5)
        self.risk_manager = RiskManager()

    def run(self):
        while True:
            # 1. Check if in trading hours
            if not session_manager.is_trading_hours():
                time.sleep(60)
                continue

            # 2. Check daily stop
            if daily_monitor.is_daily_stop_hit():
                time.sleep(60)
                continue

            # 3. Scan all strategies for signals
            all_signals = []
            for strategy in self.strategies:
                if strategy.enabled:
                    signals = strategy.scan_for_setups()
                    all_signals.extend(signals)

            # 4. Resolve conflicts (max 1 trade per pair)
            filtered_signals = self.conflict_resolver.filter(all_signals)

            # 5. Execute trades
            for signal in filtered_signals:
                self.execute_trade(signal)

            # 6. Manage open positions (BE moves, time exits)
            self.position_manager.manage_open_positions()

            # 7. Sleep before next scan
            time.sleep(15)  # Scan every 15 seconds

Testing Before 7-Day Paper Trading

Unit Tests

# Test detectors
pytest tests/test_detectors.py -v

# Test strategy signal generation
pytest tests/test_strategy_2.py -v

Dry Run

# Run orchestrator in logging-only mode (no execution)
python main.py --dry-run

# Expected: Bot scans every 15 seconds, generates signals, logs decisions
# No actual trades executed

Manual Testing

# Test individual components
from core.mt5_connector import MT5Connector
from detectors.fvg_detector import FVGDetector
from strategies.strategy_2_fvg_fade import Strategy2_FVGFade

mt5 = MT5Connector()
mt5.initialize()

# Test FVG detection
detector = FVGDetector()
data = mt5.get_candles("EURUSD", "M15", count=100)
fvgs = detector.detect(data, "EURUSD", 1.0850)
print(f"Found {len(fvgs)} FVGs")

# Test strategy
strategy = Strategy2_FVGFade(mt5, {...})
signals = strategy.scan_for_setups()
print(f"Generated {len(signals)} signals")

Configuration Examples

Conservative Settings (Learning Mode)

{
  "risk": {
    "grade_a_plus": 50,   // 0.5% risk even for A+
    "grade_a": 25,        // 0.25% for A
    "grade_b": 10         // 0.1% for B
  },
  "trading": {
    "max_trades_per_day": 4,  // Limit trades while learning
    "daily_loss_limit": 100   // Tighter daily stop
  }
}

Aggressive Settings (After Validation)

{
  "risk": {
    "grade_a_plus": 150,  // 1.5% risk for A+
    "grade_a": 75,        // 0.75% for A
    "grade_b": 25         // 0.25% for B
  },
  "trading": {
    "max_trades_per_day": 12,
    "daily_loss_limit": 300
  }
}

7-Day Paper Trading Checklist

Before starting:

  • All 5 strategies implemented and tested
  • Orchestrator complete and tested
  • Exit logic modules implemented
  • Unit tests passing
  • Dry run successful (24 hours, no crashes)
  • MT5 demo account ready (NOT FundingPips account)
  • Leverage verified at 1:100

During 7 days:

  • Bot runs 24/7 without crashes
  • Daily review: logs/trades_YYYY-MM-DD.json
  • Monitor hold times (should be ≤ 60 min average)
  • Check no daily loss > $200

Success criteria:

  • ≥10 total trades executed
  • Win rate ≥ 50%
  • Average hold time ≤ 60 minutes
  • No daily loss > $200
  • Bot uptime > 95%

Next Steps

  1. Implement High-Priority Components (Days 1-5)

    • Orchestrator (strategy_orchestrator.py, conflict_resolver.py, daily_monitor.py)
    • Position manager (position_manager.py)
    • Exit logic (time_based_exit.py, target_based_exit.py)
    • Main entry point (main.py)
  2. Implement Remaining Strategies (Days 6-8)

    • Strategy 1 (VP Retest) - Use Strategy 2 as template
    • Strategy 3 (OB Bounce) - Use Order Block detector
    • Strategy 4 (Liq Sweep) - Need liquidity detector first
    • Strategy 5 (ICT Combined) - Combine all detectors
  3. Testing (Days 9-11)

    • Unit tests for all detectors
    • Strategy signal generation tests
    • Integration tests for orchestrator
    • Dry run for 24 hours
  4. 7-Day Paper Trading (Days 12-18)

    • Enable live execution on demo account
    • Daily monitoring and log review
    • Parameter adjustments if needed
  5. Production Readiness (Days 19-21)

    • Analyze 7-day results
    • Final parameter tuning
    • Decision: Deploy or iterate

Troubleshooting

Bot Won't Start

  • Check MT5 terminal is running and logged in
  • Verify config/main_config.json is valid JSON
  • Check logs/bot_activity.log for errors

No Signals Generated

  • Check session_manager.is_trading_hours() returns True
  • Verify pairs are trading (not weekend)
  • Check detector parameters in config (may be too strict)

Trades Not Executing

  • Check if dry_run mode is enabled in config
  • Verify MT5 account has sufficient margin
  • Check logs for order rejection errors

Daily Stop Hit Too Quickly

  • Review trade sizing (may be too aggressive)
  • Check strategy grades (may be too many B setups)
  • Analyze trade_log for losing patterns

Support & Resources

  • Plan Document: C:\Users\User\.claude\plans\cached-inventing-blanket.md
  • Existing MT5 Code: scripts/mt5/vp_auto_trader.py (reference patterns)
  • Volume Profile Engine: scripts/analysis-tools/volume_profile.py (reuse for detector)
  • FundingPips Rules: FundingPips_PropFirm_Guide.md

Last Updated: 2026-06-03 Version: 0.1.0-alpha (Core Foundation)

About

Algo bot trading for forex

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0