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

smashers pip collector.mq5

Похожие материалы по тегам

ares_indicator.pineTradingView · 1 общих теговgold_trend_revers.mq5MQL5 / MetaTrader 5 · 1 общих тегов!!!-mt4 x-xardg-rsi.mq5MQL5 / MetaTrader 5 · 1 общих тегов! cycle-identifier.mq5MQL5 / MetaTrader 5 · 1 общих тегов!!! rsi ma simple+arrows 1.2 (mtf).mq5MQL5 / MetaTrader 5 · 1 общих теговprecisionflowea.mq5MQL5 / MetaTrader 5 · 1 общих тегов
Вы автор или правообладатель?

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

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

О программе

«SMASHERS PIP COLLECTOR» — это пользовательский индикатор для MetaTrader 5, который объединяет несколько технических индикаторов (RSI, Stochastic, Supertrend, CCI) и анализ ценового действия для формирования торговых сигналов с уровнями тейк-профита и стоп-лосса. Индикатор отображает на графике стрелки сигналов, прямоугольные рамки риск-доходности, линии EMA 750, VWAP и полосы ATR, а также предоставляет информационную панель со статистикой.

В основе работы лежит система подтверждений: сигнал генерируется при достижении минимального количества совпадающих условий от выбранных индикаторов. Дополнительно применяются фильтры — скользящая средняя EMA 750, VWAP, полосы ATR и фильтр торговых сессий (Азия, Лондон, Нью-Йорк). Все параметры настраиваются через панель свойств индикатора.

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

Индикатор работает на графике и не выполняет автоматическую торговлю — он предназначен для визуального анализа и передачи сигналов внешним советникам через буферы.

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

НастройкаОписание
grp_tp_inputs Группа входных параметров TP-системы.
RSI Length (InpTPRsiLen) Период индикатора RSI.
RSI Overbought (InpTPRsiOB) Порог перекупленности RSI — значение выше которого индикатор считается перекупленным.
RSI Oversold (InpTPRsiOS) Порог перепроданности RSI — значение ниже которого индикатор считается перепроданным.
Stochastic %K Length (InpStochKLen) Период линии %K стохастика.
Stochastic %D Length (InpStochDLen) Период сглаживания линии %D стохастика.
Stochastic Smooth (InpStochSmooth) Период сглаживания линии %K стохастика.
Supertrend ATR Multiplier (InpSTAtrMult) Множитель ATR для определения ширины полос Supertrend.
Supertrend ATR Length (InpSTAtrLen) Период ATR для расчёта индикатора Supertrend.
CCI Length (InpCCILen) Период индикатора CCI (Commodity Channel Index).
CCI Overbought (InpCCIOB) Порог перекупленности CCI — значение выше которого индикатор считается перекупленным.
CCI Oversold (InpCCIOS) Порог перепроданности CCI — значение ниже которого индикатор считается перепроданным.
Price Action Lookback (InpLookBackBars) Количество баров назад для анализа ценового действия (сравнение текущей цены с ценой в прошлом).
Minimum Confirmations (1-8) (InpMinTPConf) Минимальное количество совпадающих подтверждений от индикаторов для формирования сигнала (от 1 до 8).
grp_tp_toggles Группа переключателей индикаторов TP-системы.
Use RSI (InpUseTPRSI) Включает или отключает использование RSI в системе подтверждений сигналов.
Use Stochastic (InpUseTPStoch) Включает или отключает использование Stochastic в системе подтверждений сигналов.
Use Supertrend (InpUseTPSTrend) Включает или отключает использование Supertrend в системе подтверждений сигналов.
Use CCI (InpUseTPCCI) Включает или отключает использование CCI в системе подтверждений сигналов.
Use Price Action (InpUseTPPriceAct) Включает или отключает использование анализа ценового действия в системе подтверждений.
grp_filters Группа настроек фильтров.
Enable EMA 750 Filter (InpUseEMA750) Включает или отключает фильтр скользящей средней EMA 750 при формировании сигналов.
Enable VWAP Filter (InpUseVWAP) Включает или отключает использование VWAP в качестве фильтра при формировании сигналов.
Enable ATR Band Filter (InpUseATRBand) Включает или отключает фильтр полос ATR при формировании сигналов.
ATR Multiplier (InpAtrMult) Множитель ATR для расчёта ширины полос ATR на основе EMA 750.
grp_theme Группа настроек цветовой темы графика.
Auto-Apply Custom TPL Theme (InpApplyTheme) Автоматически применяет пользовательскую цветовую тему на график при загрузке индикатора.
Chart Background (InpBgColor) Цвет фона графика.
Text / Scale Color (InpFgColor) Цвет текста и шкалы на графике.
Bar Up Color (InpBarUpColor) Цвет растущих (бычьих) баров на графике.
Bar Down Color (InpBarDownColor) Цвет нисходящих (медвежьих) баров на графике.
Bullish Candle Color (InpBullColor) Цвет тел бычьих свечей на графике.
Bearish Candle Color (InpBearColor) Цвет тел медвежьих свечей на графике.
Grid Color (InpGridColor) Цвет ценовой сетки на графике.
Bid Line Color (InpBidLineColor) Цвет линии Bid на графике.
Ask Line Color (InpAskLineColor) Цвет линии Ask на графике.
Stops Color (InpStopsColor) Цвет уровней стоп-лосса на графике.
grp_display Группа настроек отображения графика и интерфейса.
Show TP Signals △▽ (InpShowTPSignals) Отображает или скрывает стрелки-сигналы △ и ▽ на графике.
Signal Arrow Size (Font Size) (InpArrowSize) Размер шрифта стрелок-сигналов на графике.
Show EMA 750 Line (InpShowEMA750Line) Отображает или скрывает линию скользящей средней EMA 750 на графике.
Show VWAP Line (InpShowVWAPLine) Отображает или скрывает линию VWAP на графике.
Show ATR Bands (InpShowATRBands) Отображает или скрывает полосы ATR на графике.
grp_trade_settings Группа настроек торговли и отображения торговой информации.
Show Risk Reward Boxes (InpShowRR) Отображает или скрывает прямоугольные рамки риск-доходности для активных виртуальных сделок.
Overlap Trades (InpOverlapTrades) Разрешает одновременное открытие нескольких виртуальных сделок без ожидания закрытия предыдущих.
SL Buffer (pips) (InpRrSlPips) Дополнительный буфер в пипсах для расчёта расстояния стоп-лосса от цены входа.
Risk:Reward Ratio (InpRrRatio) Соотношение риска к доходности — во сколько раз тейк-профит превышает стоп-лосс.
Show TP/SL Pip Labels (InpShowPipLabels) Отображает или скрывает текстовые метки с количеством пипсов у уровней TP и SL.
Show Dashboard Table (InpShowTable) Отображает или скрывает информационную панель дашборда на графике.
grp_sessions Группа настроек торговых сессий.
Broker UTC Offset (Hours) (InpUtcOffset) Смещение часового пояса брокера от UTC в часах для корректного определения торговых сессий.
Enable Session Filter (InpUseSessionFlt) Включает или отключает фильтр торговых сессий.
Show Session Stats in Table (InpShowSessStats) Отображает или скрывает строки со статистикой по торговым сессиям в дашборде.
Best Session: rank by Pips (InpBestByPips) Определяет критерий ранжирования сессий — по чистым пипсам или по количеству сделок.
Include Asia (InpUseAsia) Включает или отключает учёт азиатской торговой сессии.
Asia Time Range (InpAsiaSession) Временной диапазон азиатской торговой сессии в формате ЧЧ:ММ-ЧЧ:ММ.
Include London (InpUseLondon) Включает или отключает учёт лондонской торговой сессии.
London Time Range (InpLondonSession) Временной диапазон лондонской торговой сессии в формате ЧЧ:ММ-ЧЧ:ММ.
Include New York (InpUseNY) Включает или отключает учёт нью-йоркской торговой сессии.
New York Time Range (InpNYSession) Временной диапазон нью-йоркской торговой сессии в формате ЧЧ:ММ-ЧЧ:ММ.
grp_alerts Группа настроек оповещений.
Enable Buy Alert (InpAlertBuy) Включает или отключает оповещение при появлении сигнала на покупку.
Enable Sell Alert (InpAlertSell) Включает или отключает оповещение при появлении сигнала на продажу.
Enable TP/SL Alert (InpAlertTPSL) Включает или отключает оповещение при достижении уровней тейк-профита или стоп-лосса.
Enable Entry Alert (InpAlertEntry) Включает или отключает оповещение при исполнении входа в позицию с указанием цены, стоп-лосса и тейк-профита.
Получить полный код

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

#property version   "2.00"

#property indicator_chart_window
#property indicator_buffers 6
#property indicator_plots   6

#property indicator_label1  "EMA 750"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrSilver
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1

#property indicator_label2  "VWAP"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrMediumVioletRed
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1

#property indicator_label3  "ATR Upper Band"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrGray
#property indicator_style3  STYLE_SOLID
#property indicator_width3  1

#property indicator_label4  "ATR Lower Band"
#property indicator_type4   DRAW_LINE
#property indicator_color4  clrGray
#property indicator_style4  STYLE_SOLID
#property indicator_width4  1

#property indicator_label5  "TP Buy Buffer"
#property indicator_type5   DRAW_NONE
#property indicator_label6  "TP Sell Buffer"
#property indicator_type6   DRAW_NONE

#define DASHBOARD_PREFIX    "SMASH_DB_"
#define RRBOX_PREFIX        "SMASH_RR_"
#define SIGNAL_PREFIX       "SMASH_SIG_"
#define MAX_TRACKED_TRADES  1500
#define SYSTEM_VERSION      "V3.4 ENTERPRISE"

enum ENUM_TRADE_SESSION
  {
   SESS_ASIA = 0,    // Asia Session
   SESS_LONDON = 1,  // London Session
   SESS_NY = 2,      // New York Session
   SESS_OFF = 3      // Off-Session
  };

sinput string                 grp_tp_inputs     = "─── TP SYSTEM INPUTS ───";
input int                     InpTPRsiLen       = 25;       // RSI Length
input int                     InpTPRsiOB        = 55;       // RSI Overbought
input int                     InpTPRsiOS        = 45;       // RSI Oversold
input int                     InpStochKLen      = 14;       // Stochastic %K Length
input int                     InpStochDLen      = 3;        // Stochastic %D Length
input int                     InpStochSmooth    = 3;        // Stochastic Smooth
input double                  InpSTAtrMult      = 3.0;      // Supertrend ATR Multiplier
input int                     InpSTAtrLen       = 10;       // Supertrend ATR Length
input int                     InpCCILen         = 20;       // CCI Length
input double                  InpCCIOB          = 100.0;    // CCI Overbought
input double                  InpCCIOS          = -100.0;   // CCI Oversold
input int                     InpLookBackBars   = 5;        // Price Action Lookback
input int                     InpMinTPConf      = 5;        // Minimum Confirmations (1-8)

sinput string                 grp_tp_toggles    = "─── INDICATOR TOGGLES ───";
input bool                    InpUseTPRSI       = true;     // Use RSI
input bool                    InpUseTPStoch     = true;     // Use Stochastic
input bool                    InpUseTPSTrend    = true;     // Use Supertrend
input bool                    InpUseTPCCI       = true;     // Use CCI
input bool                    InpUseTPPriceAct  = true;     // Use Price Action

sinput string                 grp_filters       = "─── FILTERS ───";
input bool                    InpUseEMA750      = true;     // Enable EMA 750 Filter
input bool                    InpUseVWAP        = true;     // Enable VWAP Filter
input bool                    InpUseATRBand     = false;    // Enable ATR Band Filter
input double                  InpAtrMult        = 10.0;     // ATR Multiplier

sinput string                 grp_theme         = "─── CHART THEME 🎨 ───";
input bool                    InpApplyTheme     = true;     // Auto-Apply Custom TPL Theme
input color                   InpBgColor        = 0;        // Chart Background
input color                   InpFgColor        = 1513907;  // Text / Scale Color
input color                   InpBarUpColor     = 1513907;  // Bar Up Color
input color                   InpBarDownColor   = 1513907;  // Bar Down Color
input color                   InpBullColor      = 0;        // Bullish Candle Color
input color                   InpBearColor      = 1513907;  // Bearish Candle Color
input color                   InpGridColor      = 1315860;  // Grid Color
input color                   InpBidLineColor   = 10061943; // Bid Line Color
input color                   InpAskLineColor   = 1315860;  // Ask Line Color
input color                   InpStopsColor     = 255;      // Stops Color

sinput string                 grp_display       = "─── DISPLAY ───";
input bool                    InpShowTPSignals  = true;     // Show TP Signals △▽
input int                     InpArrowSize      = 14;       // Signal Arrow Size (Font Size)
input bool                    InpShowEMA750Line = false;     // Show EMA 750 Line
input bool                    InpShowVWAPLine   = false;     // Show VWAP Line
input bool                    InpShowATRBands   = false;     // Show ATR Bands

sinput string                 grp_trade_settings= "─── TRADE SETTINGS ───";
input bool                    InpShowRR         = true;     // Show Risk Reward Boxes
input bool                    InpOverlapTrades  = false;    // Overlap Trades
input double                  InpRrSlPips       = 10.0;     // SL Buffer (pips)
input double                  InpRrRatio        = 3.0;      // Risk:Reward Ratio
input bool                    InpShowPipLabels  = true;     // Show TP/SL Pip Labels
input bool                    InpShowTable      = true;     // Show Dashboard Table

sinput string                 grp_sessions      = "─── SESSIONS ───";
input int                     InpUtcOffset      = 1;        // Broker UTC Offset (Hours)
input bool                    InpUseSessionFlt  = true;     // Enable Session Filter
input bool                    InpShowSessStats  = false;    // Show Session Stats in Table
input bool                    InpBestByPips     = true;     // Best Session: rank by Pips
input bool                    InpUseAsia        = true;     // Include Asia
input string                  InpAsiaSession    = "00:00-08:00"; // Asia Time Range
input bool                    InpUseLondon      = true;     // Include London
input string                  InpLondonSession  = "07:00-16:00"; // London Time Range
input bool                    InpUseNY          = true;     // Include New York
input string                  InpNYSession      = "13:00-22:00"; // New York Time Range

sinput string                 grp_alerts        = "─── ALERTS ───";
input bool                    InpAlertBuy       = true;     // Enable Buy Alert
input bool                    InpAlertSell      = true;     // Enable Sell Alert
input bool                    InpAlertTPSL      = true;     // Enable TP/SL Alert
input bool                    InpAlertEntry     = true;     // Enable Entry Alert

double         ExtEmaBuffer[];
double         ExtVwapBuffer[];
double         ExtAtrUpBuffer[];
double         ExtAtrDnBuffer[];
double         ExtBuyArrowBuffer[];
double         ExtSellArrowBuffer[];

int            handle_rsi;
int            handle_stoch;
int            handle_cci;
int            handle_ema750;
int            handle_atr;

double         rsi_buf[];
double         stoch_k_buf[];
double         stoch_d_buf[];
double         cci_buf[];
double         ema750_buf[];
double         atr_buf[];

double         global_pip_size;

class CChartThemeEngine
  {
public:
   CChartThemeEngine() {}

   void InjectTheme()
     {
      if(!InpApplyTheme) return;

      ChartSetInteger(0, CHART_MODE, CHART_CANDLES);
      ChartSetInteger(0, CHART_SHOW_GRID, false);
      ChartSetInteger(0, CHART_SHOW_VOLUMES, CHART_VOLUME_TICK);
      ChartSetInteger(0, CHART_AUTOSCROLL, true);
      ChartSetInteger(0, CHART_SHIFT, true);
      ChartSetInteger(0, CHART_SHOW_OHLC, false);
      ChartSetInteger(0, CHART_SHOW_BID_LINE, true);
      ChartSetInteger(0, CHART_SHOW_ASK_LINE, true);
      ChartSetInteger(0, CHART_SHOW_TRADE_LEVELS, true);
      ChartSetInteger(0, CHART_SHOW_ONE_CLICK, false);

      ChartSetInteger(0, CHART_COLOR_BACKGROUND, InpBgColor);
      ChartSetInteger(0, CHART_COLOR_FOREGROUND, InpFgColor);
      ChartSetInteger(0, CHART_COLOR_GRID, InpGridColor);

      ChartSetInteger(0, CHART_COLOR_CHART_UP, InpBarUpColor);
      ChartSetInteger(0, CHART_COLOR_CHART_DOWN, InpBarDownColor);

      ChartSetInteger(0, CHART_COLOR_CANDLE_BULL, InpBullColor);
      ChartSetInteger(0, CHART_COLOR_CANDLE_BEAR, InpBearColor);

      ChartSetInteger(0, CHART_COLOR_BID, InpBidLineColor);
      ChartSetInteger(0, CHART_COLOR_ASK, InpAskLineColor);
      ChartSetInteger(0, CHART_COLOR_STOP_LEVEL, InpStopsColor);
      ChartSetInteger(0, CHART_COLOR_VOLUME, InpBarUpColor);

      ChartRedraw(0);
     }
  };

CChartThemeEngine gTheme;

class CSystemLogger
  {
private:
   bool m_enable_logging;

public:
   CSystemLogger()
     {
      m_enable_logging = false; 
     }

   void Info(string message)
     {
      if(m_enable_logging)
         Print("[FX SMASHERS INFO] ", message);
     }

   void Error(string message)
     {
      Print("[FX SMASHERS ERROR] ", message);
     }

   void LogTrade(int ticket, string type, double price, double sl, double tp)
     {
      if(m_enable_logging)
         PrintFormat("[TRADE EVENT] Ticket: %d | Type: %s | Entry: %.5f | SL: %.5f | TP: %.5f", ticket, type, price, sl, tp);
     }
  };

CSystemLogger gLogger;

class CMathUtils
  {
public:
   CMathUtils() {}

   double CalculateDistance(double price1, double price2)
     {
      return MathAbs(price1 - price2);
     }

   double CalculatePipValue(double price_distance, double pip_size)
     {
      if(pip_size == 0) return 0.0;
      return price_distance / pip_size;
     }

   double CalculateWinRate(int wins, int total_trades)
     {
      if(total_trades <= 0) return 0.0;
      return ((double)wins / (double)total_trades) * 100.0;
     }

   double RoundToTick(double price, double tick_size)
     {
      if(tick_size == 0) return price;
      return MathRound(price / tick_size) * tick_size;
     }
  };

CMathUtils gMath;

class CChartVisuals
  {
public:
   CChartVisuals() {}

   void CreateRectangle(string name, datetime time1, double price1, datetime time2, double price2, color bg_color, color border_color)
     {
      if(ObjectFind(0, name) < 0)
        {
         ObjectCreate(0, name, OBJ_RECTANGLE, 0, time1, price1, time2, price2);
        }
      else
        {
         ObjectSetInteger(0, name, OBJPROP_TIME, 0, time1);
         ObjectSetDouble(0, name, OBJPROP_PRICE, 0, price1);
         ObjectSetInteger(0, name, OBJPROP_TIME, 1, time2);
         ObjectSetDouble(0, name, OBJPROP_PRICE, 1, price2);
        }

      ObjectSetInteger(0, name, OBJPROP_COLOR, border_color);
      ObjectSetInteger(0, name, OBJPROP_BGCOLOR, bg_color);
      ObjectSetInteger(0, name, OBJPROP_FILL, true);
      ObjectSetInteger(0, name, OBJPROP_BACK, true);
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
     }

   void UpdateRectangleEnd(string name, datetime time2)
     {
      if(ObjectFind(0, name) >= 0)
        {
         ObjectSetInteger(0, name, OBJPROP_TIME, 1, time2);
        }
     }

   void CreateTextLabel(string name, datetime time, double price, string text, color text_color, int font_size, ENUM_ANCHOR_POINT anchor = ANCHOR_LEFT_LOWER)
     {
      if(ObjectFind(0, name) < 0)
        {
         ObjectCreate(0, name, OBJ_TEXT, 0, time, price);
        }
      else
        {
         ObjectSetInteger(0, name, OBJPROP_TIME, time);
         ObjectSetDouble(0, name, OBJPROP_PRICE, price);
        }

      ObjectSetString(0, name, OBJPROP_TEXT, text);
      ObjectSetInteger(0, name, OBJPROP_COLOR, text_color);
      ObjectSetInteger(0, name, OBJPROP_FONTSIZE, font_size);
      ObjectSetString(0, name, OBJPROP_FONT, "Arial");
      ObjectSetInteger(0, name, OBJPROP_ANCHOR, anchor);
      ObjectSetInteger(0, name, OBJPROP_SELECTABLE, false);
      ObjectSetInteger(0, name, OBJPROP_HIDDEN, true);
     }

   void CreateTriangleSignal(datetime time, double price, bool is_buy)
     {
      if(!InpShowTPSignals) return;

      string obj_name = SIGNAL_PREFIX + TimeToString(time);
      if(is_buy)
        {

         CreateTextLabel(obj_name, time, price, "△", clrLime, InpArrowSize, ANCHOR_UPPER);
        }
      else
        {

         CreateTextLabel(obj_name, time, price, "▽", clrRed, InpArrowSize, ANCHOR_LOWER);
        }
     }

   void DeleteObject(string name)
     {
      if(ObjectFind(0, name) >= 0)
        {
         ObjectDelete(0, name);
        }
     }

   void CleanAllPrefix(string prefix)
     {
      ObjectsDeleteAll(0, prefix);
     }
  };

CChartVisuals gVisuals;

class CVirtualTrade
  {
public:
   int                  m_ticket;
   datetime             m_entry_time;
   double               m_entry_price;
   double               m_sl_level;
   double               m_tp_level;
   bool                 m_is_long;
   ENUM_TRADE_SESSION   m_session;
   bool                 m_is_active;
   double               m_result_pips;

   string               m_sl_box_name;
   string               m_tp_box_name;
   string               m_tp_label_name;
   string               m_sl_label_name;

   CVirtualTrade()
     {
      m_ticket = 0;
      m_is_active = false;
      m_result_pips = 0.0;
     }

   void Initialize(int ticket_id, datetime entry_t, double entry_p, double sl, double tp, bool is_long_trade, ENUM_TRADE_SESSION sess)
     {
      m_ticket = ticket_id;
      m_entry_time = entry_t;
      m_entry_price = entry_p;
      m_sl_level = sl;
      m_tp_level = tp;
      m_is_long = is_long_trade;
      m_session = sess;
      m_is_active = true;
      m_result_pips = 0.0;

      string ticket_str = IntegerToString(m_ticket);
      m_sl_box_name = RRBOX_PREFIX + "SL_" + ticket_str;
      m_tp_box_name = RRBOX_PREFIX + "TP_" + ticket_str;
      m_tp_label_name = RRBOX_PREFIX + "LBL_TP_" + ticket_str;
      m_sl_label_name = RRBOX_PREFIX + "LBL_SL_" + ticket_str;
     }
  };

class CTradeManager
  {
private:
   CVirtualTrade        m_trades[MAX_TRACKED_TRADES];
   int                  m_active_count;
   int                  m_total_historical;

public:

   int                  stat_total_trades;
   int                  stat_total_wins;
   double               stat_win_pips;
   double               stat_loss_pips;

   int                  asia_total;
   int                  asia_wins;
   double               asia_win_pips;
   double               asia_loss_pips;

   int                  lon_total;
   int                  lon_wins;
   double               lon_win_pips;
   double               lon_loss_pips;

   int                  ny_total;
   int                  ny_wins;
   double               ny_win_pips;
   double               ny_loss_pips;

   int                  off_total;
   int                  off_wins;
   double               off_win_pips;
   double               off_loss_pips;

   CTradeManager()
     {
      ResetStatistics();
     }

   void ResetStatistics()
     {
      m_active_count = 0;
      m_total_historical = 0;
      stat_total_trades = 0;
      stat_total_wins = 0;
      stat_win_pips = 0.0;
      stat_loss_pips = 0.0;

      asia_total = 0; asia_wins = 0; asia_win_pips = 0.0; asia_loss_pips = 0.0;
      lon_total = 0; lon_wins = 0; lon_win_pips = 0.0; lon_loss_pips = 0.0;
      ny_total = 0; ny_wins = 0; ny_win_pips = 0.0; ny_loss_pips = 0.0;
      off_total = 0; off_wins = 0; off_win_pips = 0.0; off_loss_pips = 0.0;
     }

   int GetActiveTradeCount() 
     { 
      return m_active_count; 
     }

   bool OpenVirtualTrade(datetime exec_time, double exec_price, double exec_sl, double exec_tp, bool is_buy, ENUM_TRADE_SESSION trade_session)
     {
      if(!InpOverlapTrades && m_active_count > 0) return false;
      if(m_active_count >= MAX_TRACKED_TRADES) return false;

      m_total_historical++;
      m_trades[m_active_count].Initialize(m_total_historical, exec_time, exec_price, exec_sl, exec_tp, is_buy, trade_session);

      if(InpShowRR)
        {
         RenderRiskRewardBoxes(m_trades[m_active_count], exec_time);
        }

      gLogger.LogTrade(m_total_historical, is_buy ? "LONG" : "SHORT", exec_price, exec_sl, exec_tp);
      m_active_count++;
      return true;
     }

   void EvaluateActiveTrades(int index, const datetime &time_arr[], const double &high_arr[], const double &low_arr[], const double &close_arr[])
     {
      for(int i = m_active_count - 1; i >= 0; i--)
        {
         bool is_sl_hit = false;
         bool is_tp_hit = false;

         if(m_trades[i].m_is_long)
           {
            if(low_arr[index] <= m_trades[i].m_sl_level) is_sl_hit = true;
            if(high_arr[index] >= m_trades[i].m_tp_level) is_tp_hit = true;
           }
         else
           {
            if(high_arr[index] >= m_trades[i].m_sl_level) is_sl_hit = true;
            if(low_arr[index] <= m_trades[i].m_tp_level) is_tp_hit = true;
           }

         if(InpShowRR && !is_sl_hit && !is_tp_hit)
           {
            UpdateBoxTimings(m_trades[i], time_arr[index]);
           }

         if(is_sl_hit || is_tp_hit)
           {
            if(InpShowRR) UpdateBoxTimings(m_trades[i], time_arr[index]);

            double pips_captured = 0.0;

            if(is_tp_hit)
              {
               pips_captured = gMath.CalculatePipValue(gMath.CalculateDistance(m_trades[i].m_tp_level, m_trades[i].m_entry_price), global_pip_size);
               stat_total_wins++;
               stat_win_pips += pips_captured;

               if(InpShowRR && InpShowPipLabels) 
                 {
                  string label_txt = "+" + DoubleToString(pips_captured, 1) + " pips";
                  gVisuals.CreateTextLabel(m_trades[i].m_tp_label_name, time_arr[index], m_trades[i].m_tp_level, label_txt, clrLimeGreen, 10, ANCHOR_LEFT_LOWER);
                 }
               gVisuals.DeleteObject(m_trades[i].m_sl_label_name);

               RecordSessionWin(m_trades[i].m_session, pips_captured);
              }
            else
              {
               pips_captured = gMath.CalculatePipValue(gMath.CalculateDistance(m_trades[i].m_sl_level, m_trades[i].m_entry_price), global_pip_size);
               stat_loss_pips += pips_captured;

               if(InpShowRR && InpShowPipLabels) 
                 {
                  string label_txt = "-" + DoubleToString(pips_captured, 1) + " pips";
                  gVisuals.CreateTextLabel(m_trades[i].m_sl_label_name, time_arr[index], m_trades[i].m_sl_level, label_txt, clrRed, 10, ANCHOR_LEFT_LOWER);
                 }
               gVisuals.DeleteObject(m_trades[i].m_tp_label_name);

               RecordSessionLoss(m_trades[i].m_session, pips_captured);
              }

            stat_total_trades++;
            RemoveTradeFromActiveList(i);
           }
        }
     }

private:
   void RecordSessionWin(ENUM_TRADE_SESSION sess, double pips)
     {
      switch(sess)
        {
         case SESS_ASIA: asia_total++; asia_wins++; asia_win_pips += pips; break;
         case SESS_LONDON: lon_total++; lon_wins++; lon_win_pips += pips; break;
         case SESS_NY: ny_total++; ny_wins++; ny_win_pips += pips; break;
         case SESS_OFF: off_total++; off_wins++; off_win_pips += pips; break;
        }
     }

   void RecordSessionLoss(ENUM_TRADE_SESSION sess, double pips)
     {
      switch(sess)
        {
         case SESS_ASIA: asia_total++; asia_loss_pips += pips; break;
         case SESS_LONDON: lon_total++; lon_loss_pips += pips; break;
         case SESS_NY: ny_total++; ny_loss_pips += pips; break;
         case SESS_OFF: off_total++; off_loss_pips += pips; break;
        }
     }

   void RemoveTradeFromActiveList(int index_to_remove)
     {
      for(int k = index_to_remove; k < m_active_count - 1; k++)
        {
         m_trades[k] = m_trades[k+1];
        }
      m_active_count--;
     }

   void RenderRiskRewardBoxes(CVirtualTrade &trade_obj, datetime current_time)
     {
      color color_tp_bg = clrSpringGreen;
      color color_sl_bg = clrCrimson;

      datetime extend_time = current_time + PeriodSeconds();

      gVisuals.CreateRectangle(trade_obj.m_tp_box_name, trade_obj.m_entry_time, trade_obj.m_entry_price, extend_time, trade_obj.m_tp_level, color_tp_bg, color_tp_bg);

      gVisuals.CreateRectangle(trade_obj.m_sl_box_name, trade_obj.m_entry_time, trade_obj.m_entry_price, extend_time, trade_obj.m_sl_level, color_sl_bg, color_sl_bg);
     }

   void UpdateBoxTimings(CVirtualTrade &trade_obj, datetime current_time)
     {
      datetime new_end_time = current_time + PeriodSeconds();
      gVisuals.UpdateRectangleEnd(trade_obj.m_tp_box_name, new_end_time);
      gVisuals.UpdateRectangleEnd(trade_obj.m_sl_box_name, new_end_time);
     }
  };

CTradeManager gTracker;

class CDashboardInterface
  {
private:
   int m_offset_x;
   int m_offset_y;
   int m_width_cell;
   int m_height_cell;

public:
   CDashboardInterface()
     {

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

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

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

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

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

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

Стоимость полного кода
3 014,90₽ ≈ $36.85