Period_Converter_Opt
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «period_converter_opt-1.mq5» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
Period_Converter_Opt — пользовательский индикатор для MetaTrader 4, предназначенный для конвертации графиков в офлайн-режиме с более высоким таймфреймом на основе данных исходного графика. Индикатор записывает агрегированные свечи в файлы истории (.hst) и/или CSV, что позволяет создавать и автоматически обновлять офлайн-графики новых периодов. Поддерживается как обновление в реальном времени, так и обновление через заданный интервал в миллисекундах. Индикатор сохраняет свои данные между перезапусками терминала и может работать с несколькими конвертерами одновременно на одном графике с разными множителями периода.
Настройки программы
| Настройка | Описание |
|---|---|
| code version (Version) | Версия кода — Числовой идентификатор версии индикатора. |
| BuildInfo | Информация о сборке — Текстовая строка с информацией о версии и авторе сборки. |
| new period multiplier factor (PeriodMultiplier) | Множитель периода — Целочисленный множитель, определяющий новый таймфрейм как произведение текущего периода на это значение. |
| also output CSV file? (OutputCSVFile) | Режим вывода CSV — Целочисленный параметр, управляющий режимом записи выходных файлов: только HST, HST с CSV или только CSV. |
| update interval in milliseconds, zero means update real-time. (UpdateInterval) | Интервал обновления — Интервал обновления данных в миллисекундах; нулевое значение означает обновление в реальном времени. |
| Enabled | Включён — Логический переключатель, позволяющий активировать или деактивировать работу индикатора без его удаления с графика. |
| Debug | Отладка — Логический переключатель, включающий вывод отладочных сообщений через функцию Alert. |
Поиск по коду файла
#property indicator_chart_window
#property show_inputs
#include <WinUser32.mqh>
/*
Readme:
I. Features:
This is an improved version of period converter for MT4 based on the
MT4's default period converter by metaquotes.
The default period converter script do not support real-time refreshing,
and consume lots of CPU (50%-9x%) making the whole system slow.
Also, the default one is a script which do not save when you exit MT4,
so you have to apply every converter script again after restarting, quite
annoying.
This one fixed all above problems:
1. Real-time updating or custom interval millisecond level updating.
2. Low CPU cost, average 5%-10% or less.
3. Works as an indicator, so can be saved and reloaded during restart.
4. There is no one converter per chart limitation as it is not script
any more, you can only use one window as source to generate as many
new timeframe chart as possible.
5. Auto updating if there is new history block loaded.
II. How to use:
Copy the mq4 file to your MT4 indicators folder (experts\indicators)
to install it as an indicator, NOT script. then in the custom indicator
list, attach period_converter_opt to the chart you want.
It support 4 parameters:
PeriodMultiplier: new period multiplier factor, default is 2
UpdateInterval: update interval in milliseconds,
zero means update real-time. default is zero.
Enabled: You can disable it without remove it with this option.
Other parameters are comments or for debugging, it is safe to ignore them.
Also Make sure you have Allow Dll imports option checked in common tab or
it won't work
After that, File->Open Offline to open the generated offline data. then
the offline data will be updated automatically.
As long as you keep the source chart open and the converter indicator
running, the generated chart including indicators inside will always
be updated. also you can close the generated chart and open again
later from File->Open Offline without problem.
If you want to quit MT4, you can leave those offline chart as other
normal online charts. when you start MT4 next time, those charts will
also be loaded and updated.
III. Notes:
1. Do NOT uncheck the "offline chart" option in offline chart common properties.
or after MT4 restart, it will treat that chart as online chart and request
the data from server, resulting empty chart window.
2. You can attach more than one converter to same window with different
PeriodMultiplier, e.g: you can attach 3 converter with
PeriodMultiplier = 2, 4, 10 to M1 to generate M2, M4, M10 at the same time.
It is even ok to use the M1 chart to generate Hourly chart like H2, which
only cost a few more CPU resource during initial conversion. but usually
most server don't have much data for those short period. resulting the
generated data isn't long enough for long period. so it is suggested
to use Hourly/Daily charts as source when needed.
3. The real-time updating mode updates quotes as fast as possible, but as
this is done via script, and MT will skip calling start() function when
your PC is busy and lots of quotes income. anyway, this seldom happen,
and you can at least get 10 updates each seconds which is much more
than enough.
4. The offline chart don't have a bid line showing in chart, but all data
in the chart including the indicators is still being updated,
so don't worry. you can show the bid line by unclick the "offline chart"
option in chart properties. but which don't helps much and if you forget
to check "offline chart" option before exit. it will cause errors and
become empty on next startup. you have to close the window and open
again from File->Open offline, which don't worth the trouble.
IV. History:
2005.12.24 1.4 faster to detect if data changed by removing float point
operations, added support to output CSV file in real time.
OutputCSVFile = 0 means no CSV.
OutputCSVFile = 1 means CSV + HST
OutputCSVFile = 2 CSV only, no HST .
(useful if you want to generate CSV for builtin periods)
CSV Filename will be the same as HST file except the extension.
added safe checking for PeriodMultiplier.
2005.12.04 1.3 Fixed missing data when there is large amount of data
loaded in several blocks, and support auto updating
when new history is loaded.
2005.11.29 1.2 Additional fix for missing data and server changing.
2005.11.29 1.1 Fixed missing partial data after restart.
Reinitialize after changing server or data corrupted.
2005.11.28 1.0 Initial release
*/
extern double Version = 1.4; // code version
extern string BuildInfo = "2005.12.24 by w***5*@talkforex.com";
extern int PeriodMultiplier = 2; // new period multiplier factor
extern int OutputCSVFile = 0; // also output CSV file?
extern int UpdateInterval = 0; // update interval in milliseconds, zero means update real-time.
extern bool Enabled = true;
extern bool Debug = false;
int FileHandle = -1;
int CSVHandle = -1;
int NewPeriod = 0;
#define OUTPUT_HST_ONLY 0
#define OUTPUT_CSV_HST 1
#define OUTPUT_CSV_ONLY 2
#define CHART_CMD_UPDATE_DATA 33324
void DebugMsg(string msg)
{
if (Debug) Alert(msg);
}
int init()
{
// код доступен только после оплаты
}
void deinit()
{
if(FileHandle >= 0) {
FileClose(FileHandle);
FileHandle = -1;
}
if (CSVHandle >= 0) {
FileClose(CSVHandle);
CSVHandle = -1;
}
}
int OpenHistoryFile()
{
string name;
name = Symbol() + NewPeriod;
if (OutputCSVFile != OUTPUT_CSV_ONLY) {
FileHandle = FileOpenHistory(name + ".hst", FILE_BIN|FILE_WRITE);
if (FileHandle < 0) return(-1);
}
if (OutputCSVFile != OUTPUT_HST_ONLY) {
CSVHandle = FileOpen(name + ".csv", FILE_CSV|FILE_WRITE, ',');
if (CSVHandle < 0) return(-1);
}
return (0);
}
int WriteHistoryHeader()
{
string c_copyright;
int i_digits = Digits;
int i_unused[13] = {0};
int version = 400;
if (FileHandle < 0) return (-1);
c_copyright = "(C)opyright 2003, MetaQuotes SПоказано первые 50% кода (символов: 9592)
Открыть по тарифу
Купите тариф с пакетом открытий или войдите, если тариф уже есть. Открытый файл останется в вашем кабинете навсегда.
Разовая покупка файла
На этой странице откроется полный исходный код файла вместо ознакомительного фрагмента.
Зачем нужен email? После подтверждения оплаты файл сохранится в кабинете на этот email. Если аккаунта ещё нет, мы создадим его и пришлём ссылку для задания пароля. Если аккаунт уже есть, покупка добавится в него. Укажите адрес, к которому у вас есть доступ.
Чтобы оформить заказ, введите email и перейдите к оплате.