Je vois, jusqu'à présent c'est plus facile pour moi d'écrire de cette façon.
Pouvez-vous me dire comment éviter que le "while" soit exécuté une fois de plus ?
Le "plus facile" n'existe pas - on n'écrit pas " dis-moi comment me débarrasser de tout ça BIENTÔT...". "Et dans le code, il faut garder à l'esprit que tout ce que vous avez écrit doit être compris par une machine muette.
Il y a donc deux voies : la bonne et la mauvaise.
Je comprends la paresse de le réécrire correctement, la paresse de comprendre les règles, alors dites-moi depuis combien de temps vous essayez d'écrire ce truc dans un fichier? Trois semaines...
Bonjour, pourriez-vous me dire comment écrire une condition : si une position ouverte(peu importe le nombre, la numérotation n'est pas nécessaire) ferme une ou plusieurs positions rentables, comment en ouvrir une nouvelle après cela ?
Stasjan: Bonjour, conseillez comment écrire une condition : si une position ouverte (peu importe combien, la numérotation n'est pas nécessaire) ferme une ou plusieurs positions rentables, comment ouvrir une nouvelle position (une) après cela ?
Éditez pour vous-même :
//---Поиск последнего отработавшего ордера для открытия очередной позиции --- for (orderIndex = (OrdersHistoryTotal() - 1); orderIndex >= 0; orderIndex--)
{
if (!OrderSelect(orderIndex, SELECT_BY_POS, MODE_HISTORY)) {Print("Ошибка при доступе к исторической базе (",GetLastError(),")");continue;}
if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != MagicNumber)) continue;
//------------------------- Принимаем в расчет только ордер, закрытый cамым крайним -----------------------if (time<OrderCloseTime()) //(сравниваем его с хранящимся в пероеменной time)
{
time=OrderCloseTime(); //если время закрытия ордера больше - ложим его в переменную int lastType = OrderType();
double lastLots = OrderLots();
double lastProfit = OrderProfit() + OrderSwap();
// Анализ только что закрывшегося ордера if (lastProfit >= 0.0)
{
//---Ордер закрылся с прибылью - обнуляем счетчик итераций, счетчик для подсчета последовательного убытка позиций колен лавины,//---текущий и суммарный убыток и открываемся стартовым лотом по тренду
Sum_Loss=0;
Iteration = 0;
if (Lot(StopLossPips)==false) //Функции передаем ширину накала
{
Comment("Пополните счет. Не хватает средств на минимальный лот. Советник остановлен."); // Если средств не хватает на мин, то выходPrint ("Пополните счет. Не хватает средств на минимальный лот. Lots_New = ",Lots_New, " AccountFreeMargin() = ", AccountFreeMargin() );
// Если средств не хватает на мин, то выходreturn (0);
}
// Ордер закрылся с прибылью, открываемся стартовым лотом // if (iOpen(Symbol(),signal_period,1)<iClose(Symbol(),signal_period,1))if(OsMA_1>0 && OsMA_2<0)
switch(Filter.Hour) // торги по времени Да=1/Нет=0
{
case0: WmOrderSend(Symbol(), OP_BUY, Lots_New, Ask, 0, 0, "старт после профита", MagicNumber); break;
case1: if (TimeHour(TimeCurrent()) >= Start && TimeHour(TimeCurrent()) < End)WmOrderSend(Symbol(), OP_BUY, Lots_New, Ask, 0, 0, "старт после профита", MagicNumber); break;
}
if(OsMA_1<0 && OsMA_2>0)
switch(Filter.Hour) // торги по времени Да=1/Нет=0
{
case0: WmOrderSend(Symbol(), OP_SELL, Lots_New, Bid, 0, 0, "старт после профита", MagicNumber); break;
case1: if (TimeHour(TimeCurrent()) >= Start && TimeHour(TimeCurrent()) < End)WmOrderSend(Symbol(), OP_SELL, Lots_New, Bid, 0, 0, "старт после профита", MagicNumber); break;
}
}
else
{
// Ордер закрылся с убытком - открываемся в ОБРАТНОМ направлении c увеличением объема позиции в соотв-ии с вариантом ММ, если // количество итераций не выше максимального if (Iteration <= Max_Iteration && VAR_MM == 0)
// Последующие лоты открываются по множителю в соответствие с числами ФИБО switch(Iteration) // Заголовок switch
{ // Начало тела switch case1 : Lots_New = lastLots * 1; lots = lastLots; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );break; //расчет нового объема case2 : Lots_New = lots * 2; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case3 : Lots_New = lots * 3; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case4 : Lots_New = lots * 5; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case5 : Lots_New = lots * 8; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case6 : Lots_New = lots * 13; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case7 : Lots_New = lots * 21; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case8 : Lots_New = lots * 34; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case9 : Lots_New = lots * 55; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case10: Lots_New = lots * 89; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case11: Lots_New = lots * 144; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case12: Lots_New = lots * 233; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case13: Lots_New = lots * 377; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case14: Lots_New = lots * 610; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case15: Lots_New = lots * 987; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
case16: Lots_New = lots * 1597; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New ); break;
default: Lots_New = lots * 2584; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );
} // Конец тела switch // ---------НОРМАЛИЗУЕМ НОВЫЕ РАСЧЕТНЫЕ ЛОТЫ И ОТКРЫВАЕМ ОЧЕРЕДНУЮ ПОЗИЦИЮ...
Lots_New = NormalizeLots(Lots_New);
if (lastType == OP_SELL) WmOrderSend(Symbol(), OP_BUY, Lots_New, Ask, 0, 0, "итерация" , MagicNumber);
if (lastType == OP_BUY) WmOrderSend(Symbol(), OP_SELL,Lots_New, Bid, 0, 0, "итерация" , MagicNumber);
} // к еlse - конец работы после предыдущего убыточного закрытого ордера return (0);
} // к if (time<OrderCloseTime()) - конец анализа и торгов по итогам закрытия самого свежего ордера // Найден закрытый ордер, но он старый break;
} // выход из цикла по истории ордеров
le "plus facile" n'existe pas - on n'écrit pas "dis-moi comment m'en débarrasser pendant que tu le fais"... "Vous devez garder à l'esprit que tout ce que vous avez écrit doit être compris par une pièce de matériel stupide.
Il y a donc deux voies : la bonne et la mauvaise.
Je comprends aussi les TRES paresseux pour réécrire correctement, TRES paresseux pour comprendre les règles, alors dites-moi depuis combien de temps vous harcelez votre sujet avec l'écriture dans un fichier ? Trois semaines....
Je résous les problèmes au fur et à mesure qu'ils se présentent, le Conseiller Expert que je programme depuis le 10 janvier. Cela fait 4 semaines. J'essaie de programmer en MQL depuis le 6 janvier.
orb: Je résous les problèmes au fur et à mesure qu'ils se présentent, le Conseiller Expert que je programme depuis le 10 janvier. Cela fait 4 semaines. J'essaie de programmer en MQL depuis le 6 janvier.
Vous devez écrire le principe correctement. les données sur l'entrée, sur la sortie, ce qui est dans le bloc principal. et puis optimiser le code. avec le temps, il deviendra une habitude, exactement l'optimisation et l'écriture correcte, et je mai vous comprendre et être comme vous, qui n'est pas l'optimisation pour un débutant.
Stasjan: Merci Roman, mais je n'arrive pas à comprendre d'où vient la moitié des variables car tout le code
#include <stdlib.mqh>#include <stderror.mqh>//#include <dynamic_channel.mqh> // динамический канал//#include <TrailingByFractals_LAVINA.mqh>//#include <TrailingByFractals.mqh>//// Внешние переменные (оптимизируются)externstring A0 = "Параметры ММ";
externdouble Lots = 0.1; // Стартовый лотexterndouble MaxRisk = 0; // риск на капитал в %// рассчитываем объем позиции взависимости от размера стопа, при заданном риске// например при депо 10 000 риск 1% при стопе 100 пп это будет примерно лот 0.1,// при стопе 200 пп уже лот должен быть 0.05, для того чтобы риск 1% остался на том же уровнеexternint MaxLoss = 90; // Максимально допустимая просадка в процентах от балансаexterndouble StopLoss = 0; // Стоплосс в пипсах - для пятизнака для йены, золота, серебра...int TakeProfitPips = 0; // Тейкпрофит в пипсах externint Period_ATR = 30; // значение АТР для расчета динамического каналаexterndouble Mul_TP = 4.0; // целевая прибыль в единицах волатильности (АТР)externdouble Mul_Sl = 0.8; // защитная остановка с последующим переворотом при ее сработке уже // увеличенным лотом в единицах волатильности (АТР)externint Max_Iteration = 36; // Максимальное количество итераций (ордеров) в мартине externint k = 2; // с какой итерации тралимexternint VAR_MM = 0; // используемый вариант усреднения в соотв-ии: множитель с числами ФИБО = 0 / множитель по арифметической прогрессии = 1// 2 - классический мартин - удвоение предыдущего объема с 3-его усреднения externstring Trailing = "---------- Параметры трала";
externint UseTrailing = 1; // Использовать = 1/не использовать = 0 трал externint type = 0; // вид трала - возможные значения: 0 - простой, 1 - по фракталам, 2 - по теням N свечей. externbool trlinloss = false; // Тралим только профит для всех видов траловexternstring A1 = "Параметры простого трала,пo фракталам,теням N баров,каналу,МА,SAR";
externint TralingStop = 1000; // дистанция простого трала в положительной зоне (пункты)externint indent = 100; // отступ (пунктов) при трале по фракталам, теням N свечей, ценовому каналу, МА,SARexternint bars_n = 10; // количество баров, для трала по их теням (от 1 и больше) или расчета границ канала externstring A2 = "Таймфрейм, время работы и параметры технических индикаторов";
//extern int t_trend_period =6; // 1-М1, 2-М5, 3-М15, 4-М30, 5-Н1...-для старшего фильтра, внутри которого работаемexternint s_trend_period = 3; // PERIOD_M1 1 1 минута// PERIOD_M5 5 5 минут// PERIOD_M15 15 15 минут// PERIOD_M30 30 30 минут// PERIOD_H1 60 1 час// PERIOD_H4 240 4 часа// PERIOD_D1 1440 1 день// PERIOD_W1 10080 1 неделя// PERIOD_MN1 43200 1 месяц// 0 (ноль) 0 Период текущего графика externint Filter.Hour=0; // Д-Фильтр: торговля по часам, вне этих часовых рамок новые сделки не открываем, но текущие итеpации завершаемexternint Start=9;
externint End=20;
// Параметры используемых индикаторовexternint Fast = 5;
externint Slow = 39;
externint Signal = 20;
externint MagicNumber = 7; // магик //extern int Period_MA = 20; // Период МА //extern int Period_ADX = 40; //extern int ADXOpenLevel = 12; //---- входные параметры индикатора iVAR//extern int n = 5;//extern int nBars = 100000;//extern int Iteration = 0; // счетчик для подсчета итераций, колен лавины//extern int Sum_Loss = 0;#include <TrailingByFractals_LAVINA.mqh> // ТРАЛ ПО ФРАКТАЛАМ#include <TrailingByShadows.mqh> // ТРАЛ ПО ТЕНЯМ N БАРОВ//// Глобальные переменные//staticdatetime prevtime = 0; // по ценам открытияbool IsExpertFailed = false;
bool IsExpertStopped = false;
int NumberOfTry = 25;
int SlipPips = 3;
int signal_period;
int trend_period;
bool UseSound = true;
color ColorBuy = Blue;
color ColorSell = Red;
string ok.wav;
double Level_new, PointValue,
lots; // вспомогательная переменная для расчета нового размера лота при очередной итерацииint Iteration, Counter_Loss, Ticket_at_history; // счетчик для подсчета последовательного убытка позиций колен лавины//bool Flag_Counter_Loss = false;double Current_Loss, Sum_Loss; // текущий и суммарный убытокint ticket; // Номер ордераdouble orderLots; // Lots double orderProfit; // Profitdouble Price; // Цена открытия рыночного ордераdouble SL; // Значение StopLoss ордераdouble TP; // Значение TakeProfit ордераdouble F1 = 1.0; // значение цены фрактала вверх (на 2-ом баре)double F11 = 1.0; // вспомогательная переменнаяdouble F2 = -200.0; // значение цены фрактала вниз (на 2-ом баре)double F22 =-200.0; // вспомогательная переменная double V_StopLossPips=0;
double V_TakeProfitPips=0;
//double StopLossPips;int Ticker, Counter;
double channel;
double StopLossPips;
double Lots_New; // Количество лотов для новых ордеровint time = 0; // время - для определения факта работы только с последним закрытым ордером
Si vous n'avez pas de compte, veuillez vous inscrire
Autorisez l'utilisation de cookies pour vous connecter au site Web MQL5.com.
Veuillez activer les paramètres nécessaires dans votre navigateur, sinon vous ne pourrez pas vous connecter.
Vous êtes connecté. L'authentification à deux facteurs a été désactivée. Configurez-la à nouveau et scannez un nouveau code QR, ou continuez avec l'authentification à deux facteurs désactivée.
Bonjour, question sur la durée de vie des commandes, j'ai besoin qu'une commande soit "vivante" pendant 2 minutes.
Pourquoi une telle construction donne l'erreur 3 - pourquoi et comment la corriger ?
Je vois, jusqu'à présent c'est plus facile pour moi d'écrire de cette façon.
Pouvez-vous me dire comment éviter que le "while" soit exécuté une fois de plus ?
Le "plus facile" n'existe pas - on n'écrit pas " dis-moi comment me débarrasser de tout ça BIENTÔT...". "Et dans le code, il faut garder à l'esprit que tout ce que vous avez écrit doit être compris par une machine muette.
Il y a donc deux voies : la bonne et la mauvaise.
Je comprends la paresse de le réécrire correctement, la paresse de comprendre les règles, alors dites-moi depuis combien de temps vous essayez d'écrire ce truc dans un fichier? Trois semaines...
Bonjour, conseillez comment écrire une condition : si une position ouverte (peu importe combien, la numérotation n'est pas nécessaire) ferme une ou plusieurs positions rentables, comment ouvrir une nouvelle position (une) après cela ?
Éditez pour vous-même :
le "plus facile" n'existe pas - on n'écrit pas "dis-moi comment m'en débarrasser pendant que tu le fais"... "Vous devez garder à l'esprit que tout ce que vous avez écrit doit être compris par une pièce de matériel stupide.
Il y a donc deux voies : la bonne et la mauvaise.
Je comprends aussi les TRES paresseux pour réécrire correctement, TRES paresseux pour comprendre les règles, alors dites-moi depuis combien de temps vous harcelez votre sujet avec l'écriture dans un fichier ? Trois semaines....
Je résous les problèmes au fur et à mesure qu'ils se présentent, le Conseiller Expert que je programme depuis le 10 janvier. Cela fait 4 semaines. J'essaie de programmer en MQL depuis le 6 janvier.
Merci Roman, mais je n'arrive pas à comprendre d'où vient la moitié des variables car tout le code
Comment déterminer le prix maximum ou minimum entre deux périodes de temps ? Existe-t-il une fonction spéciale pour cela ?