AI Architecture User Guide

In-depth reference for EAsiTrader's AI integration — covering the end-to-end architecture, prompt construction, response validation, and the decision-making process across all four AI modes (Monitor, Filter, Gate, Autonomous). Companion to the AI Settings section of the EAsiTrader User Guide. For preset file generation with AI configuration, see Preset Generation.

Table of Contents

  1. Introduction
  2. How the System Works End-to-End
  3. AI Modes In Depth
  4. The AI Assessment
  5. Decision History and Accuracy Feedback
  6. Multi-Provider Configuration
  7. Ask AI Chat Panel
  8. GroundedEvents vs Raw Data
  9. Writing Effective Strategy Prompts
  10. Trading Style In Detail
  11. Cost Management
  12. Error Handling and Resilience
  13. Trade Management Permissions Reference
  14. Closed Trade History
  15. Configuration Recipes
  16. Troubleshooting
  17. Appendix: JSON Response Schema

Introduction

This guide provides a comprehensive, in-depth reference for EAsiTrader's AI integration. It is intended as a companion to the AI Settings section of the main EAsiTrader User Guide, expanding on the architecture, decision-making process, and practical usage patterns that will help you get the most out of AI-assisted trading.

EAsiTrader's AI system connects your Expert Advisor to external large language models (such as OpenAI's GPT series, Anthropic's Claude, or Gemini) via the NTL API. The AI receives structured market data — OHLC prices, indicator readings, grounded market structure events, and optionally your open positions — and returns a structured JSON assessment. The EA then uses that assessment deterministically: filtering entries, modulating position sizes, or executing autonomous trade instructions, depending on your chosen mode.

The key design principle is deterministic safety: every AI output passes through local validation before it can affect trading. The AI advises; the EA decides.


How the System Works End-to-End

Understanding the full request-response lifecycle helps you configure the system effectively and troubleshoot issues when they arise.

1. Request Trigger

The EA decides when to call the AI based on your configured mode:

  • Periodic modes (Monitor Only, Filter Signals, Autonomous) check on each new bar whether a refresh is needed. A refresh is triggered when the previous assessment has expired (its valid_minutes window has elapsed), the configured refresh interval has passed, and any AI trigger script permits it.
  • GatedTrading mode calls the AI on-demand when your entry scripts generate a trade signal. The signal parameters (direction, entry price, stop loss, take profit, volume, risk/reward ratio) are cached and sent to the AI for evaluation. When management permissions are enabled, the AI also receives position and order data so it can issue management instructions alongside the gate evaluation.
  • Open positions in any mode with position management capability (Autonomous, or GatedTrading with management permissions) bypass the validity window and trading hours checks — if you have active trades and the refresh interval has elapsed, a new request is sent regardless of whether the previous assessment is still technically valid or whether the current time falls outside your configured Trading Hours. This ensures the AI can react to changing conditions around your positions. When no positions are open, AI requests respect your Trading Hours settings and are suppressed outside the configured window. Note: when the market itself is closed (e.g. weekends), no AI requests are sent regardless of position state — this is expected since no price movement or execution can occur until the market reopens, at which point the AI resumes automatically on the first new bar.

2. Prompt Construction

The prompt builder assembles two prompt components:

System Prompt — Defines the AI's role and behavioural rules. This varies by mode: a "technical market analyst" for advisory modes, a "trading signal gatekeeper" for GatedTrading mode, and an analyst with "full autonomy to manage trades" for Autonomous mode. Your Strategy Instructions are injected here under a dedicated "Trading Strategy" section. The Trading Style (Conservative, Moderate, Aggressive) is embedded as explicit behavioural guidance.

In GatedTrading mode with management permissions, the system prompt additionally includes a "Position Management" section instructing the AI that it may close, modify SL, or modify TP for existing positions, and that when no pending signal is present it should focus on position management only.

User Prompt — Contains the actual market data and context:

  • Market context — symbol and timeframe, current server time
  • OHLC price data for all configured timeframes (up to Max Bars depth)
  • Indicator data — GroundedEvents, raw buffer values, or both (controlled by AI Export Mode)
  • Candlestick chart images — PNG charts per timeframe when Include Candlestick Chart is enabled
  • Prior assessment summary — providing continuity between requests
  • Decision history with accuracy statistics from recent assessments (see Decision History below)
  • Required JSON response schema

When the AI has position management capability (Autonomous mode, or GatedTrading with management permissions), the prompt additionally includes:

  • Account data — balance and free margin
  • Open position details — ticket, direction, lots, entry price, current SL/TP, profit in points and R-multiple, bars open
  • Pending order details
  • Recently closed trades (if enabled)
  • Permissions block defining what actions the AI may take

In GatedTrading mode, the prompt also includes the pending entry signal with its direction, entry price, stop loss, take profit, stop size in points, reward in points, risk/reward ratio, volume, signal time, and order type (market, stop, or limit).

3. API Request

The assembled prompt is sent to your configured AI provider(s) via the NTL API.

Single-Provider Mode — When you configure a single provider in your Providers Config String, requests are sent directly to that provider. This is the simplest configuration and suitable for most use cases.

Multi-Provider Mode — When multiple providers are configured (separated by semicolons), the EA sends the same prompt to each provider in parallel via separate NTL API requests. The primary provider (the first in your config string, or the first alias matching the current market) exclusively drives all trading decisions — its assessment updates the dashboard, its instructions are routed to the trade engine, and its accuracy is tracked in decision history. Secondary providers run in parallel for monitoring: their assessments are stored and trigger alert notifications so you can compare how different models interpret the same market data, but they do not influence trading. There is no automated consensus or voting — the primary provider's response is used as-is.

Provider Aliases — Each provider configuration supports an alias field, enabling per-market provider routing. For example, you might configure provider=OpenAI,alias=EURUSD,model=gpt-4o,temperature=0.3 alongside provider=Anthropic,alias=GBPUSD,model=claude-sonnet-4-20250514,temperature=0.3. The EA selects the appropriate configuration for each market based on its alias. This lets you use different models, temperatures, or even different providers for different instruments — perhaps a more conservative model for volatile pairs and a more creative one for trending markets.

The Providers Config String specifies the provider, model, temperature, and optional alias as comma-separated key-value pairs. Multiple providers are separated by semicolons.

4. Response Parsing

When the AI responds, the response parser extracts the structured JSON and populates the assessment. The parser is lenient with missing fields, applying sensible defaults: regime defaults to "unknown", bias to "neutral", risk_mode to "normal", and confidence to 0.5. If regime_confidence or bias_confidence are omitted, they default to the overall confidence value. The valid_minutes field (defaulting to 5 minutes if omitted) determines how long the assessment remains active before the EA requests a refresh.

The parser also normalises all price values to the symbol's tick size and all volume values to broker limits, ensuring that AI-suggested levels are always valid for order submission.

For modes with position management capability (Autonomous and GatedTrading with management permissions), the parser also extracts the instructions array, where each instruction specifies an action, a ticket reference, price levels, sizing, confidence, validity window, and reasoning.

5. Validation and Execution

Before any assessment or instruction can affect trading, it passes through local validation:

  • Confidence threshold: The assessment's overall confidence must meet or exceed your Min Confidence Threshold (default 0.30). Below this, the assessment is ignored and safe defaults apply.
  • Validity window: The assessment must not have expired (current time must be before validUntil).
  • Status check: The assessment must be in Valid or Stale status — Default, Error, and Expired states are rejected. (See Context Staleness for the full assessment lifecycle.)

For trade instructions (in Autonomous and GatedTrading modes), the instruction validator performs additional checks: permission verification (is the requested action allowed by your permission flags?), confidence threshold per instruction, position limit checks, ticket validation for modify/close actions, risk limit enforcement (lot size and risk percentage), and pending order price validation (e.g., buy stop must be above current ask).

If an instruction exceeds risk limits, the validator reduces the size to the configured limit rather than rejecting it outright. This preserves the AI's directional intent at a safe scale.

6. Decision Recording

After each successful AI response is parsed, the EA records the assessment in the decision history (see Decision History section below). Before updating to the new assessment, the prior assessment's directional prediction is evaluated against actual price movement. This creates a rolling accuracy record that is persisted to disk and fed back into future prompts, enabling the AI to learn from its own recent performance within the session.

7. Assessment Application

Once validated, the assessment influences trading according to your mode (see AI Modes In Depth for full details):

  • Monitor Only: Assessment is displayed on the chart dashboard. No trading impact.
  • Filter Signals: When your entry scripts fire, the EA checks the assessment. If the AI's bias opposes the trade direction, the entry is filtered (blocked). If risk_mode is "avoid", the entry is blocked. If risk_mode is "reduced" or "minimal", the entry proceeds with a smaller position size.
  • GatedTrading: The AI evaluates the specific pending signal. Its bias and risk_mode are interpreted as Allow, Filter, or Reduce decisions. If management permissions are enabled, validated management instructions (close, modify SL/TP) are also forwarded to the trade execution layer.
  • Autonomous: Validated instructions are forwarded to the trade execution layer for processing.

AI Modes In Depth

Disabled

All AI features are off. No API calls are made, no AI-related processing occurs, and no AI data is displayed. Use this when you want purely script-driven or manual trading.

Monitor Only

The AI analyses the market periodically and its assessment is displayed on the chart, but it has zero impact on trade execution. This mode is ideal for several scenarios: evaluating AI quality before committing to automated use, comparing AI assessments against your own analysis to build confidence, running the AI alongside manual trading for a second opinion, and testing different provider/model configurations to find what works best for your instruments.

API calls occur on each new bar (subject to the refresh interval and the AI's own validity window), so costs accumulate steadily. Start with a moderate refresh interval (10–15 minutes) while evaluating.

Filter Signals

This is the most common production mode for traders who use EAsiScript entry signals. The AI maintains a periodic assessment of market conditions, and when your scripts generate a trade signal, the assessment is consulted before execution.

How filtering works: When a long entry signal fires, the EA checks whether the AI's bias allows long entries — this passes if the bias is Neutral, Bullish, or StrongBull. A Bearish or StrongBear bias blocks the long entry. The same logic applies in reverse for short entries. Additionally, the EA checks whether risk_mode is anything other than "avoid" — if the AI has set risk_mode to "avoid", all entries are blocked regardless of direction.

How risk modulation works: If the entry passes the directional filter, the EA applies two position sizing multipliers that are combined:

Bias multiplier — adjusts size based on alignment with the AI's directional view:

Bias Aligned with trade Against trade
Neutral 1.0× 1.0×
Bullish / Bearish 1.1× 0.75×
StrongBull / StrongBear 1.25× 0.5×

Risk multiplier — scales based on the AI's risk assessment:

Risk Mode Multiplier
Normal 1.0×
Reduced 0.5×
Minimal 0.25×
Aggressive 1.5×
Avoid 0.0× (blocks trade)

The two multipliers are combined. For example, a StrongBull bias with Reduced risk on a long entry produces 1.25 × 0.5 = 0.625× the normal position size.

Fail-open behaviour: If the AI is unavailable (no assessment received, assessment expired, or confidence below threshold), all multipliers default to 1.0 and all directional filters default to "allow". Your scripts continue trading normally without AI influence. This makes Filter Signals the safest active mode — AI unavailability never blocks trading.

GatedTrading

GatedTrading is designed for traders who want their scripts to control when trades are entered, but want AI oversight on whether each entry should proceed. Optionally, it also gives the AI the ability to actively manage open positions — trailing stops, adjusting targets, and closing trades — while keeping entry decisions script-driven.

The AI is called on-demand when your entry scripts generate a signal, not periodically. This minimises API calls and costs while still providing AI validation at decision points.

Entry Gating

When a signal fires, the EA caches all signal parameters (direction, entry price, SL, TP, volume, stop size in points, reward in points, risk/reward ratio, order type) and immediately submits an AI request. The signal is held in a pending state — no trade is executed until the AI responds.

The AI receives the full signal context in its prompt, including the entry direction, exact prices, stop size in points, reward in points, and the risk/reward ratio. It evaluates whether the signal should proceed based on market structure alignment, risk/reward acceptability, and current conditions.

The AI's standard assessment fields (bias, risk_mode) are mapped to a gate decision. If the bias aligns with the signal direction AND risk_mode is "normal" or "aggressive", the signal is allowed. If the bias opposes the signal direction OR risk_mode is "avoid", the signal is filtered (blocked). If risk_mode is "reduced" or "minimal", the signal is allowed with a reduced position size.

Position Management

When management permissions are enabled (Allow Close, Allow Modify SL, Allow Modify TP), GatedTrading gains a second capability. The AI receives open position data, pending order data, and the permissions block alongside the signal context. It can then issue management instructions — close, modify SL, modify TP, or modify both — for existing positions. The available actions in GatedTrading are deliberately limited to management: close, modify_sl, modify_tp, modify_both, and hold. Open and place-order actions are excluded because entries always come from scripts.

When no pending signal is present (for example, during periodic management-only requests triggered by open positions), the AI is instructed to focus on position management only. This means a GatedTrading setup with management permissions gives you script-controlled entries with AI-controlled trade management — combining the best of both approaches.

Timing Considerations

Gate signals use a short cooldown (5 seconds) rather than the full refresh interval, preventing rapid-fire requests while keeping response times practical. The cached signal expires after the configured timeout (default 100 seconds) — if the AI hasn't responded by then, the signal is discarded. This prevents stale signals from executing after market conditions have moved.

Fail-Closed Behaviour

Unlike Filter Signals, GatedTrading requires AI approval for entries. If the AI is unreachable, pending signals are discarded. This protects you from unvalidated entries but means API outages will prevent new entries. However, if management permissions are enabled, any existing positions continue to be managed via broker-enforced SL/TP until AI context is restored.

Autonomous

Full AI control over trading decisions. The AI can open positions, close positions, modify SL/TP levels, place pending orders, and cancel orders — all subject to the permission flags you configure.

This is the most powerful and the most dangerous mode. All permissions default to true, so when you first enable Autonomous mode, review each permission and disable any capabilities you do not want the AI to have.

Hybrid configurations: Autonomous mode supports partial permission sets. When AIAllowOpen is false, the AI cannot open market order positions — entry scripts execute directly for market orders instead. When AIAllowPlaceOrders is false, the AI cannot place pending orders — entry scripts handle pending order placement directly. This enables a common pattern where scripts control entries and the AI controls position management (close, modify SL/TP). In simulation mode, where no AI is available, all entry scripts execute directly regardless of permission settings.

One position per assessment: The AI is instructed to open at most one new position per assessment cycle. This prevents the AI from rapidly accumulating positions if it becomes overly bullish or bearish.

Instruction lifecycle: When the AI returns trade instructions, each instruction goes through this pipeline: the response parser extracts it from the JSON, the instruction validator checks it against permissions, confidence thresholds, position limits, risk limits, and price validity, and valid instructions are queued for execution by the trade engine. Each instruction carries its own confidence score, validity window, and reasoning text.

Conflict detection: The instruction set is validated for internal conflicts before any individual instruction is processed. For example, if the AI requests both opening a long position and opening a short position in the same assessment, the entire set is rejected as conflicting.

Risk override: If the AI requests a position size that exceeds your configured max lots or max risk percentage, the validator reduces the size to the limit rather than rejecting the instruction. This preserves the AI's directional intent while enforcing your risk rules.


The AI Assessment

Every AI response produces a structured assessment that drives all AI-influenced decisions. Understanding each field helps you interpret the dashboard display and tune your settings effectively.

Market Regime

The regime classifies current market behaviour. The AI chooses from seven options:

Regime Description Typical Implications
Trending Clear directional movement with higher highs/lows (uptrend) or lower highs/lows (downtrend) Trend-following strategies favoured; mean reversion risky
Ranging Horizontal consolidation between identifiable support and resistance Breakout strategies on watch; trend signals unreliable
Volatile High ATR, erratic price swings without clear direction Reduced position sizing recommended; wider stops needed
Quiet Low volatility, tight price ranges Breakout potential; current signals may be noise
Breakout Transitioning from range — price breaking through established levels Momentum entry opportunities; false breakout risk
Reversal Evidence of trend exhaustion and potential direction change Counter-trend setups forming; confirmation needed
Unknown Insufficient data or conflicting signals Safe default; AI falls back to neutral recommendations

Directional Bias

The AI's view on likely price direction:

Bias Effect on Longs Effect on Shorts Multiplier (Aligned) Multiplier (Against)
Neutral Allowed Allowed 1.0× 1.0×
Bullish Allowed Filtered 1.1× 0.75×
StrongBull Allowed Filtered 1.25× 0.5×
Bearish Filtered Allowed 0.75× (longs) 1.1× (shorts)
StrongBear Filtered Allowed 0.5× (longs) 1.25× (shorts)

"Filtered" means the entry is blocked in Filter/GatedTrading modes. In Monitor Only mode, the bias is displayed but not enforced. In Autonomous mode, the AI manages direction through its own instructions rather than through bias filtering.

Risk Mode

The AI's recommended risk posture:

Risk Mode Multiplier Trading Allowed? Typical Trigger
Normal 1.0× Yes Standard conditions, no unusual factors
Reduced 0.5× Yes (half size) Elevated uncertainty, conflicting signals, approaching key levels
Minimal 0.25× Yes (quarter size) High volatility, very unclear conditions
Aggressive 1.5× Yes (boosted) Strong trend with confirmation (used sparingly)
Avoid 0.0× No Extreme conditions where trading is inadvisable

Confidence Scores

The assessment contains three confidence values from the AI, each ranging from 0.0 to 1.0:

  • Overall — Aggregate confidence across all components. This is the score checked against your Min Confidence Threshold.
  • Regime — How certain the AI is about its market structure classification. Defaults to the overall value if not provided.
  • Bias — How certain the AI is about its directional view. Defaults to the overall value if not provided.

Interpreting confidence patterns:

  • High overall, low components: The AI is generally confident but hedging on specifics. Common in transitional markets.
  • Low overall, high regime: Clear market structure but uncertain about implications. Example: an obvious range where breakout direction is unclear.
  • High bias, low overall: Confident in direction but uncertain about overall conditions. Consider taking the directional signal but with conservative position size.
  • All scores below 0.3: The AI has insufficient data or deeply conflicting signals. The assessment will be ignored (below default threshold) and safe defaults apply.

Key Levels

The AI identifies support and resistance prices from visible price action and indicator data. These are returned as arrays of prices in the key_levels object. In Autonomous mode, the AI may use these levels for SL/TP placement on its trade instructions.

Referenced Events

When using GroundedEvents export mode, the AI is instructed to cite the specific event IDs that influenced its assessment. These IDs appear in the referenced_events array. This creates an audit trail: you can trace exactly which market structure events (Fair Value Gaps (FVGs), Change of Character (ChoCh) signals, liquidity sweeps) the AI relied upon for its conclusions.

Validity Window

The valid_minutes field (typically 15–60 minutes) tells the EA how long the AI expects its assessment to remain relevant. The EA converts this to a validUntil timestamp and uses it to avoid sending unnecessary refresh requests — until that time passes, no new periodic request is sent (saving API costs). When it expires, the next new bar triggers a refresh.

How the validity window affects the assessment lifecycle depends on the Use Valid Until setting (InpTradeTool_AIUseValidUntil, default: false). When off, assessments remain in Valid status until a new assessment replaces them — the valid_minutes value still controls request scheduling but does not cause the assessment to expire or become stale. When on, assessments transition to Stale once validUntil passes, and eventually to Expired if not refreshed. Enable this setting if you want the EA to discard outdated assessments automatically rather than continuing to act on them indefinitely.

The AI adapts this window based on conditions: in volatile markets, it may set a shorter validity (5–10 minutes) to ensure frequent updates; in quiet markets, it may extend to 30–60 minutes.

Example: Assessment Lifecycle With and Without Use Valid Until

Suppose the AI returns an assessment at 10:00 with valid_minutes: 30 and the refresh interval is 15 minutes.

Use Valid Until off (default):

Time Event Status
10:00 Assessment arrives Valid
10:15 Refresh interval fires — but validUntil (10:30) has not passed Valid (request skipped, saving API cost)
10:30 validUntil passes — next new bar triggers a refresh request Valid (still acting on old assessment until replacement arrives)
10:31 New assessment arrives Valid (replaces old)
If no replacement ever arrives Stays Valid indefinitely

Use Valid Until on:

Time Event Status
10:00 Assessment arrives Valid
10:15 Refresh interval fires — validUntil not yet passed Valid (request skipped)
10:30 validUntil passes — assessment transitions automatically Stale (EA treats with caution; triggers refresh)
10:31 New assessment arrives Valid (replaces stale)
10:30+ If no replacement arrives within the expiry grace period Expired (EA discards and reverts to safe defaults)

The key difference: with Use Valid Until off, an old assessment remains active forever until replaced. With it on, assessments have a defined shelf life — useful when you prefer the EA to stop acting on outdated analysis rather than continue indefinitely.


Decision History and Accuracy Feedback

EAsiTrader maintains a rolling history of AI decision records that creates a self-correcting feedback loop. Each assessment is recorded when it arrives, its prediction accuracy is evaluated when it is replaced, and the resulting history is fed back into future prompts so the AI can learn from its own recent performance.

How It Works

When a new AI assessment arrives, the EA performs three steps in sequence:

  1. Evaluate the prior assessment — Before replacing the old assessment, the EA compares the prior assessment's directional bias against actual price movement between the time the assessment was generated and the time it expired (or was replaced). A minimum movement threshold of 50 points filters out noise: if the bias was Bullish or StrongBull and price moved more than 50 points up, the bias is marked correct. If the bias was Bearish or StrongBear and price moved more than 50 points down, it is marked correct. Neutral bias is marked correct when the absolute price movement stays within 50 points, consistent with the expectation of no strong directional move.

  2. Record the new assessment — The new assessment's regime, bias, risk mode, confidence, and reasoning are captured in a decision record along with the current price and a sequence ID. As instructions from the assessment are later executed, failed, or rejected, those outcomes are also recorded against the same decision record.

  3. Build the history prompt — On the next AI request, the decision history assembles a structured prompt section containing the recent decision records (up to the last 10 assessments) and aggregated accuracy statistics. The accuracy stats include total assessments evaluated, the number where the directional bias was correct, and the average confidence when the AI was correct versus when it was wrong. Closed trade outcomes are cross-referenced by decision ID and shown inline under the assessment that opened them.

What the AI Sees

The AI receives a "Decision History" section in its user prompt that includes a summary of recent assessments with their outcomes and an accuracy report. For example, if the AI's bias has been correct on 6 out of the last 10 assessments with an average confidence of 0.72 when correct and 0.55 when wrong, that information is embedded in the prompt. This allows the AI to calibrate its confidence scores more accurately and recognise patterns in its own errors.

When a decision led to a trade that has since closed, the trade outcome (direction, profit in points, close reason) appears directly under that decision. This connects the AI's market read to the actual money outcome — a correct bias with a stopped-out trade is qualitatively different from a correct bias with a profitable trade.

The accuracy report also includes losing streak detection: if the last three or more consecutive bias predictions were wrong, the AI is explicitly warned and advised to consider reducing its confidence. This nudge helps prevent the AI from maintaining high confidence during periods when its model of the instrument is clearly miscalibrated.

Below is an abbreviated example of the kind of decision history the AI receives in its prompt:

## Decision History (last 10 assessments)

[5 bars ago] Regime=Trending, Bias=Bullish (conf 0.72), Risk=Normal
  Reasoning: Bullish ChoCh confirmed at 1.1025, price above 200 EMA.
  Instructions: OpenLong 0.10 SL=1.1020 TP=1.1100
  Outcome: +85.0 points, Bias CORRECT
  Trade: LONG +32.0 pts, sl_hit

[2 bars ago] Regime=Trending, Bias=Bullish (conf 0.68), Risk=Reduced
  Reasoning: Trend intact but approaching resistance at 1.1085.
  Instructions: hold
  Outcome: +22.0 points, Bias WRONG

[Current] Regime=Ranging, Bias=Neutral (conf 0.55), Risk=Normal
  Reasoning: Price consolidating between 1.1050-1.1085.
  Instructions: hold
  Outcome: pending

## Assessment Accuracy (last 2 evaluated)
Bias: 1/2 correct (50%)
Avg confidence when correct: 0.72, when wrong: 0.68

Persistence

Decision history is persisted to per-market .jsonl files (one per symbol/timeframe combination, e.g., EURUSD_H1.jsonl) under the strategy's Tester\history\ or Live\<accountNumber>\history\ folder. The format is append-only JSON Lines: every assessment, prior-outcome evaluation, and instruction-outcome update appends a full snapshot of the affected record on its own line, so the history survives EA restarts. On load, records are deduplicated by sequence ID (last write wins) and the in-memory ring keeps the most recent 10 by default. When the file grows beyond 10× that limit it is compacted automatically.

Trade Outcome Linking

When the AI opens a position, the position ticket is mapped to the current decision's sequence ID. When that position later closes, the closed-trade snapshot carries the decision ID, enabling the prompt builder to show the trade result inline under the originating decision. This closes the loop between "what did the AI predict?" and "did the resulting trade make money?" — the most actionable form of feedback for improving trade quality.

Why This Matters

Without decision history, each AI request is stateless — the AI has no knowledge of whether its previous assessments were accurate. With decision history enabled, the AI can: adjust confidence levels based on recent accuracy (lowering confidence if it has been frequently wrong), recognise when its regime classifications are consistently incorrect for the current instrument, adapt its approach if a particular bias direction keeps failing, correlate instruction outcomes with assessment quality, and see whether its trades were profitable or stopped out.

This feedback loop is automatic — there are no settings to configure. It operates in all active AI modes (Monitor Only, Filter Signals, GatedTrading, and Autonomous).


Multi-Provider Configuration

EAsiTrader supports configuring multiple AI providers

Single vs Multi-Provider

Single provider is the simplest setup. You configure one provider in your Providers Config String and all AI requests go to that provider. This is sufficient for most traders and keeps costs predictable.

Multiple providers can be configured by separating provider definitions with semicolons in the config string.

Provider Config String Format

Each provider is defined as comma-separated key-value pairs:

provider=OpenAI,model=gpt-4o,temperature=0.3

Multiple providers are separated by semicolons:

provider=OpenAI,model=gpt-4o,temperature=0.3;provider=Anthropic,model=claude-sonnet-4-20250514,temperature=0.3

Available keys include provider (OpenAI, Anthropic, Gemini), model (the specific model identifier), temperature (0.0–1.0), alias (for per-market routing), and maxOutputTokens (the maximum number of tokens in the AI's response — if omitted, the provider's default applies; increase this if you find responses are being truncated, particularly in Autonomous mode with complex instruction sets).

Per-Market Provider Aliases

The alias field enables different provider configurations for different markets. When you include an alias, the EA routes requests from that market to the matching provider configuration:

provider=OpenAI,alias=EURUSD,model=gpt-4o,temperature=0.2;provider=OpenAI,alias=XAUUSD,model=gpt-4o,temperature=0.4

In this example, EURUSD requests use a lower temperature (more deterministic) while XAUUSD uses a higher temperature (more creative). You could also use entirely different providers or models per market.

If no alias matches the current market, the EA falls back to the first provider configuration without an alias, or the first configuration overall.

Cost Considerations

Multi-provider mode multiplies your API costs by the number of active providers. If you configure three providers, each request costs roughly 3× what a single provider would cost. Only the primary provider drives trading — the additional cost covers monitoring and comparison. Use multi-provider mode selectively, and consider whether the monitoring value justifies the extra spend.


Ask AI Chat Panel

EAsiTrader includes a built-in interactive AI chat panel that lets you have ad-hoc conversations with your configured AI provider directly from within the EA. This is separate from the automated assessment system — it's a tool for on-demand analysis, strategy discussion, and data exploration.

Accessing the Panel

The Ask AI panel is located in the Tester tab as a sub-tab. It provides a prompt editor where you can type questions or analysis requests, a response display area, and controls for managing conversations.

Data Attachments

The panel's most powerful feature is the ability to attach live trading data to your prompts. Ten attachment toggles let you include any combination of:

Attachment Description
OHLC Current OHLC price data exported from the chart's series
Indicators Refreshes all indicators and exports their current state
News News URLs configured in your AI settings for server-side ingestion
Stats Your statistics log file with performance metrics
Trades Your trades log file with historical trade data
EAsiScript User guide URLs for the scripting system
Presets Your common and market-specific preset configuration files
Code Interpreter Enables the AI to execute code for data analysis
Images Enables image generation (16:9 aspect ratio)
Chart Candlestick chart PNG image of current price action for visual AI analysis

Each attachment is one-shot per send — toggling OHLC on attaches the current OHLC data to the next message only. This keeps token usage controlled.

Use Cases

Strategy development: Attach your OHLC and Indicators data, then ask the AI to analyse current market structure and suggest entry criteria. The AI sees the same data it would receive in automated mode, so its analysis is grounded in actual market conditions.

Performance review: Attach your Stats and Trades logs, then ask the AI to identify patterns in your winning and losing trades, suggest improvements, or highlight time-of-day performance differences.

Configuration tuning: Attach your Presets file and ask the AI to review your settings and suggest optimisations based on your trading goals.

Ad-hoc analysis: Ask questions about specific market conditions, test strategy ideas, or get a second opinion on a trade setup — all with access to your live data.

Conversation Management

The panel supports full conversation threading — follow-up messages maintain context from previous exchanges. Use the Reset button to clear the conversation and start fresh. The Load/Save functions let you persist prompts to .txt files in the AI Prompts folder and save responses to the AI Results folder, building a library of reusable prompts and analysis results.

Output files generated by the AI (when Code Interpreter is enabled) are automatically downloaded and saved to your AI Results folder.


GroundedEvents vs Raw Data

This is one of the most important configuration decisions for AI quality and cost.

What Are GroundedEvents?

Grounded events are pre-computed, validated market structure facts exported by EAsiTrader's indicators. Each event has a unique ID, a type (FVG, ChoCh, liquidity sweep, etc.), associated price levels, and a timestamp. The indicator has already done the computational work of identifying these structures — the AI receives them as established facts, not raw data to interpret.

The AI prompt explicitly instructs: "Do not infer structural events (FVG, ChoCh, sweeps) beyond what is listed in grounded_events." This prevents hallucination — the AI cannot claim to see a Fair Value Gap that doesn't exist in the data.

When the AI references a grounded event in its reasoning, it includes the event ID in the referenced_events array. This creates verifiable, auditable analysis.

Important: Only enabled indicators export GroundedEvents and raw buffer data to AI requests. In the GUI, enable an indicator by ticking the checkbox alongside its name in the Indicators List. In a preset file, prefix the indicator's creation string with + (e.g. InpTradeTool_CustomIndicator6=+NTL\ChoCh(...).ex5,...). An indicator that is not enabled will not contribute any data to the AI, even if AI Mode is active and the indicator is listed in the Custom Indicators section. This applies to all export modes — GroundedEvents Only, Raw Only, and Both.

What Is Raw Indicator Data?

Raw data consists of timestamped buffer values from each enabled indicator, provided as structured JSON (inline mode) or CSV (file mode). The AI receives the actual numerical readings and must interpret their meaning itself.

This gives the AI maximum flexibility — it can spot patterns across indicator interactions that GroundedEvents don't capture — but it uses significantly more tokens and is more susceptible to misinterpretation. The AI might, for example, see a price level and incorrectly infer it represents a Fair Value Gap when the indicator data doesn't support that conclusion.

Recommendations

Production trading: Use GroundedEvents Only (default). This gives the lowest token cost, prevents hallucination, and produces the most consistent and verifiable assessments. The AI focuses on validated market structure rather than attempting to re-derive it from raw numbers.

Development and debugging: Use Both to compare what the AI derives from raw data against the GroundedEvents. This helps you validate that your indicators are exporting meaningful events and that the AI is interpreting them correctly.

Advanced usage: Use Raw Only when you want the AI to have full interpretive freedom, perhaps with indicators that don't export GroundedEvents, or when you're exploring whether the AI can find patterns your GroundedEvents don't capture. Be aware of higher costs and potential inconsistency.

Cost Impact

Grounded events are compact — typically a small JSON array of 10 or fewer events with IDs, types, and price levels. Raw buffer data for the same indicators might include hundreds of timestamped rows across multiple buffers. The token difference can be 5–10× or more, directly affecting API cost per request.

Candlestick Chart Images

When Include Candlestick Chart is enabled (InpTradeTool_AIIncludeCandlestickChart, default: false), the EA renders candlestick charts as PNG images and attaches them to the AI prompt alongside the structured data. One image is generated for each configured timeframe — for example, if your Timeframes setting includes M15 and H1, the AI receives two chart images in addition to the OHLC data.

This gives the AI a visual representation of price action, which can improve pattern recognition for setups that are easier to identify visually (double tops, head-and-shoulders, channel boundaries) than from raw numbers alone. The images are generated locally by the EA and sent via the NTL API to providers that support image inputs.

Cost impact: Each chart image adds to the request token count. The cost varies by provider and model — image tokens are typically more expensive than text tokens. Enable this feature selectively, and consider using it alongside GroundedEvents Only mode to keep the text token count low while adding visual context.


Writing Effective Strategy Prompts

The Strategy Instructions setting is your direct communication channel to the AI. Text you enter here is injected verbatim into the AI's system prompt under a "Trading Strategy" section. This is the single most impactful configuration option for tailoring AI behaviour to your trading approach.

Principles of Effective Strategy Prompts

Be specific and actionable. The AI performs best when given concrete criteria rather than vague guidance. Compare:

Weak: "Trade with the trend."

Strong: "Only assign bullish bias when price is above the 200-bar EMA and the most recent ChoCh event confirms a bullish break of structure. Only assign bearish bias when price is below the 200-bar EMA and the most recent ChoCh confirms bearish BOS."

Reference the data the AI actually receives. The AI can only work with what's in its prompt. If you reference indicators or concepts that aren't in the exported data, the AI will either ignore them or hallucinate. Stick to OHLC price action concepts, the specific grounded event types your indicators export, and the raw indicator buffers included in the data.

Use the AI's output vocabulary. Frame instructions in terms of the fields the AI controls: regime, bias, risk_mode, confidence, key_levels, and (in Autonomous or GatedTrading with management permissions) instructions. For example:

"Set risk_mode to 'reduced' during the first 30 minutes after London open (08:00-08:30 server time) due to high spread and erratic price action."

"When a bullish FVG event exists within 20 points of current price, increase bias confidence by 0.1 if the bias is already bullish."

Keep it concise. The strategy instructions become part of every AI request. Excessively long instructions consume tokens on every call. Aim for clear, direct statements rather than lengthy explanations. A well-crafted prompt of 5–15 lines is typically more effective than a rambling paragraph.

Strategy Prompt Templates

Trend-Following Strategy

Focus on trend continuation setups only.
Assign bullish/bearish bias only when the most recent ChoCh event confirms the direction.
Set risk_mode to 'reduced' during the first and last hour of the trading session.
Prefer 'normal' risk_mode when bias aligns with the higher timeframe trend visible in multi-TF OHLC data.
Set risk_mode to 'avoid' when regime is 'ranging' — wait for breakout confirmation.
Key levels should prioritise recent swing highs and lows from ChoCh and LP events.

Mean Reversion / Range Strategy

Focus on range-bound setups.
Set regime to 'ranging' when price has tested both support and resistance from LP events within the last 50 bars.
Assign bullish bias only near identified support levels (within 15 points).
Assign bearish bias only near identified resistance levels (within 15 points).
Set risk_mode to 'avoid' when regime shifts to 'breakout' or 'trending'.
Keep valid_minutes short (5-10) when price is near key levels — reassess frequently.

News-Aware Configuration

If current server time is within 15 minutes of a major session open (London 08:00, New York 13:00 server time), set risk_mode to at least 'reduced'.
After session opens, if volatility normalises within 3-5 bars, return to 'normal' risk_mode.
Avoid setting 'aggressive' risk_mode during the London/New York overlap (13:00-16:00 server time).

Conservative Capital Preservation

Never set risk_mode to 'aggressive'.
Default bias to 'neutral' unless confidence exceeds 0.7.
Set risk_mode to 'reduced' whenever regime is 'volatile'.
Set risk_mode to 'avoid' when regime is 'unknown'.
Use tight valid_minutes (5-10) to ensure frequent reassessment.
Key levels should include only levels with at least two touches visible in OHLC data.

Aggressive Momentum

Favour 'aggressive' risk_mode when regime is 'trending' and bias confidence exceeds 0.75.
Set strong bias (strongbull/strongbear) when momentum is confirmed by multiple timeframes.
Allow 'normal' risk_mode even when regime is 'volatile' if bias is clear.
Extend valid_minutes (20-45) during clean trends to reduce API calls.
Only use 'avoid' when data is genuinely insufficient.

Autonomous Mode — SMC-Based

Trade Smart Money Concepts: FVG entries, ChoCh confirmations, liquidity sweeps.
Open positions only after a ChoCh confirms direction AND an unfilled FVG provides an entry zone.
Set SL behind the FVG zone boundary (the high for shorts, the low for longs).
Set TP at the next LP (liquidity pool) level visible in GroundedEvents.
If no clear FVG entry exists near current price, return an empty instructions array.
Trail stops to break-even once position reaches 1R profit.
Close positions early if a ChoCh event fires in the opposite direction.

Common Mistakes to Avoid

Don't reference external information. Statements like "Consider NFP data this Friday" are meaningless to the AI — it has no knowledge of economic calendars unless you provide news URLs. The AI's data grounding rules explicitly forbid referencing information not in the prompt.

Don't override the response format. Instructions like "respond in a different JSON format" will cause parsing failures. The EA expects the exact schema defined in the prompt.

Don't set contradictory rules. "Always be aggressive" combined with "never risk more than minimal" will confuse the AI. It will either ignore one instruction or produce inconsistent assessments.

Don't micromanage every bar. The AI is designed to provide a stable view across several bars. Instructions that change behaviour bar-by-bar undermine the assessment stability and increase the likelihood of whipsaw recommendations.

Don't make instructions too long. Every token in your strategy instructions is sent on every request. A 500-word strategy prompt at 15-minute intervals adds up to significant token usage over time.


Trading Style In Detail

The Trading Style setting (Conservative, Moderate, Aggressive) applies across all active modes — not just Autonomous. It is communicated to the AI in the system prompt as explicit behavioural guidance that shapes how the AI applies your strategy instructions and interprets market conditions.

Conservative

In Filter/GatedTrading modes, the AI uses stricter thresholds. It sets "avoid" for signals with confidence below 0.7 or unclear setups, and prefers "reduced" risk_mode for marginal signals. It will block more entries and produce smaller positions overall.

In Autonomous mode, the AI employs selective entry criteria, sets tighter initial stops (1–2R), targets modest gains (1.5–2R), locks in profits early by trailing stops aggressively, and prefers single position management over pyramiding.

Moderate (Default)

Balanced approach. The AI uses "avoid" only for clearly adverse conditions, applies standard confidence thresholds, and allows trades through when conditions are ambiguous but not clearly negative.

Aggressive

The AI favours allowing trades. In Filter/GatedTrading modes, it only blocks signals with strongly opposing evidence and prefers "normal" or "aggressive" risk_mode when the signal has any merit.

In Autonomous mode, the AI accepts wider stops (2–4R), targets larger moves (3–5R), has higher drawdown tolerance, and may build positions in strong trends.

Style Comparison: Same Market, Different Outcomes

Consider EURUSD on H1: price is above the 200 EMA but approaching a resistance zone at 1.1080 with a bullish ChoCh confirmed at 1.1025. A long entry signal fires at 1.1045.

Aspect Conservative Moderate Aggressive
Bias Bullish (conf 0.65) Bullish (conf 0.72) StrongBull (conf 0.80)
Risk Mode Reduced Normal Normal
Filter decision Allow at 0.5× size (reduced risk near resistance) Allow at 1.0× size Allow at 1.25× size (StrongBull aligned)
Autonomous SL 1.1030 (15 pips — tight, ~1R) 1.1020 (25 pips — moderate, ~1.5R) 1.1010 (35 pips — wide, ~2R)
Autonomous TP 1.1070 (25 pips — 1.7R) 1.1085 (40 pips — 1.6R) 1.1120 (75 pips — 2.1R)
Trail behaviour Trail to break-even at 1R Trail to break-even at 1.5R Hold for extended move

The same bullish setup produces a cautious half-size trade under Conservative, a standard trade under Moderate, and a larger-than-normal trade with wider targets under Aggressive.


Cost Management

AI API calls cost money. Understanding the cost drivers helps you balance analysis quality against budget.

Cost Drivers

Request frequency is the primary cost factor. Periodic modes (Monitor Only, Filter Signals, Autonomous) call the AI on every bar that passes the refresh interval check. On a 5-minute chart with a 5-minute refresh interval, that's up to 12 calls per hour. On a 1-minute chart with no refresh interval, it could be 60 calls per hour.

Token volume per request depends on Max Bars (more history = more tokens), number of configured timeframes (each adds a full OHLC dataset), export mode (Raw data is 5–10× larger than GroundedEvents), number of open positions and orders (in modes with position management), strategy instruction length, and decision history prompt content (compact, but adds some overhead per request).

Multi-provider configuration multiplies per-request costs by the number of active providers. Three providers means roughly 3× the cost per assessment cycle.

The AI's own validity window provides natural cost optimisation. When the AI sets valid_minutes to 30, no new request is made for 30 minutes even if the refresh interval is lower. The AI adapts this based on conditions — volatile markets get shorter windows, quiet markets get longer ones.

Cost Optimisation Strategies

Use GatedTrading mode when you have reliable entry scripts. The AI is only called when a signal fires (plus any management requests for open positions), which might be a few times per day rather than every few minutes. This can reduce costs by 90% or more compared to periodic modes.

Increase the Refresh Interval to set a floor on request frequency. A 15-minute interval limits you to 4 calls per hour maximum, regardless of timeframe.

Use GroundedEvents Only for export mode. Raw indicator data can be 5–10× larger in tokens. Grounded events are compact and produce better results.

Reduce Max Bars to 100–200 unless your strategy requires deep history. 300 bars of 5-minute data is 25 hours of history — more than enough for most intraday strategies.

Limit additional timeframes. Each timeframe in the Timeframes setting adds a complete OHLC dataset. Two additional timeframes triples your OHLC data volume. Use only the timeframes that genuinely inform your analysis.

Use single-provider mode unless you specifically want to compare models. Multi-provider mode adds cost without directly improving trading decisions — it is a monitoring tool, not a confidence booster.

Monitor token usage via the inputTokens and outputTokens fields in the assessment metadata. These are tracked per request and cumulatively across the session, and can help you identify unexpectedly expensive configurations.


Error Handling and Resilience

The AI system is designed to degrade gracefully when things go wrong.

Error Throttling

If an API call fails, the EA applies exponential backoff. The first retry is delayed by 60 seconds, and subsequent failures double the delay up to a maximum of 1 hour. This prevents hammering a failing API endpoint with rapid retries, which would waste money and potentially trigger rate limits.

Errors are classified into ten distinct types, each with appropriate backoff behaviour:

Error Type Behaviour
Network Transient — standard exponential backoff
Timeout Transient — standard exponential backoff
Server Transient — standard exponential backoff
RateLimit Respects the server's Retry-After header
InvalidRequest Indicates a malformed request or bad parameters — logged and retried with backoff
ModelUnavailable The requested model is temporarily unavailable — retried with backoff
Auth Fatal — invalid API key or licence problem. Halts AI requests with a 24-hour lockout
QuotaExceeded Fatal — usage quota exhausted. Halts AI requests with a 24-hour lockout
Unknown Unclassified error — treated as transient with standard backoff

Fatal errors (Auth and QuotaExceeded) halt AI requests entirely until manually cleared. To resume after fixing the underlying issue, use the "Clear Fatal Error" function.

The backoff calculation caps at 10 consecutive errors. Once 10 consecutive failures are reached, the backoff delay stays at its maximum (1 hour for transient errors) until a successful request resets the counter.

Example — Auth error scenario: You accidentally paste an expired API key into your provider configuration. The first AI request fails with an Auth error. The EA immediately classifies this as fatal, locks out all AI requests, and logs a warning. No further requests are attempted — there is no backoff or retry because the error is unrecoverable without intervention. You notice the warning on the chart dashboard, correct the API key in your settings, and use "Clear Fatal Error" to resume. The EA immediately attempts a new request with the corrected key.

Example — Network error scenario: Your internet connection drops briefly. The first request fails with a Network error. The EA waits 60 seconds, then retries. If the connection is still down, it waits 120 seconds, then 240 seconds, doubling each time up to 1 hour. After 10 consecutive failures the delay remains at 1 hour. When connectivity is restored, the next successful request resets the counter and normal operation resumes.

Context Staleness

Assessments transition through a lifecycle: Default → Valid → Stale → Expired. A Valid assessment is fresh and actively used. A Stale assessment has passed its validity window but is still usable (with caution) if it meets the confidence threshold. An Expired assessment is too old and is treated as unavailable.

Mode-Specific Resilience

Filter Signals is fail-open: if the AI is unavailable, entries proceed normally with default (1.0×) multipliers. This is the safest behaviour for most traders.

GatedTrading is fail-closed for entries: if the AI is unreachable, pending entry signals are discarded. This protects you from unvalidated entries but means API outages stop new trades from opening. Existing positions retain their broker-enforced SL/TP and are not affected by AI unavailability.

Autonomous mode falls back to broker-enforced SL/TP management only when AI context is unavailable. Existing positions retain their stop loss and take profit levels as placed by the broker, but no new trades are opened and no active management occurs until AI context is restored.


Trade Management Permissions Reference

Each permission independently controls a category of trade actions. All default to true. These permissions apply to Autonomous mode and, for management actions, to GatedTrading mode.

Permission Actions Controlled Autonomous GatedTrading Considerations
Allow Open Open Long, Open Short Enables the AI to initiate new market positions. The AI respects max positions and risk limits. Not available in GatedTrading (entries come from scripts).
Allow Close Close position Enables early exits based on AI analysis. The AI can mark closes as only_if_profitable.
Allow Modify SL Modify SL, Modify Both* Enables stop-loss trailing and adjustment. Useful for active trade management.
Allow Modify TP Modify TP, Modify Both* Enables take-profit adjustment for trend extension or early profit-taking.
Allow Place Orders Buy Stop, Sell Stop, Buy Limit, Sell Limit Enables pending order placement at key levels. Not available in GatedTrading.
Allow Cancel Orders Cancel Order Enables removal of pending orders that no longer align with the AI's view.

*Modify Both (adjusting SL and TP simultaneously) requires both Allow Modify SL and Allow Modify TP.

Starting out (minimal risk): Enable only Allow Modify SL. The AI can trail stops on positions opened by your scripts but cannot open or close trades. This lets you evaluate AI trade management quality with minimal risk. This works in both Autonomous and GatedTrading modes.

Active management (GatedTrading): Use GatedTrading mode with Allow Close and Allow Modify SL enabled. Your scripts control entries via the gate evaluation, and the AI manages the resulting positions — trailing stops and closing early when conditions deteriorate. Note: GatedTrading can block or delay entries — the AI must approve each signal before it executes (fail-closed). This is desirable when you want AI oversight on entry quality, but unsuitable for time-sensitive entries like breakout strategies.

Active management (Autonomous, management only): Use Autonomous mode with Allow Close and Allow Modify SL enabled, but Allow Open and Allow Place Orders disabled. Entry scripts execute unconditionally without AI involvement. The AI runs periodically and can only manage existing positions — trailing stops and closing early when conditions deteriorate. This is the right choice when entries must execute immediately and the AI's role is purely position management.

Full autonomy: Enable Allow Open, Allow Close, Allow Modify SL, and Allow Modify TP. The AI has complete trade lifecycle control. Add Allow Place Orders if your strategy benefits from pending orders at key levels.


Closed Trade History

When Allow Closed History is enabled, the AI receives up to 5 recently closed trades from the current trading session. This applies to any mode where the AI has position management capability — Autonomous mode, and GatedTrading with management permissions enabled. Each trade includes its direction, entry and exit prices, profit in points, R-multiple, duration in bars, and close reason (SL hit, TP hit, manual close, AI-instructed, expired, or margin call).

This feedback loop enables the AI to avoid re-entry traps at levels where stops were recently hit, adjust stop placement based on repeated stop-out patterns, factor session P&L context into risk decisions (such as becoming more cautious after a string of losses), and confirm trend direction from profitable trade patterns.

If the market session start cannot be determined (e.g., market is closed), the system falls back to trades from the last 12 hours.


Configuration Recipes

The recipes below show AI Section settings in isolation. Remember that any indicators whose GroundedEvents or raw data the AI should receive must be enabled with the + prefix in the Custom Indicators section of your preset file. See the full preset file examples in the EAsiTrader User Guide for complete configurations.

Recipe 1: Low-Cost Signal Validation

Goal: Validate entry signals with AI while minimising API costs.

Setting Value Rationale
AI Mode GatedTrading (3) AI called only when signals fire
Export Mode GroundedEvents Only (0) Minimal token usage
Max Bars 150 Sufficient context, low cost
Timeframes (empty) Chart timeframe only
Trading Style Moderate (1) Balanced filtering
Min Confidence 0.30 Default threshold
Strategy Instructions Focus on trend alignment and key level proximity.

Corresponding .set file AI Section:

;
; Section AI
;
InpTradeTool_AIMode=3 // GatedTrading
InpTradeTool_AIProvidersConfigString=provider=Gemini,model=gemini-3-pro-preview,temperature=0.2
InpTradeTool_AIStrategyInstructions=Focus on trend alignment and key level proximity.
InpTradeTool_AITradingStyle=1 // Moderate
InpTradeTool_AIUrls=
InpTradeTool_AITimeframes=
InpTradeTool_AIMaxHistorySizeInBars=150
InpTradeTool_AIRefreshIntervalMinutes=15
InpTradeTool_AIMinConfidenceThreshold=0.3000
InpTradeTool_AIExportMode=0 // GroundedEvents Only
InpTradeTool_AIGateSignalTimeoutInSeconds=100
InpTradeTool_AIAllowOpen=false
InpTradeTool_AIAllowClose=false
InpTradeTool_AIAllowModifySL=false
InpTradeTool_AIAllowModifyTP=false
InpTradeTool_AIAllowPlaceOrders=false
InpTradeTool_AIAllowCancelOrders=false
InpTradeTool_AIIncludeClosedHistory=true
InpTradeTool_AIIncludeCandlestickChart=false
InpTradeTool_AIUseValidUntil=false

Note: In GatedTrading mode, AIAllowOpen and AIAllowPlaceOrders must be false — entries always come from scripts. This recipe uses no management permissions, so all AIAllow* flags are false.

Recipe 2: AI-Enhanced Trend Following

Goal: Use AI to filter entries and modulate risk for a trend-following strategy.

Setting Value Rationale
AI Mode Filter Signals (2) Continuous assessment, filters entries
Export Mode GroundedEvents Only (0) Focus on ChoCh and structure events
Max Bars 300 Deeper history for trend identification
Timeframes H1,H4 Multi-timeframe trend alignment
Refresh Interval 10 Balance cost and freshness
Trading Style Moderate (1) Standard filtering
Min Confidence 0.40 Slightly higher threshold for quality
Strategy Instructions See Trend-Following template above

Recipe 3: Gated Script Entries with AI Trade Management

Goal: Scripts control entries with AI oversight on whether each entry should proceed, plus AI management of the resulting positions.

Important: GatedTrading holds each script signal in a pending state until the AI responds — the AI can block entries that conflict with its assessment, and signals are discarded if the AI doesn't respond within the timeout (fail-closed). This is appropriate when you want the AI to validate entries before execution. If your entry signals are time-sensitive (e.g., breakout strategies where a missed signal means a missed trade for the day), use Recipe 4 instead.

Setting Value Rationale
AI Mode GatedTrading (3) Gate entries + manage positions
Export Mode GroundedEvents Only (0) Cost efficiency
Max Bars 200 Sufficient context for management
Timeframes M15 One higher timeframe for context
Trading Style Moderate (1) Balanced approach
Allow Close true AI can exit early
Allow Modify SL true AI can trail stops
Allow Modify TP false Let TP levels stand
Allow Closed History true Learn from recent trades
Min Confidence 0.40 Moderate bar for management decisions
Strategy Instructions Trail stops to break-even at 1R. Close early if ChoCh fires against position direction.

Corresponding .set file AI Section:

;
; Section AI
;
InpTradeTool_AIMode=3 // GatedTrading
InpTradeTool_AIProvidersConfigString=provider=Gemini,model=gemini-3-pro-preview,temperature=0.2
InpTradeTool_AIStrategyInstructions=Trail stops to break-even at 1R.\nClose early if ChoCh fires against position direction.
InpTradeTool_AITradingStyle=1 // Moderate
InpTradeTool_AIUrls=
InpTradeTool_AITimeframes=M15
InpTradeTool_AIMaxHistorySizeInBars=200
InpTradeTool_AIRefreshIntervalMinutes=15
InpTradeTool_AIMinConfidenceThreshold=0.4000
InpTradeTool_AIExportMode=0 // GroundedEvents Only
InpTradeTool_AIGateSignalTimeoutInSeconds=100
InpTradeTool_AIAllowOpen=false
InpTradeTool_AIAllowClose=true
InpTradeTool_AIAllowModifySL=true
InpTradeTool_AIAllowModifyTP=false
InpTradeTool_AIAllowPlaceOrders=false
InpTradeTool_AIAllowCancelOrders=false
InpTradeTool_AIIncludeClosedHistory=true
InpTradeTool_AIIncludeCandlestickChart=false
InpTradeTool_AIUseValidUntil=false

Note: AIAllowOpen and AIAllowPlaceOrders are false (GatedTrading — entries from scripts only). AIAllowClose and AIAllowModifySL are true for active position management. Strategy Instructions use literal \n as the newline separator between lines.

Recipe 4: Ungated Script Entries with AI Trade Management

Goal: Scripts control entries unconditionally (no AI gate delay or rejection), AI manages the resulting positions.

This is the right choice when your entry signals are time-sensitive and must execute immediately — for example, opening range breakout strategies where the signal fires once and a missed entry means a missed trade for the day. The AI's role is purely position management after entry: trailing stops, closing early when conditions deteriorate, and adjusting SL levels.

Setting Value Rationale
AI Mode Autonomous (4) Periodic AI with no entry gating
Export Mode GroundedEvents Only (0) Cost efficiency
Max Bars 200 Sufficient context for management
Timeframes M15 One higher timeframe for context
Trading Style Moderate (1) Balanced approach
Refresh Interval 15 Regular position checks
Allow Open false Entries come from scripts only
Allow Close true AI can exit early
Allow Modify SL true AI can trail stops
Allow Modify TP false Let TP levels stand
Allow Place Orders false No AI-initiated orders
Allow Closed History true Learn from recent trades
Min Confidence 0.40 Moderate bar for management decisions
Strategy Instructions Trail stops to break-even at 1R. Close early if ChoCh fires against position direction.

Corresponding .set file AI Section:

;
; Section AI
;
InpTradeTool_AIMode=4 // Autonomous
InpTradeTool_AIProvidersConfigString=provider=Gemini,model=gemini-3-pro-preview,temperature=0.2
InpTradeTool_AIStrategyInstructions=Trail stops to break-even at 1R.\nClose early if ChoCh fires against position direction.
InpTradeTool_AITradingStyle=1 // Moderate
InpTradeTool_AIUrls=
InpTradeTool_AITimeframes=M15
InpTradeTool_AIMaxHistorySizeInBars=200
InpTradeTool_AIRefreshIntervalMinutes=15
InpTradeTool_AIMinConfidenceThreshold=0.4000
InpTradeTool_AIExportMode=0 // GroundedEvents Only
InpTradeTool_AIGateSignalTimeoutInSeconds=100
InpTradeTool_AIAllowOpen=false
InpTradeTool_AIAllowClose=true
InpTradeTool_AIAllowModifySL=true
InpTradeTool_AIAllowModifyTP=false
InpTradeTool_AIAllowPlaceOrders=false
InpTradeTool_AIAllowCancelOrders=false
InpTradeTool_AIIncludeClosedHistory=true
InpTradeTool_AIUseValidUntil=false

Note: AIAllowOpen and AIAllowPlaceOrders are false — the AI cannot initiate trades or place orders. Entry scripts execute without AI involvement. The AI runs periodically and can only manage existing positions via AIAllowClose and AIAllowModifySL. Strategy Instructions use literal \n as the newline separator between lines.

Recipe 5: Autonomous Scalping

Goal: AI-driven scalping on a 5-minute chart.

Setting Value Rationale
AI Mode Autonomous (4) Full AI control
Export Mode GroundedEvents Only (0) Speed and cost efficiency
Max Bars 100 Short-term focus
Timeframes M15 One higher timeframe for context
Refresh Interval 5 Frequent updates for active trading
Trading Style Moderate (1) Balanced aggression
Allow Open true Can initiate trades
Allow Close true Can exit early
Allow Modify SL true Can trail stops
Allow Modify TP false Let TP levels stand
Allow Closed History true Learn from recent trades
Min Confidence 0.50 Higher bar for autonomous action
Strategy Instructions See Autonomous Mode — SMC-Based template above

Corresponding .set file AI Section:

;
; Section AI
;
InpTradeTool_AIMode=4 // Autonomous
InpTradeTool_AIProvidersConfigString=provider=Gemini,model=gemini-3-pro-preview,temperature=0.2
InpTradeTool_AIStrategyInstructions=Trade Smart Money Concepts: FVG entries, ChoCh confirmations, liquidity sweeps.\nOpen only after ChoCh confirms direction AND an unfilled FVG provides entry zone.\nSet SL behind FVG boundary. Set TP at the next LP level.\nReturn empty instructions if no clear setup exists.\nTrail stops to break-even at 1R. Close early on opposite ChoCh.\nNever use aggressive risk_mode. Use reduced when regime is volatile.
InpTradeTool_AITradingStyle=1 // Moderate
InpTradeTool_AIUrls=
InpTradeTool_AITimeframes=M15
InpTradeTool_AIMaxHistorySizeInBars=100
InpTradeTool_AIRefreshIntervalMinutes=5
InpTradeTool_AIMinConfidenceThreshold=0.5000
InpTradeTool_AIExportMode=0 // GroundedEvents Only
InpTradeTool_AIGateSignalTimeoutInSeconds=100
InpTradeTool_AIAllowOpen=true
InpTradeTool_AIAllowClose=true
InpTradeTool_AIAllowModifySL=true
InpTradeTool_AIAllowModifyTP=false
InpTradeTool_AIAllowPlaceOrders=false
InpTradeTool_AIAllowCancelOrders=false
InpTradeTool_AIIncludeClosedHistory=true
InpTradeTool_AIIncludeCandlestickChart=false
InpTradeTool_AIUseValidUntil=false

Note: In Autonomous mode, at least AIAllowOpen or AIAllowClose must be true. AIStrategyInstructions must be non-empty — it provides the AI with the decision-making framework. When AIAllowOpen and AIAllowPlaceOrders are both true, entry scripts are not needed since the AI controls all trade entries. When either is false, entry scripts must be defined to handle the order types the AI lacks permission to create — scripts execute directly for those order types.

Recipe 6: Conservative Portfolio Overlay

Goal: AI as a safety net across multiple charts.

Setting Value Rationale
AI Mode Filter Signals (2) Protective filtering
Export Mode GroundedEvents Only (0) Cost-efficient
Max Bars 200 Moderate context
Timeframes (empty) Chart timeframe only (cost control across many charts)
Refresh Interval 15 Low frequency across multiple instances
Trading Style Conservative (0) Maximum protection
Min Confidence 0.30 Default
Strategy Instructions See Conservative Capital Preservation template above

Recipe 7: Multi-Provider Autonomous Trading

Goal: Autonomous trading with a secondary provider for monitoring and comparison.

Setting Value Rationale
AI Mode Autonomous (4) Full AI control
Export Mode GroundedEvents Only (0) Cost efficiency (multi-provider already multiplies cost)
Max Bars 200 Moderate context
Timeframes M15 One higher timeframe for context
Refresh Interval 10 Moderate frequency
Trading Style Moderate (1) Standard approach
Providers Config provider=OpenAI,model=gpt-4o,temperature=0.3;provider=Anthropic,model=claude-sonnet-4-20250514,temperature=0.3 OpenAI as primary, Anthropic for monitoring
Allow Open true Can initiate trades
Allow Close true Can exit early
Allow Modify SL true Can trail stops
Allow Modify TP true Full management
Allow Closed History true Learn from recent trades
Min Confidence 0.60 Higher bar for autonomous action
Strategy Instructions See Autonomous Mode — SMC-Based template above

Corresponding .set file AI Section:

;
; Section AI
;
InpTradeTool_AIMode=4 // Autonomous
InpTradeTool_AIProvidersConfigString=provider=OpenAI,model=gpt-4o,temperature=0.3;provider=Anthropic,model=claude-sonnet-4-20250514,temperature=0.3
InpTradeTool_AIStrategyInstructions=Trade Smart Money Concepts: FVG entries, ChoCh confirmations, liquidity sweeps.\nOpen only after ChoCh confirms direction AND an unfilled FVG provides entry zone.\nSet SL behind FVG boundary. Set TP at the next LP level.\nReturn empty instructions if no clear setup exists.\nTrail stops to break-even at 1R. Close early on opposite ChoCh.\nNever use aggressive risk_mode. Use reduced when regime is volatile.
InpTradeTool_AITradingStyle=1 // Moderate
InpTradeTool_AIUrls=
InpTradeTool_AITimeframes=M15
InpTradeTool_AIMaxHistorySizeInBars=200
InpTradeTool_AIRefreshIntervalMinutes=10
InpTradeTool_AIMinConfidenceThreshold=0.6000
InpTradeTool_AIExportMode=0 // GroundedEvents Only
InpTradeTool_AIGateSignalTimeoutInSeconds=100
InpTradeTool_AIAllowOpen=true
InpTradeTool_AIAllowClose=true
InpTradeTool_AIAllowModifySL=true
InpTradeTool_AIAllowModifyTP=true
InpTradeTool_AIAllowPlaceOrders=false
InpTradeTool_AIAllowCancelOrders=false
InpTradeTool_AIIncludeClosedHistory=true
InpTradeTool_AIIncludeCandlestickChart=false
InpTradeTool_AIUseValidUntil=false

Note: Multi-provider mode multiplies API costs by the number of providers (2× in this example). Only OpenAI (the first provider) drives trading decisions — Anthropic runs in parallel for monitoring. Compare their assessments via alert notifications to evaluate whether a different primary provider might perform better for your instruments.

Generating Complete AI Preset Files

The recipes above show the AI Section settings in isolation. To generate a complete, working .set preset file that includes all sections (Header, Scripts, Risk Management, Position Management, etc.), provide the Preset Generation Guide to your AI session and describe your strategy. The Preset Generation Guide is a single, machine-actionable reference containing the Defaults.set template, all setting definitions, indicator creation strings, EAsiScript patterns, AI mode configuration, validation rules, and complete preset file examples for every AI mode.

For example prompts showing how to describe strategies to AI, see Learn EAsiScript Guide → AI Prompt Examples.


Troubleshooting

AI Not Making Requests

Check that AI Mode is not Disabled, a provider config string is set, the refresh interval hasn't locked out requests (check throttle status), no fatal error is active (clear it if so), the market is open (the session check must pass), and in GatedTrading mode, that entry scripts are configured and generating signals.

Assessments Ignored (No Effect on Trading)

Check that the assessment's overall confidence meets your Min Confidence Threshold, the assessment hasn't expired (check data age vs valid_minutes), AI Mode is Filter Signals or GatedTrading (Monitor Only doesn't affect trades), and in Filter mode, that entry scripts are actually generating signals for the AI to filter.

High API Costs

Reduce Max Bars, remove unnecessary additional timeframes, switch to GroundedEvents Only export mode, increase the Refresh Interval, consider switching to GatedTrading mode if you have reliable entry scripts, shorten your Strategy Instructions, and if using multi-provider mode, consider whether single-provider is sufficient for your current mode.

AI Assessments Seem Wrong

Verify that the indicators you expect the AI to use are enabled (prefixed with + in the preset file, or checkbox ticked in the GUI) — disabled indicators do not export GroundedEvents or raw data to AI requests. Switch export mode to "Both" temporarily to compare GroundedEvents against raw data interpretation. Check that your indicators are exporting meaningful GroundedEvents (indicators that don't export events contribute nothing in GroundedEvents Only mode). Review the AI's reasoning field and referenced_events to understand its logic. Check the decision history — if the AI's recent accuracy is low, it may be receiving insufficient or misleading data for the current instrument. Try adjusting the temperature in your provider config (lower = more consistent, higher = more varied). Experiment with different models — newer models often produce better structured analysis.

Autonomous or GatedTrading Instructions Rejected

Check the Experts log for validation messages. Common causes include insufficient permissions (the requested action isn't enabled), confidence below threshold on the individual instruction, position limit exceeded (already at max_positions), risk limit exceeded (instruction wanted more lots or risk than allowed), invalid pending order prices (buy stop must be above ask, etc.), conflicting instructions in the same set, and in GatedTrading, attempting to use open or place-order actions (which are restricted to Autonomous mode).

Decision History Issues

Decision history files (.jsonl) are persisted automatically. If you suspect corrupted history is affecting AI quality, you can delete the relevant .jsonl file from your strategy's Tester\history\ (or Live\<accountNumber>\history\) folder — the EA will start fresh with no history on the next assessment cycle.


Appendix: JSON Response Schema

This is the complete JSON schema the AI must return. Understanding it helps when reviewing logs or crafting strategy prompts.

{
  "regime": "trending | ranging | volatile | quiet | breakout | reversal | unknown",
  "bias": "bullish | bearish | neutral | strongbull | strongbear",
  "risk_mode": "normal | reduced | minimal | aggressive | avoid",
  "confidence": 0.0-1.0,
  "regime_confidence": 0.0-1.0,
  "bias_confidence": 0.0-1.0,
  "valid_minutes": 15,
  "reasoning": "Brief explanation of assessment rationale",
  "key_levels": {
    "resistance": [1.1050, 1.1075],
    "support": [1.1020, 1.0995]
  },
  "warnings": ["Array of concerns or caveats"],
  "referenced_events": ["EVT_001", "EVT_003"],
  "instructions": [
    {
      "action": "open_long | open_short | close | modify_sl | modify_tp | modify_both | place_buy_stop | place_sell_stop | place_buy_limit | place_sell_limit | cancel_order | hold",
      "ticket": 0,
      "entry_price": 0.0,
      "sl_price": 1.1020,
      "tp_price": 1.1080,
      "lots": 0.0,
      "risk_percent": 1.0,
      "confidence": 0.75,
      "only_if_profitable": false,
      "valid_minutes": 5,
      "reasoning": "Explanation for this specific action"
    }
  ]
}

Notes on specific fields:

  • confidence, regime_confidence, and bias_confidence are the three confidence values the AI provides. If regime_confidence or bias_confidence are omitted, they default to the overall confidence value. There is no risk_confidence field in the schema — internally, risk confidence defaults to the overall value.
  • valid_minutes at the assessment level controls how long before the EA requests a refresh. At the instruction level, it controls how long the instruction remains executable.
  • ticket of 0 means new position (for open actions). For modify, close, and cancel actions, this must reference an existing position or order ticket.
  • entry_price of 0 means market price (for open actions). For pending orders, this is the trigger price and is required.
  • lots of 0 means the EA should calculate position size based on risk_percent and the stop loss distance.
  • risk_percent of 0 means use the EA's configured default risk per trade. When the AI specifies a non-zero risk_percent, it is capped by your configured Max Risk Per Trade setting — if the AI requests 2.0% but your limit is 1.0%, the validator reduces it to 1.0%, preserving the AI's trade intent at your risk limit.
  • The instructions array is present in Autonomous mode (full action set) and in GatedTrading mode with management permissions (limited to close, modify_sl, modify_tp, modify_both, and hold). In all other modes, it is omitted.
  • referenced_events should list only IDs from the grounded_events data provided in the prompt. The AI is instructed not to fabricate event references.
  • All prices in the response are normalised to the symbol's tick size, and all volume values are normalised to broker limits, ensuring AI-suggested values are always valid for order submission.

Example response — EURUSD H1, Autonomous mode with Allow Open and Allow Modify SL enabled:

{
  "regime": "trending",
  "bias": "bullish",
  "risk_mode": "normal",
  "confidence": 0.78,
  "regime_confidence": 0.82,
  "bias_confidence": 0.74,
  "valid_minutes": 30,
  "reasoning": "Price is above the 200-bar EMA with a confirmed bullish ChoCh at 1.1025. An unfilled FVG between 1.1030-1.1042 provides a potential entry zone. Higher timeframe H4 also shows bullish structure.",
  "key_levels": {
    "resistance": [1.1085, 1.1120],
    "support": [1.1030, 1.1005]
  },
  "warnings": ["London session close approaching — volatility may drop"],
  "referenced_events": ["CC_B_014", "FV_B_027"],
  "instructions": [
    {
      "action": "open_long",
      "ticket": 0,
      "entry_price": 0,
      "sl_price": 1.1020,
      "tp_price": 1.1085,
      "lots": 0,
      "risk_percent": 1.0,
      "confidence": 0.76,
      "only_if_profitable": false,
      "valid_minutes": 10,
      "reasoning": "Long entry near FVG zone with SL below ChoCh level. TP at first resistance."
    }
  ]
}

In this example the AI identifies a trending, bullish market with 0.78 overall confidence. It references two GroundedEvents (a ChoCh and an FVG) and issues a single open-long instruction. The entry_price of 0 means execute at market price; lots of 0 means calculate position size from the 1.0% risk_percent and the stop distance. The assessment is valid for 30 minutes, but the instruction itself expires after 10 minutes.

Rev: 28.03.2026 Preset generation — reference PresetGeneration.md with download URL Rev: 08.04.2026 — Decision history now append-only JSONL under Tester\history\ / Live\<accountNumber>\history\ (folder-per-type layout); replaces old .hist JSON ring-buffer description Rev: 11.04.2026 — Decision history ring buffer 5→10, pips→points naming, trade outcome linking via ticket map, losing streak threshold 2→3, reasoning truncation re-enabled at 200 chars