How to code an EA to open trade based on specific time?

I have created my own EA at free ea building site but I want it to open trade during 1800 ~ 0800 time.
Time is based on broker provided on my mt4. Someone please help me :51:

Use the Hour() function to find the current time (broker) and compare that to your hour range. If outside the range return and do nothing. Don’t try figuring out the current time because then you have to account for minutes and seconds, thats too messy.

Omg, I dont know how to do this :frowning:
I need someone to edit my ea for time function…

Hi eLis6375

Add this to your variables.

extern bool UseTimer = true; // Use start & end times in Hours
extern int StartTime = 8; // Start hour of Trading day
extern int EndTime = 18; // End hour of Trading day

datetime CurrentTime;

Then add this code before any Buy or Sell code .

// Trading hours
if(UseTimer == true)
{
CurrentTime = TimeLocal();

int GetWeekday = TimeDayOfWeek(CurrentTime);
int GetHour = TimeHour(CurrentTime);
int GetMinute = TimeMinute(CurrentTime);

if(GetHour > StartTime && GetHour < EndTime && GetWeekday <6)
{
bool TradeAllowed = true;

 }
 else TradeAllowed = false;
 }
 else TradeAllowed = true;

Then in your Buy or Sell code add “&& TradeAllowed == true”

So if you had
// Buy trade
if(FastMA > SlowMA) If this was your entry signal code then you now need.

if(FastMA>SlowMA && TradeAllowed == true)

Thats it.

Now go to Amazon and get the book “Expert Advisor Programming” by Andrew R Young.

Regards Trader009.

Hello,

I am just adding to this thread since I used part of this code to implement trading hours. These lines above also present settings to decide what days your EA should be trading (i.e., int GetWeekday = TimeDayOfWeek(CurrentTime) ).

I stared my EA just a bit before 11 pm GMT on a sunday. There was a signal (according to my EA) but the EA did not take any trade until the midnight.

Now, I am not so familiar with the TimeDayOfweek function but apparently it codes integers a days of the week starting from zero which is sunday. I thought that the line << if(GetHour > StartTime && GetHour < EndTime && GetWeekday <6) >> would have made the EA trade starting from sunday night, but maybe I am not seeing something obvious. I m reasoning that if <6 this should mean to trade all days but not saturday.

Please find below my EA code:

//±-----------------------------------------------------------------+
//| Triple-MA-Crossover - Massi .mq4 |
//| |
//| |
//±-----------------------------------------------------------------+
#property copyright “Dr. Massimiliano Papera”

extern int magicNumber = 1111;
extern double lots = 0.5;
extern int MAFastPeriod = 8;
extern int MAMediumPeriod = 100;
extern int MASlowPeriod = 400;
extern bool UseTimeServer = true; // Use start & end times in Hours and Minutes HH:MM
extern string TradeStartTime = “1:05”;
extern string TradeStopTime = “22:50”;
//extern bool trail = True;
//extern double TrailingStop = 1000;
//extern int takeProfit = 0;
extern int stopLoss = 1500;

//extern int StartTime = 1:05; // Start hour of Trading day
//extern int EndTime = 22:50; // End hour of Trading day

datetime CurrentTime;

int slippage = 3;
double takeProfit = 0;
//double stopLoss = 0;
int ticket;
int counter;
bool openOrder;
bool buySignal;
bool sellSignal;

//place before init, or after the code at the bottom
//{
//for (int i = 0; i < OrdersTotal(); i++) {
//OrderSelect(i, SELECT_BY_POS, MODE_TRADES);

//if ( OrderSymbol()==Symbol() )
//{
//if (OrderType() == OP_BUY) {
//if (Bid - OrderOpenPrice() > TrailingStop * MarketInfo(OrderSymbol(), MODE_POINT)) {
//if (OrderStopLoss() < Bid - TrailingStop * MarketInfo(OrderSymbol(), MODE_POINT)) {
//OrderModify(OrderTicket(), OrderOpenPrice(), Bid - TrailingStop * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
//}
//}
//} else if (OrderType() == OP_SELL) {
//if (OrderOpenPrice() - Ask > TrailingStop * MarketInfo(OrderSymbol(), MODE_POINT)) {
//if ((OrderStopLoss() > Ask + TrailingStop * MarketInfo(OrderSymbol(), MODE_POINT)) ||
//(OrderStopLoss() == 0)) {
//OrderModify(OrderTicket(), OrderOpenPrice(),
//Ask + TrailingStop * MarketInfo(OrderSymbol(), MODE_POINT), OrderTakeProfit(), Red);
//}
//}
//}
//}
//}
//}

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

openOrder = false;
generateSignals();

//monitor open trades
for(counter=0;counter<OrdersTotal();counter++)
{
OrderSelect(counter, SELECT_BY_POS, MODE_TRADES);
if (OrderMagicNumber() == magicNumber)
{
openOrder = true;
if (OrderType() == OP_BUY && !buySignal)
{
closeBuyTrade();
openOrder = false;
}
else if (OrderType() == OP_SELL && !sellSignal)
{
closeSellTrade();
openOrder = false;
}
}
}

//if there are no open orders, check for a signal
if (!openOrder)
{
if (buySignal)
placeBuy();
else if (sellSignal)
placeSell();
}
return(0);
}

//±-----------------------------------------------------------------+
//| place BUY trade |
//±-----------------------------------------------------------------+
void placeBuy()
{
RefreshRates();
ticket=OrderSend(Symbol(),OP_BUY,lots,Ask,slippage,Ask-(stopLossPoint),takeProfit,“buy Triple-MA-Crossover EA MP”,magicNumber,0,Green);
if(ticket<0)
{
Print(“BUY failed with error #”,GetLastError()," at ",Ask);
return;
}
}
//±-----------------------------------------------------------------+
//| place SELL trade |
//±-----------------------------------------------------------------+
void placeSell()
{
RefreshRates();
ticket=OrderSend(Symbol(),OP_SELL,lots,Bid,slippage,Bid+(stopLoss
Point),takeProfit,“sell Triple-MA-Crossover EA MP”,magicNumber,0,Red);
if(ticket<0)
{
Print(“SELL failed with error #”,GetLastError()," at ",Bid);
return;
}
}
//±-----------------------------------------------------------------+
//| generate a buy or sell signal
//±-----------------------------------------------------------------+

void generateSignals()
{
// Trading hours

if(UseTimeServer == true)
{
CurrentTime = TimeCurrent();

int GetWeekday = TimeDayOfWeek(CurrentTime);
//int GetHour = TimeHour(CurrentTime);
//int GetMinute = TimeMinute(CurrentTime);

if(CurrentTime>StrToTime(TradeStartTime) && CurrentTime<StrToTime(TradeStopTime) && GetWeekday <6)

// if(GetHour > StartTime && GetHour < EndTime && GetWeekday <6)
{
bool TradeAllowed = true;

}
else TradeAllowed = false;
}
else TradeAllowed = true;

buySignal = false;
sellSignal = false;

if (iMA(NULL,0,MAFastPeriod,0,MODE_EMA,PRICE_CLOSE,1) > iMA(NULL,0,MAMediumPeriod,0,MODE_EMA,PRICE_CLOSE,1) &&
iMA(NULL,0,MAFastPeriod,0,MODE_EMA,PRICE_CLOSE,1) > iMA(NULL,0,MASlowPeriod,0,MODE_EMA,PRICE_CLOSE,1) && TradeAllowed == true)
buySignal = true;

if (iMA(NULL,0,MAFastPeriod,0,MODE_EMA,PRICE_CLOSE,1) < iMA(NULL,0,MAMediumPeriod,0,MODE_EMA,PRICE_CLOSE,1) &&
iMA(NULL,0,MAFastPeriod,0,MODE_EMA,PRICE_CLOSE,1) < iMA(NULL,0,MASlowPeriod,0,MODE_EMA,PRICE_CLOSE,1)&& TradeAllowed == true)
sellSignal = true;

//if (trail) trail();
}
//±-----------------------------------------------------------------+
//| close BUY trade
//±-----------------------------------------------------------------+
void closeBuyTrade()
{
RefreshRates();
OrderClose(OrderTicket(),OrderLots(),Bid,slippage,Green);
}
//±-----------------------------------------------------------------+
//| close SELL trade
//±-----------------------------------------------------------------+
void closeSellTrade()
{
RefreshRates();
OrderClose(OrderTicket(),OrderLots(),Ask,slippage,Red);
}

Hi notradingzone,

I don’t use BabyPips any more as I have moved on, so can’t be your friend.

Your 11:00 problem. If you look in the journal you will probably see something like “market is closed” which is why your EA failed to trade. Clearly the market is not closed and I have had this on most days of the week. I have found a work around for the problem and that is not to trade at 23:00.
I think the problem is Broker server overload or changer time at end of day.

Here is the filter to avoid trading at 23:00, but waiting until just after to make the trade.
if(Hour()==23 && Minute()==0)Sleep(90000); // This adds a 1.5 min delay so you trade at 23:01:30

I have this code in all my EA’s as standard.

Hope this helps.