Skip to content
Strings001Public

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

Forex Bot

A risk-first Python foundation for researching and paper-trading forex strategies.

Current status

The initial vertical slice includes:

  • typed candles, signals, and trades
  • validated paper/backtest/live configuration
  • moving-average crossover signals using closed candles
  • risk-based position sizing and drawdown protection
  • deterministic backtest primitives

Live trading is not implemented and is disabled by default. Backtest results are hypothetical and do not establish profitability.

Quick start

python -m venv .venv
. .venv/bin/activate
pip install -e ".[dev]"
pytest
forex-bot validate-config

Moon Trading Institute dashboard

Start the interactive research console with the bundled EUR/USD daily dataset:

forex-bot dashboard

Open http://127.0.0.1:8765 in a browser. The dashboard requires owner-created credentials before showing the control room:

export FOREX_BOT_DASHBOARD_USER="your-member-username"
export FOREX_BOT_DASHBOARD_PASSWORD="a-long-owner-issued-password"

The owner must set and distribute these credentials. This local server has no email provider configured, so it does not send credentials automatically to academymoonfx@gmail.com; connect an approved transactional email service before automating that workflow.

The dashboard also includes a read-only MT5 demo check. Configure the broker before using Check demo connection:

export FOREX_BOT_BROKER=mt5
export FOREX_BOT_MT5_SYMBOL=EURUSD

After MT5 is configured, the authenticated dashboard shows only the configured MT5 symbol, closed M15 candle data, current bid/ask, open positions, and entered-trade count. The Start and Stop controls explicitly start and stop the managed MT5 demo monitor, and every submitted order uses the existing PLACE_DEMO_ORDER safety gate.

For MT5 support on Windows, install the optional integration with python -m pip install -e ".[mt5]". Keep MT5 open and logged into a demo account, then set FOREX_BOT_BROKER=mt5 and FOREX_BOT_MT5_SYMBOL=EURUSD before starting the dashboard. The control page includes Close positions, which stops the monitor and closes all positions on the verified demo account after confirmation.

The frontend is split into a public sign-in page (/), a protected bot-control page (/dashboard.html), a protected live market and trade-entry page (/market.html), and a protected resources/contact page (/resources.html). Support contact is academymoonfx@gmail.com. Its visual theme follows the operating system's light/dark preference. Start Bot does not open PowerShell or execute arbitrary desktop commands; it uses the server-managed MT5 process so browser actions remain permission-gated and auditable.

Each authenticated browser receives a device identifier. Activation is refused once the MT5 entry count reaches 30 for that device, and the owner must renew access out of band. The current in-memory dashboard server does not persist renewals across restarts; use a database-backed license store before deploying this beyond a trusted local environment.

To close all open positions on the verified MT5 demo account:

forex-bot mt5-close-all-demo --confirm CLOSE_ALL_DEMO_POSITIONS

This command is rejected without the exact confirmation token and is restricted by the adapter to MT5 demo accounts.

Walk-forward training

Run the explainable parameter-selection loop against the bundled data:

forex-bot train

The trainer tests moving-average candidates on each historical training window, selects the best risk-adjusted candidate, and evaluates it only on the following unseen validation window. It prints the selected parameters and out-of-sample results; it does not activate a strategy or place orders.

The next implementation slice will add the broker protocol and simulator, then OANDA practice and MetaTrader 5 adapters behind the same risk and execution boundary.

Run a one-shot, non-trading daily self-assessment using the existing out-of-sample ML walk-forward evaluation:

forex-bot assess

The machine-readable report is written atomically to reports/daily_assessment.json by default. Set FOREX_BOT_ASSESSMENT_REPORT or pass --report-path to choose another local path. When FOREX_BOT_DATA_URL is set, the command refreshes the dataset when the existing refresh policy says it is due. The assessment never promotes a model, starts the dashboard or MT5 monitor, places orders, or guarantees accuracy; its results are hypothetical and subject to data quality, sample-size, leakage, and execution assumptions.

Optional Linux user-level schedule

The repository includes an opt-in systemd user service and timer for running this non-trading assessment once daily. The timer is disabled until you install and enable it. The units use only the repository virtualenv and forex-bot assess; they do not start the dashboard, MT5 monitor, or any order path.

From the repository root, replace /workspaces/harry-gt in deploy/systemd/forex-bot-assess.service with this checkout's absolute path if it differs, then install the units:

mkdir -p ~/.config/systemd/user
cp deploy/systemd/forex-bot-assess.service deploy/systemd/forex-bot-assess.timer ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now forex-bot-assess.timer
systemctl --user status forex-bot-assess.timer

OnCalendar runs at 06:00 UTC. Persistent=true runs a missed invocation after the user session returns. To run one assessment immediately, use systemctl --user start forex-bot-assess.service; inspect output with journalctl --user -u forex-bot-assess.service. This schedule does not provide credentials and does not enable live trading.

The repository also includes an opt-in daily test-runner service. It runs the full pytest -q suite at 06:15 UTC, after the assessment, using only the repository virtualenv. It does not start the dashboard, MT5 monitor, or any order path. Install and enable it alongside the assessment schedule:

cp deploy/systemd/forex-bot-tests.service deploy/systemd/forex-bot-tests.timer ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now forex-bot-tests.timer
systemctl --user status forex-bot-tests.timer

Run the test service immediately with systemctl --user start forex-bot-tests.service; inspect results with journalctl --user -u forex-bot-tests.service. The test timer is independent of the assessment timer, so it can be disabled without affecting assessment:

systemctl --user disable --now forex-bot-tests.timer
rm ~/.config/systemd/user/forex-bot-tests.service ~/.config/systemd/user/forex-bot-tests.timer
systemctl --user daemon-reload

Disable and remove the schedule with:

systemctl --user disable --now forex-bot-assess.timer
rm ~/.config/systemd/user/forex-bot-assess.service ~/.config/systemd/user/forex-bot-assess.timer
systemctl --user daemon-reload

Demo strategy cycle

With MT5 open and the demo account logged in, preview the current multi-timeframe strategy signal:

python -m forex_bot.cli mt5-demo-trade

The command reads closed 15-minute, 1-hour, and 4-hour candles and places nothing by default. It calculates volume from 1% equity risk and broker tick metadata. Only after reviewing the preview should you explicitly submit one demo order:

python -m forex_bot.cli mt5-demo-trade --confirm PLACE_DEMO_ORDER

This is a one-cycle command, not an unattended trading service. Verify the order, stop, target, volume, and demo account in MT5 after submission. Never use the confirmation on a live account.

To check automatically every 5 minutes without placing orders:

python -m forex_bot.cli mt5-monitor

After reviewing preview cycles, demo order placement can be explicitly enabled:

python -m forex_bot.cli mt5-monitor --place-demo-orders --confirm PLACE_DEMO_ORDER

The monitor ignores the current forming candle, prevents duplicate handling of the same signal, and skips new entries when a position for the symbol already exists. Stop it with Ctrl+C.

The first historical sandbox run is documented in BACKTEST_REPORT.md, using the reproducible dataset at data/eurusd_daily_2024_2026.csv.

Economic news sources

The trainer and demo/paper entry filters can combine multiple licensed economic-event sources. Provide comma-separated local CSV paths and matching provider URLs; URLs are refreshed into the paths in the same order:

export FOREX_BOT_NEWS_EVENTS_PATHS="data/calendar-primary.csv,data/calendar-secondary.csv"
export FOREX_BOT_NEWS_EVENTS_URLS="https://provider.example/primary.csv,https://provider.example/secondary.csv"
export FOREX_BOT_NEWS_BLACKOUT_HOURS=1

Each CSV must contain timestamp,currency,impact, with timezone-aware timestamps and low, medium, or high impact. Exact duplicate events are merged, and the source that supplied the first copy is retained. The legacy singular FOREX_BOT_NEWS_EVENTS_PATH and FOREX_BOT_NEWS_EVENTS_URL variables remain supported. A provider's website homepage is not a data source; use its authorized export or API endpoint.

The tiered-target run is documented in TIERED_BACKTEST_REPORT.md. It uses spread, slippage, stops, mark-to-market drawdown, and a 20-entry cap.

The fixed 1:2 risk-to-reward comparison is documented in STANDARD_RR_BACKTEST_REPORT.md.

The corrected ATR/filter/next-open model is documented in IMPROVED_BACKTEST_REPORT.md.

The recent multi-pair intraday test is documented in INTRADAY_100_TRADE_REPORT.md.

The shared-account portfolio test is documented in COMBINED_PORTFOLIO_REPORT.md.

The portfolio engine supports a maximum of 2 entries per pair per day and 5 total daily entries.

The three-strategy comparison is documented in STRATEGY_COMPARISON_REPORT.md.

MT5 preparation includes a read-only adapter and forex-bot mt5-check. The official MT5 Python package and a running terminal must be available on the host where this command runs; no password belongs in this repository or chat.

Windows MT5 setup

Run these commands in PowerShell from the project folder on the same PC where the MT5 desktop terminal is installed:

py -3.11 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install MetaTrader5
python -m pip install -e ".[dev]"
$env:FOREX_BOT_BROKER = "mt5"
$env:FOREX_BOT_MT5_SYMBOL = "EURUSD"
$env:FOREX_BOT_STRATEGY_VERSION = "v3"
$env:PYTHONPATH = "src"
python -m forex_bot.cli mt5-check

The MT5 preview and monitor select a strategy per currency pair using closed-candle walk-forward results. If no strategy meets the minimum evidence and drawdown gates, they fall back to the structured regime router. Choose strategy version v1, v2, v3, or v3-balanced with FOREX_BOT_STRATEGY_VERSION or --strategy-version. Version 3 adds candlestick/advisory confirmation; v3-balanced keeps pair and higher-timeframe gates but logs candlestick/advisory checks without using them as hard entry vetoes.

How the bot trades

The bot makes a trade decision in layers on every monitoring cycle. This is the actual execution model used by the monitor and strategy router:

  1. Market regime detection

    The bot continuously classifies the current market environment:

    • Trending vs. ranging (ADX or the slope of a long moving average)
    • High vs. low volatility (ATR relative to its own history)
    • Risk-on vs. risk-off sentiment (used to judge carry-trade viability)

    It assigns a regime label and confidence score for each new bar.

  2. Independent strategy modules

    Each strategy runs in parallel and always emits a signal with a confidence score, regardless of the current regime:

    • Trend-following module
    • Mean-reversion module
    • Carry-trade module (checks interest-rate differential and regime for risk-off unwinds)
    • Stat-arb / pairs module (when correlated pairs are available)

    These modules are independent; they do not need to agree with one another to produce a valid output.

  3. Weighting engine

    The bot combines regime state and recent performance to assign each strategy a dynamic weight, recalculated periodically (for example, daily):

    • Base weight increases when the current regime favors that strategy
    • Trend strategies get more weight in high-ADX conditions
    • Mean-reversion strategies get more weight in ranging conditions
    • Any strategy in an extended drawdown is trimmed, with a floor so it never collapses to zero

    This keeps the bot adaptive without allowing one strategy to dominate the portfolio based on a short-lived spike.

  4. Aggregation

    The bot combines all weighted signals into a single net position per currency pair:

    net_signal = Σ (strategy_signal × strategy_weight × strategy_confidence)

    If several strategies agree on the same direction, the position is reinforced; if they disagree, they partially cancel. This reduces false positives without hard voting thresholds.

  5. Risk and position sizing

    Risk controls are enforced independently of the signal source:

    • Exposure is capped per pair and portfolio-wide
    • Fixed fractional risk is used per trade (for example, 0.5–1% of equity)
    • Correlation checks prevent the portfolio from stacking the same directional bet through more than one strategy
  6. Execution and logging

    The bot executes the net trade, but it also logs each individual strategy signal and its contribution to that trade. This keeps every order auditable and makes it clear which strategy is adding value versus dragging performance.

  7. Feedback loop

    Rolling performance statistics per strategy feed back into the weighting engine. This is deliberately delayed (weekly or monthly) so the bot does not chase noise and overreact to short-term volatility.

In practice, this means the monitor does not simply pick one strategy at random. It evaluates the market regime, runs several independent modules, blends them by weight and confidence, applies risk caps, and then logs the full contribution of each signal before execution.

The MT5 connection automatically shuts down and rejects further operations after 30 days. This applies to direct CLI launches and dashboard launches; no separate PowerShell cleanup command is required.

Multiple MT5 accounts

Run one monitor process per account, with a separate MT5 terminal data folder and a separate PowerShell window. Each process is isolated by its account ID and terminal path:

# Window 1
$env:FOREX_BOT_ACCOUNT_ID = "account-one"
$env:FOREX_BOT_MT5_PATH = "C:\MT5\account-one\terminal64.exe"
$env:FOREX_BOT_MT5_SYMBOLS = "EURUSD,GBPUSD"
python -m forex_bot.cli mt5-monitor
# Window 2
$env:FOREX_BOT_ACCOUNT_ID = "account-two"
$env:FOREX_BOT_MT5_PATH = "C:\MT5\account-two\terminal64.exe"
$env:FOREX_BOT_MT5_SYMBOLS = "USDJPY,XAUUSD"
python -m forex_bot.cli mt5-monitor

Use unique terminal paths for each account. When a connection reaches 30 days from activation, the broker shuts it down automatically and that monitor can no longer read data or place orders.

Bot launcher: demo and live trading

Use the included launcher instead of retyping environment variables every time:

.\start_mt5_bot.ps1

It sets MT5 auto mode, clears fixed symbol lists, reads enabled currency pairs from Market Watch, and starts the monitor. If MT5 is installed in its default location, no path is needed. For a separate installation, pass the real existing terminal64.exe path:

.\start_mt5_bot.ps1 -Mt5Path "C:\Path\To\Your\terminal64.exe" -AccountId "account-one"

Auto mode re-reads Market Watch on every monitoring cycle. Enable the currency pairs you want in MT5 Market Watch and disable any pairs you do not want traded. The connection expires automatically after 30 days.

The same Start-ForexBot command supports both demo and live trading. Without -Live, it starts demo/auto mode. Add -Live only when you deliberately want live mode; live mode requires an account ID, a private live secret, and the exact order confirmation.

Start-ForexBot automatically enables demo order placement by default. It opens only signals that pass the strategy and risk checks, attaches the calculated stop-loss and take-profit to the MT5 order, and closes bot-owned losing positions that exceed FOREX_BOT_MAX_HOLD_DAYS. Profitable positions are protected by the monitor. MT5 itself closes positions when their stop-loss or take-profit is reached. The launcher refuses to place orders on a live account unless live mode and the exact live confirmation are explicitly supplied.

To make the launcher available whenever a new PowerShell window opens, run this once from any PowerShell folder. This searches your Downloads, Documents, and Desktop folders for the project launcher, so it does not depend on the current folder or a fixed path:

New-Item -ItemType File -Path $PROFILE -Force | Out-Null
@"
function Start-ForexBot {
    $searchRoots = @("Downloads", "Documents", "Desktop") |
        ForEach-Object { Join-Path `$HOME `$_ } |
        Where-Object { Test-Path `$_ -PathType Container }
    $launcher = Get-ChildItem -Path $searchRoots -Filter "start_mt5_bot.ps1" -File -Recurse -ErrorAction SilentlyContinue |
        Where-Object { `$_.FullName -like "*\harry-gt-main\start_mt5_bot.ps1" } |
      Sort-Object { `$_.FullName.Length } |
        Select-Object -First 1
    if (-not `$launcher) {
        throw "Could not find start_mt5_bot.ps1 under Downloads, Documents, or Desktop."
    }
    & `$launcher.FullName @args
}
"@ | Set-Content $PROFILE
. $PROFILE
Start-ForexBot

For live MT5 monitoring, configure the approved device and live confirmations before enabling order placement:

$env:FOREX_BOT_MODE = "live"
$env:FOREX_BOT_DEVICE_ID = "trusted-laptop"
$env:FOREX_BOT_ACCOUNT_ID = "your-live-account-id"
$env:FOREX_BOT_LIVE_CONFIRMED = "true"
$env:FOREX_BOT_LIVE_CONFIRMATION = "I_UNDERSTAND_LIVE_RISK"
$env:FOREX_BOT_LIVE_SECRET = "set-a-secret-in-your-local-environment"
python -m forex_bot.cli mt5-monitor --place-orders --confirm PLACE_LIVE_ORDER

Live startup runs the security agent, strategy research thread, pattern confirmation, advisory checks, news filter, and risk guards before an order can be sent. With no symbol variables set, live mode uses the enabled currency pairs in MT5 Market Watch and re-reads them every monitoring cycle. To launch this safely through the reusable launcher:

Start-ForexBot -Live -AccountId "your-live-account-id" -LiveSecret "set-a-secret-in-your-local-environment" -PlaceOrders -Confirm PLACE_LIVE_ORDER

The MT5 monitor journals previews, fills, and closed deals for both demo and live runs in reports/mt5_trade_journal.json by default. Bot-owned closed deals update the adaptive learner in adaptive_learning.db; set FOREX_BOT_JOURNAL_PATH, FOREX_BOT_LEARNING_DB, or FOREX_BOT_PATTERN_DB to use other local paths. Learning is recorded once per MT5 deal and includes profit, commission, and swap.

Before the check, open MT5, log into the demo account, select the broker's exact symbol in Market Watch, and enable Algo Trading. The check is read-only and does not place an order. Some brokers use suffixes such as EURUSDm or XAUUSDm; use the exact symbol shown in MT5.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages