//+------------------------------------------------------------------+
//|                                                   Basket EA.mq4  |
//|                                  Copyright © 2010, Xin Li        |
//|                              http://www.ligonier.org             |
//| http://www.forexfactory.com/showthread.php?p=6143205#post6143205 |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2010, XIN LI"
#property link      " http://www.ligonier.org"
#property strict
//
#include <WinUser32.mqh>
#include <stdlib.mqh>
#define  NL    "\n"
/*
void DisplayUserFeedback()
void CalculateHighestLowestTrades()
void LookForTradingOpportunities()
   double CalculateTakeProfit(string symbol, int type)
   double CalculateStopLoss(string symbol, int type)

void CalculateNoOfTrades()
bool O_R_CheckForHistory(int ticket) //Cheers Matt
void CalculateBasketUpl()
bool DoesTradeExist(string symbol)
bool SendSingleTrade(string symbol, int type, string comment, double lotsize, double price, double stop, double take)
void CloseAllTrades()
void CountOpenTrades()
double CalculateVirtualTradeProfit(string symbol)
void CalculateDailyResult()
*/
//
extern double  Lot=0.1;
extern int     MagicNumber=3654;
extern string  TradeComment="Basket";
extern double  TakeProfit=0;
extern double  StopLoss=0;
extern bool    CriminalIsECN=false;
//
extern string  basket=" Basket Setting";
//
extern int     NumOfPairs = 14;
extern bool    BuyNow=false;
extern bool    SellNow=false;
extern bool    AutoTrading=false;
string         Pair_suffix;
//string         shortname;
extern string  bc="----Basket closure inputs per pair----";
extern double  CashTakeProfitPerPair=25;
extern bool    CloseBasket=false;
//
string         TradePair[14];
double         Factor,multiplier[14];
int            j,StartBar, Digit;
string         Currency;
static int     ExtHandle=-1;
static int     tf = 0;
int            MN=0;
//
bool HASellNow = false;
bool HABuyNow = false;
bool VQSellNow = false;
bool VQBuyNow = false;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
double         Upl;
//
string         ScreenMessage;
bool           StopTrading = false;
string         InputString;//For pair extraction
datetime       OldTradingTime;
//
//Running total of trades
int            LossTrades, WinTrades;
double         OverallProfit;
//
//Matt's O-R stuff
int 	         O_R_Setting_max_retries 	= 10;
double 	      O_R_Setting_sleep_time 		= 4.0; /* seconds */
double 	      O_R_Setting_sleep_max 		= 15.0; /* seconds */
//
//Order closure stuff
int            OpenTrades;
double         upl;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   //----
   int retval;
   Get_Trade_Pairs();
   //
   if (TradeComment == "") TradeComment = " ";
   //
   //Reset CriminIsECN if crim is IBFX and the punter does not know or, like me, keeps on forgetting
   string name = TerminalCompany();
   int ispart = StringFind(name, "IBFX", 0);
   if (ispart < 0) ispart = StringFind(name, "Interbank FX", 0);
   if (ispart > -1) CriminalIsECN = true;   
   //OldTradingTime = iTime(NULL, TradingTimeFrame, 0);
   //Confirm Trades
   if (BuyNow)
   {
      retval = MessageBox(Symbol() + ": do you wish to Open buy Basket?", "Question", MB_YESNO|MB_ICONQUESTION);
      if (retval == IDNO) BuyNow = false;
      else BuyNow = true;   
   }  //if (UseSafetyFeature)
   if (SellNow)
   {
      retval = MessageBox(Symbol() + ": do you wish to Open Sell Basket?", "Question", MB_YESNO|MB_ICONQUESTION);
      if (retval == IDNO) SellNow = false;
      else SellNow = true;   
   }  //if (UseSafetyFeature)
   //
   if (CloseBasket)
   {
      retval = MessageBox(Symbol() + ": do you wish to Close Basket?", "Question", MB_YESNO|MB_ICONQUESTION);
      if (retval == IDNO) CloseBasket = false;
      else CloseBasket = true;   
   }  //if (UseSafetyFeature)
   //
   DisplayUserFeedback();
   //----
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   //----
   
   //----
}
//
void DisplayUserFeedback(void)
{
   string Gap = "                                 ";
   //
   ScreenMessage = "";
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
   ScreenMessage = StringConcatenate(ScreenMessage, Gap, TimeToStr(TimeCurrent(), TIME_DATE|TIME_MINUTES|TIME_SECONDS), NL );
   if (!IsDemo() )
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL, "********************THIS EA IS FOR DEMO ONLY. IT IS STILL UNDER DEVELOPMENT.********************", NL, NL);
      return;
   }
   //  ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Trade pairs: ", TradePairs, NL);
   if (TakeProfit > 0)
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Take profit: ", TakeProfit, " pips", NL);
   }
   if (StopLoss > 0)
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Stop loss: ", StopLoss, " pips", NL);
   }
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Magic number: ", MagicNumber);
   ScreenMessage = StringConcatenate(ScreenMessage, ":  Trade comment: ", TradeComment, NL);
   if (CriminalIsECN)
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "CriminalIsECN = true", NL);
   }  else
   {
      ScreenMessage = StringConcatenate(ScreenMessage,Gap, "CriminalIsECN = false", NL);
   }
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "Open trades = ", OpenTrades, 
                                     ": Upl = ", DoubleToStr(upl, 2), 
                                     ": CashTakeProfit = ", DoubleToStr(CashTakeProfitPerPair, 2),
                                     NL);
   ScreenMessage = StringConcatenate(ScreenMessage, Gap, "Results today. Wins: ", WinTrades, ": Losses ", LossTrades,
                                     ": P/L ", DoubleToStr(OverallProfit, 2), NL);
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, NL);
   ScreenMessage = StringConcatenate(ScreenMessage, Gap, "BuyNow: ", BuyNow, ": SellNow ", SellNow,
                                     ": CloseBasket ", CloseBasket, NL);
   // }//if (ShowAllOnChart)
   ScreenMessage = StringConcatenate(ScreenMessage,Gap, "AutoTrading: ", AutoTrading,NL);
   //
   Comment(ScreenMessage);
   //
}  //void DisplayUserFeedback()
//=============================================================================
//                           O_R_CheckForHistory()
//
//  This function is to work around a very annoying and dangerous bug in MT4:
//      immediately after you send a trade, the trade may NOT show up in the
//      order history, even though it exists according to ticket number.
//      As a result, EA's which count history to check for trade entries
//      may give many multiple entries, possibly blowing your account!
//
//  This function will take a ticket number and loop until
//  it is seen in the history.
//
//  RETURN VALUE:
//     TRUE if successful, FALSE otherwise
//
//
//  FEATURES:
//     * Re-trying under some error conditions, sleeping a random
//       time defined by an exponential probability distribution.
//
//     * Displays various error messages on the log for debugging.
//
//  ORIGINAL AUTHOR AND DATE:
//     Matt Kennel, 2010
//
//=============================================================================
bool O_R_CheckForHistory(int ticket)
{
   //My thanks to Matt for this code. He also has the undying gratitude of all users of my trading robots
   int lastTicket = OrderTicket();
   //
   int cnt = 0;
   int c;
   int err = GetLastError(); // so we clear the global variable.
   err = 0;
   bool exit_loop = false;
   bool success=false;
   //
   while (!exit_loop)
   {
      /* loop through open trades */
      int total=OrdersTotal();
      for( c = 0; c < total; c++ )
      {
         if(OrderSelect(c,SELECT_BY_POS,MODE_TRADES) == true)
         {
            if (OrderTicket() == ticket)
            {
               success   = true;
               exit_loop = true;
            }
         }
      }
      if (cnt > 3)
      {
         /* look through history too, as order may have opened and closed immediately */
         total=OrdersHistoryTotal();
         for(c = 0; c < total; c++)
         {
            if(OrderSelect(c,SELECT_BY_POS,MODE_HISTORY) == true)
            {
               if (OrderTicket() == ticket)
               {
                  success   = true;
                  exit_loop = true;
               }
            }
         }
      }
      cnt = cnt+1;
      if (cnt > O_R_Setting_max_retries)
      {
         exit_loop = true;
      }
      if (!(success || exit_loop))
      {
         Print( "Did not find #"+IntegerToString(ticket)+" in history, sleeping, then doing retry #"+IntegerToString(cnt) );
         O_R_Sleep(O_R_Setting_sleep_time, O_R_Setting_sleep_max);
      }
   }  // (!exit_loop)
   // Select back the prior ticket num in case caller was using it.
   if (lastTicket >= 0)
   {
      if ( !OrderSelect(lastTicket, SELECT_BY_TICKET, MODE_TRADES) )
         Print("Never found #"+IntegerToString(ticket)+" in Trades! crap!");
   }
   if (!success)
   {
      Print("Never found #"+IntegerToString(ticket)+" in history! crap!");
   }
   return(success);
}  //End bool O_R_CheckForHistory(int ticket)
//=============================================================================
//                              O_R_Sleep()
//
//  This sleeps a random amount of time defined by an exponential
//  probability distribution. The mean time, in Seconds is given
//  in 'mean_time'.
//  This returns immediately if we are backtesting
//  and does not sleep.
//
//=============================================================================
void O_R_Sleep(double mean_time, double max_time)
{
   if (IsTesting()) {
      return;   // return immediately if backtesting.
   }
   //
   double p = (MathRand()+1) / 32768.0;
   double t = -MathLog(p)*mean_time;
   t = MathMin(t,max_time);
   int ms = (int) t*1000;
   if (ms < 10)
   {
      ms=10;
   }
   Sleep(ms);
}//End void O_R_Sleep(double mean_time, double max_time)
/*
void CalculateBasketUpl()
{
   Upl = 0;
   for (int cc = OrdersTotal() - 1; cc >= 0 ; cc--)
   {
      if (!OrderSelect(cc,SELECT_BY_POS))
         continue;
      if (OrderMagicNumber()==MagicNumber)      
      {
         Upl+= (OrderProfit() + OrderSwap() + OrderCommission() );
      }//if (OrderMagicNumber()==MagicNumber && OrderSymbol() == Symbol() )      
   }//for (int cc = OrdersTotal() - 1; cc >= 0 ; cc--)
}//End void CalculateBasketUpl();
*/
bool DoesTradeExist(string symbol, int type)
{
   if (OrdersTotal() == 0)
      return(false);
   for (int cc = OrdersTotal() - 1; cc >= 0 ; cc--)
   {
      if (!OrderSelect(cc,SELECT_BY_POS))
         continue;
      if (OrderMagicNumber()==MagicNumber && OrderSymbol() == symbol && OrderType()==type )      
      {
         return(true);         
      }//if (OrderMagicNumber()==MagicNumber && OrderSymbol() == Symbol() )      
   }//for (int cc = OrdersTotal() - 1; cc >= 0 ; cc--)
   return(false);
}//End bool DoesTradeExist()
//
bool SendSingleTrade(string symbol, int type, string comment, double lotsize, double price, double stop, double take)
{
   //Find order opening price. Might be a good idea to move tp/sl calculation here as well
   int ticket = 0, err = 0;
   RefreshRates();
   if (type == OP_BUY)
   {
      price = MarketInfo(symbol, MODE_ASK);
   }//if(type == OP_BUY)
   //
   if (type == OP_SELL)
   {
      price = MarketInfo(symbol, MODE_BID);
   }//if(type == OP_BUY)
   //
   if (!CriminalIsECN)
   {
      ticket = OrderSend(symbol,type, lotsize, price, 0, stop, take, comment, MagicNumber, 0, CLR_NONE);
   }
   //Is a 2 stage criminal
   if (CriminalIsECN)
   {
      bool result;
      ticket = OrderSend(symbol,type, lotsize, price, 0, 0, 0, comment, MagicNumber, 0, 0);
      if (ticket > 0)
      {
	     if (take > 0 && stop > 0)
        {
           while(IsTradeContextBusy())
           { Sleep(100);   }
           result = OrderModify(ticket, OrderOpenPrice(), stop, take, OrderExpiration(), CLR_NONE);
           if (!result)
           {
               err=GetLastError();
               Print(symbol, " SL/TP  order modify failed with error(",err,"): ",ErrorDescription(err));               
           }   //if (!result)			  
        }   //if (take > 0 && stop > 0)
        //
	     if (take != 0 && stop == 0)
        {
           while(IsTradeContextBusy())
           { Sleep(100);   }
           result = OrderModify(ticket, OrderOpenPrice(), OrderStopLoss(), take, OrderExpiration(), CLR_NONE);
           if (!result)
           {
               err=GetLastError();
               Print(symbol, " SL  order modify failed with error(",err,"): ",ErrorDescription(err));               
           }   //if (!result)			  
        }//if (take == 0 && stop != 0)
        //
        if (take == 0 && stop != 0)
        {
           while(IsTradeContextBusy())
           {   Sleep(100); }
           result = OrderModify(ticket, OrderOpenPrice(), stop, OrderTakeProfit(), OrderExpiration(), CLR_NONE);
           if (!result)
           {
               err=GetLastError();
               Print(symbol, " SL  order modify failed with error(",err,"): ",ErrorDescription(err));               
           }//if (!result)			  
        }//if (take == 0 && stop != 0)
      }//if (ticket > 0)
   }//if (CriminalIsECN)
   //Error trapping for both
   if (ticket < 0)
   {
      string stype;
      if (type == OP_BUY) stype = "OP_BUY";
      if (type == OP_SELL) stype = "OP_SELL";
      if (type == OP_BUYLIMIT) stype = "OP_BUYLIMIT";
      if (type == OP_SELLLIMIT) stype = "OP_SELLLIMIT";
      if (type == OP_BUYSTOP) stype = "OP_BUYSTOP";
      if (type == OP_SELLSTOP) stype = "OP_SELLSTOP";
      Alert(WindowExpertName(), " ", symbol, " ", stype," order send failed with error(",err,"): ",ErrorDescription(err));
      Print(WindowExpertName(), " ", symbol, " ", stype," order send failed with error(",err,"): ",ErrorDescription(err));
      return(false);
   }//if (ticket < 0)  
   //Make sure the trade has appeared in the platform's history to avoid duplicate trades
   if (!O_R_CheckForHistory(ticket) )
      return(false); 
   //Got this far, so trade send succeeded
   return(true);
   //
}//End bool SendSingleTrade(int type, string comment, double lotsize, double price, double stop, double take)
//
double CalculateTakeProfit(string symbol, int type)
{
   if (TakeProfit == 0) return(0);
   //
   RefreshRates();
   double ask = MarketInfo(symbol, MODE_ASK);
   double bid = MarketInfo(symbol, MODE_BID);
   int digits = (int) MarketInfo(symbol, MODE_DIGITS);
   double point = MarketInfo(symbol, MODE_POINT);
   double take = TakeProfit;
   double TP = TakeProfit;
   //
   //Convert tp/sl for x digit crims
   int lmultiplier = 1;
   if(digits == 2 || digits == 4)
      lmultiplier = 1;
   if(digits == 3 || digits == 5)
      lmultiplier = 10;
   if(digits == 6)
      lmultiplier = 100;   
   if(digits == 7)
      lmultiplier = 1000;   
   //
   TP*= lmultiplier;
   //
   if (type == OP_BUY)
   {
      take = NormalizeDouble(ask + (TP * point), digits);
   }//if (type = OP_BUY)
   //
   if (type == OP_SELL)
   {
      take = NormalizeDouble(bid - (TP * point), digits);
   }//if (type == OP_SELL)
   //
   return(take);
   //
}  //End double CalculateTakeProfit(MostProfitablePair, MostProfitableType)
//
double CalculateStopLoss(string symbol, int type)
{
   if (StopLoss == 0)
      return(0);
   RefreshRates();
   //
   double ask = MarketInfo(symbol, MODE_ASK);
   double bid = MarketInfo(symbol, MODE_BID);
   int digits = (int) MarketInfo(symbol, MODE_DIGITS);
   double point = MarketInfo(symbol, MODE_POINT);
   double stop = StopLoss;
   double SL = StopLoss;
   //
   //Convert tp/sl for x digit crims
   int lmultiplier = 1;
   if(digits == 2 || digits == 4)
      lmultiplier = 1;
   if(digits == 3 || digits == 5)
      lmultiplier = 10;
   if(digits == 6)
      lmultiplier = 100;   
   if(digits == 7)
      lmultiplier = 1000;   
   //
   SL*= lmultiplier;
   //
   if (type == OP_BUY)
   {
      stop = NormalizeDouble(ask - (SL * point), digits);
   }//if (type = OP_BUY)
   //
   if (type == OP_SELL)
   {
      stop = NormalizeDouble(bid + (SL * point), digits);
   }//if (type == OP_SELL)
   //
   return(stop);
   //
}//End double CalculateStopLoss(string symbol, int type)
//==============================
void CloseAllTrades(void)
{
   //
   CloseBasket = false;
   //
   for (int cc = OrdersTotal() - 1; cc >= 0; cc--)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) )
         continue;
      if (OrderMagicNumber() != MagicNumber)
         continue;
      while(IsTradeContextBusy() )
      { Sleep(100);  }
      //
      bool result = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 5000, CLR_NONE);
      if (!result)
         CloseBasket = true;  // try again
      Sleep(100);
   }//for (int cc = OrdersTotal() - 1; cc >= 0, cc--)
}//bool CloseAllTrades()
//
void CountOpenTrades(void)
{
   upl = 0;
   OpenTrades = 0;
   if (OrdersTotal() == 0)
      return;
   for (int cc = 0; cc <= OrdersTotal() - 1; cc++)
   {
      if (!OrderSelect(cc, SELECT_BY_POS) )
         continue;
      if (OrderMagicNumber() == MagicNumber)
      {
         upl+= (OrderProfit() + OrderSwap() + OrderCommission());
         OpenTrades++;
      }//if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
   }//for (int cc = 0; cc < OrdersTotal() - 1; cc++)
}//End void CountOpenTrades();
//
void CalculateDailyResult( void )
{
   //Calculate the no of winners and losers from today's trading. These are held in the history tab.
   LossTrades = 0;
   WinTrades = 0;
   OverallProfit = 0;
   for (int cc = 0; cc <= OrdersHistoryTotal(); cc++)
   {
      if (!OrderSelect(cc, SELECT_BY_POS, MODE_HISTORY) )
         continue;
      if (OrderMagicNumber() != MagicNumber)
         continue;
      //
      OverallProfit+= (OrderProfit() + OrderSwap() + OrderCommission() );
      if (OrderProfit() > 0)
         WinTrades++;
      if (OrderProfit() < 0)
         LossTrades++;
   }//for (int cc = 0; cc <= tot -1; cc++)
}//End void CalculateDailyResult()
//+------------------------------------------------------------------+
//| expert Tick Event Handler                                        |
//+------------------------------------------------------------------+
void OnTick()
{
   if (OrdersTotal() == 0)
      CloseBasket = false;
   //
   if (CloseBasket)
   {
      CloseAllTrades();
      SellNow=false;
      BuyNow=false;
      if (CloseBasket)
         return;
   }//if (ForceClose)
   //Basket closure opps
   CountOpenTrades();
   if (upl >= CashTakeProfitPerPair*NumOfPairs)
   {
      CloseAllTrades();
      if (CloseBasket) 
      {
         CloseAllTrades();
         SellNow=false;
         BuyNow=false;
         return;
      }//if (ForceClose)    
      SellNow=false;
      BuyNow=false;      
   }//if (upl >= CashTakeProfit)
   //The next routine takes care of all trade closure possibilities
   int kj, type;
   double take, stop, price;
   if( !AutoTrading ) 
   {
      if(BuyNow ) // BuyNow
      {
         for( kj=0; kj<NumOfPairs; kj++)
         {
            if(DoesTradeExist(TradePair[kj], OP_SELL) && (TradePair[kj]!="USDCHF" || TradePair[kj]!="GBPCHF"))
            {
               CloseAllTrades();
            }
            type=OP_BUY;
            if(TradePair[kj]=="USDCHF" || TradePair[kj]=="GBPCHF")
            {
               type=OP_SELL;
            }
            if(!DoesTradeExist(TradePair[kj], type))
            {
               take=CalculateTakeProfit(TradePair[kj], type);
               stop=CalculateStopLoss(TradePair[kj], type);
               RefreshRates();
               price = MarketInfo(TradePair[kj], MODE_ASK);
               if(type==OP_SELL)
               {
                  price =  MarketInfo(TradePair[kj], MODE_BID);
               }
               SendSingleTrade(TradePair[kj], type, "Basket Order", Lot,  price, stop, take);
            }
         } // for(int kj=0;kj<NumOfPairs;kj++)
         BuyNow=false;
      } //BuyNow 
      if(SellNow) //SellNow
      {
         for( kj=0;kj<NumOfPairs;kj++)
         {
            if(DoesTradeExist(TradePair[kj], OP_BUY) && (TradePair[kj]!="USDCHF" || TradePair[kj]!="GBPCHF"))
            {
               CloseAllTrades();
            }
            type=OP_SELL;
            if(TradePair[kj]=="USDCHF" || TradePair[kj]=="GBPCHF")
            {
               type=OP_BUY;
            }
            if(!DoesTradeExist(TradePair[kj], type))
            {
               take=CalculateTakeProfit(TradePair[kj], type);
               stop=CalculateStopLoss(TradePair[kj], type);
               RefreshRates();
               price = MarketInfo(TradePair[kj], MODE_BID);
               if(type==OP_BUY)
               {
                  price =  MarketInfo(TradePair[kj], MODE_ASK);
               }
               SendSingleTrade(TradePair[kj], type, "Basket Order", Lot,  price, stop, take);
            }
         } //  for( kj=0;kj<NumOfPairs;kj++)
         SellNow=false;
      }
   }//  if(!AutoTrading)
   // 
   if(AutoTrading)
   {
      static datetime tLast = 0;
      if ( tLast == Time[0] )
         return;
      tLast = Time[0];
      double HA00=iCustom(NULL, 0, "Heiken_Ashi_Smoothed",2,15,2,15,0,1);
      double HA10=iCustom(NULL, 0, "Heiken_Ashi_Smoothed",2,15,2,15,1,1);
      double HA20=iCustom(NULL, 0, "Heiken_Ashi_Smoothed",2,15,2,15,2,1);
      double HA30=iCustom(NULL, 0, "Heiken_Ashi_Smoothed",2,15,2,15,3,1);
      double HA01=iCustom(NULL, 0, "Heiken_Ashi_Smoothed",2,15,2,15,0,2);
      double HA11=iCustom(NULL, 0, "Heiken_Ashi_Smoothed",2,15,2,15,1,2);
      double HA21=iCustom(NULL, 0, "Heiken_Ashi_Smoothed",2,15,2,15,2,2);
      double HA31=iCustom(NULL, 0, "Heiken_Ashi_Smoothed",2,15,2,15,3,2);
      double VQz20=iCustom(NULL, 0, "VQzz2",60,6,2,2,5,false,3,1);
      //  if((HA00 > HA10 && HA20 > HA30) && (HA01 < HA11 || HA21 < HA31) && VQz20 < 0 ) SellNow=true;
      //  if((HA00 < HA10 && HA20 < HA30) && (HA01 > HA11 || HA21 > HA31) && VQz20 > 0 ) BuyNow=true;
      if((HA00 > HA10 && HA20 > HA30) && (HA01 < HA11 || HA21 < HA31)  )
         HASellNow=true;
      if((HA00 < HA10 && HA20 < HA30) && (HA01 > HA11 || HA21 > HA31)  )
         HABuyNow=true;
      if(VQz20 < 0 )
         VQSellNow = true;
      if(VQz20 > 0 )
         VQBuyNow = true;
      if (VQSellNow && HASellNow)
         SellNow = true;
      if (VQBuyNow && HABuyNow )
         BuyNow = true;
      if (BuyNow ) // BuyNow
      {
         for( kj=0;kj<NumOfPairs;kj++)
         {
            if(DoesTradeExist(TradePair[kj], OP_SELL) && (TradePair[kj]!="USDCHF" || TradePair[kj]!="GBPCHF"))
            {
               CloseAllTrades();
            }
            type=OP_BUY;
            if(TradePair[kj]=="USDCHF" || TradePair[kj]=="GBPCHF")
            {
               type=OP_SELL;
            }
            if(!DoesTradeExist(TradePair[kj], type))
            {
               take=CalculateTakeProfit(TradePair[kj], type);
               stop=CalculateStopLoss(TradePair[kj], type);
               RefreshRates();
               price = MarketInfo(TradePair[kj], MODE_ASK);
               if(type==OP_SELL)
               {
                  price =  MarketInfo(TradePair[kj], MODE_BID);
               }
               SendSingleTrade(TradePair[kj], type, "Basket Order", Lot,  price, stop, take);
            }
         } // for(int kj=0;kj<NumOfPairs;kj++)
         BuyNow=false;
         VQBuyNow = false;
         HABuyNow = false;
      } //BuyNow 
      if(SellNow) //SellNow
      {
         for( kj=0;kj<NumOfPairs;kj++)
         {
            if(DoesTradeExist(TradePair[kj], OP_BUY) && (TradePair[kj]!="USDCHF" || TradePair[kj]!="GBPCHF"))
            {
               CloseAllTrades();
            }
            type=OP_SELL;
            if(TradePair[kj]=="USDCHF" || TradePair[kj]=="GBPCHF")
            {
               type=OP_BUY;
            }
            if(!DoesTradeExist(TradePair[kj], type))
            {
               take=CalculateTakeProfit(TradePair[kj], type);
               stop=CalculateStopLoss(TradePair[kj], type);
               RefreshRates();
               price = MarketInfo(TradePair[kj], MODE_BID);
               if(type==OP_BUY)
               {
                  price =  MarketInfo(TradePair[kj], MODE_ASK);
               }
               SendSingleTrade(TradePair[kj], type, "Basket Order", Lot,  price, stop, take);
            }
         } //  for( kj=0;kj<NumOfPairs;kj++)
         SellNow=false;
         HASellNow = false;
         VQSellNow = false;
      }
   }// if(AutoTrading) {
   //Daily results so far - they work on what in in the history tab, so users need warning that
   //what they see displayed on screen depends on that.   
   //Code courtesy of TIG yet again. Thanks, George.
   static int OldHistoryTotal;
   if (OrdersHistoryTotal() != OldHistoryTotal)
   {
      CalculateDailyResult();//Does no harm to have a recalc from time to time
      OldHistoryTotal = OrdersHistoryTotal();
   }//if (OrdersHistoryTotal() != OldHistoryTotal)
   /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
   DisplayUserFeedback();
   Sleep(500);
   //  }//while (x == 0)
}//End int start()
//+------------------------------------------------------------------+
int Get_Trade_Pairs(void)
{
   switch (NumOfPairs)
   {
      case 1:  TradePair[0] = "GBPJPY" + Pair_suffix;
               Factor=0.0;
               break;
      case 2:  TradePair[0] = "GBPUSD" + Pair_suffix;
               TradePair[1] = "EURUSD" + Pair_suffix;
               Factor=200.0;
               break;
      case 4:  TradePair[0] = "GBPUSD" + Pair_suffix;
               TradePair[1] = "EURJPY" + Pair_suffix;
               TradePair[2] = "EURUSD" + Pair_suffix;
               TradePair[3] = "GBPJPY" + Pair_suffix;
               Factor=400.0;
               break;
      case 6:  TradePair[0] = "GBPUSD" + Pair_suffix;
               TradePair[1] = "EURJPY" + Pair_suffix;
               TradePair[2] = "AUDUSD" + Pair_suffix;
               TradePair[3] = "EURUSD" + Pair_suffix;
               TradePair[4] = "GBPJPY" + Pair_suffix;
               TradePair[5] = "NZDUSD" + Pair_suffix;
               Factor=600.0;
               break;
      case 8:  TradePair[0] = "GBPUSD" + Pair_suffix;
               TradePair[1] = "EURJPY" + Pair_suffix;
               TradePair[2] = "AUDUSD" + Pair_suffix;
               TradePair[3] = "NZDJPY" + Pair_suffix;
               TradePair[4] = "EURUSD" + Pair_suffix;
               TradePair[5] = "GBPJPY" + Pair_suffix;
               TradePair[6] = "NZDUSD" + Pair_suffix;
               TradePair[7] = "AUDJPY" + Pair_suffix;
               Factor=800.0;
               break;
      case 10: TradePair[0] = "GBPUSD" + Pair_suffix;
               TradePair[1] = "EURGBP" + Pair_suffix;
               TradePair[2] = "GBPJPY" + Pair_suffix;
               TradePair[3] = "CADJPY" + Pair_suffix;
               TradePair[4] = "NZDUSD" + Pair_suffix;
               TradePair[5] = "EURUSD" + Pair_suffix;
               TradePair[6] = "USDJPY" + Pair_suffix;
               TradePair[7] = "AUDUSD" + Pair_suffix;
               TradePair[8] = "NZDJPY" + Pair_suffix;
               TradePair[9] = "GBPCHF" + Pair_suffix;
               Factor=1000.0;
               break;
      case 12: TradePair[0] = "GBPUSD" + Pair_suffix;
               TradePair[1] = "EURGBP" + Pair_suffix;
               TradePair[2] = "GBPJPY" + Pair_suffix;
               TradePair[3] = "CADJPY" + Pair_suffix;
               TradePair[4] = "NZDUSD" + Pair_suffix;
               TradePair[5] = "AUDJPY" + Pair_suffix;
               TradePair[6] = "EURUSD" + Pair_suffix;
               TradePair[7] = "USDJPY" + Pair_suffix;
               TradePair[8] = "AUDUSD" + Pair_suffix;
               TradePair[9] = "NZDJPY" + Pair_suffix;
               TradePair[10] = "GBPCHF" + Pair_suffix;
               TradePair[11] = "CHFJPY" + Pair_suffix;
               Factor=1200.0;
               break;
      case 14: TradePair[0] = "GBPUSD" + Pair_suffix;
               TradePair[1] = "EURGBP" + Pair_suffix;
               TradePair[2] = "GBPJPY" + Pair_suffix;
               TradePair[3] = "USDCHF" + Pair_suffix;
               TradePair[4] = "NZDUSD" + Pair_suffix;
               TradePair[5] = "AUDJPY" + Pair_suffix;
               TradePair[6] = "EURJPY" + Pair_suffix;
               TradePair[7] = "EURUSD" + Pair_suffix;
               TradePair[8] = "USDJPY" + Pair_suffix;
               TradePair[9] = "AUDUSD" + Pair_suffix;
               TradePair[10] = "NZDJPY" + Pair_suffix;
               TradePair[11] = "GBPCHF" + Pair_suffix;
               TradePair[12] = "CHFJPY" + Pair_suffix;
               TradePair[13] = "EURCHF" + Pair_suffix;
               Factor=1400.0;
               break;
      default: break;
   }
   Currency=Currency+Pair_suffix;
   //----
   return(0);
}
//