Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 538

 
Ihor Herasko:

This method of swap calculation is called rollover. You cannot know about it programmatically in MT4. Only indirectly after the midnight change of working market orders. There are a lot of such small, but rather unpleasant problems in MT4. In MT5 there are a little less, but they still exist.

These are the swap values in pips. They should be converted into the currency of the deposit, based on the volume of the market order. Then you will get the real swap size.

"There is no way to find out about it programmatically in MT4". - Thank you for your time and replies.

 

Good day! Dear forum users, please help me to understand the algorithm. The aim is to determine the price range in the specified period of time and set the buy and sell stops at max and min. Stoplosses are set on opposite orders, TakeProfit should be equal to StopLoss*2.

Then, after each closing by Stop Loss, the order is restored with the same Stop Loss and Take Profit as the closed one and the whole cycle is completed once one of the orders is closed by Take Profit. And all from the beginning we define the range and go.

But now he just does not place TP or rather he places it at the open price and stop loss is not on the range size, i.e. not on an oppositely directed order. I thank him in advance for his help.

static int prevtime = 0;
int MagicNumber = 12345678;
input int stoploss = 40;
input int takeprofit = 50;
input int padding = 5;
int a=1;
input string startTime = "14:35";
input string endTime = "18:35";
int expertBars;
double max, min;
bool isEndTime = true;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   //sendOrders();
   
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
#include <expert.mq4>
 
int start()
{  
    //Возвращает максимум и минимум за промежуток
    if(isTime()) getMaxMin();
    
    // всё, что задается ниже - будет работать по "ценам открытия"
    //нового бара, т.е. будет срабатывать в момент его появления
    //на том графике, на кот. стоит советник
    CheckEvents( MagicNumber );
    if ( eventBuyClosed_SL > 0 ) {
        Alert( _Symbol, OrderClosePrice(), ": Buy-позиция закрыта по СтопЛоссу!" );
        double minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
        Alert("Минимальный стоп левел: ", minstoplevel);
        OrderSend(_Symbol,OP_BUYSTOP,OrderLots(),OrderOpenPrice(),3,OrderStopLoss(),OrderTakeProfit(),"My order",MagicNumber,0,clrGreen);
    }
    
    if ( eventBuyClosed_TP > 0 ) {
        Alert( _Symbol, OrderClosePrice(), ": Buy-позиция закрыта по ТейкПрофиту!" );
        deleteAllPaddingOrders();
    }
    
    if ( eventSellClosed_SL > 0 ) {
        Alert( _Symbol, OrderClosePrice(), ": Sell-позиция закрыта по СтопЛоссу!" );
        double minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
        Alert("Минимальный стоп левел: ", minstoplevel);
        OrderSend(_Symbol,OP_SELLSTOP,OrderLots(),OrderOpenPrice(),3,OrderStopLoss(),OrderTakeProfit(),"My order",MagicNumber,0,clrRed);
    }
    
    if ( eventSellClosed_TP > 0 ) {
        Alert( _Symbol, OrderClosePrice(), ": Sell-позиция закрыта по ТейкПрофиту!" );
        deleteAllPaddingOrders();
    }
    
    if ( eventBuyLimitOpened > 0 || eventBuyStopOpened > 0 || 
          eventSellLimitOpened > 0 || eventSellStopOpened > 0 )
        Alert( _Symbol, OrderType(), ": сработал отложенный ордер!" );
return(0);
}
//-----------------------------------------------------------------+
void deleteAllPaddingOrders() {
  int total = OrdersTotal();
  for(int i=total-1;i>=0;i--)
  {
    OrderSelect(i, SELECT_BY_POS);
    int type   = OrderType();
    if (OrderMagicNumber() != MagicNumber) continue;
    if (OrderSymbol() != _Symbol) continue;
    bool result = false;
    
    switch(type)
    {
      //Close opened long positions
      case OP_BUY       : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
                          break;
      
      //Close opened short positions
      case OP_SELL      : result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
      //                    break;

      //Close pending orders
      //case OP_BUYLIMIT  :
      //case OP_SELLLIMIT :
      case OP_BUYSTOP   :
      case OP_SELLSTOP  : result = OrderDelete( OrderTicket() );
    }
    
    if(result == false)
    {
      Alert("Order " , OrderTicket() , " failed to close. Error:" , GetLastError() );
      Sleep(3000);
    }
    return;
  }
  
  return;
}
void sendOrders(bool isFirst) {
   //--- получим минимальное значение Stop level
   double minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
   Print("Minimum Stop Level=",minstoplevel," points");
   //--- BUYSTOP
   //--- вычисленные значения цен SL и TP должны быть нормализованы
   //--- размещаем рыночный ордер на покупку 1 лота
   int ticketBuyStop, ticketSellStop;
   if(!isFirst) {
      ticketBuyStop=OrderSend(Symbol(),OP_BUYSTOP,1,Ask + padding * Point,20,Bid -padding*Point,Ask + padding * Point,"My order",MagicNumber,0,clrGreen);
      ticketSellStop=OrderSend(Symbol(),OP_SELLSTOP,1,Bid - padding * Point,20,Ask + padding*Point,Bid - padding * Point,"My order",MagicNumber,0,clrRed);
   } else { 
      ticketBuyStop=OrderSend(Symbol(),OP_BUYSTOP,1,max + padding * Point,20,min -padding*Point,max + (max - min + padding) * Point,"My order",MagicNumber,0,clrGreen);
      ticketSellStop=OrderSend(Symbol(),OP_SELLSTOP,1,min - padding * Point,20,max + padding*Point,min - (max - min  + padding)*Point,"My order",MagicNumber,0,clrRed);
   }
   if(ticketBuyStop<0)
     {
     Print("OrderSend завершилась с ошибкой #",GetLastError());
      
         deleteAllPaddingOrders();
         if(a <=5) {
         //sendOrders(isFirst);
         a= a+1;
      }
     }
   else
      Print("Функция OrderSend успешно выполнена");
   //---BUYSTOP
   
   //---SELLSTOP
   //--- вычисленные значения цен SL и TP должны быть нормализованы
   //--- размещаем рыночный ордер на покупку 1 лота
   
   if(ticketSellStop<0)
     {
      
         deleteAllPaddingOrders();
         if(a <= 5) {
            //sendOrders();
            a= a+1;
            Print("a", a);
         }
         Print("OrderSend завершилась с ошибкой #",GetLastError());
       
     }
   else
      Print("Функция OrderSend успешно выполнена");
   //---SELLSTOP
   return;
}
bool getMaxMin() {
   int startIndex = iBarShift(_Symbol, 0, StrToTime(startTime), true);
   min=iLow(NULL,0,iLowest(NULL,0,MODE_LOW,startIndex,0));
   max=iHigh(NULL,0,iHighest(NULL,0,MODE_HIGH,startIndex,0));
   Alert("Min: ", min);
   Alert("Max: ", max);
   sendOrders(true);
   return true;
}

//===============================================================================+
//======| возвращает true если временной диапозон кончился                       |
//===============================================================================+
bool isTime() {
   if (TimeHour(StrToTime(startTime)) == Hour() && TimeMinute(StrToTime(startTime)) == Minute() && isEndTime) { Alert("Start Timeline"); isEndTime = false; deleteAllPaddingOrders();};
   if(TimeHour(StrToTime(endTime)) == Hour() && TimeMinute(StrToTime(endTime)) <= Minute() && !isEndTime) { Alert("End Timeline"); isEndTime = true; return true;};
   return false;
}

//=====================================================================+
//======| возвращает true если появился новый бар, иначе false |
//=====================================================================+
//bool isNewBar()
//{
//bool res=false;
//if(expertBars!=iBars(Symbol(),0))
//{
//expertBars=iBars( Symbol (),0);
//res=true;
//}
//return(res);
//}
 
Sobbaka:

There is no need to duplicate questions in different threads.

 

Good afternoon!

When testing in the log I get OrderSend error 130 - if I understand correctly it can only be related to stops or strokes, please check what is wrong:

#define  MagicNumber1 100            //Buy
input double MaximumRisk=0.03;      //Max риск в сделке
 input double K=1;                   //Коэффициент риск к прибыли
input int OrderPoint=30;            //Расстояние до отложенного ордера
double Price=0;                     //Цена для установки отложенного ордера
double SL=0;                        //Stop Loss
double TP=0;                        //Take Profit
double Lots=0;                      //Просчет лотности исходя из max риска одной сделки


void OnTick()
{
//Параметры для открытия ордера                   
Price = NormalizeDouble(High[1]+OrderPoint*Point,Digits); //Цена открытия ордера
SL = NormalizeDouble(Low[1]-Point,Digits); //Стоп лосс
if ((Price-SL)<NormalizeDouble(MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits))
{SL=Price-NormalizeDouble(MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);}
TP = NormalizeDouble((Price-SL)*K+Price,Digits); //Тэйк профит
//Просчет лотности исходя из риска в сделке
Lots = NormalizeDouble(((AccountBalance()*MaximumRisk/100.0)/((Price-SL)*1000.0)),1);

//Установка отложенного ордера
bool send1=OrderSend(Symbol(),OP_BUYSTOP,Lots,Price,3,SL,TP,"comment",MagicNumber1,0,clrGreen);
}
 
YanSay:

Good afternoon!

When testing in the log there is an error OrderSend error 130 - if I understand correctly it can only be related to stops or strokes,

The open prices of pending orders are also affected. That is why we need to check the distance between the current market price and the open price of the order. In this case: Price - Ask.

 
Ihor Herasko:

The opening price of pending orders also applies. Therefore we should also check the distance between the current market price and the opening price of the order. In this case: Price - Ask.

Thank you!
 
Artyom Trishkin:
What does the Hour() function return ?

Returns the current hour. that's how I work: if the current hour is greater than 11 and less than 17,

if(Hour()>=17&&Hour()<=11)continue;

but how?

 
Tigerfreerun:

It's a bit complicated for me. Could you explain in which part of the code to add and what does it mean mn and mag_n? where should I put my EA medjic here?

Before your condition put

if(Hour()>=0&&Hour()<=8&&!OP_TO(mag_n))step = 5; else step =10;

mag_n - where do I put my EA's IG here?

 
PolarSeaman:

I am writing: if the current hour is more than 11 and less than 17, how should it be?

I understand that the question is about the indicator. Instead ofHour() -> time[i]

 
Vitaly Muzichenko:

I understand the question is about the indicator. Instead ofHour() -> time[i].

Yes, you helped that, now I want to limit the time. Exclude counting from 5pm to 11pm.

  for(int i=limit-2; i>0; i--) 
     {
     if(Hour()>=17&&Hour()<=11)continue;
      if(i%2==0) 
        {
         if(open[i]<close[i] && open[i+1]>close[i+1]) 
           {
            k1++;
           // if(k1>max) {max=k1; dat_max=time[i];}
            if(k1>=4)Print("Num: ",k1,"dat_max ",time[i]);
            SetText("Obj_"+(string)time[i],(string)k1,time[i],high[i],Arr);
           }
         else k1=0;
         
           } else {
         if(open[i]<close[i] && open[i+1]>close[i+1]) 
           {
            k2++;
            //if(k2>max){ max=k2; dat_max=time[i];}
            if(k2>=4)Print("Num: ",k2,"dat_max ",time[i]);
            SetText("Obj_"+(string)time[i],(string)k2,time[i],high[i],Arr);
           }
         else k2=0;
         
        }
      
     }