2 HowAddAiToBot
Niquel Mendoza edited this page 2026-04-30 16:38:49 +00:00

Adding AI to a Trading Bot

In this mini-article, we'll explore how to integrate artificial intelligence into a trading bot for MT5.

What is AI Capable Of?

Within a trading bot, AI is primarily used to detect patterns and apply filters based on input data. The idea is that, through this data and the use of algorithms, the model can predict certain outcomes, such as the probability of a trade being profitable.

AI Integration Process

To integrate AI into a trading bot, you can follow these steps:

1. Define the Model's Objective

First, you must decide what you want the model to predict. Some examples:

  • Filter trading signals
  • Estimate the probability of a profitable trade
  • Predict future price movements

2. Convert the Problem to Numbers

AI works with numerical data, so you must translate your objective into quantifiable values.

  • If the result is discrete (for example: 0 = do not trade, 1 = trade), you're dealing with a classification problem.
  • If the result is continuous (for example: future price or expected return), you're dealing with a regression problem.

3. Define the Features (Model Inputs)

Features are the data that the model will use to make predictions.

A good way to define them is to ask yourself:

If I had to make this decision manually, what information would I use?

Examples of features:

  • Technical indicators (RSI, MACD, moving averages)
  • Volume
  • Previous candles
  • Volatility Afterward, you can apply feature engineering:
  • Correlations
  • Normalization
  • Variable selection

4. Generate the Dataset

Once features are defined, you need to generate historical data.

You can:

  • Export it to a .csv file
  • Use external tools or libraries
  • Generate it directly from MT5 It's important that the data is well-aligned and clean.

5. Train the Model

With the dataset ready, you train the model in Python.

Some model options:

  • MLP (Basic neural network) → Good general option
  • Decision Trees / Random Forest → Robust and easy to interpret
  • RNN / LSTM → Useful for time series The choice depends on the problem and the data.

6. Export the Model

Once trained, export the model to a compatible format such as ONNX.

This allows you to easily integrate it into your MT5 bot.


Conclusion

Integrating AI into a trading bot is not just "adding a model," but correctly designing:

  • The problem
  • The data
  • The features
  • The training A solid foundation in these points will make the difference between a useful model and one that adds no value.

How Do I Use AiDataTaskRunner for This?

AiDataTaskRunner is a tool that simplifies much of the AI integration process through a graphical interface (GUI) within MT5.

The general workflow remains the same, but where it truly adds value is in feature generation, which is usually one of the most tedious and difficult parts to scale.

Problem with the Manual Approach

Traditionally, traders generate features manually within MQL5, which presents several drawbacks:

  1. Difficult maintenance: Hardcoding all features in functions
  2. Lack of scalability: Adding complexity (news, external data, etc.) becomes tedious
  3. Code duplication: Managing multiple models requires multiplying code
  4. Inflexibility: Changing features requires modifying and recompiling the bot

Example of the Manual Approach (Inefficient)

Option 1: Simple features with time structures

MqlDateTime time_struct;
string time = (string)datetime(rates[0].time); // Convert seconds to datetime
TimeToStruct((datetime)StringToTime(time), time_struct);
 
vector x = {rates[0].open,
            rates[0].high, 
            rates[0].low, 
            rates[0].close, 
            time_struct.day, 
            time_struct.day_of_week, 
            time_struct.day_of_year, 
            time_struct.mon};

Option 2: Features based on indicators

string data[50000][12];
int indexx = 0;
 
void getData(){
    double close = iClose(_Symbol, PERIOD_CURRENT, 1);
    double close2 = iClose(_Symbol, PERIOD_CURRENT, 2);
    double close3 = iClose(_Symbol, PERIOD_CURRENT, 3);
    
    double stationary = 1000 * (close - iOpen(_Symbol, PERIOD_CURRENT, 1)) / close;
    double stationary2 = 1000 * (close2 - iOpen(_Symbol, PERIOD_CURRENT, 2)) / close2;
    double stationary3 = 1000 * (close3 - iOpen(_Symbol, PERIOD_CURRENT, 3)) / close3;
    
    double highDistance = 1000 * (close - high) / close;
    double lowDistance = 1000 * (close - low) / close;
    double boxSize = 1000 * (high - low) / close;
    
    double adx[];
    double rsi[];
    double rvi[];
    double sto[];
    
    CopyBuffer(handleAdx, 0, 1, 1, adx);
    CopyBuffer(handleRsi, 0, 1, 1, rsi);
    CopyBuffer(handleRvi, 0, 1, 1, rvi);
    CopyBuffer(handleSto, 0, 1, 1, sto);
    
    data[indexx][0] = DoubleToString(adx[0], 2);
    data[indexx][1] = DoubleToString(rsi[0], 2);
    data[indexx][2] = DoubleToString(rvi[0], 2);
    data[indexx][3] = DoubleToString(sto[0], 2);
    data[indexx][4] = DoubleToString(stationary, 2);
    data[indexx][5] = DoubleToString(boxSize, 2);
    data[indexx][6] = DoubleToString(stationary2, 2);
    data[indexx][7] = DoubleToString(stationary3, 2);
    data[indexx][8] = DoubleToString(highDistance, 2);
    data[indexx][9] = DoubleToString(lowDistance, 2);
    
    indexx++;
}

The Solution: AiDataGenByLeo

Instead of hardcoding features in MQL5, AiDataGenByLeo (custom library) allows you to define features in a specific DSL language (as string or file) that is processed automatically.

Advantages

Scalable: Add complex features without modifying MQL5 Maintainable: Centralized changes in configuration files Reusable: One bot generates data for multiple models Flexible: Supports external data (news, neural networks, etc.)

DSL Syntax Example

name = [RSI Context Matrix]
 
@ Config
{
  cols = 3;
}
 
@ New Matrix(rows=5)
{
  # Generate([0,1,5])
  {
    [Rsi_Valor][](Timeframe=_Period|Period=14|Applied=PRICE_CLOSE|Hide=true)
    [Vidya_Distancia][](Timeframe=_Period|CmoPeriod=9|EmaPeriod=12|Applied=PRICE_CLOSE|Hide=true)
    [StdDev_Normalizado][](Timeframe=_Period|MaPeriod=20|MaShift=0|MaMethod=MODE_SMA|Applied=PRICE_CLOSE|Hide=true)
  }
}

Workflow in AiDataTaskRunner

Define Features

Define your features using the AiDataGenByLeo DSL (in file or string format).

Tab: Data Generation

In the panel, access the data_generation tab to:

  • Select Timeframe and Symbol: Choose which timeframes and assets the data generation bot will run on
  • Configure output files: Define what files (CSV, scalers, etc.) will be generated
  • Define destination folder: Data will be automatically organized in: SymbolFolder/Timeframe/Label_LabelID/

Tab: Workflows (Automation)

Use the workflows tab to create automatic pipelines via YAML:

data_generation:
  symbol: EURUSD
  timeframe: H1
  features: path/to/features.fgblc
  output_format: csv
  
training:
  model_type: decision_tree
  hyperparameters:
    max_depth: 10
    min_samples_split: 5

Train the Model

The panel includes a default Python trainer that uses:

  • Algorithm: Decision Trees
  • Optimization: Optuna + SelectKBest
  • Output: Features ID file (xfeatures_id) Configure and run:
  1. Adjust the trainer's JSON configuration
  2. Run the training
  3. The features ID file is automatically generated

Bot Integration

Once the process is complete:

  1. Integrate the AiDataGenByLeo library into your bot
  2. The bot automatically generates data with the defined features
  3. The model is ready to use

Summary of the Improved Process

Step Manual Method With AiDataTaskRunner
Define Features Hardcode in MQL5 DSL in .fgblc file
Generate Data Manual or scripting Panel → Data Generation
Train Model Custom Python code Panel → Automatic Trainer
Configure Pipeline Multiple scripts YAML in Workflows tab
Maintain Modify code Edit features file
Scalability Difficult Excellent

Complete Step-by-Step Example

For a detailed tutorial with complete examples, see the page: QuickStartPanelUse