Project Camarilla Bot needs your Help

 

Hi, I am making simple Expert Advisor Based on REVERSAL camarilla equation with only FOUR entry criteria, 2 for Buy and 2 for Sell.

A. Entry Point for Buy

     1. when Ask price crosses above L4

     2. when Ask price crosses above L3

B. Entry Point for Sell

     3. when Bid price crosses below H4

     4. when Bid price crosses below H3

Take Profit = None

Stop loss = 20 pips (Trailing)

Lot Size = 0.01 (Micro Account)

So far i have coded the below program, But its not working. Help me !

<Deleted>

//+------------------------------------------------------------------+
//|                                                      Cambot1.mq4 |
//|                                                    Vaibhav Tejas |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Vaibhav Tejas"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
input int StopLoss         = 0; // The default stop loss (0 disable)
double   Lots,
         Resistance4[],
         Resistance3[],

         Support3[],
         Support4[];
         
double   range;       

int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot = Lots;
   lot = NormalizeDouble((AccountFreeMargin()/5)/1000.0,1); // Calculate Lot size as a fifth of available free equity.
   if(lot<0.01) lot=0.01; //Ensure the minimal amount is 0.01 lots
   return(lot);
  }


void OnTick()
  {   

    
  }
//---
// Declare the variables to be used in getting the valuse for the lines
 int start()
 {
      int      ticket,total;
      double   ShortSL,LongSL;
      int      change_day_hour=0,
               counted_bars=IndicatorCounted(),
               number_of_bars_to_use   =  Bars - counted_bars,
               cnt=720;
            
      double   yesterday_high,
               yesterday_low,
               yesterday_close;
                                
      // Find out if there are enough Bars to perform a calculation
           if (counted_bars<0) return(-1);
      if (counted_bars>0) counted_bars--;

      // Bars in an internal value for the Number of bars in the current chart.

      //---- 
      for(int i=number_of_bars_to_use; i>=0; i--)
       {
             // Check to see if this record is the 1st of the day
            // then set the valuse for yesterday.
        
         if ( TimeHour(Time[i]) == change_day_hour && TimeMinute(Time[i]) == 0 )
                      
            {
              // Calculate yesterday's High, Low and Close
            
              yesterday_close=  Close[i + 1];
              yesterday_high =  iHigh(Symbol(),PERIOD_D1,1);
              yesterday_low  =  iLow(Symbol(),PERIOD_D1,1);
              range          =  yesterday_high - yesterday_low;
           
            } 
        
            //----- My Carmarilla Pivot Calculation =====> USED <=====       
        

            Resistance4[i] = yesterday_close + (range * 1.1 / 2);
            Resistance3[i] = yesterday_close + (range * 1.1 / 4);
        
            Support3[i] = yesterday_close - (range * 1.1 / 4);
            Support4[i] = yesterday_close - (range * 1.1 / 2);   
                                    
       } 
  
  
  
  // Check if there has been a cross on this tick from the two SMAs
  
  int isCrossedS3 = CheckForCross(Ask+2*Point, Support3[0]);
   {
     // Get the current total orders
     total = OrdersTotal();
    
     // Calculate Stop Loss and Take profit
     if(StopLoss > 0)
      {
        ShortSL = Bid+(StopLoss*Point);
        LongSL = Ask-(StopLoss*Point);
      }
  
      // Only open one trade at a time..
      if(total < 1)
        {
          // Buy - Long position
          if(isCrossedS3 == 1)
            {
              ticket = OrderSend(Symbol(), OP_BUY, LotsOptimized(),Ask,5, 0, 0, "Double SMA Crossover",0,0,Blue);
              if(ticket > 0)
                {
                 if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
                 Print("BUY Order Opened: ", OrderOpenPrice(), " SL:", LongSL, " TP: ", 0);
                }
                else
                Print("Error Opening BUY  Order: ", GetLastError());
                return(0);
            } 
        }         
      return(0);  
  }

  int isCrossedS4 = CheckForCross(Ask+2*Point, Support4[0]);
     {
       // Get the current total orders
       total = OrdersTotal();
  
       // Only open one trade at a time..
       if(total < 1)
        {
           // Buy - Long position
           if(isCrossedS4 == 1)
            {
              ticket = OrderSend(Symbol(), OP_BUY, LotsOptimized(),Ask,5, 0, 0, "Double SMA Crossover",0,0,Blue);
              if(ticket > 0)
                {
                 if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
                 Print("BUY Order Opened: ", OrderOpenPrice(), " SL:", LongSL, " TP: ", 0);
                }
                else
                Print("Error Opening BUY  Order: ", GetLastError());
                return(0);
            }   
        }
        return(0);
     }
      
  int isCrossedR3 = CheckForCross(Bid-2*Point, Resistance3[0]);   
      
      if(isCrossedR3 == 2)
       {
        ticket = OrderSend(Symbol(), OP_SELL, LotsOptimized(),Bid,5, ShortSL, 0, "Double SMA Crossover",0,0,Red);
        if(ticket > 0)
         {
          if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
          Print("SELL Order Opened: ", OrderOpenPrice(), " SL:", ShortSL, " TP: ", 0);
         }
        else
          Print("Error Opening SELL Order: ", GetLastError());
          return(0);
       }
      
  int isCrossedR4 = CheckForCross(Bid-2*Point, Resistance4[0]);   
      
      if(isCrossedR4 == 2)
       {
        ticket = OrderSend(Symbol(), OP_SELL, LotsOptimized(),Bid,5, ShortSL, 0, "Double SMA Crossover",0,0,Red);
        if(ticket > 0)
         {
          if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
          Print("SELL Order Opened: ", OrderOpenPrice(), " SL:", ShortSL, " TP: ", 0);
         }
        else
          Print("Error Opening SELL Order: ", GetLastError());
          return(0);
       }
      
      return(0);
 }
      

//+------------------------------------------------------------------+
//| Check for cross over of inputs                                      |
//+------------------------------------------------------------------+
int CheckForCross(double input1, double input2)
{
  static int previous_direction = 0;
  static int current_direction = 0;
 
  
  if(input1 > input2)            // Up Direction = 1
  {
    current_direction = 1;
  }
 
  
  if(input1 < input2)            // Down Direction = 2
  {
    current_direction = 2;
  }
 
  // Detect a direction change
  if(current_direction != previous_direction)
  {
    previous_direction = current_direction;
    return (previous_direction);
  } 
  else 
  {
    return (0);
  }
}



 
Please edit your post and use the code button (Alt+S) to paste code.
 
Vaibhav Tejas: But its not working. Help me !
  1. Please edit your (original) post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
              Messages Editor

  2. "Doesn't work" is meaningless — just like saying the car doesn't work. Doesn't start, won't go in gear, no electrical, missing the key, flat tires — meaningless.

    Help you with what? You haven't stated a problem. There are no mind readers here and our crystal balls are cracked.

  3. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?

  4.                counted_bars=IndicatorCounted(),
    
       if (counted_bars<0) return(-1);
    There are no buffers in EAs, no IndicatorCounted. Indicators can not trade.

  5.          Resistance4[],
    
             Resistance3[],
    ⋮
                Resistance4[i] = yesterday_close + (range * 1.1 / 2);
    How do you expect to store values into an empty array.

  6. void OnTick(){}
    //---
    // Declare the variables to be used in getting the valuse for the lines
     int start(){
    You should stop using the old event handlers and IndicatorCounted() and start using new event handlers. Do not use both.
              Event Handling Functions - MQL4 Reference
              How to do your lookbacks correctly - MQL4 programming forum #9-14 2016.05.11

 
Edit your original post.
 
William Roeder:
  1. Please edit your (original) post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
              Messages Editor

  2. "Doesn't work" is meaningless — just like saying the car doesn't work. Doesn't start, won't go in gear, no electrical, missing the key, flat tires — meaningless.

    Help you with what? You haven't stated a problem. There are no mind readers here and our crystal balls are cracked.

  3. Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?

  4. There are no buffers in EAs, no IndicatorCounted. Indicators can not trade.

  5. How do you expect to store values into an empty array.

  6. You should stop using the old event handlers and IndicatorCounted() and start using new event handlers. Do not use both.
              Event Handling Functions - MQL4 Reference
              How to do your lookbacks correctly - MQL4 programming forum #9-14 2016.05.11


I appreciate your help.

My knowledge to coding was in 2004 and that was to add two variable and print "hello world" after that nada. I love trading, previous month i got my hands on MT4 then i found EA. So jumped in and tried to make EA from modifying two sources.

1. Camarilla Indicator

2. Crossover of Two moving Averages.

// Source 2. Crossover of Two Moving Average

// Define our Parameters
input double Lots          = 0.1;
input int PeriodOne        = 40; // The period for the first SMA
input int PeriodTwo        = 100; // The period for the second SMA
input int TakeProfit       = 40; // The take profit level (0 disable)
input int StopLoss         = 0; // The default stop loss (0 disable)
//+------------------------------------------------------------------+
//| expert initialization functions                                  |
//+------------------------------------------------------------------+
int init()
{
  return(0);
}
int deinit()
{
  return(0);
}
//+------------------------------------------------------------------+
//| Check for cross over of SMA                                      |
//+------------------------------------------------------------------+
int CheckForCross(double input1, double input2)
{
  static int previous_direction = 0;
  static int current_direction  = 0;
 
  // Up Direction = 1
  if(input1 > input2){
    current_direction = 1;
  }
 
  // Down Direction = 2
  if(input1 < input2){
    current_direction = 2;
  }
 
  // Detect a direction change
  if(current_direction != previous_direction){
    previous_direction = current_direction;
    return (previous_direction);
  } else {
    return (0);
  }
}
 
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot = Lots;
   // Calculate Lot size as a fifth of available free equity.
   lot = NormalizeDouble((AccountFreeMargin()/5)/1000.0,1);
   if(lot<0.1) lot=0.1; //Ensure the minimal amount is 0.1 lots
   return(lot);
  }
 
 
//+------------------------------------------------------------------+
//+ Break Even                                                       |
//+------------------------------------------------------------------+
bool BreakEven(int MN){
  int Ticket;
 
  for(int i = OrdersTotal() - 1; i >= 0; i--) {
    OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
 
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == MN){
      Ticket = OrderModify(OrderTicket(), OrderOpenPrice(), OrderOpenPrice(), OrderTakeProfit(), 0, Green);
      if(Ticket < 0) Print("Error in Break Even : ", GetLastError());
        break;
      }
    }
 
  return(Ticket);
}
 
//+------------------------------------------------------------------+
//+ Run the algorithm                                               |
//+------------------------------------------------------------------+
int start()
{
  int cnt, ticket, total;
  double shortSma, longSma, ShortSL, ShortTP, LongSL, LongTP;
 
  // Parameter Sanity checking
  if(PeriodTwo < PeriodOne){
    Print("Please check settings, Period Two is lesser then the first period");
    return(0);
  }
 
  if(Bars < PeriodTwo){
    Print("Please check settings, less then the second period bars available for the long SMA");
    return(0);
  }
 
  // Calculate the SMAs from the iMA indicator in MODE_SMMA using the close price
  shortSma = iMA(NULL, 0, PeriodOne, 0, MODE_SMMA, PRICE_CLOSE, 0);
  longSma = iMA(NULL, 0, PeriodTwo, 0, MODE_SMMA, PRICE_CLOSE, 0);
 
  // Check if there has been a cross on this tick from the two SMAs
  int isCrossed = CheckForCross(shortSma, longSma);
 
  // Get the current total orders
  total = OrdersTotal();
 
  // Calculate Stop Loss and Take profit
  if(StopLoss > 0){
    ShortSL = Bid+(StopLoss*Point);
    LongSL = Ask-(StopLoss*Point);
  }
  if(TakeProfit > 0){
    ShortTP = Bid-(TakeProfit*Point);
    LongTP = Ask+(TakeProfit*Point);
  }
 
  // Only open one trade at a time..
  if(total < 1){
    // Buy - Long position
    if(isCrossed == 1){
        ticket = OrderSend(Symbol(), OP_BUY, LotsOptimized(),Ask,5, LongSL, LongTP, "Double SMA Crossover",MAGICNUM,0,Blue);
        if(ticket > 0){
          if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
            Print("BUY Order Opened: ", OrderOpenPrice(), " SL:", LongSL, " TP: ", LongTP);
          }
          else
            Print("Error Opening BUY  Order: ", GetLastError());
            return(0);
        }
    // Sell - Short position
    if(isCrossed == 2){
      ticket = OrderSend(Symbol(), OP_SELL, LotsOptimized(),Bid,5, ShortSL, ShortTP, "Double SMA Crossover",MAGICNUM,0,Red);
      if(ticket > 0){
        if(OrderSelect(ticket, SELECT_BY_TICKET, MODE_TRADES))
          Print("SELL Order Opened: ", OrderOpenPrice(), " SL:", ShortSL, " TP: ", ShortTP);
        }
        else
          Print("Error Opening SELL Order: ", GetLastError());
          return(0);
      }
    }
 
  // Manage open orders for exit criteria
  for(cnt = 0; cnt < total; cnt++){
    OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
    if(OrderType() <= OP_SELL && OrderSymbol() == Symbol()){
      // Look for long positions
      if(OrderType() == OP_BUY){
        // Check for Exit criteria on buy - change of direction
        if(isCrossed == 2){
          OrderClose(OrderTicket(), OrderLots(), Bid, 3, Violet); // Close the position
          return(0);
        }
      }
      else //Look for short positions - inverse of prior conditions
      {
        // Check for Exit criteria on sell - change of direction
        if(isCrossed == 1){
          OrderClose(OrderTicket(), OrderLots(), Ask, 3, Violet); // Close the position
          return(0);
        }
      }
      // If we are in a loss - Try to BreakEven
      Print("Current Unrealized Profit on Order: ", OrderProfit());
      if(OrderProfit() < 0){
        BreakEven(MAGICNUM);
      }
    }
 
  }
 
  return(0);
}
// Source 1. Camarilla Indicator

#property indicator_chart_window

#property indicator_buffers 9

// Establish the Colors for the Pivot lines

// Color1 is for the Pivot Point Line
#property indicator_color1 Yellow 

// Colors 1 through 4 are for the Resistance Lines
#property indicator_color2 Red
#property indicator_color3 Red
#property indicator_color4 Red
#property indicator_color5 Red

// Colors 5 through 9 are for the Support Lines
#property indicator_color6 Aqua
#property indicator_color7 Aqua
#property indicator_color8 Aqua
#property indicator_color9 Aqua


// Set Buffers

double   Resistance4[],
         Resistance3[],
         Resistance2[],
         Resistance1[],
         
         PivotPoint[],

         Support1[],
         Support2[],
         Support3[],
         Support4[];
         
double   range;         
/*
string   Res4,
         Res3,
         Res2,
         Res1,
         
         Pivot,
         
         Sup1,
         Sup2,
         Sup3,
         Sup4;
*/         
int      WhichWindow=0,
         WhatTime=0, 
         WhatPrice=0;        

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+

int init()
  {

   // Set up the Pivot Lines
   // Resistance Lines

   SetIndexStyle(1,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(1,Resistance4);
   SetIndexStyle(2,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(2,Resistance3);
   SetIndexStyle(3,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(3,Resistance2);
   SetIndexStyle(4,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(4,Resistance1);
   
   // Camarilla Pivot Point Line
   
   SetIndexStyle(0,DRAW_LINE,STYLE_SOLID,2);
   SetIndexBuffer(0,PivotPoint);
   
   // Support Lines
   
   SetIndexStyle(5,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(5,Support1);
   SetIndexStyle(6,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(6,Support2);
   SetIndexStyle(7,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(7,Support3);
   SetIndexStyle(8,DRAW_LINE,STYLE_SOLID,1);
   SetIndexBuffer(8,Support4);

   return(0);
  }

//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+

int deinit()
  {
  
      ObjectsRedraw();
   
   return(0);
  }

//+------------------------------------------------------------------+
//| Camarilla Level Indicator Iteration Function                              |
//+------------------------------------------------------------------+

int start()
{
   // Declare the variables to be used in getting the valuse for the lines

   int      change_day_hour=0,
            counted_bars=IndicatorCounted(),
            number_of_bars_to_use   =  Bars - counted_bars,
            cnt=720;
            
   double   yesterday_high,
            yesterday_low,
            yesterday_close;
                                
// Find out if there are enough Bars to perform a calculation
        if (counted_bars<0) return(-1);
   if (counted_bars>0) counted_bars--;

// Bars in an internal value for the Number of bars in the current chart.

//---- 
   for(int i=number_of_bars_to_use; i>=0; i--)
      {

        
      if    (
            // Check to see if this record is the 1st of the day
            // then set the valuse for yesterday.
            
            TimeHour(Time[i]) == change_day_hour &&
            TimeMinute(Time[i]) == 0
            )
                      
            {
            // Calculate yesterday's High, Low and Close
            
            yesterday_close=  Close[i + 1];
            yesterday_high =  iHigh(Symbol(),PERIOD_D1,1);
            yesterday_low  =  iLow(Symbol(),PERIOD_D1,1);
            range          =  yesterday_high - yesterday_low;
           
            } // if
            
            //Comment(" ");
            /*Comment("Current bar for ", Symbol(), "Open : ",  iOpen(Symbol(),PERIOD_D1,1),", High : ",
                                      iHigh(Symbol(),PERIOD_D1,1),", Low : ",  iLow(Symbol(),PERIOD_D1,1),", Close : ",
                                      iClose(Symbol(),PERIOD_D1,1),", ", iVolume(Symbol(),PERIOD_D1,1));*/


        
        
        //----- Standard Pivot Calculation =====> NOT USED <=====
        //----- P[] = (yesterday_high + yesterday_low + yesterday_close)/3; 

        Resistance4[i] = yesterday_close + (range * 1.1 / 2);
        Resistance3[i] = yesterday_close + (range * 1.1 / 4);
        Resistance2[i] = yesterday_close + (range * 1.1 / 6);
        Resistance1[i] = yesterday_close + (range * 1.1 / 12);

        Support1[i] = yesterday_close - (range * 1.1 / 12);
        Support2[i] = yesterday_close - (range * 1.1 / 6);
        Support3[i] = yesterday_close - (range * 1.1 / 4);
        Support4[i] = yesterday_close - (range * 1.1 / 2);
        
        //----- My Carmarilla Pivot Calculation =====> USED <=====
        
        PivotPoint[i] = (Resistance1[i] + Support1[i]) / 2;
                
      } // if

      return(0);

} // start()
 //+------------------------------------------------------------------+
Reason: