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

 
Vitalie Postolache:
The error is somewhere higher up in the code, in the order selection area.
I don't touch the rest of it.
 
spoiltboy:
I don't touch the rest.
In any case, you need to see the preceding and following code, not just the condition lines.
 
Artyom Trishkin:
In any case you need to see the preceding and following code, not just the condition lines.
extern int pointsl=100, pointtp=100, MagicB=111111, MagicS=2222, bars=10; extern double lotB=0.1, lotS=0.1;
double slB, tpB, slS, tpS; double x=0, z=0;


void OnTick()
{
double maxpr1=9999; double minpr1=9999;

for(int shift1=0; shift1<bars; shift1++)
{double i=iHigh(Symbol(), PERIOD_CURRENT, shift1);
if (i>maxpr1){maxpr1=i;}}

for(int shiftA1=0; shiftA1<bars; shiftA1++)
{double y=iLow(Symbol(), PERIOD_CURRENT, shiftA1);
if (y<minpr1) {minpr1=y;}}

if (BuyLimitCount()==0 && BuyCount()==0){
slB=NormalizeDouble(minpr1-pointsl*Point,5);
tpB=NormalizeDouble(minpr1+pointsl*Point,5);
int ticketUP=OrderSend(Symbol(), OP_BUYLIMIT, lotB, minpr1, 3, slB, tpB, "", MagicB, 0, Red);
if (ticketUP==-1) Print("ERROR OP_BUY"); else Print("OP_BUY OK");}

if (SellLimitCount()==0 && SellCount() ==0){
slS=NormalizeDouble(maxpr1+pointsl*Point,5);
tpS=NormalizeDouble(maxpr1+pointsl*Point,5);
int ticketD=OrderSend(Symbol(), OP_SELLLIMIT, lotS, maxpr1, 3, slS, tpS, "", MagicS, 0, Blue);
if (ticketD==-1) Print("ERROR OP_SELL"); else Print("OP_SELL OK");}

if (x!=maxpr1){x=maxpr1; OrderDelete(ticketD);}
if (z!=minpr1){z=minpr1; OrderDelete(ticketUP);}


double maxpr=-9999; double minpr=9999;

for(int shift=0; shift<bars; shift++)
{double e=iHigh(Symbol(), PERIOD_CURRENT, shift);
if (e>maxpr){maxpr=e;}}

for(int shiftA=0; shiftA<bars; shiftA++)
{double r=iLow(Symbol(), PERIOD_CURRENT, shiftA);
if (r<minpr) {minpr=r;}}

string a;
if(bars==1)a="bar:";
else a= IntegerToString(bars,1) + " bars: ";
Comment("Last ", a, "max ", DoubleToStr(maxpr, 5), ", min ", DoubleToStr(minpr, 5),";
}

int BuyLimitCount(){
int count=0;
for(int i=OrdersTotal()-1; i>=0; i--){
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true){
if(OrderMagicNumber()==MagicB){
if(OrderType()==OP_BUYLIMIT)
count++;}}return(count);}

int BuyCount(){
int count=0;
for(int i=OrdersTotal()-1; i>=0; i--){
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true){
if(OrderMagicNumber()==MagicB){
if(OrderType()==OP_BUY)
count++;}}}return(count);}

int SellLimitCount(){
int count=0;
for(int i=OrdersTotal()-1; i>=0; i--){
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true){
if(OrderMagicNumber()==MagicS){
if(OrderType()==OP_SELLLIMIT)
count++;}}}return(count);}

int SellCount(){
int count=0;
for(int i=OrdersTotal()-1; i>=0; i--){
if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES)==true){
if(OrderMagicNumber()==MagicS){
if(OrderType()==OP_SELL)
count++;}}}return(count);}
 
spoiltboy:
...
And anyway, what are you trying to do with this, sorry, creepy code?
 
spoiltboy:

You can't clean up the code and paste it properly with the SRC, can you?

Why don't you apply OrderSelect before trying to delete?

 
spoiltboy:
...

I don't know why you need so many loops there, when you can fill in the required structure fields about the number of orders and positions in one.

I have removed unnecessary things, and I have also removed the deletion. You do not need to delete by ticket (you still need to know it before deleting), but in the loop to find the right order by index, and delete it.

So, we need one more function to search and delete orders, which should be called in case of a condition, but what kind of condition - I did not understand it right away when looking through your code, and I did not have time to look it through. Describe necessary conditions in words and we will tell you how to delete.

I had written it on my own, without looking, so there may be errors in the function filling the structure with the number of orders and positions - I have not checked it.

//--- input variables
input    double   LotB=0.1;      // Лот Buy
input    double   LotS=0.1;      // Лот Sell
input    int      Pointsl=100;   // StopLoss в пунктах
input    int      Pointtp=100;   // TakeProfit в пунктах
input    int      NumBars=10;    // Количество баров для поиска Max/Min
input    int      Magic=100500;  // Magic

//--- global variables
struct DataNumOrders
  {
   int buy;          // Количество позиций Buy
   int sell;         // Количество позиций Sell
   int buy_limit;    // Количество ордеров BuyLimit
   int buy_stop;     // Количество ордеров BuyStop
   int sell_limit;   // Количество ордеров SellLimit
   int sell_stop;    // Количество ордеров SellStop
  };
DataNumOrders numOrders;   // Количество ордеров
double lotB, lotS;
int    pointsl, pointtp, numBars;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   numBars=(NumBars<1?1:NumBars>Bars?Bars:NumBars);
   pointsl=(Pointsl<0?0:Pointsl);
   pointtp=(Pointtp<0?0:Pointtp);
   double minLot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);
   double maxLot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MAX);
   lotB=(LotB<minLot?minLot:LotB>maxLot?maxLot:LotB);
   lotS=(LotS<minLot?minLot:LotS>maxLot?maxLot:LotS);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   //--- заполним структуру количеством ордеров и позиций
   GetNumOrders(Symbol(),Magic,numOrders);
  
   //--- найдём максимальную и минимальную цены за bars свечей
   double maxPrice=0.0; double minPrice=DBL_MAX;
   for(int i=0; i<numBars; i++) {
      double max_i=iHigh(Symbol(),PERIOD_CURRENT,i);
      if(max_i>maxPrice) maxPrice=max_i;
      double min_i=iLow(Symbol(),PERIOD_CURRENT,i);
      if(min_i<minPrice) minPrice=min_i;
      }

   //--- выставим BuyLimit
   if(numOrders.buy_limit==0 && numOrders.buy==0) {
      double slB=(pointsl==0?0:NormalizeDouble(minPrice-pointsl*Point(),Digits()));
      double tpB=(pointtp==0?0:NormalizeDouble(minPrice+pointtp*Point(),Digits()));
      int ticketUP=OrderSend(Symbol(), OP_BUYLIMIT, lotB, minPrice, 3, slB, tpB, "", Magic, 0, clrRed);
      if(ticketUP==-1) Print("ERROR OP_BUY");
      else Print("OP_BUY OK");
      }
   //--- выставим SellLimit
   if(numOrders.buy_limit==0 && numOrders.sell==0) {
      double slS=(pointsl==0?0:NormalizeDouble(maxPrice+pointsl*Point(),Digits()));
      double tpS=(pointtp==0?0:NormalizeDouble(maxPrice-pointtp*Point(),Digits()));
      int ticketD=OrderSend(Symbol(), OP_SELLLIMIT, lotS, maxPrice, 3, slS, tpS, "", Magic, 0, clrBlue);
      if(ticketD==-1) Print("ERROR OP_SELL");
      else Print("OP_SELL OK");
      }

   //--- Тут должно быть удаление, но не понятно при каких условиях. Опишите их
  
  
   //---
   string a=(numBars==1)?"bar: ":IntegerToString(numBars,1)+" bar's: ";
   Comment("Last ", a, "max ", DoubleToStr(maxPrice, Digits()), ", min ", DoubleToStr(minPrice, Digits()),".");
  }
//+------------------------------------------------------------------+
//| Записывает в структуру количество позиций и отложенных ордеров   |
//+------------------------------------------------------------------+
void GetNumOrders(string symbol_name, int magic_number, DataNumOrders &number_of) {
   ZeroMemory(number_of);
   for(int i=OrdersTotal()-1; i>=0; i--) {
      if(OrderSelect(i,SELECT_BY_POS)) {
         if(OrderMagicNumber()!=magic_number) continue;
         if(OrderSymbol()!=symbol_name)       continue;
         if(OrderType()==OP_BUY)       number_of.buy++;
         if(OrderType()==OP_BUYLIMIT)  number_of.buy_limit++;
         if(OrderType()==OP_BUYSTOP)   number_of.buy_stop++;
         if(OrderType()==OP_SELL)      number_of.sell++;
         if(OrderType()==OP_SELLLIMIT) number_of.sell_limit++;
         if(OrderType()==OP_SELLSTOP)  number_of.sell_stop++;
         }
      }
}
//+------------------------------------------------------------------+
 
Artyom Trishkin:
In general, what are you trying to do with this, sorry, creepy code?
The EA counts min and max for the last X bars and places orders on them. Then, if the high or low decreases or increases, we have to delete the order and open it using the new data.


 

how to write the following :

If the price has changed by 1% say OPEN day more than Slose day by 1%

 
Movlat Baghiyev:

how to write the following :

If the price has changed by 1%, say the OPEN day is greater than the Close day by 1%.

That's different, now it's clear what the 1% is relative to ;)

if(Open[x] > Close[x]+Open[x]*0.01) {code}
 
spoiltboy:
The Expert Advisor counts min and max for the last X bars and places orders by them. Further, if there is a decrease of maximum or increase of minimum, you need to delete the corresponding order and open it by the new data.


Why delete when you can modify the setting price and stop and takeout relative to the new level? After all, you only place pending orders when there are no pending orders and no market positions. So: if there is a pending order in the market and there is no corresponding market position, then we just need to modify the prices at the pending order - the set price to a new level and its stop order - respectively to the new level.

Every time you need to remember the found prices of Max and Min. If the current found price of Max is less than the previous one, we modify the pending BuyLimit and memorise the new price of Max. For Min price, mirror it.

Reason: