my ea send order buy and sell at the same time

 
#property copyright "Copyright ฉ 2016 Tor"
#property link      "http://einvestor.ru/"
#property version   "1.0"
#property description "This Expert Advisor loads the News from the site Investing.com without using .dll"
#property strict

input  int AfterNewsStop=5; // Indent after News, minuts
input  int BeforeNewsStop=5; // Indent before News, minuts
input bool NewsLight= false; // Enable light news
input bool NewsMedium=false; // Enable medium news
input bool NewsHard=true; // Enable hard news
input int  offset=3;     // Your Time Zone, GMT (for news)
input string NewsSymb="USD,EUR,GBP,CHF,CAD,AUD,NZD,JPY"; //Currency to display the news (empty - only the current currencies) 
input bool  DrawLines=true;       // Draw lines on the chart
input bool  Next           = false;      // Draw only the future of news line
input bool  Signal         = false;      // Signals on the upcoming news
input string EAconfig = "++++++++++ EA Configuration +++++++++++";
input int MagicNumber = 11111;

input double Lots =0.01;
input int SL = 1000;
input int TP = 100;
input bool Martingale = true;
input double Multiple = 1.3;
input int Maxorder = 13;
input int Distance = 100;
input double Profit = 50;

input string Indicators = "+++++++++++++++++++++" ;
input int FastMA = 15;
input int SlowMA = 200; 
input ENUM_MA_METHOD MAMethod = MODE_SMA;
input ENUM_APPLIED_PRICE ApplyPrice = PRICE_CLOSE;
input int Candle =1;
input double ATRVoulume = 0.1;
input double MaDistance = 0.00;
//-----------------------//
//----------------------------//
#import "wininet.dll"
int InternetOpenW(string sAgent,int lAccessType,string sProxyName="",string sProxyBypass="",int lFlags=0);
int InternetOpenUrlW(int hInternetSession,string sUrl,string sHeaders="",int lHeadersLength=0,int lFlags=0,int lContext=0);
int InternetReadFile(int hFile,uchar &sBuffer[],int lNumBytesToRead,int &lNumberOfBytesRead);
int InternetCloseHandle(int hInet);
#import
int hSession_IEType;
int hSession_Direct;
int Internet_Open_Type_Preconfig=0;
int Internet_Open_Type_Direct=1;

int hSession(bool Direct){
   string InternetAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Q312461)";
   if(Direct){
      if(hSession_Direct==0){
         hSession_Direct=InternetOpenW(InternetAgent,Internet_Open_Type_Direct,"0","0",0);
      }
   return(hSession_Direct);
   } else {
   if(hSession_IEType==0){
      hSession_IEType=InternetOpenW(InternetAgent,Internet_Open_Type_Preconfig,"0","0",0);
   }
   return(hSession_IEType);
   }
}
string httpGET(string strUrl){
   int handler=hSession(false);
   int response= InternetOpenUrlW(handler,strUrl);
   if(response == 0)return("0");
   uchar ch[100000]; string toStr=""; int dwBytes,h=-1;
   while(InternetReadFile(response,ch,100000,dwBytes)){
      if(dwBytes<=0) break; toStr=toStr+CharArrayToString(ch,0,dwBytes);
   }
   InternetCloseHandle(response);
   return(toStr);
}
string URL = "https://script.google.com/macros/s/AKfycbyI8Ig7Ht1_ottrvoUC4OxtiBM0d-4TeyOJgU3gtJZnj5LDvBM/exec";


//-----------------//
datetime LastTradeTime = 0;
double TradeSize = 0.1;
int MaxSlippage = 3; //adjusted in OnInit
int MaxOpenTrades = 1000;
int MaxLongTrades = 1;
int MaxShortTrades = 1;
int MaxPendingOrders = 1000;
int MaxLongPendingOrders = 1000;
int MaxShortPendingOrders = 1000;
bool Hedging = false;
int OrderRetry = 5; //# of retries if sending order returns error
int OrderWait = 5; //# of seconds to wait if sending order returns error
int LotDigits; //initialized in OnInit



color highc          = clrRed;     // Colour important news
color mediumc        = clrBlue;    // Colour medium news
color lowc           = clrLime;    // The color of weak news
int   Style          = 2;          // Line style
int   Upd            = 86400;      // Period news updates in seconds

bool  Vhigh          = false;
bool  Vmedium        = false;
bool  Vlow           = false;
int   MinBefore=0;
int   MinAfter=0;

int NomNews=0;
string NewsArr[4][1000];
int Now=0;
datetime LastUpd;
string str1;

//-----------------//
int bar=-1;
double fector=1;
int trend=-1;

void myAlert(string type, string message)
  {
   if(type == "print")
      Print(message);
   else if(type == "error")
     {
      Print(type+" | EMA Close @ "+Symbol()+","+IntegerToString(Period())+" | "+message);
     }
   else if(type == "order")
     {
      Print(type+" | EMA Close @ "+Symbol()+","+IntegerToString(Period())+" | "+message);
     }
   else if(type == "modify")
     {
     }
  }

int myOrderSend(int type, double price, double volume, string ordername) //send order, return ticket ("price" is irrelevant for market orders)
  {
   if(!IsTradeAllowed()) return(-1);
   int retries = 0;
   int err = 0;
   int long_trades = TradesCount(OP_BUY);
   int short_trades = TradesCount(OP_SELL);
   int long_pending = TradesCount(OP_BUYLIMIT) + TradesCount(OP_BUYSTOP);
   int short_pending = TradesCount(OP_SELLLIMIT) + TradesCount(OP_SELLSTOP);
   string ordername_ = ordername;
   if(ordername != "")
      ordername_ = "("+ordername+")";
   //test Hedging
   if(!Hedging && ((type % 2 == 0 && short_trades + short_pending > 0) || (type % 2 == 1 && long_trades + long_pending > 0)))
     {
      myAlert("print", "Order"+ordername_+" not sent, hedging not allowed");
      return(-1);
     }
   //test maximum trades
   if((type % 2 == 0 && long_trades >= MaxLongTrades)
   || (type % 2 == 1 && short_trades >= MaxShortTrades)
   || (long_trades + short_trades >= MaxOpenTrades)
   || (type > 1 && type % 2 == 0 && long_pending >= MaxLongPendingOrders)
   || (type > 1 && type % 2 == 1 && short_pending >= MaxShortPendingOrders)
   || (type > 1 && long_pending + short_pending >= MaxPendingOrders)
   )
     {
      myAlert("print", "Order"+ordername_+" not sent, maximum reached");
      return(-1);
     }
   //prepare to send order
   while(IsTradeContextBusy()) Sleep(100);
   RefreshRates();
   if(type == OP_BUY)
      price = Ask;
   else if(type == OP_SELL)
      price = Bid;
   else if(price < 0) //invalid price for pending order
     {
      myAlert("order", "Order"+ordername_+" not sent, invalid price for pending order");
          return(-1);
     }
   int clr = (type % 2 == 1) ? clrRed : clrBlue;
   while(ticket < 0 && retries < OrderRetry+1)
     {
      ticket = OrderSend(Symbol(), type, NormalizeDouble(volume, LotDigits), NormalizeDouble(price, Digits()), MaxSlippage, 0, 0, ordername, MagicNumber, 0, clr);
      if(ticket < 0)
        {
         err = GetLastError();
         myAlert("print", "OrderSend"+ordername_+" error #"+IntegerToString(err));
         Sleep(OrderWait*1000);
        }
      retries++;
     }
   if(ticket < 0)
     {
      myAlert("error", "OrderSend"+ordername_+" failed "+IntegerToString(OrderRetry+1)+" times; error #"+IntegerToString(err));
      return(-1);
     }
   string typestr[6] = {"Buy", "Sell", "Buy Limit", "Sell Limit", "Buy Stop", "Sell Stop"};
   myAlert("order", "Order sent"+ordername_+": "+typestr[type]+" "+Symbol()+" Magic #"+IntegerToString(MagicNumber));
   return(ticket);
  }

int TradesCount(int type) //returns # of open trades for order type, current symbol and magic number
  {
   int result = 0;
   int total = OrdersTotal();
   for(int i = 0; i < total; i++)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false) continue;
      if(OrderMagicNumber() != MagicNumber || OrderSymbol() != Symbol() || OrderType() != type) continue;
      result++;
     }
   return(result);
  }

int ticket;
double askPrice,bidPrice;
bool NewOrder = False;
void OpenBuy()
{
   ticket = OrderSend(Symbol(),OP_BUY,NewLots(),Ask,3,Ask-SL*Point,Ask+TP*Point,"EA Trade V.5 WTF",MagicNumber,0,clrGreen);
   askPrice=Ask;
   NewOrder=true;
}

void OpenSell()
{
   ticket = OrderSend(Symbol(),OP_SELL,NewLots(),Bid,3,Bid+SL*Point,Bid-TP*Point,"EA Trade V.5 WTF",MagicNumber,0,clrRed);
   bidPrice=Bid;
   NewOrder=true;
}

void CloseBuy()
  {
   for(int y=OrdersTotal()-1; y>=0; y--)
     {
      if(OrderSelect(y,SELECT_BY_POS,MODE_TRADES))
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            ticket=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),5,Black);
           }
     }
  }

void CloseSell()
  {
   for(int y=OrdersTotal()-1; y>=0; y--)
     {
      if(OrderSelect(y,SELECT_BY_POS,MODE_TRADES))       
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            ticket=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),5,Black);
           }
     }
  }
double FastMA2SlowMA2,SlowMA1FastMA1;
double ATR;
double StopLoss,TakeProfit;
double FastMA1,SlowMA1,FastMA2,SlowMA2;
double bid,ask;
void GetMA()
  
   {
   FastMA1=iMA(NULL,0,FastMA,0,MAMethod,ApplyPrice,Candle);
   SlowMA1=iMA(NULL,0,SlowMA,0,MAMethod,ApplyPrice,Candle);
   FastMA2=iMA(NULL,0,FastMA,0,MAMethod,ApplyPrice,Candle);
   SlowMA2=iMA(NULL,0,SlowMA,0,MAMethod,ApplyPrice,Candle);
   ATR =iATR(NULL,0,14,0);
   FastMA2SlowMA2=FastMA2-SlowMA2;
   SlowMA1FastMA1=SlowMA1-FastMA1;
   }
   
void EntryOrder()
{
   if(OrdersTotal()==0)    
    //Open Buy Order
   {
   if(iMA(NULL, PERIOD_CURRENT, FastMA, 0, MAMethod, ApplyPrice, 1) > iMA(NULL, PERIOD_CURRENT, SlowMA, 0, MAMethod, ApplyPrice, 1) //Moving Average > Moving Average
   && iMA(NULL, PERIOD_CURRENT, FastMA, 0, MAMethod, ApplyPrice, 2) < iMA(NULL, PERIOD_CURRENT, SlowMA, 0, MAMethod, ApplyPrice, 2) //Moving Average < Moving Average
   && ATR >=ATRVoulume && FastMA2SlowMA2>=MaDistance )
     {OpenBuy();
      RefreshRates();
      ask = Ask;
      StopLoss = SL * Point(); //Stop Loss = value in points (relative to price)
      TakeProfit = TP * Point(); //Take Profit = value in points (relative to price)
        
     
      
     }
    }
  if(OrdersTotal()==0)
  {  
  if(iMA(NULL, PERIOD_CURRENT, FastMA, 0, MAMethod, ApplyPrice, 1) < iMA(NULL, PERIOD_CURRENT, SlowMA, 0, MAMethod, ApplyPrice, 1) //Moving Average < Moving Average
   && iMA(NULL, PERIOD_CURRENT, FastMA, 0, MAMethod, ApplyPrice, 2) > iMA(NULL, PERIOD_CURRENT, SlowMA, 0, MAMethod, ApplyPrice, 2) //Moving Average > Moving Average
   &&  ATR >=ATRVoulume &&SlowMA1FastMA1>=MaDistance )
     { OpenSell();
      RefreshRates();
      bid = Bid;
      StopLoss = SL * Point(); //Stop Loss = value in points (relative to price)
      TakeProfit = TP * Point(); //Take Profit = value in points (relative to price)   
         
     }       
   }
}
//+------------------------------------------------------------------+
//|                                              |
//+------------------------------------------------------------------+

void Martin()
{
   if(Martingale)
   {
   if(CountBuy()>0 && askPrice-Ask >= Distance*Point && CountBuy() < Maxorder) 
   OpenBuy();  
   if(CountSell()>0&& Bid-bidPrice >= Distance*Point && CountSell() < Maxorder) 
   OpenSell();   
   }
}

int CountBuy()
{
   int Count=0;
   for(int i =OrdersTotal()-1;i>=0;i--)
   {
      bool res = OrderSelect(i,SELECT_BY_POS,OrderMagicNumber() == MagicNumber);
      if(OrderType()==OP_BUY)
      
      {
         Count++;
      }
   }
   return Count;
}

int CountSell()
{
   int Count=0;
   for(int i =OrdersTotal()-1;i>=0;i--)
   {
      bool res = OrderSelect(i,SELECT_BY_POS,OrderMagicNumber() == MagicNumber);
      if(OrderType()==OP_SELL)
      
      {
         Count++;
      }
   }
   return Count;
}

double NewLots()
{
   double NewLots=Lots;
   for(int i = OrdersTotal()-1;i>=0;i--)
   {
      bool res =OrderSelect(i,SELECT_BY_POS);
      NewLots=NewLots*Multiple;
   }
   return NewLots;
}

void CloseByProfit()
{
   if(AccountProfit() >= Profit)
   {
      for(int i = OrdersTotal()-1;i>=0;i--)
      {
      bool res =OrderSelect(i,SELECT_BY_POS);
      ticket = OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),50,clrBlack);
      }
   }
}
double sumLots,sumOrder,NewPrice,NewTPPrice;     
void ModifyTP()
{  
if(NewOrder)
{
   sumOrder=0;
   sumLots=0;     
   NewPrice=0;
   NewTPPrice=0;
   for(int i=OrdersTotal()-1;i>=0;i--)
   {
      if(OrderSelect(i,SELECT_BY_POS))
      if(OrderSymbol()==Symbol())
  
      {
         sumOrder+= OrderOpenPrice()*OrderLots();
         sumLots+= OrderLots();
                 
      }
   }
   if (sumLots==0) return;
   else
   NewPrice=NormalizeDouble(sumOrder/sumLots,Digits);
   
   for(int y=OrdersTotal()-1;y>=0;y--)
   {
      if(OrderSelect(y,SELECT_BY_POS))
      if(OrderSymbol()==Symbol())
      {
         if(OrderType()==OP_BUY)
         {
            NewTPPrice=NewPrice+Profit*Point;
            break;
         }
         if(OrderType()==OP_SELL)
         {
            NewTPPrice=NewPrice-Profit*Point;
            break;
         }
      }
   }
   
   for(int j=OrdersTotal()-1;j>=0;j--)
   {
      if(OrderSelect(j,SELECT_BY_POS))
      if(OrderSymbol()==Symbol())
      {
         ticket=OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),NewTPPrice,0,clrGold);
      }
   }
   }
   NewOrder=false;
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
int OnInit()
{
   string text =  httpGET(URL);
   
   //text = StringSubstr(text, StringFind(text,"[member]"),200);


 //  text = StringSubstr(text, StringFind(text,"[member]"),200);

   
   if( StringFind(text, "user\":"+IntegerToString(AccountNumber())+",",0)!=-1 )
   {
    {
      Alert("Login successful!");
   
    }
   {if(StringLen(NewsSymb)>1)str1=NewsSymb;
   else str1=Symbol();

   Vhigh=NewsHard;
   Vmedium=NewsMedium;
   Vlow=NewsLight;
   
   MinBefore=BeforeNewsStop;
   MinAfter=AfterNewsStop;
   }
  {   
     //initialize LotDigits
   double LotStep = MarketInfo(Symbol(), MODE_LOTSTEP);
   if(LotStep >= 1) LotDigits = 0;
   else if(LotStep >= 0.1) LotDigits = 1;
   else if(LotStep >= 0.01) LotDigits = 2;
   else LotDigits = 3;
   LastTradeTime = 0;
   TradeSize = Lots; //initialize to input
  
   
   return(INIT_SUCCEEDED);
  }
  }
  else
      {
      Alert("Login error!Please Contact fb.com/poom225");
      ExpertRemove();
      return-1; // closeEA
      }
   }

void OnTick()

   {
//---
  GetMA();
      Martin();
      ModifyTP();
      
   double CheckNews=0;
   if(AfterNewsStop>0)
     {
      if(TimeCurrent()-LastUpd>=Upd){Comment("News Loading...");Print("News Loading...");UpdateNews();LastUpd=TimeCurrent();Comment("");}
      WindowRedraw();
      //---Draw a line on the chart news--------------------------------------------
      if(DrawLines)
        {
         for(int i=0;i<NomNews;i++)
           {
            string Name=StringSubstr(TimeToStr(TimeNewsFunck(i),TIME_MINUTES)+"_"+NewsArr[1][i]+"_"+NewsArr[3][i],0,63);
            if(NewsArr[3][i]!="")if(ObjectFind(Name)==0)continue;
            if(StringFind(str1,NewsArr[1][i])<0)continue;
            if(TimeNewsFunck(i)<TimeCurrent() && Next)continue;

            color clrf = clrNONE;
            if(Vhigh && StringFind(NewsArr[2][i],"High")>=0)clrf=highc;
            if(Vmedium && StringFind(NewsArr[2][i],"Moderate")>=0)clrf=mediumc;
            if(Vlow && StringFind(NewsArr[2][i],"Low")>=0)clrf=lowc;

            if(clrf==clrNONE)continue;

            if(NewsArr[3][i]!="")
              {
               ObjectCreate(Name,0,OBJ_VLINE,TimeNewsFunck(i),0);
               ObjectSet(Name,OBJPROP_COLOR,clrf);
               ObjectSet(Name,OBJPROP_STYLE,Style);
               ObjectSetInteger(0,Name,OBJPROP_BACK,true);
              }
           }
        }
      //---------------event Processing------------------------------------
      int i;
      CheckNews=0;
      for(i=0;i<NomNews;i++)
        {
         int power=0;
         if(Vhigh && StringFind(NewsArr[2][i],"High")>=0)power=1;
         if(Vmedium && StringFind(NewsArr[2][i],"Moderate")>=0)power=2;
         if(Vlow && StringFind(NewsArr[2][i],"Low")>=0)power=3;
         if(power==0)continue;
         if(TimeCurrent()+MinBefore*60>TimeNewsFunck(i) && TimeCurrent()-MinAfter*60<TimeNewsFunck(i) && StringFind(str1,NewsArr[1][i])>=0)
           {
            CheckNews=1;
            break;
           }
         else CheckNews=0;

        }
      if(CheckNews==1 && i!=Now && Signal) { Alert("In ",(int)(TimeNewsFunck(i)-TimeCurrent())/60," minutes released news ",NewsArr[1][i],"_",NewsArr[3][i]);Now=i;}
/***  ***/
     }

   if(CheckNews>0)
     {
      /////  We are doing here if we are in the framework of the news
      Comment("News time");

     }else{
      // We are out of scope of the news release (No News)
      Comment("No news");
      
   EntryOrder();
     }
 
   }

Hi,I have a problem, want to help me find a bug.

my ea send order buy and sell at the same time

i use MA Cross Martingale But My EA buy and sell at the same time .

see picture EA Buy and Sell 0.50 And Buy 0.65 (I using Martingale 1.3 & 0.5*1.3 = 0.65) Same Time and same price

  
 

This line contains a bug:

      bool res = OrderSelect(i,SELECT_BY_POS,OrderMagicNumber() == MagicNumber);

Both in CountBuy/Sell. You probably wanted to check the magic number on a separate instruction.

Also, several other places make use of OrdersTotal() where only the EA's orders should be counted. There might be more that requires a fix.

By the way this is MQL 4.

 
lippmaje:

This line contains a bug:

Both in CountBuy/Sell. You probably wanted to check the magic number on a separate instruction.

Also, several other places make use of OrdersTotal() where only the EA's orders should be counted. There might be more that requires a fix.

By the way this is MQL 4.

Thank you so much . I can fix it Now

But i have new a problem .My EA i Open Order and TP ,but EA Open Order again ( Ex. time19.30.00 Open Buy  Gold 1200.00  time 19.31.00 TP 1202.00 => time 19.31.00 Open Buy Gold 1202.00)

how do i can fix it ? 

 
เจนภพ เจนภพ: t EA Open Order again
  1. You are looking at a signal. Act on a change of signal.
              MQL4 (in Strategy Tester) - double testing of entry conditions - MQL5 programming forum #1 2017.12.12

  2. Don't double post! You already had this thread open.
              General rules and best pratices of the Forum. - General - MQL5 programming forum 2017.07.19

 
เจนภพ เจนภพ:

Do not double post!

I have deleted your duplicated post.

Reason: