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
|
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...).
|
| | |
|
| | |
|
| | |
|
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)
|
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)
|
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
|
| | |
|
2026-11-01 11:50:50 -05:00 | | | def SaveFile(self, out : COutFile) -> bool:
|
2026-11-01 10:04:21 -05:00 | | | try:
|
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))
|
2026-11-01 10:04:21 -05:00 | | | return True
|
| | | except OSError as e:
|
2026-11-01 11:50:50 -05:00 | | | self.LogCriticalError(f"Failed to create file:\n'{out.m_path}'\n{e}")
|
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])
|
| | |
|
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
|
| | |
|
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
|
| | |
|
2026-11-01 11:50:50 -05:00 | | | #--- Parseamos ahora si el archivo de indicadores (una sola pasada)
|
2026-11-01 10:04:21 -05:00 | | | inds = self.LoadJson(self.m_fn_src_file_ind)
|
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:
|
2026-11-01 10:04:21 -05:00 | | | return False
|
| | |
|
2026-11-01 11:50:50 -05:00 | | | #--- Generamos
|
| | | self.EmitMain(specs)
|
| | | if self.m_pool is not None and not self.EmitPool(specs):
|
2026-11-01 10:04:21 -05:00 | | | return False
|
| | |
|
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
|
| | |
|
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
|
| | |
|
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
|
2026-11-01 10:04:21 -05:00 | | |
|
| | | #+------------------------------------------------------------------+
|
2026-11-01 11:50:50 -05:00 | | | #| Prologo (header + props + guard + includes + namespace) |
|
2026-11-01 10:04:21 -05:00 | | | #+------------------------------------------------------------------+
|
2026-11-01 11:50:50 -05:00 | | | def FileProrrogo(self, out : COutFile, file : dict) -> bool:
|
2026-11-01 10:04:21 -05:00 | | | #--- Campos obligatorios
|
2026-11-01 11:50:50 -05:00 | | | out.m_path = file.get("path", "")
|
| | | if not out.m_path:
|
2026-11-01 10:04:21 -05:00 | | | self.LogError("No se pudo obtener el campo path")
|
| | | return False
|
| | |
|
2026-11-01 11:50:50 -05:00 | | | pure = os.path.basename(out.m_path) # nombre puro del archivo
|
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
|
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))
|
2026-11-01 10:04:21 -05:00 | | |
|
| | | #--- Guard (trunca a 256)
|
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))
|
2026-11-01 10:04:21 -05:00 | | |
|
2026-11-01 11:50:50 -05:00 | | | out.Add(TPL_BLOCK)
|
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
|
2026-11-01 11:50:50 -05:00 | | | out.Add(TPL_INCLUDE.format(open=op, path=path, close=cl))
|
| | |
|
| | | out.Add("\n")
|
2026-11-01 10:04:21 -05:00 | | |
|
2026-11-01 10:13:47 -05:00 | | | #--- Namepsace
|
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")
|
2026-11-01 10:13:47 -05:00 | | |
|
| | | # Final
|
2026-11-01 10:04:21 -05:00 | | | self.LogInfo(f"Archivo = '{pure}' procesado correctamente")
|
| | | return True
|
| | |
|
| | | #+------------------------------------------------------------------+
|
2026-11-01 11:50:50 -05:00 | | | #| Epilogo (fin del namespace + fin del guard) |
|
2026-11-01 10:04:21 -05:00 | | | #+------------------------------------------------------------------+
|
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:
|
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")
|
2026-11-01 11:50:50 -05:00 | | | return None
|
| | |
|
| | | specs: list[CIndSpec] = []
|
| | | classes = set()
|
| | | prefixes = set()
|
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}]")
|
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)
|
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")
|
2026-11-01 11:50:50 -05:00 | | | return None
|
2026-11-01 10:04:21 -05:00 | | |
|
| | | #--- type: "$ENUM" (se copia sin $) o numero unsigned
|
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):
|
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")
|
2026-11-01 11:50:50 -05:00 | | | return None
|
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")
|
2026-11-01 11:50:50 -05:00 | | | return None
|
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}")
|
2026-11-01 11:50:50 -05:00 | | | return None
|
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")
|
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
|
2026-11-01 10:32:00 -05:00 | | | resource: str = ind.get("resource", "")
|
| | | if resource:
|
| | | resource = f", \"{resource}\""
|
2026-11-01 10:04:21 -05:00 | | |
|
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)
|
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())
|