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

******** v2.7

flexy the dragon v2.7.mq4

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

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 общих тегов
Вы автор или правообладатель?

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

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

О программе

******** v2.7 — торговый советник для MetaTrader 4, основанный на сеточной стратегии. Советник работает по тиковым событиям, анализирует рыночные данные и при необходимости совершает торговые операции через стандартные функции MQL4. В коде заявлена высокая степень риска, поэтому автор рекомендует использовать его только на демонстрационном счёте до полного понимания логики и принятия возможных потерь.

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

Сигналы могут формироваться как встроенными индикаторами (Bollinger Bands, Stochastic, RSI, CCI), так и до трёх пользовательских индикаторов с указанием имени, буферов и типа сигнала. Реализованы ограничения по времени работы, а также визуальное отображение линий и меток на графике. Все входные параметры вынесены в настройки и снабжены комментариями.

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

НастройкаОписание
. (gap00) Разделитель 00 — Разделитель в списке настроек.
Name of Strategy (Strategy) Название стратегии — Название стратегии, отображаемое в настройках.
Description (Description) Описание — Описание стратегии, отображаемое в настройках.
color of description (clrStrategy) Цвет стратегии — Цвет описания стратегии.
Magic Number (0 = automatic) (magic) Магический номер — Магический номер ордеров; 0 — автоматический.
. (gap01) Разделитель 01 — Разделитель в списке настроек.
Show Profit/Loss Info? (show_profit) Показывать прибыль — Показывать информацию о прибыли и убытках.
Show Trading Info? (show_forecast) Показывать торговлю — Показывать информацию о торговле.
Show Settings Info? (show_settings) Показывать настройки — Показывать информацию о настройках.
Show Indicators Info? (show_indicators) Показывать индикаторы — Показывать информацию об индикаторах.
(set all to "false" for fastest backtest) (show_info) Показывать информацию — Пояснение к отображению информации.
. (gap10) Разделитель 10 — Разделитель в списке настроек.
======> O R D E R S E T T I N G S <====== (Order_Settings) Настройки ордеров — Раздел настроек ордеров.
. (gap11) Разделитель 11 — Разделитель в списке настроек.
Base Lot Size (for first order) (min_lots) Базовый лот — Базовый размер лота для первого ордера.
Lot Progression (0=fixed 1=sum 2=marti 3=fibo) (progression) Прогрессия лота — Тип прогрессии лота: 0 — фиксированный, 1 — сумма, 2 — мартингейл, 3 — фибоначчи.
Lot Multiplier (only for martingale) (lot_multiplicator) Множитель лота — Множитель лота для мартингейла.
Use Auto Lot Size? (calculated by auto lot Balance) (use_autolot) Авто-лот — Использовать автоматический расчёт размера лота от баланса.
Auto Lot Balance (multiplied by base lot size) (AutoLotBalance) Баланс для авто-лота — Баланс, от которого рассчитывается автоматический размер лота.
. (gap13) Разделитель 13 — Разделитель в списке настроек.
Max. Spread (to open orders, in pts) (max_spread) Макс. спред — Максимальный спред для открытия ордеров в пунктах.
. (gap14) Разделитель 14 — Разделитель в списке настроек.
======> G R I D S E T T I N G S <====== (Grid_Settings) Настройки сетки — Раздел настроек сетки ордеров.
. (gap20) Разделитель 20 — Разделитель в списке настроек.
Max. Positions (per grid cycle) (max_positions) Макс. позиций — Максимальное количество позиций в одном цикле сетки.
Grid Progression (0=fixed 1=sum 2=marti 3=fibo) (gs_progression) Прогрессия сетки — Тип прогрессии сетки: 0 — фиксированная, 1 — сумма, 2 — мартингейл, 3 — фибоначчи.
Grid Multiplier (only for 2=martingale) (gs_multiplicator) Множитель сетки — Множитель для прогрессии сетки (только для мартингейла).
. (gap21) Разделитель 21 — Разделитель в списке настроек.
Fixed Grid Step (in pips) (grid_size) Шаг сетки — Фиксированный шаг сетки в пунктах.
Fixed Take Profit (in pips) (take_profit) Тейк-профит — Фиксированный тейк-профит в пунктах.
. (gap22) Разделитель 22 — Разделитель в списке настроек.
Use Dynamic Grid? (based on ATR) (Use_ATR) Использовать ATR — Использовать динамическую сетку на основе ATR.
ATR Time Frame (ATR_tf) Таймфрейм ATR — Таймфрейм для расчёта ATR.
ATR Period (ATR_Period) Период ATR — Период индикатора ATR, используемый при динамической сетке.
Dynamic Grid Step (ATR ratio) (ATR_Multiplier) Множитель ATR для сетки — Коэффициент для расчёта динамического шага сетки на основе ATR.
Dynamic Take Proft (ATR ratio) (TP_Multiplier) Множитель TP — Коэффициент для расчёта динамического тейк-профита на основе ATR.
. (gap23) Разделитель 23 — Разделитель в списке настроек.
======> R I S K S E T T I N G S <====== (Risk_Settings) Настройки риска — Раздел настроек риска.
. (gap30) Разделитель 30 — Разделитель в списке настроек.
1 Profit Lock / Trail Stop (profit_lock) Блокировка прибыли — Уровень блокировки прибыли / трейлинг-стопа.
(must be used!, locks in profit, 1.0 = 100%) (profit_info) Информация о прибыли — Пояснение к параметру блокировки прибыли.
2 Equity Warning / Yoga Mode (equity_warning) Предупреждение по эквити — Порог предупреждения по эквити, при котором останавливается открытие ордеров.
(stop open orders on low equity, 0.7 = 70%) (equity_info) Информация об эквити — Пояснение к параметру предупреждения по эквити.
3 Cycle Risk / Stop Loss (cycleEquityRisk) Риск цикла — Риск на цикл сетки в процентах от эквити.
(close orders of one grid cycle, 0.01 = 1%) (cycleEquityRisk_info) Информация о риске цикла — Пояснение к параметру риска цикла.
. (gap31) Разделитель 31 — Разделитель в списке настроек.
======> R E C O V E R Y S E T T I N G S <====== (Recovery_Settings) Настройки восстановления — Раздел настроек восстановления.
. (gap40) Разделитель 40 — Разделитель в списке настроек.
1 Partial Closing (partial_closing) Частичное закрытие — Количество ордеров для начала закрытия последней и первой сделки сетки.
(number of orders to start closing last + 1st trade of grid) (partial_closing_info) Информация о частичном закрытии — Пояснение к параметру частичного закрытия.
2 Grid Outscaling (grid_outscaling) Аутскалинг сетки — Количество ордеров для начала закрытия первых сделок сетки в убытке.
(number of orders to start closing 1st grid trades in loss) (grid_outscaling_info) Информация об аутскалинге — Пояснение к параметру аутскалинга сетки.
3 Profit Reducing (profit_reducing) Снижение профита — Снижение тейк-профита в пунктах за каждый ордер сетки до минимума 1 пункт.
(reduces take profit in pips per grid order down to min. 1 pip) (profit_reducing_info) Информация о снижении профита — Пояснение к параметру снижения профита.
4 Cycle Hedging (hedging_active) Хеджирование цикла — Хеджировать весь цикл сетки при достижении максимального количества позиций.
(hedge entire grid cycle, if maximum positions are reached) (hedging_active_info) Информация о хеджировании — Пояснение к параметру хеджирования цикла.
5 Profit Chasing (profit_chasing) Погоня за прибылью — Количество ордеров для погони за максимальной прибылью.
(number of orders to chase maximum profit) (profit_chasing_info) Информация о погоне за прибылью — Пояснение к параметру погони за прибылью.
. (gap41) Разделитель 41 — Разделитель в списке настроек.
======> B A S I C I N D I C A T O R S <====== (Indicators_Settings) Настройки индикаторов — Раздел настроек базовых индикаторов.
. (gap50) Разделитель 50 — Разделитель в списке настроек.
Combine Signals (use all indicators together) (Conjunct_Idx) Объединять сигналы — Использовать все индикаторы совместно для формирования сигнала.
Open Both Cycles (buy+sell in both directions) (both_cycle) Оба цикла — Открывать оба цикла (покупка и продажа в обоих направлениях).
Strict Signals (open next grid orders only on signal) (strict_signals) Строгие сигналы — Открывать следующие ордера сетки только по сигналу.
One Candle Limit (only one grid order per candle) (one_candle_limit) Один ордер на свечу — Ограничение: только один ордер сетки на свечу.
. (gap51) Разделитель 51 — Разделитель в списке настроек.
Bollinger Bands (BB) ************ (Bollinger_Bands) Полосы Боллинджера — Раздел настроек полос Боллинджера.
Use BB signals? (Use_BB) Использовать BB — Использовать сигналы полос Боллинджера.
Invert trigger (follow trend)? (BB_invert) Инверсия BB — Инвертировать сигнал полос Боллинджера.
Time frame (BB_tf) Таймфрейм BB — Таймфрейм для полос Боллинджера.
Period (BB_Period) Период BB — Период полос Боллинджера.
Deviation (set to "0.01" for moving average) (BB_Dev) Отклонение BB — Отклонение для полос Боллинджера.
Price method (ask/bid, high/low) (BB_Mod) Метод цены BB — Метод цены для полос Боллинджера.
Shift (BB_Shift) Сдвиг BB — Сдвиг полос Боллинджера.
. (gap52) Разделитель 52 — Разделитель в списке настроек.
Stochastic Oscillator (STO) ************ (Stochastic_Oscillator) Стохастический осциллятор — Раздел настроек стохастического осциллятора.
Use STO signals? (Use_Stoch) Использовать STO — Использовать сигналы стохастика.
Invert trigger (follow trend)? (STO_invert) Инверсия STO — Инвертировать сигнал стохастика.
Time frame (Stoch_tf) Таймфрейм STO — Таймфрейм для стохастика.
Period %K line (Stoch_K) Период %K — Период линии %K стохастика.
Period %D line (Stoch_D) Период %D — Период линии %D стохастика.
Slowing value (Stoch_Slowing) Замедление STO — Значение замедления стохастика.
MA method (Stoch_Method) Метод MA STO — Метод сглаживания для стохастика.
Price method (low/high, close/close) (Stoch_Price) Метод цены STO — Метод цены для стохастика.
Upper level (Stoch_Upper) Верхний уровень STO — Верхний уровень стохастика.
Lower level (Stoch_Lower) Нижний уровень STO — Нижний уровень стохастика.
Shift (Stoch_Shift) Сдвиг STO — Сдвиг стохастика.
. (gap53) Разделитель 53 — Разделитель в списке настроек.
Relative Strength Index (RSI) ************ (Relative_Strength_Index) Индекс относительной силы — Раздел настроек индикатора RSI.
Use RSI signals? (Use_RSI) Использовать RSI — Использовать сигналы RSI.
Invert trigger (follow trend)? (RSI_invert) Инверсия RSI — Инвертировать сигнал RSI.
Time trame (RSI_tf) Таймфрейм RSI — Таймфрейм для RSI.
Period (RSI_Period) Период RSI — Период RSI.
Upper level (RSI_Upper) Верхний уровень RSI — Верхний уровень RSI.
Lower level (RSI_Lower) Нижний уровень RSI — Нижний уровень RSI.
Shift (RSI_Shift) Сдвиг RSI — Сдвиг RSI.
. (gap54) Разделитель 54 — Разделитель в списке настроек.
Commodity Channel Index (CCI) ************ (Commodity_Channel_Index) Индекс товарного канала — Раздел настроек индикатора CCI.
Use CCI signals? (Use_CCI) Использовать CCI — Использовать сигналы CCI.
Invert trigger (follow trend)? (CCI_invert) Инверсия CCI — Инвертировать сигнал CCI.
Получить полный код

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

#define max_open_positions 100      // maximum number of open positions
#define max_auto_open_positions 90  // maximum number of automatic open positions (10 positions for hedge trading)
#define EMPTY_VALUE 2147483647

#include <stdlib.mqh>
#include <stderror.mqh>

#define versionNo "2.7"
#define versionBMI "**************** v" + versionNo
#define versionOld "based on Super Money and Ikarus Grid EAs"

#property version versionNo
#property strict

#property description   "based on Super Money and Ikarus Grid EAs"

string key = "***** *** ******";
string key_hedging = "Reverse";

enum BB_options {ASK_BID, HIGH_LOW};
enum STO_options {LOW_HIGH, CLOSE_CLOSE};
enum weekdays {SUN, MON, TUE, WED, THU, FRI, SAT};

enum ENUM_INDICATOR_TYPE {
    Empty_Indicator = 1,
    Value_Indicator,
    Price_Indicator,
    Cross_Indicator};

int user_slippage = 2;

sinput string gap00; // .
input string Strategy = "FLEXY THE DRAGON v2.7";   // Name of Strategy
input string Description = "keep calm. play safe. get rich. :)"; // Description
extern color clrStrategy         = clrSlateGray;   // color of description
extern int magic = 0;                              // Magic Number (0 = automatic)
sinput string gap01; // .
input bool show_profit           = true;           // Show Profit/Loss Info?
input bool show_forecast         = true;           // Show Trading Info?
input bool show_settings         = false;          // Show Settings Info?
input bool show_indicators       = false;          // Show Indicators Info?
sinput string show_info;                           // (set all to "false" for fastest backtest)
sinput string gap10; // .
sinput string Order_Settings;                      // ======>  O R D E R   S E T T I N G S  <======
sinput string gap11; // .
extern double min_lots          = 0.01;            // Base Lot Size (for first order)
extern int progression          = 2;               // Lot Progression (0=fixed 1=sum 2=marti 3=fibo)
extern double lot_multiplicator = 1.5;             // Lot Multiplier (only for martingale)
input bool use_autolot          = false;           // Use Auto Lot Size? (calculated by auto lot Balance)
extern int AutoLotBalance       = 5000;            // Auto Lot Balance (multiplied by base lot size)
sinput string gap13; // .
extern int max_spread           = 100;             // Max. Spread (to open orders, in pts)
sinput string gap14; // .
sinput string Grid_Settings;                       // ======>  G R I D   S E T T I N G S  <======
sinput string gap20; // .
extern int max_positions       = 10;               // Max. Positions (per grid cycle)
extern int gs_progression      = 2;                // Grid Progression (0=fixed 1=sum 2=marti 3=fibo)
extern double gs_multiplicator = 1.0;              // Grid Multiplier (only for 2=martingale)
sinput string gap21; // .
extern double grid_size        = 40.0;             // Fixed Grid Step (in pips)
extern double take_profit      = 20.0;             // Fixed Take Profit (in pips)
sinput string gap22; // .
extern bool Use_ATR            = false;            // Use Dynamic Grid? (based on ATR)
extern ENUM_TIMEFRAMES ATR_tf  = PERIOD_CURRENT;   // ATR Time Frame
extern int ATR_Period          = 20;               // ATR Period
extern double ATR_Multiplier   = 2.0;              // Dynamic Grid Step (ATR ratio)
extern double TP_Multiplier    = 1.0;              // Dynamic Take Proft (ATR ratio)
sinput string gap23; // .
sinput string Risk_Settings;                       // ======>  R I S K   S E T T I N G S  <======
sinput string gap30; // .
extern double profit_lock        = 1.0;            // #1 Profit Lock / Trail Stop
sinput string profit_info;                         // (must be used!, locks in profit, 1.0 = 100%)
extern double equity_warning     = 0.7;            // #2 Equity Warning / Yoga Mode 
sinput string equity_info;                         // (stop open orders on low equity, 0.7 = 70%)
extern double cycleEquityRisk    = 0.0;            // #3 Cycle Risk / Stop Loss
sinput string cycleEquityRisk_info;                // (close orders of one grid cycle, 0.01 = 1%)
extern double account_risk       = 0.9;            // #4 Shut Down / Account Risk
sinput string account_risk2;                       // (close all orders and turn off, 0.9 = 90%)
sinput string gap31; // .
sinput string Recovery_Settings;                   // ======>  R E C O V E R Y   S E T T I N G S  <======
sinput string gap40; // .
extern int partial_closing       = 5;              // #1 Partial Closing
sinput string partial_closing_info;                // (number of orders to start closing last + 1st trade of grid)
extern int grid_outscaling       = 0;              // #2 Grid Outscaling
sinput string grid_outscaling_info;                // (number of orders to start closing 1st grid trades in loss)
extern double profit_reducing    = 0.0;            // #3 Profit Reducing
sinput string profit_reducing_info;                // (reduces take profit in pips per grid order down to min. 1 pip)
extern bool hedging_active       = false;          // #4 Cycle Hedging
sinput string hedging_active_info;                 // (hedge entire grid cycle, if maximum positions are reached)
extern int profit_chasing        = 0;              // #5 Profit Chasing
sinput string profit_chasing_info;                 // (number of orders to chase maximum profit)
sinput string gap41; // .
sinput string Indicators_Settings;                 // ======>  B A S I C   I N D I C A T O R S  <======
sinput string gap50; // .
extern bool Conjunct_Idx         = true;           // Combine Signals (use all indicators together)
extern bool both_cycle           = false;          // Open Both Cycles (buy+sell in both directions)
extern bool strict_signals       = false;          // Strict Signals (open next grid orders only on signal)
extern bool one_candle_limit     = true;           // One Candle Limit (only one grid order per candle)
sinput string gap51; // .
sinput string Bollinger_Bands;                     // ************  Bollinger Bands (BB)  ************
extern bool Use_BB               = false;          // Use BB signals?
extern bool BB_invert            = false;          // Invert trigger (follow trend)?
extern ENUM_TIMEFRAMES BB_tf     = PERIOD_CURRENT; // Time frame
extern int BB_Period     = 20;                     // Period
extern double BB_Dev     = 2.0;                    // Deviation (set to "0.01" for moving average)
extern BB_options BB_Mod = ASK_BID;                // Price method (ask/bid, high/low)
extern int BB_Shift      = 0;                      // Shift
sinput string gap52; // .
sinput string Stochastic_Oscillator;               // ************  Stochastic Oscillator (STO)  ************
extern bool Use_Stoch    = false;                  // Use STO signals?
extern bool STO_invert   = false;                  // Invert trigger (follow trend)?
extern ENUM_TIMEFRAMES Stoch_tf = PERIOD_CURRENT;  // Time frame
extern int Stoch_K       = 14;                     // Period %K line
extern int Stoch_D       = 1;                      // Period %D line
extern int Stoch_Slowing = 3;                      // Slowing value
extern ENUM_MA_METHOD Stoch_Method = MODE_SMA;     // MA method
extern ENUM_STO_PRICE Stoch_Price = STO_LOWHIGH;   // Price method (low/high, close/close)
extern double Stoch_Upper = 80;                    // Upper level
extern double Stoch_Lower = 20;                    // Lower level
extern int Stoch_Shift    = 0;                     // Shift
sinput string gap53; // .
sinput string Relative_Strength_Index;             // ************  Relative Strength Index (RSI)  ************
extern bool Use_RSI      = false;                  // Use RSI signals?
extern bool RSI_invert   = false;                  // Invert trigger (follow trend)?
extern ENUM_TIMEFRAMES RSI_tf = PERIOD_CURRENT;    // Time trame
extern int RSI_Period    = 14;                     // Period
extern double RSI_Upper  = 80;                     // Upper level
extern double RSI_Lower  = 20;                     // Lower level
extern int RSI_Shift     = 0;                      // Shift
sinput string gap54; // .
sinput string Commodity_Channel_Index;             // ************  Commodity Channel Index (CCI)  ************
extern bool Use_CCI      = false;                  // Use CCI signals?
extern bool CCI_invert   = false;                  // Invert trigger (follow trend)?
extern ENUM_TIMEFRAMES CCI_tf = PERIOD_CURRENT;    // Time frame
extern int CCI_Period    = 14;                     // Period
extern double CCI_Upper  = 200;                    // Upper level
extern double CCI_Lower  = -200;                   // Lower level
extern int CCI_Shift     = 0;                      // Shift
sinput string gap55; // .
sinput string Custom_Indicators;                        // ======>  C U S T O M   I N D I C A T O R S  <======
sinput string gap60; // .
sinput string C1;                                       // ************  Custom Indicator 1  ************
extern bool Use_C1           = false;                   // Use Custom Indicator?
input string C1_Name         = "";                      // Indicator Name (in indicator folder)
input ENUM_INDICATOR_TYPE C1_Type = Empty_Indicator;    // Indicator Type (see below info) 
input int C1_BuyBuffer       = 0;                       // Buy buffer number (usually "0")
input int C1_SellBuffer      = 1;                       // Sell buffer number (usually "1")
input double C1_BuyValue     = 1.0;                     // Buy value* (only for value type)
input double C1_SellValue    = 1.0;                     // Sell value* (only for value type)
extern bool C1_Invert        = true;                    // Follow signal? (inverts trigger)
extern bool C1_Wait          = true;                    // Wait for closed bar? (use previous bar)
extern bool C1_Exit          = false;                   // Exit other open orders? (experimental)
sinput string gap61; // .
sinput string C2;                                       // ************  Custom Indicator 2  ************
extern bool Use_C2           = false;                   // Use Custom Indicator?
input string C2_Name         = "";                      // Indicator Name (in indicator folder)
input ENUM_INDICATOR_TYPE C2_Type = Empty_Indicator;    // Indicator Type (see below info) 
input int C2_BuyBuffer       = 0;                       // Buy buffer number (usually "0")
input int C2_SellBuffer      = 1;                       // Sell buffer number (usually "1")
input double C2_BuyValue     = 1.0;                     // Buy value* (only for value type)
input double C2_SellValue    = 1.0;                     // Sell value* (only for value type)
extern bool C2_Invert        = true;                    // Follow signal? (inverts trigger)
extern bool C2_Wait          = true;                    // Wait for closed bar? (use previous bar)
extern bool C2_Exit          = false;                   // Exit other open orders? (experimental)
sinput string gap62; // .
sinput string C3;                                       // ************  Custom Indicator 3  ************
extern bool Use_C3           = false;                   // Use Custom Indicator?
input string C3_Name         = "";                      // Indicator Name (in indicator folder)
input ENUM_INDICATOR_TYPE C3_Type = Empty_Indicator;    // Indicator Type (see below info) 
input int C3_BuyBuffer       = 0;                       // Buy buffer number (usually "0")
input int C3_SellBuffer      = 1;                       // Sell buffer number (usually "1")
input double C3_BuyValue     = 1.0;                     // Buy value* (only for value type)
input double C3_SellValue    = 1.0;                     // Sell value* (only for value type)
extern bool C3_Invert        = true;                    // Follow signal? (inverts trigger)
extern bool C3_Wait          = true;                    // Wait for closed bar? (use previous bar)
extern bool C3_Exit          = false;                   // Exit other open orders? (experimental)
sinput string Type_Info0; // .
sinput string Type_Info1;                               // 1. Type in indicator name "folder/ExampleRSI" without ".ex4" 
sinput string Type_Info2;                               // 2. Find and type in the number of the buffer from the colors 
sinput string Type_Info3;                               //    tab of the indi or by pressing CTRL+D to show the values
sinput string Type_Info4;                               // 3. Select the Indicator Type:
sinput string Type_Info5;                               // a) Empty Type: triggers signal if [buffer] is "not empty" - for arrows
sinput string Type_Info6;                               // b) Value Type: if [buffer] is </> than [buy/sell value]* - for oscillators
sinput string Type_Info7;                               // c) Price Type: if [price] is </> than [buffer] - for MAs or lines
sinput string Type_Info8;                               // d) Cross Type: if [price] crosses [buffer] up/down - for MAs or lines
sinput string gap63; // .
sinput string Time_Settings;                       // ======>  W O R K I N G   T I M E S  <======
sinput string gap70; // .
extern bool Restricted_Working_Time = false;       // Use Working Times?
extern weekdays StartDay = MON;                    // Weekday Start (select)
extern weekdays StopDay = FRI;                     // Weekday Stop (select)
extern int StartHour = 8;                          // Hour Start (0-24)
extern int StartMin = 0;                           // Minute Start (0-59)
extern int StartSec = 0;                           // Second Start (0-59)
extern int StopHour = 16;                          // Hour Stop (0-24)
extern int StopMin  = 0;                           // Minute Stop (0-59)
extern int StopSec  = 0;                           // Second Stop (0-59)
sinput string gap71; // .
sinput string Visual_Settings;                     // ======>  V I S U A L   S E T T I N G S  <======
sinput string gap80; // .
sinput string buy_sell_lines;                      // ************  Display Next Buy/Sell Lines  ************
extern color Color_NXT_Buy    = clrDodgerBlue;     // Next buy line color
extern color Color_NXT_Sell   = clrCrimson;        // Next sell line color
extern int Style_NX           = 3;                 // Next line type (0,1,2,3,4)
extern int Width_NX           = 0;                 // Next line width (0,1,2,3,4)
sinput string gap81; // .
sinput string delimeter_01;                        // ************  Display Take Profit Lines  ************
extern color Color_TP_Buy     = clrDodgerBlue;     // Buy TP line color
extern color Color_TP_Sell    = clrCrimson;        // Sell TP line color
extern int Style_TP           = 0;                 // TP lines type (0,1,2,3,4)
extern int Width_TP           = 2;                 // TP lines width (0,1,2,3,4)
sinput string gap82; // .
sinput string profit_lock_lines;                   // ************  Display Profit Lock Lines  ************
extern bool displayPLL          = true;            // Display profit lock lines?
extern color Color_PL_Buy       = clrGold;         // Lock line buy color
extern color Color_PL_Sell      = clrGold;         // Lock line sell color
extern int Style_PL             = 1;               // Lock line type (0,1,2,3,4)
extern int Width_PL             = 0;               // Lock line width (0,1,2,3,4)
sinput string gap83; // .
sinput string closed_profits;                      // ************  Display Profit Labels  ************
input bool display_CP         = true;              // Display profit labels?
input string Font_Fam_CP = "Roboto Condensed Bold";// Font family (install on PC)
input int Font_Size_CP        = 10;                // Font size
input int move_CP             = -100;              // Position (in pts, from closed price)
input color Color_CP_Pos      = clrSpringGreen;    // Positive color
input color Color_CP_Neg      = clrOrangeRed;      // Negative color
sinput string gap84; // .
sinput string breakeven_boxes;                     // ************  Display Breakeven Prices  ************
extern bool displayBE         = false;             // Display single BE price box?
extern color Color_BE         = clrOrchid;         // BE price box color
extern bool displayBES        = true;              // Display separate BE price boxes? 
extern color Color_BE_Buy     = clrDodgerBlue;     // BE price box buy color
extern color Color_BE_Sell    = clrCrimson;        // BE price box sell color
sinput string gap85; // .
extern int loginfo = 1;                            // Send Log Information

static int totalOpenBuys =  0;
static int totalOpenSells =  0;

int lastCandleIndex =  0;

bool buy_chased = false, sell_chased = false;
int buy_tickets[max_open_positions];
int sell_tickets[max_open_positions];

double buy_lots[max_open_positions];
double sell_lots[max_open_positions];

double buy_profit[max_open_positions];
double sell_profit[max_open_positions];

double buy_price[max_open_positions];
double sell_price[max_open_positions];

int hedge_buy_tickets[max_open_positions];
int hedge_sell_tickets[max_open_positions];

double hedge_buy_lots[max_open_positions];
double hedge_sell_lots[max_open_positions];

double hedge_buy_profit[max_open_positions];
double hedge_sell_profit[max_open_positions];

double hedge_buy_price[max_open_positions];
double hedge_sell_price[max_open_positions];

int hedge_magic = 0;
bool is_sell_hedging_active = false, is_buy_hedging_active = false;
bool is_sell_hedging_order_active = false, is_buy_hedging_order_active = false;

int buys = 0, sells = 0, hedge_buys = 0, hedge_sells = 0;

double line_buy = 0, line_sell = 0, line_buy_tmp = 0, line_sell_tmp = 0, line_buy_next = 0;
double line_sell_next = 0, line_buy_ts = 0, line_sell_ts = 0, line_margincall = 0;

double total_buy_profit = 0, total_sell_profit = 0, total_buy_swap = 0, total_sell_swap = 0;
double total_hedge_buy_profit = 0, total_hedge_sell_profit = 0, total_hedge_buy_swap = 0, total_hedge_sell_swap = 0;
double buy_max_profit = 0, buy_close_profit = 0;
double buy_max_hedge_profit = 0, buy_close_hedge_profit = 0;
double sell_max_profit = 0, sell_close_profit = 0;
double sell_max_hedge_profit = 0, sell_close_hedge_profit = 0;
double total_buy_lots = 0, total_sell_lots = 0;
double total_hedge_buy_lots = 0, total_hedge_sell_lots = 0;
double relativeVolume = 0;
double buy_close_profit_trail_orders = 0, sell_close_profit_trail_orders = 0;
bool buy_max_order_lot_open = false, sell_max_order_lot_open = false;

double dLots = 0; // разность объемов ордеров Buy и Sell
double dlots = 0; //убираем погрешность в расчете разности объема ордеров

int colInPlus  = clrSpringGreen;
int colInMinus = clrOrangeRed;
int colNeutral = clrSlateGray;
int colBlue    = clrBlue;
int colBuy     = C'34,81,221';
int colSell    = C'234,21,64';
int colCodeGreen  = C'74,85,96';
int colCodeYellow = clrGold;
int colCodeRed    = clrRed;
int colPauseButtonPassive = C'74,85,96';

int colFontLight  = clrWhite;
int colFontDark   = C'74,85,96';  
int colFontGray   = clrSlateGray;
int colFontWhite  = clrWhite;
int colFontYellow = clrYellow;

int panelCol = colNeutral;         // fore color of neutral panel text
int instrumentCol = colNeutral;    // panel color that changes depending on its value

int slippage = 0;                  // is fix; depending on chart: 2 or 20
int retry_attempts = 10;
double sleep_time = 4.0;           // in seconds
int sleep_maximum = 25;            // in seconds
string OrderReliable_Fname = "OrderReliable fname unset";
static int _OR_err = 0;
string OrderReliableVersion = "V1_1_1";

enum ACCOUNT_STATE {as_green, as_yellow, as_red};
int accountState = as_green;

double max_equity = 0;             // maximum of equity ever reached, saved in global vars
double max_float = 0;              // minimum of equity ever reached, saved in global vars

int stopNextCycle = 0;          // flag, if trading will be terminated after next successful cycle, trades normally until cyle is closed
int restAndRealize = 0;         // flag, if trading will be terminated after next successful cycle, does not open new positions
int stopAll = 0;                // flag, if stopAll must close all and stop trading or continue with trading

int showComment = 1;            // flag for comment at left side
bool isFirstStartLoop = true;   // flag, to do some things only one time after program start

int btnLeftAxis = 220;                          // distance of 1st button from left
int btnTopAxis = 1;                             // distance of all buttons from top
int btnHeight = 23;                             // height of buttons
int btnGap = 2;                                 // gap between buttons
int btnWidth =97;                               // width of small buttons
int btnNextLeft = btnWidth + btnGap;            // distance to next small button
int btnNextTop = btnHeight + btnGap;            // distance of next buttons from top

string debugCommentDyn = "\n";        // will be added to regular Comment txt and updated each program loop
string debugCommentStat = "";         // will be added only - no updates
string debugCommentCloseBuys = "";    // show condition, when cycle will be closed
string debugCommentCloseSells = "";
string codeRedMsg = "";               // tell user, why account state is yellow or red
string codeYellowMsg = "";
double ter_IkarusChannel = 0;         // line_buy - line_sell
string globalVarsID = Symbol() + "_" + (string)magic + "_"; //ID to specify the global vars from other charts

int ter_digits = 0;
double ter_priceBuy = 0;
double ter_priceSell = 0;
double ter_point = 0;
double ter_tick_value = 0;
double ter_tick_size = 0;
double ter_spread = 0;
datetime ter_timeNow = 0;             // date and time while actual loop

double ter_ticksPerGrid = 0;          // ticks of 1 min_lot per 1 grid size
int ter_chartMultiplier = 1;          // if digits = 3 or 5: chart multiplier = 10
string ter_currencySymbol = "$";      // € if account is in Euro, $ for all other

double ter_MODE_MARGINHEDGED = MarketInfo(Symbol(), MODE_MARGINHEDGED);
double ter_MODE_MARGININIT = MarketInfo(Symbol(), MODE_MARGININIT);
double ter_MODE_MARGINMAINTENANCE = MarketInfo(Symbol(), MODE_MARGINMAINTENANCE);
double ter_MODE_MARGINREQUIRED = MarketInfo(Symbol(), MODE_MARGINREQUIRED);

double freemargin = AccountFreeMargin();

double Ur_total_BE = 0;
double Ur_BE_buy = 0;
double Ur_BE_sell = 0;

double ATR_Buy = 0;
double ATR_Sell = 0;

datetime current_candle_open;
int current_tick;

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

void OnDeinit(const int reason)
{

   DeleteButton("btnStopAll");
   DeleteButton("btnrestAndRealize");
   DeleteButton("btnstopNextCycle");

   DeleteButton("btnhedgeBuy");
   DeleteButton("btnhedgeSell");
   DeleteButton("btnCloseLastBuy");
   DeleteButton("btnCloseLastSell");
   DeleteButton("btnCloseAllBuys");
   DeleteButton("btnCloseAllSells");

   if(ObjectFind("BE_buy") != -1)
      ObjectDelete("BE_buy");
   if(ObjectFind("BE_sell") != -1)
      ObjectDelete("BE_sell");
   if(ObjectFind("BE_total") != -1)
      ObjectDelete("BE_total");
}

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

void robot()
  {
   int ticket = - 1;
   bool closed = FALSE;

   double local_total_buy_profit = 0, local_total_sell_profit = 0;

   if(((100 - (100 * account_risk)) / 100)*AccountBalance() > AccountEquity())
     {

      stopAll = 1;

     }

   local_total_buy_profit = total_buy_profit;
   local_total_sell_profit = total_sell_profit;

   if(hedge_buys > 0)
     {

      local_total_sell_profit = total_sell_profit + total_hedge_buy_profit;
     }

   if(hedge_sells > 0)
     {

      local_total_buy_profit = total_buy_profit + total_hedge_sell_profit;
     }

   if(buys == 0 && Time_to_Trade())
     {

      if(Use_ATR)
        {
         grid_size = ATR_Grid_Size();
         take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
        }

      if(Use_BB || Use_Stoch || Use_RSI || Use_CCI || Use_C1 || Use_C2 || Use_C3)
        {
         if(!stopNextCycle && !restAndRealize && Indicators_Buy())
           {
            ticket = OrderSendReliable(Symbol(), OP_BUY, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
            if(sells == 0 && both_cycle)
              {
               ticket = OrderSendReliable(Symbol(), OP_SELL, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
              }
           }
        }
      else
        {
         if(!stopNextCycle && !restAndRealize)
           {
            ticket = OrderSendReliable(Symbol(), OP_BUY, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
           }
        }
     }

   if(buys == 1)
     {
      if(Use_ATR)
        {
         grid_size = ATR_Grid_Size();
         take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
        }

      if(!stopNextCycle && !restAndRealize && max_positions > 1)
        {

         if(buy_profit[buys - 1] <= CalculateSL(buy_lots[buys - 1], 1))
           {

            NewGridOrder(OP_BUY, false);
           }
        }

      if(buy_max_profit == 0 && local_total_buy_profit > CalculateTP(buy_lots[0]))
        {
         buy_max_profit = local_total_buy_profit;
         buy_close_profit = profit_lock * buy_max_profit;
        }

      if(buy_max_profit > 0 && local_total_buy_profit > buy_max_profit)
        {
         buy_max_profit = local_total_buy_profit;
         buy_close_profit = profit_lock * local_total_buy_profit;
        }

      if(buy_max_profit > 0 && buy_close_profit > 0
         && buy_max_profit >= buy_close_profit && local_total_buy_profit < buy_close_profit)
        {

         closeAllBuys();
        }
     } // if (buys==1)

   if(buys > 1)
     {
      if(Use_ATR)
        {
         grid_size = ATR_Grid_Size();
         take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
        }

      if(buy_profit[buys - 1] <= CalculateSL(buy_lots[buys - 1], buys))
        {

         if(buys < max_auto_open_positions)
           {
            if(buys < max_positions && !buy_max_order_lot_open)
              {
               NewGridOrder(OP_BUY, false);
              }
           }
        }

      if(buy_max_profit == 0 && progression == 0 && local_total_buy_profit > CalculateTP(buy_lots[0]))
        {
         buy_max_profit = local_total_buy_profit;
         buy_close_profit = profit_lock * buy_max_profit;
         if(!buy_chased && profit_chasing > 0)
           {
            if(buys < max_auto_open_positions && buys < max_positions)
              {
               ticket = OrderSendReliable(Symbol(), OP_BUY, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
              }
            buy_chased = true;
           }
        }
      if(buy_max_profit == 0 && progression == 1 && local_total_buy_profit > buys * CalculateTP(buy_lots[0]))
        {
         buy_max_profit = local_total_buy_profit;
         buy_close_profit = profit_lock * buy_max_profit;
         if(!buy_chased && profit_chasing > 0)
           {
            if(buys < max_auto_open_positions && buys < max_positions)
               ticket = OrderSendReliable(Symbol(), OP_BUY, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
            buy_chased = true;
           }
        }
      if(buy_max_profit == 0 && progression == 2 && local_total_buy_profit > CalculateTP(buy_lots[buys - 1]))
        {
         buy_max_profit = local_total_buy_profit;
         buy_close_profit = profit_lock * buy_max_profit;
         if(!buy_chased && profit_chasing > 0)
           {
            if(buys < max_auto_open_positions && buys < max_positions)
              {
               ticket = OrderSendReliable(Symbol(), OP_BUY, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
              }
            buy_chased = true;
           }
        }
      if(buy_max_profit == 0 && progression == 3 && local_total_buy_profit > CalculateTP(buy_lots[buys - 1]))
        {
         buy_max_profit = local_total_buy_profit;
         buy_close_profit = profit_lock * buy_max_profit;
         if(!buy_chased && profit_chasing > 0)
           {
            if(buys < max_auto_open_positions && buys < max_positions)
              {
               ticket = OrderSendReliable(Symbol(), OP_BUY, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
              }
            buy_chased = true;
           }
        }

      if(buy_max_profit > 0 && local_total_buy_profit > buy_max_profit)
        {
         buy_max_profit = local_total_buy_profit;
         buy_close_profit = profit_lock * local_total_buy_profit;
        }

      if(buy_max_profit > 0 && buy_close_profit > 0 && buy_max_profit >= buy_close_profit
         && local_total_buy_profit < buy_close_profit)
        {

         closeAllBuys();
        }
     } // if (buys>1)

   debugCommentCloseBuys
      = "\nbuys will be closed if:\n" +
        "    - buy max profit: " + DoubleToString(buy_max_profit, 2) + " > buy close profit: " + DoubleToString(buy_close_profit, 2) + "     AND \n" +
        "    - total buy profit: " + DoubleToString(local_total_buy_profit, 2) + " < buy close profit: " + DoubleToString(buy_close_profit, 2) + "\n";

   if(sells == 0 && Time_to_Trade())
     {

      if(Use_ATR)
        {
         grid_size = ATR_Grid_Size();
         take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier;
        }

      if(Use_BB || Use_Stoch || Use_RSI || Use_CCI || Use_C1 || Use_C2 || Use_C3)
        {
         if(!stopNextCycle && !restAndRealize && Indicators_Sell())
           {
            ticket = OrderSendReliable(Symbol(), OP_SELL, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
            if(buys == 0 && both_cycle)
              {
               ticket = OrderSendReliable(Symbol(), OP_BUY, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
              }
           }
        }
      else
        {
         if(!stopNextCycle && !restAndRealize)
           {
            ticket = OrderSendReliable(Symbol(), OP_SELL, CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
           }
        }
     }

   if(sells == 1)
     {
      if(Use_ATR)
        {
         grid_size = ATR_Grid_Size();
         take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
        }

      if(!stopNextCycle && !restAndRealize && max_positions > 1)
        {
         if(sell_profit[sells - 1] <= CalculateSL(sell_lots[sells - 1], 1))
           {

            NewGridOrder(OP_SELL, false);
           }
        }

      if(sell_max_profit == 0 && local_total_sell_profit > CalculateTP(sell_lots[0]))
        {
         sell_max_profit = local_total_sell_profit;
         sell_close_profit = profit_lock * sell_max_profit;
        }

      if(sell_max_profit > 0 && local_total_sell_profit > sell_max_profit)
        {
         sell_max_profit = local_total_sell_profit;
         sell_close_profit = profit_lock * local_total_sell_profit;
        }

      if(sell_max_profit > 0 && sell_close_profit > 0
         && sell_max_profit >= sell_close_profit && local_total_sell_profit < sell_close_profit)
        {

         closeAllSells();
        }
     } // if (sells==1)

   if(sells > 1)
     {
      if(Use_ATR)
        {
         grid_size = ATR_Grid_Size();
         take_profit = TP_Multiplier * ATR_Grid_Size() / ATR_Multiplier; // maybe fixed take profit better?
        }

      if(sell_profit[sells - 1] <= CalculateSL(sell_lots[sells - 1], sells))
        {

         if(sells < max_auto_open_positions)
           {
            if(sells < max_positions && !sell_max_order_lot_open)
              {
               NewGridOrder(OP_SELL, false);
              }
           }
        }

      if(sell_max_profit == 0 && progression == 0 && local_total_sell_profit > CalculateTP(sell_lots[0]))
        {
         sell_max_profit = local_total_sell_profit;
         sell_close_profit = profit_lock * sell_max_profit;
         if(!sell_chased && profit_chasing > 0)
           {
            if(buys < max_auto_open_positions && buys < max_positions)
              {
               ticket = OrderSendReliable(Symbol(), OP_SELL, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
              }
            sell_chased = true;
           }
        }
      if(sell_max_profit == 0 && progression == 1 && local_total_sell_profit > sells * CalculateTP(sell_lots[0]))
        {
         sell_max_profit = local_total_sell_profit;
         sell_close_profit = profit_lock * sell_max_profit;
         if(!sell_chased && profit_chasing > 0)
           {
            if(buys < max_auto_open_positions && buys < max_positions)
              {
               ticket = OrderSendReliable(Symbol(), OP_SELL, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
              }
            sell_chased = true;
           }
        }
      if(sell_max_profit == 0 && progression == 2 && local_total_sell_profit > CalculateTP(sell_lots[sells - 1]))
        {
         sell_max_profit = local_total_sell_profit;
         sell_close_profit = profit_lock * sell_max_profit;
         if(!sell_chased && profit_chasing > 0)
           {
            if(buys < max_auto_open_positions && buys < max_positions)
              {
               ticket = OrderSendReliable(Symbol(), OP_SELL, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
              }
            sell_chased = true;
           }
        }
      if(sell_max_profit == 0 && progression == 3 && local_total_sell_profit > CalculateTP(sell_lots[sells - 1]))
        {
         sell_max_profit = local_total_sell_profit;
         sell_close_profit = profit_lock * sell_max_profit;
         if(!sell_chased && profit_chasing > 0)
           {
            if(buys < max_auto_open_positions && buys < max_positions)
              {
               ticket = OrderSendReliable(Symbol(), OP_SELL, profit_chasing * CalculateStartingVolume(), MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
              }
            sell_chased = true;
           }
        }

      if(sell_max_profit > 0 && local_total_sell_profit > sell_max_profit)
        {
         sell_max_profit = local_total_sell_profit;
         sell_close_profit = profit_lock * sell_max_profit;
        }

      if(sell_max_profit > 0 && sell_close_profit > 0
         && sell_max_profit >= sell_close_profit && local_total_sell_profit < sell_close_profit)
        {

         closeAllSells();
        }
     } // if (sells>1)

   debugCommentCloseSells = "\nsells will be closed if:\n" +
                            "    - sell max profit: " + DoubleToString(sell_max_profit, 2) + " > sell close profit: " + DoubleToString(sell_close_profit, 2) + " AND \n" +
                            "    - total sell profit: " + DoubleToString(local_total_sell_profit, 2) + " < sell close profit: " + DoubleToString(sell_close_profit, 2);

   WriteIniData();
  }

void checkAccountState()
  {
   accountState = as_green;   // init state
   codeYellowMsg = "";        // #038: give user info, why account state is yellow or red
   codeRedMsg = "";
   double myPercentage = 0;

   if(buys >= max_positions)
      accountState = as_yellow;
   if(sells >= max_positions)
      accountState = as_yellow;
   if(accountState == as_yellow)
      codeYellowMsg = "Code YELLOW: Max positions reached";

   if(CalculateNextMargin() > AccountFreeMargin())
     {
      accountState = as_red;
      codeRedMsg = "Code RED: Next M. " + DoubleToString(CalculateNextMargin(), 2) + " > Free M. " + DoubleToString(AccountFreeMargin(), 2);
     }

   if((100 - (100 * equity_warning)) / 100 * max_equity > AccountEquity())
     {
      accountState = as_red;
      if(codeRedMsg == "")
        {
         codeRedMsg = "Code RED: Equ. " + DoubleToStr(AccountEquity(), 2) + " < " + DoubleToStr((100 * equity_warning), 0) + "% of max. equ. " + DoubleToStr(max_equity, 2);
        }
      else
        {
         codeRedMsg += "\nand\nEqu. " + DoubleToStr(AccountEquity(), 2) + " < " + DoubleToStr((100 * equity_warning), 0) + "% of max. equ. " + DoubleToStr(max_equity, 2);
        }
     }

   switch(accountState)
     {
      case as_yellow:
         SetButtonColor("btnhedgeBuy", colCodeYellow, colFontDark);
         SetButtonColor("btnhedgeSell", colCodeYellow, colFontDark);
         SetButtonColor("btnCloseLastBuy", colCodeYellow, colFontDark);
         SetButtonColor("btnCloseLastSell", colCodeYellow, colFontDark);
         SetButtonColor("btnCloseAllBuys", colCodeYellow, colFontDark);
         SetButtonColor("btnCloseAllSells", colCodeYellow, colFontDark);
         SetButtonColor("btnShowComment", colCodeYellow, colFontDark);
         break;
      case as_red:
         SetButtonColor("btnhedgeBuy", colCodeRed, colFontLight);
         SetButtonColor("btnhedgeSell", colCodeRed, colFontLight);
         SetButtonColor("btnCloseLastBuy", colCodeRed, colFontLight);
         SetButtonColor("btnCloseLastSell", colCodeRed, colFontLight);
         SetButtonColor("btnCloseAllBuys", colCodeRed, colFontLight);
         SetButtonColor("btnCloseAllSells", colCodeRed, colFontLight);
         SetButtonColor("btnShowComment", colCodeRed, colFontLight);
         break;
      default:
         SetButtonColor("btnhedgeBuy", colBuy, colFontLight);
         SetButtonColor("btnhedgeSell", colSell, colFontLight);
         SetButtonColor("btnCloseLastBuy", colBuy, colFontLight);
         SetButtonColor("btnCloseLastSell", colSell, colFontLight);
         SetButtonColor("btnCloseAllBuys", colBuy, colFontLight);
         SetButtonColor("btnCloseAllSells", colSell, colFontLight);
         SetButtonColor("btnShowComment", colNeutral, colFontLight);
         break;
     }

   return;
  }

double calculateVolume(int positions)
{
   double factor = 0.0;  // Modified to allow for decimal precision
   int i = 0;

   if(positions == 0)
      return(min_lots);

   switch(gs_progression)
   {
      case 0:
         factor = 1.0;  // Modified to include decimal places
         break;
      case 1:
         factor = positions;
         break;
      case 2:
         for(i = 1, factor = 1.0; i < positions; i++)
            factor = factor * gs_multiplicator;
         break;
      case 3:
         factor = CalculateFibonacci(positions);
         break;
   }

   return(factor * min_lots);
}

double CalculateNextVolume(int orderType)
  {
   if(orderType == OP_BUY && buys == 0)
      return(min_lots);
   if(orderType == OP_SELL && sells == 0)
      return(min_lots);

   switch(progression)
     {
      case 0:
         return(min_lots);
         break;
      case 1:
         if(orderType == OP_BUY)
           {
            return(buy_lots[buys - 1] + buy_lots[0]);
           }
         else
           {
            return(sell_lots[sells - 1] + sell_lots[0]);
           }
         break;
      case 2:
         if(orderType == OP_BUY)
           {
            return (NormalizeDouble(min_lots * MathPow(lot_multiplicator, buys),2));            //(lot_multiplicator * buy_lots[buys - 1]);
           }
         else
           {
            return (NormalizeDouble(min_lots * MathPow(lot_multiplicator, sells),2));           //(lot_multiplicator * sell_lots[sells - 1]);
           }
         break;
      case 3:
         if(orderType == OP_BUY)
           {
            return(CalculateFibonacci(buys + 1) * buy_lots[0]);
           }
         else
           {
            return(CalculateFibonacci(sells + 1) * sell_lots[0]);
           }
         break;
     }

   return(min_lots);
  }

double CalculateNextMargin()
  {
   double leverage = 100 / AccountLeverage();

   if(buys + sells == 0)
      return(min_lots * leverage * ter_MODE_MARGINREQUIRED);
   if(buys > sells)
     {
      return(CalculateNextVolume(OP_BUY) * leverage  * ter_MODE_MARGINREQUIRED);
     }
   else
     {
      return(CalculateNextVolume(OP_SELL) * leverage * ter_MODE_MARGINREQUIRED);
     }
  }

double CalculateStartingVolume()
{
   double volume;
   if(use_autolot)
   {

      volume = AccountBalance() * min_lots / AutoLotBalance;
   }
   else
   {

      volume = min_lots;
   }
   return (volume);

   if(volume > MarketInfo(Symbol(), MODE_MAXLOT))
     {
      volume = MarketInfo(Symbol(), MODE_MAXLOT);
     }

   if(volume < MarketInfo(Symbol(), MODE_MINLOT))
     {
      volume = MarketInfo(Symbol(), MODE_MINLOT);
     }
   return(volume);
  }

double calculateTicksByPrice(double volume, double price)
  {
   if(volume == 0)
      return(0);
   return(price * ter_tick_size / ter_tick_value / volume);
  }

double CalculatePriceByTickDiff(double volume, double diff)
  {
   return(ter_tick_value * volume * diff / ter_tick_size);
  }

double CalculatePipValue(double volume)
  {
   double aux_mm_value = 0;

   double aux_mm_tick_value = ter_tick_value;
   double aux_mm_tick_size = ter_tick_size;
   int aux_mm_digits = ter_digits;
   double aux_mm_veces_lots;

   if(volume != 0)
     {
      aux_mm_veces_lots = 1 / volume;
      if(aux_mm_digits == 5 || aux_mm_digits == 3)
        {
         aux_mm_value = aux_mm_tick_value * 10;
        }
      else
         if(aux_mm_digits == 4 || aux_mm_digits == 2)
           {
            aux_mm_value = aux_mm_tick_value;
           }
      aux_mm_value = aux_mm_value / aux_mm_veces_lots;
     }

   return(aux_mm_value);
  }

double CalculateTP(double volume)
  {
   double aux_take_profit;

   double reducedTakeProfitBuys = take_profit - buys * profit_reducing;
   double reducedTakeProfitSells = take_profit - sells * profit_reducing;

   double aux_tp_buy = reducedTakeProfitBuys * CalculatePipValue(volume);
   double aux_tp_sell = reducedTakeProfitSells * CalculatePipValue(volume);

   aux_take_profit = MathMin(aux_tp_buy, aux_tp_sell);

   aux_take_profit = MathMax(1, aux_take_profit);

   return(aux_take_profit);
  }

double CalculateSL(double volume, int positions)
  {

   double aux_stop_loss;

   double myVal = calculateVolume(positions) / min_lots;

   aux_stop_loss = - (myVal * grid_size * CalculatePipValue(volume));

   return(aux_stop_loss);
  }

int CalculateFibonacci(int index)
  {
   int val1 = 0;
   int val2 = 1;
   int val3 = 0;

   for(int i = 1; i < index; i++)   // use this for: 1, 1, 2, 3, 5, 8, 13, 21, ...
     {
      val3 = val2;
      val2 = val1 + val2;
      val1 = val3;
     }

   return val2;
  }

void closeAllSells()
  {
   sell_max_profit = 0;
   sell_close_profit = 0;

   if(sells > 0)
     {
      closeAllhedgeBuys();
      for(int i = 0; i <= sells - 1; i++)
        {
         bool retVal = OrderCloseReliable(sell_tickets[i], sell_lots[i], MarketInfo(Symbol(), MODE_ASK), slippage, Red);
        }
      ObjectDelete("TakeProfit_sell");
      ObjectDelete("ProfitLock_sell");
      ObjectDelete("Next_sell");
      ObjectDelete("NewTakeProfit_sell");
      line_sell = 0;
      line_sell_tmp = 0;
      line_sell_next = 0;
      line_sell_ts = 0;
     }
  }

void closeAllBuys()
  {
   buy_max_profit = 0;
   buy_close_profit = 0;

   if(buys > 0)
     {
      closeAllhedgeSells();
      for(int i = 0; i <= buys - 1; i++)
        {
         bool retVal = OrderCloseReliable(buy_tickets[i], buy_lots[i], MarketInfo(Symbol(), MODE_BID), slippage, Blue);
        }
      ObjectDelete("TakeProfit_buy");
      ObjectDelete("ProfitLock_buy");
      ObjectDelete("Next_buy");
      ObjectDelete("NewTakeProfit_buy");
      line_buy = 0;
      line_buy_tmp = 0;
      line_buy_next = 0;
      line_buy_ts = 0;
     }
  }

void closeAllhedgeSells()
  {
   if(hedge_sells > 0)
     {
      for(int i = 0; i <= hedge_sells - 1; i++)
        {
         bool retVal = OrderCloseReliable(hedge_sell_tickets[i], hedge_sell_lots[i], MarketInfo(Symbol(), MODE_ASK), slippage, Red);
        }
     }
  }

void closeAllhedgeBuys()
  {
   if(hedge_buys > 0)
     {
      for(int i = 0; i <= hedge_buys - 1; i++)
        {
         bool retVal = OrderCloseReliable(hedge_buy_tickets[i], hedge_buy_lots[i], MarketInfo(Symbol(), MODE_BID), slippage, Blue);
        }
     }
  }

void closeBuyHedgeAndFirstSellOrder()
  {
   buy_max_hedge_profit = 0;
   buy_close_hedge_profit = 0;

   bool retVal = OrderCloseReliable(sell_tickets[0], sell_lots[0], MarketInfo(Symbol(), MODE_ASK), slippage, Red);
   closeAllhedgeBuys();
  }

void closeBuyHedgeAndLastAndSecondLastSellOrder()
  {

   closeAllhedgeBuys();
   bool retVal = OrderCloseReliable(sell_tickets[sells - 1], sell_lots[sells - 1], MarketInfo(Symbol(), MODE_ASK), slippage, Red);
   bool retVal2 = OrderCloseReliable(sell_tickets[sells - 2], sell_lots[sells - 2], MarketInfo(Symbol(), MODE_ASK), slippage, Red);
  }

void closeSellHedgeAndFirstBuyOrder()
  {
   sell_max_hedge_profit = 0;
   sell_close_hedge_profit = 0;

   bool retVal = OrderCloseReliable(buy_tickets[0], buy_lots[0], MarketInfo(Symbol(), MODE_BID), slippage, Blue);
   closeAllhedgeSells();
  }

void closeSellHedgeAndLastAndSecondLastBuyOrder()
  {

   closeAllhedgeSells();
   bool retVal = OrderCloseReliable(buy_tickets[buys - 1], buy_lots[buys - 1], MarketInfo(Symbol(), MODE_BID), slippage, Blue);
   bool retVal2 = OrderCloseReliable(buy_tickets[buys - 2], buy_lots[buys - 2], MarketInfo(Symbol(), MODE_BID), slippage, Blue);
  }

void closeLastAndFirstBuyOrder()
  {

   bool retVal = OrderCloseReliable(buy_tickets[0], buy_lots[0], MarketInfo(Symbol(), MODE_BID), slippage, Blue);
   bool retVal2 = OrderCloseReliable(buy_tickets[buys - 1], buy_lots[buys - 1], MarketInfo(Symbol(), MODE_BID), slippage, Blue);
  }

void closeLastAndFirstSellOrder()
  {

   bool retVal = OrderCloseReliable(sell_tickets[0], sell_lots[0], MarketInfo(Symbol(), MODE_ASK), slippage, Red);
   bool retVal2 = OrderCloseReliable(sell_tickets[sells - 1], sell_lots[sells - 1], MarketInfo(Symbol(), MODE_ASK), slippage, Red);
  }

void NewGridOrder(int orderType, bool ishedgely)
  {

    if (one_candle_limit && (Bars(_Symbol, _Period) - lastCandleIndex) <  1)
    {
        Print("One candle limit is enabled. Not opening a new order.");
        return;
    }

   if (strict_signals) {
   if (orderType == OP_BUY && !Indicators_Buy()) {
   return;  // No valid buy signal, do not open new buy order
   }
   if (orderType == OP_SELL && !Indicators_Sell()) {
   return;  // No valid sell signal, do not open new sell order
   }}

   int ticket;
   double next_lot = min_lots;

   if(restAndRealize && !ishedgely)
      return;
   if(orderType == OP_BUY)
     {

      if(progression == 0)
         next_lot = min_lots;
      if(progression == 1)
         next_lot = buy_lots[buys - 1] + buy_lots[0];
      if(progression == 2)
         next_lot = (NormalizeDouble(min_lots * MathPow(lot_multiplicator, buys),2));

      if(progression == 3)
         next_lot = CalculateFibonacci(buys + 1) * min_lots;

      ticket = OrderSendReliable(Symbol(), OP_BUY, next_lot, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)buys, magic, 0, Blue);
     }
   else
     {

      if(progression == 0)
         next_lot = min_lots;
      if(progression == 1)
         next_lot = sell_lots[sells - 1] + sell_lots[0];
      if(progression == 2)
         next_lot = (NormalizeDouble(min_lots * MathPow(lot_multiplicator, sells),2));

      if(progression == 3)
         next_lot = CalculateFibonacci(sells + 1) * min_lots;

      ticket = OrderSendReliable(Symbol(), OP_SELL, next_lot, MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)sells, magic, 0, Red);
     }

    lastCandleIndex = Bars(_Symbol, _Period);

  }

void NewGridOrderMaxPos(int orderType)
  {
   int ticket;

   if(restAndRealize)
      return;
   if(orderType == OP_BUY)
     {

      if(progression == 0)
         ticket = OrderSendReliable(Symbol(), OP_BUY, min_lots, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)hedge_buys, magic, 0, Blue);
      if(progression == 1)
         ticket = OrderSendReliable(Symbol(), OP_BUY, max_positions * min_lots, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)hedge_buys, magic, 0, Blue);
      if(progression == 2)
         ticket = OrderSendReliable(Symbol(), OP_BUY, (lot_multiplicator * max_positions) * min_lots, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)hedge_buys, magic, 0, Blue);
      if(progression == 3)
         ticket = OrderSendReliable(Symbol(), OP_BUY, CalculateFibonacci(max_positions) * min_lots, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key + "-" + (string)hedge_buys, magic, 0, Blue);
     }
   else
     {

      if(progression == 0)
         ticket = OrderSendReliable(Symbol(), OP_SELL, buy_lots[0], MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)hedge_sells, magic, 0, Red);
      if(progression == 1)
         ticket = OrderSendReliable(Symbol(), OP_SELL, max_positions * min_lots, MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)hedge_sells, magic, 0, Red);
      if(progression == 2)
         ticket = OrderSendReliable(Symbol(), OP_SELL, (lot_multiplicator * max_positions) * min_lots, MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)hedge_sells, magic, 0, Red);
      if(progression == 3)
         ticket = OrderSendReliable(Symbol(), OP_SELL, CalculateFibonacci(max_positions) * min_lots, MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key + "-" + (string)hedge_sells, magic, 0, Red);
     }
  }

void NewHedgingOrder(int orderType)
  {
   int ticket;

   if(restAndRealize)
      return;
   if(orderType == OP_BUY)
     {

      if(progression == 0)
         ticket = OrderSendReliable(Symbol(), OP_BUY, min_lots, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key_hedging + "-" + (string)hedge_buys, hedge_magic, 0, Blue);
      if(progression == 1)
         ticket = OrderSendReliable(Symbol(), OP_BUY, max_positions * min_lots, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key_hedging + "-" + (string)hedge_buys, hedge_magic, 0, Blue);
      if(progression == 2)
         ticket = OrderSendReliable(Symbol(), OP_BUY, (lot_multiplicator * max_positions) * min_lots, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key_hedging + "-" + (string)hedge_buys, hedge_magic, 0, Blue);
      if(progression == 3)
         ticket = OrderSendReliable(Symbol(), OP_BUY, CalculateFibonacci(max_positions) * min_lots, MarketInfo(Symbol(), MODE_ASK), slippage, 0, 0, key_hedging + "-" + (string)hedge_buys, hedge_magic, 0, Blue);
     }
   else
     {

      if(progression == 0)
         ticket = OrderSendReliable(Symbol(), OP_SELL, min_lots, MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key_hedging + "-" + (string)hedge_sells, hedge_magic, 0, Red);
      if(progression == 1)
         ticket = OrderSendReliable(Symbol(), OP_SELL, max_positions * min_lots, MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key_hedging + "-" + (string)hedge_sells, hedge_magic, 0, Red);
      if(progression == 2)
         ticket = OrderSendReliable(Symbol(), OP_SELL, (lot_multiplicator * max_positions) * min_lots, MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key_hedging + "-" + (string)hedge_sells, hedge_magic, 0, Red);
      if(progression == 3)
         ticket = OrderSendReliable(Symbol(), OP_SELL, CalculateFibonacci(max_positions) * min_lots, MarketInfo(Symbol(), MODE_BID), slippage, 0, 0, key_hedging + "-" + (string)hedge_sells, hedge_magic, 0, Red);
     }
  }

void handleCycleRisk()
  {

   if(cycleEquityRisk > 0)
     {

      double local_total_buy_profit = 0, local_total_sell_profit = 0;

      local_total_buy_profit = total_buy_profit;
      local_total_sell_profit = total_sell_profit;

      if(hedge_buys > 0)
        {

         local_total_sell_profit = total_sell_profit + total_hedge_buy_profit;
        }

      if(hedge_sells > 0)
        {
         local_total_buy_profit = total_buy_profit + total_hedge_sell_profit;
        }

      if((cycleEquityRisk * AccountBalance()) * -1 > local_total_sell_profit)
        {
         closeAllSells();
        }

      if((cycleEquityRisk * AccountBalance()) * -1 > local_total_buy_profit)
        {
         closeAllBuys();
        }
     }
  }

void handleHedging()
  {

   if(hedging_active)   // hedging is active but not open
     {

      if(!isHedgingSellActive() && buys >= max_positions)
        {
         if(buy_profit[buys - 1] <= CalculateSL(buy_lots[buys - 1], buys))
           {
            NewHedgingOrder(OP_SELL);
            NewGridOrderMaxPos(OP_BUY);
           }
        }
      if(!isHedgingBuyActive() && sells >= max_positions)
        {
         if(sell_profit[sells - 1] <= CalculateSL(sell_lots[sells - 1], sells))
           {
            NewHedgingOrder(OP_BUY);
            NewGridOrderMaxPos(OP_SELL);
           }
        }
     }

   if(isHedgingBuyActive())
     {
      if(total_hedge_buy_profit > 0)
        {
         double sum_buy_profit = total_hedge_buy_profit + sell_profit[0]; // hedge - first order
         if(buy_max_hedge_profit == 0 && sum_buy_profit > CalculateTP(min_lots))   // fixed 10%
           {
            buy_max_hedge_profit = sum_buy_profit;
            buy_close_hedge_profit = profit_lock * sum_buy_profit;
           }

         if(buy_max_hedge_profit > 0 && sum_buy_profit > buy_max_hedge_profit)
           {
            buy_max_hedge_profit = sum_buy_profit;
            buy_close_hedge_profit = profit_lock * buy_max_hedge_profit;
           }

         if(buy_max_hedge_profit > 0 && buy_close_hedge_profit > 0
            && buy_max_hedge_profit >= buy_close_hedge_profit && sum_buy_profit < buy_close_hedge_profit)
           {

            closeBuyHedgeAndFirstSellOrder();
           }
        }

if (sells >= 2) {
    if ((sell_profit[sells - 1] + sell_profit[sells - 2]) > 0) {
        double sum_buy_profit = total_hedge_buy_profit + (sell_profit[sells - 1] + sell_profit[sells - 2]);
        if (sum_buy_profit > CalculateTP(min_lots)) {
            closeBuyHedgeAndLastAndSecondLastSellOrder();
        }
    }
}

     }

   if(isHedgingSellActive())
     {
      if(total_hedge_sell_profit > 0)
        {
         double sum_sell_profit = total_hedge_sell_profit + buy_profit[0]; // hedge - first order
         if(sell_max_hedge_profit == 0 && sum_sell_profit > CalculateTP(min_lots))   // fixed 10%
           {
            sell_max_hedge_profit = sum_sell_profit;
            sell_close_hedge_profit = profit_lock * sum_sell_profit;
           }

         if(sell_max_hedge_profit > 0 && sum_sell_profit > sell_max_hedge_profit)
           {
            sell_max_hedge_profit = sum_sell_profit;
            sell_close_hedge_profit = profit_lock * sell_max_hedge_profit;
           }

         if(sell_max_hedge_profit > 0 && sell_close_hedge_profit > 0
            && sell_max_hedge_profit >= sell_close_hedge_profit && sum_sell_profit < sell_close_hedge_profit)
           {

            closeSellHedgeAndFirstBuyOrder();
           }
        }
if (buys >= 2) {
    if ((buy_profit[buys - 1] + buy_profit[buys - 2]) > 0) {
        double sum_sell_profit = total_hedge_sell_profit + buy_profit[buys - 1] + buy_profit[buys - 2];
        if (sum_sell_profit > CalculateTP(min_lots)) {
            closeSellHedgeAndLastAndSecondLastBuyOrder();
        }
    }
}

     }
  }

bool isHedgingBuyActive()
  {

   if(is_buy_hedging_order_active)
     {
      return true;
     }

   return false;
  }

bool isHedgingSellActive()
  {

   if(is_sell_hedging_order_active)
     {
      return true;
     }

   return false;
  }

void thinOutTheGrid()
  {

   if(buys >= partial_closing && !isHedgingSellActive())
     {

      if(buy_profit[buys - 1] > 0)
        {
         double buy_profit_first_and_last = buy_profit[buys - 1] + buy_profit[0];
         if(buy_profit_first_and_last > CalculateTP(buy_lots[0]))
           {
            closeLastAndFirstBuyOrder();
           }
        }
     }

   if(sells >= partial_closing && !isHedgingBuyActive())
     {

      if(sell_profit[sells - 1] > 0)
        {
         double sell_profit_first_and_last = sell_profit[sells - 1] + sell_profit[0];
         if(sell_profit_first_and_last > CalculateTP(sell_lots[0]))
           {
            closeLastAndFirstSellOrder();
           }
        }
     }
  }

bool isOrderInLoss(int ticket) {
    if (OrderSelect(ticket, SELECT_BY_TICKET)) {
        return OrderProfit() <   0;
    }
    return false;
}

void closeOrdersInLoss() {

    if (grid_outscaling >   0) {

        int totalOrders = (buys + sells);

        if (totalOrders > grid_outscaling) {

            for (int i =   0; i < buys; i++) {
                if (isOrderInLoss(buy_tickets[i])) {
                    bool result = OrderClose(buy_tickets[i], buy_lots[i], MarketInfo(Symbol(), MODE_BID), slippage, Blue);
                    if (!result) {
                        Print("Failed to close buy order with ticket ", buy_tickets[i]);
                    }

                    totalOrders--;
                }

                if (totalOrders <= grid_outscaling) break;
            }

            for (int i =   0; i < sells; i++) {
                if (isOrderInLoss(sell_tickets[i])) {
                    bool result = OrderClose(sell_tickets[i], sell_lots[i], MarketInfo(Symbol(), MODE_ASK), slippage, Red);
                    if (!result) {
                        Print("Failed to close sell order with ticket ", sell_tickets[i]);
                    }

                    totalOrders--;
                }

                if (totalOrders <= grid_outscaling) break;
            }
        }
    }
}

enum enObjectOperation
  {
   LODraw = 0,
   LODelete = 1
  };

bool BB_Buy()
  {
   double BBL = iBands(Symbol(), BB_tf, BB_Period, BB_Dev, 0, PRICE_CLOSE, MODE_LOWER, BB_Shift);
   double BBU = iBands(Symbol(), BB_tf, BB_Period, BB_Dev, 0, PRICE_CLOSE, MODE_UPPER, BB_Shift);
   if(!BB_invert)
     {
      if(BB_Mod == ASK_BID && Ask < BBL)
         return(true);
      if(BB_Mod == HIGH_LOW && Low[0] < BBL)
         return(true);
      return(false);
     }
   else
     {
      if(BB_Mod == ASK_BID && Ask > BBU)
         return(true);
      if(BB_Mod == HIGH_LOW && Low[0] > BBU)
         return(true);
      return(false);
     }
  }

bool BB_Sell()
  {

   double BBL = iBands(Symbol(), BB_tf, BB_Period, BB_Dev, 0, PRICE_CLOSE, MODE_LOWER, BB_Shift);
   double BBU = iBands(Symbol(), BB_tf, BB_Period, BB_Dev, 0, PRICE_CLOSE, MODE_UPPER, BB_Shift);
   if(!BB_invert)
     {
      if(BB_Mod == ASK_BID && Bid > BBU)
         return(true);
      if(BB_Mod == HIGH_LOW && High[0] > BBU)
         return(true);
      return(false);
     }
   else
     {
      if(BB_Mod == ASK_BID && Bid < BBL)
         return(true);
      if(BB_Mod == HIGH_LOW && High[0] < BBL)
         return(true);
      return(false);
     }
  }

bool STO_Buy()
  {
   double Sto_Value = iStochastic(Symbol(), Stoch_tf, Stoch_K, Stoch_D, Stoch_Slowing, Stoch_Method, Stoch_Price, MODE_SIGNAL, Stoch_Shift);
   if(!STO_invert)
     {
      if(Sto_Value < Stoch_Lower)
         return(true);
      return(false);
     }
   else
     {
      if(Sto_Value > Stoch_Lower && Sto_Value < Stoch_Upper)
         return(true);
      return(false);
     }
  }

bool STO_Sell()
  {
   double Sto_Value = iStochastic(Symbol(), Stoch_tf, Stoch_K, Stoch_D, Stoch_Slowing, Stoch_Method, Stoch_Price, MODE_SIGNAL, Stoch_Shift);
   if(!STO_invert)
     {
      if(Sto_Value > Stoch_Upper)
         return(true);
      return(false);
     }
   else
     {
      if(Sto_Value > Stoch_Lower && Sto_Value < Stoch_Upper)
         return(true);
      return(false);
     }
  }

bool RSI_Buy()
  {
   double RSI_Value = iRSI(Symbol(), RSI_tf, RSI_Period, PRICE_CLOSE, RSI_Shift);
   if(!RSI_invert)
     {
      if(RSI_Value < RSI_Lower)
         return(true);
      return(false);
     }
   else
     {
      if(RSI_Value > RSI_Lower && RSI_Value < RSI_Upper)
         return(true);
      return(false);
     }
  }

bool RSI_Sell()
  {
   double RSI_Value = iRSI(Symbol(), RSI_tf, RSI_Period, PRICE_CLOSE, RSI_Shift);
   if(!RSI_invert)
     {
      if(RSI_Value > RSI_Upper)
         return(true);
      return(false);
     }
   else
     {
      if(RSI_Value > RSI_Lower && RSI_Value < RSI_Upper)
         return(true);
      return(false);
     }
  }

bool CCI_Buy()
  {
   double CCI_Value = iCCI(Symbol(), CCI_tf, CCI_Period, PRICE_CLOSE, CCI_Shift);
   if(!CCI_invert)
     {
      if(CCI_Value < CCI_Lower)
         return(true);
      return(false);
     }
   else
     {
      if(CCI_Value > CCI_Lower && CCI_Value < CCI_Upper)
         return(true);
      return(false);
     }
  }

bool CCI_Sell()
  {
   double CCI_Value = iCCI(Symbol(), CCI_tf, CCI_Period, PRICE_CLOSE, CCI_Shift);
   if(!CCI_invert)
     {
      if(CCI_Value > CCI_Upper)
         return(true);
      return(false);
     }
   else
     {
      if(CCI_Value > CCI_Lower && CCI_Value < CCI_Upper)
         return(true);
      return(false);
     }
  }

bool C1_Buy()
{
if (Use_C1) {
    double customIndicator1BuyValue = iCustom(NULL, 0, C1_Name, C1_BuyBuffer, 0);
    double customIndicator1SellValue = iCustom(NULL, 0, C1_Name, C1_SellBuffer, 0);
}
   double buySignal;
   if (C1_Wait) {buySignal = iCustom(NULL, 0, C1_Name, C1_BuyBuffer, 1);} 
   else         {buySignal = iCustom(NULL, 0, C1_Name, C1_BuyBuffer, 0);}

if (C1_Type == Empty_Indicator) {
    if (C1_Invert) {
        if (buySignal != EMPTY_VALUE) {
        if (C1_Exit) {closeAllSells();}
            return true;
        } else {
            return false;
        }
    } else {
        if (buySignal == EMPTY_VALUE) {
        if (C1_Exit) {closeAllSells();}
            return true;
        } else {
            return false;
        }
    }
    } else if (C1_Type == Value_Indicator) {
        if(!C1_Invert){
            if (buySignal > C1_BuyValue) {
            if (C1_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (buySignal < C1_BuyValue) {
            if (C1_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C1_Type == Price_Indicator) {
        if(!C1_Invert){
            if (Close[0] < buySignal) {
            if (C1_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[0] > buySignal) {
            if (C1_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C1_Type == Cross_Indicator) {
    double bufferValue;
    if (C1_Wait) {
        bufferValue = iCustom(NULL, 0, C1_Name, C1_BuyBuffer, 0);
        if(!C1_Invert){
            if (Close[2] < bufferValue && Close[1] > bufferValue) {
            if (C1_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[2] > bufferValue || Close[1] < bufferValue) {
            if (C1_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else {
        bufferValue = iCustom(NULL, 0, C1_Name, C1_BuyBuffer, 0);
        if(!C1_Invert){
            if (Open[0] < bufferValue && Close[0] > bufferValue) {
            if (C1_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Open[0] > bufferValue || Close[0] < bufferValue) {
            if (C1_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    }
}
    return false;
}

bool C1_Sell()
{

   double sellSignal;
   if (C1_Wait) {sellSignal = iCustom(NULL, 0, C1_Name, C1_SellBuffer, 1);} 
   else         {sellSignal = iCustom(NULL, 0, C1_Name, C1_SellBuffer, 0);}

if (C1_Type == Empty_Indicator) {
    if (C1_Invert) {
        if (sellSignal != EMPTY_VALUE) {
        if (C1_Exit) {closeAllBuys();}
            return true;
        } else {
            return false;
        }
    } else {
        if (sellSignal == EMPTY_VALUE) {
        if (C1_Exit) {closeAllBuys();}
            return true;
        } else {
            return false;
        }
    }
    } else if (C1_Type == Value_Indicator) {
        if(!C1_Invert){
            if (sellSignal > C1_SellValue) {
            if (C1_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (sellSignal < C1_SellValue) {
            if (C1_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C1_Type == Price_Indicator) {
        if(!C1_Invert){
            if (Close[0] > sellSignal) {
            if (C1_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[0] < sellSignal) {
            if (C1_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C1_Type == Cross_Indicator) {
    double bufferValue;
    if (C1_Wait) {
        bufferValue = iCustom(NULL, 0, C1_Name, C1_SellBuffer, 0);
        if(!C1_Invert){
            if (Close[2] > bufferValue && Close[1] < bufferValue) {
            if (C1_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[2] < bufferValue || Close[1] > bufferValue) {
            if (C1_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else {
        bufferValue = iCustom(NULL, 0, C1_Name, C1_SellBuffer, 0);
        if(!C1_Invert){
            if (Open[0] > bufferValue && Close[0] < bufferValue) {
            if (C1_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Open[0] < bufferValue || Close[0] > bufferValue) {
            if (C1_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    }
}
    return false;
}

bool C2_Buy()
{
if (Use_C2) {
    double customIndicator1BuyValue = iCustom(NULL, 0, C2_Name, C2_BuyBuffer, 0);
    double customIndicator1SellValue = iCustom(NULL, 0, C2_Name, C2_SellBuffer, 0);
}
   double buySignal;
   if (C2_Wait) {buySignal = iCustom(NULL, 0, C2_Name, C2_BuyBuffer, 1);} 
   else         {buySignal = iCustom(NULL, 0, C2_Name, C2_BuyBuffer, 0);}

if (C2_Type == Empty_Indicator) {
    if (C2_Invert) {
        if (buySignal != EMPTY_VALUE) {
        if (C2_Exit) {closeAllSells();}
            return true;
        } else {
            return false;
        }
    } else {
        if (buySignal == EMPTY_VALUE) {
        if (C2_Exit) {closeAllSells();}
            return true;
        } else {
            return false;
        }
    }
    } else if (C2_Type == Value_Indicator) {
        if(!C2_Invert){
            if (buySignal > C2_BuyValue) {
            if (C2_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (buySignal < C2_BuyValue) {
            if (C2_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C2_Type == Price_Indicator) {
        if(!C2_Invert){
            if (Close[0] < buySignal) {
            if (C2_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[0] > buySignal) {
            if (C2_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C2_Type == Cross_Indicator) {
    double bufferValue;
    if (C2_Wait) {
        bufferValue = iCustom(NULL, 0, C2_Name, C2_BuyBuffer, 0);
        if(!C2_Invert){
            if (Close[2] < bufferValue && Close[1] > bufferValue) {
            if (C2_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[2] > bufferValue || Close[1] < bufferValue) {
            if (C2_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else {
        bufferValue = iCustom(NULL, 0, C2_Name, C2_BuyBuffer, 0);
        if(!C2_Invert){
            if (Open[0] < bufferValue && Close[0] > bufferValue) {
            if (C2_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Open[0] > bufferValue || Close[0] < bufferValue) {
            if (C2_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    }
}
    return false;
}

bool C2_Sell()
{

   double sellSignal;
   if (C2_Wait) {sellSignal = iCustom(NULL, 0, C2_Name, C2_SellBuffer, 1);} 
   else         {sellSignal = iCustom(NULL, 0, C2_Name, C2_SellBuffer, 0);}

if (C2_Type == Empty_Indicator) {
    if (C2_Invert) {
        if (sellSignal != EMPTY_VALUE) {
        if (C2_Exit) {closeAllBuys();}
            return true;
        } else {
            return false;
        }
    } else {
        if (sellSignal == EMPTY_VALUE) {
        if (C2_Exit) {closeAllBuys();}
            return true;
        } else {
            return false;
        }
    }
    } else if (C2_Type == Value_Indicator) {
        if(!C2_Invert){
            if (sellSignal > C2_SellValue) {
            if (C2_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (sellSignal < C2_SellValue) {
            if (C2_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C2_Type == Price_Indicator) {
        if(!C2_Invert){
            if (Close[0] > sellSignal) {
            if (C2_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[0] < sellSignal) {
            if (C2_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C2_Type == Cross_Indicator) {
    double bufferValue;
    if (C2_Wait) {
        bufferValue = iCustom(NULL, 0, C2_Name, C2_SellBuffer, 0);
        if(!C2_Invert){
            if (Close[2] > bufferValue && Close[1] < bufferValue) {
            if (C2_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[2] < bufferValue || Close[1] > bufferValue) {
            if (C2_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else {
        bufferValue = iCustom(NULL, 0, C2_Name, C2_SellBuffer, 0);
        if(!C2_Invert){
            if (Open[0] > bufferValue && Close[0] < bufferValue) {
            if (C2_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Open[0] < bufferValue || Close[0] > bufferValue) {
            if (C2_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    }
}
    return false;
}

bool C3_Buy()
{
if (Use_C3) {
    double customIndicator1BuyValue = iCustom(NULL, 0, C3_Name, C3_BuyBuffer, 0);
    double customIndicator1SellValue = iCustom(NULL, 0, C3_Name, C3_SellBuffer, 0);
}
   double buySignal;
   if (C3_Wait) {buySignal = iCustom(NULL, 0, C3_Name, C3_BuyBuffer, 1);} 
   else         {buySignal = iCustom(NULL, 0, C3_Name, C3_BuyBuffer, 0);}

if (C3_Type == Empty_Indicator) {
    if (C3_Invert) {
        if (buySignal != EMPTY_VALUE) {
        if (C3_Exit) {closeAllSells();}
            return true;
        } else {
            return false;
        }
    } else {
        if (buySignal == EMPTY_VALUE) {
        if (C3_Exit) {closeAllSells();}
            return true;
        } else {
            return false;
        }
    }
    } else if (C3_Type == Value_Indicator) {
        if(!C3_Invert){
            if (buySignal > C3_BuyValue) {
            if (C3_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (buySignal < C3_BuyValue) {
            if (C3_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C3_Type == Price_Indicator) {
        if(!C3_Invert){
            if (Close[0] < buySignal) {
            if (C3_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[0] > buySignal) {
            if (C3_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C3_Type == Cross_Indicator) {
    double bufferValue;
    if (C3_Wait) {
        bufferValue = iCustom(NULL, 0, C3_Name, C3_BuyBuffer, 0);
        if(!C3_Invert){
            if (Close[2] < bufferValue && Close[1] > bufferValue) {
            if (C3_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[2] > bufferValue || Close[1] < bufferValue) {
            if (C3_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    } else {
        bufferValue = iCustom(NULL, 0, C3_Name, C3_BuyBuffer, 0);
        if(!C3_Invert){
            if (Open[0] < bufferValue && Close[0] > bufferValue) {
            if (C3_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Open[0] > bufferValue || Close[0] < bufferValue) {
            if (C3_Exit) {closeAllSells();}
                return true;
            } else {
                return false;
            }
        }
    }
}
    return false;
}

bool C3_Sell()
{

   double sellSignal;
   if (C3_Wait) {sellSignal = iCustom(NULL, 0, C3_Name, C3_SellBuffer, 1);} 
   else         {sellSignal = iCustom(NULL, 0, C3_Name, C3_SellBuffer, 0);}

if (C3_Type == Empty_Indicator) {
    if (C3_Invert) {
        if (sellSignal != EMPTY_VALUE) {
        if (C3_Exit) {closeAllBuys();}
            return true;
        } else {
            return false;
        }
    } else {
        if (sellSignal == EMPTY_VALUE) {
        if (C3_Exit) {closeAllBuys();}
            return true;
        } else {
            return false;
        }
    }
    } else if (C3_Type == Value_Indicator) {
        if(!C3_Invert){
            if (sellSignal > C3_SellValue) {
            if (C3_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (sellSignal < C3_SellValue) {
            if (C3_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C3_Type == Price_Indicator) {
        if(!C3_Invert){
            if (Close[0] > sellSignal) {
            if (C3_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[0] < sellSignal) {
            if (C3_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else if (C3_Type == Cross_Indicator) {
    double bufferValue;
    if (C3_Wait) {
        bufferValue = iCustom(NULL, 0, C3_Name, C3_SellBuffer, 0);
        if(!C3_Invert){
            if (Close[2] > bufferValue && Close[1] < bufferValue) {
            if (C3_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Close[2] < bufferValue || Close[1] > bufferValue) {
            if (C3_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    } else {
        bufferValue = iCustom(NULL, 0, C3_Name, C3_SellBuffer, 0);
        if(!C3_Invert){
            if (Open[0] > bufferValue && Close[0] < bufferValue) {
            if (C3_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        } else {
            if (Open[0] < bufferValue || Close[0] > bufferValue) {
            if (C3_Exit) {closeAllBuys();}
                return true;
            } else {
                return false;
            }
        }
    }
}
    return false;
}

double ATR_Grid_Size()
  {
   int digits, scale = 10000;
   digits = (int)MarketInfo(Symbol(), MODE_DIGITS);

   if(digits == 3 || digits == 2)
      scale = 100;
   if(Use_ATR &&  NewBarTF(ATR_tf))
     {
      return ((int)round(ATR_Multiplier * scale * iATR(Symbol(), ATR_tf, ATR_Period, 0)));
     }
   else
     {
      return grid_size;
     }
  }

bool Indicators_Buy()
{
   bool BB_ret, STO_ret, RSI_ret, CCI_ret, C1_ret, C2_ret, C3_ret;
   if(Conjunct_Idx)
   {
      BB_ret = true;
      STO_ret = true;
      RSI_ret = true;
      CCI_ret = true;
      C1_ret = true;
      C2_ret = true;
      C3_ret = true;
      if(Use_BB)
         BB_ret = BB_Buy();
      if(Use_Stoch)
         STO_ret = STO_Buy();
      if(Use_RSI)
  

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

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

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

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

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

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

Стоимость полного кода
12 252,90₽ ≈ $149.75