Strategy_Xpert_pack_0.5.2





//+------------------------------------------------------------------+
//|                                               Strategy Xpert.mq4 |
//|                      Copyright © 2009, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"

//#include "libraries/trade.mq4"

extern int        Magic             =  12345;

extern string     TradeLots_        =  "Åñëè 0 èñïîëüçóåòñÿ àâòîëîò, åñëè íå 0 èñïîëüçóåòñÿ çàäàííûé ôèêñèðîâàííûé";
extern double     TradeLots         =  0;
// risk for automatic lots size counting
extern string     RiskPercentage_   =  "Ðèñê â ïðîöåíòàõ (2 ýòî äâà ïðîöåíòà!, 0.1 ýòî äåñÿòàÿ ïðîöåíòà!)";
extern double     RiskPercentage    =  0;

// maximum acceptable slippage for the price
extern int        Slippage          =  30;

extern string     TimesToRepeat_    =  "Äëÿ òåñòåðà íåâàæíî. Ñêîëüêî ðàç ïîâòîðÿòü ïîïûòêè ïîñòàâèòü îðäåð";
// maximum loop count for orders opening if failed due to requoting
extern int        TimesToRepeat     =  3;

/// \brief Equal to ternar operator 
/// needed = Condition ? IfTrue : IfFalse;
/// \param IfTrue
/// \param IfFalse
/// \return matching value from parameters
double DoubleIf(bool Condition, double IfTrue, double IfFalse)
{
   if (Condition) return (IfTrue);
   else           return (IfFalse);
}

void WaitForContext()
{
   while (IsTradeContextBusy())
   {
      Sleep(100);
   }
}

void OpenBuy(int MN, int Target, int Loss, double Lot)
{
   int count = 0;
   while (count < TimesToRepeat)
   {
      WaitForContext();
      RefreshRates();
   
      double TP = DoubleIf(Target > 0, Ask + Target*Point, 0);
      double SL = DoubleIf(Loss > 0, Ask - Loss*Point, 0);
   
      double LotsToBid = DoubleIf(Lot == 0, GetLotsToBid(RiskPercentage), Lot);
   
      int res = OrderSend(Symbol(), OP_BUY, LotsToBid, Ask, Slippage, SL, TP, NULL, MN, 0, Blue);
      
      if (res > 0) return;
      
      count++;
   }
}

void OpenSell(int MN, int Target, int Loss, double Lot)
{
   int count = 0;
   while (count < TimesToRepeat)
   {
      WaitForContext();
      RefreshRates();
   
      double TP = DoubleIf(Target > 0, Bid - Target*Point, 0);
      double SL = DoubleIf(Loss > 0, Bid + Loss*Point, 0);
   
      double LotsToBid = DoubleIf(Lot == 0, GetLotsToBid(RiskPercentage), Lot);
   
      int res = OrderSend(Symbol(), OP_SELL, LotsToBid, Bid, Slippage, SL, TP, NULL, MN, 0, Red);
      
      if (res > 0) return;

      count++;
   }
}

void CloseSells(int MagicNumber, int Slippage)
{
   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      // already closed
      if(OrderSelect(i, SELECT_BY_POS) == false) continue;
      // not current symbol
      if(OrderSymbol() != Symbol()) continue;
      // order was opened in another way
      if(OrderMagicNumber() != MagicNumber) continue;
      
      if(OrderType() == OP_SELL)
      {
         int count = 0;
         while (count < TimesToRepeat)
         {
            WaitForContext();
            
            RefreshRates();
            if (OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Red))
            {
               break;
            }
            count++;
         }
      }
   }
}

void CloseBuys(int MagicNumber, int Slippage)
{
   for(int i = OrdersTotal(); i >= 0; i--)
   {
      // already closed
      if(OrderSelect(i, SELECT_BY_POS) == false) continue;
      // not current symbol
      if(OrderSymbol() != Symbol()) continue;
      // order was opened in another way
      if(OrderMagicNumber() != MagicNumber) continue;
      
      if(OrderType() == OP_BUY)
      {
         int count = 0;
         while (count < TimesToRepeat)
         {
            WaitForContext();
            
            RefreshRates();
            if (OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Blue))
            {
               break;
            }
            count++;
         }
      }
   }
}

bool GetActiveOrders(int MagicNumber = -1)
{
   for(int i = 0; i < OrdersTotal(); i++)
   {
      // already closed
      if(OrderSelect(i, SELECT_BY_POS) == false) continue;
      // not current symbol
      if(OrderSymbol() != Symbol()) continue;
      // order was opened in another way
      if(OrderMagicNumber() != MagicNumber && MagicNumber != -1) continue;
      
      if(OrderType() == OP_SELL || OrderType() == OP_BUY)
      {
         return (true);
      }
   }
   
   return (false);
}

int GetOrdersCount(int MagicNumber = -1, int Type = -1, string symb = "")
{
   int count = 0;
   
   for(int i = 0; i < OrdersTotal(); i++)
   {
      // already closed
      if(OrderSelect(i, SELECT_BY_POS) == false) continue;
      // not current symbol
      if(OrderSymbol() != Symbol() && symb == "") continue;
      // not specified symbol
      if(OrderSymbol() != symb && symb != "" && symb != "all") continue;
      // order was opened in another way
      if(OrderMagicNumber() != MagicNumber && MagicNumber != -1) continue;
      
      if(OrderType() == Type || Type == -1)
      {
         count++;
      }
   }
   
   return (count);
}

double GetLotsToBid(double RiskPercentage)
{
   double margin  = MarketInfo(Symbol(), MODE_MARGINREQUIRED);
   double minLot  = MarketInfo(Symbol(), MODE_MINLOT);
   double maxLot  = MarketInfo(Symbol(), MODE_MAXLOT);
   double step    = MarketInfo(Symbol(), MODE_LOTSTEP);
   double account = AccountFreeMargin();
   
   double percentage = account*RiskPercentage/100;
   
   double lots = MathRound(percentage/margin/step)*step;
   
   if(lots < minLot)
   {
      lots = minLot;
   }
   
   if(lots > maxLot)
   {
      lots = maxLot;
   }

   return (lots);
}

int GetStopLevel()
{
   return (MathMax(MathRound(MarketInfo(Symbol(), MODE_STOPLEVEL)), 3));
}

///===========================================================================================
// end trade.mq4
///===========================================================================================

// Externs
extern string OpenDesc1          = "Óñëîâèÿ îòêðûòèÿ -- ñâÿçàíû ìåæäó ñîáîé îïåðàöèåé || (OR)";
extern string OpenDesc2          = "Êàæäîå óëîâèå ÿâëÿåòñÿ ñîñòàâíûì è ñîñòîèò èç ýëåìåíòàðíûõ óñëîâèé (íèæå),";
extern string OpenDesc3          = "ñâÿçàííûõ ìåæäó ñîáîé îïåðàöèåé && (AND)";

extern string OpenCondition1     = "";
extern string OpenCondition2     = "";
extern string OpenCondition3     = "";

extern string CloseDesc1         = "Óñëîâèÿ çàêðûòèÿ -- ñâÿçàíû ìåæäó ñîáîé îïåðàöèåé || (OR)";
extern string CloseDesc2         = "Êàæäîå óëîâèå ÿâëÿåòñÿ ñîñòàâíûì è ñîñòîèò èç ýëåìåíòàðíûõ óñëîâèé (íèæå),";
extern string CloseDesc3         = "ñâÿçàííûõ ìåæäó ñîáîé îïåðàöèåé && (AND)";

extern string CloseCondition1    = "";
extern string CloseCondition2    = "";
extern string CloseCondition3    = "";

extern string OptCondDesc1       = "Òåêóùåå îïòèìèçèðóåìîå óñëîâèå -- îäíîâðåìåííî ìîæåò ";
extern string OptCondDesc2       = "îïòèìèçèðîâàòüñÿ òîëüêî îäíî ñîñòàâíîå óñëîâèå";
extern string OptCondDesc3       = "-1 îïòèìèçàöèÿ îòñóòñòâóåò";
extern string OptCondDesc4       = "0 -- OpenCondition1";
extern string OptCondDesc5       = "1 -- OpenCondition2";
extern string OptCondDesc6       = "2 -- OpenCondition3";
extern string OptCondDesc7       = "3 -- CloseCondition1";
extern string OptCondDesc8       = "4 -- CloseCondition2";
extern string OptCondDesc9       = "5 -- CloseCondition3";

extern int    OptimizingCondition = 0;

extern string MaxCount_          = "Ìàêñèìàëüíîå êîëè÷åñòâî àòîìàðíûõ óñëîâèé â îïòèìèçèðóåìîì óñëîâèè";

extern int    MaxElementsCount   = 5;

extern string MaxOrders_         = "Ìàêñèìàëüíîå êîëè÷åñòâî îäíîâðåìåííî îòêðûòûõ îðäåðîâ";
extern string MaxOrders1_        = "Åñëè 0 -- êîëè÷åñòâî íåîãðàíè÷åíî";

extern int    MaxOrders          = 3;

extern string CloseWhenOpen_     = "Åñëè 1 -- ïðè íàëè÷èè ïðîòèâîïîëîæíîãî ñèãíàëà îòêðûòèÿ ñäåëêè çàêðûâàþòñÿ";
extern string CloseWhenOpen1_    = "Åñëè 0 -- ñäåëêè çàêðûâàþòñÿ òîëüêî ïî ñèãíàëó çàêðûòèÿ";

extern int    CloseWhenOpen      = 1;

extern string Condition_1_       = "Close[1] > EMA(EMAPeriod)";
extern int    Condition_1        = 0;

extern string Condition_2_       = "MACD(MACDFast, MACDSlow, MACDSignal) > 0";
extern int    Condition_2        = 0;

extern string Condition_3_       = "MACD(MACDFast, MACDSlow, MACDSignal, 1) > MACD(MACDFast, MACDSlow, MACDSignal, 2)";
extern int    Condition_3        = 0;

extern string Condition_4_       = "CCI(CCIPeriod, 1) > CCILevel";
extern int    Condition_4        = 0;

extern string Condition_5_       = "Open[1] > Open[0]";
extern int    Condition_5        = 0;

extern string Condition_6_       = "RSI(RSIPeriod, 1) > 50 + RSILevel";
extern int    Condition_6        = 0;

extern string Condition_7_       = "BullsPower(BullsBearsPeriod, 1) > 0";
extern int    Condition_7        = 0;

extern string Condition_8_       = "BearsPower(BullsBearsPeriod, 1) > 0";
extern int    Condition_8        = 0;

extern string Condition_9_       = "Close(1) < BBands(BBandsPeriod, BBandsDeviation, 1)";
extern int    Condition_9        = 0;

extern string Condition_10_      = "lower iFractals available";
extern int    Condition_10       = 0;

extern string Condition_11_      = "CCI(CCIPeriod, 1) < -CCILevel";
extern int    Condition_11       = 0;

extern string Condition_12_      = "RSI(RSIPeriod, 1) < 50 - RSILevel";
extern int    Condition_12       = 0;

extern string Condition_13_      = "Close(1) < BBands(BBandsPeriod, BBandsDeviation, 1)";
extern int    Condition_13       = 0;

extern string Condition_14_      = "upper iFractals available";
extern int    Condition_14       = 0;

// here

extern string Secondary_         = "Ïàðàìåòðû âòîðè÷íîé îïòèìèçàöèè";

extern int    EMAPeriod          = 20;

extern int    MACDFast           = 12;
extern int    MACDSlow           = 26;
extern int    MACDSignal         = 9;

extern int    CCIPeriod          = 15;
extern int    CCILevel           = 90;

extern int    RSIPeriod          = 12;
extern int    RSILevel           = 20;

extern int    BullsBearsPeriod   = 13;

extern int    BBandsPeriod       = 20;
extern int    BBandsDeviation    = 2;

extern string Stops_             = "Ñòîïû Target -- TakeProfit â ïóíêòàõ, Loss -- StopLoss";

extern int    Target             = 0;
extern int    Loss               = 100;

extern string FileSettings_      = "Íàñòðîéêè äëÿ ðàáîòû ñ ôàéëàìè";

extern int    SaveToFile         = 0;
extern int    LoadFromFile       = 0;
extern string FileName           = "Strategy.csv";


// Defines
#define CONDITION_COUNT    14

// here

// Globals
string   symbol;
datetime LastTime;
int      ElementsCount;
bool     CriticalError;

bool NeedOpenBuys;
bool NeedOpenSells;
bool NeedCloseBuys;
bool NeedCloseSells;

int OpenCondition1Array[CONDITION_COUNT];
int OpenCondition2Array[CONDITION_COUNT];
int OpenCondition3Array[CONDITION_COUNT];

int CloseCondition1Array[CONDITION_COUNT];
int CloseCondition2Array[CONDITION_COUNT];
int CloseCondition3Array[CONDITION_COUNT];

// Conditions
bool BuyCondition(int index)
{
   switch (index)
   {
      case 0:  return (BuyCondition1());
      case 1:  return (BuyCondition2());
      case 2:  return (BuyCondition3());
      case 3:  return (BuyCondition4());
      case 4:  return (BuyCondition5());
      case 5:  return (BuyCondition6());
      case 6:  return (BuyCondition7());
      case 7:  return (BuyCondition8());
      case 8:  return (BuyCondition9());
      case 9:  return (BuyCondition10());
      case 10:  return (BuyCondition11());
      case 11:  return (BuyCondition12());
      case 12:  return (BuyCondition13());
      case 13:  return (BuyCondition14());
      default: return (false);
   }
   
   // here
}

bool SellCondition(int index)
{
   switch (index)
   {
      case 0:  return (SellCondition1());
      case 1:  return (SellCondition2());
      case 2:  return (SellCondition3());
      case 3:  return (SellCondition4());
      case 4:  return (SellCondition5());
      case 5:  return (SellCondition6());
      case 6:  return (SellCondition7());
      case 7:  return (SellCondition8());
      case 8:  return (SellCondition9());
      case 9:  return (SellCondition10());
      case 10:  return (SellCondition11());
      case 11:  return (SellCondition12());
      case 12:  return (SellCondition13());
      case 13:  return (SellCondition14());
      default: return (false);
   }
   
   // here
}

///=============================================================================================

bool BuyCondition1()
{
   return (Close[1] > iMA(symbol, 0, EMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1));
}

bool SellCondition1()
{
   return (Close[1] < iMA(symbol, 0, EMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1));
}

///=============================================================================================

bool BuyCondition2()
{
   return (iMACD(symbol, 0, MACDFast, MACDSlow, MACDSignal, PRICE_CLOSE, MODE_SIGNAL, 1) > 0);
}

bool SellCondition2()
{
   return (iMACD(symbol, 0, MACDFast, MACDSlow, MACDSignal, PRICE_CLOSE, MODE_SIGNAL, 1) < 0);
}

///=============================================================================================

bool BuyCondition3()
{
   return ( iMACD(symbol, 0, MACDFast, MACDSlow, MACDSignal, PRICE_CLOSE, MODE_SIGNAL, 1) > 
            iMACD(symbol, 0, MACDFast, MACDSlow, MACDSignal, PRICE_CLOSE, MODE_SIGNAL, 2));
}

bool SellCondition3()
{
   return ( iMACD(symbol, 0, MACDFast, MACDSlow, MACDSignal, PRICE_CLOSE, MODE_SIGNAL, 1) <
            iMACD(symbol, 0, MACDFast, MACDSlow, MACDSignal, PRICE_CLOSE, MODE_SIGNAL, 2));
}

///=============================================================================================

bool BuyCondition4()
{
   return ( iCCI(symbol, 0, CCIPeriod, PRICE_CLOSE, 1) > CCILevel);
}

bool SellCondition4()
{
   return ( iCCI(symbol, 0, CCIPeriod, PRICE_CLOSE, 1) < -CCILevel);
}

///=============================================================================================

bool BuyCondition5()
{
   return ( Open[1] > Open[0]);
}

bool SellCondition5()
{
   return ( Open[1] < Open[0]);
}

///=============================================================================================

bool BuyCondition6()
{
   return ( iRSI(symbol, 0, RSIPeriod, PRICE_CLOSE, 1) > 50 + RSILevel);
}

bool SellCondition6()
{
   return ( iRSI(symbol, 0, RSIPeriod, PRICE_CLOSE, 1) < 50 - RSILevel);
}

///=============================================================================================

bool BuyCondition7()
{
   return ( iBullsPower(symbol, 0, BullsBearsPeriod, PRICE_CLOSE, 1) > 0);
}

bool SellCondition7()
{
   return ( iBullsPower(symbol, 0, BullsBearsPeriod, PRICE_CLOSE, 1) < 0);
}

///=============================================================================================

bool BuyCondition8()
{
   return ( iBearsPower(symbol, 0, BullsBearsPeriod, PRICE_CLOSE, 1) > 0);
}

bool SellCondition8()
{
   return ( iBearsPower(symbol, 0, BullsBearsPeriod, PRICE_CLOSE, 1) < 0);
}

///=============================================================================================

bool BuyCondition9()
{
   return ( iBands(symbol, 0, BBandsPeriod, BBandsDeviation, 0, PRICE_CLOSE, MODE_LOWER, 1) > Open[0]);
}

bool SellCondition9()
{
   return ( iBands(symbol, 0, BBandsPeriod, BBandsDeviation, 0, PRICE_CLOSE, MODE_UPPER, 1) < Open[0]);
}

///=============================================================================================

bool BuyCondition10()
{
   return ( iFractals(symbol, 0, MODE_LOWER, 1) != EMPTY_VALUE);
}

bool SellCondition10()
{
   return ( iFractals(symbol, 0, MODE_UPPER, 1) != EMPTY_VALUE);
}

///=============================================================================================

bool BuyCondition11()
{
   return ( SellCondition4());
}

bool SellCondition11()
{
   return ( BuyCondition4());
}

///=============================================================================================

bool BuyCondition12()
{
   return ( SellCondition6());
}

bool SellCondition12()
{
   return ( BuyCondition6());
}

///=============================================================================================

bool BuyCondition13()
{
   return ( SellCondition9());
}

bool SellCondition13()
{
   return ( BuyCondition9());
}

///=============================================================================================

bool BuyCondition14()
{
   return ( SellCondition10());
}

bool SellCondition14()
{
   return ( BuyCondition10());
}

///=============================================================================================

// here

// Functions
void SignalFromString(int& array[CONDITION_COUNT], string s)
{
   int length = StringLen(s);
   
   if (StringLen(s) != CONDITION_COUNT && s != "")
   {
      Print("Wrong string signal ", s, "! Needed mask size is ", CONDITION_COUNT);
   }
   
   for (int i = 0; i < CONDITION_COUNT; i++)
   {
      array[i] = 0;
      
      if (length != 0)
      {
         if (StringGetChar(s, i) == 'S') array[i] = 1;
         if (StringGetChar(s, i) == 'R') array[i] = 2;
      }
   }
}

string SignalToString(int array[CONDITION_COUNT])
{
   static string result;
   
   for (int i = 0; i < CONDITION_COUNT; i++)
   {
      string c = "0";
      if (array[i] == 1) c = "S";
      if (array[i] == 2) c = "R";
      
      result = result + c;
   }
   
   return(result);
}

int CorrectedCondition(int condition, string name)
{
   if (condition > 2 || condition < 0)
   {
      Print("Wrong ", name, " value -- should be {0, 1, 2}, but actual value is ", condition);
      return (0);
   }
   return (condition);
}

void SignalFromOptions(int& array[CONDITION_COUNT])
{
   array[0] = CorrectedCondition(Condition_1, "Condition_1");
   array[1] = CorrectedCondition(Condition_2, "Condition_2");
   array[2] = CorrectedCondition(Condition_3, "Condition_3");
   array[3] = CorrectedCondition(Condition_4, "Condition_4");
   array[4] = CorrectedCondition(Condition_5, "Condition_5");
   array[5] = CorrectedCondition(Condition_6, "Condition_6");
   array[6] = CorrectedCondition(Condition_7, "Condition_7");
   array[7] = CorrectedCondition(Condition_8, "Condition_8");
   array[8] = CorrectedCondition(Condition_9, "Condition_9");
   array[9] = CorrectedCondition(Condition_10, "Condition_10");
   array[10] = CorrectedCondition(Condition_11, "Condition_11");
   array[11] = CorrectedCondition(Condition_12, "Condition_12");
   array[12] = CorrectedCondition(Condition_13, "Condition_13");
   array[13] = CorrectedCondition(Condition_14, "Condition_14");
// here

   ElementsCount = 0;
   for (int i = 0; i < CONDITION_COUNT; i++)
   {
      ElementsCount += MathAbs(array[i]);
   }
}

void CreateSignal()
{
   SignalFromString(OpenCondition1Array, OpenCondition1);
   SignalFromString(OpenCondition2Array, OpenCondition2);
   SignalFromString(OpenCondition3Array, OpenCondition3);

   SignalFromString(CloseCondition1Array, CloseCondition1);
   SignalFromString(CloseCondition2Array, CloseCondition2);
   SignalFromString(CloseCondition3Array, CloseCondition3);

   switch (OptimizingCondition)
   {
      case 0:
      {
         SignalFromOptions(OpenCondition1Array);
         break;
      }
      case 1:
      {
         SignalFromOptions(OpenCondition2Array);
         break;
      }
      case 2:
      {
         SignalFromOptions(OpenCondition3Array);
         break;
      }
      case 3:
      {
         SignalFromOptions(CloseCondition1Array);
         break;
      }
      case 4:
      {
         SignalFromOptions(CloseCondition2Array);
         break;
      }
      case 5:
      {
         SignalFromOptions(CloseCondition3Array);
         break;
      }
   }
}

int GetSignal(int array[CONDITION_COUNT])
{
   bool buySignal = true;
   bool sellSignal = true;
   bool canTrust = false;
   
   for (int i = 0; i < CONDITION_COUNT; i++)
   {
      if (array[i] != 0)
      {
         canTrust = true;
      }
      else continue;
      
      if (
            !(
               (BuyCondition(i) && array[i] == 1) ||
               (!BuyCondition(i) && array[i] == 2)
            )
         )
      {
         buySignal = false;
      }

      if (
            !(
               (SellCondition(i) && array[i] == 1) ||
               (!SellCondition(i) && array[i] == 2)
            )
         )
      {
         sellSignal = false;
      }
   }
   
   buySignal = buySignal && canTrust;
   sellSignal = sellSignal && canTrust;
   
   if (buySignal) return (1);
   if (sellSignal) return (-1);
   
   return(0);
}

void GetSignals()
{
   NeedOpenBuys = false;
   NeedOpenSells = false;
   NeedCloseBuys = false;
   NeedCloseSells = false;

   int open1Res = GetSignal(OpenCondition1Array);
   int open2Res = GetSignal(OpenCondition2Array);
   int open3Res = GetSignal(OpenCondition3Array);

   NeedOpenBuys = 
      (open1Res == 1) ||
      (open2Res == 1) ||
      (open3Res == 1);
      
   NeedOpenSells = 
      (open1Res == -1) ||
      (open2Res == -1) ||
      (open3Res == -1);

   int close1Res = GetSignal(CloseCondition1Array);
   int close2Res = GetSignal(CloseCondition2Array);
   int close3Res = GetSignal(CloseCondition3Array);

   NeedCloseBuys = 
      (close1Res == 1) ||
      (close2Res == 1) ||
      (close3Res == 1);
      
   NeedCloseSells = 
      (close1Res == -1) ||
      (close2Res == -1) ||
      (close3Res == -1);
}

bool LoadStrategyFromFile()
{
   int hFile = FileOpen(FileName, FILE_READ | FILE_CSV, ' ');
   
   if (hFile < 1) return (false);
   
   OpenCondition1 = FileReadString(hFile);
   OpenCondition2 = FileReadString(hFile);
   OpenCondition3 = FileReadString(hFile);
   
   CloseCondition1 = FileReadString(hFile);
   CloseCondition2 = FileReadString(hFile);
   CloseCondition3 = FileReadString(hFile);
   
   CloseWhenOpen = FileReadNumber(hFile);
   
   FileClose(hFile);
   
   return (true);
}

void SaveStrategyToFile()
{
   int hFile = FileOpen(FileName, FILE_WRITE | FILE_CSV, ' ');
   
   if (hFile < 1) return (false);
   
   FileWrite(hFile, OpenCondition1);
   FileWrite(hFile, OpenCondition2);
   FileWrite(hFile, OpenCondition3);
   
   FileWrite(hFile, CloseCondition1);
   FileWrite(hFile, CloseCondition2);
   FileWrite(hFile, CloseCondition3);
   
   FileWrite(hFile, CloseWhenOpen);

   FileClose(hFile);
   
   return (true);
}

int init()
{
   LastTime = Time[0];
   symbol   = Symbol();
   ElementsCount = 0;
   CriticalError = false;
   
   if (LoadFromFile == 1)
   {
      LoadStrategyFromFile();
   }
   
   CreateSignal();

   return(0);
}

void ResultToString(string& s)
{
   switch (OptimizingCondition)
   {
      case 0:
      {
         s = (SignalToString(OpenCondition1Array));
         break;
      }
      case 1:
      {
         s = (SignalToString(OpenCondition2Array));
         break;
      }
      case 2:
      {
         s = (SignalToString(OpenCondition3Array));
         break;
      }
      case 3:
      {
         s = (SignalToString(CloseCondition1Array));
         break;
      }
      case 4:
      {
         s = (SignalToString(CloseCondition2Array));
         break;
      }
      case 5:
      {
         s = (SignalToString(CloseCondition3Array));
         break;
      }
   }
}

int deinit()
{
   string res;
   ResultToString(res);
   Print(res);
   
   switch (OptimizingCondition)
   {
      case 0: 
      {
         OpenCondition1 = res;
         break;
      }
      case 1:
      {
         OpenCondition2 = res;
         break;
      }
      case 2:
      {
         OpenCondition3 = res;
         break;
      }
      case 3:
      {
         CloseCondition1 = res;
         break;
      }
      case 4:
      {
         CloseCondition2 = res;
         break;
      }
      case 5:
      {
         CloseCondition3 = res;
         break;
      }
   }
   
   if (SaveToFile == 1) SaveStrategyToFile();
}

void Check()
{
   if (NeedCloseBuys)
   {
      CloseBuys(Magic, Slippage);
   }
   
   if (NeedCloseSells)
   {
      CloseSells(Magic, Slippage);
   }

   if (NeedOpenBuys)
   {
      if (CloseWhenOpen == 1)
      {
         CloseSells(Magic, Slippage);
      }

      if (GetOrdersCount(Magic) < MaxOrders || MaxOrders == 0)
      {
         OpenBuy(Magic, Target, Loss, TradeLots);
      }
   }
   
   if (NeedOpenSells)
   {
      if (CloseWhenOpen == 1)
      {
         CloseBuys(Magic, Slippage);
      }

      if (GetOrdersCount(Magic) < MaxOrders || MaxOrders == 0)
      {
         OpenSell(Magic, Target, Loss, TradeLots);
      }
   }
}

int start()
{
   if (CriticalError) return(0);
   if (!IsTradeAllowed()) return(0);
   
   if (LastTime == Time[0]) return(0);
   LastTime = Time[0];
   
   if ((ElementsCount == 0 && OptimizingCondition != -1) || ElementsCount > MaxElementsCount) return(0);
   
   double margin = AccountFreeMargin();
   double minBet = GetLotsToBid(0)*MarketInfo(symbol, MODE_MARGINREQUIRED);
   
   if (!GetActiveOrders(Magic) && minBet > margin)
   {
      CriticalError = true;
      return(0);
   }

   GetSignals();
   Check();

   return(0);
}



Sample





Analysis



Market Information Used:

Series array that contains close prices for each bar
Series array that contains open prices of each bar
Series array that contains open time of each bar


Indicator Curves created:


Indicators Used:

Moving average indicator
MACD Histogram
Commodity channel index
Relative strength index
Bulls Power indicator
Bears Power indicator
Bollinger bands indicator
Fractals


Custom Indicators Used:

Order Management characteristics:
It automatically opens orders when conditions are reached
Checks for the total of open orders

It Closes Orders by itself

Other Features:

Uses files from the file system
It reads information from a file
It writes information to file