I need to add a function in a new Expert, just created, based on hilo

MQL5 Experts

Job finished

Execution time 3 hours
Feedback from employee
Amazing Customer, Very fast replying and testing! I'm looking forward to future work with him. Very easy to work with Rafael!
Feedback from customer
Perfect job! Better than expected, this guy even made the code better than it was before... I will definitely hire him again. Thanks bro!!

Specification

I would like to add a function to my simple GannHilo EA.

I would like for each new hilo signal to check how many signals there were in a range of X previous bars closed, and if the number of previous signals in this range is equal to Y, then it enables trading as a filter, with the type filter bool. This filter, once activated, must be deactivated when a trade reaches the take profit line, then returning to check the number of signals again for a new entry.

The function must only consider bars, regardless of time. Thanks!

//+------------------------------------------------------------------+
//|                                                     Canais01.mq5 |
//|                                  Copyright 2023, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
CTrade trade;
CSymbolInfo simbolo; 



input int      Periodo   = 20;       // Período Média
//input int      PeriodoCurto   = 20;       // Período Média Curta
input double   SL             = 0.0;      // Stop Loss
input double   TP             = 0.0;      // Take Profit
input double   lotes  = 1;        // Volume Inicial
input string   inicio         = "09:00";  // Horário de Início (entradas)
input string   termino        = "17:00";  // Horário de Término (entradas)
input string   fechamento     = "17:30";  // Horário de Fechamento (posições)
input int      periodo_verificacao = 10; // verifica
input int      alternanciaMinima = 1;

bool HabilitarVenda = true;
bool HabilitarCompra = true;
int count_above_ma = 0;

int handleHilo; // Manipuladores dos dois indicadores de média móvel
      double hilo[];

// Estruturas de tempo para manipulação de horários
MqlDateTime horario_inicio, horario_termino, horario_fechamento, horario_atual;
MqlRates rates[];


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---

   if(!simbolo.Name(_Symbol))
   {
      printf("Ativo Inválido!");
      return INIT_FAILED;
   }

      // Criação dos manipuladores com Períodos curto e longo
      


   
      // Criação das structs de tempo
   TimeToStruct(StringToTime(inicio), horario_inicio);
   TimeToStruct(StringToTime(termino), horario_termino);
   TimeToStruct(StringToTime(fechamento), horario_fechamento);
   
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
      handleHilo = iCustom(Symbol(), Period(), "GannHilo", Periodo);
           // Cópia dos buffers dos indicadores de média móvel com períodos curto e longo

      ArraySetAsSeries(hilo, true);
      ArraySetAsSeries(rates, true);

       
    CopyBuffer(handleHilo, 0, 0, 3, hilo);
    CopyRates(Symbol(), Period(), 0, 3, rates);
  
//---
      if(HorarioEntrada())
   {
      // Compra em caso de cruzamento da média curta para cima da média longa
   if(rates[1].close > hilo[1] && rates[2].close < hilo[2] && HabilitarCompra == true){
      
               //double ma_value = hilo[0];

               

               
                  // Verificar quantas vezes os últimos 10 candles fecharam acima da média móvel
                  //count_above_ma = 0;
                  

        
                  CloseAllSellPositions();
                  Compra();
                  HabilitarCompra = false;
                  HabilitarVenda = true;
                  
            }
   
   // Venda em caso de cruzamento da média curta para baixo da média longa
   else if(rates[1].close < hilo[1] && rates[2].close > hilo[2] && HabilitarVenda == true){
         CloseAllBuyPositions();
         Venda();
         HabilitarVenda = false;
         HabilitarCompra = true;
         }


      // EA está posicionado
/*      if(!SemPosicao())
      {
         BreakEven();
      }*/
   //}
   
      // EA em horário de fechamento de posições abertas
   if(HorarioFechamento())
   {
      // EA está posicionado, fechar posição
      if(!SemPosicao()/* || !SemOrdem()*/)
         Fechar();
   }
   }
  } //fecha ontick

//+------------------------------------------------------------------+
//| Checar se horário atual está dentro do horário de entradas       |
//+------------------------------------------------------------------+
bool HorarioEntrada()
{
   TimeToStruct(TimeCurrent(), horario_atual); // Obtenção do horário atual
   
   // Hora dentro do horário de entradas
   if(horario_atual.hour >= horario_inicio.hour && horario_atual.hour <= horario_termino.hour)
   {
      // Hora atual igual a de início
      if(horario_atual.hour == horario_inicio.hour)
         // Se minuto atual maior ou igual ao de início => está no horário de entradas
         if(horario_atual.min >= horario_inicio.min)
            return true;
         // Do contrário não está no horário de entradas
         else
            return false;
      
      // Hora atual igual a de término
      if(horario_atual.hour == horario_termino.hour)
         // Se minuto atual menor ou igual ao de término => está no horário de entradas
         if(horario_atual.min <= horario_termino.min)
            return true;
         // Do contrário não está no horário de entradas
         else
            return false;
      
      // Hora atual maior que a de início e menor que a de término
      return true;
   }
   
   // Hora fora do horário de entradas
   return false;
}
//+------------------------------------------------------------------+
//| Checar se horário atual está dentro do horário de fechamento     |
//+------------------------------------------------------------------+
bool HorarioFechamento()
{
   TimeToStruct(TimeCurrent(), horario_atual); // Obtenção do horário atual
   
   // Hora dentro do horário de fechamento
   if(horario_atual.hour >= horario_fechamento.hour)
   {
      // Hora atual igual a de fechamento
      if(horario_atual.hour == horario_fechamento.hour)
         // Se minuto atual maior ou igual ao de fechamento => está no horário de fechamento
         if(horario_atual.min >= horario_fechamento.min)
            return true;
         // Do contrário não está no horário de fechamento
         else
            return false;
      
      // Hora atual maior que a de fechamento
      return true;
   }
   
   // Hora fora do horário de fechamento
   return false;
}

void Compra()
{           
      if(trade.Buy(lotes, NULL, 0, 0, 0, "Compra CruzamentoMediaEA")) // Envio da ordem de compra pela classe responsável
            {
                AddTakeStop(SL, TP);
            }
}

void Venda()
{     
      if(trade.Sell(lotes, NULL, 0, 0, 0, "venda CruzamentoMediaEA")) // Envio da ordem de compra pela classe responsável
                     {
                AddTakeStop(SL, TP);
            }
}

void AddTakeStop(double p_sl, double p_tp)
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        string symbol = PositionGetSymbol(i);

        if (symbol == Symbol())
        {
            ulong ticket = PositionGetInteger(POSITION_TICKET);
            double precoEntrada = PositionGetDouble(POSITION_PRICE_OPEN);

            double novoSL;
            double novoTP;

            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
            {
                novoSL = NormalizeDouble(precoEntrada - (p_sl * _Point), _Digits);
                novoTP = NormalizeDouble(precoEntrada + (p_tp * _Point), _Digits);

                trade.PositionModify(ticket, novoSL, novoTP);
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
            {
                novoSL = NormalizeDouble(precoEntrada + (p_sl * _Point), _Digits);
                novoTP = NormalizeDouble(precoEntrada - (p_tp * _Point), _Digits);

                trade.PositionModify(ticket, novoSL, novoTP);
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Fechar posição aberta                                            |
//+------------------------------------------------------------------+
void Fechar()
{  
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
        {
            ulong ticket = PositionGetTicket(i);
            trade.PositionClose(ticket);
        }
    }
    

    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
        {
            ulong ticket = PositionGetTicket(i);
            trade.PositionClose(ticket);
        }
    }

}

void CloseAllBuyPositions()
{  
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
        {
            ulong ticket = PositionGetTicket(i);
            trade.PositionClose(ticket);
        }
    }
 }
    
void CloseAllSellPositions()
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionGetSymbol(i) == _Symbol && PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
        {
            ulong ticket = PositionGetTicket(i);
            trade.PositionClose(ticket);
        }
    }

}

//+------------------------------------------------------------------+
//| Verificar se há posição aberta                                   |
//+------------------------------------------------------------------+
bool SemPosicao()
{  
   return !PositionSelect(_Symbol);
   //return resultado;
}

//+------------------------------------------------------------------+
//| Estratégia de cruzamento de médias                               |
//+------------------------------------------------------------------+
/*int Cruzamento()
{
   // Cópia dos buffers dos indicadores de média móvel com períodos curto e longo
   double MediaCurta[], MediaLonga[];
   ArraySetAsSeries(MediaCurta, true);
   ArraySetAsSeries(MediaLonga, true);
   CopyBuffer(handlemediacurta, 0, 0, 2, MediaCurta);
   CopyBuffer(handlemedialonga, 0, 0, 2, MediaLonga);
   
   // Compra em caso de cruzamento da média curta para cima da média longa
   if(MediaCurta[1] <= MediaLonga[1] && MediaCurta[0] > MediaLonga[0]){
      CloseAllBuyPositions();
      return 1;
      tradar = 1;
            }
   
   // Venda em caso de cruzamento da média curta para baixo da média longa
   if(MediaCurta[1] >= MediaLonga[1] && MediaCurta[0] < MediaLonga[0]){

      return -1;
         CloseAllSellPositions();}
      
   return 0;
}*/

//+------------------------------------------------------------------+


Files:

MQ5
GannHilo.mq5
4.6 Kb

Responded

1
Developer 1
Rating
(287)
Projects
359
29%
Arbitration
37
27% / 65%
Overdue
10
3%
Working
2
Developer 2
Rating
(16)
Projects
35
23%
Arbitration
4
0% / 50%
Overdue
2
6%
Working
3
Developer 3
Rating
(453)
Projects
566
26%
Arbitration
24
42% / 38%
Overdue
85
15%
Free
Published: 6 codes
4
Developer 4
Rating
Projects
0
0%
Arbitration
2
0% / 100%
Overdue
0
Free
5
Developer 5
Rating
Projects
1
0%
Arbitration
0
Overdue
0
Free
6
Developer 6
Rating
(5)
Projects
7
43%
Arbitration
8
13% / 88%
Overdue
0
Free
7
Developer 7
Rating
(298)
Projects
478
40%
Arbitration
105
40% / 24%
Overdue
82
17%
Loaded
Published: 2 codes
8
Developer 8
Rating
(50)
Projects
51
8%
Arbitration
0
Overdue
0
Free
9
Developer 9
Rating
(3)
Projects
4
0%
Arbitration
2
0% / 100%
Overdue
1
25%
Free
Similar orders
A robot 30+ USD
Je souhaite trouver un développeur pour réaliser ce travail et effectuer les paiements via cette application. Je m'engage à ne communiquer avec les candidats que par cette application, y compris par messageries tierces, correspondance personnelle ou courriel. Je comprends que toute personne ne respectant pas ces conditions sera interdite de publier des commandes sur la plateforme Freelance
I am looking for an experienced MQL5/MT5 developer to develop a custom Expert Advisor based on a complete technical architecture already prepared by the client. This is not a request to design a trading strategy from scratch . The strategy architecture, entry/exit concepts, filters, risk-management requirements and testing requirements are already documented. The main responsibility will be MQL5 development
EAs 100+ USD
To apply, you must already have your EA running on an active MT5 trading account connected to the market. The account must have genuine trading history that can be independently reviewed and verified. EA Requirements 1. Prop-Firm Compatible Risk Management - The EA must include daily and overall drawdown protection. - Required inputs: "MaxDailyLoss = 5%" "MaxTotalDrawdown = 10%" - Once either limit is
Strategy 40 - 60 USD
yo i have a strategy i would really like to turn into a signal bot basically please this is very technical and serious to me the strategy needs more time 1 time frame and the bot most be 100% accurate
Ready to use bot 100+ USD
seller must provide the following to be considered... i will answer to all who fit this description, and can purchase more than 1 EA... - brief strategy description - overall EA expectancy - 1 week limited trial version, with whatever settings you consider best (can be blocked on demo, i don't really care) - investor password from a reputable broker (if history is available... live / demo, same thing, doesn't really
I want you to develop a professional HFT trading robot for MT5/MQL5 , initially focused on XAUUSD . The robot should be designed for high-speed tick-level trading , analyzing real-time bid/ask movement, spread, tick velocity, momentum, volatility, price acceleration and short-term market microstructure to identify very short-term opportunities. The core strategy should be capable of opening 5–10+ positions in a
can you help me use a Tickblaze Algo NRBO on the NT platform? I have it somewhat set up, but I have other questions about running it & knowing how to operate it in NT. Thank you if anyone have experience in this kindly bib and let do it asap
I need a fully automated custom Expert Advisor for MetaTrader 5 (MQL5). The EA is intended for use on a The5ers $100,000 2-Step prop-firm account. IMPORTANT DELIVERY REQUIREMENT: I must receive the complete editable .mq5 source code as well as the compiled .ex5 file. Compiled-only delivery is NOT acceptable. The EA must be coded specifically for this project and must not copy trades, use external trading signals or
I've got a Pine Script from Trading View. I need help from a programmer who can help with optimising the strategy by 1) Adding a couple of further rules 2) Redesign the trading alert arrows & colours I need, please, a programmer who is 1) Good at Pine language 2) Has excellent after-job support (not for free though) 3) Possess the ability to work with others. 4) Able to deliver the job at the shortest possible time
I need an experienced TradingView Pine Script developer to build and test a custom intraday strategy for NQ/MNQ . I am not looking for a conversion . I need the strategy researched, developed, tested, and optimized based on my requirements. Requirements: NQ/MNQ intraday trading 5–15 minute charts New York session only Flat before market close Base logic using Zero Lag Signals , with additional filters if justified

Project information

Budget
30+ USD
Deadline
from 1 to 2 day(s)