Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 105

 
Forexman77:


Hello!

Sorry for bringing up a relatively old topic. I have understood everything with the code.

Now I have a puzzle, how to open a trade. For example, right after a given range, we are looking for

The price is lower than the maximum by a certain amount of points. We open a deal.

I have tried to add such a code and run it in the tester, but it does not open deals.

What to do?

This should work, I haven't tested it myself, as the terminal is busy optimizing another EA so far

#define magic 123456789
extern int StartHour=16;
extern int StartMinute=1;
extern int StopHour=17;
extern int StopMinute=59;
bool Flag=true; // Флаг разрешения открытия позиции, чтобы не плодить бесконечное число ордеров
double lots=0.1;// размер лота
double sl=100;  // стоплосс в пунктах
double tp=100;  // тейкпрофит в пунктах
int ticket=-1;
int OldBar;
int init() {
 sl=NormalizeDouble(sl*Point,Digits);//стоплосс в поинтах
 tp=NormalizeDouble(tp*Point,Digits);//тейкпрофит в поинтах
 return(0);}
int deinit() {return(0);}
int start(){
 static double Maximum=-1;
 int StartTime=StartHour*60+StartMinute;
 int StopTime=StopHour*60+StopMinute;
 if(StopTime<=StartTime) {Print("ERROR: Неправильные времена"); return(0);}
 int CurrentMinutesFromDayStart=Hour()*60+Minute();// Текущее время в минутах от начала дня
 datetime td=iTime(Symbol(),PERIOD_D1,0);// Время открытия дневного бара в секундах от 01.01.1970
 if(CurrentMinutesFromDayStart<StartTime) {Maximum=-1;Flag=true;}// Если StartTime еще не настало, то после StopTime нужно пересчитать Maximum и можно открывать ордер
// В 22:55 Принудительно закрываем ордер
 if(CurrentMinutesFromDayStart>22*60+55 && ticket>=0) if(OrderSelect(ticket,SELECT_BY_TICKET)) if(OrderCloseTime()==0) if(OrderClose(ticket,OrderLots(),Ask,30,Magenta)) ticket=-1;
 if(CurrentMinutesFromDayStart>StopTime && Maximum<0) {// если максимум ещё не посчитан
  datetime ts=td+StartTime*60;// начало временного диапазона в секундах от 01.01.1970
  int start= iBarShift(Symbol(),PERIOD_M1,ts,false);// смещение бара, которому принадлежит ts
  ts=td+StopTime*60;// конец временного диапазона в секундах от 01.01.1970
  int count= iBarShift(Symbol(),PERIOD_M1,ts,false);// смещение бара, которому принадлежит ts
  count=start-count;// Сколко баров длится временной интервал
  Maximum=iHigh(Symbol(),PERIOD_M1,iHighest(Symbol(),PERIOD_M1,MODE_HIGH,count,start));//Находим максимум на заданном временном интервале
 }
 if(Maximum>0 && Flag) {
  double signal = Maximum - Bid;
  if (signal-12*Point>0.0) { // к примеру если ниже максимума на 12 пунктов, в этом случае откроем SELL                                       
   ticket=OrderSend(Symbol(),OP_SELL,lots,Bid,30,Ask+sl,Ask-tp,"My order",magic,0,Blue);
   if(ticket>=0) Flag=false;// Ордер открылся, сегодня больше не открываем.         
  }
 }
 return(0);
}
 
Sepulca:

This should work, I haven't tested it myself as the terminal is busy optimising another EA

Thank you!
 
Sepulca:

This should work, I haven't tested it myself as the terminal is busy optimising another EA


// В 22:55 Принудительно закрываем ордер
 if(CurrentMinutesFromDayStart>22*60+55 && ticket>=0) if(OrderSelect(ticket,SELECT_BY_TICKET)) if(OrderCloseTime()==0) if(OrderClose(ticket,OrderLots(),Ask,
   30,Magenta)) ticket=-1;
Can I remove this line or it won't work without it? I do not understand why I have to close the order?
 
Forexman77:

Can this line be removed or will it not work without it? I do not understand why I have to close an order?

Of course you can remove it, it is only to test it and not to multiply the number of open orders. This is just a training example of an EA. It opens no more than one SELL order per day. And in your EA, you should decide yourself how to close orders: by stop loss, take profit or other conditions. The time 22:55 is chosen because many brokerage companies significantly increase spread, especially on Fridays after 11:00 PM. You may think that we should open more than one order per day. And this is an example for an order placed to one side. We should look for the minimum by analogy. This code as an example, I hope it will facilitate the creation of my own EA)
 

Hello!

I'm a dummy, but I want to change something in the code myself...

Any advice, if you don't mind your time...

I have a few questions:

1. How do I add a variable "stop loss" to my EA ? I want to be able to change it, of course.

2. How to enable my EA to add a comment for each of my trades ?

3. How to add an EA with a magic number?

 
K-o-t:

Hello!

I'm a dummy, but I want to change something in the code myself...

Any advice, if you don't mind your time...

I have a few questions:

1. How do I add a variable "stop loss" to my EA ? I want to be able to change it, of course.

2. How to enable my EA to add a comment for each of my trades ?

3. How to add an EA with a magic number?

1. external double StopLoss=100.0;//add stop loss variable

2-3. int ticket=OrderSend(Symbol, TypeOfOrder,LotsOfOrder, OpenPriceOfOrder,Slippage, OpenPriceOfOrder+/-StopLoss,OpenPriceOfOrder-/+TakeProfit,YourMagicNumber,0, CLR_NONE) ;

4. READ!

 
artmedia70:

Here's the joint:

 for (int i=OrdersHistoryTotal()-1; i>=0; i--)
   {
      if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
      if (OrderMagicNumber() != i_magic) continue;
      if (OrderSymbol() != Symbol()) continue;
      if (OrderType() > 1) continue;               // Все удалённые отложки нас не интересуют.. 
  
      if (lastOrderCloseTime < OrderCloseTime())   // Находим время закрытия..
          lastOrderCloseTime = OrderCloseTime();   // ..последней закрытой позиции в истории
      
      if (MathAbs(OrderTakeProfit() - OrderOpenPrice()) < i_tp * pt) return(0); // ЗДЕСЬ ВЫХОДИМ ПРИ ПЕРВОМ ВСТРЕЧНОМ
      
      lastOOTHist = OrderOpenTime();   // Тогда время открытия последней закрытой позиции из истории
   }
Actually, yes, I had a fresh look this morning. It turns out that the first order, which has more profit than required, gives a signal to continue the function (i.e. is not missed) and then, of course, everything will be wrong.
 

Good afternoon!

Can you tell me how to set up the optimisation of the Expert Advisor so that it shows negative pass results as well?

 
filpan:

Good afternoon!

Can you tell me how to set up the optimisation of the Expert Advisor so that it shows negative pass results as well?

In the tab with optimization results, right-click on any result and uncheck "do not show useless results" (or something like that).
 
Found it, thanks!