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

Candle Pattern Stats

candlepatternstats.mq5
Поделиться этим товаромОтправьте ссылку на карточку
VK Telegram MAX WhatsApp
Вы автор или правообладатель?

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

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

О программе

Candle Pattern Stats — пользовательский индикатор для MetaTrader 5, который отмечает на графике закрытые свечные паттерны: бычий и медвежий engulfing, бычий и медвежий pin bar, а также inside bar. Отметка производится только на закрытых свечах, что исключает перерисовку.

Для каждого обнаруженного паттерна индикатор ведёт скользящую статистику — долю последних N разрешённых случаев, когда цена двигалась на X*ATR в пользу сделки, прежде чем развернулась на Y*ATR против. Статистика носит исключительно исторический характер и не является прогнозом.

Индикатор имеет настраиваемые параметры определений паттернов, опциональный фильтр тренда по EMA, информационную панель с результатами и систему уведомлений (всплывающие окна, push-уведомления, звук). Индикатор не выполняет торговых операций и предназначен только для анализа.

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

НастройкаОписание
InpATRPeriod Период расчёта ATR (метод Уилдера)
InpMinRangeATR Минимальный диапазон свечи-сигнала, в единицах ATR
InpPinWickPct Pin bar: минимальная доля доминирующего фитиля от диапазона свечи (50–95)
InpPinBodyPct Pin bar: максимальная доля тела свечи от диапазона (1–50)
InpUseInside Включить распознавание inside bar
InpUseEngulfing Включить распознавание engulfing
InpUsePin Включить распознавание pin bar
InpTrendFilter Фильтр тренда по EMA (длинные позиции только выше EMA, короткие — только ниже)
InpEMAPeriod Период EMA для фильтра тренда
InpTargetATR X: благоприятное движение в единицах ATR от свечи-сигнала
InpStopATR Y: неблагоприятное движение в единицах ATR от свечи-сигнала
InpSampleN N: размер скользящей выборки (последних N разрешённых случаев на паттерн)
InpMaxBars Количество баров ожидания X или Y до отбрасывания случая
InpShowPanel Отображать панель статистики
InpPanelBottom Панель в нижнем левом углу (по умолчанию верхний левый)
InpOffsetX Смещение панели по X (в пикселях)
InpOffsetY Смещение панели по Y (в пикселях)
InpPanelBg Фон панели
InpPanelText Цвет текста панели
InpArrowOffsetATR Расстояние стрелки от свечи, в единицах ATR
InpAlertPopup Уведомление: всплывающее окно
InpAlertPush Уведомление: push-уведомление
InpAlertSound Уведомление: звук
InpSoundFile Файл звука для уведомления

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

#property version   "1.00"
#property description "Marks engulfing, pin bar and inside bar patterns on closed bars (no repainting) with configurable definitions and an optional EMA trend filter."
#property description "For each pattern it shows, in a small panel, the rolling share of the last N cases where price moved X*ATR in favour before Y*ATR against. Historical statistics only - not a forecast."
#property description "20 buffers (signals, rolling hit rate, sample size) readable with iCustom(). Optional alerts on closed bars. Objects are removed when the indicator is removed."
#property indicator_chart_window
#property indicator_buffers 22
#property indicator_plots   20

#property indicator_label1  "Bullish engulfing"
#property indicator_label2  "Bearish engulfing"
#property indicator_label3  "Bullish pin bar"
#property indicator_label4  "Bearish pin bar"
#property indicator_label5  "Inside bar"
#property indicator_label6  "Signal bull engulfing"
#property indicator_label7  "Signal bear engulfing"
#property indicator_label8  "Signal bull pin bar"
#property indicator_label9  "Signal bear pin bar"
#property indicator_label10 "Signal inside bar"
#property indicator_label11 "Rate bull engulfing %"
#property indicator_label12 "Rate bear engulfing %"
#property indicator_label13 "Rate bull pin bar %"
#property indicator_label14 "Rate bear pin bar %"
#property indicator_label15 "Rate inside bar %"
#property indicator_label16 "N bull engulfing"
#property indicator_label17 "N bear engulfing"
#property indicator_label18 "N bull pin bar"
#property indicator_label19 "N bear pin bar"
#property indicator_label20 "N inside bar"
#property indicator_type1   DRAW_ARROW
#property indicator_type2   DRAW_ARROW
#property indicator_type3   DRAW_ARROW
#property indicator_type4   DRAW_ARROW
#property indicator_type5   DRAW_ARROW
#property indicator_type6   DRAW_NONE
#property indicator_type7   DRAW_NONE
#property indicator_type8   DRAW_NONE
#property indicator_type9   DRAW_NONE
#property indicator_type10  DRAW_NONE
#property indicator_type11  DRAW_NONE
#property indicator_type12  DRAW_NONE
#property indicator_type13  DRAW_NONE
#property indicator_type14  DRAW_NONE
#property indicator_type15  DRAW_NONE
#property indicator_type16  DRAW_NONE
#property indicator_type17  DRAW_NONE
#property indicator_type18  DRAW_NONE
#property indicator_type19  DRAW_NONE
#property indicator_type20  DRAW_NONE
#property indicator_color1  clrGreen
#property indicator_color2  clrRed
#property indicator_color3  clrDodgerBlue
#property indicator_color4  clrOrangeRed
#property indicator_color5  clrDimGray
#property indicator_width1  1
#property indicator_width2  1
#property indicator_width3  1
#property indicator_width4  1
#property indicator_width5  1

input int    InpATRPeriod      = 14;        // ATR period (Wilder)
input double InpMinRangeATR    = 0.5;       // Minimum bar range of the signal bar, in ATR
input int    InpPinWickPct     = 60;        // Pin bar: dominant wick, minimum % of the bar range (50-95)
input int    InpPinBodyPct     = 30;        // Pin bar: body, maximum % of the bar range (1-50)
input bool   InpUseInside      = true;      // Inside bar: enable
input bool   InpUseEngulfing   = true;      // Engulfing: enable
input bool   InpUsePin         = true;      // Pin bar: enable

input bool   InpTrendFilter    = false;     // EMA trend filter (long only above EMA, short only below)
input int    InpEMAPeriod      = 50;        // EMA period for the trend filter

input double InpTargetATR      = 1.0;       // X: favourable move, in ATR of the signal bar
input double InpStopATR        = 1.0;       // Y: adverse move, in ATR of the signal bar
input int    InpSampleN        = 50;        // N: rolling sample (last N resolved cases per pattern)
input int    InpMaxBars        = 48;        // Bars to wait for X or Y before a case is discarded

input bool   InpShowPanel      = true;      // Show the statistics panel
input bool   InpPanelBottom    = false;     // Panel at the bottom-left corner (default top-left)
input int    InpOffsetX        = 10;        // Panel X offset (pixels)
input int    InpOffsetY        = 20;        // Panel Y offset (pixels)
input color  InpPanelBg        = clrWhiteSmoke; // Panel background
input color  InpPanelText      = clrBlack;  // Panel text colour
input double InpArrowOffsetATR = 0.25;      // Arrow distance from the bar, in ATR

input bool   InpAlertPopup     = false;     // Alert: popup window
input bool   InpAlertPush      = false;     // Alert: push notification
input bool   InpAlertSound     = false;     // Alert: sound
input string InpSoundFile      = "alert.wav"; // Alert: sound file

#define NPAT 5
const string PFX = "CPS_";

double A0[], A1[], A2[], A3[], A4[];       // arrows
double S0[], S1[], S2[], S3[], S4[];       // signals
double R0[], R1[], R2[], R3[], R4[];       // rolling hit rate
double C0[], C1[], C2[], C3[], C4[];       // sample size
double ATRBuf[], EMABuf[];

const string PAT_NAME[NPAT] = {"Bullish engulfing", "Bearish engulfing", "Bullish pin bar", "Bearish pin bar", "Inside bar"};

struct CPSCase
  {
   int    bar;      // bar index of the signal bar
   int    pat;      // pattern 0..4
   int    dir;      // +1 long, -1 short
   double tp;       // favourable level
   double sl;       // adverse level
  };

CPSCase g_open[];
int     g_openN = 0;

int     g_ring[];          // NPAT * g_N entries, 1 = hit, 0 = miss
int     g_cnt[NPAT];
int     g_head[NPAT];
int     g_wins[NPAT];
int     g_expired[NPAT];

int      g_N = 50;
int      g_done = 0;        // bars [0, g_done) are fully processed (closed bars only)
datetime g_lastAlertBar = 0;
int      g_rows = 0;

int OnInit()
  {
      // код доступен только после оплаты
   }

void OnDeinit(const int reason)
  {
   ObjectsDeleteAll(0, PFX);
   ChartRedraw(0);
  }

void ResetState()
  {
   ArrayResize(g_ring, NPAT * g_N);
   ArrayInitialize(g_ring, 0);
   ArrayResize(g_open, 0);
   g_openN = 0;
   for(int p = 0; p < NPAT; p++)
     {
      g_cnt[p] = 0; g_head[p] = 0; g_wins[p] = 0; g_expired[p] = 0;
     }
   g_done = 0;
   g_lastAlertBar = 0;
  }

void SetSignal(const int p, const int i, const double v)
  {
   switch(p)
     {
      case 0: S0[i] = v; break;
      case 1: S1[i] = v; break;
      case 2: S2[i] = v; break;
      case 3: S3[i] = v; break;
      default: S4[i] = v; break;
     }
  }

double GetSignal(const int p, const int i)
  {
   switch(p)
     {
      case 0: return(S0[i]);
      case 1: return(S1[i]);
      case 2: return(S2[i]);
      case 3: return(S3[i]);
     }
   return(S4[i]);
  }

void SetArrow(const int p, const int i, const double v)
  {
   switch(p)
     {
      case 0: A0[i] = v; break;
      case 1: A1[i] = v; break;
      case 2: A2[i] = v; break;
      case 3: A3[i] = v; break;
      default: A4[i] = v; break;
     }
  }

void SetStats(const int p, const int i)
  {
   const double rate = (g_cnt[p] > 0) ? 100.0 * g_wins[p] / g_cnt[p] : EMPTY_VALUE;
   const double n = g_cnt[p];
   switch(p)
     {
      case 0: R0[i] = rate; C0[i] = n; break;
      case 1: R1[i] = rate; C1[i] = n; break;
      case 2: R2[i] = rate; C2[i] = n; break;
      case 3: R3[i] = rate; C3[i] = n; break;
      default: R4[i] = rate; C4[i] = n; break;
     }
  }

void PushOutcome(const int p, const int hit)
  {
   const int idx = p * g_N + g_head[p];
   if(g_cnt[p] == g_N)
      g_wins[p] -= g_ring[idx];
   else
      g_cnt[p]++;
   g_ring[idx] = hit;
   g_wins[p] += hit;
   g_head[p] = (g_head[p] + 1) % g_N;
  }

void ResolveOpen(const int i, const double hi, const double lo)
  {
   int w = 0;                                  // stable compaction: cases resolve in signal order
   for(int k = 0; k < g_openN; k++)
     {
      const CPSCase c = g_open[k];
      bool hitTP, hitSL;

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

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

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

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

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

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

Стоимость полного кода
1 433₽ ≈ $18