Trade Blocker EA

 
Hello, I'm trying to code a EA to block orders being opened once the max number of trades is opened on the terminal. But I'm keeping Autotrading enabled. Just trying to block Additional trades from Any charts or EAs.

Here is the code so far: If there is a EA for this that exists or a way to Limit the amount of trades opened to the Terminal let me know.


// Input parameters
input int maxTrades = 2; // Maximum allowed trades

// Global variables
bool allowTrading = true; // Flag to allow or block trading
int totalTradesAllCharts = 0; // Total trades from all charts

#define CHART_NAME "MyEA" // Unique name for the Expert Advisor (change it if you use multiple EAs)

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    totalTradesAllCharts = GetTotalTradesAllCharts();
    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    if (!IsTradingAllowed())
        return;

    // Your trading logic goes here (not required for this example)
}

//+------------------------------------------------------------------+
//| Function to get the total trades from all charts                |
//+------------------------------------------------------------------+
int GetTotalTradesAllCharts()
{
    int totalTrades = 0;

    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);

        // Check if the order is a buy or sell order from any chart
        if (OrderType() == OP_BUY || OrderType() == OP_SELL)
        {
            if (OrderMagicNumber() == CHART_NAME)
            {
                // Store the ticket number of the last order placed by this EA
                // To prevent blocking orders from the current chart
                int ticket = OrderTicket();
            }
            totalTrades++;
        }
    }

    return totalTrades;
}

//+------------------------------------------------------------------+
//| Function to check if trading is allowed                          |
//+------------------------------------------------------------------+
bool IsTradingAllowed()
{
    totalTradesAllCharts = GetTotalTradesAllCharts();

    if (totalTradesAllCharts >= maxTrades)
    {
        // Block trading by closing any new trades immediately after opening
        for (int i = OrdersTotal() - 1; i >= 0; i--)
        {
            OrderSelect(i, SELECT_BY_POS, MODE_TRADES);

            // Check if the order is a market or pending order from any chart
            if (OrderSymbol() == Symbol() && OrderMagicNumber() == CHART_NAME &&
                (OrderType() == OP_BUY || OrderType() == OP_SELL ||
                 OrderType() == OP_BUYSTOP || OrderType() == OP_SELLSTOP ||
                 OrderType() == OP_BUYLIMIT || OrderType() == OP_SELLLIMIT))
            {
                OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 0, clrNONE);
                Print("Maximum trades reached from all charts. Trading is now blocked.");
            }
        }

        allowTrading = false;
        return false;
    }

    return true;
}


Files:
 

Improperly formatted code removed by moderator. Please EDIT your post and use the CODE button (Alt-S) when inserting code.

Code button in editor

Hover your mouse over your post and select "edit" ... 

 
Frank William Jr Colbert:
Hello, I'm trying to code a EA to block orders being opened once the max number of trades is opened on the terminal. But I'm keeping Autotrading enabled. Just trying to block Additional trades from Any charts or EAs.

Here is the code so far: If there is a EA for this that exists or a way to Limit the amount of trades opened to the Terminal let me know.




how do you want to do that? - I cannot think of any way to prevent MT from opening a position if it is told to open one....
 
Alain Verleyen #:

Improperly formatted code removed by moderator. Please EDIT your post and use the CODE button (Alt-S) when inserting code.

Hover your mouse over your post and select "edit" ... 

Thanks got it!

 
Dominik Christian Egert #:
how do you want to do that? - I cannot think of any way to prevent MT from opening a position if it is told to open one....

Want to manage different EAs across different charts and want to control the max number of trades across all the EAs.

Some EAs have Max Orders coded in but others don't.

One way was disabling  Auto Trading until a trade closes then enable it back on.

// Input parameters
extern int MaxTrades = 5; // Change this value to set the maximum number of trades

// Global variable
string globalVarName = "MaxTrades_AllowTrading"; // Name of the global variable to store the trading permission

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Check the global variable to see if trading is allowed from other EAs
    double varValue = GlobalVariableGet(globalVarName);
    if (varValue == 0)
    {
        int result = GlobalVariableSet(globalVarName, true);
        if (result == 0)
        {
            Print("Error while accessing the global variable. Error code: ", GetLastError());
        }
    }

    // Refresh the rates to update the trading permission
    RefreshRates();

    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    int totalOrders = OrdersTotal();
    bool tradingAllowed = true;
    int main = GetAncestor(WindowHandle(Symbol(), Period()), 2/*GA_ROOT*/);

    if (totalOrders >= MaxTrades)
    {
        tradingAllowed = false;
    }

    if (tradingAllowed != TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
    {
        if (tradingAllowed)
        {
            Print("Auto Trading::::: Starting AutoTrading for all terminal charts");
        }
        else
        {
            Print("Auto Trading::::: Stopping AutoTrading for all terminal charts");
        }

        PostMessageA(main, WM_COMMAND, MT4_WMCMD_EXPERTS, 0);

        // Update the global variable with the current trading permission
        int result = GlobalVariableSet(globalVarName, tradingAllowed);
        if (result == 0)
        {
            Print("Error while setting the global variable. Error code: ", GetLastError());
        }
    }
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Reset the global variable on deinitialization
    int result = GlobalVariableSet(globalVarName, true);
    if (result == 0)
    {
        Print("Error while setting the global variable. Error code: ", GetLastError());
    }
}


But I'm trying to see about blocking trades across all EAs running on a terminal.

One EA managing  max trades across all running EAs.

Instead of disabling Auto Trading to Keep the EAs managing any opened trades.

Files:
 
Frank William Jr Colbert #:

Want to manage different EAs across different charts and want to control the max number of trades across all the EAs.

Some EAs have Max Orders coded in but others don't.

One way was disabling  Auto Trading until a trade closes then enable it back on.


But I'm trying to see about blocking trades across all EAs running on a terminal.

One EA managing  max trades across all running EAs.

Instead of disabling Auto Trading to Keep the EAs managing any opened trades.


You cannot stop an EA from opening new positions without interupting the EA itself.

It's not possible.
 
Yeah, you're only going to be able to control trade entries on EAs you control the code for. If you're wanting a portfolio management approach, you really have to own all the code.
Reason: