//+-------------+
//|Damon ATP EA |
//+-------------+
#property copyright "Mario Wondrak"
#property link      "mario.wondrak@gmx.net"

/*

Theory of operation 
http://www.forexfactory.com/showthread.php?t=82845

*/
extern string Basic        = "=====================:: Basic Settings ::=====================";
extern int    MagicNumber  =  123952;      // allows multiple experts to trade on same account
// extra user input
extern int    Buffer       =       2;
// extra user input

// user input
extern string MM           = "===============:: Money Management Settings ::================";
extern string MMManual     = "= Option Moneymanagement:                                    =";
extern string MMManual2    = "= 0 = Safety, 1 = Conservative, 2 = Moderate, 3 = Aggressive =";
extern int MoneyManagement =       0;
extern bool   UseAutoMM    =    true;
extern bool   UseDamonlStop=    true;
extern bool   UseSWIStop   =   false;
extern double ProfitMade   =       0;    // how much money do you expect to make
extern double LossLimit    =       0;    // how much loss can you tolorate
extern int    BreakEven    =       0;    // set break even when this many pips are made
extern double TrailStop    =       0;    // trailing stop (999=no trailing stop)
extern int    StartHour    =       0;    // your local time to start making trades
extern int    StopHour     =      24;    // your local time to stop making trades
extern int    BasketProfit =    9999;    // if equity reaches this level, close trades
extern int    BasketLoss   =    9999;    // if equity reaches this -level, close trades
extern double Lots         =       0.2;  // how many lots to trade at a time 
extern int    MaxLots      =      20;
extern int    AlarmStop    =      20;
extern bool   LotIncrease  =    true;    // grow lots based on balance = true
extern bool   UseAlarmStop =   false;


extern string News         = "==================:: News Indicator Settings ::===============";
extern string NewsManual   = "=    Use News Alarm to prevent trading arroung News Times    =";
extern bool   UseNewsAlarm =   false;
extern int    MinsBeforeNews =   720; // mins before an event to stay out of trading
extern int    MinsAfterNews  =   180; // mins after  an event to stay out of trading
// // Global variable at top of file for News Indicator
bool NewsTime;    

// non-external flag settings
bool   logging=true  ;                   // log data or not
int    Slippage=2;                       // how many pips of slippage can you tolorate
double Price;

// naming and numbering
string TradeComment = "===Damonl_ATP_EA_1a===";   // comment so multiple EAs can be seen in Account History
double StartingBalance=0;                // lot size control if LotIncrease == true

// Bar handling
datetime bartime=0;                      // used to determine when a bar has moved
int      bartick=0;                      // number of times bars have moved

// Trade control
bool   TradeAllowed=true;                // used to manage trades
static int MACDTrendUp = 0;
static int LGTrendUp = 0;
static int MATrendUp = 0;
static int StochTrendUp = 0;
static int AOTrendUp = 0;
static int ACTrendUp = 0;
static int PivotTrendUp = 0;
static string W1SolarTrend = "NO";
static string D1SolarTrend = "NO";
static string W1NLMATrend = "NO";
static string StochTrend = "NO";
static string PivotTrend = "NO";
static string Status = "No Trend verified. Waiting for Signals...";
string TradeStyle = "No";
double OldLots;
int OldTrailStop;
// Min/Max tracking and tick logging
int    maxOrders;                        // statistic for maximum numbers or orders open at one time
double maxEquity;                        // statistic for maximum equity level
double minEquity;                        // statistic for minimum equity level

bool BUYSignal = false;
bool SELLSignal = false;
// used for verbose error logging
#include <stdlib.mqh>


//+-------------+
//| Custom init |
//|-------------+
// Called ONCE when EA is added to chart or recompiled

int init()
  {
   if(LotIncrease)
     {
      StartingBalance=AccountBalance()/Lots;
      logwrite(TradeComment+MagicNumber,"LotIncrease ACTIVE Account balance="+AccountBalance()+" Lots="+Lots+" StartingBalance="+StartingBalance);
     }
    else
     {
      logwrite(TradeComment+MagicNumber,"LotIncrease NOT ACTIVE Account balance="+AccountBalance()+" Lots="+Lots);
     }

   logwrite(TradeComment+MagicNumber,"Init Complete");
   Comment(" ");
   OldTrailStop = TrailStop;
   OldLots = Lots;
  }

//+----------------+
//| Custom DE-init |
//+----------------+
// Called ONCE when EA is removed from chart

int deinit()
  {

   // always indicate deinit statistics
   logwrite(TradeComment+MagicNumber,"MAX number of orders "+maxOrders);
   logwrite(TradeComment+MagicNumber,"MAX equity           "+maxEquity);
   logwrite(TradeComment+MagicNumber,"MIN equity           "+minEquity);

   // so you can see stats in journal
   Print("MAX number of orders "+maxOrders);
   Print("MAX equity           "+maxEquity);
   Print("MIN equity           "+minEquity);


   logwrite(TradeComment+MagicNumber,"DE-Init Complete");
   
   Comment(" ");
  }
 // Function to check if it is news time
void NewsHandling()
{
   if(UseNewsAlarm == true)
   {
      static int PrevMinute = -1;
   
      if (Minute() != PrevMinute)
      {
         PrevMinute = Minute();
         int minutesSincePrevEvent = iCustom(NULL, 0, "4XB GO FFCal", true, true, false, true, true, 1, 0);
         int minutesUntilNextEvent = iCustom(NULL, 0, "4XB GO FFCal", true, true, false, true, true, 1, 1);
         NewsTime = false;
         if ((minutesUntilNextEvent <= MinsBeforeNews) || (minutesSincePrevEvent <= MinsAfterNews))
         {
            NewsTime = true;
         }
      }
   }
}//newshandling

bool NewBar()
{
   static datetime lastbar = 0;
   datetime curbar = Time[0];
   if(lastbar!=curbar)
   {
      lastbar=curbar;
      return (true);
   }
   else
   {
      return(false);
   }
}  
//+-----------+
//| Main      |
//+-----------+
// Called EACH TICK and each Bar[]

int start()
  {
   //PROTECTION EXPIRE DATE
   /*
   string expire_date = "2006.31.06"; //<-- hard coded datetime
   datetime e_d = StrToTime(expire_date);
  
   if (CurTime() >= e_d)
   {
      Alert ("The trial version has been expired!");
      return(0);
   }
   // your normal code!
   return(0);
   */
   //PROTECTION ACCOUNT NUMBER
   /*
   int hard_accnt = 11111; //<-- type the user account here before compiling
   int accnt = AccountNumber();
  
   if (accnt != hard_accnt)
   {
      Alert ("You can not use this account (" + DoubleToStr(accnt,0) + ") with this program!");
      return(0);
   }
   */
   //PROTECTION ACCOUNT TYPE
   /*
   bool demo_account = IsDemo();
  
   if (!demo_account)
   {
      Alert ("You can not use the program with a real account!");
      return(0);
   }
   */
   int      cnt=0;
   int      gle=0;
   int      ticket=0;
   int      OrdersPerSymbol=0;
   int      OrdersBUY=0;
   int      OrdersSELL=0;
  
   // stoploss and takeprofit and close control
   double SL=0;
   double TP=0;
   double CurrentProfit=0;
   double CurrentBasket=0;
   
   // direction control
   bool BUYme=false;
   bool SELLme=false;
   
 
   // bar counting, Newstime check
   if(bartime!=Time[0]) 
     {
         bartime=Time[0];
         bartick++; 
         NewsHandling();
         if(Hour()>=StartHour && Hour()<=StopHour && NewsTime != true)
         {
            TradeAllowed=true;
            BUYSignal = false;
            SELLSignal = false;
         }
     }

   // Lot increasement based on AccountBalance when expert is started
   // this will trade 1.0, then 1.1, then 1.2 etc as account balance grows
   // or 0.9 then 0.8 then 0.7 as account balance shrinks 
   if(UseAutoMM == false)
   {
      if(LotIncrease)
      {
         Lots=NormalizeDouble(AccountBalance()/StartingBalance,1);
         if(Lots>MaxLots) Lots=MaxLots;
      }
   }
   if(UseAutoMM == true)
   {
      if(MoneyManagement == 0)
      {
         Lots = NormalizeDouble(AccountBalance()/40000,2);
         TradeStyle = "Safety";
      }
      if(MoneyManagement == 1)
      {
         Lots = NormalizeDouble(AccountBalance()/30000,2);
         TradeStyle = "Conservative";
      }
      if(MoneyManagement == 2)
      {
         Lots = NormalizeDouble(AccountBalance()/20000,2);
         TradeStyle = "Moderate";
      }
      if(MoneyManagement == 3)
      {
         Lots = NormalizeDouble(AccountBalance()/10000,2);
         TradeStyle = "Aggressive";
      }
   }

   OrdersPerSymbol=0;
   for(cnt=OrdersTotal();cnt>=0;cnt--)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
        {
         OrdersPerSymbol++;
         if(OrderType()==OP_BUY) {OrdersBUY++;}
         if(OrderType()==OP_SELL){OrdersSELL++;}
        }
     }
   
   // keep some statistics
  // if(OrdersPerSymbol>maxOrders) TradeAllowed = false;

     
   //+-----------------------------+
   //| Insert your indicator here  |
   //| And set either BUYme or     |
   //| SELLme true to place orders |
   //+-----------------------------+
   
   //PIVOT
   bool Use_Sunday_Data   = false;
   bool Daily             = True;
   bool Daily_SR_Levels   = True;
   bool Weekly            = True;
   bool Weekly_SR_Levels  = False;
   bool Monthly           = True;
   bool Monthly_SR_Levels = False;

   double YesterdayHigh;
   double YesterdayLow;
   double YesterdayClose;
   double Day_Price[][6];
   double Pivot,S1,S2,S3,R1,R2,R3;
      
   double WeekHigh;
   double WeekLow;
   double WeekClose;
   double Weekly_Price[][6];
   double WeekPivot,WS1,WS2,WS3,WR1,WR2,WR3;
   
   double MonthHigh;
   double MonthLow;
   double MonthClose;
   double Month_Price[][6];
   double MonthPivot,MS1,MS2,MS3,MR1,MR2,MR3;
   
   ArrayCopyRates(Day_Price,(Symbol()), 1440);

   
  
   YesterdayHigh  = Day_Price[1][3];
   YesterdayLow   = Day_Price[1][2];
   YesterdayClose = Day_Price[1][4];
   
   Pivot = ((YesterdayHigh + YesterdayLow + YesterdayClose)/3);

   R1 = (2*Pivot)-YesterdayLow;
   S1 = (2*Pivot)-YesterdayHigh;

   R2 = Pivot+(R1-S1);
   S2 = Pivot-(R1-S1);
   
   R3 = (YesterdayHigh + (2*(Pivot-YesterdayLow)));
   S3 = (YesterdayLow - (2*(YesterdayHigh-Pivot)));  
  
  
if (Use_Sunday_Data == false)
 {   
   while (DayOfWeek() == 1)
      {
       
              
       YesterdayHigh  = Day_Price[2][3];
       YesterdayLow   = Day_Price[2][2];
       YesterdayClose = Day_Price[2][4];
   
       Pivot = ((YesterdayHigh + YesterdayLow + YesterdayClose)/3);

       R1 = (2*Pivot)-YesterdayLow;
       S1 = (2*Pivot)-YesterdayHigh;

       R2 = Pivot+(R1-S1);
       S2 = Pivot-(R1-S1);
   
       R3 = (YesterdayHigh + (2*(Pivot-YesterdayLow)));
       S3 = (YesterdayLow - (2*(YesterdayHigh-Pivot)));
       break;
      }
 }
   ArrayCopyRates(Weekly_Price, Symbol(), 10080);

   WeekHigh  = Weekly_Price[1][3];
   WeekLow   = Weekly_Price[1][2];
   WeekClose = Weekly_Price[1][4];

   WeekPivot = ((WeekHigh + WeekLow + WeekClose)/3);

      WR1 = (2*WeekPivot)-WeekLow;
      WS1 = (2*WeekPivot)-WeekHigh;

      WR2 = WeekPivot+(WR1-WS1);
      WS2 = WeekPivot-(WR1-WS1);

      WS3 = (WeekLow - (2*(WeekHigh-WeekPivot)));
      WR3 = (WeekHigh + (2*(WeekPivot-WeekLow)));

//--------------------------------------------------------
//--------------------------------------------------------


   ArrayCopyRates(Month_Price, Symbol(), 43200);

   MonthHigh  = Month_Price[1][3];
   MonthLow   = Month_Price[1][2];
   MonthClose = Month_Price[1][4];

   MonthPivot = ((MonthHigh + MonthLow + MonthClose)/3);

      MR1 = (2*MonthPivot)-MonthLow;
      MS1 = (2*MonthPivot)-MonthHigh;

      MR2 = MonthPivot+(MR1-MS1);
      MS2 = MonthPivot-(MR1-MS1);

      MS3 = (MonthLow - (2*(MonthHigh-MonthPivot)));
      MR3 = (MonthHigh + (2*(MonthPivot-MonthLow)));
      
   if(Pivot < Bid){PivotTrendUp = 1;PivotTrend = "UP";}
   if(Pivot > Ask){PivotTrendUp =-1;PivotTrend = "DOWN";}  
   //Pending Orders 
   double PrevBarHigh = iHigh(NULL,PERIOD_D1,1);
   double PrevBarLow = iLow(NULL,PERIOD_D1,1);
    
   double W1Solar11 = iCustom(NULL,PERIOD_W1,"4XB ATP Solar",0,1);
   double W1Solar11Pre = iCustom(NULL,PERIOD_W1,"4XB ATP Solar",0,2);
   double D1Solar11 = iCustom(NULL,PERIOD_D1,"4XB ATP Solar",0,1);
   double D1Solar11Pre = iCustom(NULL,PERIOD_D1,"4XB ATP Solar",0,2);
   
   double W1NLMAUP = iCustom(NULL,PERIOD_W1,"4XB ATP Solar",1,0);
   double W1NLMADN = iCustom(NULL,PERIOD_W1,"4XB ATP Solar",2,0);
   double W1NLMAUPPre = iCustom(NULL,PERIOD_W1,"4XB ATP Solar",1,1);
   double W1NLMADNPre = iCustom(NULL,PERIOD_W1,"4XB ATP Solar",2,1);
   
   if(W1Solar11 > 0 && W1Solar11Pre < W1Solar11)W1SolarTrend = "UP Strong";
   if(W1Solar11 > 0 && W1Solar11Pre > W1Solar11)W1SolarTrend = "UP Weak";
   if(W1Solar11 < 0 && W1Solar11Pre > W1Solar11)W1SolarTrend = "DOWN Strong";
   if(W1Solar11 < 0 && W1Solar11Pre < W1Solar11)W1SolarTrend = "DOWN Weak";
   
   if(D1Solar11 > 0 && D1Solar11Pre < D1Solar11)D1SolarTrend = "UP Strong";
   if(D1Solar11 > 0 && D1Solar11Pre > D1Solar11)D1SolarTrend = "UP Weak";
   if(D1Solar11 < 0 && D1Solar11Pre > D1Solar11)D1SolarTrend = "DOWN Strong";
   if(D1Solar11 < 0 && D1Solar11Pre < D1Solar11)D1SolarTrend = "DOWN Weak";
   
   if(W1NLMAUP != EMPTY_VALUE && W1NLMAUPPre != EMPTY_VALUE)W1NLMATrend = "Blue";//UP
   if(W1NLMADN != EMPTY_VALUE && W1NLMADNPre != EMPTY_VALUE)W1NLMATrend = "Red";
   if(W1NLMAUP != EMPTY_VALUE && W1NLMADNPre != EMPTY_VALUE)W1NLMATrend = "Yellow from Red";
   if(W1NLMADN != EMPTY_VALUE && W1NLMAUPPre != EMPTY_VALUE)W1NLMATrend = "Yellow from Blue";
   
   //Possible Uptrends
   if((W1NLMATrend == "Blue" && W1SolarTrend == "UP Strong" && D1SolarTrend == "UP Strong") || (W1NLMATrend == "Blue" && W1SolarTrend == "UP Weak" && D1SolarTrend == "UP Weak"))
   {
      Status = "Strong UP Trend indicated. Placing BuyStop!";
      Price = PrevBarHigh + Ask - Bid + Buffer*Point; 
      Lots = OldLots;
      if(BUYSignal == false)BUYme = true;
   }
   if((W1NLMATrend == "Red" && W1SolarTrend == "UP Strong" && D1SolarTrend == "UP Strong") || (W1NLMATrend == "Red" && W1SolarTrend == "UP Weak" && D1SolarTrend == "UP Weak"))
   {
      Status = "Weak UP Trend indicated. Placing BuyStop!";
      Price = PrevBarHigh + Ask - Bid + Buffer*Point; 
      Lots = NormalizeDouble(Lots/2,2);
      if(BUYSignal == false)BUYme = true;
   }
   if((W1NLMATrend == "Yellow from Blue" && W1SolarTrend == "UP Strong" && D1SolarTrend == "UP Strong") || (W1NLMATrend == "Yellow from Blue" && W1SolarTrend == "UP Weak" && D1SolarTrend == "UP Weak"))
   {
      Status = "Weak UP Trend indicated. Placing BuyStop!";
      Price = PrevBarHigh + Ask - Bid + Buffer*Point; 
      Lots = NormalizeDouble(Lots/2,2);
      if(BUYSignal == false)BUYme = true;
   }
   if((W1NLMATrend == "Yellow from Red" && W1SolarTrend == "UP Strong" && D1SolarTrend == "UP Strong") || (W1NLMATrend == "Yellow from Red" && W1SolarTrend == "UP Weak" && D1SolarTrend == "UP Weak"))
   {
      Status = "Strong UP Trend indicated. Placing BuyStop!";
      Price = PrevBarHigh + Ask - Bid + Buffer*Point; 
      Lots = OldLots;
      if(BUYSignal == false)BUYme = true;
   }
   //Possible DownTrends
   if((W1NLMATrend == "Red"  && W1SolarTrend == "DOWN Strong" && D1SolarTrend == "DOWN Strong") || (W1NLMATrend == "Red"  && W1SolarTrend == "DOWN Weak" && D1SolarTrend == "DOWN Weak"))
   {
      Status = "Strong DOWN Trend indicated. Placing SellLimit";
      Price = PrevBarLow - (Ask - Bid) - Buffer*Point; 
      Lots = OldLots;
      if(SELLSignal == false)SELLme = true;
   }
   if((W1NLMATrend == "Blue"  && W1SolarTrend == "DOWN Strong" && D1SolarTrend == "DOWN Strong") || (W1NLMATrend == "Blue"  && W1SolarTrend == "DOWN Weak" && D1SolarTrend == "DOWN Weak"))
   {
      Status = "Weak DOWN Trend indicated. Placing SellLimit";
      Price = PrevBarLow - (Ask - Bid) - Buffer*Point; 
      Lots = NormalizeDouble(Lots/2,2);
      if(SELLSignal == false)SELLme = true;
   }
   if((W1NLMATrend == "Yellow from Blue"  && W1SolarTrend == "DOWN Strong" && D1SolarTrend == "DOWN Strong") || (W1NLMATrend == "Yellow from Blue"  && W1SolarTrend == "DOWN Weak" && D1SolarTrend == "DOWN Weak"))
   {
      Status = "Strong DOWN Trend indicated. Placing SellLimit";
      Price = PrevBarLow - (Ask - Bid) - Buffer*Point; 
      Lots = OldLots;
      if(SELLSignal == false)SELLme = true;
   }
   if((W1NLMATrend == "Yellow from Red"  && W1SolarTrend == "DOWN Strong" && D1SolarTrend == "DOWN Strong") || (W1NLMATrend == "Yellow from Red"  && W1SolarTrend == "DOWN Weak" && D1SolarTrend == "DOWN Weak"))
   {
      Status = "Weak DOWN Trend indicated. Placing SellLimit";
      Price = PrevBarLow - (Ask - Bid) - Buffer*Point; 
      Lots = NormalizeDouble(Lots/2,2);
      if(SELLSignal == false)SELLme = true;
   }
 
   double D1SolarStop = iCustom(NULL,PERIOD_D1,"4XB ATP Solar",0,1); 
   double D1SolarStopPre = iCustom(NULL,PERIOD_D1,"4XB ATP Solar",0,2);  
   


   //+------------+
   //| End Insert |
   //+------------+
   
   //Comments
   Comment(
            "\nAccount: ", AccountNumber(),
            "\nName: ", AccountName(),
            "\nBroker: ", AccountCompany(),
            "\nEA: ", TradeComment,
            "\nMagicNumber: ",MagicNumber,
            "\n------------------------------------------",
            "\nProfit: ", AccountProfit(),
            "\nEquity: ", AccountEquity(),
            "\nBalance: ", AccountBalance(),
            "\nFree Margin: ", AccountFreeMargin(),
            "\nLots: ", Lots,
            "\nMaximum Equity: ",maxEquity,
            "\nMinimum Equity: ",minEquity,
            "\n------------------------------------------",
            "\nStatus: ",Status,
            "\nMoney Management: ",TradeStyle,
            "\nTrailstop: ", TrailStop,
            "\nW1 NLMA Trend: ",W1NLMATrend,
            "\nW1 Solar Trend: ", W1SolarTrend,
            "\nD1 Solar Trend: ", D1SolarTrend,
            "\nSpread: ", Ask - Bid,
            "\nOrdersBUY: ", OrdersBUY,
            "\nOrdersSELL: ", OrdersSELL,
            "\nBUYSignal: ",BUYSignal,
            "\nSELLSignal: ",SELLSignal,
            "\nPivot Trend: ", PivotTrend,
            "\nSignal Bar High: ", PrevBarHigh,
            "\nSignal Bar Low: ", PrevBarLow,
            "\nPrice: ",Price,
            "\nTrade Allowed: ", TradeAllowed

            );
   
   //ENTRY LONG (buy, Ask) 
   if( (OrdersPerSymbol==0 && BUYme)||(TradeAllowed && BUYme) )
     {
      if(LossLimit ==0) SL=0; else SL=Ask-((LossLimit+10)*Point );
      if(ProfitMade==0) TP=0; else TP=Ask+((ProfitMade+10)*Point );
      ticket=OrderSend(Symbol(),OP_BUYSTOP,Lots,Price,Slippage,SL,TP,TradeComment+MagicNumber,MagicNumber,0,Green);
      gle=GetLastError();
      if(gle==0)
        {
         if(logging) logwrite(TradeComment+MagicNumber,"BUY Ticket="+ticket+" Ask="+Ask+" Lots="+Lots+" SL="+SL+" TP="+TP);
         TradeAllowed=false;
         BUYSignal = true;
         SELLSignal = false;
         Lots = OldLots;
        }
         else 
        {
         logwrite(TradeComment+MagicNumber,"-----ERROR-----  opening BUY order :"+gle+" ticket="+ticket+" "+ErrorDescription(gle)); 
         if(gle == 130)
         {
            ticket=OrderSend(Symbol(),OP_BUY,Lots,Price,Slippage,SL,TP,TradeComment+MagicNumber,MagicNumber,0,Green);
            gle=GetLastError();
            if(gle==0)
            {
             if(logging) logwrite(TradeComment+MagicNumber,"BUY Ticket="+ticket+" Ask="+Ask+" Lots="+Lots+" SL="+SL+" TP="+TP);
             TradeAllowed=false;
             BUYSignal = true;
             SELLSignal = false;
             Lots = OldLots;
            }
            else
            {
               logwrite(TradeComment+MagicNumber,"-----ERROR-----  opening BUY order :"+gle+" ticket="+ticket+" "+ErrorDescription(gle)); 
            }
         }
        }
     }//BUYme
        

   //ENTRY SHORT (sell, Bid)
   if( (OrdersPerSymbol==0 && SELLme)||(TradeAllowed && SELLme) )
    {
      if(LossLimit ==0) SL=0; else SL=Bid+((LossLimit+10)*Point );
      if(ProfitMade==0) TP=0; else TP=Bid-((ProfitMade+10)*Point );
      ticket=OrderSend(Symbol(),OP_SELLLIMIT,Lots,Price,Slippage,SL,TP,TradeComment+MagicNumber,MagicNumber,0,Red);
      gle=GetLastError();
      if(gle==0)
        {
         if(logging) logwrite(TradeComment+MagicNumber,"SELL Ticket="+ticket+" Bid="+Bid+" Lots="+Lots+" SL="+SL+" TP="+TP);
         TradeAllowed=false;
         SELLSignal = true;
         BUYSignal = false;
         Lots = OldLots;
        }
         else 
        {
         logwrite(TradeComment+MagicNumber,"-----ERROR-----  opening SELL order :"+gle+" ticket="+ticket+" "+ErrorDescription(gle));
         if(gle == 130)
         {
            ticket=OrderSend(Symbol(),OP_SELL,Lots,Price,Slippage,SL,TP,TradeComment+MagicNumber,MagicNumber,0,Red);
            gle=GetLastError();
            if(gle==0)
            {
             if(logging) logwrite(TradeComment+MagicNumber,"SELL Ticket="+ticket+" Bid="+Bid+" Lots="+Lots+" SL="+SL+" TP="+TP);
             TradeAllowed=false;
             SELLSignal = true;
             BUYSignal = false;
             Lots = OldLots;
            }
            else
            {
               logwrite(TradeComment+MagicNumber,"-----ERROR-----  opening SELL order :"+gle+" ticket="+ticket+" "+ErrorDescription(gle));
            }
         }
        }
      }//SELLme

     
   //Basket profit or loss
   CurrentBasket=AccountEquity()-AccountBalance();
   if( CurrentBasket>=BasketProfit || CurrentBasket<=(BasketLoss*(-1)) ) CloseEverything();

   // accumulate statistics
   if(CurrentBasket>maxEquity) maxEquity=CurrentBasket;
   if(CurrentBasket<minEquity) minEquity=CurrentBasket;
   

   //
   // Order Management
   //
   for(cnt=OrdersTotal();cnt>=0;cnt--)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber )
        {
        
         if(OrderType()==OP_BUY)
           {
            CurrentProfit=Bid-OrderOpenPrice() ;
            if(logging) logwrite(TradeComment+MagicNumber,"BUY  CurrentProfit="+CurrentProfit/Point+" CurrentBasket="+CurrentBasket/Point);

            //
            // Modify for break even
            //=======================
            //
            // OrderStopLoss will be equal to OrderOpenPrice if this event happens
            // thus it will only ever get executed one time per ticket
            if( BreakEven>0 )
              {
               if (CurrentProfit >= BreakEven*Point && OrderOpenPrice()>OrderStopLoss())
                 {
                  SL=OrderOpenPrice()+(Ask-Bid);
                  TP=OrderTakeProfit();
                  OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0, White);
                  gle=GetLastError();
                  if(gle==0)
                    {
                     if(logging) logwrite(TradeComment+MagicNumber,"MODIFY BUY BE Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                    }
                     else 
                    {
                     logwrite(TradeComment+MagicNumber,"-----ERROR----- MODIFY BUY  BE Bid="+Bid+" error="+gle+" "+ErrorDescription(gle));
                    }
                 }
              }
            if(UseDamonlStop == true)
            {
                  if(D1SolarStop < 0 && D1SolarStopPre > D1SolarStop)
                  {
                     SL = PrevBarLow - (Ask - Bid) - Buffer*Point;
                     OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0,White);
                     gle=GetLastError();
                     if(gle==0)
                       {
                        if(logging) logwrite(TradeComment+MagicNumber,"MODIFY BUY TS Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                        Status = "Possible Trendchange. Set StopLoss on Previous Barīs Low."; 
                       }
                        else 
                       {
                        logwrite(TradeComment+MagicNumber,"-----ERROR----- MODIFY BUY TS Bid="+Bid+" error="+gle+" "+ErrorDescription(gle)+" ");
                       } 
                  }
            }
            if(UseSWIStop == true)
            {
               if(D1SolarStop < 0 && D1SolarStopPre > D1SolarStop)
                  {
                     CloseBuyOrders();
                     Status = "Possible Trendchange. Closing BUY Orders.";
                  }
            }
            //
            // check for trailing stop
            //=========================
            //
            if( TrailStop>0 )  
              {                 
               if( Bid-OrderOpenPrice()>(TrailStop*Point) )
                 {
                  if( OrderStopLoss()<Bid-(TrailStop*Point) )
                    {
                     SL=Bid-(TrailStop*Point);
                     TP=OrderTakeProfit();
                     OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0,White);
                     gle=GetLastError();
                     if(gle==0)
                       {
                        if(logging) logwrite(TradeComment+MagicNumber,"MODIFY BUY TS Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                       }
                        else 
                       {
                        logwrite(TradeComment+MagicNumber,"-----ERROR----- MODIFY BUY TS Bid="+Bid+" error="+gle+" "+ErrorDescription(gle)+" ");
                       }
                    }
                 }
              }


            //
            // Did we make a profit
            //======================
            //
            if(ProfitMade>0 && CurrentProfit>=(ProfitMade*Point))
              {
               OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,White);
               gle=GetLastError();
               if(gle==0)
                 {
                  if(logging) logwrite(TradeComment+MagicNumber,"CLOSE BUY PROFIT Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                 }
                else 
                 {
                  logwrite(TradeComment+MagicNumber,"-----ERROR----- CLOSE BUY PROFIT Bid="+Bid+" error="+gle+" "+ErrorDescription(gle));
                 }
              }
              

            //
            // Did we take a loss
            //====================
            //
            if( LossLimit>0 && CurrentProfit<=(LossLimit*(-1)*Point)  )
              {
               OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,White);
               gle=GetLastError();
               if(gle==0)
                 {
                  if(logging) logwrite(TradeComment+MagicNumber,"CLOSE BUY LOSS Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                 }
                else 
                 {
                  logwrite(TradeComment+MagicNumber,"-----ERROR----- CLOSE BUY LOSS Bid="+Bid+" error="+gle+" "+ErrorDescription(gle));
                 }
              }
              
           } // if BUY


         if(OrderType()==OP_SELL)
           {

            CurrentProfit=OrderOpenPrice()-Ask;
            if(logging) logwrite(TradeComment+MagicNumber,"SELL CurrentProfit="+CurrentProfit/Point+" CurrentBasket="+CurrentBasket/Point);

            //
            // Modify for break even
            //=======================
            //
            // OrderStopLoss will be equal to OrderOpenPrice if this event happens
            // thus it will only ever get executed one time per ticket
            if( BreakEven>0 )
              {
               if (CurrentProfit >= BreakEven*Point && OrderOpenPrice()<OrderStopLoss())
                 {
                  SL=OrderOpenPrice()-(Ask-Bid);
                  TP=OrderTakeProfit();
                  OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0, White);
                  gle=GetLastError();
                  if(gle==0)
                    {
                     if(logging) logwrite(TradeComment+MagicNumber,"MODIFY SELL BE Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                    }
                     else 
                    {
                     logwrite(TradeComment+MagicNumber,"-----ERROR----- MODIFY SELL BE Ask="+Ask+" error="+gle+" "+ErrorDescription(gle));
                    }
                 }
              }
            if(UseDamonlStop == true)
            {
                if(D1SolarStop > 0 && D1SolarStopPre < D1SolarStop)
                  {
                     SL = PrevBarHigh + (Ask - Bid) + Buffer*Point;
                     OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0,White);
                     gle=GetLastError();
                     if(gle==0)
                       {
                        if(logging) logwrite(TradeComment+MagicNumber,"MODIFY SELL TS Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                        Status = "Possible Trendchange. Set StopLoss on Previous Barīs High.";                     
                       }
                        else 
                       {
                        logwrite(TradeComment+MagicNumber,"-----ERROR----- MODIFY SELL TS Ask="+Ask+" error="+gle+" "+ErrorDescription(gle));
                       }
                  }
            }
            if(UseSWIStop == true)
            {
               if(D1SolarStop > 0 && D1SolarStopPre < D1SolarStop)
               {
                  CloseSellOrders();
                  Status = "Possible Trendchange. Closing SELL Orders."; 
               }
            }

            //
            // check for trailing stop
            //=========================
            //
            if(TrailStop>0)  
              {                 
               if( (OrderOpenPrice()-Ask)>(TrailStop*Point) )
                 {
                  if( OrderStopLoss()>(Ask+(TrailStop*Point)) || (OrderStopLoss()==0) )
                    {
                     SL=Ask+(TrailStop*Point);
                     TP=OrderTakeProfit();
                     OrderModify(OrderTicket(),OrderOpenPrice(),SL,TP,0,White);
                     gle=GetLastError();
                     if(gle==0)
                       {
                        if(logging) logwrite(TradeComment+MagicNumber,"MODIFY SELL TS Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                       }
                        else 
                       {
                        logwrite(TradeComment+MagicNumber,"-----ERROR----- MODIFY SELL TS Ask="+Ask+" error="+gle+" "+ErrorDescription(gle));
                       }
                    }
                 }
              }


            //
            // Did we make a profit
            //======================
            //
            if( ProfitMade>0 && CurrentProfit>=(ProfitMade*Point) )
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
               gle=GetLastError();
               if(gle==0)
                 {
                  if(logging) logwrite(TradeComment+MagicNumber,"CLOSE SELL PROFIT Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                 }
                  else 
                 {
                  logwrite(TradeComment+MagicNumber,"-----ERROR----- CLOSE SELL PROFIT Ask="+Ask+" error="+gle+" "+ErrorDescription(gle));
                 }
                 
              }


            //
            // Did we take a loss
            //====================
            //
            if( LossLimit>0 && CurrentProfit<=(LossLimit*(-1)*Point) )
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
               gle=GetLastError();
               if(gle==0)
                 {
                  if(logging) logwrite(TradeComment+MagicNumber,"CLOSE SELL LOSS Ticket="+OrderTicket()+" SL="+SL+" TP="+TP);
                 }
                  else 
                 {
                  logwrite(TradeComment+MagicNumber,"-----ERROR----- CLOSE SELL LOSS Ask="+Ask+" error="+gle+" "+ErrorDescription(gle));
                 }
                 
              }


           } //if SELL
           
        } // if(OrderSymbol)
        
     } // for

  } // start()

//+-----------------+
//| CloseEverything |
//+-----------------+
// Closes all OPEN and PENDING orders

int CloseEverything()
{
   double myAsk;
   double myBid;
   int    myTkt;
   double myLot;
   int    myTyp;

   int i;
   bool result = false;
    
   for(i=OrdersTotal();i>=0;i--)
   {
      OrderSelect(i, SELECT_BY_POS);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber )
      {          
         myBid=MarketInfo(OrderSymbol(),MODE_BID);            
         myTkt=OrderTicket();
         myLot=OrderLots();
         myTyp=OrderType();
            
         switch( myTyp )
         {
            //Close opened long positions
            case OP_BUY      :result = OrderClose(myTkt, myLot, myBid, Slippage, Red);
            break;
      
            //Close opened short positions
            case OP_SELL     :result = OrderClose(myTkt, myLot, myAsk, Slippage, Red);
            break;

            //Close pending orders
            case OP_BUYLIMIT :
            case OP_BUYSTOP  :
            case OP_SELLLIMIT:
            case OP_SELLSTOP :result = OrderDelete( OrderTicket() );
         }
         if(result == false)
         {
            Alert("Order " , myTkt , " failed to close. Error:" , GetLastError() );
            Print("Order " , myTkt , " failed to close. Error:" , GetLastError() );
            Sleep(3000);
         }  

         Sleep(1000);
      }
  } //for
  
} // closeeverything
//+-----------------+
//| CloseSellOrders |
//+-----------------+

int CloseSellOrders()
{
   double myAsk;
   double myBid;
   int    myTkt;
   double myLot;
   int    myTyp;

   int i;
   bool result = false;
    
   for(i=OrdersTotal();i>=0;i--)
   {
      OrderSelect(i, SELECT_BY_POS);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber )
      {
         myAsk=MarketInfo(OrderSymbol(),MODE_ASK);            
         myBid=MarketInfo(OrderSymbol(),MODE_BID);            
         myTkt=OrderTicket();
         myLot=OrderLots();
         myTyp=OrderType();
            
         switch( myTyp )
         {
         
            //Close opened short positions
            case OP_SELL     :result = OrderClose(myTkt, myLot, myAsk, Slippage, Red);
            break;

         }
    
         if(result == false)
         {
            Alert("Order " , myTkt , " failed to close. Error:" , GetLastError() );
            Print("Order " , myTkt , " failed to close. Error:" , GetLastError() );
            Sleep(3000);
         }  
         else return(result);
         Sleep(1000);
       }

    } //for
  
} // closeSell
//+-----------------+
//| CloseBuyOrders  |
//+-----------------+

int CloseBuyOrders()
{
   double myAsk;
   double myBid;
   int    myTkt;
   double myLot;
   int    myTyp;

   int i;
   bool result = false;
    
   for(i=OrdersTotal();i>=0;i--)
   {
      OrderSelect(i, SELECT_BY_POS);
      if( OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber )
      {
         myAsk=MarketInfo(OrderSymbol(),MODE_ASK);            
         myBid=MarketInfo(OrderSymbol(),MODE_BID);            
         myTkt=OrderTicket();
         myLot=OrderLots();
         myTyp=OrderType();
            
         switch( myTyp )
         {
            //Close opened long positions
            case OP_BUY      :result = OrderClose(myTkt, myLot, myBid, Slippage, Red);
            break;
      
         
         }
    
         if(result == false)
         {
            Alert("Order " , myTkt , " failed to close. Error:" , GetLastError() );
            Print("Order " , myTkt , " failed to close. Error:" , GetLastError() );
            Sleep(3000);
         }  
         else return(result);
         Sleep(1000);
      }

   } //for
  
} // closebuy


void logwrite (string filename, string mydata)
  {
   int myhandle;
   myhandle=FileOpen(Symbol()+"_"+filename, FILE_CSV|FILE_WRITE|FILE_READ, ";");
   if(myhandle>0)
     {
      FileSeek(myhandle,0,SEEK_END);
      FileWrite(myhandle, mydata+" "+CurTime());
      FileClose(myhandle);
     }
  } 


 
   
 
   
  

