[ARCHIVE] Toute question de débutant, afin de ne pas encombrer le forum. Professionnels, ne passez pas à côté. Nulle part sans toi - 3. - page 578

 
Bonjour, j'ai remanié l'EA standard Macd Sample, en ajoutant des capacités multidevises. Le problème est que, même s'il ouvre les transactions en tant que multidevises, il ne les ferme qu'en cas de profit ou de stop suiveur - bien que la fermeture après modification d'une condition soit également écrite dans l'EA. Je demande l'aide de notre communauté :)
//+------------------------------------------------------------------+
//|                                                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.
 

Les gars, pouvez-vous me dire comment régler ce problème, avant tout allait bien - les rapports étaient sauvegardés dans opera... Maintenant, il s'affiche dans la fenêtre lorsqu'on essaie d'enregistrer un rapport de testeur de stratégie.


Problème résolu. J'ai compris. Mon ordinateur a commencé à ouvrir des fichiers html avec wordpress pour une raison quelconque... Je me suis converti à Opera - tout fonctionne comme il se doit.

 

Bon après-midi. Veuillez conseiller un débutant.

Comment corriger l'EA "tradingexpert.mq4" du tutoriel MQL4. Si je voulais ouvrir un nouvel ordre dans cette direction, l'EA attendrait un signal de l'indicateur pour ouvrir dans la direction opposée.

On m'a dit d'utiliser la fonction alias KimIV - "GetTypeLastClosePos()". J'ai essayé de l'appliquer, mais les transactions ne s'ouvrent pas. Veuillez me conseiller sur la manière de corriger l'EA. Voici le code avec mes modifications surlignées en rouge.

//--------------------------------------------------------------------
 // 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);
 }
  
 
J'ai écrit un EA, il n'y a pas d'erreurs, il est testé dans le Strategy Tester, mais il ne peut pas être utilisé sur un compte de démonstration. Quel est le problème ?
 
Roman.:

Les gars, pouvez-vous me dire comment régler ce problème, avant tout allait bien - les rapports étaient sauvegardés dans opera... Maintenant, il s'affiche dans la fenêtre lorsqu'on essaie d'enregistrer un rapport de testeur de stratégie.


Problème résolu. J'ai compris. Mon ordinateur a commencé à ouvrir des fichiers html avec wordpress pour une raison quelconque... Je me suis converti à Opera - tout fonctionne comme il se doit.


Peut-être que vos fichiers html sont ouverts avec le bloc-notes par défaut ? Essayez de regarder dans le panneau de configuration sous l'onglet "Programme par défaut".
 
Veuillez m'indiquer comment écrire la condition "si le dernier type d'ordre fermé était OP_BUY" dans MQL4.
 
future:
Veuillez m'indiquer comment écrire la condition "si le dernier type d'ordre fermé était OP_BUY" dans MQL4.
if(OrdersHistoryTotal()>0)
{

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

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

}
 
link1:
J'ai écrit un EA, il n'y a pas d'erreurs, il est testé dans le Strategy Tester, mais il ne peut pas être utilisé sur un compte de démonstration. Quel est le problème ?
Il existe une branche spéciale pour ce genre de questions ;))
 
alsu:
Pour de telles questions, il existe une branche spéciale))))


aha x ))))))

Je me demande qui me répond par télépathie ;)

Peut-être que vous devez ajouter une condition au code, que le compte est une démo

J'ai reçu votre conseil, mais le code, malheureusement, ne peut pas le sortir (

 
link1:


aha x ))))))

et je me demande qui me répond par télépathie ;)

peut-être dans le code il faut ajouter une condition que le compte est une démo

J'ai compris l'astuce, mais je ne peux pas vous montrer le code.

Alors le seul conseil que je puisse vous donner est de mettre des empreintes à tous les endroits potentiellement problématiques, et de nous donner les logs de l'EA non commerciale. À moins, bien sûr, que vous puissiez trouver les empreintes vous-même.
Raison: