FxMath Trading AI — Documentation

v1.1 (RF) & v1.0 (LGBM+RL) · MQL4 / MQL5 · FxMath
Complete settings reference for both EA versions
RF Random Forest v1.1 — DLL-Free LGBM+RL LightGBM + Q-Learning v1.0

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.

RF v1.1 uses a built-in Random Forest written entirely in MQL4/MQL5 — no external dependencies, DLLs, or Python. Contains 19 features.
LGBM+RL v1.0 uses a cross-compiled C++ DLL with LightGBM gradient boosting (more accurate, faster training) plus a Q-Learning agent that dynamically adjusts trading thresholds. Contains 28 features.

Version Comparison

FeatureRF v1.1LGBM+RL v1.0
ML EngineRandom Forest (pure MQL)LightGBM Gradient Boosting (DLL)
Number of Features1928
Q-Learning RL27 states, 3 actions, epsilon-greedy
Tick VolumeIncluded (volume ratio feature)
Rolling Skew/KurtosisIncluded
Trend StrengthMA distance+ LinReg slope, Elder-Ray, CMO
DLLNoneLGBM_RL_Engine.dll (15MB, static)
Magic Number202405202406
Panel9 rows10 rows (+ RL status)

Installation

Both Versions

  1. Copy .mq4 / .mq5 to MQL4\Experts\ or MQL5\Experts\
  2. Compile in MetaEditor (F7)
  3. Attach to a chart

LGBM+RL Only — DLL Setup

  1. Copy LGBM_RL_Engine.dll to MQL4\Libraries\ or MQL5\Libraries\
  2. Restart MetaTrader or use Tools → Options → Expert Advisors: Allow DLL Imports
  3. 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:

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)

#FeatureDescription
1Price PositionClose in 20-bar range [0,1]
21-Bar Return(c0 - c1) / c1
3-5MA DistanceClose relative to MA5, MA20, MA50
6-7MA CrossoverMA5-MA20, MA10-MA50 normalized
8Candle BodyBody/high-low range [-1,1]
95-Bar Return(c0 - c5) / c5
10RSIRSI(14) / 100
11Bollinger %B%B(20,2)
12ATR/PriceATR(14) / close
13-15MACDLine, signal, histogram all / close
16Momentum10-bar return
17Short-term VolBar HL range / close
18Price Position (5)Close in 5-bar range
19RSI SlopeRSI(14) change over 3 bars

New Features 20-28 (LGBM+RL only)

#FeatureDescription
20Volatility RatioATR(14) / avg ATR across 3 windows — expanding/contracting regime
21LinReg Slope (10)Linear regression slope / close — clean trend direction
22Bar Strength(high - low) / ATR(14) — relative bar magnitude
23Volume RatioVolume(0) / SMA(Volume, 10) — volume spike detection
24Rolling Skew10-bar return skewness — distribution asymmetry
25Rolling Kurtosis10-bar excess kurtosis — tail risk
26Elder-Ray Bull(high - EMA(13)) / close — buyer strength
27Elder-Ray Bear(low - EMA(13)) / close — seller strength
28CMO(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

DimensionBinsDefaultParameter
Win Rate (last 20 trades)2-53InpRLWinBins
Volatility (ATR/price)2-53InpRLVolBins
Consecutive Losses2-43InpRLLossBins

Default total: 27 states. The state is computed each new bar before prediction.

Actions

ActionBuyThreshold adj.SellThreshold adj.MinConfidence adj.Effect
0 — Conservative+0.08−0.08+0.10Fewer trades, higher quality
1 — NormalInput paramInput paramInput paramDefault behavior
2 — Aggressive−0.05+0.05−0.05More trades, lower threshold

Reward

reward = profit / ATR_at_open — normalized to volatility. Clipped to [-3, +3].

Learning Loop

  1. On each new bar: discretize market state → get action via epsilon-greedy
  2. Apply action adjustments to thresholds
  3. Predict, vote, trade
  4. 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

  1. Data Collection: Fetch InpTrainBars (default 500) of OHLCV data per TF
  2. Feature Extraction: Compute all 19/28 features for each bar
  3. Label Generation: Label = 1 if future close > current close + 0.3 × ATR(14), else 0
  4. Training: Train RF (in-memory) or LGBM (via DLL) on feature matrix
  5. Retrain: Every InpRFRetrainBars / InpLGBMRetrainBars bars

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:

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)

ParameterDefaultRangeDescription
InpNumTrees205-50Number of decision trees
InpMaxDepth83-15Max tree depth
InpMinSamples52-50Min samples per leaf
InpRFRetrainBars20050-1000Retrain every N bars
InpHorizon131-50Prediction horizon (bars ahead)

LGBM+RL v1.0 Parameters

⚡ LightGBM Settings (LGBM+RL only)

ParameterDefaultRangeDescription
InpNumLeaves3115-127Max leaves per tree — controls tree complexity
InpLearningRate0.050.01-0.3Shrinkage rate — lower = more robust
InpNumIterations10010-500Number of boosting rounds
InpMinDataInLeaf105-100Min samples per leaf — prevents overfitting
InpFeatureFraction0.80.1-1.0Feature sampling per iteration
InpBaggingFraction0.80.1-1.0Data sampling per iteration
InpLGBMRetrainBars20050-1000Retrain every N bars
InpHorizon131-50Prediction horizon

RL Parameters (LGBM+RL only)

🤖 Q-Learning RL Settings

ParameterDefaultRangeDescription
InpRLEnablefalseEnable RL threshold adjustment
InpRLAlpha0.100.01-0.5Q-learning learning rate
InpRLGamma0.900.8-0.99Discount factor
InpRLEpsilon0.300.05-0.5Initial exploration rate
InpRLEpsilonDecay0.9980.9-1.0Epsilon decay per trade
InpRLWinBins32-5Win rate state bins
InpRLVolBins32-5Volatility state bins
InpRLLossBins32-4Consecutive loss bins
InpRLSavePath"RFConsensus_RL.qtable"Q-table persistence file

Common Parameters (both versions)

🔧 Feature Settings

ParameterDefaultRangeDescription
InpFeatLookback205-100Price-range lookback period
InpFeatBBPeriod205-50Bollinger period
InpFeatRSIPeriod145-30RSI period
InpFeatMACDFast125-30MACD fast
InpFeatMACDSlow2610-60MACD slow
InpFeatMACDSignal95-20MACD signal
InpTrainBars500100-2000Training data size

⏱ Multi-Timeframe Voting

ParameterDefault (MQ5)Description
InpTF1PERIOD_M1Timeframe #1
InpTF2PERIOD_M5Timeframe #2
InpTF3PERIOD_M15Timeframe #3
InpMainTFPERIOD_M5Main TF (SL/TP, new-bar trigger)
InpVoteMin2Min TFs agreeing (1-3)

💰 Trading Thresholds

ParameterDefaultRangeDescription
InpBuyThreshold0.550.50-0.90Buy if probability > this
InpSellThreshold0.450.10-0.50Sell if probability < this
InpMinConfidence0.200.05-0.50Min confidence for signal
InpLotSize0.010.01-100Fixed lot size
InpMaxSpread30001-10000Max spread (points)

📐 Money Management

ParameterDefaultDescription
InpUseMMfalseEnable % risk position sizing
InpRiskPercent1.0Risk % of equity per trade

🛑 Risk Management

ParameterDefaultDescription
InpATRPeriod14ATR period for SL/TP
InpSLMultiplier1.0SL = ATR × multiplier
InpTPMultiplier2.0TP = ATR × multiplier

🔁 Trailing Stop & Break-Even

ParameterDefaultDescription
InpTrailEnablefalseEnable trailing stop
InpTrailTriggerPct50.0Start trail at X% of TP distance
InpTrailDistPct25.0Trail distance = Y% of TP
InpBEEnablefalseEnable break-even
InpBETriggerPct30.0Move SL to entry at X% of TP

⏰ Time Filter

ParameterDefaultDescription
InpTimeFilterEnablefalseEnable session time filter
InpStartHour8Session start (server time, 0-23)
InpEndHour20Session end (server time, 0-23)

🖥 Display & Identification

ParameterDefault (RF)Default (LGBM+RL)Description
InpShowOnCharttruetrueShow chart panel
InpMagicNumber202405202406Unique order identifier
InpTradeComment"RFConsensus""LGBM_RL"Order comment prefix

Chart Panel

When InpShowOnChart = true, an information panel appears on the chart:

Tip: Start conservatively (20 trees / 31 leaves, 2-of-3 vote, 1% risk) on a demo account. For LGBM+RL, leave InpRLEnable=false initially to establish baseline performance before enabling the RL agent.

FxMath_RFConsensus v1.1 · FxMath_RFConsensus_LGBM_RL v1.0 · Documentation