//+��������������������������������������������������������������������+
//|             === EA_Cleopatra v 4.8.3 ===                            |*
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#property description "�������� ����������� ���� ����������"                                                                 
#property description "������ �� �������� ���������� || ������ �� �������� ��������"                                                                       
#property description "������ ��������� � ������ ����� || ������ ���� ���������� ������������" 
#property description "���.���. ������ �� ���������� �� ����� ������"                                                                        
#property description "��������� �������� ���������� �� ����� ������"                                                                 
#property description "� �������� ������������� �� ����������� ������ � ��� �� ����������"                                                       
#property description "�������� ������� �� ������ ������ �������� �������������"
#property description "Z407402122356"
#property description "R118943337169" 
#property description "�������"                                                   
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//# property strict
#property copyright "Copyright � EA_Cleopatra, SNAIKE"
#property link      "http://ea-signal.ru/sovetniki_1_8/"
//#property strict
//+------------------------------------------------------------------+
//| #import                                                          |
//+------------------------------------------------------------------+
/*#import "user32.dll"
   int GetDC(int hWnd);
   int ReleaseDC(int hWnd, int hDC);
#import "Gdi32.dll"
   bool GetTextExtentPoint32A(int hdc, string lpString, int size, int& lpSize[]);
   int CreateFontA(int nHeight,int nWidth,int nEscapement,int nOrientation,int fnWeight,int fdwItalic,int fdwUnderline,
                  int fdwStrikeOut,int fdwCharSet,int fdwOutputPrecision,int fdwClipPrecision,int fdwQuality,
                  int fdwPitchAndFamily,string lpszFace);
  int SelectObject(int hdc,int hgdiobj);
  bool DeleteObject(int hObject);
  int GetDeviceCaps(int hdc,int nIndex);
#import*/

//+------------------------------------------------------------------+
//| #define                                                          |
//+------------------------------------------------------------------+
#define DEFAULT_CHARSET 1
#define OUT_DEFAULT_PRECIS 0
#define CLIP_DEFAULT_PRECIS 0
#define DEFAULT_QUALITY 0
#define DEFAULT_PITCH 0
#define FF_MODERN 48
#define LOGPIXELSX 88

//+------------------------------------------------------------------+
//| extern variables                                                 |
//+------------------------------------------------------------------+
extern bool   Info          = true; // ��� ���������, ��������� ������������� �������� ����� � ���������� ����������������
//extern bool   TradePanel    = true; // ������ �������� ������.
extern bool   AutoDigits    = false;// ����������� ��� ��������� ���������� � ������� � ������ ���.(�������� ��� �� � 5-� ������� ���������)
extern bool   NewCycle_ON   = true; // ��� ������� - ���� �������������� �� �����, ����� ���� �� ����������
extern string I = "-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-";
//+-------------------------------------------------------------------
extern string T0 = "����� �� ��";
extern double DefaultProfit = 10;   // ���� ������ ������������� � ������� �� ����� ��� ������. 
                                    // ������� ����� ������ ������� �� ����� ��� ������ ��� �������� �������
extern double StopLoss      = 100;  // ��� ���������� ������ % ������ � ������ �������� ������� ��� ������. 
                                    
//---------------------------------------
extern string T1 = "����� ��������";
extern bool   Trall_on      = true; // ���.����. ������������ �������� �����
extern double Tral_Start    = 5;    // ���������� ������ ����� �� ����� Profit � ������� (������������ �� � �������).
extern double Tral_Size     = 5;    // �������� ����� ����� Tral_Start � �������. 
                                    // ����������, ������ ���� � �������, �� 5 ������� ����� ��     
                                    // ������������� ����� �� ���� ������� � ������� ����, 
                                    // ���������� ���� � ����� ��, ������� ��� ������.
//---------------------------------------
extern string T2 = "��������� MM";
extern double Risk          = 0.1;  // ������ ������ �������� � % �� ��������� �������, 
                                    // ���� Risk=0 �� ������ ������ ����������� �������� DefaultLot
extern double DefaultLot    = 0.1;  // ������������� ���, ���� ��������� Risk = 0
extern double MaxLot        = 10;   // ����������� ��������� ��� ��� ��������
extern bool   FixLot        = false;// ���� TRUE, �� ������������� ���, ���� FALSE � ������������ ������������ ��� �������� ������  
                                    // ���� ������� CCI_On = True, PiramidOn = false, � ������ ��� ����������� ����������
//---------------------------------------
extern string T2_1 = "����� ������ ��������";
extern int    Metod         = 1;    // 1 - ���� � ����� ������ ����� �������� ��������� ��.
                                    //     � ������ �������� � ����������� �� �������� MartinOn PiramidOn. ����� �� ��� ��������.
                                    // 2 � ���� � ����� ������ ����� �������� ��������� ��. 
                                    //     ����� �������� ����������� ��������. ���� ����� ��� � ������ ������� 
                                    //     ������ �� ������� ������� ������ �� ��������� ��� � ������ ��������,
                                    //     � ���������� ���������� ������ �� ��������� ��������� � ��������� 
                                    //     Dist �� ������� ����.
//---------------------------------------
extern string T3 = "��������� ���������� �������";
extern double Dist          = 3;    // ����������, �� ������� ������������ ���������� ������ 
                                    // �������� ����������� Pipstep. � � �������� ��������
                                    // ��� �������� �� ����. ���������� ���� �� �������� �� ������
                                    // �������� �2 �� ������� ��������� ������� ���������� � ����������
                                    // MartinStep � PiramidStep (� ����������� ��� �������� ������ �������� ��� ��� ���)
                                    // ������������ ���������� ����� �� ���������� 3 ������ �� ������� ����.
extern double Step          = 3;    // ��� ������� ���� - ��� �������� ������ �� �����. ��� ���-�� ���� ����� ������� �� �����
//---------------------------------------
extern string T4 = "= ��������� ������� =";
extern bool   MartinOn      = true; // ���. ����. ������ �� ������ �����������
extern double MartinStep    = 20;   // ��� � ������� ��� �������� ���������� ������ �� �����������
extern double MartinLotExponent = 1.4;// ��������� ���� ��� �������. ��������� ����������� ������� ������ ������ �����
extern int    Close_M_orders  = 20; // ��������� ������� ����� ��� ������� ��� ����� ������� ����������� �����������
//---------------------------------------
extern string T5_9 = "��������� ��� �������";
extern bool   M_WL            = true;    // ���������, ���������� ��������� �������.
extern int    M_BU_Start      = 1;       // � ������ ������ �������� ���������� ��� ������
extern int    M_WLstart       = 30;      // ������ ��������� (������ �������)
extern int    M_WLlevel       = 1;       // ���� ��������� (������ �������)
//---------------------------------------
extern string T5_8 = "Trailing ��������� �������";
extern bool   M_Trailing      = true;    // ���. ���������    
extern int    M_Trailing_Start  = 1;       // � ������ ������ �������� ������� ���� ��� ��� ������.
extern int    M_TrailingStop  = 30;      // ������ ����� � �������      
extern int    M_TrailingStep  = 30;      // ��� ����� � �������
//----------------------------------------
extern string T4_1 = "��������� ��������� ����� N-�� ������ �������";
extern bool   MartinOnNew   = false;// ������������ �� ��������� ������ ����������� ������� ����� N-�� ������.
extern int    LotNoM        = 20;   // ����� ���������� ����� ������ ����������� ������� ���������� ���� 
                                    // ������ ���� MartinOnNew =true
extern double PiramidStart  = 2;    // ��� ���������� ����� �������� � % ���������, �������� ����������� ��������.
                                    // ���� ������� ����� ������������. ���� 0 �� ���������
extern int    LotN_M        = 3;    // � ������ ������ ����� �������� ��������� �������
extern double MartinLotExponenNew=1.5;// ����������� ���������� ����
extern double MartinStepNew = 20;   // ��� �������� ����� � �������
extern double MartinK_Step  = 1.2;  // ����������� ���������� ���� ����� ��������� ����������� �������. 0 ���������
//---------------------------------------
extern string l = "-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-^-=-";
extern string T5 = "= ��������� �������� =";
extern bool   PiramidOn     = false;// ���.����. �� ������ ��������.
extern double PiramidStep   = 20;   // ��� � ������� ��� �������� ���������� ������ ��������.
extern double PiramidLotExponent = 1.4;// ��������� ���� ��� ��������. �� �� ����� ��� � ������� ������ 
                                    // ��������� ������� ���������� �� ���� �����
extern int    Close_P_orders= 20;   // ��������� ������� ����� ��� ������� ��� ����� ������� ����������� �����������.
extern int    PiramidStopLoss = 0;  // ������ �������������� ����� ��� ������� ����������� ������.
                                    // ���� 0 �� �� ���� ��� �� ������������.
extern int    Piramid_TP    = 20;   // ���� ������ ���������� �������, ���� ���� �� ���� ������ �� ������������.
extern bool   UseRevers     = true; // ��������� ������� 
extern int    PiramidRevers = 10;   // ������� �������� ����������� ��� ������������ �������.
//---------------------------------------
extern string T6 = "��������� ��� ��������";
extern bool   P_WL            = true;    // ���������, ���������� ��������� �������.
extern int    P_BU_Start      = 1;       // � ������ ������ �������� ���������� ��� ������
extern int    P_WLstart       = 30;      // ������ ��������� (������ �������)
extern int    P_WLlevel       = 1;       // ���� ��������� (������ �������)
//---------------------------------------
extern string T7 = "Trailing ��������� ��������";
extern bool   P_Trailing      = true;    // ���. ���������  
extern int    P_Trailing_Start= 1;       // � ������ ������ �������� ������� ���� ��� ��� ������.   
extern int    P_TrailingStop  = 30;      // ������ ����� � �������      
extern int    P_TrailingStep  = 30;      // ��� ����� � �������
//---------------------------------------
extern string T8 = "��������� ��������� ����� N-�� ������ ��������";
extern bool   PiramidOnNew  = false;// ������������ �� ��������� ������ ����������� �������� ����� N-�� ������
extern int    LotNoP        = 20;   // ����� ���������� ����� ������ ����������� �������� 
                                    // ���������� ���� ������ ���� PiramidOnNew =true
extern int    LotN_P        = 3;    // � ������ ������ ����� �������� ���������
extern double PiramidLotExponenNew = 1.5;// ����������� ���������� ����
extern double PiramidStepNew= 20;   // ��� �������� ����� � �������
extern double Persen_open   = 30;   // ����� ��������� �� �������� ����� ������� ������� ��������� ����� �������� ��� ���������   
                                    // ������� ����������� �������� ���������� PiramidStart  = 5	                                                 
//---------------------------------------
string T8_1 = "�������� ���������";
bool   CloseBy              = false;// ���� TRUE, �� �������� ��������� �������,  ���� FALSE � �������� ������;
//---------------------------------------
extern string T9 = "��������� ���������";
extern int    PositionX     = 10;   // ��������� ������������� ����� �� ��� � �� ������ ������� �������
extern int    PositionY     = 15;   // ��������� ������������� ����� �� ��� Y �� ������� ������� �������
extern int    FontSize      = 9;    // ������ ������ � ������������ �����
extern color  BULineColor   = Yellow; // ���� ����� ���������
extern color  TPLineColor   = Gray;   // ���� ����� ��
extern color  TralLineColor = DarkOrange;// ���� ����� �����
extern color  BuyStopColor  = DeepSkyBlue;// ���� ������� �� �������
extern color  SellStopColor = Red;  // ���� ������� �� �������
//---------------------------------------
extern string T10 = "����� ���������";
extern int    MagicMartin    = 777;  // ���������� ����� �������
extern int    MagicPiramid   = 888;    // ���������� ����� ��������
extern int    PauseTrade     = 6;    // ����� �������� ����� ��������� ��������� � ���
extern int    PauseTrade2    = 1;    // ����� �������� ����� ������ � �����, �� ������ ����� � ����� � �������.
extern int    PauseTradezamok= 0;    // ����� �������� � �������, ����� ��������� ������� �����.
extern int    Slippege       = 2;    // ���������� ��������������� ���� � ������� ��� �������� ������
extern double Test_com_in_pip = 0.5; // �������� ��� ����� �������� � ������� ��������� (� ������ ������ ������� ��������������)
//---------------------------------------
extern string T11 = "��������� CCI";
extern bool   CCI_On         = false;// ���� - true � �������� PiramidOn = false �� ����� ����� � ����� ��������� ������ ������� 
                                    // ������������ �� ������� CCI, ���� false �� ����� ������� MartinStep
extern int    CCI_TimeFrame  = 2;   // �� CCI(0-������� �� �������, 1=�1,2=�5,3=�15, 4=�30,5=�1, 6=�4,7=D1,8=W1,9=MN1) 
extern double Level          = 100; // ������� CCI
extern int    Period_CCI     = 14;  // ������  CCI
//---------------------------------------
extern string T12 = "����� ������ ���������";
extern string StartHour = "00:00";  // ����� ������ ��������
extern string EndHour   = "23:59";  // ����� ��������� ��������
//---------------------------------------
extern string T13 = "��� ������ ������ ���������";
extern bool Trade_in_Monday  =true; //��������� � ����������� 
extern bool Trade_in_Tuesday =true; //��������� � ������� 
extern bool Trade_in_Wednesday=true;//��������� � ����� 
extern bool Trade_in_Thursday=true; //��������� � ������� 
extern bool Trade_in_Friday  =true; //��������� � �������

extern string t9="��������� ���������� MTS";
extern bool  Vxod_MTS          =  true;   // ��������� ������������� ������� �� ���������� ������.
extern int   TF_MTF            =  5;      // �� ���������� 0-������� �� �������, 1=�1,2=�5,3=�15,4=�30,5=�1,6=�4,7=D1,8=W1,9=MN1)  
extern int   Per_MTS           =  9;      // ������ ���������  

/*#import "mt4gui2.dll"
string   guiVersion();
string   guiGetText(int,int);
bool     guiIsClicked(int,int);
bool     guiIsChecked(int,int);
int      guiAdd(int,string,int,int,int,int,string);
int      guiSetBgColor(int,int,int);
int      guiSetBorderColor(int,int,int);
int      guiSetTextColor(int,int,int);
int      guiRemove(int,int);
int      guiRemoveAll(int);
int      guiSetText(int,int,string,int,string);
int      guiSetChecked(int,int,bool);
int      guiEnable(int,int,int);
int      guiAddListItem(int,int,string);
int      guiGetListSel(int,int);
int      guiSetListSel(int,int,int);
int      guiCleanup (int);
#import*/





 

//+------------------------------------------------------------------+
//| global variables                                                 |
//+------------------------------------------------------------------+

string sPref = "Cleopatra_";  // ������� ����������� ��������
string sPrefIndPan = "CleoInfoPan_"; // ������� ����������� �������� � �������������� ������
int iDigitLot = 0;      // ���-�� ������ ����� ������� � �������� ����
bool isWorking = true;  // ���� ��������� �� ����������� ����������� ��������
int iTicket = -1;       // ����� ������ ����� ������
bool PiramidAutoStart = false; // ��������� �� ��������� �������� ��� ���������� �������� ��������
double PiramidStartLot = 0.0;

double MBuyStop = 0.0;   // ���� �������� ������ martin BuyStop
double MBuyStopLot = 0.0;// ��� ������ martin BuyStop
int MBuyStopNumb = 0.0;  // ����� ������ martin BuyStop

double MSellStop = 0.0;   // ���� �������� ������ martin SellStop
double MSellStopLot = 0.0;// ��� ������ martin BuyStop
int MSellStopNumb = 0.0;  // ����� ������ martin BuyStop

double PBuyStop = 0.0;   // ���� �������� ������ piramid BuyStop
double PBuyStopLot = 0.0;// ��� ������ piramid BuyStop
int PBuyStopNumb = 0.0;  // ����� ������ piramid BuyStop
double PBuyStopStopLoss = 0.0; // ������ �������� piramid BuyStop
double PBuyStopTakeProfit = 0.0; // ������ ���������� piramid BuyStop

double PSellStop = 0.0;   // ���� �������� ������ piramid SellStop
double PSellStopLot = 0.0;// ��� ������ piramid SellStop
int PSellStopNumb = 0.0;  // ����� ������ piramid SellStop
double PSellStopStopLoss = 0.0; // ������ �������� piramid SellStop
double PSellStopTakeProfit = 0.0; // ������ ���������� piramid SellStop

double TralStartPrice = 0.0;  // ���� � ������� �������� �������� �������
double TralPrice = 0.0; // ������� ������� ����� ���������
int TralType = 0;       // ��� ������� ����������� �� �����

string FontName = "Arial"; // �������� ������ � ������������ ����� �����
color BaseColor = White;

int DC_hWnd = 0;
int DC_hFont = 0;
int DC_hnd = 0;

bool StopMartin = false;
bool StopPiramid = false;
double AveregeLine = 0.0;
double TPLine = 0.0;
bool CommentSet = false;
double OpenLot = 0.0;
bool InitDC = false;

double dPiramidStopLoss = 0.0;
double dPiramidTP = 0.0;
double dP_WLstart = 0.0;
double dP_WLlevel = 0.0;
double dP_TrailingStop = 0.0;
double dP_TrailingStep = 0.0;
//--------------------------------
double dM_WLstart = 0.0;
double dM_WLlevel = 0.0;
double dM_TrailingStop = 0.0;
double dM_TrailingStep = 0.0;

//--- ����������� ������
int Buy_flag = 0;
int Sell_flag = 0;
int martin_flag=1, piramid_flag=2;
int Magic_martin = 0;
int Magic_piramid = 0;
//---

bool err;
double Lot2,LotR ;
int hwnd,M_buybtn,P_buybtn,lottxt,P_sellbtn,M_sellbtn,closesellbtn,closebtn,closebuybtn,totalord,totalbuy,totalsell,tick2;
string Symb,comment;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()

{
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ����� ���� ��� ����������� ��������� ������ �� ������� �� �������� �����
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  /*if(!IsTesting() && !IsOptimization()) 
{
  if(IsDemo()==false)// �������� �������� ������ �� ���� �����
   {
       if(TimeCurrent()>StrToTime("2015.01.01 00:00"))// ����������� ������ ��������� �� �������
          {
            Alert("���� ������ ��������� �� ���� �����  �����", 
                  "�������� ����� �������� ������ � ������ ����� ��� �� ���� �����");
            return(0);
          }
       }
 } */
   
    if(AutoDigits && (Digits == 5 || Digits == 3)){
       DefaultProfit       *= 10;
       Tral_Start          *= 10; 
       Tral_Size           *= 10; 
       Dist                *= 10;
       Step                *= 10;
       MartinStep          *= 10;
       M_WLstart           *= 10;
       M_WLlevel           *= 10;
       M_TrailingStop      *= 10;
       M_TrailingStep      *= 10;
       MartinStepNew       *= 10;
       PiramidStep         *= 10;
       PiramidStopLoss     *= 10;
       Piramid_TP          *= 10;
       P_WLstart           *= 10;
       P_WLlevel           *= 10;
       P_TrailingStop      *= 10;
       P_TrailingStep      *= 10;
       PiramidStepNew      *= 10;
       Test_com_in_pip     *= 10;
	}
   //--- ���������� ���������� ����������� ��������
   if (GlobalVariableCheck("M_piramid") && GlobalVariableCheck("M_martin")) {
      Magic_martin = GlobalVariableGet("M_martin");
      Magic_piramid = GlobalVariableGet("M_piramid");
   } else {
      GlobalVariableSet("M_martin", MagicMartin);
      GlobalVariableSet("M_piramid", MagicPiramid);
      Magic_martin = MagicMartin;
      Magic_piramid = MagicPiramid;
   }
   if (GlobalVariableGet("Buy_flag") && GlobalVariableGet("Sell_flag")) {   
      Buy_flag = GlobalVariableGet("Buy_flag");
      Sell_flag = GlobalVariableGet("Sell_flag");
   }
   
   //--- 
   iDigitLot = InfoGetLotDigit(_Symbol);
   DeleteObject();
   Symb = Symbol();
   
   
   
     /* if(TradePanel)
    {
      hwnd=WindowHandle(Symb,Period());
      guiRemoveAll(hwnd);
     lottxt      = guiAdd(hwnd,"text"  , 76,-39,70,20, DoubleToStr(Lot2,2));  
     M_buybtn      = guiAdd(hwnd,"button",5,-60,70,20,"M_BUY"              );    
     M_sellbtn     = guiAdd(hwnd,"button",  5,-39,70,20,"M_SELL"             ); 
     P_buybtn      = guiAdd(hwnd,"button",147,-60,70,20,"P_BUY"              );    
     P_sellbtn     = guiAdd(hwnd,"button",  147,-39,70,20,"P_SELL"             );   
   
     closesellbtn= guiAdd(hwnd,"button",313,-39,90,20,"Close SELL"       );    
     closebuybtn = guiAdd(hwnd,"button",405,-39,90,20,"Close BUY"        );
     
      guiSetBgColor(hwnd,lottxt        , clrGreenYellow   );  // Lot    
      //----------------------------------------------------
      guiSetBgColor(hwnd,M_sellbtn     , clrOrangeRed     );  // Martin SELL      button color
      guiSetBorderColor(hwnd,M_sellbtn , clrBlack         ); 
      guiSetTextColor(hwnd,M_sellbtn   , clrBlack         );
      //----------------------------------------------------
      guiSetBgColor(hwnd,M_buybtn      , clrCornflowerBlue);  // Martin BUY       button color
      guiSetBorderColor(hwnd,M_buybtn  , clrBlack         ); 
      guiSetTextColor(hwnd,M_buybtn    , clrBlack         );
      //----------------------------------------------------
      guiSetBgColor(hwnd,P_sellbtn     , clrOrangeRed     );  // Piramid SELL      button color
      guiSetBorderColor(hwnd,P_sellbtn , clrBlack         ); 
      guiSetTextColor(hwnd,P_sellbtn   , clrBlack         );
      //----------------------------------------------------
      guiSetBgColor(hwnd,P_buybtn      , clrCornflowerBlue);  // Piramid BUY       button color
      guiSetBorderColor(hwnd,P_buybtn  , clrBlack         ); 
      guiSetTextColor(hwnd,P_buybtn    , clrBlack         );
      //----------------------------------------------------
      //guiSetBgColor(hwnd,closebtn    , clrGold          );  // CloseALL  button color
      guiSetBgColor(hwnd,closesellbtn     , clrOrangeRed     );  // CloseSELL button color
      guiSetBorderColor(hwnd,closesellbtn , clrBlack         ); 
      guiSetTextColor(hwnd,closesellbtn   , clrBlack         );
      //------------------------------------------------------
      guiSetBgColor(hwnd,closebuybtn      , clrCornflowerBlue);  // CloseBUY  button color
      guiSetBorderColor(hwnd,closebuybtn  , clrBlack         ); 
      guiSetTextColor(hwnd,closebuybtn    , clrBlack         );
      //-----------------------------------------------------
     }*/
//---- �������� ��������� ������������� ������
   if(DefaultProfit < 0.0) DefaultProfit = 0.0;
   if(StopLoss < 0.0) StopLoss = 0.0;
   //if(StopLoss > AccountEquity()) Alert("������� StopLoss ��������� ������ ��������� ������� �� �����!");
   if(Tral_Start < 0.0) Tral_Start = 0.0;
   if(Tral_Size < 0.0) Tral_Size = 0.0;
   if(Risk < 0.0) Risk = 0.0;
   if(Metod < 1){ Alert("����������� ������ �����, �������� �� ����� � 1");Metod = 1; }else if(Metod > 2){ Alert("����������� ������ �����, �������� �� ����� � 2");Metod = 2; }
   if(Dist < 1.0) Dist = 1.0;
   if(Step < 1.0) Step = 1.0;
   if(MartinStep < 1.0) MartinStep = 1.0;
   if(MartinLotExponent < 0.0) MartinLotExponent = 1.0;
   if(Slippege < 0) Slippege = 0;
   if(MaxLot > MarketInfo(_Symbol,MODE_MAXLOT)) MaxLot = MarketInfo(_Symbol,MODE_MAXLOT);
   if(Close_M_orders < 0) Close_M_orders = 0;
   if(PiramidStopLoss < 0) PiramidStopLoss = 0;   
   if(Piramid_TP < 0) Piramid_TP = 0;
   
   if(M_BU_Start< 0) M_BU_Start= 0.0;
   if(M_WLlevel < 0) M_WLlevel = 0.0;
   if(M_WLstart < 0) M_WLstart = 0.0;
   if(M_Trailing_Start< 0) M_Trailing_Start= 0.0;
   if(M_TrailingStop < 0) M_TrailingStop = 0.0;
   if(M_TrailingStep < 0) M_TrailingStep = 0.0; 
   //-------------------------------------
   
   if(P_BU_Start< 0) P_BU_Start= 0.0;
   if(P_WLlevel < 0) P_WLlevel = 0.0;
   if(P_WLstart < 0) P_WLstart = 0.0;
   if(P_Trailing_Start< 0) P_Trailing_Start= 0.0;
   if(P_TrailingStop < 0) P_TrailingStop = 0.0;
   if(P_TrailingStep < 0) P_TrailingStep = 0.0;

   switch(CCI_TimeFrame){
      case 1: CCI_TimeFrame = PERIOD_M1; break;
      case 2: CCI_TimeFrame = PERIOD_M5; break;
      case 3: CCI_TimeFrame = PERIOD_M15; break;
      case 4: CCI_TimeFrame = PERIOD_M30; break;
      case 5: CCI_TimeFrame = PERIOD_H1; break;
      case 6: CCI_TimeFrame = PERIOD_H4; break;
      case 7: CCI_TimeFrame = PERIOD_D1; break;
      case 8: CCI_TimeFrame = PERIOD_W1; break;
      case 9: CCI_TimeFrame = PERIOD_MN1; break;
      default: CCI_TimeFrame = 0;         
   }
   
   if(MartinOn && PiramidOn) CCI_On = false;
   
//---- ����������� �������   
   InfoChangeToDigit(_Symbol, DefaultProfit);
   InfoChangeToDigit(_Symbol, Tral_Start);
   InfoChangeToDigit(_Symbol, Tral_Size);
   DefaultLot = InfoNormalizeVolume(_Symbol, DefaultLot);
   InfoChangeToDigit(_Symbol, Dist);
   InfoChangeToDigit(_Symbol, Step);
   InfoChangeToDigit(_Symbol, MartinStep);
   InfoChangeToDigit(_Symbol, MartinStepNew);
   InfoChangeToDigit(_Symbol, PiramidStep);
   InfoChangeToDigit(_Symbol, PiramidStepNew);
   PiramidAutoStart = PiramidOn;
   
   dPiramidStopLoss = PiramidStopLoss;
   InfoChangeToDigit(_Symbol, dPiramidStopLoss);
   dPiramidTP = Piramid_TP;
   InfoChangeToDigit(_Symbol, dPiramidTP);

   //dM_BU_Start = M_BU_Start;
   //InfoChangeToDigit(_Symbol, dM_BU_Start);  
//-----------------------------------------
   dM_WLstart = M_WLstart;
   InfoChangeToDigit(_Symbol, dM_WLstart);
//-----------------------------------------
   dM_WLlevel = M_WLlevel;
   InfoChangeToDigit(_Symbol, dM_WLlevel);
//-----------------------------------------
   dM_TrailingStop = M_TrailingStop;
   InfoChangeToDigit(_Symbol, dM_TrailingStop);
//----------------------------------------
   dM_TrailingStep = M_TrailingStep;
   InfoChangeToDigit(_Symbol, dM_TrailingStep);
   //--++++++++++++++++++++++++++++++++++++++++++---------------------------------------
   //dP_BU_Start = P_BU_Start;
   //InfoChangeToDigit(_Symbol, dP_BU_Start);
   //-----------
   dP_WLstart = P_WLstart;
   InfoChangeToDigit(_Symbol, dP_WLstart);
   dP_WLlevel = P_WLlevel;
   InfoChangeToDigit(_Symbol, dP_WLlevel);
   dP_TrailingStop = P_TrailingStop;
   InfoChangeToDigit(_Symbol, dP_TrailingStop);
   dP_TrailingStep = P_TrailingStep;
   InfoChangeToDigit(_Symbol, dP_TrailingStep);

//---- ������� ������ �� ������� ������� ����� ������� ���������� �������   
   MBuyStop    = 0.0;
   MBuyStopLot = 0.0;
   MBuyStopNumb= 0.0;
   
   MSellStop    = 0.0;
   MSellStopLot = 0.0;
   MSellStopNumb= 0.0;
   
   PBuyStop    = 0.0;
   PBuyStopLot = 0.0;
   PBuyStopNumb= 0.0;
   PBuyStopStopLoss = 0.0;
   PBuyStopTakeProfit = 0.0;
   
   PSellStop    = 0.0;
   PSellStopLot = 0.0;
   PSellStopNumb= 0.0;
   PSellStopStopLoss = 0.0;
   PSellStopTakeProfit = 0.0;
      
    //---- �������� ��������� ��� ���
   if(IsExpertEnabled()){  
//---- ���� ��� ���� ���������� ����� - ������������ ���������� ��� ��������� ����� �����
   int _martin_cnt = OrdersGetCount(_Symbol, 99, Magic_martin, "", 0, 0);
   int _piramid_cnt = OrdersGetCount(_Symbol, 99, Magic_piramid, "", 0, 0);
   if(_martin_cnt+_piramid_cnt == 0){
      // �������� ��������� �� �������� ������
      if (TimeFilter())
     
      {
         // �������� �������� ���-�� ������
         Comment("�������� �������. �� �������� �������� "+DoubleToStr(PauseTrade,0)+" ���.");
         Sleep(PauseTrade*1000);
         Comment("");
         //
         SendOrder(OP_BUY, GetLot(), Ask, Magic_martin, "0:start");
         Comment("�� �������� ������� ������ �������� "+DoubleToStr(PauseTradezamok,0)+" ���.");
         Sleep(PauseTradezamok*60000);
         Comment("");
         SendOrder(OP_SELL, GetLot(), Bid, Magic_martin, "0:start");
      }else{
         Comment("�������� �������. �������� � ������� ����� ���������!");
         CommentSet = true;
      }
   }
   
 }  
//---- 
   //GetDCWithFontNameAndSize(FontName, FontSize);   
//----

   return(INIT_SUCCEEDED);
  }
  
  


//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//----
   GraphDelete(sPref);
   GraphDelete(sPrefIndPan);
   if(CommentSet){ Comment(""); CommentSet = false; }
//----
   /*DCRelease();
   if(hwnd>0) {guiRemoveAll(hwnd);guiCleanup (hwnd);} */
 }  
 
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
void OnTick()
  {
  
//---- 

 //=========================================  ����� ������ ��������  ===================================================

   /*if(TradePanel)
     {
      if(guiGetText(hwnd,lottxt)!="")LotR=StrToDouble(guiGetText(hwnd,lottxt));
      if(guiIsClicked(hwnd,P_buybtn))
        {
         if(Info) Print("��������� ����� �������� BUY �������");        
         comment=StringConcatenate("P����� ��������, ","Magic : ",Magic_piramid);
         SendOrder(OP_BUY,LotR,Ask,Magic_piramid,comment,0,0);
         if(tick2!=-1)
           {
            if(Info)  Print ("����� �������� BUY ������� ������ �������");
            Sleep(PauseTrade*1000);
           }
         else Print("������ ������� �������� ������ �������� BUY");
        }      
//---------------------------------------------------------------        
      if(guiIsClicked(hwnd,P_sellbtn))
        {
         if(Info) Print("��������� ����� �������� SELL �������");
         comment=StringConcatenate("P����� ��������, ","Magic : ",Magic_piramid);
         SendOrder(OP_SELL,LotR,Bid,Magic_piramid,comment,0,0);
         if(tick2!=-1)
           {
            if(Info)  Print ("������ ����� �������� SELL  ������ �������");
            Sleep(PauseTrade*1000);
           }
         else Print("������ ������� �������� ������ �������� SELL");
        }
//-----------------------------------------------------------------
      if(guiGetText(hwnd,lottxt)!="")LotR=StrToDouble(guiGetText(hwnd,lottxt));
      if(guiIsClicked(hwnd,M_buybtn))
        {
         if(Info) Print("��������� ����� ������ BUY �������");        
         comment=StringConcatenate("P����� ������, ","Magic : ",Magic_martin);
         SendOrder(OP_BUY,LotR,Ask,Magic_martin,comment,0,0);
         if(tick2!=-1)
           {
            if(Info)  Print ("����� ������ BUY ������� ������ �������");
            Sleep(PauseTrade*1000);
           }
         else Print("������ ������� �������� ������ ������ BUY");
        }
        
//---------------------------------------------------------------        
      if(guiIsClicked(hwnd,M_sellbtn))
        {
         if(Info) Print("��������� ����� ������ SELL �������");
         comment=StringConcatenate("P����� ������, ","Magic : ",Magic_martin);
         SendOrder(OP_SELL,LotR,Bid,Magic_martin,comment,0,0);
         if(tick2!=-1)
           {
            if(Info)  Print ("������ ����� ������ SELL  ������ �������");
            Sleep(PauseTrade*1000);
           }
         else Print("������ ������� �������� ������ ������ SELL");
        }    
       
 //--------------------------------------------------------------
      if(guiIsClicked(hwnd,closebtn))
        {
         if(totalord==0) Print("��� �������� �������");
         else
           {
            if(Info>=1) Print("��������� BCE ������ �������");
            err=CloseOrders();
            if(err)
              {
               if(Info>=1)  Print ("������ BUY � SELL ������� ������� �������");
               if(Info>=1) {PlaySound("alert.wav"); Sleep(2000);}
              }
            else Print("������ ������� �������� ������� BUY � SELL");
            return(0);
           }
        }
         
 //--------------------------------------------------------------------------       
      if(guiIsClicked(hwnd,closesellbtn))
        {
            if(Info) Print("��������� SELL ������ �������");
            OrdersClose(2, Magic_martin, True, _Symbol, "");
            OrdersClose(2, Magic_piramid, True, _Symbol, "");              
        }     
//----------------------------------------------------------------------------        
      if(guiIsClicked(hwnd,closebuybtn))
        {
            if(Info) Print("��������� BUY ������ �������");
            OrdersClose(0, Magic_martin, True, _Symbol, "");
            OrdersClose(0, Magic_piramid, True, _Symbol, ""); 
        }
    }*/
//===============================================================================================
 int _order_number;  
   // �������� ����� ������ ����� ���������� �������� ����� - ������� �� ��������� NewCycle_ON
   if(isWorking){
      // �������� ���-�� �������� �������
      int _martin_cnt = OrdersGetCount(_Symbol, 99, Magic_martin, "", 0, 0);
      int _piramid_cnt = OrdersGetCount(_Symbol, 99, Magic_piramid, "", 0, 0);      
      if(_martin_cnt+_piramid_cnt == 0){
         // �������� ��������� �� �������� ������
         if(TimeFilter()){
            if(IsExpertEnabled()){
            if(CommentSet){ Comment(""); CommentSet = false; }
            // ���� �������� ������� ��� - �������� �������������� �����
            SendOrder(OP_BUY, GetLot(), Ask, Magic_martin, "0:start");
            Comment("�� �������� ������� ������ �������� "+DoubleToStr(PauseTradezamok,0)+" ���.");
            Sleep(PauseTradezamok*60000);
            Comment("");
            SendOrder(OP_SELL, GetLot(), Bid, Magic_martin, "0:start");
            
            Sleep(PauseTrade*1000); 
            }
         }else{
            if(AveregeLine > 0.0) AveregeLine = 0.0;
         }
         // �������������� ������������� �������� � ���������� ������� ������ �������������
         PiramidAutoStart = PiramidOn;
         PiramidStartLot = 0.0;
         StopMartin = false;
         StopPiramid = false;
      }else{
         //----------------------------------
         // �������� �� ������������� �������� ������ ��� ���������� ��������� StopLoss � ������ ��������
         if(!CloseByStopLoss()){         
            //----------------------------------
            // �������� �� �������� �� �� ��� �� ���������
            if(!CloseByTPAndTral()){
               //----------------------------------
               // �������� �� ����������� ��������� �������� ��� ���������� �������� �������� � ���������
               EnablePiramid();
               //----------------------------------
               // ������������� ������������ ����������� ������
               TrailVirtPendOrd();
               // �������� ����������� ���������� �������
               OpenVirtPendOrd();                         
               //----------------------------------                 
               // ������� ���������� � ��������� �������� Sell ������
               double dSellInfo[]; string sSellInfo[];
               bool _sell_opened = OrdersGetLastOpenInfo(_Symbol, OP_SELL, 99, "", dSellInfo, sSellInfo);
               //������� ���������� � ��������� �������� Buy ������
               double dBuyInfo[]; string sBuyInfo[];
               bool _buy_opened = OrdersGetLastOpenInfo(_Symbol, OP_BUY, 99, "", dBuyInfo, sBuyInfo);
               //----------------------------------
               // �������� �� ������������� �������             
               if (UseRevers) ReversPiramid(dSellInfo[7], dBuyInfo[7]);                
               //----------------------------------                                            
               if(_sell_opened){                  
                  // ��������� ��������� ������� ��������
                  PiramidBE(OP_SELL);
                  // ��������� ��������� ������� �������
                  MartinBE(OP_SELL);
                  // �������� ������� �������
                  MartinTrailing(OP_SELL);
                  // �������� ������� ��������
                  PiramidTrailing(OP_SELL);
                  // ��������� ������ ����������� ������
                  _order_number = StrToInteger(StringSubstr(sSellInfo[1],0,StringFind(sSellInfo[1],":")));
                  // �������� - ����� �� ��������� ������ ������
                  if(MartinOn && (Sell_flag == martin_flag || StringFind(sSellInfo[1],":start")>-1)
                     /*((StringFind(sSellInfo[1],":start")>-1 || StringFind(sSellInfo[1],":martin")>-1) &&
                     (!_buy_opened || StringFind(sBuyInfo[1],":martin")==-1))*/)
                  {
                     // �������� �� ���������� ������ ������� ����� ���������� ��������� ���-�� �����
                     if(!fStopMartin(_order_number)){
                        // �������� - ���������� �� �������� ���-�� ������� ��� �������� ������ ������
                        //if(NormalizeDouble(Bid-dSellInfo[3],Digits) >= GetMartinStepPip(_order_number)){                  
                        if(GetSignal(OP_SELL, dSellInfo[3], _order_number)){
                           // �������� �� �������� ������� ����� ���������� �������� ��������� ���-�� �������
                           if(Close_M_orders==0 || !CheckOpenOrdCnt(OP_SELL,_order_number)){
                              // ������� ���� ������� ����� �������
                              OpenLot = GetLot(2, dSellInfo[6], _order_number, Bid-dSellInfo[3], GetMartinStepPip(_order_number));
                              // �������� ������ ������ � ����������� �� ������
                              switch(Metod){
                                 case 1:
                                    if((MTS()==-1 && Vxod_MTS==1) || Vxod_MTS==0) //�������� ������ �� ���������� ������                                        
                                    SendOrder(OP_SELL, OpenLot, Bid, Magic_martin, DoubleToStr((_order_number+1),0)+":martin");
                                 
                                    Sleep(PauseTrade*1000);
      
                                    break;
                                 case 2:
                                    // �������� ��� �� �������� ���� ������ - ������ � ��� ��� ���������� ����� ����������
                                    if(MSellStop == 0.0){
                                       MSellStop = NormalizeDouble(Bid-Dist,Digits);
                                       MSellStopLot = OpenLot;
                                       MSellStopNumb= _order_number+1;
                                    }
                                    break;
                              }
                              Sell_flag = martin_flag;
                              GlobalVariableSet("Sell_flag",Sell_flag);
                           }
                        }
                     }                     
                  }
                  // �������� ����� �� ����������� ������ ��������
                  if((PiramidOn || PiramidAutoStart) && (Sell_flag == piramid_flag || StringFind(sSellInfo[1],":start")>-1)
                     /*(StringFind(sSellInfo[1],":start")>-1 || StringFind(sSellInfo[1],":piramid")>-1) &&
                     (!_buy_opened || StringFind(sBuyInfo[1],":piramid")==-1)*/)
                  {
                     // �������� �� ���������� ������ �������� ����� ���������� ��������� ���-�� �����
                     if(!fStopPiramid(_order_number)){
                        // �������� - ���������� �� �������� ���-�� ������� ��� �������� ������ ��������
                        if(NormalizeDouble(dSellInfo[3]-Bid,Digits) >= GetPiramidStepPip(_order_number)){                  
                           // �������� �� �������� ������� ����� ���������� �������� ��������� ���-�� �������
                           if(Close_P_orders==0 || !CheckOpenOrdCntP(OP_SELL,_order_number)){
                              OpenLot = dSellInfo[6];
                              if(PiramidAutoStart && !PiramidOn && _order_number==1) OpenLot = PiramidStartLot;
                              Print(" Sell piramid lot : ",OpenLot, " Orders sell : ", _order_number);
                              // �������� ������ �������� � ����������� �� ������
                              switch(Metod){
                                 case 1:
                                    if((MTS()==-1 && Vxod_MTS==1) || Vxod_MTS==0) //�������� ������ �� ���������� ������                                       
                                    SendOrder(OP_SELL, GetLot(3,OpenLot,_order_number), Bid, Magic_piramid, DoubleToStr((_order_number+1),0)+":piramid", dPiramidStopLoss, dPiramidTP);
                                    //
                                    Sleep(PauseTrade*1000);                                    
                                    break;
                                 case 2:
                                    if(PSellStop == 0.0){
                                       PSellStop = NormalizeDouble(Bid-Dist,Digits);
                                       PSellStopLot = GetLot(3,OpenLot, _order_number);                                          
                                       PSellStopNumb= _order_number+1;
                                       PSellStopStopLoss = dPiramidStopLoss;
                                       PSellStopTakeProfit = dPiramidTP;
                                    }
                                    break;
                              }
                              Sell_flag = piramid_flag;
                              GlobalVariableSet("Sell_flag",Sell_flag);
                           }
                        }
                     }                     
                  }
               }               
               //----------------------------------
               if(_buy_opened){
                  // ��������� ��������� ������� ��������
                  PiramidBE(OP_BUY);
                  // ��������� ��������� ������� �������
                  MartinBE(OP_BUY);
                  // �������� ������� �������
                  MartinTrailing(OP_BUY);
                  // �������� ������� ��������
                  PiramidTrailing(OP_BUY);
                  // ��������� ������ ����������� ������
                  _order_number = StrToInteger(StringSubstr(sBuyInfo[1],0,StringFind(sBuyInfo[1],":")));                  
                  // �������� - ����� �� ��������� ������ ������
                  if(MartinOn && (Buy_flag == martin_flag || StringFind(sSellInfo[1],":start")>-1)               
                     /*(StringFind(sBuyInfo[1],":start")>-1 || StringFind(sBuyInfo[1],":martin")>-1) &&
                     (!_sell_opened || StringFind(sSellInfo[1],":martin")==-1)*/)
                  {                     
                     // �������� �� ���������� ������ ������� ����� ���������� ��������� ���-�� �����
                     if(!fStopMartin(_order_number)){
                        // �������� - ���������� �� �������� ���-�� ������� ��� �������� ������ ������
                        //if(NormalizeDouble(dBuyInfo[3]-Ask,Digits) >= GetMartinStepPip(_order_number)){
                        if(GetSignal(OP_BUY, dBuyInfo[3], _order_number)){
                           // �������� �� �������� ������� ����� ���������� �������� ��������� ���-�� �������
                           if(Close_M_orders==0 || !CheckOpenOrdCnt(OP_BUY,_order_number)){
                              // ������ ���������� ����
                              OpenLot = GetLot(2, dBuyInfo[6], _order_number, dBuyInfo[3]-Ask, GetMartinStepPip(_order_number));
                              // �������� ������ ������ � ����������� �� ������
                              switch(Metod){
                                 case 1:
                                    if((MTS()==1 && Vxod_MTS==1) || Vxod_MTS==0) //�������� ������ �� ���������� ������       
                                    SendOrder(OP_BUY, OpenLot, Ask, Magic_martin, DoubleToStr((_order_number+1),0)+":martin");
                                    //
                                    Sleep(PauseTrade*1000);                                    
                                    break;
                                 case 2:
                                    // �������� ��� �� �������� ���� ������ - ������ � ��� ��� ���������� ����� ����������
                                    if(MBuyStop == 0.0){
                                       MBuyStop = NormalizeDouble(Ask+Dist,Digits);
                                       MBuyStopLot = OpenLot;
                                       MBuyStopNumb= _order_number+1;                                       
                                    }
                                    break;
                              }
                              Buy_flag = martin_flag;
                              GlobalVariableSet("Buy_flag",Buy_flag);
                           }
                        }
                     }                     
                  }
                  // �������� ����� �� ����������� ������ ��������
                  if((PiramidOn || PiramidAutoStart) && (Buy_flag == piramid_flag || StringFind(sSellInfo[1],":start")>-1)
                     /*(StringFind(sBuyInfo[1],":start")>-1 || StringFind(sBuyInfo[1],":piramid")>-1) &&
                     (!_sell_opened || StringFind(sSellInfo[1],":piramid")==-1)*/)
                  {                     
                     // �������� �� ���������� ������ �������� ����� ���������� ��������� ���-�� �����
                     if(!fStopPiramid(_order_number)){                           
                        // �������� - ���������� �� �������� ���-�� ������� ��� �������� ������ ��������
                        if(NormalizeDouble(Ask-dBuyInfo[3],Digits) >= GetPiramidStepPip(_order_number)){
                           // �������� �� �������� ������� ����� ���������� �������� ��������� ���-�� �������
                           if(Close_P_orders==0 || !CheckOpenOrdCntP(OP_BUY,_order_number)){
                              OpenLot = dBuyInfo[6];
                              if(PiramidAutoStart && !PiramidOn && _order_number==1) OpenLot = PiramidStartLot;
                              // �������� ������ �������� � ����������� �� ������
                              Print(" Buy piramid lot : ",OpenLot, " Orders buy : ", _order_number);
                              switch(Metod){
                                 case 1:
                                    if((MTS()==1 && Vxod_MTS==1) || Vxod_MTS==0) //�������� ������ �� ���������� ������                                        
                                    SendOrder(OP_BUY, GetLot(3, OpenLot, _order_number), Ask, Magic_piramid, DoubleToStr((_order_number+1),0)+":piramid", dPiramidStopLoss, dPiramidTP);
                                    //
                                    Sleep(PauseTrade*1000);      
                                    break;
                                 case 2:
                                    // �������� ��� �� �������� ���� ������ - ������ � ��� ��� ���������� ����� ����������
                                    if(PBuyStop == 0.0){
                                       PBuyStop = NormalizeDouble(Ask+Dist,Digits);                                          
                                       PBuyStopLot = GetLot(3, OpenLot, _order_number);                                          
                                       PBuyStopNumb= _order_number+1;
                                       PBuyStopStopLoss = dPiramidStopLoss;
                                       PBuyStopTakeProfit = dPiramidTP;
                                    }
                                    break;
                              }
                              Buy_flag = piramid_flag;
                              GlobalVariableSet("Buy_flag",Buy_flag);
                           }
                        }
                     }                     
                  }            
               }
            }
         }         
      }
   
      //----------------------------------
      // ��������������� ������������
      /*if(!InitDC){
         GetDCWithFontNameAndSize(FontName, FontSize);
         InitDC = true;
      }*/
      DrawInfo();
   }   
//----
  }
//+------------------------------------------------------------------+  
// �������� ���� ������� �������                                     +
//+------------------------------------------------------------------+
void MartinTrailing(int type){
   if(M_Trailing && M_TrailingStop > 0.0){
      // �������� ������ ������� ��� ���������� ���������
      int _tickets[][2];
      int _orders_cnt = 0,i;
      ArrayResize(_tickets,OrdersTotal());
      for(i=OrdersTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS)){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic_martin && OrderType()==type){
               _tickets[_orders_cnt][0] = OrderTicket();
               _tickets[_orders_cnt][1] = OrderOpenTime();
               _orders_cnt++;
            }
         }
      }
      // �������� ��� �� ���-�� ������� � ������ ���� ������ ��� ����� M_BU_Start
      if(M_Trailing_Start > 0 && _orders_cnt >= M_Trailing_Start){
         ArrayResize(_tickets,_orders_cnt);
         // ����������� ������ �� ������� �������� �������
         // ����� ������� � ������ ������ ����� �����, ������� ������ ������ ���������
         // � ����� ������ ����� ����� ������� ������� ����� ��������� ����� ���������
         ArrayTwoSortInt(_tickets, 1);
         // ��������� ��������� ��� ��� �������, ������� ������ ���� ����� M_BU_Start
         for(i=_orders_cnt-1;i>=M_Trailing_Start-1;i--){
            if(OrderSelect(_tickets[i][0],SELECT_BY_TICKET)){
               if(StringFind(OrderComment(),":start")==-1){
                 double _price,_new_sl;
                  bool t=false;
                  switch(OrderType()){
                     case OP_BUY:
                        
                        _price = OrderStopLoss();                     
                        if(_price == 0.0 || _price < OrderOpenPrice()) _price = OrderOpenPrice();
                        //
                        if(Bid >= NormalizeDouble(_price+dM_TrailingStop,Digits)){
                           _new_sl = NormalizeDouble(Bid-dM_TrailingStep,Digits);
                           if(NormalizeDouble(OrderStopLoss()-_new_sl,Digits)!=0.0 && _new_sl > _price){
                              t=OrderModify(OrderTicket(),OrderOpenPrice(),_new_sl,OrderTakeProfit(),OrderExpiration());
                           }
                        }
                        break;
                     case OP_SELL:
                         //bool t=false;
                        _price = OrderStopLoss();
                        if(_price == 0.0 || _price > OrderOpenPrice()) _price = OrderOpenPrice();
                        //
                        if(Ask <= NormalizeDouble(_price-dM_TrailingStop,Digits)){
                           _new_sl = NormalizeDouble(Ask+dM_TrailingStep,Digits);
                           if(NormalizeDouble(OrderStopLoss()-_new_sl,Digits)!=0.0 && _new_sl < _price){
                            t=OrderModify(OrderTicket(),OrderOpenPrice(),_new_sl,OrderTakeProfit(),OrderExpiration());
                           }
                        }
                        break;
                  }
               }
            }
         }
      }
   }
} 
//=======================================================================================================================
void PiramidTrailing(int type){
   if(P_Trailing && P_TrailingStop > 0.0){
      // �������� ������ ������� ��� ���������� ���������
      int _tickets[][2];
      int _orders_cnt = 0,i;
      ArrayResize(_tickets,OrdersTotal());
      for(i=OrdersTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS)){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic_piramid && OrderType()==type){
               _tickets[_orders_cnt][0] = OrderTicket();
               _tickets[_orders_cnt][1] = OrderOpenTime();
               _orders_cnt++;
            }
         }
      }
      // �������� ��� �� ���-�� ������� � ������ ���� ������ ��� ����� M_BU_Start
      if(P_Trailing_Start > 0 && _orders_cnt >= P_Trailing_Start){
         ArrayResize(_tickets,_orders_cnt);
         // ����������� ������ �� ������� �������� �������
         // ����� ������� � ������ ������ ����� �����, ������� ������ ������ ���������
         // � ����� ������ ����� ����� ������� ������� ����� ��������� ����� ���������
         ArrayTwoSortInt(_tickets, 1);
         // ��������� ��������� ��� ��� �������, ������� ������ ���� ����� M_BU_Start
         for(i=_orders_cnt-1;i>=P_Trailing_Start-1;i--){
            if(OrderSelect(_tickets[i][0],SELECT_BY_TICKET)){
               if(StringFind(OrderComment(),":start")==-1){
                double _price,_new_sl;
                 bool t=false;
                  switch(OrderType()){
                     case OP_BUY:
                    
                        _price = OrderStopLoss();                     
                        if(_price == 0.0 || _price < OrderOpenPrice()) _price = OrderOpenPrice();
                        //
                        if(Bid >= NormalizeDouble(_price+dP_TrailingStop,Digits)){
                           _new_sl = NormalizeDouble(Bid-dP_TrailingStep,Digits);
                           if(NormalizeDouble(OrderStopLoss()-_new_sl,Digits)!=0.0 && _new_sl > _price){
                             t= OrderModify(OrderTicket(),OrderOpenPrice(),_new_sl,OrderTakeProfit(),OrderExpiration());
                           }
                        }                     
                        break;
                     case OP_SELL:
                        _price = OrderStopLoss();
                        if(_price == 0.0 || _price > OrderOpenPrice()) _price = OrderOpenPrice();
                        //
                        if(Ask <= NormalizeDouble(_price-dP_TrailingStop,Digits)){
                           _new_sl = NormalizeDouble(Ask+dP_TrailingStep,Digits);
                           if(NormalizeDouble(OrderStopLoss()-_new_sl,Digits)!=0.0 && _new_sl < _price){
                              t=OrderModify(OrderTicket(),OrderOpenPrice(),_new_sl,OrderTakeProfit(),OrderExpiration());
                           }
                        }
                        break;
                  }
               }
            }
         }
      }
   }
}  
//+------------------------------------------------------------------+  
// ��������� ��������� ��� ������� �������                           +
//+------------------------------------------------------------------+
void MartinBE(int type){
   if(M_WL && M_WLstart > 0){
      // �������� ������ ������� ��� ���������� ���������
      int _tickets[][2];
      int _orders_cnt = 0,i;
      ArrayResize(_tickets,OrdersTotal());
      for(i=OrdersTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS)){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic_martin && OrderType()==type){
               _tickets[_orders_cnt][0] = OrderTicket();
               _tickets[_orders_cnt][1] = OrderOpenTime();
               _orders_cnt++;
            }
         }
      }
      // �������� ��� �� ���-�� ������� � ������ ���� ������ ��� ����� M_BU_Start
      if(M_BU_Start > 0 && _orders_cnt >= M_BU_Start){
         ArrayResize(_tickets,_orders_cnt);
         // ����������� ������ �� ������� �������� �������
         // ����� ������� � ������ ������ ����� �����, ������� ������ ������ ���������
         // � ����� ������ ����� ����� ������� ������� ����� ��������� ����� ���������
         ArrayTwoSortInt(_tickets, 1);
         // ��������� ��������� ��� ��� �������, ������� ������ ���� ����� M_BU_Start
         for(i=_orders_cnt-1;i>=M_BU_Start-1;i--){
            if(OrderSelect(_tickets[i][0],SELECT_BY_TICKET)){
               if(StringFind(OrderComment(),":start")==-1){
               double _new_sl;
               //--- ���� �������� � �����
               double com_swap = (OrderSwap()+OrderCommission())/OrderLots()*Point;
               if (IsTesting()) com_swap = (OrderSwap()/OrderLots()*Point)+(-1*(Test_com_in_pip*Point));
               //---  
               bool t=false;             
                  switch(OrderType()){
                     case OP_BUY:
                     
                        if(OrderStopLoss()==0.0 || OrderStopLoss() < NormalizeDouble(OrderOpenPrice()+dM_WLlevel-com_swap,Digits)){
                           if(Bid >= NormalizeDouble(OrderOpenPrice()+dM_WLstart-com_swap,Digits)){
                              _new_sl = NormalizeDouble(OrderOpenPrice()+dM_WLlevel-com_swap,Digits);
                              if(NormalizeDouble(OrderStopLoss()-_new_sl,Digits)!=0.0){    
                                t= OrderModify(OrderTicket(),OrderOpenPrice(),_new_sl,OrderTakeProfit(),OrderExpiration());
                              }
                           }
                        }
                        break;
                     case OP_SELL:
                        if(OrderStopLoss()==0.0 || OrderStopLoss() > NormalizeDouble(OrderOpenPrice()-dM_WLlevel+com_swap,Digits)){
                           if(Ask <= NormalizeDouble(OrderOpenPrice()-dM_WLstart+com_swap,Digits)){
                              _new_sl = NormalizeDouble(OrderOpenPrice()-dM_WLlevel+com_swap,Digits);
                              if(NormalizeDouble(OrderStopLoss()-_new_sl,Digits)!=0.0){    
                                 t=OrderModify(OrderTicket(),OrderOpenPrice(),_new_sl,OrderTakeProfit(),OrderExpiration());
                              }
                           }
                        }
                        break;
                  }
               }               
            }
         }
      }      
   }
}
//+------------------------------------------------------------------++
// ��������� ���������� ���������� ������� int �� ��������� ��������� ������� �������� � �������� ����������� ����������
// array - ����������� ��������� ������ int
// mode - ����������� ���������� (MODE_ASCEND - �� �����������; MODE_DESCEND - �� ��������)
//-// ��� ������������ ��������
void ArrayTwoSortInt(int &array[][], int key, int mode=MODE_ASCEND){ int dt_temp = 0,q,i,j;  int line = ArrayRange(array,0); int line2 = ArrayRange(array,1); if(key >= 0 && key < line2){ for(i=line-1;i>=0;i--){ for (j=0; j<i; j++){ if (mode==MODE_ASCEND){ if(array[j][key]>array[j+1][key]){ for(q=0;q<line2;q++){ dt_temp = array[j][q]; array[j][q] = array[j+1][q]; array[j+1][q] = dt_temp; } } }else{ if(array[j][key]<array[j+1][key]){ for(q=0;q<line2;q++){ dt_temp = array[j][q]; array[j][q] = array[j+1][q]; array[j+1][q] = dt_temp; } } } } } } }
//+------------------------------------------------------------------++
//=========================================================================================================
// ��������� ��������� ��� ������� ��������                                                               =
//=========================================================================================================
void PiramidBE(int type){
   if(P_WL && P_WLstart > 0){
      // �������� ������ ������� ��� ���������� ���������
      int _tickets[][2];
      int _orders_cnt = 0,i;
      ArrayResize(_tickets,OrdersTotal());
      for(i=OrdersTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS)){
            if(OrderSymbol()==Symbol() && OrderMagicNumber()==Magic_piramid && OrderType()==type){
               _tickets[_orders_cnt][0] = OrderTicket();
               _tickets[_orders_cnt][1] = OrderOpenTime();
               _orders_cnt++;
            }
         }
      }
      // �������� ��� �� ���-�� ������� � ������ ���� ������ ��� ����� M_BU_Start
      if(P_BU_Start > 0 && _orders_cnt >= P_BU_Start){
         ArrayResize(_tickets,_orders_cnt);
         // ����������� ������ �� ������� �������� �������
         // ����� ������� � ������ ������ ����� �����, ������� ������ ������ ���������
         // � ����� ������ ����� ����� ������� ������� ����� ��������� ����� ���������
         ArrayTwoSortInt(_tickets, 1);
         // ��������� ��������� ��� ��� �������, ������� ������ ���� ����� M_BU_Start
         for(i=_orders_cnt-1;i>=P_BU_Start-1;i--){
            if(OrderSelect(_tickets[i][0],SELECT_BY_TICKET)){               
               if(StringFind(OrderComment(),":start")==-1){
               double _new_sl;
               //--- ���� �������� � �����
               double com_swap = (OrderSwap()+OrderCommission())/OrderLots()*Point;
               if (IsTesting()) com_swap = (OrderSwap()/OrderLots()*Point)+(-1*(Test_com_in_pip*Point));
               //---
               bool t=false;
                  switch(OrderType()){
                     case OP_BUY:
                     
                        if(OrderStopLoss()==0.0 || OrderStopLoss() < NormalizeDouble(OrderOpenPrice()+dP_WLlevel-com_swap,Digits)){
                           if(Bid >= NormalizeDouble(OrderOpenPrice()+dP_WLstart-com_swap,Digits)){
                              _new_sl = NormalizeDouble(OrderOpenPrice()+dP_WLlevel-com_swap,Digits);
                              if(NormalizeDouble(OrderStopLoss()-_new_sl,Digits)!=0.0){    
                                t= OrderModify(OrderTicket(),OrderOpenPrice(),_new_sl,OrderTakeProfit(),OrderExpiration());
                              }
                           }
                        }
                        break;
                     case OP_SELL:
                        if(OrderStopLoss()==0.0 || OrderStopLoss() > NormalizeDouble(OrderOpenPrice()-dP_WLlevel+com_swap,Digits)){
                           if(Ask <= NormalizeDouble(OrderOpenPrice()-dP_WLstart+com_swap,Digits)){
                              _new_sl = NormalizeDouble(OrderOpenPrice()-dP_WLlevel+com_swap,Digits);
                              if(NormalizeDouble(OrderStopLoss()-_new_sl,Digits)!=0.0){    
                                t= OrderModify(OrderTicket(),OrderOpenPrice(),_new_sl,OrderTakeProfit(),OrderExpiration());
                              }
                           }
                        }
                        break;
                  }
               }
            }
         }
      }
   }
}
//+------------------------------------------------------------------+  
// ��������� ��������� �� �������� ��� �������� ������
bool GetSignal(int _type, double _price_open, int _order_number){
   bool _res = false;
   double _cci = 0.0;
   double _cci1 = 0.0;
   //
   switch(_type){
      case OP_SELL:
         // �������� - ���������� �� �������� ���-�� ������� ��� �������� ������ ������
         if(NormalizeDouble(Bid-_price_open,Digits) >= GetMartinStepPip(_order_number)){   
            if(CCI_On){
               _cci = CCI(0);
               _cci1 = CCI(1);               
               if(_cci <= Level && _cci1 > Level) _res = true;
            }else _res = true;
         }
         break;
      case OP_BUY:
         // �������� - ���������� �� �������� ���-�� ������� ��� �������� ������ ������
         if(NormalizeDouble(_price_open-Ask,Digits) >= GetMartinStepPip(_order_number)){   
            if(CCI_On){
               _cci = CCI(0);
               _cci1 = CCI(1);
               if(_cci >= -Level && _cci1 < -Level) _res = true;
            }else _res = true;
         }
         break;      
   }
   return(_res);   
}  
//+------------------------------------------------------------------+
// ���������� �������� ���������� ��I � ��������� �����������
double CCI(int _bar){ return(NormalizeDouble(iCCI(NULL,CCI_TimeFrame,Period_CCI,PRICE_CLOSE,_bar),4)); }
//+------------------------------------------------------------------+
// ��������� ���������� �� �������� ��������� ������
// ���� �� - ��������� ��� ����� ������� � ���������� true
bool CheckOpenOrdCnt(int _type, int _current_cnt){
   bool _res = false;
   
   if(Close_M_orders > 0 && _current_cnt >= Close_M_orders-1){      
      // ������� ��� ������ 
      for(int i=OrdersTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS)){
            if(OrderSymbol()==_Symbol && OrderMagicNumber()==Magic_martin && OrderType()==_type)
            {
               OrdersClose(33, OrderTicket(), false, _Symbol, "");
            }
         }         
      }
      _res = true;
   }   
   return(_res);
}
//+------------------------------------------------------------------+
// ��������� ���������� �� �������� ��������� ������
// ���� �� - ��������� ��� ����� ������� � ���������� true
bool CheckOpenOrdCntP(int _type, int _current_cnt){
   bool _res = false;   
   if(Close_P_orders > 0 && _current_cnt >= Close_P_orders-1){      
      // ������� ��� ������ 
      for(int i=OrdersTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS)){
            if(OrderSymbol()==_Symbol && 
               (OrderMagicNumber()==Magic_piramid || StringFind(OrderComment(),":start")>-1) && 
               OrderType()==_type)
            {
               OrdersClose(33, OrderTicket(), false, _Symbol, "");
            }
         }         
      }
      _res = true;
   }   
   return(_res);
}
//+------------------------------------------------------------------+
// ��������� true ���� ��������� �������� � ������� �����

bool TimeFilter(){

 bool _res = false;
   datetime _time_curent = TimeCurrent();
   datetime _time_start = StrToTime(DoubleToStr(Year(),0)+"."+DoubleToStr(Month(),0)+"."+DoubleToStr(Day(),0)+" "+StartHour);
   datetime _time_stop = StrToTime(DoubleToStr(Year(),0)+"."+DoubleToStr(Month(),0)+"."+DoubleToStr(Day(),0)+" "+EndHour);
   if(((Trade_in_Monday==true) && (TimeDayOfWeek(Time[0]) == 1)) ||
   ((Trade_in_Tuesday==true) && (TimeDayOfWeek(Time[0]) == 2)) ||
   ((Trade_in_Wednesday==true) && (TimeDayOfWeek(Time[0]) == 3)) ||
   ((Trade_in_Thursday==true) && (TimeDayOfWeek(Time[0]) == 4)) ||
   ((Trade_in_Friday==true) && (TimeDayOfWeek(Time[0]) == 5)))
   
   
   if(_time_start > _time_stop){
      if(_time_curent >= _time_start || _time_curent <= _time_stop) _res = true;
   }else   
      if(_time_curent >= _time_start && _time_curent <= _time_stop) _res = true;
      
      return(_res); 
  
 }     
     

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



//+------------------------------------------------------------------+
// �������������� �����������
void DrawInfo(){
   if(Info){
      //
      int _x = PositionX,i;
      int _y = PositionY;
      color _clr = CLR_NONE;
      string sInfo[9];
      //---- ���� ������      
      double _buy_lot = OrdersGetOpenLot(_Symbol, OP_BUY, 99, "", 0, 0);
      sInfo[0] = DoubleToStr(_buy_lot,iDigitLot);      
      double _sell_lot = OrdersGetOpenLot(_Symbol, OP_SELL, 99, "", 0, 0);
      sInfo[1] = DoubleToStr(_sell_lot,iDigitLot);      
      double _buy_result = OrdersGetProfit(99, OP_BUY, _Symbol, "");
      sInfo[2] = DoubleToStr(_buy_result,2);      
      double _sell_result = OrdersGetProfit(99, OP_SELL, _Symbol, "");
      sInfo[3] = DoubleToStr(_sell_result,2);      
      double _all_result = NormalizeDouble(_buy_result+_sell_result,2);      
      sInfo[4] = DoubleToStr(_all_result,2);      
      // dd
      double _dd = 0.0;
      if(_all_result < 0.0) _dd = NormalizeDouble((_all_result/AccountBalance())*100,2);
      sInfo[5] = DoubleToStr(_dd,2);
      //  balance
      double _balance = AccountBalance();
      sInfo[6] = DoubleToStr(_balance,2);
      // equity
      double _equity = AccountEquity();
      double _equity_persent = NormalizeDouble((_equity/_balance)*100,2);
      sInfo[7] = DoubleToStr(AccountFreeMargin(),2);
      // level
      sInfo[8] = DoubleToStr(InfoGetMarginLevel(),2);      
      //---- ��������� ������ ����� ������� ������
      int _max_size = 0; int _temp_size = 0;
      for(i=0;i<9;i++){
         //_temp_size = GetStringSizeInPix(sInfo[i]);         
         if(_temp_size > _max_size) _max_size = _temp_size;
      }
      _max_size += (_x+50);
      // ----
      // �������� / ����������� �������������� ������ 
      if(_buy_lot == 0.0) _clr = White; else _clr = clrDeepSkyBlue;      
      Label("BuyVolume", _max_size, _y, "����� Buy:", BaseColor);
      Label("vBuyVolume", _x, _y, sInfo[0], _clr);
      
      _y += FontSize + 5;
      
      if(_sell_lot == 0.0) _clr = White; else _clr = clrRed;      
      Label("SellVolume", _max_size, _y, "����� Sell:", BaseColor);
      Label("vSellVolume", _x, _y, sInfo[1], _clr);
      
      _y += FontSize + 5;
      
      if(_buy_result == 0.0) _clr = White; else if(_buy_result < 0.0) _clr = Red; else _clr = clrDeepSkyBlue;
      Label("BuyProfit", _max_size, _y, "������ Buy:", BaseColor);
      Label("vBuyProfit", _x, _y, sInfo[2], _clr);
      
      _y += FontSize + 5;
      
      if(_sell_result == 0.0) _clr = White; else if(_sell_result < 0.0) _clr = Red; else _clr = clrDeepSkyBlue;
      Label("SellProfit", _max_size, _y, "������ Sell:", BaseColor);
      Label("vSellProfit", _x, _y, sInfo[3], _clr);
      
      _y += FontSize + 5;
      
      if(_all_result == 0.0) _clr = White; else if(_all_result < 0.0) _clr = Red; else _clr = clrDeepSkyBlue;
      Label("AllProfit", _max_size, _y, "��������� ������:", BaseColor);
      Label("vAllProfit", _x, _y, sInfo[4], _clr);
            
      _y += FontSize + 5;
      
      if(_dd == 0.0) _clr = White; else _clr = clrDarkOrange;
      Label("DD", _max_size, _y, "��������:", BaseColor);
      Label("vDD", _x, _y, sInfo[5], _clr);
      
      _y += FontSize + 10;
      
      Label("Balance", _max_size, _y, "������:", BaseColor);
      Label("vBalance", _x, _y, sInfo[6], clrDeepSkyBlue);
      
      _y += FontSize + 5;
      
      if(_equity_persent > 80) _clr = clrGreen; else if(_equity_persent > 50) _clr = clrDeepSkyBlue; else if(_equity_persent > 30) _clr = clrDarkOrange; else _clr = clrRed;
      Label("Equity", _max_size, _y, "��������:", BaseColor);
      Label("vEquity", _x, _y, sInfo[7], _clr);
      
      _y += FontSize + 5;
      
      Label("Level", _max_size, _y, "�������:", BaseColor);
      Label("vLevel", _x, _y, sInfo[8], clrDeepSkyBlue);
      
      _y += FontSize + 15;
         
      if(TralPrice > 0.0){         
         Label("vTral", _x, _y, "> �������� �������� ���� <", clrDarkOrange);
         _y += FontSize + 5;
      }else{
         if(ObjectFind(sPrefIndPan+"vTral")>-1) ObjectDelete(sPrefIndPan+"vTral");
      }
      
      if(!NewCycle_ON){         
         Label("vNewCycle_ON", _x, _y, "> ������ NewCycle <", clrDarkOrange);
         _y += FontSize + 5;
      }else{
         if(ObjectFind(sPrefIndPan+"vNewCycle_ON")>-1) ObjectDelete(sPrefIndPan+"vNewCycle_ON");
      }
      
      if(!PiramidOn && PiramidAutoStart){
         Label("vPiramidAutoStart", _x, _y, "> ����������� �������� ��� <", clrDarkOrange);
         _y += FontSize + 5;
      }else{
         if(ObjectFind(sPrefIndPan+"vPiramidAutoStart")>-1) ObjectDelete(sPrefIndPan+"vPiramidAutoStart");
      }
      
      if(StopMartin){
         Label("vStopMartin", _x, _y, "> ����������� ���������� ���� <", clrDarkOrange);
         _y += FontSize + 5;
      }else{
         if(ObjectFind(sPrefIndPan+"vStopMartin")>-1) ObjectDelete(sPrefIndPan+"vStopMartin");
      }
      
      if(StopPiramid){
         Label("vStopPiramid", _x, _y, "> ����������� �������� ���� <", clrDarkOrange);
         _y += FontSize + 5;
      }else{
         if(ObjectFind(sPrefIndPan+"vStopPiramid")>-1) ObjectDelete(sPrefIndPan+"vStopPiramid");
      
      }
      
      //---- ������ � ������� ����� �������
      GraphDelete(sPref);
      // ���������� ������
      int _bar_on_chart = WindowBarsPerChart();
      int _need_bar = _bar_on_chart / 2; 
      int _first_visible_bar = WindowFirstVisibleBar();
      datetime _time_bar = Time[_first_visible_bar] + ((Period()*60) * _need_bar);
      //      
      if(AveregeLine > 0.0){
         GraphHLineCreate(sPref+"AverLine", AveregeLine, BULineColor, STYLE_SOLID, 1);
         GraphTextCreate(sPref+"txtAverLine",0, _time_bar, AveregeLine, BULineColor, FontSize, 0.0, "������� ��", FontName);
         
         GraphHLineCreate(sPref+"TPLine", TPLine, TPLineColor, STYLE_SOLID, 1);
         GraphTextCreate(sPref+"txtTPLine",0, _time_bar, TPLine, TPLineColor, FontSize, 0.0, "������� ��", FontName);
      }
      if(TralStartPrice > 0.0){
         GraphHLineCreate(sPref+"TralPrice", TralStartPrice, DarkOrange, STYLE_SOLID, 1);
         GraphTextCreate(sPref+"txtTralPrice",0, _time_bar, TralStartPrice, DarkOrange, FontSize, 0.0, "������ ������ �����", FontName);
      }else
      if(TralPrice > 0.0){
         GraphHLineCreate(sPref+"TralPrice", TralPrice, DarkOrange, STYLE_SOLID, 1);
         GraphTextCreate(sPref+"txtTralPrice",0, _time_bar, TralPrice, DarkOrange, FontSize, 0.0, "�������� ����", FontName);
      }
            
      if(MBuyStop > 0.0){
         GraphHLineCreate(sPref+"MBuyStop", MBuyStop, BuyStopColor, STYLE_SOLID, 1);
         GraphTextCreate(sPref+"txtMBuyStop",0, _time_bar, MBuyStop, BuyStopColor, FontSize, 0.0, "BUY", FontName);
      }
      if(MSellStop > 0.0){
         GraphHLineCreate(sPref+"MSellStop", MSellStop, SellStopColor, STYLE_SOLID, 1);
         GraphTextCreate(sPref+"txtMSellStop",0, _time_bar, MSellStop, SellStopColor, FontSize, 0.0, "SELL", FontName);
      }
      if(PBuyStop > 0.0){
         GraphHLineCreate(sPref+"PBuyStop", PBuyStop, BuyStopColor, STYLE_SOLID, 1);
         GraphTextCreate(sPref+"txtPBuyStop",0, _time_bar, PBuyStop, BuyStopColor, FontSize, 0.0, "BUY", FontName);
      }
      if(PSellStop > 0.0){
         GraphHLineCreate(sPref+"PSellStop", PSellStop, SellStopColor, STYLE_SOLID, 1);
         GraphTextCreate(sPref+"txtPSellStop",0, _time_bar, PSellStop, SellStopColor, FontSize, 0.0, "SELL", FontName);
      }      
      //---- ����������� �������� ��� ������� ������      
     /* string _ord_text = "";
      _bar_on_chart = WindowBarsPerChart();
      _need_bar = _bar_on_chart / 4; 
      _first_visible_bar = WindowFirstVisibleBar();
      _time_bar = Time[_first_visible_bar] + ((Period()*60) * _need_bar);
      //
      for(i=OrdersTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS)){
            if(OrderSymbol()==Symbol() && (OrderMagicNumber()==Magic_martin || OrderMagicNumber()==Magic_piramid)){
               _ord_text = "Lot:"+DoubleToStr(OrderLots(),iDigitLot)+" Prof:"+DoubleToStr(OrderProfit()+OrderSwap()+OrderCommission(),2);
               GraphTextCreate(sPref+":"+DoubleToStr(OrderTicket(),0),0, _time_bar, OrderOpenPrice(), DeepSkyBlue, FontSize, 0.0, _ord_text, FontName);
            }
         }
      }*/
   }   
}

//+------------------------------------------------------------------+
// �������� / ��������� �������������� ������
void Label(string _name, int _x, int _y, string _text, color _clr){   
   _name = sPrefIndPan+_name;
   if(ObjectFind(_name)==-1){
      GraphLabelCreate(0, _name, _x, _y, 1, _text, FontSize, FontName, _clr);
   }else{
      if(ObjectGet(_name, OBJPROP_COLOR) != _clr) ObjectSet(_name,OBJPROP_COLOR,_clr);
      if(ObjectGet(_name, OBJPROP_XDISTANCE) != _x) ObjectSet(_name,OBJPROP_XDISTANCE,_x);
      if(ObjectGet(_name, OBJPROP_YDISTANCE) != _y) ObjectSet(_name,OBJPROP_YDISTANCE,_y);
      if(ObjectDescription(_name) != _text) ObjectSetText(_name, _text, FontSize);
   }
}
//+------------------------------------------------------------------+
// ������� ������� ������ Horisontal Line ��������� �����, �����
void GraphHLineCreate(string sName, double _dPrice, color MyColor, int _iStyle, int _iWidth){ObjectCreate(sName,OBJ_HLINE,0,0,_dPrice);ObjectSet(sName,OBJPROP_COLOR,MyColor);ObjectSet(sName,OBJPROP_STYLE,_iStyle); ObjectSet(sName,OBJPROP_WIDTH,_iWidth); }
//+------------------------------------------------------------------+
// ������� ������� ������ Label � �������� ����(�������) ������� � �������� ���������, �������, �������, �������� ������, ������ ������, � ������������ �� ������ � � y
void GraphLabelCreate(int Handle, string NameObject, int x, int y, int Corn, string text, int _FontSize, string _FontName, color FontColor){ObjectCreate(NameObject, OBJ_LABEL, Handle, 0, 0);ObjectSet(NameObject, OBJPROP_CORNER, Corn); ObjectSet(NameObject, OBJPROP_XDISTANCE, x); ObjectSet(NameObject, OBJPROP_YDISTANCE, y); ObjectSetText(NameObject, text, _FontSize, _FontName, FontColor);}
//+------------------------------------------------------------------+
// ������� ������� ������ Text � ��������� ����(�������) ������� � �������� ���������, �������, �������, �������� �����, ������ ������, ����� ������� ������
void GraphTextCreate(string _n,int _h, datetime x, double y, color _c,int _FontSize, double _Angle, string _text, string _FontName){ ObjectCreate(_n, OBJ_TEXT, _h, x, y); ObjectSet(_n, OBJPROP_ANGLE, _Angle); ObjectSetText(_n, _text, _FontSize, _FontName, _c); }
//+------------------------------------------------------------------+
// ���������� �������� ��������� ��������� ������� ������� � �������� ��������� ������� � �������� ������ 
// ����������� ����� ������� ������� 
/*void GetDCWithFontNameAndSize(string _font_name, int _font_size){      
   DC_hWnd=WindowHandle(Symbol(), Period());   
   DC_hnd = GetDC(DC_hWnd);
   int dpi=GetDeviceCaps(DC_hnd,88);  //88=LOGPIXELSX   
   int fontheight = MathRound(_font_size*dpi/72.0);
   DC_hFont=CreateFontA(fontheight,0,0,0,0,0,0,0,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH|FF_MODERN,_font_name); 
   SelectObject(DC_hnd,DC_hFont);
}
// ����������� ������� DC � Font
void DCRelease(){ ReleaseDC(DC_hWnd,DC_hnd); DeleteObject(DC_hFont); DC_hWnd = 0; DC_hFont = 0; DC_hnd = 0; }
// �������� ������ ������ � ��������
int GetStringSizeInPix(string _str){ 
   int size[2];    
   GetTextExtentPoint32A(DC_hnd,_str,StringLen(_str),size); 
   return(size[0]+4); 
}*/
//+------------------------------------------------------------------+
// ������� ������������ ������� ����� � ��������� 
double InfoGetMarginLevel(){ double dMarginNow = AccountMargin(); if(dMarginNow==0) dMarginNow = 1; return(NormalizeDouble(((AccountEquity()/dMarginNow)*100),2)); }
//+------------------------------------------------------------------+
// ������� ���������� ���������� � ��������� �������� ������ (����� ��� �� ������)
////// ��������:
// _symbol     - ���������� ��� ������ ������ ("" - ����� �� ���� ������������)
// _type_order - ��� �������� ������ (-1 - ����� ���)
//               ��������� �����:
//               99 - ��� ������
//               10 - Buy � Sell
//               50 - ���������� (BuyStop, BuyLimit, SellStop, SellLimit)
//               51 - BuyStop � BuyLimit
//               52 - SellStop � SellLimit
//               53 - BuyStop � SellStop
//               54 - BuyLimit � SellLimit
// _magic      - ���������� ����� ������ ���:
//               -1 - ����� �� ������� �� ����������� ������
//               99 - ����� �� �������� Magic_martin � Magic_piramid
// _comment    - ������ ������� ������ ��������� ����������� ������ ("" - ����� �� ������� �� ����������� ������)
////// ����������� ������� (���������):
// dblInfo - ������ ��������� ���� (����� ���������� �������� �������):
//           0 - OrderTicket, ����� ������ ������
//           1 - OrderType, ��� ������
//           2 - OrderOpenTime, ����� �������� ������
//           3 - OrderOpenPrice, ���� �������� ������
//           4 - OrderStopLoss, ���� �������� ������� ��� ���������� ������ �����������
//           5 - OrderTakeProfit, ���� �������� ������� ��� ���������� ������ ������������
//           6 - OrderLots, ����� ������
//           7 - OrderMagicNumber, ���������� ����� ������
//           8 - OrderProfit, �������� ������ ������� 
//           9 - OrderCommission, �������� ������������ �������� 
//           10- OrderSwap, �������� �����
// strInfo - ������ ���������� ����:
//           0 - OrderSymbol, ���������� �� �������� ������ ������
//           1 - OrderComment, ����������� ���������� ������
//-// true ���� ���������� �������, false � ��������� ������
bool OrdersGetLastOpenInfo(string _symbol, int _type_order, int _magic, string _comment, double& dblInfo[], string& strInfo[]){    
   bool res = false; 
   datetime time = 0;
   int ticket = 0; 
   
   for(int i=OrdersTotal()-1;i>=0;i--){ 
      if(OrderSelect(i,SELECT_BY_POS)){ 
         if((time==0 || OrderOpenTime()>time) && 
            (_symbol=="" || OrderSymbol()==_symbol) && 
            (_type_order==-1 || InfoisTypeOrdPartOfGroup(OrderType(), _type_order)) && 
            (_magic==-1 || _magic==OrderMagicNumber() || (_magic==99 && (Magic_martin==OrderMagicNumber() || Magic_piramid==OrderMagicNumber()))) && 
            (_comment=="" || StringFind(OrderComment(),_comment)!=-1)) 
         { 
            time = OrderOpenTime(); 
            ticket = OrderTicket(); 
         } 
      } 
   } 
   if(time>0){ 
      if(OrderSelect(ticket,SELECT_BY_TICKET)){ 
         ArrayResize(dblInfo,11); ArrayInitialize(dblInfo,0); 
         ArrayResize(strInfo,2); 
         dblInfo[0] = OrderTicket(); 
         dblInfo[1] = OrderType(); 
         dblInfo[2] = OrderOpenTime(); 
         dblInfo[3] = OrderOpenPrice(); 
         dblInfo[4] = OrderStopLoss(); 
         dblInfo[5] = OrderTakeProfit(); 
         dblInfo[6] = OrderLots(); 
         dblInfo[7] = OrderMagicNumber(); 
         dblInfo[8] = OrderProfit(); 
         dblInfo[9] = OrderCommission(); 
         dblInfo[10]= OrderSwap(); 
         strInfo[0] = OrderSymbol(); 
         strInfo[1] = OrderComment(); 
         res = true; 
      } 
   } 
   if(!res){ 
      ArrayResize(dblInfo,0); 
      ArrayResize(strInfo,0); 
   } 
   return(res); 
}
//+------------------------------------------------------------------+
// ��������� �������� �� �� � ���������
//-// ���������� true ���� ������ ���� �������
bool CloseByTPAndTral(){
   bool _res = false;
   //
   if(TralPrice > 0.0){
      switch(TralType){
         case OP_BUY:
            if(Bid <= TralPrice){               
               PlaySound("wait.wav");         
               OrdersClose(33, Magic_martin, true, _Symbol, "");
               OrdersClose(33, Magic_piramid, true, _Symbol, "");
               OpenCloseLineDraw();
               
               if(!NewCycle_ON) isWorking = false;
               else{
                  Sleep(PauseTrade2*60000);
               }
               TralPrice = 0.0;
               StopMartin = false;
               StopPiramid = false;
               return(true);
            }else{
               if(NormalizeDouble(Bid-TralPrice,Digits) >= Tral_Size){
                  TralPrice = NormalizeDouble(Bid-Tral_Size,Digits);
               }               
            }
            break;
         case OP_SELL:
            if(Ask >= TralPrice){
               PlaySound("wait.wav");         
               OrdersClose(33, Magic_martin, true, _Symbol, "");
               OrdersClose(33, Magic_piramid, true, _Symbol, "");
               OpenCloseLineDraw();
               
               if(!NewCycle_ON) isWorking = false;
               else{
                  Sleep(PauseTrade2*60000);
               }
               TralPrice = 0.0;
               StopMartin = false;
               StopPiramid = false;
               return(true);
            }else{
               if(NormalizeDouble(TralPrice-Ask,Digits) >= Tral_Size){
                  TralPrice = NormalizeDouble(Ask+Tral_Size,Digits);
               }               
            }
            break;         
      }
   }else{
      // �������� ���������� ������ StartTral
      if(TralStartPrice > 0.0){
         switch(TralType){
            case OP_BUY:
               if(NormalizeDouble(Bid-TralStartPrice,Digits) >= 0.0){
                  TralPrice = NormalizeDouble(Bid-Tral_Size,Digits);
                  PlaySound("wait.wav");         
                  OrdersClose(2, Magic_piramid, true, _Symbol, "");
                  OrdersClose(2, Magic_martin, true, _Symbol, "");
                  OpenCloseLineDraw();
                  
                  TralStartPrice = 0.0;
                  return(true);
               }
               break;
            case OP_SELL:
               if(NormalizeDouble(TralStartPrice-Ask,Digits) >= 0.0){
                  TralPrice = NormalizeDouble(Ask+Tral_Size,Digits);
                  PlaySound("wait.wav");         
                  OrdersClose(0, Magic_piramid, true, _Symbol, "");
                  OrdersClose(0, Magic_martin, true, _Symbol, "");
                  OpenCloseLineDraw();
                  
                  TralStartPrice = 0.0;
                  return(true);
               }
               break;
         }
      }      
      // ���������� �������� ������ Buy � Sell
      double _buy_lot = OrdersGetOpenLot(_Symbol, OP_BUY, 99, "", 0, 0);
      double _sell_lot = OrdersGetOpenLot(_Symbol, OP_SELL, 99, "", 0, 0);
      // ��������� ����� ����������� ����� ������� �����
      int _type_ord_tp = EMPTY; if(_buy_lot > _sell_lot) _type_ord_tp = OP_BUY; else if(_buy_lot < _sell_lot) _type_ord_tp = OP_SELL;
      // ��������� ������� ���� ��� ������������ ����
      double _aver_price = 0.0;
      double _tp_line = 0.0;
      //
      switch(_type_ord_tp){
         case OP_BUY:
            //_aver_price = OrdersGetAveragePrice(_Symbol, OP_BUY, 99, "", 0, 0);
            _aver_price = AveragePriceAllSeries(_buy_lot, _sell_lot);
            if(_aver_price > 0.0){
               _tp_line = NormalizeDouble(_aver_price + DefaultProfit,Digits);
               // ���� ���������� ����� ��
               if(Bid >= _tp_line){
                  // ������ ��� ���������� ������
                  MBuyStop    = 0.0;
                  MBuyStopLot = 0.0;
                  MBuyStopNumb= 0.0;                        
                  PSellStop    = 0.0;
                  PSellStopLot = 0.0;
                  PSellStopNumb= 0.0;
                  PSellStopStopLoss=0.0;
                  PSellStopTakeProfit=0.0;
                  // �������� ����� �� ������� ��� ������ ����� ��� ������ ����� - ��������� �������
                  if(!Trall_on){
                     // �������� ���� ������ ������� ��������
                     PlaySound("wait.wav");         
                     OrdersClose(33, Magic_martin, true, _Symbol, "");
                     OrdersClose(33, Magic_piramid, true, _Symbol, "");
                     OpenCloseLineDraw();
                     
                     if(!NewCycle_ON) isWorking = false;
                     _res = true;
                  }else{
                     // ��������� ������� ������ ���������
                     TralStartPrice = NormalizeDouble(_tp_line+Tral_Start,Digits); 
                     TralType = OP_BUY;
                  }
               }else{
                  TralStartPrice = 0.0;
                  TralType = EMPTY;
               }
            }
            break;
         case OP_SELL:
            //_aver_price = OrdersGetAveragePrice(_Symbol, OP_SELL, 99, "", 0, 0);
            _aver_price = AveragePriceAllSeries(_buy_lot, _sell_lot);
            if(_aver_price > 0.0){
               _tp_line = NormalizeDouble(_aver_price - DefaultProfit,Digits);
               // ���� ���������� ����� ��
               if(Ask <= _tp_line){
                  // ������ ��� ���������� ������
                  MSellStop    = 0.0;
                  MSellStopLot = 0.0;
                  MSellStopNumb= 0.0;   
                  PBuyStop    = 0.0;
                  PBuyStopLot = 0.0;
                  PBuyStopNumb= 0.0;
                  PBuyStopStopLoss=0.0;
                  PBuyStopTakeProfit=0.0;              
                  // �������� ����� �� ������� ��� ������ ����� ��� ������ ����� - ��������� �������
                  if(!Trall_on){
                     // �������� ���� ������ ������� ��������
                     PlaySound("wait.wav");         
                     OrdersClose(33, Magic_martin, true, _Symbol, "");
                     OrdersClose(33, Magic_piramid, true, _Symbol, "");
                     OpenCloseLineDraw();
                     
                     if(!NewCycle_ON) isWorking = false;
                     _res = true;                  
                  }else{
                     // ��������� ������� ������ ���������                    
                     TralStartPrice = NormalizeDouble(_tp_line-Tral_Start,Digits); 
                     TralType = OP_SELL;                  
                  }
               }else{
                  TralStartPrice = 0.0;
                  TralType = EMPTY;
               }
            }
            break;
      }
      //
      AveregeLine = _aver_price;
      TPLine = _tp_line;
   }
   return(_res);
}
//+------------------------------------------------------------------+
// ������� ����������� ������� ���� ���� �������� ������� ������ �����������
double AveragePriceAllSeries(double _buy_lot, double _sell_lot){
   double _res = 0.0;
   
   double _buy_aver_price = OrdersGetAveragePrice(_Symbol, OP_BUY, 99, "", 0, 0);
   double _sell_aver_price = OrdersGetAveragePrice(_Symbol, OP_SELL, 99, "", 0, 0);   
   double _lock_point = NormalizeDouble((_sell_aver_price-_buy_aver_price)/Point,0);
   double _lock_in_currency = 0.0;
   double _price_of_point = InfoGetPriceOfPoint(_Symbol);
   
   // ��������� �������� ����� �� ������ �� ����������� ��� �������
   if(_buy_aver_price == 0.0 && _sell_aver_price > 0.0){
      _res = _sell_aver_price;
   }else{
      if(_buy_aver_price > 0.0 && _sell_aver_price == 0.0){
         _res = _buy_aver_price;      
      }else{      
         if(_buy_lot < _sell_lot) _lock_in_currency = NormalizeDouble(_lock_point*(_price_of_point*_buy_lot),2);
         else{ 
            if(_lock_point > 0) _lock_point = -_lock_point;
            else _lock_point = MathAbs(_lock_point);
            _lock_in_currency = NormalizeDouble(_lock_point*(_price_of_point*_sell_lot),2);
         }

         double _target_lot = NormalizeDouble(MathAbs(_buy_lot-_sell_lot),iDigitLot);
         if(_target_lot > 0.0){
            int _target_pip = _lock_in_currency / (_target_lot * _price_of_point);
            double _target_point = NormalizeDouble(_target_pip*Point,Digits);
   
            if(_buy_lot > _sell_lot){
               _res = NormalizeDouble(_buy_aver_price + _target_point,Digits);
            }else{
               _res = NormalizeDouble(_sell_aver_price + _target_point,Digits);
            }   
         }
      }
   }
   return(_res);
}
//+------------------------------------------------------------------+
//������� ��������� ��������� ������ ������ �� �������� ���� � ������ �������� � ������� �� 1 ���
double InfoGetPriceOfPoint(string B){RefreshRates();double S = 0; if(B!=""){S = MarketInfo(B,MODE_TICKVALUE)/(MarketInfo(B,MODE_TICKSIZE)/MarketInfo(B,MODE_POINT));}return(S);}
//+------------------------------------------------------------------+
// ������� ����������� ������� ���� � ������� �� �������� ����������
// _symbol - ���������� ("", ����� ����������)
// _type   - ��� ������� (-1, ����� ��� �������)
// _magic  - ���������� ����� ������� ��������� ���:
//           -1 - �� ������ ����������� ������
//           99 - ����� �� �������� Magic_martin � Magic_piramid
// _comm   - ������ ������� ������ ����������� � ����������� ("", � ����� ������������)
// minOpenTime - ����� �������� ������ ������ ���� ������ ��� ����� ��������� (0 - �� ������������)
// maxOpenTime - ����� �������� ������ ������ ���� ������ ��� ����� ��������� (0 - �� ������������)
//-// ������������ ��������: ������� ���� ��� 0 � ��������� ������
double OrdersGetAveragePrice(string _symbol, int _type, int _magic, string _comm, datetime minOpenTime, datetime maxOpenTime){ 
   double dRes = 0, dSumLot=0, swap_comm = 0; 
   int _cnt_orders = 0;
   double point_cost = InfoGetPriceOfPoint(_Symbol);
   
   for(int i=OrdersTotal()-1;i>=0;i--){ 
      if(OrderSelect(i,SELECT_BY_POS)){ 
         if((_symbol=="" || OrderSymbol()==_symbol) && 
            (_magic==-1 || OrderMagicNumber()==_magic || (_magic==99 && (OrderMagicNumber()==Magic_martin || OrderMagicNumber()==Magic_piramid))) && 
            (_type==-1 || OrderType()==_type) && 
            (_comm=="" || StringFind(OrderComment(),_comm)!=-1) && 
            (minOpenTime==0 || OrderOpenTime()>=minOpenTime) && 
            (maxOpenTime==0 || OrderOpenTime()<=maxOpenTime))
         { 
         //--- ���� �������� � �����
            if (OrderType() == OP_BUY) {
               swap_comm = ((-1*OrderCommission())+OrderSwap())/OrderLots()*Point;              
               if (IsTesting()) swap_comm = (OrderSwap()/OrderLots()*Point)+(Test_com_in_pip*Point);
            } else 
            if (OrderType() == OP_SELL) {
               swap_comm = (OrderCommission()-OrderSwap())/OrderLots()*Point;
               if (IsTesting()) swap_comm = (OrderSwap()/OrderLots()*Point)+(-1*Test_com_in_pip*Point);
            }
         //---
            dRes += (OrderOpenPrice()+swap_comm)*OrderLots(); 
            dSumLot += OrderLots(); 
            _cnt_orders++;
         } 
      } 
   } 
   if(_cnt_orders > 0){
      dRes = NormalizeDouble(dRes/dSumLot,MarketInfo(_symbol,MODE_DIGITS)); 
   }
   return(dRes); 
}
//+------------------------------------------------------------------+
// ������� ��������� ���-�� �������� �����
// _symbol - ���������� ("", ����� ����������)
// _type   - ��� ������� (-1, ����� ��� �������)
//           ��������� �����:
//           99 - ��� ������
//           10 - Buy � Sell
//           50 - ���������� (BuyStop, BuyLimit, SellStop, SellLimit)
//           51 - BuyStop � BuyLimit
//           52 - SellStop � SellLimit
//           53 - BuyStop � SellStop
//           54 - BuyLimit � SellLimit
// _magic  - ���������� ����� ������� ��������� ���:
//           -1 - �� ������ ����������� ������
//           99 - ����� �� �������� Magic_martin � Magic_piramid
// _comm   - ������ ������� ������ ����������� � ����������� ("", � ����� ������������)
// minOpenTime - ����� �������� ������ ������ ���� ������ ��� ����� ��������� (0 - �� ������������)
// maxOpenTime - ����� �������� ������ ������ ���� ������ ��� ����� ��������� (0 - �� ������������)
//-// ���������� ���-�� �������� ������� ��� 0
double OrdersGetOpenLot(string _symbol, int _type, int _magic, string _comm, datetime minOpenTime, datetime maxOpenTime){ 
   int a1,order_type; 
   double lot=0; 
   
   for(a1=OrdersTotal()-1;a1>=0;a1--){ 
      if(OrderSelect(a1,SELECT_BY_POS)){ 
         if((_symbol=="" || OrderSymbol()==_symbol) && 
            (_magic==-1 || OrderMagicNumber()==_magic || (_magic==99 && (OrderMagicNumber()==Magic_martin || OrderMagicNumber()==Magic_piramid))) && 
            (_comm=="" || StringFind(OrderComment(),_comm)!=-1) && 
            (minOpenTime==0 || OrderOpenTime()>=minOpenTime) && 
            (maxOpenTime==0 || OrderOpenTime()<=maxOpenTime))
         { 
            if(_type==99){
               lot +=OrderLots(); 
            }else{ 
               order_type = OrderType(); 
               if((_type==OP_BUY || _type==10) && order_type==OP_BUY) lot +=OrderLots(); 
               if((_type==OP_SELL || _type==10) && order_type==OP_SELL)lot+=OrderLots(); 
               if((_type==OP_SELLSTOP  || _type==50 || _type==52 || _type==53) && order_type==OP_SELLSTOP) lot+=OrderLots(); 
               if((_type==OP_BUYSTOP   || _type==50 || _type==51 || _type==53) && order_type==OP_BUYSTOP)  lot+=OrderLots(); 
               if((_type==OP_SELLLIMIT || _type==50 || _type==52 || _type==54) && order_type==OP_SELLLIMIT)lot+=OrderLots(); 
               if((_type==OP_BUYLIMIT  || _type==50 || _type==51 || _type==54) && order_type==OP_BUYLIMIT) lot+=OrderLots(); 
            } 
         } 
      } 
   } 
   return(lot); 
}
//+------------------------------------------------------------------+
// �������� ���������� ���������� �������
void OpenVirtPendOrd(){
   if(Metod==2){
      if(MSellStop > 0.0){         
         if(Bid <= MSellStop){            
            SendOrder(OP_SELL, MSellStopLot, Bid, Magic_martin, DoubleToStr(MSellStopNumb,0)+":martin");
            
            Sleep(PauseTrade*1000);
         
            MSellStop = 0.0;
            MSellStopLot = 0.0;
            MSellStopNumb = 0;
         }
      }
      if(MBuyStop > 0.0){
         if(Ask >= MBuyStop){
            SendOrder(OP_BUY, MBuyStopLot, Ask, Magic_martin, DoubleToStr(MBuyStopNumb,0)+":martin");            
               
            Sleep(PauseTrade*1000);
         
            MBuyStopLot = 0.0;
            MBuyStopNumb = 0;
            MBuyStop = 0.0;
         }
      }
      if(PSellStop > 0.0){
         if(Bid <= PSellStop){
            SendOrder(OP_SELL, PSellStopLot, Bid, Magic_piramid, DoubleToStr(PSellStopNumb,0)+":piramid",PSellStopStopLoss,PSellStopTakeProfit);
            //
            Sleep(PauseTrade*1000);
            //       
            PSellStopLot = 0.0;
            PSellStopNumb = 0;
            PSellStop = 0.0;
            PSellStopStopLoss=0.0;
            PSellStopTakeProfit=0.0;
         }
      }
      if(PBuyStop > 0.0){
         if(Ask >= PBuyStop){            
            SendOrder(OP_BUY, PBuyStopLot, Ask, Magic_piramid, DoubleToStr(PBuyStopNumb,0)+":piramid",PBuyStopStopLoss,PBuyStopTakeProfit);
            //               
            Sleep(PauseTrade*1000);
            //
            PBuyStopLot = 0.0;
            PBuyStopNumb = 0;
            PBuyStop = 0.0;
            PBuyStopStopLoss = 0.0;
            PBuyStopTakeProfit = 0.0;
         }
      }
   }
}
//+------------------------------------------------------------------+
// ��������� �������� ����������� ���������� ������� �������� �� �������� ��� �������� ��� ������ 2
void TrailVirtPendOrd(){
   double _val = 0.0;
   if(Metod==2){
      if(MSellStop > 0.0){         
         if(NormalizeDouble(Bid-MSellStop,Digits) > Step){
            _val = NormalizeDouble(Bid-Dist,Digits);
            if(_val > MSellStop){
               MSellStop = _val;
               //Print("MSellStop = "+MSellStop);
            }
         }
      }
      if(MBuyStop > 0.0){
         if(NormalizeDouble(MBuyStop-Ask,Digits) > Step){
            _val = NormalizeDouble(Ask+Dist,Digits);
            if(_val < MBuyStop){
               MBuyStop = _val;            
               //Print("MBuyStop="+MBuyStop);
            }
         }
      }
      if(PSellStop > 0.0){
         if(NormalizeDouble(Bid-PSellStop,Digits) > Step){
            _val = NormalizeDouble(Bid-Dist,Digits);
            if(_val > PSellStop){
               PSellStop = _val;
               //Print("PSellStop="+PSellStop);
            }
         }
      }
      if(PBuyStop > 0.0){
         if(NormalizeDouble(PBuyStop-Ask,Digits) > Step){
            _val = NormalizeDouble(Ask+Dist,Digits);
            if(_val < PBuyStop){
               PBuyStop = _val;
               //Print("PBuySto="+PBuyStop);
            }
         }
      }
   }
}
//+------------------------------------------------------------------+
// ��������� ������ ��� ���������� ��������� ������ � ������ ��������
// ���������� true ���� �������� ���������� � false ���� ���
bool CloseByStopLoss(){
   bool _res = false;
   //if(StopLoss > 0.0)
   if (AccountEquity()<=AccountBalance()*(1-StopLoss /100))
   {
      double _all_result = OrdersGetProfit(99, 11, _Symbol, "");
      if(_all_result <= -StopLoss){         
         PlaySound("wait.wav");
         OrdersClose(33, Magic_martin, true, _Symbol, "");
         OrdersClose(33, Magic_piramid, true, _Symbol, "");
         OpenCloseLineDraw();
         
         if(!NewCycle_ON){
            isWorking = false;
         }else{
            Sleep(PauseTrade2*60000);
         }
         _res = true;
         
         StopMartin = false;
         StopPiramid = false;
      }
   }
   return(_res);
}
//+------------------------------------------------------------------+
// ��������� �������� ��� ���������� �������� ��������
void EnablePiramid(){
   if(!PiramidOn && PiramidStart > 0.0 && !PiramidAutoStart){
      
      double _buy_result = OrdersGetProfit(99, OP_BUY, _Symbol, "");
      double _sell_result = OrdersGetProfit(99, OP_SELL, _Symbol, "");      
      double _all_result = MathAbs(_buy_result+_sell_result);
      
      if(NormalizeDouble((_all_result/AccountBalance())*100,2) >= PiramidStart){
         PiramidAutoStart = true;
         
         double _open_martin = 0.0;
         // ��������� ����� �� ����������� �������� �������� ��������
         if(_buy_result < 0.0 && _sell_result >= 0.0){
            // ��������� ����� �������� ������ �������
            _open_martin = OrdersGetOpenLot(_Symbol, OP_BUY, Magic_martin, "", 0, 0);
         }else
         if(_buy_result >= 0.0 && _sell_result < 0.0){
            // ��������� ����� �������� ������ �������
            _open_martin = OrdersGetOpenLot(_Symbol, OP_SELL, Magic_martin, "", 0, 0);
         }
         
         // ���������� ����������� ������ ���� ��������
         PiramidStartLot = NormalizeDouble(_open_martin*(Persen_open/100),iDigitLot);         
         if(PiramidStartLot > MarketInfo(_Symbol,MODE_MAXLOT)) PiramidStartLot = MarketInfo(_Symbol,MODE_MAXLOT);
         if(PiramidStartLot < MarketInfo(_Symbol,MODE_MINLOT)) PiramidStartLot = MarketInfo(_Symbol,MODE_MINLOT);         
      }
   }
}
//+------------------------------------------------------------------+
// Revers
void ReversPiramid(int m_sell, int m_buy) {
   ///if(!PiramidOn && PiramidStart > 0.0 && !PiramidAutoStart){
      
      double _buy_result = OrdersGetProfit(99, OP_BUY, _Symbol, "");
      double _sell_result = OrdersGetProfit(99, OP_SELL, _Symbol, "");      
      //double _all_result = MathAbs(_buy_result+_sell_result);
     
      if (_buy_result != 0 &&  _sell_result != 0) {        
        /* if(_buy_result < 0.0 && _sell_result >= 0.0){
            Buy_flag = martin_flag;
            Sell_flag = piramid_flag;
         } else {
            if(_buy_result >= 0.0 && _sell_result < 0.0){
               Buy_flag = piramid_flag;
               Sell_flag = martin_flag;  
            }
          Magic_piramid = MagicPiramid;
          Magic_martin = MagicMartin;
         }   */                               
         if(NormalizeDouble((_buy_result/AccountBalance())*100,2) <= -PiramidRevers && m_buy == Magic_piramid){
          Buy_flag = martin_flag;
          Sell_flag = piramid_flag;
          Magic_piramid = MagicMartin;
          Magic_martin = MagicPiramid;
         }
         if(NormalizeDouble((_sell_result/AccountBalance())*100,2) <= -PiramidRevers && m_sell == Magic_piramid){
          Buy_flag = piramid_flag;
          Sell_flag = martin_flag;
          Magic_piramid = MagicMartin;
          Magic_martin = MagicPiramid;          
         }         
      } 
      GlobalVariableSet("Buy_flag",Buy_flag);
      GlobalVariableSet("Sell_flag",Sell_flag);
      GlobalVariableSet("M_piramid",Magic_piramid);
      GlobalVariableSet("M_martin",Magic_martin);
}
//+------------------------------------------------------------------+
// ������� ������ ����� ����� ������ �������� � �������� �������
void OpenCloseLineDraw(){
   // ������ � ������ ������
   if(Info /*&& !IsTesting() && !IsOptimization()*/){
      string _name = "";
      color _clr = CLR_NONE;
      for(int i=OrdersHistoryTotal()-1;i>=0;i--){
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)){
            if(OrderSymbol()==Symbol() && (OrderMagicNumber() == Magic_martin || OrderMagicNumber() == Magic_piramid) && OrderType()<2){
               _name = "close line by #"+DoubleToStr(OrderTicket(),0);
               if(ObjectFind(_name)==-1){
                  if(OrderType()==OP_BUY) _clr = clrBlue; else _clr = clrRed;
                  GraphTrendLineCreate(_name, 0, OrderOpenTime(), OrderOpenPrice(), OrderCloseTime(), OrderClosePrice(), false, _clr, STYLE_DOT, 1);
               }
            }            
         }      
      }   
   }
}
//+------------------------------------------------------------------+
// ������� ������� ������ Trend Line � �������� ����(��� ����) �������, � �������� ������, ������������, ������������� ���� ��� �����, �����, ����� ����� � �� ���� ����� 
void GraphTrendLineCreate(string sName, int _iHandle, datetime _x1, double _y1, datetime _x2, double _y2, bool _isRay, color _MyColor, int _iStyle, int _Width){ ObjectCreate(sName, OBJ_TREND, _iHandle, _x1, _y1, _x2, _y2); ObjectSet(sName, OBJPROP_RAY, _isRay); ObjectSet(sName, OBJPROP_COLOR, _MyColor); ObjectSet(sName, OBJPROP_STYLE, _iStyle); ObjectSet(sName,OBJPROP_WIDTH,_Width); }
//+------------------------------------------------------------------+
// ������� �������� ������� ������ �� ����� ��� ���������� �������� 
// _m - ���������� ����� ������� ���:
//      -1 - �� �����������
//      99 - ����� �� �������� Magic_martin � Magic_piramid
// _type   - ��� ������� (-1, ����� ��� �������), ��������� ���������:
//           11 - �������� �������
//           12 - ���������� ������
// _s      - ���������� (-1, ����� ����������)
// _scomm  - ������ ������� ������ ����������� � ����������� ("", � ����� ������������)
double OrdersGetProfit(int _m, int _type, string _s, string _scomm){ 
   double dRes = 0; 
   for(int i=OrdersTotal()-1;i>=0;i--){ 
      if(OrderSelect(i,SELECT_BY_POS)){ 
         if((_m==-1 || OrderMagicNumber()==_m || (_m==99 && (Magic_martin==OrderMagicNumber() || Magic_piramid==OrderMagicNumber()))) && 
            (_s=="" || _s==OrderSymbol()) && 
            (_scomm=="" || StringFind(OrderComment(),_scomm)!=-1) && 
            (_type==-1 || _type==OrderType() || (_type==11 && OrderType()<2) || (_type==12 && OrderType()>1)))
         { 
            dRes += OrderProfit()+OrderCommission()+OrderSwap(); 
         } 
      } 
   } 
   return(NormalizeDouble(dRes,2)); 
}
//+------------------------------------------------------------------+
// ������� ���������� ����� ���������� ������ � ����������� �� ����
// 0 - �������� ������ ������� �������
double GetLot(int _type=1, double _lst_lot = 0.0, int _number_order = 0, double _real_step = 0.0, double _target_step = 0.0){
   double _res = 0.0;   
   switch(_type){
      case 1:  // ��� ��� ������ �������
         if(Risk==0.0){
            _res = DefaultLot;
         }else{
            _res = InfoLotPersentOfDeposit(_Symbol, Risk, iDigitLot);
         }
         break;
      case 2:  // ��� ��� ������ ������
         
         if(!FixLot && CCI_On && !PiramidOn){
            // ��������� ������ �������� ����
            _res = NormalizeDouble(_lst_lot*GetMartinLotExponent(_number_order),iDigitLot);            
            // ��������� �� ������� ����� ��������� ������ �������� ���� � ����������� �� ���������� �������
            if(_real_step > _target_step){
               double _lot_exponent = NormalizeDouble(_real_step/_target_step,2);
               _res = NormalizeDouble(_res*_lot_exponent,iDigitLot);
            }
         }else
            _res = NormalizeDouble(_lst_lot*GetMartinLotExponent(_number_order),iDigitLot);
                     
         break;
      case 3:  // ��� ��� ������ ��������
         
         if(_number_order == 1){
            _res = _lst_lot;            
         }else{            
            _res = NormalizeDouble(_lst_lot*GetPiramidLotExponent(_number_order),iDigitLot);
         }         
         break;
   }
   return(_res);
}
//+------------------------------------------------------------------+
// �������� �������
void SendOrder(int _type, double _dlot, double _price, int _magic, string _comment, double _stoploss = 0.0, double _takeprofit = 0.0){
   // ����������� �������� ������� ���� 
   if(_dlot > MaxLot) _dlot = MaxLot;
   // �������� �� ������������� ������� �� �����
   bool _check_margin = true;
   ResetLastError();
   if(AccountFreeMarginCheck(_Symbol,_type,_dlot)<=0.0 || GetLastError()==134){
      _check_margin = false;
   }
   if(_check_margin){
      // �������� ������� �� �������� ������
      OrdersOpen(InfoGetTypeTrdOperInInterFrm(_type), _dlot, _price, _Symbol, _comment, _stoploss, _takeprofit, iDigitLot, Slippege, _magic, iTicket);
      // ������ �� ��� ������ - ����������� ������
      if(iTicket < 0){
         // ���� ������� �������� ������� ������ �����
         if(_comment == "1:start"){
            Alert("��������!����������� ������ ��� �������� ������� ������ �����!����� �� ��� ������!");
         }
         PlaySound("stops.wav");
      }else{
         PlaySound("ok.wav");
      }
   }else{
      Comment("��������! �� ���������� ������� ��� �������� ������ ������!");
      CommentSet = true;
   }
}
//+------------------------------------------------------------------+
// ���������� true ���� ���������� ���������� �������� ������ ������� ����� ��������� ������
bool fStopMartin(int _number_order){
   bool _res = false;
   if(MartinOnNew && _number_order >= LotNoM){
      _res = true;
      StopMartin = true;
   }
   return(_res);
}
//+------------------------------------------------------------------+
// ���������� true ���� ���������� ���������� �������� ������� � �������� ����� ��������� ������
bool fStopPiramid(int _number_order){
   bool _res = false;
   if(PiramidOnNew && _number_order >= LotNoP){
      _res = true;
      StopPiramid = true;
   }
   return(_res);
}
//+------------------------------------------------------------------+
// ���������� ���-�� ������� �� ���� �������� ����������� ������ ��� �������� ������ ������ ������
double GetMartinStepPip(int _number_order){
   double _res = MartinStep;
   if(MartinOnNew && _number_order >= LotN_M){
      if(MartinK_Step > 0.0){
         _res = MartinStepNew * MathPow(MartinK_Step,_number_order-LotN_M);
      }else _res = MartinStepNew;
   }
   return(_res);
}
//+------------------------------------------------------------------+
// ���������� ���-�� ������� �� ���� �������� ����������� ������ ��� �������� ������ ������ � ��������
double GetPiramidStepPip(int _number_order){
   double _res = 0.0;
   if(Metod==2 && PiramidOn && MartinOn){
      _res = MartinStep;
      if(MartinOnNew && _number_order >= LotN_M){
         _res = MartinStepNew;
      }
   }else{
      _res = PiramidStep;
      if(PiramidOnNew && _number_order >= LotN_P){
         _res = PiramidStepNew;
      }
   }
   return(_res);
}
//+------------------------------------------------------------------+
// ���������� ��������� ���� ��� �������� ������ ������
double GetMartinLotExponent(int _number_order){
   double _res = MartinLotExponent;
   if(MartinOnNew && _number_order >= LotN_M){
      _res = MartinLotExponenNew;
   }
   return(_res);
}
//+------------------------------------------------------------------+
// ���������� ��������� ���� ��� �������� ������ � ��������
double GetPiramidLotExponent(int _number_order){
   double _res = PiramidLotExponent;
   if(PiramidOnNew && _number_order >= LotN_P){
      _res = PiramidLotExponenNew;
   }
   return(_res);
}
//+------------------------------------------------------------------+
// ������������ ���� �������� �������� MT �� ���������� ������������� ��� ������� Order.Open
// _type - ��� �������� ��������
//-// ��������� ��� �������� �������� �� ���������� ������������� ��� -1
int InfoGetTypeTrdOperInInterFrm(int _type){ int _res = -1; switch(_type){ case OP_BUY: _res = 1; break; case OP_SELL: _res = 2; break; case OP_BUYSTOP: _res = 3; break; case OP_SELLSTOP: _res = 4; break; case OP_BUYLIMIT: _res = 5; break; case OP_SELLLIMIT: _res = 6; break; } return(_res); }  
//+------------------------------------------------------------------+
// ������� ����������� ��� �� ��������� ��������� �������� �� ��������
// _Symb       - ���������� �� �������� ����� ������� �������
// _dPersent   - ������� �� ��������
// _iDigitLot  - �������� ����
// _isCalcRealPos - ��������� ������� �������� ������� (true - ��, false - ���). ��� ���� ����������� ������� � ������������ ��
// _imagic - ���������� ����� ������� ������� ����� ��������� (-1, ��������� ��� ������), �� ��������� -1
//-// ���������� ������ ������������ ����
double InfoLotPersentOfDeposit(string _Symb, double _dPersent, int _iDigitLot){ 
   double dL = 0; 
   double One_Lot = MarketInfo(_Symb,MODE_MARGINREQUIRED); 
   double Balance = AccountEquity(); 
   double dPriceP = 0; 
   double dLossRes = 0; 
   int iTypeOrder = 0; 
   
   dL = NormalizeDouble(Balance*_dPersent/100/One_Lot,_iDigitLot); 
   if(dL<MarketInfo(_Symb,MODE_MINLOT)){ 
      Print("����������� ���("+DoubleToStr(dL,2)+") ������ ������������("+DoubleToStr(MarketInfo(_Symb,MODE_MINLOT),2)+"). ��� ������� �� �����������."); 
      dL=MarketInfo(_Symb,MODE_MINLOT); 
   } 
   if(dL>MarketInfo(_Symb,MODE_MAXLOT)){ 
      Print("����������� ���("+DoubleToStr(dL,2)+") ������ �������������("+DoubleToStr(MarketInfo(_Symb,MODE_MAXLOT),2)+"). ��� ������� �� ������������."); 
      dL=MarketInfo(_Symb,MODE_MAXLOT); 
   } 
   return(dL); 
}
//+------------------------------------------------------------------+
// ��������� ��������� �����������
//void Log(string _str){ if(Info) Print("_str"); }
//+------------------------------------------------------------------+
// ��������� ��������� ����������� ��� �������
//void Debug(string _str){ Print("DEBUG :: "+_str); }
//+------------------------------------------------------------------+
// ��������� ����� �������� � ������� �� ���-�� ������ � ����������
// symbol - ���������� �� �������� ������������ �������� ���������
// v - �������� ���������� �� ������, ������� ����� ��������������
//--// �� ���������� ��������
void InfoChangeToDigit(string symbol, double& v) { v *= MarketInfo(symbol,MODE_TICKSIZE); return; }
//+------------------------------------------------------------------+
// ������� ������� ������� ����� ������� �������� ���������� ������
void GraphDelete(string _sName){ for(int i=0;i<ObjectsTotal();i++){ if(StringFind(ObjectName(i),_sName,0)!=-1){ ObjectDelete(ObjectName(i)); i=-1; } } }
//+------------------------------------------------------------------++
// ������������� ���������� �������� ������ �������
// _symbol - �������� �����������
// _volume - ����� ������� ����� ���������
// _round_met - ������ ����������� (false - ���� (�� ���������), true - �����) 
double InfoNormalizeVolume(string _symbol, double _volume, bool _round_met=false, bool _pre_round = true){ double new_volume = -1, k; if (_symbol=="") _symbol=Symbol(); double lot_step=MarketInfo(_symbol, MODE_LOTSTEP); double min_lot=MarketInfo(_symbol, MODE_MINLOT); double max_lot=MarketInfo(_symbol, MODE_MAXLOT); int digit_lot = InfoGetLotDigit(_symbol); if(_pre_round) _volume = NormalizeDouble(_volume,digit_lot); if(min_lot>0 && max_lot>0){ if (lot_step>0) k=1/lot_step; else k=1/min_lot; if (_round_met) new_volume = MathCeil(_volume*k)/k; else new_volume = MathFloor(_volume*k)/k; if (new_volume<min_lot) new_volume=min_lot;  if (new_volume>max_lot) new_volume=max_lot; if(NormalizeDouble(_volume-new_volume,digit_lot)!=0) Print("InfoNormalizeVolume : ��� ("+DoubleToStr(_volume,digit_lot)+") ��� �������� �� "+DoubleToStr(new_volume,digit_lot)); } return(NormalizeDouble(new_volume,digit_lot)); }
//+------------------------------------------------------------------++
//������� ���������� �������� ����
// symbol - ���������� �� �������� ������������� �������� ��������
//--// ���-�� ������ ����� ������� ��� 0
int InfoGetLotDigit(string symbol){ return(MathCeil(MathAbs(MathLog( MarketInfo(Symbol(), MODE_MINLOT) )/MathLog(10)))); }
//+------------------------------------------------------------------+
// ������� ������� ���-�� �������
// _symbol - ���������� ("", ����� ����������)
// _type   - ��� ������� (-1, ����� ��� �������)
//           ��������� �����:
//           99 - ��� ������
//           10 - Buy � Sell
//           50 - ���������� (BuyStop, BuyLimit, SellStop, SellLimit)
//           51 - BuyStop � BuyLimit
//           52 - SellStop � SellLimit
//           53 - BuyStop � SellStop
//           54 - BuyLimit � SellLimit
// _magic  - ���������� ����� ������� ��������� (-1, �� ������ ����������� ������)
// _comm   - ������ ������� ������ ����������� � ����������� ("", � ����� ������������)
// minOpenTime - ����� �������� ������ ������ ���� ������ ��� ����� ��������� (0 - �� ������������)
// maxOpenTime - ����� �������� ������ ������ ���� ������ ��� ����� ��������� (0 - �� ������������)
//-// ���������� ���-�� �������� ������� ��� 0
int OrdersGetCount(string _symbol, int _type, int _magic, string _comm, datetime minOpenTime, datetime maxOpenTime){ int iCount=0; if(OrdersTotal()<=0) return(0); for(int a1=OrdersTotal()-1;a1>=0;a1--){ if(OrderSelect(a1,SELECT_BY_POS)){ if((_symbol=="" || _symbol==OrderSymbol()) && (_magic==-1 || _magic==OrderMagicNumber()) && (_comm=="" || StringFind(OrderComment(),_comm)!=-1) &&  (minOpenTime==0 || OrderOpenTime()>=minOpenTime) && (maxOpenTime==0 || OrderOpenTime()<=maxOpenTime)){ if(_type==99){ iCount++; }else{ switch(OrderType()){ case OP_BUY: if(_type==OP_BUY || _type==10) iCount++; break; case OP_BUYSTOP: if(_type==OP_BUYSTOP || _type==50 || _type==51 || _type==53) iCount++; break; case OP_BUYLIMIT: if(_type==OP_BUYLIMIT || _type==50 || _type==51 || _type==54) iCount++; break; case OP_SELL: if(_type==OP_SELL || _type==10) iCount++; break; case OP_SELLSTOP: if(_type==OP_SELLSTOP || _type==50 || _type==52 || _type==53) iCount++; break; case OP_SELLLIMIT: if(_type==OP_SELLLIMIT || _type==50 || _type==52 || _type==54) iCount++; break; } } } } } return(iCount); }
//+------------------------------------------------------------------+
// ������� ������������� ������
// 1 - Buy, 2 - Sell, 3 - BuyStop, 4 - SellStop, 5 - BuyLimit, 6 - SellLimit
void OrdersOpen(int type_order,double Lot, double price, string SymbolSend, string Comm, double SL, double TP, int dlot, int slip, int mag, int& tick, color clr=CLR_NONE)
{int l_error_130=0; double takeprofit, stoplosse;
switch(type_order){
  case 1 :
      while(true){
       if(IsTradeAllowed())
       {RefreshRates();          
          tick = OrderSend(SymbolSend,OP_BUY,NormalizeDouble(Lot,dlot),NormalizeDouble(MarketInfo(SymbolSend,MODE_ASK),MarketInfo(SymbolSend,MODE_DIGITS)),slip,0,0,Comm,mag,0,clrBlue);
          if(tick==-1) { if(ErrorCheck(GetLastError(),l_error_130)) return; }else{ break; }
          continue;
      } }
      if(tick!=-1 && (SL!=0 || TP!=0)){  
          while(true){
            if(IsTradeAllowed()){
              RefreshRates();
               if(OrderSelect(tick,SELECT_BY_TICKET)){                  
                  if(SL==0) { stoplosse = 0; }else{ stoplosse = OrderOpenPrice()-SL; }
                  if(TP==0) { takeprofit = 0;}else{ takeprofit= OrderOpenPrice()+TP; }
                 if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(stoplosse,MarketInfo(SymbolSend,MODE_DIGITS)),NormalizeDouble(takeprofit,MarketInfo(SymbolSend,MODE_DIGITS)),0)) break;
                 if(ErrorCheck(GetLastError(),l_error_130)) break;
                 continue;                 
               }else{ Print("OrderSelectError "+DoubleToStr(GetLastError(),0)); }
      } } }        
      break;
  case 2 :
      while(true){   
       if(IsTradeAllowed()){
          RefreshRates();
          tick = OrderSend(SymbolSend,OP_SELL,NormalizeDouble(Lot,dlot),NormalizeDouble(MarketInfo(SymbolSend,MODE_BID),MarketInfo(SymbolSend,MODE_DIGITS)),slip,0,0,Comm,mag,0,clrRed);
          if(tick==-1) { if(ErrorCheck(GetLastError(),l_error_130)) return; }else{ break; }
          continue;
      } }
      if(tick!=-1 && (SL!=0 || TP!=0)){  
          while(true){
            if(IsTradeAllowed()){
               RefreshRates();
               if(OrderSelect(tick,SELECT_BY_TICKET)){                  
                  if(SL==0) { stoplosse = 0; }else{ stoplosse = OrderOpenPrice()+SL; }
                  if(TP==0) { takeprofit = 0;}else{ takeprofit= OrderOpenPrice()-TP; }
                 if(OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(stoplosse,MarketInfo(SymbolSend,MODE_DIGITS)),NormalizeDouble(takeprofit,MarketInfo(SymbolSend,MODE_DIGITS)),0)) break;
                 if(ErrorCheck(GetLastError(),l_error_130)) break;
                 continue;                 
               }else{ Print("OrderSelectError "+DoubleToStr(GetLastError(),0)); }
      } } }        
     break;  
  case 3 :
      while(true){   
       if(IsTradeAllowed()){
          RefreshRates();
          if(SL==0) { stoplosse = 0; }else{ stoplosse = price-SL;}
          if(TP==0) { takeprofit = 0;}else{ takeprofit= price+TP;}
          tick = OrderSend(SymbolSend,OP_BUYSTOP,NormalizeDouble(Lot,dlot),NormalizeDouble(price,MarketInfo(SymbolSend,MODE_DIGITS)),slip,NormalizeDouble(stoplosse,MarketInfo(SymbolSend,MODE_DIGITS)),NormalizeDouble(takeprofit,MarketInfo(SymbolSend,MODE_DIGITS)),Comm,mag,0,clr);
          if(tick==-1){if(ErrorCheck(GetLastError(),l_error_130)) break;}else{ break; }
          continue;   
      } }                
      break;
  case 4 :
      while(true){   
         if(IsTradeAllowed()){
            RefreshRates();             
             if(SL==0) { stoplosse = 0; }else{ stoplosse = price+SL;}
             if(TP==0) { takeprofit = 0;}else{ takeprofit= price-TP;}
             tick = OrderSend(SymbolSend,OP_SELLSTOP,NormalizeDouble(Lot,dlot),NormalizeDouble(price,MarketInfo(SymbolSend,MODE_DIGITS)),slip,NormalizeDouble(stoplosse,MarketInfo(SymbolSend,MODE_DIGITS)),NormalizeDouble(takeprofit,MarketInfo(SymbolSend,MODE_DIGITS)),Comm,mag,0,clr);
             if(tick==-1){if(ErrorCheck(GetLastError(),l_error_130)) break;}else{ break; }
             continue;    
      } }   
     break; 
  case 5 :
      while(true){   
         if(IsTradeAllowed()){
            RefreshRates();             
             if(SL==0) { stoplosse = 0; }else{ stoplosse = price-SL;}
             if(TP==0) { takeprofit = 0;}else{ takeprofit= price+TP;}
             tick = OrderSend(SymbolSend,OP_BUYLIMIT,NormalizeDouble(Lot,dlot),NormalizeDouble(price,MarketInfo(SymbolSend,MODE_DIGITS)),slip,NormalizeDouble(stoplosse,MarketInfo(SymbolSend,MODE_DIGITS)),NormalizeDouble(takeprofit,MarketInfo(SymbolSend,MODE_DIGITS)),Comm,mag,0,clr);
             if(tick==-1){if(ErrorCheck(GetLastError(),l_error_130)) break;}else{ break; }
             continue;    
      } }   
     break;
  case 6 :
      while(true){   
         if(IsTradeAllowed()){
            RefreshRates();             
             if(SL==0) { stoplosse = 0; }else{ stoplosse = price+SL;}
             if(TP==0) { takeprofit = 0;}else{ takeprofit= price-TP;}
             tick = OrderSend(SymbolSend,OP_SELLLIMIT,NormalizeDouble(Lot,dlot),NormalizeDouble(price,MarketInfo(SymbolSend,MODE_DIGITS)),slip,NormalizeDouble(stoplosse,MarketInfo(SymbolSend,MODE_DIGITS)),NormalizeDouble(takeprofit,MarketInfo(SymbolSend,MODE_DIGITS)),Comm,mag,0,clr);
             if(tick==-1){if(ErrorCheck(GetLastError(),l_error_130)) break;}else{ break; }
             continue;    
      } }   
     break;
} }
//+------------------------------------------------------------------+
// ������ ��������� ������
//33 - all, 0 - buy, 2 - sell, 11 - buystop and buylimit, 21 - sellstop and selllimit, 
//31 - selllimit and buylimit, 41 - buystop and sellstop
//51 - buylimit and sellstop, 61 - selllimit and buystop
//_mag = -1 - ��������� �� ������ ������
// ������ ��������� ������
bool OrdersClose(int type, int _mag, bool _isMagic, string _sSymbol, string _scomm, color clr=CLR_NONE){
   if(OrdersTotal()<1) return(true);
   int ordertype, l_error_130;
   for(int a1=OrdersTotal()-1;a1>=0;a1--){
      if(OrderSelect(a1,SELECT_BY_POS) && ((_isMagic && OrderMagicNumber()==_mag) || (!_isMagic && OrderTicket()==_mag) || _mag==-1 )
                                       && ((_sSymbol!="" && OrderSymbol()==_sSymbol) || _sSymbol=="") && (_scomm=="" || StringFind(OrderComment(),_scomm)!=-1) ){  
         ordertype = OrderType();         
         if((type==33 || type==0) && ordertype==OP_BUY) {
            while(true) {
               RefreshRates();                   
               if(IsTradeAllowed()){ 
                  if(OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),MarketInfo(OrderSymbol(),MODE_DIGITS)),0,clrDarkOrange)) break; 
                  else if(ErrorCheck(GetLastError(),l_error_130)) break;
               }               
         }  }                      
         if((type==33 || type==11 || type==41 || type==61) && ordertype==OP_BUYSTOP) {
            while(true) {
               RefreshRates();                                  
               if(IsTradeAllowed()){ 
                  if(OrderDelete(OrderTicket(),clr)) break; 
                  else if(ErrorCheck(GetLastError(),l_error_130)) break;
               }               
         }   }                 
         if((type==33 || type==11 || type==31 || type==51) && ordertype==OP_BUYLIMIT) {
            while(true) {
               RefreshRates();                                  
               if(IsTradeAllowed()){ 
                  if(OrderDelete( OrderTicket(),clr)) break; 
                  else if(ErrorCheck(GetLastError(),l_error_130)) break;
               }               
         }   }        
         if((type==33 || type==2) && ordertype==OP_SELL) {
            while(true) {
               RefreshRates();                   
               if(IsTradeAllowed()){ 
                  if(OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),MarketInfo(OrderSymbol(),MODE_DIGITS)),0,clrDarkOrange)) break; 
                  else if(ErrorCheck(GetLastError(),l_error_130)) break;
               }
         }    }         
         if((type==33 || type==21 || type==41 || type==51) && ordertype==OP_SELLSTOP) {
            while(true) {
               RefreshRates();                   
               if(IsTradeAllowed()){ 
                  if(OrderDelete(OrderTicket(),clr)) break; 
                  else if(ErrorCheck(GetLastError(),l_error_130)) break;
               }               
         }    }         
         if((type==33 || type==21 || type==31 || type==61) && ordertype==OP_SELLLIMIT) {
            while(true) {
               RefreshRates();                   
               if(IsTradeAllowed()){ 
                  if(OrderDelete(OrderTicket(),clr)) break; 
                  else if(ErrorCheck(GetLastError(),l_error_130)) break;
               }               
   } } } } return(true); }   
//+------------------------------------------------------------------+
//������� ��������� ��� ������
bool ErrorCheck(int l_error_64, int& error_130){   
   if(l_error_64==0) return(true);
   switch(l_error_64){
      case 4:  Print("�������� ������ �����. ���� 500 ��...");       Sleep(500); return(false);
      case 6:  Print("��� ����� � ��������. ���� 2 ���...");         Sleep(2000);return(false);  
      case 8:  Print("������� ������ �������. ���� 1 ���...");       Sleep(1000);return(false);  
      case 129:Print("������ � ����. ���� 500 �� � ������� ����...");Sleep(500); return(false);
      case 135:Print("���� ����������. ������� ��� ���..");                      return(false);   
      case 136:Print("��� ���. ��� ����� ���..");                   Sleep(1);   return(false);
      case 137:Print("������ �����. ���� 500 ��...");                Sleep(500); return(false);
      case 138:Print("����� ����. �������.");                                    return(false);
      case 141:Print("������� ����� ��������. ���� 1 ������..");     Sleep(60000);return(false);
      case 146:Print("���������� �������� ������. ������� ���..");   Sleep(500); return(false);      
      case 130: if(error_130==0) {Print("������ ����. ������� �������� ����...");Sleep(1000);error_130++;return(false); }else{ Print("����������� ������ � ����."); return(true);}
      default: Print("����������� ������ � "+DoubleToStr(l_error_64,0));                        return(true);
   }         
   return(true);
}
//+------------------------------------------------------------------+
// ���������� ������ �� �������� ��� ������ �������� ������ ����� �������
// _type_order - ��� ������ (Buy, Sell, BuyStop, SellStop, BuyLimit, SellLimit)
// _type_group - ��� ������:
//               99 - ��� ������
//               10 - Buy � Sell
//               50 - ���������� (BuyStop, BuyLimit, SellStop, SellLimit)
//               51 - BuyStop � BuyLimit
//               52 - SellStop � SellLimit
//               53 - BuyStop � SellStop
//               54 - BuyLimit � SellLimit
bool InfoisTypeOrdPartOfGroup(int _type_order, int _type_group){ if(_type_order < 0) return(false); bool _res = false; switch(_type_order){ case OP_BUY: switch(_type_group){ case 99: case 10: case OP_BUY: _res = true; } break; case OP_SELL: switch(_type_group){ case 99: case 10: case OP_SELL: _res = true; } break; case OP_BUYSTOP: switch(_type_group){ case 99: case 50: case 51: case 53: case OP_BUYSTOP: _res = true; } break; case OP_SELLSTOP: switch(_type_group){ case 99: case 50: case 52: case 53: case OP_SELLSTOP: _res = true; } break; case OP_BUYLIMIT: switch(_type_group){ case 99: case 50: case 51: case 54: case OP_BUYLIMIT: _res = true; } break; case OP_SELLLIMIT: switch(_type_group){ case 99: case 50: case 52: case 54: case OP_SELLLIMIT: _res = true; } break; } return(_res); }
//+------------------------------------------------------------------+
//=========================================================================================================================================//
// Kordan . ������� �������� ��������                                                                                                      //
//=========================================================================================================================================//

int DeleteObject() {
     
int    ObjTotal = ObjectsTotal()          ;
string ObName                             ;
   for(int i = 0; i < ObjTotal; i++){
   ObName = ObjectName(i)                 ;
      if(StringSubstr(ObName,0,1) == "I" 
      || StringSubstr(ObName,0,1) == "i") { 
         ObjectDelete(ObName)             ;
            Comment("")                   ; 
         i = i - 1                        ;
      }
   }
return(0);      
} 


//=========================================================================================================================================//
//                      ������ �� ���������� MTS                                                                                           //
int  mper[10]={0,1,5,15,30,60,240,1440,10080,43200};
//=========================================================================================================================================// 
//=============================== ������� SVG ======================================================
int MTS(){ 
   int MTSSignal=0;
   int MTSstart=0;
   double MTS_Green1=iCustom(Symbol(),mper[TF_MTF],"medium",Per_MTS,1,0);
   double MTS_Red1=iCustom(Symbol(),mper[TF_MTF],"medium",Per_MTS,2,0);
   double MTS_Green2=iCustom(Symbol(),mper[TF_MTF],"medium",Per_MTS,1,1);
   double MTS_Red2=iCustom(Symbol(),mper[TF_MTF],"medium",Per_MTS,2,1);
   if((MTS_Green1!=EMPTY_VALUE)&&(MTS_Green2!=EMPTY_VALUE)) MTSstart=1;
   if((MTS_Red1!=EMPTY_VALUE)&&(MTS_Red2!=EMPTY_VALUE)) MTSstart=-1;
   if(MTSstart<0) MTSSignal= -1;                                         //������ Sell 
   if(MTSstart>0) MTSSignal = 1;                                         // ������ Buy
   return(MTSSignal);
}