[ARCHIVE!] Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Can't go anywhere without you - 4. - page 391

 
hello! is it possible to modify an order once? i am currently modifying an order at every tick! i don't think this is right!...
 
Hello Professionals, please advise! How should I write it in the EA so that when a bet is off, the EA takes a new bet in the opposite direction on the same bar (like a "flip"). I'm testing with the "when a new bar opens" model. For the example EA:
//+------------------------------------------------------------------+
//|                                                      CrossMa.mq4 |
//|                      Copyright © 2005, George-on-Don             |
//|                                       http://www.forex.aaanet.ru |
//+------------------------------------------------------------------+
#include <stdlib.mqh>
#include <stderror.mqh>
 
#define MAGICMA  20050610
 
extern double Lots               = 0.1;
extern double MaximumRisk        = 0.02;
extern double DecreaseFactor     = 3;
extern double MovingPeriod       = 12;
extern double MovingShift        = 0;
extern double MovingPeriod1      = 4;
extern double AtrPer             = 6;
extern bool   SndMl              = True ;
//+------------------------------------------------------------------+
//| Расчет открытия позиции                                          |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
  {
   int buys=0,sells=0;
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
        {
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
        }
     }
//---- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
  }
//+------------------------------------------------------------------+
//| Расчет оптимальной величины лота                                 |
//+------------------------------------------------------------------+
double LotsOptimized()
  {
   double lot=Lots;
   int    orders=HistoryTotal();     // history orders total
   int    losses=0;                  // number of losses orders without a break
//---- select lot size
   lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//---- calcuulate number of losses orders without a break
   if(DecreaseFactor>0)
     {
      for(int i=orders-1;i>=0;i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
         if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
         //----
         if(OrderProfit()>0) break;
         if(OrderProfit()<0) losses++;
        }
      if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
     }
//---- return lot size
   if(lot<0.1) lot=0.1;
   return(lot);
  }
//+------------------------------------------------------------------+
//| Проверка для открытия позиции с первым тиком нового бара.        |
//+------------------------------------------------------------------+
void CheckForOpen()
  {
   double mas;
   double maf;
   double mas_p;
   double maf_p;
   double Atr;
   int    res;
   string sHeaderLetter;
   string sBodyLetter;
//---- go trading only for first tiks of new bar
   if(Volume[0]>1) return;
//---- get Moving Average 
   mas=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,1); // динный мувинг 12
   maf=iMA(NULL,0,MovingPeriod1,MovingShift,MODE_SMA,PRICE_CLOSE,1);// короткий мувинг 4
   mas_p=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,2); // динный мувинг 12
   maf_p=iMA(NULL,0,MovingPeriod1,MovingShift,MODE_SMA,PRICE_CLOSE,2);// короткий мувинг 4
   Atr = iATR(NULL,0,AtrPer,0);
 //---- Условие продажи
   if(maf<mas && maf_p>=mas_p)  
     {
      res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
       if (SndMl == True && res != -1) 
         {
         sHeaderLetter = "Operation SELL by" + Symbol()+"";
         sBodyLetter = "Order Sell by"+ Symbol() + " at " + DoubleToStr(Bid,4)+ ", and set stop/loss at " + DoubleToStr(Ask+Atr,4)+"";
         sndMessage(sHeaderLetter, sBodyLetter);
         }
      return;
     }
//---- Условие покупки
   if(maf>mas && maf_p<=mas_p)  
     {
      res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
      if ( SndMl == True && res != -1)
      { 
      sHeaderLetter = "Operation BUY at" + Symbol()+"";
      sBodyLetter = "Order Buy at"+ Symbol() + " for " + DoubleToStr(Ask,4)+ ", and set stop/loss at " + DoubleToStr(Bid-Atr,4)+"";
      sndMessage(sHeaderLetter, sBodyLetter);
      }
      return;
     }
//----
  }
//+------------------------------------------------------------------+
//| ПРоверка для закрытия открытой позиции                           |
//+------------------------------------------------------------------+
void CheckForClose()
  {
   double mas;
   double maf;
   double mas_p;
   double maf_p;
   string sHeaderLetter;
   string sBodyLetter;
   bool rtvl;
//---- 
   if(Volume[0]>1) return;
//----  
   mas=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,1); // динный мувинг 12
   maf=iMA(NULL,0,MovingPeriod1,MovingShift,MODE_SMA,PRICE_CLOSE,1);// короткий мувинг 4
   mas_p=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,2); // динный мувинг 12
   maf_p=iMA(NULL,0,MovingPeriod1,MovingShift,MODE_SMA,PRICE_CLOSE,2);// короткий мувинг 4
//----
   for(int i=0;i<OrdersTotal();i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false)        break;
      if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
      //----  
      if(OrderType()==OP_BUY)
        {
         if(maf<mas && maf_p>=mas_p) rtvl=OrderClose(OrderTicket(),OrderLots(),Bid,3,Lime);
            if ( SndMl == True && rtvl != False )
            {
            sHeaderLetter = "Operation CLOSE BUY at" + Symbol()+"";
            sBodyLetter = "Close order Buy at"+ Symbol() + " for " + DoubleToStr(Bid,4)+ ", and finish this Trade";
            sndMessage(sHeaderLetter, sBodyLetter);
            }
         break;
        }
      if(OrderType()==OP_SELL)
        {
         if(maf>mas && maf_p<=mas_p) rtvl=OrderClose(OrderTicket(),OrderLots(),Ask,3,Lime);
         if ( SndMl == True && rtvl != False ) 
         {
         sHeaderLetter = "Operation CLOSE SELL at" + Symbol()+"";
         sBodyLetter = "Close order Sell at"+ Symbol() + " for " + DoubleToStr(Ask,4)+ ", and finish this Trade";
         sndMessage(sHeaderLetter, sBodyLetter);
         }
         break;
        }
     }
//----
  }
  
//--------------------------------------------------------------------
// функция отправки ссобщения об отрытии или закрытии позиции
//--------------------------------------------------------------------
void sndMessage(string HeaderLetter, string BodyLetter)
{
   int RetVal;
   SendMail( HeaderLetter, BodyLetter );
   RetVal = GetLastError();
   if (RetVal!= ERR_NO_MQLERROR) Print ("Ошибка, сообщение не отправлено: ", ErrorDescription(RetVal));
}
//+------------------------------------------------------------------+
//| Майн функция                                                     |
//+------------------------------------------------------------------+
void start()
  {
//---- check for history and trading
   if(Bars<25 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol
   if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
   else                                    CheckForClose();
//----
  }
//+------------------------------------------------------------------+
Thank you!
 

Good afternoon. Question about standard SendMail function ... In orderto understand how the function works, I wrote this script:

//+------------------------------------------------------------------+
//|                                             функция_SendMail.mq4 |
//|                      Copyright © 2012, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
int start()
  {
//+------------------------------------------------------------------+

SendMail("Скрипт Функция_SendMail","Webmoney - идите в жопу!!!!");
Alert(GetLastError());
   
//+------------------------------------------------------------------+   
   return(0);
  }
//+------------------------------------------------------------------+

When running in the client terminal window, an error appears in the log:

In the settings (client terminal menu Tools -> Settings -> Mail tab) the following parameters are set:

Where instead of three dots in fields SMTP login and From Whom there is a name of that mailbox from which I want to send message, and in field To - name of mailbox to which I want to send message.

At the same time theport number specified in theSMTP Server field is really 25:

Note: the screenshot was made in the Help section of the Mail.Ru.

Question: what is this error and how to get rid of it? The compiler doesn't detect errors and the GetLastError() function returns 0.

P.S. In order not to clutter up the forum, thank you in advance for your response.

 
7777877:

Good afternoon. Question about standard SendMail function ... In orderto understand how the function works, I wrote this script:

When running in the client terminal window, an error appears in the log:

In the settings (client terminal menu Tools -> Settings -> Mail tab) the following parameters are set:

Where instead of three dots in fields SMTP login and From Whom there is a name of that mailbox from which I want to send message, and in field To - name of mailbox to which I want to send message.

At the same time theport number specified in theSMTP Server field is really 25:

Note: the screenshot was made in the Help section of the Mail.Ru.

Question: what is this error and how to get rid of it? The compiler doesn't show errors and the GetLastError() function returns 0.

P.S. To avoid littering the forum, thank you in advance for your response.

Look at the port and the encryption. Maybe you should set it to 2525.
 

help please.

Here's the code


//-----------------Закрытие по истории в безубыток--------------------
   //---------------------расчет по истории ордеров номера очередной итерации----------------------------------------------- 
  Iteration = 0; // зануляем инерации перед их учетом в цикле по истории
  Sum_Loss = 0;  // суммарный убыток по этим итерациям

datetime 
Time_at_History_Current = 0,
Time_at_History_Previos = 0;     
 
 if(OrdersHistoryTotal() != 0)
   {
    for(int counter = OrdersHistoryTotal()-1; counter >= 0; counter--)
      {
       OrderSelect(counter, SELECT_BY_POS, MODE_HISTORY);
       if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
         {
          if(OrderType() == OP_BUY || OrderType() == OP_SELL)
            {
             if(OrderProfit() < 0) // если убыток по выбранному ордеру, то считаем суммарный и записываем время закрытия ордера
                                   // для последующего его анализа при подсчете количества итераций
                {
                 double lastLoss = OrderProfit();
                 Sum_Loss=Sum_Loss+lastLoss;  // считаем общий убыток по закрытым подряд убыточным ордерам
                 Time_at_History_Current = OrderCloseTime();
                } 
             
             //Print(" Time_at_History_Current_в цикле = ", TimeToStr(Time_at_History_Current, TIME_DATE|TIME_SECONDS));
             //Print(" Time_at_History_Previos_в цикле = ", TimeToStr(Time_at_History_Previos, TIME_DATE|TIME_SECONDS));
             
             if(Time_at_History_Current != Time_at_History_Previos) // если они не равны, то считаем итерации и делаем их равными
               {
                Time_at_History_Previos = Time_at_History_Current ;
                Iteration++;
                //Print("Iteration at History в условии сравнения  = ",  Iteration);
               }   
             else // они равны, то проверяем, дополнительно, наличие профита по выбранному следующему ордеру и выходим из цикла
               {
                if(OrderProfit() >= 0)
                  break;
               }
            }
         }
      }
   }

if (Sum_Loss < 0.0) { // Имеем убыток по закрытым позам
double money = Lots;
   BuyLots = GetBuyLotsSum();
        SellLots = GetSellLotsSum();
        if(BuyLots  > SellLots)money = BuyLots * 10;
        if(BuyLots  < SellLots)money = SellLots * 10;
  if (((AccountEquity() + Sum_Loss + (Sum_Loss / money)) >= AccountBalance()) && (((totalSell > 0) && (totalBuy < 1)) || ((totalSell < 1) && (totalBuy > 0)))) { // Достигли безубытка
    // Здесь какой-то код, который необходимо выполнить при достижении безубытка
        CloseAllBuy();
           CloseAllSell();
           Sum_Loss = 0.0;
           

I have no way to make a loop open when a deal was closed in minus and if the next order closed above zero, i.e. positive balance, but less than negative, we add plus to negative and get a new negative value, which is already less.

if(OrderProfit() >= 0 && Sum_Loss < 0.0)
                  double lastLoss_two = OrderProfit();
                 Sum_Loss=Sum_Loss+lastLoss_two;  // считаем общий убыток по закрытым подряд убыточным ордерам
                 Time_at_History_Current = OrderCloseTime();
               }

If it is more negative, according to the signal, we close the order and start the cycle from the beginning.


The situation is that when this code closes the deal in loss, then it remembers the minus balance, and when it closes the deal in the plus, and the plus is less than the balance, then it resets Sum_Loss and I need that it would not zeroed, and mowed down.

So this is how it works now:

it checks a closed order, if the profit of closed order is less than zero, then this profit is added to Sum_Loss, and so on until the profit of open trade exceeds (will be more than) Sum_Loss, when reached, the trade is closed, and Sum_Loss is zeroed and the cycle begins again.

I need:

order closed in minus, its minus profit was added to Sum_Loss, then if the next deal closed with a positive profit, Sum_Loss is reduced by the amount derived from the profit, which means that the next open order Sum_Loss is already a smaller amount, and so on until the order profit is greater than Sum_Loss, and then Sum_Loss is cleared and a new cycle starts.

Sum_Loss = 0;

1st closed order: Profit (-50) < 0

Sum_Loss + profit (Sum_Loss + (-50))

Sum_Loss = -50;

2nd closed order: Profit (+40) > 0 and Sum_Loss < 0

Sum_Loss + profit (Sum_Loss + 40)

Sum_Loss = -10
 
7777877:

Good afternoon. Question about standard SendMail function ... In orderto understand how the function works, I wrote this script:

When running in the client terminal window, an error appears in the log:

In the settings (client terminal menu Tools -> Settings -> Mail tab) the following parameters are set:

Where instead of three dots in fields SMTP login and From Whom there is a name of that mailbox from which I want to send message, and in field To - name of mailbox to which I want to send message.

At the same time theport number specified in theSMTP Server field is really 25:

Note: the screenshot was made in the Help section of the Mail.Ru.

Question: what is this error and how to get rid of it? The compiler doesn't show errors and the GetLastError() function returns 0.

P.S. To avoid littering the forum, thank you in advance for your reply.

help

the server smtp.mail.ru:25 really works

 
YOUNGA:

help

The smtp.mail.ru:25 server really works.

My test login, from whom, to whom, matches.

Maybe the firewalls are getting in the way?

Oh, man, that's a million tips - reset the terminal!


 

Help out people

I put a pending order at price x. The order is converted into a market order at price Y. Can I find out somewhere at which price the pending order was placed (in the journal ...or ) or I will have to write my own array

 

Good evening!

Please advise me on the possible source of the error. I'm just learning the language, so I'm a little stumped.

The task in Expert Advisor code is to read data from .scv file (two values in a line, 400 lines) and write them into an array.

double signals_array[400][2];

int init()
  {

   int Handle;
      Handle=FileOpen("Signals.csv",FILE_CSV|FILE_READ,";");// Открытие файла
   if(Handle<0)                        // Неудача при открытии файла
      {
      if(GetLastError()==4103)         // Если файла не существует,..
         Alert("Нет файла");//.. извещаем трейдера 
      else                             // При любой другой ошибке..
         Alert("Ошибка при открытии файла");//..такое сообщ
         PlaySound("Bzrrr.wav");          // Звуковое сопровождение
         return;                          // Выход из start()      
      }

   for (int i = 0; i < 400; i++)
      {
      for (int j = 0; j < 2; j++)
         signals_array[i][j] = StrToDouble(FileReadString(Handle));
      }

Alert (signals_array[120][0],"; ",signals_array[0][1]," OK!");
//----
   return(0);
  }

The problem is this: if I throw the EA on a chart, it prints an alert with the correct values from the array, but if I try to test the EA, it prints an alert "No file" in the log. That is, it seems it cannot access the file (although it's unbelievable) and writes values into the array (which is confirmed by another alert), but gets stuck on finding the file, according to the log. Confused. Below is a screenshot.

 

alexeymosc:

The problem is as follows: if I throw the Expert Advisor onto the chart, it outputs an alert with the correct values from the array, but if I try to test the Expert Advisor, it outputs the "No file" alert in the log. I.e. it seems it cannot access the file (although it's unbelievable) and writes values into an array (this is confirmed by another alert) but freezes on finding a file in the log. Confused.


In the tester and on the chart the files are written and read in different directories:

  1. MetaTrader 4\tester\experts\files
  2. MetaTrader 4\experts\files
Reason: