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

ALGO Indicator

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

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

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

О программе

Данный продукт представляет собой торговый советник для MetaTrader 5, портированный с индикатора ALGO Indicator из Pine Script v5. Советник использует скользящие средние альтернативного таймфрейма (TEMA, HullMA, ALMA) для формирования торговых сигналов на основе пересечений серий закрытия и открытия. Поддерживаются сделки как в направлении Long, так и Short, или только один из них.

Система включает три уровня фиксации прибыли и один уровень стоп-лосса, настраиваемых в процентах от цены входа. Размер позиции рассчитывается как процент от текущего баланса счёта. Внутри бара управляются частичные закрытия по уровням TP1–TP3 и стоп-лоссу с возможностью строгого режима закрытия только активной транши.

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

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

НастройкаОписание
InpUseRes Переключатель использования альтернативного таймфрейма для расчёта сигналов.
InpIntRes Множитель для определения альтернативного таймфрейма (кратное текущему таймфрейму).
InpBasisType Тип используемой скользящей средней: TEMA, HullMA или ALMA.
InpBasisLen Период (количество баров) для расчёта скользящей средней.
InpOffsetSigma Параметр сигма (sigma) для расчёта ALMA или смещение для LSMA.
InpOffsetALMA Параметр смещения (offset) для расчёта скользящей средней ALMA.
InpDelayOffset Задержка в барах для расчёта скользящей средней альтернативного таймфрейма.
InpTradeType Направление торговых операций: Long, Short, оба направления или без сделок.
InpPctOfEquity Процент от текущего баланса счёта, используемый для расчёта размера позиции при входе.
InpLxLvlTP1 Уровень первой фиксации прибыли в процентах от цены входа.
InpLxQtyTP1 Процент объёма текущей позиции, закрываемый при достижении уровня TP1.
InpLxLvlTP2 Уровень второй фиксации прибыли в процентах от цены входа.
InpLxQtyTP2 Процент объёма текущей позиции, закрываемый при достижении уровня TP2.
InpLxLvlTP3 Уровень третьей фиксации прибыли в процентах от цены входа.
InpLxQtyTP3 Процент объёма текущей позиции, закрываемый при достижении уровня TP3.
InpLxLvlSL Уровень стоп-лосса в процентах от цены входа.
InpAlertOn Включение или выключение отображения уведомлений-меток на графике для торговых сигналов.
InpDrawLines Включение или выключение отрисовки горизонтальных линий входа, TP и SL с метками на графике.
InpStrictPineSL Режим строгого стоп-лосса: при срабатывании закрывается только активная транш в объёме, указанном параметром qty_percent.
InpMagicNumber Магический номер для идентификации позиций, открытых данным советником.
InpSlippage Максимально допустимое проскальзывание в пунктах при исполнении торговых операций.

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

#property version   "1.00"
#property strict

#include <Trade\Trade.mqh>

enum ENUM_MA_TYPE
{
   MA_TEMA   = 0, // TEMA
   MA_HULLMA = 1, // HullMA
   MA_ALMA   = 2  // ALMA
};

enum ENUM_TRADE_TYPE
{
   TRADE_BOTH  = 0, // BOTH
   TRADE_LONG  = 1, // LONG
   TRADE_SHORT = 2, // SHORT
   TRADE_NONE  = 3  // NONE
};

input group "=== SAIYAN OCC ==="
input bool            InpUseRes         = true;       // Use Alternate Signals
input int             InpIntRes         = 10;         // Multiplier for Alternate Signals
input ENUM_MA_TYPE    InpBasisType      = MA_ALMA;    // MA Type
input int             InpBasisLen       = 50;         // MA Period
input int             InpOffsetSigma    = 5;          // Offset for LSMA / Sigma for ALMA
input double          InpOffsetALMA     = 2.0;        // Offset for ALMA
input int             InpDelayOffset    = 0;          // Delay Open/Close MA
input ENUM_TRADE_TYPE InpTradeType      = TRADE_BOTH; // What trades should be taken

input group "=== Risk Management ==="
input double          InpPctOfEquity    = 1.0;        // Default Qty (% of Equity, Pine default = 1%)
input double          InpLxLvlTP1       = 0.2;        // Level TP1 (%)
input double          InpLxQtyTP1       = 80.0;       // Qty TP1 (%)
input double          InpLxLvlTP2       = 0.5;        // Level TP2 (%)
input double          InpLxQtyTP2       = 10.0;       // Qty TP2 (%)
input double          InpLxLvlTP3       = 7.0;        // Level TP3 (%)
input double          InpLxQtyTP3       = 2.0;        // Qty TP3 (%)
input double          InpLxLvlSL        = 0.5;        // Stop Loss (%)

input group "=== Display & Execution ==="
input bool            InpAlertOn        = true;       // Alert Labels On/Off
input bool            InpDrawLines      = true;       // Draw Entry / TP / SL Lines & Labels
input bool            InpStrictPineSL   = true;       // Strict Pine SL (closes active tranche qty_percent only)
input ulong           InpMagicNumber    = 26052026;   // Magic Number
input int             InpSlippage       = 10;         // Max Slippage (points)

CTrade trade;

double   g_condition        = 0.0;
double   g_prevCondition    = 0.0;

double   g_entryLine        = 0.0;
double   g_slLine           = 0.0;
double   g_tp1Line          = 0.0;
double   g_tp2Line          = 0.0;
double   g_tp3Line          = 0.0;

double   g_prevSlLine       = 0.0;
double   g_prevTp1Line      = 0.0;
double   g_prevTp2Line      = 0.0;
double   g_prevTp3Line      = 0.0;

bool     g_hasPrevAlt       = false;
double   g_prevCloseAlt     = 0.0;
double   g_prevOpenAlt      = 0.0;

datetime g_lastBarTime      = 0;
datetime g_entryTime        = 0;
double   g_initialVolume    = 0.0;
bool     g_tp1Executed      = false;
bool     g_tp2Executed      = false;
bool     g_tp3Executed      = false;
bool     g_slExecutedStage1 = false;
bool     g_slExecutedStage2 = false;
bool     g_slExecutedStage3 = false;

const string OBJ_PREFIX     = "ALGO_IND_";

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

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

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

void ProcessClosedBar()
{

   if(Bars(_Symbol, _Period) < 50)
      return;

   double currCloseAlt = 0.0, currOpenAlt = 0.0;
   if(!ComputeAltSeriesAtShift(1, currCloseAlt, currOpenAlt))
      return;

   if(!g_hasPrevAlt)
   {
      double initPrevClose = 0.0, initPrevOpen = 0.0;
      if(!ComputeAltSeriesAtShift(2, initPrevClose, initPrevOpen))
         return;
      g_prevCloseAlt = initPrevClose;
      g_prevOpenAlt  = initPrevOpen;
      g_hasPrevAlt   = true;
   }

   bool lxTrigger = false;
   bool sxTrigger = false;
   bool leTrigger = (currCloseAlt > currOpenAlt && g_prevCloseAlt <= g_prevOpenAlt);
   bool seTrigger = (currCloseAlt < currOpenAlt && g_prevCloseAlt >= g_prevOpenAlt);

   double close1 = iClose(_Symbol, _Period, 1);
   double high1  = iHigh(_Symbol, _Period, 1);
   double low1   = iLow(_Symbol, _Period, 1);
   double high2  = iHigh(_Symbol, _Period, 2);
   double low2   = iLow(_Symbol, _Period, 2);
   datetime time1 = iTime(_Symbol, _Period, 1);

   double prevCond = g_condition;

   double oldSlLine  = g_slLine;
   double oldTp1Line = g_tp1Line;
   double oldTp2Line = g_tp2Line;
   double oldTp3Line = g_tp3Line;

   if(leTrigger && prevCond <= 0.0)
      g_entryLine = close1;
   else if(seTrigger && prevCond >= 0.0)
      g_entryLine = close1;

   double slTopLvl = close1 + (close1 * (InpLxLvlSL / 100.0));
   double slBotLvl = close1 - (close1 * (InpLxLvlSL / 100.0));
   if(prevCond <= 0.0 && leTrigger)
      g_slLine = slBotLvl;
   else if(prevCond >= 0.0 && seTrigger)
      g_slLine = slTopLvl;

   bool slLong  = CheckCross(low1,  low2,  g_slLine, oldSlLine, false);
   bool slShort = CheckCross(high1, high2, g_slLine, oldSlLine, true);

   g_tp3Line = CalcTpLine(prevCond, 1.2, leTrigger, seTrigger, close1, InpLxLvlTP3, InpLxLvlTP3, oldTp3Line);
   g_tp2Line = CalcTpLine(prevCond, 1.1, leTrigger, seTrigger, close1, InpLxLvlTP2, InpLxLvlTP2, oldTp2Line);
   g_tp1Line = CalcTpLine(prevCond, 1.0, leTrigger, seTrigger, close1, InpLxLvlTP1, InpLxLvlTP1, oldTp1Line);

   bool tp3Long  = CheckCross(high1, high2, g_tp3Line, oldTp3Line, true);
   bool tp3Short = CheckCross(low1,  low2,  g_tp3Line, oldTp3Line, false);
   bool tp2Long  = CheckCross(high1, high2, g_tp2Line, oldTp2Line, true);
   bool tp2Short = CheckCross(low1,  low2,  g_tp2Line, oldTp2Line, false);
   bool tp1Long  = CheckCross(high1, high2, g_tp1Line, oldTp1Line, true);
   bool tp1Short = CheckCross(low1,  low2,  g_tp1Line, oldTp1Line, false);

   double newCond = prevCond;
   if(leTrigger && prevCond <= 0.0)
      newCond = 1.0;
   else if(seTrigger && prevCond >= 0.0)
      newCond = -1.0;
   else if(tp3Long && prevCond == 1.2)
      newCond = 1.3;
   else if(tp3Short && prevCond == -1.2)
      newCond = -1.3;
   else if(tp2Long && prevCond == 1.1)
      newCond = 1.2;
   else if(tp2Short && prevCond == -1.1)
      newCond = -1.2;
   else if(tp1Long && prevCond == 1.0)
      newCond = 1.1;
   else if(tp1Short && prevCond == -1.0)
      newCond = -1.1;
   else if(slLong && prevCond >= 1.0)
      newCond = 0.0;
   else if(slShort && prevCond <= -1.0)
      newCond = 0.0;
   else if(lxTrigger && prevCond >= 1.0)
      newCond = 0.0;
   else if(sxTrigger && prevCond <= -1.0)
      newCond = 0.0;

   g_prevCondition = prevCond;
   g_condition     = newCond;

   bool longE    = leTrigger && prevCond <=  0.0 && g_condition ==  1.0;
   bool shortE   = seTrigger && prevCond >=  0.0 && g_condition == -1.0;
   bool longX    = lxTrigger && prevCond >=  1.0 && g_condition ==  0.0;
   bool shortX   = sxTrigger && prevCond <= -1.0 && g_condition ==  0.0;
   bool longSL   = slLong    && prevCond >=  1.0 && g_condition ==  0.0;
   bool shortSL  = slShort   && prevCond <= -1.0 && g_condition ==  0.0;
   bool longTP3  = tp3Long   && prevCond ==  1.2 && g_condition ==  1.3;
   bool shortTP3 = tp3Short  && prevCond == -1.2 && g_condition == -1.3;
   bool longTP2  = tp2Long   && prevCond ==  1.1 && g_condition ==  1.2;
   bool shortTP2 = tp2Short  && prevCond == -1.1 && g_condition == -1.2;
   bool longTP1  = tp1Long   && prevCond ==  1.0 && g_condition ==  1.1;
   bool shortTP1 = tp1Short  && prevCond == -1.0 && g_condition == -1.1;

   double posVol = 0.0;
   int    posDir = 0; // +1 = Long, -1 = Short, 0 = Flat
   GetCurrentPosition(posVol, posDir);

   bool allowLong  = (InpTradeType == TRADE_BOTH || InpTradeType == TRADE_LONG);
   bool allowShort = (InpTradeType == TRADE_BOTH || InpTradeType == TRADE_SHORT);

   if(allowLong && posDir <= 0 && longE)
   {
      if(posDir < 0)
         CloseAllPositions(-1);

      double lots = CalculateEntryVolume(close1);
      if(lots > 0.0 && trade.Buy(lots, _Symbol, 0.0, 0.0, 0.0, "LE"))
      {
         g_initialVolume    = lots;
         g_entryTime        = time1;
         ResetExitFlags();
      }
   }

   if(longX && posDir > 0)
      CloseAllPositions(1);

   if(allowShort && posDir >= 0 && shortE)
   {
      if(posDir > 0)
         CloseAllPositions(1);

      double lots = CalculateEntryVolume(close1);
      if(lots > 0.0 && trade.Sell(lots, _Symbol, 0.0, 0.0, 0.0, "SE"))
      {
         g_initialVolume    = lots;
         g_entryTime        = time1;
         ResetExitFlags();
      }
   }

   if(shortX && posDir < 0)
      CloseAllPositions(-1);

   if(longE || shortE)
      g_entryTime = time1;

   if(InpAlertOn)
   {
      if(longE)               DrawSignalLabel(time1, low1,   "BUY",         clrGreen,  ANCHOR_TOP);
      if(shortE)              DrawSignalLabel(time1, high1,  "SELL",        clrRed,    ANCHOR_BOTTOM);
      if(longX || shortX)     DrawSignalLabel(time1, close1, "Close",       clrGray,   ANCHOR_BOTTOM);
      if(longTP1 || shortTP1) DrawSignalLabel(time1, close1, "Trail SL",    clrWhite,  ANCHOR_TOP);
      if(longTP2 || shortTP2) DrawSignalLabel(time1, close1, "Book Profit", clrLime,   ANCHOR_BOTTOM);
      if(longTP3 || shortTP3) DrawSignalLabel(time1, close1, "BP3",         clrOlive,  ANCHOR_BOTTOM);
      if(longSL || shortSL)   DrawSignalLabel(time1, close1, "SL",          clrMaroon, ANCHOR_BOTTOM);
   }

   if(InpDrawLines && g_entryTime > 0)
      UpdateTradeLines(leTrigger || seTrigger);

   g_prevCloseAlt = currCloseAlt;
   g_prevOpenAlt  = currOpenAlt;
   g_prevSlLine   = g_slLine;
   g_prevTp1Line  = g_tp1Line;
   g_prevTp2Line  = g_tp2Line;
   g_prevTp3Line  = g_tp3Line;
}

void ManageIntraBarExits()
{
   double posVol = 0.0;
   int    posDir = 0;
   GetCurrentPosition(posVol, posDir);
   if(posDir == 0 || posVol <= 0.0)
      return;

   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

   if(posDir > 0)
   {

      if(g_condition == 1.0)
      {
         if(!g_tp1Executed && g_tp1Line > 0.0 && bid >= g_tp1Line)
         {
            if(ClosePartialByPercent(1, InpLxQtyTP1, "LXTP1"))
               g_tp1Executed = true;
         }
         else if(!g_slExecutedStage1 && g_slLine > 0.0 && bid <= g_slLine)
         {
            if(InpStrictPineSL)
               g_slExecutedStage1 = ClosePartialByPercent(1, InpLxQtyTP1, "SL");
            else
               g_slExecutedStage1 = CloseAllPositions(1);
         }
      }

      else if(g_condition == 1.1)
      {
         if(!g_tp2Executed && g_tp2Line > 0.0 && bid >= g_tp2Line)
         {
            if(ClosePartialByPercent(1, InpLxQtyTP2, "LXTP2"))
               g_tp2Executed = true;
         }
         else if(!g_slExecutedStage2 && g_slLine > 0.0 && bid <= g_slLine)
         {
            if(InpStrictPineSL)
               g_slExecutedStage2 = ClosePartialByPercent(1, InpLxQtyTP2, "SL");
            else
               g_slExecutedStage2 = CloseAllPositions(1);
         }
      }

      else if(g_condition == 1.2)
      {
         if(!g_tp3Executed && g_tp3Line > 0.0 && bid >= g_tp3Line)
         {
            if(ClosePartialByPercent(1, InpLxQtyTP3, "LXTP3"))
               g_tp3Executed = true;
         }
         else if(!g_slExecutedStage3 && g_slLine > 0.0 && bid <= g_slLine)
         {
            if(InpStrictPineSL)
               g_slExecutedStage3 = ClosePartialByPercent(1, InpLxQtyTP3, "SL");
            else
               g_slExecutedStage3 = CloseAllPositions(1);
         }
      }
   }

   else if(posDir < 0)
   {

      if(g_condition == -1.0)
      {
         if(!g_tp1Executed && g_tp1Line > 0.0 && ask <= g_tp1Line)
         {
            if(ClosePartialByPercent(-1, InpLxQtyTP1, "SXTP1"))
               g_tp1Executed = true;
         }
         else if(!g_slExecutedStage1 && g_slLine > 0.0 && ask >= g_slLine)
         {
            if(InpStrictPineSL)
               g_slExecutedStage1 = ClosePartialByPercent(-1, InpLxQtyTP1, "SL");
            else
               g_slExecutedStage1 = CloseAllPositions(-1);
         }
      }

      else if(g_condition == -1.1)
      {
         if(!g_tp2Executed && g_tp2Line > 0.0 && ask <= g_tp2Line)
         {
            if(ClosePartialByPercent(-1, InpLxQtyTP2, "SXTP2"))
               g_tp2Executed = true;
         }
         else if(!g_slExecutedStage2 && g_slLine > 0.0 && ask >= g_slLine)
         {
            if(InpStrictPineSL)
               g_slExecutedStage2 = ClosePartialByPercent(-1, InpLxQtyTP2, "SL");
            else
               g_slExecutedStage2 = CloseAllPositions(-1);
         }
      }

      else if(g_condition == -1.2)
      {
         if(!g_tp3Executed && g_tp3Line > 0.0 && ask <= g_tp3Line)
         {
            if(ClosePartialByPercent(-1, InpLxQtyTP3, "SXTP3"))
               g_tp3Executed = true;
         }
         else if(!g_slExecutedStage3 && g_slLine > 0.0 && ask >= g_slLine)
         {
            if(InpStric

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