Schaff_EA_V1





//+------------------------------------------------------------------+
//|                                                    Schaff_EA.mq4 |
//|                                    Copyright © 2009, Robert Hill |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2009, Robert Hill"
#property link      ""
#include <stdlib.mqh>
#include <stderror.mqh> 

// Define signal types
#define NONE 0
#define LONG 1
#define SHORT 2
#define CLOSEBUY 3
#define CLOSESELL 4

//---- input parameters
extern int       MagicBase=20000;
extern string    myComment = "Schaff";
extern int       Slippage = 3;
 
extern string  p1 = "Schaff 1 inputs";
extern int STCPeriod    = 10;
extern int CDPeriod     = 25;
extern int FastMAPeriod = 23;
extern int SlowMAPeriod = 50;
extern double sm1 = 2;

extern string  p2 = "Schaff 2 inputs";
extern int MAShort=12;
extern int MALong=50;
extern double Cycle=10;
extern int CountBars=300;
extern double sm2 = 2;

extern int WhichSchaff = 1;


extern int     ovrbotlevel=80;
extern int     ovrsoldlevel=20;
extern int     TargetBotLevel = 80;
extern int     TargetSoldLevel = 20;

extern int     StopLoss = 100;
extern int     TakeProfit = 100;

extern string  tsp = "--Trailing Stop Types--";
extern string  tsp0 = " 0 = Do not trail";
extern string  tsp1 = " 1 = Trail immediately";
extern string  tsp2 = " 2 = Wait to trail";
extern string  tsp3 = " 3 = Uses 3 levels before trail";
extern string  tsp4 = " 4 = Breakeven + Lockin";
extern int     TrailingStopType = 2;

extern string  ts2 = "Settings for Type 2";
extern double  TrailingStop = 25;      // Change to whatever number of pips you wish to trail your position with.

extern string  ts3 = "Settings for Type 3";
extern double  FirstMove = 10;        // Type 3  first level pip gain
extern double  FirstStopLoss = 30;    // Move Stop to Breakeven
extern double  SecondMove = 25;       // Type 3 second level pip gain
extern double  SecondStopLoss = 20;   // Move stop to lock is profit
extern double  ThirdMove = 35;        // type 3 third level pip gain
extern double  TrailingStop3 = 15;    // Move stop and trail from there

extern string  ts4 = "Settings for Type 4";
extern double  BreakEven = 25;
extern int     LockInPips = 10;        // Profit Lock in pips

//+---------------------------------------------------+
//|Money Management                                   |
//+---------------------------------------------------+
extern string  mm = "---Money Management---";
extern double  Lots=0.01;
extern bool    UseMoneyManagement = false; // Change to false to shutdown money management controls.
extern bool    BrokerIsIBFX = false;
extern bool    BrokerIsCrownForex = false;
extern string  m1="Set mini and micro to false for standard account";
extern bool    AccountIsMini = false;
extern bool    AccountIsMicro = true;
extern double  TradeSizePercent = 1;  // Change to whatever percent of equity you wish to risk.
extern bool    BrokerPermitsFractionalLots = true;

extern string  es3="Sunday No Trade - Enter 0 for false, 1 for true";
extern int    UseSundayNoTrade = 0;
extern string  em3="Monday No Trade - Enter 0 for false, 1 for true";
extern int    UseMondayNoTrade = 0;
extern string  ef3="Friday No Trade - Enter 0 for false, 1 for true";
extern int    UseFridayNoTradeTime = 0;
extern int     FridayFinalHour = 20;   // No trades to start after time

extern string  th0="--Trading Hours Filter--";
extern string  th2="UseTradingHours - Enter 0 for false, 1 for true";
extern int    UseTradingHours = 0;
extern string  th4="TradeAsian - Enter 0 for false, 1 for true";
extern int    TradeAsianMarket = 1;
extern int     AsianStart = 100;       // Start trades after time
extern int     AsianStop = 400;      // Stop trading after time
extern string  th5="Trade Europe - Enter 0 for false, 1 for true";
extern int    TradeEuropeanMarket = 1;
extern int     EurStart = 900;       // Start trades after time
extern int     EurStop = 1400;      // Stop trading after time
extern string  th6="Trade NY - Enter 0 for false, 1 for true";
extern int    TradeNewYorkMarket = 1;
extern int     NYStart = 1600;       // Start trades after time
extern int     NYStop = 1700;      // Stop trading after time

double myPoint;

int MagicNumber;
double mLots; 
int LastTrade = NONE;

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {

	  MagicNumber = MagicBase + func_Symbol2Val(Symbol())*100 + Period();

     myPoint = SetPoint();
   
   return(0);
  }

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
  return(0);
  }  

//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
  bool YesStop;
  
   int NumOrders = 0,  signal = 0;

   if (IsTesting() == false)
   {
     if (IsExpertEnabled() == false)
     {
      return(0);
     }
   }
   if (IsTradeAllowed()==false ) return(0);
   

  NumOrders = CalculateCurrentOrders();
  if (NumOrders == 0)
  {
     YesStop = CheckTradeFilters();
     if (YesStop == false)
     {
       if (!NewBar()) return(0); // wait until first tick after bar close to take any action; 
       signal = GetEntrySignal();
       if (signal != NONE)
       {
        mLots = GetLots();
        OpenNewTrades(signal, mLots);
       }
     }
  }
  else
  {
     RefreshRates();
     CheckForClose();
  }
  return(0);
}

double GetSchaffTrend(int pos)
{
   double mSchaff;
   
   if (WhichSchaff == 1)
   {
    mSchaff = iCustom(NULL,0,"SchaffTrendCycle1",STCPeriod,CDPeriod,FastMAPeriod,SlowMAPeriod,sm1,0,pos);
   }
   else
   {
    mSchaff = iCustom(NULL,0,"Schaff_Trend_Cycle2",MAShort,MALong,Cycle,CountBars,sm2,0,pos);
   }
   
   return(mSchaff);
   
}

int GetEntrySignal()
{

   double Schaff1, Schaff2;
   
   Schaff2 = GetSchaffTrend(2);
   
   if (Schaff2 > ovrbotlevel)
   {
      Schaff1 = GetSchaffTrend(1);
      if (Schaff1 < ovrbotlevel) return(SHORT);
   }
   if (Schaff2 < ovrsoldlevel)
   {
      Schaff1 = GetSchaffTrend(1);
      if (Schaff1 > ovrsoldlevel) return(LONG);
   }
   return(NONE);
   
}

int GetExitSignal(int cmd)
{
   double Schaff1, Schaff2;
   
   Schaff2 = GetSchaffTrend(2);
   
   if (cmd == OP_BUY)
   {
     if (Schaff2 >= TargetBotLevel)
     {
        Schaff1 = GetSchaffTrend(1);
        if (Schaff1 < TargetBotLevel) return(CLOSEBUY);
     }
   }
   
   if (cmd == OP_SELL)
   {
     if (Schaff2 <= TargetSoldLevel)
     {
        Schaff1 = GetSchaffTrend(1);
        if (Schaff1 > TargetSoldLevel) return(CLOSESELL);
     }
   }
    
   return(NONE);
   
}


void OpenNewTrades(int mSignal, double mLots)
{
  int ticket, err;
  double TPprice,STprice;
  double OrderOP;
      
   RefreshRates();
   
    if (mSignal == SHORT)
    { 
    
      ticket=OrderSend(Symbol(),OP_SELL,mLots,Bid,Slippage * myPoint,0,0,
                  myComment,MagicNumber,0,Red); //Sell at Market price
      if (ticket > 0)
      {
         LastTrade = SHORT;
         OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES);
         OrderOP = OrderOpenPrice();
         if (StopLoss != 0 || TakeProfit != 0)
	      {
            TPprice = 0;
            if (TakeProfit > 0)
            {
               TPprice=TakeShort(OrderOP, TakeProfit);
            }
            STprice = 0;
            if (StopLoss > 0)
            {
              STprice=StopShort(OrderOP, StopLoss);
		        STprice = ValidStopLoss(OP_SELL,Ask, STprice);
		      }   
 // Normalize stoploss / takeprofit to the proper # of digits.
            if (Digits > 0) 
            {
              STprice = NormalizeDouble( STprice, Digits);
              TPprice = NormalizeDouble( TPprice, Digits); 
            }
		      ModifyOrder(ticket, OrderOP, STprice, TPprice, LightGreen);
         } 
      }
    }
    
    if (mSignal == LONG)   
    {
      ticket=OrderSend(Symbol(),OP_BUY,mLots,Ask,Slippage * myPoint,0,0,
                   myComment,MagicNumber,0,Lime); //Buy at Market price
      if (ticket > 0)
      {
         LastTrade = LONG;
         OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES);
         OrderOP = OrderOpenPrice();
         if (StopLoss != 0 || TakeProfit != 0)
	      {
            TPprice = 0;
            if (TakeProfit > 0)
            {
              TPprice=TakeLong(OrderOP,TakeProfit);
            }
            STprice = 0;
            if (StopLoss > 0)
            {
              STprice=StopLong(OrderOP ,StopLoss);
		        STprice = ValidStopLoss(OP_BUY,Bid, STprice); 
		      }  
 // Normalize stoploss / takeprofit to the proper # of digits.
            if (Digits > 0) 
            {
              STprice = NormalizeDouble( STprice, Digits);
              TPprice = NormalizeDouble( TPprice, Digits); 
            }
		      ModifyOrder(ticket, OrderOP, STprice, TPprice, Red);
         }
      }
    }
   if(ticket<0)
   {
     err = GetLastError();
     Print("OrderSend failed : (" +  err + ")");
     Print(ErrorDescription(err));
   }
}


void CheckForClose()
{
   int Signal, result, err;
   
// Check for open trades to close or modify

    for(int cnt=OrdersTotal()-1;cnt>=0;cnt--)
    {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
      {
        Signal = GetExitSignal(OrderType());
        result = true;
        if(OrderType() == OP_BUY)
        {
           if (Signal == CLOSEBUY)
           {
              result = OrderClose(OrderTicket(), OrderLots(), Bid, 3, Red);
           }
           else
              if (TrailingStopType > 0) HandleTrailingStop(OP_BUY,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
 
        }
        if(OrderType() == OP_SELL)
        {
           if (Signal == CLOSESELL)
           {
             result = OrderClose(OrderTicket(), OrderLots(), Ask, 3, Lime);
           }
           else
             if (TrailingStopType > 0) HandleTrailingStop(OP_SELL,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
 
        }
        if (result == false)
        {
		     err = GetLastError();
           Print(" Error closing order : (" +  err + ")");
           Print(ErrorDescription(err));
        }
        
      }
    }
 }
//----

//+------------------------------------------------------------------+
//| HandleTrailingStop                                               |
//| Type 1 moves the stoploss without delay.                         |
//| Type 2 waits for price to move the amount of the trailStop       |
//| before moving stop loss then moves like type 1                   |
//| Type 3 uses up to 3 levels for trailing stop                     |
//|      Level 1 Move stop to 1st level                              |
//|      Level 2 Move stop to 2nd level                              |
//|      Level 3 Trail like type 1 by fixed amount other than 1      |
//| Type 4 Move stop to breakeven + Lockin, no trail                 |
//| Type 5 uses steps for 1, every step pip move moves stop 1 pip    |
//| Type 6 Uses EMA to set trailing stop                             |
//+------------------------------------------------------------------+
int HandleTrailingStop(int type, int ticket, double op, double os, double tp)
{
   switch (TrailingStopType)
   {
     case 1 : Immediate_TrailingStop (type, ticket, op, os, tp);
              break;
     case 2 : Delayed_TrailingStop (type, ticket, op, os, tp);
              break;
     case 3 : ThreeLevel_TrailingStop (type, ticket, op, os, tp);
              break;
     case 4 : BreakEven_TrailingStop (type, ticket, op, os, tp);
              break;
	}
   return(0);
}

int ModifyOrder(int ord_ticket,double op, double oSL, double oTP, color mColor)
{
    int CloseCnt, err;
    double myStop, myTake;
    
/*
    if (Digits > 0)
    {
       myStop = NormalizeDouble( oSL, Digits);
       myTake = NormalizeDouble( oTP, Digits);
    }
*/
    CloseCnt=0;
    while (CloseCnt < 3)
    {
       if (OrderModify(ord_ticket,op,oSL,oTP,0,mColor))
       {
         CloseCnt = 3;
       }
       else
       {
          err=GetLastError();
          Print(CloseCnt," Error modifying order : (", err , ") " + ErrorDescription(err));
         if (err>0) CloseCnt++;
       }
    }
}

double ValidStopLoss(int type, double price, double SL)
{

   double mySL;
   double minstop;
   
   if (SL < 0.1) return(SL);
   
   mySL = SL;
   minstop = MarketInfo(Symbol(),MODE_STOPLEVEL);
   if (Digits == 3 || Digits == 5) minstop = minstop / 10;
   if (type == OP_BUY)
   {
		 if((price - SL) < minstop*myPoint) mySL = price - minstop*myPoint;
   }
   if (type == OP_SELL)
   {
       if((SL-price) < minstop*myPoint)  mySL = price + minstop*myPoint;  
   }

   return(NormalizeDouble(mySL,MarketInfo(Symbol(), MODE_DIGITS)));   
}

//+------------------------------------------------------------------+
//|                                       Immediate_TrailingStop.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by MrPip,robydoby314@yahoo.com   |
//|                                                                  |   
//| Moves the stoploss without delay.                                |
//+------------------------------------------------------------------+
void Immediate_TrailingStop(int type, int ticket, double op, double os, double tp)
{

   int digits;
   double pt, pBid, pAsk, BuyStop, SellStop;

   digits = MarketInfo(Symbol( ), MODE_DIGITS);
   
   if (type==OP_BUY)
   {
     pBid = MarketInfo(Symbol(), MODE_BID);
     pt = StopLoss * myPoint;
     if(pBid-os > pt)
     {
       BuyStop = pBid - pt;
       if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
		 BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop);   
       if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
		 return;
	  }
   }
   if (type==OP_SELL)
   {
     pAsk = MarketInfo(Symbol(), MODE_ASK);
     pt = StopLoss * myPoint;
     if(os - pAsk > pt)
     {
       SellStop = pAsk + pt;
       if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
       SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
       if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
		 return;
     }
   }   
}

//+------------------------------------------------------------------+
//|                                         Delayed_TrailingStop.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by MrPip,robydoby314@yahoo.com   |
//|                                                                  |   
//| Waits for price to move the amount of the TrailingStop           |
//| Moves the stoploss pip for pip after delay.                      |
//+------------------------------------------------------------------+
void Delayed_TrailingStop(int type, int ticket, double op, double os, double tp)
{
   int digits;
   double pt, pBid, pAsk, BuyStop, SellStop;

   pt = TrailingStop * myPoint;
   digits = MarketInfo(Symbol(), MODE_DIGITS);
   
   if (type==OP_BUY)
   {
     pBid = MarketInfo(Symbol(), MODE_BID);
     BuyStop = pBid - pt;
     if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
	  BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop);   
     if (pBid-op > pt && os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
	  return;
   }
   if (type==OP_SELL)
   {
     pAsk = MarketInfo(Symbol(), MODE_ASK);
     pt = TrailingStop * myPoint;
     SellStop = pAsk + pt;
     if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
     if (op - pAsk > pt && os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
	  return;
   }   
}
 
//+------------------------------------------------------------------+
//|                                           BreakEvenExpert_v1.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by IgorAD,igorad2003@yahoo.co.uk |   
//|            http://finance.groups.yahoo.com/group/TrendLaboratory |                                      
//+------------------------------------------------------------------+
void BreakEven_TrailingStop(int type, int ticket, double op, double os, double tp)
{

   int digits;
   double pBid, pAsk, BuyStop, SellStop;

   digits = MarketInfo(Symbol(), MODE_DIGITS);
   
  if (type==OP_BUY)
  {
    pBid = MarketInfo(Symbol(), MODE_BID);
    if ( pBid-op > myPoint*BreakEven ) 
    {
       BuyStop = op + LockInPips * myPoint;
       if (digits > 0) BuyStop = NormalizeDouble( BuyStop, digits);
		 BuyStop = ValidStopLoss(OP_BUY,pBid, BuyStop);   
       if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
		 return;
	 }
  }
  if (type==OP_SELL)
  {
    pAsk = MarketInfo(Symbol(), MODE_ASK);
    if ( op - pAsk > myPoint*BreakEven ) 
    {
       SellStop = op - LockInPips * myPoint;
       if (digits > 0) SellStop = NormalizeDouble( SellStop, digits);
       SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);  
       if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
		 return;
    }
  }   

}

//+------------------------------------------------------------------+
//|                                      ThreeLevel_TrailingStop.mq4 |
//|                                  Copyright © 2006, Forex-TSD.com |
//|                         Written by MrPip,robydoby314@yahoo.com   |   
//|                                                                  |
//| Uses up to 3 levels for trailing stop                            |
//|      Level 1 Move stop to 1st level                              |
//|      Level 2 Move stop to 2nd level                              |
//|      Level 3 Trail like type 1 by fixed amount other than 1      |
//+------------------------------------------------------------------+
void ThreeLevel_TrailingStop(int type, int ticket, double op, double os, double tp)
{

   int digits;
   double pBid, pAsk, BuyStop, SellStop;

   digits = MarketInfo(Symbol(), MODE_DIGITS) ;

   if (type == OP_BUY)
   {
      pBid = MarketInfo(Symbol(), MODE_BID);
      if (pBid - op > FirstMove * myPoint)
      {
         BuyStop = op + FirstMove*myPoint - FirstStopLoss * myPoint;
         if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
		   BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
         if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
      }
              
      if (pBid - op > SecondMove * myPoint)
      {
         BuyStop = op + SecondMove*myPoint - SecondStopLoss * myPoint;
         if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
		   BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
         if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
      }
                
      if (pBid - op > ThirdMove * myPoint)
      {
         BuyStop = pBid  - ThirdMove*myPoint;
         if (digits > 0) BuyStop = NormalizeDouble(BuyStop, digits); 
		   BuyStop = ValidStopLoss(OP_BUY, pBid, BuyStop);   
         if (os < BuyStop) ModifyOrder(ticket,op,BuyStop,tp,LightGreen);
      }
   }
       
    if (type ==  OP_SELL)
    {
        pAsk = MarketInfo(Symbol(), MODE_ASK);
        if (op - pAsk > FirstMove * myPoint)
        {
           SellStop = op - FirstMove * myPoint + FirstStopLoss * myPoint;
           if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
		     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);   
           if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
        }
        if (op - pAsk > SecondMove * myPoint)
        {
           SellStop = op - SecondMove * myPoint + SecondStopLoss * myPoint;
           if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
		     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);   
           if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
        }
        if (op - pAsk > ThirdMove * myPoint)
        {
           SellStop = pAsk + ThirdMove * myPoint;               
           if (digits > 0) SellStop = NormalizeDouble(SellStop, digits); 
		     SellStop = ValidStopLoss(OP_SELL, pAsk, SellStop);   
           if (os > SellStop) ModifyOrder(ticket,op,SellStop,tp,DarkOrange);
        }
    }

}


//-- Check for Start of a new Bar
bool NewBar()
{
   static datetime dt = 0;
   
   if (Time[0] != dt)
   {
      dt = Time[0];
      return(true);
   }
   return(false);
}

double StopLong(double price,int stop)
{
 if(stop==0)
  return(0);
 else
  return(price-(stop*myPoint));
}

double StopShort(double price,int stop)
{
 if(stop==0)
  return(0);
 else
  return(price+(stop*myPoint));
}

double TakeLong(double price,int take)
{
 if(take==0)
  return(0);
 else
  return(price+(take*myPoint));
}

double TakeShort(double price,int take)
{
 if(take==0)
  return(0);
 else
  return(price-(take*myPoint));
}

int CalculateCurrentOrders()
{
   int buys = 0, sells = 0, num = 0;
   for(int i=OrdersTotal()-1;i>=0;i--)
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()== Symbol() && OrderMagicNumber()== MagicNumber)
      {
        if(OrderType() == OP_BUY)  buys++;
        if(OrderType() == OP_SELL) sells++;
      }
   }
     
   num = buys + sells;
   return(num);
}


//+------------------------------------------------------------------+
//| Get number of lots for this trade                                |
//+------------------------------------------------------------------+
double GetLots()
{
   double lot;
   double myMaxLot = MarketInfo(Symbol(), MODE_MAXLOT);
   
   if(UseMoneyManagement == false) return(Lots);

   if (BrokerIsIBFX == true)
   {
     lot = Calc_IBFX_Money_Management();
     return(lot);
   }
   
   if (BrokerIsCrownForex == true)
   {
     lot = Calc_CrownMoney_Management();
     return(lot);
   }
//   lot = LotsOptimized();
   lot=NormalizeDouble((AccountEquity()*TradeSizePercent/10000)/10,2);

//   lot = MathRound( lot/myStep ) * myStep;

// Use at least 1 micro lot
   if (AccountIsMicro == true)
   {
      lot = MathFloor(lot*100)/100;
      if (lot < 0.01) lot = 0.01;
      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }

// Use at least 1 mini lot
   if(AccountIsMini == true)
   {
      lot = MathFloor(lot*10)/10;
      if (lot < 0.1) lot = 0.1;
      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }
   
// Standard account   
   if( BrokerPermitsFractionalLots == false)
   {
      if (lot >= 1.0) lot = MathFloor(lot); else lot = 1.0;
   }
   
   if (lot < 1.0) lot = 1.0;
   if (lot > myMaxLot) lot = myMaxLot;

   return(lot);
}

double Calc_CrownMoney_Management()
{
   double lot;

   lot=NormalizeDouble((AccountEquity()*TradeSizePercent/10000)/10,1);

//   lot = MathRound( lot/myStep ) * myStep;

// Use at least 1 mini lot
   if(AccountIsMini == true)
   {
      lot = MathFloor(lot*10)/10 * 10000;
      if (lot < 10000) lot = 10000;
//      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }
   
// Standard account   
   
   lot = lot * 100000;
   if (lot < 100000) lot = 100000;
//   if (lot > myMaxLot) lot = myMaxLot;

   return(lot);
}

double Calc_IBFX_Money_Management()
{
// variables used for money management
   double lot;
   double myMaxLot = MarketInfo(Symbol(), MODE_MAXLOT);

   lot=NormalizeDouble((AccountEquity()*TradeSizePercent/10000)/10,2);
   
// Use at least 1 micro lot
   if (AccountIsMicro == true)
   {
      lot = lot * 10;
      lot = MathFloor(lot*100)/100;
      if (lot < 0.1) lot = 0.1;
      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }

// Use at least 1 mini lot
   if(AccountIsMini == true)
   {
      lot = lot * 10;
      lot = MathFloor(lot*10)/10;
      if (lot < 1) lot = 1;
      if (lot > myMaxLot) lot = myMaxLot;
      return(lot);
   }
   
   // Standard Account
   
   if(BrokerPermitsFractionalLots == true)
        lot = StrToDouble(DoubleToStr(lot, 2));
   else
        lot = MathFloor(lot);
   
   if (lot > myMaxLot) lot = myMaxLot;

   return(lot); 
}

double SetPoint()
{
   double mPoint;
   
   if (Digits < 4)
      mPoint = 0.01;
   else
      mPoint = 0.0001;
   
   return(mPoint);
}

int func_Symbol2Val(string symbol)
 {
   string mySymbol = StringSubstr(symbol,0,6);
   
	if(mySymbol=="AUDCAD") return(1);
	if(mySymbol=="AUDJPY") return(2);
	if(mySymbol=="AUDNZD") return(3);
	if(mySymbol=="AUDUSD") return(4);
	if(mySymbol=="CHFJPY") return(5);
	if(mySymbol=="EURAUD") return(6);
	if(mySymbol=="EURCAD") return(7);
	if(mySymbol=="EURCHF") return(8);
	if(mySymbol=="EURGBP") return(9);
	if(mySymbol=="EURJPY") return(10);
	if(mySymbol=="EURUSD") return(11);
	if(mySymbol=="GBPCHF") return(12);
	if(mySymbol=="GBPJPY") return(13);
	if(mySymbol=="GBPUSD") return(14);
	if(mySymbol=="NZDJPY") return(15);
	if(mySymbol=="NZDUSD") return(16);
	if(mySymbol=="USDCAD") return(17);
	if(mySymbol=="USDCHF") return(18);
	if(mySymbol=="USDJPY") return(19);
   Comment("unexpected Symbol");
	return(999);
}


bool CheckTradeFilters()
{
   bool myStop, Expired;
   
   myStop = false;
   
      
      if (UseTradingHours == 1)
      {
        myStop = CheckTradingTimes();
   
        if (myStop == true)
        {
          Comment ("Trading has been stopped - wrong time of day");
        }
        else
        {
          Comment ("Trading has resumed - time is OK");
        }
      }
      else
          Comment("Trading Time filter not in use");

//+------------------------------------------------------------------+
//| Sunday No trade zone                                             |
//+------------------------------------------------------------------+
   if (myStop == false)
   {
      if (UseSundayNoTrade == 1)
      {
         if(DayOfWeek()==0)
         {
            myStop = true;
            Comment ("Trading has been stopped - Sunday");
         }
      }
   }
//+------------------------------------------------------------------+
//| Monday No trade zone                                             |
//+------------------------------------------------------------------+
   if (myStop == false)
   {
      if (UseMondayNoTrade == 1)
      {
         if(DayOfWeek()==1)
         {
            myStop = true;
            Comment ("Trading has been stopped - Monday");
         }
      }
   }
   
//+------------------------------------------------------------------+
//| Friday No trade zone                                             |
//+------------------------------------------------------------------+
   if (myStop == false)
   {
      if (UseFridayNoTradeTime == 1)
      {
         if(DayOfWeek()==5 && Hour() >= FridayFinalHour)
         {
            myStop = true;
            Comment ("Trading has been stopped - Friday");
         }
      }
   }

   
   return(myStop);
}


bool IsNotValidTradingTime( int StartHour, int EndHour)
{
  int lHour=Hour() *100+Minute( );
  if(StartHour<=EndHour)
  {
    if(lHour<StartHour || lHour>EndHour) return(true) ;
  }
  else if(lHour>EndHour && lHour<StartHour) return(true) ;
  return(false) ;
}

bool CheckTradingTimes()
{
   bool StopTrading;
   int ct;
   ct = Hour() * 100 + Minute();
   
     StopTrading = true;
// Check trading Asian Market
     if (TradeAsianMarket == 1)
     {
        StopTrading = IsNotValidTradingTime(AsianStart, AsianStop);
     }
     if (StopTrading == true)
     {
// Check trading European Market
       if (TradeEuropeanMarket == 1)
       {
         StopTrading = IsNotValidTradingTime(EurStart, EurStop);
       }
     }
     if (StopTrading == true)
     {
// Check trading New York Market
       if (TradeNewYorkMarket == 1)
       {
         StopTrading = IsNotValidTradingTime(NYStart, NYStop);
       }
     }
     
     return(StopTrading);
}
//----








Sample





Analysis



Market Information Used:

Series array that contains open time of each bar


Indicator Curves created:


Indicators Used:




Custom Indicators Used:
SchaffTrendCycle1
Schaff_Trend_Cycle2

Order Management characteristics:

Checks for the total of open orders
It Closes Orders by itself
It can change open orders parameters, due to possible stepping strategy

Other Features: