KI Nest Wave (Non-Repaint) MetaTrader 4 Expert Advisor

The KI Nest Wave (Non-Repaint) is an Expert Advisor designed for automated trading. It utilizes a set of predefined signals and trading conditions to manage trades in the financial markets. With features such as custom signal generation, trend strength evaluation, and time-based filters, this EA aims to streamline the trading process by executing orders based on its internal logic. The non-repaint aspect ensures that the signals it generates do not change after being produced, providing a consistent basis for decision-making. This EA integrates several tools and strategies to assist in managing trades effectively.

#include <stdlib.mqh>
#include <WinUser32.mqh>

// External parameters
extern int Confirm = 1;                // Confirmation parameter
extern int length1 = 3, length2 = 10, length3 = 16; // Signal lengths
extern double lots = 0.1;              // Trading lot size
extern int TakeProfit = 0;             // Take profit level
extern int StopLoss = 0;               // Stop loss level
extern bool UseTrail = true;           // Enable trailing stop
extern double TrailingAct = 10;        // Trailing activation level
extern double TrailingStep = 40;       // Trailing step in points
extern bool UseADX = false;            // Enable ADX filter
extern double ADXthresh = 30;          // ADX threshold
extern bool UseTimeFilter = false;     // Enable time filter
extern int BeginHour = 8;              // Begin trading hour
extern int EndHour = 18;               // End trading hour
extern bool Reverse = false;           // Reverse trading signals

// Global variables
int bar;
int TestStart;
int k;
int mm, dd, yy, hh, min, ss, tf;
string comment;
string syym;
string qwerty;
int OrderID = 234;       // Unique identifier for orders
double TrailPrice;       // Price level for trailing stop

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Initialize the Expert Advisor
    Comment("Last signal = ", lastsig());
    return (INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Cleanup on deinitialization
}

//+------------------------------------------------------------------+
//| Check if current time is within the trading hours                |
//+------------------------------------------------------------------+
int TimeFilter()
{
    if (Hour() > EndHour || Hour() < BeginHour)
    {
        return (1); // Outside trading hours
    }
    return (0); // Within trading hours
}

//+------------------------------------------------------------------+
//| Calculate the number of current orders on the symbol             |
//+------------------------------------------------------------------+
int CalculateCurrentOrders()
{
    int orders = 0;
    for (int i = 0; i < OrdersTotal(); i++)
    {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            if (OrderSymbol() == Symbol() && OrderMagicNumber() == OrderID)
            {
                orders++;
            }
        }
    }
    return (orders);
}

//+------------------------------------------------------------------+
//| Get signal value from custom indicator                           |
//+------------------------------------------------------------------+
double signal(int p, int x)
{
    int l1 = length1, l2 = length2, l3 = length3;
    double sig = NormalizeDouble(iCustom(NULL, 0, "KI_signals_v2", l1, l2, l3, p, x), 4);
    if (sig > 0 && sig < 100) return (sig);
    return (0);
}

//+------------------------------------------------------------------+
//| Get the last signal value                                        |
//+------------------------------------------------------------------+
double lastsig()
{
    static double lst;
    for (int i = 100; i >= 0; i--)
    {
        if (signal(2, i) > 0) lst = signal(2, i);
        if (signal(3, i) > 0) lst = signal(3, i);
    }
    return (lst);
}

//+------------------------------------------------------------------+
//| Determine the trading signal based on custom and ADX indicators   |
//+------------------------------------------------------------------+
int TradeSignal(int f)
{
    double adxsig = iADX(NULL, 0, 14, 0, MODE_MAIN, 0);
    int x = Confirm;
    bool ADX = (UseADX ? adxsig > ADXthresh : true);

    if (signal(2, x) > 0 && ADX)
    {
        return (Reverse ? 2 : 1);
    }
    if (signal(3, x) > 0 && ADX)
    {
        return (Reverse ? 1 : 2);
    }
    return (0);
}

//+------------------------------------------------------------------+
//| Check and open orders based on trading signal                    |
//+------------------------------------------------------------------+
void CheckForOpen()
{
    double sl, tp;
    int res, error;

    if (TradeSignal(1) == 2)
    {
        sl = (StopLoss == 0) ? 0 : Bid + Point * StopLoss;
        tp = (TakeProfit == 0) ? 0 : Bid - Point * TakeProfit;
        res = OrderSend(Symbol(), OP_SELL, lots, Bid, 3, sl, tp, "D2", OrderID, 0, Blue);
        if (res < 0)
        {
            error = GetLastError();
            Print("Error = ", ErrorDescription(error));
        }
    }
    if (TradeSignal(1) == 1)
    {
        sl = (StopLoss == 0) ? 0 : Ask - Point * StopLoss;
        tp = (TakeProfit == 0) ? 0 : Ask + Point * TakeProfit;
        res = OrderSend(Symbol(), OP_BUY, lots, Ask, 3, sl, tp, "D2", OrderID, 0, Red);
        if (res < 0)
        {
            error = GetLastError();
            Print("Error = ", ErrorDescription(error));
        }
    }
}

//+------------------------------------------------------------------+
//| Check and close orders based on trading signal                   |
//+------------------------------------------------------------------+
void CheckForClose()
{
    int res, error;
    for (int i = 0; i < OrdersTotal(); i++)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if (OrderType() == OP_BUY && OrderMagicNumber() == OrderID && Symbol() == OrderSymbol())
        {
            if (TradeSignal(2) == 2) // MA SELL signals
            {
                res = OrderClose(OrderTicket(), OrderLots(), Bid, 3, White);
                TrailPrice = 0;
                if (res < 0)
                {
                    error = GetLastError();
                    Print("Error = ", ErrorDescription(error));
                }
            }
        }
        if (OrderType() == OP_SELL && OrderMagicNumber() == OrderID && Symbol() == OrderSymbol())
        {
            if (TradeSignal(2) == 1) // MA BUY signals
            {
                res = OrderClose(OrderTicket(), OrderLots(), Ask, 3, White);
                TrailPrice = 0;
                if (res < 0)
                {
                    error = GetLastError();
                    Print("Error = ", ErrorDescription(error));
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Manage trailing stop positions                                   |
//+------------------------------------------------------------------+
void TrailingPositions()
{
    for (int i = 0; i < OrdersTotal(); i++)
    {
        if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            if (OrderSymbol() == Symbol())
            {
                if (OrderType() == OP_SELL)
                {
                    if (OrderOpenPrice() - Ask > TrailingAct * Point && TrailPrice == 0)
                    {
                        TrailPrice = Ask + TrailingStep * Point;
                        Print("TRAIL PRICE SET: ", TrailPrice);
                        if (TrailingStep > 8)
                        {
                            ModifyStopLoss(TrailPrice);
                        }
                    }
                    if (TrailPrice != 0 && Ask + TrailingStep * Point < TrailPrice)
                    {
                        TrailPrice = Ask - TrailingStep * Point;
                        Print("TRAIL PRICE MODIFIED: ", TrailPrice);
                        if (TrailingStep > 8)
                        {
                            ModifyStopLoss(TrailPrice);
                        }
                    }
                    if (TrailPrice != 0 && Ask >= TrailPrice)
                    {
                        CloseOrder(2);
                    }
                }
                if (OrderType() == OP_BUY)
                {
                    if (Bid - OrderOpenPrice() > TrailingAct * Point && TrailPrice == 0)
                    {
                        TrailPrice = Bid - TrailingStep * Point;
                        Print("TRAIL PRICE SET: ", TrailPrice);
                        if (TrailingStep > 8)
                        {
                            ModifyStopLoss(TrailPrice);
                        }
                    }
                    if (TrailPrice != 0 && Bid - TrailingStep * Point > TrailPrice)
                    {
                        TrailPrice = Bid - TrailingStep * Point;
                        Print("TRAIL PRICE MODIFIED: ", TrailPrice);
                        if (TrailingStep > 8)
                        {
                            ModifyStopLoss(TrailPrice);
                        }
                    }
                    if (TrailPrice != 0 && Bid <= TrailPrice)
                    {
                        CloseOrder(1);
                    }
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Modify the stop loss of an order                                 |
//+------------------------------------------------------------------+
void ModifyStopLoss(double ldStop)
{
    bool fm;
    double ldOpen = OrderOpenPrice();
    double ldTake = OrderTakeProfit();

    fm = OrderModify(OrderTicket(), ldOpen, ldStop, ldTake, 0, Pink);
}

//+------------------------------------------------------------------+
//| Close an order based on the type (1 for buy, 2 for sell)         |
//+------------------------------------------------------------------+
void CloseOrder(int ord)
{
    int res, error;
    for (int i = 0; i < OrdersTotal(); i++)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if (OrderType() == OP_BUY && OrderMagicNumber() == OrderID)
        {
            if (ord == 1)
            {
                res = OrderClose(OrderTicket(), OrderLots(), Bid, 3, White);
                TrailPrice = 0;
                if (res < 0)
                {
                    error = GetLastError();
                    Print("Error = ", ErrorDescription(error));
                }
            }
        }
        if (OrderType() == OP_SELL && OrderMagicNumber() == OrderID)
        {
            if (ord == 2)
            {
                res = OrderClose(OrderTicket(), OrderLots(), Ask, 3, White);
                TrailPrice = 0;
                if (res < 0)
                {
                    error = GetLastError();
                    Print("Error = ", ErrorDescription(error));
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Main function executed on every tick                            |
//+------------------------------------------------------------------+
void OnTick()
{
    if (Bars < 100 || !IsTradeAllowed()) return;

    if (CalculateCurrentOrders() == 0)
    {
        TrailPrice = 0;
        if (UseTimeFilter && TimeFilter() == 1) return;
        CheckForOpen();
    }
    else
    {
        CheckForClose();
    }

    if (UseTrail)
    {
        TrailingPositions();
    }
    // if (UseEmailAlerts) { MailAlert(); }
}

Overview of the Expert Advisor

This Expert Advisor is designed to automate trading decisions based on custom signals and various market conditions. It integrates several features to determine when to open or close trades and how to manage positions effectively. Let’s break down each component and see how they contribute to the overall trading strategy.

See also  Astron Prime Signal v3 (Non - Repaint) MetaTrader 5 Expert Advisor

Key Components of the Expert Advisor

Signal Generation

The EA relies on custom signals to determine trading opportunities. These signals are derived from specific indicators and parameters set within the EA. The logic is based on predefined conditions, such as the length of the signal and the threshold values used for generating trading signals.

Trading Conditions

The EA evaluates trading conditions using several factors:

  • ADX Filter: The Average Directional Index (ADX) is used to assess the strength of the trend. The EA checks if the ADX value exceeds a certain threshold to confirm the strength of the trend before making a trading decision.
  • Time Filter: The EA can restrict trading to specific hours of the day. This feature helps avoid trading during periods of low market activity, which can lead to less reliable signals.
  • Reverse Trading Option: The EA includes an option to reverse the trading signals. This means it can trade in the opposite direction if the reverse option is enabled.

Order Management

Once trading signals are generated, the EA manages trades based on the following:

  • Opening Orders: The EA can place buy or sell orders based on the signals it receives. It includes parameters for setting stop loss and take profit levels. If the conditions are met, the EA sends the appropriate trade orders.
  • Closing Orders: The EA monitors open trades and checks if conditions are met to close them. It uses signals to determine the optimal time to exit trades and manage positions.

Trailing Stop

The EA features a trailing stop mechanism to lock in profits as the market moves in favor of a trade. The trailing stop adjusts dynamically based on market conditions and predefined parameters. This feature helps protect gains by moving the stop loss level as the price changes.

See also  Meta Cluster Filter Price v1.0 (Non-Repaint) MT 4 Indicator

Summary of Features

  • Custom Signals: Generates trading signals based on specific indicators and parameters.
  • ADX Filter: Filters trades based on the strength of the trend.
  • Time Filter: Limits trading to specific hours to avoid low activity periods.
  • Reverse Trading: Allows for trading in the opposite direction if enabled.
  • Order Management: Handles the opening and closing of trades based on signals.
  • Trailing Stop: Adjusts the stop loss to secure profits as the market moves.

Conclusion

This Expert Advisor is a versatile tool designed to automate trading decisions based on a combination of custom signals, trend strength, and time filters. By understanding its components and how they work together, traders can better appreciate the functionality of this EA and how it can be utilized to manage trades effectively.

Leave a Comment