I am struggling with this little mq4 piece of code.
I get the following error
return value of ‘OrderModify’ should be checked ea3WayHedging_1-9.mq4 399 10
{
OrderModify(orders[0].ticket, NormalizeDouble(Ask + TrailingDistanceOrder1*point, Digits), OrderStopLoss(), OrderTakeProfit(), OrderExpiration());
}
{
if ( ! OrderModify(orders[0].ticket, NormalizeDouble(Ask + TrailingDistanceOrder1*point, Digits), OrderStopLoss(), OrderTakeProfit(), OrderExpiration())) continue;
}
then I get this error
‘;’ — ‘continue’ must be used within some loop only ea3WayHedging_1-9.mq4 399 172
any idea what I am doing wrong and how to correct it would be appreciated.
Franzel
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
int Counted_bars; // Количество просчитанных баров
Counted_bars=IndicatorCounted(); // Количество просчитанных баров
int i=Bars-Counted_bars-1; // Индекс первого непосчитанного
if (i>History-1) // Если много баров то ..
i=History-1; // ..рассчитывать заданное колич.
while(i>=0) // Цикл по непосчитанным барам
{
double MA_l_0 = iMA(NULL,0,perMA_1,0,modeMA_1,PRICE_CLOSE,i);
double MA_l_1 = iMA(NULL,0,perMA_1,0,modeMA_1,PRICE_CLOSE,i+1);
double MA_g_0 = iMA(NULL,0,perMA_2,0,modeMA_2,PRICE_CLOSE,i);
double MA_g_1 = iMA(NULL,0,perMA_2,0,modeMA_2,PRICE_CLOSE,i+1);
double STD_0 = iStdDev(NULL,0,perSTD,0,modeSTD,PRICE_CLOSE,i);
double STD_1 = iStdDev(NULL,0,perSTD,0,modeSTD,PRICE_CLOSE,i+1);
//double ELR_1=((High[i]+Low[i])/2)-iMA(NULL,0,perELR,0,1,PRICE_CLOSE,i);
//double ELR_2=((High[i]+Low[i])/2)-iMA(NULL,0,perELR,0,1,PRICE_CLOSE,i+1);
//Buy
if(MA_l_0 > MA_l_1 &&
MA_g_0 > MA_g_1 &&
STD_0 > STD_1)
if(Hour() < 9 || Hour() > 20) UPBuffer[i] = 0;
else UPBuffer[i] = Low[i];
else
//Sell
if(MA_l_0 < MA_l_1 &&
MA_g_0 < MA_g_1 &&
STD_0 > STD_1 )
if(Hour() < 9 || Hour() > 20) DNBuffer[i] = 0;
else DNBuffer[i] = High[i];
i--;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
Так и не разобрался. Написал 4 советника с разными тралами. У всех в тесте ошибка 130. Не знаю почему она возникает и как сделать так, чтобы ее не было. Еще трал по фракталам вроде работает, но когда тестируешь с визуализацией — тест дальше первой сделки не идет( отрывается первый ордер и все, дальше никаких признаков жизни). А трала по pSAR заметил такую вещь. Советник открыл БАЙ, но цена тут же пошла вниз. А значения то индикатора получается сверху свечи, то есть стоплосс не может быть больше текущей цены. И у нас открыта позиция на долгое время без стоплосса. На скрине отметил это красной стрелкой. Подскажите как быть в данной ситуации?
Вот поправленный трал с фракталами:
void Trailing()
{
SL = 0;
fractal_down = NormalizeDouble(iFractals(NULL,0,MODE_LOWER,5),Digits);
fractal_up = NormalizeDouble(iFractals(NULL,0,MODE_UPPER,5),Digits);
for (int i =0;i {
if (OrderSelect(i,SELECT_BY_POS))
{
if (OrderSymbol()==Symbol()&&OrderMagicNumber()==Magic)
if (OrderType()==OP_BUY)
{
if(fractal_down>0)
{
SL=NormalizeDouble(fractal_down,Digits);
if (OrderStopLoss()!=SL)
{
if(SL bool rez = OrderModify(OrderTicket(),OrderOpenPrice(),SL,0,0);
}
}
}
if (OrderType()==OP_SELL)
{
if(fractal_up>0)
{
SL=NormalizeDouble(fractal_up,Digits);
if (OrderStopLoss()!=SL)
{
if(SL > Ask + MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
bool rez = OrderModify(OrderTicket(),OrderOpenPrice(),SL,0,0);
}
}
}
} }
}
Ошибка 130 — это неправильные стопы.Возможно просто стоп-лосс который Вы хотите разместить находится слишком близко
от текущей цены.
Сделайте проверку
if(SL > Ask + MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
Изменено 4 августа, 2015 пользователем Konstebl
Блог им. andresh
- 10 июня 2014, 16:55
- |
- Андрэ
-
попробовал запустить советник в МТ4 на MQL4:
extern int H = 14;
extern int M = 25;
int start()
{
if(OrdersTotal()==0 && Hour( )==H && Minute( ) ==M)
OrderSend(«USDJPY», OP_SELL,0.1,Bid,0,Ask+200*Point,Ask-200*Point,»»,123,0,Red);
}
и никак не могу разобраться, чего не хватает. ошибок нет, но есть 2 предупреждения:
return value of ‘OrderSend’ should be checked
not all control paths return a value
не могу понять, что ещё нужно… Пожскажите пожалуйста, а?
- Ключевые слова:
- MQL4,
- советники
- хорошо
-
0
25 комментариев
- 10 июня 2014, 17:08
- Ответить
Язык недавно сильно переработали, возможно поэтому.
- 10 июня 2014, 17:11
- Ответить
The0bald, пасип. да туповат я, видимо. не могу там найти. ща ещё раз попробую.)
- 10 июня 2014, 17:13
- Ответить
5й параметр — проскальзывание может добавить, чтобы больше нуля.
а если это весь код то должен быть последним оператор return(0);
- 10 июня 2014, 17:12
- Ответить
Бартоломей Цигенбальг, Ура, второе замечание исчезло!!! Осталось только: return value of ‘OrderSend’ should be checked
- 10 июня 2014, 17:14
- Ответить
Андрэ, это про return. про 5-й параметр соображаю…
- 10 июня 2014, 17:15
- Ответить
Бартоломей Цигенбальг, это про return. про 5-й параметр соображаю… не поясните?
- 10 июня 2014, 17:16
- Ответить
так красивее и все всех устраивает )))
проскальзывание дает шанс открыться по рынку при худшей цене на заданное отклонение именно этим параметром.
- 10 июня 2014, 17:17
- Ответить
Бартоломей Цигенбальг, ух ты!!! ошибок нет! Спасибо большое! )))) буду ковыряться дальше! )
- 10 июня 2014, 17:24
- Ответить
Андрэ, не совсем правильно в коде, потому что он за минуту пока удовлетворяет условиям может кучу ордеров наоткрывать )))
- 10 июня 2014, 17:26
- Ответить
не не норм. там есть проверка на количество открытых ордеров
- 10 июня 2014, 17:35
- Ответить
Бартоломей Цигенбальг, тоже присмотрелся, сообразил! )))) спасибо огромное! плюсануть не могу, плюсовалка не позволяет)
- 10 июня 2014, 17:37
- Ответить
имхо, лучше с mql5 начать изучение. 4 недавно сильно переделали — книга не актуальна, справка не доделана, не понятно какие функции заменили на аналог из мт5 какие старые оставили, косяки наверняка есть после серьезной переработки.
- 10 июня 2014, 17:44
- Ответить
The0bald, логично, НО, эти советники на МТ4 не работают, насколько я знаю. это придётся и платформу менять, а не хотелось бы.
- 10 июня 2014, 17:46
- Ответить
Андрэ, На новой МТ4 старые исходники все равно придется переделывать.
- 10 июня 2014, 18:24
- Ответить
The0bald, возможно. просто у меня сейчас 2 робота на МТ4 работают, я доволен. вот, взялся сам изучать роботописательство. пока я «БЛИЖЕ» к МТ4. ) вы пишете сами? успешно?
- 10 июня 2014, 18:28
- Ответить
Андрэ, Пишу давно, правда индикаторы в основном
- 10 июня 2014, 18:30
- Ответить
The0bald, Привет, можно обращятся с просьбой по поводу mql если не трудно?
- 10 июня 2014, 21:00
- Ответить
нужно посмотреть на один индюк, выдает сигнал не всегда а нужно чтобы всегда выдал, если вам удобно можно в скайп общятся, мой скайп dimii1000
- 10 июня 2014, 22:17
- Ответить
в личку не могу писать, рейтинга не хватает (( я тут больше читатель, почту оставьте если не трудно, моя почта [email protected]
- 10 июня 2014, 22:42
- Ответить
- 10 июня 2014, 22:53
- Ответить
In this video, we want to create a trailing stop for sell trades, you can see here the red line is the railing stop and when the price falls the trailing stop will follow, so let’s find out how to code something like this in MQL4.
To do that please click on the little button here or press F4 in your Metatrader, now you should see the Metaeditor window and here you want to click on: “File/ New/ Expert Advisor (template)” from template, “Continue”, I will call this file: “SimpleSellTrailingStop”, click on “Continue”, “Continue” and “Finish”.
Now we can delete everything that is above the “OnTick” function and let’s also remove the two comment lines here.
Inside of the “OnTick” function we first want to check if we have no open orders that is done by checking if the function “OrdersTotal” delivers a value below 1, and if this is the case we want to open a demo sell trade, so let’s actually call that “sellticket” because if we don’t have open positions we will not find out if the trailing stop works.
Obviously, you wouldn’t do that on a real account without any entry signal, so let’s use “OrderSend” to open a demo trade (OP_SELL) for 10 micro lot.
Now we want to go through all the open orders, we use “OrdersTotal” to give us the current number of orders and we use a “for” loop to count down from the number of orders we have.
Inside of the “for” loop we use “OrderSelect”, the number of the current order, we want to select by position (SELECT_BY_POS) and we use “MODE_TRADES” as we want to find out everything about the open orders. In our case we want to check if the order belongs to the current chart, that is done by comparing the return value for the function “OrderSymbol” with the return value of the function “Symbol()” and I would also like to find out if the current order type equals “OP_SELL” because this is what we need to find the sell orders.
In the next step we need to find out if the order stop loss (OrderStopLoss) equals 0 (zero) or if the order stop loss (OrderStopLoss) is too high and is bigger than the current Bid price plus 150 points, and if this is the case we use “OrderModify” for the current ticket number (OrderTicket) that has the order open price (OrderOpenPrice), we now want to set the current stop loss to 150 points above the Bid price, the order take profit value (OrderTakeProfit) will not be changed, we don’t need any expiration date (0) and we don’t need a color (CLR_NONE).
Please don’t forget to close all the braces here and that’s about it.
If this is too complicated for you right now you maybe want to watch the other videos in this basic series or if you are interested you could also become a member of the premium course.
For now please click on the “Compile” button here or press F7, we get one warning that we should check the “OrderModify” return value but for this simple example we don’t need to do that so if you don’t have any errors here you can now click on the little button here or press F4 to go back to Metatrader.
In Metatrader we just pick a clean chart, right-click into the chart, select “Template/ Save Template” and we save it as “tester.tpl” as this is the template that is going to be used in the Strategy Tester. You can override the current one and when you are done you can click on “View/ Strategy Tester” or press CTRL and R, please pick the new file: “SimpleSellTrailingStop.ex4”, mark the option for the visual mode here and start a test.
And here we are, this is our sell trade, and we should see the trailing stop coming down.
There it is! And in this little video, you have learned how to create an automated trailing stop for sell trades and you have coded it yourself with a few lines of MQL4 code.




