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

MQL5 EA

작업 종료됨

실행 시간 3 시간
고객의 피드백
Perfect job! Better than expected, this guy even made the code better than it was before... I will definitely hire him again. Thanks bro!!
피고용인의 피드백
Amazing Customer, Very fast replying and testing! I'm looking forward to future work with him. Very easy to work with Rafael!

명시

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;
}*/

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


파일:

MQ5
GannHilo.mq5
4.6 Kb

응답함

1
개발자 1
등급
(295)
프로젝트
367
30%
중재
37
27% / 65%
기한 초과
10
3%
작업중
게재됨: 10 코드
2
개발자 2
등급
(16)
프로젝트
35
23%
중재
4
0% / 50%
기한 초과
2
6%
작업중
3
개발자 3
등급
(453)
프로젝트
566
26%
중재
24
42% / 38%
기한 초과
85
15%
무료
게재됨: 6 코드
4
개발자 4
등급
프로젝트
0
0%
중재
2
0% / 100%
기한 초과
0
무료
5
개발자 5
등급
프로젝트
1
0%
중재
0
기한 초과
0
무료
6
개발자 6
등급
(5)
프로젝트
7
43%
중재
8
13% / 88%
기한 초과
0
무료
7
개발자 7
등급
(298)
프로젝트
478
40%
중재
105
40% / 24%
기한 초과
82
17%
로드됨
게재됨: 2 코드
8
개발자 8
등급
(50)
프로젝트
51
8%
중재
0
기한 초과
0
무료
9
개발자 9
등급
(3)
프로젝트
4
0%
중재
2
0% / 100%
기한 초과
1
25%
무료
비슷한 주문
Experienced Trading Software Developer Needed – Multi-Platform Development Hello! I'm looking for an experienced developer to create a custom trading indicator and convert it into an automated trading bot for the following platforms: MT5 NinjaTrader 8 Quantower cTrader The plan is to develop the same indicator and trading bot for all four platforms, one after another. Project requirements: Custom trading indicator
un écosystème logiciel asynchrone multi-comptes dopé par un module de supervision par Intelligence Artificielle (Guardian AI). La solution assure le pilotage automatisé, le filtrage de marché en temps réel et le contrôle des risques pour 20+ comptes MetaTrader 4/5 (via MetaApi) et Deriv sur VPS Equinix NY4. vous aurez plus de detail dans les échanges
Order flow 30+ USD
Hi! I need an experience developer with order flow, volume delta, and futures scalping, and I wanted to ask you a few questions. Have you personally developed and tested fast-paced strategies for Gold Futures (GC), particularly those that enter during short-term price impulses and scale into positions as momentum builds? From your experience, what indicators or signals help you determine whether an impulse has enough
I am looking for an experienced MQL5 developer for the first milestone of a larger MetaTrader 5 project: a multi-symbol, multi-timeframe signal scanner with alerts. This milestone covers indicator integration only. There is no order placement or trade management at any stage. Scope of this milestone Read outputs from three custom indicators (provided as compiled files after selection and NDA) reliably via iCustom and
RA_BOT 2.0 36+ USD
//@version=4 study(title="UT Bot Alerts", overlay = true) // Inputs a = input(1, title = "Key Vaule. 'This changes the sensitivity'") c = input(10, title = "ATR Period") h = input(false, title = "Signals from Heikin Ashi Candles") xATR = atr(c) nLoss = a * xATR src = h ? security(heikinashi(syminfo.tickerid), timeframe.period, close, lookahead = false) : close xATRTrailingStop = 0.0 xATRTrailingStop := iff(src >
Andrew 50 - 200 USD
Hello, I am from Tanzania. I am looking for a professional MQL5 programmer from Tanzania who can help me develop and improve my automated MT5 trading robot. The project is called SMC XAVAGE AI, and it trades XAUUSD (Gold). I would like to discuss the project with you. Are you based in Tanzania? Would it be possible to arrange a meeting or a call? Thank you
Metafix 50 - 200 USD
Here is a professional specification you can send directly to your developer. # Project Requirements Specification: MetaTrader 5 Trading Robot Development ### 1. Project Overview I want to develop an automated Forex trading robot (Expert Advisor) for MetaTrader 5 (MT5). The robot should analyse the financial markets, identify trading opportunities, and execute trades automatically based on predefined strategies. ###
1. Platform: MT4 The EA required is not linked, neither depending on trading strategy nor trading signals nor indicators. 2. Initial order is a pending order (buy stop/ sell stop) and it is created manually. It is open for a specified symbol (pair) at a specified price with a specified S/L 3. Example: buy stop 0.1 lot GBPUSD @ 1.3085 WITH S/L @1.3075 Once target price is reached, pending order will
I am looking for an experienced trading software developer interested in building a long-term working relationship. Im a professional Trader, Coach and Mentor, I work with traders and Student who require customized trading solutions, including automated trading bots, Expert Advisors, custom indicators, trading strategies and other algorithmic trading tools. I am looking for a technically skilled developer who can
Salman serhal 30 - 100 USD
MT5 ICT XAUUSD Sell-Only Trading Robot with Fibonacci Confirmation I am looking for an experienced MQL5 developer to create a custom Expert Advisor (EA) for MetaTrader 5, specifically for trading Gold (XAUUSD). 1. Trading Strategy The robot must use the ICT trading methodology and focus on SELL trades only. The strategy should include: * Identify important resistance and premium zones. * Use Fibonacci retracement

프로젝트 정보

예산
30+ USD
기한
에서 1 로 2 일