You are absolutely correct! My apologies. PositionsTotal() is an MQL5 function. In MQL4, we need to manually count the open positions using OrdersTotal() and iterating through them.
Here's the corrected MQL4 code that defines and uses a function to count open positions:
#property copyright "AI Trading System"
#property link "http://www.example.com"
#property version "1.00"
#property strict
// Input parameters
input int InputLookbackPeriod = 50; // Lookback period
input double InputLearningRate = 0.01; // Learning rate
input int InputTrainingFrequency = 100; // Training frequency
// Constants
#define INPUT_SIZE 5
#define HIDDEN_SIZE 10
#define OUTPUT_SIZE 1
// Global variables for Neural Network
double WeightsInputHidden[INPUT_SIZE][HIDDEN_SIZE];
double WeightsHiddenOutput[HIDDEN_SIZE][OUTPUT_SIZE];
double BiasHidden[HIDDEN_SIZE];
double BiasOutput[OUTPUT_SIZE];
double Momentum[INPUT_SIZE][HIDDEN_SIZE];
double MomentumHidden[HIDDEN_SIZE][OUTPUT_SIZE];
//+------------------------------------------------------------------+
//| Sigmoid activation function |
//+------------------------------------------------------------------+
double Sigmoid(double x)
{
return 1.0 / (1.0 + MathExp(-x));
}
//+------------------------------------------------------------------+
//| Initialize Neural Network |
//+------------------------------------------------------------------+
void InitializeNetwork()
{
// Initialize weights and momentum
for(int i = 0; i < INPUT_SIZE; i++)
{
for(int j = 0; j < HIDDEN_SIZE; j++)
{
WeightsInputHidden[i][j] = (MathRand()/32767.0 - 0.5) * 0.1;
Momentum[i][j] = 0;
}
}
for(int i = 0; i < HIDDEN_SIZE; i++)
{
for(int j = 0; j < OUTPUT_SIZE; j++)
{
WeightsHiddenOutput[i][j] = (MathRand()/32767.0 - 0.5) * 0.1;
MomentumHidden[i][j] = 0;
}
BiasHidden[i] = (MathRand()/32767.0 - 0.5) * 0.1;
}
for(int i = 0; i < OUTPUT_SIZE; i++)
{
BiasOutput[i] = (MathRand()/32767.0 - 0.5) * 0.1;
}
}
//+------------------------------------------------------------------+
//| Forward Propagation |
//+------------------------------------------------------------------+
double ForwardPropagate(double &inputs[])
{
double hidden[HIDDEN_SIZE];
double output = 0;
// Calculate hidden layer
for(int i = 0; i < HIDDEN_SIZE; i++)
{
hidden[i] = BiasHidden[i];
for(int j = 0; j < INPUT_SIZE; j++)
{
hidden[i] += inputs[j] * WeightsInputHidden[j][i];
}
hidden[i] = Sigmoid(hidden[i]);
}
// Calculate output
for(int i = 0; i < HIDDEN_SIZE; i++)
{
output += hidden[i] * WeightsHiddenOutput[i][0];
}
output += BiasOutput[0];
output = Sigmoid(output);
return output;
}
//+------------------------------------------------------------------+
//| Generate AI Features |
//+------------------------------------------------------------------+
void GenerateFeatures(double &features[])
{
// Ensure enough bars are available
if(Bars < InputLookbackPeriod + 2) // Need at least lookbackPeriod + 2 bars for features 1, 2, 3
{
Print("Not enough bars for feature generation.");
// Return some default or zero features, or handle appropriately
for(int i = 0; i < INPUT_SIZE; i++) features[i] = 0.0;
return;
}
// Feature 1: Price momentum
features[0] = (Close[0] - Close[InputLookbackPeriod]) / Close[InputLookbackPeriod];
// Feature 2: Price volatility (standard deviation)
double sum = 0, sumSq = 0;
for(int i = 0; i < InputLookbackPeriod; i++)
{
sum += Close[i];
sumSq += Close[i] * Close[i];
}
double mean = sum / InputLookbackPeriod;
double variance = (sumSq / InputLookbackPeriod) - (mean * mean);
features[1] = MathSqrt(MathAbs(variance)); // Use MathAbs in case of floating point issues
// Feature 3: Price acceleration (change in momentum)
// Need at least 3 bars for this (index 0, 1, 2)
double momentum1 = (Close[0] - Close[1]); // Using absolute price diff for simplicity
double momentum2 = (Close[1] - Close[2]);
features[2] = momentum1 - momentum2;
// Normalize if needed, e.g., features[2] = (momentum1 - momentum2) / Point;
// Feature 4: High/Low ratio relative to current price
features[3] = (High[0] - Low[0]) / Close[0]; // Ratio relative to Close
// Feature 5: Time-based feature (normalized bar index)
features[4] = (double)Bars / (double)InputLookbackPeriod; // Simple normalization
// You might want to normalize all features between 0 and 1 or -1 and 1
// For this basic example, raw values are used, which might not be optimal for the NN.
// Example normalization (min-max scaling, needs min/max values from training data):
// features[i] = (features[i] - min_feature_i) / (max_feature_i - min_feature_i);
}
//+------------------------------------------------------------------+
//| Train Neural Network |
//+------------------------------------------------------------------+
void TrainNetwork(double &inputs[], double target)
{
// Ensure enough bars for training target
if(Bars < 2) return; // Need at least 2 bars for the simple target below
// Forward pass
double hidden[HIDDEN_SIZE];
double output = 0;
double net_hidden[HIDDEN_SIZE]; // Store net inputs before activation for gradient calculation
for(int i = 0; i < HIDDEN_SIZE; i++)
{
net_hidden[i] = BiasHidden[i];
for(int j = 0; j < INPUT_SIZE; j++)
{
net_hidden[i] += inputs[j] * WeightsInputHidden[j][i];
}
hidden[i] = Sigmoid(net_hidden[i]);
}
double net_output = BiasOutput[0];
for(int i = 0; i < HIDDEN_SIZE; i++)
{
net_output += hidden[i] * WeightsHiddenOutput[i][0];
}
output = Sigmoid(net_output);
// Backward pass (Backpropagation with Momentum)
double error = target - output;
double outputGradient = output * (1 - output) * error; // Derivative of Sigmoid * Error
// Update output weights and bias
for(int i = 0; i < HIDDEN_SIZE; i++)
{
// Calculate change with momentum
double deltaWeightHiddenOutput = InputLearningRate * outputGradient * hidden[i];
MomentumHidden[i][0] = 0.9 * MomentumHidden[i][0] + deltaWeightHiddenOutput; // Use 0.9 as momentum factor
WeightsHiddenOutput[i][0] += MomentumHidden[i][0];
}
double deltaBiasOutput = InputLearningRate * outputGradient;
BiasOutput[0] += deltaBiasOutput;
// Calculate hidden layer errors and update input weights/biases
double hiddenGradients[HIDDEN_SIZE];
for(int i = 0; i < HIDDEN_SIZE; i++)
{
// Gradient for hidden layer includes output gradient and derivative of hidden activation
// Error backpropagated from output: outputGradient * WeightsHiddenOutput[i][0]
// Derivative of sigmoid at hidden layer: hidden[i] * (1 - hidden[i])
hiddenGradients[i] = hidden[i] * (1 - hidden[i]) * (outputGradient * WeightsHiddenOutput[i][0]); // Chain rule
}
for(int i = 0; i < HIDDEN_SIZE; i++)
{
double deltaBiasHidden = InputLearningRate * hiddenGradients[i];
BiasHidden[i] += deltaBiasHidden; // No momentum typically applied to hidden biases in basic implementation
for(int j = 0; j < INPUT_SIZE; j++)
{
double deltaWeightInputHidden = InputLearningRate * hiddenGradients[i] * inputs[j];
Momentum[j][i] = 0.9 * Momentum[j][i] + deltaWeightInputHidden;
WeightsInputHidden[j][i] += Momentum[j][i];
}
}
}
//+------------------------------------------------------------------+
//| Count Open Positions (MQL4 equivalent of PositionsTotal) |
//+------------------------------------------------------------------+
int CountOpenPositions()
{
int openPositions = 0;
for (int i = 0; i < OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
// Check if it's a BUY or SELL order (open position)
if (OrderType() == OP_BUY || OrderType() == OP_SELL)
{
openPositions++;
}
}
}
return openPositions;
}
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
InitializeNetwork();
// Seed the random number generator
MathSrand(GetTickCount());
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Close any open positions if needed (optional, use with caution)
// int total = CountOpenPositions();
// for(int i = total - 1; i >= 0; i--)
// {
// if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
// {
// if(OrderType() == OP_BUY) OrderClose(OrderTicket(), OrderLots(), Bid, 3);
// if(OrderType() == OP_SELL) OrderClose(OrderTicket(), OrderLots(), Ask, 3);
// }
// }
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Ensure enough bars are available before proceeding
if(Bars < InputLookbackPeriod + 2)
{
Print("Waiting for enough bars...");
return; // Exit if not enough bars
}
static int barCount = 0;
static datetime lastBarTime = 0;
// Check if a new bar has started
if (lastBarTime != iTime(Symbol(), Period(), 0))
{
lastBarTime = iTime(Symbol(), Period(), 0);
// --- Logic to run ONCE per new bar ---
// Generate features from the completed bar
double features[INPUT_SIZE];
GenerateFeatures(features);
// Forward pass to get prediction for the *next* bar movement
double prediction = ForwardPropagate(features);
// Trading logic
// Calculate lot size based on a small percentage of balance (e.g., 0.1%)
// Ensure minimum lot size and account constraints are met
double lotSize = NormalizeDouble(AccountBalance() * 0.001 / 100000.0, 2); // Risk 0.1% per $100,000 account, adjust as needed
double minLot = MarketInfo(Symbol(), MODE_MINLOT);
double lotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
lotSize = MathMax(minLot, NormalizeDouble(lotSize, MathMax(0, (int)MathLog10(1.0/lotStep)))); // Ensure lot size is valid
// Define minimal prediction thresholds for clearer signals
double buyThreshold = 0.6; // Adjust these based on backtesting
double sellThreshold = 0.4;
int currentPositions = CountOpenPositions();
int ticket = -1;
int magic = 12345; // Unique Magic Number for this EA
// Close losing positions (simple example, implement proper Stop Loss/Take Profit)
// This loop is inefficient on every tick; better to use SL/TP or run less often
// for (int i = OrdersTotal() - 1; i >= 0; i--) {
// if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == magic) {
// if (OrderType() == OP_BUY && (Bid - OrderOpenPrice()) < -10 * Point) { // Example: close if losing 10 pips
// OrderClose(OrderTicket(), OrderLots(), Bid, 3);
// }
// if (OrderType() == OP_SELL && (OrderOpenPrice() - Ask) < -10 * Point) { // Example: close if losing 10 pips
// OrderClose(OrderTicket(), OrderLots(), Ask, 3);
// }
// }
// }
if(currentPositions == 0) // Only open a trade if no positions are open
{
if(prediction > buyThreshold)
{
ticket = OrderSend(Symbol(), OP_BUY, lotSize, Ask, 3, Ask - 200*Point, Ask + 300*Point, "AI Buy", magic, 0, clrGreen); // Example SL/TP
if(ticket < 0) Print("OrderSend failed for BUY. Error: ", GetLastError());
}
else if(prediction < sellThreshold)
{
ticket = OrderSend(Symbol(), OP_SELL, lotSize, Bid, 3, Bid + 200*Point, Bid - 300*Point, "AI Sell", magic, 0, clrRed); // Example SL/TP
if(ticket < 0) Print("OrderSend failed for SELL. Error: ", GetLastError());
}
}
// Periodic training - Train on the result of the *previous* bar
barCount++;
if(barCount >= InputTrainingFrequency)
{
// Generate training features from the bar that just closed (i.e., iTime(..., 1))
double trainingFeatures[INPUT_SIZE];
// We need features calculated *before* the last bar closed to predict that bar's outcome.
// This requires storing historical feature data, which complicates this simple example.
// For simplicity in this example, we'll use features from the *current* bar,
// and train against whether the *last* bar was profitable or not.
// A proper training setup would require storing features from bar N-1 and training against the outcome of bar N.
// Let's simplify: train on current features predicting simple up/down for *next* bar.
// This is not ideal supervised learning, but fits the live nature of OnTick.
GenerateFeatures(trainingFeatures); // Use features from the completed bar (index 0)
// Simple training target: Did the price increase in the last completed bar?
// This is a highly simplified target and may not align with the NN's prediction output.
// A better target would be: did the price move significantly up/down within a future window?
double target = (Close[0] > Open[0]) ? 1.0 : 0.0; // Target 1 if bar closed higher than opened, else 0
// You might need to adjust the target based on what you *want* the prediction to mean (e.g., 1=go up next bar, 0=go down next bar)
Print("Retraining network...");
TrainNetwork(trainingFeatures, target);
barCount = 0;
}
// --- End logic to run ONCE per new bar ---
}
// --- Logic to run ON EVERY TICK (if needed, often empty for bar-based EAs) ---
// You could put stop loss/take profit management here if not using built-in SL/TP
// Or check for closing conditions based on current prediction
// Example: If position is open and prediction strongly reverses, close it.
if (CountOpenPositions() > 0)
{
double features[INPUT_SIZE];
GenerateFeatures(features); // Get features from current tick data
double currentPrediction = ForwardPropagate(features);
for (int i = OrdersTotal() - 1; i >= 0; i--)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == magic)
{
// Check for reversal signal
if (OrderType() == OP_BUY && currentPrediction < sellThreshold) // If BUY and now predicting sell
{
// Optional: Implement a closing logic here
// OrderClose(OrderTicket(), OrderLots(), Bid, 3);
// Print("Closing BUY position on reversal signal.");
}
else if (OrderType() == OP_SELL && currentPrediction > buyThreshold) // If SELL and now predicting buy
{
// Optional: Implement a closing logic here
// OrderClose(OrderTicket(), OrderLots(), Ask, 3);
// Print("Closing SELL position on reversal signal.");
}
// Check for simple profit target (if not using built-in TP)
// if (OrderType() == OP_BUY && (Bid - OrderOpenPrice()) >= 100 * Point && OrderTakeProfit() == 0) { // Example: close at 100 pips profit if no TP set
// OrderClose(OrderTicket(), OrderLots(), Bid, 3);
// }
// if (OrderType() == OP_SELL && (OrderOpenPrice() - Ask) >= 100 * Point && OrderTakeProfit() == 0) { // Example: close at 100 pips profit if no TP set
// OrderClose(OrderTicket(), OrderLots(), Ask, 3);
// }
}
}
}
// --- End logic to run ON EVERY TICK ---
}
Changes Made:
CountOpenPositions() Function: Added a new function CountOpenPositions() that iterates through OrdersTotal() and counts orders where OrderType() is either OP_BUY or OP_SELL. This is the correct MQL4 way to check for open positions.
- Replaced
PositionsTotal(): Replaced all instances of PositionsTotal() with the call to the new CountOpenPositions() function.
- Array Access: Switched from
iClose/iHigh/iLow functions with 0 shift to the standard MQL4 price arrays Close[0], High[0], Low[0], etc. This is generally more efficient for accessing recent bar data. Added checks for Bars < ... to prevent errors when not enough historical data is loaded.
- Tick vs Bar Logic: Moved the main trading logic (feature generation, prediction, trade decision, training) inside a check for a new bar (
lastBarTime != iTime(...)). This ensures the AI processes information and makes decisions only once per completed bar, which is typical and avoids excessive computation on every single tick. The closing logic can still run on every tick if desired (as shown in the commented section).
- Feature
features[2] Calculation: Corrected the calculation for price acceleration to use Close[0], Close[1], Close[2].
- Normalization Note: Added a comment about the importance of normalizing features, which is crucial for Neural Network training but complex to implement fully without pre-analysis of data ranges. The current features are raw values.
- Training Target Note: Added comments explaining the simplification of the training target and the ideal (but more complex) approach of storing historical features.
- Lot Sizing: Modified lot sizing to be dynamic based on account balance. Adjust the risk percentage (0.001) and the denominator (100000.0) according to your actual risk tolerance and account size.
- Magic Number: Added a
magic number to identify trades opened by this specific EA, which is good practice.
- OrderSend Check: Added
if(ticket < 0) Print("OrderSend failed...") to see if the order placement was successful.
- Example SL/TP: Added basic Stop Loss and Take Profit levels to the
OrderSend calls as a starting point for risk management. You adjust these or implement more sophisticated methods.
This corrected version should compile and run in MQL4, addressing the PositionsTotal error and improving the structure. Remember that achieving high accuracy and low drawdown with a simple NN and limited features without extensive training data and optimization within MQL4 constraints is very difficult and requires significant further development and testing.