//+------------------------------------------------------------------+
//|                                             GBPUSD_Pip_Boxer.mq4 |
//|                           Copyright © 2006, www.fxnewstrader.com |
//|                                     http://www.fxnewstrader.com/ |
//+------------------------------------------------------------------+
//Beta 7 - Monday December 4, 2006

// TERMS and Conditions

/*
GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
 
0. This License applies to any program or other work which contains a notice placed by 
the copyright holder saying it may be distributed under the terms of this General Public 
License. The "Program", below, refers to any such program or work, and a "work based on 
the Program" means either the Program or any derivative work under copyright law: that is 
to say, a work containing the Program or a portion of it, either verbatim or with 
modifications and/or translated into another language. (Hereinafter, translation is 
included without limitation in the term "modification".) Each licensee is addressed as "you". 

Activities other than copying, distribution and modification are not covered by this License; 
they are outside its scope. The act of running the Program is not restricted, and the output 
from the Program is covered only if its contents constitute a work based on the Program 
(independent of having been made by running the Program). Whether that is true depends on 
what the Program does. 

1. You may copy and distribute verbatim copies of the Program's source code as you receive 
it, in any medium, provided that you conspicuously and appropriately publish on each copy 
an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that 
refer to this License and to the absence of any warranty; and give any other recipients of 
the Program a copy of this License along with the Program. 

You may charge a fee for the physical act of transferring a copy, and you may at your option 
offer warranty protection in exchange for a fee. 

2. You may modify your copy or copies of the Program or any portion of it, thus forming a work 
based on the Program, and copy and distribute such modifications or work under the terms of 
Section 1 above, provided that you also meet all of these conditions: 

a) You must cause the modified files to carry prominent notices stating that you changed the 
files and the date of any change. 
b) You must cause any work that you distribute or publish, that in whole or in part contains 
or is derived from the Program or any part thereof, to be licensed as a whole at no charge to 
all third parties under the terms of this License. 

c) If the modified program normally reads commands interactively when run, you must cause it, 
when started running for such interactive use in the most ordinary way, to print or display 
an announcement including an appropriate copyright notice and a notice that there is no warranty 
(or else, saying that you provide a warranty) and that users may redistribute the program under 
these conditions, and telling the user how to view a copy of this License. (Exception: if the 
Program itself is interactive but does not normally print such an announcement, your work based 
on the Program is not required to print an announcement.) 

These requirements apply to the modified work as a whole. If identifiable sections of that work 
are not derived from the Program, and can be reasonably considered independent and separate works 
in themselves, then this License, and its terms, do not apply to those sections when you distribute 
them as separate works. But when you distribute the same sections as part of a whole which is a 
work based on the Program, the distribution of the whole must be on the terms of this License, 
whose permissions for other licensees extend to the entire whole, and thus to each and every part 
regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest 
your rights to work written entirely by you; rather, the intent is to exercise the right to control 
the distribution of derivative or collective works based on the Program. 

In addition, mere aggregation of another work not based on the Program with the Program (or with 
a work based on the Program) on a volume of a storage or distribution medium does not bring the 
other work under the scope of this License. 

3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code 
or executable form under the terms of Sections 1 and 2 above provided that you also do one of the 
following: 

a) Accompany it with the complete corresponding machine-readable source code, which must be distributed 
under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, 
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a 
charge no more than your cost of physically performing source distribution, a complete machine-readable 
copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on 
a medium customarily used for software interchange; or, 

c) Accompany it with the information you received as to the offer to distribute corresponding source 
code. (This alternative is allowed only for noncommercial distribution and only if you received the 
program in object code or executable form with such an offer, in accord with Subsection b above.) 

The source code for a work means the preferred form of the work for making modifications to it. For 
an executable work, complete source code means all the source code for all modules it contains, plus 
any associated interface definition files, plus the scripts used to control compilation and installation 
of the executable. However, as a special exception, the source code distributed need not include 
anything that is normally distributed (in either source or binary form) with the major components 
(compiler, kernel, and so on) of the operating system on which the executable runs, unless that component 
itself accompanies the executable. 

If distribution of executable or object code is made by offering access to copy from a designated place, 
then offering equivalent access to copy the source code from the same place counts as distribution of 
the source code, even though third parties are not compelled to copy the source along with the object code. 

4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under 
this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and 
will automatically terminate your rights under this License. However, parties who have received copies, 
or rights, from you under this License will not have their licenses terminated so long as such parties 
remain in full compliance. 

5. You are not required to accept this License, since you have not signed it. However, nothing else 
grants you permission to modify or distribute the Program or its derivative works. These actions are 
prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program 
(or any work based on the Program), you indicate your acceptance of this License to do so, and all its 
terms and conditions for copying, distributing or modifying the Program or works based on it. 

6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically 
receives a license from the original licensor to copy, distribute or modify the Program subject to these 
terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights 
granted herein. You are not responsible for enforcing compliance by third parties to this License. 

7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason 
(not limited to patent issues), conditions are imposed on you (whether by court order, agreement 
or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions 
of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this 
License and any other pertinent obligations, then as a consequence you may not distribute the Program 
at all. For example, if a patent license would not permit royalty-free redistribution of the Program 
by all those who receive copies directly or indirectly through you, then the only way you could satisfy 
both it and this License would be to refrain entirely from distribution of the Program. 

If any portion of this section is held invalid or unenforceable under any particular circumstance, 
the balance of the section is intended to apply and the section as a whole is intended to apply in 
other circumstances. 

It is not the purpose of this section to induce you to infringe any patents or other property right 
claims or to contest validity of any such claims; this section has the sole purpose of protecting the 
integrity of the free software distribution system, which is implemented by public license practices. 
Many people have made generous contributions to the wide range of software distributed through that 
system in reliance on consistent application of that system; it is up to the author/donor to decide 
if he or she is willing to distribute software through any other system and a licensee cannot impose 
that choice. 

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of 
this License. 

8. If the distribution and/or use of the Program is restricted in certain countries either by patents 
or by copyrighted interfaces, the original copyright holder who places the Program under this License 
may add an explicit geographical distribution limitation excluding those countries, so that distribution 
is permitted only in or among countries not thus excluded. In such case, this License incorporates the 
limitation as if written in the body of this License. 

9. The Free Software Foundation may publish revised and/or new versions of the General Public License 
from time to time. Such new versions will be similar in spirit to the present version, but may differ 
in detail to address new problems or concerns. 

Each version is given a distinguishing version number. If the Program specifies a version number of 
this License which applies to it and "any later version", you have the option of following the terms 
and conditions either of that version or of any later version published by the Free Software Foundation. 
If the Program does not specify a version number of this License, you may choose any version ever published 
by the Free Software Foundation. 

10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions 
are different, write to the author to ask for permission. For software which is copyrighted by the Free 
Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our 
decision will be guided by the two goals of preserving the free status of all derivatives of our free software 
and of promoting the sharing and reuse of software generally. 

NO WARRANTY 
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT 
PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER 
PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, 
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 
THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 

12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, 
OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU 
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE 
OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE 
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 

13. THE PROGRAMMER OF THIS APPLICATION SHALL NOT BE TAKEN RESPONSIBLE FOR ANY LOSSES DUE TO USE OF THIS 
APPLICATION. YOU ARE USING THIS APPLICATION AT YOUR OWN DISCRETION.
 
END OF TERMS AND CONDITIONS 

*/


extern double TakeProfit = 83;
extern double StopLoss = 98;
extern double Value_At_Risk = 1;
extern double TrailingStop = 60;
extern double price_deviation=-7;
extern int    _server_time=1;
extern int    _time_shift=0;
extern bool   revenge=true;
extern bool   counter_trade=true;
extern double _trailing_stop_percentage=0.75;
extern double user_lot_size=1;
extern double cci_check=80;
extern int    cci_period=11;
extern int    opt_active_time=6;
extern double _mid_range_factor=0.31;
extern bool   account_risk_control=true;


//---Global variables
int update_day_year, update_day_week, failiur_day_year, failiur_day_week, ticket;
int LongOrShort;
int _file_handle;
double highest_high, lowest_low, mid_range_in_pips;
int cnt, total;
string  CrossCurrency, CurrencyPair;
bool condition1, condition2;
double StopLossPrice, Prev_Closed_Price;
double optimum_trailing_stop;

//+------------------------------------------------------------------+
//| Initialization                                                   |
//+------------------------------------------------------------------+
int init()
   {
      update_day_year=-100;
      update_day_week=-100;
      failiur_day_year=-100;
      failiur_day_week=-100;
      ticket=-100;
      LongOrShort=-100;
      highest_high=1000;
      lowest_low=-1000;
      //---read optimum trailing stop from a file
      _file_handle=FileOpen("gbpusd_pip_boxer_ts.dat",FILE_BIN|FILE_READ);
         if (_file_handle<1)
            {
               optimum_trailing_stop=_trailing_stop_percentage*TakeProfit;
               //---adding the optimum trailing stop to a binary file
               _file_handle=FileOpen("gbpusd_pip_boxer_ts.dat",FILE_BIN|FILE_WRITE);
               if (_file_handle<1)
                  Print("Can't open file error - ",GetLastError());
                  else
                     {
                        FileWriteDouble(_file_handle, optimum_trailing_stop, DOUBLE_VALUE);
                        FileClose(_file_handle);
                        Print("Don't worry about the 'file open' error message. The EA created the missing file with proper settings.");
                     }
               //--end of updating the binary file
            }
            else
               {
                  optimum_trailing_stop=FileReadDouble(_file_handle, DOUBLE_VALUE);
                  FileClose(_file_handle);
               }
      //end of reading the opt trailing stop from a file
      return(0);
   }

//+------------------------------------------------------------------+
//| Lot Size Calculator                                              |
//+------------------------------------------------------------------+
double lot_size_calc(double drawdown_in_pips)
   {
      double no_of_lots, CrossToUSD;
      if (Value_At_Risk<=0) return(user_lot_size);      
      
      CrossCurrency=StringSubstr(Symbol(),3,3);
      if (CrossCurrency != "USD") 
         {
            CurrencyPair=StringConcatenate("USD",CrossCurrency);
            CrossToUSD=MarketInfo(CurrencyPair, MODE_BID);
         }
         else CrossToUSD = 1.0000;  
   
      double _lot_size_val=MarketInfo(Symbol(), MODE_LOTSIZE);
      no_of_lots=(Value_At_Risk*0.01*AccountFreeMargin()*CrossToUSD)/(drawdown_in_pips*Point*_lot_size_val);
      no_of_lots=MathRound(10*no_of_lots)/10;
      double Minimum_Lot_Count = MarketInfo(Symbol(), MODE_MINLOT);
      if (no_of_lots < Minimum_Lot_Count) no_of_lots=Minimum_Lot_Count;
      return(no_of_lots);
   }

//+------------------------------------------------------------------+
//| Calculating the Box Size                                         |
//+------------------------------------------------------------------+
int the_box_size()
   {
      if ((TimeHour(CurTime())==11+_time_shift+_server_time)&&(TimeMinute(CurTime())>1)&&(TimeMinute(CurTime())<=14))
      {
         //if ((update_day_year!=DayOfYear())&&(update_day_week!=DayOfWeek()))
            {
               int highest_bar=Highest(NULL, PERIOD_M15, MODE_HIGH, 30, 0);
               highest_high=iHigh(NULL, PERIOD_M15, highest_bar);
               int lowest_bar=Lowest(NULL, PERIOD_M15, MODE_LOW, 30, 0);
               lowest_low=iLow(NULL, PERIOD_M15, lowest_bar);
               mid_range_in_pips=((highest_high-lowest_low)*_mid_range_factor)/Point;
               update_day_year=DayOfYear();
               update_day_week=DayOfWeek();
               //Print("Procedure 1 results: hh, ll, dayyear, dayweek...",highest_high,", ",lowest_low,", ",update_day_year,", ",update_day_week,", ",price_deviation*Point); 
            }
      }
      return(0);
   }

//+------------------------------------------------------------------+
//| Initial Entry to the Market                                      |
//+------------------------------------------------------------------+
int the_initial_entry()
   {
      double init_lot_Count=lot_size_calc(StopLoss);
      double init_stop_loss=StopLoss;
      double max_loss_in_pips;
      bool _go_long, _go_short;
      string _current_message="";
      
      _go_long=false;
      _go_short=false;
      
      double last_cci=iCCI(NULL,PERIOD_M15,cci_period,PRICE_TYPICAL,1);
      
      //--conditions to long trade
      if((last_cci>=cci_check)&&(Bid>=(highest_high+price_deviation*Point))) 
         {
            _go_long=true;
            _current_message="Normal Long Pip Boxer";
         }
      
      if((counter_trade)&&(last_cci>(-1*cci_check))&&(Bid<=(lowest_low-price_deviation*Point)))
         {
            _go_long=true;
            _current_message="Counter Long Pip Boxer";
         } 
      
      //--conditions to short trade
      if((last_cci<=(-1*cci_check))&&(Bid<=(lowest_low-price_deviation*Point)))
         {
            _go_short=true;
            _current_message="Normal Short Pip Boxer";
         }
      if((counter_trade)&&(last_cci<cci_check)&&(Bid>=(highest_high+price_deviation*Point)))
         {
            _go_short=true;
            _current_message="Counter Short Pip Boxer";
            
         } 
      
      
      
      /*
      if(AccountFreeMargin()<(1000*init_lot_Count))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }*/
      
      
      // check for long position (BUY) opportunity
      if(_go_long)
        {
         max_loss_in_pips=(Ask-MathMin(Low[0],Low[1]))/Point;
         init_stop_loss=MathMax(max_loss_in_pips,StopLoss);
         init_stop_loss=MathMax(init_stop_loss,mid_range_in_pips);
         init_lot_Count=lot_size_calc(init_stop_loss);
         double max_win_in_pips=MathMax(mid_range_in_pips, TakeProfit);
         double init_take_profit=max_win_in_pips;
         optimum_trailing_stop=MathMax(TrailingStop,(_trailing_stop_percentage*init_take_profit));
         //---adding the optimum trailing stop to a binary file
         _file_handle=FileOpen("gbpusd_pip_boxer_ts.dat",FILE_BIN|FILE_WRITE);
         if (_file_handle<1)
               Print("Can't open file error - ",GetLastError());
            else
               {
                  FileWriteDouble(_file_handle, optimum_trailing_stop, DOUBLE_VALUE);
                  FileClose(_file_handle);
               }
         //--end of updating the binary file
         ticket=OrderSend(Symbol(),OP_BUY,init_lot_Count,Ask,2,Ask-init_stop_loss*Point,Ask+init_take_profit*Point,_current_message,690169,0,Green);
         if(ticket>0)
            {
               if(OrderSelect(ticket,SELECT_BY_TICKET)) 
                 {
                     //Print("Main BUY order opened : ",OrderOpenPrice());
                     //Print("I am procedure 2...LONG",OrderOpenPrice(),",",update_day_year,",",failiur_day_year);
                     StopLossPrice=OrderStopLoss( );
                     LongOrShort=1;
                     failiur_day_year=DayOfYear();
                     failiur_day_week=DayOfWeek(); 
                 }
            }
            else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
      
      // check for short position (SELL) opportunity
      if(_go_short)
        {
         max_loss_in_pips=(MathMax(High[0],High[1])-Bid)/Point;
         init_stop_loss=MathMax(max_loss_in_pips,StopLoss);
         double current_spread_in_pips=MarketInfo(Symbol(),MODE_SPREAD);
         init_stop_loss=MathMax(init_stop_loss,(mid_range_in_pips+current_spread_in_pips));
         init_lot_Count=lot_size_calc(init_stop_loss);
         max_win_in_pips=MathMax((mid_range_in_pips-current_spread_in_pips), TakeProfit);
         init_take_profit=max_win_in_pips;
         optimum_trailing_stop=MathMax(TrailingStop,(_trailing_stop_percentage*init_take_profit));
         //---adding the optimum trailing stop to a binary file
         _file_handle=FileOpen("gbpusd_pip_boxer_ts.dat",FILE_BIN|FILE_WRITE);
         if (_file_handle<1)
               Print("Can't open file error - ",GetLastError());
            else
               {
                  FileWriteDouble(_file_handle, optimum_trailing_stop, DOUBLE_VALUE);
                  FileClose(_file_handle);
               }
         //--end of updating the binary file
         ticket=OrderSend(Symbol(),OP_SELL,init_lot_Count,Bid,2,Bid+init_stop_loss*Point,Bid-init_take_profit*Point,_current_message,690169,0,Red);
         if(ticket>0)
            {
               if(OrderSelect(ticket,SELECT_BY_TICKET)) 
                  {
                    //Print("Main SELL order opened : ",OrderOpenPrice());
                    //Print("I am procedure 2...SHORT",OrderOpenPrice(),",",update_day_year,",",failiur_day_year);
                    StopLossPrice=OrderStopLoss( );
                    LongOrShort=-1;
                    failiur_day_year=DayOfYear();
                    failiur_day_week=DayOfWeek(); 
                  }
            }
            else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }    
      return(0);
   }

//+------------------------------------------------------------------+
//| Secondary entry to the market                                    |
//+------------------------------------------------------------------+
int revenge_the_fail()
   {
      double revenge_lot_count=lot_size_calc(StopLoss);
      double revenge_stop_loss=StopLoss;
      double revenge_max_loss_in_pips;
      /*
      if(AccountFreeMargin()<(1000*revenge_lot_count))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }*/
      
      // check for long position (BUY) opportunity
      if((LongOrShort==-1)&&(MathAbs(Prev_Closed_Price-StopLossPrice)<=(1*Point)))
        {
         revenge_max_loss_in_pips=(Ask-MathMin(Low[0],Low[1]))/Point;
         revenge_stop_loss=MathMax(revenge_max_loss_in_pips,StopLoss);
         revenge_stop_loss=MathMax(revenge_stop_loss,mid_range_in_pips);
         revenge_lot_count=lot_size_calc(revenge_stop_loss);
         double revenge_max_win_in_pips=MathMax(mid_range_in_pips, TakeProfit);
         double revenge_take_profit=revenge_max_loss_in_pips;
         optimum_trailing_stop=MathMax(TrailingStop,(_trailing_stop_percentage*revenge_take_profit));
         //---adding the optimum trailing stop to a binary file
         _file_handle=FileOpen("gbpusd_pip_boxer_ts.dat",FILE_BIN|FILE_WRITE);
         if (_file_handle<1)
               Print("Can't open file error - ",GetLastError());
            else
               {
                  FileWriteDouble(_file_handle, optimum_trailing_stop, DOUBLE_VALUE);
                  FileClose(_file_handle);
               }
         //--end of updating the binary file
         ticket=OrderSend(Symbol(),OP_BUY,revenge_lot_count,Ask,2,Ask-revenge_stop_loss*Point,Ask+revenge_take_profit*Point,"Revenge Long Pip Boxer",690169,0,Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
               {
                  //Print("2BUY order opened : ",OrderOpenPrice());
                  //Print("I am procedure 3...LONG",OrderOpenPrice(),",",update_day_year,",",failiur_day_year);
                  //StopLossPrice=OrderStopLoss( );
                  //LongOrShort=0;
                  failiur_day_year=-100;
                  failiur_day_week=-100;
                  update_day_year=-100;
                  update_day_week=-100; 
               }
           }
           else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
      
      // check for short position (SELL) opportunity
      if((LongOrShort==1)&&(MathAbs(Prev_Closed_Price-StopLossPrice)<=(1*Point)))
        {
         revenge_max_loss_in_pips=(MathMax(High[0],High[1])-Bid)/Point;
         revenge_stop_loss=MathMax(revenge_max_loss_in_pips,StopLoss);
         double current_spread_in_pips=MarketInfo(Symbol(),MODE_SPREAD);
         revenge_stop_loss=MathMax(revenge_stop_loss,(mid_range_in_pips+current_spread_in_pips));
         revenge_lot_count=lot_size_calc(revenge_stop_loss);
         revenge_max_win_in_pips=MathMax((mid_range_in_pips-current_spread_in_pips), TakeProfit);
         revenge_take_profit=revenge_max_win_in_pips;
         optimum_trailing_stop=MathMax(TrailingStop,(_trailing_stop_percentage*revenge_take_profit));
         //---adding the optimum trailing stop to a binary file
         _file_handle=FileOpen("gbpusd_pip_boxer_ts.dat",FILE_BIN|FILE_WRITE);
         if (_file_handle<1)
               Print("Can't open file error - ",GetLastError());
            else
               {
                  FileWriteDouble(_file_handle, optimum_trailing_stop, DOUBLE_VALUE);
                  FileClose(_file_handle);
               }
         //--end of updating the binary file
         ticket=OrderSend(Symbol(),OP_SELL,revenge_lot_count,Bid,2,Bid+revenge_stop_loss*Point,Bid-revenge_take_profit*Point,"Revenge Short Pip Boxer",690169,0,Red);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
               {
                  //Print("SELL order opened : ",OrderOpenPrice());
                  //Print("I am procedure 3...SHORT",OrderOpenPrice(),",",update_day_year,",",failiur_day_year);
                  //StopLossPrice=OrderStopLoss( );
                  //LongOrShort=0;
                  failiur_day_year=-100;
                  failiur_day_week=-100;
                  update_day_year=-100;
                  update_day_week=-100; 
               }
           }
           else Print("Error opening SELL order : ",GetLastError()); 
         return(0); 
        }
      return(0);
   }

//+------------------------------------------------------------------+
//| Main Procedure                                                   |
//+------------------------------------------------------------------+
int start()
  {
   double Lot_Count;
   
   /*
   //Correcting the behaviour of the system based on daylight saving time
   if ((DayOfYear()>=91)&&(DayOfYear()<=302)) 
      _server_time=1;
      else _server_time=2;
   
   Print("Server Time: ",_server_time);*/
// initial data checks
// it is important to make sure that the expert works with a normal
// chart and the user did not make any mistakes setting external 
// variables (Lots, StopLoss, TakeProfit, 
// TrailingStop) in our case, we check TakeProfit
// on a chart of less than 100 bars
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   if(TakeProfit<10)
     {
      Print("TakeProfit less than 10");
      return(0);  // check TakeProfit
     }

   
   //---calculates number of lots to trade based on account risk
   if ((account_risk_control)&&(Value_At_Risk>10))
     {
      Print("Too risky. The risk replaced with 10%.");
      Value_At_Risk=10;
     }
   
   
   //Procedure 1---calculating the higest_high and lowest_low
   int todays_box_size=the_box_size();
   
   //---check for open trades
   total=OrdersTotal();
   int _currently_open=0;
   
   if (total<1) _currently_open=0;
   
   if (total>=1)
      {
         for (int _count_it=0; _count_it<total; _count_it++)
            {
              OrderSelect(_count_it,SELECT_BY_POS,MODE_TRADES);
              if ((OrderMagicNumber()==690169))
               {
                  _currently_open++;
                  ticket=OrderTicket();
               }
            }
      }
   
   //Procedure 2---initial entery to the market
   if ((TimeHour(CurTime())==11+_time_shift+_server_time)&&(TimeMinute(CurTime())>=15)) 
      condition1=true;
      else condition1=false;
   if ((TimeHour(CurTime())>=(12+_time_shift+_server_time))&&(TimeHour(CurTime())<(12+_time_shift+opt_active_time+_server_time))) 
      condition2=true;
      else condition2=false;
      
   if((_currently_open==0)&&(condition1||condition2))
   {
    if((update_day_year==DayOfYear())&&(update_day_week==DayOfWeek())&&(failiur_day_year!=DayOfYear())&&(failiur_day_week!=DayOfWeek())) 
     int my_initial_entry_to_market=the_initial_entry();
   }

   //Procedure 3---secondary entery to the market
   if ((TimeHour(CurTime())==11+_time_shift+_server_time)&&(TimeMinute(CurTime())>=15)) 
      condition1=true;
      else condition1=false;
   if ((TimeHour(CurTime())>=(12+_time_shift+_server_time))&&(TimeHour(CurTime())<(12+_time_shift+opt_active_time+_server_time))) 
      condition2=true;
      else condition2=false;
   if(OrderSelect(ticket,SELECT_BY_TICKET)) 
      Prev_Closed_Price=OrderClosePrice();
      else return(-666);   
   
   if((revenge)&&(_currently_open==0)&&(condition1||condition2))
    {
      if((ticket>0)&&(failiur_day_year==DayOfYear())&&(failiur_day_week==DayOfWeek())) 
         {
            int this_is_my_revenge=revenge_the_fail(); 
         }
    } 
    
   //Procedure 4---trailing stop
   if ((_currently_open==1)&&(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)))
      {
       if (OrderType()<=OP_SELL && OrderSymbol()==Symbol())
         {
            //---- correct a long position
            if (OrderType()==OP_BUY)
               {
                  if(optimum_trailing_stop>0)  
                     {                 
                        if((Bid-OrderOpenPrice())>(Point*optimum_trailing_stop))
                           {
                              if(OrderStopLoss()<(Bid-Point*optimum_trailing_stop))
                                 {
                                    OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*optimum_trailing_stop,OrderTakeProfit(),0,Green);
                                    return(0);
                                 }
                           }
                     }
               }
            //---- exit a short position
            if (OrderType()==OP_SELL)
               {
                  if(optimum_trailing_stop>0)  
                     {                 
                        if((OrderOpenPrice()-Ask)>(Point*optimum_trailing_stop))
                           {
                              if(OrderStopLoss()>(Ask+Point*optimum_trailing_stop))
                                 {
                                    OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*optimum_trailing_stop,OrderTakeProfit(),0,Green);
                                    return(0);
                                 }
                           }
                     }                
               }
         }  
      } 
     
   return(0);
  }
// the end.