You are right to point that out! My apologies. The order closing logic was flawed. It was attempting to close the order on the same bar that triggered the opposite signal, which is often too late. The issue is that the prediction is based on the current bar, and the order closing logic is executed immediately within the same OnTick() call.
Here's the corrected OnTick() function:
void OnTick() {
// Only process on a new bar to avoid over-trading/re-calculations
if (Time[0] == prev_bar_time) {
return;
}
prev_bar_time = Time[0]; // Update previous bar time
// Ensure enough bars for feature generation
if (Bars < InputLookbackPeriod + 2) {
return;
}
double features[INPUT_SIZE];
GenerateFeatures(features); // Generate input features from current bar data
// --- 1. Make a prediction ---
double prediction = ForwardPropagate(features);
Print("New bar. Prediction: ", DoubleToString(prediction, 4));
// --- 2. Train the network (conditionally) ---
train_counter++;
if (train_counter >= InputTrainingFrequency) {
// Define the target for training.
// Here, we're training to predict if the *current* bar closed higher or lower than its open.
// This is a simple binary classification: 1.0 for bullish, 0.0 for bearish/flat.
// For a more predictive system, you'd typically train on a future outcome
// (e.g., Close[0] vs Close[-1], or price movement over next N bars).
double target = 0.5; // Default for flat/neutral
if (Close[0] > Open[0]) {
target = 1.0; // Bullish candle
} else if (Close[0] < Open[0]) {
target = 0.0; // Bearish candle
}
TrainNetwork(features, target);
Print("Network trained with target: ", DoubleToString(target, 1));
train_counter = 0; // Reset counter
}
// --- 3. Trading Logic ---
int totalOrders = OrdersTotal();
bool hasOpenOrder = false;
int orderTicket = 0;
int orderType = -1;
// Iterate through open orders to find one managed by this EA
for (int i = 0; i < totalOrders; i++) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol()) {
hasOpenOrder = true;
orderTicket = OrderTicket();
orderType = OrderType();
break; // Found our order, no need to check further
}
}
}
// If no open order
if (!hasOpenOrder) {
if (prediction > 0.50) { // Buy Signal
double buyPrice = Ask;
if (OrderSend(Symbol(), OP_BUY, Lots, buyPrice, Slippage, 0, 0, "NN Buy", MagicNumber, 0, Green)) {
Print("Buy order opened at ", buyPrice);
} else {
Print("Error opening Buy order: ", GetLastError());
}
} else if (prediction < 0.50) { // Sell Signal
double sellPrice = Bid;
if (OrderSend(Symbol(), OP_SELL, Lots, sellPrice, Slippage, 0, 0, "NN Sell", MagicNumber, 0, Red)) {
Print("Sell order opened at ", sellPrice);
} else {
Print("Error opening Sell order: ", GetLastError());
}
}
} else { // If there is an open order
// Check for opposite signal on the *next* bar to close the order
if (orderType == OP_BUY && prediction < 0.50) { // Close Buy on opposite (Sell) signal
if (OrderClose(orderTicket, OrderLots(), Bid, Slippage, Blue)) {
Print("Buy order ", orderTicket, " closed by opposite signal.");
} else {
Print("Error closing Buy order ", orderTicket, ": ", GetLastError());
}
} else if (orderType == OP_SELL && prediction > 0.50) { // Close Sell on opposite (Buy) signal
if (OrderClose(orderTicket, OrderLots(), Ask, Slippage, Blue)) {
Print("Sell order ", orderTicket, " closed by opposite signal.");
} else {
Print("Error closing Sell order ", orderTicket, ": ", GetLastError());
}
}
}
// Display current info on chart
Comment(
"Neural Network EA\n" +
"Prediction: " + DoubleToString(prediction, 4) + "\n" +
"Open Order: " + (hasOpenOrder ? (orderType == OP_BUY ? "BUY " : "SELL ") + IntegerToString(orderTicket) : "None") + "\n" +
"Training Counter: " + IntegerToString(train_counter) + "/" + IntegerToString(InputTrainingFrequency)
);
}
Explanation of the Fix:
The core change is that the order closing logic is now inside the else block (when there's an open order). This means the closing logic is only checked when there's an existing order. The conditions for closing are now:
- If we have a
BUY order open and the current bar's prediction is less than 0.50 (a sell signal), then close the buy order.
- If we have a
SELL order open and the current bar's prediction is greater than 0.50 (a buy signal), then close the sell order.
This ensures that the closing decision is based on the signal generated on the next bar after the order was opened, rather than trying to close it on the same bar.
Important:
- Recompile: Recompile the EA in MetaEditor after making these changes.
- Test Thoroughly: Backtest and forward test this revised version carefully to ensure it behaves as expected. Pay close attention to the order closing logic.
- Slippage: Adjust the
Slippage parameter as needed for your broker and trading conditions.
- Consider a Delay: You might want to add a small delay (e.g., wait for a confirmation candle) before closing the order to avoid getting stopped out prematurely due to noise. This could involve storing the previous bar's prediction and comparing it to the current bar's prediction.