HiveLoggerMT5
- Bibliotecas
-
Sergey Chekhovskikh
👋 Hi there! I write robots, systems, and other stuff in Python and MQL5.
📊 My workday is a marathon of creating neural networks and algorithmic trading robots, which I make trade through MetaTrader. I teach them to play the market just like I taught my dog to balance a treat on his nose. - Versión: 1.6
HiveLoggerMT5 es una biblioteca de registro compilada para programas MQL5.
Con una sola llamada se escribe una breve línea legible para el usuario en el diario de expertos y el evento completo como una línea JSON en un archivo local dentro del entorno aislado de la terminal.
Un experto, un servicio o un script deja un rastro legible por máquina que cualquier herramienta compatible con JSON puede filtrar y analizar posteriormente.
Sin DLL, sin acceso a la red, sin dependencias externas.
Dos registros con una sola llamada
Cada evento aceptado genera:
- una entrada de una línea en el diario de Experts —nivel, nombre del evento estable, mensaje breve— para el operador que supervisa el gráfico;
- un registro JSONL completo en el archivo de registro para agentes, recopiladores y análisis posterior.
Campos del registro: v (versión del formato), time_local, time_local_ms (marca de tiempo en milisegundos), source (nombre del programa), level, event, message, account, chart_id, command_id. Un evento es una línea física que termina con LF, por lo que una cola escrita parcialmente nunca corrompe los registros anteriores y un recopilador puede reanudar su funcionamiento tras un reinicio. El campo command_id vincula todos los eventos de un comando en una cadena.
Conexión en tres pasos
- El terminal instala la biblioteca adquirida en MQL5\Libraries\Market\.
- Guarda el encabezado siguiente como MQL5\Include\HiveLoggerMT5.mqh.
- Incluye el encabezado en tu programa: abre una sesión en OnInit, registra los eventos y ciérrala en OnDeinit.
#include <HiveLoggerMT5.mqh>
int OnInit()
{
if(!HiveOpenDefault())
return INIT_FAILED;
HiveLogInfo("session.start","logger ready");
return INIT_SUCCEEDED;
}
void OnTick()
{
HiveLogDebug("tick.processed","...");
}
void OnDeinit(const int reason)
{
HiveLogInfo("session.stop",IntegerToString(reason));
HiveClose();
} El encabezado completo del comprador (guárdalo como MQL5\Include\HiveLoggerMT5.mqh):
//+------------------------------------------------------------------+
//| HiveLoggerMT5.mqh |
//| HiveLoggerMT5 - MQL5 Market edition, customer header |
//| |
//| The single file a customer needs besides the binary: |
//| 1. Copy this file to MQL5\Include\HiveLoggerMT5.mqh |
//| 2. Copy HiveLoggerMT5.ex5 to MQL5\Libraries\Market\ |
//| (keep the Market subfolder name; the #import below uses it) |
//| 3. #include <HiveLoggerMT5.mqh> and call the Hive* functions. |
//| |
//| Flat C-style API over the binary library: full functional parity |
//| with the class API 1.6.1 except the sink interface, which stays |
//| a GitHub-edition feature (pointers do not pass through #import). |
//| The JSONL output is byte-identical to the class API, so the |
//| tools/hivelog.py CLI reads it without changes. |
//+------------------------------------------------------------------+
#ifndef HIVELOGGERMT5_MQH
#define HIVELOGGERMT5_MQH
// Log levels: pass as int to HiveLog/HiveSetMinLevel; the library
// validates the range.
enum ENUM_HIVE_LEVEL
{
HIVE_DEBUG=0,
HIVE_INFO=1,
HIVE_WARN=2,
HIVE_ERROR=3
};
// Write status codes returned by HiveWriteStatus (1.6.1 semantics):
// SHORT means a partial packet write or a discarded packet (the lost
// lines are counted in HiveDroppedLines); FLUSH means every byte was
// written but the flush was not confirmed. Both survive HiveClose and
// are reset by any HiveOpen with a valid path, even a failed one; a
// repeated Open on the open logger and an invalid path keep them.
// The MARKET_ prefix avoids clashing with the HIVE_WRITE_* enum members
// of the class edition (Include/HiveLogger/HiveLogger.mqh) if a buyer
// mixes both editions in one project.
#define HIVE_MARKET_WRITE_OK 0
#define HIVE_MARKET_WRITE_SHORT 1
#define HIVE_MARKET_WRITE_FLUSH 2
#import "Market\HiveLoggerMT5.ex5"
bool HiveOpen(const string folder,const string prefix);
bool HiveLog(const int level,const string event_type,const string message,
const string command_id);
bool HiveSetMinLevel(const int level);
bool HiveSetMaxFileBytes(const long bytes);
bool HiveSetRetentionFiles(const int files);
bool HiveSetRetentionAgeDays(const int days);
bool HiveSetRetentionTotalBytes(const long bytes);
bool HiveSetPreciseTime(const bool on);
bool HiveSetBuffering(const bool on,const int lines,const long bytes);
int HiveFlush(void);
int HiveBufferedLines(void);
int HiveDroppedLines(void);
int HiveWriteStatus(void);
int HiveWriteError(void);
string HivePath(void);
void HiveClose(void);
#import
// Inline wrappers with the common defaults. The #import prototypes
// above carry no default arguments (not guaranteed through #import),
// so these compile-time helpers keep call sites short. They never
// enter the .ex5.
bool HiveOpenDefault(void)
{
return HiveOpen("HiveLogger","");
}
bool HiveLogDebug(const string event_type,const string message,
const string command_id="")
{
return HiveLog(HIVE_DEBUG,event_type,message,command_id);
}
bool HiveLogInfo(const string event_type,const string message,
const string command_id="")
{
return HiveLog(HIVE_INFO,event_type,message,command_id);
}
bool HiveLogWarn(const string event_type,const string message,
const string command_id="")
{
return HiveLog(HIVE_WARN,event_type,message,command_id);
}
bool HiveLogError(const string event_type,const string message,
const string command_id="")
{
return HiveLog(HIVE_ERROR,event_type,message,command_id);
}
// Default packet limits match the class API: 64 lines, 32 KiB.
bool HiveSetBufferingDefault(const bool on)
{
return HiveSetBuffering(on,64,32768);
}
#endif // HIVELOGGERMT5_MQH
Descripción general de la API
| Función | Finalidad |
|---|---|
| HiveOpen(carpeta, prefijo) / HiveOpenDefault() | Abre una sesión; carpeta predeterminada HiveLogger, prefijo predeterminado vacío. Las rutas no válidas (absolutas, .., : ) devuelven false. |
| HiveLog(nivel, tipo_evento, mensaje, id_comando) | Un evento para ambos registros. Devuelve «false» si falla la escritura en el archivo; los eventos filtrados devuelven «true» sin E/S de archivo. |
| HiveLogDebug/Info/Warn/Error(evento, mensaje, id_comando) | Envoltorios de conveniencia para los niveles. |
| HiveSetMinLevel(nivel) | Filtro de nivel: HIVE_DEBUG < HIVE_INFO < HIVE_WARN < HIVE_ERROR. |
| HiveSetMaxFileBytes(bytes) | Rotación de archivos por tamaño; los segmentos reciben los sufijos -0, -1, ... |
| HiveSetRetentionFiles(n) / HiveSetRetentionAgeDays(d) / HiveSetRetentionTotalBytes(b) | Límites de retención aplicados en HiveOpen; el archivo abierto nunca se elimina, pero su tamaño cuenta para el total. |
| HiveSetBuffering(on, lines, bytes) / HiveFlush() | Escrituras en búfer (por defecto 64 líneas / 32 768 bytes, se aplican a partir del siguiente HiveOpen); el vaciado explícito devuelve el número de líneas escritas. |
| HiveBufferedLines() / HiveDroppedLines() | Profundidad de la cola y recuento acumulado de líneas perdidas debido a los límites del búfer. |
| HiveSetPreciseTime(on) | Marcas de tiempo en milisegundos. «on» (por defecto) realiza la calibración una vez en la siguiente llamada a Open; «off» omite la espera de calibración y registra solo los segundos. |
| HiveWriteStatus() / HiveWriteError() | Último error de escritura/vaciado: HIVE_MARKET_WRITE_OK/SHORT/FLUSH más el error del sistema operativo. Persiste tras un HiveClose; se restablece con cualquier HiveOpen con una ruta válida. |
| HivePath() | Ruta relativa del archivo actual dentro de MQL5\Files; vacía mientras esté cerrado. |
| HiveClose() | Vacíe y cierre la sesión. |
Notas sobre el comportamiento
- Una sesión por programa; cada programa tiene su propio contexto de biblioteca, por lo que varios expertos registran datos de forma independiente.
- Si se vuelve a llamar a HiveOpen en el registrador abierto, se mantiene el archivo actual y se devuelve «true»; primero hay que cambiar de carpeta mediante HiveClose.
- El terminal crea el directorio de registro si no existe.
- En el Strategy Tester, la biblioteca escribe en el entorno de pruebas; la precisión en milisegundos depende del tiempo del terminal, que el tester virtualiza.
- El esquema JSONL es estable y está documentado; el lenguaje del contenido del mensaje es el que pase el llamante.
Requisitos
Terminal MetaTrader 5 con soporte para Market. La biblioteca no realiza operaciones de trading ni lee el estado de la cuenta para su funcionamiento; funciona en cualquier tipo de cuenta.
