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

flexy the dragon v2.6.mq4

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

ea robofibo source v.11.2.mq4MetaTrader 4 · 1 общих теговᴇɴᴛʀʏ.txtTradingView · 1 общих теговzonestrategy.mqhMetaTrader 5 · 1 общих теговxauusd_simple_strategy7.mq4MetaTrader 4 · 1 общих теговxauusd_grok_presisi_scalper_v1.4 - anti detach.mq5MetaTrader 5 · 1 общих теговxauusd_gold_perfect.mq4MetaTrader 4 · 1 общих тегов
Вы автор или правообладатель?

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

Получить полный код

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

#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.5"
#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 = "Flexy The Dragon";
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_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 int profit_chasing        = 0;              // #2 Profit Chasing
sinput string profit_chasing_info;                 // (number of orders to chase maximum profit)
extern double equity_warning     = 0.7;            // #3 Equity Warning / Yoga Mode 
sinput string equity_info;                         // (stop open orders on low equity, 0.7 = 70%)
extern double cycleEquityRisk    = 0.0;            // #4 Cycle Risk / Stop Loss
sinput string cycleEquityRisk_info;                // (close orders of one grid cycle, 0.01 = 1%)
extern double account_risk       = 0.9;            // #5 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       = 0;              // 1# Partial Closing
sinput string partial_closing_info;                // (number of orders to start closing last + 1st trade of grid)
extern int partial_breaking      = 0;              // 2# Partial Breaking
sinput string partial_breaking_info;               // (number of orders to start closing 1st grid trades in loss)
extern double reduce_tp          = 0.0;            // 3# Profit Reducing
sinput string reduce_tp_info;                      // (reduces take profit per grid order in pips, min. 1pip)
extern bool hedging_active       = false;          // 4# Cycle Hedging
sinput string hedging_active_info;                 // (hedge entire grid cycle, if maximum positions are reached)
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"
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

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   = clrSlateGray;  
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 * 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 (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 (partial_breaking >   0) {

        int totalOrders = (buys + sells);

        if (totalOrders > partial_breaking) {

            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 <= partial_breaking) 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 <= partial_breaking) 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)
         RSI_ret = RSI_Buy();
      if(Use_CCI)
         CCI_ret = CCI_Buy();
      

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

Что вы получите после оплаты

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

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

Стоимость полного кода
12 212₽