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

sqdynamicbreakoutbox_v1 600+.mq4

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

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

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

О программе

Индикатор для MetaTrader 4, отображающий динамические боксы прорыва на основе зон консолидации цены. Бокс формируется, когда диапазон цены остаётся ниже заданного порога в течение минимального периода времени. После формирования бокс растягивается до момента прорыва цены за его границы.

Индикатор строит линии прорыва (жёлтую и пурпурную) с заданным отступом от краёв бокса, отображает уровни фиксации прибыли в виде уровней Фибоначчи и показывает стрелки сигналов на покупку и продажу при закрытии свечей за пределами бокса. Поддерживаются уведомления по электронной почте, звуковые оповещения и push-уведомления.

Также индикатор ведёт статистику по сессиям боксообразования: отслеживает максимальное потенциальное расстояние до цели для сделок покупки и продажи, отображает итоговые и средние значения в информационной панели. При включённой соответствующей настройке статистика сохраняется в CSV-файл.

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

НастройкаОписание
BoxLength Длина бокса — Минимальная продолжительность зоны консолидации в единицах BoxTimeFrame, при превышении которой строится бокс.
BoxTimeFrame Таймфрейм бокса — Таймфрейм, на котором измеряется длительность консолидации для определения бокса.
fixed box range, when AutoBoxRange is false (BoxRange) Фиксированный диапазон бокса — Размер бокса в пунктах, используется когда AutoBoxRange выключен.
when true, will use AutoBoxRangeDailyATRfactor*daily_ATR_value as the BoxRange value; (AutoBoxRange) Автоматический диапазон бокса — При включении размер бокса рассчитывается на основе дневного ATR с заданным периодом и множителем.
AutoBoxRangeDailyATRperiod Период дневного ATR — Период расчёта дневного ATR, используемого для автоматического определения размера бокса.
AutoBoxRangeDailyATRfactor Множитель дневного ATR — Множитель, умножаемый на значение дневного ATR для получения размера бокса.
add this amount to the Box Yellow and Magenta lines (BoxBufferPips) Буфер в пунктах — Отступ в пунктах от краёв бокса, на котором строятся линии прорыва.
calendar days back; 0=full history (DaysBack) Количество дней назад — Глубина анализа в календарных днях; 0 означает полную историю.
number of bars to close outside the BO levels to signal trades; 0 means "enter immediately on Breako (MinBarsClosedOutsi Минимум баров вне бокса для сигнала — Количество свечей, закрывшихся за пределами уровней прорыва, необходимое для формирования сигнала; 0 означает немедленный вход при прорыве.
false will hide the display panel (ShowDisplayPanel) Показать панель отображения — При false скрывает информационную панель со статистикой.
false will hide the TP levels (ShowTPLevels) Показать уровни TP — При false скрывает уровни фиксации прибыли на графике.
to limit the TP levels to the last Box only (ShowTPLevelsOnLastBoxOnly) Уровни TP только на последнем боксе — При включении уровни фиксации прибыли отображаются только для последнего сформированного бокса.
TP1 Уровень TP 1 — Значение первого уровня фиксации прибыли (фактор или фиксированные пункты).
TP2 Уровень TP 2 — Значение второго уровня фиксации прибыли (фактор или фиксированные пункты).
TP3 Уровень TP 3 — Значение третьего уровня фиксации прибыли (фактор или фиксированные пункты).
TP4 Уровень TP 4 — Значение четвёртого уровня фиксации прибыли (фактор или фиксированные пункты).
TP5 Уровень TP 5 — Значение пятого уровня фиксации прибыли (фактор или фиксированные пункты).
TP6 Уровень TP 6 — Значение шестого уровня фиксации прибыли (фактор или фиксированные пункты).
TP7 Уровень TP 7 — Значение седьмого уровня фиксации прибыли (фактор или фиксированные пункты).
TP8 Уровень TP 8 — Значение восьмого уровня фиксации прибыли (фактор или фиксированные пункты).
TP9 Уровень TP 9 — Значение девятого уровня фиксации прибыли (фактор или фиксированные пункты).
TPFiboColor Цвет линий TP Фибоначчи — Цвет отображения уровней Фибоначчи для TP.
TPLevelColor Цвет уровней TP — Цвет линий уровней фиксации прибыли.
TPFiboBars Баров для Фибо-уровней — Количество баров, на которое растягиваются уровни Фибоначчи.
any TP input above this value is considered as a FIXED PIP value, below is a FACTOR of the box size (TP_is_pips_above) Порог фиксированных пунктов TP — Значение, выше которого параметры TP считаются фиксированными пунктами, ниже — множителем размера бокса.
BuySignalArrowCode Код стрелки сигнала покупки — Код графического объекта-стрелки для сигнала на покупку.
BuySignalArrowColor Цвет стрелки сигнала покупки — Цвет стрелки, указывающей сигнал на покупку.
SellSignalArrowCode Код стрелки сигнала продажи — Код графического объекта-стрелки для сигнала на продажу.
SellSignalArrowColor Цвет стрелки сигнала продажи — Цвет стрелки, указывающей сигнал на продажу.
SignalMail Отправка email-уведомления — При включении отправляет уведомление на email при формировании сигнала.
SignalAlert Звуковое оповещение — При включении воспроизводит звуковой сигнал при формировании сигнала.
SignalNotification Push-уведомление — При включении отправляет push-уведомление на мобильное устройство при формировании сигнала.
CreateStatisticsFile Создавать файл статистики — При включении сохраняет статистические данные в CSV-файл в папке experts/files.
BreakoutBoxFontSize Размер шрифта бокса — Размер шрифта для подписей на боксах.
BreakoutBoxColor Цвет бокса прорыва — Цвет прямоугольника основного бокса прорыва.
BreakoutBoxContColor Цвет продолжения бокса — Цвет прямоугольника продолжения бокса, показывающего его границы в течение сессии.
true will draw a full rectangle rather than an "empty" rectangle (BreakoutBoxContFullColored) Полноцветное продолжение бокса — При true отрисовывает заполненный прямоугольник продолжения, при false — пустой контур.
BreakoutBoxContPriceColor Цвет ценовых меток продолжения — Цвет ценовых меток на прямоугольнике продолжения бокса.
BreakoutPriceColor Цвет ценовых меток прорыва — Цвет ценовых меток на уровнях высока и низа бокса.
BreakoutPriceWidth Ширина ценовых меток прорыва — Толщина линий ценовых меток уровней прорыва.
StatsColor Цвет статистики — Цвет текста в информационной панели статистики.
StatsBGColor Цвет фона статистики — Фоновый цвет области отображения статистики.
0=upper-left, 1=upper-right, 2=lower-left, 3=lower-right (StatsCorner) Угол отображения статистики — Угол экрана для размещения панели статистики: 0 — верхний левый, 1 — верхний правый, 2 — нижний левый, 3 — нижний правый.
false to remove vertival Box delimiter lines; (BoxVerticalLineDelimiter) Вертикальная разделительная линия бокса — При true отображает вертикальную линию, отмечающую начало формирования бокса.
BoxVerticalLineColor Цвет вертикальной разделительной линии — Цвет вертикальной линии, отмечающей начало формирования бокса.
SwingLabelsFontSize Размер шрифта меток свинга — Размер шрифта для подписей максимальных отклонений цены от уровней прорыва.
SwingLabelsColor Цвет меток свинга — Цвет подписей максимальных отклонений цены от уровней прорыва.
Fonts Шрифт — Имя шрифта, используемого для текстовых меток на графике.
debug Режим отладки — Уровень детализации отладочного вывода.
Получить полный код

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

#define VERSION "v1.12"
#define DATE    "2011.09.09"

/*+------------------------------------------------------------------+
 * sqDynamicBreakoutBox.mq4, by Squalou, 2011.07.05:
 * - draws Dynamic Breakout Boxes based on consolidation areas;
 * - consolidation areas are defined by a minimum period of time during which
 *   the Range of PA remained below a minimum Range value;
 * - Inputs:
 *   - BoxLength and BoxTimeFrame: define the minimum duration of the congestion areas
 *     Better than specifying a number of bars, because this will not independ
 *     on the chart's timeframe;
 *   - BoxRange: the Box Range in pips;
 *   - AutoBoxRange (true/false), AutoBoxRangeDailyATRperiod(=30) and AutoBoxRangeDailyATRfactor(=0.25):
 *     to automatically determine a the Box size based on Daily ATR, rather than a fixed size.
 *   - BoxBufferPips: draws the Yellow and Magenta "breakout" lines at this distance from the actual Box;
 *
 * This indicator was inspired by a thread opened by "forexhard" on ForexFactory.
 * 
 * Thank you forexhard for this!
 *
 * - History:
 *
 * - v1.12 (2011.09.09):
 *   Now that the CZ Box stretches until the breakout occurs, it will also stretch until it reaches its maximum allowed height;
 *   Therefore the box edges and TP levels will CHANGE in these conditions.
 *   Buy/sell signals could wrongly trigger when the previous 2 candles would close on OPPOSITE sides of the box (consecutive up and down long candles);
 *   Fixed possible zero devide error when BoxBufferPips=0;
 *   Cosmetic changes:
 *    the signal arrows are now placed at the left of the entry candle, and point to the exact entry price;
 *    BO and BOCont lines adjusted to where they should be starting/ending;
 * 
 * - v1.11 (2011.09.08): 
 *   CZ boxes now stretch until PA breaks out of the BO; the Box size label now also shows the length of the Box (e.g "36p x 26" for 26 bars);
 *   Buy/Sell signal arrows are printed when MinBarsClosedOutsideBO bars have closed outside the BO levels;
 *   added "ShowTPLevelsOnLastBoxOnly" input;
 *   last Fibs now extend beyond the current last candle
 *   price labels on last box made bigger; controled by "BreakoutPriceWidth" input;
 *   added "ShowDisplayPanel" input;
 *   fixed DaysBack=0 case (was limiting to about 578 days max)
 *   changed default colors to a "blueish" palette;
 *
 * - v1.10 (2011.08.25): 
 *   added "MinBarsClosedOutsideBO" input: number of bars to close outside the BO levels to signal trades; 0 means "enter immediately on Breakout"
 *   added email and alarm options: "SignalMail" and "SignalAlert";
 *   added cosmetic inputs: "TP_is_pips_above", "BreakoutBoxFontSize", "SwingLabelsFontSize", "BreakoutPriceColor", "BreakoutBoxContPriceColor";
 *   change: TP levels should be calculated based on the Box itself, NOT counting the bufferpips;
 *   CAUTION: FIXED TP pips are counted based on the BUY/SELL ENTRY LEVELS,
 *            whereas TPs based on FACTORS are calculated from the BOX EDGE LEVELS independently from the BoxBufferPips input;
 *            Therefore, changing BoxBufferPips will only affect FIXED PIPS TP levels.
 *   fix: TP9 was not showing;
 *
 * - v1.9 (2011.08.22): 
 *   added "ShowTPLevels" input to allow hiding them;
 *   changed the display panel a bit;
 *   changed default settings:
 *      DaysBack is set to 100(days) to limit the cpu load;
 *      all TP levels are now set to the last fib factors proposed by Mer;
 *      the minimum value for a TP level to be taken as a pip number is 20 (was 10);
 *   optimized cpu load;
 *
 * - v1.8 (2011.07.25): 
 *   added drawing of "Fib levels" for up to 9 TP targets on each side of the CZ Breakout areas;
 *   new inputs: TP1..TP9 values: when <10, they are taken as a factor of the "Breakout Extent" (=Box extent + BufferPips), else they are in pips;
 *
 * - v1.7c (2011.07.22): more cosmetics... new inputs: "SwingLabelsColor","Fonts";
 * - v1.7b (2011.07.21):
 *   more cosmetics... added a "box continuation rectangle" on each Box (selectable color with BreakoutBoxContColor),
 *   and price labels at the right of the last box continuation rectangle;
 *
 * - v1.7a (2011.07.20):
 *   - added various cosmetic inputs (StatsColor,StatsBGColor,StatsCorner,BoxVerticalLineDelimiter,BoxVerticalLineColor);
 *     added a "background" to the Stats area;
 *
 * - v1.6 (2011.07.20):
 *   - Display each Box size in pips;
 *
 * - v1.5 (2011.07.12):
 *   - added "AutoBoxRange" (true/false), "AutoBoxRangeDailyATRperiod"(=30) and "AutoBoxRangeDailyATRfactor"(=0.25) inputs:
 *     when true, will use AutoBoxRangeDailyATRfactor*daily_ATR_value as the BoxRange value;
 *
 * - v1.4 (2011.07.11):
 *   - added saving of statistical data into a CSV file saved in (mt4)/experts/files folder;
 *     the CSV file name is on the typical model "EURUSD-sqDynamicBreakoutBox(4x60min,30p).csv"
 *     Controlled by "CreateStatisticsFile"(true/false) input;
 *
 * - v1.3 (2011.07.08):
 *   - added statistical data on maximum Buy/Sell expenctancy for each "Session";
 *     max Buys and Sells for each Session are indicated on the chart itself,
 *     the total and average maximum pips are displayed in the upper right corner;
 *
 * - v1.2 (2011.07.07):
 *   - added drawing of vertical lines marking the bar on which the Box initially formed;
 *     This helps locate the Boxes compared on other indicator windows.
 *
 * - v1.1 (2011.07.06):
 *   - added "BoxBufferPips" input, draws the Yellow and Magenta lines at this buffer away from the formed Box;
 *     These are your real breakout lines;
 *
 * - v1.0 (2011.07.05): initial version;
 *

*/

#property indicator_chart_window

#property indicator_buffers 6

#property indicator_color1 C'0,200,200' // Breakout Box High Line
#property indicator_width1 2
#property indicator_color2 C'0,200,200' // Breakout Box Low Line
#property indicator_width2 2

#property indicator_color3 C'0,200,200' // Breakout Box High Line Continuation
#property indicator_color4 C'0,200,200' // Breakout Box Low Line Continuation

#property indicator_color5 clrLime      // BUY Arrow
#property indicator_color6 clrOrangeRed // SELL Arrow
#property indicator_width5 2
#property indicator_width6 2

extern int    BoxLength                   = 22;
extern int    BoxTimeFrame                = 15;
extern int    BoxRange                    = 30; // fixed box range, when AutoBoxRange is false
extern bool   AutoBoxRange                = true;// when true, will use AutoBoxRangeDailyATRfactor*daily_ATR_value as the BoxRange value;
extern int    AutoBoxRangeDailyATRperiod  = 30;
extern double AutoBoxRangeDailyATRfactor  = 0.20;
extern int    BoxBufferPips               = 5; // add this amount to the Box Yellow and Magenta lines
extern int    DaysBack                    = 100; // calendar days back; 0=full history

extern int    MinBarsClosedOutsideBO      = 2; // number of bars to close outside the BO levels to signal trades; 0 means "enter immediately on Breakout"

extern bool   ShowDisplayPanel            = true; // false will hide the display panel

extern bool   ShowTPLevels                = true; // false will hide the TP levels
extern bool   ShowTPLevelsOnLastBoxOnly   = true; // to limit the TP levels to the last Box only

extern double TP1                         = 0.618;
extern double TP2                         = 1.382;
extern double TP3                         = 2.618;
extern double TP4                         = 4.236;
extern double TP5                         = 5.854;
extern double TP6                         = 7.472;
extern double TP7                         = 9.090;
extern double TP8                         = 11.708;
extern double TP9                         = 14.326;
extern color  TPFiboColor                 = clrNONE;
extern color  TPLevelColor                = clrGray;
extern int    TPFiboBars                  = 5;      
extern double TP_is_pips_above            = 20; // any TP input above this value is considered as a FIXED PIP value, below is a FACTOR of the box size (including bufferpips);

extern int    BuySignalArrowCode          = 2;
extern color  BuySignalArrowColor         = clrYellow;
extern int    SellSignalArrowCode         = 2;
extern color  SellSignalArrowColor        = clrRed;

extern bool   SignalMail                  = false;
extern bool   SignalAlert                 = false;
extern bool   SignalNotification          = false;

extern bool   CreateStatisticsFile        = false;
extern int    BreakoutBoxFontSize         = 12;
extern color  BreakoutBoxColor            = C'0,170,170';
extern color  BreakoutBoxContColor        = clrDarkSlateGray;
extern bool   BreakoutBoxContFullColored  = true; // true will draw a full rectangle rather than an "empty" rectangle
extern color  BreakoutBoxContPriceColor   = clrDarkSlateGray;
extern color  BreakoutPriceColor          = C'0,170,170';
extern int    BreakoutPriceWidth          = 2;
extern color  StatsColor                  = C'0,220,220';
extern color  StatsBGColor                = clrTeal;
extern int    StatsCorner                 = 1; // 0=upper-left, 1=upper-right, 2=lower-left, 3=lower-right
extern bool   BoxVerticalLineDelimiter    = false; // false to remove vertival Box delimiter lines;
extern color  BoxVerticalLineColor        = clrDarkSlateGray;
extern int    SwingLabelsFontSize         = 12;
extern color  SwingLabelsColor            = clrDarkOrange;
extern string Fonts                       = "Arial";

extern int    debug                       = 0;

double highBO[],lowBO[];
double highBOcont[],lowBOcont[];
double periodForMinRange[];
double BuySignal[],SellSignal[];

int _period,_minP,_maxP,_prevP;
double _Range;

datetime current_box_forming_time,current_box_1st_bar_time;

string prefix;
string strBoxRange;

int BarsBack,lasttime;
bool force_full_redraw;

double pip;
int pipMult,pipMultTab[]={1,10,1,10,1,10,100}; // multiplier to convert pips to Points;

double TP[10],TPInput[10],TP_pips[10],BuyTP[10],SellTP[10];
double BoxHighValue,BoxLowValue,BoxExtent,highBOvalue,lowBOvalue,BOExtent;
double SL,SLInput;

int init()

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

int deinit()

{
  RemoveObjects(prefix);
  force_full_redraw=true;
  return(0);
}

int start()

{
      // код доступен только после оплаты
   }
  double upper,lower,best_buy,best_sell;
  int jj;
  int i, limit, counted_bars=IndicatorCounted();

  if (force_full_redraw) {
    force_full_redraw=false;
    lasttime=0;
    counted_bars=0;
    ArrayInitialize(highBO,EMPTY_VALUE);
    ArrayInitialize(lowBO,EMPTY_VALUE);
    ArrayInitialize(highBOcont,EMPTY_VALUE);
    ArrayInitialize(lowBOcont,EMPTY_VALUE);
    ArrayInitialize(BuySignal,EMPTY_VALUE);
    ArrayInitialize(SellSignal,EMPTY_VALUE);
  }

  if (lasttime==Time[0]) return(0); //once per Bar
  lasttime=Time[0];

  limit = MathMax(MathMin(BarsBack,Bars-counted_bars-1),1);

  for (i=limit; i>0; i--)
  {
    if (AutoBoxRange == true) {// determine the BoxRange dynamically using the Daily ATR;
      _Range = AutoBoxRangeDailyATRfactor  * iATR(NULL,PERIOD_D1,AutoBoxRangeDailyATRperiod,iBarShift(NULL,PERIOD_D1,iTime(NULL,0,i),true)+1);
    }

    _period = GetPeriodForMinRange(i, _minP, 999, _Range, periodForMinRange[i+1]);
    periodForMinRange[i] = _period;
    upper = High[iHighest(NULL, 0, MODE_HIGH, _period, i)];
    lower = Low [iLowest (NULL, 0, MODE_LOW,  _period, i)];

    highBOcont[i] = highBOcont[i+1];
    lowBOcont[i]  = lowBOcont[i+1];

    if (_period > _minP) { // Price range remained below BoxRange longer than BoxLength:

      if (highBO[i+1]==EMPTY_VALUE && lowBO[i+1]==EMPTY_VALUE) { // no Box was forming:

        if (highBO[i+_minP]==EMPTY_VALUE && lowBO[i+_minP]==EMPTY_VALUE) {

          get_session_swing_hi_and_lo(Time[i+1], current_box_forming_time, highBOvalue, lowBOvalue, best_buy, best_sell);

          if (CreateStatisticsFile) save_stats_in_CSV(Time[i+1], current_box_forming_time, best_buy, best_sell, (highBOvalue-lowBOvalue)/pip);

          if (High[i+_period-1]==upper) upper = lower+_Range;
          if (Low[i+_period-1]==lower)  lower = upper-_Range;

          for (jj = i+_minP-1; jj>=i; jj--) {
            highBO[jj] = upper + BoxBufferPips * pip;
            lowBO[jj]  = lower - BoxBufferPips * pip;
          }

          highBOcont[i+1] = EMPTY_VALUE;
          lowBOcont[i+1]  = EMPTY_VALUE;
          highBOcont[i] = upper + BoxBufferPips * pip;
          lowBOcont[i]  = lower - BoxBufferPips * pip;
          current_box_forming_time = Time[i]; // remember Box starting candle;
          current_box_1st_bar_time = Time[i+_minP-1]; // remember time of Box 1st bar;

          drawBox(prefix+"trueBox"+TimeToStr(current_box_1st_bar_time), current_box_1st_bar_time, upper, current_box_forming_time, lower, BreakoutBoxColor, 0, STYLE_SOLID, true, "");
          drawLbl(prefix+"infoBox"+TimeToStr(current_box_1st_bar_time), DoubleToStr((upper-lower)/pip,0)+"p x "+DoubleToStr(iBarShift(NULL,0,current_box_1st_bar_time)-iBarShift(NULL,0,current_box_forming_time)+1,0), current_box_1st_bar_time+(current_box_forming_time-current_box_1st_bar_time)/2, lower - BoxBufferPips * pip, BreakoutBoxFontSize, Fonts, BreakoutBoxColor, 3);
          if (BoxVerticalLineDelimiter) drawVLine(prefix+"V"+TimeToStr(current_box_1st_bar_time), current_box_forming_time, BoxVerticalLineColor);
        }
      } else { // a Box was already forming:

        if (Low[i] >= lowBO[i+1] && High[i] <= highBO[i+1]) {

          if (High[i+_period-1]==upper) upper = lower+_Range;
          if (Low[i+_period-1]==lower)  lower = upper-_Range;

          for (jj = iBarShift(NULL,0,current_box_1st_bar_time); jj>=i; jj--) {
            highBO[jj] = upper + BoxBufferPips * pip;
            lowBO[jj]  = lower - BoxBufferPips * pip;
          }

          highBOcont[i+1] = EMPTY_VALUE;
          lowBOcont[i+1]  = EMPTY_VALUE;
          highBOcont[i] = upper + BoxBufferPips * pip;
          lowBOcont[i]  = lower - BoxBufferPips * pip;
          current_box_forming_time = Time[i]; // update Box "forming" candle;

          drawBox(prefix+"trueBox"+TimeToStr(current_box_1st_bar_time), current_box_1st_bar_time, upper, current_box_forming_tim

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

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

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

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

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

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

Стоимость полного кода
2 557,10₽ ≈ $31.26