From 0d25548ed54418acadc59ffaca61620b3ecea78f Mon Sep 17 00:00:00 2001 From: GifariKemal Date: Fri, 6 Feb 2026 13:22:46 +0700 Subject: [PATCH] refactor: restructure repository and add README, CLAUDE.md, LICENSE - Move utility scripts to scripts/ (check_market, check_positions, etc.) - Move test files to tests/ (test_modules, test_mt5_connection, etc.) - Move deprecated dashboards to archive/ - Move research files to docs/research/ - Add sys.path fix to all moved Python files - Rewrite README.md with architecture diagram and badges - Add CLAUDE.md project guide - Add MIT LICENSE - Update .gitignore with archive/ pattern Co-Authored-By: Claude Opus 4.6 --- .gitignore | 6 + CLAUDE.md | 124 +++++++++ LICENSE | 21 ++ README.md | 253 +++++++++++++----- .../comparison_report.xlsx | Bin .../create_comparison.py | 0 dashboard_gui.py => archive/dashboard_gui.py | 0 .../dashboard_modern.py | 0 dashboard_pro.py => archive/dashboard_pro.py | 0 .../start_dashboard.bat | 0 ...NALISA STRUKTUR DASAR RISK & KELEMAHAN.txt | 0 ... Algoritmik 2026_ Arsitektur & Strategi.md | 0 .../Rancang Bangun Sistem Trading Otomatis.md | 0 .../research/comprehensive_news_test.py | 0 .../research/deep_news_analysis.py | 0 .../research/final_news_verification.py | 0 check_market.py => scripts/check_market.py | 4 + .../check_positions.py | 5 +- check_status.py => scripts/check_status.py | 5 +- .../close_positions.py | 5 +- .../get_trade_history.py | 5 +- modify_tp.py => scripts/modify_tp.py | 5 +- test_modules.py => tests/test_modules.py | 4 +- .../test_mt5_connection.py | 5 +- .../test_risk_settings.py | 4 + 25 files changed, 364 insertions(+), 82 deletions(-) create mode 100644 CLAUDE.md create mode 100644 LICENSE rename comparison_report.xlsx => archive/comparison_report.xlsx (100%) rename create_comparison.py => archive/create_comparison.py (100%) rename dashboard_gui.py => archive/dashboard_gui.py (100%) rename dashboard_modern.py => archive/dashboard_modern.py (100%) rename dashboard_pro.py => archive/dashboard_pro.py (100%) rename start_dashboard.bat => archive/start_dashboard.bat (100%) rename ANALISA STRUKTUR DASAR RISK & KELEMAHAN.txt => docs/research/ANALISA STRUKTUR DASAR RISK & KELEMAHAN.txt (100%) rename {Riset Gemini => docs/research/Riset Gemini}/Blueprint Sistem Trading Algoritmik 2026_ Arsitektur & Strategi.md (100%) rename {Riset Gemini => docs/research/Riset Gemini}/Rancang Bangun Sistem Trading Otomatis.md (100%) rename comprehensive_news_test.py => docs/research/comprehensive_news_test.py (100%) rename deep_news_analysis.py => docs/research/deep_news_analysis.py (100%) rename final_news_verification.py => docs/research/final_news_verification.py (100%) rename check_market.py => scripts/check_market.py (96%) rename check_positions.py => scripts/check_positions.py (91%) rename check_status.py => scripts/check_status.py (90%) rename close_positions.py => scripts/close_positions.py (91%) rename get_trade_history.py => scripts/get_trade_history.py (95%) rename modify_tp.py => scripts/modify_tp.py (92%) rename test_modules.py => tests/test_modules.py (98%) rename test_mt5_connection.py => tests/test_mt5_connection.py (95%) rename test_risk_settings.py => tests/test_risk_settings.py (76%) diff --git a/.gitignore b/.gitignore index 9af82a6..69521c1 100644 --- a/.gitignore +++ b/.gitignore @@ -78,3 +78,9 @@ desktop.ini # Docker docker/data/ + +# Archive +archive/ + +# Junk +nul diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..8093c2d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,124 @@ +# CLAUDE.md — XAUBot AI + +## Project Overview + +XAUBot AI is an automated XAUUSD (Gold) trading bot that combines Machine Learning (XGBoost), Smart Money Concepts (SMC), and Hidden Markov Model (HMM) regime detection. It runs on MetaTrader 5 via an async Python loop, executing trades on M15 candles. + +## Directory Structure + +``` +. +├── main_live.py # Main async trading orchestrator +├── train_models.py # Model training script +├── src/ # Core modules +│ ├── config.py # Trading configuration & capital modes +│ ├── mt5_connector.py # MetaTrader 5 connection layer +│ ├── smc_polars.py # Smart Money Concepts (Polars-based) +│ ├── ml_model.py # XGBoost trading model +│ ├── feature_eng.py # Feature engineering (37 features) +│ ├── regime_detector.py # HMM market regime detection +│ ├── risk_engine.py # Risk calculations & validation +│ ├── smart_risk_manager.py # Dynamic risk management +│ ├── session_filter.py # Trading session filter (Sydney/London/NY) +│ ├── position_manager.py # Open position management +│ ├── dynamic_confidence.py # Adaptive confidence thresholds +│ ├── auto_trainer.py # Auto-retraining pipeline +│ ├── news_agent.py # Economic news filtering +│ ├── telegram_notifier.py # Telegram alerts +│ ├── trade_logger.py # Trade logging to DB +│ ├── utils.py # Utility functions +│ └── db/ # Database schemas +├── backtests/ # Backtesting scripts +│ ├── backtest_live_sync.py # Main backtest (synced with live logic) +│ └── archive/ # Old backtest versions +├── scripts/ # Utility scripts +│ ├── check_market.py # Quick SMC market analysis +│ ├── check_positions.py # View open positions +│ ├── check_status.py # Account status check +│ ├── close_positions.py # Close all positions +│ ├── modify_tp.py # Modify take-profit levels +│ └── get_trade_history.py # Pull trade history from MT5 +├── tests/ # Test scripts +│ ├── test_modules.py # Module integration tests +│ ├── test_mt5_connection.py# MT5 connection test +│ └── test_risk_settings.py # Risk settings test +├── models/ # Trained models (.pkl) +├── data/ # Market data & trade logs +├── docs/ # Documentation +│ ├── arsitektur-ai/ # Architecture docs (23 components) +│ └── research/ # Research & analysis files +├── web-dashboard/ # Next.js monitoring dashboard +├── docker/ # Docker configuration +└── logs/ # Runtime logs +``` + +## Key Commands + +```bash +# Run the live trading bot +python main_live.py + +# Train/retrain ML models +python train_models.py + +# Run backtest with threshold tuning +python backtests/backtest_live_sync.py --tune + +# Run backtest with specific threshold +python backtests/backtest_live_sync.py --threshold 0.50 --save + +# Run module tests +python tests/test_modules.py + +# Check market status +python scripts/check_market.py +``` + +## Architecture + +The bot runs an **async candle-based loop** on M15 timeframe: + +1. **Data Fetch** — Pull OHLCV from MT5, convert to Polars DataFrame +2. **Feature Engineering** — Calculate 37 technical features (RSI, ATR, MACD, Bollinger, etc.) +3. **SMC Analysis** — Detect Order Blocks, Fair Value Gaps, BOS, CHoCH +4. **Regime Detection** — HMM classifies market as trending/ranging/volatile +5. **ML Prediction** — XGBoost outputs BUY/SELL/HOLD with confidence score +6. **Entry Filtering** — 11 entry filters must pass (session, regime, spread, cooldown, etc.) +7. **Risk Sizing** — ATR-based SL, dynamic position sizing, Kelly criterion +8. **Trade Execution** — Send order to MT5 with broker-level SL/TP +9. **Position Management** — 10 exit conditions (trailing SL, time exit, regime change, etc.) +10. **Logging** — Trade logged to PostgreSQL + Telegram notification + +## Tech Stack + +- **Python 3.11+** — Main runtime +- **Polars** — Data engine (not Pandas) +- **XGBoost** — ML model for signal prediction +- **hmmlearn** — Hidden Markov Model for regime detection +- **MetaTrader5** — Broker connection +- **asyncio + aiohttp** — Async execution & HTTP +- **loguru** — Structured logging +- **PostgreSQL** — Trade database +- **Next.js** — Web dashboard (optional) + +## Configuration + +All secrets in `.env`: +- `MT5_LOGIN`, `MT5_PASSWORD`, `MT5_SERVER`, `MT5_PATH` — Broker credentials +- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID` — Notifications +- `CAPITAL` — Trading capital +- `SYMBOL` — Default: XAUUSD + +Capital modes auto-configure risk parameters: +- **MICRO** (<$500): 2% risk/trade +- **SMALL** ($500-$10k): 1.5% risk/trade +- **MEDIUM** ($10k-$100k): 0.5% risk/trade +- **LARGE** (>$100k): 0.25% risk/trade + +## Important Notes + +- All data processing uses **Polars**, not Pandas +- The bot targets **< 50ms per loop** iteration +- Models are stored as `.pkl` files in `models/` +- Backtest logic is **synced with live** (`backtest_live_sync.py` mirrors `main_live.py`) +- Scripts in `scripts/` and `tests/` include `sys.path` fix so they work from any directory diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b849415 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025-2026 Gifari Kemal + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index d57dad1..2b95f5b 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,112 @@ -# Smart Automatic Trading BOT + AI +# XAUBot AI -An intelligent automated trading system for XAUUSD (Gold) using Machine Learning and Smart Money Concepts (SMC). +**AI-powered XAUUSD (Gold) trading bot** with XGBoost ML, Smart Money Concepts (SMC), and HMM regime detection for MetaTrader 5. + +[![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/) +[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) +[![MetaTrader 5](https://img.shields.io/badge/broker-MetaTrader%205-orange.svg)](https://www.metatrader5.com/) + +--- ## Features -- **ML-Powered Predictions**: XGBoost model with 37 features for market direction prediction -- **Smart Money Concepts (SMC)**: Order Blocks, Fair Value Gaps, Break of Structure, Change of Character -- **HMM Regime Detection**: Hidden Markov Model for market regime classification -- **Dynamic Risk Management**: ATR-based stop loss, position sizing, and smart exits -- **Session-Aware Trading**: Optimized for different market sessions (Sydney, London, NY) -- **Auto-Retraining**: Models automatically retrain based on market conditions -- **Telegram Notifications**: Real-time trade alerts and market updates -- **Web Dashboard**: Real-time monitoring interface +| Feature | Description | +|---------|-------------| +| **XGBoost ML Model** | 37-feature model predicting BUY/SELL/HOLD with calibrated confidence | +| **Smart Money Concepts** | Order Blocks, Fair Value Gaps, Break of Structure, Change of Character | +| **HMM Regime Detection** | 3-state Hidden Markov Model classifying trending/ranging/volatile markets | +| **Dynamic Risk Management** | ATR-based stop loss, Kelly criterion sizing, daily loss limits | +| **Session-Aware Trading** | Optimized for Sydney, London, and New York sessions | +| **Auto-Retraining** | Models automatically retrain when market conditions shift | +| **Telegram Alerts** | Real-time trade notifications and daily summaries | +| **Web Dashboard** | Next.js monitoring interface for live tracking | -## Performance (Backtest Jan 2025 - Feb 2026) +## Architecture + +``` + ┌─────────────────┐ + │ MetaTrader 5 │ + │ (XAUUSD M15) │ + └────────┬─────────┘ + │ OHLCV + ┌────────▼─────────┐ + │ Data Pipeline │ + │ (Polars Engine) │ + └────────┬─────────┘ + │ + ┌─────────────────┼─────────────────┐ + │ │ │ + ┌────────▼───────┐ ┌──────▼───────┐ ┌───────▼──────┐ + │ SMC Analyzer │ │ Feature Eng │ │ HMM Regime │ + │ (OB/FVG/BOS) │ │ (37 features) │ │ Detector │ + └────────┬───────┘ └──────┬───────┘ └───────┬──────┘ + │ │ │ + └─────────────────┼─────────────────┘ + │ + ┌────────▼─────────┐ + │ XGBoost Model │ + │ (Signal + Conf) │ + └────────┬─────────┘ + │ + ┌─────────────────┼─────────────────┐ + │ │ │ + ┌────────▼───────┐ ┌──────▼───────┐ ┌───────▼──────┐ + │ 11 Entry │ │ Risk Engine │ │ Position │ + │ Filters │ │ (ATR + Kelly)│ │ Manager │ + └────────┬───────┘ └──────┬───────┘ └───────┬──────┘ + │ │ │ + └────────────────┼──────────────────┘ + │ + ┌────────▼─────────┐ + │ Trade Execution │ + │ (MT5 + Logging) │ + └───────────────────┘ +``` + +## Project Structure + +``` +xaubot-ai/ +├── main_live.py # Main async trading orchestrator +├── train_models.py # Model training script +├── src/ # Core modules +│ ├── config.py # Trading configuration & capital modes +│ ├── mt5_connector.py # MetaTrader 5 connection layer +│ ├── smc_polars.py # Smart Money Concepts analyzer +│ ├── ml_model.py # XGBoost trading model +│ ├── feature_eng.py # Feature engineering (37 features) +│ ├── regime_detector.py # HMM market regime detection +│ ├── risk_engine.py # Risk calculations & validation +│ ├── smart_risk_manager.py # Dynamic risk management +│ ├── session_filter.py # Session filter (Sydney/London/NY) +│ ├── position_manager.py # Open position management +│ ├── dynamic_confidence.py # Adaptive confidence thresholds +│ ├── auto_trainer.py # Auto-retraining pipeline +│ ├── news_agent.py # Economic news filtering +│ ├── telegram_notifier.py # Telegram alerts +│ ├── trade_logger.py # Trade logging to DB +│ └── utils.py # Utility functions +├── backtests/ # Backtesting +│ ├── backtest_live_sync.py # Main backtest (synced with live) +│ └── archive/ # Historical versions +├── scripts/ # Utility scripts +│ ├── check_market.py # Quick SMC market analysis +│ ├── check_positions.py # View open positions +│ ├── check_status.py # Account status check +│ ├── close_positions.py # Emergency close all +│ ├── modify_tp.py # Modify take-profit levels +│ └── get_trade_history.py # Pull trade history +├── tests/ # Tests +├── models/ # Trained models (.pkl) +├── data/ # Market data & trade logs +├── docs/ # Documentation +│ ├── arsitektur-ai/ # Architecture docs (23 components) +│ └── research/ # Research & analysis +├── web-dashboard/ # Next.js monitoring dashboard +└── docker/ # Docker configuration +``` + +## Backtest Results (Jan 2025 - Feb 2026) | Metric | Value | |--------|-------| @@ -24,80 +117,92 @@ An intelligent automated trading system for XAUUSD (Gold) using Machine Learning | Max Drawdown | 2.2% | | Sharpe Ratio | 4.83 | -## Architecture +## Installation +### Prerequisites + +- Python 3.11+ +- MetaTrader 5 terminal (Windows) +- PostgreSQL (optional, for trade logging) + +### Setup + +```bash +# Clone the repository +git clone https://github.com/GifariKemal/xaubot-ai.git +cd xaubot-ai + +# Install dependencies +pip install -r requirements.txt + +# Configure environment +cp .env.example .env +# Edit .env with your MT5 credentials and Telegram token ``` -├── main_live.py # Main trading orchestrator -├── src/ -│ ├── ml_model.py # XGBoost ML model -│ ├── smc_polars.py # Smart Money Concepts analyzer -│ ├── regime_detector.py # HMM market regime detection -│ ├── smart_risk_manager.py # Risk management system -│ ├── feature_eng.py # Feature engineering -│ ├── mt5_connector.py # MetaTrader 5 connection -│ ├── session_filter.py # Trading session management -│ └── ... -├── backtests/ -│ ├── backtest_live_sync.py # Main backtest (synced with live) -│ └── archive/ # Historical backtest scripts -├── models/ # Trained ML models (.pkl) -├── data/ # Market data and trade logs -├── docs/ # Documentation -└── web-dashboard/ # Next.js monitoring dashboard + +### Configuration + +Key settings in `.env`: + +```env +# MetaTrader 5 +MT5_LOGIN=your_login +MT5_PASSWORD=your_password +MT5_SERVER=your_server +MT5_PATH=C:/Program Files/MetaTrader 5/terminal64.exe + +# Telegram Notifications +TELEGRAM_BOT_TOKEN=your_bot_token +TELEGRAM_CHAT_ID=your_chat_id + +# Trading +CAPITAL=5000 +SYMBOL=XAUUSD +``` + +### Run + +```bash +# Train models first +python train_models.py + +# Start the bot +python main_live.py + +# Run backtest +python backtests/backtest_live_sync.py --tune ``` ## Risk Management -- **ATR-Based Stop Loss**: Minimum 1.5 ATR distance -- **Broker-Level Protection**: Emergency SL at broker level -- **Time-Based Exit**: Max 6 hours per trade -- **Daily Loss Limit**: 5% of capital -- **Position Limit**: Max 2 concurrent positions +| Protection | Details | +|-----------|---------| +| **ATR-Based Stop Loss** | Minimum 1.5x ATR distance | +| **Broker-Level SL** | Emergency SL set at broker level | +| **Position Sizing** | Kelly criterion with capital mode scaling | +| **Daily Loss Limit** | 5% of capital per day | +| **Total Loss Limit** | 10% of capital | +| **Position Limit** | Max 2 concurrent positions | +| **Time-Based Exit** | Max 6 hours per trade | +| **Session Filter** | Only trades during active sessions | +| **Spread Filter** | Rejects trades during high spread | +| **Cooldown** | Minimum time between trades | -## Installation +## Tech Stack -1. Clone the repository -2. Install dependencies: - ```bash - pip install -r requirements.txt - ``` -3. Copy `.env.example` to `.env` and configure: - - MT5 credentials - - Telegram bot token - - Database connection -4. Train models: - ```bash - python train_models.py - ``` -5. Run the bot: - ```bash - python main_live.py - ``` - -## Configuration - -Key settings in `.env`: -- `MT5_LOGIN`, `MT5_PASSWORD`, `MT5_SERVER` - MetaTrader 5 credentials -- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID` - Telegram notifications -- `CAPITAL` - Trading capital amount -- `SYMBOL` - Trading symbol (default: XAUUSD) - -## Backtest - -Run backtest with threshold tuning: -```bash -python backtests/backtest_live_sync.py --tune -``` - -Run backtest with specific threshold: -```bash -python backtests/backtest_live_sync.py --threshold 0.50 --save -``` +- **Polars** — High-performance data engine (not Pandas) +- **XGBoost** — Gradient boosted ML model +- **hmmlearn** — Hidden Markov Model for regime detection +- **MetaTrader5** — Broker connection API +- **asyncio** — Async event loop for low-latency execution +- **loguru** — Structured logging +- **PostgreSQL** — Trade database +- **Next.js** — Web dashboard ## Disclaimer -This software is for educational purposes only. Trading involves substantial risk of loss. Past performance is not indicative of future results. Use at your own risk. +> This software is for **educational and research purposes only**. Trading foreign exchange (Forex) and commodities on margin carries a high level of risk and may not be suitable for all investors. Past performance is not indicative of future results. You could lose some or all of your investment. **Use at your own risk.** ## License -MIT License +[MIT License](LICENSE) - Copyright (c) 2025-2026 Gifari Kemal diff --git a/comparison_report.xlsx b/archive/comparison_report.xlsx similarity index 100% rename from comparison_report.xlsx rename to archive/comparison_report.xlsx diff --git a/create_comparison.py b/archive/create_comparison.py similarity index 100% rename from create_comparison.py rename to archive/create_comparison.py diff --git a/dashboard_gui.py b/archive/dashboard_gui.py similarity index 100% rename from dashboard_gui.py rename to archive/dashboard_gui.py diff --git a/dashboard_modern.py b/archive/dashboard_modern.py similarity index 100% rename from dashboard_modern.py rename to archive/dashboard_modern.py diff --git a/dashboard_pro.py b/archive/dashboard_pro.py similarity index 100% rename from dashboard_pro.py rename to archive/dashboard_pro.py diff --git a/start_dashboard.bat b/archive/start_dashboard.bat similarity index 100% rename from start_dashboard.bat rename to archive/start_dashboard.bat diff --git a/ANALISA STRUKTUR DASAR RISK & KELEMAHAN.txt b/docs/research/ANALISA STRUKTUR DASAR RISK & KELEMAHAN.txt similarity index 100% rename from ANALISA STRUKTUR DASAR RISK & KELEMAHAN.txt rename to docs/research/ANALISA STRUKTUR DASAR RISK & KELEMAHAN.txt diff --git a/Riset Gemini/Blueprint Sistem Trading Algoritmik 2026_ Arsitektur & Strategi.md b/docs/research/Riset Gemini/Blueprint Sistem Trading Algoritmik 2026_ Arsitektur & Strategi.md similarity index 100% rename from Riset Gemini/Blueprint Sistem Trading Algoritmik 2026_ Arsitektur & Strategi.md rename to docs/research/Riset Gemini/Blueprint Sistem Trading Algoritmik 2026_ Arsitektur & Strategi.md diff --git a/Riset Gemini/Rancang Bangun Sistem Trading Otomatis.md b/docs/research/Riset Gemini/Rancang Bangun Sistem Trading Otomatis.md similarity index 100% rename from Riset Gemini/Rancang Bangun Sistem Trading Otomatis.md rename to docs/research/Riset Gemini/Rancang Bangun Sistem Trading Otomatis.md diff --git a/comprehensive_news_test.py b/docs/research/comprehensive_news_test.py similarity index 100% rename from comprehensive_news_test.py rename to docs/research/comprehensive_news_test.py diff --git a/deep_news_analysis.py b/docs/research/deep_news_analysis.py similarity index 100% rename from deep_news_analysis.py rename to docs/research/deep_news_analysis.py diff --git a/final_news_verification.py b/docs/research/final_news_verification.py similarity index 100% rename from final_news_verification.py rename to docs/research/final_news_verification.py diff --git a/check_market.py b/scripts/check_market.py similarity index 96% rename from check_market.py rename to scripts/check_market.py index 23104e1..b625953 100644 --- a/check_market.py +++ b/scripts/check_market.py @@ -1,4 +1,8 @@ """Quick market analysis script""" +# Run from project root: python scripts/check_market.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + from dotenv import load_dotenv load_dotenv() diff --git a/check_positions.py b/scripts/check_positions.py similarity index 91% rename from check_positions.py rename to scripts/check_positions.py index c8595f8..18cf1d9 100644 --- a/check_positions.py +++ b/scripts/check_positions.py @@ -1,5 +1,8 @@ """Check open positions and account status.""" -import os +# Run from project root: python scripts/check_positions.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + from dotenv import load_dotenv load_dotenv() diff --git a/check_status.py b/scripts/check_status.py similarity index 90% rename from check_status.py rename to scripts/check_status.py index 1b6623e..8593c24 100644 --- a/check_status.py +++ b/scripts/check_status.py @@ -1,7 +1,10 @@ """Quick status check script.""" +# Run from project root: python scripts/check_status.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + import MetaTrader5 as mt5 from dotenv import load_dotenv -import os from datetime import datetime, timedelta load_dotenv() diff --git a/close_positions.py b/scripts/close_positions.py similarity index 91% rename from close_positions.py rename to scripts/close_positions.py index 08eedbe..3aeb4cb 100644 --- a/close_positions.py +++ b/scripts/close_positions.py @@ -1,5 +1,8 @@ """Close all open positions.""" -import os +# Run from project root: python scripts/close_positions.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + from dotenv import load_dotenv load_dotenv() diff --git a/get_trade_history.py b/scripts/get_trade_history.py similarity index 95% rename from get_trade_history.py rename to scripts/get_trade_history.py index 8c133b0..2aa5bb8 100644 --- a/get_trade_history.py +++ b/scripts/get_trade_history.py @@ -1,5 +1,8 @@ """Get real trading history from MT5.""" -import os +# Run from project root: python scripts/get_trade_history.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + from datetime import datetime, timedelta from dotenv import load_dotenv load_dotenv() diff --git a/modify_tp.py b/scripts/modify_tp.py similarity index 92% rename from modify_tp.py rename to scripts/modify_tp.py index 2159f6b..99b104b 100644 --- a/modify_tp.py +++ b/scripts/modify_tp.py @@ -1,5 +1,8 @@ """Modify TP of open positions to closer targets.""" -import os +# Run from project root: python scripts/modify_tp.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + from dotenv import load_dotenv load_dotenv() diff --git a/test_modules.py b/tests/test_modules.py similarity index 98% rename from test_modules.py rename to tests/test_modules.py index ade5563..731f4c4 100644 --- a/test_modules.py +++ b/tests/test_modules.py @@ -3,8 +3,10 @@ Module Test Script ================== Tests all modules to ensure they work correctly. """ +# Run from project root: python tests/test_modules.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -import sys import polars as pl import numpy as np from datetime import datetime, timedelta diff --git a/test_mt5_connection.py b/tests/test_mt5_connection.py similarity index 95% rename from test_mt5_connection.py rename to tests/test_mt5_connection.py index ee83e23..d3bc00f 100644 --- a/test_mt5_connection.py +++ b/tests/test_mt5_connection.py @@ -3,9 +3,10 @@ Test MT5 Connection =================== Quick test to verify MT5 connection and data retrieval. """ +# Run from project root: python tests/test_mt5_connection.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -import os -import sys from loguru import logger # Configure logging diff --git a/test_risk_settings.py b/tests/test_risk_settings.py similarity index 76% rename from test_risk_settings.py rename to tests/test_risk_settings.py index 0a613be..0170c2d 100644 --- a/test_risk_settings.py +++ b/tests/test_risk_settings.py @@ -1,4 +1,8 @@ """Test new risk settings.""" +# Run from project root: python tests/test_risk_settings.py +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + from src.smart_risk_manager import create_smart_risk_manager # Test dengan modal $50