MQLArticles/IndicatorsCts/Imp/Internal/App.py
351 lines
16 KiB
Python
Nique_372
2026-11-01 10:04:21 -05:00
#+------------------------------------------------------------------+
#| App.py |
#| Copyright 2026, Niquel Mendoza. |
#| https://www.mql5.com |
#+------------------------------------------------------------------+
#+------------------------------------------------------------------+
#| Imports |
#+------------------------------------------------------------------+
import json
import os
import sys
from tsn_utils import CLoggerBase
Nique_372
2026-11-01 11:50:50 -05:00
from Base.Common import *
#+------------------------------------------------------------------+
#| Notas de diseno |
#+------------------------------------------------------------------+
# Flujo: config.json -> prologo de cada archivo (main_file, pool_file opcional)
# indicators.json -> ParseIndicators (UNA sola pasada, valida todo) -> lista de CIndSpec
# EmitMain / EmitPool recorren la lista sin volver a comprobar nada.
#
# Validaciones: solo las que el compilador de mql5 NO da (campos faltantes, duplicados de class_name/prefix,
# y el tipo de cada parametro para saber como escribirlo en la key del pool).
# NO se validan identificadores (class_name, creator, nombres/tipos de parametros): se pegan tal cual
# y si estan mal lo dice el compilador de mql5.
#
# Escapes: los includes se escapan (\ => \\) porque json los des-escapa y mql5 los necesita.
# El campo "resource" NO se escapa: se escribe tal cual, si lleva "\" o '"' hay que ponerlo ya escapado en el json
# (ej. "::Shared Projects\\\\X.ex5"). Cambiarlo cuando haga falta.
#
# Pool: el campo "prefix" de cada indicador se usa para Get<prefix> / Remove<prefix> y como key (string)
# dentro del pool; el miembro es s_<prefix en snake_case> (SuperTrend => s_super_trend). Por eso se escribe
# en CamelCase igual que el nombre que se quiere en la API (GetSuperTrend, GetStdDev, GetAdxWilder...).
Nique_372
2026-11-01 10:04:21 -05:00
#+------------------------------------------------------------------+
#| Clase principal |
#+------------------------------------------------------------------+
class CApp(CLoggerBase):
def __init__(self):
super().__init__()
self.m_fn_src_file_ind = "" # archivo de config de indicadores (json)
Nique_372
2026-11-01 11:50:50 -05:00
self.m_main = COutFile() # Main.mqh (clases de los indicadores)
self.m_pool = None # Pool.mqh (opcional: solo si config tiene pool_file)
Nique_372
2026-11-01 10:04:21 -05:00
#+------------------------------------------------------------------+
#| Utilidades de archivos |
#+------------------------------------------------------------------+
def LoadJson(self, file : str) -> dict | None:
try:
with open(file, "r", encoding="utf-8-sig") as f:
return json.load(f)
except (OSError, json.JSONDecodeError) as e:
self.LogError(f"Fallo al leer/parsear json:\nFile: '{file}'\n{e}")
return None
Nique_372
2026-11-01 11:50:50 -05:00
def SaveFile(self, out : COutFile) -> bool:
Nique_372
2026-11-01 10:04:21 -05:00
try:
Nique_372
2026-11-01 11:50:50 -05:00
with open(out.m_path, "w", encoding="utf-8", newline="") as f:
f.write("".join(out.m_buf))
Nique_372
2026-11-01 10:04:21 -05:00
return True
except OSError as e:
Nique_372
2026-11-01 11:50:50 -05:00
self.LogCriticalError(f"Failed to create file:\n'{out.m_path}'\n{e}")
Nique_372
2026-11-01 10:04:21 -05:00
return False
#+------------------------------------------------------------------+
#| Utilidades de escritura |
#+------------------------------------------------------------------+
# Linea con texto dentro del header de comentarios (trunca al espacio util)
@staticmethod
def LineWC(text : str) -> str:
return TPL_LINEW.format(text=text[:SCRIPT_LINEW_PURESIZE])
Nique_372
2026-11-01 11:50:50 -05:00
# Bloque con titulo //+---+ //| titulo | //+---+
@staticmethod
def BlockWC(text : str) -> str:
return TPL_LINE + SCRIPT_EOL + CApp.LineWC(text) + SCRIPT_EOL + TPL_LINE + SCRIPT_EOL
Nique_372
2026-11-01 10:04:21 -05:00
#+------------------------------------------------------------------+
#| Run |
#+------------------------------------------------------------------+
def Run(self, fn_config : str) -> bool:
#--- Parseamos la configuracion
config = self.LoadJson(fn_config)
if config is None or not self.ProccesConfig(config):
return False
Nique_372
2026-11-01 11:50:50 -05:00
#--- Parseamos ahora si el archivo de indicadores (una sola pasada)
Nique_372
2026-11-01 10:04:21 -05:00
inds = self.LoadJson(self.m_fn_src_file_ind)
Nique_372
2026-11-01 11:50:50 -05:00
if inds is None:
return False
specs: list[CIndSpec] = self.ParseIndicators(inds, need_prefix=self.m_pool is not None)
if specs is None:
Nique_372
2026-11-01 10:04:21 -05:00
return False
Nique_372
2026-11-01 11:50:50 -05:00
#--- Generamos
self.EmitMain(specs)
if self.m_pool is not None and not self.EmitPool(specs):
Nique_372
2026-11-01 10:04:21 -05:00
return False
Nique_372
2026-11-01 11:50:50 -05:00
#--- Guardamos los archivos finales
for out in (self.m_main, self.m_pool):
if out is not None and not self.SaveFile(out):
return False
Nique_372
2026-11-01 10:04:21 -05:00
self.LogInfo("Se termino")
return True
#+------------------------------------------------------------------+
#| Config |
#+------------------------------------------------------------------+
def ProccesConfig(self, root : dict) -> bool:
self.m_fn_src_file_ind = root.get("src_inds_file", "")
if not isinstance(self.m_fn_src_file_ind, str) or not self.m_fn_src_file_ind:
self.LogError("Falta el campo 'src_inds_file' que indica el archivo donde estan los indicadores, o esta malformado")
return False
Nique_372
2026-11-01 11:50:50 -05:00
if not self.FileProrrogo(self.m_main, root.get("main_file", {})):
return False
#--- Pool (opcional)
if "pool_file" in root:
self.m_pool = COutFile()
return self.FileProrrogo(self.m_pool, root["pool_file"])
return True
Nique_372
2026-11-01 10:04:21 -05:00
#+------------------------------------------------------------------+
Nique_372
2026-11-01 11:50:50 -05:00
#| Prologo (header + props + guard + includes + namespace) |
Nique_372
2026-11-01 10:04:21 -05:00
#+------------------------------------------------------------------+
Nique_372
2026-11-01 11:50:50 -05:00
def FileProrrogo(self, out : COutFile, file : dict) -> bool:
Nique_372
2026-11-01 10:04:21 -05:00
#--- Campos obligatorios
Nique_372
2026-11-01 11:50:50 -05:00
out.m_path = file.get("path", "")
if not out.m_path:
Nique_372
2026-11-01 10:04:21 -05:00
self.LogError("No se pudo obtener el campo path")
return False
Nique_372
2026-11-01 11:50:50 -05:00
pure = os.path.basename(out.m_path) # nombre puro del archivo
Nique_372
2026-11-01 10:04:21 -05:00
autor = file.get("autor", "")
link = file.get("link", "")
for name, val in (("autor", autor), ("link", link)):
if not val:
self.LogError(f"Falta el campo {name} en file = '{pure}'")
return False
#--- Header + props
Nique_372
2026-11-01 11:50:50 -05:00
out.Add(TPL_HEADER.format(line=TPL_LINE, file=self.LineWC(pure),
autor=self.LineWC(autor), link=self.LineWC(link),
autor_raw=autor, link_raw=link))
Nique_372
2026-11-01 10:04:21 -05:00
#--- Guard (trunca a 256)
Nique_372
2026-11-01 11:50:50 -05:00
out.m_guard = file.get("guard", "")[:SCRIPT_MAX_GUARD]
if out.m_guard:
out.Add(TPL_GUARD_INIT.format(guard=out.m_guard))
Nique_372
2026-11-01 10:04:21 -05:00
Nique_372
2026-11-01 11:50:50 -05:00
out.Add(TPL_BLOCK)
Nique_372
2026-11-01 10:04:21 -05:00
#--- Includes
for i, include in enumerate(file.get("includes", [])):
if "relative" in include:
path, op, cl = include["relative"], '"', '"'
elif "mql5" in include:
path, op, cl = include["mql5"], "<", ">"
else:
self.LogError(f"includes[{i}]: solo se permite dos tipos [relative, mql5] nada mas")
return False
path = path[:SCRIPT_MAX_INCLUDE].replace("\\", "\\\\") # json lo des-escapa, mql5 lo necesita
Nique_372
2026-11-01 11:50:50 -05:00
out.Add(TPL_INCLUDE.format(open=op, path=path, close=cl))
out.Add("\n")
Nique_372
2026-11-01 10:04:21 -05:00
Nique_372
2026-11-01 10:13:47 -05:00
#--- Namepsace
Nique_372
2026-11-01 11:50:50 -05:00
out.m_namespace = file.get("namespace", "")
if out.m_namespace:
out.Add(TPL_BLOCK) # bloque
out.Add(f"namespace {out.m_namespace}\n{{\n")
Nique_372
2026-11-01 10:13:47 -05:00
# Final
Nique_372
2026-11-01 10:04:21 -05:00
self.LogInfo(f"Archivo = '{pure}' procesado correctamente")
return True
#+------------------------------------------------------------------+
Nique_372
2026-11-01 11:50:50 -05:00
#| Epilogo (fin del namespace + fin del guard) |
Nique_372
2026-11-01 10:04:21 -05:00
#+------------------------------------------------------------------+
Nique_372
2026-11-01 11:50:50 -05:00
def FileEpilogue(self, out : COutFile) -> None:
if out.m_namespace:
out.Add("//---\n}\n")
if out.m_guard:
out.Add(TPL_GUARD_END.format(guard=out.m_guard))
#+------------------------------------------------------------------+
#| Pool: como se escribe un parametro en la key |
#+------------------------------------------------------------------+
@staticmethod
def PoolWriter(tipo : str) -> str | None:
w = POOL_WRITERS.get(tipo)
if w is None and (tipo.startswith("ENUM_")):
w = POOL_WRITE_ENUM
return w
#+------------------------------------------------------------------+
#| Indicadores: parseo + validacion (una sola pasada) |
#+------------------------------------------------------------------+
def ParseIndicators(self, root : dict, need_prefix : bool) -> list[CIndSpec] | None:
Nique_372
2026-11-01 10:04:21 -05:00
indicators = root.get("indicators")
if indicators is None:
self.LogError("No se encontro indicators en el root")
Nique_372
2026-11-01 11:50:50 -05:00
return None
specs: list[CIndSpec] = []
classes = set()
prefixes = set()
Nique_372
2026-11-01 10:04:21 -05:00
for curr_el, ind in enumerate(indicators):
#--- class_name
class_name = ind.get("class_name")
if not class_name:
self.LogError(f"No se encontro el campo class_name en indicators[{curr_el}]")
Nique_372
2026-11-01 11:50:50 -05:00
return None
if class_name in classes:
self.LogError(f"indicators[{curr_el}]: class_name = '{class_name}' repetido")
return None
classes.add(class_name)
#--- prefix (solo obligatorio si se genera el pool)
prefix = ind.get("prefix", "")
if need_prefix:
if not prefix:
self.LogError(f"indicators[{curr_el}], Clase = {class_name}: falta el campo prefix (el pool lo necesita)")
return None
if prefix in prefixes:
self.LogError(f"indicators[{curr_el}], Clase = {class_name}: prefix = '{prefix}' repetido")
return None
prefixes.add(prefix)
Nique_372
2026-11-01 10:04:21 -05:00
#--- num_buffers
num_buffers = ind.get("num_buffers", 0)
if not isinstance(num_buffers, int) or num_buffers < 1:
self.LogError(f"indicators[{curr_el}], Clase = {class_name}, proporciono un numero de buffers menor a 1")
Nique_372
2026-11-01 11:50:50 -05:00
return None
Nique_372
2026-11-01 10:04:21 -05:00
#--- type: "$ENUM" (se copia sin $) o numero unsigned
Nique_372
2026-11-01 11:50:50 -05:00
ind_type = ind.get("type")
if isinstance(ind_type, str) and ind_type.startswith("$"):
ind_type = ind_type[1:]
elif not (isinstance(ind_type, int) and ind_type >= 0):
Nique_372
2026-11-01 10:04:21 -05:00
self.LogError(f"indicators[{curr_el}]: no se encontro el campo 'type' o debe ser string (enum, empieza con $) o un numero unsigned valido")
Nique_372
2026-11-01 11:50:50 -05:00
return None
Nique_372
2026-11-01 10:04:21 -05:00
#--- creator
creator = ind.get("creator")
if not isinstance(creator, str):
self.LogError(f"indicator[{curr_el}][{class_name}]: no se encontro el campo creator o no es string")
Nique_372
2026-11-01 11:50:50 -05:00
return None
Nique_372
2026-11-01 10:04:21 -05:00
#--- parameters { nombre : tipo }
params = ind.get("parameters")
if not isinstance(params, dict):
self.LogError(f"Campo parameters no esta presente.. en pos = {curr_el}")
Nique_372
2026-11-01 11:50:50 -05:00
return None
Nique_372
2026-11-01 10:04:21 -05:00
if not all(isinstance(t, str) for t in params.values()):
self.LogError(f"indicator[{curr_el}]: solo se permite strings como valores en parameters")
Nique_372
2026-11-01 11:50:50 -05:00
return None
#--- Pool: el tipo de cada parametro debe tener forma de escribirse en la key
if need_prefix:
for n, t in params.items():
if self.PoolWriter(t) is None:
self.LogError(f"indicator[{curr_el}][{class_name}]: el parametro '{n}' tiene un tipo no soportado por el pool ('{t}'), "
f"debe ser nativo o empezar con ENUM_ (o estar en POOL_EXTRA_ENUMS)")
return None
#--- resource
Nique_372
2026-11-01 10:32:00 -05:00
resource: str = ind.get("resource", "")
if resource:
resource = f", \"{resource}\""
Nique_372
2026-11-01 10:04:21 -05:00
Nique_372
2026-11-01 11:50:50 -05:00
specs.append(CIndSpec(class_name, prefix, num_buffers, ind_type, creator, resource, list(params.items())))
return specs
#+------------------------------------------------------------------+
#| Main.mqh: clases de los indicadores |
#+------------------------------------------------------------------+
def EmitMain(self, specs : list[CIndSpec]) -> None:
for s in specs:
self.m_main.Add(TPL_BLOCK)
self.m_main.Add(TPL_CLASS_IND.format(class_name=s.class_name, num_buffers=s.num_buffers, type=s.ind_type,
creator=s.creator, resource=s.resource, firma=s.firma, valores=s.valores))
self.FileEpilogue(self.m_main)
#+------------------------------------------------------------------+
#| Pool.mqh: cache de indicadores |
#+------------------------------------------------------------------+
def EmitPool(self, specs : list[CIndSpec]) -> bool:
pool = POOL_CLASS_NAME
#--- Clase
self.m_pool.Add(self.BlockWC("Cache de indicadores"))
self.m_pool.Add(TPL_POOL_CLASS_HEAD.format(pool=pool))
for s in specs:
self.m_pool.Add(TPL_POOL_MEMBER.format(class_name=s.class_name, prefix=s.prefix, m=s.member))
self.m_pool.Add(TPL_POOL_CLASS_MID.format(pool=pool))
for s in specs:
self.m_pool.Add(TPL_POOL_DECL.format(class_name=s.class_name, prefix=s.prefix, m=s.member, firma=s.firma))
self.m_pool.Add(TPL_POOL_CLASS_END)
self.m_pool.Add("\n")
#--- Init + RemoveFromArray
self.m_pool.Add(TPL_POOL_COMMON.format(pool=pool))
#--- Get* de cada indicador
for s in specs:
self.m_pool.Add(TPL_BLOCK)
writes = "".join(f" s_bit.{self.PoolWriter(t).format(v=n)};\n" for n, t in s.params)
self.m_pool.Add(TPL_POOL_GET.format(class_name=s.class_name, pool=pool, prefix=s.prefix, m=s.member,
firma=s.firma, valores=s.valores, writes=writes))
#--- Deinit
self.m_pool.Add(TPL_POOL_DEINIT_HEAD.format(pool=pool))
for s in specs:
self.m_pool.Add(TPL_POOL_DEINIT_ITEM.format(prefix=s.prefix, m=s.member))
self.m_pool.Add(TPL_POOL_DEINIT_END.format())
#--- Variables estaticas
self.m_pool.Add("\n")
self.m_pool.Add(TPL_POOL_STATIC_HEAD.format(pool=pool))
for s in specs:
self.m_pool.Add(TPL_POOL_STATIC_ITEM.format(class_name=s.class_name, pool=pool, prefix=s.prefix, m=s.member))
self.FileEpilogue(self.m_pool)
Nique_372
2026-11-01 10:04:21 -05:00
return True
#+------------------------------------------------------------------+
#| Main |
#+------------------------------------------------------------------+
def Main() -> int:
#--- Path completo al json de configuracion
fn_config = sys.argv[1] if len(sys.argv) > 1 else \
r"C:\Users\leoxd\AppData\Roaming\MetaQuotes\Terminal\D0E8209F77C8CF37AD8BF550E51FF075\MQL5\Shared Projects\MQLArticles\IndicatorsCts\Imp\Code\Config\config.json"
app = CApp()
app.AddLogFlags(CLoggerBase.LOG_ALL)
return 0 if app.Run(fn_config) else 1
if __name__ == "__main__":
sys.exit(Main())