Warrior_EA/Expert/Persistence/ModelPersistence.mqh

707 lines
44 KiB
MQL5
Raw Permalink Normal View History

refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//+------------------------------------------------------------------+
//| Warrior_EA |
//| AnimateDread |
//| |
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
//| Model .stats / .cfg sidecars, CPU-inference validation, net load |
//| retry. STATELESS - every field these methods touch is shared |
//| elsewhere in the signal (grep-verified), unlike CChartUI's |
//| arrow-restore/rescan queues, so this collaborator owns nothing |
//| but the borrowed view. Every read/write below is a pure |
//| relocation of Expert\AIBase\Persistence.mqh's original bodies - |
//| same order, same conditionals, no logic changes. |
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
#ifndef WARRIOR_PERSISTENCE_MODELPERSISTENCE_MQH
#define WARRIOR_PERSISTENCE_MODELPERSISTENCE_MQH
class CModelPersistence
{
private:
CPersistenceView *m_view; // BORROWED - the signal owns the adapter, not the reverse
public:
CModelPersistence(void) : m_view(NULL) { }
void Bind(CPersistenceView *view) { m_view = view; }
void EnforceTopologyContract(void);
bool SaveModelStats(string fileName, bool common);
bool LoadModelStats(string fileName, bool common);
bool ValidateCpuInference(void);
bool SaveTopologyConfiguration(string fileName, int initialNeuronsCount, int hiddenLayersCount, double neuronsReduction, int minNeuronsCount, int optimizationAlgo, int historyBars, int outputNeuronsCount, int neuronsCount, int studyPeriod, int minTrainYear, bool isInitialized, int stopTrainWR, int fractalPeriods, int convFilterCount, int lstmHiddenSize, bool common);
bool LoadAndCompareTopologyConfiguration(string fileName, int &initialNeuronsCount, int &hiddenLayersCount, double neuronsReduction, int minNeuronsCount, int optimizationAlgo, int &historyBars, int outputNeuronsCount, int neuronsCount, int minTrainYear, bool isInitialized, int stopTrainWR, int fractalPeriods, int &convFilterCount, int &lstmHiddenSize, bool common);
string ReadAltDataPinFromCfg(void);
bool LoadNetWithRetry(double &indicatorParams[]);
};
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//+------------------------------------------------------------------+
//| Re-assert the parts of a just-loaded net that the CODE owns but |
//| the FILE also stores. See OutputLayerActivation()'s declaration |
//| comment and CNet::EnforceOutputActivation() (AI\Network.mqh). |
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
void CModelPersistence::EnforceTopologyContract(void)
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(!m_view.NetLoaded())
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
return;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
//--- Stale conv receptive field. Unlike the activation below this cannot be repaired in place: the
//--- conv weight block is (window+1)*window_out, so a different window is a different tensor. Flag it
//--- and let the caller retrain - see m_topologySuperseded's use in InitNeuralNetwork.
if(m_view.UsesConvStage())
feat(ai): real conv receptive field + the reference's channel pool CONV's convolution used window = step = one bar, which is a per-bar projection - a 1x1 conv with a temporal receptive field of ONE BAR. It never mixed information across time, so "convolutional" described the layer type and nothing about what it computed. Same finding that sank HYBRID's LSTM. Pooling was removed on 2026-07-29 for being misconfigured against the conv output's memory layout. That removal was right; leaving the conv at a one-bar window was not. The two belong together: the NeuroNet_DNG reference (references\MQL5\Experts\EDL\Trajectory.mqh layers 2-5, kernels byte-identical to ours) pairs conv(window=2, step=1, window_out=4) with pool(window=4, step=4), and the pool only earns its place because a conv with a real receptive field sits above it. The input is bar-major (BufferTempData appends m_neuronsCount contiguous features per bar), so a flat window of k*m_neuronsCount spans exactly k bars - the receptive field needed NO kernel change. The conv output is position-major, so window == step == window_out is a clean max-over-channels, which is what the reference does and what the existing pool kernels already implement correctly. New chain at H1 defaults (420 = 20 bars x 21): conv1 w=42 s=21 out=8 -> 19 pos x 8 = 152 pool w=8 s=8 -> 19 conv2 w=2 s=1 out=8 -> 18 pos x 8 = 144 (effective field: 3 bars) We deliberately stop before the reference's SECOND pool: a channel pool emits one scalar per position, so a trailing pool would hand the dense stack 18 values and force it to fan out 18 -> 64. That is a bottleneck below every learnable layer - the same class of mistake the 2026-07-29 removal was about. Fixes a latent sizing bug this exposed: CNet's conv/pool position cursor tracked sliding POSITIONS, but a conv's real width is units_count * window_out. Any pool stacked on a conv would therefore have sized against a width window_out times too small and silently built the wrong shape. Both branches now read the built layer's actual Neurons(), which is what the batch-norm branch already did for the same reason. Also closes the architecture-pinning trap: a .nnw persists the window each conv was built with, so an existing CONV/HYBRID model would have loaded cleanly and gone on training under the OLD architecture. The conv weight tensor is (window+1)*window_out, so this cannot be repaired in place - EnforceTopologyContract now detects it, reports both shapes, and retrains. Conv chain shape is derived in one place (ConvReceptiveFieldBars / ConvFirstStagePositions / HasSecondConvStage / ConvOutputPositions / ConvOutputWidth) and consumed by AddConvStage, LstmFanIn and the startup config line, so what is built and what is logged cannot drift. Both builds compile 0 errors, 0 warnings. Forces a CONV and HYBRID retrain. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:05:37 -04:00
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
uint loadedWindow = m_view.NetFirstConvWindow();
uint intendedWindow = (uint)(m_view.ConvReceptiveFieldBars() * m_view.NeuronsCount());
feat(ai): real conv receptive field + the reference's channel pool CONV's convolution used window = step = one bar, which is a per-bar projection - a 1x1 conv with a temporal receptive field of ONE BAR. It never mixed information across time, so "convolutional" described the layer type and nothing about what it computed. Same finding that sank HYBRID's LSTM. Pooling was removed on 2026-07-29 for being misconfigured against the conv output's memory layout. That removal was right; leaving the conv at a one-bar window was not. The two belong together: the NeuroNet_DNG reference (references\MQL5\Experts\EDL\Trajectory.mqh layers 2-5, kernels byte-identical to ours) pairs conv(window=2, step=1, window_out=4) with pool(window=4, step=4), and the pool only earns its place because a conv with a real receptive field sits above it. The input is bar-major (BufferTempData appends m_neuronsCount contiguous features per bar), so a flat window of k*m_neuronsCount spans exactly k bars - the receptive field needed NO kernel change. The conv output is position-major, so window == step == window_out is a clean max-over-channels, which is what the reference does and what the existing pool kernels already implement correctly. New chain at H1 defaults (420 = 20 bars x 21): conv1 w=42 s=21 out=8 -> 19 pos x 8 = 152 pool w=8 s=8 -> 19 conv2 w=2 s=1 out=8 -> 18 pos x 8 = 144 (effective field: 3 bars) We deliberately stop before the reference's SECOND pool: a channel pool emits one scalar per position, so a trailing pool would hand the dense stack 18 values and force it to fan out 18 -> 64. That is a bottleneck below every learnable layer - the same class of mistake the 2026-07-29 removal was about. Fixes a latent sizing bug this exposed: CNet's conv/pool position cursor tracked sliding POSITIONS, but a conv's real width is units_count * window_out. Any pool stacked on a conv would therefore have sized against a width window_out times too small and silently built the wrong shape. Both branches now read the built layer's actual Neurons(), which is what the batch-norm branch already did for the same reason. Also closes the architecture-pinning trap: a .nnw persists the window each conv was built with, so an existing CONV/HYBRID model would have loaded cleanly and gone on training under the OLD architecture. The conv weight tensor is (window+1)*window_out, so this cannot be repaired in place - EnforceTopologyContract now detects it, reports both shapes, and retrains. Conv chain shape is derived in one place (ConvReceptiveFieldBars / ConvFirstStagePositions / HasSecondConvStage / ConvOutputPositions / ConvOutputWidth) and consumed by AddConvStage, LstmFanIn and the startup config line, so what is built and what is logged cannot drift. Both builds compile 0 errors, 0 warnings. Forces a CONV and HYBRID retrain. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:05:37 -04:00
if(loadedWindow > 0 && loadedWindow != intendedWindow)
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
m_view.SetTopologySuperseded(true);
Print(m_view.Id() + ": SUPERSEDED architecture on disk - the saved model's conv receptive field is " +
IntegerToString((int)loadedWindow) + " (" + IntegerToString((int)(loadedWindow / (uint)MathMax(1, m_view.NeuronsCount()))) +
feat(ai): real conv receptive field + the reference's channel pool CONV's convolution used window = step = one bar, which is a per-bar projection - a 1x1 conv with a temporal receptive field of ONE BAR. It never mixed information across time, so "convolutional" described the layer type and nothing about what it computed. Same finding that sank HYBRID's LSTM. Pooling was removed on 2026-07-29 for being misconfigured against the conv output's memory layout. That removal was right; leaving the conv at a one-bar window was not. The two belong together: the NeuroNet_DNG reference (references\MQL5\Experts\EDL\Trajectory.mqh layers 2-5, kernels byte-identical to ours) pairs conv(window=2, step=1, window_out=4) with pool(window=4, step=4), and the pool only earns its place because a conv with a real receptive field sits above it. The input is bar-major (BufferTempData appends m_neuronsCount contiguous features per bar), so a flat window of k*m_neuronsCount spans exactly k bars - the receptive field needed NO kernel change. The conv output is position-major, so window == step == window_out is a clean max-over-channels, which is what the reference does and what the existing pool kernels already implement correctly. New chain at H1 defaults (420 = 20 bars x 21): conv1 w=42 s=21 out=8 -> 19 pos x 8 = 152 pool w=8 s=8 -> 19 conv2 w=2 s=1 out=8 -> 18 pos x 8 = 144 (effective field: 3 bars) We deliberately stop before the reference's SECOND pool: a channel pool emits one scalar per position, so a trailing pool would hand the dense stack 18 values and force it to fan out 18 -> 64. That is a bottleneck below every learnable layer - the same class of mistake the 2026-07-29 removal was about. Fixes a latent sizing bug this exposed: CNet's conv/pool position cursor tracked sliding POSITIONS, but a conv's real width is units_count * window_out. Any pool stacked on a conv would therefore have sized against a width window_out times too small and silently built the wrong shape. Both branches now read the built layer's actual Neurons(), which is what the batch-norm branch already did for the same reason. Also closes the architecture-pinning trap: a .nnw persists the window each conv was built with, so an existing CONV/HYBRID model would have loaded cleanly and gone on training under the OLD architecture. The conv weight tensor is (window+1)*window_out, so this cannot be repaired in place - EnforceTopologyContract now detects it, reports both shapes, and retrains. Conv chain shape is derived in one place (ConvReceptiveFieldBars / ConvFirstStagePositions / HasSecondConvStage / ConvOutputPositions / ConvOutputWidth) and consumed by AddConvStage, LstmFanIn and the startup config line, so what is built and what is logged cannot drift. Both builds compile 0 errors, 0 warnings. Forces a CONV and HYBRID retrain. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:05:37 -04:00
" bars), this build specifies " + IntegerToString((int)intendedWindow) + " (" +
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
IntegerToString(m_view.ConvReceptiveFieldBars()) + " bars). The conv weight tensor is a different" +
feat(ai): real conv receptive field + the reference's channel pool CONV's convolution used window = step = one bar, which is a per-bar projection - a 1x1 conv with a temporal receptive field of ONE BAR. It never mixed information across time, so "convolutional" described the layer type and nothing about what it computed. Same finding that sank HYBRID's LSTM. Pooling was removed on 2026-07-29 for being misconfigured against the conv output's memory layout. That removal was right; leaving the conv at a one-bar window was not. The two belong together: the NeuroNet_DNG reference (references\MQL5\Experts\EDL\Trajectory.mqh layers 2-5, kernels byte-identical to ours) pairs conv(window=2, step=1, window_out=4) with pool(window=4, step=4), and the pool only earns its place because a conv with a real receptive field sits above it. The input is bar-major (BufferTempData appends m_neuronsCount contiguous features per bar), so a flat window of k*m_neuronsCount spans exactly k bars - the receptive field needed NO kernel change. The conv output is position-major, so window == step == window_out is a clean max-over-channels, which is what the reference does and what the existing pool kernels already implement correctly. New chain at H1 defaults (420 = 20 bars x 21): conv1 w=42 s=21 out=8 -> 19 pos x 8 = 152 pool w=8 s=8 -> 19 conv2 w=2 s=1 out=8 -> 18 pos x 8 = 144 (effective field: 3 bars) We deliberately stop before the reference's SECOND pool: a channel pool emits one scalar per position, so a trailing pool would hand the dense stack 18 values and force it to fan out 18 -> 64. That is a bottleneck below every learnable layer - the same class of mistake the 2026-07-29 removal was about. Fixes a latent sizing bug this exposed: CNet's conv/pool position cursor tracked sliding POSITIONS, but a conv's real width is units_count * window_out. Any pool stacked on a conv would therefore have sized against a width window_out times too small and silently built the wrong shape. Both branches now read the built layer's actual Neurons(), which is what the batch-norm branch already did for the same reason. Also closes the architecture-pinning trap: a .nnw persists the window each conv was built with, so an existing CONV/HYBRID model would have loaded cleanly and gone on training under the OLD architecture. The conv weight tensor is (window+1)*window_out, so this cannot be repaired in place - EnforceTopologyContract now detects it, reports both shapes, and retrains. Conv chain shape is derived in one place (ConvReceptiveFieldBars / ConvFirstStagePositions / HasSecondConvStage / ConvOutputPositions / ConvOutputWidth) and consumed by AddConvStage, LstmFanIn and the startup config line, so what is built and what is logged cannot drift. Both builds compile 0 errors, 0 warnings. Forces a CONV and HYBRID retrain. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:05:37 -04:00
" shape, so this cannot be repaired in place - retraining from era 0.");
}
}
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
ENUM_ACTIVATION intended = m_view.OutputLayerActivation();
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
ENUM_ACTIVATION stale = intended;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(!m_view.NetEnforceOutputActivation(intended, stale))
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
return;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
Print(m_view.Id() + ": REPAIRED loaded model - output layer activation was " + ActivationName(stale) +
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
" on disk, topology specifies " + ActivationName(intended) +
". The saved file was produced by an older build; it has been corrected in memory and the next" +
" save will persist the correction. If training looks wrong from here, reset weights and retrain -" +
" these weights were learned against the stale head.");
}
//+------------------------------------------------------------------+
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//| Persist/restore the calibration state that must survive a restart |
//| for live trading to behave like training: the true class priors |
//| and m_confidenceCalScale. Same FILE_COMMON/tester write-guard as |
//| CNet::Save so a backtest never overwrites the shared production |
//| stats. Versioned/magic-prefixed; a mismatch is treated as absent. |
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
bool CModelPersistence::SaveModelStats(string fileName, bool common)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
//--- mirror CNet::Save's guard: shared production stats are never written from inside a backtest
if(common && (MQLInfoInteger(MQL_OPTIMIZATION) || MQLInfoInteger(MQL_TESTER) || MQLInfoInteger(MQL_FORWARD)))
return true;
//--- Staged through a temp file + atomic rename (System\AtomicFile.mqh).
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
int statsCommonFlag = (common ? FILE_COMMON : 0);
string statsTmpName = "";
int handle = AtomicWriteBegin(fileName + ".stats", statsCommonFlag, statsTmpName);
if(handle == INVALID_HANDLE)
{
Print(__FUNCTION__ + ": FileOpen failed for " + statsTmpName + ", error " + IntegerToString(GetLastError()) +
" - calibration/online-learning state not persisted.");
return false;
}
//--- WST6 has the SAME field layout as WST5 - the bump exists to invalidate stale IS counters,
//--- whose MEANING changed: they used to count every oversampled occurrence, now they count each
//--- bar once.
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
bool ok = true;
fix(vote): persist the member's skill verdict - a converged model was ruled no-skill on every restart SP500 resumed converged at era 136 with its tier ladder correctly restored and still swept 4999 bars reporting "0 had a snapshot, drew 0 arrow(s)" while the other five charts drew 221-312. HasDemonstratedEdge() - added with the no-skill exclusion - compares m_eraStatPrecPct against m_eraStatChancePct. Both are written once per era by EnsembleStashEraStats. A converged model runs no eras, so after a restart both sat at their -1 ctor defaults, every member was ruled no-skill, ReconstructionWeight() returned 0 for all four, and the overlay divisor was zero on every bar. Exactly the failure the WST7 ladder persistence fixed one level down: the ladder says how much a member votes, this says whether it may. RankTiersFromOos already computes the pair (pooled holdout precision and the zero-skill reference rate) and now records it as the CERTIFIED edge. That path is reached by the era end AND by the deployed replay, which is the only measurement a converged model will ever make. Persisted as WST8; HasDemonstratedEdge() prefers the era pair and falls back to it. The census line also had to be fixed: it reported "NOT ONE of those bars had a single member snapshot ... no enrolled member has published m_overlaySigSnap" for a condition that was purely a skill verdict. The snapshots were there. It now counts the two causes separately and names the one that fired. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 16:53:16 -04:00
if(FileWriteInteger(handle, 0x57535438) <= 0) // 'WST8' magic/version (WST8 = +the member's certified precision/chance pair, WST7 = +the ensemble's certified record, WST6 = IS-counter meaning fixed, WST5 = +compounded IS/OOS counts, WST4 = +live reliability, WST3 = +online state, WST2 = +CPU-marker, WST1 = base)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteDouble(handle, m_view.PriorBuy()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteDouble(handle, m_view.PriorSell()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteDouble(handle, m_view.PriorNeutral()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteDouble(handle, m_view.ConfidenceCalScale()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
//--- CPU-inference-safe marker (see ValidateCpuInference): gates whether an inference-only backtest
//--- of this model may run DLL-free. Appended after the v1 fields so a v1 reader stops cleanly before it.
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteInteger(handle, m_view.MqlInferenceValidated() ? 1 : 0) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
//--- Online continual-learning state (WST3, see OnlineLearnStep) - the bar-time watermark of the
//--- newest bar already learned from, the rolling guardrail accuracy, and the cumulative update count.
//--- Appended after the WST2 fields so a WST2 reader stops cleanly before them.
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteLong(handle, (long)m_view.OnlineLearnedUpToTime()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteDouble(handle, m_view.OnlineRollingAcc()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteLong(handle, m_view.OnlineSamples()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
//--- Deployed model's last-measured OOS reliability (WST4) - the live status panel shows this as the
//--- "signal hit-rate" so a freshly-reloaded, inference-only model still reports what to expect live
//--- (these members are computed only during training, so without persistence they read n/a on reload).
//--- Appended after the WST3 fields so a WST3 reader stops cleanly before them.
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteInteger(handle, m_view.LastBuyFiredPrecPct()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteInteger(handle, m_view.LastSellFiredPrecPct()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteInteger(handle, m_view.LastBuyRecallPct()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteInteger(handle, m_view.LastSellRecallPct()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteInteger(handle, m_view.LastBuyFired()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteInteger(handle, m_view.LastSellFired()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
//--- Compounded, persistent IS/OOS accuracy counts (WST5) - see m_cumIsCorrect. Carried across
//--- restarts so the panel's accuracy keeps compounding instead of restarting each session.
//--- Appended after the WST4 fields so a WST4 reader stops cleanly before them.
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteLong(handle, m_view.CumIsCorrect()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteLong(handle, m_view.CumIsTotal()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteLong(handle, m_view.CumOosCorrect()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteLong(handle, m_view.CumOosTotal()) <= 0)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
ok = false;
fix(vote): persist the tier ladder - a converged model was mute after every restart THIS IS NOT A DISPLAY BUG. A deployed model could not vote, or trade, at any point after a terminal restart, and never would have. LiveVoteContribution() returns 0 for every call until m_tiersSelfRanked is set - deliberately, and correctly: before RankTiersFromOos() runs, m_pattern_0..3 hold the constructor's stock 25/50/75/100, which since the 2026-08-18 currency change is the WRONG UNIT rather than a weak opinion, and one unranked member would drag the whole ensemble over any threshold. But that ladder is produced ONLY by a completed pass 3, and it was never persisted - the code comment at LiveVoteContribution says so outright. A converged model runs no further passes. So on every restart it lost its entire vote permanently: LiveVoteContribution -> 0 => no live vote ("0 vote/4 flat") ReconstructionWeight -> 0 => overlay divisor 0 ("0 had a snapshot") => no arrows => no fired bars, so g_ensCumOosTotal stays 0 => "measuring..." forever Every symptom reported over the last three exchanges is that one cause. The log is unambiguous: six H4 charts resumed at era 70/71, all 24 rescans completed with ~2700 Buy / ~2200 Sell per model, and the overlay then swept 4999 bars finding "0 had a snapshot". The calls were there; nothing was permitted to count them. WST7 now stores the four tier weights, the module trust weight and the self-ranked flag beside the model. Restored only when the stored flag says the ladder was MEASURED - a .stats written before a model's first pass 3 holds the stock ladder, and adopting that as if measured is the exact error the flag exists to prevent. A .stats predating WST7 has no ladder, so existing converged models stay silent until their next scoring pass mints one. That case now prints a warning naming all three of its symptoms, because each one independently looks like a different bug. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 14:26:33 -04:00
//--- THE TIER LADDER (WST7), AND IT IS THE MOST IMPORTANT THING IN THIS FILE.
//---
//--- These four weights plus the module trust weight are the model's VOTE. They are produced only
//--- by a completed pass 3 (RankTiersFromOos), and until they exist LiveVoteContribution() returns
//--- 0 for every call - deliberately, because the constructor's stock 25/50/75/100 ladder is the
//--- wrong UNIT (a win-rate currency since 2026-08-18), not a weak opinion, and one unranked member
//--- would drag the whole ensemble over any threshold.
//---
//--- That silencing is right while training and catastrophic on a resume. A CONVERGED model runs no
//--- further passes, so every restart left it permanently mute: no live vote, no reconstruction
//--- weight, an overlay divisor of zero on every bar, and therefore no arrows and no aggregate win
//--- rate. Diagnosed 2026-08-25 from six H4 charts that read "0 vote/4 flat, peak 0.0%" and swept
//--- 4999 bars finding "0 had a snapshot" - with the models resumed at era 70/71 and every rescan
//--- reporting ~2700 Buy / ~2200 Sell. The calls were there; nothing was allowed to count them.
if(ok && FileWriteInteger(handle, m_view.TierWeight(0)) <= 0)
ok = false;
if(ok && FileWriteInteger(handle, m_view.TierWeight(1)) <= 0)
ok = false;
if(ok && FileWriteInteger(handle, m_view.TierWeight(2)) <= 0)
ok = false;
if(ok && FileWriteInteger(handle, m_view.TierWeight(3)) <= 0)
ok = false;
if(ok && FileWriteDouble(handle, m_view.ModuleTrustWeight()) <= 0)
ok = false;
if(ok && FileWriteInteger(handle, m_view.TiersSelfRanked() ? 1 : 0) <= 0)
ok = false;
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
//--- THE ENSEMBLE'S CERTIFIED RECORD (WST7). Everything below is CHART-scoped, not member-scoped -
//--- every member writes the same values into its own .stats, and load takes the most complete
//--- copy. That redundancy is deliberate: there is no ensemble-owned file, and inventing one would
//--- need its own key, its own atomic write and its own reset-weights wipe, all of which this
//--- sidecar already has.
//---
//--- WHY IT HAS TO BE PERSISTED AT ALL: these were session globals written once per era at pass-3
//--- completion. A DEPLOYED ensemble runs no further eras, so on every restart the aggregate win
//--- rate, the deploy verdict and the panel line that reports them were lost and could never be
//--- regenerated - the panel then fell back to the per-member rows (user report 2026-08-25).
//---
//--- The vote threshold rides along because every number here is CONDITIONAL ON IT: `fired` counts
//--- only bars where |vote| cleared it. Restoring these under a different threshold would report a
//--- win rate for a strategy the chart is no longer running.
if(ok && FileWriteLong(handle, g_ensCumOosCorrect) <= 0)
ok = false;
if(ok && FileWriteLong(handle, g_ensCumOosTotal) <= 0)
ok = false;
if(ok && FileWriteDouble(handle, g_ensBestPrecPct) <= 0)
ok = false;
if(ok && FileWriteDouble(handle, g_ensBestChancePct) <= 0)
ok = false;
if(ok && FileWriteInteger(handle, g_ensBestCalls) <= 0)
ok = false;
if(ok && FileWriteInteger(handle, g_ensDeployApproved ? 1 : 0) <= 0)
ok = false;
if(ok && FileWriteDouble(handle, g_ensembleVoteThreshold) <= 0)
ok = false;
fix(vote): persist the member's skill verdict - a converged model was ruled no-skill on every restart SP500 resumed converged at era 136 with its tier ladder correctly restored and still swept 4999 bars reporting "0 had a snapshot, drew 0 arrow(s)" while the other five charts drew 221-312. HasDemonstratedEdge() - added with the no-skill exclusion - compares m_eraStatPrecPct against m_eraStatChancePct. Both are written once per era by EnsembleStashEraStats. A converged model runs no eras, so after a restart both sat at their -1 ctor defaults, every member was ruled no-skill, ReconstructionWeight() returned 0 for all four, and the overlay divisor was zero on every bar. Exactly the failure the WST7 ladder persistence fixed one level down: the ladder says how much a member votes, this says whether it may. RankTiersFromOos already computes the pair (pooled holdout precision and the zero-skill reference rate) and now records it as the CERTIFIED edge. That path is reached by the era end AND by the deployed replay, which is the only measurement a converged model will ever make. Persisted as WST8; HasDemonstratedEdge() prefers the era pair and falls back to it. The census line also had to be fixed: it reported "NOT ONE of those bars had a single member snapshot ... no enrolled member has published m_overlaySigSnap" for a condition that was purely a skill verdict. The snapshots were there. It now counts the two causes separately and names the one that fired. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 16:53:16 -04:00
//--- THIS MEMBER'S CERTIFIED PRECISION AND CHANCE RATE (WST8) - member-scoped, unlike the block
//--- above. The SAME failure the tier ladder had, discovered the same way: SP500 resumed converged
//--- at era 136 with its ladder restored and still swept 4999 bars reporting "0 had a snapshot,
//--- drew 0 arrow(s)", because HasDemonstratedEdge() (added 2026-08-26 with the no-skill exclusion)
//--- compares two era-only doubles that a converged model never recomputes. Both sat at -1, so
//--- every member was ruled no-skill, ReconstructionWeight() returned 0 and the overlay divisor was
//--- zero on every bar. Persisting the ladder alone was not enough - the ladder says HOW MUCH a
//--- member votes, this says WHETHER IT MAY.
if(ok && FileWriteDouble(handle, m_view.CertifiedPrecPct()) <= 0)
ok = false;
if(ok && FileWriteDouble(handle, m_view.CertifiedChancePct()) <= 0)
ok = false;
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//--- A partial write (disk full mid-write) now discards the temp and leaves the previous good
//--- .stats in place, instead of publishing a truncated one that reads back as all-zero
//--- calibration state.
return AtomicWriteEnd(handle, fileName + ".stats", statsTmpName, statsCommonFlag, ok, __FUNCTION__);
}
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
bool CModelPersistence::LoadModelStats(string fileName, bool common)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
if(!FileIsExist(fileName + ".stats", common ? FILE_COMMON : 0))
return false;
//--- share flags: read-only, must not fail just because another process holds the file - see CopySharedFile().
int handle = FileOpen(fileName + ".stats", (common ? FILE_COMMON : 0) | FILE_BIN | FILE_READ | FILE_SHARE_READ | FILE_SHARE_WRITE);
if(handle == INVALID_HANDLE)
return false;
int magic = FileReadInteger(handle);
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
if(magic != 0x57535431 && magic != 0x57535432 && magic != 0x57535433 && magic != 0x57535434 &&
fix(vote): persist the member's skill verdict - a converged model was ruled no-skill on every restart SP500 resumed converged at era 136 with its tier ladder correctly restored and still swept 4999 bars reporting "0 had a snapshot, drew 0 arrow(s)" while the other five charts drew 221-312. HasDemonstratedEdge() - added with the no-skill exclusion - compares m_eraStatPrecPct against m_eraStatChancePct. Both are written once per era by EnsembleStashEraStats. A converged model runs no eras, so after a restart both sat at their -1 ctor defaults, every member was ruled no-skill, ReconstructionWeight() returned 0 for all four, and the overlay divisor was zero on every bar. Exactly the failure the WST7 ladder persistence fixed one level down: the ladder says how much a member votes, this says whether it may. RankTiersFromOos already computes the pair (pooled holdout precision and the zero-skill reference rate) and now records it as the CERTIFIED edge. That path is reached by the era end AND by the deployed replay, which is the only measurement a converged model will ever make. Persisted as WST8; HasDemonstratedEdge() prefers the era pair and falls back to it. The census line also had to be fixed: it reported "NOT ONE of those bars had a single member snapshot ... no enrolled member has published m_overlaySigSnap" for a condition that was purely a skill verdict. The snapshots were there. It now counts the two causes separately and names the one that fired. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 16:53:16 -04:00
magic != 0x57535435 && magic != 0x57535436 && magic != 0x57535437 && magic != 0x57535438)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
FileClose(handle);
return false;
}
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
m_view.SetPriorBuy(FileReadDouble(handle));
m_view.SetPriorSell(FileReadDouble(handle));
m_view.SetPriorNeutral(FileReadDouble(handle));
m_view.SetConfidenceCalScale(FileReadDouble(handle));
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
//--- THE VERSION TESTS ARE ">=", NOT AN OR-CHAIN. The magics are the ASCII bytes 'WST1'..'WST7',
//--- so they increase monotonically and "this field exists from vN onward" is exactly an ordering
//--- question. The chain this replaces had to be edited in five places to add one version, and a
//--- missed one would silently read the NEXT field's bytes into this one - a corruption that reads
//--- back as plausible numbers rather than as a failure. The accepted set is already validated by
//--- the magic check above, so ">=" cannot admit an unknown format here.
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//--- v2+ appended the CPU-inference-safe marker; v1 files predate it (treated as not-yet-validated so
//--- the model stays on the DLL path until re-deployed by a build that runs ValidateCpuInference).
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
m_view.SetMqlInferenceValidated((magic >= 0x57535432) ? (FileReadInteger(handle) != 0) : false);
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//--- v3 appended the online continual-learning state. Older files predate it: leave the watermark at 0
//--- (OnlineLearnStep anchors it to the current frontier on first run - no retroactive backprop) and
//--- the rolling accuracy at -1 (re-seeded from the deploy baseline on the first update).
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
if(magic >= 0x57535433)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
m_view.SetOnlineLearnedUpToTime((datetime)FileReadLong(handle));
m_view.SetOnlineRollingAcc(FileReadDouble(handle));
m_view.SetOnlineSamples(FileReadLong(handle));
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
}
//--- v4 appended the deployed model's last-measured OOS reliability (for the live status panel). Older
//--- files predate it: the members keep their -1 / 0 ctor defaults, so the panel shows no hit-rate line
//--- until the model is re-trained (or re-deployed) by a WST4+ build - exactly the pre-persistence behaviour.
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
if(magic >= 0x57535434)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
m_view.SetLastBuyFiredPrecPct(FileReadInteger(handle));
m_view.SetLastSellFiredPrecPct(FileReadInteger(handle));
m_view.SetLastBuyRecallPct(FileReadInteger(handle));
m_view.SetLastSellRecallPct(FileReadInteger(handle));
m_view.SetLastBuyFired(FileReadInteger(handle));
m_view.SetLastSellFired(FileReadInteger(handle));
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
}
//--- v5 appended the compounded/persistent IS/OOS accuracy counts (see m_cumIsCorrect). Older files
//--- predate it: the counts keep their 0 ctor defaults, so the panel shows "measuring" until the next
//--- era scores signals - then it resumes compounding from there.
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
if(magic >= 0x57535435)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
m_view.SetCumIsCorrect(FileReadLong(handle));
m_view.SetCumIsTotal(FileReadLong(handle));
m_view.SetCumOosCorrect(FileReadLong(handle));
m_view.SetCumOosTotal(FileReadLong(handle));
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//--- A WST5 file's IS pair counted every OVERSAMPLED OCCURRENCE, so it was measured against a
//--- ~58%-directional queue instead of the real ~6% distribution - not comparable with the
//--- OOS pair beside it, and the source of the "IS 77% / OOS 12%, looks like overfitting"
//--- reading.
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
if(magic == 0x57535435)
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
m_view.SetCumIsCorrect(0);
m_view.SetCumIsTotal(0);
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
}
}
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
//--- v7 appended the ENSEMBLE's certified record - chart-scoped, mirrored into every member's file.
//--- See the matching write for why it must be persisted at all.
if(magic >= 0x57535437)
{
fix(vote): persist the tier ladder - a converged model was mute after every restart THIS IS NOT A DISPLAY BUG. A deployed model could not vote, or trade, at any point after a terminal restart, and never would have. LiveVoteContribution() returns 0 for every call until m_tiersSelfRanked is set - deliberately, and correctly: before RankTiersFromOos() runs, m_pattern_0..3 hold the constructor's stock 25/50/75/100, which since the 2026-08-18 currency change is the WRONG UNIT rather than a weak opinion, and one unranked member would drag the whole ensemble over any threshold. But that ladder is produced ONLY by a completed pass 3, and it was never persisted - the code comment at LiveVoteContribution says so outright. A converged model runs no further passes. So on every restart it lost its entire vote permanently: LiveVoteContribution -> 0 => no live vote ("0 vote/4 flat") ReconstructionWeight -> 0 => overlay divisor 0 ("0 had a snapshot") => no arrows => no fired bars, so g_ensCumOosTotal stays 0 => "measuring..." forever Every symptom reported over the last three exchanges is that one cause. The log is unambiguous: six H4 charts resumed at era 70/71, all 24 rescans completed with ~2700 Buy / ~2200 Sell per model, and the overlay then swept 4999 bars finding "0 had a snapshot". The calls were there; nothing was permitted to count them. WST7 now stores the four tier weights, the module trust weight and the self-ranked flag beside the model. Restored only when the stored flag says the ladder was MEASURED - a .stats written before a model's first pass 3 holds the stock ladder, and adopting that as if measured is the exact error the flag exists to prevent. A .stats predating WST7 has no ladder, so existing converged models stay silent until their next scoring pass mints one. That case now prints a warning naming all three of its symptoms, because each one independently looks like a different bug. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 14:26:33 -04:00
//--- THE TIER LADDER FIRST, in write order. Restoring it is what lets a resumed converged model
//--- vote at all - see the matching write for the failure it fixes. Adopted UNCONDITIONALLY:
//--- these weights belong to the .nnw sitting beside this file, they were measured on that
//--- model's own holdout, and the alternative is not a safer number but silence.
int t0 = FileReadInteger(handle);
int t1 = FileReadInteger(handle);
int t2 = FileReadInteger(handle);
int t3 = FileReadInteger(handle);
double moduleW = FileReadDouble(handle);
bool ranked = (FileReadInteger(handle) != 0);
//--- ...but only when the file actually carries a ranked ladder. A model that was saved BEFORE
//--- its first pass 3 stored the stock 25/50/75/100, and adopting that as if measured is the
//--- precise error the self-ranked flag exists to prevent.
if(ranked)
{
m_view.SetTierWeight(0, t0);
m_view.SetTierWeight(1, t1);
m_view.SetTierWeight(2, t2);
m_view.SetTierWeight(3, t3);
if(moduleW > 0.0 && moduleW <= 1.0)
m_view.SetModuleTrustWeight(moduleW);
m_view.SetTiersSelfRanked(true);
Print(m_view.Id() + ": restored the measured tier ladder from .stats -> T0=" + IntegerToString(t0) +
" T1=" + IntegerToString(t1) + " T2=" + IntegerToString(t2) + " T3=" + IntegerToString(t3) +
" | module weight " + DoubleToString(moduleW, 2) +
". This model can vote immediately; without it a converged model stays silent until it retrains.");
}
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
long ensCorrect = FileReadLong(handle);
long ensTotal = FileReadLong(handle);
double ensPrec = FileReadDouble(handle);
double ensChance = FileReadDouble(handle);
int ensCalls = FileReadInteger(handle);
bool ensDeploy = (FileReadInteger(handle) != 0);
double ensThresh = FileReadDouble(handle);
fix(persist): adopt the pinned threshold on load; trim the accuracy label THE REGRESSION, mine, from c6eb908. LoadModelStats() dropped the whole ensemble record unless the stored threshold EQUALLED the live one. That was right while the threshold was an operator input - a record built at 25% says nothing about a chart now running 15%. Once the threshold became derived and pinned the comparison inverted its own meaning: at load time g_ensembleVoteThreshold is still the Signal_ThresholdOpen SEED, so the stored derived value never matches and the record is ALWAYS dropped. Two things died with it, silently: * g_ensDeployApproved - a DEPLOYED ensemble came back as a training one on every restart, discarding the family-wise deploy it had earned. * the pinned threshold itself - PublishVoteThreshold() only fires on a positive g_ensDerivedThreshold, so a deployed chart would have traded the .chr seed instead of the rung its deploy was certified at. certified != traded, the defect 2c443ba fixed, reintroduced three commits later. Not yet observed live only because SP500 deployed at 10:20, after the last restart at 09:54, so no restart has crossed a deployed state. Now ADOPTED, not compared: threshold, counts and deploy flag restore together, the only coherent state - the counts were conditional on that threshold, which is why it is stored beside them. Same doctrine as the .cfg topology: adopt what the model was certified with, never re-derive it underneath a checkpoint. The most-complete-copy guard is unchanged. It now logs what it restored. THE PANEL LABEL. "Vote win rate: 34% (338 calls at or above the 15% threshold, this era 31%)" -> "Accuracy: 34%". The call count, threshold and this-era figure are diagnostics, all present in the era log line, and on a panel they buried the one number anyone reads. The threshold no longer needs naming either: it is derived and pinned rather than an operator's choice, so it is not a caveat on the percentage. The era/models/deployable suffix appended at era end goes with them. Compiled clean; NOT yet run. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 11:59:25 -04:00
//--- THE THRESHOLD IS NOW ADOPTED, NOT COMPARED (2026-08-26). It used to be compared, and that
//--- was right while it was an OPERATOR'S INPUT: a record built at 25% said nothing about a
//--- chart now running 15%, so it was dropped and the next era rebuilt it. Since the threshold
//--- became a DERIVED, PINNED property of the checkpoint, the comparison inverted its own
//--- meaning - at load time g_ensembleVoteThreshold is still the Signal_ThresholdOpen SEED, so
//--- the stored value never matches and the record is always dropped. Two things died with it,
//--- both silently:
//--- * g_ensDeployApproved. A DEPLOYED ensemble came back as a training one on every restart.
//--- * the pinned threshold itself. PublishVoteThreshold() only fires on a positive
//--- g_ensDerivedThreshold, so a deployed chart would have traded the .chr seed instead of
//--- the rung its deploy was certified at - certified != traded, again.
//--- Adopting restores threshold, counts and deploy flag TOGETHER, which is the only coherent
//--- state: the counts were conditional on that threshold, and it is stored beside them for
//--- exactly that reason. Same doctrine as the .cfg topology - adopt what the model was
//--- certified with, never re-derive it underneath a checkpoint.
//---
//--- THE MOST COMPLETE COPY STILL WINS. Every member writes this same record into its own
//--- .stats at slightly different moments, so a member whose file was written an era earlier
//--- must not overwrite a fuller one loaded a moment ago. Ordering by total fired bars is
//--- monotone (the counters only accumulate), which is what makes load order not matter.
if(ensThresh > 0.0 && ensTotal >= g_ensCumOosTotal)
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
{
g_ensCumOosCorrect = ensCorrect;
g_ensCumOosTotal = ensTotal;
g_ensBestPrecPct = ensPrec;
g_ensBestChancePct = ensChance;
g_ensBestCalls = ensCalls;
g_ensDeployApproved = ensDeploy;
fix(persist): adopt the pinned threshold on load; trim the accuracy label THE REGRESSION, mine, from c6eb908. LoadModelStats() dropped the whole ensemble record unless the stored threshold EQUALLED the live one. That was right while the threshold was an operator input - a record built at 25% says nothing about a chart now running 15%. Once the threshold became derived and pinned the comparison inverted its own meaning: at load time g_ensembleVoteThreshold is still the Signal_ThresholdOpen SEED, so the stored derived value never matches and the record is ALWAYS dropped. Two things died with it, silently: * g_ensDeployApproved - a DEPLOYED ensemble came back as a training one on every restart, discarding the family-wise deploy it had earned. * the pinned threshold itself - PublishVoteThreshold() only fires on a positive g_ensDerivedThreshold, so a deployed chart would have traded the .chr seed instead of the rung its deploy was certified at. certified != traded, the defect 2c443ba fixed, reintroduced three commits later. Not yet observed live only because SP500 deployed at 10:20, after the last restart at 09:54, so no restart has crossed a deployed state. Now ADOPTED, not compared: threshold, counts and deploy flag restore together, the only coherent state - the counts were conditional on that threshold, which is why it is stored beside them. Same doctrine as the .cfg topology: adopt what the model was certified with, never re-derive it underneath a checkpoint. The most-complete-copy guard is unchanged. It now logs what it restored. THE PANEL LABEL. "Vote win rate: 34% (338 calls at or above the 15% threshold, this era 31%)" -> "Accuracy: 34%". The call count, threshold and this-era figure are diagnostics, all present in the era log line, and on a panel they buried the one number anyone reads. The threshold no longer needs naming either: it is derived and pinned rather than an operator's choice, so it is not a caveat on the percentage. The era/models/deployable suffix appended at era end goes with them. Compiled clean; NOT yet run. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 11:59:25 -04:00
g_ensembleVoteThreshold = ensThresh;
g_ensDerivedThreshold = ensThresh;
PrintFormat("%s: restored the ensemble record - %d%% threshold (pinned), %d calls, %d%% win"
" rate, deploy %s. The chart trades the rung its checkpoint was certified at.",
__FUNCTION__, (int)MathRound(ensThresh), (int)ensTotal,
(ensTotal > 0 ? (int)MathRound(100.0 * ensCorrect / ensTotal) : 0),
(ensDeploy ? "APPROVED" : "not yet approved"));
fix(panel,arrows): one deploy predicate, a deployed-only readout, and persist the vote arrows Four reported symptoms, three of them one root cause: the ensemble's certified record was session-scoped and written ONLY at pass-3 completion. A deployed ensemble runs no further eras, so every restart lost the aggregate win rate, the aggregate panel line and the overlay snapshots - and could never regenerate them, because regeneration only happens at an era end that will never come. THE SELF-CONTRADICTION. Member rows read "Live - learning from new bars" (from m_trainingComplete) while the line under them read "training, not tradable yet" (from `prospective`, which means "this number came from ProspectiveVote() rather than a real Direction() call" - what happens on any bar where every member abstains, and which says nothing whatever about training state). Both now resolve through one predicate: WarriorChartModelsDeployed(), fed by members publishing their own state on the same slot and cadence as their vote. Adds a third verdict word, "armed (bar still open)", for a deployed model on a prospective recompute - the case that used to claim it was training. DEPLOYED PANEL. Once every published model is converged the per-member rows are dropped: what ships is the aggregate vote win rate, the live vote, and the verdict. While training the rows stay - they are the only way a collapsed or lagging member is visible, since a collapsed member abstains and so is invisible in the aggregate by construction. ACCURACY NOW RESPECTS THE ENTRY THRESHOLD. The panel's "precision 65%" came from m_cumOosCorrect/m_cumOosTotal, which counts every bar a model called Buy or Sell - threshold-blind, and per-model rather than per-vote. The correct number already existed (votePrecPct: bars where |vote| >= threshold and the direction policy allows) and is now what the panel shows, with the threshold named in the text because the number is meaningless without it. VOTE ARROWS PERSIST. With DrawUnfilteredSignals off - the default - the chart shows SIG_VOTE_PREFIX arrows, and nothing saved them: CChartUI's .arrows sidecar is member-scoped and never saw that layer. New CVoteArrowStore mirrors them to a chart-keyed sidecar and restores them progressively at init, on the same budgeted non-blocking path. The header stores the open/close thresholds; a mismatch on load DISCARDS the arrows rather than redrawing a picture of a strategy no longer configured - stale arrows are worse than none, because none is visibly empty and stale is confidently wrong. Also: .stats bumped to WST7 carrying the ensemble record (guarded on threshold match, most-complete-copy-wins), and the loader's version tests collapsed from an or-chain to ">=" - the magics are ASCII 'WST1'.. 'WST7' so they are already ordered, and a missed arm in that chain reads the NEXT field's bytes into this one, which fails as plausible numbers rather than as an error. Compile-verified in _claude_stage: 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:00:15 -04:00
}
}
fix(vote): persist the member's skill verdict - a converged model was ruled no-skill on every restart SP500 resumed converged at era 136 with its tier ladder correctly restored and still swept 4999 bars reporting "0 had a snapshot, drew 0 arrow(s)" while the other five charts drew 221-312. HasDemonstratedEdge() - added with the no-skill exclusion - compares m_eraStatPrecPct against m_eraStatChancePct. Both are written once per era by EnsembleStashEraStats. A converged model runs no eras, so after a restart both sat at their -1 ctor defaults, every member was ruled no-skill, ReconstructionWeight() returned 0 for all four, and the overlay divisor was zero on every bar. Exactly the failure the WST7 ladder persistence fixed one level down: the ladder says how much a member votes, this says whether it may. RankTiersFromOos already computes the pair (pooled holdout precision and the zero-skill reference rate) and now records it as the CERTIFIED edge. That path is reached by the era end AND by the deployed replay, which is the only measurement a converged model will ever make. Persisted as WST8; HasDemonstratedEdge() prefers the era pair and falls back to it. The census line also had to be fixed: it reported "NOT ONE of those bars had a single member snapshot ... no enrolled member has published m_overlaySigSnap" for a condition that was purely a skill verdict. The snapshots were there. It now counts the two causes separately and names the one that fired. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 16:53:16 -04:00
//--- v8 appended THIS MEMBER's certified precision/chance pair - what HasDemonstratedEdge() reads,
//--- and therefore whether this member is allowed into the vote at all. Older files predate it: the
//--- pair keeps its -1 defaults and the member stays no-skill until its next era measures one,
//--- which for a CONVERGED model is never - so a WST7 file must be re-saved once by this build.
if(magic >= 0x57535438)
{
double certPrec = FileReadDouble(handle);
double certChance = FileReadDouble(handle);
if(certPrec >= 0.0 && certChance >= 0.0)
{
m_view.SetCertifiedEdge(certPrec, certChance);
PrintVerbose(m_view.Id() + ": restored the certified edge from .stats -> " +
DoubleToString(certPrec, 1) + "% precision against a " + DoubleToString(certChance, 1) +
"% chance rate (" + (certPrec > certChance ? "MAY VOTE" : "no skill - excluded from the vote") +
"). Without it a resumed converged model is ruled no-skill and the overlay divisor is zero.");
}
}
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
FileClose(handle);
return true;
}
//+------------------------------------------------------------------+
//| Deploy-time self-check (chart only, where a compute backend |
//| exists): run the just-saved deployed model through both the |
//| backend Net and a throwaway pure-MQL5 clone (CNet::SetCpuInference|
//| loaded from the same .nnw) on one real input window, and return |
//| true only if their outputs match within CPU_INFERENCE_MAX_DIFF. |
//| This is what lets an inference-only backtest run DLL-free; any |
//| error, size mismatch, or a not-yet-ported architecture (conv/LSTM |
//| CPU load fails) returns false -> the model stays on the DLL path. |
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
//| The Net-pointer/throwaway-clone core is consolidated as ONE view |
//| call (PersistRunCpuInferenceSelfCheck) rather than field-by-field -|
//| it is irreducible pointer/object work, not signal state. |
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
bool CModelPersistence::ValidateCpuInference(void)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
//--- Chart-only: needs a real backend to compare against, and only the shared production model (not a
//--- per-agent optimization cache) is ever seeded into a buyer's inference-only backtest.
if(MQLInfoInteger(MQL_TESTER) || MQLInfoInteger(MQL_OPTIMIZATION) || MQLInfoInteger(MQL_FORWARD))
return false;
double maxDiff = DBL_MAX;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
bool pass = m_view.RunCpuInferenceSelfCheck(maxDiff);
PrintVerbose(m_view.Id() + ": CPU-inference validation " + (pass ? "PASSED - backtests may run DLL-free" :
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
"FAILED - backtests keep using the DLL") + " (max |delta| = " +
(maxDiff == DBL_MAX ? "n/a" : DoubleToString(maxDiff, 8)) + ", tol " +
DoubleToString(CPU_INFERENCE_MAX_DIFF, 8) + ")");
return pass;
}
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
bool CModelPersistence::SaveTopologyConfiguration(string fileName, int initialNeuronsCount, int hiddenLayersCount, double neuronsReduction, int minNeuronsCount, int optimizationAlgo, int historyBars, int outputNeuronsCount, int neuronsCount, int studyPeriod, int minTrainYear, bool isInitialized, int stopTrainWR, int fractalPeriods, int convFilterCount, int lstmHiddenSize, bool common)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
string configFileName = fileName + ".cfg";
//--- Staged through a temp file + atomic rename (System\AtomicFile.mqh). It also stops an
//--- exclusive writer from blocking that reader's FILE_SHARE_READ|FILE_SHARE_WRITE open on
//--- another instance.
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
int cfgCommonFlag = (common ? FILE_COMMON : 0);
string cfgTmpName = "";
int handle = AtomicWriteBegin(configFileName, cfgCommonFlag, cfgTmpName);
if(handle == INVALID_HANDLE)
{
Print("Error: Unable to open file ", cfgTmpName, " : Error code: ", GetLastError());
ResetLastError();
return false;
}
//--- ON-DISK LAYOUT - DO NOT REORDER OR RETYPE. Appending a NEW field at the end is the only
//--- backward-safe change. LoadAndCompareTopologyConfiguration() reads these back positionally,
//--- and every existing .cfg on every deployed install has this exact sequence; changing it
//--- silently invalidates them all (-> "configuration mismatch" -> retrain from era 0).
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
bool ok = (FileWriteInteger(handle, initialNeuronsCount) >= sizeof(int));
if(ok && FileWriteInteger(handle, hiddenLayersCount) < sizeof(int)) ok = false;
if(ok && FileWriteDouble(handle, neuronsReduction) < sizeof(double)) ok = false;
if(ok && FileWriteInteger(handle, minNeuronsCount) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, optimizationAlgo) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, historyBars) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, outputNeuronsCount) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, neuronsCount) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, studyPeriod) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, minTrainYear) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, isInitialized) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, stopTrainWR) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, fractalPeriods) < sizeof(int)) ok = false;
//--- APPENDED 2026-07-30, which the note above names as the only backward-safe change. A .cfg
//--- written before this shipped simply ends here; the loader checks the file length before
//--- reading them.
feat(nn): derive dense depth, train on all history, pin the shape in .cfg Completes the derived-topology work. Three inputs removed. AIType loses its depth suffix - AI_MLP/AI_CONV/AI_LSTM/AI_HYBRID, five entries instead of eight. Depth is now derived from the two endpoints the taper already has to connect (derived first-layer width, output-tied final width) at a 2x per-layer compression target, clamped [2..5]. Asking a user to pick a layer count while the code derives the widths those layers taper between was asking for half a decision: at 64 units tapering to 12, four layers compress by 1.4x per step and five by 1.3x, so the extra depth bought no abstraction. On the shipping H1/10y default the derivation lands on 3 layers - the depth that actually won Run 2. StudyPeriods removed. There is no case for training on less data than the broker provides at a ~6% directional base rate; the honest generalization read comes from the OOS holdout, not from withholding history. Training now starts at the earliest available bar, floored by MinTrainYear, which answers a different question (excluding dubious pre-history) and stays. That required closing the hazard the old code documented: the capacity budget now MEASURES the symbol's real bar count, and a topology derived from a measurement would widen as history downloads. Both ends are now pinned. Every derived value left the weights-filename fingerprint - keying a filename on a measured quantity means the EA looks for a file that does not exist, starts from era 0 and orphans a trained model, silently, because a missing cache is the normal first-run state. The shape lives in the .cfg instead, where LoadAndCompare now ADOPTS the four derived fields rather than diffing them; a mismatch there would discard a fully-trained model over nothing the user did. Two fields appended to the .cfg for the conv/LSTM stages, length-guarded on read because FileReadInteger past EOF returns 0 with no error. ForceHiddenLayers, a compile-time constant like DebuggingMode, pins depth for diagnostic comparisons. It joins the fingerprint only when non-zero, so forced depths get their own files - sequential comparisons only, not simultaneous from one .ex5. Derived shape, H1/10y defaults (21 features x 20 bars): first layer 64, 3 dense, 8 conv filters, 16 LSTM units. The LSTM block halves from ~58k to ~28k weights. Both builds compile 0 errors, 0 warnings. Re-keys existing models. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 10:05:40 -04:00
if(ok && FileWriteInteger(handle, convFilterCount) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, lstmHiddenSize) < sizeof(int)) ok = false;
feat(target): delete the barrier/geometry stack - the label is the verdict Step 3 of the swing-pivot plan, whole-hog. The swing label is now the ONE target and the era verdict is precision + recall per class against the label's own base rate - no win rate, no break-even, no expectancy, no geometry anywhere in training. DELETED - Expert/Excursion/ (4), Expert/BarrierHorizon/ (4), GeometrySweep, FirstPassageLadder, Labeling/TripleBarrier.mqh (CLabelOverlap survives in Labeling/LabelOverlap.mqh), 3 test EAs. - TripleBarrierLabel + walk, fractal label, geometry derivation/scan/ adoption, exit-policy replay, excursion MI targets, the drift verdict (DIRECTION_INTELLIGENT), the recall floor, balanced-accuracy telemetry, the barrier defines, the .cfg geometry adopt (slots kept as zeros for the positional layout), the derived-geometry live-order override. - TRAINING_TARGET input/enum: direction models are always swing; META2 re-keys the meta head onto label agreement (descriptor loses its two geometry slots). REWORKED - Labels.mqh (1795 -> ~370 lines): AdvanceSwingLabelState with FINALITY-GATED CACHING - an unresolved bar (pivot pair uncommitted) is never cached, so it can never freeze as a false Neutral; training, calibration, OOS scoring and online learning all skip unresolved bars. - SDeployVerdict: significance-only; SOosTally chance = larger directional class share; pooled gate poolability = timeframe (record v2). - Purge/embargo/declustering gaps: the measured mean label resolution lag (LabelResolutionBars), not a barrier horizon. - Pool purge key + backfill DB rows: marked at the bar the label resolved on (m_labelResolveAge), not a fabricated barrier touch. - Online learning frontier: finality, not a horizon delay. - m_bestBalancedOos -> m_bestSelectionScore, m_erasSinceBestBalanced -> m_erasSinceBest, ensemble vote outcome arrays -> label arrays. STEP 4 folded in: Entry_Multiplier / SL_Mode / TP_Mode / tradingdirection are inputs again - trade management is the tester GA's search space. Fingerprints: every direction model re-keys (TGT:SWG1 now unconditional, CUT token gone); META1 -> META2. Full retrain, as planned. Compile-verified in _claude_stage: Warrior_EA + both surviving test EAs, 0 errors, 0 warnings each. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 20:42:31 -04:00
//--- LEGACY GEOMETRY SLOTS (were SL/TP modes + the derived barrier pair, deleted with the
//--- barrier stack 2026-08-24). Written as zeros to keep the positional layout: the dirConf
//--- double and the two pin strings below sit AFTER these four fields in every .cfg on disk.
if(ok && FileWriteInteger(handle, 0) < sizeof(int)) ok = false;
if(ok && FileWriteInteger(handle, 0) < sizeof(int)) ok = false;
if(ok && FileWriteDouble(handle, 0.0) < sizeof(double)) ok = false;
if(ok && FileWriteDouble(handle, 0.0) < sizeof(double)) ok = false;
//--- APPENDED 2026-08-09, same append-and-length-guard convention as everything above it.
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && FileWriteDouble(handle, m_view.BestDirConfThreshold()) < sizeof(double)) ok = false;
//--- APPENDED 2026-08-11, same append-and-length-guard convention. Written as char-count then
//--- characters; empty (no set pinned yet) writes 0 and no string, which the reader adopts as
//--- "nothing pinned" - the state a fresh model is in.
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
int xaPinLen = StringLen(m_view.CrossAssetPairsPinned());
if(ok && FileWriteInteger(handle, xaPinLen) < sizeof(int)) ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && xaPinLen > 0 && FileWriteString(handle, m_view.CrossAssetPairsPinned()) <= 0) ok = false;
//--- APPENDED 2026-08-16, same append-and-length-guard convention. Width changes already re-key
//--- the weight fingerprint through neuronsCount; this records which NAMES that width was made
//--- of.
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
int altPinLen = StringLen(m_view.AltDataNamesPinned());
if(ok && FileWriteInteger(handle, altPinLen) < sizeof(int)) ok = false;
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(ok && altPinLen > 0 && FileWriteString(handle, m_view.AltDataNamesPinned()) <= 0) ok = false;
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
if(!ok)
{
Print("Error writing ", configFileName, " : Error code: ", GetLastError());
ResetLastError();
}
return AtomicWriteEnd(handle, configFileName, cfgTmpName, cfgCommonFlag, ok, __FUNCTION__);
}
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
bool CModelPersistence::LoadAndCompareTopologyConfiguration(string fileName, int &initialNeuronsCount, int &hiddenLayersCount, double neuronsReduction, int minNeuronsCount, int optimizationAlgo, int &historyBars, int outputNeuronsCount, int neuronsCount, int minTrainYear, bool isInitialized, int stopTrainWR, int fractalPeriods, int &convFilterCount, int &lstmHiddenSize, bool common)
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
string configFileName = fileName + ".cfg";
if(!FileIsExist(configFileName, common ? FILE_COMMON : 0))
{
//--- Not an error: no cached config for this parameter set yet - normal on the first run of a config
//--- (and every first tester/optimizer pass on a fresh agent). The caller treats a false return as
//--- "start fresh", so log it as informational rather than "Error" (which read as a real failure).
PrintVerbose(__FUNCTION__ + ": no cached topology config at " + configFileName + " yet - treating as a fresh start for this configuration");
return false;
}
//--- share flags: read-only, see CopySharedFile().
int handle = FileOpen(configFileName, FILE_READ | FILE_BIN | FILE_SHARE_READ | FILE_SHARE_WRITE | (common ? FILE_COMMON : 0));
if(handle == INVALID_HANDLE)
{
Print("Error: Unable to open file ", configFileName);
return false;
}
int savedInitialNeurons = FileReadInteger(handle);
int savedHiddenLayers = FileReadInteger(handle);
double savedReductionFactor = FileReadDouble(handle);
int savedMinNeurons = FileReadInteger(handle);
int savedOptimizationAlgo = FileReadInteger(handle);
int savedHistoryBars = FileReadInteger(handle);
int savedOutputNeuronsCount = FileReadInteger(handle);
int savedNeuronsCount = FileReadInteger(handle);
int savedStudyPeriod = FileReadInteger(handle);
int savedMinTrainYear = FileReadInteger(handle);
bool savedIsInitialized = FileReadInteger(handle); // read for layout only - NOT compared (see below)
int savedStopTrainWR = FileReadInteger(handle); // retired MinWR slot - layout only, NOT compared (see below)
int savedFractalPeriods = FileReadInteger(handle);
feat(nn): derive dense depth, train on all history, pin the shape in .cfg Completes the derived-topology work. Three inputs removed. AIType loses its depth suffix - AI_MLP/AI_CONV/AI_LSTM/AI_HYBRID, five entries instead of eight. Depth is now derived from the two endpoints the taper already has to connect (derived first-layer width, output-tied final width) at a 2x per-layer compression target, clamped [2..5]. Asking a user to pick a layer count while the code derives the widths those layers taper between was asking for half a decision: at 64 units tapering to 12, four layers compress by 1.4x per step and five by 1.3x, so the extra depth bought no abstraction. On the shipping H1/10y default the derivation lands on 3 layers - the depth that actually won Run 2. StudyPeriods removed. There is no case for training on less data than the broker provides at a ~6% directional base rate; the honest generalization read comes from the OOS holdout, not from withholding history. Training now starts at the earliest available bar, floored by MinTrainYear, which answers a different question (excluding dubious pre-history) and stays. That required closing the hazard the old code documented: the capacity budget now MEASURES the symbol's real bar count, and a topology derived from a measurement would widen as history downloads. Both ends are now pinned. Every derived value left the weights-filename fingerprint - keying a filename on a measured quantity means the EA looks for a file that does not exist, starts from era 0 and orphans a trained model, silently, because a missing cache is the normal first-run state. The shape lives in the .cfg instead, where LoadAndCompare now ADOPTS the four derived fields rather than diffing them; a mismatch there would discard a fully-trained model over nothing the user did. Two fields appended to the .cfg for the conv/LSTM stages, length-guarded on read because FileReadInteger past EOF returns 0 with no error. ForceHiddenLayers, a compile-time constant like DebuggingMode, pins depth for diagnostic comparisons. It joins the fingerprint only when non-zero, so forced depths get their own files - sequential comparisons only, not simultaneous from one .ex5. Derived shape, H1/10y defaults (21 features x 20 bars): first layer 64, 3 dense, 8 conv filters, 16 LSTM units. The LSTM block halves from ~58k to ~28k weights. Both builds compile 0 errors, 0 warnings. Re-keys existing models. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 10:05:40 -04:00
//--- Appended 2026-07-30 - guard on the actual file length rather than reading optimistically, because
//--- FileReadInteger past the end returns 0 with no error, and adopting a conv filter count of 0 would
//--- build a degenerate topology out of a file that was merely written by an older build.
bool haveDerivedStages = (FileSize(handle) >= (ulong)FileTell(handle) + 2 * sizeof(int));
int savedConvFilters = haveDerivedStages ? FileReadInteger(handle) : 0;
int savedLstmHidden = haveDerivedStages ? FileReadInteger(handle) : 0;
feat(target): delete the barrier/geometry stack - the label is the verdict Step 3 of the swing-pivot plan, whole-hog. The swing label is now the ONE target and the era verdict is precision + recall per class against the label's own base rate - no win rate, no break-even, no expectancy, no geometry anywhere in training. DELETED - Expert/Excursion/ (4), Expert/BarrierHorizon/ (4), GeometrySweep, FirstPassageLadder, Labeling/TripleBarrier.mqh (CLabelOverlap survives in Labeling/LabelOverlap.mqh), 3 test EAs. - TripleBarrierLabel + walk, fractal label, geometry derivation/scan/ adoption, exit-policy replay, excursion MI targets, the drift verdict (DIRECTION_INTELLIGENT), the recall floor, balanced-accuracy telemetry, the barrier defines, the .cfg geometry adopt (slots kept as zeros for the positional layout), the derived-geometry live-order override. - TRAINING_TARGET input/enum: direction models are always swing; META2 re-keys the meta head onto label agreement (descriptor loses its two geometry slots). REWORKED - Labels.mqh (1795 -> ~370 lines): AdvanceSwingLabelState with FINALITY-GATED CACHING - an unresolved bar (pivot pair uncommitted) is never cached, so it can never freeze as a false Neutral; training, calibration, OOS scoring and online learning all skip unresolved bars. - SDeployVerdict: significance-only; SOosTally chance = larger directional class share; pooled gate poolability = timeframe (record v2). - Purge/embargo/declustering gaps: the measured mean label resolution lag (LabelResolutionBars), not a barrier horizon. - Pool purge key + backfill DB rows: marked at the bar the label resolved on (m_labelResolveAge), not a fabricated barrier touch. - Online learning frontier: finality, not a horizon delay. - m_bestBalancedOos -> m_bestSelectionScore, m_erasSinceBestBalanced -> m_erasSinceBest, ensemble vote outcome arrays -> label arrays. STEP 4 folded in: Entry_Multiplier / SL_Mode / TP_Mode / tradingdirection are inputs again - trade management is the tester GA's search space. Fingerprints: every direction model re-keys (TGT:SWG1 now unconditional, CUT token gone); META1 -> META2. Full retrain, as planned. Compile-verified in _claude_stage: Warrior_EA + both surviving test EAs, 0 errors, 0 warnings each. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 20:42:31 -04:00
//--- LEGACY GEOMETRY SLOTS - read for the positional layout only, never adopted: the barrier
//--- stack these described was deleted 2026-08-24 and the write side now emits zeros.
feat: entry/SL/TP stop being inputs - the barrier geometry is measured Three enums left the Inputs tab. They were three things a user had to pick and, in the tester, three more axes for a genetic optimization to overfit. Entry_Multiplier is pinned to MARKET. Its pending modes place the entry at a LEVEL while the rest of the pipeline measures from the bar open - the exact mismatch that manufactured the +0.097 R "retail fade" result later retracted as a fill artifact. This codebase's fill model cannot honestly simulate a pending entry, so it is no longer offered. SL_Mode/TP_Mode become a STARTING pair. ReportBarrierGeometryScan now ADOPTS its winner instead of printing "set SL_Mode/TP_Mode to X and retrain": - only when it clears the family-wise gate from 04ee2e1 (beat the null of the MAXIMUM, not merely the incumbent). This is why that gate had to land first: without it, removing the inputs would hand a noise-picked geometry direct control over the training target with no human in the loop - strictly worse than the input it replaced. On SP500 H1 today it does NOT clear (p=0.1463), so 2:6 is what you get - now chosen by measurement rather than assumed. - only at m_eraCount == 0. Relabelling a partly-trained net moves the target out from under weights already fitted to the old one. THE GEOMETRY LEFT THE WEIGHTS-FILENAME HASH, because it is now measured. Same rule that moved the horizon and the derived topology values out: a filename keyed on a measured quantity changes the moment the measurement does - a few more bars shift which pairing wins - and the EA then looks for a file that does not exist, starts from era 0 and orphans a trained model silently. It is PINNED IN THE .cfg instead: appended at the end (the only backward-safe change), length-guarded like the 2026-07-30 derived pair, and ADOPTED on load rather than compared, so a trained model keeps the barriers it actually learned and never re-measures. Two traps closed while wiring it, neither of which announces itself: - m_barrierHorizonResolved latches the horizon ONCE PER PROCESS. Adopting 2:8 (wants ~192 bars) after it settled for 2:6 (128) would label the new target against the old ceiling - the truncation fixed in 168422f, where every model learned "target within 128 bars" while the EA holds to SL/TP. It lands in Neutral, not in the timeout counter watching for it. Unlatched on adoption, along with the label cache the old barriers filled. - the .cfg adopt runs at init, before the horizon latches and before any label is computed, so a resumed model has its pinned pair in place first. Verified, not assumed. FORCES A FULL RETRAIN: the fingerprint change orphans every existing .nnw. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 09:39:30 -04:00
bool haveBarrierGeometry = (FileSize(handle) >= (ulong)FileTell(handle) + 2 * sizeof(int));
feat(target): delete the barrier/geometry stack - the label is the verdict Step 3 of the swing-pivot plan, whole-hog. The swing label is now the ONE target and the era verdict is precision + recall per class against the label's own base rate - no win rate, no break-even, no expectancy, no geometry anywhere in training. DELETED - Expert/Excursion/ (4), Expert/BarrierHorizon/ (4), GeometrySweep, FirstPassageLadder, Labeling/TripleBarrier.mqh (CLabelOverlap survives in Labeling/LabelOverlap.mqh), 3 test EAs. - TripleBarrierLabel + walk, fractal label, geometry derivation/scan/ adoption, exit-policy replay, excursion MI targets, the drift verdict (DIRECTION_INTELLIGENT), the recall floor, balanced-accuracy telemetry, the barrier defines, the .cfg geometry adopt (slots kept as zeros for the positional layout), the derived-geometry live-order override. - TRAINING_TARGET input/enum: direction models are always swing; META2 re-keys the meta head onto label agreement (descriptor loses its two geometry slots). REWORKED - Labels.mqh (1795 -> ~370 lines): AdvanceSwingLabelState with FINALITY-GATED CACHING - an unresolved bar (pivot pair uncommitted) is never cached, so it can never freeze as a false Neutral; training, calibration, OOS scoring and online learning all skip unresolved bars. - SDeployVerdict: significance-only; SOosTally chance = larger directional class share; pooled gate poolability = timeframe (record v2). - Purge/embargo/declustering gaps: the measured mean label resolution lag (LabelResolutionBars), not a barrier horizon. - Pool purge key + backfill DB rows: marked at the bar the label resolved on (m_labelResolveAge), not a fabricated barrier touch. - Online learning frontier: finality, not a horizon delay. - m_bestBalancedOos -> m_bestSelectionScore, m_erasSinceBestBalanced -> m_erasSinceBest, ensemble vote outcome arrays -> label arrays. STEP 4 folded in: Entry_Multiplier / SL_Mode / TP_Mode / tradingdirection are inputs again - trade management is the tester GA's search space. Fingerprints: every direction model re-keys (TGT:SWG1 now unconditional, CUT token gone); META1 -> META2. Full retrain, as planned. Compile-verified in _claude_stage: Warrior_EA + both surviving test EAs, 0 errors, 0 warnings each. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 20:42:31 -04:00
if(haveBarrierGeometry)
{
FileReadInteger(handle);
FileReadInteger(handle);
}
feat: derive the ATR multiples from measured excursions - no hardcoded geometry The barrier was still two constants. SL_Mode/TP_Mode left the Inputs tab in 3482b6c, but the fallback was a hardcoded 2:6 and the geometry scan only ever chose from a hardcoded grid {2,3} x {2,3,4,6,8,10}. Picking the least-bad of eleven guesses is not deriving anything. WHY THE SCAN WAS THE WRONG INSTRUMENT, now measurable rather than argued. It ranks pairings by how predictable their OUTCOME is - a question about direction. The excursion test (2c78f3b) ran on SP500 H1 and direction is the one thing absent: ASYMMETRY p=0.0846, against RANGE/UP/DOWN all at p=0.0050, with RANGE scoring 0.01345 vs a 0.00343 null - 4x, where the barrier label sits at 1.01x. Hence the scan failing its own gate on every run, and its "winner" wandering 2:8 -> 3:8 -> 2:8 -> 2:4 across four runs of the same data. Excursion SIZE is strongly measurable, so derive the geometry from that instead. stop = q25 of measured ADVERSE travel (ordinary noise does not reach it) target = q50 of measured FAVOURABLE travel (reached ~half the time, by construction, inside the horizon) Continuous, in ATR units, superseding the enum multiples. Reachability ("target on X% of bars, stop on Y%") and the implied break-even are printed so the choice is auditable rather than trusted. FIXED-POINT ITERATION, not one-shot. ComputeBarrierHorizonBars scales the horizon with the target (first-passage time grows with the band) and the excursions are measured OVER the horizon, so target -> horizon -> excursions -> target is a real loop - deriving once sizes the target from travel measured under the PREVIOUS horizon. Re-measures until the multiples move <5%, capped at 3 passes, and says so if it does not settle. Does NOT create expectancy, and the log says as much: chance precision equals break-even at every geometry (m/(m+k) on both sides). It buys a target the market reaches and a stop that survives noise. Where Min_Risk_Reward_Ratio forces a target the market rarely reaches, it WARNS rather than overriding - the ratio is the user's risk policy, so the honest move is to state its cost. That is the collision that once rejected 100% of setups. Pinned in the .cfg as doubles appended AFTER this morning's two ints, so .cfg files written earlier today still load (their length guard finds no doubles) and a model that carries them was trained on them and never re-derives. Also fixes a message from e5ceed6 that claimed "this model resumed from disk" unconditionally - it printed above a "seeding era 0" line on a brand-new model, because the branch fires whenever the cache is not built, which is equally true before a fresh model's first prebuild. A diagnostic that misreports its own trigger is worse than one that says nothing: it gets quoted back as evidence. FORCES A FULL RETRAIN (labels change). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 12:06:25 -04:00
bool haveDerivedGeometry = (FileSize(handle) >= (ulong)FileTell(handle) + 2 * sizeof(double));
feat(target): delete the barrier/geometry stack - the label is the verdict Step 3 of the swing-pivot plan, whole-hog. The swing label is now the ONE target and the era verdict is precision + recall per class against the label's own base rate - no win rate, no break-even, no expectancy, no geometry anywhere in training. DELETED - Expert/Excursion/ (4), Expert/BarrierHorizon/ (4), GeometrySweep, FirstPassageLadder, Labeling/TripleBarrier.mqh (CLabelOverlap survives in Labeling/LabelOverlap.mqh), 3 test EAs. - TripleBarrierLabel + walk, fractal label, geometry derivation/scan/ adoption, exit-policy replay, excursion MI targets, the drift verdict (DIRECTION_INTELLIGENT), the recall floor, balanced-accuracy telemetry, the barrier defines, the .cfg geometry adopt (slots kept as zeros for the positional layout), the derived-geometry live-order override. - TRAINING_TARGET input/enum: direction models are always swing; META2 re-keys the meta head onto label agreement (descriptor loses its two geometry slots). REWORKED - Labels.mqh (1795 -> ~370 lines): AdvanceSwingLabelState with FINALITY-GATED CACHING - an unresolved bar (pivot pair uncommitted) is never cached, so it can never freeze as a false Neutral; training, calibration, OOS scoring and online learning all skip unresolved bars. - SDeployVerdict: significance-only; SOosTally chance = larger directional class share; pooled gate poolability = timeframe (record v2). - Purge/embargo/declustering gaps: the measured mean label resolution lag (LabelResolutionBars), not a barrier horizon. - Pool purge key + backfill DB rows: marked at the bar the label resolved on (m_labelResolveAge), not a fabricated barrier touch. - Online learning frontier: finality, not a horizon delay. - m_bestBalancedOos -> m_bestSelectionScore, m_erasSinceBestBalanced -> m_erasSinceBest, ensemble vote outcome arrays -> label arrays. STEP 4 folded in: Entry_Multiplier / SL_Mode / TP_Mode / tradingdirection are inputs again - trade management is the tester GA's search space. Fingerprints: every direction model re-keys (TGT:SWG1 now unconditional, CUT token gone); META1 -> META2. Full retrain, as planned. Compile-verified in _claude_stage: Warrior_EA + both surviving test EAs, 0 errors, 0 warnings each. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 20:42:31 -04:00
if(haveDerivedGeometry)
{
FileReadDouble(handle);
FileReadDouble(handle);
}
feat: fitted directional confidence threshold - selectivity gets a mechanism The training loss and the selection metric wanted different things and only the second one knew it. Logit-adjusted cross-entropy has no term for "how often should I trade", so the head calls a direction on 87-91% of bars. The selection metric is precision x coverage credit, saturating at the coverage floor - above the floor extra calls earn NOTHING and only precision counts. So selection wanted few good calls, the loss produced many mediocre ones, and all selection could do was pick the least-bad era out of what it was handed. Nothing pushed the model toward selectivity. This gives the decision RULE the policy instead of distorting the loss (which is estimating class probabilities correctly, and a probability estimate should not be bent to encode a trading policy - Elkan 2001: estimate, then choose the operating point separately). AdjustedSignalFromSoftmax now abstains unless the winning direction's softmax margin over its best rival clears a fitted threshold. Margin, not the winning probability: the latter moves with overall calibration rather than with how close the decision actually was. Fitted on IS, applied to OOS and live. Pass 2 already forward-passes every IS sample, so the margin histogram is harvested there for free (primary occurrences only, so the oversampled replay queue cannot skew the operating point); the fit runs at the end of pass 2, BEFORE pass 3, so the deploy gate grades the thresholded model on bars the threshold never saw. Fitting on pass 3's own predictions would be choosing the operating point on the data being graded - the best-of-N error corrected in five other places here. Objective: maximise IS directional precision subject to still clearing the SAME coverage floor the deploy gate uses (base rate x 0.25, re-derived locally so the two cannot drift apart). Swept top-down in one pass; ties go to the LOWER threshold, since equal precision for less coverage is strictly worse. Under DIR_CONF_MIN_FIT_CALLS (200) it runs unthresholded rather than on a guess. The threshold is part of the MODEL, not the run: captured with Net.CaptureWeights(), restored with the weights at both restore sites, and appended to the .cfg under the same length-guard convention so a deployed model reloads at the operating point its gate actually cleared. A pre-2026-08-09 .cfg reads 0.0, which is exactly the behaviour it was trained under. Per-era line now prints "@margin>=X.XX" next to coverage, so a coverage drop can be attributed to the operating point rather than guessed at. Both build variants compile 0 errors / 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 15:04:37 -04:00
//--- Appended 2026-08-09. A .cfg from before then simply ends here and the guard yields 0.0, which is
//--- exactly the right default: unthresholded, i.e. the behaviour that model was trained under.
bool haveDirConf = (FileSize(handle) >= (ulong)FileTell(handle) + sizeof(double));
double savedDirConf = haveDirConf ? FileReadDouble(handle) : 0.0;
//--- Appended 2026-08-11: the cross-asset pair set this model was trained against. Length-guarded
//--- like everything above; a sanity cap on the count rejects a garbage length from a truncated or
//--- misaligned file rather than asking FileReadString for megabytes.
bool haveXaPin = (FileSize(handle) >= (ulong)FileTell(handle) + sizeof(int));
int xaPinLen = haveXaPin ? FileReadInteger(handle) : 0;
string savedXaPairs = "";
if(haveXaPin && xaPinLen > 0 && xaPinLen <= 16 * CROSSASSET_MAX_PAIRS)
savedXaPairs = FileReadString(handle, xaPinLen);
//--- Appended 2026-08-16: the alt-data feature name list.
bool haveAltPin = (FileSize(handle) >= (ulong)FileTell(handle) + sizeof(int));
int altPinLen = haveAltPin ? FileReadInteger(handle) : 0;
string savedAltNames = "";
if(haveAltPin && altPinLen > 0 && altPinLen <= ALTDATA_MAX_PIN_CHARS)
savedAltNames = FileReadString(handle, altPinLen);
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
FileClose(handle);
feat(target): delete the barrier/geometry stack - the label is the verdict Step 3 of the swing-pivot plan, whole-hog. The swing label is now the ONE target and the era verdict is precision + recall per class against the label's own base rate - no win rate, no break-even, no expectancy, no geometry anywhere in training. DELETED - Expert/Excursion/ (4), Expert/BarrierHorizon/ (4), GeometrySweep, FirstPassageLadder, Labeling/TripleBarrier.mqh (CLabelOverlap survives in Labeling/LabelOverlap.mqh), 3 test EAs. - TripleBarrierLabel + walk, fractal label, geometry derivation/scan/ adoption, exit-policy replay, excursion MI targets, the drift verdict (DIRECTION_INTELLIGENT), the recall floor, balanced-accuracy telemetry, the barrier defines, the .cfg geometry adopt (slots kept as zeros for the positional layout), the derived-geometry live-order override. - TRAINING_TARGET input/enum: direction models are always swing; META2 re-keys the meta head onto label agreement (descriptor loses its two geometry slots). REWORKED - Labels.mqh (1795 -> ~370 lines): AdvanceSwingLabelState with FINALITY-GATED CACHING - an unresolved bar (pivot pair uncommitted) is never cached, so it can never freeze as a false Neutral; training, calibration, OOS scoring and online learning all skip unresolved bars. - SDeployVerdict: significance-only; SOosTally chance = larger directional class share; pooled gate poolability = timeframe (record v2). - Purge/embargo/declustering gaps: the measured mean label resolution lag (LabelResolutionBars), not a barrier horizon. - Pool purge key + backfill DB rows: marked at the bar the label resolved on (m_labelResolveAge), not a fabricated barrier touch. - Online learning frontier: finality, not a horizon delay. - m_bestBalancedOos -> m_bestSelectionScore, m_erasSinceBestBalanced -> m_erasSinceBest, ensemble vote outcome arrays -> label arrays. STEP 4 folded in: Entry_Multiplier / SL_Mode / TP_Mode / tradingdirection are inputs again - trade management is the tester GA's search space. Fingerprints: every direction model re-keys (TGT:SWG1 now unconditional, CUT token gone); META1 -> META2. Full retrain, as planned. Compile-verified in _claude_stage: Warrior_EA + both surviving test EAs, 0 errors, 0 warnings each. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 20:42:31 -04:00
//--- Operating point, adopted on the same grounds. Unlike the topology it IS re-fitted every era while
feat: fitted directional confidence threshold - selectivity gets a mechanism The training loss and the selection metric wanted different things and only the second one knew it. Logit-adjusted cross-entropy has no term for "how often should I trade", so the head calls a direction on 87-91% of bars. The selection metric is precision x coverage credit, saturating at the coverage floor - above the floor extra calls earn NOTHING and only precision counts. So selection wanted few good calls, the loss produced many mediocre ones, and all selection could do was pick the least-bad era out of what it was handed. Nothing pushed the model toward selectivity. This gives the decision RULE the policy instead of distorting the loss (which is estimating class probabilities correctly, and a probability estimate should not be bent to encode a trading policy - Elkan 2001: estimate, then choose the operating point separately). AdjustedSignalFromSoftmax now abstains unless the winning direction's softmax margin over its best rival clears a fitted threshold. Margin, not the winning probability: the latter moves with overall calibration rather than with how close the decision actually was. Fitted on IS, applied to OOS and live. Pass 2 already forward-passes every IS sample, so the margin histogram is harvested there for free (primary occurrences only, so the oversampled replay queue cannot skew the operating point); the fit runs at the end of pass 2, BEFORE pass 3, so the deploy gate grades the thresholded model on bars the threshold never saw. Fitting on pass 3's own predictions would be choosing the operating point on the data being graded - the best-of-N error corrected in five other places here. Objective: maximise IS directional precision subject to still clearing the SAME coverage floor the deploy gate uses (base rate x 0.25, re-derived locally so the two cannot drift apart). Swept top-down in one pass; ties go to the LOWER threshold, since equal precision for less coverage is strictly worse. Under DIR_CONF_MIN_FIT_CALLS (200) it runs unthresholded rather than on a guess. The threshold is part of the MODEL, not the run: captured with Net.CaptureWeights(), restored with the weights at both restore sites, and appended to the .cfg under the same length-guard convention so a deployed model reloads at the operating point its gate actually cleared. A pre-2026-08-09 .cfg reads 0.0, which is exactly the behaviour it was trained under. Per-era line now prints "@margin>=X.XX" next to coverage, so a coverage drop can be attributed to the operating point rather than guessed at. Both build variants compile 0 errors / 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 15:04:37 -04:00
//--- training continues (the margin distribution moves with the weights), so this restores the value a
//--- DEPLOYED model should trade at and the value a resuming run starts from until its next pass 2.
if(haveDirConf && savedDirConf > 0.0)
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
m_view.SetDirConfThreshold(savedDirConf);
m_view.SetBestDirConfThreshold(savedDirConf);
feat: fitted directional confidence threshold - selectivity gets a mechanism The training loss and the selection metric wanted different things and only the second one knew it. Logit-adjusted cross-entropy has no term for "how often should I trade", so the head calls a direction on 87-91% of bars. The selection metric is precision x coverage credit, saturating at the coverage floor - above the floor extra calls earn NOTHING and only precision counts. So selection wanted few good calls, the loss produced many mediocre ones, and all selection could do was pick the least-bad era out of what it was handed. Nothing pushed the model toward selectivity. This gives the decision RULE the policy instead of distorting the loss (which is estimating class probabilities correctly, and a probability estimate should not be bent to encode a trading policy - Elkan 2001: estimate, then choose the operating point separately). AdjustedSignalFromSoftmax now abstains unless the winning direction's softmax margin over its best rival clears a fitted threshold. Margin, not the winning probability: the latter moves with overall calibration rather than with how close the decision actually was. Fitted on IS, applied to OOS and live. Pass 2 already forward-passes every IS sample, so the margin histogram is harvested there for free (primary occurrences only, so the oversampled replay queue cannot skew the operating point); the fit runs at the end of pass 2, BEFORE pass 3, so the deploy gate grades the thresholded model on bars the threshold never saw. Fitting on pass 3's own predictions would be choosing the operating point on the data being graded - the best-of-N error corrected in five other places here. Objective: maximise IS directional precision subject to still clearing the SAME coverage floor the deploy gate uses (base rate x 0.25, re-derived locally so the two cannot drift apart). Swept top-down in one pass; ties go to the LOWER threshold, since equal precision for less coverage is strictly worse. Under DIR_CONF_MIN_FIT_CALLS (200) it runs unthresholded rather than on a guess. The threshold is part of the MODEL, not the run: captured with Net.CaptureWeights(), restored with the weights at both restore sites, and appended to the .cfg under the same length-guard convention so a deployed model reloads at the operating point its gate actually cleared. A pre-2026-08-09 .cfg reads 0.0, which is exactly the behaviour it was trained under. Per-era line now prints "@margin>=X.XX" next to coverage, so a coverage drop can be attributed to the operating point rather than guessed at. Both build variants compile 0 errors / 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 15:04:37 -04:00
PrintFormat("%s: adopting the directional confidence threshold this model was trained with - %.2f. "
"Below that winner-vs-rival softmax margin it abstains rather than trading.",
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
__FUNCTION__, savedDirConf);
feat: fitted directional confidence threshold - selectivity gets a mechanism The training loss and the selection metric wanted different things and only the second one knew it. Logit-adjusted cross-entropy has no term for "how often should I trade", so the head calls a direction on 87-91% of bars. The selection metric is precision x coverage credit, saturating at the coverage floor - above the floor extra calls earn NOTHING and only precision counts. So selection wanted few good calls, the loss produced many mediocre ones, and all selection could do was pick the least-bad era out of what it was handed. Nothing pushed the model toward selectivity. This gives the decision RULE the policy instead of distorting the loss (which is estimating class probabilities correctly, and a probability estimate should not be bent to encode a trading policy - Elkan 2001: estimate, then choose the operating point separately). AdjustedSignalFromSoftmax now abstains unless the winning direction's softmax margin over its best rival clears a fitted threshold. Margin, not the winning probability: the latter moves with overall calibration rather than with how close the decision actually was. Fitted on IS, applied to OOS and live. Pass 2 already forward-passes every IS sample, so the margin histogram is harvested there for free (primary occurrences only, so the oversampled replay queue cannot skew the operating point); the fit runs at the end of pass 2, BEFORE pass 3, so the deploy gate grades the thresholded model on bars the threshold never saw. Fitting on pass 3's own predictions would be choosing the operating point on the data being graded - the best-of-N error corrected in five other places here. Objective: maximise IS directional precision subject to still clearing the SAME coverage floor the deploy gate uses (base rate x 0.25, re-derived locally so the two cannot drift apart). Swept top-down in one pass; ties go to the LOWER threshold, since equal precision for less coverage is strictly worse. Under DIR_CONF_MIN_FIT_CALLS (200) it runs unthresholded rather than on a guess. The threshold is part of the MODEL, not the run: captured with Net.CaptureWeights(), restored with the weights at both restore sites, and appended to the .cfg under the same length-guard convention so a deployed model reloads at the operating point its gate actually cleared. A pre-2026-08-09 .cfg reads 0.0, which is exactly the behaviour it was trained under. Per-era line now prints "@margin>=X.XX" next to coverage, so a coverage drop can be attributed to the operating point rather than guessed at. Both build variants compile 0 errors / 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 15:04:37 -04:00
}
//--- Cross-asset pair set: adopt, don't compare, same grounds as the derived barrier - it records
//--- the panel this model's features were trained against. Already on disk, so the one-shot
//--- re-save in BuildCrossAssetPanel is moot for this model.
if(savedXaPairs != "")
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
m_view.SetCrossAssetPairsPinned(savedXaPairs);
m_view.SetCrossAssetCfgSaved(true);
PrintFormat("%s: adopting the cross-asset pair set this model was trained on - [%s]. The panel "
"builds from exactly this set; Market Watch changes do not alter it.",
__FUNCTION__, savedXaPairs);
}
//--- Alt-data name list: same adopt-don't-compare grounds. ReadAltDataPinFromCfg() normally
//--- adopted this before the width sum; a mismatch here means the .cfg changed between the two
//--- reads (or the pre-reader could not open it) - adopt and say so, because training on inputs
//--- whose names have silently shifted is exactly the misalignment the pin exists to prevent.
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
if(savedAltNames != "" && savedAltNames != m_view.AltDataNamesPinned())
{
PrintFormat("%s: alt-data pin from the .cfg [%s] differs from the one applied at width "
"derivation [%s] - adopting the .cfg's. If the width no longer matches, this run "
"will (correctly) refuse the saved weights.",
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
__FUNCTION__, savedAltNames, m_view.AltDataNamesPinned());
m_view.SetAltDataNamesPinned(savedAltNames);
m_view.ApplyAltDataPinnedNames(savedAltNames);
}
//--- isInitialized is DELIBERATELY excluded from the comparison: it is a runtime lifecycle flag,
//--- not a topology/input parameter, and it is always false at the point the compare and the
//--- fresh-start save run (set true only at the end of InitNeuralNetwork).
feat(nn): derive dense depth, train on all history, pin the shape in .cfg Completes the derived-topology work. Three inputs removed. AIType loses its depth suffix - AI_MLP/AI_CONV/AI_LSTM/AI_HYBRID, five entries instead of eight. Depth is now derived from the two endpoints the taper already has to connect (derived first-layer width, output-tied final width) at a 2x per-layer compression target, clamped [2..5]. Asking a user to pick a layer count while the code derives the widths those layers taper between was asking for half a decision: at 64 units tapering to 12, four layers compress by 1.4x per step and five by 1.3x, so the extra depth bought no abstraction. On the shipping H1/10y default the derivation lands on 3 layers - the depth that actually won Run 2. StudyPeriods removed. There is no case for training on less data than the broker provides at a ~6% directional base rate; the honest generalization read comes from the OOS holdout, not from withholding history. Training now starts at the earliest available bar, floored by MinTrainYear, which answers a different question (excluding dubious pre-history) and stays. That required closing the hazard the old code documented: the capacity budget now MEASURES the symbol's real bar count, and a topology derived from a measurement would widen as history downloads. Both ends are now pinned. Every derived value left the weights-filename fingerprint - keying a filename on a measured quantity means the EA looks for a file that does not exist, starts from era 0 and orphans a trained model, silently, because a missing cache is the normal first-run state. The shape lives in the .cfg instead, where LoadAndCompare now ADOPTS the four derived fields rather than diffing them; a mismatch there would discard a fully-trained model over nothing the user did. Two fields appended to the .cfg for the conv/LSTM stages, length-guarded on read because FileReadInteger past EOF returns 0 with no error. ForceHiddenLayers, a compile-time constant like DebuggingMode, pins depth for diagnostic comparisons. It joins the fingerprint only when non-zero, so forced depths get their own files - sequential comparisons only, not simultaneous from one .ex5. Derived shape, H1/10y defaults (21 features x 20 bars): first layer 64, 3 dense, 8 conv filters, 16 LSTM units. The LSTM block halves from ~58k to ~28k weights. Both builds compile 0 errors, 0 warnings. Re-keys existing models. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 10:05:40 -04:00
if(savedInitialNeurons > 0)
initialNeuronsCount = savedInitialNeurons;
if(savedHiddenLayers > 0)
hiddenLayersCount = savedHiddenLayers;
if(savedConvFilters > 0)
convFilterCount = savedConvFilters;
if(savedLstmHidden > 0)
lstmHiddenSize = savedLstmHidden;
//--- historyBars joined the adopt list 2026-08-11 when the window became DERIVED
//--- (DeriveHistoryBars): the measurement moves as history downloads, so comparing it would
//--- discard a trained model for nothing the user did - the exact failure mode this block exists
//--- to prevent.
if(savedHistoryBars > 0 && savedHistoryBars != historyBars)
{
PrintFormat("%s: adopting the input window this model was trained with - %d bars (a fresh "
"derivation would have said %d).", __FUNCTION__, savedHistoryBars, historyBars);
historyBars = savedHistoryBars;
}
feat(nn): derive dense depth, train on all history, pin the shape in .cfg Completes the derived-topology work. Three inputs removed. AIType loses its depth suffix - AI_MLP/AI_CONV/AI_LSTM/AI_HYBRID, five entries instead of eight. Depth is now derived from the two endpoints the taper already has to connect (derived first-layer width, output-tied final width) at a 2x per-layer compression target, clamped [2..5]. Asking a user to pick a layer count while the code derives the widths those layers taper between was asking for half a decision: at 64 units tapering to 12, four layers compress by 1.4x per step and five by 1.3x, so the extra depth bought no abstraction. On the shipping H1/10y default the derivation lands on 3 layers - the depth that actually won Run 2. StudyPeriods removed. There is no case for training on less data than the broker provides at a ~6% directional base rate; the honest generalization read comes from the OOS holdout, not from withholding history. Training now starts at the earliest available bar, floored by MinTrainYear, which answers a different question (excluding dubious pre-history) and stays. That required closing the hazard the old code documented: the capacity budget now MEASURES the symbol's real bar count, and a topology derived from a measurement would widen as history downloads. Both ends are now pinned. Every derived value left the weights-filename fingerprint - keying a filename on a measured quantity means the EA looks for a file that does not exist, starts from era 0 and orphans a trained model, silently, because a missing cache is the normal first-run state. The shape lives in the .cfg instead, where LoadAndCompare now ADOPTS the four derived fields rather than diffing them; a mismatch there would discard a fully-trained model over nothing the user did. Two fields appended to the .cfg for the conv/LSTM stages, length-guarded on read because FileReadInteger past EOF returns 0 with no error. ForceHiddenLayers, a compile-time constant like DebuggingMode, pins depth for diagnostic comparisons. It joins the fingerprint only when non-zero, so forced depths get their own files - sequential comparisons only, not simultaneous from one .ex5. Derived shape, H1/10y defaults (21 features x 20 bars): first layer 64, 3 dense, 8 conv filters, 16 LSTM units. The LSTM block halves from ~58k to ~28k weights. Both builds compile 0 errors, 0 warnings. Re-keys existing models. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 10:05:40 -04:00
//--- savedStudyPeriod is read for layout only and NOT compared - the StudyPeriods input it mirrored was
//--- removed 2026-07-30 (training covers all available history), so like the retired MinWR slot its
//--- value says nothing about whether the saved WEIGHTS are compatible.
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
string diff = "";
if(savedReductionFactor != neuronsReduction) diff += " reduction " + DoubleToString(savedReductionFactor, 4) + "->" + DoubleToString(neuronsReduction, 4) + ";";
if(savedMinNeurons != minNeuronsCount) diff += " minNeurons " + IntegerToString(savedMinNeurons) + "->" + IntegerToString(minNeuronsCount) + ";";
if(savedOptimizationAlgo != optimizationAlgo) diff += " optimizer " + IntegerToString(savedOptimizationAlgo) + "->" + IntegerToString(optimizationAlgo) + ";";
if(savedOutputNeuronsCount != outputNeuronsCount) diff += " outputs " + IntegerToString(savedOutputNeuronsCount) + "->" + IntegerToString(outputNeuronsCount) + ";";
if(savedNeuronsCount != neuronsCount) diff += " inputWidth " + IntegerToString(savedNeuronsCount) + "->" + IntegerToString(neuronsCount) + " (a feature toggle changed);";
if(savedMinTrainYear != minTrainYear) diff += " minTrainYear " + IntegerToString(savedMinTrainYear) + "->" + IntegerToString(minTrainYear) + ";";
//--- (savedStopTrainWR deliberately NOT compared - retired input, see the note above)
if(savedFractalPeriods != fractalPeriods) diff += " fractalPeriods " + IntegerToString(savedFractalPeriods) + "->" + IntegerToString(fractalPeriods) + ";";
if(diff != "")
{
Print("Configuration mismatch for ", configFileName, " -> retraining from era 0. Changed:", diff,
" (a saved model only reloads when these parameters match exactly; revert the changed input to resume the existing model.)");
FileDelete(configFileName, common ? FILE_COMMON : 0);
return false;
}
return true;
}
//+------------------------------------------------------------------+
//| Early read of ONE appended .cfg field: the alt-data feature name |
//| list. |
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
string CModelPersistence::ReadAltDataPinFromCfg(void)
{
bool inTesterOrOpt = (bool)MQLInfoInteger(MQL_TESTER) || (bool)MQLInfoInteger(MQL_OPTIMIZATION);
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
string fileName = inTesterOrOpt ? (m_view.FileName() + "_optcache") : m_view.FileName();
int commonFlag = inTesterOrOpt ? 0 : FILE_COMMON;
if(!FileIsExist(fileName + ".cfg", commonFlag))
{
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
fileName = m_view.FileName();
commonFlag = FILE_COMMON;
if(!FileIsExist(fileName + ".cfg", commonFlag))
return "";
}
int handle = FileOpen(fileName + ".cfg", FILE_READ | FILE_BIN | FILE_SHARE_READ | FILE_SHARE_WRITE | commonFlag);
if(handle == INVALID_HANDLE)
return "";
string pin = "";
//--- fixed layout: 12 ints + 1 double (see SaveTopologyConfiguration's write order)
bool ok = FileSeek(handle, 12 * sizeof(int) + sizeof(double), SEEK_SET);
//--- appended segments, in order: conv/lstm ints, sl/tp ints, derived sl/tp doubles,
//--- dirConf double, xa pin (int + chars), alt pin (int + chars)
if(ok && FileSize(handle) >= (ulong)FileTell(handle) + 2 * sizeof(int))
ok = FileSeek(handle, 2 * sizeof(int), SEEK_CUR);
else ok = false;
if(ok && FileSize(handle) >= (ulong)FileTell(handle) + 2 * sizeof(int))
ok = FileSeek(handle, 2 * sizeof(int), SEEK_CUR);
else ok = false;
if(ok && FileSize(handle) >= (ulong)FileTell(handle) + 2 * sizeof(double))
ok = FileSeek(handle, 2 * sizeof(double), SEEK_CUR);
else ok = false;
if(ok && FileSize(handle) >= (ulong)FileTell(handle) + sizeof(double))
ok = FileSeek(handle, sizeof(double), SEEK_CUR);
else ok = false;
if(ok && FileSize(handle) >= (ulong)FileTell(handle) + sizeof(int))
{
int xaLen = FileReadInteger(handle);
if(xaLen > 0 && xaLen <= 16 * CROSSASSET_MAX_PAIRS)
FileReadString(handle, xaLen); // skip the cross-asset pin (length in CHARS, as written)
else if(xaLen != 0)
ok = false; // garbage length: stop walking, yield no pin
}
else ok = false;
if(ok && FileSize(handle) >= (ulong)FileTell(handle) + sizeof(int))
{
int altLen = FileReadInteger(handle);
if(altLen > 0 && altLen <= ALTDATA_MAX_PIN_CHARS)
pin = FileReadString(handle, altLen);
}
FileClose(handle);
return pin;
}
//+------------------------------------------------------------------+
//| LoadNetWithRetry's operand - see RetryWithBackoff.mqh's |
//| declaration comment for the shared exponential-backoff shape |
//| this plugs into (same shape CopyFileWithRetry uses, System\ |
//| SharedFileCopy.mqh). LoadNetOnce has no quiet param of its own, |
//| so quiet is simply unused here - nothing to forward it to. |
//+------------------------------------------------------------------+
class CLoadNetOnceOp : public IRetryableOp
{
private:
CPersistenceView *m_view; // BORROWED, same as CModelPersistence's own m_view
public:
double indicatorParams[];
CLoadNetOnceOp(CPersistenceView *view) : m_view(view) { }
virtual bool TryOnce(bool quiet) override { return m_view.LoadNetOnce(indicatorParams); }
};
//+------------------------------------------------------------------+
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
//| See the declaration comment - retries Net.Load() against the |
//| active file. Covers the same transient-lock class as |
//| CopyFileWithRetry (e.g. antivirus briefly holding the file just |
//| written into the tester's local sandbox) rather than assuming any |
//| single failed read means "no model"/"corrupt file". |
//+------------------------------------------------------------------+
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
bool CModelPersistence::LoadNetWithRetry(double &indicatorParams[])
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
{
const int RETRY_ATTEMPTS = 5;
const int RETRY_DELAY_CAP_MS = 2000;
CLoadNetOnceOp op(m_view);
bool loaded = RetryWithBackoff(GetPointer(op), RETRY_ATTEMPTS, 200, RETRY_DELAY_CAP_MS);
ArrayCopy(indicatorParams, op.indicatorParams);
refactor: split CExpertSignalAIBase implementation by responsibility ExpertSignalAIBase.mqh was 8216 lines: the class declaration followed by 87 method bodies covering training, labelling, feature extraction, persistence, chart drawing, online learning, the GA auto-tuner and inference, all in one file. Train() alone is 1492 lines; a change to arrow drawing meant scrolling past the era loop. Moved the bodies into Expert\AIBase\, included at the bottom of the original after the class declaration: Training.mqh 1607 era loop, plateau ladder, checkpoint select, deploy Features.mqh 1093 indicator creation + per-bar input feature vector ChartUI.mqh 634 arrows, arrow persistence, status panel, cleanup Persistence.mqh 492 .stats/.cfg sidecars, CPU-inference validation, copy OnlineLearning.mqh 461 live continual learning, EMA shadow, OOS simulator Labels.mqh 309 ZigZag pivot labels, async label-cache prebuild AutoTune.mqh 275 genetic tuner (population, crossover, halving) Inference.mqh 235 softmax, prior calibration, class priors ExpertSignalAIBase.mqh 8216 -> 3131 (declaration + topology build only) This is a pure relocation - verified mechanically, not by eye: HEAD's file reconstructed from the eight partials plus the surviving remainder is byte-identical to HEAD, span for span (scratchpad verify_split.py). No declaration moved, no signature changed, no code rewritten, so behaviour is unchanged by construction. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:42:45 -04:00
return loaded;
}
refactor(persistence): ModelPersistence is a real collaborator, not a raw-include partial (S3) Expert/AIBase/Persistence.mqh (598 lines, 8 methods) -> Expert/Persistence/: IPersistenceView.mqh (abstract, 68 read+write accessors) + AIBasePersistenceView.mqh/ AIBasePersistenceViewImpl.mqh (the adapter) + ModelPersistence.mqh (CModelPersistence, the real collaborator - signal owns m_modelPersistence and binds it to m_persistenceView, same shape as ChartUI's S2). Grep-verified before starting: every field these 8 methods touch is ALSO touched elsewhere in the class (Training/Lifecycle/OnlineLearning/Topology/FeatureScreen/ Labels.mqh) or already exposed via ChartView. Zero exclusive state, unlike ChartUI's arrow-restore/rescan queues - CModelPersistence is stateless, holding only the borrowed view pointer, operating entirely through 68 Persist*/PersistSet*() accessors on the signal. ValidateCpuInference's Net-pointer/throwaway-clone core is ONE consolidated view call (PersistRunCpuInferenceSelfCheck) rather than field-by-field - irreducible pointer/ object work, not signal state, same doctrine as ChartScoreBarForRescan. LoadNetWithRetry keeps its original CheckPointer(Net)-free Net.Load() call unchanged (no guard added - would change failure behaviour on what must be a pure relocation). This code writes the actual on-disk .cfg/.stats binary layouts every deployed model depends on (explicit "DO NOT REORDER" comment in the original), so beyond compiling clean (0 errors, 0 warnings) this was verified with a positional field-order diff: every FileWrite*/FileRead* call's target field, extracted and normalized from both the original and the new file, matches 1:1 in the same order (43/43 on the write side covering SaveModelStats+SaveTopologyConfiguration, 17/17 on LoadModelStats' read side; LoadAndCompareTopologyConfiguration's local-variable read block was copied verbatim, untouched, so nothing to diff there). The magic-version conditionals (WST2-6, haveDerivedStages/haveBarrierGeometry/etc.) moved unchanged. All 8 methods keep their exact original signatures as one-line forwards - zero external call sites changed.
2026-08-23 21:45:09 -04:00
#endif // WARRIOR_PERSISTENCE_MODELPERSISTENCE_MQH
//+------------------------------------------------------------------+