Commit graph Warrior_EA/Variables
Author SHA1 Message Date
AnimateDread
70cdec2717 fix(ai): drop the conv pooling stage - it reduced across filters, not time
FeedForwardConv emits POSITION-MAJOR output, matrix_o[out + window_out * i],
so one bar's window_out filter responses are contiguous and consecutive bars
sit window_out apart. Both pooling implementations (FeedForwardProof and
CPU_FeedForwardProof) slide FLAT over that buffer - pos = i * step, reducing
`window` CONSECUTIVE elements. On a position-major layout those neighbours
are different FILTERS of the same bar, never one filter across time.

At the shipped 3/2 the pool computed max(bar0_f0, bar0_f1, bar0_f2), then
max(bar0_f2, bar0_f3, bar0_f4), with every 8th window straddling a bar
boundary. So it collapsed unrelated feature detectors into whichever fired
hardest, passed gradient to that winner only, and halved the feature map
while doing it - all below every learnable layer, where nothing above can
recover it. The removed inputs' own labels ("3 Bars") show time-axis pooling
was the intent throughout.

Measured cost: CONV sat pinned at ~40% balanced accuracy for 510 eras with
Sell recall 0%, while plain MLPs on the same data reached 57-61%. HYBRID,
which also carried this stage, came second-worst of the batch-norm group.

Not fixable in the topology: pooling one filter across time needs a stride
of window_out BETWEEN samples within a window, which a consecutive-window
kernel cannot express at any window/step. That needs a stride-aware kernel
in Network.cl + WarriorCPU.cpp + WarriorDML.cpp and a DLL rebuild, and is
only worth doing if a conv front-end earns its place without downsampling
first - with 20 sliding positions there is little to gain by halving them.

ConvPoolWindow/ConvPoolStep and their enums are removed with it, along with
the |CP: fingerprint term added earlier today.

Both builds compile 0 errors, 0 warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 19:28:44 -04:00
AnimateDread
f2ec1edf84 feat(ai): logit-adjusted loss, replacing oversampling and the post-hoc prior
Menon et al. 2021 (ICLR), "Long-tail learning via logit adjustment": add
tau*log(prior_c) to each class logit inside the training gradient. Softmax
CE on adjusted logits is consistent for BALANCED error - the metric
checkpoint selection already ranks on - so the loss and the deploy decision
finally optimize the same thing.

The engine already computed a true softmax + categorical-CE gradient and
wrote it over the per-neuron sigmoid delta, so this is an offset added to
three logits in the two places that gradient is built (backProp scalar path
and backPropOCL). No backend, kernel or DLL change; the forward pass and
every inference path are untouched, which is the point - the network learns
to absorb the offset, so its raw argmax becomes the balanced-optimal
decision with nothing applied at inference.

Replaces rather than stacks. Minority replay is disabled while this is on,
and the post-hoc inference prior is forced off. Stacking is not a
theoretical worry: simulated on the measured 1118/1119/34298 distribution
in the weak-signal regime, plain CE collapses to Neutral (33.4% balanced,
Buy 0%), replay reaches 48.1%, logit adjustment 50.9% with better balance -
and BOTH together score 45.4% with Neutral recall at 0%, worse than either
alone. Buda et al. 2018 predicts exactly that.

Motivation from the six-chart run: every topology took one direction to
~50% recall and abandoned the other, the direction chosen arbitrarily (the
batch-norm control went Buy 1% / Sell 42%, the inverse of the other five).
One era in 1,301 cleared the per-class recall floor.

Fingerprinted conditionally, so the converged 60.7% models on disk keep
their filenames and stay loadable as the fallback.

Both builds compile 0 errors, 0 warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 19:05:14 -04:00
AnimateDread
2695a961c4 refactor(perf): pin CPU threads per network, drop the TargetCPULoad input
Dividing a machine budget by the live chart count was wrong twice over.
The count is a snapshot taken when each net's pool is built, and charts
attach one at a time: five charts measured 10/6/5/4/4% of the same budget,
because the first only ever saw itself and the last saw all five. So the
earliest chart got several times the threads of the latest - skewing any
cross-topology comparison run on those charts, which is the exact thing
the setting existed to make fair. Nothing rebalanced afterwards either,
and rebalancing would mean tearing down a DLL context under a live trainer.

Both problems disappear once the answer stops depending on how many charts
are running. Each net now asks for a fixed 2 worker threads, converted to
the percentage the DLL wants from the detected core count.

Two is not a compromise: since the topology became data-derived the widest
dense layer is 64 units, so each ParallelFor has almost nothing to split
and per-dispatch overhead dominates. An MLP era cost ~66s at a wildly
oversubscribed 12 threads and ~80s at 1 thread - a 20% spread across a 12x
difference in thread count. Two per net also lands six concurrent charts
exactly on a 12-core box.

Removing the input costs nothing on the product side: a Market build has no
DLL tier at all, so it was already compiled out to a constant there and no
buyer could reach it.

Both builds compile 0 errors, 0 warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 15:33:37 -04:00
AnimateDread
692cb0eeaa refactor(ai): derive the dense taper's shape, not just its first layer
Deriving the first layer's width left NeuronsReduction and MinNeuronsCount
behind as inputs calibrated for something that no longer exists. Against a
hand-picked 500-wide first layer "keep 30%, floor at 20" produced a genuine
funnel - 500 -> 150 -> 45. Against the derived 64 it degenerates to
64 -> 20 -> 20: the reduction factor stops mattering after one step, and
"minimum neurons per layer" silently becomes the width of every layer but
the first. Two knobs whose labels no longer describe what they do.

The taper now runs geometrically from the derived first-layer width down to
a final hidden layer sized off the output count, spread evenly over however
many layers the chosen AIType implies:

    MLP_3L      64 -> 28 -> 12 -> 3      29,151 dense weights
    MLP_4L      64 -> 37 -> 21 -> 12 -> 3    30,450
    CONV/LSTM/HYBRID_2L   64 -> 12 -> 3      27,763

and it stays a funnel at the floor, where the old rule could not:

    D1 (first layer floored to 16)   16 -> 14 -> 12 -> 3

Both inputs are removed. With the width derived there is no freedom left in
the taper, so keeping either would only let the user contradict the
derivation. The layer COUNT stays selectable, because it is bundled into
AIType alongside the conv/LSTM front-end - depth is an architecture choice,
not a data-derived quantity, and pairing them means the two cannot
contradict each other.

m_minNeuronsCount / m_neuronsReduction survive as frozen members: nothing
reads them to build a topology any more, but they hold positional slots in
the .cfg sidecar and the weights fingerprint, and changing either value
would re-key every model on disk for no behavioural reason.

The DB config fingerprint drops both terms.

Compiles 0 errors, 0 warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 14:03:42 -04:00
AnimateDread
af209997fc refactor(ai): derive the first dense layer's width instead of asking for it
InitialNeurons was an input whose only defensible value depends on two
things the user cannot see when picking from a dropdown: how wide the input
vector ended up after feature selection, and how much in-sample data the
study period actually yields. Left to a hand-picked constant it was badly
wrong - 500 units against a 420-wide input is 210,500 weights, 72% of a
292,583-weight model, against ~36,500 training bars of which only ~2,236
are directional. That is 6.6 weights per training bar, and it EXPANDS a set
of highly correlated inputs rather than compressing them.

The symptom was already in the logs and had been read as a depth problem:
the shallowest topology consistently beat the deepest (perceptron 52.7%
balanced, hybrid 41.3%). Over-parameterization predicts that ordering just
as well as covariate shift does, and only one of the two had been addressed.

ComputeFirstLayerWidth() budgets roughly one first-layer weight per
in-sample bar. Measured across the configurations in use:

    M15 10y -> 256 units, 129,071 weights, 0.73 per bar
    H1  10y ->  64 units,  28,727 weights, 0.65 per bar
    H4  10y ->  16 units,   7,559 weights, 0.68 per bar

Two design points that matter:
  - It estimates in-sample bars from the STUDY PERIOD and timeframe, not
    from Bars(). What is downloaded grows over a terminal's lifetime, and a
    topology that widened as history filled in would re-key its own weights
    file and discard a trained model.
  - The result is snapped down to a coarse power-of-two ladder, so the
    estimate would have to be wrong by ~2x to change the answer.

Every field it reads is already part of the weights-filename fingerprint,
so the derived value needs no fingerprint entry of its own. The public
setter is removed - it could only have been called after construction, and
would either be ignored or silently re-key the model mid-run.

Where the data cannot support even the floor (D1 over 10 years is under
2,000 bars) it now says so and names the fixes, rather than quietly
training a model with more weights than examples.

The DB config fingerprint drops the term too, which re-keys existing
pattern databases once - correct, since a model an order of magnitude
smaller should not inherit the old one's win-rate history.

Compiles 0 errors, 0 warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 13:01:16 -04:00
AnimateDread
30206cbabc feat(ai): batch normalization between dense layers
The only bounded stage in the entire forward path was the sigmoid
classification head - every hidden stage is PRELU. That is a network with
no internal scale control, and the failure ordered exactly by depth: on
SP500 H1 the shallow perceptron held ~52% balanced accuracy while the
deepest topology sat on the 33.3% one-class floor, with the per-bar logit
spread decaying monotonically (0.45 -> 0.38 over ~200 eras) until the
evidence tilt fell under the class-prior tilt. That is the signature of
internal covariate shift, which chapter 6.1 of the reference book is
entirely about and which the NeuroNet_DNG engine addresses with a layer
this project never had.

Two mechanisms make this the right fix rather than more hyperparameter
nudging:
  - it decouples WEIGHT_DECAY from the learned function (van Laarhoven
    2017) - with a normalized layer downstream, decay can no longer grind
    the discriminative signal away, it only rescales the effective
    learning rate;
  - it is the precondition for ever running an unbounded logit head here.
    The 2026-07-27 attempt blew up (IS error 5.6e15) precisely because
    nothing upstream constrained scale.

Implementation notes:
  - CNeuronBatchNormOCL computes host-side rather than as a fourth copy of
    a kernel across Network.cl + WarriorCPU.cpp + WarriorDML.cpp. The math
    is elementwise O(n); this way it behaves identically on all four
    compute tiers, needs no DLL rebuild, and cannot drift between
    backends. Same precedent as the softmax+CCE gradient and the
    per-sample loss weighting, both computed in MQL5 for that reason.
  - Statistics are exponential moving, not a stored mini-batch: training
    is pure online SGD, one update per sample, so there is no batch to
    average over. BatchNormWindow is an EMA window length.
  - gamma/beta are excluded from weight decay, deliberately - decaying
    gamma toward zero is the exact pathology being fixed.
  - The layer self-sizes from whatever sits below it, because a conv/pool
    stage's output width is derived inside the CNet constructor and is not
    knowable to the topology builder.
  - Checkpoint capture/restore/blend carry gamma/beta and the running
    statistics alongside the dense matrix, so the plateau ladder cannot
    restore a mismatched pair.
  - SeedOutputLayerBias accepted only an exact defNeuronBaseOCL as the
    weight-carrying penultimate layer; with normalization enabled that is
    the batch-norm layer, so the cold-start bias seed would have silently
    stopped being applied.
  - Refuses to build, loudly, if a topology asks for normalization with no
    compute backend at all - rather than quietly training a different
    architecture than the one requested.

EnableBatchNorm (default on) and BatchNormWindow (1000 samples) are
inputs so the effect can be A/B'd without a recompile. Both feed the
weights-filename fingerprint, appended conditionally so existing non-BN
configs keep their fingerprints and are not forced to retrain.

Verified: analytic gradients match finite differences to 1.5e-7 relative
over 200 random cases; a faithful port of the full forward/backward chain
collapses to the 33.3% floor by era 4 without this layer and holds
36-43% with it. Compiles 0 errors, 0 warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:34:29 -04:00
AnimateDread
cc625c827e fix(training): escape the recall-gate catch-22 that let runs decay unchecked
Evidence (MQL5\Logs, SP500 H1, 2026-07-29):

  Perceptron  era  61  Buy 32% Sell 27% Neut 94%  bal 51%
  LSTM        era 160  Buy 16% Sell 11% Neut 98%  bal 42%  (peaked 49% @ era 44)
  Hybrid      era 179  Buy  5% Sell  2% Neut 99%  bal 35%  (peaked 41%)
  CONV        era 228  Buy  2% Sell  4% Neut 99%  bal 35%  (peaked 40% @ era 122)

Every model peaks early then decays monotonically toward Neutral, and nothing
stops it: the restore-best-weights + decay-eta handler is gated on
m_bestPassedRecall, which stays false forever when no checkpoint ever clears the
per-class floor. CONV ran 228 eras with eta pinned at its 0.000300 start. The
plateau ladder cannot end such a run either (stage 3 refuses to deploy without a
recall pass, so it resets ~27 times), making it a 1000-era one-way trip.

The gate's own justification had expired. It was written when the pre-pass
tiebreak was blended-accuracy-only, where "best" really did mean "called Neutral
most confidently". The balanced-selection change replaced that with
`balancedOosEra > m_bestBalancedOos` plus an isFullyCollapsedEra exclusion, so a
Neutral-only era now scores ~33% - the FLOOR of the balanced metric - and cannot
anchor the checkpoint at all. Pre-pass "best" now means "most class-balanced so
far", which is worth defending; and isWorseEra is itself a balanced-accuracy
regression, so it cannot fire merely for trading Neutral calls for Buy/Sell.

The original concern still holds while the best-so-far IS near-collapse, so the
escape is margin-guarded: defend the checkpoint only once balanced accuracy sits
more than BALANCED_WORTH_DEFENDING_MARGIN_PCT (5pp) above the one-class floor of
100/3. Against the run above that engages for all three stuck topologies
(42.3/41.3/50.0 vs a 38.3 threshold) while a genuinely collapsed run still
explores freely.

Two inputs restored to the regime that actually produced a deploy:

- MinRecall 60 -> 40. The one successful auto-deploy in the logs (Hybrid, 28th
  00:50, best balanced 66.0%) ran against a 40% floor. 60 has never been shown
  reachable here - a floor above what the config can reach is the same "target
  set too high" failure the surrounding comment already warns about.

- OversampleParity 60 -> 90. 60 overcorrected. Runs now START Neutral-dominant
  (Buy 0-11% recall at era 1) and call Buy/Sell on 0-4% of bars against a ~6%
  true base rate - under-calling, with no headroom to converge down from. The
  deploying run began at Buy 90% / Sell 36%, 24% of bars called, and settled into
  the floor from above. Raw over-calling is the intended starting condition; live
  calls are base-rate-calibrated by AILogitPriorStrength, which is why the input's
  own note says to judge over-calling by live-fired precision, not raw counts.

Compiles 0 errors, 0 warnings.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 07:51:08 -04:00
AnimateDread
4f28165cd3 fix: remove broken DFA optimizer, use plain gradient descent
The DFA (Direct Feedback Alignment) option was never a correct implementation:
it deterministically flipped the sign of half of all gradients based on
connection index parity, causing permanent gradient ascent for those weights
and guaranteed divergence. The backward pass was also incompatible with the
OpenCL/DirectML neuron model (layer.Total() == 1). This change removes all DFA
logic, including the enum value and `DfaFeedbackSignal` method, and replaces it
with plain gradient descent in all momentum update kernels. The `optimizer`
kernel argument is retained for binary compatibility but is no longer used.
2026-07-29 00:03:54 -04:00
AnimateDread
30c0aafff8 feat(Network): add DFA training and optimizer snapshot support
Introduce Direct Feedback Alignment (DFA) backward pass with gradient clipping, feedback matrix initialization, and a dedicated backPropDfa method. Add optimizer snapshot/restore hooks (CaptureOptimizerSnapshot, RestoreOptimizerSnapshot, SetOptimizerForAllNeurons) to temporarily switch the entire network's optimizer for replay-only updates during pass 2, preserving the original optimizer state. Support all neuron types including dropout, deconv, LSTM, and softmax in the snapshot logic.
2026-07-28 17:42:12 -04:00
AnimateDread
d988c8829a refactor(inputs): switch default training optimizer to DFA 2026-07-28 15:05:56 -04:00
AnimateDread
a303f5b86c refactor: merge AI topology preset into AI_CHOICE enum
Eliminate the separate `AI_TOPOLOGY_PRESET` enum and input.
Fold the topology presets directly into `AI_CHOICE` as new combined values (MLP_3L, MLP_4L, CONV_2L, LSTM_2L, HYBRID_2L) plus `AI_NONE`.
Remove the `TopologyPreset` input variable and update default `AIType` assignments.
Update the market description to reflect the simplified single‑selector interface.

**Why:**
Users previously had to choose an AI architecture and a topology preset separately.
Now the UI shows one coherent selector that bundles architecture with its appropriate dense‑layer depth, reducing complexity and preventing mismatches.
2026-07-28 12:02:58 -04:00
AnimateDread
e4f88d7934 feat: replace HiddenLayersCount with AI_TOPOLOGY_PRESET for architecture-aware topology presets 2026-07-28 11:47:29 -04:00
AnimateDread
941c88a20f refactor(hyperparams): soften labels, shrink network, tune priors and gamma 2026-07-28 10:49:53 -04:00
AnimateDread
031f147b2a feat: change default AI type to HYBRID and bump version to 3.2
Set the default AIType to HYBRID for non-MARKET builds. Update project version to 3.2.
2026-07-27 22:30:06 -04:00
AnimateDread
e043e565eb feat: implement hybrid AI signal with CNN-LSTM architecture and add pooling parameters 2026-07-27 22:08:55 -04:00
AnimateDread
48abb89e6a fix: skip DirectML DLL in tester, add NaN guards, improve chart cleanup
In AI/Network.mqh, return early from InitDirectML during
tester/optimization/forward runs to prevent agent-side file-lock
failures caused by rapid stop/restart cycles accessing DLL imports.

In Expert/ExpertSignalAIBase.mqh, add MathIsValidNumber checks in
CalibratedConfidenceMagnitude and SignaledConfidence to safely handle
NaN values, and refactor ShutdownChartCleanup to accept a preserve
flag, avoiding unnecessary chart purges during tester runs for faster
shutdowns. Also add m_purgeChartOnDestruct member.

In AI/NeuronDirectML.mqh, clean up a minor comment formatting issue.
2026-07-27 15:52:39 -04:00
AnimateDread
13562221f4 refactor: use LOGIT_PRIOR_OFF as default for AILogitPriorStrength 2026-07-27 11:53:47 -04:00
AnimateDread
3a37b9115e fix: correct inference-only new-bar detection and add stop validation
In inference-only backtests, dtStudied could be ahead of the test range, causing new-bar detection to freeze. Replaced with m_lastBarTime to keep detection aligned with runtime history. Added diagnostic logging when a non-neutral softmax output is neutralized by prior correction. Also added validation for order_price, sl, and tp in stop-checking functions to catch non-finite or negative values.
2026-07-27 11:51:45 -04:00
1e4c54b95a refactor: update classic signal presets and disable close vote by default
- Append '(classic)' to RSI period 14, indicator period 14, risk-reward 1:2, and risk percent 1 preset comments
- Change Min_Vote_Close default from VOTE_CLOSE_80 to VOTE_CLOSE_DISABLED
2026-07-26 18:48:34 -04:00
b2069bcee4 feat(signals): add MACD/Ichimoku presets and Vote_Close disabled option
Add MACD_FAST, MACD_SLOW, MACD_SIGNAL presets and Ichimoku Tenkan, Kijun, Senkou presets to InputEnums.mqh. All combinations are designed to satisfy the respective indicator's validation rules (fast < slow for MACD, Tenkan < Kijun < Senkou B for Ichimoku), eliminating init errors and allowing the auto-tuner to perturb settings independently.

Introduce VOTE_CLOSE_PRESETS enum with a Disabled option (value 101) that bypasses vote-driven position closing via arithmetic thresholding, removing the need for a separate boolean flag. This ensures positions exit only via stop-loss, take-profit, or trailing when disabled.
2026-07-26 18:33:12 -04:00
8d4fe088b8 refactor: unify AI and classic vote parameters to Min_Vote_Open/Close
Removes standalone AI confidence parameters (MinAIConfidence, MinAIExitConfidence) and replaces them with unified Min_Vote_Open and Min_Vote_Close thresholds that apply to both AI and classic engines. Updates all code comments, report suggestions, and market descriptions accordingly, simplifying configuration and ensuring consistent vote requirements across entry and exit logic.
2026-07-26 17:27:51 -04:00
a17f8f1e15 fix(signal): snapshot alternation gate to prevent premature consumption on discarded votes
Add BeginVote/RevokeVote lifecycle hooks to ExpertSignalCustom and ExpertSignalAIBase.
Snapshot m_lastNonNeutralSignal before condition evaluation in Direction(), and restore
the snapshot if the vote is later discarded (e.g., Hybrid quorum shortfall).
Previously, a discarded vote still consumed the alternation gate, which could
permanently gate out valid signals until the opposite direction appeared.
2026-07-26 17:09:13 -04:00
AnimateDread
5247c34fe9 fix: add error logging for buffer failures and reject trades on invalid stop loss 2026-07-26 12:12:14 -04:00
AnimateDread
c30a10f7b9 fix(ExpertSignal): convert TP from ATR-relative to risk-relative to fix zero-trade bug
The previous TP calculation used ATR from entry, decoupled from the swing-anchored SL distance. This caused the Min_Risk_Reward_Ratio rejection filter to always fail because reward < 2*risk with default settings, preventing any trades. Now TP is a multiple of the actual trade risk (entry-to-stop distance), restoring coupling and ensuring the default RR filter is satisfiable. Also enforce minimum SL distance before TP calculation to maintain correct risk-ratio.
2026-07-25 22:33:45 -04:00
AnimateDread
8ae14c60a8 fix: protect TargetCPULoad for Market build and update description
The Market build has no DLL tier (WarriorCPU.dll is compiled out per MQL5 Market rules), so the TargetCPULoad input would have sat unused in the Inputs tab. Now it is conditionally compiled as a const when WARRIOR_MARKET_BUILD is defined, keeping the call site intact while avoiding a dead input.

The Market_Description.html was rewritten to better explain the EA's neural network, its self-training on unseen data, and the dual classic/AI signal paths, along with installation details and screenshots.
2026-07-25 21:32:15 -04:00
AnimateDread
c7e533a880 feat(ExpertSignalAIBase): add plateau ladder escalation and legacy MinWR shim
Implement a plateau detection mechanism that escalates through warm restart, gamma annealing, and eventual deployment when balanced accuracy stagnates for `PLATEAU_PATIENCE_ERAS`. Also add a compatibility shim for the removed `MinWR` input to preserve model filenames and `.cfg` layout.
2026-07-25 15:55:56 -04:00
AnimateDread
5d6f03014e fix: implement atomic file save in CNet::Save to prevent data corruption
The previous save directly wrote to the target file, which could leave a truncated/partial file if the process was force-killed (e.g., MT5 deinit timeout). Now the save writes to a temporary file (.savetmp) and only renames it over the real file after a successful write. This ensures that an interrupted save never corrupts the last good model. Additionally, improved diagnostics in CNet::Load to distinguish corrupt/incompatible files from compute errors.
2026-07-25 01:21:05 -04:00
AnimateDread
d7c550c470 feat: add in-memory weight snapshot/restore for mid-run stability
Add CaptureWeights and RestoreWeights methods that snapshot every neuron's weights into host arrays (CArrayDouble per neuron) and restore them in-place via setWeights. This replaces the file-based SaveCheckpoint/LoadCheckpoint for the mid-run best-era rollback, because the file path re-creates neurons (CLayer+Init) which fails on the multithreaded CPU-DLL backend (CDirectMLMy/WarriorCPU.dll) that cannot allocate a second full set of neuron tensors while the live set exists. In-memory weight copy uses only getWeights/setWeights, already proven by the per-era shadow blend. Snapshots weights only (not Adam moments); the regression handler decays eta on restore and clips per-step deltas to prevent stale-moment overshoot. Snapshot is valid only within a single Train() run. Also adds HaveWeightSnapshot() query and the m_weightSnapshot / m_haveWeightSnapshot member variables.
2026-07-24 21:21:47 -04:00
AnimateDread
b78bb5d2ec feat: support pure-MQL5 CPU inference for OCL neuron layers without GPU backend 2026-07-24 11:52:19 -04:00
AnimateDread
72797ab7ba feat: prevent saving empty network and add logit adjustment calibration
- Guard CNet::Save to refuse writing a 0-layer network (prevents overwriting ~18MB model with empty stub)
- In CNet::Load and LoadCheckpoint, treat 0-layer files as load failure (older stubs still on disk)
- Introduce LOGIT_PRIOR_STRENGTH_PRESETS enum (0–100%) to control logit adjustment tau
- Prepare member variables and AdjustedSignalFromSoftmax for prior-corrected posterior at inference
- Ensure raw argmax scoring for recall/convergence remains unchanged; correction only affects live signal
2026-07-23 19:36:34 -04:00
AnimateDread
aee542bc2f refactor(indicator-resources): centralize indicator embedding in main EA file
Moved #resource directives for all custom indicators from IndicatorResources.mqh to Warrior_EA.mq5 to keep embedding logic in a single location and simplify build configuration. Updated comments to clarify MARKET vs. private build behaviour and path resolution.
2026-07-23 15:28:04 -04:00
AnimateDread
4bc196d5d4 feat: add unified MA type support to indicator tuner
Add `MA_TYPE_PRESETS` enum covering advanced (ALMA, DEMA, ZLEMA, T3, Kalman) and standard (SMA, EMA, SMMA, LWMA) moving averages. Integrate `maType` and `bestMaType` into `CADIndicatorTuner` struct, update flatten/unflatten routines, and bump `AD_TUNE_PARAM_COUNT` to 33. This allows the auto-tuner to search over MA type alongside period, improving feature discovery.
2026-07-23 15:02:09 -04:00
AnimateDread
771c9b58ec feat: add weight scaling parameter to neuron initialization for improved training stability
- Added optional `weighScale` parameter (default -1.0) to `CNeuronBase::Init` and `CLayer::CreateElement`.
- Updated `CNeuronPool::Init` to use LeCun-uniform scaling (1/sqrt(window+1)) for its base initialization.
- Updated `CNet::CNet` to use He-scaled initialization (sqrt(2/neurons)) for dense layers.
- These changes enable more flexible and statistically sound weight initialization, matching the rationale used in OCL-based implementations, leading to better training stability and convergence.
2026-07-22 22:51:04 -04:00
AnimateDread
d667896457 refactor(AI): clean up comments and add conditional compilation guards
Remove verbose book references from input parameter comments in
Network.mqh for clarity. Add #ifndef guard around ENUM_OPTIMIZATION
to allow inclusion from multiple headers without redefinition.
Document the MQL5 Market DLL restriction in NeuronDirectML.mqh and
introduce WARRIOR_MARKET_BUILD macro to conditionally compile out
DirectML DLL imports for Market-compliant builds.
2026-07-22 17:17:23 -04:00
AnimateDread
0f0958856c feat: restructure input enums with intelligent SL/TP and AI exit
Replace old ATR_MULTIPLIER, THRESHOLDS_PRESET enums with new
STOP_LOSS_MODE, TAKE_PROFIT_MODE, AI_EXIT_MODE enums that support
ATR-based, intelligent confidence-scaled, and swing-anchored modes.
Also fix LSTM signal identity string.
2026-07-22 13:33:56 -04:00
AnimateDread
c024e8dede feat: add non-max suppression and balanced accuracy for signal clustering and checkpoint ranking
Implement non-max suppression (NMS) to declutter signal visualizations by keeping only the first bar of each same-direction run, controlled by m_signalClusterWindow. Also replace blended accuracy with balanced accuracy (macro-recall) for checkpoint selection to avoid neutral bias, tracked via m_bestBalancedOos. This improves signal clarity and model deployment quality.
2026-07-21 00:03:45 -04:00
AnimateDread
7aec5c4916 feat(ExpertSignalAIBase): extend swing context with recent price-action features
Increase the swing context neuron count from 5 to 9 by adding four fresh, non-repainting features: Donchian range position at 20 and 50 bars, 20-bar return, and 20-bar SMA extension. These are computed from closed bars only, eliminating lookahead. They provide immediate trend/position context that the stale (~100-bar-old) confirmed pivot anchor cannot, enabling the network to differentiate genuine reversals at range extremes from mid-trend bars that resemble pivot shapes.
2026-07-20 19:17:23 -04:00
AnimateDread
e13ee77c94 feat(signal): add oversampling parity fraction and min signal confidence threshold
Introduce OVERSAMPLE_PARITY_FRACTION (0.7) to control minority class oversampling scaling, reducing low-quality directional calls by not fully replicating to parity. Add m_minSignalConfidence (0.5) to require a minimum softmax probability for live Buy/Sell orders, preventing firing on bare plurality (~0.34) and improving signal quality.
2026-07-20 15:55:21 -04:00
AnimateDread
e8452913c0 feat: add swing-context feature with confirmed zigzag pivot
Introduce m_useSwingContext flag and FindConfirmedZigZagPivot method to compute normalized swing direction/magnitude/age features from the existing ADZigZag indicator. Only pivots that are at least m_swingConfirmationBars old are trusted, preventing lookahead bias. The SWING_SCAN_CAP_BARS macro limits backward scan depth. Default is off.
2026-07-19 11:04:38 -04:00
AnimateDread
3fbe16127e docs: simplify comments and enum descriptions across AI and Enums
Remove overly verbose explanations in Network.mqh comments and InputEnums.mqh enum values. Shorten descriptions to improve readability without losing essential information.
2026-07-18 23:59:40 -04:00
AnimateDread
6f95a402f4 refactor: replace class-balance loss weighting with data-level oversampling
Class-balance correction is now performed entirely via data-level oversampling (duplicating minority-class bars) instead of using a per-occurrence loss-weight multiplier combined with oversampling. The loss-weight mechanism proved ineffective due to Adam's near-invariance to constant gradient rescaling (Kingma & Ba 2015). The CLASS_SAMPLE_WEIGHT_PRESET enum is retained for a possible future supplemental loss weight, but m_maxClassSampleWeight currently has no effect. The MAX_OVERSAMPLE_REPLICAS constant is now the sole bound on correction strength.

Updated comments in InputEnums.mqh and ExpertSignalAIBase.mqh to reflect this change.
2026-07-18 23:25:54 -04:00
AnimateDread
d91cabc114 refactor(MoneyIntelligent): replace streak-chasing lot sizing with fractional-Kelly criterion
Optimize() scaled lot size off account trade-history streaks with no Magic-number
filter (picked up other EAs'/manual trades) and an unconfigurable m_factor stuck at
1.0 (Factor() was never wired from an input), so a 3-trade streak could triple lot
size or send it negative. It was also entirely disconnected from what the AI model
actually knows about the current setup.

Replaced both AdjustRiskAmount()'s linear confidence-only scale and Optimize()'s
streak multiplier with one edge-based model: p from the empirically calibrated
AI/DB confidence magnitude, b from the trade's real reward:risk ratio (newly
bridged from OpenParams() via g_TradeRewardRiskRatio), quarter-Kelly applied and
clamped so risk% can only ever scale down from its configured ceiling, never above it.
2026-07-18 17:39:58 -04:00
AnimateDread
31b2711c8f feat: add daily-loss and max-drawdown risk circuit breakers
Audit turned up a real gap for a prop-firm-portfolio-manager use
case: nothing in this codebase watched for account-level daily-loss
or max-drawdown breaches - the single most common way a prop-firm
evaluation actually gets failed.

New Signals/SignalRiskGuard.mqh (CSignalRiskGuard), wired into the
exact same filter-composition chain as SignalNewsFilter/
SignalSessionFilter (CreateSignalWithRetry/AddFilterToSignal, no new
architecture). Vetoes new entries only (never closes existing
positions - a materially bigger behavior change, left to the
trader/EA's own SL/TP handling) once either MaxDailyLossPct or
MaxDrawdownPct (new RISK_LIMIT_PCT_PRESET inputs, both default
disabled) is breached. Peak equity and the current broker day's
starting balance persist to a small local per-symbol-per-magic state
file - peak equity in particular must survive a restart to mean
anything, otherwise a restart would silently reset drawdown tracking.

New RISK_LIMIT_PCT_PRESET enum (2/3/4/5/8/10/15/20%) rather than
reusing PERCENTAGE_PRESETS, which steps by 10 starting at 10 - too
coarse for prop-firm-style limits (commonly single-digit daily loss,
~8-10% max drawdown). Compiled clean (MetaEditor, 0 errors/0
warnings).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 17:29:38 -04:00
AnimateDread
d75bd6d6a8 feat: add configurable news event proximity/impact as an NN input feature
Price, time, volume, and volatility were already trained-model input
features; the real economic calendar (already used for the live
NewsFilter veto) is now an optional one too, reusing
System/NewsRelevance.mqh's symbol-relevance logic from the prior fix.

New EnableNews/NewsFeatureWindowMinutes inputs gate two features per
bar: minutes-since and minutes-until the nearest symbol-relevant
calendar event, impact-weighted. Deliberately limited to proximity +
impact, not actual-vs-forecast deviation - release schedules are
public knowledge ahead of time (not lookahead bias to use for a
historical training bar), but a release's actual outcome is not.

Wired identically to the existing EnableVolume/EnableTime/EnableATR
toggles: InitIndicators() accounts for the +2 neuron count,
BufferTempDataCompute() appends the two feature values, PAI/CONV/LSTM
all wired in Warrior_EA.mq5. Compiled clean (MetaEditor, 0 errors/0
warnings).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 17:26:04 -04:00
AnimateDread
97cf7be556 chore: cleanup pass - dead code, stale wizard scaffolding, one edge-case guard
- Variables/Inputs.mqh: drop the dead commented-out HybridSignals input
  line; add a one-line note above the section-header input strings
  clarifying they're intentional MetaTrader GUI dividers (consumed by
  the terminal, not any MQL5 statement) so a future audit doesn't
  re-flag them as unwired.
- Signals/SignalSessionFilter.mqh: replace the never-filled-in MQL5
  Wizard template header (ProjectName/CompanyName placeholders) with
  this codebase's real header, matching every other Signals/*.mqh file.
- Signals/SignalNewsFilter.mqh: remove the stale NEWS_IMPACT template
  macro - it was only ever used as the constructor default, immediately
  overridden by the real NF_MinImpact input at wiring time.
- Expert/ExpertSignalAIBase.mqh: guard the SERIES_LASTBAR_DATE read in
  ScheduleTrainingIfNeeded() so a failed lookup (0) can't silently be
  read as "no new bar pending" and stall training/signal refresh.

Compiled clean (MetaEditor, 0 errors/0 warnings) after each change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 15:49:59 -04:00
AnimateDread
a9b497f615 fix(Inputs): shorten input comments that overflowed MQL5's 255-char identifier=value limit
trainingMode, ClassSampleWeight, FocalLossGamma, and SwingConfirmationBars'
inline display comments measured 214-306 chars combined with their
identifier - over MQL5's documented 255-char identifier=value ceiling for
the terminal/testing-agent exchange protocol, risking silent cropping in
the Inputs dialog. Trimmed to a max of 189 chars; full rationale for each
stays in the existing block comments above each input.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 15:44:57 -04:00
AnimateDread
6a687cda41 feat: add SGD+momentum optimizer and input-driven hyperparameters
Replace hardcoded lr and momentum with new input variables for Adam and
SGD+momentum. Add OpenCL kernel LSTM_UpdateWeightsMomentum alongside the
existing Adam kernel. Update comments and revert beta1 to book default 0.9.
2026-07-18 14:56:41 -04:00
AnimateDread
87ca08f21b refactor: tune optimizer momentum and integrate focal loss to reduce multi-era bias
- Lowered Adam momentum parameter b1 from 0.9 to 0.8, shortening the effective memory window (~5 steps) to reduce multi-era bias streaks observed in training runs.
- Added FOCAL_GAMMA_PRESET enum and corresponding member variable m_focalGamma to apply focal loss modulation (Lin et al. 2017) on top of class-balance weighting, targeting the same streak issue by downweighting already-confident examples.
- Updated comments to document the rationale and experimental nature of both changes.
2026-07-18 10:03:21 -04:00
AnimateDread
1a804fce28 feat: make class-balance oversampling multiplier configurable via input enum
Replace the hardcoded `MAX_CLASS_SAMPLE_WEIGHT` (3.0) with a tunable member variable `m_maxClassSampleWeight`, controlled by the new `CLASS_SAMPLE_WEIGHT_PRESET` input enum. This allows adjusting the ceiling on rare-class sample weights to prevent the previously observed anti-correlated Buy/Sell recall whipsaw (where a high multiplier caused one era's gradients to overwrite another class's separability). Default is CSW_15 (1.5x), which is gentler than the old 3.0x; lower values down to 1.0x disable rebalancing to train on raw label distribution, while higher values (up to 3.0x) converge faster but risk instability. This tuning can now be done without recompiling.
2026-07-18 02:01:06 -04:00
AnimateDread
457ae4acac refactor: Remove test holdout slice, add live signal alternation gate
- Removed TEST_HOLDOUT_PRESET enum and its associated member variables (m_testHoldoutPct, dTestForecast, m_testSamples) from ExpertSignalAIBase to simplify code and eliminate unused test slice logic.
- Added m_lastNonNeutralSignal member to track the last non-neutral signal during live inference, preventing LongCondition()/ShortCondition() from opening a second consecutive same-direction trade (which would be a false fire based on training patterns where valid reversals always alternate direction).
- This live-only mechanism does not affect historical training or backpropagation.
2026-07-17 23:55:10 -04:00