CandleStix





//*****************************************************************//
//Candlestix©    By xxDavidxSxx@yahoo.com                         //
//*****************************************************************//
#property copyright " David Stanley Copyright © 2007"
#property link      "xxDavidxSxx@Yahoo.com"

#include       <stdlib.mqh>
#include       <stderror.mqh> 


extern int     ProfitTarget = 80;                    // Change to whatever number of pips you wish to trail your position with.
extern double  TrailingStop = 60;                                   
extern double  Lots = 0.1;
extern int     MagicNumber=123400;
extern int     Slippage = 5;
extern bool    UseNoTradeDay=false;
extern int     NoTradeDay = 5;
extern int     volume=200;
//---------------------------------------------------------------------//

bool           UseTrailingStop = true;
extern int            StopLoss = 60;
int            TrailingStopType = 2;                 // Type 1 moves stop immediately, Type 2 waits til value of TS is reached
int            SignalCandle=1;                       //set to 1 if you want to get the cangle close 0 for current
int            err, ticket, MyTrades;
int            OpenLong;
int            OpenShort;
int            EWOCCIColor;
//+---------------------------------------------------+
//|Money Management                                   |
//+---------------------------------------------------+
extern bool    UseMoneyManagement = true;           // Change to false to shutdown money management controls.
extern int     MM_Type = 2;
//+---------------------------------------------------+
//|Money Management type 1                            |
//+---------------------------------------------------+
extern string  StrSep1 = "-----MoneyManagementType 1 -----";
extern double  MMRisk=0.15;                         // Risk Factor
extern double  LossMax=1000;                        // Maximum Loss by 1 Lot
//+---------------------------------------------------+
//|Money Management type 2                            |
//+---------------------------------------------------+
extern string  StrSep2 = "-----MoneyManagementType 2 -----";
extern bool    AccountIsMini = true;                // Change to true if trading mini account
extern double  TradeSizePercent = 35;               // Change to whatever percent of equity you wish to risk.
double         MaxLots = 10;
//+--------------Is It Time To Trade?----------------------+

extern int     GMT_Offset = 0;
extern string  sm="--Trading Hours--";
extern bool    UseTradingHours = false;
extern bool    TradeAsianMarket = false;
extern int     StartHour1 = 1;                      // Start trades after time
extern int     StopHour1 = 10;                      // Stop trading after time
extern bool    TradeEuropeanMarket = true;
extern int     StartHour2 = 9;                      // Start trades after time
extern int     StopHour2 = 14;                      // Stop trading after time
extern bool    TradeNewYorkMarket = true;
extern int     StartHour3 = 15;                     // Start trades after time
extern int     StopHour3 = 23;                      // Stop trading after time
bool           YesStop; 
//+---------------------------------------------------------------+//

double BarClosePrev3=0,BarClosePrev4=0,BarClosePrev5=0,PrevDClose=0, PrevDHigh=0, PrevDLow=0, Pivot=0, BarClose=0,BarClosePrev=0,BarClosePrev2=0,
       PrevBarHigh=0,PrevBarLow=0,Lotsi=0,BarOpen=0,PrevBarHigh2=0,PrevBarLow2=0,
       h=0,m=0,s=0,ewo=0,ewos=0,ewop,ewosp; 
double BarOpen2=0,PrevPHigh=0,PrevPLow=0,PrevPClose=0,PivotP=0,
        Bar=0;

bool   TradeAllowed=true;
datetime   dayofyear;
datetime   timehour;
int init() 
  {
    MagicNumber = MagicNumber;
 }

//+------------------------------------------------------------------+
//+                            MAKE LABEL                            +
//+------------------------------------------------------------------+
int ObjectMakeLabel( string n, int xoff, int yoff, int WindowToUse ){
   ObjectCreate( n, OBJ_LABEL, WindowToUse, 0, 0 );
   ObjectSet( n, OBJPROP_CORNER, 2 );
   ObjectSet( n, OBJPROP_XDISTANCE, xoff );
   ObjectSet( n, OBJPROP_YDISTANCE, yoff );
   ObjectSet( n, OBJPROP_BACK, true );
}


bool CheckTradingTimes()
{
   bool StopTrading;
   int offsetStartHour1, offsetStopHour1;
   int offsetStartHour2, offsetStopHour2;
   int offsetStartHour3, offsetStopHour3;
   
   offsetStartHour1 = StartHour1 + GMT_Offset;
   offsetStopHour1 = StopHour1 + GMT_Offset;
   offsetStartHour2 = StartHour2 + GMT_Offset;
   offsetStopHour2 = StopHour2 + GMT_Offset;
   offsetStartHour3 = StartHour3 + GMT_Offset;
   offsetStopHour3 = StopHour3 + GMT_Offset;
   
     StopTrading = true;
//------------------------------- Check trading Asian Market-------------------------//
     if (TradeAsianMarket)
     {
        if (offsetStartHour1 > 18)
        {
//----------------------- Check broker that uses Asian open before 0:00--------------//

          if (Hour() >= offsetStartHour1) StopTrading = false;
           if (!StopTrading)
           {
            if (offsetStopHour1 < 24)
            {
              if ( Hour() <= offsetStopHour1) StopTrading = false;
             }
            if (offsetStopHour1 >=0)
            {
              if ( Hour() <= offsetStopHour1) StopTrading = false;
            }
          }
        }
        else
        {
          if (Hour() >= offsetStartHour1 && Hour() <= offsetStopHour1) StopTrading = false;
        }
     }
     if (StopTrading)
     {
//------------------------------ Check trading European Market------------------------//
       if (TradeEuropeanMarket)
       {
         if (Hour() >= offsetStartHour2 && Hour() <= offsetStopHour2) StopTrading = false;
       }
     }
     if (StopTrading)
     {
// Check trading New York Market
       if (TradeNewYorkMarket)
       {
         if (Hour() >= offsetStartHour3 && Hour() <= offsetStopHour3) StopTrading = false;
       }
     }
     
     return(StopTrading);
 
    
}
int start()
{


 if (OrdersTotal() > 0 &&  OrderMagicNumber() == MagicNumber)
  EWOCCIColor=DarkSeaGreen;
 {
  if (OrdersTotal() < 1 && OrderMagicNumber() == MagicNumber)
   EWOCCIColor=Maroon;
   }
  string comm,print;
print="CandleStix";
comm=print;
ObjectMakeLabel( "CandleStix", 25, 12, 0);
   ObjectSetText( "CandleStix", "Version 1", 8, "Arial", EWOCCIColor );
ObjectCreate("CandleStix", OBJ_LABEL, 0, 0, 0);
ObjectSetText("CandleStix", comm, 60, "Times New Roman", EWOCCIColor);



//----------Lets Get Min. S/L Distance Allowed By Broker-------------------------//
int h=TimeHour(TimeCurrent());
int m=TimeMinute(TimeCurrent());
int s=TimeSeconds(TimeCurrent());
int     day; 
int     S_StopLoss;
int     L_StopLoss;
int err;
err=GetLastError();
double dblMinStopDistance = MarketInfo(Symbol(),MODE_STOPLEVEL)*MarketInfo(Symbol(), MODE_POINT);
Comment ("Min Stop Distance : ",dblMinStopDistance,"            ","CandleStix Copyright © 2007","       ","xxDavidxSxx@Yahoo.com","    ",h,":",m,":",s);  
int NumTrades = 0;
int OpenLong,OpenShort; 
  for (int i = 0; i < OrdersTotal(); i++)
  {
    OrderSelect(i, SELECT_BY_POS);
    if (OrderSymbol() == Symbol())
     {
      if (OrderType() == OP_BUY ) NumTrades++;
      if (OrderType() == OP_SELL )NumTrades++;
    }
  }

bool Trading = true;

  if (UseNoTradeDay) 
{
   if(  DayOfWeek() == NoTradeDay  ){
 //Comment("No Trade Friday ","    ",h,":",m,":",s);
   Trading=false;
   }else{
     //Comment ("Trading Day O-K","    ",h,":",m,":",s);
   Trading=true;
   }
}
//---------------------------Lets Determine Lot Size---------------------------//
 
L_StopLoss = iLow(Symbol(),PERIOD_D1,0);
S_StopLoss = iHigh(Symbol(),PERIOD_D1,0);
  if (NumTrades == 0) 
   {
    if (TradeAllowed)
      {
        if (MM_Type == 1)
        Lotsi = MoneyManagement ( UseMoneyManagement, Lots, MMRisk, LossMax);
          else
        Lotsi = GetLots();
//-----------------------------Is It Time To Trade?----------------------------//          
   YesStop = false;
   if (UseTradingHours) YesStop = CheckTradingTimes();
   if (YesStop)
    {
    //Comment ("Trading has been stopped as requested - wrong time of day");
     ObjectMakeLabel( "StopTrade", 25, 12, 0);
   ObjectSetText( "StopTrade", "Trading has been stopped as requested - wrong time of day", 8, "Arial", MediumVioletRed );
    }
  else
  {
  //Comment ("Time To Trade!");
    ObjectMakeLabel( "StopTrade", 25, 12, 0);
   ObjectSetText( "StopTrade", "Trade Time O-K ! ", 8, "Arial", Turquoise );
   
  }

  //-------------------------------Bar Close---==----------------------------//

PrevPClose   = iClose(Symbol(),PERIOD_H4,2);
PrevPHigh    = iHigh(Symbol(),PERIOD_H4,2);
PrevPLow     = iLow(Symbol(),PERIOD_H4,2);
PivotP        = (PrevPHigh + PrevPLow + PrevPClose)/3;

PrevDClose   = iClose(Symbol(),PERIOD_D1,1);
PrevDHigh    = iHigh(Symbol(),PERIOD_D1,1);
PrevDLow     = iLow(Symbol(),PERIOD_D1,1);
Pivot        = (PrevDHigh + PrevDLow + PrevDClose)/3;
Bar          = iClose(Symbol(),0,0);
BarClose     = iClose(Symbol(),0,1);                        
BarClosePrev2= iClose(Symbol(),0,2); 
BarClosePrev3= iClose(Symbol(),0,3);
BarClosePrev4= iClose(Symbol(),PERIOD_D1,3);
BarClosePrev5= iClose(Symbol(),PERIOD_D1,4);
BarOpen      = iOpen(Symbol(),0,0);
BarOpen2      = iOpen(Symbol(),0,1);
PrevBarHigh  = High[2];
PrevBarLow   = Low[2];
PrevBarHigh2  = High[3];
PrevBarLow2   = Low[3];



 //----------------------------------SIGNAL GENERATOR--------------------------//           

 if (YesStop == false)        
  if ( dayofyear!=DayOfYear())//compare the day of the year of the last order sent)
  //if ( timehour != Hour())
 if ( BarClosePrev2 < PrevBarLow2 && BarClose > PrevBarHigh &&    BarClose > Pivot && BarClose > BarClosePrev4)
                 //if (BarClose < BarOpen2 && BarOpen > BarClose )
                 {       
             OrderSend(Symbol(), OP_BUY, Lotsi, Ask, Slippage, Ask - StopLoss * Point, Ask + ProfitTarget * Point,"EWOCCI Long",MagicNumber, 0); 
           dayofyear=DayOfYear();//record trade day right after ordersend
           timehour=Hour();
               }
          
          //----Short--------------------//

     if (YesStop == false)     
    if (dayofyear!=DayOfYear())//compare the day of the year of the last order sent)
      //if ( timehour != Hour())   
          if ( BarClosePrev2 > PrevBarHigh2 && BarClose < PrevBarLow &&    BarClose < Pivot && BarClose < BarClosePrev4) 
             //if (BarClose > BarOpen2 && BarOpen < BarClose )
              {
          OrderSend(Symbol(), OP_SELL, Lotsi, Bid, Slippage, Bid + StopLoss * Point, Bid - ProfitTarget * Point,"EWOCCI SELL",MagicNumber, 0);
               dayofyear=DayOfYear();//record trade day right after ordersend
               timehour=Hour();
               }
               if ( timehour != Hour())          
               
            {
             return(0);
           }
        }
     }
	  
	   
//------------------------------TRAILING STOP FUNCTION-------------------------//  
  if (UseTrailingStop)
   {
    for (i = 0; i < OrdersTotal(); i++)
     {
       OrderSelect(i, SELECT_BY_POS, MODE_TRADES);

     if ( OrderSymbol() == Symbol() )
      {
       if ( OrderType() == OP_BUY && OrderMagicNumber() == MagicNumber)
        {
          HandleTrailingStop(OP_BUY,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
          }

      if ( OrderType() == OP_SELL && OrderMagicNumber() == MagicNumber)
         {
          HandleTrailingStop(OP_SELL,OrderTicket(),OrderOpenPrice(),OrderStopLoss(),OrderTakeProfit());
	  	   }
	    }
     }
   }
  return(0);
 }

// ---------------------------------- Money Management, by Robert Hill--------------------//

double MoneyManagement ( bool flag, double Lots, double risk, double maxloss)
   {
     Lotsi=Lots;
	    
   if ( flag ) Lotsi=NormalizeDouble(Lots*AccountFreeMargin()*risk/maxloss,1);   
     
   if (Lotsi<0.1) Lotsi=0.1;  
   return(Lotsi);
   } 

//-------------------------------------Lets Determine Lot Size---------------------------//                             

double GetLots()
{
   double lot;
   
   if(UseMoneyManagement)
    {
     lot = LotsOptimized();
      }
       else
        {
         lot = Lots;
   
   
   if(AccountIsMini)
    {
     if (lot < 0.1) lot = 0.1;
      }
       else
      {
     if (lot >= 1.0) lot = MathFloor(lot); else lot = 1.0;
      }
       if (lot > MaxLots) lot = MaxLots;
        }
         return(lot);
        }




//------------------ Calculate optimal lot size based on percent of Account---------------//                                   


double LotsOptimized()
  {
   double lot=Lots;
//---- select lot size
   lot=NormalizeDouble(MathFloor(AccountFreeMargin()*TradeSizePercent/10000)/10,1);
   
  
  if(AccountIsMini)
  {
    lot = MathFloor(lot*10)/10;
    }
   return(lot);
  }
  


//-------------- Modify Open Position Controls  Try to modify position 3 times -----------//                                 

bool ModifyOrder(int nOrderType, int ord_ticket,double op, double price,double tp, color mColor = CLR_NONE)
{
    int cnt, err;
    double myStop;
    
    myStop = ValidStopLoss (nOrderType, price);
    cnt=0;
   
       if (OrderModify(ord_ticket,op,myStop,tp,0,mColor))
       {
        return(true);
       }
       else 
       {
          err=GetLastError();
          if (err > 1) Print(cnt," Error modifying order : (", ord_ticket , ") " + ErrorDescription(err), " err ",err);
          if (err>0) cnt++;
          Sleep (10000);
          }
       
    
    return(false);
   }



//---------------------------------Adjust stop loss so that it is legal------------------//
double ValidStopLoss(int cmd, double sl)
{
   
   if (sl == 0) return(0.0);
   
   double mySL, myPrice;
   double dblMinStopDistance = MarketInfo(Symbol(),MODE_STOPLEVEL)*MarketInfo(Symbol(), MODE_POINT);
   mySL = sl;
// Check if SlopLoss needs to be modified

   switch(cmd)
   {
   case OP_BUY:
      myPrice = MarketInfo(Symbol(), MODE_BID);
	   if (myPrice - sl < dblMinStopDistance)
	    
		mySL = myPrice - dblMinStopDistance;	// we are long
		break;
      
   case OP_SELL:
      myPrice = MarketInfo(Symbol(), MODE_ASK);
	   if (sl - myPrice < dblMinStopDistance) 
		mySL = myPrice + dblMinStopDistance;	// we are Short
      
      
   }
   return(NormalizeDouble(mySL,MarketInfo(Symbol(), MODE_DIGITS)));
  }



//+------------------------------------------------------------------+
//| 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                   |    
//+------------------------------------------------------------------+
int HandleTrailingStop(int type, int ticket, double op, double os, double tp)
{
    double pt, TS=0, myAsk, myBid;
    double bos,bop,opa,osa;
    
    switch(type)
    {
       case OP_BUY:
       {
		 myBid = MarketInfo(Symbol(),MODE_BID);
       switch(TrailingStopType)
       {
        case 1: pt = Point*StopLoss;
                if(myBid-os > pt)
                 ModifyOrder(type, ticket,op,myBid-pt,tp, Aqua);
                break;
        case 2: pt = Point*TrailingStop;
                if(myBid-op > pt && os < myBid - pt)
                 ModifyOrder(type, ticket,op,myBid-pt,tp, Aqua);
                break;
       }
       return(0);
       break;
       }
    case  OP_SELL:
    {
		myAsk = MarketInfo(Symbol(),MODE_ASK);
       switch(TrailingStopType)
       {
        case 1: pt = Point*StopLoss;
                if(os - myAsk > pt)
                 ModifyOrder(type, ticket,op,myAsk+pt,tp, Aqua);
                break;
        case 2: pt = Point*TrailingStop;
                if(op - myAsk > pt && os > myAsk+pt)
                 ModifyOrder(type, ticket,op,myAsk+pt,tp, Aqua);
                break;
                }
                
                
      }
     return(0);
    }
  } 
  







Sample





Analysis



Market Information Used:

Series array that contains the lowest prices of each bar
Series array that contains the highest prices of each bar
Series array that contains close prices for each bar
Series array that contains open prices of each bar


Indicator Curves created:


Indicators Used:



Custom Indicators Used:

Order Management characteristics:

Checks for the total of open orders
It automatically opens orders when conditions are reached
It can change open orders parameters, due to possible stepping strategy

Other Features:

BackTest : EURUSD on H1

From 2009-08-01 to 2009-10-01 Profit Factor:1.17 Total Net Profit:80.00

BackTest : EURUSD on H1

From 2009-12-01 to 2010-01-17 Profit Factor:1.07 Total Net Profit:40.00

BackTest : EURUSD on H1

From 2010-04-01 to 2010-04-30 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2010-05-01 to 2010-05-31 Profit Factor:0.00 Total Net Profit:0.00

BackTest : EURUSD on H1

From 2010-06-01 to 2010-06-30 Profit Factor:0.00 Total Net Profit:0.00

BackTest : GBPUSD on H1

From 2010-01-01 to 2010-02-27 Profit Factor:0.58 Total Net Profit:-254.00

BackTest : USDCAD on H1

From 2009-12-01 to 2010-01-01 Profit Factor:0.00 Total Net Profit:-454.48

BackTest : USDCHF on H1

From 2009-12-01 to 2010-01-01 Profit Factor:0.38 Total Net Profit:-293.29

BackTest : USDJPY on H1

From 2009-11-01 to 2009-11-30 Profit Factor:0.33 Total Net Profit:-180.53

Request Backtest for CandleStix


From : (yyyy/mm/dd) To: (yyyy/mm/dd)

Pair: Period: