es_capelast_reversed_ECN_v1.04

Orders Execution
Checks for the total of open ordersIt automatically opens orders when conditions are reachedIt can change open orders parameters, due to possible stepping strategyIt Closes Orders by itself
Miscellaneous
It opens Message Boxes to the userIt plays sound alertsIt issuies visual alerts to the screen
0 Views
0 Downloads
0 Favorites

Profitability Reports

AUD/USD Oct 2024 - Jan 2025
73.00 %
Total Trades 267
Won Trades 0
Lost trades 0
Win Rate 0.00 %
Expected payoff -7.01
Gross Profit 5114.60
Gross Loss -6985.20
Total Net Profit -1870.60
-100%
-50%
0%
50%
100%
es_capelast_reversed_ECN_v1.04
//+------------------------------------------------------------------+
//|                               es_capelast_reversed_ECN_v1.04.mq4 |
//|                                    Copyright © 2009, OGUZ BAYRAM |
//|                                            es_cape77@hotmail.com |
//+------------------------------------------------------------------+

#include <WinUser32.mqh>

extern int YourAccountNumber = 123456;
extern double lTakeProfit = 10.0;
extern double sTakeProfit = 10.0;
extern double lStopLoss = 2000.0;
extern double sStopLoss = 2000.0;
extern string gs_addSpread = "Add spread to profit target? T/F";
extern bool gb_addSpread = FALSE;
extern int max_num_orders = 100;
extern int max_orders_per_symbol = 10;
extern int max_num_buys_per_symbol = 5;

extern string stagger_settings = "Stagger Settings (-2)Use Spread (-1)Auto";
extern bool stagger_trades = TRUE;
extern double buy_stagger = -1; //Automatic
extern double sell_stagger = -1; //Automatic

extern string gsTimeFilter="------Time Filter Parameters-----";
extern bool TradeOnSunday=true;//|---------------time filter on sunday
extern bool MondayToThursdayTimeFilter=false;//|-time filter the week
extern int MondayToThursdayStartHour=0;//|-------start hour time filter the week
extern int MondayToThursdayEndHour=24;//|--------end hour time filter the week
extern bool FridayTimeFilter=false;//|-----------time filter on friday
extern int FridayStartHour=0;//|-----------------start hour time filter on friday
extern int FridayEndHour=21;//|------------------end hour time filter on friday
extern bool close_all_trades=FALSE;//|-----------close all open trades ouside of filtered times
extern string gsTimeFilterEnd="--End of Time Filter Parameters--";

extern color clOpenBuy = Green;
extern color clOpenSell = Red;
extern string Name_Expert = "es_capelast_reversed_ECN_v1.04";
extern int magic_number = 789667;
extern int Slippage = 1;
extern bool UseSound = FALSE;
extern string NameFileSound = "Alert.wav";
extern double Lots = 0.2;
extern bool reverseLogic = FALSE;

// Global Variables --------------------

int gi_ticket_number;
double gd_pipValue; //Real pip value for the chart, 0.0001 or 0.01
double gd_digit;
bool gb_accountVerified = FALSE;
bool gb_okToBuy = FALSE; // Set TRUE when number of buy orders < max_num_buys_per_symbol
bool gb_okToSell = FALSE; // Set TRUE when number of sell orders < max_orders_per_symbol-max_num_buys_per_symbol

// End Global Variables ----------------

int init(){
   //Rudimentary check for broker trade conditions
   int li_stoplevel = GetStopLevel();
   if ((lTakeProfit < li_stoplevel) ||
         (sTakeProfit < li_stoplevel) ||
         (lStopLoss < li_stoplevel) ||
         (sStopLoss < li_stoplevel)){
         MessageBox("Failed to initialize because profit or stop set too tight.\n Broker minimum is " + li_stoplevel + " pips. Now closing the ea.");
         //Shut down the ea
         PostMessageA( WindowHandle( Symbol(), Period()), WM_COMMAND, 33050, 0);
         return(0);
   }
   
   //Very basic logic check regarding number of ordrers
   if (max_num_buys_per_symbol>max_orders_per_symbol){
         MessageBox("Failed to initialize because maximun buys per symbol.\n is greater than the maximum orders per symbol. Now closing the ea.");
         //Shut down the ea
         PostMessageA( WindowHandle( Symbol(), Period()), WM_COMMAND, 33050, 0);
         return(0);
   }
   if (max_orders_per_symbol>max_num_orders){
         MessageBox("Failed to initialize because maximun orders per symbol.\n is greater than the total number of maximum orders. Now closing the ea.");
         //Shut down the ea
         PostMessageA( WindowHandle( Symbol(), Period()), WM_COMMAND, 33050, 0);
         return(0);
   }
   
   //Account check
   if (IsDemo() == TRUE){
      gb_accountVerified = TRUE;
      Comment(Name_Expert + " trading on DEMO account");
   }
   else { //real trading Account
      gb_accountVerified = CheckAccountNumber();
      if (gb_accountVerified == FALSE) return (0);
      Comment(Name_Expert + " trading on LIVE account");
   }
   //Fix for decimal brokers (5 digit)
   gd_pipValue = GetRealPipValue();
   gd_digit = SetDigit();
   if (Digits==5 || Digits==3)
      Slippage *= 10;
}
void deinit() {
   Comment("");
}

int start() {
   if (IsTradeAllowed() == FALSE) return (0);
   
   if (Bars < 100) {
      Print("bars less than 100");
      return (0);
   }
   if (lTakeProfit < 1.0) {
      Print("TakeProfit less than 1");
      return (0);
   }
   if (sTakeProfit < 1.0) {
      Print("TakeProfit less than 1");
      return (0);
   }
   double diClose0 = iClose(NULL, PERIOD_M5, 0);
   double diMA1 = iMA(NULL, PERIOD_M5, 5, 0, MODE_EMA, PRICE_OPEN, 1);
   double diClose2 = iClose(NULL, PERIOD_M5, 0);
   double diMA3 = iMA(NULL, PERIOD_M5, 4, 0, MODE_EMA, PRICE_OPEN, 1);
   if (AccountFreeMargin() < 1000.0 * Lots) {
      Print("We have no money. Free Margin = ", AccountFreeMargin());
      return (0);
   }
   if (!TimeFilterOK()) {
         if (close_all_trades)
            CloseAllTrades();
      return(0);
   }
   
   double buyStaggerAmount = 0.0; 
   double sellStaggerAmount = 0.0;
   if (stagger_trades) {
      buyStaggerAmount = GetStaggerAmount(buy_stagger, lTakeProfit, max_num_buys_per_symbol);
      sellStaggerAmount = GetStaggerAmount(sell_stagger, sTakeProfit, (max_orders_per_symbol-max_num_buys_per_symbol));
   }
   
   GetBuySellStatus(buyStaggerAmount, sellStaggerAmount); //Set okToBuy and okToSell Flags

   // Everything is ready to go for a trade
   if (!ExistPositions()) {
      if (diClose0 < diMA1) {
         if (reverseLogic) {
            if (gb_okToSell) OpenSell();}
         else {
            if (gb_okToBuy) OpenBuy();}
         return (0);
      }
      if (diClose2 > diMA3) {
         if (reverseLogic) {
            if (gb_okToBuy) OpenBuy();}
         else {
            if (gb_okToSell) OpenSell();}
         return (0);
      }
   }
   return (0);
}

// Check for free order slots
bool ExistPositions() {
   if ((OrdersTotal() >= max_num_orders ) || (OrderCount() >= max_orders_per_symbol))
      return (TRUE);
   else
      return (FALSE); 
}

//Count orders on current chart symbol 
int OrderCount () {
   int count=0;
   for (int j=0; j<OrdersTotal(); j++) {
      if (OrderSelect(j, SELECT_BY_POS, MODE_TRADES))
         if (OrderSymbol() == Symbol()) count++;
   }
   return (count);
}

//Determine if there are any buy or sell orders that can be filled
//and set the global flags gb_okToBuy and gb_okToSell
void GetBuySellStatus(double ld_buyStaggerAmount, double ld_sellStaggerAmount) {
   int currentNumberBuyOrders = 0;
   int currentNumberSellOrders = 0;
   bool lb_buyStaggerOK = TRUE; // buy stagger condition met switch
   bool lb_sellStaggerOK = TRUE; // sell stagger condition met switch
   for (int k=0; k<OrdersTotal(); k++) {
      if (OrderSelect(k, SELECT_BY_POS, MODE_TRADES))
         if (OrderSymbol() == Symbol()) {
            if (OrderType()==OP_BUY) {
               currentNumberBuyOrders++;
               //check old order price is outside of stagger range
               if (lb_buyStaggerOK&&stagger_trades)
                  lb_buyStaggerOK = PriceOutsideStaggerRange(OrderOpenPrice(), ld_buyStaggerAmount, OP_BUY);
               }
            else {
               currentNumberSellOrders++;
               //check old order price is outside of stagger range
               if (lb_sellStaggerOK&&stagger_trades)
                  lb_sellStaggerOK = PriceOutsideStaggerRange(OrderOpenPrice(), ld_sellStaggerAmount, OP_SELL);
               }
         }
   }

// Now set the global flags based on number of buy and sell orders found
   gb_okToBuy = SetBuySellFlags(currentNumberBuyOrders, max_num_buys_per_symbol);
   gb_okToSell = SetBuySellFlags(currentNumberSellOrders, (max_orders_per_symbol - max_num_buys_per_symbol));

   // and finally...set buy/sell state depending on the stagger conditions
   // Can simplify: gb_okToBuy&&lb_buyStaggerOK ||(gb_okToBuy&&(!stagger_trades));
   //           to: gb_okToBuy&&(lb_buyStaggerOK||(!stagger_trades));
   //      Because: A.B+B.C = A.(B+C)
   if (currentNumberBuyOrders==0)
      gb_okToBuy = TRUE;
   else
      gb_okToBuy = gb_okToBuy&&(lb_buyStaggerOK||(!stagger_trades));
   if (currentNumberSellOrders==0)
      gb_okToSell = TRUE;
   else
      gb_okToSell = gb_okToSell&&(lb_sellStaggerOK||(!stagger_trades));
}

bool PriceOutsideStaggerRange(double orderPriceOpen, double ld_stagger, int position) {
   // Ask for buying
   // Bid fpr selling
   //Print("Stagger is: ", DoubleToStr(ld_stagger, Digits));
   if (position == OP_BUY) {
      if ((Ask>orderPriceOpen+ld_stagger) || (Ask<orderPriceOpen-ld_stagger)) //price +/- stagger
        return (TRUE);}
   else { // position == OP_SELL
     if ((Bid>orderPriceOpen+ld_stagger) || (Bid<orderPriceOpen-ld_stagger)) //price +/- stagger
        return (TRUE);}
   // if within stagger range
   return (FALSE);
}

// used to set global flags gb_okToBuy & gb_okToSell
bool SetBuySellFlags(int currentNumOrders, int maxNumOrders) {
   if (currentNumOrders < maxNumOrders)
      return (TRUE);
   else
      return (FALSE);   
}

void OpenBuy() {
   double ldLot = GetSizeLot();
   double ldStop = GetStopLossBuy();
   double ldTake = GetTakeProfitBuy();
   string lsComm = GetCommentForOrder();
   gi_ticket_number = OrderSend(Symbol(), OP_BUY, ldLot, Ask, Slippage, 0, 0, Name_Expert, magic_number, 0, clOpenBuy);
   OrderSelect(gi_ticket_number, SELECT_BY_TICKET);
   OrderModify(OrderTicket(), OrderOpenPrice(), ldStop, ldTake, 0, Blue);
   if (UseSound) PlaySound(NameFileSound);
}

void OpenSell() {
   double ldLot = GetSizeLot();
   double ldStop = GetStopLossSell();
   double ldTake = GetTakeProfitSell();
   string lsComm = GetCommentForOrder();
   gi_ticket_number = OrderSend(Symbol(), OP_SELL, ldLot, Bid, Slippage, 0, 0, Name_Expert, magic_number, 0, clOpenSell);
   OrderSelect(gi_ticket_number, SELECT_BY_TICKET);
   OrderModify(OrderTicket(), OrderOpenPrice(), ldStop, ldTake, 0, Red);
   if (UseSound) PlaySound(NameFileSound);
}

string GetCommentForOrder() {
   return (Name_Expert);
}

double GetSizeLot() {
   return (Lots);
}

double GetRealPipValue() {
   double ld_pipValue;
   if (Digits < 4) ld_pipValue = 0.01;
   else ld_pipValue = 0.0001;
   return (ld_pipValue);
}

double GetStaggerAmount(double setting, int profit_target, int max_num_orders) {
   if (setting < -1) // use spread
      return (gd_pipValue*GetSpread());
   else {if (setting < 0) //use auto
      return (NormalizeDouble(gd_pipValue*(profit_target/max_num_orders), Digits));}
 
   return (gd_pipValue*setting);
}

double GetSpread() {
   double spread = MarketInfo(Symbol(), MODE_SPREAD);
   if (Digits==5 || Digits==3)
      spread /= 10;
   return (spread);
}

double SetDigit() {
   double ld_digit;
   if (Digits < 4) ld_digit = 2;
   else ld_digit = 4;
   return (ld_digit);
}

double GetStopLevel() {
   //get stop level from broker in pips
   double ld_stopLevel;
   ld_stopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
   if (Digits == 3 || Digits == 5) ld_stopLevel /= 10;
   return (ld_stopLevel);
}

double GetTakeProfitBuy() {
   double ld_takeProfit = Ask + lTakeProfit * gd_pipValue;
   //take into account the spread if required
   if (gb_addSpread) ld_takeProfit += (gd_pipValue*MarketInfo(Symbol(), MODE_SPREAD));
   ld_takeProfit = NormalizeDouble(ld_takeProfit, gd_digit);
   return (ld_takeProfit);
}

double GetTakeProfitSell() {
   double ld_takeProfit = Bid - sTakeProfit * gd_pipValue;
   //take into account the spread if required
   if (gb_addSpread) ld_takeProfit -= (gd_pipValue*MarketInfo(Symbol(), MODE_SPREAD));
   ld_takeProfit = NormalizeDouble(ld_takeProfit, gd_digit);
   return (ld_takeProfit);
}

double GetStopLossBuy() {
   return (NormalizeDouble((Bid - lStopLoss * gd_pipValue), gd_digit));
}

double GetStopLossSell() {
   return (NormalizeDouble((Ask + sStopLoss * gd_pipValue), gd_digit));
}

bool CheckAccountNumber() {
   if (YourAccountNumber == AccountNumber()) return (TRUE);
   Alert("AccountNumber entered is incorrect.\n You entered ", YourAccountNumber);
   return (FALSE);
}

//|---------time filter
bool TimeFilterOK() {
   if((TradeOnSunday==false&&DayOfWeek()==0)||
      (MondayToThursdayTimeFilter&&DayOfWeek()>=0 &&
         DayOfWeek()<=4 &&
         !(Hour()>=MondayToThursdayStartHour &&
         Hour()<MondayToThursdayEndHour)) ||
      (FridayTimeFilter&&DayOfWeek()==5 &&
         !(Hour()>=FridayStartHour &&
         Hour()<FridayEndHour)))
      return(FALSE);
   else
      return(TRUE);
}

void CloseAllTrades() {
   bool   result;
   double price;
   int    cmd,error,total;
//----
  total = OrdersTotal();
  for(int i=total-1;i>=0;i--)
  {
   if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
      if (magic_number == OrderMagicNumber()) { //Only close trade made by ea
         cmd=OrderType();
         if(OrderSymbol()==Symbol()){
            while(true){
               if(cmd==OP_BUY) price=Bid;
               else            price=Ask;
               result=OrderClose(OrderTicket(),OrderLots(),price,3,CLR_NONE);
               if(result!=TRUE) { error=GetLastError(); Print("LastError = ",error); }
               else error=0;
               if(error==135) RefreshRates();
               else break;
            }
         }
      }
   }
   else Print( "Error when order select ", GetLastError());
  }
//----
   return(0);
  }
//+------------------------------------------------------------------+


Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---