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

Flexy The Dragon

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

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

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

О программе

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

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

НастройкаОписание
Magic Number (0 = automatic) (magic) Магическое число (0 = автоматически).
. (gap00) Разделитель.
Show Indicators Info? (show_indicators) Показывать информацию об индикаторах.
Show Trading Info? (show_forecast) Показывать торговую информацию.
Show Settings Info? (show_settings) Показывать информацию о настройках.
. (gap10) Разделитель.
======> O R D E R S E T T I N G S <====== (Order_Settings) Заголовок раздела настроек ордеров.
. (gap11) Разделитель.
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) Разделитель.
Max. Spread (to open orders, in pts) (max_spread) Максимальный спред для открытия ордеров (в пунктах).
. (gap14) Разделитель.
======> G R I D S E T T I N G S <====== (Grid_Settings) Заголовок раздела настроек сетки.
. (gap20) Разделитель.
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 martingale) (gs_multiplicator) Множитель сетки (только для мартингейла).
. (gap21) Разделитель.
Fixed Grid Step (in pips) (grid_size) Фиксированный шаг сетки (в пипсах).
Fixed Take Profit (in pips) (take_profit) Фиксированный тейк-профит (в пипсах).
. (gap22) Разделитель.
Use Dynamic Grid? (based on ATR) (Use_ATR) Использовать динамическую сетку на основе ATR.
ATR Time Frame (ATR_tf) Таймфрейм ATR.
ATR Period (ATR_Period) Период ATR.
Dynamic Grid Step (ATR ratio) (ATR_Multiplier) Множитель ATR для динамического шага сетки.
Dynamic Take Proft (ATR ratio) (TP_Multiplier) Множитель ATR для динамического тейк-профита.
. (gap23) Разделитель.
======> R I S K S E T T I N G S <====== (Risk_Settings) Заголовок раздела настроек риска.
. (gap30) Разделитель.
Profit Lock / Trail Stop (profit_lock) Фиксация прибыли / трейлинг-стоп.
(safe profit per grid step, 0.01 = 1%) (profit_lock2) Безопасная прибыль на шаг сетки (0.01 = 1%).
Cycle Risk / Stop Loss (cycleEquityRisk) Риск цикла / стоп-лосс.
(close orders of grid cycle, 0.01 = 1%) (cycleEquityRisk2) Закрывать ордера сеточного цикла (0.01 = 1%).
. (gap31) Разделитель.
Yoga Mode / Equity Warning (equity_warning) Режим йоги / предупреждение по эквити.
(stop opening orders [yellow], 0.01 = 1%) (equity_warning2) Останавливать открытие ордеров [жёлтый] (0.01 = 1%).
. (gap32) Разделитель.
Reduce Profit (reduce_tp) Уменьшение прибыли.
(reduces take profit per grid order, min. 1pip) (reduce_tp2) Уменьшает тейк-профит на каждый ордер сетки, минимум 1 пипс.
Partial Closing (grid_partially_close) Частичное закрытие.
(number of orders to close last + 1st trade of cycle) (grid_partially_close2) Количество ордеров для закрытия последней и первой сделки цикла.
Cycle Hedging (hedging_active) Хеджирование цикла.
(hedge entire cycle, if max. positions reached) (hedging_active2) Хеджировать весь цикл, если достигнуто максимальное количество позиций.
Profit Chasing (profit_chasing) Погоня за прибылью.
(number of profitable orders to chase max. profit) (profit_chasing2) Количество прибыльных ордеров для погони за максимальной прибылью.
. (gap33) Разделитель.
======> B A S I C I N D I C A T O R S <====== (Indicators_Settings) Заголовок раздела базовых индикаторов.
. (gap50) Разделитель.
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) Строгие сигналы (открывать следующие ордера сетки только по сигналу).
. (gap51) Разделитель.
Bollinger Bands (BB) ************ (Bollinger_Bands) Заголовок раздела настроек полос Боллинджера.
Use BB signals? (Use_BB) Использовать сигналы BB.
Invert trigger (follow trend)? (BB_invert) Инвертировать триггер (следовать за трендом).
Time frame (BB_tf) Таймфрейм полос Боллинджера.
Period (BB_Period) Период полос Боллинджера.
Deviation (set to "0.01" for moving average) (BB_Dev) Отклонение полос Боллинджера (установите 0.01 для скользящей средней).
Price method (ask/bid, high/low) (BB_Mod) Метод цены для полос Боллинджера (ask/bid или high/low).
Shift (BB_Shift) Сдвиг полос Боллинджера.
. (gap52) Разделитель.
Stochastic Oscillator (STO) ************ (Stochastic_Oscillator) Заголовок раздела настроек стохастического осциллятора.
Use STO signals? (Use_Stoch) Использовать сигналы STO.
Invert trigger (follow trend)? (STO_invert) Инвертировать триггер (следовать за трендом).
Time frame (Stoch_tf) Таймфрейм стохастика.
Period %K line (Stoch_K) Период линии %K.
Period %D line (Stoch_D) Период линии %D.
Slowing value (Stoch_Slowing) Значение замедления.
MA method (Stoch_Method) Метод скользящей средней.
Price method (low/high, close/close) (Stoch_Price) Метод цены (low/high или close/close).
Upper level (Stoch_Upper) Верхний уровень стохастика.
Lower level (Stoch_Lower) Нижний уровень стохастика.
Shift (Stoch_Shift) Сдвиг стохастика.
. (gap53) Разделитель.
Relative Strength Index (RSI) ************ (Relative_Strength_Index) Заголовок раздела настроек RSI.
Use RSI signals? (Use_RSI) Использовать сигналы RSI.
Invert trigger (follow trend)? (RSI_invert) Инвертировать триггер (следовать за трендом).
Time trame (RSI_tf) Таймфрейм RSI.
Period (RSI_Period) Период RSI.
Upper level (RSI_Upper) Верхний уровень RSI.
Lower level (RSI_Lower) Нижний уровень RSI.
Shift (RSI_Shift) Сдвиг RSI.
. (gap54) Разделитель.
Commodity Channel Index (CCI) ************ (Commodity_Channel_Index) Заголовок раздела настроек CCI.
Use CCI signals? (Use_CCI) Использовать сигналы CCI.
Invert trigger (follow trend)? (CCI_invert) Инвертировать триггер (следовать за трендом).
Time frame (CCI_tf) Таймфрейм CCI.
Period (CCI_Period) Период CCI.
Upper level (CCI_Upper) Верхний уровень CCI.
Lower level (CCI_Lower) Нижний уровень CCI.
Shift (CCI_Shift) Сдвиг CCI.
. (gap55) Разделитель.
======> C U S T O M I N D I C A T O R S <====== (Custom_Indicators) Заголовок раздела пользовательских индикаторов.
. (gap60) Разделитель.
Custom Indicator 1 ************ (C1) Заголовок раздела пользовательского индикатора 1.
Use Custom Indicator? (Use_C1) Использовать пользовательский индикатор.
Получить полный код

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

#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.1"
#define versionBMI "Flexy The Dragon 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;

extern int magic = 0;                              // Magic Number (0 = automatic)
sinput string gap00; // .
input bool show_indicators = false;                // Show Indicators Info?
input bool show_forecast = true;                   // Show Trading Info?
input bool show_settings = false;                  // Show Settings Info?
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 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;            // Profit Lock / Trail Stop
sinput string profit_lock2;                        // (safe profit per grid step, 0.01 = 1%)
extern double cycleEquityRisk    = 0.0;            // Cycle Risk / Stop Loss
sinput string cycleEquityRisk2;                    // (close orders of grid cycle, 0.01 = 1%)
sinput string gap31; // .
extern double equity_warning     = 0.0;            // Yoga Mode / Equity Warning 
sinput string equity_warning2;                     // (stop opening orders [yellow], 0.01 = 1%)
extern double account_risk       = 1.0;            // Shut Down / Account Risk
sinput string account_risk2;                       // (close all open orders [red], 0.01 = 1%)
sinput string gap32; // .
extern double reduce_tp          = 0.0;            // Reduce Profit
sinput string reduce_tp2;                          // (reduces take profit per grid order, min. 1pip)
extern int grid_partially_close  = 0;              // Partial Closing
sinput string grid_partially_close2;               // (number of orders to close last + 1st trade of cycle)
extern bool hedging_active       = false;          // Cycle Hedging
sinput string hedging_active2;                     // (hedge entire cycle, if max. positions reached)
extern int profit_chasing        = 0;              // Profit Chasing
sinput string profit_chasing2;                     // (number of profitable orders to chase max. profit)
sinput string gap33; // .
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)
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"
sinput string Type_Info6;                               // b) Value Type: if [buffer] is </> than [buy/sell value]*
sinput string Type_Info7;                               // c) Price Type: if [price] is </> than [buffer]
sinput string Type_Info8;                               // d) Cross Type: if [price] crosses [buffer] up/down
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

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    = clrRoyalBlue;

int colFontLight  = clrWhite;
int colFontDark   = clrSlateGray;  
int colFontGray   = clrSlateGray;
int colFontWhite  = clrWhite;
int colFontYellow = clrYellow;

int colCodeGreen  = clrGreen;
int colCodeYellow = clrGold;
int colCodeRed    = clrRed;
int colPauseButtonPassive = clrBlue;

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 btnWidth = 100;            // width of smallest buttons
int btnHeight = 20;           // height of all buttons
int btnGap = 3;               // gap, between buttons
int btnLeftAxis = 250;        // distance of button from left screen border
int btnTopAxis = 4;           // distance of button from top screen border
int btnNextLeft = btnWidth + btnGap;      // distance to next button
int btnNextTop = btnHeight + btnGap;      // distance to next button

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;

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", colCodeGreen, colFontLight);
         SetButtonColor("btnhedgeSell", colCodeGreen, colFontLight);
         SetButtonColor("btnCloseLastBuy", colCodeGreen, colFontLight);
         SetButtonColor("btnCloseLastSell", colCodeGreen, colFontLight);
         SetButtonColor("btnCloseAllBuys", colCodeGreen, colFontLight);
         SetButtonColor("btnCloseAllSells", colCodeGreen, colFontLight);
         SetButtonColor("btnShowComment", colCodeGreen, 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 * reduce_tp;
   double reducedTakeProfitSells = take_profit - sells * reduce_tp;

   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 (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);
     }
  }

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 >= grid_partially_close && !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 >= grid_partially_close && !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();
           }
        }
     }
  }

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)
         RSI_ret = RSI_Buy();
      if(Use_CCI)
         CCI_ret = CCI_Buy();
      if(Use_C1)
         C1_ret = C1_Buy();
      if(Use_C2)
         C2_ret = C2_Buy();
      if(Use_C3)
         C3_ret = C3_Buy();
      if(BB_ret && STO_ret && RSI_ret && CCI_ret && C1_ret && C2_ret && C3_ret)
         return (true);
      return(false);
   }
   else
   {
      if(Use_BB)
         BB_ret = BB_Buy();
      else
         BB_ret = false;
      if(Use_Stoch)
         STO_ret = STO_Buy();
      else
         STO_ret = false;
      if(Use_RSI)
         RSI_ret = RSI_Buy();
      else
         RSI_ret = false;
      if(Use_CCI)
         CCI_ret = CCI_Buy();
      else
         CCI_ret = false;
      if(Use_C1)
         C1_ret = C1_Buy();
      else
         C1_ret = false;
      if(Use_C2)
         C2_ret = C2_Buy();
      else
         C2_ret = false;
      if(Use_C3)
         C3_ret = C3_Buy();
      else
         C3_ret = false;
      if(BB_ret || STO_ret || RSI_ret || CCI_ret || C1_ret || C2_ret || C3_ret)
         return (true);
      return(false);
   }
   return (false);
}

bool Indicators_Sell()
{
   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_Sell();
      if(Use_Stoch)
         STO_ret = STO_Sell();
      if(Use_RSI)
         RSI_ret = RSI_Sell();
      if(Use_CCI)
         CCI_ret = CCI_Sell();
      if(Use_C1)
         C

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

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

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

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

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

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

Стоимость полного кода
12 133,60₽ ≈ $148.30