Algorithm manually automate

Author: Copyright © 2021, Aleksandr Klapatyuk
8 Views
0 Downloads
0 Favorites
Algorithm manually automate
ÿþ//+------------------------------------------------------------------+

//|                                  Algorithm manually automate.mq5 |

//|                           Copyright © 2021, Aleksandr Klapatyuk. |

//|                            https://www.mql5.com/ru/users/sanalex |

//+------------------------------------------------------------------+

#property copyright   "Copyright © 2021, Aleksandr Klapatyuk"

#property link        "https://www.mql5.com/ru/users/sanalex"

#define   EAName      "Algorithm manually automate"

#define   EAVersion   "1.005"

#property description "Copyright 2021, Strx"

#property description "https://www.mql5.com/en/users/strx"

#property description "Copyright © 2021, Vladimir Karputov"

#property description "http://wmua.ru/slesar/"

#property description "Klymenko Roman (needtome@icloud.com)"

#property description "https://www.mql5.com/ru/users/needtome"

#property description "Copyright © 2021, SEM "

#property description "https://www.mql5.com/ru/users/seliveru"

#property version     EAVersion

//---

#define MACD_MAGIC 0

//---

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>

#include <Trade\PositionInfo.mqh>

#include <Trade\AccountInfo.mqh>

#include <Arrays\ArrayString.mqh>

#include <ChartObjects\ChartObject.mqh>

#include <ChartObjects\ChartObjectsLines.mqh>

//+------------------------------------------------------------------+

//| ENUM_LOT_RISK                                                    |

//+------------------------------------------------------------------+

enum LotMax

  {

   Lot=0,   // Lots

   Lotx2=1, // Lots*2

   Risk=2,  // Risk

  };

//+------------------------------------------------------------------+

//| ENUM_PROFIT_COMMAND                                              |

//+------------------------------------------------------------------+

enum ENUM_MODE

  {

   mode_All=0,        // .

   mode_Ind=1,        // +. $8;LB@

  };

//+------------------------------------------------------------------+

//| ENUM_PROFIT_COMMAND                                              |

//+------------------------------------------------------------------+

enum ENUM_P

  {

   tpl_b=0,           // Close

   tpl_s=1,           // Close + Open + '.tpl'

  };

//+------------------------------------------------------------------+

//| ENUM_FILTER_COMMAND                                              |

//+------------------------------------------------------------------+

enum ENUM_FILTR_COMMAND

  {

   Filter_Off=0,      // OFF

   Filter_Stop=1,     // Filter Line Up:Down

   Filter_All=2,      // Filter Line Up:Down:Middle

  };

//+------------------------------------------------------------------+

//| ENUM_TRADE_COMMAND                                               |

//+------------------------------------------------------------------+

enum ENUM_TRADE_COMMAND

  {

   Turn_Off=0,        // TURN OFF

   tpl=1,             // '.tpl' All

   Close_AllExt=2,    // CloseAll + ExpertRemoves

   Close_All_All=3,   // CloseAll

   close_tpl_b=4,     // Close Sell + Open Buy + '.tpl'

   close_tpl_s=5,     // Close Buy + Open Sell + '.tpl'

   close_all_tpl=6,   // Close Buy's Sell's + '.tpl'

   UpName=7,          // Line Open UpName

   DownName=8,        // Line Open DownName

   UpName_s=9,        // Line Open UpName + Open Sell

   UpName_b=10,       // Line Open UpName + Open Buy

   DownName_b=11,     // Line Open DownName + Open Buy

   DownName_s=12,     // Line Open DownName + Open Sell

   ClUpName=13,       // Line Close UpName

   ClDownName=14,     // Line Close DownName

   ClUpName_s=15,     // Line Close UpName + Open Sell

   ClUpName_b=16,     // Line Close UpName + Open Buy

   ClDownName_b=17,   // Line Close DownName + Open Buy

   ClDownName_s=18,   // Line Close DownName + Open Sell

   close_buys=19,     // Close All Buy's

   close_sells=20,    // Close All Sell's

   close_all=21,      // Close All Buy's and Sell's

   open_buy=22,       // Open  Buy

   open_sell=23,      // Open  Sell

   close_open_b=24,   // Close Sell + Open Buy

   close_open_s=25,   // Close Buy + Open Sell

   open_buy_sell=26,  // Open  Buy and Sell

  };

//+------------------------------------------------------------------+

sinput group "----------------- Balans Parameters --------------------"

sinput string             Template                   = "ADX";            // <O H01;>=0(without '.tpl')

sinput double             TargetProfit               = 1000000;          // 0;0=A + @81K;L(?@81028BL : 10;0=AC)

sinput double             TargetLoss                 = 0;                // 0;0=A - #1KB>:(>B=OBL >B 10;0=A0)

sinput bool               AllCloseAllNotifications   = false;            // AllCloseAllNotifications

sinput bool               AllCloseAllEmails          = false;            // AllCloseAllEmails

sinput group "----------------- Balans Parameters 1 ------------------"

sinput double             TargetProfit_1             = 1000000;          // 1I0O @81K;L 0;NB5 '0'--> 5;L7O

sinput double             TargetLoss_1               = 1000000;          // 1I89 #1KB>: 0;NB5 '0'--> 5;L7O

sinput group "----------------- Balans BUY+SELL ----------------------"

sinput double             TargetProfit_2             = 1000000;          // BUY+SELL @81K;L 0;NB5 '0'--> 5;L7O

sinput double             TargetLoss_2               = 1000000;          // BUY+SELL #1KB>: 0;NB5 '0'--> 5;L7O

sinput group "----------------- TP SL In currency --------------------"

sinput double             InpTProfit                 = 40000;            // In currency the amount 1I89 TP

sinput double             InpStopLoss                = 1000000;          // In currency the amount 1I89 SL

sinput ENUM_P             InpProfitCommand           = tpl_b;            // TP SL: command Close

sinput string             Template_1                 = "NACHALO";        // <O H01;>=0(without '.tpl')

sinput group "----------------- Lots Parameters ----------------------"

sinput LotMax             InpLotRisk                 = Risk;             // : Lots,- Lots*2,- Risk

sinput double             MaximumRisk                = 0.02;             // : Maximum Risk in percentage

sinput double             DecreaseFactor             = 3;                // : Descrease factor

sinput group "----------------- Start Stop ---------------------------"

sinput datetime           HoursFrom                  = D'1970.01.02';    // 1 @5<O: AB0@B

sinput datetime           HoursTo                    = D'1970.01.01';    // @5<O: AB>?

sinput datetime           HoursFrom2                 = D'1970.01.01';    // 2 @5<O: AB0@B

sinput group "----------------- Time:Start Stop ----------------------"

sinput int                HoursFrom1                 = 0;                // @5<O: AB0@B

sinput int                HoursTo1                   = 24;               // @5<O: AB>?

sinput group "----------------- Obj: VLine:UP ------------------------"

sinput ENUM_MODE          FilterLine_1               = mode_All;         // FILTER: .+.

sinput string             InpObjVLineName            = "<O VLine";      // Name: VLine

sinput ENUM_TRADE_COMMAND InpVLineCommand            = Turn_Off;         // VLine command:

sinput group "----------------- Obj: VLine:DOWN ----------------------"

sinput ENUM_MODE          FilterLine_2               = mode_All;         // FILTER: .+.

sinput string             InpObjVLineNameD           = "<O VLine";      // Name: VLine

sinput ENUM_TRADE_COMMAND InpVLineCommandD           = Turn_Off;         // VLine command:

sinput group "----------------- Indicators: UP -----------------------"

sinput bool               InpIndicators_1            = false;            // Indicators: Start (true)

sinput ENUM_MODE          FilterLine_3               = mode_All;         // FILTER: .+.

sinput string             short_name_1               = "Turning point";  // Name Indicators "UP"

sinput int                InpBars_1                  = 0;                // Bars

sinput ENUM_TIMEFRAMES    Period_1                   = PERIOD_CURRENT;   // Period Indicators

sinput ENUM_TRADE_COMMAND InpLongOpened_1Command     = close_open_b;     // Buy command:

sinput ENUM_TRADE_COMMAND InpShortOpened_1Command    = close_open_s;     // Sell command:

sinput group "----------------- Indicators: DOWN ---------------------"

sinput bool               InpIndicators_2            = false;            // Indicators: Start (true)

sinput ENUM_MODE          FilterLine_4               = mode_All;         // FILTER: .+.

sinput string             short_name_2               = "Turning point";  // Name Indicators "DOWN"

sinput int                InpBars_2                  = 0;                // Bars

sinput ENUM_TIMEFRAMES    Period_2                   = PERIOD_CURRENT;   // Period Indicators

sinput ENUM_TRADE_COMMAND InpLongOpened_2Command     = close_open_b;     // Buy command:

sinput ENUM_TRADE_COMMAND InpShortOpened_2Command    = close_open_s;     // Sell command:

sinput group "----------------- Trailing Line:1 ----------------------"

sinput bool               InpStartOpen               = false;            // Start Trailing Line

sinput ENUM_MODE          FilterLine_5               = mode_All;         // FILTER: .+.

sinput string             InpObjUpNameOpen           = "openup";         // Obj: Up (Trailing Horizontal Line)

sinput ENUM_TRADE_COMMAND InpTradeCommandY1          = open_sell;        // Trade command:

sinput color              InpObjUpclrOpen            = clrBlue;          // Obj: command: MonitoringColor, EA only monitors this lines color

sinput ENUM_MODE          FilterLine_6               = mode_All;         // FILTER: .+.

sinput string             InpObjDownNameOpen         = "opendown";       // Obj: Down (Trailing Horizontal Line)

sinput ENUM_TRADE_COMMAND InpTradeCommandU1          = open_buy;         // Trade command:

sinput color              InpObjDownclrOpen          = clrRed;           // Obj: command: MonitoringColor, EA only monitors this lines color

sinput double             InpObjTrailingStopOpen     = 0;                // Obj: Trailing Stop (distance from price to object, in pips)

sinput double             InpObjTrailingStepOpen     = 0;                // Obj: Trailing Step, in pips (1.00045-1.00055=1 pips)

sinput group "----------------- Trailing Line:2 ----------------------"

sinput bool               InpStartClos               = false;            // Start Trailing Line

sinput ENUM_MODE          FilterLine_7               = mode_All;         // FILTER: .+.

sinput string             InpObjUpNameClos           = "closup";         // Obj: Up (Trailing Horizontal Line)

sinput ENUM_TRADE_COMMAND InpTradeCommandY2          = close_sells;      // Trade command:

sinput color              InpObjUpclrClos            = clrBlue;          // Obj: command: MonitoringColor, EA only monitors this lines color

sinput ENUM_MODE          FilterLine_8               = mode_All;         // FILTER: .+.

sinput string             InpObjDownNameClos         = "closdown";       // Obj: Down (Trailing Horizontal Line)

sinput ENUM_TRADE_COMMAND InpTradeCommandU2          = close_buys;       // Trade command:

sinput color              InpObjDownclrClos          = clrRed;           // Obj: command: MonitoringColor, EA only monitors this lines color

sinput double             InpObjTrailingStopClos     = 0;                // Obj: Trailing Stop (distance from price to object, in pips)

sinput double             InpObjTrailingStepClos     = 0;                // Obj: Trailing Step, in pips (1.00045-1.00055=1 pips)

sinput group "----------------- Buy::UP ------------------------------"

sinput ENUM_MODE          FilterLine_9               = mode_All;         // FILTER: .+.

sinput ENUM_TRADE_COMMAND InpColorBuyCommand         = open_buy;         // Trade command:

sinput color              MonitoringColorBuy         = clrGold;          // Buy MonitoringColor, EA only monitors this lines color

sinput color              CrossedColorBuy            = clrGreen;         // CrossedColor, EA changes crossed lines color to this value

sinput bool               EnableAlertsBuy            = false;            // EnableAlertsBuy

sinput bool               EnableNotificationsBuy     = false;            // EnableNotificationsBuy

sinput bool               EnableEmailsBuy            = false;            // EnableEmailsBuy

sinput group "----------------- Distance: ----------------------------"

sinput double             InpObjStepStopUp           = 0;                // Obj: Distance from price to object, in pips

sinput group "----------------- Sell::DOWN ---------------------------"

sinput ENUM_MODE          FilterLine_10              = mode_All;         // FILTER: .+.

sinput ENUM_TRADE_COMMAND InpColorSellCommand        = open_sell;        // Trade command:

sinput color              MonitoringColorSell        = clrYellow;        // Sell MonitoringColor, EA only monitors this lines color

sinput color              CrossedColorSell           = clrGreen;         // CrossedColor, EA changes crossed lines color to this value

sinput bool               EnableAlertsSell           = false;            // EnableAlertsSell

sinput bool               EnableNotificationsSell    = false;            // EnableNotificationsSell

sinput bool               EnableEmailsSell           = false;            // EnableEmailsSell

sinput group "----------------- Close Buy::UP ------------------------"

sinput ENUM_MODE          FilterLine_11              = mode_All;         // FILTER: .+.

sinput ENUM_TRADE_COMMAND InpCloseBuyCommand         = close_buys;       // Trade command:

sinput color              MonitoringColorClosBuy     = clrOrangeRed;     // Close Buy MonitoringColor, EA only monitors this lines color

sinput color              CrossedColorClosBuy        = clrGreen;         // CrossedColor, EA changes crossed lines color to this value

sinput bool               EnableAlertsClosBuy        = false;            // EnableAlertsClosBuy

sinput bool               EnableNotificationsClosBuy = false;            // EnableNotificationsClosBuy

sinput bool               EnableEmailsClosBuy        = false;            // EnableEmailsClosBuy

sinput group "----------------- Distance: ----------------------------"

sinput double             InpObjStepStopDown         = 0;                // Obj: Distance from price to object, in pips

sinput group "----------------- Close Sell::DOWN ---------------------"

sinput ENUM_MODE          FilterLine_12              = mode_All;         // FILTER: .+.

sinput ENUM_TRADE_COMMAND InpCloseSellCommand        = close_sells;      // Trade command:

sinput color              MonitoringColorClosSell    = clrMagenta;       // Close Sell MonitoringColor, EA only monitors this lines color

sinput color              CrossedColorClosSell       = clrGreen;         // CrossedColor, EA changes crossed lines color to this value

sinput bool               EnableAlertsClosSell       = false;            // EnableAlertsClosSell

sinput bool               EnableNotificationsClosSell= false;            // EnableNotificationsClosSell

sinput bool               EnableEmailsClosSell       = false;            // EnableEmailsClosSell

sinput group "----------------- Button: ------------------------------"

sinput ENUM_TRADE_COMMAND InpTradeCommandBuy         = open_buy;         // Obj(BUY):

sinput ENUM_TRADE_COMMAND InpTradeCommandSell        = open_sell;        // Obj(SELL):

sinput ENUM_TRADE_COMMAND InpTradeCommandClosBuy     = close_buys;       // Obj(ClosBuy):

sinput ENUM_TRADE_COMMAND InpTradeCommandClosSell    = close_sells;      // Obj(ClosSell):

sinput group "----------------- Trade Line UP ------------------------"

sinput ENUM_MODE          FilterLine_13              = mode_All;         // FILTER: .+.

sinput ENUM_TIMEFRAMES    InpPeriod_Up               = PERIOD_CURRENT;   // Period

sinput ENUM_TRADE_COMMAND InpCommandOpenedUp         = open_buy;         // Trade command:

sinput string             InpNameAverageUp           = "Line Up";        // Line Name UP(Horizontal Line or Trend Line)

sinput ENUM_TRADE_COMMAND InpCommandOpenedUpLow      = open_sell;        // Trade command:

sinput bool               InpDelLineUp               = false;            // Delete (Horizontal Line or Trend Line)

sinput double             InpObjStepTradeUp          = 0;                // Obj: Distance from price to object, in pips

sinput color              InpObjAverageclrUp         = clrBlue;          // EA only monitors this lines color

sinput group "----------------- Trade Line_2 UP ----------------------"

sinput ENUM_MODE          FilterLine_15              = mode_All;         // FILTER: .+.

sinput ENUM_TIMEFRAMES    InpPeriod_Up_2             = PERIOD_CURRENT;   // Period

sinput ENUM_TRADE_COMMAND InpCommandOpenedUp_2       = open_buy;         // Trade command:

sinput string             InpNameAverageUp_2         = "Line_2 Up";      // Line Name UP(Horizontal Line or Trend Line)

sinput ENUM_TRADE_COMMAND InpCommandOpenedUpLow_2    = open_sell;        // Trade command:

sinput bool               InpDelLineUp_2             = false;            // Delete (Horizontal Line or Trend Line)

sinput double             InpObjStepTradeUp_2        = 0;                // Obj: Distance from price to object, in pips

sinput color              InpObjAverageclrUp_2       = clrBlue;          // EA only monitors this lines color

sinput group "----------------- Trade Line DOWN ----------------------"

sinput ENUM_MODE          FilterLine_14              = mode_All;         // FILTER: .+.

sinput ENUM_TIMEFRAMES    InpPeriod_Down             = PERIOD_CURRENT;   // Period

sinput ENUM_TRADE_COMMAND InpCommandOpenedDown       = open_buy;         // Trade command:

sinput string             InpNameAverageDown         = "Line Down";      // Line Name DOWN(Horizontal Line or Trend Line)

sinput ENUM_TRADE_COMMAND InpCommandOpenedDownLow    = open_sell;        // Trade command:

sinput bool               InpDelLineDown             = false;            // Delete (Horizontal Line or Trend Line)

sinput double             InpObjStepTradeDown        = 0;                // Obj: Distance from price to object, in pips

sinput color              InpObjAverageclrDown       = clrRed;           // EA only monitors this lines color

sinput group "----------------- Trade Line_2 DOWN --------------------"

sinput ENUM_MODE          FilterLine_16              = mode_All;         // FILTER: .+.

sinput ENUM_TIMEFRAMES    InpPeriod_Down_2           = PERIOD_CURRENT;   // Period

sinput ENUM_TRADE_COMMAND InpCommandOpenedDown_2     = open_buy;         // Trade command:

sinput string             InpNameAverageDown_2       = "Line_2 Down";    // Line Name DOWN(Horizontal Line or Trend Line)

sinput ENUM_TRADE_COMMAND InpCommandOpenedDownLow_2  = open_sell;        // Trade command:

sinput bool               InpDelLineDown_2           = false;            // Delete (Horizontal Line or Trend Line)

sinput double             InpObjStepTradeDown_2      = 0;                // Obj: Distance from price to object, in pips

sinput color              InpObjAverageclrDown_2     = clrRed;           // EA only monitors this lines color

sinput group "----------------- FILTER:Command -----------------------"

sinput ENUM_FILTR_COMMAND ObjFilterStopUp            = Filter_Off;       // Filter

sinput string             InpNameupper               = "8=88 Up";       // FILTER Upper (Horizontal Line or Trend Line)

sinput ENUM_FILTR_COMMAND ObjFilterStopLow           = Filter_Off;       // Filter

sinput string             InpNamelower               = "8=88 Low";      // FILTER Lower (Horizontal Line or Trend Line)

sinput group "----------------- :(+): Line:Middle --------------------"

sinput string             InpNameaverageUp           = "Middle:Up";      // FILTER Up (Horizontal Line or Trend Line)

sinput string             InpNameaverageLow          = "Middle:Low";     // FILTER Low (Horizontal Line or Trend Line)

//+------------------------------------------------------------------+

ushort   InpSignalsFrequency=1;  // Search signals, in seconds (min value "1")

uint     maxLimits=1;            // >;-2> >78F88 B:@KBL 2 >4=C AB>@>=C

uint     SLEEPTIME=1;            // @5<O ?0C7K <564C ?>2B>@0<8 2 A5:C=40E

uint     Deviation=10;           // B:;>=5=85 F5=K

bool     ObjRevers=false;        // Revers

//+------------------------------------------------------------------+

bool     ExtTurnOff              = false;    //

bool     ExttplAll               = false;    //

bool     ExtUpName               = false;    //

bool     ExtDownName             = false;    //

bool     ClExtUpName             = false;    //

bool     ClExtDownName           = false;    //

bool     ExtUpNameColor          = false;    //

bool     ExtDownNameColor        = false;    //

bool     ClExtUpNameColor        = false;    //

bool     ClExtDownNameColor      = false;    //

bool     ExtNeedCloseBuy         = false;    //

bool     ExtNeedCloseSell        = false;    //

bool     ExtNeedCloseAll         = false;    //

bool     ExtNeedOpenBuy          = false;    //

bool     ExtNeedOpenSell         = false;    //

bool     ExtAllCloseAll          = false;    //

bool     ExtCloseAll             = false;    //

bool     ExtFilter_Off           = false;    //

bool     ExtFilter_Stop          = false;    //

bool     ExtFilter_All           = false;    //

bool     ExMode_All              = false;    //

bool     ExMode_Ind              = false;    //

bool     ExtUpNameUp             = false;    //

bool     ExtDownNameDown         = false;    //

bool     ExtUpNameUp_2           = false;    //

bool     ExtDownNameDown_2       = false;    //

ENUM_TIMEFRAMES TimeFrame=PERIOD_CURRENT;    //

string   m_name[]= {"BUY","SELL","BUY_Close","SELL_Close","CLOSE_ALL","without '.tpl'"};

//+------------------------------------------------------------------+

//| MACD Sample expert class                                         |

//+------------------------------------------------------------------+

class CSampleExpert

  {

protected:

   double            m_adjusted_point;             // point value adjusted for 3 or 5 points

   CTrade            m_trade;                      // trading object

   CSymbolInfo       m_symbol;                     // symbol info object

   CPositionInfo     m_position;                   // trade position object

   CAccountInfo      m_account;                    // account info wrapper

   //--- Logic vars

   CArrayString      m_objectNamesBuy;

   CArrayString      m_objectNamesSell;

   CArrayString      m_objectNamesClosBuy;

   CArrayString      m_objectNamesClosSell;

   //--- indicators

   int               m_handle_macd_1;              // indicator handle

   int               m_handle_macd_2;              // indicator handle

   //--- indicator buffers

   double            m_buff_MACD_main_1[];         // indicator main buffer

   double            m_buff_MACD_signal_1[];       // indicator signal buffer

   double            m_buff_MACD_main_2[];         // indicator main buffer

   double            m_buff_MACD_signal_2[];       // indicator signal buffer

   //--- indicator data for processing

   double            m_macd_current_1;

   double            m_signal_current_1;

   double            m_macd_current_2;

   double            m_signal_current_2;



public:

                     CSampleExpert(void);

                    ~CSampleExpert(void);

   bool              Init(void);

   void              Deinit(void);

   bool              Processing(void);

   void              ProcessingFilter(void);

   void              ProcessingUp(void);

   void              ProcessingDown(void);

   bool              Processing_1(void);

   bool              Processing_2(void);

   bool              ProcessingBuy(void);

   bool              ProcessingSell(void);

   bool              ProcessingClosBuy(void);

   bool              ProcessingClosSell(void);



protected:

   //--- Inline functions

   string            FormatPrice(double price) { return StringFormat("%."+(string)m_symbol.Digits()+"f",price); };

   bool              IsNewBar() { return iVolume(NULL,0,0)==1; };

   double            TradeSizeOptimized(void);

   double            OptimizedBuy(void);

   double            OptimizedSell(void);

   double            m_obj_trailing_stopOpen;      // Obj: Trailing Stop   -> double

   double            m_obj_trailing_stepOpen;      // Obj: Trailing Step   -> double

   double            m_obj_trailing_stopClos;      // Obj: Trailing Stop   -> double

   double            m_obj_trailing_stepClos;      // Obj: Trailing Step   -> double

   double            m_obj_trailing_stopOpenColor; // Obj: Trailing Stop   -> double

   double            m_obj_trailing_stopClosColor; // Obj: Trailing Stop   -> double

   double            m_obj_trailing_Up;            // Obj: Trailing Stop   -> double

   double            m_obj_trailing_Down;          // Obj: Trailing Step   -> double

   double            m_obj_trailing_Up_2;          // Obj: Trailing Stop   -> double

   double            m_obj_trailing_Down_2;        // Obj: Trailing Step   -> double

   double            m_obj_up_priceOpen;           //

   double            m_obj_down_priceOpen;         //

   double            m_obj_up_priceClos;           //

   double            m_obj_down_priceClos;         //

   datetime          m_obj_last_trailingOpen;      // "0" -> D'1970.01.01 00:00';

   datetime          m_prev_barsOpen;              // "0" -> D'1970.01.01 00:00';

   datetime          m_obj_last_trailingClos;      // "0" -> D'1970.01.01 00:00';

   datetime          m_prev_barsClos;              // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastSignalsRx;             // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBarsRx;                // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastSignalsSx;             // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBarsSx;                // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastSignalsRz;             // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBarsRz;                // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastSignalsSz;             // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBarsSz;                // "0" -> D'1970.01.01 00:00';

   datetime          ExtVLinetime;                 // "0" -> D'1970.01.01 00:00';

   datetime          ExtVLinetimeD;                // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBars_1;                // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBars_2;                // "0" -> D'1970.01.01 00:00';

   datetime          InpHoursTo;                   // "0" -> D'1970.01.01 00:00';

   datetime          InpHoursTo_1;                 // "0" -> D'1970.01.01 00:00';

   datetime          HoursTo2;                     // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastUpper;                 // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevUpper;                 // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastAverage;               // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevAverage;               // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastLower;                 // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevLower;                 // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBarsUp;                // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastAverageUp;             // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBarsDown;              // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastAverageDown;           // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBarsUp_2;              // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastAverageUp_2;           // "0" -> D'1970.01.01 00:00';

   datetime          ExtPrevBarsDown_2;            // "0" -> D'1970.01.01 00:00';

   datetime          ExtLastAverageDown_2;         // "0" -> D'1970.01.01 00:00';

   //--- Logic functions

   int               FindActiveObjectsBuy(void);

   bool              ActiveObjectBuy(string objName);

   bool              PriceCrossedBuy(string objName);

   void              NotifyCrossingBuy(string objName);

   int               FindActiveObjectsSell();

   bool              ActiveObjectSell(string objName);

   bool              PriceCrossedSell(string objName);

   void              NotifyCrossingSell(string objName);

   int               FindActiveObjectsClosBuy(void);

   bool              ActiveObjectClosBuy(string objName);

   bool              PriceCrossedClosBuy(string objName);

   void              NotifyCrossingClosBuy(string objName);

   int               FindActiveObjectsClosSell();

   bool              ActiveObjectClosSell(string objName);

   bool              PriceCrossedClosSell(string objName);

   void              NotifyCrossingClosSell(string objName);

   void              NotifyAllCloseAll(string objName);

   void              NotifyLongShortClos(string objName);

   bool              InitIndicators_1(void);

   bool              InitIndicators_2(void);

   bool              LongOpened_1(void);

   bool              ShortOpened_1(void);

   bool              LongOpened_2(void);

   bool              ShortOpened_2(void);

   bool              InpTradeCommand(int i);

   bool              ProfitTarget(void);

   bool              ProfitTarget_1(void);

   bool              ProfitTarget_2(void);

   bool              ProfitOnTick(void);

   bool              LongObjClosed(void);

   bool              ShortObjClosed(void);

   bool              LongShortObjClosed(void);

   bool              LongObjOpened(void);

   bool              ShortObjOpened(void);

   bool              RefreshRates(void);

   bool              FreezeStopsLevels(double &level);

   void              ClosePositions(const ENUM_POSITION_TYPE pos_type,const double level);

   void              CloseAll(void);

   void              CloseAllProfit(void);

   void              CloseAllLoss(void);

   void              ClosePosition(const string symbol);

   bool              InitTrade(const string symbol);

   bool              IsFillingTypeAllowed(string symbol,int fill_type);

   void              DeleteChart(void);

   void              DeleteChart_1(void);

   bool              OrderCloseByTicket(bool &Signal,const string symbol,ulong ticket,uint deviation);

   void              ButtonCreate(string name,int Xdist,int Ydist,int Xsize,int Ysize,int FONTSIZE=12);

   bool              ButtonOnTick(void);

   void              ObjVLinetime(void);

   void              ObjVLinetimeD(void);

   void              OnTickObjTrailingOpen(void);

   void              ObjTrailingOpen(void);

   bool              HLineMove(const long chart_ID=0,const string name="HLine",double price=0);

   void              OnTickObjTrailingClos(void);

   void              ObjTrailingClos(void);

   bool              Obj_SELLOpen(void);

   bool              Obj_BUYOpen(void);

   bool              Obj_SELLClos(void);

   bool              Obj_BUYClos(void);

   bool              Obj_SELLOpenColor(string objName);

   bool              Obj_BUYOpenColor(string objName);

   bool              Obj_SELLClosColor(string objName);

   bool              Obj_BUYClosColor(string objName);

   bool              Obj_AverageUp(void);

   bool              Obj_AverageDown(void);

   bool              Obj_AverageUp_2(void);

   bool              Obj_AverageDown_2(void);

   void              OnTickInpNameRx(void);

   void              OnTickInpNameSx(void);

   void              OnTickInpNameRz(void);

   void              OnTickInpNameSz(void);

   bool              TrendOpenedUp(void);

   bool              TrendOpenedDown(void);

   bool              TrendOpenedUp_2(void);

   bool              TrendOpenedDown_2(void);

   void              OnTickInpLower(void);

   void              OnTickInpUpper(void);

   void              OnTickBalance(void);

   int               CreateHline(long ch_id,int sub_window,string name,double price,color clr,ENUM_LINE_STYLE style,

                                 int width,bool back,bool selectable,bool selected,bool hidden,long z_order);

  };

CSampleExpert ExtExpert;

//+------------------------------------------------------------------+

//| Constructor                                                      |

//+------------------------------------------------------------------+

CSampleExpert::CSampleExpert(void) : m_adjusted_point(0),

   m_handle_macd_1(INVALID_HANDLE),

   m_handle_macd_2(INVALID_HANDLE),

   m_macd_current_1(0),

   m_signal_current_1(0),

   m_macd_current_2(0),

   m_signal_current_2(0),

   m_obj_trailing_stopOpen(0),

   m_obj_trailing_stepOpen(0),

   m_obj_last_trailingOpen(0),

   m_prev_barsOpen(0),

   m_obj_up_priceOpen(0),

   m_obj_down_priceOpen(0),

   m_obj_trailing_stopClos(0),

   m_obj_trailing_stepClos(0),

   m_obj_last_trailingClos(0),

   m_obj_trailing_stopOpenColor(0),

   m_obj_trailing_stopClosColor(0),

   m_obj_trailing_Up(0),

   m_obj_trailing_Down(0),

   m_obj_trailing_Up_2(0),

   m_obj_trailing_Down_2(0),

   m_prev_barsClos(0),

   ExtLastSignalsRx(0),

   ExtPrevBarsRx(0),

   ExtLastSignalsSx(0),

   ExtPrevBarsSx(0),

   ExtLastSignalsRz(0),

   ExtPrevBarsRz(0),

   ExtLastSignalsSz(0),

   ExtPrevBarsSz(0),

   ExtVLinetime(0),

   ExtVLinetimeD(0),

   ExtPrevBars_1(0),

   ExtPrevBars_2(0),

   InpHoursTo(0),

   InpHoursTo_1(0),

   HoursTo2(0),

   ExtLastUpper(0),

   ExtPrevUpper(0),

   ExtLastAverage(0),

   ExtPrevAverage(0),

   ExtLastLower(0),

   ExtPrevLower(0),

   ExtPrevBarsUp(0),

   ExtLastAverageUp(0),

   ExtPrevBarsDown(0),

   ExtLastAverageDown(0),

   ExtPrevBarsUp_2(0),

   ExtLastAverageUp_2(0),

   ExtPrevBarsDown_2(0),

   ExtLastAverageDown_2(0),

   m_obj_up_priceClos(0),

   m_obj_down_priceClos(0)

  {

   ArraySetAsSeries(m_buff_MACD_main_1,true);

   ArraySetAsSeries(m_buff_MACD_signal_1,true);

   ArraySetAsSeries(m_buff_MACD_main_2,true);

   ArraySetAsSeries(m_buff_MACD_signal_2,true);

  }

//+------------------------------------------------------------------+

//| Destructor                                                       |

//+------------------------------------------------------------------+

CSampleExpert::~CSampleExpert(void)

  {

  }

//+------------------------------------------------------------------+

//| Script program start function                                    |

//+------------------------------------------------------------------+

bool  CSampleExpert::InpTradeCommand(int i)

  {

   bool res=false;

//---

   switch(i)

     {

      case Turn_Off:// TURN OFF

         ExtTurnOff=true;

         break;

      case tpl:// '.tpl' All

         ExttplAll=true;

         DeleteChart();

         break;

      case Close_AllExt:// CloseAll + ExpertRemoves

         ExtAllCloseAll=true;

         NotifyAllCloseAll("");

         ExpertRemove();

         DeleteChart();

         PlaySound("expert.wav");

         break;

      case Close_All_All:// CloseAll

         ExtAllCloseAll=true;

         NotifyAllCloseAll("");

         break;

      case  close_tpl_b:// Close Sell + Open Buy + '.tpl'

         ExtNeedCloseSell=true;

         NotifyCrossingClosSell("");

         ExtNeedOpenBuy=true;

         NotifyCrossingBuy("");

         ExpertRemove();

         DeleteChart_1();

         PlaySound("alert.wav");

         break;

      case  close_tpl_s:// Close Buy + Open Sell + '.tpl'

         ExtNeedCloseBuy=true;

         NotifyCrossingClosBuy("");

         ExtNeedOpenSell=true;

         NotifyCrossingSell("");

         ExpertRemove();

         DeleteChart_1();

         PlaySound("alert.wav");

         break;

      case close_all_tpl:// Close Buy's Sell's + '.tpl'

         ExtNeedCloseAll=true;

         NotifyLongShortClos("");

         ExpertRemove();

         DeleteChart_1();

         PlaySound("alert.wav");

         break;

      case  UpName:// Line Open UpName

         ExtUpName=true;

         Obj_BUYOpen();

         ExtUpNameColor=true;

         Obj_BUYOpenColor("BUYOpenColor");

         ExtUpNameUp=true;

         Obj_AverageUp();

         break;

      case  DownName:// Line Open DownName

         ExtDownName=true;

         Obj_SELLOpen();

         ExtDownNameColor=true;

         Obj_SELLOpenColor("SELLOpenColor");

         ExtDownNameDown=true;

         Obj_AverageDown();

         break;

      case  UpName_s:// Line Open UpName + Open Sell

         ExtUpName=true;

         Obj_BUYOpen();

         ExtUpNameColor=true;

         Obj_BUYOpenColor("BUYOpenColor");

         ExtUpNameUp=true;

         Obj_AverageUp();

         ExtNeedOpenSell=true;

         NotifyCrossingSell("");

         break;

      case  UpName_b:// Line Open UpName + Open Buy

         ExtUpName=true;

         Obj_BUYOpen();

         ExtUpNameColor=true;

         Obj_BUYOpenColor("BUYOpenColor");

         ExtUpNameUp=true;

         Obj_AverageUp();

         ExtNeedOpenBuy=true;

         NotifyCrossingBuy("");

         break;

      case  DownName_b:// Line Open DownName + Open Buy

         ExtDownName=true;

         Obj_SELLOpen();

         ExtDownNameColor=true;

         Obj_SELLOpenColor("SELLOpenColor");

         ExtDownNameDown=true;

         Obj_AverageDown();

         ExtNeedOpenBuy=true;

         NotifyCrossingBuy("");

         break;

      case  DownName_s:// Line Open DownName + Open Sell

         ExtDownName=true;

         Obj_SELLOpen();

         ExtDownNameColor=true;

         Obj_SELLOpenColor("SELLOpenColor");

         ExtDownNameDown=true;

         Obj_AverageDown();

         ExtNeedOpenSell=true;

         NotifyCrossingSell("");

         break;

      case  ClUpName:// Line Close UpName

         ClExtUpName=true;

         Obj_BUYClos();

         ClExtUpNameColor=true;

         Obj_BUYClosColor("BUYClosColor");

         ExtUpNameUp_2=true;

         Obj_AverageUp_2();

         break;

      case  ClDownName:// Line Close DownName

         ClExtDownName=true;

         Obj_SELLClos();

         ClExtDownNameColor=true;

         Obj_SELLClosColor("SELLClosColor");

         ExtDownNameDown_2=true;

         Obj_AverageDown_2();

         break;

      case  ClUpName_s:// Line Close UpName + Open Sell

         ClExtUpName=true;

         Obj_BUYClos();

         ClExtUpNameColor=true;

         Obj_BUYClosColor("BUYClosColor");

         ExtUpNameUp_2=true;

         Obj_AverageUp_2();

         ExtNeedOpenSell=true;

         NotifyCrossingSell("");

         break;

      case  ClUpName_b:// Line Close UpName + Open Buy

         ClExtUpName=true;

         Obj_BUYClos();

         ClExtUpNameColor=true;

         Obj_BUYClosColor("BUYClosColor");

         ExtUpNameUp_2=true;

         Obj_AverageUp_2();

         ExtNeedOpenBuy=true;

         NotifyCrossingBuy("");

         break;

      case  ClDownName_b:// Line Close DownName + Open Buy

         ClExtDownName=true;

         Obj_SELLClos();

         ClExtDownNameColor=true;

         Obj_SELLClosColor("SELLClosColor");

         ExtDownNameDown_2=true;

         Obj_AverageDown_2();

         ExtNeedOpenBuy=true;

         NotifyCrossingBuy("");

         break;

      case  ClDownName_s:// Line Close DownName + Open Sell

         ClExtDownName=true;

         Obj_SELLClos();

         ClExtDownNameColor=true;

         Obj_SELLClosColor("SELLClosColor");

         ExtDownNameDown_2=true;

         Obj_AverageDown_2();

         ExtNeedOpenSell=true;

         NotifyCrossingSell("");

         break;

      case  close_buys:// Close All Buy's

         ExtNeedCloseBuy=true;

         NotifyCrossingClosBuy("");

         break;

      case  close_sells:// Close All Sell's

         ExtNeedCloseSell=true;

         NotifyCrossingClosSell("");

         break;

      case close_all:// Close All Buy's and Sell's

         ExtNeedCloseAll=true;

         NotifyLongShortClos("");

         break;

      case open_buy:// Open  Buy

         ExtNeedOpenBuy=true;

         NotifyCrossingBuy("");

         break;

      case open_sell:// Open  Sell

         ExtNeedOpenSell=true;

         NotifyCrossingSell("");

         break;

      case  close_open_b:// Close Sell + Open Buy

         ExtNeedCloseSell=true;

         NotifyCrossingClosSell("");

         ExtNeedOpenBuy=true;

         NotifyCrossingBuy("");

         break;

      case  close_open_s:// Close Buy + Open Sell

         ExtNeedCloseBuy=true;

         NotifyCrossingClosBuy("");

         ExtNeedOpenSell=true;

         NotifyCrossingSell("");

         break;

      case  open_buy_sell:// Open  Buy and Sell

         ExtNeedOpenBuy=true;

         NotifyCrossingBuy("");

         ExtNeedOpenSell=true;

         NotifyCrossingSell("");

         break;

     }

   res=true;

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Calculate optimal lot size                                       |

//+------------------------------------------------------------------+

double CSampleExpert::TradeSizeOptimized(void)

  {

   double price=0.0;

   double margin=0.0;

//--- select lot size

   if(!SymbolInfoDouble(_Symbol,SYMBOL_ASK,price))

      return(0.0);

   if(!OrderCalcMargin(ORDER_TYPE_BUY,_Symbol,1.0,price,margin))

      return(0.0);

   if(margin<=0.0)

      return(0.0);

   double lot=NormalizeDouble(AccountInfoDouble(ACCOUNT_MARGIN_FREE)*MaximumRisk/margin,2);

//--- calculate number of losses orders without a break

   if(DecreaseFactor>0)

     {

      //--- select history for access

      HistorySelect(0,TimeCurrent());

      //---

      int    orders=HistoryDealsTotal();  // total history deals

      int    losses=0;                    // number of losses orders without a break

      for(int i=orders-1; i>=0; i--)

        {

         ulong ticket=HistoryDealGetTicket(i);

         if(ticket==0)

           {

            Print("HistoryDealGetTicket failed, no trade history");

            break;

           }

         //--- check symbol

         if(HistoryDealGetString(ticket,DEAL_SYMBOL)!=_Symbol)

            continue;

         //--- check Expert Magic number

         if(HistoryDealGetInteger(ticket,DEAL_MAGIC)!=MACD_MAGIC)

            continue;

         //--- check profit

         double profit=HistoryDealGetDouble(ticket,DEAL_PROFIT);

         if(profit>0.0)

            break;

         if(profit<0.0)

            losses++;

        }

      //---

      if(losses>1)

         lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);

     }

//--- normalize and check limits

   double stepvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);

   lot=stepvol*NormalizeDouble(lot/stepvol,0);

   double minvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);

   if(lot<minvol)

      lot=minvol;

   double maxvol=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);

   if(lot>maxvol)

      lot=maxvol;

//--- return trading volume

   return(lot);

  }

//+------------------------------------------------------------------+

//| Calculate optimal lot size                                       |

//+------------------------------------------------------------------+

double CSampleExpert::OptimizedBuy(void)

  {

   double PROFIT_BUY=0.00;

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+m_position.Select(Symbol());

           }

        }

     }

   double Lots=MaximumRisk;

   double ab=PROFIT_BUY;

   switch(InpLotRisk)

     {

      case Lot:

         Lots=MaximumRisk;

         break;

      case Lotx2:

         if(ab>0 && ab<=1)

            Lots=MaximumRisk*2;

         if(ab>1 && ab<=2)

            Lots=MaximumRisk*4;

         if(ab>2 && ab<=3)

            Lots=MaximumRisk*8;

         if(ab>3)

            Lots=MaximumRisk*16;

         break;

      case Risk:

         Lots=TradeSizeOptimized();

         break;

     }

   return(Lots);

  }

//+------------------------------------------------------------------+

//| Calculate optimal lot size                                       |

//+------------------------------------------------------------------+

double CSampleExpert::OptimizedSell(void)

  {

   double PROFIT_SELL=0.00;

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         if(m_position.PositionType()==POSITION_TYPE_SELL)

           {

            PROFIT_SELL=PROFIT_SELL+m_position.Select(Symbol());

           }

        }

     }

   double Lots=MaximumRisk;

   double ab=PROFIT_SELL;

   switch(InpLotRisk)

     {

      case Lot:

         Lots=MaximumRisk;

         break;

      case Lotx2:

         if(ab>0 && ab<=1)

            Lots=MaximumRisk*2;

         if(ab>1 && ab<=2)

            Lots=MaximumRisk*4;

         if(ab>2 && ab<=3)

            Lots=MaximumRisk*8;

         if(ab>3)

            Lots=MaximumRisk*16;

         break;

      case Risk:

         Lots=TradeSizeOptimized();

         break;

     }

   return(Lots);

  }

//+------------------------------------------------------------------+

//| Check for long position closing                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::ProfitTarget(void)

  {

   bool res=false;

   if(AccountInfoDouble(ACCOUNT_EQUITY)<=TargetLoss ||

      AccountInfoDouble(ACCOUNT_EQUITY)>=TargetProfit)

     {

      ExtAllCloseAll=true;

      NotifyAllCloseAll("");

      ExpertRemove();

      DeleteChart();

      PlaySound("expert.wav");

      res=true;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check ProfitTarget closing                                       |

//+------------------------------------------------------------------+

bool CSampleExpert::ProfitTarget_1(void)

  {

   bool res=false;

   double growth=0.00;

   static double bal=0.00;

   bal=AccountInfoDouble(ACCOUNT_BALANCE);

   growth=growth+bal-AccountInfoDouble(ACCOUNT_EQUITY);

   if(growth<=-TargetProfit_1 || growth>=TargetLoss_1)

     {

      ExtAllCloseAll=true;

      NotifyAllCloseAll("");

      PlaySound("request.wav");

      res=true;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check ProfitTarget closing                                       |

//+------------------------------------------------------------------+

bool CSampleExpert::ProfitTarget_2(void)

  {

   bool res=false;

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

           }

         else

           {

            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

           }

        }

     }

   double growth=0.00;

   static double balbuy=0.00;

   static double balsell=0.00;

   balbuy=PROFIT_BUY;

   balsell=PROFIT_SELL;

   growth=growth+balbuy+balsell;

   if(growth>=TargetProfit_2 || growth<=-TargetLoss_2)

     {

      ExtNeedCloseAll=true;

      NotifyLongShortClos("");

      PlaySound("request.wav");

      res=true;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for long position closing                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::ProfitOnTick(void)

  {

   bool res=false;

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

           }

         else

           {

            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

           }

        }

     }

   for(int w=PositionsTotal()-1; w>=0; w--) // returns the number of current positions

      if(m_position.SelectByIndex(w)) // selects the position by index for further access to its properties

         if(m_position.Symbol()==m_symbol.Name())

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               if(PROFIT_BUY<-InpStopLoss || PROFIT_BUY>=InpTProfit) // if the profit

                 {

                  switch(InpProfitCommand)

                    {

                     case  tpl_b:

                        ExtNeedCloseBuy=true;

                        NotifyCrossingClosBuy("");

                        PlaySound("request.wav");

                        break;

                     case  tpl_s:

                        ExtNeedCloseBuy=true;

                        NotifyCrossingClosBuy("");

                        ExtNeedOpenSell=true;

                        NotifyCrossingSell("");

                        ExpertRemove();

                        DeleteChart_1();

                        PlaySound("alert.wav");

                        break;

                    }

                 }

               res=true;

              }

           }

   for(int u=PositionsTotal()-1; u>=0; u--) // returns the number of current positions

      if(m_position.SelectByIndex(u)) // selects the position by index for further access to its properties

         if(m_position.Symbol()==m_symbol.Name())

           {

            if(m_position.PositionType()==POSITION_TYPE_SELL)

              {

               if(PROFIT_SELL<-InpStopLoss || PROFIT_SELL>=InpTProfit) // if the profit

                 {

                  switch(InpProfitCommand)

                    {

                     case  tpl_b:

                        ExtNeedCloseSell=true;

                        NotifyCrossingClosSell("");

                        PlaySound("request.wav");

                        break;

                     case  tpl_s:

                        ExtNeedCloseSell=true;

                        NotifyCrossingClosSell("");

                        ExtNeedOpenBuy=true;

                        NotifyCrossingBuy("");

                        ExpertRemove();

                        DeleteChart_1();

                        PlaySound("alert.wav");

                        break;

                    }

                 }

               res=true;

              }

           }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for long position closing                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::LongObjClosed(void)

  {

   bool res=false;

//--- should it be closed?

   if(!ObjRevers)

     {

      if(ExtNeedCloseBuy)

        {

         //--- close position

         double level;

         if(FreezeStopsLevels(level))

            ClosePositions(POSITION_TYPE_BUY,level);

         //--- processed and cannot be modified

         res=true;

        }

      else

         ExtNeedCloseBuy=false;

     }

//--- result

   if(ObjRevers)

     {

      if(ExtNeedCloseBuy)

        {

         //--- close position

         double level;

         if(FreezeStopsLevels(level))

            ClosePositions(POSITION_TYPE_SELL,level);

         //--- processed and cannot be modified

         res=true;

        }

      else

         ExtNeedCloseBuy=false;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for short position closing                                 |

//+------------------------------------------------------------------+

bool CSampleExpert::ShortObjClosed(void)

  {

   bool res=false;

//--- should it be closed?

   if(!ObjRevers)

     {

      if(ExtNeedCloseSell)

        {

         //--- close position

         double level;

         if(FreezeStopsLevels(level))

            ClosePositions(POSITION_TYPE_SELL,level);

         //--- processed and cannot be modified

         res=true;

        }

      else

         ExtNeedCloseSell=false;

     }

//--- result

   if(ObjRevers)

     {

      if(ExtNeedCloseSell)

        {

         //--- close position

         double level;

         if(FreezeStopsLevels(level))

            ClosePositions(POSITION_TYPE_BUY,level);

         //--- processed and cannot be modified

         res=true;

        }

      else

         ExtNeedCloseSell=false;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for short position closing                                 |

//+------------------------------------------------------------------+

bool CSampleExpert::LongShortObjClosed(void)

  {

   bool res=false;

//--- should it be closed?

   if(ExtNeedCloseAll)

     {

      //--- close position

      double level;

      if(FreezeStopsLevels(level))

         ClosePositions(POSITION_TYPE_BUY,level);

      if(FreezeStopsLevels(level))

         ClosePositions(POSITION_TYPE_SELL,level);

      //--- processed and cannot be modified

      res=true;

     }

   else

      ExtNeedCloseAll=false;

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for long position opening                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::LongObjOpened(void)

  {

   bool res=false;

//--- check for long position (BUY) possibility

   if(!ObjRevers)

     {

      if(ExtNeedOpenBuy)

        {

         double price=m_symbol.Ask();

         for(uint i=0; i<maxLimits; i++)

           {

            //--- open position

            if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_BUY,OptimizedBuy(),price,0.0,0.0))

               printf("Position by %s to be opened",m_symbol.Name());

            else

              {

               printf("Error opening BUY position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());

               printf("Open parameters : price=%f,TP=%f",price,0.0);

              }

            res=true;

           }

         ExtNeedOpenBuy=false;

         //--- in any case we must exit from expert

        }

     }

//--- check for long position (BUY) possibility

   if(ObjRevers)

      if(ExtNeedOpenBuy)

        {

           {

            double price=m_symbol.Bid();

            for(uint y=0; y<maxLimits; y++)

              {

               if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_SELL,OptimizedSell(),price,0.0,0.0))

                  printf("Position by %s to be opened",m_symbol.Name());

               else

                 {

                  printf("Error opening SELL position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());

                  printf("Open parameters : price=%f,TP=%f",price,0.0);

                 }

               res=true;

              }

            ExtNeedOpenBuy=false;

            //--- in any case we must exit from expert

           }

        }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for short position opening                                 |

//+------------------------------------------------------------------+

bool CSampleExpert::ShortObjOpened(void)

  {

   bool res=false;

//--- check for short position (SELL) possibility

   if(!ObjRevers)

     {

      if(ExtNeedOpenSell)

        {

         double price=m_symbol.Bid();

         for(uint y=0; y<maxLimits; y++)

           {

            if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_SELL,OptimizedSell(),price,0.0,0.0))

               printf("Position by %s to be opened",m_symbol.Name());

            else

              {

               printf("Error opening SELL position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());

               printf("Open parameters : price=%f,TP=%f",price,0.0);

              }

            res=true;

           }

         ExtNeedOpenSell=false;

         //--- in any case we must exit from expert

        }

     }

//--- check for short position (SELL) possibility

   if(ObjRevers)

     {

      if(ExtNeedOpenSell)

        {

         double price=m_symbol.Ask();

         for(uint i=0; i<maxLimits; i++)

           {

            //--- open position

            if(m_trade.PositionOpen(m_symbol.Name(),ORDER_TYPE_BUY,OptimizedBuy(),price,0.0,0.0))

               printf("Position by %s to be opened",m_symbol.Name());

            else

              {

               printf("Error opening BUY position by %s : '%s'",m_symbol.Name(),m_trade.ResultComment());

               printf("Open parameters : price=%f,TP=%f",price,0.0);

              }

            res=true;

           }

         ExtNeedOpenSell=false;

         //--- in any case we must exit from expert

        }

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Refreshes the symbol quotes data                                 |

//+------------------------------------------------------------------+

bool CSampleExpert::RefreshRates(void)

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

     {

      Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");

      return(false);

     }

//--- protection against the return value of "zero"

   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)

     {

      Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");

      return(false);

     }

//---

   return(true);

  }

//+------------------------------------------------------------------+

//| Check Freeze and Stops levels                                    |

//+------------------------------------------------------------------+

bool CSampleExpert::FreezeStopsLevels(double &level)

  {

//--- check Freeze and Stops levels

   if(!RefreshRates() || !m_symbol.Refresh())

      return(false);

//--- FreezeLevel -> for pending order and modification

   double freeze_level=m_symbol.FreezeLevel()*m_symbol.Point();

   if(freeze_level==0.0)

      freeze_level=(m_symbol.Ask()-m_symbol.Bid())*3.0;

//--- StopsLevel -> for TakeProfit and StopLoss

   double stop_level=m_symbol.StopsLevel()*m_symbol.Point();

   if(stop_level==0.0)

      stop_level=(m_symbol.Ask()-m_symbol.Bid())*3.0;

   if(freeze_level<=0.0 || stop_level<=0.0)

      return(false);

   level=(freeze_level>stop_level)?freeze_level:stop_level;

   double spread=m_symbol.Spread()*m_adjusted_point;

   level=(level>spread)?level:spread;

//---

   return(true);

  }

//+------------------------------------------------------------------+

//| Close positions                                                  |

//+------------------------------------------------------------------+

void CSampleExpert::ClosePositions(const ENUM_POSITION_TYPE pos_type,const double level)

  {

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions

      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties

         if(m_position.Symbol()==m_symbol.Name()/* && m_position.Magic()==InpMagic*/)

            if(m_position.PositionType()==pos_type)

              {

               if(m_position.PositionType()==POSITION_TYPE_BUY)

                 {

                  bool take_profit_level=(m_position.TakeProfit()!=0.0 && m_position.TakeProfit()-m_position.PriceCurrent()>=level) || m_position.TakeProfit()==0.0;

                  bool stop_loss_level=(m_position.StopLoss()!=0.0 && m_position.PriceCurrent()-m_position.StopLoss()>=level) || m_position.StopLoss()==0.0;

                  if(take_profit_level && stop_loss_level)

                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol

                 }

               if(m_position.PositionType()==POSITION_TYPE_SELL)

                 {

                  bool take_profit_level=(m_position.TakeProfit()!=0.0 && m_position.PriceCurrent()-m_position.TakeProfit()>=level) || m_position.TakeProfit()==0.0;

                  bool stop_loss_level=(m_position.StopLoss()!=0.0 && m_position.StopLoss()-m_position.PriceCurrent()>=level) || m_position.StopLoss()==0.0;

                  if(take_profit_level && stop_loss_level)

                     m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbol

                 }

               PlaySound("ok.wav");

              }

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

void CSampleExpert::CloseAll(void)

  {

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions

      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties

        {

         ClosePosition(m_position.Symbol()); // close a position by the specified symbo

        }

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

void CSampleExpert::CloseAllProfit(void)

  {

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions

      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties

        {

         if(m_position.Commission()+m_position.Swap()+m_position.Profit()>0.0)

            ClosePosition(m_position.Symbol()); // close a position by the specified symbo

        }

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

void CSampleExpert::CloseAllLoss(void)

  {

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions

      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties

        {

         if(m_position.Commission()+m_position.Swap()+m_position.Profit()<0.0)

            ClosePosition(m_position.Symbol());  // close a position by the specified symbo

        }

  }

//+------------------------------------------------------------------+

//| Close selected position                                          |

//+------------------------------------------------------------------+

void CSampleExpert::ClosePosition(const string symbol)

  {

   if(InitTrade(symbol))

      m_trade.PositionClose(m_position.Ticket()); // close a position by the specified symbo

   PlaySound("ok.wav");

  }

//+------------------------------------------------------------------+

//| Init trade object                                                |

//+------------------------------------------------------------------+

bool CSampleExpert::InitTrade(const string symbol)

  {

   if(!m_symbol.Name(symbol)) // sets symbol name

      return(false);

//---

   if(IsFillingTypeAllowed(symbol,SYMBOL_FILLING_FOK))

      m_trade.SetTypeFilling(ORDER_FILLING_FOK);

   else

      if(IsFillingTypeAllowed(symbol,SYMBOL_FILLING_IOC))

         m_trade.SetTypeFilling(ORDER_FILLING_IOC);

      else

         m_trade.SetTypeFilling(ORDER_FILLING_RETURN);

//---

   return(true);

//---

  }

//+------------------------------------------------------------------+

//| Checks if the specified filling mode is allowed                  |

//+------------------------------------------------------------------+

bool CSampleExpert::IsFillingTypeAllowed(string symbol,int fill_type)

  {

//--- Obtain the value of the property that describes allowed filling modes

   int filling=(int)SymbolInfoInteger(symbol,SYMBOL_FILLING_MODE);

//--- Return true, if mode fill_type is allowed

   return((filling & fill_type)==fill_type);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

void CSampleExpert::DeleteChart(void)

  {

   long currChart,prevChart=ChartFirst();

   int i=0,limit=100;

   bool errTemplate;

   while(i<limit)

     {

      currChart=ChartNext(prevChart);

      if(TimeFrame!=PERIOD_CURRENT)

        {

         ChartSetSymbolPeriod(prevChart,ChartSymbol(prevChart),TimeFrame);

        }

      errTemplate=ChartApplyTemplate(prevChart,Template+".tpl");

      if(!errTemplate)

        {

         Print("Error ",ChartSymbol(prevChart),"-> ",GetLastError());

        }

      if(currChart<0)

         break;

      Print(i,ChartSymbol(currChart)," ID =",currChart);

      prevChart=currChart;

      i++;

     }

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

void CSampleExpert::DeleteChart_1(void)

  {

   long prevChart=0;

   bool errTemplate;

   if(TimeFrame!=PERIOD_CURRENT)

     {

      ChartSetSymbolPeriod(prevChart,ChartSymbol(prevChart),TimeFrame);

     }

   errTemplate=ChartApplyTemplate(prevChart,Template_1+".tpl");

   if(!errTemplate)

     {

      Print("Error ",ChartSymbol(prevChart),"-> ",GetLastError());

     }

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickObjTrailingOpen(void)

  {

//---

   if(Deviation>=10) // trailing no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-m_obj_last_trailingOpen>10)

        {

         if(RefreshRates())

            ObjTrailingOpen();

         else

            return;

         m_obj_last_trailingOpen=time_current;

        }

     }

//--- we work only at the time of the birth of new bar

   datetime time_0=iTime(m_symbol.Name(),Period(),0);

   if(time_0==m_prev_barsOpen)

      return;

   m_prev_barsOpen=time_0;

   if(Deviation<10) // trailing only at the time of the birth of new bar

     {

      if(RefreshRates())

         ObjTrailingOpen();

     }

  }

//+------------------------------------------------------------------+

//| Object Trailing                                                  |

//|   InpObjTrailingStop: min distance from price to object          |

//+------------------------------------------------------------------+

void CSampleExpert::ObjTrailingOpen(void)

  {

   if(InpObjTrailingStopOpen==0)

      return;

   double new_up_price        = 0.0;   //

   double new_down_price      = 0.0;   //

   double current_up_price    = ObjectGetDouble(0,InpObjUpNameOpen,OBJPROP_PRICE);

   double current_down_price  = ObjectGetDouble(0,InpObjDownNameOpen,OBJPROP_PRICE);

   if(current_up_price>0.0)

     {

      if(current_up_price>(m_symbol.Ask()+(m_obj_trailing_stopOpen+m_obj_trailing_stepOpen)))

        {

         m_obj_up_priceOpen=m_symbol.NormalizePrice(m_symbol.Ask()+m_obj_trailing_stopOpen);

         HLineMove(0,InpObjUpNameOpen,m_obj_up_priceOpen);

        }

     }

   if(current_down_price>0.0)

     {

      if(current_down_price<m_symbol.Bid()-(m_obj_trailing_stopOpen+m_obj_trailing_stepOpen))

        {

         m_obj_down_priceOpen=m_symbol.NormalizePrice(m_symbol.Bid()-m_obj_trailing_stopOpen);

         HLineMove(0,InpObjDownNameOpen,m_obj_down_priceOpen);

        }

     }

  }

//+------------------------------------------------------------------+

//| Move horizontal line                                             |

//+------------------------------------------------------------------+

bool CSampleExpert::HLineMove(const long chart_ID=0,const string name="HLine",double price=0)

  {

//--- if the line price is not set, move it to the current Bid price level

   if(!price)

      price=SymbolInfoDouble(Symbol(),SYMBOL_BID);

//--- reset the error value

   ResetLastError();

//--- move a horizontal line

   if(!ObjectMove(chart_ID,name,0,0,price))

     {

      Print(__FUNCTION__,

            ": failed to move the horizontal line! Error code = ",GetLastError());

      return(false);

     }

//--- successful execution

   return(true);

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickObjTrailingClos(void)

  {

//---

   if(Deviation>=10) // trailing no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-m_obj_last_trailingClos>10)

        {

         if(RefreshRates())

            ObjTrailingClos();

         else

            return;

         m_obj_last_trailingClos=time_current;

        }

     }

//--- we work only at the time of the birth of new bar

   datetime time_0=iTime(m_symbol.Name(),Period(),0);

   if(time_0==m_prev_barsClos)

      return;

   m_prev_barsClos=time_0;

   if(Deviation<10) // trailing only at the time of the birth of new bar

     {

      if(RefreshRates())

         ObjTrailingClos();

     }

  }

//+------------------------------------------------------------------+

//| Object Trailing                                                  |

//|   InpObjTrailingStop: min distance from price to object          |

//+------------------------------------------------------------------+

void CSampleExpert::ObjTrailingClos(void)

  {

   if(InpObjTrailingStopClos==0)

      return;

   double new_up_price        = 0.0;   //

   double new_down_price      = 0.0;   //

   double current_up_price    = ObjectGetDouble(0,InpObjUpNameClos,OBJPROP_PRICE);

   double current_down_price  = ObjectGetDouble(0,InpObjDownNameClos,OBJPROP_PRICE);

   if(current_up_price>0.0)

     {

      if(current_up_price>(m_symbol.Ask()+(m_obj_trailing_stopClos+m_obj_trailing_stepClos)))

        {

         m_obj_up_priceClos=m_symbol.NormalizePrice(m_symbol.Ask()+m_obj_trailing_stopClos);

         HLineMove(0,InpObjUpNameClos,m_obj_up_priceClos);

        }

     }

   if(current_down_price>0.0)

     {

      if(current_down_price<m_symbol.Bid()-(m_obj_trailing_stopClos+m_obj_trailing_stepClos))

        {

         m_obj_down_priceClos=m_symbol.NormalizePrice(m_symbol.Bid()-m_obj_trailing_stopClos);

         HLineMove(0,InpObjDownNameClos,m_obj_down_priceClos);

        }

     }

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_BUYOpen(void)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ExtUpName)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Long

      curPrice=lastme.bid;

      for(uint i=0; i<1; i++)

        {

         curPrice+=m_obj_trailing_stopOpen;

         if(curPrice-lastme.ask<minStop)

            continue;

         CreateHline(0,0,InpObjUpNameOpen,curPrice,InpObjUpclrOpen,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ExtUpName=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_SELLOpen(void)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ExtDownName)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Short

      curPrice=lastme.ask;

      for(uint i=0; i<1; i++)

        {

         curPrice-=m_obj_trailing_stopOpen;

         if(lastme.bid-curPrice<minStop)

            continue;

         CreateHline(0,0,InpObjDownNameOpen,curPrice,InpObjDownclrOpen,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ExtDownName=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_BUYClos(void)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ClExtUpName)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Long

      curPrice=lastme.bid;

      for(uint i=0; i<1; i++)

        {

         curPrice+=m_obj_trailing_stopClos;

         if(curPrice-lastme.ask<minStop)

            continue;

         CreateHline(0,0,InpObjUpNameClos,curPrice,InpObjUpclrClos,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ClExtUpName=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_SELLClos(void)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ClExtDownName)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Short

      curPrice=lastme.ask;

      for(uint i=0; i<1; i++)

        {

         curPrice-=m_obj_trailing_stopClos;

         if(lastme.bid-curPrice<minStop)

            continue;

         CreateHline(0,0,InpObjDownNameClos,curPrice,InpObjDownclrClos,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ClExtDownName=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_BUYOpenColor(string objName)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ExtUpNameColor)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Long

      curPrice=lastme.bid;

      for(uint i=0; i<1; i++)

        {

         curPrice+=m_obj_trailing_stopOpenColor;

         if(curPrice-lastme.ask<minStop)

            continue;

         CreateHline(0,0,objName,curPrice,MonitoringColorBuy,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ExtUpNameColor=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_SELLOpenColor(string objName)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ExtDownNameColor)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Short

      curPrice=lastme.ask;

      for(uint i=0; i<1; i++)

        {

         curPrice-=m_obj_trailing_stopOpenColor;

         if(lastme.bid-curPrice<minStop)

            continue;

         CreateHline(0,0,objName,curPrice,MonitoringColorSell,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ExtDownNameColor=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_BUYClosColor(string objName)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ClExtUpNameColor)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Long

      curPrice=lastme.bid;

      for(uint i=0; i<1; i++)

        {

         curPrice+=m_obj_trailing_stopClosColor;

         if(curPrice-lastme.ask<minStop)

            continue;

         CreateHline(0,0,objName,curPrice,MonitoringColorClosBuy,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ClExtUpNameColor=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_SELLClosColor(string objName)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ClExtDownNameColor)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Short

      curPrice=lastme.ask;

      for(uint i=0; i<1; i++)

        {

         curPrice-=m_obj_trailing_stopClosColor;

         if(lastme.bid-curPrice<minStop)

            continue;

         CreateHline(0,0,objName,curPrice,MonitoringColorClosSell,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ClExtDownNameColor=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_AverageUp(void)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ExtUpNameUp)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Long

      curPrice=lastme.bid;

      for(uint i=0; i<1; i++)

        {

         curPrice+=m_obj_trailing_Up;

         if(curPrice-lastme.ask<minStop)

            continue;

         CreateHline(0,0,InpNameAverageUp,curPrice,InpObjAverageclrUp,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ExtUpNameUp=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_AverageDown(void)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ExtDownNameDown)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Short

      curPrice=lastme.ask;

      for(uint i=0; i<1; i++)

        {

         curPrice-=m_obj_trailing_Down;

         if(lastme.bid-curPrice<minStop)

            continue;

         CreateHline(0,0,InpNameAverageDown,curPrice,InpObjAverageclrDown,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ExtDownNameDown=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_AverageUp_2(void)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ExtUpNameUp_2)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Long

      curPrice=lastme.bid;

      for(uint i=0; i<1; i++)

        {

         curPrice+=m_obj_trailing_Up_2;

         if(curPrice-lastme.ask<minStop)

            continue;

         CreateHline(0,0,InpNameAverageUp_2,curPrice,InpObjAverageclrUp_2,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ExtUpNameUp_2=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

bool CSampleExpert::Obj_AverageDown_2(void)

  {

   bool res=false;

// F5=0 4;O 2KAB02;5=8O >@45@>2 A5B:8

   if(ExtDownNameDown_2)

     {

      double curPrice;

      // B5:CI0O F5=0 ?> 8=AB@C<5=BC

      MqlTick lastme;

      SymbolInfoTick(m_symbol.Name(),lastme);

      // 5A;8 B5:CI59 F5=K ?>;CG8BL =5 C40;>AL, >B<5=O5< 2KAB02;5=85 A5B:8

      if(lastme.bid==0)

        {

         return(true);

        }

      // <8=8<0;L=>5 @0AAB>O=85 >B F5=K, =0 :>B>@>< <>6=> AB028BL AB>? ;>AAK

      double minStop=SymbolInfoDouble(m_symbol.Name(),SYMBOL_POINT)*SymbolInfoInteger(m_symbol.Name(),SYMBOL_TRADE_STOPS_LEVEL);

      // 2KAB02;O5< >@45@0 2 Short

      curPrice=lastme.ask;

      for(uint i=0; i<1; i++)

        {

         curPrice-=m_obj_trailing_Down_2;

         if(lastme.bid-curPrice<minStop)

            continue;

         CreateHline(0,0,InpNameAverageDown_2,curPrice,InpObjAverageclrDown_2,0,0,1,1,1,1,2);

         PlaySound("tick.wav");

        }

      res=true;

     }

   else

      ExtDownNameDown_2=false;

//---

   return(res);

  }

//+------------------------------------------------------------------+

//|  !>740=85 3>@87>=B0;L=>3>, F5=>2>3> C@>2=O                       |

//+------------------------------------------------------------------+

int CSampleExpert::CreateHline(long ch_id,int sub_window,

                               string name,double price,

                               color clr,ENUM_LINE_STYLE style,

                               int width,bool back,

                               bool selectable,bool selected,

                               bool hidden,long z_order)

  {

   int    err = GetLastError();

   string lnName = name;

   err = 0;

   if(ObjectFind(0,lnName)!=-1)

      ObjectDelete(0,lnName);

   if(!ObjectCreate(ch_id,lnName,OBJ_HLINE,sub_window,0,price))

     {

      err = GetLastError();

      Print("Can't create object #", lnName, "# Error(",err,"):", err);

      return(err);

     }

   ObjectSetInteger(ch_id,lnName,OBJPROP_COLOR,clr);

   ObjectSetInteger(ch_id,lnName,OBJPROP_STYLE,style);

   ObjectSetInteger(ch_id,lnName,OBJPROP_WIDTH,width);

   ObjectSetInteger(ch_id,lnName,OBJPROP_BACK,back);

   ObjectSetInteger(ch_id,lnName,OBJPROP_SELECTABLE,selectable);

   ObjectSetInteger(ch_id,lnName,OBJPROP_SELECTED,selected);

   ObjectSetInteger(ch_id,lnName,OBJPROP_HIDDEN,hidden);

   ObjectSetInteger(ch_id,lnName,OBJPROP_ZORDER,z_order);

   return(0);

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void CSampleExpert::ButtonCreate(string name,int Xdist,

                                 int Ydist,int Xsize,int Ysize,int FONTSIZE=12)

  {

   if(ObjectFind(0,m_symbol.Name()+name)<0)

      ObjectCreate(0,m_symbol.Name()+name,OBJ_BUTTON,0,100,100);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_COLOR,clrWhite);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_BGCOLOR,clrBlack);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_XDISTANCE,Xdist);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_YDISTANCE,Ydist);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_XSIZE,Xsize);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_YSIZE,Ysize);

   ObjectSetString(0,m_symbol.Name()+name,OBJPROP_FONT,"Sans Serif");

   ObjectSetString(0,m_symbol.Name()+name,OBJPROP_TEXT,name);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_FONTSIZE,FONTSIZE);

   ObjectSetInteger(0,m_symbol.Name()+name,OBJPROP_SELECTABLE,false);

  }

//+------------------------------------------------------------------+

//| Check for long position closing                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::ButtonOnTick(void)

  {

   bool res=false;

   if(ObjectGetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_STATE,0)==true)

     {

      InpTradeCommand(InpTradeCommandClosSell);

      ObjectSetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_STATE,false);

      ObjectSetInteger(0,m_symbol.Name()+"SELL",OBJPROP_STATE,false);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"BUY_Close",OBJPROP_STATE,0)==true)

     {

      InpTradeCommand(InpTradeCommandClosBuy);

      ObjectSetInteger(0,m_symbol.Name()+"BUY_Close",OBJPROP_STATE,false);

      ObjectSetInteger(0,m_symbol.Name()+"BUY",OBJPROP_STATE,false);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_STATE,0)==true)

     {

      ExtAllCloseAll=true;

      NotifyAllCloseAll("");

      ExpertRemove();

      DeleteChart();

      PlaySound("expert.wav");

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_STATE,false);

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE",OBJPROP_STATE,false);

     }

   double PROFIT_BUY=0.00;

   double PROFIT_SELL=0.00;

   double PROFIT_CLOSE=0.00;

   double PROFIT_BUY_Lot=0.00;

   double PROFIT_SELL_Lot=0.00;

   double PROFIT_CLOSE_Lot=0.00;

   int _all =0;

   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions

     {

      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol ?>78F88

      if(position_GetSymbol==m_symbol.Name())

        {

         PROFIT_CLOSE_Lot=AccountInfoDouble(ACCOUNT_EQUITY);

         _all=_all+1;

         if(m_position.PositionType()==POSITION_TYPE_BUY)

           {

            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);

            PROFIT_BUY_Lot=PROFIT_BUY_Lot+PositionGetDouble(POSITION_VOLUME);

           }

         else

           {

            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);

            PROFIT_SELL_Lot=PROFIT_SELL_Lot+PositionGetDouble(POSITION_VOLUME);

           }

           {

            PROFIT_CLOSE=AccountInfoDouble(ACCOUNT_PROFIT);

            PROFIT_CLOSE_Lot=AccountInfoDouble(ACCOUNT_PROFIT);

           }

        }

     }

   ObjectSetString(0,m_symbol.Name()+"BUY_Close",OBJPROP_TEXT,"BUY Close ("+DoubleToString(PROFIT_BUY,2)+")");

   if(PROFIT_BUY>0)

     {

      ObjectSetInteger(0,Symbol()+"BUY_Close",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_BUY==0)

        {

         ObjectSetInteger(0,m_symbol.Name()+"BUY_Close",OBJPROP_BGCOLOR,clrBlack);

        }

      else

        {

         ObjectSetInteger(0,m_symbol.Name()+"BUY_Close",OBJPROP_BGCOLOR,clrCrimson);

        };

   ObjectSetString(0,m_symbol.Name()+"SELL_Close",OBJPROP_TEXT,"SELL Close ("+DoubleToString(PROFIT_SELL,2)+")");

   if(PROFIT_SELL>0)

     {

      ObjectSetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_SELL==0)

        {

         ObjectSetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_BGCOLOR,clrBlack);

        }

      else

        {

         ObjectSetInteger(0,m_symbol.Name()+"SELL_Close",OBJPROP_BGCOLOR,clrCrimson);

        }

   ObjectSetString(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_TEXT,DoubleToString(PROFIT_CLOSE,2)

                   +":all="+DoubleToString(PositionsTotal(),0));

   if(PROFIT_CLOSE>0)

     {

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrLimeGreen);

     }

   else

      if(PROFIT_CLOSE==0)

        {

         ObjectSetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrBlack);

        }

      else

        {

         ObjectSetInteger(0,m_symbol.Name()+"CLOSE_ALL",OBJPROP_BGCOLOR,clrCrimson);

        }

   ObjectSetString(0,m_symbol.Name()+"BUY",OBJPROP_TEXT,"BUY Lot ("+DoubleToString(PROFIT_BUY_Lot,2)+")");

   ObjectSetString(0,m_symbol.Name()+"SELL",OBJPROP_TEXT,"SELL Lot ("+DoubleToString(PROFIT_SELL_Lot,2)+")");

   ObjectSetString(0,m_symbol.Name()+"CLOSE",OBJPROP_TEXT,"CLOSE Lot ("+DoubleToString(PROFIT_CLOSE_Lot,2)+")");

   ObjectSetString(0,m_symbol.Name()+"without '.tpl'",OBJPROP_TEXT,".tpl"+",Tool="+DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY),2));

   if(ObjectGetInteger(0,m_symbol.Name()+"BUY",OBJPROP_STATE,0)==true)

     {

      ObjectSetInteger(0,m_symbol.Name()+"BUY",OBJPROP_BGCOLOR,clrDeepSkyBlue);

     }

   else

     {

      ObjectSetInteger(0,m_symbol.Name()+"BUY",OBJPROP_BGCOLOR,clrBlack);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"SELL",OBJPROP_STATE,0)==true)

     {

      ObjectSetInteger(0,m_symbol.Name()+"SELL",OBJPROP_BGCOLOR,clrRed);

     }

   else

     {

      ObjectSetInteger(0,m_symbol.Name()+"SELL",OBJPROP_BGCOLOR,clrBlack);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"CLOSE",OBJPROP_STATE,0)==true)

     {

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE",OBJPROP_BGCOLOR,clrRed);

     }

   else

     {

      ObjectSetInteger(0,m_symbol.Name()+"CLOSE",OBJPROP_BGCOLOR,clrBlack);

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"without '.tpl'",OBJPROP_STATE,0)==true)

     {

      DeleteChart();

      PlaySound("alert.wav");

     };

   if(ObjectGetInteger(0,m_symbol.Name()+"SELL",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,m_symbol.Name()+"SELL",OBJPROP_STATE,0);

      InpTradeCommand(InpTradeCommandSell);

      res=true;

     }

   if(ObjectGetInteger(0,m_symbol.Name()+"BUY",OBJPROP_STATE)!=0)

     {

      ObjectSetInteger(0,m_symbol.Name()+"BUY",OBJPROP_STATE,0);

      InpTradeCommand(InpTradeCommandBuy);

      res=true;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickInpNameRx(void)

  {

   if(InpSignalsFrequency>=SLEEPTIME) // search for trading signals no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-ExtLastSignalsRx>SLEEPTIME)

        {

         MqlRates rates[];

         //ArraySetAsSeries(rates,true);

         int start_pos=0,count=1;

         if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)

           {

            ExtPrevBarsRx=0;

            return;

           }

         double price_line=0.0;

         if(ObjectFind(0,InpObjUpNameOpen)>=0)

           {

            long object_type=ObjectGetInteger(0,InpObjUpNameOpen,OBJPROP_TYPE);

            if(object_type==OBJ_HLINE)

               price_line=ObjectGetDouble(0,InpObjUpNameOpen,OBJPROP_PRICE);

            else

               if(object_type==OBJ_TREND)

                  price_line=ObjectGetValueByTime(0,InpObjUpNameOpen,rates[0].time,0);

            if(price_line>0.0)

              {

               if((rates[0].open>price_line && rates[0].close<price_line) ||

                  (rates[0].open<price_line && rates[0].close>price_line))

                 {

                  InpTradeCommand(InpTradeCommandY1);

                  ObjectsDeleteAll(0,InpObjUpNameOpen);

                  ExtUpName=true;

                  Obj_BUYOpen();

                 }

              }

           }

         ExtLastSignalsRx=time_current;

        }

     }

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickInpNameSx(void)

  {

   if(InpSignalsFrequency>=SLEEPTIME) // search for trading signals no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-ExtLastSignalsSx>SLEEPTIME)

        {

         MqlRates rates[];

         //ArraySetAsSeries(rates,true);

         int start_pos=0,count=1;

         if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)

           {

            ExtPrevBarsSx=0;

            return;

           }

         double price_line=0.0;

         if(ObjectFind(0,InpObjDownNameOpen)>=0)

           {

            long object_type=ObjectGetInteger(0,InpObjDownNameOpen,OBJPROP_TYPE);

            if(object_type==OBJ_HLINE)

               price_line=ObjectGetDouble(0,InpObjDownNameOpen,OBJPROP_PRICE);

            else

               if(object_type==OBJ_TREND)

                  price_line=ObjectGetValueByTime(0,InpObjDownNameOpen,rates[0].time,0);

            if(price_line>0.0)

              {

               if((rates[0].open>price_line && rates[0].close<price_line) ||

                  (rates[0].open<price_line && rates[0].close>price_line))

                 {

                  InpTradeCommand(InpTradeCommandU1);

                  ObjectsDeleteAll(0,InpObjDownNameOpen);

                  ExtDownName=true;

                  Obj_SELLOpen();

                 }

              }

           }

         ExtLastSignalsSx=time_current;

        }

     }

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickInpNameRz(void)

  {

   if(InpSignalsFrequency>=SLEEPTIME) // search for trading signals no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-ExtLastSignalsRz>SLEEPTIME)

        {

         MqlRates rates[];

         //ArraySetAsSeries(rates,true);

         int start_pos=0,count=1;

         if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)

           {

            ExtPrevBarsRz=0;

            return;

           }

         double price_line=0.0;

         if(ObjectFind(0,InpObjUpNameClos)>=0)

           {

            long object_type=ObjectGetInteger(0,InpObjUpNameClos,OBJPROP_TYPE);

            if(object_type==OBJ_HLINE)

               price_line=ObjectGetDouble(0,InpObjUpNameClos,OBJPROP_PRICE);

            else

               if(object_type==OBJ_TREND)

                  price_line=ObjectGetValueByTime(0,InpObjUpNameClos,rates[0].time,0);

            if(price_line>0.0)

              {

               if((rates[0].open>price_line && rates[0].close<price_line) ||

                  (rates[0].open<price_line && rates[0].close>price_line))

                 {

                  InpTradeCommand(InpTradeCommandY2);

                  ObjectsDeleteAll(0,InpObjUpNameClos);

                  ClExtUpName=true;

                  Obj_BUYClos();

                 }

              }

           }

         ExtLastSignalsRz=time_current;

        }

     }

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickInpNameSz(void)

  {

   if(InpSignalsFrequency>=SLEEPTIME) // search for trading signals no more than once every 10 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-ExtLastSignalsSz>SLEEPTIME)

        {

         MqlRates rates[];

         //ArraySetAsSeries(rates,true);

         int start_pos=0,count=1;

         if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)

           {

            ExtPrevBarsSz=0;

            return;

           }

         double price_line=0.0;

         if(ObjectFind(0,InpObjDownNameClos)>=0)

           {

            long object_type=ObjectGetInteger(0,InpObjDownNameClos,OBJPROP_TYPE);

            if(object_type==OBJ_HLINE)

               price_line=ObjectGetDouble(0,InpObjDownNameClos,OBJPROP_PRICE);

            else

               if(object_type==OBJ_TREND)

                  price_line=ObjectGetValueByTime(0,InpObjDownNameClos,rates[0].time,0);

            if(price_line>0.0)

              {

               if((rates[0].open>price_line && rates[0].close<price_line) ||

                  (rates[0].open<price_line && rates[0].close>price_line))

                 {

                  InpTradeCommand(InpTradeCommandU2);

                  ObjectsDeleteAll(0,InpObjDownNameClos);

                  ClExtDownName=true;

                  Obj_SELLClos();

                 }

              }

           }

         ExtLastSignalsSz=time_current;

        }

     }

  }

//+------------------------------------------------------------------+

//| Check for long position opening                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::TrendOpenedUp(void)

  {

   bool res=false;

   datetime time_0=iTime(m_symbol.Name(),InpPeriod_Up,0);

   if(time_0==ExtPrevBarsUp)

      return(true);

   ExtPrevBarsUp=time_0;

     {

      if(ObjectFind(0,InpNameAverageUp)<0)

         return(true);

      MqlRates ratesAverage[];

      ArraySetAsSeries(ratesAverage,true);

      int start_pos=0,count=3;

      if(CopyRates(m_symbol.Name(),Period(),start_pos,count,ratesAverage)!=count)

         return(false);

      if(ratesAverage[0].time==ExtLastAverageUp)

         return(true);

      double price_line=0.0;

      long object_type=ObjectGetInteger(0,InpNameAverageUp,OBJPROP_TYPE);

      if(object_type==OBJ_HLINE)

         price_line=ObjectGetDouble(0,InpNameAverageUp,OBJPROP_PRICE);

      else

         if(object_type==OBJ_TREND)

            price_line=ObjectGetValueByTime(0,InpNameAverageUp,ratesAverage[1].time,0);

      double value_by_time=price_line;

      if(value_by_time==0.0)

         return(true);

      if(ratesAverage[1].open<value_by_time && ratesAverage[1].close>value_by_time)

        {

         InpTradeCommand(InpCommandOpenedUp);

         if(InpDelLineUp)

            ObjectsDeleteAll(0,InpNameAverageUp);

         ExtUpNameUp=true;

         Obj_AverageUp();

         res=true;

        }

      if(ratesAverage[1].open>value_by_time && ratesAverage[1].close<value_by_time)

        {

         InpTradeCommand(InpCommandOpenedUpLow);

         if(InpDelLineUp)

            ObjectsDeleteAll(0,InpNameAverageUp);

         ExtUpNameUp=true;

         Obj_AverageUp();

         res=true;

        }

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for long position opening                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::TrendOpenedDown(void)

  {

   bool res=false;

   datetime time_0=iTime(m_symbol.Name(),InpPeriod_Down,0);

   if(time_0==ExtPrevBarsDown)

      return(true);

   ExtPrevBarsDown=time_0;

     {

      if(ObjectFind(0,InpNameAverageDown)<0)

         return(true);

      MqlRates ratesAverage[];

      ArraySetAsSeries(ratesAverage,true);

      int start_pos=0,count=3;

      if(CopyRates(m_symbol.Name(),Period(),start_pos,count,ratesAverage)!=count)

         return(false);

      if(ratesAverage[0].time==ExtLastAverageDown)

         return(true);

      double price_line=0.0;

      long object_type=ObjectGetInteger(0,InpNameAverageDown,OBJPROP_TYPE);

      if(object_type==OBJ_HLINE)

         price_line=ObjectGetDouble(0,InpNameAverageDown,OBJPROP_PRICE);

      else

         if(object_type==OBJ_TREND)

            price_line=ObjectGetValueByTime(0,InpNameAverageDown,ratesAverage[1].time,0);

      double value_by_time=price_line;

      if(value_by_time==0.0)

         return(true);

      if(ratesAverage[1].open<value_by_time && ratesAverage[1].close>value_by_time)

        {

         InpTradeCommand(InpCommandOpenedDown);

         if(InpDelLineDown)

            ObjectsDeleteAll(0,InpNameAverageDown);

         ExtDownNameDown=true;

         Obj_AverageDown();

         res=true;

        }

      if(ratesAverage[1].open>value_by_time && ratesAverage[1].close<value_by_time)

        {

         InpTradeCommand(InpCommandOpenedDownLow);

         if(InpDelLineDown)

            ObjectsDeleteAll(0,InpNameAverageDown);

         ExtDownNameDown=true;

         Obj_AverageDown();

         res=true;

        }

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for long position opening                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::TrendOpenedUp_2(void)

  {

   bool res=false;

   datetime time_0=iTime(m_symbol.Name(),InpPeriod_Up_2,0);

   if(time_0==ExtPrevBarsUp_2)

      return(true);

   ExtPrevBarsUp_2=time_0;

     {

      if(ObjectFind(0,InpNameAverageUp_2)<0)

         return(true);

      MqlRates ratesAverage[];

      ArraySetAsSeries(ratesAverage,true);

      int start_pos=0,count=3;

      if(CopyRates(m_symbol.Name(),Period(),start_pos,count,ratesAverage)!=count)

         return(false);

      if(ratesAverage[0].time==ExtLastAverageUp_2)

         return(true);

      double price_line=0.0;

      long object_type=ObjectGetInteger(0,InpNameAverageUp_2,OBJPROP_TYPE);

      if(object_type==OBJ_HLINE)

         price_line=ObjectGetDouble(0,InpNameAverageUp_2,OBJPROP_PRICE);

      else

         if(object_type==OBJ_TREND)

            price_line=ObjectGetValueByTime(0,InpNameAverageUp_2,ratesAverage[1].time,0);

      double value_by_time=price_line;

      if(value_by_time==0.0)

         return(true);

      if(ratesAverage[1].open<value_by_time && ratesAverage[1].close>value_by_time)

        {

         InpTradeCommand(InpCommandOpenedUp_2);

         if(InpDelLineUp_2)

            ObjectsDeleteAll(0,InpNameAverageUp_2);

         ExtUpNameUp_2=true;

         Obj_AverageUp_2();

         res=true;

        }

      if(ratesAverage[1].open>value_by_time && ratesAverage[1].close<value_by_time)

        {

         InpTradeCommand(InpCommandOpenedUpLow_2);

         if(InpDelLineUp_2)

            ObjectsDeleteAll(0,InpNameAverageUp_2);

         ExtUpNameUp_2=true;

         Obj_AverageUp_2();

         res=true;

        }

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for long position opening                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::TrendOpenedDown_2(void)

  {

   bool res=false;

   datetime time_0=iTime(m_symbol.Name(),InpPeriod_Down_2,0);

   if(time_0==ExtPrevBarsDown_2)

      return(true);

   ExtPrevBarsDown_2=time_0;

     {

      if(ObjectFind(0,InpNameAverageDown_2)<0)

         return(true);

      MqlRates ratesAverage[];

      ArraySetAsSeries(ratesAverage,true);

      int start_pos=0,count=3;

      if(CopyRates(m_symbol.Name(),Period(),start_pos,count,ratesAverage)!=count)

         return(false);

      if(ratesAverage[0].time==ExtLastAverageDown_2)

         return(true);

      double price_line=0.0;

      long object_type=ObjectGetInteger(0,InpNameAverageDown_2,OBJPROP_TYPE);

      if(object_type==OBJ_HLINE)

         price_line=ObjectGetDouble(0,InpNameAverageDown_2,OBJPROP_PRICE);

      else

         if(object_type==OBJ_TREND)

            price_line=ObjectGetValueByTime(0,InpNameAverageDown_2,ratesAverage[1].time,0);

      double value_by_time=price_line;

      if(value_by_time==0.0)

         return(true);

      if(ratesAverage[1].open<value_by_time && ratesAverage[1].close>value_by_time)

        {

         InpTradeCommand(InpCommandOpenedDown_2);

         if(InpDelLineDown_2)

            ObjectsDeleteAll(0,InpNameAverageDown_2);

         ExtDownNameDown_2=true;

         Obj_AverageDown_2();

         res=true;

        }

      if(ratesAverage[1].open>value_by_time && ratesAverage[1].close<value_by_time)

        {

         InpTradeCommand(InpCommandOpenedDownLow_2);

         if(InpDelLineDown_2)

            ObjectsDeleteAll(0,InpNameAverageDown_2);

         ExtDownNameDown_2=true;

         Obj_AverageDown_2();

         res=true;

        }

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

void CSampleExpert::ObjVLinetime(void)

  {

   if(ObjectFind(0,InpObjVLineName)>=0)

     {

      ExtVLinetime=(datetime)(ObjectGetInteger(0,InpObjVLineName,OBJPROP_TIME,0));

      if(ExtVLinetime<TimeCurrent())

        {

         InpTradeCommand(InpVLineCommand);

         ObjectsDeleteAll(0,InpObjVLineName);

         PlaySound("timeout.wav");

        }

     }

//---

  }

//+------------------------------------------------------------------+

//| start function                                                   |

//+------------------------------------------------------------------+

void CSampleExpert::ObjVLinetimeD(void)

  {

   if(ObjectFind(0,InpObjVLineNameD)>=0)

     {

      ExtVLinetimeD=(datetime)(ObjectGetInteger(0,InpObjVLineNameD,OBJPROP_TIME,0));

      if(ExtVLinetimeD<TimeCurrent())

        {

         InpTradeCommand(InpVLineCommandD);

         ObjectsDeleteAll(0,InpObjVLineNameD);

         PlaySound("timeout.wav");

        }

     }

//---

  }

//+------------------------------------------------------------------+

//| Initialization and checking for input parameters                 |

//+------------------------------------------------------------------+

bool CSampleExpert::Init(void)

  {

//--- initialize common information

   if(!m_symbol.Name(Symbol())) // sets symbol name

      return(false);

   RefreshRates();

   m_trade.SetExpertMagicNumber(MACD_MAGIC); // magic

   m_trade.SetMarginMode();

   m_trade.SetTypeFillingBySymbol(Symbol());

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)

      digits_adjust=10;

   m_adjusted_point=m_symbol.Point()*digits_adjust;

//--- set default deviation for trading in adjusted points

   m_obj_trailing_stopOpen      = InpObjTrailingStopOpen*m_adjusted_point;

   m_obj_trailing_stepOpen      = InpObjTrailingStepOpen*m_adjusted_point;

   m_obj_trailing_stopClos      = InpObjTrailingStopClos*m_adjusted_point;

   m_obj_trailing_stepClos      = InpObjTrailingStepClos*m_adjusted_point;

   m_obj_trailing_stopOpenColor = InpObjStepStopUp*m_adjusted_point;

   m_obj_trailing_stopClosColor = InpObjStepStopDown*m_adjusted_point;

   m_obj_trailing_Up            = InpObjStepTradeUp*m_adjusted_point;

   m_obj_trailing_Down          = InpObjStepTradeDown*m_adjusted_point;

   m_obj_trailing_Up_2          = InpObjStepTradeUp_2*m_adjusted_point;

   m_obj_trailing_Down_2        = InpObjStepTradeDown_2*m_adjusted_point;

//--- set default deviation for trading in adjusted points

   m_trade.SetDeviationInPoints(3*digits_adjust);

//---

   int _y=70;

   for(int i=0; i<ArraySize(m_name); i++)

     {

      ButtonCreate(m_name[i],5,_y,110,15,8);

      _y=_y+17;

     }

//---

   if(InpIndicators_1 && !InitIndicators_1())

      return(false);

//---

   if(InpIndicators_2 && !InitIndicators_2())

      return(false);

//--- succeed

   return(true);

  }

//+------------------------------------------------------------------+

//| Initialization of the indicators                                 |

//+------------------------------------------------------------------+

bool CSampleExpert::InitIndicators_1(void)

  {

//--- create MACD indicator

   if(m_handle_macd_1==INVALID_HANDLE)

      if((m_handle_macd_1=iCustom(m_symbol.Name(),Period_1,short_name_1))==INVALID_HANDLE)

        {

         printf("Error creating indicator_1");

         return(false);

        }

//--- succeed

   return(true);

  }

//+------------------------------------------------------------------+

//| Initialization of the indicators                                 |

//+------------------------------------------------------------------+

bool CSampleExpert::InitIndicators_2(void)

  {

//--- create MACD indicator

   if(m_handle_macd_2==INVALID_HANDLE)

      if((m_handle_macd_2=iCustom(m_symbol.Name(),Period_2,short_name_2))==INVALID_HANDLE)

        {

         printf("Error creating indicator_2");

         return(false);

        }

//--- succeed

   return(true);

  }

//+------------------------------------------------------------------+

//| Check for long position opening                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::LongOpened_1(void)

  {

   bool res=false;

//--- check for long position (BUY) possibility

   if(m_macd_current_1<m_signal_current_1)

     {

      InpTradeCommand(InpLongOpened_1Command);

      //--- in any case we must exit from expert

      res=true;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for short position opening                                 |

//+------------------------------------------------------------------+

bool CSampleExpert::ShortOpened_1(void)

  {

   bool res=false;

//--- check for short position (SELL) possibility

   if(m_macd_current_1>m_signal_current_1)

     {

      InpTradeCommand(InpShortOpened_1Command);

      //--- in any case we must exit from expert

      res=true;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for long position opening                                  |

//+------------------------------------------------------------------+

bool CSampleExpert::LongOpened_2(void)

  {

   bool res=false;

//--- check for long position (BUY) possibility

   if(m_macd_current_2<m_signal_current_2)

     {

      InpTradeCommand(InpLongOpened_2Command);

      //--- in any case we must exit from expert

      res=true;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| Check for short position opening                                 |

//+------------------------------------------------------------------+

bool CSampleExpert::ShortOpened_2(void)

  {

   bool res=false;

//--- check for short position (SELL) possibility

   if(m_macd_current_2>m_signal_current_2)

     {

      InpTradeCommand(InpShortOpened_2Command);

      //--- in any case we must exit from expert

      res=true;

     }

//--- result

   return(res);

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

bool CSampleExpert::Processing_1(void)

  {

//--- we work only at the time of the birth of new bar

   datetime time_0=iTime(m_symbol.Name(),Period_1,0);

   if(time_0==ExtPrevBars_1)

      return(false);

   ExtPrevBars_1=time_0;

   if(!m_symbol.RefreshRates())

     {

      ExtPrevBars_1=0;

      return(false);

     }

//--- refresh indicators

   if(BarsCalculated(m_handle_macd_1)<2)

      return(false);

   if(CopyBuffer(m_handle_macd_1,0,InpBars_1,2,m_buff_MACD_main_1)  !=2 ||

      CopyBuffer(m_handle_macd_1,1,InpBars_1,2,m_buff_MACD_signal_1)!=2)

     {

      ExtPrevBars_1=0;

      return(false);

     }

//   m_indicators.Refresh();

//--- to simplify the coding and speed up access

//--- data are put into internal variables

   m_macd_current_1   =m_buff_MACD_main_1[0];

   m_signal_current_1 =m_buff_MACD_signal_1[0];

//--- check for long position (BUY) possibility

   if(LongOpened_1())

      return(true);

//--- check for short position (SELL) possibility

   if(ShortOpened_1())

      return(true);

//--- exit without position processing

   return(false);

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

bool CSampleExpert::Processing_2(void)

  {

//--- we work only at the time of the birth of new bar

   datetime time_0=iTime(m_symbol.Name(),Period_2,0);

   if(time_0==ExtPrevBars_2)

      return(false);

   ExtPrevBars_2=time_0;

   if(!m_symbol.RefreshRates())

     {

      ExtPrevBars_2=0;

      return(false);

     }

//--- refresh indicators

   if(BarsCalculated(m_handle_macd_2)<2)

      return(false);

   if(CopyBuffer(m_handle_macd_2,0,InpBars_2,2,m_buff_MACD_main_2)  !=2 ||

      CopyBuffer(m_handle_macd_2,1,InpBars_2,2,m_buff_MACD_signal_2)!=2)

     {

      ExtPrevBars_2=0;

      return(false);

     }

//   m_indicators.Refresh();

//--- to simplify the coding and speed up access

//--- data are put into internal variables

   m_macd_current_2   =m_buff_MACD_main_2[0];

   m_signal_current_2 =m_buff_MACD_signal_2[0];

//--- check for long position (BUY) possibility

   if(LongOpened_2())

      return(true);

//--- check for short position (SELL) possibility

   if(ShortOpened_2())

      return(true);

//--- exit without position processing

   return(false);

  }

//+------------------------------------------------------------------+

//| OnTickBalance                                                    |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickBalance(void)

  {

   ButtonOnTick();

   if(InpStartOpen)

     {

      OnTickObjTrailingOpen();

     }

   if(InpStartClos)

     {

      OnTickObjTrailingClos();

     }

   if(m_position.Select(Symbol()))

     {

      ProfitOnTick();

      ProfitTarget_2();

     }

   if(ProfitTarget())

     {

      return;

     }

   if(ProfitTarget_1())

     {

      return;

     }

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

bool CSampleExpert::Processing(void)

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

      return(false);

   OnTickBalance();

//---

   if((HoursFrom<HoursTo && TimeLocal()>=HoursFrom && TimeLocal()<HoursTo) ||

      (HoursFrom>HoursTo && (TimeLocal()<HoursTo || TimeLocal()>=HoursFrom)) ||

      (HoursFrom2<HoursTo2 && TimeLocal()>=HoursFrom2 && TimeLocal()<HoursTo2) ||

      (HoursFrom2>HoursTo2 && (TimeLocal()<HoursTo2 || TimeLocal()>=HoursFrom2)))

     {

      MqlDateTime currTime;

      TimeLocal(currTime);

      int hour0 = currTime.hour;

      if((HoursFrom1 < HoursTo1 && hour0 >= HoursFrom1 && hour0 < HoursTo1) ||

         (HoursFrom1 > HoursTo1 && (hour0 < HoursTo1 || hour0 >= HoursFrom1)))

        {

         OnTickInpUpper();

         OnTickInpLower();

         ProcessingFilter();

         switch(ObjFilterStopUp)

           {

            case Filter_Off:

               ExtFilter_Off=true;

               ProcessingUp();

               break;

           }

         switch(ObjFilterStopLow)

           {

            case Filter_Off:

               ExtFilter_Off=true;

               ProcessingDown();

               break;

           }

        }

     }

//--- exit without position processing

   return(false);

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

void CSampleExpert::ProcessingFilter(void)

  {

   switch(FilterLine_1)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         ObjVLinetime();

         break;

     }

   switch(FilterLine_2)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         ObjVLinetimeD();

         break;

     }

   switch(FilterLine_3)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         if(InpIndicators_1 && Processing_1())

           {

            return;

           }

         break;

     }

   switch(FilterLine_4)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         if(InpIndicators_2 && Processing_2())

           {

            return;

           }

         break;

     }

   switch(FilterLine_5)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         OnTickInpNameRx();

         break;

     }

   switch(FilterLine_6)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         OnTickInpNameSx();

         break;

     }

   switch(FilterLine_7)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         OnTickInpNameRz();

         break;

     }

   switch(FilterLine_8)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         OnTickInpNameSz();

         break;

     }

   switch(FilterLine_9)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         ProcessingBuy();

         break;

     }

   switch(FilterLine_10)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         ProcessingSell();

         break;

     }

   switch(FilterLine_11)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         ProcessingClosBuy();

         break;

     }

   switch(FilterLine_12)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         ProcessingClosSell();

         break;

     }

   switch(FilterLine_13)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         TrendOpenedUp();

         break;

     }

   switch(FilterLine_14)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         TrendOpenedDown();

         break;

     }

   switch(FilterLine_15)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         TrendOpenedUp_2();

         break;

     }

   switch(FilterLine_16)

     {

      case mode_All:

         ExMode_All=true;

         break;

      case mode_Ind:

         ExMode_Ind=true;

         TrendOpenedDown_2();

         break;

     }

   Comment("MonitoringBuy ",m_objectNamesBuy.Total()," lines""\n",

           "MonitoringClose ",m_objectNamesClosBuy.Total()," lines""\n",

           "=============""\n",

           "MonitoringSell ",m_objectNamesSell.Total()," lines""\n",

           "MonitoringClose ",m_objectNamesClosSell.Total()," lines");

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

void CSampleExpert::ProcessingUp(void)

  {

   if(InpIndicators_1 && Processing_1())

     {

      return;

     }

   ObjVLinetime();

   OnTickInpNameRx();

   OnTickInpNameRz();

   ProcessingBuy();

   ProcessingClosBuy();

   TrendOpenedUp();

   TrendOpenedUp_2();

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

void CSampleExpert::ProcessingDown(void)

  {

   if(InpIndicators_2 && Processing_2())

     {

      return;

     }

   ObjVLinetimeD();

   OnTickInpNameSx();

   OnTickInpNameSz();

   ProcessingSell();

   ProcessingClosSell();

   TrendOpenedDown();

   TrendOpenedDown_2();

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickInpUpper(void)

  {

   if(InpSignalsFrequency>=SLEEPTIME) // search for trading signals no more than once every 1 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-ExtLastUpper>SLEEPTIME)

        {

         MqlRates rates[],rates_1[];

         //ArraySetAsSeries(rates,true);

         int start_pos=0,count=1;

         if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)

           {

            ExtPrevUpper=0;

            return;

           }

         int start_pos_1=0,count_1=1;

         if(CopyRates(m_symbol.Name(),Period(),start_pos_1,count_1,rates_1)!=count_1)

           {

            ExtPrevAverage=0;

            return;

           }

         double price_line=0.0,price_line_1=0.0;

         if(ObjectFind(0,InpNameaverageUp)>=0 || ObjectFind(0,InpNameupper)>=0)

           {

            long object_type_1=ObjectGetInteger(0,InpNameaverageUp,OBJPROP_TYPE);

            if(object_type_1==OBJ_HLINE)

               price_line_1=ObjectGetDouble(0,InpNameaverageUp,OBJPROP_PRICE);

            else

               if(object_type_1==OBJ_TREND)

                  price_line_1=ObjectGetValueByTime(0,InpNameaverageUp,rates_1[0].time,0);

            long object_type=ObjectGetInteger(0,InpNameupper,OBJPROP_TYPE);

            if(object_type==OBJ_HLINE)

               price_line=ObjectGetDouble(0,InpNameupper,OBJPROP_PRICE);

            else

               if(object_type==OBJ_TREND)

                  price_line=ObjectGetValueByTime(0,InpNameupper,rates[0].time,0);

            if(price_line>0.0 || price_line_1>0.0)

              {

               switch(ObjFilterStopUp)

                 {

                  case Filter_Off:

                     ExtFilter_Off=true;

                     break;

                  case Filter_Stop:

                     ExtFilter_Stop=true;

                     if(rates[0].open>price_line)

                       {

                        ProcessingUp();

                       }

                     break;

                  case Filter_All:

                     ExtFilter_All=true;

                     if(rates[0].open<price_line && rates_1[0].close>price_line_1)

                       {

                        ProcessingUp();

                       }

                     break;

                 }

              }

           }

         ExtLastUpper=time_current;

         ExtLastAverage=time_current;

        }

     }

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void CSampleExpert::OnTickInpLower(void)

  {

   if(InpSignalsFrequency>=SLEEPTIME) // search for trading signals no more than once every 1 seconds

     {

      datetime time_current=TimeCurrent();

      if(time_current-ExtLastLower>SLEEPTIME)

        {

         MqlRates rates[],rates_1[];

         //ArraySetAsSeries(rates,true);

         int start_pos=0,count=1;

         if(CopyRates(m_symbol.Name(),Period(),start_pos,count,rates)!=count)

           {

            ExtPrevLower=0;

            return;

           }

         int start_pos_1=0,count_1=1;

         if(CopyRates(m_symbol.Name(),Period(),start_pos_1,count_1,rates_1)!=count_1)

           {

            ExtPrevAverage=0;

            return;

           }

         double price_line=0.0,price_line_1=0.0;

         if(ObjectFind(0,InpNameaverageLow)>=0 || ObjectFind(0,InpNamelower)>=0)

           {

            long object_type_1=ObjectGetInteger(0,InpNameaverageLow,OBJPROP_TYPE);

            if(object_type_1==OBJ_HLINE)

               price_line_1=ObjectGetDouble(0,InpNameaverageLow,OBJPROP_PRICE);

            else

               if(object_type_1==OBJ_TREND)

                  price_line_1=ObjectGetValueByTime(0,InpNameaverageLow,rates_1[0].time,0);

            long object_type=ObjectGetInteger(0,InpNamelower,OBJPROP_TYPE);

            if(object_type==OBJ_HLINE)

               price_line=ObjectGetDouble(0,InpNamelower,OBJPROP_PRICE);

            else

               if(object_type==OBJ_TREND)

                  price_line=ObjectGetValueByTime(0,InpNamelower,rates[0].time,0);

            if(price_line>0.0 || price_line_1>0.0)

              {

               switch(ObjFilterStopLow)

                 {

                  case Filter_Off:

                     ExtFilter_Off=true;

                     break;

                  case Filter_Stop:

                     ExtFilter_Stop=true;

                     if(rates[0].open<price_line)

                       {

                        ProcessingDown();

                       }

                     break;

                  case Filter_All:

                     ExtFilter_All=true;

                     if(rates[0].open>price_line && rates_1[0].close<price_line_1)

                       {

                        ProcessingDown();

                       }

                     break;

                 }

              }

           }

         ExtLastLower=time_current;

         ExtLastAverage=time_current;

        }

     }

  }

//+------------------------------------------------------------------+

//| Send Notifications function

//+------------------------------------------------------------------+

void CSampleExpert::NotifyLongShortClos(string objName)

  {

   ExtNeedCloseAll=true;

   LongShortObjClosed();

   PlaySound("ok.wav");

   string msg="Clos Buy Sell ''"+objName+"' on "+m_symbol.Name();

   if(AllCloseAllNotifications)

      SendNotification(msg);

   if(AllCloseAllEmails)

      SendMail(EAName+" EventClos_Buy_Sell",msg);

   Print(msg);

  }

//+------------------------------------------------------------------+

//| Send Notifications function

//+------------------------------------------------------------------+

void CSampleExpert::NotifyAllCloseAll(string objName)

  {

   ExtAllCloseAll=true;

   CloseAllProfit();

   CloseAllLoss();

   CloseAll();

   Sleep(SLEEPTIME*1000);

   CloseAllProfit();

   CloseAllLoss();

   Sleep(SLEEPTIME*1000);

   CloseAll();

   PlaySound("ok.wav");

   string msg="AllCloseAll ''"+objName+"' on "+m_symbol.Name();

   if(AllCloseAllNotifications)

      SendNotification(msg);

   if(AllCloseAllEmails)

      SendMail(EAName+" AllCloseAll",msg);

   Print(msg);

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

bool CSampleExpert::ProcessingBuy(void)

  {

   bool rv=false;

   int i;

   string objName;

   if(m_symbol.RefreshRates())

     {

      if(FindActiveObjectsBuy())

        {

         for(i=0; i<m_objectNamesBuy.Total(); i++)

           {

            objName=m_objectNamesBuy[i];

            if(PriceCrossedBuy(objName))

              {

               ObjectSetInteger(0,objName,OBJPROP_COLOR,CrossedColorBuy);

               InpTradeCommand(InpColorBuyCommand);

               ExtUpNameColor=true;

               Obj_BUYOpenColor(objName);

              }

           }

        }

     }

   return(rv);

  }

//+------------------------------------------------------------------+

//| Send Notifications function                                      |

//+------------------------------------------------------------------+

void CSampleExpert::NotifyCrossingBuy(string objName)

  {

   ExtNeedOpenBuy=true;

   LongObjOpened();

   PlaySound("ok.wav");

   string msg="Price crossed lineBuy ''"+objName+"' on "+m_symbol.Name();

   if(EnableAlertsBuy)

      Alert(msg);

   if(EnableNotificationsBuy)

      SendNotification(msg);

   if(EnableEmailsBuy)

      SendMail(EAName+" EventBuy",msg);

   Print(msg);

  }

//+------------------------------------------------------------------+

//| Returns true if objName has been crossed up or down by current price

//+------------------------------------------------------------------+

bool CSampleExpert::PriceCrossedBuy(string objName)

  {

   ENUM_OBJECT objType;

   double objPrice=0.0,openPrice,curPrice;

   objType=(ENUM_OBJECT)ObjectGetInteger(0,objName,OBJPROP_TYPE);

   if(objType==OBJ_HLINE)

     {

      objPrice= ObjectGetDouble(0, objName, OBJPROP_PRICE);

     }

   else

      if(objType==OBJ_TREND)

        {

         objPrice=ObjectGetValueByTime(0,objName,TimeCurrent(),0);

        }

   if(objPrice)

     {

      openPrice= iOpen(NULL,0,0);

      curPrice = iClose(NULL,0,0);

      return (openPrice<=objPrice && curPrice>objPrice) || (openPrice>=objPrice && curPrice<objPrice);

     }

   return false;

  }

//+------------------------------------------------------------------+

//| Returns true if object has to be monitored based on color and

//| previous crosses

//+------------------------------------------------------------------+

bool CSampleExpert::ActiveObjectBuy(string objName)

  {

   int objColor=(int)ObjectGetInteger(0,objName,OBJPROP_COLOR,0);

   return objColor == MonitoringColorBuy;

  }

//+------------------------------------------------------------------+

//| Returns the list of object to be monitored

//+------------------------------------------------------------------+

int CSampleExpert::FindActiveObjectsBuy(void)

  {

   m_objectNamesBuy.Clear();

   int nHLines=ObjectsTotal(0,-1,OBJ_HLINE),

       nTrendLines=ObjectsTotal(0,-1,OBJ_TREND),

       i;

   string objName;

   for(i=0; i<nHLines; i++)

     {

      objName=ObjectName(0,i,0,OBJ_HLINE);

      if(ActiveObjectBuy(objName))

        {

         m_objectNamesBuy.Add(objName);

        }

     }

   for(i=0; i<nTrendLines; i++)

     {

      objName=ObjectName(0,i,0,OBJ_TREND);

      if(ActiveObjectBuy(objName))

        {

         m_objectNamesBuy.Add(objName);

        }

     }

   return m_objectNamesBuy.Total();

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

bool CSampleExpert::ProcessingSell(void)

  {

   bool rv=false;

   int i;

   string objName;

   if(m_symbol.RefreshRates())

     {

      if(FindActiveObjectsSell())

        {

         for(i=0; i<m_objectNamesSell.Total(); i++)

           {

            objName=m_objectNamesSell[i];

            if(PriceCrossedSell(objName))

              {

               ObjectSetInteger(0,objName,OBJPROP_COLOR,CrossedColorSell);

               InpTradeCommand(InpColorSellCommand);

               ExtDownNameColor=true;

               Obj_SELLOpenColor(objName);

              }

           }

        }

     }

   return(rv);

  }

//+------------------------------------------------------------------+

//| Send Notifications function

//+------------------------------------------------------------------+

void CSampleExpert::NotifyCrossingSell(string objName)

  {

   ExtNeedOpenSell=true;

   ShortObjOpened();

   PlaySound("ok.wav");

   string msg="Price crossed lineSell ''"+objName+"' on "+m_symbol.Name();

   if(EnableAlertsSell)

      Alert(msg);

   if(EnableNotificationsSell)

      SendNotification(msg);

   if(EnableEmailsSell)

      SendMail(EAName+" EventSell",msg);

   Print(msg);

  }

//+------------------------------------------------------------------+

//| Returns true if objName has been crossed up or down by current price

//+------------------------------------------------------------------+

bool CSampleExpert::PriceCrossedSell(string objName)

  {

   ENUM_OBJECT objType;

   double objPrice=0.0,openPrice,curPrice;

   objType=(ENUM_OBJECT)ObjectGetInteger(0,objName,OBJPROP_TYPE);

   if(objType==OBJ_HLINE)

     {

      objPrice= ObjectGetDouble(0, objName, OBJPROP_PRICE);

     }

   else

      if(objType==OBJ_TREND)

        {

         objPrice=ObjectGetValueByTime(0,objName,TimeCurrent(),0);

        }

   if(objPrice)

     {

      openPrice= iOpen(NULL,0,0);

      curPrice = iClose(NULL,0,0);

      return (openPrice<=objPrice && curPrice>objPrice) || (openPrice>=objPrice && curPrice<objPrice);

     }

   return false;

  }

//+------------------------------------------------------------------+

//| Returns true if object has to be monitored based on color and

//| previous crosses

//+------------------------------------------------------------------+

bool CSampleExpert::ActiveObjectSell(string objName)

  {

   int objColor=(int)ObjectGetInteger(0,objName,OBJPROP_COLOR,0);

   return objColor == MonitoringColorSell;

  }

//+------------------------------------------------------------------+

//| Returns the list of object to be monitored

//+------------------------------------------------------------------+

int CSampleExpert::FindActiveObjectsSell(void)

  {

   m_objectNamesSell.Clear();

   int nHLines=ObjectsTotal(0,-1,OBJ_HLINE),

       nTrendLines=ObjectsTotal(0,-1,OBJ_TREND),

       i;

   string objName;

   for(i=0; i<nHLines; i++)

     {

      objName=ObjectName(0,i,0,OBJ_HLINE);

      if(ActiveObjectSell(objName))

        {

         m_objectNamesSell.Add(objName);

        }

     }

   for(i=0; i<nTrendLines; i++)

     {

      objName=ObjectName(0,i,0,OBJ_TREND);

      if(ActiveObjectSell(objName))

        {

         m_objectNamesSell.Add(objName);

        }

     }

   return m_objectNamesSell.Total();

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

bool CSampleExpert::ProcessingClosBuy(void)

  {

   bool rv=false;

   int i;

   string objName;

   if(m_symbol.RefreshRates())

     {

      if(FindActiveObjectsClosBuy())

        {

         for(i=0; i<m_objectNamesClosBuy.Total(); i++)

           {

            objName=m_objectNamesClosBuy[i];

            if(PriceCrossedClosBuy(objName))

              {

               ObjectSetInteger(0,objName,OBJPROP_COLOR,CrossedColorClosBuy);

               InpTradeCommand(InpCloseBuyCommand);

               ClExtUpNameColor=true;

               Obj_BUYClosColor(objName);

              }

           }

        }

     }

   return(rv);

  }

//+------------------------------------------------------------------+

//| Send Notifications function

//+------------------------------------------------------------------+

void CSampleExpert::NotifyCrossingClosBuy(string objName)

  {

   ExtNeedCloseBuy=true;

   LongObjClosed();

   PlaySound("ok.wav");

   string msg="Price crossed lineClosBuy ''"+objName+"' on "+m_symbol.Name();

   if(EnableAlertsClosBuy)

      Alert(msg);

   if(EnableNotificationsClosBuy)

      SendNotification(msg);

   if(EnableEmailsClosBuy)

      SendMail(EAName+" EventClosBuy",msg);

   Print(msg);

  }

//+------------------------------------------------------------------+

//| Returns true if objName has been crossed up or down by current price

//+------------------------------------------------------------------+

bool CSampleExpert::PriceCrossedClosBuy(string objName)

  {

   ENUM_OBJECT objType;

   double objPrice=0.0,openPrice,curPrice;

   objType=(ENUM_OBJECT)ObjectGetInteger(0,objName,OBJPROP_TYPE);

   if(objType==OBJ_HLINE)

     {

      objPrice= ObjectGetDouble(0, objName, OBJPROP_PRICE);

     }

   else

      if(objType==OBJ_TREND)

        {

         objPrice=ObjectGetValueByTime(0,objName,TimeCurrent(),0);

        }

   if(objPrice)

     {

      openPrice= iOpen(NULL,0,0);

      curPrice = iClose(NULL,0,0);

      return (openPrice<=objPrice && curPrice>objPrice) || (openPrice>=objPrice && curPrice<objPrice);

     }

   return false;

  }

//+------------------------------------------------------------------+

//| Returns true if object has to be monitored based on color and

//| previous crosses

//+------------------------------------------------------------------+

bool CSampleExpert::ActiveObjectClosBuy(string objName)

  {

   int objColor=(int)ObjectGetInteger(0,objName,OBJPROP_COLOR,0);

   return objColor == MonitoringColorClosBuy;

  }

//+------------------------------------------------------------------+

//| Returns the list of object to be monitored

//+------------------------------------------------------------------+

int CSampleExpert::FindActiveObjectsClosBuy(void)

  {

   m_objectNamesClosBuy.Clear();

   int nHLines=ObjectsTotal(0,-1,OBJ_HLINE),

       nTrendLines=ObjectsTotal(0,-1,OBJ_TREND),

       i;

   string objName;

   for(i=0; i<nHLines; i++)

     {

      objName=ObjectName(0,i,0,OBJ_HLINE);

      if(ActiveObjectClosBuy(objName))

        {

         m_objectNamesClosBuy.Add(objName);

        }

     }

   for(i=0; i<nTrendLines; i++)

     {

      objName=ObjectName(0,i,0,OBJ_TREND);

      if(ActiveObjectClosBuy(objName))

        {

         m_objectNamesClosBuy.Add(objName);

        }

     }

   return m_objectNamesClosBuy.Total();

  }

//+------------------------------------------------------------------+

//| main function returns true if any position processed             |

//+------------------------------------------------------------------+

bool CSampleExpert::ProcessingClosSell(void)

  {

   bool rv=false;

   int i;

   string objName;

   if(m_symbol.RefreshRates())

     {

      if(FindActiveObjectsClosSell())

        {

         for(i=0; i<m_objectNamesClosSell.Total(); i++)

           {

            objName=m_objectNamesClosSell[i];

            if(PriceCrossedClosSell(objName))

              {

               ObjectSetInteger(0,objName,OBJPROP_COLOR,CrossedColorClosSell);

               InpTradeCommand(InpCloseSellCommand);

               ClExtDownNameColor=true;

               Obj_SELLClosColor(objName);

              }

           }

        }

     }

   return(rv);

  }

//+------------------------------------------------------------------+

//| Send Notifications function

//+------------------------------------------------------------------+

void CSampleExpert::NotifyCrossingClosSell(string objName)

  {

   ExtNeedCloseSell=true;

   ShortObjClosed();

   PlaySound("ok.wav");

   string msg="Price crossed lineClosSell ''"+objName+"' on "+m_symbol.Name();

   if(EnableAlertsClosSell)

      Alert(msg);

   if(EnableNotificationsClosSell)

      SendNotification(msg);

   if(EnableEmailsClosSell)

      SendMail(EAName+" EventClosSell",msg);

   Print(msg);

  }

//+------------------------------------------------------------------+

//| Returns true if objName has been crossed up or down by current price

//+------------------------------------------------------------------+

bool CSampleExpert::PriceCrossedClosSell(string objName)

  {

   ENUM_OBJECT objType;

   double objPrice=0.0,openPrice,curPrice;

   objType=(ENUM_OBJECT)ObjectGetInteger(0,objName,OBJPROP_TYPE);

   if(objType==OBJ_HLINE)

     {

      objPrice= ObjectGetDouble(0, objName, OBJPROP_PRICE);

     }

   else

      if(objType==OBJ_TREND)

        {

         objPrice=ObjectGetValueByTime(0,objName,TimeCurrent(),0);

        }

   if(objPrice)

     {

      openPrice= iOpen(NULL,0,0);

      curPrice = iClose(NULL,0,0);

      return (openPrice<=objPrice && curPrice>objPrice) || (openPrice>=objPrice && curPrice<objPrice);

     }

   return false;

  }

//+------------------------------------------------------------------+

//| Returns true if object has to be monitored based on color and

//| previous crosses

//+------------------------------------------------------------------+

bool CSampleExpert::ActiveObjectClosSell(string objName)

  {

   int objColor=(int)ObjectGetInteger(0,objName,OBJPROP_COLOR,0);

   return objColor == MonitoringColorClosSell;

  }

//+------------------------------------------------------------------+

//| Returns the list of object to be monitored

//+------------------------------------------------------------------+

int CSampleExpert::FindActiveObjectsClosSell(void)

  {

   m_objectNamesClosSell.Clear();

   int nHLines=ObjectsTotal(0,-1,OBJ_HLINE),

       nTrendLines=ObjectsTotal(0,-1,OBJ_TREND),

       i;

   string objName;

   for(i=0; i<nHLines; i++)

     {

      objName=ObjectName(0,i,0,OBJ_HLINE);

      if(ActiveObjectClosSell(objName))

        {

         m_objectNamesClosSell.Add(objName);

        }

     }

   for(i=0; i<nTrendLines; i++)

     {

      objName=ObjectName(0,i,0,OBJ_TREND);

      if(ActiveObjectClosSell(objName))

        {

         m_objectNamesClosSell.Add(objName);

        }

     }

   return m_objectNamesClosSell.Total();

  }

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit(void)

  {

//--- create all necessary objects

   if(!ExtExpert.Init())

      return(INIT_FAILED);

//--- secceed

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

   for(int i=0; i<ArraySize(m_name); i++)

     {

      ObjectDelete(0,Symbol()+m_name[i]);

     }

   Print(TimeCurrent(),": ",__FUNCTION__," reason code = ",reason);

//--- "clear" comment

   Comment("");

  }

//+------------------------------------------------------------------+

//| Expert new tick handling function                                |

//+------------------------------------------------------------------+

void OnTick(void)

  {

   ExtExpert.Processing();

  }

//+------------------------------------------------------------------+

Comments