FxMath Trading AI — Documentation
Complete settings reference for both EA versions
Overview
Both versions are self-contained Expert Advisors that train machine learning models directly inside MetaTrader. They collect price data, extract technical features, train models, and combine predictions from three timeframes via confidence-weighted voting.
Version Comparison
| Feature | RF v1.1 | LGBM+RL v1.0 |
|---|---|---|
| ML Engine | Random Forest (pure MQL) | LightGBM Gradient Boosting (DLL) |
| Number of Features | 19 | 28 |
| Q-Learning RL | — | 27 states, 3 actions, epsilon-greedy |
| Tick Volume | — | Included (volume ratio feature) |
| Rolling Skew/Kurtosis | — | Included |
| Trend Strength | MA distance | + LinReg slope, Elder-Ray, CMO |
| DLL | None | LGBM_RL_Engine.dll (15MB, static) |
| Magic Number | 202405 | 202406 |
| Panel | 9 rows | 10 rows (+ RL status) |
Installation
Both Versions
- Copy
.mq4/.mq5toMQL4\Experts\orMQL5\Experts\ - Compile in MetaEditor (F7)
- Attach to a chart
LGBM+RL Only — DLL Setup
- Copy
LGBM_RL_Engine.dlltoMQL4\Libraries\orMQL5\Libraries\ - Restart MetaTrader or use Tools → Options → Expert Advisors: Allow DLL Imports
- The DLL is fully static — only depends on KERNEL32, msvcrt, WS2_32, IPHLPAPI
ML Engines
Random Forest (v1.1)
Ensemble of decision trees trained with bootstrap aggregation (80% sample) and Gini impurity splitting. Hyperparameters: InpNumTrees (5-50), InpMaxDepth (3-15), InpMinSamples (2-50).
LightGBM (v1.0)
Gradient boosting via the C API of Microsoft's LightGBM library. Hyperparameters: InpNumLeaves (15-127), InpLearningRate (0.01-0.3), InpNumIterations, InpMinDataInLeaf, InpFeatureFraction, InpBaggingFraction. Uses objective=binary with metric=binary_logloss.
Multi-Timeframe Voting
Three independent models on three configurable timeframes. Each predicts UP probability. The EA combines them:
- BUY when at least
InpVoteMinTFs have probability aboveBuyThreshold - SELL when at least
InpVoteMinTFs have probability belowSellThreshold - NEUTRAL otherwise
Votes are weighted by confidence (|prob - 0.5| × 2). In the LGBM+RL version, BuyThreshold, SellThreshold, and MinConfidence are dynamically adjusted by the RL agent.
28 Features (LGBM+RL) / 19 Features (RF)
All features are computed per-TF and normalized. The RF version uses features 1-19. The LGBM+RL version adds 9 more.
Original 19 Features (both versions)
| # | Feature | Description |
|---|---|---|
| 1 | Price Position | Close in 20-bar range [0,1] |
| 2 | 1-Bar Return | (c0 - c1) / c1 |
| 3-5 | MA Distance | Close relative to MA5, MA20, MA50 |
| 6-7 | MA Crossover | MA5-MA20, MA10-MA50 normalized |
| 8 | Candle Body | Body/high-low range [-1,1] |
| 9 | 5-Bar Return | (c0 - c5) / c5 |
| 10 | RSI | RSI(14) / 100 |
| 11 | Bollinger %B | %B(20,2) |
| 12 | ATR/Price | ATR(14) / close |
| 13-15 | MACD | Line, signal, histogram all / close |
| 16 | Momentum | 10-bar return |
| 17 | Short-term Vol | Bar HL range / close |
| 18 | Price Position (5) | Close in 5-bar range |
| 19 | RSI Slope | RSI(14) change over 3 bars |
New Features 20-28 (LGBM+RL only)
| # | Feature | Description |
|---|---|---|
| 20 | Volatility Ratio | ATR(14) / avg ATR across 3 windows — expanding/contracting regime |
| 21 | LinReg Slope (10) | Linear regression slope / close — clean trend direction |
| 22 | Bar Strength | (high - low) / ATR(14) — relative bar magnitude |
| 23 | Volume Ratio | Volume(0) / SMA(Volume, 10) — volume spike detection |
| 24 | Rolling Skew | 10-bar return skewness — distribution asymmetry |
| 25 | Rolling Kurtosis | 10-bar excess kurtosis — tail risk |
| 26 | Elder-Ray Bull | (high - EMA(13)) / close — buyer strength |
| 27 | Elder-Ray Bear | (low - EMA(13)) / close — seller strength |
| 28 | CMO(10) | Chande Momentum Oscillator [-1, 1] |
Q-Learning RL Agent (LGBM+RL Only)
The Q-Learning agent dynamically adjusts trading thresholds based on market conditions. It uses a tabular Q-table with 27 states × 3 actions.
State Space
| Dimension | Bins | Default | Parameter |
|---|---|---|---|
| Win Rate (last 20 trades) | 2-5 | 3 | InpRLWinBins |
| Volatility (ATR/price) | 2-5 | 3 | InpRLVolBins |
| Consecutive Losses | 2-4 | 3 | InpRLLossBins |
Default total: 27 states. The state is computed each new bar before prediction.
Actions
| Action | BuyThreshold adj. | SellThreshold adj. | MinConfidence adj. | Effect |
|---|---|---|---|---|
| 0 — Conservative | +0.08 | −0.08 | +0.10 | Fewer trades, higher quality |
| 1 — Normal | Input param | Input param | Input param | Default behavior |
| 2 — Aggressive | −0.05 | +0.05 | −0.05 | More trades, lower threshold |
Reward
reward = profit / ATR_at_open — normalized to volatility. Clipped to [-3, +3].
Learning Loop
- On each new bar: discretize market state → get action via epsilon-greedy
- Apply action adjustments to thresholds
- Predict, vote, trade
- When trade closes: compute reward → update Q-table → decay epsilon
Q-Table Persistence
The Q-table is saved to InpRLSavePath (default: RFConsensus_RL.qtable) on OnDeinit and loaded automatically on OnInit. Knowledge accumulates across sessions.
Training Pipeline
- Data Collection: Fetch
InpTrainBars(default 500) of OHLCV data per TF - Feature Extraction: Compute all 19/28 features for each bar
- Label Generation: Label = 1 if future close > current close + 0.3 × ATR(14), else 0
- Training: Train RF (in-memory) or LGBM (via DLL) on feature matrix
- Retrain: Every
InpRFRetrainBars/InpLGBMRetrainBarsbars
Labels are volatility-adaptive — in high-volatility regimes, the threshold widens so the model focuses on meaningful moves, not market noise.
Trading Logic
At most one position at a time. When a new signal arrives:
- No position → open trade at market
- Has position → let SL/TP close it (no reversal — avoids overtrading)
Filters: spread check, time filter (InpTimeFilterEnable), minimum confidence.
SL/TP from ATR on main TF. Trailing stop and break-even update every tick.
RF v1.1 Parameters
📊 Random Forest Settings (RF only)
| Parameter | Default | Range | Description |
|---|---|---|---|
| InpNumTrees | 20 | 5-50 | Number of decision trees |
| InpMaxDepth | 8 | 3-15 | Max tree depth |
| InpMinSamples | 5 | 2-50 | Min samples per leaf |
| InpRFRetrainBars | 200 | 50-1000 | Retrain every N bars |
| InpHorizon1 | 3 | 1-50 | Prediction horizon (bars ahead) |
LGBM+RL v1.0 Parameters
⚡ LightGBM Settings (LGBM+RL only)
| Parameter | Default | Range | Description |
|---|---|---|---|
| InpNumLeaves | 31 | 15-127 | Max leaves per tree — controls tree complexity |
| InpLearningRate | 0.05 | 0.01-0.3 | Shrinkage rate — lower = more robust |
| InpNumIterations | 100 | 10-500 | Number of boosting rounds |
| InpMinDataInLeaf | 10 | 5-100 | Min samples per leaf — prevents overfitting |
| InpFeatureFraction | 0.8 | 0.1-1.0 | Feature sampling per iteration |
| InpBaggingFraction | 0.8 | 0.1-1.0 | Data sampling per iteration |
| InpLGBMRetrainBars | 200 | 50-1000 | Retrain every N bars |
| InpHorizon1 | 3 | 1-50 | Prediction horizon |
RL Parameters (LGBM+RL only)
🤖 Q-Learning RL Settings
| Parameter | Default | Range | Description |
|---|---|---|---|
| InpRLEnable | false | — | Enable RL threshold adjustment |
| InpRLAlpha | 0.10 | 0.01-0.5 | Q-learning learning rate |
| InpRLGamma | 0.90 | 0.8-0.99 | Discount factor |
| InpRLEpsilon | 0.30 | 0.05-0.5 | Initial exploration rate |
| InpRLEpsilonDecay | 0.998 | 0.9-1.0 | Epsilon decay per trade |
| InpRLWinBins | 3 | 2-5 | Win rate state bins |
| InpRLVolBins | 3 | 2-5 | Volatility state bins |
| InpRLLossBins | 3 | 2-4 | Consecutive loss bins |
| InpRLSavePath | "RFConsensus_RL.qtable" | — | Q-table persistence file |
Common Parameters (both versions)
🔧 Feature Settings
| Parameter | Default | Range | Description |
|---|---|---|---|
| InpFeatLookback | 20 | 5-100 | Price-range lookback period |
| InpFeatBBPeriod | 20 | 5-50 | Bollinger period |
| InpFeatRSIPeriod | 14 | 5-30 | RSI period |
| InpFeatMACDFast | 12 | 5-30 | MACD fast |
| InpFeatMACDSlow | 26 | 10-60 | MACD slow |
| InpFeatMACDSignal | 9 | 5-20 | MACD signal |
| InpTrainBars | 500 | 100-2000 | Training data size |
⏱ Multi-Timeframe Voting
| Parameter | Default (MQ5) | Description |
|---|---|---|
| InpTF1 | PERIOD_M1 | Timeframe #1 |
| InpTF2 | PERIOD_M5 | Timeframe #2 |
| InpTF3 | PERIOD_M15 | Timeframe #3 |
| InpMainTF | PERIOD_M5 | Main TF (SL/TP, new-bar trigger) |
| InpVoteMin | 2 | Min TFs agreeing (1-3) |
💰 Trading Thresholds
| Parameter | Default | Range | Description |
|---|---|---|---|
| InpBuyThreshold | 0.55 | 0.50-0.90 | Buy if probability > this |
| InpSellThreshold | 0.45 | 0.10-0.50 | Sell if probability < this |
| InpMinConfidence | 0.20 | 0.05-0.50 | Min confidence for signal |
| InpLotSize | 0.01 | 0.01-100 | Fixed lot size |
| InpMaxSpread | 3000 | 1-10000 | Max spread (points) |
📐 Money Management
| Parameter | Default | Description |
|---|---|---|
| InpUseMM | false | Enable % risk position sizing |
| InpRiskPercent | 1.0 | Risk % of equity per trade |
🛑 Risk Management
| Parameter | Default | Description |
|---|---|---|
| InpATRPeriod | 14 | ATR period for SL/TP |
| InpSLMultiplier | 1.0 | SL = ATR × multiplier |
| InpTPMultiplier | 2.0 | TP = ATR × multiplier |
🔁 Trailing Stop & Break-Even
| Parameter | Default | Description |
|---|---|---|
| InpTrailEnable | false | Enable trailing stop |
| InpTrailTriggerPct | 50.0 | Start trail at X% of TP distance |
| InpTrailDistPct | 25.0 | Trail distance = Y% of TP |
| InpBEEnable | false | Enable break-even |
| InpBETriggerPct | 30.0 | Move SL to entry at X% of TP |
⏰ Time Filter
| Parameter | Default | Description |
|---|---|---|
| InpTimeFilterEnable | false | Enable session time filter |
| InpStartHour | 8 | Session start (server time, 0-23) |
| InpEndHour | 20 | Session end (server time, 0-23) |
🖥 Display & Identification
| Parameter | Default (RF) | Default (LGBM+RL) | Description |
|---|---|---|---|
| InpShowOnChart | true | true | Show chart panel |
| InpMagicNumber | 202405 | 202406 | Unique order identifier |
| InpTradeComment | "RFConsensus" | "LGBM_RL" | Order comment prefix |
Chart Panel
When InpShowOnChart = true, an information panel appears on the chart:
- Title — EA name and version
- VOTE result — BUY/SELL/NEUTRAL with agreement count
- 3 × TF rows — probability and confidence per timeframe
- Entry / SL / TP levels
- RL Status (LGBM+RL only) — action, epsilon, trade count
- Position status — direction and floating profit
FxMath_RFConsensus v1.1 · FxMath_RFConsensus_LGBM_RL v1.0 · Documentation