Ai in Simple Language

Shahryar Yeganeh Hajahmadi  

Building artificial intelligence in MetaQuotes involves developing algorithms that can learn from data and make predictions or decisions based on that data. In order to build AI in MetaQuotes, you will need to have a solid understanding of machine learning, programming, and the MetaQuotes platform. First, we need to define the problem that we want to solve. For example, we might want to use historical data to predict the price of a particular financial instrument. To do this, we will use a machine learning algorithm called a neural network. Here's an example of how to build a neural network in Python using the Keras library:


from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))


  • In this code, we create a neural network model with three layers: an input layer, a hidden layer, and an output layer. The input layer has 12 neurons, the hidden layer has 8 neurons, and the output layer has 1 neuron. The "relu" activation function is used in the hidden layers, while the sigmoid function is used in the output layer. Next, we need to gather data to train the neural network. We can do this by downloading historical price data for the financial instrument that we want to predict. We will use this data to train the neural network to make predictions. Here's an example of how to download historical price data using MetaTrader 5 platform:


import MetaTrader5 as mt5
import pandas as pd

symbol = 'EURUSD'
timeframe = mt5.TIMEFRAME_H1

mt5.initialize()
rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, 10000)
mt5.shutdown()

df = pd.DataFrame(rates)


  • In this code, we use the copy_rates_from_pos function to download the last 10,000 bars of price data for the EURUSD currency pair on a 1-hour timeframe. The data is returned as a list of dictionaries, which we convert to a pandas DataFrame for easier manipulation. Now that we have our data, we need to preprocess it before using it to train the neural network. We might want to normalize the data, split it into training and testing sets, and preprocess it in other ways. Here's an example of how to preprocess the data using the scikit-learn library:


from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split

scaler = MinMaxScaler(feature_range=(0, 1))
scaled = scaler.fit_transform(df['close'].values.reshape(-1, 1))

X = []
y = []

for i in range(60, len(df)):
    X.append(scaled[i-60:i, 0])
    y.append(scaled[i, 0])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)


  • In this code, we use the MinMaxScaler function to normalize the close price data to a range of 0 to 1. We then split the data into 60-day windows and use them as input features for the neural network. The output labels are the next day's close price. We also split the data into training and testing sets using the train_test_split function. Finally, we can use the preprocessed data to train the neural network using the fit method. Here's an example of how to train the model:


model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=50, batch_size=32,validation_data=(X_test, y_test))


    • In this code, we use the `compile` method to configure the neural network with a binary cross-entropy loss function, an Adam optimizer, and an accuracy metric. We then use the `fit` method to train the model for 50 epochs with a batch size of 32, and we validate the model using the testing set. After the model is trained, we can use it to make predictions on new data. Here's an example of how to use the trained model to predict the next day's price:


last_60_days = df['close'].tail(60).values.reshape(1, -1)
last_60_days_scaled = scaler.transform(last_60_days)

prediction = model.predict(last_60_days_scaled)
predicted_price = scaler.inverse_transform(prediction)[0][0]


  • In this code, we use the last 60 days of close price data to make a prediction for the next day's price. We scale the data using the `MinMaxScaler`, pass it through the neural network using the `predict` method, and then scale the prediction back to the original price range using the `inverse_transform` method.



Here is the complete example:


import pandas as pd
import numpy as np
import talib
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import Adam

# Load historical price data
df = pd.read_csv('AAPL.csv')

# Define technical indicators
df['sma20'] = talib.SMA(df['Close'], timeperiod=20)
df['sma50'] = talib.SMA(df['Close'], timeperiod=50)
df['rsi'] = talib.RSI(df['Close'], timeperiod=14)
df['macd'], df['macd_signal'], df['macd_hist'] = talib.MACD(df['Close'], fastperiod=12, slowperiod=26, signalperiod=9)

# Preprocess the data
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(df[['Close', 'sma20', 'sma50', 'rsi', 'macd', 'macd_signal', 'macd_hist']])

X_train = []
y_train = []

# Generate training data
for i in range(50, len(scaled_data)):
    X_train.append(scaled_data[i-50:i])
    y_train.append(scaled_data[i, 0])

X_train, y_train = np.array(X_train), np.array(y_train)

# Build the neural network
model = Sequential()
model.add(Dense(128, input_shape=(X_train.shape[1], X_train.shape[2]), activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1))
model.compile(optimizer=Adam(lr=0.0005), loss='mean_squared_error')

# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=32)

# Use the model to predict future prices
last_50_days = df[-50:].values
last_50_days_scaled = scaler.transform(last_50_days)
X_test = []
X_test.append(last_50_days_scaled)
X_test = np.array(X_test)

predicted_price = model.predict(X_test)
predicted_price = scaler.inverse_transform(predicted_price)

# Make trading decisions based on the predicted price
if predicted_price > df.iloc[-1]['Close']:
    print('Buy')
elif predicted_price < df.iloc[-1]['Close']:
    print('Sell')
else:
    print('Hold')


If you want to try another example, keep reading!


  • In this example, we'll walk through the process of building an RNN model to predict the price of Apple stock. We'll use historical price data and a popular deep learning library called TensorFlow to build and train the model.First, let's start by collecting historical price data for Apple stock. We'll use the Yahoo Finance API to download the data. We'll collect the daily closing price for the past 5 years.


import yfinance as yf

# Download Apple stock price data
ticker = "AAPL"
data = yf.download(ticker, period="5y", interval="1d", group_by='ticker')


  • Next, we'll preprocess the data to prepare it for use in the RNN model. We'll split the data into training and testing sets, and then normalize the data so that all values are between 0 and 1.

# Split data into training and testing sets
train_data = data.iloc[:-30]
test_data = data.iloc[-30:]

# Normalize the data
train_min = train_data.min()
train_max = train_data.max()
train_data = (train_data - train_min) / (train_max - train_min)
test_data = (test_data - train_min) / (train_max - train_min)


  • Now that we have our preprocessed data, we can start building the RNN model. We'll use TensorFlow's Keras API to build the model. We'll create a simple RNN model with one input layer, one RNN layer, and one output layer.


from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, SimpleRNN

# Build the RNN model
model = Sequential([
    SimpleRNN(32, input_shape=(5, 1)),
    Dense(1)
])

# Compile the model
model.compile(loss="mse", optimizer="adam")


  • The input to the RNN model is a sequence of the past 5 closing prices for Apple stock, and the output is the predicted closing price for the next day. We'll train the model on batches of 32 sequences at a time.


# Prepare training data
X_train = []
y_train = []
for i in range(5, len(train_data)):
    X_train.append(train_data.iloc[i-5:i].to_numpy())
    y_train.append(train_data.iloc[i].to_numpy())

X_train = np.array(X_train)
y_train = np.array(y_train)

# Train the model
model.fit(X_train, y_train, batch_size=32, epochs=50)


  • Finally, we'll use the trained RNN model to predict the closing prices for the test data. We'll evaluate the performance of the model by calculating the mean squared error (MSE) between the predicted and actual closing prices.


# Prepare test data
X_test = []
y_test = []
for i in range(5, len(test_data)):
    X_test.append(test_data.iloc[i-5:i].to_numpy())
    y_test.append(test_data.iloc[i].to_numpy())

X_test = np.array(X_test)
y_test = np.array(y_test)

# Use the model to predict prices
predictions = model.predict(X_test)

# Calculate MSE
mse = ((predictions - y_test) ** 2).mean()
print("Mean Squared Error:", mse)



Here is the complete code:


import yfinance as yf

# Download Apple stock price data
ticker = "AAPL"
data = yf.download(ticker, period="5y", interval="1d", group_by='ticker')

# Split data into training and testing sets
train_data = data.iloc[:-30]
test_data = data.iloc[-30:]

# Normalize the data
train_min = train_data.min()
train_max = train_data.max()
train_data = (train_data - train_min) / (train_max - train_min)
test_data = (test_data - train_min) / (train_max - train_min)

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, SimpleRNN

# Build the RNN model
model = Sequential([
    SimpleRNN(32, input_shape=(5, 1)),
    Dense(1)
])

# Compile the model
model.compile(loss="mse", optimizer="adam")

# Prepare training data
X_train = []
y_train = []
for i in range(5, len(train_data)):
    X_train.append(train_data.iloc[i-5:i].to_numpy())
    y_train.append(train_data.iloc[i].to_numpy())

X_train = np.array(X_train)
y_train = np.array(y_train)

# Train the model
model.fit(X_train, y_train, batch_size=32, epochs=50)

# Prepare test data
X_test = []
y_test = []
for i in range(5, len(test_data)):
    X_test.append(test_data.iloc[i-5:i].to_numpy())
    y_test.append(test_data.iloc[i].to_numpy())

X_test = np.array(X_test)
y_test = np.array(y_test)

# Use the model to predict prices
predictions = model.predict(X_test)

# Calculate MSE
mse = ((predictions - y_test) ** 2).mean()
print("Mean Squared Error:", mse)


import pandas as pd
import numpy as np
import gym

# Define the trading environment
class TradingEnvironment(gym.Env):
    def __init__(self, data, initial_budget):
        self.data = data
        self.initial_budget = initial_budget
        self.current_budget = initial_budget
        self.shares_held = 0
        self.current_step = 0
        self.total_steps = len(data) - 1
        self.reward_range = (-1, 1)
        self.action_space = gym.spaces.Discrete(3) # 0: Sell, 1: Hold, 2: Buy
        self.observation_space = gym.spaces.Box(low=0, high=1, shape=(6,))

    def _next_observation(self):
        obs = np.array([
            self.data.loc[self.current_step, 'Open'] / self.initial_budget,
            self.data.loc[self.current_step, 'High'] / self.initial_budget,
            self.data.loc[self.current_step, 'Low'] / self.initial_budget,
            self.data.loc[self.current_step, 'Close'] / self.initial_budget,
            self.current_budget / self.initial_budget,
            self.shares_held / self.total_shares
        ])
        return obs

    def _take_action(self, action):
        current_price = self.data.loc[self.current_step, 'Close']
        if action == 0: # Sell
            if self.shares_held == 0:
                reward = -1
            else:
                sell_price = self.shares_held * current_price
                self.current_budget += sell_price
                self.shares_held = 0
                reward = (sell_price - self.initial_budget) / self.initial_budget
        elif action == 1: # Hold
            reward = 0
        elif action == 2: # Buy
            if self.current_budget < current_price:
                reward = -1
            else:
                buy_price = self.current_budget // current_price
                self.shares_held += buy_price
                self.current_budget -= buy_price * current_price
                reward = (self.initial_budget - buy_price * current_price) / self.initial_budget
        return reward

    def step(self, action):
        self.current_step += 1
        reward = self._take_action(action)
        obs = self._next_observation()
        done = self.current_step == self.total_steps
        return obs, reward, done, {}

    def reset(self):
        self.current_budget = self.initial_budget
        self.shares_held = 0
        self.current_step = 0
        return self._next_observation()

# Load historical price data
df = pd.read_csv('AAPL.csv')

# Define the reinforcement learning algorithm
env = TradingEnvironment(df, 1000)
state_size = env.observation_space.shape[0]
action_size = env.action_space.n

from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam

def build_model(state_size, action_size):
    model = Sequential()
    model.add(Dense(64, input_dim=state_size, activation='relu'))
    model.add(Dense(32, activation='relu'))
    model.add(Dense(action_size, activation='linear'))
    model.compile(loss='mse', optimizer=Adam())
    return model

model = build_model(state_size, action_size)




// Define inputs
input int fastMA = 10;
input int slowMA = 20;

// Define global variables
int crossAbove, crossBelow;

// Initialize the EA
void OnInit()
{
    // Set the indicators
    IndicatorSetString(INDICATOR_SHORTNAME, "SMA Crossover");
    IndicatorSetInteger(INDICATOR_DIGITS, MarketInfo(_Symbol, MODE_DIGITS));
    IndicatorSetInteger(INDICATOR_LEVELS, 2);

    // Initialize the variables
    crossAbove = crossBelow = 0;
}

// Start the EA
void OnTick()
{
    // Get the current values of the fast and slow SMAs
    double fastSMA = iMA(_Symbol, 0, fastMA, 0, MODE_SMA, PRICE_CLOSE, 0);
    double slowSMA = iMA(_Symbol, 0, slowMA, 0, MODE_SMA, PRICE_CLOSE, 0);

    // Check for a bullish crossover
    if(fastSMA > slowSMA && crossBelow == 1)
    {
        // Buy at market price
        OrderSend(_Symbol, OP_BUY, 0.1, Ask, 3, 0, 0, "SMA Buy", MagicNumber);

        // Reset the crossBelow variable
        crossBelow = 0;

        // Set the crossAbove variable
        crossAbove = 1;
    }

    // Check for a bearish crossover
    if(fastSMA < slowSMA && crossAbove == 1)
    {
        // Sell at market price
        OrderSend(_Symbol, OP_SELL, 0.1, Bid, 3, 0, 0, "SMA Sell", MagicNumber);

        // Reset the crossAbove variable
        crossAbove = 0;

        // Set the crossBelow variable
        crossBelow = 1;
    }
}



  • This EA uses the iMA() function to calculate the values of the fast and slow SMAs, and then checks for a crossover between the two. If a bullish crossover occurs (i.e., the fast SMA crosses above the slow SMA) and the crossBelow variable is set to 1 (indicating that a bearish crossover occurred on the previous tick), the EA sends a buy order at the market price. If a bearish crossover occurs (i.e., the fast SMA crosses below the slow SMA) and the crossAbove variable is set to 1 (indicating that a bullish crossover occurred on the previous tick), the EA sends a sell order at the market price. The MagicNumber variable is used to identify the orders placed by the EA.

Reason: