Вопросы от начинающих MQL5 MT5 MetaTrader 5 - страница 919
Вы упускаете торговые возможности:
- Бесплатные приложения для трейдинга
- 8 000+ сигналов для копирования
- Экономические новости для анализа финансовых рынков
Регистрация
Вход
Вы принимаете политику сайта и условия использования
Если у вас нет учетной записи, зарегистрируйтесь
У вас расчёт индикатора идёт от начала к концу (от самых поздних исторических данных к самым свежим - к текущим). А это говорит об индексации как в таймсерии. Значит и массивы должны быть соответственно индексированы, что у вас и есть.
Что не так работает тогда?
да все работает один в один мой порт в MQL5 из MQL4, а вижу что код некрасивый из за ArraySetAsSeries() вот и спрашиваю
вот оба кода
ну научите образцово показательно написать этот индикатор под MT5 !!! - не красивый мой код и точка! )))
ЗЫ совсем не помню как под МТ5 писать индикаторы, сел и за 40 минут тупо переписал с помощью хелпа, но результат... имхо на троечку (((
да все работает один в один мой порт в MQL5 из MQL4, а вижу что код некрасивый из за ArraySetAsSeries() вот и спрашиваю
вот оба кода
ну научите образцово показательно написать этот индикатор под MT5 !!! - не красивый мой код и точка! )))
При обратном цикле вам нужно обязательно делать массивы таймсериями иначе индексация буферов в цикле не будет совпадать с индексацией требуемых данных - индекс цикла в массиве буферов индикатора будет идти от начала к концу, а в open[], high[], low[], close[] и остальных - от конца к началу. Ну или переворачивайте цикл для соответствия его индексации массивов open[], high[], low[], close[] и остальных с индексацией буферов, что сложнее.
Если хотите аллегории, и будет понятнее, то вот вам аллегория:
Вы стоите у ж/д полотна и смотрите на два поезда. Они либо идут в одном направлении - оба слева-направо (ArraySetAsSeries(array,true) - первый поезд и цикл от limit до 0 - второй поезд),
либо идут навстречу друг-другу - (ArraySetAsSeries(array,false) - справа-налево - первый поезд, и цикл от limit до 0 - слева-направо- второй поезд)
И, да: код не глядел - не охота скачивать, сохранять у себя (и так очень много ненужных кодов с форума), сравнивать их промеж собою...
Проще вам было выложить их кодами в сообщение - один и второй - тогда было бы видно сразу что к чему.
Ну или переворачивайте цикл для соответствия его индексации массивов open[], high[], low[], close[] и остальных, что сложнее.
я сегодня весь вечер переворачиваю, вот терпение закончилось (((
насколько я понял проблему:
- в МТ5 массивы которые назначаются индикаторными буферами по умолчанию индексируются слева на право;
- в МТ5 таймсерии open[], high[], low[], close[] доступные из OnCalculate() всегда передаются с индексацией справо на лево
- т..е исходя из пп 1 и 2, чтобы произвести расчет индикатора из конца истории к нулевому бару придется:
а) или переназначить индексацию буфферных массивов
б) или делать цикл в котором будет пересчет нумерации элементов массива слева на право, а в другом справо на лево:
т.е. красивого решения моего вопроса не существует? вариант а) - в моих исходниках реализован, вариант б) - не вижу смысла лишние расчеты делать
исходники:
МТ5:
МТ4:
я сегодня весь вечер переворачиваю, вот терпение закончилось (((
насколько я понял проблему:
- в МТ5 массивы которые назначаются индикаторными буферами по умолчанию индексируются слева на право;
- в МТ5 таймсерии open[], high[], low[], close[] доступные из OnCalculate() всегда передаются с индексацией справо на лево
- т..е исходя из пп 1 и 2, чтобы произвести расчет индикатора из конца истории к нулевому бару придется:
а) или переназначить индексацию буфферных массивов
б) или делать цикл в котором будет пересчет нумерации элементов массива слева на право, а в другом справо на лево:
т.е. красивого решения моего вопроса не существует? вариант а) - в моих исходниках реализован, вариант б) - не вижу смысла лишние расчеты делать
Массивы все индексируются справа-нелево. Поэтому, чтобы полностью соответствовать циклу слева-направо (а он от limit до 0 - именно слева-направо), то вам нужно всем используемым массивам задать нужную индексацию: буферам в OnInit(), используемым таймсериям - в OnCalculate().
Либо делать цикл от 0 до limit, что не всегда просто сделать при портации из mql4 в mql5
Поэтому вариант с ArraySetAsSeries() в данном случае выгодней.
Массивы все индексируются справа-нелево. Поэтому, чтобы полностью соответствовать циклу слева-направо (а он от limit до 0 - именно слева-направо), то вам нужно всем используемым массивам задать нужную индексацию: буферам в OnInit(), используемым таймсериям - в OnCalculate().
Либо делать цикл от 0 до limit, что не всегда просто сделать при портации из mql4 в mql5
Поэтому вариант с ArraySetAsSeries() в данном случае выгодней.
ну вот смотри, убрал из своего кода все ArraySetAsSeries() (вверху в Init() и в OnCalculate() в первых строках) и исправил цикл:
for(i=0;i<limit;i++)
в теории все должно сойтись! но нет! графики то разные получились, вот что никак не могу понять!
ну вот смотри, убрал из своего кода все ArraySetAsSeries() (вверху в Init() и в OnCalculate() в первых строках) и исправил цикл:
for(i=0;i<limit;i++)
в теории все должно сойтись! но нет! графики то разные получились, вот что никак не могу понять!
Я ж говорю - сложнее. Логику менять нужно. Не достаточно просто цикл перевернуть.
Вот один маленький пример: в коде есть
Buf_NTLine1[i+1])
куда будет обращаться индекс i+1 при разных индексациях массивов?
и там много такого. IHighest() - начало и количество... Откуда начинает при одной индексации и при другой?
И т.д. ...
и там много такого. IHighest() - начало и количество... Откуда начинает при одной индексации и при другой?
блин! точно! молодец!!! да, вот тут то и весь прикол!!!
нда... много отличий в МТ5, уж очень много на голову программиста ложится всяких проверок и всяких предусмотрительностей...
да, вот еще вопрос, вроде не давно видел сообщение, что в МТ5 не всегда все в Init() корректно инициализируется, вроде связано, что Init() может закончится даже если не готовы таймфреймы
вчера несколько раз видел баг: если этот индикатор под МТ5 переключать по ТФ, то иногда индикаторные буфера могут быть не пустыми - вроде старые значения остаются если в OnCalculate() не присваивать каждому элементу в индикаторном массиве конкретное значение, попробовал в Init() воткнуть ArrayInitialize(arr, 0.0) - тоже то работает то нет..
насколько я правильно понимаю:
- в МТ5 при инициализации в Init() индикаторные буфера автоматически не инициализируются? (в МТ4 ну не помню чтобы в буферах что то оставалось)
- в МТ5 в Init() размеры буферных массивов могут быть неизвестны если не подгрузилась история, поэтому ArrayInitialize(arr, 0.0) тоже не всегда корректно инициализирует буфера?
блин! точно! молодец!!! да, вот тут то и весь прикол!!!
нда... много отличий в МТ5, уж очень много на голову программиста ложится всяких проверок и всяких предусмотрительностей...
да, вот еще вопрос, вроде не давно видел сообщение, что в МТ5 не всегда все в Init() корректно инициализируется, вроде связано, что Init() может закончится даже если не готовы таймфреймы
вчера несколько раз видел баг: если этот индикатор под МТ5 переключать по ТФ, то иногда индикаторные буфера могут быть не пустыми - вроде старые значения остаются если в OnCalculate() не присваивать каждому элементу в индикаторном массиве конкретное значение, попробовал в Init() воткнуть ArrayInitialize(arr, 0.0) - тоже то работает то нет..
насколько я правильно понимаю:
- в МТ5 при инициализации в Init() индикаторные буфера автоматически не инициализируются? (в МТ4 ну не помню чтобы в буферах что то оставалось)
- в МТ5 в Init() размеры буферных массивов могут быть неизвестны если не подгрузилась история, поэтому ArrayInitialize(arr, 0.0) тоже не всегда корректно инициализирует буфера?
Особо не вникал в логику.
Особо не вникал в логику.
Так правильнее будет: нечего ставить точки входа на макс/мин цены - лучше на цену открытия.
И линии убрать нужно - зачем они на графике? Если только стоп тащить по ним?
declaration without type
Если я компилирую включаемый файл, то ошибок нет. Если же я компилирую основной файл программы, в который включаю данный включаемый файл, то ошибка declaration without type. Он не видит объект, объявленный во включаемом файле protected CSomeClass *object. Во включаемом файле есть директива #include "SomeClass.mqh". А в основном файле создается объект класса включаемого файла и вызывается один из методов.