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

autofibonacci.mq5

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

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

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

О программе

AutoFibonacci — это пользовательский индикатор для платформы MetaTrader 5, предназначенный для автоматического построения уровней Фибоначчи на последнем обнаруженном свинге. Индикатор анализирует ценовые данные и определяет свингные максимумы и минимумы, после чего отображает уровни ретрейсмента Фибоначчи на завершённом ценовом участке.

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

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

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

НастройкаОписание
InpSwingLeft Количество баров слева от кандидата, которые должны быть ниже (для свинг-хай) или выше (для свинг-лоу) для подтверждения свинга. Минимум 1.
InpSwingRight Количество баров справа от кандидата, которые должны быть ниже (для свинг-хай) или выше (для свинг-лоу) для подтверждения свинга. Минимум 1.
InpMinLegPoints Минимальный размер ценового участка между двумя свингами в пунктах. Если участок меньше этого значения, он игнорируется. 0 — без фильтра.
InpHistoryBars Количество баров, просматриваемых при первоначальной загрузке индикатора для поиска исторических свегов. Минимум 100.
InpLevels Процентные уровни Фибоначчи через запятую (до 12 значений). Например: 0,23.6,38.2,50,61.8,78.6,100.
InpExtendRight Если включено, линии уровней Фибоначчи продлеваются вправо за пределы последнего бара.
InpShowLabels Отображать текстовые метки с названием уровня и ценой рядом с каждой линией уровня.
InpLevelColor Цвет линий уровней Фибоначчи и их текстовых меток.
InpLegColor Цвет линии, соединяющей два свинг-пункта (ценовой участок).
InpShowPivots Отмечать свингные максимумы и минимумы точками-стрелками на графике.
InpShowInfoLabel Отображать метку в углу графика с информацией о текущем свеге и проценте ретрейсмента.
InpLabelColor Цвет текстовой метки с информацией о ретрейсменте.

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

#property version     "1.00"
#property description "Auto Fibonacci Retracement on the latest swing."
#property description "Swing highs and lows are detected automatically; the Fibonacci levels are"
#property description "drawn on the latest completed swing leg and move when a new swing is confirmed."

#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   2

#property indicator_label1  "Swing High"
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrTomato
#property indicator_width1  3

#property indicator_label2  "Swing Low"
#property indicator_type2   DRAW_ARROW
#property indicator_color2  clrLimeGreen
#property indicator_width2  3

input group "Swing detection"
input int    InpSwingLeft      = 5;                           // Bars to the left that must be lower/higher (1 or more)
input int    InpSwingRight     = 5;                           // Bars to the right that must be lower/higher (1 or more)
input int    InpMinLegPoints   = 0;                           // Minimum size of a swing leg in points (0 = no filter)
input int    InpHistoryBars    = 3000;                        // Bars searched for swings on load (100 or more)

input group "Fibonacci levels"
input string InpLevels         = "0,23.6,38.2,50,61.8,78.6,100"; // Levels in percent, comma separated (up to 12)
input bool   InpExtendRight    = true;                        // Extend the level lines to the right
input bool   InpShowLabels     = true;                        // Show a label (level and price) for every line
input color  InpLevelColor     = clrGoldenrod;                // Color of the level lines and labels
input color  InpLegColor       = clrGray;                     // Color of the line that joins the two swing points

input group "Display"
input bool   InpShowPivots     = true;                        // Mark the swing highs and lows with dots
input bool   InpShowInfoLabel  = true;                        // Show label with the swing and the current retracement
input color  InpLabelColor     = clrSilver;                   // Info label color

const int MAX_LEVELS = 12;

double BufPivHigh[];   // price of a swing high at the bar of the swing
double BufPivLow[];    // price of a swing low at the bar of the swing

double   g_pivPrice[2];  // swing prices
datetime g_pivTime[2];   // swing bar times
int      g_pivType[2];   // +1 swing high, -1 swing low
int      g_pivCount = 0; // number of swing points stored (0..2)

double   g_level[12];     // levels as ratios (38.2 -> 0.382)
string   g_levelText[12]; // level texts as typed by the user
int      g_levelCount = 0;
int      g_lastCand   = 0;     // last bar that was checked as a swing candidate
bool     g_changed    = false; // the leg changed and the objects must be redrawn
string   g_prefix     = "";    // prefix of the chart objects created by this instance

bool ParseLevels()
  {
   string parts[];
   int n = StringSplit(InpLevels, ',', parts);
   if(n < 1 || n > MAX_LEVELS)
      return(false);

   for(int k = 0; k < n; k++)
     {
      StringTrimLeft(parts[k]);
      StringTrimRight(parts[k]);
      if(StringLen(parts[k]) == 0)
         return(false);
      g_levelText[k] = parts[k];
      g_level[k]     = StringToDouble(parts[k]) / 100.0;
     }
   g_levelCount = n;
   return(true);
  }

void AddPivot(const int type, const double price, const datetime t)
  {

   if(g_pivCount == 0)
     {
      g_pivType[0]  = type;
      g_pivPrice[0] = price;
      g_pivTime[0]  = t;
      g_pivCount    = 1;
      return;
     }

   int li = g_pivCount - 1;   // index of the latest swing point

   if(type == g_pivType[li])
     {

      bool moreExtreme = (type > 0) ? (price > g_pivPrice[li]) : (price < g_pivPrice[li]);
      if(moreExtreme)
        {
         g_pivPrice[li] = price;
         g_pivTime[li]  = t;
         g_changed      = true;
        }
      return;
     }

   if(InpMinLegPoints > 0 && MathAbs(price - g_pivPrice[li]) / _Point < (double)InpMinLegPoints)
      return;

   if(g_pivCount == 1)
     {
      g_pivType[1]  = type;
      g_pivPrice[1] = price;
      g_pivTime[1]  = t;
      g_pivCount    = 2;
     }
   else
     {

      g_pivType[0]  = g_pivType[1];
      g_pivPrice[0] = g_pivPrice[1];
      g_pivTime[0]  = g_pivTime[1];
      g_pivType[1]  = type;
      g_pivPrice[1] = price;
      g_pivTime[1]  = t;
     }
   g_changed = true;
  }

void SetLine(const string name, const datetime t1, const double p1, const datetime t2, const double p2,
             const color clr, const ENUM_LINE_STYLE style, const bool rayRight)
  {
   if(ObjectFind(0, name) < 0)
     {
      if(!ObjectCreate(0, name, OBJ_TREND, 0, t1, p1, t2, p2))
         return;
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
      ObjectSetInteger(0, name, OBJPROP_RAY_LEFT, false);
      ObjectSetInteger(0, name, OBJPROP_WIDTH, 1);
     }
   ObjectSetInteger(0, name, OBJPROP_TIME, 0, t1);
   ObjectSetDouble(0, name, OBJPROP_PRICE, 0, p1);
   ObjectSetInteger(0, name, OBJPROP_TIME, 1, t2);
   ObjectSetDouble(0, name, OBJPROP_PRICE, 1, p2);
   ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
   ObjectSetInteger(0, name, OBJPROP_STYLE, style);
   ObjectSetInteger(0, name, OBJPROP_RAY_RIGHT, rayRight);
  }

void SetText(const string name, const datetime t, const double price, const string text, const color clr)
  {
   if(ObjectFind(0, name) < 0)
     {
      if(!ObjectCreate(0, name, OBJ_TEXT, 0, t, price))
         return;
      ObjectSetInteger(0, name, OBJPROP_ANCHOR, ANCHOR_LEFT);
      ObjectSetInteger(0, name, OBJPROP_FONTSIZE, 8);
      ObjectSetString(0, name, OBJPROP_FONT, "Arial");
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
     }
   ObjectSetInteger(0

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