Kindly Request Some More Eyes On My OrderSend 4756 Error

 
Dear MQL5 Community, I kindly request another pair of eyes on my 4756 ordersend issue! :)

Not a coder by trade, I typically work with freelancers. However with a bit of free time this summer I decided to try and work on a basic MT5 MA cross system on my own.

I've gotten more or less to the "end" in that it compiles and seems to run. However, it cannot complete any trades. I consistently get the "OrderSend failed with error(4756)", but so far as I can tell everything appears to be correct.

I have attached the code here below. Please note that there are some calls to some divergence functions (strategy mode 3), but these can be ignored.

The code has a number of print statements for debugging, and I have also attached a screenshot of a failed trade showing them:
a) "0" comments are from before the MqlTradeRequest structure definition
b) "1" comments are from after the MqlTradeRequest structure definition and normalization of data, to ensure consistency before the order send function.

In the image, we can see:
1) the candle where the trade was sent
2) the ask price at the time
3) the SL (50 points) and the TP (100 points)
4) the volume

Note that the OP_BUY and OP_SELL are 0 and 1 respectively for the operation types.

I have also tested this on two different terminals using two different brokers during normal trading hours. The pair used was EURUSD, so nothing exotic.

Thoughts on what might be blocking me here? Happy for any pointers!

//+------------------------------------------------------------------+
#property copyright "X"
#property link          "https://www.mql5.com"
#property version       "1.00"

// Declare order operation constants
#define OP_BUY  0
#define OP_SELL 1

// Define input parameters
input int fastSMA = 10;
input int slowSMA = 50;
input int rsiPeriod = 14;
input int rsiThresholdLong = 30;
input int rsiThresholdShort = 70;
input double stopLossPips = 50;
input double takeProfitPips = 100;
input string startTime = "00:00";
input string endTime = "23:59";
input int trailingStop = 20;
input int StrategyMode = 1; 
input bool moneyManagement = true; 
input double stepForAccountSize = 10000; 
input double steppedLotSize = 0.1;

bool sellFlag = false;
bool buyFlag = false;

int previousBarsCount = -1;  // Add this global variable to track the previous Bars count

//+------------------------------------------------------------------+
int OnInit()
{
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
}

//+------------------------------------------------------------------+
void OnTick()
{
    if (!IsTradingTime())
        return;

    // Check if a new bar has started
    int currentBarsCount = Bars(_Symbol, _Period);
    if (currentBarsCount == previousBarsCount)
        return; // If not, exit the function
    previousBarsCount = currentBarsCount; // Update the previous bars count for the next tick

    double fastMA[3], slowMA[3], closeArray[3];
    if(!GetMovingAverages(fastMA, slowMA) || !GetCloseData(closeArray))
        return;

    if (StrategyMode == 1 || StrategyMode == 3)
    {
        if (fastMA[2] < slowMA[2] && fastMA[1] > slowMA[1])
        {
            sellFlag = true;
            buyFlag = false;
        }

        if (fastMA[2] > slowMA[2] && fastMA[1] < slowMA[1])
        {
            buyFlag = true;
            sellFlag = false;
        }

        if (sellFlag && closeArray[1] < fastMA[2])
        {
            if (StrategyMode == 1 || (StrategyMode == 3 && iRSI(Symbol(), 0, rsiPeriod, PRICE_CLOSE) < rsiThresholdShort && CheckBearishDivergence()))
            {
                Trade(OP_SELL);
                sellFlag = false; 
            }
        }
        else if (buyFlag && closeArray[1] > fastMA[2])
        {
            if (StrategyMode == 1 || (StrategyMode == 3 && iRSI(Symbol(), 0, rsiPeriod, PRICE_CLOSE) > rsiThresholdLong && CheckBullishDivergence()))
            {
                Trade(OP_BUY);
                buyFlag = false; 
            }
        }
    }
}

bool GetMovingAverages(double &fastMA[], double &slowMA[])
{
    int handleFastMA = iMA(Symbol(), 0, fastSMA, 0, MODE_SMA, PRICE_CLOSE);
    int handleSlowMA = iMA(Symbol(), 0, slowSMA, 0, MODE_SMA, PRICE_CLOSE);

    if(CopyBuffer(handleFastMA, 0, 1, 3, fastMA) <= 0)
    {
        Print("Failed to copy fastMA. Error code: ", GetLastError());
        return false;
    }
    if(CopyBuffer(handleSlowMA, 0, 1, 3, slowMA) <= 0)
    {
        Print("Failed to copy slowMA. Error code: ", GetLastError());
        return false;
    }
    return true;
}

bool GetCloseData(double &closeArray[])
{
    if (CopyClose(Symbol(), 0, 0, 3, closeArray) <= 0)
    {
        Print("Failed to copy close prices. Error code: ", GetLastError());
        return false;
    }
    return true;
}

void Trade(int operation)
{
    double lotSize;
    
    if(moneyManagement) 
    {
        double accountSize = AccountInfoDouble(ACCOUNT_BALANCE);
        lotSize = steppedLotSize * (accountSize / stepForAccountSize);
    } 
    else 
    {
        lotSize = steppedLotSize;
    }

    // Retrieve broker's limitations for lot sizes
    double minLot = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MIN);
    double maxLot = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_MAX);
    double lotStep = SymbolInfoDouble(Symbol(), SYMBOL_VOLUME_STEP);

    // Ensure the lot size isn't less than the minimum
    if (lotSize < minLot)
        lotSize = minLot;

    // Ensure the lot size isn't more than the maximum
    if (lotSize > maxLot)
        lotSize = maxLot;

    // Adjust the lot size to fit the step size
    lotSize = minLot + ((int)((lotSize - minLot) / lotStep)) * lotStep;

    double bid, ask;
    MqlTick last_tick;
    if(SymbolInfoTick(Symbol(), last_tick))
    {
        bid = last_tick.bid;
        ask = last_tick.ask;
    }

    double slPrice, tpPrice;
    if (operation == OP_BUY)
    {
        slPrice = bid - stopLossPips * SymbolInfoDouble(Symbol(), SYMBOL_POINT);
        tpPrice = ask + takeProfitPips * SymbolInfoDouble(Symbol(), SYMBOL_POINT);
    }
    else
    {
        slPrice = ask + stopLossPips * SymbolInfoDouble(Symbol(), SYMBOL_POINT);
        tpPrice = bid - takeProfitPips * SymbolInfoDouble(Symbol(), SYMBOL_POINT);
    }

    Print("Volume 0: ", lotSize);
    Print("Priceask 0: ", ask);
    Print("Pricebid 0: ", bid);
    Print("TP0: ", tpPrice);
    Print("SL0: ", slPrice);

    MqlTradeRequest request;
    request.action = TRADE_ACTION_DEAL;
    request.symbol = Symbol();
    request.volume = lotSize;
    request.type = (ENUM_ORDER_TYPE)operation;
    request.price = (operation == OP_BUY) ? ask : bid;
    request.sl = slPrice;
    request.tp = tpPrice;
    request.type_filling = (ENUM_ORDER_TYPE_FILLING)ORDER_FILLING_FOK;

    //Normalize the prices
    int decimal_places = SymbolInfoInteger(Symbol(), SYMBOL_DIGITS);
    request.price = NormalizeDouble((operation == OP_BUY) ? ask : bid, decimal_places);
    request.sl = NormalizeDouble(slPrice, decimal_places);
    request.tp = NormalizeDouble(tpPrice, decimal_places);
    request.volume = NormalizeDouble(lotSize, 2); // Round to 2 decimal places

    Print("decimals: ",decimal_places);
    Print("Volume1: ", request.volume);
    Print("Price1: ", request.price);
    Print("TP1: ", request.tp);
    Print("SL1: ", request.sl);
    Print("Request Type: ", request.type);

    MqlTradeResult result;
    if (!OrderSend(request, result))
    {
    PrintFormat("OrderSend failed with error(%d)", GetLastError());
    PrintFormat("Requested OP: %d | Volume: %f | Price: %f | SL: %f | TP: %f", operation, request.volume, request.price, request.sl, request.tp);
    }
}

bool IsTradingTime()
{
    MqlDateTime currentStruct;
    MqlDateTime startStruct;
    MqlDateTime endStruct;

    TimeToStruct(TimeCurrent(), currentStruct);
    TimeToStruct(StringToTime(startTime), startStruct);
    TimeToStruct(StringToTime(endTime), endStruct);

    if ((currentStruct.hour > startStruct.hour) || (currentStruct.hour == startStruct.hour && currentStruct.min >= startStruct.min))
    {
        if ((currentStruct.hour < endStruct.hour) || (currentStruct.hour == endStruct.hour && currentStruct.min <= endStruct.min))
            return true;
    }

    return false;
}

bool CheckBullishDivergence()
{
    double priceHighPrev = iHigh(Symbol(), 0, 1);
    double rsiHighPrev = iRSI(Symbol(), 0, rsiPeriod, 1);

    return (priceHighPrev < iHigh(Symbol(), 0, 0) && rsiHighPrev > iRSI(Symbol(), 0, rsiPeriod, 0));
}

bool CheckBearishDivergence()
{
    double priceLowPrev = iLow(Symbol(), 0, 1);
    double rsiLowPrev = iRSI(Symbol(), 0, rsiPeriod, 1);

    return (priceLowPrev > iLow(Symbol(), 0, 0) && rsiLowPrev < iRSI(Symbol(), 0, rsiPeriod, 0));
}
//-------------------------------END-------------------------------
Files:
imageA.png  81 kb
 
That's ChatGPT code right ? (or build using some similar tool).
 
Alain Verleyen #:
That's ChatGPT code right ? (or build using some similar tool).

Hi Alain, it is.

TBH I found it to be tremendously useful. Not for outright coding, since so far as I can tell it can't do that very well and generates a lot of errors by mixing languages and sometimes it makes things up. Nonetheless when used in pieces like function by function, it is good at:
1) explaining functions and logic.
2) providing code and logic suggestions, helping suggest efficiencies.
3) debugging, to a certain extent, by offering suggestions on why things may not work.

I've found that all of that together has increased my understanding of the language considerably over the past couple of weeks, in a much more accessible fashion than simply reading the documentation here. While I can read code, it's not my "bread and butter" so I need a crutch basically to help me along.

That being said, it helped me through a lot of bugs but does not seem to be able to help me at this (I hope) last issue. At the end of the day experienced human coders are still required :)

Any thoughts on what the issue could be?

In parallel, I'm curious to know what made you think it might be an gpt generated code?

Have a great evening,

Cornelius

 

Why ChatGPT?

It is looking for what you can find too!
But if you find it here (e.g.: https://www.mql5.com/en/search#!keyword=ma%20cross), it will probably run, while ChatGPT will most likely never run.
Bear in mind there's virtually nothing that hasn't already been programmed for MT4/MT5 and is ready for you - copy & paste the fastest way to program :)

 
Cornelius Alexius Zuend #:

Hi Alain, it is.

TBH I found it to be tremendously useful. Not for outright coding, since so far as I can tell it can't do that very well and generates a lot of errors by mixing languages and sometimes it makes things up. Nonetheless when used in pieces like function by function, it is good at:
1) explaining functions and logic.
2) providing code and logic suggestions, helping suggest efficiencies.
3) debugging, to a certain extent, by offering suggestions on why things may not work.

I've found that all of that together has increased my understanding of the language considerably over the past couple of weeks, in a much more accessible fashion than simply reading the documentation here. While I can read code, it's not my "bread and butter" so I need a crutch basically to help me along.

That being said, it helped me through a lot of bugs but does not seem to be able to help me at this (I hope) last issue. At the end of the day experienced human coders are still required :)

Any thoughts on what the issue could be?

In parallel, I'm curious to know what made you think it might be an gpt generated code?

Have a great evening,

Cornelius

It's actually useless from my point of view. Of course, as a professional coder, it's hard for me to put myself in your shoes, but I am trying to understand, so thank you for the explanation.

This code will never work and to make it working you would have to learn the language or rely on someone else to fix it for you. The main issue is : it's a mix of MQL4 and MQL5 which will not run either on MT4 or MT5.

In parallel, I'm curious to know what made you think it might be an gpt generated code?

It's obvious. It's like listening someone talking a foreign language, if this language is natural for you, you will immediately know it's not a native people using its mother language, but you will also recognize the accent used and where the person is coming from.

 
Alain Verleyen #:

It's actually useless from my point of view. Of course, as a professional coder, it's hard for me to put myself in your shoes, but I am trying to understand, so thank you for the explanation.

This code will never work and to make it working you would have to learn the language or rely on someone else to fix it for you. The main issue is : it's a mix of MQL4 and MQL5 which will not run either on MT4 or MT5.

It's obvious. It's like listening someone talking a foreign language, if this language is natural for you, you will immediately know it's not a native people using its mother language, but you will also recognize the accent used and where the person is coming from.

Hi Alain, thanks for taking the time I appreciate being able to discuss it.

" It's actually useless from my point of view. " --> made me laugh ;)

" It's obvious. It's like listening someone talking a foreign language, ... recognize the accent used and where the person is coming from. " --> very interesting and as someone who speaks a couple, I fully understand thanks for that example.

" The main issue is : it's a mix of MQL4 and MQL5 which will not run either on MT4 or MT5 " --> insightful thank you. There were absolutely some cases where it was suggesting things that were MQL4, however these were only obvious to me when the compiler returned an error and I investigated the specific case. You're saying that there are still some MQL4 functions in the above code? That's really interesting since it seems to compile as an MT5 code.

Additionally, all of the individual elements appear to be correct up to the order send, the price values, SL, TP etc.

For the purpose of discussion (and food for thought) I also created a custom indicator using the same process. It is a lot simpler, perhaps, and maybe it was the luck of the "gpt draw", however it is functioning correctly on a live chart so it seems that this Frankenstein method of code generation can still bear fruit.

As the non native speaker in foreign lands, my goal is simply to be understood and get what I need (dos cervezas por favor). On the other hand, I can appreciate that other people's attempts to speak the language can be painful to watch -> thanks for being patient :)

 
You should use available classes in mql5 . Like Trade class… is easier and you don’t need to understand how is opening the trade… 😁… Trade.Buy() … and it will do all the work for you 
 
Daniel Cioca #:
You should use available classes in mql5 . Like Trade class… is easier and you don’t need to understand how is opening the trade… 😁… Trade.Buy() … and it will do all the work for you 
Trade.Buy(), eh?


Thanks for the tip Daniel, I'll check it out!

 
Cornelius Alexius Zuend #:

Hi Alain, thanks for taking the time I appreciate being able to discuss it.

" It's actually useless from my point of view. " --> made me laugh ;)

" It's obvious. It's like listening someone talking a foreign language, ... recognize the accent used and where the person is coming from. " --> very interesting and as someone who speaks a couple, I fully understand thanks for that example.

" The main issue is : it's a mix of MQL4 and MQL5 which will not run either on MT4 or MT5 " --> insightful thank you. There were absolutely some cases where it was suggesting things that were MQL4, however these were only obvious to me when the compiler returned an error and I investigated the specific case. You're saying that there are still some MQL4 functions in the above code? That's really interesting since it seems to compile as an MT5 code.

Additionally, all of the individual elements appear to be correct up to the order send, the price values, SL, TP etc.

For the purpose of discussion (and food for thought) I also created a custom indicator using the same process. It is a lot simpler, perhaps, and maybe it was the luck of the "gpt draw", however it is functioning correctly on a live chart so it seems that this Frankenstein method of code generation can still bear fruit.

As the non native speaker in foreign lands, my goal is simply to be understood and get what I need (dos cervezas por favor). On the other hand, I can appreciate that other people's attempts to speak the language can be painful to watch -> thanks for being patient :)

Ok as you seem in a different process compared to most others ChatGPT guys, I will help :

The main issues are with indicators and getting their values.

1. This will be unreliable : because the handle to iMA should not be set in the same function as the CopyBuffer(). The indicator handles should be initialized in OnInit() event handler, that gives time to the indicator to be started and calculated. Also an handle should only be initialized ONCE, not each time a function is called.

bool GetMovingAverages(double &fastMA[], double &slowMA[])
{
    int handleFastMA = iMA(Symbol(), 0, fastSMA, 0, MODE_SMA, PRICE_CLOSE);
    int handleSlowMA = iMA(Symbol(), 0, slowSMA, 0, MODE_SMA, PRICE_CLOSE);

    if(CopyBuffer(handleFastMA, 0, 1, 3, fastMA) <= 0)
    {
        Print("Failed to copy fastMA. Error code: ", GetLastError());
        return false;
    }
    if(CopyBuffer(handleSlowMA, 0, 1, 3, slowMA) <= 0)
    {
        Print("Failed to copy slowMA. Error code: ", GetLastError());
        return false;
    }
    return true;
}

2. This is the MQL4 way to get an indicator value, it should be changed to the MQL5 way with an handle and using CopyBuffer().

bool CheckBullishDivergence()
{
    double priceHighPrev = iHigh(Symbol(), 0, 1);
    double rsiHighPrev = iRSI(Symbol(), 0, rsiPeriod, 1);

    return (priceHighPrev < iHigh(Symbol(), 0, 0) && rsiHighPrev > iRSI(Symbol(), 0, rsiPeriod, 0));
}

If you need more information about how to get values from indicator in MQL5 please check the documentation and search on the forum, it's has been discussed zillions times.

There are other issues, but let's start with these ones.