Multi Levels Trend Expert Advisor Structure for MetaTrader

Answered using GPT-4o Mini by GPT4oMini.app

Question:

//|$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ // Multi Levels Trend Expert Advisor //
//|$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ #define NL "\n"

extern double Lots = 1; extern double L1 = 1; extern double L2 = 2; extern double L3 = 4; extern double L4 = 8; extern double TP = 600; extern double DP = 1440; extern double MAP = 34; extern double MaxTrade = 4; extern int TradeType = 0; // 0 to follow the trend, 1 to force buy, 2 to force sell extern bool CloseAllNow = false; // closes all orders now extern bool CloseProfitableTradesOnly = false; // closes only profitable trades extern double ProftableTradeAmount = 1; // Only trades above this amount close out extern bool ClosePendingOnly = false; // closes pending orders only extern bool UseAlerts = false;

//+-------------+ //| Custom init | //|-------------+ int init() {

}

//+----------------+ //| Custom DE-init | //+----------------+ int deinit() {

}

Answer:

It looks like you're working on a Multi Levels Trend Expert Advisor (EA) for trading in MetaTrader, likely using MQL4 or MQL5. The code snippet you've provided includes some external parameters and the initialization and deinitialization functions. Below, I'll provide a more complete structure for your EA, including the main trading logic, order management, and some additional functions that you might find useful.

Complete Structure for Multi Levels Trend EA

//|$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
//  Multi Levels Trend Expert Advisor
//  
//|$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
#define     NL    "\n" 

extern double Lots = 1;
extern double L1 = 1;
extern double L2 = 2;
extern double L3 = 4;
extern double L4 = 8;
extern double TP = 600; // Take Profit in points
extern double DP = 1440; // Distance in points for new orders
extern int MAP = 34; // Moving Average Period
extern double MaxTrade = 4; // Maximum number of trades
extern int TradeType = 0; // 0 to follow the trend, 1 to force buy, 2 to force sell
extern bool CloseAllNow = false; // closes all orders now
extern bool CloseProfitableTradesOnly = false; // closes only profitable trades
extern double ProfitableTradeAmount = 1; // Only trades above this amount close out
extern bool ClosePendingOnly = false; // closes pending orders only
extern bool UseAlerts = false;

//+-------------+
//| Custom init |
//|-------------+
int OnInit()
{
    // Initialization code here
    return INIT_SUCCEEDED;
}

//+----------------+
//| Custom DE-init |
//+----------------+
void OnDeinit(const int reason)
{
    // Cleanup code here
}

//+------------------+
//| Main function     |
//+------------------+
void OnTick()
{
    // Check for close all orders condition
    if (CloseAllNow)
    {
        CloseAllOrders();
        return;
    }

    // Check for close profitable trades condition
    if (CloseProfitableTradesOnly)
    {
        CloseProfitableTrades();
        return;
    }

    // Check for close pending orders condition
    if (ClosePendingOnly)
    {
        ClosePendingOrders();
        return;
    }

    // Main trading logic
    if (OrdersTotal() < MaxTrade)
    {
        double ma = iMA(NULL, 0, MAP, 0, MODE_SMA, PRICE_CLOSE, 0);
        double price = Close[0];

        if (TradeType == 0) // Follow the trend
        {
            if (price > ma)
            {
                OpenBuyOrder();
            }
            else if (price < ma)
            {
                OpenSellOrder();
            }
        }
        else if (TradeType == 1) // Force buy
        {
            OpenBuyOrder();
        }
        else if (TradeType == 2) // Force sell
        {
            OpenSellOrder();
        }
    }
}

//+------------------+
//| Open Buy Order   |
//+------------------+
void OpenBuyOrder()
{
    double price = Ask;
    double sl = price - DP * Point;
    double tp = price + TP * Point;

    int ticket = OrderSend(Symbol(), OP_BUY, Lots, price, 3, sl, tp, "Buy Order", 0, 0, clrGreen);
    if (ticket < 0)
    {
        Print("Error opening buy order: ", GetLastError());
    }
}

//+------------------+
//| Open Sell Order  |
//+------------------+
void OpenSellOrder()
{
    double price = Bid;
    double sl = price + DP * Point;
    double tp = price - TP * Point;

    int ticket = OrderSend(Symbol(), OP_SELL, Lots, price, 3, sl, tp, "Sell Order", 0, 0, clrRed);
    if (ticket < 0)
    {
        Print("Error opening sell order: ", GetLastError());
    }
}

//+------------------+
//| Close All Orders  |
//+------------------+
void CloseAllOrders()
{
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        if (OrderSelect(i, SELECT_BY_POS))
        {
            if (OrderType() == OP_BUY || OrderType() == OP_SELL)
            {
                double price = (OrderType() == OP_BUY) ? Bid : Ask;
                bool result = OrderClose(OrderTicket(), OrderLots(), price, 3, clrYellow);
                if (!result)
                {
                    Print("Error closing order: ", GetLastError());
                }
            }
        }
    }
}

//+------------------+
//| Close Profitable Trades |
//+------------------+
void CloseProfitableTrades()
{
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        if (OrderSelect(i, SELECT_BY_POS))
        {
            if ((OrderProfit() > ProfitableTradeAmount) && (OrderType() == OP_BUY || OrderType() == OP_SELL))
            {
                double price = (OrderType() == OP_BUY) ? Bid : Ask;
                bool result = OrderClose(OrderTicket(), OrderLots(), price, 3, clrYellow);
                if (!result)
                {
                    Print("Error closing profitable order: ", GetLastError());
                }
            }
        }
    }
}

//+------------------+
//| Close Pending Orders |
//+------------------+
void ClosePendingOrders()
{
    for (int i = OrdersTotal() - 1; i >= 0; i--)
    {
        if (OrderSelect(i, SELECT_BY_POS))
        {
            if (OrderType() == OP_BUY_LIMIT || OrderType() == OP_SELL_LIMIT)
            {
                bool result = OrderDelete(OrderTicket());
                if (!result)
                {
                    Print("Error deleting pending order: ", GetLastError());
                }
            }
        }
    }
}

Explanation of the Code:

  1. Initialization and Deinitialization: The OnInit and OnDeinit functions are used for setting up and cleaning up the EA.
  2. Main Trading Logic: The OnTick function is called on every tick. It checks for conditions to close orders and then executes the trading logic based on the selected TradeType.
  3. Order Management: Functions are provided to open buy/sell orders, close all orders, close profitable trades, and close pending orders.
  4. Error Handling: Each order operation checks for errors and prints them to the log.

Note:

  • Make sure to test this EA in a demo account before using it in a live environment.
  • Adjust the parameters according to your trading strategy and risk management rules.
  • Consider adding more sophisticated risk management and trade management features as needed.