Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 238
You are missing trading opportunities:
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
Registration
Log in
You agree to website policy and terms of use
If you do not have an account, please register
Hello again I would like to raise a question about placing a stop on the last order.
I want to clarify that in the tester sometimes a stop is not placed on the last order.
This has not happened so far on the forward tests. But as they say, why wait?)
Code
Can you suggest the following thing, there are N EAs on the account, which under certain conditions can all open an order at the same time, each of them checks no more than 1 order on the account, but sometimes I end up with N orders, what can I do?
read articles
Pause between trades
Error 146 ("Trade flow busy") and how to deal with itread articles
Pause between trades
Error 146 ("Trade flow busy") and how to deal with itThank you!!!
Are you sure that this part of the code is the source of the problem? From what you have shown it is difficult to draw conclusions - there are a lot of unknown variables and you can't see the opening itself.
To find the reason yourself, print or display the values of the variables with comments. Then you will be able to see their values at any time.
This is based on eOpenByTime Expert Advisor from Mr. Kim. I also added a trailing stop, closed at the end of the week and opened at a certain day of the week. In this form the Expert Advisor works as it should be.
The deal opening is performed in the following way, I have added only the day of a week of deal opening but there is nothing to screw up here
if (DayOfWeek()==DayOfWeekOpen && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeOpen) && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeOpen)+Duration) { if (!ExistPositions("", Sell, MagicNumber)) { double sl, tp; if (Sell) { if (StopLoss>0) sl=Bid+StopLoss*Point; else sl=0; if (TakeProfit>0) tp=Bid-TakeProfit*Point; else tp=0; } else { if (StopLoss>0) sl=Ask-StopLoss*Point; else sl=0; if (TakeProfit>0) tp=Ask+TakeProfit*Point; else tp=0; } OpenPosition("", Sell, Lots, sl, tp, MagicNumber); } }To be honest, I do not quite understand why TimeCurrent is compared to TimeCurrent + TimeTradeOpen where TimeTradeOpen is an external parameter of the TimeTradeOpen = "19:51" type. (This is actually the position opening time we need.) I also do not understand why this comparison works. Duration is the time during which the Expert Advisor will try to open a position.
By analogy, I have added a closing of a position on Friday.
So far, everything was working.
Then I wanted to add a condition that looks at a candlestick at a given time and a given day of the week, if the candlestick is bullish, then sell, if it is bearish, then buy.
In the same way, I have copied these 3 lines, which have worked before, but now for some reason they do not want to.
After that the code for position opening follows. TimeTradeIf has a similar format TimeTradeIf = "19:51" and is also set via external parameters.
The whole code is quite long, do you need to insert?
Hello again I would like to raise a question about placing a stop on the last order.
I want to clarify that in the tester sometimes a stop is not placed on the last order.
This has not happened so far on the forward tests. But as they say, why wait?)
Code
Found the problem. The code is OK. it's the writer who demands the impossible ))
It is based on eOpenByTime Expert Advisor from esteemed Mr. Kim. I also added a trailing stop, closed at the end of the week and opened at a certain day of the week. In this form the EA works as it should.
The deal opening is performed in the following way, only the day of the week of deal opening is added by me but there is nothing to screw up here
To be honest, I do not quite understand why TimeCurrent is compared with TimeCurrent + TimeTradeOpen, where TimeTradeOpen is an external parameter of the TimeTradeOpen = "19:51" type. (This is actually the position opening time we need.) I also do not understand why this comparison works. Duration is the time during which the Expert Advisor will try to open a position.
By analogy, I have added a closing of a position on Friday.
So far, everything was working.
Then I wanted to add a condition that looks at a candlestick at a given time and a given day of the week, if the candlestick is bullish, then sell, if it is bearish, then buy.
In the same way, I have copied these 3 lines, which have worked before, but now for some reason they do not want to.
After that the code for position opening follows. TimeTradeIf has a similar format TimeTradeIf = "19:51" and is also set via external parameters.
The entire code is quite long, should I paste it?
To be honest, I have already forgotten what the problem is. In this code section I see that only short positions are checked and the opening of short positions is also specified:
To be honest, I've forgotten what the problem is. In this code section I see that only short positions are checked and only short positions are opened:
The Sell variable is external and contains true or false, 1 or 0, respectively,
Kim's is eOpenByTime.
The logic, the algorithm of actions, is flawed.
If he would drop the start() function and variables, what they carry, then we can suggest something.
Artem, this is correct, the Sell variable is external and carries the value true or false, 1 or 0 respectively,
I looked at Kim's, eOpenByTime.
The logic, the algorithm of actions, is flawed.
If he would show the start() function and variables, what they bear, then we can suggest something.
The idea is this: if a candle is bullish on a certain DayOfWeekIf at a certain time TimeTradeIf, then Sell = true (sell), if it is bearish, then Sell = false (buy).
It should be, but in the test I only get trades for sale.
eOpenByTime allows to open deal at given time, I added more at given day of week if (DayOfWeek()==DayOfWeekOpen, where DayOfWeekOpen = 1,2,3,4,5
I'm attaching the code in two parts, there's no other way around, I've highlighted the problem condition. Everything works as it should without it, i.e. we set Sell and open a deal at the right time at the right day of the week.
Only trawl has been cut out.
//+----------------------------------------------------------------------------+ //| e-OpenByTime.mq4 | //| | //| Идея : Владимир, sibtrade@hotbox.ru | //| Реализация: Ким Игорь В. aka KimIV, http://www.kimiv.ru | //| | //| 2007.04.27 Открытие позиции в заданное время. | //| 2008.04.10 Параметр MarketWatch. | //| 2008.04.14 Параметр Duration. | //+----------------------------------------------------------------------------+ #property copyright "Владимир & KimIV" #property link "http://www.kimiv.ru" //------- Внешние параметры советника -----------------------------------------+ extern string _P_Trade = "---------- Параметры торговли"; extern int DayOfWeekOpen = 3; // День недели открытия позиции extern string TimeTradeOpen = "19:51"; // Время открытия позиции extern int DayOfWeekIf = 3; // День недели условия extern string TimeTradeIf = "19:51"; // Время условия extern int DayOfWeekClose = 5; // День недели закрытия позиции extern string TimeTradeClose = "19:51"; // Время закрытия позиции extern int Duration = 300; // Продолжительность в секундах //extern bool Sell = False; // True-Sell, False-Buy extern double Lots = 0.1; // Размер лота extern int StopLoss = 30; // Размер стопа в пунктах extern int TakeProfit = 60; // Размер тейка в пунктах extern string _P_Expert = "---------- Параметры советника"; extern int MagicNumber = 0; extern int NumberAccount = 0; // Номер торгового счёта extern bool UseSound = True; // Использовать звуковой сигнал extern string NameFileSound = "expert.wav"; // Наименование звукового файла extern bool ShowComment = True; // Показывать комментарий extern bool MarketWatch = True; // Запросы под исполнение "Market Watch". extern int Slippage = 3; // Проскальзывание цены extern int NumberOfTry = 5; // Количество торговых попыток //------- Глобальные переменные советника -------------------------------------+ bool gbDisabled = False; // Флаг блокировки советника bool gbNoInit = False; // Флаг неудачной инициализации color clOpenBuy = LightBlue; // Цвет значка открытия покупки color clOpenSell = LightCoral; // Цвет значка открытия продажи bool Sell; //------- Подключение внешних модулей -----------------------------------------+ #include <stdlib.mqh> // Стандартная библиотека МТ4 //int deinit() // { //---- //---- // return(0); // } //+----------------------------------------------------------------------------+ //| | //| ПРЕДОПРЕДЕЛЁННЫЕ ФУНКЦИИ | //| | //+----------------------------------------------------------------------------+ //| Функция инициализации | //+----------------------------------------------------------------------------+ void init() { gbNoInit=False; if (!IsTradeAllowed()) { Message("Для нормальной работы советника необходимо\n"+ "Разрешить советнику торговать"); gbNoInit=True; return; } if (!IsLibrariesAllowed()) { Message("Для нормальной работы советника необходимо\n"+ "Разрешить импорт из внешних экспертов"); gbNoInit=True; return; } if (!IsTesting()) { if (IsExpertEnabled()) Message("Советник будет запущен следующим тиком"); else Message("Отжата кнопка \"Разрешить запуск советников\""); } } //+----------------------------------------------------------------------------+ //| Функция деинициализации | //+----------------------------------------------------------------------------+ void deinit() { if (!IsTesting()) Comment(""); ObjectDelete("SLb"); //Трейлингстоп ObjectDelete("SLs"); //Трейлингстоп return(0); } //+----------------------------------------------------------------------------+ //| expert start function | //+----------------------------------------------------------------------------+ void start() { if (gbDisabled) { Message("Критическая ошибка! Советник ОСТАНОВЛЕН!"); return; } if (gbNoInit) { Message("Не удалось инициализировать советник!"); return; } if (!IsTesting()) { if (NumberAccount>0 && NumberAccount!=AccountNumber()) { Comment("Торговля на счёте: "+AccountNumber()+" ЗАПРЕЩЕНА!"); return; } else Comment(""); if (ShowComment) { string st="CurTime="+TimeToStr(TimeCurrent(), TIME_MINUTES) +" TimeTrade="+TimeTradeOpen +" Позиция="+GetNameOP(Sell) +" Lots="+DoubleToStr(Lots, 1) +" StopLoss="+DoubleToStr(StopLoss, 0)+" п." +" TakeProfit="+DoubleToStr(TakeProfit, 0)+" п." +IIFs(MarketWatch, " MarketWatch", "") ; Comment(st); } else Comment(""); } // ================= Условие ===================================== //Sell = false; if (DayOfWeek()==DayOfWeekIf && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeIf) && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeIf)+Duration) { if (iClose("XAUUSD",PERIOD_H1,0)-iOpen("XAUUSD",PERIOD_H1,0)>=0) Sell = true; if (iOpen("XAUUSD",PERIOD_H1,0)-iClose("XAUUSD",PERIOD_H1,0)>0) Sell =false; } // Без условия все работает правильно. Sell тогда задаем во внешних параметрах. // ================= Открытие позиции ===================================== if (DayOfWeek()==DayOfWeekOpen && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeOpen) && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeOpen)+Duration) { if (!ExistPositions("", Sell, MagicNumber)) { double sl, tp; if (Sell) { if (StopLoss>0) sl=Bid+StopLoss*Point; else sl=0; if (TakeProfit>0) tp=Bid-TakeProfit*Point; else tp=0; } else { if (StopLoss>0) sl=Ask-StopLoss*Point; else sl=0; if (TakeProfit>0) tp=Ask+TakeProfit*Point; else tp=0; } OpenPosition("", Sell, Lots, sl, tp, MagicNumber); } } //================= Закрытие всех ордеров в пятницу ===================================== if (DayOfWeek()==DayOfWeekClose && TimeCurrent()>=StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeClose) && TimeCurrent()<StrToTime(TimeToStr(TimeCurrent(), TIME_DATE)+" "+TimeTradeClose)+Duration) { if (OrdersTotal()>0) { for (int i=OrdersTotal()-1; i>=0; i--) { if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) { if (OrderType()==OP_BUY) { RefreshRates(); OrderClose(OrderTicket(),OrderLots(),Bid,1000); return(0); } if (OrderType()==OP_SELL) { RefreshRates(); OrderClose(OrderTicket(),OrderLots(),Ask,1000); return(0); } } } } } } //+----------------------------------------------------------------------------+ //| | //| ПОЛЬЗОВАТЕЛЬСКИЕ ФУНКЦИИ | //| | //+----------------------------------------------------------------------------+ //| Автор : Ким Игорь В. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Версия : 06.03.2008 | //| Описание : Возвращает флаг существования позиций | //+----------------------------------------------------------------------------+ //| Параметры: | //| sy - наименование инструмента ("" - любой символ, | //| NULL - текущий символ) | //| op - операция (-1 - любая позиция) | //| mn - MagicNumber (-1 - любой магик) | //| ot - время открытия ( 0 - любое время открытия) | //+----------------------------------------------------------------------------+ bool ExistPositions(string sy="", int op=-1, int mn=-1, datetime ot=0) { int i, k=OrdersTotal(); if (sy=="0") sy=Symbol(); for (i=0; i<k; i++) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { if (OrderSymbol()==sy || sy=="") { if (OrderType()==OP_BUY || OrderType()==OP_SELL) { if (op<0 || OrderType()==op) { if (mn<0 || OrderMagicNumber()==mn) { if (ot<=OrderOpenTime()) return(True); } } } } } } return(False); } //+----------------------------------------------------------------------------+ //| Автор : Ким Игорь В. aka KimIV, http://www.kimiv.ru | //+----------------------------------------------------------------------------+ //| Версия : 01.09.2005 | //| Описание : Возвращает наименование торговой операции | //+----------------------------------------------------------------------------+ //| Параметры: | //| op - идентификатор торговой операции | //+----------------------------------------------------------------------------+ string GetNameOP(int op) { switch (op) { case OP_BUY : return("Buy"); case OP_SELL : return("Sell"); case OP_BUYLIMIT : return("Buy Limit"); case OP_SELLLIMIT: return("Sell Limit"); case OP_BUYSTOP : return("Buy Stop"); case OP_SELLSTOP : return("Sell Stop"); default : return("Unknown Operation"); } }What's the problem, it works.