Please any coder in the house I need help. I developed an expert advisor using CCI and moving average filter it’s working and taking trades but I have a very big major issue. The EA takes trade ok every new candle let’s say for example you attach it to the 1H timeframe it takes trade on every new hour. Normally it’s supposed to take trade when it sees an entry condition and take only one trade per time until the exit condition appears then it closes the trade. If anyone can help me here I will greatly appreciate
Hello johnsamy,
you need a flag. For example bool isTraded ; When of an position assign the variable isTraded = true;
in the conditions for openning position you should check for this variable. For example:
if(!isTraded)
{ // condition for opening position
}
When close trade or when you check if there is any open traded -> set the variable on false : isTraded = false;
//±-----------------------------------------------------------------+
//| vfx_demo.mq4 |
//| obj emmanuel |
//| |
//±-----------------------------------------------------------------+
#property copyright “obj Emmanuel”
#property version “1.05”
int _Sell = -1;
int _Buy = 1;
input int MovingPeriod =12;
input int MovingShift =0;
input int CciPeriod =14;
extern int TakeProfit = 250;
extern int StopLoss = 150;
input double Lots = 1;
int nMagic = 369853;
int LastOpenTime = 0;
int OnInit(){
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason) {
}
void OnTick()
{
int signal = signal_cci();
if (!CheckFilters(signal) && isUseFilters) return;
if (isTradeAllowed()){
if(signal== _Buy) {
buy();
}
if(signal== _Sell){
sell();
}
}
}
int signal_cci() { // ---------------------------------- CCI crossing 100 level - buy; crossing -100 level - sell
double x1,x2;
x1 = iCCI(Symbol(),_Period,14,PRICE_TYPICAL,0);
x2 = iCCI(Symbol(),_Period,14,PRICE_TYPICAL,1);
if(x1<0) return _Sell;
if(x2>0) return _Buy;
return 0;
}
extern bool isUseFilters = true;
int CheckFilters (int signal) { //true - you can trade
if(signal==_Buy) {
return iMA(NULL,0,MovingPeriod,MovingShift,MODE_EMA,PRICE_TYPICAL,0); }
if(signal==_Sell) {
return iMA(NULL,0,MovingPeriod,MovingShift,MODE_EMA,PRICE_TYPICAL,0); }
return true;
}
//--------------------------------isTradenAllowed--------------------------------
bool isTradeAllowed() {
if (LastOpenTime>=Time[0] - Period()*60) return false; // Do not open order twice on the same bar
return true;
}
bool sell() {//------------------------------sell----------------------------------
string comment ="";
int ticket = OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Bid+StopLossPoint,Bid-TakeProfitPoint,comment,nMagic);
if(ticket<0){
printf("Open SELL order error (%i) | Ask = %g, sl=%g, tp=%g",
GetLastError(),Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point);
return false;
} else {
LastOpenTime = Time[0];
}
return true;
}
bool buy( ){ // ---------------------------buy--------------------------------------
string comment = “”;
int ticket = OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLossPoint,Ask+TakeProfitPoint,comment,nMagic);
if(ticket<0) {
printf("Open BUY order error(%i) | Ask = %i, sl=%g, tp=%g",
GetLastError(),Ask,Ask-StopLoss*Point,Ask+TakeProfit*Point);
return false;
} else {
LastOpenTime = Time[0];
}
return true;
}
This is the code thanks
The problem is here .
When open an position you set the variable on current time ( LastOpenTime = Time[0])
When new bar is open LastOpenTime will be previos bar so it will be ( LastOpenTime = Time[1] ).
Time[0] - Period()*60 -> is previos bar so the calculation is Time[1] . And LastOpenTime(Time[1]) >= Time[1]. So it always will be true.
I recommend you to loop the open positions if there is no open positions then to open . Not to check the time.
Please how can I do it can you please help still new to programming thanks a lot
Hello,
This is short version of the structure i write for every EA.
#define SIGNAL_NONE 0
#define SIGNAL_BUY 1
#define SIGNAL_SELL 2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4
extern int MagicNumber = 123;
int Ticket;
…
// inialize variables
/* For example
cciValue = iCCI( … );
*/
bool IsTrade = False;
for (int i = 0; i < Total; i ++) {
Ticket = OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
if(OrderType() <= OP_SELL && OrderSymbol() == Symbol() && OrderMagicNumber() == magicNumber ) {
IsTrade = True;
if(OrderType() == OP_BUY) {
/* Enter close rules
For example
if( .... ){
Order = SIGNAL_CLOSEBUY;
}
*/
if (Order == SIGNAL_CLOSEBUY) {
Ticket = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, Green);
IsTrade = False;
continue;
}
} else {
/* Enter close rules
For example
if( .... ){
Order = SIGNAL_CLOSESELL;
}
if (Order == SIGNAL_CLOSESELL) {
Ticket = OrderClose(OrderTicket(), OrderLots(), Ask, Slippage, Red);
IsTrade = False;
continue;
}
}
}
}
// Enter entry signals
/*
if( … ) {
Order = SIGNAL_BUY;
}
if( … ) {
Order = SIGNAL_SELL;
}
*/
if (Order == SIGNAL_BUY) {
if(!IsTrade) {
....
// Open buy order
}
}
//Sell
if (Order == SIGNAL_SELL) {
if(!IsTrade) {
// Open sell order
}
}
Thanks a lot let me check it and see how I will implement it I really appreciate
Will this code prevent it from entering a trade on every new bar?
I have gone through the code couldn’t still solve the issue please can you look at my code and point out the exact things I need to correct or change to stop it from opening trade on every bar thanks a lot
Sorry little mistake. You can check it again
The problem is this : LastOpenTime>=Time[0] - Period()*60. Maybe: LastOpenTime>=Time[0] or LastOpenTime>Time[0] - Period()*60.
Ok so what code I’m I supposed to use here please help
You can use yours. But the code i had written is simple structure that you can use for your EA. The structure of one EA is most important. Because the code is executed from top to bottom , so you should have in mind what will be executed first. For example for me the right way is first to manipulate or close the current opened positions then to open another. The other thing you should consider when close/manipulate trade is to check the opened position by symbol and magic number, because you can have more than one EA. And so on , you should think first about the structure , what you want and then to start code.
if(type==OP_SELL)
if(OrderOpenPrice()-Ask>(TotalCloseTrades(1,OrderOpenPrice())+1)*WhenPartialClose*pips)
if(!OrderClose(ticket,lots/PartialFacor,Ask,3,clrRed))
printf("failure to close the order ");
}
}
for(int b=OrdersTotal()-1;b>=0;b--){
if(!OrderSelect(b,SELECT_BY_POS,MODE_TRADES))printf("unable to select an order");
int type=OrderType();
double lots= OrderLots();
int ticket = OrderTicket();
if(OrderMagicNumber()==MagicNumber && OrderSymbol()==symbol && lots==0.01)
{
if(type==OP_BUY)
if(Bid-OrderOpenPrice()>(TotalCloseTrades(0,OrderOpenPrice())+1)*WhenPartialClose*pips)
{
if(!OrderClose(ticket,lots,Bid,3,clrRed))
printf("failure to close the order ");
}
if(type==OP_SELL)
if(OrderOpenPrice()-Ask>(TotalCloseTrades(1,OrderOpenPrice())+1)*WhenPartialClose*pips)
if(!OrderClose(ticket,lots,Ask,3,clrRed))
printf("failure to close the order ");
}
}
}
//±------------------------------------------------------------------+
int TotalCloseTrades(int Order,double OpenPrice){
int Total=0;
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
if(OrderType()==Order && OrderSymbol()==symbol && OrderOpenPrice()==OpenPrice && OrderMagicNumber()==MagicNumber)
Total++;
}
return(Total);
}
//±------------------------------------------------------------------+
This is the code thanks guys
Harry:
I created this CCI and EMA EA and i compiled it and there was no error only for me to backtest it and it seems its not backtesting at the same time its not giving me any error in the journal. The EA buys when CCI is above level 0 and price is above EMA. please help guys.
//±-----------------------------------------------------------------+
//| Mega Trend EA.mq4 |
//| Copyright 2019,objemmanuel Software Corp. |
//|
//±-----------------------------------------------------------------+
#property copyright “Copyright 2019,HamzaGhennami Software Corp.”
#property version “1.00”
#property strict
int _Sell;
int _Buy;
string symbol=_Symbol;
extern int MovingPeriod=50;
extern int MovingShift =0;
extern int CciPeriod=14;
extern double LotSize=0.01;
extern bool AutoLotSizing=false;
extern double RiskPercent=0;
extern int TakeProfit=0;
extern int StopLoss=0;
extern bool UseTrailingStop=false;
extern int WhenToTrail=40;
extern int TrailAmount=20;
extern bool UsePartialClose=false;
extern int WhenPartialClose=40;
extern int PartialFacor=2;
extern int MagicNumber=22222;
double BSL=0,SSL=0,BTP=0,STP=0;
double pips=0;
//±-----------------------------------------------------------------+
//| Expert initialization function |
//±-----------------------------------------------------------------+
int OnInit()
{
//—
double ticksize=MarketInfo(symbol,MODE_TICKSIZE);
if(ticksize==0.00001 || ticksize==0.001)
pips=ticksize*10;
else pips=ticksize;
return(0);
//—
return(INIT_SUCCEEDED);
}
//±-----------------------------------------------------------------+
//| Expert deinitialization function |
//±-----------------------------------------------------------------+
void OnDeinit(const int reason)
{
//—
}
//±-----------------------------------------------------------------+
//| Expert tick function |
//±-----------------------------------------------------------------+
void OnTick()
{
int signal = CheckForTrade();
if(IsNewCandle())CheckForTrade();
if (!CheckFilters(signal) && isUseFilters) return;
if(UseTrailingStop)AdjustTrail();
if(UsePartialClose)PartialClose();
}
//±-----------------------------------------------------------------+
bool IsNewCandle()
{
static int BarsOnChart=0;
if(Bars==BarsOnChart)
return (false);
BarsOnChart=Bars;
return(true);
}
//±-----------------------------------------------------------------+
int CalculateCurrentOrders(int direction)
{
if(StopLoss!=0){
BSL=NormalizeDouble(Ask-StopLoss*pips,Digits);
SSL=NormalizeDouble(Bid+StopLoss*pips,Digits);
}
if(StopLoss!=0 && AutoLotSizing){
double pips_to_bsl=StopLoss*pips;
double Equity=AccountEquity();
double RiskedAmount=Equity*RiskPercent*0.01;
LotSize=(RiskedAmount/(pips_to_bsl/pips))/10;
}
if(TakeProfit!=0){
BTP=NormalizeDouble(Ask+TakeProfit*pips,Digits);
STP=NormalizeDouble(Bid-TakeProfit*pips,Digits);
}
if(direction==_Buy && OpenOrdersThisPairBuy(symbol)==0 && OpenOrdersThisPairSell(symbol)==0)
int BuyTicket=OrderSend(symbol,OP_BUY,LotSize,Ask,3,BSL,BTP,NULL,MagicNumber,0,clrGreen);
if(direction==_Sell && OpenOrdersThisPairBuy(symbol)==0 && OpenOrdersThisPairSell(symbol)==0)
int SellTicket=OrderSend(symbol,OP_SELL,LotSize,Bid,3,SSL,STP,NULL,MagicNumber,0,clrRed);
for(int b=OrdersTotal()-1;b>=0;b–)
{
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
if(OrderMagicNumber()==MagicNumber && OrderSymbol()==symbol)
{
double lots= OrderLots();
int ticket = OrderTicket();
if(OrderType()==OP_BUY && direction==_Sell)
{
if(OrderClose(ticket,lots,Bid,3,clrRed))
return _Sell;
}
else if(OrderType()==OP_SELL && direction==_Buy)
if(OrderClose(ticket,lots,Ask,3,clrRed))
return _Buy;
}
}
return 0;
}
//±------------------------------------------------------------------+
int OpenOrdersThisPairBuy(string SYMBOL)
{
int total=0;
for(int i=OrdersTotal()-1; i>=0; i–)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))Print("error Selecting order ",GetLastError());
if(OrderType()==0 && OrderMagicNumber()==MagicNumber && OrderSymbol()==SYMBOL)
total++;
}
return (total);
}
//±------------------------------------------------------------------+
int OpenOrdersThisPairSell(string SYMBOL)
{
int total=0;
for(int i=OrdersTotal()-1; i>=0; i–)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES))Print("error Selecting order ",GetLastError());
if(OrderType()==1 && OrderMagicNumber()==MagicNumber && OrderSymbol()==SYMBOL)
total++;
}
return (total);
}
//±------------------------------------------------------------------+
void AdjustTrail()
{
for(int b=OrdersTotal()-1;b>=0;b--)
{
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
if(OrderMagicNumber()==MagicNumber)
if(OrderSymbol()==symbol)
if(OrderType()==OP_BUY)
if(Bid-OrderOpenPrice()>WhenToTrail*pips)
if(OrderStopLoss()<Bid-TrailAmount*pips || OrderStopLoss()==0)
if(!OrderModify(OrderTicket(),OrderOpenPrice(),Bid-(TrailAmount*pips),OrderTakeProfit(),0,CLR_NONE))
Print("error modifying buy order ",GetLastError());
}
for(int s=OrdersTotal()-1;s>=0;s--)
{
if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
if(OrderMagicNumber()== MagicNumber)
if(OrderSymbol()==symbol)
if(OrderType()==OP_SELL)
if(OrderOpenPrice()-Ask>WhenToTrail*pips)
if(OrderStopLoss()>Ask+TrailAmount*pips || OrderStopLoss()==0)
if(!OrderModify(OrderTicket(),OrderOpenPrice(),Ask+(TrailAmount*pips),OrderTakeProfit(),0,CLR_NONE))
Print("error modifying sell order ",GetLastError());
}
}
//±------------------------------------------------------------------+
int CheckForTrade(){
double x1,x2;
x1 = iCCI(Symbol(),_Period,14,PRICE_TYPICAL,0);
x2 = iCCI(Symbol(),_Period,14,PRICE_TYPICAL,1);
if(x2>0 && x2!=EMPTY_VALUE)
return _Buy;
if(x1<0 && x2!=EMPTY_VALUE)
return _Sell;
return 0;
}
extern bool isUseFilters = true;
int CheckFilters (int signal) { //true - you can trade
double ma;
if(signal==_Buy) {
ma= iMA(NULL,0,MovingPeriod,MovingShift,MODE_EMA,PRICE_TYPICAL,0); }
if(signal==_Sell) {
ma= iMA(NULL,0,MovingPeriod,MovingShift,MODE_EMA,PRICE_TYPICAL,0); }
return true;
}
//±-----------------------------------------------------------------+
void PartialClose()
{
for(int b=OrdersTotal()-1;b>=0;b--){
if(!OrderSelect(b,SELECT_BY_POS,MODE_TRADES))printf("unable to select an order");
int type=OrderType();
double lots= OrderLots();
int ticket = OrderTicket();
if(OrderMagicNumber()==MagicNumber && OrderSymbol()==symbol && lots!=0.01)
{
if(type==OP_BUY)
if(Bid-OrderOpenPrice()>(TotalCloseTrades(0,OrderOpenPrice())+1)*WhenPartialClose*pips)
{
if(!OrderClose(ticket,lots/PartialFacor,Bid,3,clrRed))
printf("failure to close the order ");
}
if(type==OP_SELL)
if(OrderOpenPrice()-Ask>(TotalCloseTrades(1,OrderOpenPrice())+1)*WhenPartialClose*pips)
if(!OrderClose(ticket,lots/PartialFacor,Ask,3,clrRed))
printf("failure to close the order ");
}
}
for(int b=OrdersTotal()-1;b>=0;b--){
if(!OrderSelect(b,SELECT_BY_POS,MODE_TRADES))printf("unable to select an order");
int type=OrderType();
double lots= OrderLots();
int ticket = OrderTicket();
if(OrderMagicNumber()==MagicNumber && OrderSymbol()==symbol && lots==0.01)
{
if(type==OP_BUY)
if(Bid-OrderOpenPrice()>(TotalCloseTrades(0,OrderOpenPrice())+1)*WhenPartialClose*pips)
{
if(!OrderClose(ticket,lots,Bid,3,clrRed))
printf("failure to close the order ");
}
if(type==OP_SELL)
if(OrderOpenPrice()-Ask>(TotalCloseTrades(1,OrderOpenPrice())+1)*WhenPartialClose*pips)
if(!OrderClose(ticket,lots,Ask,3,clrRed))
printf("failure to close the order ");
}
}
}
//±------------------------------------------------------------------+
int TotalCloseTrades(int Order,double OpenPrice){
int Total=0;
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
if(OrderType()==Order && OrderSymbol()==symbol && OrderOpenPrice()==OpenPrice && OrderMagicNumber()==MagicNumber)
Total++;
}
return(Total);
}
//±------------------------------------------------------------------+
This is the code thanks guys