[ARCHIVO] Cualquier pregunta de novato, para no saturar el foro. Profesionales, no pasen de largo. En ninguna parte sin ti - 3. - página 578

 
Hola, he rediseñado el EA estándar de Macd Sample, añadiendo capacidades multidivisas. El problema es que aunque abre las operaciones como multidivisa, sólo las cierra en función de los beneficios o del trailing stop, aunque el cierre después de cambiar la condición también está escrito en el EA. Pido ayuda a nuestra comunidad :)
//+------------------------------------------------------------------+
//|                                                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.
 

Chicos, me podéis decir cómo solucionar esto, antes todo iba bien - los informes se guardaban en opera... Ahora está vomitando en la ventana al intentar guardar un informe de probador de estrategias.


Problema resuelto. Lo he descubierto. Mi ordenador empezó a abrir archivos html con wordpress por alguna razón... Me he convertido a Opera y todo funciona como debería.

 

Buenas tardes. Algunos consejos para un principiante.

Cómo corregir el EA "tradingexpert.mq4" del tutorial MQL4. Si quisiera abrir una nueva orden en esa dirección, y el EA estaría esperando una señal del indicador para abrir en la dirección opuesta.

Me dijeron que usara la función alias KimIV - "GetTypeLastClosePos()". He intentado aplicarlo, pero las operaciones no se abren. Por favor, aconséjeme cómo corregir el EA. Aquí está el código con mis cambios resaltados en rojo.

//--------------------------------------------------------------------
 // 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);
 }
  
 
Por favor, aconsejar, he escrito un EA, no hay errores, en el probador de la estrategia que las pruebas, pero no va a operar en una cuenta demo. ¿Cuál es el problema?
 
Roman.:

Chicos, podéis decirme cómo solucionar esto, antes todo iba bien - los informes se guardaban en opera... Ahora está vomitando en la ventana al intentar guardar un informe de probador de estrategias.


Problema resuelto. Lo he descubierto. Mi ordenador empezó a abrir archivos html con wordpress por alguna razón... Me he convertido a Opera y todo funciona como debería.


¿Tal vez tus archivos html se abren con el bloc de notas por defecto? prueba a mirar en el panel de control en la pestaña de programas por defecto
 
Por favor, aconseje cómo escribir la condición "si el último tipo de orden cerrada fue OP_BUY" en MQL4.
 
future:
Por favor, aconseje cómo escribir la condición "si el último tipo de orden cerrada fue OP_BUY" en MQL4.
if(OrdersHistoryTotal()>0)
{

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

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

}
 
link1:
Por favor, aconsejar, he escrito un EA, no hay errores, en el probador de la estrategia que las pruebas, pero no va a operar en una cuenta demo. ¿Cuál es el problema?
Hay una rama especial para estas cuestiones))
 
alsu:
Para estas cuestiones hay una rama especial)))


aha x ))))))

Me pregunto quién me está respondiendo telepáticamente ;)

Tal vez usted necesita para agregar alguna condición para el código, que la cuenta es una demo

Recibí tu sugerencia, pero el código, por desgracia, no puede sacarlo (

 
link1:


aha x ))))))

y me pregunto quién me está respondiendo telepáticamente ;)

tal vez en el código es necesario añadir una condición que la cuenta es una demo

Tengo la pista, pero no puedo mostrar el código.

Entonces el único consejo que te puedo dar es que pongas Prints en todos los lugares potencialmente problemáticos, y nos des los logs del EA no comercial. A menos que, por supuesto, puedas averiguar las huellas por ti mismo.
Razón de la queja: