← К каталогу
Исходный код · ID 4103

GoldTrap Trend Supervisor

goldtrap_trend_supervisor_v2_1.mq5
Вы автор или правообладатель?

Сообщите нам, если считаете, что материал размещён без разрешения.

Краткий обзор

О программе

GoldTrap Trend Supervisor v2.1 — торговый советник для MetaTrader 5, предназначенный для контроля работы советника GoldTrap. Он не воспроизводит и не изменяет внутреннюю стратегию GoldTrap, а анализирует рыночные условия и управляет запуском и остановкой GoldTrap на основе оценки тренда.

Советник рассчитывает трендовый балл по семи условиям, используя индикаторы ADX, EMA и ATR на таймфреймах M15 и H1, а также анализ недавнего движения на M5. При достижении баллом порога блокировки GoldTrap приостанавливается: удаляются отложенные ордера с магическими числами GoldTrap и закрывается график, на котором запущен GoldTrap, при условии отсутствия открытых позиций.

Если у GoldTrap уже есть открытая корзина позиций, советник не вмешивается. После того как рынок остаётся в нормальном состоянии заданное время, GoldTrap запускается повторно с применением указанного шаблона. Советник отображает панель статуса и может записывать события в журнал.

Настройки программы

НастройкаОписание
GoldTrap_Symbol Символ для мониторинга. Пустое значение означает символ графика советника
GoldTrap_Timeframe Таймфрейм, на котором запущен GoldTrap
GoldTrap_Expert_Name Точное имя EX5-советника GoldTrap без расширения файла
GoldTrap_Template Имя шаблона для запуска GoldTrap
GoldTrap_BUY_Magic Магическое число для BUY-позиций GoldTrap
GoldTrap_SELL_Magic Магическое число для SELL-позиций GoldTrap
M15_ADX_Period Период индикатора ADX на таймфрейме M15
Minimum_Trend_ADX Минимальное значение ADX для подтверждения сильного тренда
M15_Fast_EMA Период быстрой EMA на таймфрейме M15
M15_Slow_EMA Период медленной EMA на таймфрейме M15
M15_ATR_Period Период индикатора ATR на таймфрейме M15
M15_EMA_Separation_ATR Порог разделения EMA в единицах ATR на M15 для подтверждения тренда
M15_EMA_Slope_Bars Количество баров для расчёта наклона быстрой EMA на M15
M15_EMA_Slope_ATR Порог наклона EMA в единицах ATR на M15
M15_Price_Extension_ATR Порог удаления цены от EMA в единицах ATR на M15
H1_Fast_EMA Период быстрой EMA на таймфрейме H1
H1_Slow_EMA Период медленной EMA на таймфрейме H1
H1_ATR_Period Период индикатора ATR на таймфрейме H1
H1_EMA_Separation_ATR Порог разделения EMA в единицах ATR на H1 для подтверждения тренда
H1_EMA_Slope_Bars Количество баров для расчёта наклона быстрой EMA на H1
H1_EMA_Slope_ATR Порог наклона EMA в единицах ATR на H1
Recent_Move_Minutes Окно анализа недавнего движения в минутах на таймфрейме M5
Recent_Move_ATR_M15 Порог недавнего движения в единицах ATR M15 для подтверждения ускорения
Block_Trend_Score Балл тренда, при достижении которого GoldTrap блокируется (от 0 до 7)
Normal_Trend_Score Балл тренда, до которого должен упасть счёт для начала отсчёта нормализации
Normal_Minutes_To_Restart Время в минутах нормальных условий, необходимое для перезапуска GoldTrap
Check_Interval_Seconds Интервал проверки рыночных условий в секундах
Show_Status_Panel Отображение панели статуса на графике
Write_Events_To_Journal Запись событий советника в журнал
Получить полный код

Поиск по коду файла

#property strict
#property version   "2.10"
#property description "External strong-trend supervisor for GoldTrap v4.2.4 BETA fix"

#include <Trade/Trade.mqh>

CTrade trade;

input group "=== ORIGINAL GOLDTRAP ==="
input string GoldTrap_Symbol                 = "";                 // Empty = symbol of the supervisor chart
input ENUM_TIMEFRAMES GoldTrap_Timeframe      = PERIOD_M5;          // Timeframe where GoldTrap runs
input string GoldTrap_Expert_Name           = "GoldTrap_v4.2.4_BETA_fix"; // Exact EX5 name, without extension
input string GoldTrap_Template               = "GoldTrap_Default.tpl";
input ulong GoldTrap_BUY_Magic                = 837490;
input ulong GoldTrap_SELL_Magic               = 528101;

input group "=== M15 TREND FILTER ==="
input int M15_ADX_Period                     = 14;
input double Minimum_Trend_ADX             = 28.0;               // +1 point if ADX >= this value
input int M15_Fast_EMA                      = 50;
input int M15_Slow_EMA                       = 200;
input int M15_ATR_Period                     = 14;
input double M15_EMA_Separation_ATR          = 0.80;               // +1 if |EMA50-EMA200| >= X * ATR
input int M15_EMA_Slope_Bars            = 5;
input double M15_EMA_Slope_ATR            = 0.40;               // +1 if EMA50 slope >= X * ATR
input double M15_Price_Extension_ATR         = 1.00;               // +1 if price distance from EMA50 >= X * ATR

input group "=== H1 TREND CONFIRMATION ==="
input int H1_Fast_EMA                       = 50;
input int H1_Slow_EMA                        = 200;
input int H1_ATR_Period                      = 14;
input double H1_EMA_Separation_ATR           = 0.50;               // +1 if H1 trend is aligned and separated
input int H1_EMA_Slope_Bars             = 3;
input double H1_EMA_Slope_ATR             = 0.25;               // +1 if H1 slope is aligned

input group "=== RECENT ACCELERATION ==="
input int Recent_Move_Minutes         = 30;                 // M5 displacement lookback window
input double Recent_Move_ATR_M15      = 1.50;               // +1 if displacement >= X * M15 ATR

input group "=== DECISION AND RESTART ==="
input int Block_Trend_Score             = 5;                  // From 0 to 7
input int Normal_Trend_Score    = 2;                  // Score must fall to this level to begin cooldown
input int Normal_Minutes_To_Restart      = 30;                 // Continuous normal conditions required before restarting GoldTrap
input int Check_Interval_Seconds        = 2;

input group "=== DISPLAY / LOG ==="
input bool Show_Status_Panel            = true;
input bool Write_Events_To_Journal         = true;

int hADX_M15     = INVALID_HANDLE;
int hEMAFast_M15 = INVALID_HANDLE;
int hEMASlow_M15 = INVALID_HANDLE;
int hATR_M15     = INVALID_HANDLE;
int hEMAFast_H1  = INVALID_HANDLE;
int hEMASlow_H1  = INVALID_HANDLE;
int hATR_H1      = INVALID_HANDLE;

string g_symbol = "";
long   g_goldtrap_chart_id = 0;
bool   g_blocked_by_trend = false;
datetime g_normal_since = 0;
string g_last_action = "Initializing";
int g_last_score = -1;

string g_last_log = "";

struct TrendSnapshot
{
   bool valid;
   int score;
   int direction; // 1 bullish, -1 bearish, 0 undefined

   double adx;
   double atr_m15;
   double atr_h1;
   double ema_fast_m15;
   double ema_slow_m15;
   double ema_fast_h1;
   double ema_slow_h1;
   double ema_sep_atr_m15;
   double ema_slope_atr_m15;
   double price_extension_atr_m15;
   double ema_sep_atr_h1;
   double ema_slope_atr_h1;
   double recent_move_atr_m15;

   bool c_adx;
   bool c_sep_m15;
   bool c_slope_m15;
   bool c_extension_m15;
   bool c_sep_h1;
   bool c_slope_h1;
   bool c_recent_move;
};

void LogEvent(const string msg)
{
   if(!Write_Events_To_Journal)
      return;

   if(msg == g_last_log)
      return;

   Print("[GoldTrap Supervisor] ", msg);
   g_last_log = msg;
}

bool IsGoldTrapMagic(const long magic)
{
   return ((ulong)magic == GoldTrap_BUY_Magic || (ulong)magic == GoldTrap_SELL_Magic);
}

bool GetBufferValue(const int handle,const int buffer,const int shift,double &value)
{
   double data[1];
   ResetLastError();
   int copied = CopyBuffer(handle,buffer,shift,1,data);
   if(copied != 1)
      return false;

   value = data[0];
   if(value == EMPTY_VALUE)
      return false;

   return true;
}

int SignOf(const double value)
{
   if(value > 0.0) return 1;
   if(value < 0.0) return -1;
   return 0;
}

string TrendDirectionText(const int dir)
{
   if(dir > 0) return "BULLISH";
   if(dir < 0) return "BEARISH";
   return "UNDEFINED";
}

int CountGoldTrapPositions()
{
   int count = 0;

   for(int i=PositionsTotal()-1; i>=0; i--)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0)
         continue;

      if(!PositionSelectByTicket(ticket))
         continue;

      string position_symbol = "";
      long position_magic = 0;

      if(!PositionGetString(POSITION_SYMBOL, position_symbol))
         continue;

      if(!PositionGetInteger(POSITION_MAGIC, position_magic))
         continue;

      if(position_symbol != g_symbol)
         continue;

      if(IsGoldTrapMagic(position_magic))
         count++;
   }

   return count;
}

int CountGoldTrapPendingOrders()
{
   int count = 0;

   for(int i=OrdersTotal()-1; i>=0; i--)
   {
      ulong ticket = OrderGetTicket(i);
      if(ticket == 0)
         continue;

      if(OrderGetString(ORDER_SYMBOL) != g_symbol)
         continue;

      long magic = OrderGetInteger(ORDER_MAGIC);
      if(IsGoldTrapMagic(magic))
         count++;
   }

   return count;
}

bool DeleteGoldTrapPendingOrders()
{
   bool all_ok = true;

   for(int i=OrdersTotal()-1; i>=0; i--)
   {
      ulong ticket = OrderGetTicket(i);
      if(ticket == 0)
         continue;

      if(OrderGetString(ORDER_SYMBOL) != g_symbol)
         continue;

      long magic = OrderGetInteger(ORDER_MAGIC);
      if(!IsGoldTrapMagic(magic))
         continue;

      ResetLastError();
      if(!trade.OrderDelete(ticket))
      {
         all_ok = false;
         PrintFormat("[GoldTrap Supervisor] Could not delete pending order #%I64u. Retcode=%u (%s), Error=%d",
                     ticket,trade.ResultRetcode(),trade.ResultRetcodeDescription(),GetLastError());
      }
      else
      {
         PrintFormat("[GoldTrap Supervisor] GoldTrap pending order #%I64u deleted by trend filter.",ticket);
      }
   }

   return all_ok;
}

bool GoldTrapExpertNameMatches(const string expert_name)
{
   if(StringLen(expert_name) == 0)
      return false;

   if(expert_name == GoldTrap_Expert_Name)
      return true;

   if(expert_name == GoldTrap_Expert_Name + ".ex5")
      return true;

   return false;
}

bool IsExactGoldTrapChart(const long chart_id)
{
   if(chart_id <= 0 || chart_id == ChartID())
      return false;

   if(ChartSymbol(chart_id) != g_symbol)
      return false;

   if((ENUM_TIMEFRAMES)ChartPeriod(chart_id) != GoldTrap_Timeframe)
      return false;

   string expert_name = "";
   ResetLastError();
   if(!ChartGetString(chart_id,CHART_EXPERT_NAME,expert_name))
      return false;

   return GoldTrapExpertNameMatches(expert_name);
}

long FindGoldTrapChart(int &matches)
{
   matches = 0;
   long found = 0;

   long id = ChartFirst();
   while(id >= 0)
   {
      if(IsExactGoldTrapChart(id))
      {
         matches++;
         if(found == 0)
            found = id;
      }

      id = ChartNext(id);
   }

   return found;
}

bool GoldTrapChartExists()
{
   int matches = 0;
   long id = FindGoldTrapChart(matches);

   if(matches > 1)
      LogEvent("WARNING: multiple charts have the exact GoldTrap EA loaded. Keep only one controlled instance.");

   if(id != 0)
   {
      g_goldtrap_chart_id = id;
      return true;
   }

   g_goldtrap_chart_id = 0;
   return false;
}

bool StartGoldTrapChart()
{
   if(GoldTrapChartExists())
      return true;

   ResetLastError();
   long id = ChartOpen(g_symbol,GoldTrap_Timeframe);
   if(id == 0)
   {
      PrintFormat("[GoldTrap Supervisor] ERROR ChartOpen(%s,%s). Error=%d",
                  g_symbol,EnumToString(GoldTrap_Timeframe),GetLastError());
      return false;
   }

   g_goldtrap_chart_id = id;

   ResetLastError();
   if(!ChartApplyTemplate(id,GoldTrap_Template))
   {
      int err = GetLastError();
      PrintFormat("[GoldTrap Supervisor] ERROR applying template '%s'. Error=%d",GoldTrap_Template,err);
      ChartClose(id);
      g_goldtrap_chart_id = 0;
      return false;
   }

   LogEvent("GoldTrap STARTED: chart opened and template applied.");
   return true;
}

bool StopGoldTrapChart()
{

   DeleteGoldTrapPendingOrders();

   if(!GoldTrapChartExists())
   {
      g_goldtrap_chart_id = 0;
      return true;
   }

   ResetLastError();
   if(!ChartClose(g_goldtrap_chart_id))
   {
      PrintFormat("[GoldTrap Supervisor] ERROR closing GoldTrap chart ID=%I64d. Error=%d",
                  g_goldtrap_chart_id,GetLastError());
      return false;
   }

   LogEvent("GoldTrap STOPPED because of a strong trend (no open basket).");
   g_goldtrap_chart_id = 0;
   return true;
}

bool EvaluateTrend(TrendSnapshot &s)
{
   s.valid = false;
   s.score = 0;
   s.direction = 0;

   double adx=0.0;
   double emaFast15=0.0, emaSlow15=0.0, emaFast15Past=0.0;
   double atr15=0.0;
   double emaFastH1=0.0, emaSlowH1=0.0, emaFastH1Past=0.0;
   double atrH1=0.0;

   if(!GetBufferValue(hADX_M15,0,1,adx)) return false;
   if(!GetBufferValue(hEMAFast_M15,0,1,emaFast15)) return false;
   if(!GetBufferValue(hEMASlow_M15,0,1,emaSlow15)) return false;
   if(!GetBufferValue(hEMAFast_M15,0,1+M15_EMA_Slope_Bars,emaFast15Past)) return false;
   if(!GetBufferValue(hATR_M15,0,1,atr15)) return false;

   if(!GetBufferValue(hEMAFast_H1,0,1,emaFastH1)) return false;
   if(!GetBufferValue(hEMASlow_H1,0,1,emaSlowH1)) return false;
   if(!GetBufferValue(hEMAFast_H1,0,1+H1_EMA_Slope_Bars,emaFastH1Past)) return false;
   if(!GetBufferValue(hATR_H1,0,1,atrH1)) return false;

   if(atr15 <= 0.0 || atrH1 <= 0.0)
      return false;

   double closeM15 = iClose(g_symbol,PERIOD_M15,1);
   if(closeM15 <= 0.0)
      return false;

   int dir = SignOf(emaFast15 - emaSlow15);
   if(dir == 0)
      return false;

   double sep15 = MathAbs(emaFast15 - emaSlow15) / atr15;
   double slope15 = (emaFast15 - emaFast15Past) / atr15;
   double extension15 = (closeM15

Показано первые 50% кода (символов: 15638)

Открыть по тарифу

Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.

Разовая покупка файла

На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.

Чтобы оформить заказ, введите email и перейдите к оплате.

Стоимость полного кода
1 563,80₽ ≈ $19.12