﻿
# Preset Generation User Guide

Machine-actionable reference for generating EAsiTrader preset (.set) files. Contains the Defaults.set template, all setting definitions, indicator creation strings, EAsiScript pattern examples, AI mode configuration, complete preset file examples for each AI mode, and layered preset generation for incremental strategy testing. Intended as the sole reference an AI model needs to construct valid preset files without accessing source code. Source of truth: the four human-facing user guides ([EAsiTrader](EAsiTrader.md), [EAsiScript](EAsiScript.md), [Learn EAsiScript](LearnEAsiScript.md), [AI Architecture](AIArchitecture.md)).

**Download this file and provide it to your AI session:** `https://www.northentradinglabs.com/api/v1/guides/PresetGeneration.md`

---

## 1. Preset File Rules

### File Format

All sections and settings from Defaults.set must appear in exact order. Use default values for unused settings. Never add sections or settings not in the template.

Construction method: always copy the Defaults.set template verbatim, then modify only the values that differ from defaults. Never reconstruct the file from memory or generate sections independently — this causes omitted settings, reordered sections, and invented keys. The template is the structural skeleton; the strategy only changes values within it.

Section headers use the format: blank `;` line, `; Section Name`, blank `;` line.

All settings begin with `InpTradeTool_`. Use exact names from Defaults.set.

Markets: comma-separated symbol-timeframe pairs, e.g. `InpTradeTool_Market=EURUSD H1,GBPUSD H1`.

Custom indicators: numbered sequentially (`CustomIndicator0`, `CustomIndicator1`, ...). Prefix with `+` when referenced in scripts, AI Strategy Instructions, or AI Trigger Script. Indicators not referenced may be omitted.

Units and flags must include inline comments where applicable (e.g. `=0 // TradeToolStopUnits_ATR`).

Settings not applicable to the strategy use defaults or placeholders (`0`, `false`, `// Not used`).

Backtesting and Optimisation section always present even if unused.

No spaces around `=`. Consistent comment alignment.

### AI Mode Constraints

| Mode | Value | Entry Scripts | AIAllowOpen | AIAllowPlaceOrders | AIStrategyInstructions | Other AIAllow* |
|------|-------|--------|------|------|---------|---------|
| Disabled | 0 | Optional | Ignored | Ignored | Ignored | Ignored |
| Monitor Only | 1 | Optional | Ignored | Ignored | Optional | Ignored |
| Filter Signals | 2 | **Required** | Ignored | Ignored | Optional | Ignored |
| Gated Trading | 3 | **Required** | **Must be false** | **Must be false** | Optional | May enable Close/ModifySL/ModifyTP/CancelOrders |
| Autonomous | 4 | Empty when AI opens trades; present when AI manages only (AllowOpen=false) | **At least Open or Close must be true** | Optional | **Required (non-empty)** | Enable as needed |

For runtime behaviour of each mode (request triggers, fail behaviour), see [AI Modes](#ai-modes).

### Encoding Rules

- `AIStrategyInstructions`: use literal `\n` for newlines. Never use literal line breaks.
- `AIUrls`: percent-encode URLs (`https://` → `https%3A%2F%2F`, `/` → `%2F`). Separate multiple URLs with `%0A`.

### AI Trigger Script

`ScriptAITrigger` is an optional EAsiScript expression evaluated before each AI request. Non-zero = permit, zero = suppress. Evaluated only when: refresh interval elapsed AND assessment expired AND no open positions. Indicators referenced in the script must be enabled with `+` prefix.

---

### Preset Validation Checklist

1. All sections from Defaults.set present in correct order.
2. All settings within each section present — defaults for unused.
3. Setting names match exactly — all begin with `InpTradeTool_`.
4. `AIMode` value (0–4) matches intended mode.
5. AI permission flags comply with mode constraints above.
6. `AIStrategyInstructions` non-empty when AIMode=4.
7. `AIStrategyInstructions` uses literal `\n` for newlines.
8. `AIUrls` percent-encoded with `%0A` separating URLs.
9. Entry scripts defined for modes 2 and 3; typically empty for mode 4.
10. Indicators referenced in scripts, AI Strategy Instructions or AI Trigger Script enabled with `+`.
11. AI permission flags and entry script requirements match the [AI Mode Constraints](#ai-mode-constraints) table.

### Settings Quick Reference

#### Stop/Exit/BE Units

| Value | Constant | Meaning |
|-------|---|---------|
| 0 | ATR | Value × 14-period ATR |
| 1 | HH/LL | Highest high / lowest low over N bars |
| 2 | Points | Distance in points |
| 3 | Risk (R) | Value × initial SL distance |

SL supports units 0–2. TP supports units 0–3. BE supports units 0–3. Trailing SL supports units 0–3.

#### Trading Rules Enums

- RefreshMode: 0=None, 1=Every Bar, 2=Every Tick
- AllowedTradeTypes: 0=BuysAndSells, 1=BuysOnly, 2=SellsOnly
- AIMode: see [AI Modes](#ai-modes)
- AITradingStyle: 0=Conservative, 1=Moderate, 2=Aggressive
- AIExportMode: 0=GroundedEventsOnly, 1=RawOnly, 2=Both

#### Time Management

- `StartOfDayTime` / `EndOfDayTime`: restrict when **new positions** may be opened (HH:MM, server time). When both are `00:00`, no restriction applies (24-hour trading). Open positions are not affected — trailing stops, exit scripts, and AI position management continue running outside this window whenever the broker market session is open.
- `ClosePositionAtEndOfDay` / `ClosePositionAtEndOfWeek`: force-close open positions at EndOfDayTime / Friday close.
- `CloseOrderAtEndOfDay` / `CloseOrderAtEndOfWeek`: cancel pending orders at EndOfDayTime / Friday close.
- `ClosePositionTimeOffsetInSeconds` / `CloseOrderTimeOffsetInSeconds`: close positions/orders this many seconds before EndOfDayTime.

#### AITimeframes

Comma-separated list of all timeframes the AI receives OHLC and indicator data for. The chart timeframe is NOT automatically included — it must be listed explicitly. Empty = chart timeframe only. Example: `M5,H1` on an M5 chart gives the AI both M5 and H1 data.

#### User Variables

Format: `InpTradeTool_UserVAR[n]=[value];[range]` where n=0–99.
Range format: comma-separated explicit values only. The shorthand `start-end+increment` notation is reserved for the GUI and must not be used in preset files. Example: `InpTradeTool_UserVAR0=0.60;0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90` (not `0.50-0.90+0.05`).
Prefix range with `~` to disable during optimisation.
UserVARs are referenced in scripts as `VAR0`, `VAR1`, etc.

#### Overrides Preset File

Filename: `{SYMBOL}_{TIMEFRAME}.set` (e.g. `EURUSD_H1.set`), stored in subfolder named after main preset. Contains only settings that differ from the main preset. Optional — omit if no overrides needed.

---

## 2. Defaults.set Template

```ini
;
; Section Header
;
InpTradeTool_Name=Defaults
InpTradeTool_Description=
InpTradeTool_Author=
InpTradeTool_Comments=
InpTradeTool_PresetFile=Defaults.set
InpTradeTool_Market=
InpTradeTool_AIGenerated=
InpTradeTool_AIModel=
InpTradeTool_CategoryType=0
InpTradeTool_SettingsVersion=1.000
InpTradeTool_ChartImages=
;
; Section Scripts
;
InpTradeTool_ScriptLongEntry=
InpTradeTool_ScriptLongInitialStop=
InpTradeTool_ScriptLongTrailingStop=
InpTradeTool_ScriptLongLots=
InpTradeTool_ScriptLongTakeProfit=
InpTradeTool_ScriptLongBreakeven=
InpTradeTool_ScriptLongExit=
InpTradeTool_ScriptShortEntry=
InpTradeTool_ScriptShortInitialStop=
InpTradeTool_ScriptShortTrailingStop=
InpTradeTool_ScriptShortLots=
InpTradeTool_ScriptShortTakeProfit=
InpTradeTool_ScriptShortBreakeven=
InpTradeTool_ScriptShortExit=
InpTradeTool_ScriptAITrigger=
;
; Section Risk Management
;
InpTradeTool_MaxRiskPerTradeInPercent=1.00
InpTradeTool_MaxRiskPerTradeInMoney=0.00
InpTradeTool_MaxLossMarketAsPercentageOfBalance=0.00
InpTradeTool_MaxLossAccountAsPercentageOfBalance=0.00
InpTradeTool_TrailMaxLoss=false
InpTradeTool_DeviationInPoints=0
;
; Section Position Management
;
InpTradeTool_MaxLots=0.00
InpTradeTool_MaxOpenPositionsMarket=1
InpTradeTool_MaxOpenPositionsSymbol=0
InpTradeTool_MaxOpenPositionsAccount=0
InpTradeTool_MaxOpenPositionsHour=0
InpTradeTool_MaxOpenPositionsDay=0
InpTradeTool_MaxOpenPositionsWeek=0
InpTradeTool_MaxTradesPerUnitTime=0
InpTradeTool_MaxTradesUnitTimeInSeconds=0
InpTradeTool_MinTradeIntervalInSeconds=0
InpTradeTool_MagicNumber=123456789
;
; Section Trading Rules
;
InpTradeTool_AutoTradeEnabled=true
InpTradeTool_AutoTradeRefreshMode=1 // SeriesRefreshMode_EveryBar
InpTradeTool_AllowedTradeTypes=0 // AllowedTradeTypes_BuysAndSells
;
; Section Time Management
;
InpTradeTool_StartOfDayTime=00:00
InpTradeTool_EndOfDayTime=00:00
InpTradeTool_ClosePositionTimeOffsetInSeconds=0
InpTradeTool_CloseOrderTimeOffsetInSeconds=0
InpTradeTool_ClosePositionAtEndOfDay=false
InpTradeTool_ClosePositionAtEndOfWeek=false
InpTradeTool_CloseOrderAtEndOfDay=false
InpTradeTool_CloseOrderAtEndOfWeek=false
;
; Section Stop Management
;
InpTradeTool_InitialStopValue=3.00
InpTradeTool_InitialStopValueUnits=0 // TradeToolStopUnits_ATR
InpTradeTool_TrailingStopValue=0.00
InpTradeTool_TrailingStopValueUnits=0 // TradeToolStopUnits_ATR
InpTradeTool_TrailingStopValueEnabled=false
InpTradeTool_EnableTrailingStopAfterBreakeven=true
InpTradeTool_EnableTrailingStopAfterProfitInPercent=0.0000
InpTradeTool_UseSoftSLs=false
InpTradeTool_MinSLTPPriceChangeUnitsInPoints=10
;
; Section Exit Management
;
InpTradeTool_TakeProfitStopValue=2.00
InpTradeTool_TakeProfitStopValueUnits=3 // TradeToolStopUnits_R
InpTradeTool_TakeProfitStopValueEnabled=true
InpTradeTool_UseSoftTPs=false
InpTradeTool_BreakevenStopValue=1.00
InpTradeTool_BreakevenStopValueUnits=3 // TradeToolStopUnits_R
InpTradeTool_BreakevenStopValueEnabled=true
InpTradeTool_MaxGainMarketAsPercentageOfBalance=0.00
InpTradeTool_MaxGainAccountAsPercentageOfBalance=0.00
InpTradeTool_MinProfitInPoints=0
InpTradeTool_MinProfitInPointsTimeInSeconds=0
;
; Section Custom Indicators
;
InpTradeTool_CustomIndicator0=NTL\ABH(1,14,3).ex5,0,1
InpTradeTool_CustomIndicator1=NTL\ADX(1,14).ex5,0,1,2,3
InpTradeTool_CustomIndicator2=NTL\ADXW(1,14).ex5,0,1,2,3
InpTradeTool_CustomIndicator3=NTL\ATR(1,14).ex5,0
InpTradeTool_CustomIndicator4=NTL\AutoFib(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,0,4,8,50,100,0.0,10,250,45,'0.35,1',0,0,3,14).ex5,0,1,2,3,4,5
InpTradeTool_CustomIndicator5=NTL\BB(1,20,2.0).ex5,0,1,2,3
InpTradeTool_CustomIndicator6=NTL\ChoCh(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,55,3,6,55,100,0.0,8,250,45,'0.35,1',0,0,3,14,500).ex5,0,1,2,3,4,5,6,7,8
InpTradeTool_CustomIndicator7=NTL\FVG(1,0,400,0.1,0.0,0.4,3.0,0.1,3,14,0,0,0.0).ex5,0,1,2,3,4,5,6
InpTradeTool_CustomIndicator8=NTL\HLines(1,0,800,15,'S2;R2',35,0.0,0.5,100).ex5,0,1
InpTradeTool_CustomIndicator9=NTL\JCP(1).ex5,0,1
InpTradeTool_CustomIndicator10=NTL\Keltner(1,20,1,2.25).ex5,0,1,2,3
InpTradeTool_CustomIndicator11=NTL\LP(1,0,800,1,6,7,400,14,7.0,2.5,0.0,0,0.0,0.0,0.0,10,80,2).ex5,0,1,2,3,4,5,6,7,8,9,10,11,12
InpTradeTool_CustomIndicator12=NTL\MA(1,50,1,200,1).ex5,0,1,2
InpTradeTool_CustomIndicator13=NTL\MACD(1,12,26,9).ex5,0,4
InpTradeTool_CustomIndicator14=NTL\Markets(1).ex5,0
InpTradeTool_CustomIndicator15=NTL\OsMA(1,12,26,9).ex5,0,1
InpTradeTool_CustomIndicator16=NTL\PL(1,16408,4).ex5,0
InpTradeTool_CustomIndicator17=NTL\PP(1).ex5,0,1,2,3,4,5,6,7,8
InpTradeTool_CustomIndicator18=NTL\PSAR(1,0.02,0.2).ex5,0,1
InpTradeTool_CustomIndicator19=NTL\RSI(1,14,1,70,30).ex5,0,1
InpTradeTool_CustomIndicator20=NTL\Scalper(1,10000,0.7,10000,0.3,0.6,10000,0.5,0.3,10000,0.7,10,1,5,0.0,5000,1,1,19,24).ex5,0,1,2,3,4,5,6
InpTradeTool_CustomIndicator21=NTL\Stochastic(1,5,3,3,80,20).ex5,0,1,2
InpTradeTool_CustomIndicator22=NTL\ST(1,13,1.5).ex5,0,1
InpTradeTool_CustomIndicator23=NTL\TLines(1,2.5,'S2;R2',25,2,15,2,1.0,400,50,800,0.1,0.1,100).ex5,0,1,2,3,4,5,6,7,8
InpTradeTool_CustomIndicator24=NTL\TSI(1,13,21,8,25,-25,1).ex5,0,1,2
;
; Section User Variables
;
;
; Section Backtesting & Optimisation
;
InpTradeTool_TesterAccountType=0 // AccountType_Standard
InpTradeTool_TesterCommissionPerLot=0.00
InpTradeTool_TesterSpreadSchedule=
InpTradeTool_TesterSpreadScheduleEnabled=false
InpTradeTool_TesterSpreadApplyToMid=true
InpTradeTool_TesterStartingBalance=10000
InpTradeTool_TesterStartDate=0 // 1970.01.01 00:00
InpTradeTool_TesterEndDate=0 // 1970.01.01 00:00
InpTradeTool_TesterLeverage=100
InpTradeTool_OptimiseEnabled=false
InpTradeTool_OptimisePerformanceMetric1=31 // PerformanceMetric_PerformanceIndex
InpTradeTool_OptimisePerformanceMetric2=41 // PerformanceMetric_TotalProfit
InpTradeTool_OptimiseFrequencyInDays=0
InpTradeTool_OptimiseDayOfWeek=6
InpTradeTool_OptimiseHourOfDay=0
InpTradeTool_OptimiseLookbackInDays=0
InpTradeTool_OptimiseLastDate=0 // 1970.01.01 00:00
InpTradeTool_OptimiseNextDate=0 // 1970.01.01 00:00
;
; Section Compliance
;
InpTradeTool_ComplianceProfitTargetRate=0.10
InpTradeTool_ComplianceOverallLossLimitRate=0.10
InpTradeTool_ComplianceDailyLossLimitRate=0.05
InpTradeTool_ComplianceIntradayDDLimitRate=0.05
InpTradeTool_ComplianceMinTradingDays=4
InpTradeTool_ComplianceProfitTargetWarnRate=0.75
InpTradeTool_ComplianceOverallLossWarnRate=0.90
InpTradeTool_ComplianceDailyLossWarnRate=0.90
InpTradeTool_ComplianceIntradayDDWarnRate=0.90
InpTradeTool_ComplianceLogLevel=1 // Breaches Only
InpTradeTool_ComplianceTimeZone=1 // EU Central
InpTradeTool_ComplianceBoundaryHour=0
InpTradeTool_ComplianceBoundaryMinute=0
InpTradeTool_ComplianceBoundarySecond=0
;
; Section AI
;
InpTradeTool_AIMode=0
InpTradeTool_AIProvidersConfigString=provider=Gemini,model=gemini-3-pro-preview,temperature=0.2
InpTradeTool_AIStrategyInstructions=
InpTradeTool_AITradingStyle=1
InpTradeTool_AIUrls=https%3A%2F%2Fwww.dailyforex.com%2Frss%2Fforexnews.xml%0Ahttps%3A%2F%2Fwww.fxstreet.com%2Frss%0Ahttps%3A%2F%2Fstockmarketwatch.com%2Flive%2Fstock-market-today%0Ahttps%3A%2F%2Finvestinglive.com%2F%0Ahttps%3A%2F%2Fwww.fxstreet.com%2Frss%2Fanalysis
InpTradeTool_AITimeframes=
InpTradeTool_AIMaxHistorySizeInBars=300
InpTradeTool_AIRefreshIntervalMinutes=5
InpTradeTool_AIMinConfidenceThreshold=0.3000
InpTradeTool_AIUseValidUntil=false
InpTradeTool_AIExportMode=0
InpTradeTool_AIGateSignalTimeoutInSeconds=100
InpTradeTool_AIAllowOpen=true
InpTradeTool_AIAllowClose=true
InpTradeTool_AIAllowModifySL=true
InpTradeTool_AIAllowModifyTP=true
InpTradeTool_AIAllowPlaceOrders=true
InpTradeTool_AIAllowCancelOrders=true
InpTradeTool_AIIncludeClosedHistory=true
InpTradeTool_AIIncludeCandlestickChart=false
;
; Section Other
;
InpTradeTool_ATRPeriod=14
InpTradeTool_ChartImports=0 // IndicatorChartImports_Current
InpTradeTool_SymbolImports=
InpTradeTool_AlertTemplate={time}: strategy:{strategy} {symbol},{timeframe} {orderType} signal at: {entryPrice} sl={sl} tp={tp}
;
; Section Debugging
;
InpTradeTool_DebugFlags=0
;
; Section Interface
;
InpTradeTool_GuiTabsFlagMask=63
InpTradeTool_LineWidth=1
InpTradeTool_LineStyle=2 // STYLE_DOT
InpTradeTool_CPColor=0 // clrBlack
InpTradeTool_SLColor=200 // 200,0,0
InpTradeTool_TPColor=32768 // clrGreen
InpTradeTool_BEColor=8421376 // clrTeal
InpTradeTool_SOColor=0 // clrBlack
InpTradeTool_LOColor=0 // clrBlack
InpTradeTool_FontSize=9
InpTradeTool_ChartEdgeAlignment=1 // ChartEdgeAlignment_Right
```

---

## 3. Indicator Creation String Format

```
[Folder\]{Indicator}([Symbol:Timeframe,]EA_Flag[,args...]).ex5[,buffers]
```

- **Folder**: Optional. e.g. `NTL\`
- **Symbol:Timeframe**: Optional. `GBPUSD:H1` = both; `:H1` = current symbol, override TF; `GBPUSD:` = override symbol, current TF; omit = both current.
- **EA_Flag**: Always `1` for NTL indicators.
- **args**: Comma-separated parameters specific to each indicator.
- **buffers**: After `.ex5`, comma-separated buffer numbers scripts need access to. Signal buffer must be included if using `Signal()` or `Trend()`.
- **`+` prefix**: In preset files, `+` before the creation string means the indicator is actively referenced — by scripts, AI Strategy Instructions, or the AI Trigger Script.
- **VAR substitution**: Parameters can use `VAR0`, `VAR1`, etc. for optimisation.
- No quotes around symbols/timeframes. No spaces after commas.

---

## 4. Indicator Reference

Buffer indexes listed under **Buffers** are the indicator's internal buffer numbers. The numbers after `.ex5,` in each **Default** creation string are the subset of those buffers made accessible to scripts. If a buffer is not listed in the creation string, functions that depend on it (e.g. `Signal()`, `Trend()`) will not work — add the buffer index to enable them.

Parameters shown in parentheses are the indicator's internal defaults. The **Default** creation string may use different values tuned for the Defaults.set template. Parameters omitted from the creation string use their internal defaults.

---

#### Trend Indicators

### ADX1 — Average Directional Index

**Default**: `NTL\ADX(1,14).ex5,0,1,2,3` **Params**: P0=EAFlag(1), P1=Period(14), P2=TrendStrengthThreshold(20), P3=SignalLogicMethod(0: 0=ADXCrossesThreshold, 1=DICrossWhenTrending) **Buffers**: 0=ADX, 1=−DI, 2=+DI, 3=SignalFlags(Trend,Signal) **Functions**: ADX1(shift,buffer,lsr,mask), Signal('ADX1'), Trend('ADX1') **Notes**: P2 and P3 omitted from creation string — indicator uses internal defaults (20, 0).


---

### ADXW1 — ADX Welles Wilder

**Default**: `NTL\ADXW(1,14).ex5,0,1,2,3` **Params**: P0=EAFlag(1), P1=Period(14), P2=TrendStrengthThreshold(20), P3=SignalLogicMethod(0: 0=ADXWCrossesThreshold, 1=DICrossWhenTrending) **Buffers**: 0=ADXW, 1=−DI, 2=+DI, 3=SignalFlags(Trend,Signal) **Functions**: ADXW1(shift,buffer,lsr,mask), Signal('ADXW1'), Trend('ADXW1') **Notes**: P2 and P3 omitted from creation string — indicator uses internal defaults (20, 0).


---

### MA1 — Moving Average (Dual)

**Default**: `NTL\MA(1,50,1,200,1).ex5,0,1,2` **Params**: P0=EAFlag(1), P1=Period1(50), P2=Method1(1: 0=SMA, 1=EMA, 2=SMMA, 3=LWMA), P3=Period2(200), P4=Method2(1) **Buffers**: 0=Line1, 1=Line2, 2=SignalFlags(Trend,Signal) **Functions**: MA1(shift,buffer,lsr,mask), Signal('MA1'), Trend('MA1'), Cross('MA1',0,1)


---

### PSAR1 — Parabolic SAR

**Default**: `NTL\PSAR(1,0.02,0.2).ex5,0,1` **Params**: P0=EAFlag(1), P1=Step(0.02), P2=Maximum(0.2) **Buffers**: 0=PSAR, 1=SignalFlags(Trend,Signal) **Functions**: PSAR1(shift,buffer,lsr,mask), Signal('PSAR1'), Trend('PSAR1')


---

### ST1 — SuperTrend

**Default**: `NTL\ST(1,13,1.5).ex5,0,1` **Params**: P0=EAFlag(1), P1=Period(13), P2=Multiplier(1.5) **Buffers**: 0=SuperTrend, 1=SignalFlags(Trend,Signal) **Functions**: ST1(shift,buffer,lsr,mask), Signal('ST1'), Trend('ST1')


---

### TSI1 — True Strength Index

**Default**: `NTL\TSI(1,13,21,8,25,-25,1).ex5,0,1,2` **Params**: P0=EAFlag(1), P1=FastPeriod(13), P2=SlowPeriod(21), P3=SignalPeriod(8), P4=OverboughtLevel(25), P5=OversoldLevel(−25), P6=SignalLogicMethod(1: 0=TSICrossesZero, 1=TSICrossesSignal) **Buffers**: 0=TSI, 1=Signal, 2=SignalFlags(Trend,Signal,OBOS) **Functions**: TSI1(shift,buffer,lsr,mask), Signal('TSI1'), Trend('TSI1'), OBOS('TSI1')


---


#### Oscillator Indicators

### BB1 — Bollinger Bands

**Default**: `NTL\BB(1,20,2.0).ex5,0,1,2,3` **Params**: P0=EAFlag(1), P1=Period(20), P2=Deviation(2.0) **Buffers**: 0=Middle, 1=Upper, 2=Lower, 3=SignalFlags(Trend,OBOS) **Functions**: BB1(shift,buffer,lsr,mask), Signal('BB1'), Trend('BB1'), OBOS('BB1')


---

### Keltner1 — Keltner Channels

**Default**: `NTL\Keltner(1,20,1,2.25).ex5,0,1,2,3` **Params**: P0=EAFlag(1), P1=Period(20), P2=MAMethod(1=EMA), P3=ATRMultiplier(2.25) **Buffers**: 0=Middle, 1=Upper, 2=Lower, 3=SignalFlags(Trend,OBOS) **Functions**: Keltner1(shift,buffer,lsr,mask), Trend('Keltner1'), OBOS('Keltner1')


---

### MACD1 — MACD

**Default**: `NTL\MACD(1,12,26,9).ex5,0,4` **Params**: P0=EAFlag(1), P1=FastPeriod(12), P2=SlowPeriod(26), P3=SignalPeriod(9), P4=SignalLogicMethod(1: 0=HistogramCrossesZero, 1=MACDLineCrossesZero, 2=SignalLineCrossesMACDLine) **Buffers**: 0=MACD, 1=Signal, 2=Histogram, 3=Color, 4=SignalFlags(Trend,Signal) **Functions**: MACD1(shift,buffer,lsr,mask), Signal('MACD1'), Trend('MACD1') **Notes**: P4 omitted from creation string — indicator uses internal default (1). Only buffers 0 and 4 are requested in the template; to access Signal/Histogram/Color in scripts, add their indexes to the buffer list.


---

### OsMA1 — Oscillator of MA

**Default**: `NTL\OsMA(1,12,26,9).ex5,0,1` **Params**: P0=EAFlag(1), P1=FastPeriod(12), P2=SlowPeriod(26), P3=SignalPeriod(9) **Buffers**: 0=OsMA, 1=SignalFlags(Trend,Signal) **Functions**: OsMA1(shift,buffer,lsr,mask), Signal('OsMA1'), Trend('OsMA1')


---

### RSI1 — Relative Strength Index

**Default**: `NTL\RSI(1,14,1,70,30).ex5,0,1` **Params**: P0=EAFlag(1), P1=Period(14), P2=AppliedPrice(1=Close), P3=OverboughtLevel(70), P4=OversoldLevel(30) **Buffers**: 0=RSI, 1=SignalFlags(OBOS) **Functions**: RSI1(shift,buffer,lsr,mask), OBOS('RSI1') **Notes**: RSI produces OBOS signals only — no Trend or Signal flags.


---

### Stochastic1 — Stochastic Oscillator

**Default**: `NTL\Stochastic(1,5,3,3,80,20).ex5,0,1,2` **Params**: P0=EAFlag(1), P1=KPeriod(5), P2=DPeriod(3), P3=Slowing(3), P4=OverboughtLevel(80), P5=OversoldLevel(20) **Buffers**: 0=%K, 1=%D, 2=SignalFlags(Trend,Signal,OBOS) **Functions**: Stochastic1(shift,buffer,lsr,mask), Signal('Stochastic1'), Trend('Stochastic1'), OBOS('Stochastic1')


---


#### Structure / Smart Money Concepts

### AutoFib1 — Fibonacci Retracement

**Default**: `NTL\AutoFib(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,0,4,8,50,100,0.0,10,250,45,'0.35,1',0,0,3,14).ex5,0,1,2,3,4,5`

**Detection**: Finds significant swing highs and lows using bar strength analysis (how many consecutive bars a high/low remains unbroken), then fits Fibonacci retracement levels between them. A bullish Fib is a swing-low-then-swing-high impulse; a bearish Fib is a swing-high-then-swing-low impulse. A Fib terminates when price closes beyond either swing boundary or exceeds MaxFibRangeInBars.

**Level Convention**: Uses standard retracement convention: 0% = end of impulse (no retracement), 100% = origin (full retracement). So bullish 0% = swing high, 100% = swing low; bearish 0% = swing low, 100% = swing high.

**Params**: P0=EAFlag(1), P1=Timeframe(0), P2=FibLevelsCSV, P3=MinFibWidthInBars(3), P4=MaxFibWidthInBars(0=unlimited), P5=MinFibHeightInABH(4), P6=MaxFibHeightInABH(8), P7=MaxFibRangeInBars(50), P8=MinFibStrengthDifference(100, additive; used when P9=0), P9=MinFibStrengthMultiplier(0.0=disabled; when non-zero: min_0pct_strength = 100pct_strength × multiplier), P10=MinFib100Strength(10), P11=MaxFib100Strength(250, 0=unlimited), P12=MaxLookbackInBars(45), P13=ZoneLevelsCSV('0.35,1'; semicolon-separated pairs), P14=FibPatternBits(0), P15=FibPatternSize(0), P16=AppliedPrice(3: 1=Close, 3=High/Low), P17=ABHPeriod(14)

**Buffers**:

-   0=FibShift (bit-packed, written every active-Fib bar: bits 0–19 = 0% level shift, bits 20–39 = 100% level shift, bits 40–41 = FibType 01=Bullish/10=Bearish, bit 42 = Formed, bit 43 = Broken, bit 44 = 0% Level Broken, bit 45 = 100% Level Broken, bit 46 = FibMatch; 0 when no Fib active)
-   1=FibLevel0 (price at 0% level: swing HIGH for bullish, swing LOW for bearish; 0 when no Fib active)
-   2=FibLevel1 (price at 100% level: swing LOW for bullish, swing HIGH for bearish; 0 when no Fib active)
-   3=BarStrength (bit-packed: bits 0–23 = high bar strength, bits 24–47 = low bar strength)
-   4=FibTypeHistory (bits 0–49: last 50 FibType bits, 1=bullish 0=bearish, bit 0 = most recent)
-   5=SignalFlags(Trend,Signal)

**Signal Logic**: Trend = Bullish when FibType=1, Bearish when FibType=2, None otherwise. Signal fires in trend direction when bar's high/low range overlaps any configured zone. Zone prices: `zonePrice = level0Price − (level0Price − level1Price) × zoneLevel`.

**Functions**: AutoFib1(shift,buffer,lsr,mask), Signal('AutoFib1'), Trend('AutoFib1'), FibInZone('AutoFib1',...), FibPrice('AutoFib1',...)

**Notes**: FibPrice() and FibInZone() read price from buffers 1 and 2 (not buffer 0). Buffer 0 is bit-packed metadata — do not use it as a price value. Buffers 1 and 2 are populated on every bar where a Fib is active, not just on formation bars.


---

### ChoCh1 — Change of Character
**Default**: `NTL\ChoCh(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,55,3,6,55,100,0.0,8,250,45,'0.35,1',0,0,3,14,500).ex5,0,1,2,3,4,5,6,7,8`
**Params**: P0=EAFlag(1), P1=AutoFibTimeframe(0), P2=FibLevelsCSV, P3=MinFibWidthInBars(3), P4=MaxFibWidthInBars(55), P5=MinFibHeightInABH(3), P6=MaxFibHeightInABH(6), P7=MaxFibRangeInBars(55), P8=MinFibStrengthDiff(100), P9=MinFibStrengthMultiplier(0.0), P10=MinFib100Strength(8), P11=MaxFib100Strength(250), P12=MaxLookbackInBars(45), P13=ZoneLevelsCSV, P14=FibPatternBits(0), P15=FibPatternSize(0), P16=AppliedPrice(3), P17=ABHPeriod(14), P18=ChoChMaxWidthInBars(500, 0=unlimited — lookback limit for grounded event export, not a detection constraint)
**Buffers**:
-   0=BullChoChData (bit-packed: bits 0–11 backlink, bits 12–19 sweptAge, bits 20–21 type 01=bull/10=bear, bit 22 formed, bit 23 swept, bits 32–43 size)
-   1=BearChoChData (same layout as buffer 0)
-   2=BullPriceHi (swept zone upper price — level1Price from swept bearish fib)
-   3=BullPriceLo (swept zone lower price — level0Price from swept bearish fib)
-   4=BearPriceHi (swept zone upper price — level0Price from swept bullish fib)
-   5=BearPriceLo (swept zone lower price — level1Price from swept bullish fib)
-   6=AutoFibLevel0 (price at 0% Fibonacci level / pattern origin — written every bar from current AutoFib data, 0 when no data)
-   7=AutoFibLevel1 (price at 100% Fibonacci level / swing extreme — written every bar from current AutoFib data, 0 when no data)
-   8=SignalFlags(Signal only — no Trend)

**Bar types**: Formation bars (Formed=1) carry all fields — Type, Swept, Size, prices. Relay waypoints (Formed=0) carry only backlink and sweptAge; all other bits zero. Only formation bars are pattern origins.
**Functions**: ChoCh1(shift,buffer,lsr,mask), Signal('ChoCh1'), FibPrice('ChoCh1',...)
**Notes**: A ChoCh (Change of Character) detects market structure breaks — price closes beyond a prior swing extreme (AutoFib 100% level), sweeping it. A bullish ChoCh forms when close breaks below a prior bearish fib's 100% level (swing low); a bearish ChoCh forms when close breaks above a prior bullish fib's 100% level (swing high). The swept fib type is always the inverse of the ChoCh type. Signal('ChoCh1') now persists direction on subsequent bars. Use SignalBull('ChoCh1')/SignalBear('ChoCh1') to query bars since last structural break. ChoCh does not produce Trend signals. Price buffers (2–5) are conditional — they propagate forward from the formation bar while sweptAge is active (up to 255 bars), then revert to 0. FibPrice() for ChoCh reads from buffers 6 and 7 (not 1 and 2 as with AutoFib). All ChoCh buffer data is real-time safe — no future data mutations.


---

### FVG1 — Fair Value Gap
**Default**: `NTL\FVG(1,0,400,0.1,0.0,0.4,3.0,0.1,3,14,0,0,0.0).ex5,0,1,2,3,4,5,6`
**Params**: P0=EAFlag(1), P1=Timeframe(0), P2=MaxBoxWidthInBars(400, 0=no
max), P3=MinBarHeightInABH(0.1), P4=MinWickHeightInABH(0.0, 0=disable),
P5=MinGapHeightInABH(0.4), P6=MaxGapHeightInABH(3.0),
P7=MaxGapFillThreshold(0.1=10%), P8=WidthInBars(3), P9=ABHPeriod(14),
P10=RelativeHLDistance(0, 0=disable), P11=RelativeHLStrength(0, 0=disable),
P12=MinCreationBarHeightInABH(0.0, 0=disable), P13=HideFilledFVGs(false),
P14=FontSize(9)
**Detection**: A bullish FVG forms when all bars in the detection window
(default 3) are bullish (close>open) and a gap exists where the latest bar's
low exceeds the earliest bar's high (gap = latest low − earliest high). A
bearish FVG forms when all bars are bearish (close<open) and the earliest
bar's low exceeds the latest bar's high (gap = earliest low − latest high).
Gaps must fall within MinGapHeightInABH–MaxGapHeightInABH thresholds. Each
bar must meet MinBarHeightInABH. Wick heights are validated when
MinWickHeightInABH≠0: for bullish, the earliest bar's upper wick (high−close)
and latest bar's lower wick (open−low); for bearish, the earliest bar's lower
wick (close−low) and latest bar's upper wick (high−open). When
MinCreationBarHeightInABH>0, the creation bar (rightmost bar) must meet the
height threshold. When RelativeHLDistance>0 and RelativeHLStrength>0: for
bullish, the lowest low within Distance bars must be untouched in Strength
bars before it (swing low filter); for bearish, the highest high within
Distance bars must be untouched in Strength bars before it (swing high
filter).
**Signals**: Bullish FVG formed → Trend=Bullish. Bearish FVG formed →
Trend=Bearish. Bullish FVG filled → Signal=Bullish (support zone touched).
Bearish FVG filled → Signal=Bearish (resistance zone touched). Both sides
checked independently per bar.
**Fill**: Bullish fill ratio = (boxHi − currentBarLow) / boxHeight; bearish
fill ratio = (currentBarHigh − boxLo) / boxHeight. Pattern terminates when
ratio ≥ MaxGapFillThreshold. Also terminates when box width reaches
MaxBoxWidthInBars (0=disabled).
**Buffers**:
-   0=BullFVGData (bit-packed: bits 0–11 backlink, bits 12–22 unfilledAge,
    bits 23–24 type 01=bull/10=bear, bit 25 formed, bit 26 filled, bits
    27–34 fillValue 0–100, bits 35–46 size — future data, bit 47
    terminated — future data)
-   1=BearFVGData (same layout as buffer 0)
-   2=BullPriceHigh (bullish zone upper boundary = latest bar's low)
-   3=BullPriceLow (bullish zone lower boundary = earliest bar's high)
-   4=BearPriceHigh (bearish zone upper boundary = earliest bar's low)
-   5=BearPriceLow (bearish zone lower boundary = latest bar's high)
-   6=SignalFlags(Trend,Signal)

**Bar types**: Data buffers contain three bar types: (1) formation bar
(formed=1) — all 48 bits populated, pattern origin, size/terminated mutated
retroactively each bar; (2) relay waypoint (formed=0, filled=0) — only
backlink + unfilledAge populated, all other fields zero; (3) fill bar
(overwrites relay) — backlink + unfilledAge (from next surviving pattern) +
type + filled=1 + fillValue. Type is zero on relay waypoints; only meaningful
on formation and fill bars.
**Price buffer propagation**: Per side, per bar, priority (latest write wins):
(1) new formation writes zone boundaries, (2) fresh fill overwrites with
filled zone, (3) latest active pattern's zone if no fill but live patterns
exist, (4) zero if no active patterns on this side.
**Functions**: FVG1(shift,buffer,lsr,mask), Signal('FVG1'), Trend('FVG1')
**Notes**: Size and terminated fields on formation bars are future data — safe
for drawing only, must NOT be used in scripts. The indicator also accepts
P13=HideFilledFVGs(false) and P14=FontSize(9), display-only parameters
omitted from the template creation string. P10–P12 default to 0 (disabled)
and are also omitted from the template creation string.


---

### HLines1 — Horizontal Lines (Support/Resistance)

**Default**: `NTL\HLines(1,0,800,15,'S2;R2',35,0.0,0.5,100).ex5,0,1` **Params**: P0=EAFlag(1), P1=Timeframes(''=current), P2=Period(800), P3=MinStrength(100), P4=PivotString('S2;R2'), P5=MaxBodyCrosses(35), P6=PivotWeightInABH(0.0), P7=LineWobbleToleranceInABH(0.5), P8=ABHPeriod(100) **Buffers**: 0=HLinePrice, 1=SignalFlags(Signal) **Functions**: HLines1(shift,buffer,lsr,mask), Signal('HLines1'), HLineBreak('HLines1',...), HLinesBounce('HLines1',...) **Notes**: Template uses P3=15; indicator default is 100.


---

### LP1 — Liquidity Pool

**Default**: `NTL\LP(1,0,800,1,6,7,400,14,7.0,2.5,0.0,0,0.0,0.0,0.0,10,80,2).ex5,0,1,2,3,4,5,6,7,8,9,10,11,12`
**Params**: P0=EAFlag(1), P1=Timeframe(0), P2=MaxLookbackInBars(800), P3=MinPivotOrder(1), P4=MaxPivotOrder(6), P5=MinBarStrength(7), P6=MaxWidthInBars(400, 0=no max), P7=ABHPeriod(14), P8=LiquidityClassificationABH(7.0, 0=disable), P9=PostPivotSwingInABH(2.5, min post-pivot swing size in ABH units, 0=disabled), P10=PrePivotSwingInABH(0.0, min pre-pivot swing distance from previous opposite-side pivot in ABH units, 0=disabled), P11=MaxDisplacementBars(0, max bars between HL↔HH or LH↔LL paired pivots, 0=disabled), P12=MinDisplacementABH(0.0, min price distance in ABH between paired displacement pivots, 0=disabled), P13=MaxSameSideStructDiffABH(0.0, max ABH between consecutive same-side structures, 0=disabled), P14=MinSameSideStructDiffABH(0.0, min ABH between consecutive same-side structures for trend detection, 0=disabled), P15=StructureTrendLookback(10, recent structure points evaluated for trend direction, max 24), P16=StructureTrendThreshold(80, percentage of bullish/bearish points required to declare a trend, 0-100), P17=ExportType(2: 0=LiquidityOnly, 1=StructureOnly, 2=Both)
**Detection**: BSL forms at swing highs (pivot high = stop-loss accumulation level above price); SSL forms at swing lows (pivot low = stop-loss accumulation level below price). Requires pivot order >= P3, bar strength >= P5, within P2-bar lookback; if P9>0 also requires post-pivot swing/ABH >= P9; if P10>0 also requires pre-pivot swing distance from previous opposite-side pivot/ABH >= P10. A BSL is swept when price high exceeds the swing high price; an SSL is swept when price low falls below the swing low price. Market structure (HH/LH/HL/LL) is classified by comparing consecutive pivots. When P11>0 or P12>0, structures are paired (HL↔HH, LH↔LL): both must appear within P11 bars and P12 ABH of each other or both are rejected. When P13>0, a new structure is only accepted if it is within P13 ABH of the previous same-side structure. When P14>0, a new structure is only accepted if it is at least P14 ABH from the previous same-side structure. Break-of-Structure (BOS) is detected when close breaks through the last structure level (bullish checked first; at most one BOS per bar).
**Signals**: BSL swept → Signal=Bullish; SSL swept → Signal=Bearish (SSL takes priority if both swept on same bar).
**Trend**: BSL forms → Trend=Bullish; SSL forms → Trend=Bearish (SSL takes priority if both form on same bar). **Classification** (P8>0): external if max price excursion from pivot / ABH >= P8 (one-way latch; BSL excursion = pivot minus min low; SSL excursion = max high minus pivot).
**Buffers**:
-   0=BSLData (bit-packed: bits 0–11 backlink, bits 12–19 sweptAge, bits 20–21 type 01=BSL/10=SSL, bit 22 formed, bit 23 swept, bits 24–35 size — future data, bits 36–45 pivotShift — future data, bit 47 terminated — future data, bit 48 external — future data on formation bars, real-time safe on relay bars)
-   1=SSLData (same layout as buffer 0)
-   2=BSLPrice (active BSL pivot price; 0 when no active BSL)
-   3=SSLPrice (active SSL pivot price; 0 when no active SSL)
-   4=BSLSweptPrice (most recently swept BSL pivot price; meaningful only while sweptAge > 0)
-   5=SSLSweptPrice (most recently swept SSL pivot price; meaningful only while sweptAge > 0)
-   6=SweptExternalAge (bit-packed: bits 0–7 BSL external sweep age, bits 8–15 SSL external sweep age, bits 16–18 structureTrendDirection 0=ranging/1=bullish/2=bearish/3=bullish_mix/4=bearish_mix/5=bullish_range/6=bearish_range, bits 19–28 structureTrendStrength max/min ABH ratio*100 0–1023 always >=100; sweep ages independent of sweptAge, not reset by non-external sweeps, max 255 then drops to 0; read: `LP1(0,6,0,255)`=BSLAge, `LP1(0,6,8,255)`=SSLAge, `LP1(0,6,16,7)`=TrendDirection, `LP1(0,6,19,1023)`=TrendStrength)
-   7=StructureData (bit-packed: bits 0–11 backlink, bits 12–19 sweptAge — reserved/always 0, bits 20–22 structType 1=HH/2=LH/3=HL/4=LL, bit 23 formed, bit 24 swept — reserved/always 0, bits 25–34 pivotShift — future data, bit 35 terminated — future data, bits 36–43 strength 0–255)
-   8=StructurePrice (pivot price of classified structure point)
-   9=BOSData (bit-packed: bits 0–1 bosType 1=Bullish/2=Bearish, bits 2–13 brokenLevel bars back to broken structure, bit 14 formed)
-   10=BOSPrice (price of the broken structure level)
-   11=SignalFlags(Trend,Signal)
-   12=SequenceData (50-bit rolling history: bits 0-1 hold most recent BOS direction: 0=none, 1=bullish, 2=bearish; bits 2-49 hold last 24 structure swing types as 2-bit pairs, index 0 (bits 3:2)=newest, index 23 (bits 49:48)=oldest, values: 0=HH, 1=HL, 2=LH, 3=LL; forward-filled every bar)

**Functions**: LP1(shift,buffer,lsr,mask), Signal('LP1'), Trend('LP1'), StructureQuality('LP1'), StructureFlow('LP1',pattern)


---

### PL1 — Pivot Lines

**Default**: `NTL\PL(1,16408,4).ex5,0` **Params**: P0=EAFlag(1), P1=Period(16408=D1: 0=Daily, 1=Weekly, 2=Monthly), P2=Method(4: 0=None, 1=Regular, 2=Camarilla, 3=Woodie, 4=Fibonacci) **Buffers**: 0=PP, 1=R1, 2=R2, 3=R3, 4=R4, 5=S1, 6=S2, 7=S3, 8=S4 **Functions**: PL1(shift,buffer,lsr,mask) **Notes**: Only buffer 0 (PP) is requested in the template. To access R1–R4 or S1–S4 in scripts, add the required buffer indexes to the creation string.


---

### PP1 — Pivot Points

**Default**: `NTL\PP(1).ex5,0,1,2,3,4,5,6,7,8` **Params**: P0=EAFlag(1), P1=HighestOrder(6) **Buffers**:

-   0=BarStrength (bit-packed: bits 0–23 high bar strength, bits 24–47 low bar strength)
-   1=PivotOrder1Shift (bit-packed: bits 0–23 high pivot shift, bits 24–47 low pivot shift)
-   2=PivotOrder2Shift (same layout)
-   3=PivotOrder3Shift (same layout)
-   4=PivotOrder4Shift (same layout)
-   5=PivotOrder5Shift (same layout)
-   6=PivotOrder6Shift (same layout)

**Functions**: PP1(shift,buffer,lsr,mask), PivotHighPrice('PP1',...), PivotLowPrice('PP1',...), PivotTrend('PP1',...) **Notes**: Template requests buffers 0–5 (up to order 5). Buffer 6 (order 6) is available but not included by default. Shift values are relative to the queried bar — add +1 when passing to High()/Low() which expect shift from bar 1. PivotHighPrice/PivotLowPrice use internal buffer lookups (not the creation string buffer list) and work regardless of which buffers are requested.


---

### TLines1 — Trendlines

**Default**: `NTL\TLines(1,2.5,'S2;R2',25,2,15,2,1.0,400,50,800,0.1,0.1,100).ex5,0,1,2,3,4,5,6,7,8` **Params**: P0=EAFlag(1), P1=MinSwingInABH(2.5), P2=PivotString('S2;R2'), P3=MinBarStrength(25), P4=MaxBodyCrosses(2), P5=MinPivotGap(15), P6=MinPivots(2), P7=MaxPivotGapRatio(1.0), P8=MaxLineLengthInBars(400), P9=MinLineLengthInBars(50), P10=MaxLineAgeInBars(800), P11=LineToleranceInABH(0.1), P12=BodyToleranceInABH(0.1), P13=ABHPeriod(100) **Buffers**: 0=ResistanceTrendline, 1=SupportTrendline, 2=TrendlineStrength, 3=TrendlinePrice (closest to close), 4=SignalFlags(Trend,Signal), 5=ResistanceExcursion, 6=SupportExcursion **Functions**: TLines1(shift,buffer,lsr,mask), Signal('TLines1'), Trend('TLines1')


---


#### Bar Analysis

### ABH1 — Average Bar Height

**Default**: `NTL\ABH(1,14,3).ex5,0,1` **Params**: P0=EAFlag(1), P1=Period(14), P2=BarFlagBits(15: bit0=Bar, bit1=Body, bit2=UpperWick, bit3=LowerWick) **Buffers**: 0=AvgBarHeight, 1=AvgBodyHeight, 2=AvgUpperWick, 3=AvgLowerWick **Functions**: ABH1(shift,buffer,lsr,mask) **Notes**: No SignalFlags buffer. Template uses P2=3 (Bar+Body only); indicator default is 15 (all components).


---

### JCP1 — Japanese Candle Patterns

**Default**: `NTL\JCP(1).ex5,0,1` **Params**: P0=EAFlag(1) **Buffers**: 0=PatternData (bits 0–15 PatternType, bits 16–19 PatternWidthInBars), 1=SignalFlags(Signal) **Functions**: JCP1(shift,buffer,lsr,mask), Signal('JCP1')


---


#### Utility

### ATR1 — Average True Range

**Default**: `NTL\ATR(1,14).ex5,0` **Params**: P0=EAFlag(1), P1=Period(14) **Buffers**: 0=ATR **Functions**: ATR1(shift,buffer,lsr,mask)


---

### Markets1 — Market Times

**Default**: `NTL\Markets(1).ex5,0` **Params**: P0=EAFlag(1) **Buffers**: 0=MarketState (bit-packed per-market open/close and bar count for 5 markets: bit 0 Frankfurt open, bits 1–9 Frankfurt bars; bit 10 London open, bits 11–19 London bars; bit 20 New York open, bits 21–29 New York bars; bit 30 Sydney open, bits 31–39 Sydney bars; bit 40 Tokyo open, bits 41–49 Tokyo bars) **Functions**: Markets1(shift,buffer,lsr,mask)


---

### Scalper1 — Tick Scalper

**Default**: `NTL\Scalper(1,10000,0.7,10000,0.3,0.6,10000,0.5,0.3,10000,0.7,10,1,5,0.0,5000,1,1,19,24).ex5,0,1,2,3,4,5,6` **Params**: P0=EAFlag(1), P1=TickDensityWindowMs(10000), P2=TickDensitySignalThreshold(0.7), P3=TickVelocityWindowMs(10000), P4=TickVelocitySmoothing(0.3), P5=TickVelocitySignalThreshold(0.6), P6=TickAccelWindowMs(10000), P7=TickAccelSmoothing(0.5), P8=TickAccelSignalThreshold(0.3), P9=TickDirectionWindowMs(10000), P10=TickDirectionSignalThreshold(0.7), P11=TickMAPeriod(10), P12=TickMAMethod(1=EMA), P13=MADeviationThresholdPoints(5), P14=MinABHValueForSignals(0.0), P15=MinTimeBetweenSignalsMs(5000), P16=GenerateBullishSignals(1), P17=GenerateBearishSignals(1), P18=RequiredConditions(1: bit0=Density, bit1=Velocity, bit2=Acceleration, bit3=Direction, bit4=MA), P19=DirectionConditions(26: bitmap of which active metrics vote on direction) **Buffers**: 0=TickDensity (normalised 0–1), 1=TickVelocity (normalised −1 to +1), 2=TickAcceleration (normalised −1 to +1), 3=TickMA, 4–6=TickSignalBuffers (each stores two 26-bit packed signals: bit 0 direction 0=sell/1=buy, bits 1–25 ms offset from bar open; second signal at bits 26–51) **Functions**: Scalper1(shift,buffer,lsr,mask), Signal('Scalper1') **Notes**: Template uses P18=19 (Density+Velocity+MA) and P19=24 (Direction+MA); indicator defaults are P18=1 (Density only) and P19=26 (Velocity+Direction+MA). Tick-level signals use cTickSignalManager — buffers 4–6 are not standard SignalFlags but packed sub-bar signal data.


---

## 5. EAsiScript Reference

Entry, exit, and management scripts use the EAsiScript language. This section provides the complete function reference for building script expressions.

### Operators

`+` `-` `*` `/` `%` `!` `~` `<` `>` `<=` `>=` `?:` `==` `&&` `||` `&` `|` `<<` `>>`

### Built-in Variables

| Name | Value |
|------|-------|
| Bullish | 1 |
| Bearish | -1 |
| No Trend | 0 |
| Point | Symbol point value |
| Pip | Symbol pip value |
| M1–M30 | 1,2,3,4,5,6,10,12,15,20,30 |
| H1–H12 | 16385,16386,16387,16388,16390,16392,16396 |
| D1 | 16408 |
| W1 | 32769 |
| MN1 | 49153 |
| FF | 0 (Frankfurt time zone) |
| LN | 1 (London time zone) |
| NY | 2 (New York time zone) |
| SY | 3 (Sydney time zone) |
| TK | 4 (Tokyo time zone) |

### Script Types

Scripts return a price to trigger (non-zero) or 0 to skip.

| Script | Returns | Context |
|--------|---------|---------|
| Long/Short Entry | Ask()/Bid() to enter at market; stop/limit price for pending orders; 0=no signal | Evaluated each bar (or tick) |
| Long/Short Initial SL | SL price; 0=use settings default | After entry signal. Use OrderPrice() not EntryPrice() |
| Long/Short Trailing SL | New SL price; 0=no change | While position open |
| Long/Short Lots | Lot size; 0=use settings default | After entry signal |
| Long/Short TP | TP price; 0=use settings default | After entry signal. Use OrderPrice() not EntryPrice() |
| Long/Short BE | BE price; 0=no change | While position open |
| Long/Short Exit | Exit price; 0=no exit | While position open |
| AI Trigger | Non-zero=permit AI request; 0=suppress | Before AI refresh |

### Price Functions

| Function | Description |
|---|------|
| Ask(offset=0) | Ask price, adjusted by offset (price+price*offset) |
| Bid(offset=0) | Bid price, adjusted by offset |
| BodyHigh(shift=1,symbol) | High body price |
| BodyLow(shift=1,symbol) | Low body price |
| Close(shift=1,symbol,tf) | Close price |
| High(shift=0,symbol,tf) | High price |
| HighD(shift=0,symbol) | Daily high |
| HighestHigh(bars=0,shift=1,symbol,tf) | Highest high price |
| Low(shift=0,symbol,tf) | Low price |
| LowD(shift=0,symbol) | Daily low |
| LowestLow(bars=0,shift=1,symbol,tf) | Lowest low price |
| Mid(symbol) | (bid+ask)/2 |
| Open(shift=0,symbol,tf) | Open price |
| Spread(shift=1,symbol,tf) | Spread |
| Volume(shift=0,symbol,tf) | Volume |

### Bar Analysis Functions

| Function | Description |
|---|------|
| BarClosePos(shift=1) | Close position in bar range (0.0=low, 1.0=high) |
| BarImpulse(shift=1) | Signed momentum: ±(body/bar), +1 bullish, -1 bearish |
| BarMatch(shift,dir,barSize,bodySize,wickSize,upperWick,lowerWick) | 1 if bar matches criteria (sizes in points; +ve=≥, -ve=<) |
| BarMatchAvg(atrName,shift,dir,barSize,bodySize,wickSize,upperWick,lowerWick) | Like BarMatch but sizes as ABH ratio |
| BarSize(shift=1,part=0,symbol,tf) | Bar size (0=whole,1=body,2=upperWick,3=lowerWick) |
| BarSkew(shift=1) | Body midpoint position in bar range (0.0–1.0) |
| BarTrend(shift=1,symbol,tf) | 0=doji, 1=bullish, -1=bearish |
| BearishBars(count=0,symbol,tf) | Consecutive (count=0) or total bearish bars |
| BodyX(bars=0,price=0,symbol,tf) | Bars whose body crosses price |
| BoxBars(low,high,bars,symbol,tf) | Bars with open and close within price box |
| BullishBars(count=0,symbol,tf) | Consecutive (count=0) or total bullish bars |
| DayBars() | Bars since start of day |
| HighBars(bars=0,symbol,tf) | Bars with lower-or-equal high (count from latest) |
| HighestBody(bars=0,shift=1,symbol,tf) | Highest body price in range |
| HighestHigh(bars=0,shift=1,symbol,tf) | Highest high in range |
| IsDoji(shift=1,barBodyRatio=10) | 1 if bar range ≥ barBodyRatio × body |
| IsEngulfing(shift=1,dir=0) | 1 if engulfing (dir: 1=bull,-1=bear,0=any) |
| IsInsideBar(shift=1) | 1 if inside previous bar |
| IsOutsideBar(shift=1) | 1 if outside previous bar |
| IsPinBar(shift=1,wickRatio=0.33) | 1 if pin bar (wick ≥ wickRatio × bar) |
| LowBars(bars=0,symbol,tf) | Bars with higher-or-equal low |
| LowestBody(bars=0,shift=1,symbol,tf) | Lowest body price in range |
| LowestLow(bars=0,shift=1,symbol,tf) | Lowest low in range |
| UpperWickX(shift,price,symbol,tf) | 1 if price crosses upper wick |
| LowerWickX(shift,price,symbol,tf) | 1 if price crosses lower wick |
| Range(bars,mode=0,symbol,tf) | Highest high − lowest low in points over bar range |
| TrendStretch(shift=1,direction=1) | Consecutive bars closing above prev high (bull) or below prev low (bear) |
| WickRatio(shift=1) | Ratio of total wick length to body size; 0 if body is zero |

### Indicator Functions

| Function | Description |
|---|------|
| Bars(indicator) | Available bars for indicator |
| Comp(ind,buf1=0,buf2=-1,shift1=1,shift2=1) | Compare: 0=equal,-1=less,1=greater. buf2=-1 uses Close |
| Cross(ind,buf1=0,buf2=-1,shift1=1,shift2=2) | Cross detection: 0=none,-1=bearish,1=bullish. buf2=-1 uses Close |
| FibInZone(fibInd,zone1,zone2,price,shift=1) | 1 if price inside fib zone |
| FibPrice(fibInd,fibLevel,shift=1) | Price at fib level |
| HLineBreak(hlineInd,atrInd,atrMult=0.1,mode=0,shift=1) | Breakout: 1=bull,-1=bear,0=none |
| HLinesBounce(hlineInd,atrInd,atrMult=0.1,mode=0,shift=1) | Bounce: 1=bull,-1=bear,0=none |
| OBOS(ind,shift=1) | OB/OS flag: 0=none,1=oversold,-1=overbought |
| PivotHighPrice(pivotInd,minOrder=2,shift=1) | Price of pivot high ≥ minOrder |
| PivotLowPrice(pivotInd,minOrder=2,shift=1) | Price of pivot low ≥ minOrder |
| PivotTrend(pivotInd,order,mode=0,shift=1) | 1=bull,-1=bear,0=neutral. mode: 0=strict(HH&HL),1=structure(HL),2=breakout(HH) |
| Signal(ind,shift=1) | Signal direction (persisted): -1=bearish,0=none,1=bullish |
| SignalBear(ind,shift=1) | Bars since last bearish signal: 0=none,1=this bar,N=N-1 ago |
| SignalBull(ind,shift=1) | Bars since last bullish signal: 0=none,1=this bar,N=N-1 ago |
| Stat(metric) | Statistic metric value for current market |
| StructureFlow(ind,pattern,shift=1) | 1 if last 3 LP swings match pattern, 0 otherwise. Pattern: 3-digit (oldest->newest) 0=any,1=HH,2=HL,3=LH,4=LL. E.g. 212=HL->HH->HL, 102=HH->any->HL |
| StructureQuality(ind,shift=1) | Structure quality: +2=strong bull, +1=acceptable bull (or neutral swings + Bull BOS), -1=acceptable bear (or neutral swings + Bear BOS), -2=strong bear, 0=neutral |
| Trend(ind,shift=1) | Trend direction (persisted): -1=bearish,0=none,1=bullish |
| TrendBear(ind,shift=1) | Bars since bearish trend started: 0=not bearish,1=this bar,N=N-1 ago |
| TrendBull(ind,shift=1) | Bars since bullish trend started: 0=not bullish,1=this bar,N=N-1 ago |

### Position and Order Functions

| Function | Description |
|---|------|
| BarsOpen(pos) | Bars position has been open |
| BE(pos) | Breakeven price |
| Duration(pos) | Duration in seconds |
| EntryPrice(pos) | Entry/fill price (invalid in SL/TP/BE scripts — use OrderPrice) |
| IsBE() | 1 if at breakeven |
| IsOpen(pos) | 1 if position is open |
| IsPending(pos) | 1 if position is pending |
| Lots(pos) | Position size in lots |
| MaxLots(slsize=0) | Max lots from margin/risk. slsize=SL distance in points |
| MaxPoints(pos) | Max profit in points |
| MaxProfit(pos) | Max profit in money |
| OrderPrice(pos) | Order price (valid in all scripts) |
| OrderType(pos) | Order type (0=Buy,1=Sell,...) |
| Pips(pos) | Current profit in pips |
| Points(pos) | Current profit in points |
| Positions() | Number of open positions |
| PriceShift(price,shift=1) | Bars since price was within a bar's range |
| Profit(pos) | Current profit in money |
| R(pos) | Initial risk in points |
| SL(pos) | SL price |
| SLSize(pos) | SL distance in points |
| TotalPips() | Total pips all positions |
| TotalPoints() | Total points all positions |
| TotalProfit() | Total profit all positions |
| TP(pos) | TP price |

### Account / Time / Math Functions

| Function | Description |
|---|------|
| Balance() | Account balance |
| Equity() | Account equity |
| FreeMargin() | Free margin |
| Day() | Day of week (0=Sun–6=Sat) |
| Hour(tz) | Hour of latest bar. tz: 0=Frankfurt,1=London,2=NewYork,3=Sydney,4=Tokyo; omit=server |
| Minute() | Minute of latest bar |
| Time(shift=0,symbol,tf) | Bar open time |
| TimeOfDay(h1,m1,h2,m2) | Minutes past midnight; or time comparison (-1/0/1) |
| TimeShift(hour,minute) | Bars since specified time today |
| MarketOpenShift(tz,offset=0) | Shift to market open bar today. tz: 0=Frankfurt,1=London,2=NewYork,3=Sydney,4=Tokyo. offset subtracted from shift to reference bars after open |
| Abs(x), Ceil(x), Floor(x), Max(x,y), Min(x,y), Mod(x,y), Rand(), Round(x), Sqrt(x) | Standard math |

### Tick Functions

| Function | Description |
|---|------|
| TickAsk(shift=0,symbol) | Tick ask price at offset from latest tick |
| TickBid(shift=0,symbol) | Tick bid price at offset from latest tick |
| TickHighest(tickRangeInMs,symbol) | Highest ask tick price in millisecond time range |
| TickLowest(tickRangeInMs,symbol) | Lowest bid tick price in millisecond time range |
| TickRange(tickRangeInMs,symbol) | Highest ask − lowest bid in points over millisecond time range |

### AI Functions

| Function | Returns |
|---|---------|
| AiBias() | Directional bias (validated) |
| AiBiasConfidence() | Bias confidence 0.0–1.0 |
| AiBiasMultiplier(isLong) | Directional multiplier (isLong: 1=long, 0=short) |
| AiBiasRaw() | Raw bias (no validity check) |
| AiCombinedMultiplier(isLong) | Combined bias×risk multiplier |
| AiConfidence() | Overall confidence 0.0–1.0 |
| AiConfidenceRaw() | Raw confidence (no validity check) |
| AiDataAge() | Assessment age in seconds |
| AiIsBearish() | 1 if bearish |
| AiIsBullish() | 1 if bullish |
| AiIsHighRisk() | 1 if high risk |
| AiIsLowRisk() | 1 if low risk |
| AiIsRanging() | 1 if ranging regime |
| AiIsStrongBias() | 1 if strongbull or strongbear |
| AiIsTrending() | 1 if trending regime |
| AiIsUsable() | 1 if suitable for scripts |
| AiIsValid() | 1 if valid and current |
| AiIsVolatile() | 1 if volatile regime |
| AiRegime() | Market regime (validated) |
| AiRegimeConfidence() | Regime confidence 0.0–1.0 |
| AiRegimeRaw() | Raw regime (no validity check) |
| AiRiskConfidence() | Risk confidence 0.0–1.0 |
| AiRiskMode() | Risk mode (validated) |
| AiRiskModeRaw() | Raw risk mode (no validity check) |
| AiRiskMultiplier() | Risk-based position multiplier |
| AiSecondsToExpiry() | Seconds until assessment expires |
| AiStatus() | AI context status |

AI functions return defaults (0 for booleans, 1.0 for multipliers) when AI is disabled or no valid assessment exists. Not available during backtesting.

---

## 6. AI System Reference

### Provider Config String

Format: `provider=X,model=Y,temperature=Z[,alias=A][,maxOutputTokens=N]`
Multiple providers separated by `;`.
Providers: OpenAI, Anthropic, Gemini.
Alias enables per-market routing. Falls back to first config without alias.

### AI Modes

Runtime behaviour for each mode. For preset construction requirements (entry scripts, permission flags), see [AI Mode Constraints](#ai-mode-constraints).

| Mode | Request Trigger | Fail Behaviour | Trading Impact |
|------|---------|---------|---------|
| Disabled(0) | None | N/A | None |
| Monitor(1) | Periodic (new bar + refresh interval + validity expired) | N/A | Display only |
| Filter(2) | Periodic | Fail-open: entries proceed at 1.0× | Blocks opposing signals; modulates size |
| Gate(3) | On-demand when entry signal fires; periodic if mgmt permissions + open positions | Fail-closed: pending signals discarded | Approves/rejects entries; manages positions |
| Autonomous(4) | Periodic; bypasses validity for open positions | Falls back to broker SL/TP only | Full trade lifecycle |

### Filter Signals Multipliers

**Bias multiplier** (direction alignment):

| Bias | Aligned Trade | Against Trade |
|------|-------|--------|
| Neutral | 1.0× | 1.0× |
| Bullish | 1.1× | 0.75× |
| Bearish | 1.1× (short) | 0.75× (long) |
| StrongBull | 1.25× | 0.5× |
| StrongBear | 1.25× (short) | 0.5× (long) |

**Risk multiplier**:

| Risk Mode | Multiplier | Allows Trading |
|----|----|---------|
| Normal | 1.0× | Yes |
| Reduced | 0.5× | Yes |
| Minimal | 0.25× | Yes |
| Aggressive | 1.5× | Yes |
| Avoid | 0.0× | No |

Combined = bias × risk. Example: StrongBull + Reduced on long = 1.25 × 0.5 = 0.625×.

### Directional Filtering

- `AllowsLong()`: true if bias is Neutral, Bullish, or StrongBull.
- `AllowsShort()`: true if bias is Neutral, Bearish, or StrongBear.
- `AllowsTrading()`: true if risk_mode ≠ "avoid".

### Gate Signal Behaviour

Signal cached with: direction, entry price, SL, TP, stop size (points), reward (points), R:R ratio, volume, order type.
Gate signal timeout: default 100 seconds. Cooldown: 5 seconds between requests.
Gate decision: bias aligns + risk normal/aggressive = Allow; bias opposes or risk=avoid = Filter; risk reduced/minimal = Reduce.

### Assessment Lifecycle

Default → Valid → Stale → Expired.
Confidence must meet `MinConfidenceThreshold` (default 0.30).
Assessment must not be expired. Status must be Valid or Stale.

### Decision History

Automatic. Records each assessment with outcome evaluation. Rolling buffer of last 5 records. Persisted to `.hist` files (JSON). Fed back into prompts with accuracy statistics. No configuration needed.

### Closed Trade History

When `AllowClosedHistory=true`: last 5 closed trades from current session included in prompt. Each contains direction, entry/exit prices, profit (points, R-multiple), duration, close reason.

### Trade Management Permissions

| Permission | Actions | Autonomous | Gated |
|----|---------|:---:|:-----:|
| AllowOpen | open_long, open_short | ✓ | — |
| AllowClose | close | ✓ | ✓ |
| AllowModifySL | modify_sl, modify_both* | ✓ | ✓ |
| AllowModifyTP | modify_tp, modify_both* | ✓ | ✓ |
| AllowPlaceOrders | place_buy/sell_stop/limit | ✓ | — |
| AllowCancelOrders | cancel_order | ✓ | ✓ |

*modify_both requires both AllowModifySL AND AllowModifyTP.

### JSON Response Schema

```json
{
  "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": "string",
  "key_levels": {"resistance": [price,...], "support": [price,...]},
  "warnings": ["string",...],
  "referenced_events": ["EVT_001",...],
  "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": 0.0,
    "tp_price": 0.0,
    "lots": 0.0,
    "risk_percent": 0.0,
    "confidence": 0.0-1.0,
    "only_if_profitable": false,
    "valid_minutes": 5,
    "reasoning": "string"
  }]
}
```

**Field defaults**: regime→"unknown", bias→"neutral", risk_mode→"normal", confidence→0.5, regime/bias_confidence→overall confidence, valid_minutes→15.
**Instruction fields**: ticket=0→new position; entry_price=0→market price; lots=0→calculate from risk_percent; risk_percent=0→EA default.
**Instructions array**: present in Autonomous (full actions) and Gate+mgmt (close, modify_sl, modify_tp, modify_both, hold only). Omitted in other modes.
All prices normalised to tick size. All volumes normalised to broker limits. Risk overrides reduce size rather than reject.

### Trading Style Guidance

| Style | Filter/Gate Behaviour | Autonomous Behaviour |
|-------|--------|-------|
| Conservative(0) | Strict thresholds, prefer avoid/reduced, block marginal signals | Selective entries, tight stops (1-2R), modest targets (1.5-2R), trail aggressively |
| Moderate(1) | Balanced, avoid only for clearly adverse conditions | Standard thresholds, allow ambiguous signals |
| Aggressive(2) | Only block with strong opposing evidence, prefer normal/aggressive | Wider stops (2-4R), larger targets (3-5R), may pyramid |

### Grounded Events vs Raw Data

- **Grounded Events Only (0)**: Compact JSON, prevents hallucination, lowest cost. Default and recommended.
- **Raw Only (1)**: Timestamped buffer values. Maximum flexibility, 5-10× more tokens.
- **Both (2)**: For debugging/comparison.

---

## 7. Complete Preset File Examples

One complete preset file (Example 1) followed by three diff-style examples — one per AI mode. Example 1 is a full structural reference showing every section and setting. Examples 2–4 show only the settings that differ from the [Defaults.set Template](#defaultsset-template), making each mode's requirements immediately visible. Annotations follow each example as condensed key points.

### Example 1: Script-Only Strategy (AI Disabled)

```ini
;
; Section Header
;
InpTradeTool_Name=Full Auto Fibonacci Retracement Strategy
InpTradeTool_Description=A fully automated Fibonacci retracement strategy, designed for optimal performance on most major and minor currency pairs on the 1-hour timeframe. Before running, ensure to optimise for profit and drawdown in Tester > Settings. For a semi-automated approach, you can manually adjust the take-profit levels to align with what we call 'the most likely area for price to reach next,' further enhancing your win rate.
InpTradeTool_Author=
InpTradeTool_Comments=
InpTradeTool_PresetFile=NTL-FibonacciRetracement.set
InpTradeTool_Market=Major Pairs, Minor Pairs, H1
InpTradeTool_AIGenerated=
InpTradeTool_AIModel=
InpTradeTool_CategoryType=1
InpTradeTool_SettingsVersion=1.000
InpTradeTool_ChartImages=41/911/usdchf-m30-raw-trading-ltd.png
;
; Section Scripts
;
InpTradeTool_ScriptLongEntry=Signal('AutoFib1') == Bullish && Ask() > FibPrice('AutoFib1',0.762) && Low() <= LowestLow(15) && Ask() < HighestHigh(10) ? Ask() : 0 
InpTradeTool_ScriptLongInitialStop=Ask() - (ATR1() * VAR0)
InpTradeTool_ScriptLongTrailingStop=
InpTradeTool_ScriptLongLots=
InpTradeTool_ScriptLongTakeProfit=
InpTradeTool_ScriptLongBreakeven=
InpTradeTool_ScriptLongExit=
InpTradeTool_ScriptShortEntry=Signal('AutoFib1') == Bearish && FibPrice('AutoFib1',0.762) > Bid() && High() >= HighestHigh(15) && Bid() > LowestLow(10) ? Bid() : 0
InpTradeTool_ScriptShortInitialStop=Bid() + (ATR1() * VAR0)
InpTradeTool_ScriptShortTrailingStop=
InpTradeTool_ScriptShortLots=
InpTradeTool_ScriptShortTakeProfit=
InpTradeTool_ScriptShortBreakeven=
InpTradeTool_ScriptShortExit=
InpTradeTool_ScriptAITrigger=
;
; Section Risk Management
;
InpTradeTool_MaxRiskPerTradeInPercent=1.00
InpTradeTool_MaxRiskPerTradeInMoney=0.00
InpTradeTool_MaxLossMarketAsPercentageOfBalance=0.00
InpTradeTool_MaxLossAccountAsPercentageOfBalance=0.00
InpTradeTool_TrailMaxLoss=false
InpTradeTool_DeviationInPoints=0
;
; Section Position Management
;
InpTradeTool_MaxLots=0.00
InpTradeTool_MaxOpenPositionsMarket=1
InpTradeTool_MaxOpenPositionsSymbol=0
InpTradeTool_MaxOpenPositionsAccount=0
InpTradeTool_MaxOpenPositionsHour=0
InpTradeTool_MaxOpenPositionsDay=0
InpTradeTool_MaxOpenPositionsWeek=0
InpTradeTool_MaxTradesPerUnitTime=0
InpTradeTool_MaxTradesUnitTimeInSeconds=0
InpTradeTool_MinTradeIntervalInSeconds=0
InpTradeTool_MagicNumber=123456789
;
; Section Trading Rules
;
InpTradeTool_AutoTradeEnabled=true
InpTradeTool_AutoTradeRefreshMode=1 // SeriesRefreshMode_EveryBar
InpTradeTool_AllowedTradeTypes=0 // AllowedTradeTypes_BuysAndSells
;
; Section Time Management
;
InpTradeTool_StartOfDayTime=00:00
InpTradeTool_EndOfDayTime=00:00
InpTradeTool_ClosePositionTimeOffsetInSeconds=0
InpTradeTool_CloseOrderTimeOffsetInSeconds=0
InpTradeTool_ClosePositionAtEndOfDay=false
InpTradeTool_ClosePositionAtEndOfWeek=false
InpTradeTool_CloseOrderAtEndOfDay=false
InpTradeTool_CloseOrderAtEndOfWeek=false
;
; Section Stop Management
;
InpTradeTool_InitialStopValue=3.00
InpTradeTool_InitialStopValueUnits=0 // TradeToolStopUnits_ATR
InpTradeTool_TrailingStopValue=4.00
InpTradeTool_TrailingStopValueUnits=0 // TradeToolStopUnits_ATR
InpTradeTool_TrailingStopValueEnabled=false
InpTradeTool_EnableTrailingStopAfterBreakeven=true
InpTradeTool_EnableTrailingStopAfterProfitInPercent=0.0000
InpTradeTool_UseSoftSLs=false
InpTradeTool_MinSLTPPriceChangeUnitsInPoints=10
;
; Section Exit Management
;
InpTradeTool_TakeProfitStopValue=1.00
InpTradeTool_TakeProfitStopValueUnits=3 // TradeToolStopUnits_R
InpTradeTool_TakeProfitStopValueEnabled=true
InpTradeTool_UseSoftTPs=false
InpTradeTool_BreakevenStopValue=1.00
InpTradeTool_BreakevenStopValueUnits=3 // TradeToolStopUnits_R
InpTradeTool_BreakevenStopValueEnabled=true
InpTradeTool_MaxGainMarketAsPercentageOfBalance=0.00
InpTradeTool_MaxGainAccountAsPercentageOfBalance=0.00
InpTradeTool_MinProfitInPoints=0
InpTradeTool_MinProfitInPointsTimeInSeconds=0
;
; Section Custom Indicators
;
InpTradeTool_CustomIndicator0=NTL\ABH(1,14,3).ex5,0,1
InpTradeTool_CustomIndicator1=NTL\ADX(1,14).ex5,0,1,2,3
InpTradeTool_CustomIndicator2=NTL\ADXW(1,14).ex5,0,1,2,3
InpTradeTool_CustomIndicator3=+NTL\ATR(1,14).ex5,0
InpTradeTool_CustomIndicator4=+NTL\AutoFib(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,0,4,8,50,100,0.0,10,250,45,'0.35,1',0,0,3,14).ex5,0,1,2,3,4,5
InpTradeTool_CustomIndicator5=NTL\BB(1,20,2.0).ex5,0,1,2,3
InpTradeTool_CustomIndicator6=NTL\ChoCh(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,55,3,6,55,100,0.0,8,250,45,'0.35,1',0,0,3,14,500).ex5,0,1,2,3,4,5,6,7,8
InpTradeTool_CustomIndicator7=NTL\FVG(1,0,400,0.1,0.0,0.4,3.0,0.1,3,14,0,0,0.0).ex5,0,1,2,3,4,5,6
InpTradeTool_CustomIndicator8=NTL\HLines(1,0,800,15,'S2;R2',35,0.0,0.5,100).ex5,0,1
InpTradeTool_CustomIndicator9=NTL\JCP(1).ex5,0,1
InpTradeTool_CustomIndicator10=NTL\Keltner(1,20,1,2.25).ex5,0,1,2,3
InpTradeTool_CustomIndicator11=NTL\LP(1,0,800,1,6,7,400,14,7.0,2.5,0.0,0,0.0,0.0,0.0,10,80,2).ex5,0,1,2,3,4,5,6,7,8,9,10,11,12
InpTradeTool_CustomIndicator12=NTL\MA(1,50,1,200,1).ex5,0,1,2
InpTradeTool_CustomIndicator13=NTL\MACD(1,12,26,9).ex5,0,4
InpTradeTool_CustomIndicator14=NTL\Markets(1).ex5,0
InpTradeTool_CustomIndicator15=NTL\OsMA(1,12,26,9).ex5,0,1
InpTradeTool_CustomIndicator16=NTL\PL(1,16408,4).ex5,0
InpTradeTool_CustomIndicator17=NTL\PP(1).ex5,0,1,2,3,4,5,6,7,8
InpTradeTool_CustomIndicator18=NTL\PSAR(1,0.02,0.2).ex5,0,1
InpTradeTool_CustomIndicator19=NTL\RSI(1,14,1,70,30).ex5,0,1
InpTradeTool_CustomIndicator20=NTL\Scalper(1,10000,0.7,10000,0.3,0.6,10000,0.5,0.3,10000,0.7,10,1,5,0.0,5000,1,1,19,24).ex5,0,1,2,3,4,5,6
InpTradeTool_CustomIndicator21=NTL\Stochastic(1,5,3,3,80,20).ex5,0,1,2
InpTradeTool_CustomIndicator22=NTL\ST(1,13,1.5).ex5,0,1
InpTradeTool_CustomIndicator23=NTL\TLines(1,2.5,'S2;R2',25,2,15,2,1.0,400,50,800,0.1,0.1,100).ex5,0,1,2,3,4,5,6,7,8
InpTradeTool_CustomIndicator24=NTL\TSI(1,13,21,8,25,-25,1).ex5,0,1,2
;
; Section User Variables
;
InpTradeTool_UserVAR0=6;1,2,3,4,5,6,7,8,9,10
;
; Section Backtesting & Optimisation
;
InpTradeTool_TesterAccountType=0 // AccountType_Standard
InpTradeTool_TesterCommissionPerLot=0.00
InpTradeTool_TesterSpreadSchedule=
InpTradeTool_TesterSpreadScheduleEnabled=false
InpTradeTool_TesterSpreadApplyToMid=true
InpTradeTool_TesterStartingBalance=100000
InpTradeTool_TesterStartDate=0 // 1970.01.01 00:00
InpTradeTool_TesterEndDate=0 // 1970.01.01 00:00
InpTradeTool_TesterLeverage=100
InpTradeTool_OptimiseEnabled=false
InpTradeTool_OptimisePerformanceMetric1=31 // PerformanceMetric_PerformanceIndex
InpTradeTool_OptimisePerformanceMetric2=41 // PerformanceMetric_TotalProfit
InpTradeTool_OptimiseFrequencyInDays=0
InpTradeTool_OptimiseDayOfWeek=6
InpTradeTool_OptimiseHourOfDay=0
InpTradeTool_OptimiseLookbackInDays=0
InpTradeTool_OptimiseLastDate=0 // 1970.01.01 00:00
InpTradeTool_OptimiseNextDate=0 // 1970.01.01 00:00
InpTradeTool_OptimiseFilter53=1000.00;0.00 // StatType_TotalProfit
;
; Section Compliance
;
InpTradeTool_ComplianceProfitTargetRate=0.10
InpTradeTool_ComplianceOverallLossLimitRate=0.10
InpTradeTool_ComplianceDailyLossLimitRate=0.05
InpTradeTool_ComplianceIntradayDDLimitRate=0.05
InpTradeTool_ComplianceMinTradingDays=4
InpTradeTool_ComplianceProfitTargetWarnRate=0.75
InpTradeTool_ComplianceOverallLossWarnRate=0.90
InpTradeTool_ComplianceDailyLossWarnRate=0.90
InpTradeTool_ComplianceIntradayDDWarnRate=0.90
InpTradeTool_ComplianceLogLevel=1 // Breaches Only
InpTradeTool_ComplianceTimeZone=1 // EU Central
InpTradeTool_ComplianceBoundaryHour=0
InpTradeTool_ComplianceBoundaryMinute=0
InpTradeTool_ComplianceBoundarySecond=0
;
; Section AI
;
InpTradeTool_AIMode=0
InpTradeTool_AIProvidersConfigString=provider=Gemini,model=gemini-3-pro-preview,temperature=0.2
InpTradeTool_AIStrategyInstructions=
InpTradeTool_AITradingStyle=1
InpTradeTool_AIUrls=https%3A%2F%2Fwww.dailyforex.com%2Frss%2Fforexnews.xml%0Ahttps%3A%2F%2Fwww.fxstreet.com%2Frss%0Ahttps%3A%2F%2Fstockmarketwatch.com%2Flive%2Fstock-market-today%0Ahttps%3A%2F%2Finvestinglive.com%2F%0Ahttps%3A%2F%2Fwww.fxstreet.com%2Frss%2Fanalysis
InpTradeTool_AITimeframes=
InpTradeTool_AIMaxHistorySizeInBars=300
InpTradeTool_AIRefreshIntervalMinutes=5
InpTradeTool_AIMinConfidenceThreshold=0.3000
InpTradeTool_AIUseValidUntil=false
InpTradeTool_AIExportMode=0
InpTradeTool_AIGateSignalTimeoutInSeconds=100
InpTradeTool_AIAllowOpen=true
InpTradeTool_AIAllowClose=true
InpTradeTool_AIAllowModifySL=true
InpTradeTool_AIAllowModifyTP=true
InpTradeTool_AIAllowPlaceOrders=true
InpTradeTool_AIAllowCancelOrders=true
InpTradeTool_AIIncludeClosedHistory=true
InpTradeTool_AIIncludeCandlestickChart=false
;
; Section Other
;
InpTradeTool_ATRPeriod=14
InpTradeTool_ChartImports=0 // IndicatorChartImports_Current
InpTradeTool_SymbolImports=
InpTradeTool_AlertTemplate={time}: strategy:{strategy} {symbol},{timeframe} {orderType} signal at: {entryPrice} sl={sl} tp={tp}
;
; Section Debugging
;
InpTradeTool_DebugFlags=0
;
; Section Interface
;
InpTradeTool_GuiTabsFlagMask=63
InpTradeTool_LineWidth=1
InpTradeTool_LineStyle=2 // STYLE_DOT
InpTradeTool_CPColor=0 // clrBlack
InpTradeTool_SLColor=200 // 200,0,0
InpTradeTool_TPColor=32768 // clrGreen
InpTradeTool_BEColor=8421376 // clrTeal
InpTradeTool_SOColor=0 // clrBlack
InpTradeTool_LOColor=0 // clrBlack
InpTradeTool_FontSize=9
InpTradeTool_ChartEdgeAlignment=1 // ChartEdgeAlignment_Right
```

**Key points:** AIMode=0 (Disabled). No AI section active. All scripts handle entry/exit. AutoFib1 and ATR1 have `+` prefix (referenced in scripts). VAR0 used with optimisation range. OptimiseFilter53 present.

### Example 2: AI Filter Signals — RSI Trend Strategy (EURUSD H1)

All settings not shown use [Defaults.set Template](#defaultsset-template) values.

```ini
; --- Section Header ---
InpTradeTool_Name=AI-Filtered RSI Trend Strategy
InpTradeTool_Description=RSI crossover entries filtered by MA trend direction. AI Filter Signals mode provides periodic market assessment to block entries during unfavourable conditions. Optimise VAR0 (ATR stop multiplier) for best risk-adjusted performance.
InpTradeTool_PresetFile=NTL-AI-FilteredRSITrend.set
InpTradeTool_Market=EURUSD H1
InpTradeTool_AIGenerated=true

; --- Section Scripts ---
InpTradeTool_ScriptLongEntry=Signal('RSI1') == Bullish && MA1(1,0) > MA1(1,1) ? Ask() : 0
InpTradeTool_ScriptLongInitialStop=Ask() - (ATR1() * VAR0)
InpTradeTool_ScriptLongExit=MA1(1,0) < MA1(1,1) && MA1(2,0) >= MA1(2,1) ? Bid() : 0
InpTradeTool_ScriptShortEntry=Signal('RSI1') == Bearish && MA1(1,0) < MA1(1,1) ? Bid() : 0
InpTradeTool_ScriptShortInitialStop=Bid() + (ATR1() * VAR0)
InpTradeTool_ScriptShortExit=MA1(1,0) > MA1(1,1) && MA1(2,0) <= MA1(2,1) ? Ask() : 0
InpTradeTool_ScriptAITrigger=Hour() >= 8 && Hour() < 21 ? 1 : 0

; --- Section Time Management ---
InpTradeTool_StartOfDayTime=08:00
InpTradeTool_EndOfDayTime=21:00
InpTradeTool_ClosePositionAtEndOfDay=true

; --- Section Custom Indicators (+ prefix and parameter changes only) ---
InpTradeTool_CustomIndicator3=+NTL\ATR(1,14).ex5,0
InpTradeTool_CustomIndicator6=+NTL\ChoCh(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,55,3,6,55,100,0.0,8,250,45,'0.35,1',0,0,3,14,500).ex5,0,1,2,3,4,5,6,7,8
InpTradeTool_CustomIndicator11=+NTL\LP(1,0,800,1,6,7,400,14,7.0,2.5,0.0,0,0.0,0.0,0.0,10,80,2).ex5,0,1,2,3,4,5,6,7,8,9,10,11,12
InpTradeTool_CustomIndicator12=+NTL\MA(1,50,1,200,1).ex5,0,1,2
InpTradeTool_CustomIndicator19=+NTL\RSI(1,14,1,60,40).ex5,0,1

; --- Section User Variables ---
InpTradeTool_UserVAR0=2.0;1.0,1.5,2.0,2.5,3.0

; --- Section AI ---
InpTradeTool_AIMode=2 // Filter Signals
InpTradeTool_AIStrategyInstructions=Focus on trend continuation setups only.\nAssign bullish/bearish bias only when the most recent CHoCH event confirms the direction.\nSet risk_mode to 'reduced' during the first and last hour of the trading session.\nSet risk_mode to 'avoid' when regime is 'ranging' - wait for breakout confirmation.\nKey levels should prioritise recent swing highs and lows from CHoCH and LP events.
InpTradeTool_AIUrls=https%3A%2F%2Fwww.dailyforex.com%2Frss%2Fforexnews.xml%0Ahttps%3A%2F%2Fwww.fxstreet.com%2Frss
InpTradeTool_AITimeframes=H1,H4
InpTradeTool_AIRefreshIntervalMinutes=10
InpTradeTool_AIMinConfidenceThreshold=0.4000
```

**Key points:** AIMode=2 (Filter Signals). RSI1 configured with OB=60/OS=40 (non-default). ATR1, ChoCh, LP, MA1 and RSI1 have `+` prefix (referenced in scripts or AI Strategy Instructions). ScriptAITrigger gates AI requests to 08:00–21:00. AIStrategyInstructions uses literal `\n` newlines. AIUrls percent-encoded with `%0A` separators. AITimeframes=H1,H4 includes the chart timeframe plus H4 for broader trend context.

### Example 3: AI Gated Trading with Position Management — BB Breakout (GBPUSD H1)

All settings not shown use [Defaults.set Template](#defaultsset-template) values.

```ini
; --- Section Header ---
InpTradeTool_Name=AI-Gated BB Breakout with Management
InpTradeTool_Description=Bollinger Band breakout entries gated by AI approval. AI uses CHoCH confirmation to validate breakout signals. Position management enabled: AI trails stops and closes early on opposing structure.
InpTradeTool_PresetFile=NTL-AI-GatedBBBreakout.set
InpTradeTool_Market=GBPUSD H1
InpTradeTool_AIGenerated=true

; --- Section Scripts ---
InpTradeTool_ScriptLongEntry=Close(1) > BB1(1,1) && Volume(1) > Volume(2) * 1.5 ? Ask() : 0
InpTradeTool_ScriptLongInitialStop=BB1(0,0) - ATR1()
InpTradeTool_ScriptShortEntry=Close(1) < BB1(1,2) && Volume(1) > Volume(2) * 1.5 ? Bid() : 0
InpTradeTool_ScriptShortInitialStop=BB1(0,0) + ATR1()

; --- Section Position Management ---
InpTradeTool_MaxOpenPositionsDay=2

; --- Section Time Management ---
InpTradeTool_StartOfDayTime=08:00
InpTradeTool_EndOfDayTime=20:00

; --- Section Custom Indicators (+ prefix changes only) ---
InpTradeTool_CustomIndicator3=+NTL\ATR(1,14).ex5,0
InpTradeTool_CustomIndicator5=+NTL\BB(1,20,2.0).ex5,0,1,2,3
InpTradeTool_CustomIndicator6=+NTL\ChoCh(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,55,3,6,55,100,0.0,8,250,45,'0.35,1',0,0,3,14,500).ex5,0,1,2,3,4,5,6,7,8

; --- Section AI ---
InpTradeTool_AIMode=3 // Gated Trading
InpTradeTool_AIStrategyInstructions=Approve breakout entries only when CHoCH confirms direction.\nSet risk_mode to 'avoid' if no recent CHoCH supports signal direction.\nTrail stops to break-even after 1R profit.\nClose early if CHoCH fires in the opposite direction.
InpTradeTool_AIUrls=https%3A%2F%2Fwww.dailyforex.com%2Frss%2Fforexnews.xml%0Ahttps%3A%2F%2Fwww.fxstreet.com%2Frss
InpTradeTool_AITimeframes=H1
InpTradeTool_AIMaxHistorySizeInBars=200
InpTradeTool_AIMinConfidenceThreshold=0.4000
InpTradeTool_AIAllowOpen=false
InpTradeTool_AIAllowClose=true
InpTradeTool_AIAllowModifySL=true
InpTradeTool_AIAllowModifyTP=false
InpTradeTool_AIAllowPlaceOrders=false
InpTradeTool_AIAllowCancelOrders=false
```

**Key points:** AIMode=3 (Gated Trading). AIAllowOpen=false, AIAllowPlaceOrders=false (entries from scripts only — Gated Trading rule). AIAllowClose=true, AIAllowModifySL=true (AI manages positions). ATR1, BB1 and ChoCh have `+` prefix (referenced in scripts or AI Strategy Instructions). Entry scripts are AI-blind — no `Ai*()` functions. ScriptAITrigger is empty — in Gated mode, AI requests are triggered on-demand by gate signals. MaxOpenPositionsDay=2 limits daily entries. No UserVARs used.

### Example 4: Fully Autonomous AI — Smart Money Concepts (EURUSD M15)

All settings not shown use [Defaults.set Template](#defaultsset-template) values. All entry/exit scripts are empty — the AI controls all trade decisions.

```ini
; --- Section Header ---
InpTradeTool_Name=Autonomous SMC Strategy
InpTradeTool_Description=Fully autonomous AI-driven Smart Money Concepts strategy. The AI opens positions on CHoCH-confirmed direction with FVG entry zones, sets stops behind FVG boundaries, and targets LP levels. No entry or exit scripts; AI controls all trade decisions via Strategy Instructions.
InpTradeTool_PresetFile=NTL-AI-AutonomousSMC.set
InpTradeTool_Market=EURUSD M15
InpTradeTool_AIGenerated=true

; --- Section Risk Management ---
InpTradeTool_MaxLossMarketAsPercentageOfBalance=5.00
InpTradeTool_MaxLossAccountAsPercentageOfBalance=10.00

; --- Section Position Management ---
InpTradeTool_MaxOpenPositionsHour=1
InpTradeTool_MaxOpenPositionsDay=3

; --- Section Time Management ---
InpTradeTool_StartOfDayTime=07:00
InpTradeTool_EndOfDayTime=21:00
InpTradeTool_ClosePositionAtEndOfDay=true
InpTradeTool_ClosePositionAtEndOfWeek=true

; --- Section Custom Indicators (+ prefix changes only) ---
InpTradeTool_CustomIndicator6=+NTL\ChoCh(1,0,'0.0,0.3,0.5,0.618,0.762,1.0',3,55,3,6,55,100,0.0,8,250,45,'0.35,1',0,0,3,14,500).ex5,0,1,2,3,4,5,6,7,8
InpTradeTool_CustomIndicator7=+NTL\FVG(1,0,400,0.1,0.0,0.4,3.0,0.1,3,14,0,0,0.0).ex5,0,1,2,3,4,5,6
InpTradeTool_CustomIndicator11=+NTL\LP(1,0,800,1,6,7,400,14,7.0,2.5,0.0,0,0.0,0.0,0.0,10,80,2).ex5,0,1,2,3,4,5,6,7,8,9,10,11,12

; --- Section AI ---
InpTradeTool_AIMode=4 // Autonomous
InpTradeTool_AIStrategyInstructions=Trade Smart Money Concepts: FVG entries, CHoCH confirmations, liquidity sweeps.\nOpen positions only after a CHoCH confirms direction AND an unfilled FVG provides an entry zone.\nSet SL behind the FVG zone boundary (the high for shorts, the low for longs).\nSet TP at the next LP (liquidity pool) level visible in grounded events.\nIf no clear FVG entry exists near current price, return an empty instructions array.\nTrail stops to break-even once position reaches 1R profit.\nClose positions early if a CHoCH event fires in the opposite direction.\nNever use 'aggressive' risk_mode. Use 'reduced' when regime is 'volatile'.
InpTradeTool_AIUrls=https%3A%2F%2Fwww.dailyforex.com%2Frss%2Fforexnews.xml%0Ahttps%3A%2F%2Fwww.fxstreet.com%2Frss
InpTradeTool_AITimeframes=M15,H1
InpTradeTool_AIMaxHistorySizeInBars=100
InpTradeTool_AIMinConfidenceThreshold=0.5000
InpTradeTool_AIAllowOpen=true
InpTradeTool_AIAllowClose=true
InpTradeTool_AIAllowModifySL=true
InpTradeTool_AIAllowModifyTP=false
InpTradeTool_AIAllowPlaceOrders=false
InpTradeTool_AIAllowCancelOrders=false
```

**Key points:** AIMode=4 (Autonomous). AIAllowOpen=true, AIStrategyInstructions non-empty (required for Autonomous per [AI Mode Constraints](#ai-mode-constraints)). All entry/exit scripts empty. AIMinConfidenceThreshold=0.50 (higher for autonomous). AIRefreshIntervalMinutes=5 (frequent for M15). MaxLossMarket=5%, MaxLossAccount=10% (risk guardrails). MaxOpenPositionsHour=1, Day=3 (frequency limits). ClosePositionAtEndOfDay=true, AtEndOfWeek=true (no overnight/weekend holds). ChoCh, FVG and LP have `+` prefix (referenced in AI Strategy Instructions). Remaining indicators provide grounded events to AI without `+` prefix.

---

## 8. Strategy Prompt Templates

The examples above show complete preset files. When using AI modes 2–4, the `AIStrategyInstructions` setting needs carefully crafted content. The templates below provide effective starting points for each trading approach.

Effective AIStrategyInstructions content for each trading approach. These are injected verbatim into the AI's system prompt. Use literal "\n" as newline separator in preset files.

### Trend-Following

```
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

```
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

```
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

```
Favor '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 grounded events.
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.
```

---

## 9. EAsiScript Pattern Examples

The [EAsiScript Reference](#easiscript-reference) above lists all available functions. This section provides curated, ready-to-use script patterns that combine those functions into common trading logic.

Curated script patterns covering common constructions. Each shows Long direction; mirror for Short (swap Ask↔Bid, reverse comparisons, invert direction checks).

### Entry Patterns

**MA Crossover (cross detection):**
`Close(1) > MA1(1,0) && Close(2) <= MA1(2,0) ? Ask() : 0`
Current bar above MA, previous bar at or below → crossover detected.

**RSI Oversold with confirmation:**
`RSI1(1) < 30 && RSI1(1) > RSI1(2) && Close(1) > Open(1) ? Ask() : 0`
RSI below 30 + turning up + bullish candle → reversal entry.

**Signal-based (indicator built-in signal):**
`Signal('ST1') == Bullish ? Ask() : 0`
SuperTrend flips bullish. Works with any indicator that provides Signal().

**BB Breakout with volume:**
`Close(1) > BB1(1,1) && Volume(1) > Volume(2) * 1.5 ? Ask() : 0`
Close above upper band + 50% volume increase → breakout confirmed.

**Fibonacci retracement:**
`Signal('AutoFib1') == Bullish && Ask() > FibPrice('AutoFib1',0.618) ? Ask() : 0`
AutoFib bullish signal + price above 0.618 level.

**HLines breakout:**
`HLines1(1) > 0 && HLineBreak('HLines1','ATR1') == 1 && Volume(1) > Volume(2) ? Ask() : 0`
Resistance level exists + bullish break confirmed by ATR + volume rising.

**Multi-condition trend:**
`Trend('MA1') == Bullish && Close(1) > MA1(1,0) && Low(1) > MA1(1,0) ? Ask() : 0`
Trend bullish + close above MA + entire bar above MA → strong trend confirmation.

### Stop Loss Patterns

**ATR-based initial SL:**
`Ask() - (ATR1() * VAR0)`
Entry minus ATR × variable multiplier (optimisable via VAR0).

**Indicator-based SL:**
`BB1(0,0) - ATR1()`
Middle Bollinger Band minus one ATR.

**Swing low SL:**
`Low(LowestLow(3)) - ATR1(1)`
Below the lowest low of last 3 bars, with ATR buffer.

**Fibonacci level SL:**
`FibPrice('AutoFib1',0.382) - ATR1(1)`
Below the 0.382 retracement level with ATR buffer.

### Trailing Stop Patterns

**MA-tracking trail:**
`MA1(1,0) - ATR1(1) * 0.5`
Follows moving average with half-ATR buffer. Tightens as price trends.

**Condition-adaptive trail:**
`RSI1(1) > 70 ? High(1) - ATR1(1) * 0.5 : Low(1) - ATR1(1)`
Tight trail when overbought, wide trail otherwise.

**Band-following trail:**
`BB1(1,0)`
Trails the middle Bollinger Band.

**Level-based trail:**
`HLines1(1,0)`
Trails the nearest support level.

### Take Profit Patterns

**R-ratio TP (2:1):**
`OrderPrice() + (OrderPrice() - SL()) * 2`
Twice the initial risk distance from entry.

**ATR-based TP:**
`OrderPrice() + ATR1(1) * 3`
Three ATR above entry price.

**Fibonacci level TP:**
`FibPrice('AutoFib1',1.0)`
Target the 1.0 Fibonacci extension.

**Band projection TP:**
`BB1(1,1) + (BB1(1,1) - BB1(1,0))`
Projects the band width above the upper band.

**Dynamic OBOS TP:**
`OBOS('RSI1') == -1 ? Bid() : OrderPrice() + ATR1(1) * 3`
Close at market when RSI overbought, otherwise target 3 ATR.

### Breakeven Patterns

**ATR-distance BE:**
`OrderPrice() + ATR1(1)`
Move stop to entry after one ATR move in favour.

**Condition-based BE:**
`RSI1(1) > 50 ? OrderPrice() : 0`
Move to breakeven when RSI crosses above 50. Returns 0 (no action) otherwise.

**Price-confirmation BE:**
`High(1) > OrderPrice() + ATR1(1) ? OrderPrice() : 0`
Move to breakeven after price makes a new high beyond 1 ATR from entry.

**Fibonacci level BE:**
`FibPrice('AutoFib1',0.786)`
Move stop to 0.786 level once reached.

### Exit Patterns

**Opposite MA cross:**
`MA1(1,0) < MA1(1,1) && MA1(2,0) >= MA1(2,1) ? Bid() : 0`
Fast MA crosses below slow MA → exit long. Cross detection on completed bars.

### AI-Integrated Entry Patterns (Filter Signals Mode Only)

> **Important:** These AI-enhanced entry patterns are suitable for **Filter Signals** mode only. In **Gated Trading** mode, entry scripts must be AI-blind — they must not reference any `Ai*()` functions. See [Gated Trading in Detail](EAsiTrader.md#gated-trading-in-detail).

**AI bias filter:**
`AiIsBullish() == 1 && Close(1) > MA1(1,0) ? Ask() : 0`
Only enter long when AI bias is bullish AND price above MA.

**AI confidence + regime filter:**
`AiIsValid() == 1 && AiIsTrending() == 1 && Signal('RSI1') == Bullish ? Ask() : 0`
Only enter when AI confirms trending regime.

### AI-Integrated Lots Pattern

**Risk-modulated position sizing:**
`AiCombinedMultiplier(1) * 0.01`
Uses combined bias+risk multiplier to scale lot size. Returns 0 when AI says "avoid".

### AI Trigger Script Patterns

**Session time gate:**
`Hour() >= 8 && Hour() < 21 ? 1 : 0`
Only request AI during 08:00–21:00 trading hours.

**Volatility filter:**
`ATR1() > ATR1(0,0,20) * 1.2 ? 1 : 0`
Only request AI when current ATR exceeds 20-bar average by 20% (elevated volatility).

**Trend confirmation gate:**
`Trend('MA1') != 0 ? 1 : 0`
Only request AI when MA shows a clear trend (not flat).

---

## 10. Layered Preset Generation

The [Complete Preset File Examples](#complete-preset-file-examples) above show finished strategies as single files. This section takes a different approach: decomposing a strategy into progressive layers so each entry condition can be tested in isolation.

Generate a set of progressive .set files from a strategy, each adding one logical concern to the entry script. Enables incremental testing — run each layer in the Tester to isolate what each condition contributes to trade selection.

### Concept

A strategy with N entry conditions produces N layer files (minimum 2, maximum 6). Layer 1 has only the core signal. Each subsequent layer adds one condition. The final layer is the complete strategy. Non-entry settings (risk, stops, indicators, user variables) are identical across all layers.

**When to offer layered presets:** Any time a user asks for a strategy with 2+ entry conditions. Proactively suggest layered output so the user can test incrementally rather than debug a monolithic preset.

### Layer Categories

Assign each condition to the first matching category:

| Category | What it adds | Typical position |
|---|------|----------|
| **Signal** | Primary indicator signal (`Signal()`, `Cross()`) | Always L1 |
| **Trend** | Trend alignment (`Trend()`, MA direction) | L2–L3 |
| **Confirmation** | Secondary indicator, price action (`IsEngulfing`, `BarTrend`) | L2–L4 |
| **Filter** | Time, session, volatility, OBOS (`Hour()`, `OBOS()`) | L3–L5 |
| **Refinement** | Structure quality, price position (`StructureQuality()`) | L4–L6 |

### Decomposing an Existing Preset

1. Parse `ScriptLongEntry` and `ScriptShortEntry` at top-level `&&` operators (respecting parentheses and ternary nesting). Each `&&` clause is a candidate layer boundary.
2. Classify each condition into a layer category based on the functions it uses.
3. Group conditions that reference the same indicator or serve the same logical purpose into one layer.
4. L1 is always the core signal — the single condition most central to the strategy idea. It must produce trades on its own.
5. The final layer's entry scripts must be identical to the original file's entry scripts.
6. If only one side has a script (e.g. long is set, short is empty), only decompose the side that has a script. The empty side stays empty in all layers.
7. All non-entry settings (risk, stops, indicators, user variables, AI, etc.) carry through from the original preset unchanged. Never modify or overwrite the original file.

### Building Layers from a Description

1. Identify the core signal from the user's description → L1.
2. Each additional condition from the description → one layer.
3. Determine shared settings: markets, timeframe, indicators needed, risk, stops, non-entry scripts.
4. All indicators needed by the final layer appear in every layer (with or without `+` prefix). The indicator list is identical across all files.

### What Changes Between Layers

| Setting | Changes? |
|---------|---|
| `Name` | Yes — includes layer label, e.g. `Strategy (L1: Signal)` |
| `Description` | Yes — explains what this layer tests and what to look for |
| `Comments` | Yes — e.g. `Layer 1 of 3: core signal only` |
| `PresetFile` | Yes — matches the filename |
| `ScriptLongEntry` | Yes — cumulative conditions up to this layer |
| `ScriptShortEntry` | Yes — cumulative conditions up to this layer |
| `+` prefix on indicators | Yes — only indicators referenced in this layer's scripts |
| Everything else | **No** — identical across all layers |

### `+` Prefix Rules

The indicator list is identical across all layers — same indicators, same parameters, same buffers. Only `+` prefixes change per layer:

- Add `+` to indicators referenced in that layer's entry scripts.
- Indicators referenced in non-entry scripts (e.g. `ATR1()` in `ScriptLongInitialStop`) keep `+` in every layer.
- Indicators not referenced in any script in that layer have no `+`.

### File Naming

Format: `{StrategyName}-L{N}-{Category}.set`

- Use PascalCase for the strategy name, no spaces.
- Category is a short (one word) name from the layer category table.
- When decomposing an existing file, derive the strategy name from the original filename (strip `.set`).

Examples: `MACrossover-L1-Signal.set`, `MACrossover-L2-Trend.set`, `MACrossover-L3-Session.set`

### Entry Script Pattern

Each layer uses the ternary pattern with cumulative conditions:

```
L1 Long:  condition1 ? Ask() : 0
L2 Long:  condition1 && condition2 ? Ask() : 0
L3 Long:  condition1 && condition2 && condition3 ? Ask() : 0
```

Long scripts return `Ask()` (or a specific price for pending orders) on success, `0` on no signal. Short scripts return `Bid()`. Do not use nested ternaries.

### Construction Method

Start from the [Defaults.set Template](#defaultsset-template) and modify values — never construct from scratch. Every layer file must be a complete, standalone preset that can be loaded independently in the Tester.

### Example

Given a strategy with this long entry:
```
Signal('MA1') == Bullish && Trend('RSI1') == Bullish && Hour(LN) >= 8 && Hour(LN) <= 16 ? Ask() : 0
```

Layer decomposition:

| Layer | File | Long Entry | `+` Indicators |
|-------|------|----|---------|
| L1 | Strategy-L1-Signal.set | `Signal('MA1') == Bullish ? Ask() : 0` | MA1 |
| L2 | Strategy-L2-Trend.set | `Signal('MA1') == Bullish && Trend('RSI1') == Bullish ? Ask() : 0` | MA1, RSI1 |
| L3 | Strategy-L3-Session.set | Full expression (matches original) | MA1, RSI1 |

Testing workflow: L1 produces the most trades (signal only). L2 should reduce count (trend-aligned only). L3 restricts to London session hours. Compare results across layers to evaluate each filter's contribution.

---

## 11. User Prompt Patterns for Preset Generation

When this file has been provided to the AI session, the user only needs to describe their strategy — all rules, templates, and validation checklists are already available. Some users may include the legacy compliance block below from older documentation. If present, treat it as confirmation they want a complete `.set` file with strict format compliance.

### Legacy Compliance Block

> "The preset file **must strictly comply** with all the 'Rules for Creating EAsiTrader Preset Files'. Use the Defaults.set Preset File as a template. Verify your content by cross referencing your sections and settings with those from the template. **Any deviation or omission will be considered a failure to complete the task**."

### Script-Only Prompt Structure

Users typically specify: symbol/timeframe, entry logic, stop loss method, take profit method, optional exit/trailing/breakeven, risk per trade. They do NOT specify indicator creation strings, section ordering, or boilerplate settings — the AI must fill these from the Defaults.set template and indicator reference.

**Example prompts (condensed):**

- "RSI strategy on EURUSD M30. Long when RSI crosses above 30, short when crosses below 70. SL at 2× ATR. TP at 50 points. Exit on opposite RSI condition."
- "MA crossover on GBPUSD H1. Enter when fast MA crosses slow MA with RSI confirmation. SL below swing low with ATR buffer. TP at 3:1 R:R. Exit on MA cross reversal."
- "Multi-timeframe on EURUSD M15/H1. H1 trend via MA, M15 momentum via RSI, volume confirmation. ATR-based stops, trail after breakeven. London/NY overlap. 1% risk."
- "BB breakout on GBPUSD H1. Long above upper band with volume surge. Trailing stop 2 ATR. Exit if price re-enters bands. 1% risk."
- "Mean reversion on USDJPY M15. Long when RSI below 30 and returns above. SL at low of last 5 bars. TP at 2× SL distance. Exit on MA cross or RSI above 70."
- "Asian session range breakout on USDJPY M30. Range 00:00–03:00. Entry on range high/low break. Minimum range size via ATR. Exit before lunch or at 1:1 R:R."
- "S/R strategy on EURGBP H1 using HLines. Reversal candle at S/R with RSI confirmation. SL beyond level + buffer. TP at next S/R level. London session only."
- "Double-zero level strategy on USDCAD H4. Reversal at 00 levels. MACD cross + volume confirmation. ATR SL. Trail to BE after 20 pips. 1% risk scaled by distance."

### AI-Enabled Prompt Structure

Users who want AI modes specify a "Strategy Details" section (same as script-only) PLUS an "AI Configuration" section. The AI Configuration typically includes: mode number/name, Strategy Instructions content, AI timeframes (chart TF + any higher TFs), confidence threshold, refresh interval, URLs, and permission flags.

**Key pattern:** Users specify StrategyInstructions as plain English that the AI must convert to "\n"-encoded format in the preset file. If users DON'T specify StrategyInstructions, the AI should select an appropriate template from [Strategy Prompt Templates](#strategy-prompt-templates) based on the strategy type and mode.

**Example prompts (condensed):**

**Filter Signals (Mode 2):**
"AI-filtered RSI trend on EURUSD H1. Long: RSI crosses above 40 + MA trend bullish. Short: RSI crosses below 60 + MA trend bearish. SL: 2× ATR. TP: 2R. BE: after 1R. Exit: opposite MA trend. Hours 08:00–21:00, close at EOD.
AI Config: Filter Signals mode. AI trigger: 08:00–21:00 only. Strategy Instructions: trend continuation focus, reduced risk first/last hour, avoid when ranging. Additional TF: H4. Confidence: 0.40. Refresh: 10 min. URLs: DailyForex RSS, FXStreet RSS."

**Gated Trading (Mode 3):**
"AI-gated BB breakout on GBPUSD H1. Entry: close above upper BB + 1.5× volume spike. SL: middle BB minus 1 ATR. TP: 2× band width. BE: after 1 ATR. Hours 08:00–20:00. Max 2 trades/day. Entry scripts must be AI-blind (no Ai*() functions).
AI Config: Gated Trading mode. AI approves entries + manages positions. Strategy Instructions: approve only when CHoCH confirms, avoid if no CHoCH support, trail to BE after 1R, close early on opposite CHoCH. Additional TF: M15. Confidence: 0.40. Refresh: 15 min. Permissions: AIAllowOpen=false, AIAllowPlaceOrders=false, AIAllowClose=true, AIAllowModifySL=true."

**Autonomous (Mode 4):**
"Fully autonomous SMC strategy on EURUSD M15. No scripts — AI handles everything. Risk: 1% per trade, 5% per market, 10% account. Hours 07:00–21:00. Close EOD and EOW. Max 1/market, 1/hour, 3/day.
AI Config: Autonomous mode. Strategy Instructions: Trade SMC — FVG entries, CHoCH confirmations, LP targets. Open only after CHoCH confirms + unfilled FVG entry zone. SL behind FVG boundary. TP at next LP. Empty instructions if no setup. Trail to BE after 1R. Close on opposite CHoCH. Never aggressive risk_mode, use reduced when volatile. Additional TF: H1. Confidence: 0.50. Refresh: 5 min. Permissions: AIAllowOpen=true, AIAllowClose=true, AIAllowModifySL=true."

### Handling Incomplete Requests

Users often provide minimal specifications. When key information is missing:

| Missing element | Default action |
|---|---|
| No AI mode specified but mentions "AI" | Default to Filter Signals (mode 2) — safest AI mode |
| No StrategyInstructions content | Select template from [Strategy Prompt Templates](#strategy-prompt-templates) matching strategy type |
| No confidence threshold | Use 0.30 for Filter/Gated, 0.50 for Autonomous |
| No refresh interval | Use 15 min for H1+, 10 min for M15-M30, 5 min for M1-M5 |
| No AITimeframes specified | Include the chart timeframe plus one timeframe up (e.g. M5→M5,H1; M15→M15,H1; H1→H1,H4; H4→H4,D1) |
| No URLs | Include DailyForex RSS + FXStreet RSS as defaults |
| No permissions specified | Follow mode constraints from [AI Mode Constraints](#ai-mode-constraints) |
| No risk per trade | Default to 1% |
| No trading hours | Use 08:00–21:00 (London+NY) |
| No indicator parameters | Use defaults from [Indicator Reference](#indicator-reference) |
| "Add AI to my strategy" (vague) | Ask user which mode, or default Filter Signals with trend-following template |

---

*Derived from: EAsiTrader User Guide, EAsiScript User Guide, Learn EAsiScript Guide, EAsiTrader AI User Guide.*
*Rev: 28.03.2026 LP — add MaxDisplacementBars, MinDisplacementABH, MaxSameSideStructDiffABH params (P15-P17), shift ExportType to P18*
*Rev: 29.03.2026 LP — rename MarketRangeABH to MaxSameSideStructDiffABH, MarketTrendABH to MinSameSideStructDiffABH*
*Rev: 29.03.2026 — add Time Management section to Settings Quick Reference*
*Rev: 29.03.2026 — restructure: move User Prompt Patterns to end (Section 11), add Layered Preset transition, group indicators by function*
*Rev: 02.04.2026 LP — add StructureTrendLookback (P15) and StructureTrendThreshold (P16), shift ExportType to P17; fix SweptExternalAge buffer (add structureTrend fields); remove phantom ABHMultiples from StructureData*
*Rev: 02.04.2026 LP — expand StructureTrendDirection from 3 to 7 states (cross-reference count + swing strength); shift strength bits to 19-28*
*Rev: 02.04.2026 LP — add SweptExternalAge buffer extraction examples (BSLAge, SSLAge, TrendDirection, TrendStrength)*
