Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

devi codificare un EA che utilizzi l'idicatore di seguito come segnale. deve utilizzare…

  1. User

    devi codificare un EA che utilizzi l'idicatore di seguito come segnale. deve utilizzare due versioni differenti, una settata a 12 e una a 230. Quando il zig zag 230 segna un minimo vuol dire che sta iniziano un uptrend. da quel momento ogni minimo segnato dal zigzag 12 deve essere una operazione di acquisto. la conferma, oltre il minimo del zigzag 12 è data da rsi (6) che deve prima essere minore di 30 e poi rientrare. l'operazione di buy viene effettuara quando l'rsi taglia da basso verso l'alto la linea di 30 dopo averla tagliata dall'alto, ma solo se succede dopo che il zig zag 12 ha segnato un minimo

    //+------------------------------------------------------------------+ //| ZigZag.mq4 | //| Copyright 2006-2014, MetaQuotes Software Corp. | //| http://www.mql4.com | //+------------------------------------------------------------------+ #property copyright "2006-2014, MetaQuotes Software Corp." #property link "http://www.mql4.com" #property strict

    #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Red //---- indicator parameters input int InpDepth=12; // Depth input int InpDeviation=5; // Deviation input int InpBackstep=3; // Backstep //---- indicator buffers double ExtZigzagBuffer[]; double ExtHighBuffer[]; double ExtLowBuffer[]; //--- globals int ExtLevel=3; // recounting's depth of extremums //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { if(InpBackstep>=InpDepth) { Print("Backstep cannot be greater or equal to Depth"); return(INIT_FAILED); } //--- 2 additional buffers IndicatorBuffers(3); //---- drawing settings SetIndexStyle(0,DRAW_SECTION); //---- indicator buffers SetIndexBuffer(0,ExtZigzagBuffer); SetIndexBuffer(1,ExtHighBuffer); SetIndexBuffer(2,ExtLowBuffer); SetIndexEmptyValue(0,0.0); //---- indicator short name IndicatorShortName("ZigZag("+string(InpDepth)+","+string(InpDeviation)+","+string(InpBackstep)+")"); //---- initialization done return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long& tick_volume[], const long& volume[], const int& spread[]) { int i,limit,counterZ,whatlookfor=0; int back,pos,lasthighpos=0,lastlowpos=0; double extremum; double curlow=0.0,curhigh=0.0,lasthigh=0.0,lastlow=0.0; //--- check for history and inputs if(rates_total<InpDepth || InpBackstep>=InpDepth) return(0); //--- first calculations if(prev_calculated==0) limit=InitializeAll(); else { //--- find first extremum in the depth ExtLevel or 100 last bars i=counterZ=0; while(counterZ<ExtLevel && i<100) { if(ExtZigzagBuffer[i]!=0.0) counterZ++; i++; } //--- no extremum found - recounting all from begin if(counterZ==0) limit=InitializeAll(); else { //--- set start position to found extremum position limit=i-1; //--- what kind of extremum? if(ExtLowBuffer[i]!=0.0) { //--- low extremum curlow=ExtLowBuffer[i]; //--- will look for the next high extremum whatlookfor=1; } else { //--- high extremum curhigh=ExtHighBuffer[i]; //--- will look for the next low extremum whatlookfor=-1; } //--- clear the rest data for(i=limit-1; i>=0; i--)
    { ExtZigzagBuffer[i]=0.0;
    ExtLowBuffer[i]=0.0; ExtHighBuffer[i]=0.0; } } } //--- main loop
    for(i=limit; i>=0; i--) { //--- find lowest low in depth of bars extremum=low[iLowest(NULL,0,MODE_LOW,InpDepth,i)]; //--- this lowest has been found previously if(extremum==lastlow) extremum=0.0; else { //--- new last low lastlow=extremum; //--- discard extremum if current low is too high if(low[i]-extremum>InpDeviationPoint) extremum=0.0; else { //--- clear previous extremums in backstep bars for(back=1; back<=InpBackstep; back++) { pos=i+back; if(ExtLowBuffer[pos]!=0 && ExtLowBuffer[pos]>extremum) ExtLowBuffer[pos]=0.0; } } } //--- found extremum is current low if(low[i]==extremum) ExtLowBuffer[i]=extremum; else ExtLowBuffer[i]=0.0; //--- find highest high in depth of bars extremum=high[iHighest(NULL,0,MODE_HIGH,InpDepth,i)]; //--- this highest has been found previously if(extremum==lasthigh) extremum=0.0; else { //--- new last high lasthigh=extremum; //--- discard extremum if current high is too low if(extremum-high[i]>InpDeviationPoint) extremum=0.0; else { //--- clear previous extremums in backstep bars for(back=1; back<=InpBackstep; back++) { pos=i+back; if(ExtHighBuffer[pos]!=0 && ExtHighBuffer[pos]<extremum) ExtHighBuffer[pos]=0.0; } } } //--- found extremum is current high if(high[i]==extremum) ExtHighBuffer[i]=extremum; else ExtHighBuffer[i]=0.0; } //--- final cutting if(whatlookfor==0) { lastlow=0.0; lasthigh=0.0;
    } else { lastlow=curlow; lasthigh=curhigh; } for(i=limit; i>=0; i--) { switch(whatlookfor) { case 0: // look for peak or lawn if(lastlow==0.0 && lasthigh==0.0) { if(ExtHighBuffer[i]!=0.0) { lasthigh=High[i]; lasthighpos=i; whatlookfor=-1; ExtZigzagBuffer[i]=lasthigh; } if(ExtLowBuffer[i]!=0.0) { lastlow=Low[i]; lastlowpos=i; whatlookfor=1; ExtZigzagBuffer[i]=lastlow; } } break;
    case 1: // look for peak if(ExtLowBuffer[i]!=0.0 && ExtLowBuffer[i]<lastlow && ExtHighBuffer[i]==0.0) { ExtZigzagBuffer[lastlowpos]=0.0; lastlowpos=i; lastlow=ExtLowBuffer[i]; ExtZigzagBuffer[i]=lastlow; } if(ExtHighBuffer[i]!=0.0 && ExtLowBuffer[i]==0.0) { lasthigh=ExtHighBuffer[i]; lasthighpos=i; ExtZigzagBuffer[i]=lasthigh; whatlookfor=-1; }
    break;
    case -1: // look for lawn if(ExtHighBuffer[i]!=0.0 && ExtHighBuffer[i]>lasthigh && ExtLowBuffer[i]==0.0) { ExtZigzagBuffer[lasthighpos]=0.0; lasthighpos=i; lasthigh=ExtHighBuffer[i]; ExtZigzagBuffer[i]=lasthigh; } if(ExtLowBuffer[i]!=0.0 && ExtHighBuffer[i]==0.0) { lastlow=ExtLowBuffer[i]; lastlowpos=i; ExtZigzagBuffer[i]=lastlow; whatlookfor=1; }
    break;
    } } //--- done return(rates_total); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int InitializeAll() { ArrayInitialize(ExtZigzagBuffer,0.0); ArrayInitialize(ExtHighBuffer,0.0); ArrayInitialize(ExtLowBuffer,0.0); //--- first counting position return(Bars-InpDepth); } //+------------------------------------------------------------------+

  2. Assistant

    Creare un Expert Advisor (EA) basato sui criteri specificati richiede un attento monitoraggio dei segnali del ZigZag e dell'RSI, e quindi l'esecuzione delle operazioni di acquisto. Di seguito ti fornirò un esempio di codice per un EA scritto in MQL4 che implementa la tua strategia:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int Depth12 = 12;
    input int Depth230 = 230;
    input double LotSize = 0.1;
    
    // Declare ZigZag buffers
    double zzBuffer12[], zzBuffer230[];
    int last230Min = -1;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        // Initialize arrays
        ArraySetAsSeries(zzBuffer12, true);
        ArraySetAsSeries(zzBuffer230, true);
        
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        static int prevBars = 0;
        int currentBars = Bars;
        
        if(currentBars != prevBars)
        {
            CalculateZigZagBuffers();
            prevBars = currentBars;
        }
    
        double rsiValue;
        
        // Check for conditions to open buy
        if(last230Min > 0 && last230Min < Bars)
        {
            int last12Min = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, 0);
            if(last12Min != EMPTY_VALUE)
            {
                rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
                double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
                // Checking RSI crossing 30 from below
                if(prevRsiValue < 30 && rsiValue > 30)
                    OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, 0, 0, "Buy ZigZag EA", 0, 0, Green);
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Calculate ZigZag buffers                                         |
    //+------------------------------------------------------------------+
    void CalculateZigZagBuffers()
    {
        for(int i = 0; i < Bars; i++)
        {
            // Recompute ZigZag values
            zzBuffer12[i] = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, i);
            double zzValue230 = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 0, i);
    
            if(zzValue230 != EMPTY_VALUE && zzValue230 < Low[i])
            {
                // Found a new minimum in ZigZag 230
                last230Min = i;
            }
        }
    }
    

    Note di implementazione:

    1. ZigZag e RSI: Il codice utilizza la funzione iCustom per ottenere i valori dall'indicatore ZigZag e iRSI per calcolare l'indicatore RSI.
    2. Gestione Ordini: Assicurati di modificare le specifiche OrderSend per adattarle meglio alle esigenze di gestione delle operazioni, come stop loss e take profit.
    3. Debugging: Aggiungete istruzioni di Print() qualora si necessiti di effettuare il debugging durante l'esecuzione dell'EA.
    4. Ambiente: Assicurati di avere i parametri del broker corretti e che i requisiti di margine siano rispettati quando provi questo EA in un conto reale.
    5. Test su Conto Demo: Prima di utilizzare l'EA su un conto reale, è sempre consigliabile testare su un conto demo per verificare che esso funzioni come previsto.

    Questo esempio di codice è una base per creare il tuo EA, e dovresti personalizzarlo ulteriormente in base al tuo stile di programmazione e alle esigenze specifiche del tuo sistema di trading.

  3. User

    aggiungiamo lotti, stop loss e take profit

  4. Assistant

    Certo! Aggiungerò le funzionalità per gestire lot size, stop loss e take profit nel tuo EA. Per esempio, puoi usare fissi valori fissi per stop loss e take profit, oppure calcolare il rischio in percentuale del balance attuale. In questo esempio, userò valori fissi per semplicità.

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int Depth12 = 12;
    input int Depth230 = 230;
    input double LotSize = 0.1;
    input double StopLoss = 50; // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    // Declare ZigZag buffers
    double zzBuffer12[], zzBuffer230[];
    int last230Min = -1;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        // Initialize arrays
        ArraySetAsSeries(zzBuffer12, true);
        ArraySetAsSeries(zzBuffer230, true);
        
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        static int prevBars = 0;
        int currentBars = Bars;
        
        if (currentBars != prevBars)
        {
            CalculateZigZagBuffers();
            prevBars = currentBars;
        }
    
        double rsiValue;
    
        // Check for conditions to open buy
        if (last230Min > 0 && last230Min < Bars)
        {
            int last12Min = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, 0);
            if (last12Min != EMPTY_VALUE)
            {
                rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
                double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
                // Checking RSI crossing 30 from below
                if (prevRsiValue < 30 && rsiValue > 30)
                {
                    double sl = Ask - StopLoss * Point;
                    double tp = Ask + TakeProfit * Point;
    
                    int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                    
                    if (ticket < 0) 
                    {
                        Print("OrderSend failed with error #", GetLastError());
                    }
                    else 
                    {
                        Print("Order opened with ticket #", ticket);
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Calculate ZigZag buffers                                         |
    //+------------------------------------------------------------------+
    void CalculateZigZagBuffers()
    {
        for (int i = 0; i < Bars; i++)
        {
            // Recompute ZigZag values
            zzBuffer12[i] = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, i);
            double zzValue230 = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 0, i);
    
            if (zzValue230 != EMPTY_VALUE && zzValue230 < Low[i])
            {
                // Found a new minimum in ZigZag 230
                last230Min = i;
            }
        }
    }
    

    Spiegazione e Modifiche:

    1. LotSize: Ora l'EA include un parametro d'input LotSize che ti permette di specificare la dimensione del lotto per ogni operazione.
    2. Stop Loss e Take Profit: Aggiunto StopLoss e TakeProfit come input in pips, convertendoli poi in punti in modo da impostare correttamente i livelli basati su Ask.
    3. OrderSend: L'aggiunta di stop loss (sl) e take profit (tp) nella funzione OrderSend.
    4. Error Handling: Include controlli basici per assicurarsi che l'ordine sia inviato correttamente e gestire eventuali errori.

    Questi parametri possono essere impostati per adattarsi alla tua gestione del rischio e alla strategia di trading complessiva. Ricorda di testare sempre qualsiasi algoritmo in modalità demo prima di applicarlo a un conto reale.

  5. User

    ti sei dimenticato di inserire i sell che sono l'opposto dei segnali BUY, con un rsi che taglia i valori 70

  6. Assistant

    Certamente, aggiungerò la logica per le operazioni di vendita (sell) quando il ZigZag e l'RSI indicano lo scenario di una tendenza al ribasso. Per l'operazione di vendita, l'RSI deve scendere sotto il valore di 70 dopo essere stato al di sopra di esso. Ecco una versione aggiornata del codice con la logica sell inclusa:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int Depth12 = 12;
    input int Depth230 = 230;
    input double LotSize = 0.1;
    input double StopLoss = 50; // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    // Declare ZigZag buffers
    double zzBuffer12[], zzBuffer230[];
    int last230Min = -1;
    int last230Max = -1;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        // Initialize arrays
        ArraySetAsSeries(zzBuffer12, true);
        ArraySetAsSeries(zzBuffer230, true);
        
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        static int prevBars = 0;
        int currentBars = Bars;
        
        if (currentBars != prevBars)
        {
            CalculateZigZagBuffers();
            prevBars = currentBars;
        }
    
        double rsiValue;
    
        // Buy condition
        if (last230Min > 0 && last230Min < Bars)
        {
            int last12Min = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, 0);
            if (last12Min != EMPTY_VALUE)
            {
                rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
                double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
                // Checking RSI crossing 30 from below
                if (prevRsiValue < 30 && rsiValue > 30)
                {
                    double sl = Ask - StopLoss * Point;
                    double tp = Ask + TakeProfit * Point;
    
                    int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
    
                    if (ticket < 0)
                    {
                        Print("OrderSend failed with error #", GetLastError());
                    }
                    else
                    {
                        Print("Order opened with ticket #", ticket);
                    }
                }
            }
        }
    
        // Sell condition
        if (last230Max > 0 && last230Max < Bars)
        {
            int last12Max = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, 0);
            if (last12Max != EMPTY_VALUE)
            {
                rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
                double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
                // Checking RSI crossing 70 from above
                if (prevRsiValue > 70 && rsiValue < 70)
                {
                    double sl = Bid + StopLoss * Point;
                    double tp = Bid - TakeProfit * Point;
    
                    int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                    if (ticket < 0)
                    {
                        Print("OrderSend failed with error #", GetLastError());
                    }
                    else
                    {
                        Print("Order opened with ticket #", ticket);
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Calculate ZigZag buffers                                         |
    //+------------------------------------------------------------------+
    void CalculateZigZagBuffers()
    {
        for (int i = 0; i < Bars; i++)
        {
            // Recompute ZigZag values for buy
            zzBuffer12[i] = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, i);
            double zzValue230 = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 0, i);
    
            if (zzValue230 != EMPTY_VALUE && zzValue230 < Low[i])
            {
                // Found a new minimum in ZigZag 230
                last230Min = i;
            }
    
            // Recompute ZigZag values for sell
            double zzValue230Max = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 1, i);
    
            if (zzValue230Max != EMPTY_VALUE && zzValue230Max > High[i])
            {
                // Found a new maximum in ZigZag 230
                last230Max = i;
            }
        }
    }
    

    Spiegazione:

    • Condizioni di Vendita (Sell): In modo simile alle condizioni di acquisto, il codice guarda se l'RSI scende sotto 70 dopo essere stato sopra 70, utilizzando gli stessi valori di ZigZag per determinare l'inizio di un downtrend.
    • Ordini di Vendita (Sell Orders): OrderSend per un ordine di vendita si basa sulla vendita al prezzo Bid, con stop loss e take profit adeguati per le vendite.
    • Controllo Errori: Simile al buy, include controlli per gestire errori nell'invio degli ordini.

    Questo codice ora include sia le logiche per gli ordini di acquisto sia per quelli di vendita, in linea con i tuoi criteri di trading definiti. Assicurati di testare l'EA su un conto demo e di apportare eventuali modifiche necessarie per completare la tua strategia.

  7. User

    mi dice errore critico nell'EA. c'è qualche errore con iCustom?

  8. Assistant

    Gli errori critici nei codici di Expert Advisor di MQL4 spesso derivano da problemi con la funzione iCustom, specialmente se non configurata correttamente con i parametri richiesti dall'indicatore personalizzato.

    Nel codice fornito, ci sono alcune aree specifiche che potrebbero causare errori critici. Possiamo esaminare un approccio alternativo per garantire che i valori di iCustom siano recuperati correttamente.

    Ecco alcune cose da verificare e alcune modifiche da apportare al codice:

    1. Verifica del Nome dell'Indicatore: Assicurati che il nome passato a iCustom corrisponda esattamente al nome del tuo file .ex4 dell'indicatore ZigZag. Assicurati che l'indicatore sia collocato nella cartella corretta (Indicators).

    2. Controllo dei Parametri: Assicurati che i parametri siano corretti. La funzione iCustom richiede i parametri esatti utilizzati nel file dell'indicatore personalizzato.

    3. Valori di Ritorno da iCustom: Ricorda che iCustom restituisce valori EMPTY_VALUE se non riesce a recuperare correttamente i valori. Questo va gestito nel codice.

    4. Uso corretto degli Indici Buffers: Verifica che stai accedendo ai giusti buffer dell'indicatore ZigZag. Ad esempio, il buffer 0 potrebbe riferirsi ai picchi alti o bassi.

    Ecco una versione corretta e semplificata con un esempio di gestione degli errori con iCustom:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int Depth12 = 12;
    input int Depth230 = 230;
    input double LotSize = 0.1;
    input double StopLoss = 50; // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    // Declare ZigZag buffers
    double zzBuffer12[], zzBuffer230[];
    int last230Min = -1;
    int last230Max = -1;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        // Initialize arrays
        ArraySetAsSeries(zzBuffer12, true);
        ArraySetAsSeries(zzBuffer230, true);
        
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        static int prevBars = 0;
        int currentBars = Bars;
        
        if (currentBars != prevBars)
        {
            CalculateZigZagBuffers();
            prevBars = currentBars;
        }
        
        // Manage trades
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders - Open or Close based on strategy                  |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double rsiValue;
        
        // Buy condition
        if (last230Min > 0 && last230Min < Bars - 1)
        {
            int last12Min = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, 0);
            if (last12Min != EMPTY_VALUE)
            {
                rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
                double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
                // Checking RSI crossing 30 from below
                if (prevRsiValue < 30 && rsiValue > 30)
                {
                    double sl = Ask - StopLoss * Point;
                    double tp = Ask + TakeProfit * Point;
    
                    int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy ZigZag EA", 0, 0, Green);
    
                    if (ticket < 0)
                    {
                        Print("Buy OrderSend failed with error #", GetLastError());
                    }
                    else
                    {
                        Print("Buy Order opened with ticket #", ticket);
                    }
                }
            }
        }
    
        // Sell condition
        if (last230Max > 0 && last230Max < Bars - 1)
        {
            int last12Max = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, 0);
            if (last12Max != EMPTY_VALUE)
            {
                rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
                double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
                // Checking RSI crossing 70 from above
                if (prevRsiValue > 70 && rsiValue < 70)
                {
                    double sl = Bid + StopLoss * Point;
                    double tp = Bid - TakeProfit * Point;
    
                    int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                    if (ticket < 0)
                    {
                        Print("Sell OrderSend failed with error #", GetLastError());
                    }
                    else
                    {
                        Print("Sell Order opened with ticket #", ticket);
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Calculate ZigZag buffers                                         |
    //+------------------------------------------------------------------+
    void CalculateZigZagBuffers()
    {
        for (int i = 0; i < Bars; i++)
        {
            // Recompute ZigZag values for buy
            zzBuffer12[i] = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, i);
            double zzValue230 = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 0, i);
    
            if (zzValue230 != EMPTY_VALUE && zzValue230 < Low[i])
            {
                // Found a new minimum in ZigZag 230
                last230Min = i;
            }
    
            // Recompute ZigZag values for sell
            double zzValue230Max = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 1, i);
    
            if (zzValue230Max != EMPTY_VALUE && zzValue230Max > High[i])
            {
                // Found a new maximum in ZigZag 230
                last230Max = i;
            }
        }
    }
    

    Spiegazioni:

    • Verifica del Nome: Assicurati che "ZigZag" nel iCustom() sia esattamente il nome dell'indicatore se è stato salvato con un nome differente.
    • Buffer Corretti: Abbiamo usato buffer diversi nel codice per ottenere minimi e massimi. Questo presuppone che il buffer 0 sia per minimi e buffer 1 per massimi, che è standard per molti indicatori ZigZag.
    • Debug Stamp: Aggiungi Print per il debugging se vedi errori specifici o valori EMPTY_VALUE.

    Prova questo codice su Strategy Tester in modalità Visual per vedere i risultati. Eventuali ulteriori errori da iCustom possono essere meglio diagnosticati controllando gli errori di runtime e assicurandosi che gli indicatori siano correttamente posizionati e accessibili nella piattaforma.

  9. User

    2024.09.26 20:27:07.971 2023.01.05 00:00:00 zigzag EURUSD,M15: array out of range in 'zigzag.mq4' (124,19)

  10. Assistant

    L'errore "array out of range" nel tuo EA indica che il codice sta cercando di accedere a un elemento di un array che non esiste, ovvero un indice che è oltre i limiti dell'array.

    Nella tua situazione, il problema sta nel gestire gli array zzBuffer12 e zzBuffer230 in modo corretto, specialmente nel contesto di un ciclo che etichetta con il numero di barre disponibili (Bars). In MQL4, nel setup degli indicatori e nel calcolo all'interno di Expert Advisor, bisogna essere molto attenti con la gestione di indici per evitare di tentare di accedere a valori fuori dall'intervallo.

    Per risolvere questo problema, possiamo assicurarci di gestire il ciclo correttamente garantendo che gli indici utilizzati negli array siano sempre validi.

    Ecco un esempio di come potresti risolvere il problema:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int Depth12 = 12;
    input int Depth230 = 230;
    input double LotSize = 0.1;
    input double StopLoss = 50; // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    // Declare ZigZag buffers
    double zzBuffer12[], zzBuffer230[];
    int last230Min = -1;
    int last230Max = -1;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        // Assicurati che gli array siano gestiti correttamente come serie
        ArraySetAsSeries(zzBuffer12, true);
        ArraySetAsSeries(zzBuffer230, true);
        
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        static int prevBars = 0;
        int currentBars = Bars;
        
        if (currentBars != prevBars)
        {
            CalculateZigZagBuffers();
            prevBars = currentBars;
        }
        
        // Manage trades
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders - Open or Close based on strategy                  |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double rsiValue;
        
        // Buy condition
        if (last230Min >= 0 && last230Min < Bars)
        {
            double zzValueLastMin = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, last230Min);
            if (zzValueLastMin != EMPTY_VALUE)
            {
                rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
                double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
                // Checking RSI crossing 30 from below
                if (prevRsiValue < 30 && rsiValue > 30)
                {
                    double sl = Ask - StopLoss * Point;
                    double tp = Ask + TakeProfit * Point;
    
                    int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy ZigZag EA", 0, 0, Green);
    
                    if (ticket < 0)
                    {
                        Print("Buy OrderSend failed with error #", GetLastError());
                    }
                    else
                    {
                        Print("Buy Order opened with ticket #", ticket);
                    }
                }
            }
        }
    
        // Sell condition
        if (last230Max >= 0 && last230Max < Bars)
        {
            double zzValueLastMax = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, last230Max);
            if (zzValueLastMax != EMPTY_VALUE)
            {
                rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
                double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
                // Checking RSI crossing 70 from above
                if (prevRsiValue > 70 && rsiValue < 70)
                {
                    double sl = Bid + StopLoss * Point;
                    double tp = Bid - TakeProfit * Point;
    
                    int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                    if (ticket < 0)
                    {
                        Print("Sell OrderSend failed with error #", GetLastError());
                    }
                    else
                    {
                        Print("Sell Order opened with ticket #", ticket);
                    }
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Calculate ZigZag buffers                                         |
    //+------------------------------------------------------------------+
    void CalculateZigZagBuffers()
    {
        for (int i = 0; i < Bars; i++)
        {
            // Verifica che l'indice sia all'interno dei limiti prima di accedere agli array
            if (i < ArraySize(zzBuffer12) && i < ArraySize(zzBuffer230))
            {
                zzBuffer12[i] = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, i);
                double zzValue230 = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 0, i);
    
                if (zzValue230 != EMPTY_VALUE && zzValue230 < Low[i])
                {
                    // Found a new minimum in ZigZag 230
                    last230Min = i;
                }
    
                double zzValue230Max = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 1, i);
    
                if (zzValue230Max != EMPTY_VALUE && zzValue230Max > High[i])
                {
                    // Found a new maximum in ZigZag 230
                    last230Max = i;
                }
            }
        }
    }
    

    Spiegazioni:

    • Gestione degli Indici: Il loop nella funzione CalculateZigZagBuffers() è accompagnato da una verifica che assicura che il codice stia usando sempre indici validi per gli array.
    • Verifica dei Limiti dell'Array: Aggiunta una verifica per assicurarsi che l'indice i non superi la dimensione degli array zzBuffer12 e zzBuffer230 per evitare di accedere al di fuori dei limiti.

    Assicurati che l'indicatore ZigZag sia nella cartella corretta e che i suoi parametri (buffer, ordine dei parametri, ecc.) siano corretti. Inoltre, esegui il test su Strategy Tester per un feedback visivo sugli eventi e sui comportamenti dell'EA.

  11. User

    ora non da errori, ma non apre nessuna operazione. rivediamo le condizioni: zz230 crea un minimo = SOLO operazioni BUY fino al prossimo MASSIMO = okBUY okBUY && zz12 crea un minimo && rsi6 taglia il valore 30 dal basso verso l'alto = apri BUY

    per operazioni short vale il contrario

  12. Assistant

    D'accordo, ai fini dell'apertura delle operazioni, dobbiamo assicurarci che l'EA registri correttamente i minimi e i massimi del ZigZag 230 per determinare quando è attivo il periodo di acquisto (okBUY) o di vendita (okSELL), e quindi controlli l'intersezione dell'RSI nei punti giusti quando il ZigZag 12 segnala un minimo o un massimo, rispettivamente.

    Ecco come possiamo strutturare il codice secondo le condizioni che hai specificato:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int Depth12 = 12;
    input int Depth230 = 230;
    input double LotSize = 0.1;
    input double StopLoss = 50; // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    // Declare ZigZag buffers
    double zzBuffer12[], zzBuffer230[];
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        // Assicurati che gli array siano gestiti correttamente come serie
        ArraySetAsSeries(zzBuffer12, true);
        ArraySetAsSeries(zzBuffer230, true);
        
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        static int prevBars = 0;
        int currentBars = Bars;
        
        if (currentBars != prevBars)
        {
            CalculateZigZagBuffers();
            prevBars = currentBars;
        }
        
        // Manage trades
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
        double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
        // Buy logic
        if (okBUY)
        {
            double last12Min = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, 0);
            if (last12Min != 0 && prevRsiValue < 30 && rsiValue > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                
                if (ticket < 0)
                {
                    Print("Buy OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Buy Order opened with ticket #", ticket);
                }
            }
        }
    
        // Sell logic
        if (okSELL)
        {
            double last12Max = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 1, 0);
            if (last12Max != 0 && prevRsiValue > 70 && rsiValue < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                if (ticket < 0)
                {
                    Print("Sell OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Sell Order opened with ticket #", ticket);
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Calculate ZigZag buffers and determine buy/sell periods          |
    //+------------------------------------------------------------------+
    void CalculateZigZagBuffers()
    {
        for (int i = 0; i < Bars - 1; i++)
        {
            zzBuffer12[i] = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, i);
            double zzValue230 = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 0, i);
    
            if (zzValue230 != 0)
            {
                if (zzValue230 < Low[i])
                {
                    // Found a minimum in ZigZag 230
                    okBUY = true;
                    okSELL = false;
                }
                else if (zzValue230 > High[i])
                {
                    // Found a maximum in ZigZag 230
                    okSELL = true;
                    okBUY = false;
                }
            }
        }
    }
    

    Spiegazioni:

    • Gestione di okBUY e okSELL: Stabilisco okBUY = true quando il ZigZag 230 segna un minimo, e okSELL = true quando segna un massimo; entrambe le variabili si escludono a vicenda.
    • Logica dell'RSI: Il controllo degli incroci dell'RSI (30 per acquisti e 70 per vendite) avviene solo durante i periodi determinati da okBUY e okSELL.
    • Verifica dei Valori: Assicura che sia zzValue230 sia zzBuffer12 non siano 0 prima di prendere decisioni sui trading. Questo evita errori dovuti a valori errati o mancanti.

    Con questo approccio, l'EA dovrebbe eseguire correttamente le operazioni di mercato quando le condizioni specificate vengono soddisfatte. Assicurati di verificare i comportamenti con il Strategy Tester per vedere se l'algoritmo opera come previsto.

  13. User

    2024.09.26 20:31:38.238 2023.01.05 00:00:00 zigzag EURUSD,M15: array out of range in 'zigzag.mq4' (108,19)

  14. Assistant

    L'errore "array out of range" suggerisce che si sta tentando di accedere a un indice al di fuori dei limiti degli array. Questo può accadere facilmente in MQL4 se non si gestiscono correttamente i limiti degli array.

    Analisi del problema:

    Nella funzione CalculateZigZagBuffers, si esegue un loop fino a Bars - 1. Tuttavia, se gli array di ZigZag non sono stati inizializzati o non sono sufficientemente grandi per contenere tanti elementi, si potrebbe tentare di accedere a un indice fuori rango.

    Soluzione:

    Assicuriamoci prima di tutto che gli array siano necessari e correttamente dimensionati solo se sono usati per accumulare dati che verranno usati altrove. Inoltre, bisogna fare attenzione agli indici corretti degli indicatori personalizzati.

    Ecco come potresti aggiornare il codice per evitare questi errori:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int Depth12 = 12;       
    input int Depth230 = 230;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        // Manage trades
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
        double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
        // Buy logic
        if (okBUY)
        {
            double last12Min = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 0, 0);
            if (last12Min != 0 && prevRsiValue < 30 && rsiValue > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                
                if (ticket < 0)
                {
                    Print("Buy OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Buy Order opened with ticket #", ticket);
                }
            }
        }
    
        // Sell logic
        if (okSELL)
        {
            double last12Max = iCustom(NULL, 0, "ZigZag", Depth12, 5, 3, 1, 0);
            if (last12Max != 0 && prevRsiValue > 70 && rsiValue < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                if (ticket < 0)
                {
                    Print("Sell OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Sell Order opened with ticket #", ticket);
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction based on ZigZag                      |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        double zzValue230;
        for (int i = Bars - 1; i >= 0; i--)
        {
            // Calculate the ZigZag for ZZ230
            zzValue230 = iCustom(NULL, 0, "ZigZag", Depth230, 5, 3, 0, i);
    
            if (zzValue230 != 0)
            {
                if (zzValue230 < Low[i])
                {
                    // Found a minimum in ZigZag 230
                    okBUY = true;
                    okSELL = false;
                    break; // Exit loop after finding a minimum
                }
                else if (zzValue230 > High[i])
                {
                    // Found a maximum in ZigZag 230
                    okSELL = true;
                    okBUY = false;
                    break; // Exit loop after finding a maximum
                }
            }
        }
    }
    

    Dettagli Aggiornati:

    • Ciclo di Verifica: Modificato l'iteratore del loop for per andare da Bars - 1 a 0, permettendo di trovare il primo segnale valido recente.
    • Assicurati che last12Min e last12Max siano validi: Usa i risultati di iCustom per ottenere solo i valori validi e confrontali correttamente.
    • Inizializzazione Corrette: Assicurati che tutte le variabili e logic siano inizializzate e aggiornate correttamente, specialmente okBUY e okSELL.

    Con queste modifiche, puoi rilanciare il tuo programma in Strategy Tester per vedere se funziona come previsto. Tieni sempre sotto controlli di Print() per eseguire un debug più facile nel caso trovassi ulteriori problemi.

  15. User

    non apre operazioni. è corretto che nell'ea i valori siano Depth12 anzichè InDepth come nell'indicatore?

  16. Assistant

    Hai ragione nel sottolineare la questione dei nomi dei parametri. Quando usi iCustom per richiamare un indicatore personalizzato, è importante che i nomi e l'ordine dei parametri che passi corrispondano esattamente a quelli definiti nel file dell'indicatore.

    Assicurati di:

    1. Utilizzare i giusti parametri per iCustom. Nel codice EA, i nomi dei parametri con cui chiami l'indicatore devono corrispondere ai nomi usati nella definizione dell'indicatore stesso (nel tuo caso InpDepth, InpDeviation, InpBackstep).
    2. Verificare che l'indicatore esista. Assicurati di avere l'indicatore ZigZag nella cartella Indicators di MetaTrader.

    Ecco un esempio del modo corretto in cui puoi chiamare iCustom rispettando i parametri definiti nell'indicatore originale:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int InpDepth12 = 12;       
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        // Manage trades
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
        double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
        // Buy logic
        if (okBUY)
        {
            double last12Min = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 0);
            if (last12Min != 0 && prevRsiValue < 30 && rsiValue > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                
                if (ticket < 0)
                {
                    Print("Buy OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Buy Order opened with ticket #", ticket);
                }
            }
        }
    
        // Sell logic
        if (okSELL)
        {
            double last12Max = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 0);
            if (last12Max != 0 && prevRsiValue > 70 && rsiValue < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                if (ticket < 0)
                {
                    Print("Sell OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Sell Order opened with ticket #", ticket);
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction based on ZigZag                      |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        double zzValue230;
        for (int i = Bars - 1; i >= 0; i--)
        {
            // Calculate the ZigZag for ZZ230
            zzValue230 = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, i);
    
            if (zzValue230 != 0)
            {
                if (zzValue230 < Low[i])
                {
                    // Found a minimum in ZigZag 230
                    okBUY = true;
                    okSELL = false;
                    break; // Exit loop after finding a minimum
                }
                else if (zzValue230 > High[i])
                {
                    // Found a maximum in ZigZag 230
                    okSELL = true;
                    okBUY = false;
                    break; // Exit loop after finding a maximum
                }
            }
        }
    }
    

    Dettagli:

    • Usa i nomi dei parametri corretti (InpDepth12, InpDepth230, InpDeviation, InpBackstep) quando chiami iCustom.
    • Assicurati di aver incluso l'indicatore ZigZag originale: Deve essere nello stesso ambiente MetaTrader affinché iCustom funzioni correttamente.
    • Debugging: Se non apre operazioni, utilizza i messaggi Print() all'interno della funzione ManageOrders() per verificare le condizioni. Potresti voler stampare i valori RSI e ZigZag per vedere se le condizioni vengono soddisfatte.

    Testa il tuo EA sul Strategy Tester per vedere come reagisce e fai ulteriori debug in base ai risultati ottenuti.

  17. User

    continua a non aprire nessuna operazione. forse c'è un errore su come calcoli i minimi e i massimi rispetto l'idicatore originale?

  18. Assistant

    È possibile che ci siano problemi nell'interpretazione dei dati di output dall'indicatore ZigZag attraverso iCustom. Ricorda che iCustom restituisce il valore dell'indicatore per una barra specifica e potrebbe essere necessario controllare se le condizioni sui minimi e massimi vengono interpretate correttamente nel contesto del tuo trading system.

    Ecco alcune linee guida e un esempio più dettagliato su come gestire l'indicatore ZigZag per determinare i minimi e massimi correttamente:

    1. Verifica dei Valori con iCustom:

      • I valori restituiti da iCustom sono diverse combinazioni di 0 (nessun picco su quella barra) o un valore effettivo (quando l'indicatore segna un minimo o un massimo).
    2. Controlla il Buffer Corretto:

      • Assicurati di usare l'indice corretto per i buffer del tuo ZigZag. Molte implementazioni del ZigZag usano buffer differenti per segnare i picchi bassi e alti.
    3. Debug dei Risultati:

      • Stampa i risultati per alcune barre e assicurati che i picchi vengano individuati come previsto.

    Ecco come puoi strutturare il codice per aiutarti:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        if (Bars < InpDepth230) return;
    
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        // Manage trades
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
        double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
        // Buy logic
        if (okBUY)
        {
            double last12Min = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 1);
            if (last12Min != 0 && prevRsiValue < 30 && rsiValue > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy ZigZag EA", 0, 0, Green);
    
                if (ticket < 0)
                {
                    Print("Buy OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Buy Order opened with ticket #", ticket);
                }
            }
        }
    
        // Sell logic
        if (okSELL)
        {
            double last12Max = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 1);
            if (last12Max != 0 && prevRsiValue > 70 && rsiValue < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                if (ticket < 0)
                {
                    Print("Sell OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Sell Order opened with ticket #", ticket);
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag                         |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        double zzValue230 = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, 1);
    
        if (zzValue230 != 0)
        {
            if (zzValue230 < Low[1])
            {
                // Found a minimum in ZigZag 230
                okBUY = true;
                okSELL = false;
                Print("ZigZag Min found, looking for BUY signals.");
            }
            else if (zzValue230 > High[1])
            {
                // Found a maximum in ZigZag 230
                okSELL = true;
                okBUY = false;
                Print("ZigZag Max found, looking for SELL signals.");
            }
        }
    }
    

    Debugging:

    • Debug su Condizioni: Usa Print() per confermare che i segnali vengano visti, stampa zzValue230, last12Min, last12Max, okBUY e okSELL per confermare quando e se le condizioni sono soddisfatte.
    • Monitor su RSI: Assicurati che i valori RSI siano corretti e oltre le soglie specificate al momento giusto.

    Verifica:

    1. Verifica la Sintassi dell'Indicatore: Se hai accesso al codice sorgente dell'indicatore ZigZag in uso, verifica che gli indici dei buffer e la logica di estrazione siano corretti.

    2. Controlla gli Intervalli: Assicurati che l'EA parta con una quantità sufficiente di dati storici (Bars) e un segnale valido prima del tentativo operativo.

    Fai attenzione a modificare la sempre il Strategy Tester per confermare il comportamento corretto. Se ancora non funziona, puoi usare il Journal per controllare eventuali errori o avvisi.

  19. User

    non capisco perchè metti last12Min != 0. cosa c'entra con i minimi e i massimi disegnati dall'indicatore? forse questa è la parte d'interesse extremum=low[iLowest(NULL,0,MODE_LOW,InpDepth,i)];

  20. Assistant

    Scusami, sembra ci sia stata un po' di confusione riguardo all'interpretazione dei picchi e dei minimi generati dall'indicatore ZigZag tramite iCustom. È importante capire come vengono segnati i minimi e i massimi dall'indicatore ZigZag e come questi possono essere utilizzati per prendere decisioni di trading.

    Comprensione dell'Indicatore ZigZag:

    L'indicatore ZigZag tradizionalmente segnala i punti di massimo e minimo basandosi su variazioni significative nel prezzo, definendo "picchi" e "fondi". Gli extremum solitamente sono valori diversi da zero sulle barre dove si verificano.

    Assicurati di Interrogare l'indicatore in Modo Corretto:

    Ecco un modo corretto di assicurarsi che stai ottenendo e interpretando correttamente questi picchi/minimi dall'indicatore ZigZag attraverso iCustom.

    Estrarre Informazioni dal ZigZag:

    Supponiamo che il ZigZag utilizzi:

    • Buffer 0 per segnalare minimi
    • Buffer 1 per segnalare massimi

    Ecco un esempio di codice che controlla l'output di questi buffer:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        if (Bars < InpDepth230) return;
    
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        // Manage trades
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
        double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
        // Buy logic
        if (okBUY)
        {
            double last12Min = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 1);
            if (last12Min != 0 && prevRsiValue < 30 && rsiValue > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy ZigZag EA", 0, 0, Green);
    
                if (ticket < 0)
                {
                    Print("Buy OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Buy Order opened with ticket #", ticket);
                }
            }
        }
    
        // Sell logic
        if (okSELL)
        {
            double last12Max = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 1);
            if (last12Max != 0 && prevRsiValue > 70 && rsiValue < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                if (ticket < 0)
                {
                    Print("Sell OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Sell Order opened with ticket #", ticket);
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag                         |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        double zzValue230Min = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, 1);
        double zzValue230Max = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, 1);
    
        if (zzValue230Min != 0)
        {
            // Found a minimum in ZigZag 230
            okBUY = true;
            okSELL = false;
            Print("ZigZag Min found, looking for BUY signals.");
        }
        else if (zzValue230Max != 0)
        {
            // Found a maximum in ZigZag 230
            okSELL = true;
            okBUY = false;
            Print("ZigZag Max found, looking for SELL signals.");
        }
    }
    

    Spiegazione:

    • Buffer 0 vs. Buffer 1: iCustom è utilizzato con i buffer specifici (0 e 1) per distinguere tra minimi e massimi.
    • Controllo di Zero: Le condizioni come last12Min != 0 verificano se un valore reale è stato segnato, indicando un punto di estremo. Un valore di 0 significherebbe che non c'è stato un estremo su quella barra.
    • Debug Stampa: Stampa all'interno della funzione DetermineTradingDirection per verificare che il minimo/massimo corretto venga individuato.

    Azioni da Eseguire:

    • Controlla Se Gli Indici dei Buffer Sono Correttamente Impostati: Dipende dall'implementazione di ZigZag se il buffer 0 o 1 viene utilizzato per i minimi/massimi. Verifica nel codice dell'indicatore originale se puoi.
    • Debug Appropriato: Usa molteplici Print per verificare esattamente su che dati stai lavorando, dato che i valori 0 segnalano mancanza di un estremo.

    Testa attentamente nell'ambiente di sviluppo per garantire che le condizioni corrette vengano catturate e che le operazioni siano eseguite.

  21. User

    il mio indicatore zigzag non usa i buffer. studialo di nuovo e verifica come identifica i minimi e i massimi

  22. Assistant

    Se l'indicatore ZigZag che stai utilizzando non fa uso di buffer classici, ma, come suggerisci attraverso il codice fornito in precedenza, utilizza logica interna per identificare minimi e massimi, dobbiamo concentrarci su come questi vengono calcolati e restituiti.

    Dal codice originale che hai condiviso, l'indicatore ZigZag trova i minimi e massimi utilizzando le seguenti logiche:

    1. Minimo: Trovato usando la funzione iLowest, che identifica il valore più basso in un dato periodo.
    2. Massimo: Trovato usando la funzione iHighest, che identifica il valore più alto in un dato periodo.
    3. Settaggio degli Estremi: Gli estremi vengono successivamente registrati nei rispettivi buffer ExtLowBuffer e ExtHighBuffer.

    Basato sulla logica, possiamo monitorare i valori di ExtLowBuffer e ExtHighBuffer per estrapolare i minimi e i massimi.

    Ecco un esempio su come potresti modificare l'EA per utilizzare questi dati identificati dall'indicatore ZigZag:

    Il presupposto avviene sui buffer generati e non sugli iCustom poiché tale operatività si basa su un ragionamento logico creato all'interno del tuo indicatore:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Copyright 2023, Your Name                      |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        if (Bars < InpDepth230) return;
    
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        // Manage trades
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double rsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
        double prevRsiValue = iRSI(NULL, 0, 6, PRICE_CLOSE, 2);
    
        // Buy logic
        if (okBUY)
        {
            double last12Min = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 1);
            if (last12Min > 0 && prevRsiValue < 30 && rsiValue > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, sl, tp, "Buy ZigZag EA", 0, 0, Green);
    
                if (ticket < 0)
                {
                    Print("Buy OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Buy Order opened with ticket #", ticket);
                }
            }
        }
    
        // Sell logic
        if (okSELL)
        {
            double last12Max = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 1);
            if (last12Max > 0 && prevRsiValue > 70 && rsiValue < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 3, sl, tp, "Sell ZigZag EA", 0, 0, Red);
    
                if (ticket < 0)
                {
                    Print("Sell OrderSend failed with error #", GetLastError());
                }
                else
                {
                    Print("Sell Order opened with ticket #", ticket);
                }
            }
        }
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag                         |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        for (int i = 0; i < Bars; i++)
        {
            // Calculate extents
            double zzValue230Min = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, i);
            double zzValue230Max = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, i);
    
            if (zzValue230Min > 0)
            {
                // Found a new minimum in ZigZag 230
                okBUY = true;
                okSELL = false;
                Print("Minimum found for BUY.");
                break; // Once found, break out
            }
    
            if (zzValue230Max > 0)
            {
                // Found a new maximum in ZigZag 230
                okSELL = true;
                okBUY = false;
                Print("Maximum found for SELL.");
                break; // Once found, break out
            }
        }
    }
    

    Istruzioni:

    • Extract ZigZag Values: Scrivi estrazioni da ZigZag e considerali come base per la tua logica di trading.
    • Buffer Management: Assicurati di interrogare i buffer corretti con opportuni controlli su valori che indicano effettivamente la presenza di un minimo o di un massimo.
    • Impostazioni di Validità: Valida che le condizioni trovino effettivamente i nuovi minimi/massimi fissando un break nel loop per verificare risultati in sequenza.

    Debug e Verifiche

    • Print Statements: Utilizza Print nei punti critici per confermare i valori attesi come zzValue230Min e zzValue230Max.
    • Strategia di Test: Esamina il comportamento del tuo EA nel Strategy Tester di MetaTrader per identificare i minimi e massimi corretti basati sulla logica dell'indicatore. Se il comportamento non è come previsto, verifica i calcoli interni e i risultati dell'indicatore.

    L'obiettivo è consolidare il modo di estrazione dei picchi e assicurarne un uso corretto nel sistema di trading.

  23. User

    perchè setti questa condizione last12Min > 0?

  24. Assistant

    La condizione last12Min > 0 viene usata per verificare se l'indicatore ZigZag ha segnato un minimo in un punto specifico. Tuttavia, questa logica non è sempre appropriata per tutti i tipi di implementazioni di ZigZag, specialmente se l'indicatore non sta usando buffer standard o se il controllo può restituire valori negativi o esattamente zero a seconda dell'approccio dell'implementazione.

    Se il ZigZag non usa buffer classici o restituisce differenti valori per minimi, dovresti rivedere il codice dell'indicatore stesso per capire come segna i minimi e massimi. Può essere che i minimi non siano rappresentati semplicemente da valori diversi da zero.

    Cosa Fare?

    Controlla il Codice dell'Indicatore:

    Assicurati di interpretare correttamente il codice dell'indicatore per estrapolare i valori di minimo e massimo. Se l'indicazione per un minimo è specifica, ad esempio, controlla quel riferimento.

    Valutazione nei Blocchi Correlati:

    Dalla tua descrizione originale, abbiamo:

    • iLowest(NULL, 0, MODE_LOW, InpDepth, i): troverebbe l'indice del minimo e quindi useresti low[index] per ricavare quel valore. Assicurati che sia interpretato come dovrebbe.

    Se stiamo cercando di ricostruire nel tuo spazio logico possiamo utilizzare la logica del caricamento di valori articolati come mostrato precedentemente:

    Esempio Revisione

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|getName, Copyright 2023, Your Name                                |
    //|http://www.yourwebsite.com                                        |
    //+------------------------------------------------------------------+
    #property copyright "2023, Your Name"
    #property link      "http://www.yourwebsite.com"
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // in pips
    input double TakeProfit = 100; // in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int OnDeinit(const int reason)
    {
        return(0);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        if (Bars < InpDepth230) return;  // Assicurarsi che ci siano abbastanza barre
    
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag                         |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        double zz230Min = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, 0);
        double zz230Max = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, 0);
    
        if (zz230Min > 0) // Se esiste un valore di minimo
        {
            okBUY = true;
            okSELL = false;
            Print("ZigZag Minimum identified. Ready for BUY signals.");
        }
        else if (zz230Max > 0) // Se esiste un valore di massimo
        {
            okSELL = true;
            okBUY = false;
            Print("ZigZag Maximum identified. Ready for SELL signals.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
        double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
        if (okBUY)
        {
            double zz12Min = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 0);
            if (zz12Min > 0 && prevRSI < 30 && currentRSI > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                if (ticket < 0)
                    Print("Error opening Buy Order: ", GetLastError());
            }
        }
        else if (okSELL)
        {
            double zz12Max = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 0);
            if (zz12Max > 0 && prevRSI > 70 && currentRSI < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
                if (ticket < 0)
                    Print("Error opening Sell Order: ", GetLastError());
            }
        }
    }
    

    Riflessioni

    • Approccio Iterativo: Stiamo saltando su valori 0 nei controlli. Altrimenti, dovresti stabilire un campione/norme su come una soglia definisce un picco.
    • Correzioni Print() per Debug: Usa Print strategicamente per vedere se viene selezionato un nuovo minimo/massimo.
    • Validità del Buffer: Dati non prelevati dai buffer devono far riflettere su come si legge dal ZZ230.

    Riassumendo, bisogna essere chiari sul comportamento del tuo specifico ZigZag per implementare correttamente la logica trasformando questi picchi in segnali praticabili.

  25. User

    c'è qualcosa che non va. apre solamente operazioni buy e ne apre tantissime nello stesso istante, proabilmente non rispetta l'rsi o le altre condizioni

  26. Assistant

    Se l'EA sta aprendo molte operazioni contemporaneamente e non sta rispettando condizioni come quelle dell'RSI, è importante rivedere e assicurarsi che le condizioni siano implementate correttamente e che l'EA non stia eseguendo ordini ripetuti quando non dovrebbe.

    Ecco alcuni punti chiave su cui concentrarti per risolvere questi problemi:

    1. Controllo delle Condizioni:

      • Assicurati che le condizioni del tuo EA siano ben definite.
      • Verifica che le condizioni RSI siano rispettate solo al momento dell'incrocio dei livelli specificati.
    2. Limitazione delle Operazioni Aperte:

      • Aggiungi logiche per assicurarti che non vengano aperti più ordini contemporaneamente senza motivo.
      • Usa funzioni come OrdersTotal per contare quante operazioni sono aperte e per prevenire nuove aperture se un'operazione dello stesso tipo è già esistente.
    3. Debug e Logica dell'RSI:

      • Utilizza Print per verificare i valori di RSI e assicurarti che stiano superando correttamente le soglie di 30 e 70.

    Ecco un aggiornamento del codice con controllo aggiuntivo per evitare ordini ripetuti e garantire che siano seguite correttamente le condizioni:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                   Expert Advisor: Improved Version               |
    //+------------------------------------------------------------------+
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // in pips
    input double TakeProfit = 100; // in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int OnDeinit(const int reason)
    {
        return(0);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        if (Bars < InpDepth230) return;  // Assicurarsi che ci siano abbastanza dati
    
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        // Gestione degli ordini
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag                         |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        double zz230Min = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, 0);
        double zz230Max = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, 0);
    
        if (zz230Min != 0)
        {
            okBUY = true;
            okSELL = false;
            Print("ZigZag Minimum identified. Ready for BUY signals.");
        }
        else if (zz230Max != 0)
        {
            okSELL = true;
            okBUY = false;
            Print("ZigZag Maximum identified. Ready for SELL signals.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
        double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
        // Controlla se ci sono operazioni aperte per evitare ripetizioni
        int buyOrders = 0;
        int sellOrders = 0;
        
        for(int i = 0; i < OrdersTotal(); i++)
        {
            if(OrderSelect(i, SELECT_BY_POS))
            {
                if(OrderType() == OP_BUY && OrderSymbol() == Symbol())
                    buyOrders++;
                if(OrderType() == OP_SELL && OrderSymbol() == Symbol())
                    sellOrders++;
            }
        }
    
        // Logica per ordini BUY
        if (okBUY && buyOrders == 0)
        {
            double zz12Min = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 0);
            if (zz12Min != 0 && prevRSI < 30 && currentRSI > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                if (ticket < 0)
                    Print("Error opening Buy Order: ", GetLastError());
            }
        }
    
        // Logica per ordini SELL
        if (okSELL && sellOrders == 0)
        {
            double zz12Max = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 0);
            if (zz12Max != 0 && prevRSI > 70 && currentRSI < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
                if (ticket < 0)
                    Print("Error opening Sell Order: ", GetLastError());
            }
        }
    }
    

    Cosa è stato migliorato:

    • Controllo Ordini Esistenti: L'EA ora conta gli ordini esistenti per il simbolo corrente in modo da evitare di aprire ordini duplicati.
    • Condizioni RSI: Verifica che l'RSI abbia effettivamente attraversato la soglia corretta solo se unique.
    • Debug Log: Usa Print per controllare che le condizioni vengano valutate nel modo atteso e che le informazioni sulla transazione siano chiare.

    Queste modifiche dovrebbero aiutarti a prevenire l'apertura di ordine duplicati e ad assicurarti che le condizioni RSI siano considerate nel modo corretto. Verifica attentamente il blocco del codice della tua logica di trading relativa all'indicatore e sugli ordini per eventuali correzioni necessarie. Usa Strategy Tester per ulteriori debug e ottimizzazioni.

  27. User

    non funzione. zigzag non viene interpretato nel modo corretto. questo è il codice completo dell'indicatore //+------------------------------------------------------------------+ //| ZigZag.mq4 | //| Copyright 2006-2014, MetaQuotes Software Corp. | //| http://www.mql4.com | //+------------------------------------------------------------------+ #property copyright "2006-2014, MetaQuotes Software Corp." #property link "http://www.mql4.com" #property strict

    #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Red //---- indicator parameters input int InpDepth=12; // Depth input int InpDeviation=5; // Deviation input int InpBackstep=3; // Backstep //---- indicator buffers double ExtZigzagBuffer[]; double ExtHighBuffer[]; double ExtLowBuffer[]; //--- globals int ExtLevel=3; // recounting's depth of extremums //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int OnInit() { if(InpBackstep>=InpDepth) { Print("Backstep cannot be greater or equal to Depth"); return(INIT_FAILED); } //--- 2 additional buffers IndicatorBuffers(3); //---- drawing settings SetIndexStyle(0,DRAW_SECTION); //---- indicator buffers SetIndexBuffer(0,ExtZigzagBuffer); SetIndexBuffer(1,ExtHighBuffer); SetIndexBuffer(2,ExtLowBuffer); SetIndexEmptyValue(0,0.0); //---- indicator short name IndicatorShortName("ZigZag("+string(InpDepth)+","+string(InpDeviation)+","+string(InpBackstep)+")"); //---- initialization done return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int OnCalculate(const int rates_total, const int prev_calculated, const datetime &time[], const double &open[], const double &high[], const double &low[], const double &close[], const long& tick_volume[], const long& volume[], const int& spread[]) { int i,limit,counterZ,whatlookfor=0; int back,pos,lasthighpos=0,lastlowpos=0; double extremum; double curlow=0.0,curhigh=0.0,lasthigh=0.0,lastlow=0.0; //--- check for history and inputs if(rates_total<InpDepth || InpBackstep>=InpDepth) return(0); //--- first calculations if(prev_calculated==0) limit=InitializeAll(); else { //--- find first extremum in the depth ExtLevel or 100 last bars i=counterZ=0; while(counterZ<ExtLevel && i<100) { if(ExtZigzagBuffer[i]!=0.0) counterZ++; i++; } //--- no extremum found - recounting all from begin if(counterZ==0) limit=InitializeAll(); else { //--- set start position to found extremum position limit=i-1; //--- what kind of extremum? if(ExtLowBuffer[i]!=0.0) { //--- low extremum curlow=ExtLowBuffer[i]; //--- will look for the next high extremum whatlookfor=1; } else { //--- high extremum curhigh=ExtHighBuffer[i]; //--- will look for the next low extremum whatlookfor=-1; } //--- clear the rest data for(i=limit-1; i>=0; i--)
    { ExtZigzagBuffer[i]=0.0;
    ExtLowBuffer[i]=0.0; ExtHighBuffer[i]=0.0; } } } //--- main loop
    for(i=limit; i>=0; i--) { //--- find lowest low in depth of bars extremum=low[iLowest(NULL,0,MODE_LOW,InpDepth,i)]; //--- this lowest has been found previously if(extremum==lastlow) extremum=0.0; else { //--- new last low lastlow=extremum; //--- discard extremum if current low is too high if(low[i]-extremum>InpDeviationPoint) extremum=0.0; else { //--- clear previous extremums in backstep bars for(back=1; back<=InpBackstep; back++) { pos=i+back; if(ExtLowBuffer[pos]!=0 && ExtLowBuffer[pos]>extremum) ExtLowBuffer[pos]=0.0; } } } //--- found extremum is current low if(low[i]==extremum) ExtLowBuffer[i]=extremum; else ExtLowBuffer[i]=0.0; //--- find highest high in depth of bars extremum=high[iHighest(NULL,0,MODE_HIGH,InpDepth,i)]; //--- this highest has been found previously if(extremum==lasthigh) extremum=0.0; else { //--- new last high lasthigh=extremum; //--- discard extremum if current high is too low if(extremum-high[i]>InpDeviationPoint) extremum=0.0; else { //--- clear previous extremums in backstep bars for(back=1; back<=InpBackstep; back++) { pos=i+back; if(ExtHighBuffer[pos]!=0 && ExtHighBuffer[pos]<extremum) ExtHighBuffer[pos]=0.0; } } } //--- found extremum is current high if(high[i]==extremum) ExtHighBuffer[i]=extremum; else ExtHighBuffer[i]=0.0; } //--- final cutting if(whatlookfor==0) { lastlow=0.0; lasthigh=0.0;
    } else { lastlow=curlow; lasthigh=curhigh; } for(i=limit; i>=0; i--) { switch(whatlookfor) { case 0: // look for peak or lawn if(lastlow==0.0 && lasthigh==0.0) { if(ExtHighBuffer[i]!=0.0) { lasthigh=High[i]; lasthighpos=i; whatlookfor=-1; ExtZigzagBuffer[i]=lasthigh; } if(ExtLowBuffer[i]!=0.0) { lastlow=Low[i]; lastlowpos=i; whatlookfor=1; ExtZigzagBuffer[i]=lastlow; } } break;
    case 1: // look for peak if(ExtLowBuffer[i]!=0.0 && ExtLowBuffer[i]<lastlow && ExtHighBuffer[i]==0.0) { ExtZigzagBuffer[lastlowpos]=0.0; lastlowpos=i; lastlow=ExtLowBuffer[i]; ExtZigzagBuffer[i]=lastlow; } if(ExtHighBuffer[i]!=0.0 && ExtLowBuffer[i]==0.0) { lasthigh=ExtHighBuffer[i]; lasthighpos=i; ExtZigzagBuffer[i]=lasthigh; whatlookfor=-1; }
    break;
    case -1: // look for lawn if(ExtHighBuffer[i]!=0.0 && ExtHighBuffer[i]>lasthigh && ExtLowBuffer[i]==0.0) { ExtZigzagBuffer[lasthighpos]=0.0; lasthighpos=i; lasthigh=ExtHighBuffer[i]; ExtZigzagBuffer[i]=lasthigh; } if(ExtLowBuffer[i]!=0.0 && ExtHighBuffer[i]==0.0) { lastlow=ExtLowBuffer[i]; lastlowpos=i; ExtZigzagBuffer[i]=lastlow; whatlookfor=1; }
    break;
    } } //--- done return(rates_total); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int InitializeAll() { ArrayInitialize(ExtZigzagBuffer,0.0); ArrayInitialize(ExtHighBuffer,0.0); ArrayInitialize(ExtLowBuffer,0.0); //--- first counting position return(Bars-InpDepth); } //+------------------------------------------------------------------+

  28. Assistant

    Grazie per aver fornito il codice completo dell'indicatore ZigZag. Esaminiamo come migliorare l'interpretazione dei minimi e massimi che l'EA dovrebbe utilizzare per aprire le operazioni, basandoci sull'implementazione dell'indicatore.

    Comprensione dell'indicatore ZigZag:

    L'indicatore ZigZag utilizza tre buffer:

    • ExtZigzagBuffer: segnala i picchi rilevati dall'indicatore.
    • ExtLowBuffer e ExtHighBuffer: vengono utilizzati per individuare rispettivamente i minimi bassi e alti, ma alla fine forniscono gli stessi valori al buffer ExtZigzagBuffer.

    Estrarre Dati dai Buffer:

    Per estrarre correttamente i valori di minimo e massimo, possiamo accedere direttamente ai buffer ExtLowBuffer e ExtHighBuffer, poiché sono quelli che catturano i minimi e massimi prima che vengano trasferiti al ExtZigzagBuffer.

    Codice dell'EA Aggiornato:

    Ecco un esempio aggiornato del tuo EA per utilizzare correttamente l'indicatore ZigZag:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|               EA: Using ZigZag for trades based on peaks        |
    //+------------------------------------------------------------------+
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // in pips
    input double TakeProfit = 100; // in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int OnDeinit(const int reason)
    {
        return(0);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        if (Bars < InpDepth230) return;
    
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag                         |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        // Carica buffer per minimi e massimi del ZigZag a 230
        double zz230Low = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 2, 0);
        double zz230High = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, 0);
    
        if (zz230Low != 0.0) // Se esiste un valore di minimo
        {
            okBUY = true;
            okSELL = false;
            Print("ZigZag Minimum identified. Ready for BUY signals.");
        }
        else if (zz230High != 0.0) // Se esiste un valore di massimo
        {
            okSELL = true;
            okBUY = false;
            Print("ZigZag Maximum identified. Ready for SELL signals.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
        double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
        int totalOrders = OrdersTotal();
        int buyOrders = 0;
        int sellOrders = 0;
        
        for(int i = 0; i < totalOrders; i++)
        {
            if(OrderSelect(i, SELECT_BY_POS))
            {
                if(OrderType() == OP_BUY && OrderSymbol() == Symbol())
                    buyOrders++;
                if(OrderType() == OP_SELL && OrderSymbol() == Symbol())
                    sellOrders++;
            }
        }
    
        if (okBUY && buyOrders == 0)
        {
            double zz12Low = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 2, 0);
            if (zz12Low != 0.0 && prevRSI < 30 && currentRSI > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                if (ticket < 0)
                    Print("Error opening Buy Order: ", GetLastError());
            }
        }
    
        if (okSELL && sellOrders == 0)
        {
            double zz12High = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 0);
            if (zz12High != 0.0 && prevRSI > 70 && currentRSI < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
                if (ticket < 0)
                    Print("Error opening Sell Order: ", GetLastError());
            }
        }
    }
    

    Spiegazione del Codice:

    • Buffer del ZigZag: Ho assicurato di usare i buffer giusti [1] per il massimo e [2] per il minimo.
    • Check sui Valori: Massimi e minimi sono controllati per valori diversi da zero.
    • Condizione RSI: Assicurarsi di non eseguire il codice qualora l'RSI non rispetti l'incrocio stabilito.

    Consigli:

    • Testare su Demo: Testa sempre in un ambiente demo prima di andare in reale.
    • Logs: Cerca di mantenere i Print() nei punti chiave per il debugging al fine di verificare i flussi di logica.

    Spero che questo possa aiutarti a raggiungere i risultati desiderati!

  29. User

    secondo me stai facendo confusione. come fai ad impostare zz230Low != 0.0 e zz230High != 0.0 per due operazione contrarie?? rivedi tutto, così non funziona

  30. Assistant

    Hai ragione, c'è della confusione nella logica di controllo dei valori ZigZag tra minimi e massimi. Verifichiamo come avviene il rilevamento dei picchi nell'indicatore ZigZag che hai postato, per poter implementare correttamente l'Expert Advisor (EA).

    Comprensione Generale dell'Indicatore ZigZag dal Codice:

    L'indicatore ZigZag si basa sulla logica che contrassegna i punti di massimo e minimo e salva questi valori selezionati in buffer separati (ExtLowBuffer e ExtHighBuffer):

    • ExtLowBuffer: memorizza i minimi significativi.
    • ExtHighBuffer: memorizza i massimi significativi.
    • ExtZigzagBuffer: viene utilizzato per collegare gli estremi e disegnare la linea ZigZag.

    Struttura dell'EA Corretto:

    L'obiettivo è di monitorare questi buffer per avviare operazioni di acquisto (buy) sui minimi e operazioni di vendita (sell) sui massimi, sempre con l'ausilio del RSI per confermare l'immissione sul mercato.

    Ecco come puoi strutturare il tuo EA:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|               EA: Correct Usage of ZigZag for Trading           |
    //+------------------------------------------------------------------+
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // in pips
    input double TakeProfit = 100; // in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int OnDeinit(const int reason)
    {
        return(0);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        if (Bars < InpDepth230) return;
    
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag                         |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        // Verifica massimo e minimo dall'indicatore ZigZag230
        double zz230Low = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 2, 0);
        double zz230High = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, 0);
    
        if (zz230Low != 0.0) // Quando il ZigZag trova un minimo
        {
            okBUY = true;
            okSELL = false;
            Print("ZigZag Minimum identified. Ready for BUY signals.");
        }
        else if (zz230High != 0.0) // Quando il ZigZag trova un massimo
        {
            okSELL = true;
            okBUY = false;
            Print("ZigZag Maximum identified. Ready for SELL signals.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
        double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
        int totalOrders = OrdersTotal();
        int buyOrders = 0;
        int sellOrders = 0;
        
        for(int i = 0; i < totalOrders; i++)
        {
            if(OrderSelect(i, SELECT_BY_POS))
            {
                if(OrderType() == OP_BUY && OrderSymbol() == Symbol())
                    buyOrders++;
                if(OrderType() == OP_SELL && OrderSymbol() == Symbol())
                    sellOrders++;
            }
        }
    
        // Se okBUY è vero, apri un ordine di acquisto (assicurati che non ci siano altri ordini buy aperti)
        if (okBUY && buyOrders == 0)
        {
            double zz12Low = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 2, 0);
            if (zz12Low != 0.0 && prevRSI < 30 && currentRSI > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                if (ticket < 0)
                    Print("Error opening Buy Order: ", GetLastError());
            }
        }
    
        // Se okSELL è vero, apri un ordine di vendita (assicurati che non ci siano altri ordini sell aperti)
        if (okSELL && sellOrders == 0)
        {
            double zz12High = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 0);
            if (zz12High != 0.0 && prevRSI > 70 && currentRSI < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
                if (ticket < 0)
                    Print("Error opening Sell Order: ", GetLastError());
            }
        }
    }
    

    Logica dell'EA:

    • DetermineTradingDirection(): Imposta okBUY e okSELL in base al rilevamento di un minimo o massimo nel ZigZag con profondità 230.
    • ManageOrders(): Monitora le condizioni degli ordini ed esegue un nuovo ordine solo quando non ci sono ordini dello stesso tipo aperti e il segnale di RSI si verifica.

    Considerazioni Finali:

    • Buffer Accurati: Assicurati di controllare i buffer corretti secondo il tuo indicatore.
    • Debugging: Utilizza stampe Print() per verificare i valori effettivi e che le condizioni siano verificate come previsto.
    • Testing: Verifica il comportamento in ambiente demo o Strategy Tester per fare eventuali modifiche correttive.

    Questa struttura dovrebbe aiutarti a integrare correttamente il tuo EA con l'indicatore ZigZag come richiesto.

  31. User

    hai scritto lo stesso errore. due condizioni contrarie fanno lo stesso check!

  32. Assistant

    Ti chiedo scusa per l'errore. Ho frainteso il modo in cui utilizzare i buffer dell'indicatore ZigZag. Vediamo di chiarire le condizioni corrette per l'apertura di posizioni di acquisto e vendita basate sui minimi e massimi identificati dall'indicatore.

    Correzione della Logica:

    1. Determinare lo Stato di okBUY e okSELL:

      • okBUY deve essere impostato su true quando il ZigZag 230 trova un minimo (indicando un potenziale inizio di tendenza rialzista).
      • okSELL deve essere impostato su true quando il ZigZag 230 trova un massimo (indicando un potenziale inizio di tendenza ribassista).
    2. Operazioni di Acquisto e Vendita:

      • Apri un'operazione di acquisto quando c'è un estremo minimo sul ZigZag 12 dopo che okBUY è stato dichiarato vero, e il RSI conferma il segnale.
      • Apri un'operazione di vendita quando c'è un estremo massimo sul ZigZag 12 dopo che okSELL è stato dichiarato vero, e il RSI conferma il segnale.

    Codice Corretto:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|               EA: Accurate Use of ZigZag for Trading            |
    //+------------------------------------------------------------------+
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // in pips
    input double TakeProfit = 100; // in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return(INIT_SUCCEEDED);
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int OnDeinit(const int reason)
    {
        return(0);
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        if (Bars < InpDepth230) return;
    
        static int prevBars = 0;
        int currentBars = Bars;
    
        if (currentBars != prevBars)
        {
            DetermineTradingDirection();
            prevBars = currentBars;
        }
    
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag                         |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        // Accesso ai buffer dell'indicatore ZigZag230
        double zz230Low = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 2, 1);
        double zz230High = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, 1);
    
        // Assicurati che le condizioni di acquisto e vendita non siano true contemporaneamente
        if (zz230Low != 0.0)
        {
            okBUY = true; // Segnale per considerare solo acquisti
            okSELL = false;
            Print("ZigZag Minimum signal detected. BUY mode activated.");
        }
        if (zz230High != 0.0)
        {
            okSELL = true; // Segnale per considerare solo vendite
            okBUY = false;
            Print("ZigZag Maximum signal detected. SELL mode activated.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Manage Orders based on signals                                   |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
        double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
        int buyOrders = 0;
        int sellOrders = 0;
    
        for (int i = 0; i < OrdersTotal(); i++)
        {
            if (OrderSelect(i, SELECT_BY_POS))
            {
                if (OrderType() == OP_BUY && OrderSymbol() == Symbol())
                    buyOrders++;
                if (OrderType() == OP_SELL && OrderSymbol() == Symbol())
                    sellOrders++;
            }
        }
    
        // Procedura di acquisto
        if (okBUY && buyOrders == 0)
        {
            double zz12Low = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 2, 1);
            if (zz12Low != 0.0 && prevRSI < 30 && currentRSI > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                if (ticket < 0)
                    Print("Error opening Buy Order: ", GetLastError());
            }
        }
    
        // Procedura di vendita
        if (okSELL && sellOrders == 0)
        {
            double zz12High = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 1);
            if (zz12High != 0.0 && prevRSI > 70 && currentRSI < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
                if (ticket < 0)
                    Print("Error opening Sell Order: ", GetLastError());
            }
        }
    }
    

    Spiegazione Aggiornata:

    • Minimi e Massimi del ZigZag: Accesso ai buffer corretti per distinguere tra minimi e massimi usando gli indici dei buffer dell'indicatore originale.
    • Correzione delle Condizioni: Assicurati che okBUY e okSELL non siano mai true simultaneamente. Alterazione della logica che consente di gestire distintamente segnali di entrambi i lati del mercato.
    • Risoluzione del Trading: Ora l'EA apre operazioni solo quando vengono rilevati i segnali corretti e non quando le condizioni di posizione opposte sono valide contemporaneamente.

    Assicurati di testarlo ampiamente per confermare che l'EA ora risponda correttamente ai segnali di trading identificati dai segnali ZigZag e le indicazioni RSI.

  33. User

    no non funziona. l'rsi e il zigzag 230 viene ignorato per i segnali

  34. Assistant

    Mi dispiace per l'inconveniente. Rivediamo attentamente il codice dell'EA per assicurarci che utilizzi correttamente i segnali provenienti dall'indicatore ZigZag e dall'RSI. Ci assicureremo che:

    1. ZigZag 230: Serva a determinare il trend attuale (okBUY o okSELL).
    2. ZigZag 12: Identifichi i punti di entrata all'interno del trend crescente o calante.
    3. RSI: Confermi i segnali di entrata.

    Assicurati che l'EA stia gestendo correttamente le condizioni di entrata

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|               EA: Accurate Use of ZigZag e RSI for Trading       |
    //+------------------------------------------------------------------+
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // in pips
    input double TakeProfit = 100; // in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return INIT_SUCCEEDED;
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int OnDeinit(const int reason)
    {
        return 0;
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        // Assicurati che ci siano abbastanza barre storiche
        if (Bars < InpDepth230) return;
    
        static int prevCalcBars = 0;
        int currentBars = Bars;
    
        // Solo calcola nuove condizioni quando ci sono nuove barre
        if (currentBars != prevCalcBars)
        {
            DetermineTradingDirection();
            prevCalcBars = currentBars;
        }
    
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction based on ZigZag 230                  |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        // ZigZag 230 per determinare la tendenza corrente
        double zz230Min = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 2, 1);
        double zz230Max = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, 1);
    
        // Stabilire trend basato su ZigZag 230
        if (zz230Min != 0.0) // Quando ZigZag 230 trova un minimo
        {
            okBUY = true;
            okSELL = false;
            Print("Trend bullish rilevato da ZigZag 230: modalità BUY attivata.");
        }
        else if (zz230Max != 0.0) // Quando ZigZag 230 trova un massimo
        {
            okSELL = true;
            okBUY = false;
            Print("Trend bearish rilevato da ZigZag 230: modalità SELL attivata.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Gestione degli ordini in base ai segnali                         |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
        double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
        // Conta gli ordini esistenti
        int buyOrders = 0;
        int sellOrders = 0;
    
        for (int i = 0; i < OrdersTotal(); i++)
        {
            if (OrderSelect(i, SELECT_BY_POS))
            {
                if (OrderType() == OP_BUY && OrderSymbol() == Symbol())
                    buyOrders++;
                if (OrderType() == OP_SELL && OrderSymbol() == Symbol())
                    sellOrders++;
            }
        }
    
        // Processo per aprire un BUY
        if (okBUY && buyOrders == 0)
        {
            double zz12Low = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 2, 1);
            if (zz12Low != 0.0 && prevRSI < 30 && currentRSI > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                if (ticket < 0)
                    Print("Apertura Buy Order errore: ", GetLastError());
            }
        }
    
        // Processo per aprire un SELL
        if (okSELL && sellOrders == 0)
        {
            double zz12High = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 1);
            if (zz12High != 0.0 && prevRSI > 70 && currentRSI < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
                if (ticket < 0)
                    Print("Apertura Sell Order errore: ", GetLastError());
            }
        }
    }
    

    Schema Migliorato:

    • Uso Corretto dei Buffer: zz230Min e zz230Max usano indici di buffer appropriati per distinguere tra minimi (buffer[2]) e massimi (buffer[1]).
    • Conformità alle Condizioni RSI: Aggiunto il controllo incroci dell’RSI, in cui prevRSI deve essere sotto 30 prima e poi sopra per acquisti, e superiore a 70 prima, poi sotto per le vendite.
    • Prevenire Ordini Multipli: Assicura che operazioni duplicate non siano aperte per lo stesso tipo di segnale.

    Aggiornamento:

    1. Debugging: Usa Print() su valori chiave zz230Min, zz230Max, currentRSI, prevRSI per verificare condizioni.
    2. Test su Conto Demo: Verifica il comportamento su diverse condizioni di mercato per assicurarti che l'EA operi come previsto.

    Implementando questo schema, il tuo EA dovrebbe rispondere correttamente ai segnali ZigZag ed RSI per le operazioni di trading.

  35. User

    apre solo operazioni di sell ignorando la direzione di zigzag 230

  36. Assistant

    Capisco che ci sia un problema con la logica di determinazione della direzione basata sul ZigZag 230. Rivediamo il metodo per identificare correttamente i segnali forniti dal ZigZag e come assicurarsi che l'EA li interpreti giustamente.

    Revisione del Codice

    1. Logica Minimi e Massimi: Assicurati di verificare correttamente i buffer che rappresentano i minimi e i massimi per il setting di direzione.
    2. Debugging Aggiuntivo: Aggiungi istruzioni di logging per verificare quali valori vengono ottenuti dal ZigZag e cosa li attiva.

    Soluzione:

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|                  EA: Correct Use of ZigZag e RSI                 |
    //+------------------------------------------------------------------+
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // in pips
    input double TakeProfit = 100; // in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return INIT_SUCCEEDED;
    }
    
    //+------------------------------------------------------------------+
    //| Expert deinitialization function                                 |
    //+------------------------------------------------------------------+
    int OnDeinit(const int reason)
    {
        return 0;
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        // Assicurati che ci siano abbastanza barre storiche
        if (Bars < InpDepth230) return;
    
        static int prevCalcBars = 0;
        int currentBars = Bars;
    
        // Solo calcola nuove condizioni quando ci sono nuove barre
        if (currentBars != prevCalcBars)
        {
            DetermineTradingDirection();
            prevCalcBars = currentBars;
        }
    
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction based on ZigZag 230                  |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        // ZigZag 230 per determinare la tendenza corrente
        double zz230Low = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, 0);
        double zz230High = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 0, 0);
    
        // Debugging: stampare i valori del ZigZag
        Print("ZigZag Low: ", zz230Low, ", ZigZag High: ", zz230High);
    
        // Stabilire trend basato su ZigZag 230 
        if (zz230Low > 0.0) // Quando ZigZag 230 identifica un minimo
        {
            okBUY = true;
            okSELL = false;
            Print("Trend bullish rilevato da ZigZag 230: modalità BUY attivata.");
        }
        else if (zz230High > 0.0) // Quando ZigZag 230 identifica un massimo
        {
            okSELL = true;
            okBUY = false;
            Print("Trend bearish rilevato da ZigZag 230: modalità SELL attivata.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Gestione degli ordini in base ai segnali                         |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
        double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
        // Conta gli ordini esistenti
        int buyOrders = 0;
        int sellOrders = 0;
    
        for (int i = 0; i < OrdersTotal(); i++)
        {
            if (OrderSelect(i, SELECT_BY_POS))
            {
                if (OrderType() == OP_BUY && OrderSymbol() == Symbol())
                    buyOrders++;
                if (OrderType() == OP_SELL && OrderSymbol() == Symbol())
                    sellOrders++;
            }
        }
    
        // Processo per aprire un BUY
        if (okBUY && buyOrders == 0)
        {
            double zz12Low = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 0);
            if (zz12Low > 0.0 && prevRSI < 30 && currentRSI > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                if (ticket < 0)
                    Print("Apertura Buy Order errore: ", GetLastError());
            }
        }
    
        // Processo per aprire un SELL
        if (okSELL && sellOrders == 0)
        {
            double zz12High = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 0, 0);
            if (zz12High > 0.0 && prevRSI > 70 && currentRSI < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
                if (ticket < 0)
                    Print("Apertura Sell Order errore: ", GetLastError());
            }
        }
    }
    

    Cosa Controllare:

    • Uso del Buffer 0 per entrambi i check: Se il tuo indicatore ZigZag usa lo stesso buffer per entrambi, la logica dev'essere sicura che il valore sia correttamente interpretato.
    • Valorizzazione di zz230Low e zz230High: Se un valore sale sopra determinati limiti, viene considerato per stabilire la okBUY o okSELL.
    • Debugging: Tieni sempre Print() attivi con le condizioni attuali per verificare il comportamento effettivo del ZigZag nei log.

    Consiglio:

    • Controlla Logs: Usa Journal in MetaTrader per tracciare il benchmark nel processo decisionale. Ciò aiuterà a determinare quali condizioni potrebbero essere ignorate o mal interpretate dall'EA.
    • Visualizza in Strategy Tester: In modalità Visual Mode nel Strategy Tester per monitorare l'introduzione di segnali e debug direttamente sui grafici con il ZigZag sovraimpresso.

    Con questa configurazione, ci sono miglioramenti che dovrebbero aiutarti ad ottenere il comportamento corretto nell'interpretazione e utilizzo dei segnali forniti dall'indicatore ZigZag e l'RSI.

  37. User

    i valori di zigzag sono sempre 0.0

  38. Assistant

    Se i valori di ZigZag ottenuti sono sempre 0.0, è probabile che ci sia un errore nel modo in cui stiamo interrogando l'indicatore usando iCustom. Vediamo come possiamo rettificare la chiamata a iCustom e verificare che stiamo effettivamente ottenendo i dati corretti.

    Verifica della Chiamata iCustom:

    1. Assicurarsi dei Buffer Correttamente Usati: L'indicatore ZigZag che hai fornito utilizza tre buffer:

      • ExtZigzagBuffer: Buffer 0, che non dovrebbe essere interrogato esplicitamente per minimi e massimi, ma disegna la linea.
      • ExtHighBuffer: Buffer 1, memorizza i valori massimi.
      • ExtLowBuffer: Buffer 2, memorizza i valori minimi.
    2. Chiamate corrette a iCustom: Dobbiamo assicurarci di accedere ai buffer corretti.

    Revisione del Codice EA:

    Verifichiamo che il codice acceda correttamente ai buffer sperando di ottenere i valori attesi.

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|               EA: Accurate ZigZag Interpretation                 |
    //+------------------------------------------------------------------+
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // Stop Loss in pips
    input double TakeProfit = 100; // Take Profit in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
       return INIT_SUCCEEDED;
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
       // Assicurati che ci siano abbastanza barre storiche
       if (Bars < InpDepth230) return;
    
       static int prevCalcBars = 0;
       int currentBars = Bars;
    
       // Solo calcola nuove condizioni quando ci sono nuove barre
       if (currentBars != prevCalcBars)
       {
          DetermineTradingDirection();
          prevCalcBars = currentBars;
       }
    
       ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag 230                     |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
       // ZigZag 230 per determinare la tendenza corrente
       double zz230Min = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 2, 0);
       double zz230Max = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, 0);
    
       // Debugging: stampare i valori del ZigZag
       Print("ZigZag Low Buffer: ", zz230Min, ", ZigZag High Buffer: ", zz230Max);
    
       // Stabilire trend basato su ZigZag 230 
       if (zz230Min > 0.0) // Quando ZigZag 230 identifica un minimo
       {
          okBUY = true;
          okSELL = false;
          Print("Trend bullish rilevato da ZigZag 230: modalità BUY attivata.");
       }
       else if (zz230Max > 0.0) // Quando ZigZag 230 identifica un massimo
       {
          okSELL = true;
          okBUY = false;
          Print("Trend bearish rilevato da ZigZag 230: modalità SELL attivata.");
       }
    }
    
    //+------------------------------------------------------------------+
    //| Gestione degli ordini in base ai segnali                         |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
       double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
       double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
       // Conta gli ordini esistenti
       int buyOrders = 0;
       int sellOrders = 0;
    
       for (int i = 0; i < OrdersTotal(); i++)
       {
          if (OrderSelect(i, SELECT_BY_POS))
          {
             if (OrderType() == OP_BUY && OrderSymbol() == Symbol())
                buyOrders++;
             if (OrderType() == OP_SELL && OrderSymbol() == Symbol())
                sellOrders++;
          }
       }
    
       // Processo per aprire un BUY
       if (okBUY && buyOrders == 0)
       {
          double zz12Low = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 2, 0);
          if (zz12Low > 0.0 && prevRSI < 30 && currentRSI > 30)
          {
             double sl = Ask - StopLoss * Point;
             double tp = Ask + TakeProfit * Point;
             int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
             if (ticket < 0)
                Print("Apertura Buy Order errore: ", GetLastError());
          }
       }
    
       // Processo per aprire un SELL
       if (okSELL && sellOrders == 0)
       {
          double zz12High = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 0);
          if (zz12High > 0.0 && prevRSI > 70 && currentRSI < 70)
          {
             double sl = Bid + StopLoss * Point;
             double tp = Bid - TakeProfit * Point;
             int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
             if (ticket < 0)
                Print("Apertura Sell Order errore: ", GetLastError());
          }
       }
    }
    

    Controlli Finali:

    • Assicurati che l'indicatore sia inserito senza errori: Assicurati che l'indicatore ZigZag sia correttamente caricato in MetaTrader e che il percorso dell'indicatore sia preciso.
    • Buffer Corretti: Controlla che i valori cercati stiano effettivamente tracciando ciò che credi stiano monitorando i buffer — minimi in [2], massimi in [1].
    • Debugging Attivo: Controlla il Journal e stampa console per garantire che i valori siano popolati effettivamente.
    • Compatibility Check: Assicurati che non ci siano conflitti nella versione dell'indicatore rispetto alle chiamate iCustom.

    Se continuano ad esserci problemi, potrebbe essere necessario un ulteriore livello di verifica per assicurarsi che nessuna parte del flusso logico stia influenzando il comportamento dell'indicatore.

  39. User

    stesso errore

  40. Assistant

    Mi dispiace per gli inconvenienti, e apprezzo la tua pazienza. Dato che i valori risultano sempre zero, ciò potrebbe indicare un problema di accesso ai buffer o un modo errato di chiamare l'indicatore con iCustom. Assicuriamoci di seguire attentamente i passi per accedere correttamente ai dati.

    Controllare i Passi:

    1. Nome e Posizione dell'Indicatore: Assicurati di chiamare l'indicatore col nome preciso. Assicurati che l'indicatore è all'interno della cartella Experts/Indicators nel tuo terminale MetaTrader.

    2. Corretta Inizializzazione dei Buffer: Verifica di accedere correttamente ai differenti buffer. Utilizzando il codice dell'indicatore condiviso:

      • Buffer 0: ExtZigzagBuffer, la linea disegnata.
      • Buffer 1: ExtHighBuffer, che contiene massimi.
      • Buffer 2: ExtLowBuffer, che contiene minimi.
    3. Verifica Runtime: Usa debug e stampa per controllare quali valori stiano arrivando da iCustom.

    Revisione del Codice:

    Diamo un’occhiata al codice con particolare attenzione all'accesso ai buffer corretti.

    //+------------------------------------------------------------------+
    //|                                                      ZigZagEA.mq4|
    //|              EA: Correct Interpretation of ZigZag Buffers       |
    //+------------------------------------------------------------------+
    #property strict
    
    input int InpDepth12 = 12;
    input int InpDepth230 = 230;
    input int InpDeviation = 5;
    input int InpBackstep = 3;
    input double LotSize = 0.1;
    input double StopLoss = 50;   // in pips
    input double TakeProfit = 100; // in pips
    
    bool okBUY = false;
    bool okSELL = false;
    
    //+------------------------------------------------------------------+
    //| Expert initialization function                                   |
    //+------------------------------------------------------------------+
    int OnInit()
    {
        return INIT_SUCCEEDED;
    }
    
    //+------------------------------------------------------------------+
    //| Expert tick function                                             |
    //+------------------------------------------------------------------+
    void OnTick()
    {
        // Assicurati che ci siano abbastanza barre storiche
        if (Bars < InpDepth230) return;
    
        static int prevCalcBars = 0;
        int currentBars = Bars;
    
        // Solo calcola nuove condizioni quando ci sono nuove barre
        if (currentBars != prevCalcBars)
        {
            DetermineTradingDirection();
            prevCalcBars = currentBars;
        }
    
        ManageOrders();
    }
    
    //+------------------------------------------------------------------+
    //| Determine trading direction using ZigZag 230                     |
    //+------------------------------------------------------------------+
    void DetermineTradingDirection()
    {
        // Controlla i buffer corretti per minimi e massimi
        double zz230Min = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 2, 1);
        double zz230Max = iCustom(NULL, 0, "ZigZag", InpDepth230, InpDeviation, InpBackstep, 1, 1);
    
        // Debugging: stampare i valori del ZigZag
        Print("ZigZag Low Buffer: ", zz230Min, ", ZigZag High Buffer: ", zz230Max);
    
        // Stabilire trend basato su ZigZag 230 
        if (zz230Min != 0.0) // Quando ZigZag 230 identifica un minimo
        {
            okBUY = true;
            okSELL = false;
            Print("Trend bullish rilevato da ZigZag 230: modalità BUY attivata.");
        }
        else if (zz230Max != 0.0) // Quando ZigZag 230 identifica un massimo
        {
            okSELL = true;
            okBUY = false;
            Print("Trend bearish rilevato da ZigZag 230: modalità SELL attivata.");
        }
    }
    
    //+------------------------------------------------------------------+
    //| Gestione degli ordini in base ai segnali                         |
    //+------------------------------------------------------------------+
    void ManageOrders()
    {
        double currentRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 0);
        double prevRSI = iRSI(NULL, 0, 6, PRICE_CLOSE, 1);
    
        // Conta gli ordini esistenti
        int buyOrders = 0;
        int sellOrders = 0;
    
        for (int i = 0; i < OrdersTotal(); i++)
        {
            if (OrderSelect(i, SELECT_BY_POS))
            {
                if (OrderType() == OP_BUY && OrderSymbol() == Symbol())
                    buyOrders++;
                if (OrderType() == OP_SELL && OrderSymbol() == Symbol())
                    sellOrders++;
            }
        }
    
        // Processo per aprire un BUY
        if (okBUY && buyOrders == 0)
        {
            double zz12Low = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 2, 1);
            if (zz12Low != 0.0 && prevRSI < 30 && currentRSI > 30)
            {
                double sl = Ask - StopLoss * Point;
                double tp = Ask + TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, sl, tp, "Buy ZigZag EA", 0, 0, Green);
                if (ticket < 0)
                    Print("Apertura Buy Order errore: ", GetLastError());
            }
        }
    
        // Processo per aprire un SELL
        if (okSELL && sellOrders == 0)
        {
            double zz12High = iCustom(NULL, 0, "ZigZag", InpDepth12, InpDeviation, InpBackstep, 1, 1);
            if (zz12High != 0.0 && prevRSI > 70 && currentRSI < 70)
            {
                double sl = Bid + StopLoss * Point;
                double tp = Bid - TakeProfit * Point;
                int ticket = OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, sl, tp, "Sell ZigZag EA", 0, 0, Red);
                if (ticket < 0)
                    Print("Apertura Sell Order errore: ", GetLastError());
            }
        }
    }
    

    Note Finali:

    • Sviluppo e Debugging: Assicurati di verificare la directory e la presenza dell'indicatore.
    • Controlli e Validazioni: Per vedere effettivamente i dati, assicurati di avere Print() per visualizzare i risultati del iCustom.

    Se il problema persiste, sperimenta vari scenari di simulazione che daranno più visibilità alla logica dell'EA — ad esempio controllando se il Strategy Tester indica carenze nel buffer. Inoltre, puoi provare a cambiare l'offset da 0 a un valore leggermente più distante per cogliere extremi recenti.