[ARCHIVE] Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 3. - page 578

 
Hi, I've redesigned the standard Macd Sample EA, adding multicurrency capabilities. The problem is that even though it opens trades as multicurrency, it only closes them on profit or trailing stop - although closing after changing the condition is also written in the EA. I am asking for help from our community :)
//+------------------------------------------------------------------+
//|                                                MACD Sample_1.mq4 |
//|                                                            Corp. |
//|                                                          http:// |
//+------------------------------------------------------------------+

extern double Lots = 0.1;
extern double TrailingStop = 50;
extern double MACDOpenLevel=3;
extern double MACDCloseLevel=2;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
string lSymbol;
int init(){lSymbol=Symbol(); return(0);}
int deinit(){return(0);}
int start() 
{ 
  
   double MacdCurrent, MacdPrevious, SignalCurrent;  //значения индикаторов
   double SignalPrevious,bid,ask,point,digits;
   int cnt, ticket, total;   //вычисляемые значения
   
   total=SymbolOrdersTotal(lSymbol);
   if(total<1) 
   {

   
      bid   = MarketInfo(lSymbol,MODE_BID);
      ask   = MarketInfo(lSymbol,MODE_ASK);
      point = MarketInfo(lSymbol,MODE_POINT);
      digits= MarketInfo(lSymbol,MODE_DIGITS);

// on a chart of less than 100 bars
   if(Bars<100)
     {
      Print("bars less than 100");
      return(0);  
     }
   
// to simplify the coding and speed up access
// data are put into internal variables
   MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
   SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
   SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);


// no opened orders identified
      if(AccountFreeMargin()<(1000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
// check for long position (BUY) possibility
      if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<=SignalPrevious &&
         MathAbs(MacdCurrent)>(MACDOpenLevel*point) )
        {
         ticket=OrderSend(lSymbol,OP_BUY,Lots,ask,3,0,0,"macd sample new",12345,0,Green);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice()," as ", lSymbol);
           }
         else Print("Error opening BUY order :",GetLastError()," as ", lSymbol); 
         return(0); 
        }
      // check for short position (SELL) possibility
      if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>=SignalPrevious && 
         MacdCurrent>(MACDOpenLevel*point) )
        {
         ticket=OrderSend(lSymbol,OP_SELL,Lots,bid,3,0,0,"macd sample new",12345,0,Red);
         if(ticket>0)
           {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice()," as ", lSymbol);
           }
         else Print("Error opening SELL order : ",GetLastError()," as ", lSymbol); 
         return(0); 
        }
      return(0);
     }
   // it is important to enter the market correctly, 
   // but it is more important to exit it correctly...   
   for(cnt=0;cnt<total;cnt++)
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&   // check for opened position 
         OrderSymbol()==lSymbol)  // check for symbol
        {
         if(OrderType()==OP_BUY)   // long position is opened
           {
            // should it be closed?
            if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>=SignalPrevious &&
               MacdCurrent>(MACDCloseLevel*point))
                {
                 OrderClose(OrderTicket(),OrderLots(),bid,3,Violet); // close position
                 return(0); // exit
                  }
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if(Bid-OrderOpenPrice()>Point*TrailingStop)
                 {
                   OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                     return(0);
                    }
                 }
           
           }
         else // go to short position
           {
            // should it be closed?
            if(MacdCurrent<0 && MacdCurrent>SignalCurrent &&
               MacdPrevious<=SignalPrevious && MathAbs(MacdCurrent)>(MACDCloseLevel*point))
              {
               OrderClose(OrderTicket(),OrderLots(),ask,3,Violet); // close position
               return(0); // exit
              }
            // check for trailing stop
            if(TrailingStop>0)  
              {                 
               if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
                     return(0);
                   }
               }
           }
        }
     }
   return(0);
  }
  
int SymbolOrdersTotal(string lSymbol)
{
   int Res=0;
   int total=OrdersTotal();
   for (int i=0;i<total;i++) 
   {
      if (OrderSelect(i, SELECT_BY_POS))
      {
         if (OrderSymbol()==lSymbol)
         {
            Res++;
         }
      }
   }
   return(Res);
}
// the end.
 

Guys, can you tell me how to deal with this, before everything was fine - reports were saved in opera... Now it's throwing up in the window when trying to save a strategy tester report.


Problem solved. Figured it out. My computer started opening html files with wordpress for some reason... I converted to opera - everything works as it should.

 

Good afternoon. Please advise a newbie.

How to correct the "tradingexpert.mq4" EA from MQL4 tutorial. If I wanted to open a new order in that direction, and the EA would be waiting for a signal from the indicator to open in the opposite direction.

I was told to use the function aka KimIV - "GetTypeLastClosePos()". I tried to apply it, but trades are not opening. Please advise how to correct the EA. Here is the code with my changes highlighted in red.

//--------------------------------------------------------------------
 // tradingexpert.mq4 
 // Предназначен для использования в качестве примера в учебнике MQL4.
 //--------------------------------------------------------------------
 #property copyright "Copyright © Book, 2007"
 #property link "http://AutoGraf.dp.ua"
 //--------------------------------------------------------------- 1 --
 // Численные значения для М15
 extern double StopLoss =200; // SL для открываемого ордера
 extern double TakeProfit =39; // ТР для открываемого ордера
 extern int Period_MA_1=11; // Период МА 1
 extern int Period_MA_2=31; // Период МА 2
 extern double Rastvor =28.0; // Расстояние между МА 
 extern double Lots =0.1; // Жестко заданное колич. лотов
 extern double Prots =0.07; // Процент свободных средств

 bool Work=true; // Эксперт будет работать.
 string Symb; // Название финанс. инструмента
 //--------------------------------------------------------------- 2 --
 int start()
 {
 int
mn,

 Total, // Количество ордеров в окне 
 Tip=-1, // Тип выбран. ордера (B=0,S=1)
 Ticket; 
string sy;  
 double
 MA_1_t, // Значен. МА_1 текущее
 MA_2_t, // Значен. МА_2 текущее 
 Lot, // Колич. лотов в выбран.ордере
 Lts, // Колич. лотов в открыв.ордере
 Min_Lot, // Минимальное количество лотов
 Step, // Шаг изменения размера лота
 Free, // Текущие свободные средства
 One_Lot, // Стоимость одного лота
 Price, // Цена выбранного ордера
 SL, // SL выбранного ордера 
 TP; // TP выбранного ордера
 bool
 Ans =false, // Ответ сервера после закрытия
 Cls_B=false, // Критерий для закрытия Buy
 Cls_S=false, // Критерий для закрытия Sell
 Opn_B=false, // Критерий для открытия Buy
 Opn_S=false; // Критерий для открытия Sell
 //--------------------------------------------------------------- 3 --
 // Предварит.обработка
 if(Bars < Period_MA_2) // Недостаточно баров
 {
 Alert("Недостаточно баров в окне. Эксперт не работает.");
 return; // Выход из start()
 }
 if(Work==false) // Критическая ошибка
 {
 Alert("Критическая ошибка. Эксперт не работает.");
 return; // Выход из start()
 }
 //--------------------------------------------------------------- 4 --
 // Учёт ордеров
 Symb=Symbol(); // Название фин.инстр.
 Total=0; // Количество ордеров
 for(int i=1; i<=OrdersTotal(); i++) // Цикл перебора ордер
 {
 if (OrderSelect(i-1,SELECT_BY_POS)==true) // Если есть следующий
 { // Анализ ордеров:
 if (OrderSymbol()!=Symb)continue; // Не наш фин. инструм
 if (OrderType()>1) // Попался отложенный
 {
 Alert("Обнаружен отложенный ордер. Эксперт не работает.");
 return; // Выход из start()
 }
 Total++; // Счётчик рыночн. орд
 if (Total>1) // Не более одного орд
 {
 Alert("Несколько рыночных ордеров. Эксперт не работает.");
 return; // Выход из start()
 }
 Ticket=OrderTicket(); // Номер выбранн. орд.
 Tip =OrderType(); // Тип выбранного орд.
 Price =OrderOpenPrice(); // Цена выбранн. орд.
 SL =OrderStopLoss(); // SL выбранного орд.
 TP =OrderTakeProfit(); // TP выбранного орд.
 Lot =OrderLots(); // Количество лотов
 }
 }
 //--------------------------------------------------------------- 5 --

 // Торговые критерии
 MA_1_t=iMA(NULL,0,Period_MA_1,0,MODE_LWMA,PRICE_TYPICAL,0); // МА_1
 MA_2_t=iMA(NULL,0,Period_MA_2,0,MODE_LWMA,PRICE_TYPICAL,0); // МА_2

 if (MA_1_t > MA_2_t + Rastvor*Point && GetTypeLastClosePos(sy,mn)==-1) // Если разница между
 { // ..МА 1 и 2 большая
 Opn_B=true; // Критерий откр. Buy
 Cls_S=true; // Критерий закр. Sell
 }
 if (MA_1_t < MA_2_t - Rastvor*Point && GetTypeLastClosePos(sy,mn)==-1) // Если разница между
 { // ..МА 1 и 2 большая
 Opn_S=true; // Критерий откр. Sell
 Cls_B=true; // Критерий закр. Buy
 }
 //--------------------------------------------------------------- 6 --
 // Закрытие ордеров
 while(true) // Цикл закрытия орд.
 {
 if (Tip==0 && Cls_B==true) // Открыт ордер Buy..
 { //и есть критерий закр
 Alert("Попытка закрыть Buy ",Ticket,". Ожидание ответа..");
 RefreshRates(); // Обновление данных
 Ans=OrderClose(Ticket,Lot,Bid,2); // Закрытие Buy
 if (Ans==true) // Получилось :)
 {
 Alert ("Закрыт ордер Buy ",Ticket);
 break; // Выход из цикла закр
 }
 if (Fun_Error(GetLastError())==1) // Обработка ошибок
 continue; // Повторная попытка
 return; // Выход из start()
 }

 if (Tip==1 && Cls_S==true) // Открыт ордер Sell..
 { // и есть критерий закр
 Alert("Попытка закрыть Sell ",Ticket,". Ожидание ответа..");
 RefreshRates(); // Обновление данных
 Ans=OrderClose(Ticket,Lot,Ask,2); // Закрытие Sell
 if (Ans==true) // Получилось :)
 {
 Alert ("Закрыт ордер Sell ",Ticket);
 break; // Выход из цикла закр
 }
 if (Fun_Error(GetLastError())==1) // Обработка ошибок
 continue; // Повторная попытка
 return; // Выход из start()
 }
 break; // Выход из while
 }
 //--------------------------------------------------------------- 7 --
 // Стоимость ордеров
 RefreshRates(); // Обновление данных
 Min_Lot=MarketInfo(Symb,MODE_MINLOT); // Миним. колич. лотов 
 Free =AccountFreeMargin(); // Свободн средства
 One_Lot=MarketInfo(Symb,MODE_MARGINREQUIRED);// Стоимость 1 лота
 Step =MarketInfo(Symb,MODE_LOTSTEP); // Шаг изменен размера

 if (Lots > 0) // Если заданы лоты,то 
 Lts =Lots; // с ними и работаем 
 else // % свободных средств
 Lts=MathFloor(Free*Prots/One_Lot/Step)*Step;// Для открытия

 if(Lts < Min_Lot) Lts=Min_Lot; // Не меньше минимальн
 if (Lts*One_Lot > Free) // Лот дороже свободн.
 {
 Alert(" Не хватает денег на ", Lts," лотов");
 return; // Выход из start()
 }
 //--------------------------------------------------------------- 8 --
 // Открытие ордеров
 while(true) // Цикл закрытия орд.
 {
 if (Total==0 && Opn_B==true && GetTypeLastClosePos(sy,mn)==OP_SELL) // Открытых орд. нет +
 { // критерий откр. Buy
 RefreshRates(); // Обновление данных
 SL=Bid - New_Stop(StopLoss)*Point; // Вычисление SL откр.
 TP=Bid + New_Stop(TakeProfit)*Point; // Вычисление TP откр.
 Alert("Попытка открыть Buy. Ожидание ответа..");
 Ticket=OrderSend(Symb,OP_BUY,Lts,Ask,2,SL,TP);//Открытие Buy
 if (Ticket > 0) // Получилось :)
 {
 Alert ("Открыт ордер Buy ",Ticket);
 return; // Выход из start()
 }
 if (Fun_Error(GetLastError())==1) // Обработка ошибок
 continue; // Повторная попытка
 return; // Выход из start()
 }
 if (Total==0 && Opn_S==true && GetTypeLastClosePos(sy,mn)==OP_BUY) // Открытых орд. нет +
 { // критерий откр. Sell
 RefreshRates(); // Обновление данных
 SL=Ask + New_Stop(StopLoss)*Point; // Вычисление SL откр.
 TP=Ask - New_Stop(TakeProfit)*Point; // Вычисление TP откр.
 Alert("Попытка открыть Sell. Ожидание ответа..");
 Ticket=OrderSend(Symb,OP_SELL,Lts,Bid,2,SL,TP);//Открытие Sel
 if (Ticket > 0) // Получилось :)
 {
 Alert ("Открыт ордер Sell ",Ticket);
 return; // Выход из start()
 }
 if (Fun_Error(GetLastError())==1) // Обработка ошибок
 continue; // Повторная попытка
 return; // Выход из start()
 }
 break; // Выход из while
 }
 //--------------------------------------------------------------- 9 --
 return; // Выход из start()
 }
 //-------------------------------------------------------------- 10 --
 int Fun_Error(int Error) // Ф-ия обработ ошибок
 {
 switch(Error)
 { // Преодолимые ошибки 
 case 4: Alert("Торговый сервер занят. Пробуем ещё раз..");
 Sleep(3000); // Простое решение
 return(1); // Выход из функции
 case 135:Alert("Цена изменилась. Пробуем ещё раз..");
 RefreshRates(); // Обновим данные
 return(1); // Выход из функции
 case 136:Alert("Нет цен. Ждём новый тик..");
 while(RefreshRates()==false) // До нового тика
 Sleep(1); // Задержка в цикле
 return(1); // Выход из функции
 case 137:Alert("Брокер занят. Пробуем ещё раз..");
 Sleep(3000); // Простое решение
 return(1); // Выход из функции
 case 146:Alert("Подсистема торговли занята. Пробуем ещё..");
 Sleep(500); // Простое решение
 return(1); // Выход из функции
 // Критические ошибки
 case 2: Alert("Общая ошибка.");
 return(0); // Выход из функции
 case 5: Alert("Старая версия терминала.");
 Work=false; // Больше не работать
 return(0); // Выход из функции
 case 64: Alert("Счет заблокирован.");
 Work=false; // Больше не работать
 return(0); // Выход из функции
 case 133:Alert("Торговля запрещена.");
 return(0); // Выход из функции
 case 134:Alert("Недостаточно денег для совершения операции.");
 return(0); // Выход из функции
 default: Alert("Возникла ошибка ",Error); // Другие варианты 
 return(0); // Выход из функции
 }
 }
 //-------------------------------------------------------------- 11 --
 int New_Stop(int Parametr) // Проверка стоп-прик.
 {
 int Min_Dist=MarketInfo(Symb,MODE_STOPLEVEL);// Миним. дистанция
 if (Parametr<Min_Dist) // Если меньше допуст.
 {
 Parametr=Min_Dist; // Установим допуст.
 Alert("Увеличена дистанция стоп-приказа.");
 }
 return(Parametr); // Возврат значения
 }
 //-------------------------------------------------------------- 12 --
int GetTypeLastClosePos(string sy="", int mn=-1) {
 datetime t;
 int i, k=OrdersHistoryTotal(), r=-1;

 if (sy=="0") sy=Symbol();
 for (i=0; i<k; i++) {
 if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) {
 if ((OrderSymbol()==sy || sy=="") && (mn<0 || OrderMagicNumber()==mn)) {
 if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
 if (t<OrderCloseTime()) {
 t=OrderCloseTime();
 r=OrderType();
 }
 }
 }
 }
 }
 return(r);
 }
  
 
Please advise, I have written an EA, no errors, in the Strategy Tester it tests, but it won't trade on a demo account. What is the problem?
 
Roman.:

Guys, can you tell me how to deal with this, before everything was fine - reports were saved in opera... Now it's throwing up in the window when trying to save a strategy tester report.


Problem solved. Figured it out. My computer started opening html files with wordpress for some reason... I converted to opera - everything works as it should.


Maybe your html files are opened with notepad by default? try looking in the control panel under the default program tab
 
Please advise how to write the condition "if the last closed order type was OP_BUY" in MQL4.
 
future:
Please advise how to write the condition "if the last closed order type was OP_BUY" in MQL4.
if(OrdersHistoryTotal()>0)
{

   OrderSelect(OrdersHistoryTotal()-1,SELECT_BY_POS,MODE_HISTORY);

   if(OrderType()==OP_BUY)
   {
      // jagga-jagga
   }

}
 
link1:
Please advise, I have written an EA, no errors, in the Strategy Tester it tests, but it won't trade on a demo account. What is the problem?
There is a special branch for such questions))
 
alsu:
For such questions there is a special branch)))


aha x ))))))

I wonder who is telepathically answering me ;)

Maybe you need to add some condition to the code, that the account is a demo

I got your hint, but the code, unfortunately, can not put it out (

 
link1:


aha x ))))))

and i wonder who is telepathically answering me ;)

maybe in the code it is necessary to add a condition that the account is a demo

I got the hint, but i can't show you the code.

Then the only advice I can give you is to put Prints in all the potentially problematic places, and give us the logs of the non-trading EA. Unless, of course, you can figure out the prints yourself.
Reason: