Strategy · Pine Script v6 · On the chart

KAIROS LC Swing Engine V4.1 {JXS_918}

by woi-6ix

KAIROS LC Swing Engine V4.1 is an overlay trading strategy combining Nadaraya-Watson kernel swing triggers with Lorentzian Classification machine learning confirmation and adaptive session filters.

View on GitHub

Repaints

GitHub stars1on the repository
Pine versionv6current
Lines of code1,580
Settings40inputs
LicenceMPL-2.0
Last update13 days ago11 Nov 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

1,580 lines of Pine Script v6 from KAIROS_LC_Swing_Engine_V4_1_JXS_918.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

KAIROS_LC_Swing_Engine_V4_1_JXS_918.pine











// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// See https://mozilla.org/MPL/2.0/
// Lorentzian feature/distance/ANN and kernel regression logic adapted from jdehorty.
// KAIROS strategy adaptation: JXS_918.
// WHY KAIROS?
// Kairos personifies the opportune moment in Greek mythology.
// The name reflects waiting for a kernel swing signal and the enabled
// confirmation filters to align within the selected trading session.
//@version=6
//@strategy_alert_message {{strategy.order.alert_message}}
strategy(
     title="KAIROS LC Swing Engine V4.1 {JXS_918}",
     shorttitle="KAIROS V4.1",
     overlay=true,
     pyramiding=0,
     process_orders_on_close=true,
     calc_on_order_fills=true,
     currency=currency.USD,
     precision=4,
     max_labels_count=500
)
import jdehorty/KernelFunctions/2 as kernels
import jdehorty/MLExtensions/2 as ml
// Naming explanation appears in settings and when hovering over the table title.
const string KAIROS_STORY = "Kairos personifies the opportune moment in Greek mythology. This engine is named for waiting until a kernel swing signal and the enabled confirmation filters align within the selected trading session."
bool showKairosStory = input.bool(true, "Show naming explanation in table header", group="About KAIROS", tooltip=KAIROS_STORY)
// ============================================================================
// COLORS
// ============================================================================
color cGreen = color.new(#00E5C3, 0)
color cRed = color.new(#FF4D6D, 0)
color cGray = color.new(#B0BEC5, 0)
color cTransparent = color.new(color.black, 100)
color cGold = #FFD700
color cSilver = #C0C0C0
color cNavy = #0A0E1A
color cDarkNavy = #0F1420
color cLabel = #B0BEC5
// ============================================================================
// GENERAL / DIRECTION
// ============================================================================
string GROUP_GENERAL = "General"
bool enableLongs = input.bool(true, "Enable Longs", group=GROUP_GENERAL, inline="dir")
bool enableShorts = input.bool(true, "Enable Shorts", group=GROUP_GENERAL, inline="dir")
bool exitOnOppositeKernelFlip = input.bool(true, "Exit on Opposite Kernel Flip", group=GROUP_GENERAL)
bool closeAtSessionEnd = input.bool(true, "Close Position at Session End", group=GROUP_GENERAL)
// ============================================================================
// EDITABLE NEW YORK TRADING SESSION
// Default: 09:30 AM to 03:00 PM America/New_York.
// Entries are based on the bar's closing timestamp.
// ============================================================================
string GROUP_SESSION = "Trading Session"
string tradeTimezone = input.string("America/New_York", "Timezone", group=GROUP_SESSION)
int startHour = input.int(
     9,
     "Start Hour",
     minval=0,
     maxval=23,
     group=GROUP_SESSION,
     inline="start"
)
int startMinute = input.int(
     30,
     "Minute",
     minval=0,
     maxval=59,
     group=GROUP_SESSION,
     inline="start"
)
int endHour = input.int(
     15,
     "End Hour",
     minval=0,
     maxval=23,
     group=GROUP_SESSION,
     inline="end"
)
int endMinute = input.int(
     0,
     "Minute",
     minval=0,
     maxval=59,
     group=GROUP_SESSION,
     inline="end"
)
int startOfDay = startHour * 60 + startMinute
int endOfDay = endHour * 60 + endMinute
bool sessionValid = startOfDay < endOfDay
int barCloseMinute =
     hour(time_close, tradeTimezone) * 60 +
     minute(time_close, tradeTimezone)
bool inTradingSession = (
     timeframe.isintraday and
     sessionValid and
     not na(time_close) and
     barCloseMinute >= startOfDay and
     barCloseMinute < endOfDay
)
int cutoffTimestamp = timestamp(
     tradeTimezone,
     year(time_close, tradeTimezone),
     month(time_close, tradeTimezone),
     dayofmonth(time_close, tradeTimezone),
     endHour,
     endMinute
)
bool sessionCutoffBar = (
     timeframe.isintraday and
     sessionValid and
     not na(time_close) and
     time_close >= cutoffTimestamp and
     (
         na(time_close[1]) or
         time_close[1] < cutoffTimestamp
     )
)
// ============================================================================
// KERNEL REGRESSION
// The plotted green/red line is the primary KAIROS trade engine.
// ============================================================================
string GROUP_KERNEL = "Kernel Regression"
float kernelSource = input.source(
     close,
     "Source",
     group=GROUP_KERNEL
)
bool showKernel = input.bool(
     true,
     "Show Kernel Line",
     group=GROUP_KERNEL,
     inline="display"
)
bool useKernelSmoothing = input.bool(
     true,
     "Enhanced Smoothing",
     group=GROUP_KERNEL,
     inline="display"
)
int kernelLookback = input.int(
     8,
     "Lookback Window",
     minval=3,
     maxval=100,
     group=GROUP_KERNEL
)
float kernelRelativeWeight = input.float(
     8.0,
     "Relative Weighting",
     minval=0.25,
     maxval=25.0,
     step=0.25,
     group=GROUP_KERNEL
)
int kernelRegressionLevel = input.int(
     25,
     "Regression Level",
     minval=2,
     maxval=100,
     group=GROUP_KERNEL
)
int kernelLag = input.int(
     6,
     "Smoothing Lag",
     minval=1,
     maxval=20,
     group=GROUP_KERNEL
)
float yhat1 = kernels.rationalQuadratic(
     kernelSource,
     kernelLookback,
     kernelRelativeWeight,
     kernelRegressionLevel
)
int gaussianLookback = math.max(
     1,
     kernelLookback - kernelLag
)
float yhat2 = kernels.gaussian(
     kernelSource,
     gaussianLookback,
     kernelRegressionLevel
)
bool kernelBullishRate = (
     yhat1 > yhat1[1]
)
bool kernelBearishRate = (
     yhat1 < yhat1[1]
)
bool kernelBullishSmooth = (
     yhat2 >= yhat1
)
bool kernelBearishSmooth = (
     yhat2 <= yhat1
)
bool kernelBullish = (
     useKernelSmoothing
     ? kernelBullishSmooth
     : kernelBullishRate
)
bool kernelBearish = (
     useKernelSmoothing
     ? kernelBearishSmooth
     : kernelBearishRate
)
bool kernelBullishFlip = (
     bar_index > 2 and
     kernelBullish and
     not kernelBullish[1]
)
bool kernelBearishFlip = (
     bar_index > 2 and
     kernelBearish and
     not kernelBearish[1]
)
color kernelColor = (
     kernelBullish
     ? cGreen
     : kernelBearish
     ? cRed
     : cGray
)
plot(
     showKernel ? yhat1 : na,
     title="KAIROS V4.1 Kernel Regression",
     color=kernelColor,
     linewidth=2
)
// ============================================================================
// SLOPE FILTER
// Requires the kernel to have enough directional slope in ATR-normalized terms.
// A value of 0.05 means the kernel moved 0.05 ATR over the chosen lookback.
// ============================================================================
string GROUP_SLOPE = "Slope Filter"
bool useSlopeFilter = input.bool(
     false,
     "Use Slope Filter",
     group=GROUP_SLOPE
)
int slopeLookbackBars = input.int(
     2,
     "Slope Lookback Bars",
     minval=1,
     maxval=20,
     group=GROUP_SLOPE
)
int slopeAtrLength = input.int(
     14,
     "ATR Length",
     minval=1,
     group=GROUP_SLOPE
)
float minSlopeAtr = input.float(
     0.05,
     "Minimum Slope (ATR units)",
     minval=0.0,
     step=0.01,
     group=GROUP_SLOPE
)
float slopeAtr = ta.atr(
     slopeAtrLength
)
float kernelSlopeRaw = (
     yhat1 -
     yhat1[slopeLookbackBars]
)
float kernelSlopeAtr = (
     slopeAtr > 0
     ? kernelSlopeRaw / slopeAtr
     : 0.0
)
bool longSlopePass = (
     not useSlopeFilter or
     kernelSlopeAtr >= minSlopeAtr
)
bool shortSlopePass = (
     not useSlopeFilter or
     kernelSlopeAtr <= -minSlopeAtr
)
// ============================================================================
// VOLATILITY PUSH FILTER
//
// Volatility Score:
//   +1 ATR expansion
//   +1 Candle range / ATR expansion
//   +1 Volume expansion
//
// Default minimum = 2 of 3.
//
// Direction:
// LONG requires strong bullish push candle.
// SHORT requires strong bearish push candle.
// ============================================================================
string GROUP_VP = "Volatility Push"
bool useVolatilityPushFilter = input.bool(
     true,
     "Require Volatility Push",
     group=GROUP_VP
)
bool showVolatilityPush = input.bool(
     true,
     "Show VP Markers",
     group=GROUP_VP
)
int vpConfirmationWindow = input.int(
     10,
     "Confirmation Window (bars)",
     minval=0,
     maxval=10,
     group=GROUP_VP,
     tooltip="0 = Volatility Push must occur on the same bar as the kernel color change."
)
int vpFastAtrLength = input.int(
     5,
     "Fast ATR Length",
     minval=1,
     group=GROUP_VP,
     inline="atr"
)
int vpSlowAtrLength = input.int(
     20,
     "Slow ATR Length",
     minval=2,
     group=GROUP_VP,
     inline="atr"
)
float vpMinAtrRatio = input.float(
     1.10,
     "Min ATR Ratio",
     minval=0.1,
     step=0.05,
     group=GROUP_VP
)
float vpMinRangeAtr = input.float(
     1.25,
     "Min Range / ATR",
     minval=0.1,
     step=0.05,
     group=GROUP_VP
)
int vpVolumeLength = input.int(
     20,
     "Volume Average Length",
     minval=1,
     group=GROUP_VP
)
float vpMinVolumeRatio = input.float(
     1.50,
     "Min Volume Ratio",
     minval=0.1,
     step=0.05,
     group=GROUP_VP
)
int vpMinScore = input.int(
     2,
     "Minimum Volatility Score",
     minval=1,
     maxval=3,
     group=GROUP_VP
)
float vpMinBodyAtr = input.float(
     0.80,
     "Min Body / ATR",
     minval=0.0,
     step=0.05,
     group=GROUP_VP
)
float vpMinBodyRange = input.float(
     0.65,
     "Min Body / Candle Range",
     minval=0.0,
     maxval=1.0,
     step=0.05,
     group=GROUP_VP
)
float vpBullCloseLocation = input.float(
     0.70,
     "Bull Close Location >=",
     minval=0.0,
     maxval=1.0,
     step=0.05,
     group=GROUP_VP
)
float vpBearCloseLocation = input.float(
     0.30,
     "Bear Close Location <=",
     minval=0.0,
     maxval=1.0,
     step=0.05,
     group=GROUP_VP
)
float vpFastAtr = ta.atr(
     vpFastAtrLength
)
float vpSlowAtr = ta.atr(
     vpSlowAtrLength
)
float vpRange = math.max(
     high - low,
     syminfo.mintick
)
float vpBody = math.abs(
     close - open
)
float vpCloseLocation = (
     (close - low) /
     vpRange
)
float vpVolumeAverage = ta.sma(
     volume,
     vpVolumeLength
)
float vpAtrRatio = (
     vpSlowAtr > 0
     ? vpFastAtr / vpSlowAtr
     : 0.0
)
float vpRangeAtr = (
     vpSlowAtr > 0
     ? vpRange / vpSlowAtr
     : 0.0
)
float vpVolumeRatio = (
     vpVolumeAverage > 0
     ? volume / vpVolumeAverage
     : 0.0
)
float vpBodyAtr = (
     vpSlowAtr > 0
     ? vpBody / vpSlowAtr
     : 0.0
)
float vpBodyRange = (
     vpRange > 0
     ? vpBody / vpRange
     : 0.0
)
bool vpAtrPoint = (
     vpAtrRatio >= vpMinAtrRatio
)
bool vpRangePoint = (
     vpRangeAtr >= vpMinRangeAtr
)
bool vpVolumePoint = (
     vpVolumeRatio >= vpMinVolumeRatio
)
int vpScore = (
     (vpAtrPoint ? 1 : 0) +
     (vpRangePoint ? 1 : 0) +
     (vpVolumePoint ? 1 : 0)
)
bool vpQualified = (
     vpScore >= vpMinScore
)
bool bullDirectionalCandle = (
     close > open and
     vpCloseLocation >= vpBullCloseLocation and
     vpBodyAtr >= vpMinBodyAtr and
     vpBodyRange >= vpMinBodyRange
)
bool bearDirectionalCandle = (
     close < open and
     vpCloseLocation <= vpBearCloseLocation and
     vpBodyAtr >= vpMinBodyAtr and
     vpBodyRange >= vpMinBodyRange
)
bool bullVolatilityPush = (
     vpQualified and
     bullDirectionalCandle
)
bool bearVolatilityPush = (
     vpQualified and
     bearDirectionalCandle
)
int bullPushAge = nz(
     ta.barssince(bullVolatilityPush),
     100000
)
int bearPushAge = nz(
     ta.barssince(bearVolatilityPush),
     100000
)
bool bullPushConfirmed = (
     not useVolatilityPushFilter or
     (
         bullPushAge <= vpConfirmationWindow and
         bullPushAge < bearPushAge
     )
)
bool bearPushConfirmed = (
     not useVolatilityPushFilter or
     (
         bearPushAge <= vpConfirmationWindow and
         bearPushAge < bullPushAge
     )
)
plotshape(
     showVolatilityPush and
     bullVolatilityPush,
     title="Bullish Volatility Push",
     style=shape.triangleup,
     location=location.belowbar,
     color=cGreen,
     size=size.tiny,
     text="VP+"
)
plotshape(
     showVolatilityPush and
     bearVolatilityPush,
     title="Bearish Volatility Push",
     style=shape.triangledown,
     location=location.abovebar,
     color=cRed,
     size=size.tiny,
     text="VP-"
)
// ============================================================================
// 2R PROFIT / STOP MODULE
//
// Stop = ATR × Stop ATR Multiple
// Target = Stop distance × R
//
// Default:
// Stop = 1 ATR
// Target = 2R
// ============================================================================
string GROUP_RISK = "2R Profit / Stop"
bool useRiskManagement = input.bool(
     true,
     "Use Profit / Stop",
     group=GROUP_RISK
)
int riskAtrLength = input.int(
     14,
     "Risk ATR Length",
     minval=1,
     group=GROUP_RISK,
     inline="risk"
)
float stopAtrMultiple = input.float(
     1.5,
     "Stop ATR Multiple",
     minval=0.05,
     step=0.05,
     group=GROUP_RISK,
     inline="risk"
)
float rewardRiskMultiple = input.float(
     0.4,
     "Profit Target (R)",
     minval=0.10,
     step=0.25,
     group=GROUP_RISK
)
bool showRiskLevels = input.bool(
     true,
     "Show Stop / Target",
     group=GROUP_RISK
)
float riskAtr = ta.atr(
     riskAtrLength
)
var float longStop = na
var float longTarget = na
var float shortStop = na
var float shortTarget = na
// ============================================================================
// V4.1 EDITABLE QUANTITY AND INDEPENDENT MAXIMUM CASH LOSS
// Default account currency is USD. Cash protection uses the actual filled size
// and symbol point value. It shares the original exit bracket so the cash stop
// cannot lose quantity coverage to a separate ATR/target exit reservation.
// ============================================================================
string GROUP_SIZE = "V4.1 Entry Quantity"
float entryQuantityInput = input.float(2500.0, "Entry Quantity / Shares", minval=0.001, step=1, group=GROUP_SIZE, tooltip="Underlying shares/contracts per new position. Rounded down to the symbol minimum. This input overrides the quantity in strategy Properties. Reversals close the existing position and open this quantity in the new direction.")
float entryQuantity = math.floor(entryQuantityInput / syminfo.mincontract) * syminfo.mincontract
string GROUP_CASH = "V4.1 Maximum Stop Loss"
bool enableCashLossCap = input.bool(false, "Enable Maximum Cash Loss", group=GROUP_CASH)
float maximumCashLoss = input.float(500, "Maximum Loss (account currency)", minval=1, step=25, group=GROUP_CASH, tooltip="Default 500 USD per open position. Uses strategy account currency. Cash protection remains enabled if Use Profit / Stop is disabled. A stop cannot guarantee this amount on gaps/slippage; fees are excluded.")
bool showCashLossBox = input.bool(false, "Show Maximum Loss Box", group=GROUP_CASH, tooltip="Hide the box without disabling the cap. Use Enable Maximum Cash Loss to turn off protection.")
string cashBoxPosition = input.string("Bottom Left", "Loss Box Position", options=["Bottom Left", "Bottom Right", "Top Left", "Top Right"], group=GROUP_CASH)
f_cashStopDistance(float quantity) =>
    float tickValue = quantity * syminfo.pointvalue * syminfo.mintick
    float cashTicks = tickValue > 0 ? math.floor(strategy.convert_to_symbol(maximumCashLoss) / tickValue) : na
    cashTicks * syminfo.mintick
float proposedCashDistance = f_cashStopDistance(entryQuantity)
bool entryQuantityReady = entryQuantity >= syminfo.mincontract and (not enableCashLossCap or (not na(proposedCashDistance) and proposedCashDistance >= syminfo.mintick))
// Entries are skipped when the chosen size cannot fit even a one-tick cash stop.
// ============================================================================
// V4.1 LORENTZIAN CLASSIFICATION — OPTIONAL ENTRY CONFIRMATION
// Feature normalization and logarithmic distance adapted from jdehorty.
// Uses JDE-style chronological ANN acceptance and a persistent bounded vote queue.
// The rolling history is bounded, current-query samples are excluded, and fill
// callbacks do not create extra samples or fresh ML entry decisions.
// ============================================================================
string GROUP_LC = "V4.1 Lorentzian Classification"
bool useLCFilter = input.bool(true, "Enable LC Direction Filter", group=GROUP_LC, tooltip="Master switch for LC classification and its ML prediction confirmation. OFF bypasses both, leaving V3 filters plus any enabled EMA/SMA filters.")
int lcNeighborsCount = input.int(8, "Neighbor Count", minval=1, maxval=100, group=GROUP_LC)
int lcHistoryBars = input.int(2000, "Maximum Training History (bars)", minval=100, maxval=5000, group=GROUP_LC, tooltip="Rolling past-bar window for ANN candidates. Buffers never exceed this size. Large histories increase computation time.")
int lcFeatureCount = input.int(5, "Feature Slots to Consider", minval=1, maxval=5, group=GROUP_LC, tooltip="Use the first N feature slots, then apply their individual Enable switches. At least one considered slot must be enabled when LC is on.")
float lcTrainingSource = input.source(close, "Training Label Source", group=GROUP_LC)
string GROUP_PREDICTION = "V4.1 ML Prediction Confirmation"
bool useMLPredictionFilter = input.bool(true, "Enable ML Prediction Filter", group=GROUP_PREDICTION, tooltip="When LC is enabled, require a current net vote score in the trade direction. OFF uses the LC direction state alone, which persists through zero votes. The LC master switch disables both checks.")
int minMLPredictionVotes = input.int(1, "Minimum Net Directional Votes", minval=1, maxval=100, group=GROUP_PREDICTION, tooltip="Long: prediction >= this value. Short: prediction <= its negative. Must not exceed Neighbor Count when this filter is enabled. This is a vote threshold, not a probability of profit.")
string GROUP_LC_FEATURES = "V4.1 LC Feature Engineering"
bool lcEnableFeature1 = input.bool(true, "Enable Feature 1", group=GROUP_LC_FEATURES, inline="f1")
string lcFeature1Type = input.string("RSI", "Type", options=["RSI", "WT", "CCI", "ADX"], group=GROUP_LC_FEATURES, inline="f1")
int lcFeature1A = input.int(14, "Parameter A", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p1")
int lcFeature1B = input.int(1, "Parameter B", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p1")
bool lcEnableFeature2 = input.bool(true, "Enable Feature 2", group=GROUP_LC_FEATURES, inline="f2")
string lcFeature2Type = input.string("WT", "Type", options=["RSI", "WT", "CCI", "ADX"], group=GROUP_LC_FEATURES, inline="f2")
int lcFeature2A = input.int(10, "Parameter A", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p2")
int lcFeature2B = input.int(11, "Parameter B", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p2")
bool lcEnableFeature3 = input.bool(true, "Enable Feature 3", group=GROUP_LC_FEATURES, inline="f3")
string lcFeature3Type = input.string("CCI", "Type", options=["RSI", "WT", "CCI", "ADX"], group=GROUP_LC_FEATURES, inline="f3")
int lcFeature3A = input.int(20, "Parameter A", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p3")
int lcFeature3B = input.int(1, "Parameter B", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p3")
bool lcEnableFeature4 = input.bool(true, "Enable Feature 4", group=GROUP_LC_FEATURES, inline="f4")
string lcFeature4Type = input.string("ADX", "Type", options=["RSI", "WT", "CCI", "ADX"], group=GROUP_LC_FEATURES, inline="f4")
int lcFeature4A = input.int(20, "Parameter A", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p4")
int lcFeature4B = input.int(2, "Parameter B (ADX ignores B)", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p4")
bool lcEnableFeature5 = input.bool(true, "Enable Feature 5", group=GROUP_LC_FEATURES, inline="f5")
string lcFeature5Type = input.string("RSI", "Type", options=["RSI", "WT", "CCI", "ADX"], group=GROUP_LC_FEATURES, inline="f5")
int lcFeature5A = input.int(9, "Parameter A", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p5")
int lcFeature5B = input.int(1, "Parameter B", minval=1, maxval=200, group=GROUP_LC_FEATURES, inline="p5")
string GROUP_EMA = "V4.1 EMA Entry Filter"
bool useEMAEntryFilter = input.bool(false, "Enable EMA Entry Filter", group=GROUP_EMA)
int emaEntryLength = input.int(200, "EMA Length", minval=1, maxval=2000, group=GROUP_EMA)
bool showEMAEntryLine = input.bool(false, "Show EMA Line", group=GROUP_EMA)
string GROUP_SMA = "V4.1 SMA Entry Filter"
bool useSMAEntryFilter = input.bool(false, "Enable SMA Entry Filter", group=GROUP_SMA)
int smaEntryLength = input.int(200, "SMA Length", minval=1, maxval=2000, group=GROUP_SMA)
bool showSMAEntryLine = input.bool(false, "Show SMA Line", group=GROUP_SMA)
string GROUP_ML_DISPLAY = "V4.1 Filter Display"
bool showMLFilterStats = input.bool(true, "Show New Filter Statistics", group=GROUP_ML_DISPLAY)
bool showMLDataWindow = input.bool(true, "Show ML Score in Data Window", group=GROUP_ML_DISPLAY)
// V4.1 LC display controls. Both options are independent and display only.
bool showLCBarColours = input.bool(false, "Show Bar Colours", group=GROUP_ML_DISPLAY, tooltip="Colour confirmed candles using the current LC net prediction. Requires the LC Direction Filter to be enabled and warmed up.")
bool showLCBarPrediction = input.bool(false, "Show Bar Prediction Value", group=GROUP_ML_DISPLAY, tooltip="Show the actual LC net vote above positive candles and below negative/neutral candles. Votes are not probabilities. TradingView retains up to 500 labels.")

f_lcFeature(simple string featureType, simple int parameterA, simple int parameterB) =>
    switch featureType
        "RSI" => ml.n_rsi(close, parameterA, parameterB)
        "WT" => ml.n_wt(hlc3, parameterA, parameterB)
        "CCI" => ml.n_cci(close, parameterA, parameterB)
        "ADX" => ml.n_adx(high, low, close, parameterA)
        => na
// Evaluate every execution so TA series histories remain consistent.
float lcFeature1 = f_lcFeature(lcFeature1Type, lcFeature1A, lcFeature1B)
float lcFeature2 = f_lcFeature(lcFeature2Type, lcFeature2A, lcFeature2B)
float lcFeature3 = f_lcFeature(lcFeature3Type, lcFeature3A, lcFeature3B)
float lcFeature4 = f_lcFeature(lcFeature4Type, lcFeature4A, lcFeature4B)
float lcFeature5 = f_lcFeature(lcFeature5Type, lcFeature5A, lcFeature5B)
bool lcUse1 = lcFeatureCount >= 1 and lcEnableFeature1
bool lcUse2 = lcFeatureCount >= 2 and lcEnableFeature2
bool lcUse3 = lcFeatureCount >= 3 and lcEnableFeature3
bool lcUse4 = lcFeatureCount >= 4 and lcEnableFeature4
bool lcUse5 = lcFeatureCount >= 5 and lcEnableFeature5
int lcActiveFeatureCount = (lcUse1 ? 1 : 0) + (lcUse2 ? 1 : 0) + (lcUse3 ? 1 : 0) + (lcUse4 ? 1 : 0) + (lcUse5 ? 1 : 0)
bool lcFeaturesReady = (not lcUse1 or not na(lcFeature1)) and (not lcUse2 or not na(lcFeature2)) and (not lcUse3 or not na(lcFeature3)) and (not lcUse4 or not na(lcFeature4)) and (not lcUse5 or not na(lcFeature5))
if barstate.isfirst and useLCFilter
    if lcActiveFeatureCount == 0
        runtime.error("KAIROS V4.1: enable at least one considered LC feature, or turn off Enable LC Direction Filter.")
    if useMLPredictionFilter and minMLPredictionVotes > lcNeighborsCount
        runtime.error("KAIROS V4.1: Minimum Net Directional Votes cannot exceed Neighbor Count. Lower the threshold or disable ML Prediction Filter.")
// Primitive varip arrays/state survive order-fill recalculations and rollback.
varip array<float> lcHistory1 = array.new<float>()
varip array<float> lcHistory2 = array.new<float>()
varip array<float> lcHistory3 = array.new<float>()
varip array<float> lcHistory4 = array.new<float>()
varip array<float> lcHistory5 = array.new<float>()
varip array<int> lcHistoryLabels = array.new<int>()
varip array<int> lcHistoryBarIds = array.new<int>()
varip array<float> lcDistances = array.new<float>()
varip array<int> lcVotes = array.new<int>()
varip array<int> lcVoteBarIds = array.new<int>()
varip int lcLastProcessedBar = na
varip int lcPredictionBar = na
varip int lcPrediction = 0
varip int lcDirection = 0
varip float lcLastObservedPosition = 0.0
varip int lcLastObservedClosedTrades = 0
bool lcFillRecalculation = strategy.position_size != lcLastObservedPosition or strategy.closedtrades != lcLastObservedClosedTrades
lcLastObservedPosition := strategy.position_size
lcLastObservedClosedTrades := strategy.closedtrades
f_lcDistance(int index) =>
    float distance = 0.0
    if lcUse1
        distance += math.log(1 + math.abs(lcFeature1 - array.get(lcHistory1, index)))
    if lcUse2
        distance += math.log(1 + math.abs(lcFeature2 - array.get(lcHistory2, index)))
    if lcUse3
        distance += math.log(1 + math.abs(lcFeature3 - array.get(lcHistory3, index)))
    if lcUse4
        distance += math.log(1 + math.abs(lcFeature4 - array.get(lcHistory4, index)))
    if lcUse5
        distance += math.log(1 + math.abs(lcFeature5 - array.get(lcHistory5, index)))
    distance
if useLCFilter and barstate.isconfirmed and not lcFillRecalculation and (na(lcLastProcessedBar) or lcLastProcessedBar != bar_index)
    lcLastProcessedBar := bar_index
    lcPredictionBar := na
    if lcFeaturesReady and not na(lcTrainingSource[4]) and not na(lcTrainingSource)
        int oldestAllowedBar = math.max(0, bar_index - lcHistoryBars)
        // Expire votes whose source has fallen outside the rolling bar window.
        int expiredVoteIndex = array.size(lcVotes) - 1
        while expiredVoteIndex >= 0
            if array.get(lcVoteBarIds, expiredVoteIndex) < oldestAllowedBar
                array.remove(lcVotes, expiredVoteIndex)
                array.remove(lcDistances, expiredVoteIndex)
                array.remove(lcVoteBarIds, expiredVoteIndex)
            expiredVoteIndex -= 1
        int candidateCount = array.size(lcHistoryLabels)
        float lastDistance = -1.0
        if candidateCount > 0
            for candidateIndex = 0 to candidateCount - 1
                int candidateBar = array.get(lcHistoryBarIds, candidateIndex)
                // Preserve JDE's skip of indices divisible by four. Search only
                // previous samples; the current query is appended AFTER voting.
                if candidateBar >= oldestAllowedBar and candidateBar < bar_index and candidateBar % 4 != 0
                    float distance = f_lcDistance(candidateIndex)
                    if not na(distance) and distance >= lastDistance
                        lastDistance := distance
                        array.push(lcDistances, distance)
                        array.push(lcVotes, array.get(lcHistoryLabels, candidateIndex))
                        array.push(lcVoteBarIds, candidateBar)
                        if array.size(lcVotes) > lcNeighborsCount
                            int thresholdIndex = math.min(array.size(lcDistances) - 1, int(math.round(lcNeighborsCount * 3.0 / 4.0)))
                            lastDistance := array.get(lcDistances, thresholdIndex)
                            array.shift(lcDistances)
                            array.shift(lcVotes)
                            array.shift(lcVoteBarIds)
        lcPrediction := array.size(lcVotes) > 0 ? int(array.sum(lcVotes)) : 0
        lcDirection := lcPrediction > 0 ? 1 : lcPrediction < 0 ? -1 : lcDirection
        if candidateCount >= lcNeighborsCount and array.size(lcVotes) == lcNeighborsCount
            lcPredictionBar := bar_index
        // Published JDE labeling convention, retained verbatim with long=1,
        // short=-1: source[4] < source => short; source[4] > source => long.
        // These are known historical labels, never future-bar references.
        int trainingLabel = lcTrainingSource[4] < lcTrainingSource ? -1 : lcTrainingSource[4] > lcTrainingSource ? 1 : 0
        array.push(lcHistory1, lcFeature1)
        array.push(lcHistory2, lcFeature2)
        array.push(lcHistory3, lcFeature3)
        array.push(lcHistory4, lcFeature4)
        array.push(lcHistory5, lcFeature5)
        array.push(lcHistoryLabels, trainingLabel)
        array.push(lcHistoryBarIds, bar_index)
        if array.size(lcHistoryLabels) > lcHistoryBars
            array.shift(lcHistory1)
            array.shift(lcHistory2)
            array.shift(lcHistory3)
            array.shift(lcHistory4)
            array.shift(lcHistory5)
            array.shift(lcHistoryLabels)
            array.shift(lcHistoryBarIds)
int lcNeighborsUsed = array.size(lcVotes)
bool lcModelReady = useLCFilter and not na(lcPredictionBar) and lcPredictionBar == bar_index and lcNeighborsUsed == lcNeighborsCount
bool lcEntryReady = lcModelReady and not lcFillRecalculation
float lcVoteStrength = lcNeighborsUsed > 0 ? math.abs(lcPrediction) * 100.0 / lcNeighborsUsed : na
bool longLCFilterPass = not useLCFilter or (lcEntryReady and lcDirection == 1)
bool shortLCFilterPass = not useLCFilter or (lcEntryReady and lcDirection == -1)
bool longMLPredictionPass = not useLCFilter or not useMLPredictionFilter or (lcEntryReady and lcPrediction >= minMLPredictionVotes)
bool shortMLPredictionPass = not useLCFilter or not useMLPredictionFilter or (lcEntryReady and lcPrediction <= -minMLPredictionVotes)
// ============================================================================
// V4.1 LC REGIME FILTERS + WALK-FORWARD GAUSSIAN HMM
// LC filters are independent of the LC classification master switch.
// HMM: 3 Gaussian states, rolling Baum-Welch fits, causal forward probabilities.
// No future observations, whole-chart fitting, or retroactive trade relabeling.
// ============================================================================
string GROUP_REGIME = "V4.1 LC Regime Filters"
bool useLCRegimeFilter = input.bool(true, "Enable LC Regime Filter", group=GROUP_REGIME, tooltip="Original ml.regime_filter(ohlc4, threshold, enabled). Screens trending vs ranging conditions; not a bullish/bearish direction signal. Independent of Enable LC Direction Filter.")
float lcRegimeThreshold = input.float(-0.1, "LC Regime Threshold", minval=-10, maxval=10, step=0.1, group=GROUP_REGIME)
bool useLCVolatilityFilter = input.bool(false, "Enable LC Volatility Filter", group=GROUP_REGIME, tooltip="Original LC ATR(1) > ATR(10) filter. Optional in addition to the existing Volatility Push filter.")
bool useLCADXFilter = input.bool(false, "Enable LC ADX Filter", group=GROUP_REGIME)
int lcADXThreshold = input.int(20, "LC ADX Threshold", minval=0, maxval=100, group=GROUP_REGIME)
// Always evaluate imported TA functions; do not hide them behind lazy AND/OR.
bool lcRegimePass = ml.regime_filter(ohlc4, lcRegimeThreshold, useLCRegimeFilter)
bool lcVolatilityPass = ml.filter_volatility(1, 10, useLCVolatilityFilter)
bool lcADXPass = ml.filter_adx(close, 14, lcADXThreshold, useLCADXFilter)
bool lcEnvironmentPass = lcRegimePass and lcVolatilityPass and lcADXPass

string GROUP_HMM = "V4.1 Hidden Markov Regimes"
bool useHMMFilter = input.bool(true, "Enable HMM Regime Filter", group=GROUP_HMM, tooltip="Entry-only directional gate. OFF completely bypasses HMM warmup, confidence and regime checks. Does not change ATR exits or force a trade.")
int hmmTrainingBars = input.int(300, "Rolling Training Observations", minval=100, maxval=750, group=GROUP_HMM, tooltip="Refits use only the most recent prior observations. This is a rolling bar window, not years of permanently stored training.")
int hmmRefitEvery = input.int(100, "Refit Every N Observations", minval=25, maxval=2000, group=GROUP_HMM)
int hmmEMIterations = input.int(5, "Baum-Welch Iterations", minval=1, maxval=10, group=GROUP_HMM, tooltip="Fixed bounded EM iterations. Convergence is not guaranteed. Larger windows/iterations increase Pine runtime.")
int hmmAtrLength = input.int(14, "Observation ATR Length", minval=2, maxval=200, group=GROUP_HMM)
float hmmMinimumConfidence = input.float(0.55, "Minimum State Probability", minval=0.34, maxval=0.99, step=0.01, group=GROUP_HMM, tooltip="Filtered probability under the fitted HMM; NOT the probability a trade will win.")
int hmmConfirmationBars = input.int(2, "Consecutive Regime Bars", minval=1, maxval=20, group=GROUP_HMM)
float hmmMinimumDrift = input.float(0.05, "Minimum Directional Mean (ATR units)", minval=0, maxval=1, step=0.01, group=GROUP_HMM, tooltip="Bullish state mean must exceed this; bearish mean must be below its negative. Prevents calling the least-negative state bullish, or the least-positive state bearish.")
float hmmVarianceFloor = input.float(0.01, "Emission Variance Floor", minval=0.001, maxval=1, step=0.001, group=GROUP_HMM)
bool showRegimeStats = input.bool(true, "Show Regime Rows in Statistics", group=GROUP_HMM)
bool showHMMBackground = input.bool(false, "Show HMM Background", group=GROUP_HMM)
bool showHMMDataWindow = input.bool(true, "Show HMM Data Window Values", group=GROUP_HMM)

// Row-major transitions: A[i * 3 + j] = P(state j | previous state i).
f_hmmLogEmission(float observation, float mean, float variance) =>
    -0.5 * (math.log(2.0 * math.pi * variance) + math.pow(observation - mean, 2) / variance)

f_hmmEmissions(float observation, array<float> means, array<float> variances) =>
    array<float> emissions = array.new<float>(3, 0.0)
    float maxLog = -1e100
    for state = 0 to 2
        float logValue = f_hmmLogEmission(observation, array.get(means, state), array.get(variances, state))
        array.set(emissions, state, logValue)
        maxLog := math.max(maxLog, logValue)
    // Common emission scaling cancels in all normalized probabilities.
    for state = 0 to 2
        array.set(emissions, state, math.exp(array.get(emissions, state) - maxLog))
    emissions

f_hmmForward(float observation, array<float> previous, array<float> means, array<float> variances, array<float> transitions) =>
    array<float> emissions = f_hmmEmissions(observation, means, variances)
    array<float> posterior = array.new<float>(3, 0.0)
    float total = 0.0
    for nextState = 0 to 2
        float prior = 0.0
        for previousState = 0 to 2
            prior += array.get(previous, previousState) * array.get(transitions, previousState * 3 + nextState)
        float weight = prior * array.get(emissions, nextState)
        array.set(posterior, nextState, weight)
        total += weight
    for state = 0 to 2
        array.set(posterior, state, array.get(posterior, state) / math.max(total, 1e-100))
    posterior

f_hmmFit(array<float> observations, array<float> means, array<float> variances, array<float> transitions, int iterations, float varianceFloor) =>
    int sampleCount = array.size(observations)
    float sampleMean = array.avg(observations)
    float sampleVariance = math.max(array.variance(observations), varianceFloor)
    // Deterministic initialization on prior data only. No random seed or future fit.
    for state = 0 to 2
        array.set(means, state, sampleMean + (state - 1) * math.sqrt(sampleVariance))
        array.set(variances, state, sampleVariance)
        for nextState = 0 to 2
            array.set(transitions, state * 3 + nextState, state == nextState ? 0.95 : 0.025)
    array<float> startProbability = array.new<float>(3, 1.0 / 3.0)
    array<float> alpha = array.new<float>(sampleCount * 3, 0.0)
    array<float> emissions = array.new<float>(sampleCount * 3, 0.0)
    array<float> scales = array.new<float>(sampleCount, 0.0)
    for iteration = 0 to iterations - 1
        // Forward pass with per-observation scaling.
        for sample = 0 to sampleCount - 1
            array<float> emission = f_hmmEmissions(array.get(observations, sample), means, variances)
            float total = 0.0
            for state = 0 to 2
                float prior = array.get(startProbability, state)
                if sample > 0
                    prior := 0.0
                    for previousState = 0 to 2
                        prior += array.get(alpha, (sample - 1) * 3 + previousState) * array.get(transitions, previousState * 3 + state)
                float weight = prior * array.get(emission, state)
                array.set(emissions, sample * 3 + state, array.get(emission, state))
                array.set(alpha, sample * 3 + state, weight)
                total += weight
            total := math.max(total, 1e-100)
            array.set(scales, sample, total)
            for state = 0 to 2
                array.set(alpha, sample * 3 + state, array.get(alpha, sample * 3 + state) / total)
        array<float> occupancy = array.new<float>(3, 0.0)
        array<float> firstMoment = array.new<float>(3, 0.0)
        array<float> secondMoment = array.new<float>(3, 0.0)
        array<float> transitionCounts = array.new<float>(9, 0.0)
        array<float> beta = array.new<float>(3, 1.0)
        // Backward pass exists ONLY inside the historical training window.
        // It never revises emitted historical regime values or previous trades.
        int sample = sampleCount - 1
        while sample >= 0
            float gammaTotal = 0.0
            for state = 0 to 2
                gammaTotal += array.get(alpha, sample * 3 + state) * array.get(beta, state)
            float observation = array.get(observations, sample)
            for state = 0 to 2
                float gamma = array.get(alpha, sample * 3 + state) * array.get(beta, state) / math.max(gammaTotal, 1e-100)
                array.set(occupancy, state, array.get(occupancy, state) + gamma)
                array.set(firstMoment, state, array.get(firstMoment, state) + gamma * observation)
                array.set(secondMoment, state, array.get(secondMoment, state) + gamma * observation * observation)
                if sample == 0
                    array.set(startProbability, state, gamma)
            if sample > 0
                array<float> previousBeta = array.new<float>(3, 0.0)
                array<float> xi = array.new<float>(9, 0.0)
                float xiTotal = 0.0
                for previousState = 0 to 2
                    float betaSum = 0.0
                    for nextState = 0 to 2
                        float link = array.get(transitions, previousState * 3 + nextState) * array.get(emissions, sample * 3 + nextState) * array.get(beta, nextState)
                        betaSum += link
                        float weight = array.get(alpha, (sample - 1) * 3 + previousState) * link
                        array.set(xi, previousState * 3 + nextState, weight)
                        xiTotal += weight
                    array.set(previousBeta, previousState, betaSum / array.get(scales, sample))
                for index = 0 to 8
                    array.set(transitionCounts, index, array.get(transitionCounts, index) + array.get(xi, index) / math.max(xiTotal, 1e-100))
                beta := previousBeta
            sample -= 1
        // Gaussian M-step and lightly regularized transition M-step.
        for state = 0 to 2
            float weight = array.get(occupancy, state)
            if weight > 1e-6
                float mean = array.get(firstMoment, state) / weight
                float variance = array.get(secondMoment, state) / weight - mean * mean
                array.set(means, state, mean)
                array.set(variances, state, math.max(variance, varianceFloor))
            float rowTotal = 0.0
            for nextState = 0 to 2
                // Small positive pseudocount prevents zero-probability transitions.
                float count = array.get(transitionCounts, state * 3 + nextState) + 0.01
                array.set(transitions, state * 3 + nextState, count)
                rowTotal += count
            for nextState = 0 to 2
                int index = state * 3 + nextState
                array.set(transitions, index, array.get(transitions, index) / rowTotal)
    // Sort latent states by learned mean, permuting BOTH transition dimensions.
    // State 0 = lowest mean; state 1 = middle mean; state 2 = highest mean.
    array<int> stateOrder = array.sort_indices(means, order.ascending)
    array<float> oldMeans = array.copy(means)
    array<float> oldVariances = array.copy(variances)
    array<float> oldTransitions = array.copy(transitions)
    array<float> sortedStart = array.new<float>(3, 0.0)
    for state = 0 to 2
        int oldState = array.get(stateOrder, state)
        array.set(means, state, array.get(oldMeans, oldState))
        array.set(variances, state, array.get(oldVariances, oldState))
        array.set(sortedStart, state, array.get(startProbability, oldState))
        for nextState = 0 to 2
            array.set(transitions, state * 3 + nextState, array.get(oldTransitions, oldState * 3 + array.get(stateOrder, nextState)))
    // Refilter prior window under final fitted parameters to obtain P(S[t-1]).
    array<float> tail = array.copy(sortedStart)
    for sampleIndex = 0 to sampleCount - 1
        if sampleIndex == 0
            array<float> emission = f_hmmEmissions(array.get(observations, sampleIndex), means, variances)
            float total = 0.0
            for state = 0 to 2
                float weight = array.get(sortedStart, state) * array.get(emission, state)
                array.set(tail, state, weight)
                total += weight
            for state = 0 to 2
                array.set(tail, state, array.get(tail, state) / math.max(total, 1e-100))
        else
            tail := f_hmmForward(array.get(observations, sampleIndex), tail, means, variances, transitions)
    tail

float hmmATR = ta.atr(hmmAtrLength)
// Prior ATR sets the scale; current return is available only at confirmed close.
// Clip extreme observations for numerical robustness, not to cap trading loss.
float hmmObservation = not na(hmmATR[1]) and hmmATR[1] > 0 and not na(close[1]) ? math.max(-6.0, math.min(6.0, (close - close[1]) / hmmATR[1])) : na
varip array<float> hmmHistory = array.new<float>()
varip array<float> hmmMeans = array.new<float>(3, 0.0)
varip array<float> hmmVariances = array.new<float>(3, 1.0)
varip array<float> hmmTransitions = array.new<float>(9, 1.0 / 3.0)
varip array<float> hmmPosterior = array.new<float>(3, 1.0 / 3.0)
varip int hmmLastProcessedBar = na
varip int hmmPredictionBar = na
varip int hmmObservationsSeen = 0
varip int hmmLastFitObservation = na
varip int hmmFitCount = 0
varip int hmmState = 1
varip int hmmStateRun = 0
varip float hmmConfidence = na
varip bool hmmFitted = false
if useHMMFilter and barstate.isconfirmed and not lcFillRecalculation and (na(hmmLastProcessedBar) or hmmLastProcessedBar != bar_index)
    hmmLastProcessedBar := bar_index
    hmmPredictionBar := na
    if not na(hmmObservation)
        bool refitDue = not hmmFitted or hmmObservationsSeen - nz(hmmLastFitObservation, 0) >= hmmRefitEvery
        if array.size(hmmHistory) == hmmTrainingBars and refitDue
            // Current observation is not yet in the training window.
            hmmPosterior := f_hmmFit(hmmHistory, hmmMeans, hmmVariances, hmmTransitions, hmmEMIterations, hmmVarianceFloor)
            hmmFitted := true
            hmmLastFitObservation := hmmObservationsSeen
            hmmFitCount += 1
            // Require persistence again after refit; do not splice state runs.
            hmmStateRun := 0
        if hmmFitted
            hmmPosterior := f_hmmForward(hmmObservation, hmmPosterior, hmmMeans, hmmVariances, hmmTransitions)
            int nextState = 0
            for state = 1 to 2
                if array.get(hmmPosterior, state) > array.get(hmmPosterior, nextState)
                    nextState := state
            hmmStateRun := nextState == hmmState ? hmmStateRun + 1 : 1
            hmmState := nextState
            hmmConfidence := array.get(hmmPosterior, nextState)
            hmmPredictionBar := bar_index
        // Bound history and append only AFTER fitting/scoring this bar.
        array.push(hmmHistory, hmmObservation)
        if array.size(hmmHistory) > hmmTrainingBars
            array.shift(hmmHistory)
        hmmObservationsSeen += 1
    else
        hmmStateRun := 0
bool hmmModelReady = useHMMFilter and hmmFitted and not na(hmmPredictionBar) and hmmPredictionBar == bar_index
bool hmmEntryReady = hmmModelReady and not lcFillRecalculation and hmmStateRun >= hmmConfirmationBars and hmmConfidence >= hmmMinimumConfidence
bool longHMMFilterPass = not useHMMFilter or (hmmEntryReady and hmmState == 2 and array.get(hmmMeans, 2) > hmmMinimumDrift)
bool shortHMMFilterPass = not useHMMFilter or (hmmEntryReady and hmmState == 0 and array.get(hmmMeans, 0) < -hmmMinimumDrift)
// Middle-mean state is a neutral/range proxy, not a proven economic regime.
string hmmStateName = hmmState == 0 and array.get(hmmMeans, 0) < -hmmMinimumDrift ? "BEARISH" : hmmState == 2 and array.get(hmmMeans, 2) > hmmMinimumDrift ? "BULLISH" : "NEUTRAL / RANGE"
color hmmRegimeColor = hmmStateName == "BEARISH" ? cRed : hmmStateName == "BULLISH" ? cGreen : cGray
bgcolor(useHMMFilter and showHMMBackground and hmmModelReady ? color.new(hmmRegimeColor, 92) : na, title="KAIROS V4.1 HMM Regime")
plot(useHMMFilter and showHMMDataWindow and hmmModelReady ? hmmState - 1 : na, title="KAIROS V4.1 HMM State (-1/0/+1)", display=display.data_window)
plot(useHMMFilter and showHMMDataWindow and hmmModelReady ? hmmConfidence * 100 : na, title="KAIROS V4.1 HMM State Probability (%)", display=display.data_window)
plot(useHMMFilter and showHMMDataWindow and hmmModelReady ? array.get(hmmPosterior, 0) * 100 : na, title="KAIROS V4.1 HMM Bear Probability (%)", display=display.data_window)
plot(useHMMFilter and showHMMDataWindow and hmmModelReady ? array.get(hmmPosterior, 1) * 100 : na, title="KAIROS V4.1 HMM Neutral Probability (%)", display=display.data_window)
plot(useHMMFilter and showHMMDataWindow and hmmModelReady ? array.get(hmmPosterior, 2) * 100 : na, title="KAIROS V4.1 HMM Bull Probability (%)", display=display.data_window)
// END V4.1 REGIME MODULE

float emaEntryValue = ta.ema(close, emaEntryLength)
float smaEntryValue = ta.sma(close, smaEntryLength)
bool longEMAEntryPass = not useEMAEntryFilter or (not na(emaEntryValue) and close > emaEntryValue)
bool shortEMAEntryPass = not useEMAEntryFilter or (not na(emaEntryValue) and close < emaEntryValue)
bool longSMAEntryPass = not useSMAEntryFilter or (not na(smaEntryValue) and close > smaEntryValue)
bool shortSMAEntryPass = not useSMAEntryFilter or (not na(smaEntryValue) and close < smaEntryValue)
bool longV4FiltersPass = longLCFilterPass and longMLPredictionPass and longEMAEntryPass and longSMAEntryPass and lcEnvironmentPass and longHMMFilterPass
bool shortV4FiltersPass = shortLCFilterPass and shortMLPredictionPass and shortEMAEntryPass and shortSMAEntryPass and lcEnvironmentPass and shortHMMFilterPass
plot(useEMAEntryFilter and showEMAEntryLine ? emaEntryValue : na, title="KAIROS V4.1 EMA Entry Filter", color=color.new(cGold, 25), linewidth=1)
plot(useSMAEntryFilter and showSMAEntryLine ? smaEntryValue : na, title="KAIROS V4.1 SMA Entry Filter", color=color.new(cSilver, 25), linewidth=1)
plot(useLCFilter and showMLDataWindow and lcModelReady ? lcPrediction : na, title="KAIROS V4.1 ML Prediction", display=display.data_window)
plot(useLCFilter and showMLDataWindow and lcModelReady ? lcVoteStrength : na, title="KAIROS V4.1 ML Vote Strength (%)", display=display.data_window)
// ============================================================================
// V4.1 LC BAR VISUALIZATION — ADAPTED FROM JDEHORTY
// Uses the existing prediction; display settings never affect orders or filters.
// ============================================================================
bool lcVisualReady = useLCFilter and lcModelReady and barstate.isconfirmed
int lcVisualStrength = math.min(math.abs(lcPrediction), 10)
int lcVisualTransparency = math.max(0, 90 - lcVisualStrength * 10)
color lcVisualPredictionColor = (
     lcPrediction > 0
     ? color.new(#009988, lcVisualTransparency)
     : lcPrediction < 0
     ? color.new(#CC3311, lcVisualTransparency)
     : color.new(#787B86, 25)
)
barcolor(
     showLCBarColours and lcVisualReady ? color.new(lcVisualPredictionColor, 50) : na,
     title="KAIROS V4.1 LC Bar Colours"
)
// Calculate ATR on every execution to keep its series history consistent.
float lcVisualAtr = ta.atr(1)
float lcVisualLabelY = lcPrediction > 0 ? high + lcVisualAtr : low - lcVisualAtr
string lcVisualLabelStyle = lcPrediction > 0 ? label.style_label_down : label.style_label_up
// Ordinary var follows label rollback on realtime bars. If TradingView rolls
// back a drawing before another fill execution, the guard rolls back with it,
// allowing the label to be recreated. Historical fill executions are deduped.
var int lcLastVisualLabelBar = na
bool lcCanDrawPrediction = (
     showLCBarPrediction and
     lcVisualReady and
     (na(lcLastVisualLabelBar) or lcLastVisualLabelBar != bar_index)
)
if lcCanDrawPrediction
    label.new(
         x=bar_index,
         y=lcVisualLabelY,
         text=str.tostring(lcPrediction),
         xloc=xloc.bar_index,
         yloc=yloc.price,
         style=lcVisualLabelStyle,
         color=color.new(color.white, 100),
         textcolor=lcVisualPredictionColor,
         size=size.normal,
         textalign=text.align_left
    )
    lcLastVisualLabelBar := bar_index
// END V4.1 LC BAR VISUALIZATION

// ============================================================================
// END V4.1 FILTERS — V3 ENTRY TRIGGERS AND EXIT EXECUTION CONTINUE BELOW
// ============================================================================
// ============================================================================
// ENTRY CONDITIONS
//
// Kernel color change = trigger.
// Slope + Volatility Push = confirmations.
// ============================================================================
bool longEntrySignal = (
     enableLongs and
     inTradingSession and
     kernelBullishFlip and
     longSlopePass and
     bullPushConfirmed and
     longV4FiltersPass
)
bool shortEntrySignal = (
     enableShorts and
     inTradingSession and
     kernelBearishFlip and
     shortSlopePass and
     bearPushConfirmed and
     shortV4FiltersPass
)
bool canEnterLong = (
     longEntrySignal and
     strategy.position_size <= 0 and
     entryQuantityReady
)
bool canEnterShort = (
     shortEntrySignal and
     strategy.position_size >= 0 and
     entryQuantityReady
)
if canEnterLong
    strategy.entry(
         "KAIROS V4.1 Long",
         strategy.long,
         qty=entryQuantity,
         comment="KAIROS V4.1 LONG",
         alert_message="KAIROS LC V4.1 LONG | {{ticker}} @ {{strategy.order.price}}"
    )
else if canEnterShort
    strategy.entry(
         "KAIROS V4.1 Short",
         strategy.short,
         qty=entryQuantity,
         comment="KAIROS V4.1 SHORT",
         alert_message="KAIROS LC V4.1 SHORT | {{ticker}} @ {{strategy.order.price}}"
    )
// ============================================================================
// LOCK RISK LEVELS AFTER ACTUAL FILL
// ============================================================================
bool newLongPosition = (
     strategy.position_size > 0 and
     strategy.position_size[1] <= 0
)
bool newShortPosition = (
     strategy.position_size < 0 and
     strategy.position_size[1] >= 0
)
if newLongPosition
    float riskDistance = (
         riskAtr *
         stopAtrMultiple
    )
    longStop := (
         strategy.position_avg_price -
         riskDistance
    )
    longTarget := (
         strategy.position_avg_price +
         riskDistance *
         rewardRiskMultiple
    )
    if not useRiskManagement
        longStop := na
        longTarget := na
    if enableCashLossCap
        float cashStop = strategy.position_avg_price - f_cashStopDistance(math.abs(strategy.position_size))
        longStop := na(longStop) ? cashStop : math.max(longStop, cashStop)
    shortStop := na
    shortTarget := na
if newShortPosition
    float riskDistance = (
         riskAtr *
         stopAtrMultiple
    )
    shortStop := (
         strategy.position_avg_price +
         riskDistance
    )
    shortTarget := (
         strategy.position_avg_price -
         riskDistance *
         rewardRiskMultiple
    )
    if not useRiskManagement
        shortStop := na
        shortTarget := na
    if enableCashLossCap
        float cashStop = strategy.position_avg_price + f_cashStopDistance(math.abs(strategy.position_size))
        shortStop := na(shortStop) ? cashStop : math.min(shortStop, cashStop)
    longStop := na
    longTarget := na
// ============================================================================
// 2R / ATR / CASH EXITS
// ============================================================================
if (
     (useRiskManagement or enableCashLossCap) and
     strategy.position_size > 0 and
     not na(longStop)
)
    strategy.exit(
         "KAIROS V4.1 Long Risk Exit",
         from_entry="KAIROS V4.1 Long",
         stop=longStop,
         limit=longTarget,
         comment="KAIROS V4.1 LONG PROFIT/ATR/CASH EXIT",
         alert_message="KAIROS LC V4.1 LONG EXIT | {{ticker}} @ {{strategy.order.price}}"
    )
if (
     (useRiskManagement or enableCashLossCap) and
     strategy.position_size < 0 and
     not na(shortStop)
)
    strategy.exit(
         "KAIROS V4.1 Short Risk Exit",
         from_entry="KAIROS V4.1 Short",
         stop=shortStop,
         limit=shortTarget,
         comment="KAIROS V4.1 SHORT PROFIT/ATR/CASH EXIT",
         alert_message="KAIROS LC V4.1 SHORT EXIT | {{ticker}} @ {{strategy.order.price}}"
    )
// ============================================================================
// OPPOSITE KERNEL FLIP EXIT
//
// If the opposite flip also passes VP + slope confirmation,
// strategy.entry() handles the reversal.
//
// If it does not qualify as a reversal entry, the current position is closed.
// ============================================================================
if (
     exitOnOppositeKernelFlip and
     strategy.position_size > 0 and
     kernelBearishFlip and
     not canEnterShort
)
    strategy.close(
         "KAIROS V4.1 Long",
         comment="KAIROS V4.1 OPPOSITE KERNEL EXIT",
         alert_message="KAIROS LC V4.1 CLOSE LONG - KERNEL FLIP | {{ticker}} @ {{strategy.order.price}}"
    )
if (
     exitOnOppositeKernelFlip and
     strategy.position_size < 0 and
     kernelBullishFlip and
     not canEnterLong
)
    strategy.close(
         "KAIROS V4.1 Short",
         comment="KAIROS V4.1 OPPOSITE KERNEL EXIT",
         alert_message="KAIROS LC V4.1 CLOSE SHORT - KERNEL FLIP | {{ticker}} @ {{strategy.order.price}}"
    )
// ============================================================================
// SESSION CUTOFF
// ============================================================================
if (
     closeAtSessionEnd and
     sessionCutoffBar and
     strategy.position_size != 0
)
    strategy.close_all(
         comment="KAIROS V4.1 SESSION CUTOFF",
         immediately=true,
         alert_message="KAIROS LC V4.1 SESSION CUTOFF | {{ticker}} @ {{strategy.order.price}}"
    )
// ============================================================================
// RESET RISK LEVELS AFTER EXIT
// ============================================================================
if (
     strategy.position_size == 0 and
     strategy.position_size[1] != 0
)
    longStop := na
    longTarget := na
    shortStop := na
    shortTarget := na
// ============================================================================
// CHART SIGNALS
// ============================================================================
plotshape(
     longEntrySignal,
     title="KAIROS V4.1 Long Signal",
     style=shape.labelup,
     location=location.belowbar,
     color=cGreen,
     textcolor=color.white,
     size=size.small,
     text="K L"
)
plotshape(
     shortEntrySignal,
     title="KAIROS V4.1 Short Signal",
     style=shape.labeldown,
     location=location.abovebar,
     color=cRed,
     textcolor=color.white,
     size=size.small,
     text="K S"
)
plot(
     showRiskLevels and
     strategy.position_size > 0
     ? longStop
     : na,
     title="Long Stop",
     color=color.new(cRed, 10),
     linewidth=1,
     style=plot.style_linebr
)
plot(
     showRiskLevels and
     strategy.position_size > 0
     ? longTarget
     : na,
     title="Long 2R Target",
     color=color.new(cGreen, 10),
     linewidth=1,
     style=plot.style_linebr
)
plot(
     showRiskLevels and
     strategy.position_size < 0
     ? shortStop
     : na,
     title="Short Stop",
     color=color.new(cRed, 10),
     linewidth=1,
     style=plot.style_linebr
)
plot(
     showRiskLevels and
     strategy.position_size < 0
     ? shortTarget
     : na,
     title="Short 2R Target",
     color=color.new(cGreen, 10),
     linewidth=1,
     style=plot.style_linebr
)
// ============================================================================
// STRATEGY STATISTICS TABLE
// ============================================================================
string GROUP_STATS = "Statistics Table"
bool showStats = input.bool(
     true,
     "Show Statistics",
     group=GROUP_STATS
)
string statsPosition = input.string(
     "Top Right",
     "Table Position",
     options=["Top Right", "Bottom Right", "Top Left", "Bottom Left"],
     group=GROUP_STATS
)
string statsFont = input.string(
     "Small",
     "Font Size",
     options=["Small", "Normal", "Large"],
     group=GROUP_STATS
)
string statsFontFamilyInput = input.string("Monospace", "Table Font Family", options=["Default", "Monospace"], group=GROUP_STATS)
string statsFontFamily = statsFontFamilyInput == "Monospace" ? font.family_monospace : font.family_default
statsTablePosition = switch statsPosition
    "Bottom Right" => position.bottom_right
    "Top Left" => position.top_left
    "Bottom Left" => position.bottom_left
    => position.top_right
statsTextSize = switch statsFont
    "Small" => size.small
    "Large" => size.large
    => size.normal
color statsBackground = color.new(cNavy, 10)
color statsHeader = color.new(cNavy, 10)
color statsBorder = color.new(cGold, 70)
var table statsTable = table.new(
     statsTablePosition,
     2,
     25,
     bgcolor=statsBackground,
     frame_color=color.new(cGold, 45),
     frame_width=2,
     border_color=statsBorder,
     border_width=1
)
// Text formatting helpers.
f_kairosNumber(float value) =>
    na(value) ? "—" : str.tostring(value, "#.##")
f_kairosMoney(float value) =>
    f_kairosNumber(value) + " " + strategy.account_currency
// Write one table row.
f_kairosStatsRow(
     table target,
     int row,
     string labelText,
     string valueText,
     color valueColor,
     string fontSize
) =>
    table.cell(
         target,
         0,
         row,
         labelText,
         text_color=cLabel,
         text_halign=text.align_left,
         text_size=fontSize,
         text_font_family=statsFontFamily,
         bgcolor=row % 2 == 0 ? color.new(cDarkNavy, 75) : color.new(cNavy, 75)
    )
    table.cell(
         target,
         1,
         row,
         valueText,
         text_color=valueColor,
         text_halign=text.align_right,
         text_size=fontSize,
         text_font_family=statsFontFamily,
         bgcolor=row % 2 == 0 ? color.new(cDarkNavy, 75) : color.new(cNavy, 75)
    )
// Includes the last historical bar and subsequent realtime updates.
if barstate.islastconfirmedhistory or barstate.islast
    if showStats
        int closedTrades = strategy.closedtrades
        int winningTrades = strategy.wintrades
        int losingTrades = strategy.losstrades
        int evenTrades = strategy.eventrades
        float winRate = closedTrades > 0 ? winningTrades * 100.0 / closedTrades : na
        float grossLossAbs = math.abs(strategy.grossloss)
        float profitFactor = grossLossAbs > 0 ? strategy.grossprofit / grossLossAbs : na
        float averageTrade = closedTrades > 0 ? strategy.netprofit / closedTrades : na
        float netReturn = strategy.initial_capital > 0 ? strategy.netprofit / strategy.initial_capital * 100.0 : na
        string profitFactorText = grossLossAbs > 0 ? f_kairosNumber(profitFactor) : strategy.grossprofit > 0 ? "No losses" : "—"
        string positionText = strategy.position_size > 0 ? "LONG" : strategy.position_size < 0 ? "SHORT" : "FLAT"
        color positionColor = strategy.position_size > 0 ? cGreen : strategy.position_size < 0 ? cRed : color.silver
        color profitColor = strategy.netprofit > 0 ? cGreen : strategy.netprofit < 0 ? cRed : color.silver
        color averageColor = na(averageTrade) ? color.silver : averageTrade >= 0 ? cGreen : cRed
        table.cell(
             statsTable,
             0,
             0,
             "KAIROS LC V4.1",
             tooltip=showKairosStory ? KAIROS_STORY : "",
             bgcolor=statsHeader,
             text_color=cGold,
             text_halign=text.align_left,
             text_size=statsTextSize,
             text_font_family=statsFontFamily
        )
        table.cell(
             statsTable,
             1,
             0,
             "STRATEGY STATS",
             bgcolor=statsHeader,
             text_color=cSilver,
             text_halign=text.align_right,
             text_size=statsTextSize,
             text_font_family=statsFontFamily
        )
        f_kairosStatsRow(statsTable, 1, "Closed Trades", str.tostring(closedTrades), color.white, statsTextSize)
        f_kairosStatsRow(statsTable, 2, "Wins / Losses", str.tostring(winningTrades) + " / " + str.tostring(losingTrades), color.white, statsTextSize)
        f_kairosStatsRow(statsTable, 3, "Breakeven Trades", str.tostring(evenTrades), color.silver, statsTextSize)
        f_kairosStatsRow(statsTable, 4, "Win Rate", na(winRate) ? "—" : f_kairosNumber(winRate) + "%", color.white, statsTextSize)
        f_kairosStatsRow(statsTable, 5, "Profit Factor", profitFactorText, color.white, statsTextSize)
        f_kairosStatsRow(statsTable, 6, "Net Profit", f_kairosMoney(strategy.netprofit), profitColor, statsTextSize)
        f_kairosStatsRow(statsTable, 7, "Net Return", na(netReturn) ? "—" : f_kairosNumber(netReturn) + "%", profitColor, statsTextSize)
        f_kairosStatsRow(statsTable, 8, "Average Trade", na(averageTrade) ? "—" : f_kairosMoney(averageTrade), averageColor, statsTextSize)
        f_kairosStatsRow(statsTable, 9, "Max Drawdown", f_kairosMoney(strategy.max_drawdown), cRed, statsTextSize)
        f_kairosStatsRow(statsTable, 10, "Position", positionText, positionColor, statsTextSize)
        f_kairosStatsRow(statsTable, 11, "Target", useRiskManagement ? f_kairosNumber(rewardRiskMultiple) + "R" : "Disabled", color.white, statsTextSize)
        if showMLFilterStats
            string lcDirectionText = not useLCFilter ? "DISABLED" : not lcModelReady ? "WARMUP / NO DATA" : lcDirection == 1 ? "LONG" : lcDirection == -1 ? "SHORT" : "NEUTRAL"
            color lcDirectionColor = useLCFilter and lcModelReady ? (lcDirection == 1 ? cGreen : lcDirection == -1 ? cRed : cGray) : cGray
            string mlVoteText = not useLCFilter ? "DISABLED" : not lcModelReady ? "—" : str.tostring(lcPrediction) + " / " + str.tostring(lcNeighborsUsed)
            mlVoteText += useLCFilter and not useMLPredictionFilter ? " · threshold OFF" : ""
            string emaFilterText = not useEMAEntryFilter ? "DISABLED" : na(emaEntryValue) ? "WARMUP" : close > emaEntryValue ? "BULL" : close < emaEntryValue ? "BEAR" : "NEUTRAL"
            string smaFilterText = not useSMAEntryFilter ? "DISABLED" : na(smaEntryValue) ? "WARMUP" : close > smaEntryValue ? "BULL" : close < smaEntryValue ? "BEAR" : "NEUTRAL"
            f_kairosStatsRow(statsTable, 12, "LC Direction", lcDirectionText, lcDirectionColor, statsTextSize)
            f_kairosStatsRow(statsTable, 13, "ML Net Votes", mlVoteText, lcDirectionColor, statsTextSize)
            f_kairosStatsRow(statsTable, 14, "Neighbors / Features", not useLCFilter ? "DISABLED" : str.tostring(lcNeighborsUsed) + "/" + str.tostring(lcNeighborsCount) + " · " + str.tostring(lcActiveFeatureCount) + " features", color.white, statsTextSize)
            f_kairosStatsRow(statsTable, 15, "EMA " + str.tostring(emaEntryLength), emaFilterText, useEMAEntryFilter ? (close > emaEntryValue ? cGreen : close < emaEntryValue ? cRed : cGray) : cGray, statsTextSize)
            f_kairosStatsRow(statsTable, 16, "SMA " + str.tostring(smaEntryLength), smaFilterText, useSMAEntryFilter ? (close > smaEntryValue ? cGreen : close < smaEntryValue ? cRed : cGray) : cGray, statsTextSize)
        else
            table.clear(statsTable, 0, 12, 1, 16)
        if showRegimeStats
            string lcRegimeText = not useLCRegimeFilter ? "DISABLED" : lcRegimePass ? "PASS / TRENDING" : "BLOCK / RANGE"
            string hmmStatusText = not useHMMFilter ? "DISABLED" : not hmmModelReady ? "WARMUP / NO DATA" : hmmStateName
            string hmmGateText = not useHMMFilter ? "DISABLED" : not hmmModelReady ? "WARMUP" : hmmConfidence < hmmMinimumConfidence ? "LOW CONFIDENCE" : hmmStateRun < hmmConfirmationBars ? "CONFIRMING" : longHMMFilterPass ? "LONG ONLY" : shortHMMFilterPass ? "SHORT ONLY" : "BLOCK / NEUTRAL"
            f_kairosStatsRow(statsTable, 17, "LC Regime", lcRegimeText, not useLCRegimeFilter ? cGray : lcRegimePass ? cGreen : cRed, statsTextSize)
            f_kairosStatsRow(statsTable, 18, "LC Volatility / ADX", (not useLCVolatilityFilter ? "OFF" : lcVolatilityPass ? "PASS" : "BLOCK") + " / " + (not useLCADXFilter ? "OFF" : lcADXPass ? "PASS" : "BLOCK"), color.white, statsTextSize)
            f_kairosStatsRow(statsTable, 19, "HMM Regime", hmmStatusText, useHMMFilter and hmmModelReady ? hmmRegimeColor : cGray, statsTextSize)
            f_kairosStatsRow(statsTable, 20, "HMM State Probability", useHMMFilter and hmmModelReady ? f_kairosNumber(hmmConfidence * 100) + "%" : "—", color.white, statsTextSize)
            f_kairosStatsRow(statsTable, 21, "HMM Entry Gate", hmmGateText, longHMMFilterPass and useHMMFilter ? cGreen : shortHMMFilterPass and useHMMFilter ? cRed : cGray, statsTextSize)
            f_kairosStatsRow(statsTable, 22, "HMM History / Fits", not useHMMFilter ? "DISABLED" : str.tostring(array.size(hmmHistory)) + "/" + str.tostring(hmmTrainingBars) + " · " + str.tostring(hmmFitCount), color.white, statsTextSize)
            f_kairosStatsRow(statsTable, 23, "HMM Means B / N / U", useHMMFilter and hmmFitted ? f_kairosNumber(array.get(hmmMeans, 0)) + " / " + f_kairosNumber(array.get(hmmMeans, 1)) + " / " + f_kairosNumber(array.get(hmmMeans, 2)) : "—", color.white, statsTextSize)
            f_kairosStatsRow(statsTable, 24, "HMM Std B / N / U", useHMMFilter and hmmFitted ? f_kairosNumber(math.sqrt(array.get(hmmVariances, 0))) + " / " + f_kairosNumber(math.sqrt(array.get(hmmVariances, 1))) + " / " + f_kairosNumber(math.sqrt(array.get(hmmVariances, 2))) : "—", color.white, statsTextSize)
        else
            table.clear(statsTable, 0, 17, 1, 24)
    else
        table.clear(statsTable, 0, 0, 1, 24)
// ============================================================================
// ============================================================================
// EDITABLE BOTTOM WATERMARK — BELLEROPHONTES GOLD THEME
// ============================================================================
string GROUP_FOOTER = "Bottom Watermark"
bool showBottomWatermark = input.bool(true, "Show Bottom Watermark", group=GROUP_FOOTER)
string bottomWatermarkText = input.string("KAIROS · LC SWING ENGINE V4.1 · JXS_918", "Bottom Text", group=GROUP_FOOTER)
int bottomWatermarkSize = input.int(10, "Bottom Font Size", minval=8, maxval=36, group=GROUP_FOOTER)
string bottomWatermarkFamilyInput = input.string("Monospace", "Bottom Font Family", options=["Default", "Monospace"], group=GROUP_FOOTER)
color bottomWatermarkColor = input.color(color.new(#FFD700, 45), "Bottom Text Color", group=GROUP_FOOTER)
string bottomWatermarkFamily = bottomWatermarkFamilyInput == "Monospace" ? font.family_monospace : font.family_default
var table bottomWatermark = table.new(position.bottom_center, 1, 1)
if barstate.islastconfirmedhistory or barstate.islast
    if showBottomWatermark
        table.cell(bottomWatermark, 0, 0, bottomWatermarkText, text_color=bottomWatermarkColor, text_size=bottomWatermarkSize, text_font_family=bottomWatermarkFamily, bgcolor=color.new(color.black, 100))
    else
        table.clear(bottomWatermark, 0, 0, 0, 0)
// FILLED TRADE ENTRY ALERTS
//
// Requires calc_on_order_fills=true, which your strategy already uses.
// Alerts fire for actual strategy entry fills, not unfilled setup signals.
// varip preserves duplicate protection across same-bar fill recalculations.
// ============================================================================
string GROUP_TRADE_ALERTS = "Trade Entry Alerts"
bool enableTradeAlerts = input.bool(
     true,
     "Enable Filled Entry Alerts",
     group=GROUP_TRADE_ALERTS
)
bool alertLongTrades = input.bool(
     true,
     "Alert Long Entries",
     group=GROUP_TRADE_ALERTS,
     inline="direction"
)
bool alertShortTrades = input.bool(
     true,
     "Alert Short Entries",
     group=GROUP_TRADE_ALERTS,
     inline="direction"
)
varip string lastKairosEntryAlertKey = ""
if strategy.position_size != 0 and strategy.opentrades > 0
    int openTradeIndex = strategy.opentrades - 1
    int entryBar = strategy.opentrades.entry_bar_index(openTradeIndex)
    int entryTime = strategy.opentrades.entry_time(openTradeIndex)
    float actualEntryPrice = strategy.opentrades.entry_price(openTradeIndex)
    bool filledLong = strategy.position_size > 0
    string directionText = filledLong ? "LONG" : "SHORT"
    string entryAlertKey = (
         str.tostring(entryTime) + "|" +
         str.tostring(strategy.closedtrades) + "|" +
         directionText
    )
    bool entryFilledThisBar = entryBar == bar_index
    bool entryNotYetAlerted = entryAlertKey != lastKairosEntryAlertKey
    if entryFilledThisBar and entryNotYetAlerted
        lastKairosEntryAlertKey := entryAlertKey
        bool directionEnabled = filledLong ? alertLongTrades : alertShortTrades
        if barstate.isrealtime and enableTradeAlerts and directionEnabled
            string entryMessage = (
                 "KAIROS LC V4.1 " + directionText + " FILLED" +
                 " | " + syminfo.tickerid +
                 " | Timeframe: " + timeframe.period +
                 " | Entry: " + str.tostring(actualEntryPrice, format.mintick)
            )
            alert(
                 entryMessage,
                 alert.freq_all
            )
// ============================================================================
// V4.1 MAXIMUM LOSS BOX — MATCHES THE EXISTING NAVY/GOLD THEME AND TABLE FONT
// ============================================================================
cashTablePosition = switch cashBoxPosition
    "Bottom Right" => position.bottom_right
    "Top Left" => position.top_left
    "Top Right" => position.top_right
    => position.bottom_left
var table cashLossTable = table.new(cashTablePosition, 2, 7, bgcolor=statsBackground, frame_color=color.new(cGold, 45), frame_width=2, border_color=statsBorder, border_width=1)
if barstate.islastconfirmedhistory or barstate.islast
    if showCashLossBox
        float effectiveStop = strategy.position_size > 0 ? longStop : strategy.position_size < 0 ? shortStop : na
        float protectedLoss = not na(effectiveStop) and strategy.position_size != 0 ? strategy.convert_to_account(math.abs(strategy.position_avg_price - effectiveStop) * math.abs(strategy.position_size) * syminfo.pointvalue) : na
        table.cell(cashLossTable, 0, 0, "KAIROS LC V4.1", text_color=cGold, bgcolor=statsHeader, text_size=statsTextSize, text_font_family=statsFontFamily)
        table.cell(cashLossTable, 1, 0, "LOSS CONTROL", text_color=cSilver, bgcolor=statsHeader, text_size=statsTextSize, text_font_family=statsFontFamily)
        f_kairosStatsRow(cashLossTable, 1, "Cash Cap", enableCashLossCap ? "ENABLED" : "DISABLED", enableCashLossCap ? cGreen : cGray, statsTextSize)
        f_kairosStatsRow(cashLossTable, 2, "Maximum Loss", f_kairosMoney(maximumCashLoss), cGold, statsTextSize)
        f_kairosStatsRow(cashLossTable, 3, "Entry Shares / Qty", str.tostring(entryQuantity), color.white, statsTextSize)
        f_kairosStatsRow(cashLossTable, 4, "Open P/L", f_kairosMoney(strategy.openprofit), strategy.openprofit >= 0 ? cGreen : cRed, statsTextSize)
        f_kairosStatsRow(cashLossTable, 5, "Effective Stop", na(effectiveStop) ? "—" : str.tostring(effectiveStop, format.mintick), cRed, statsTextSize)
        f_kairosStatsRow(cashLossTable, 6, "Loss at Stop", na(protectedLoss) ? "—" : f_kairosMoney(protectedLoss), cRed, statsTextSize)
    else
        table.clear(cashLossTable, 0, 0, 1, 6)

Overview

KAIROS LC Swing Engine V4.1 {JXS_918} plots kernel trend lines on the price chart and opens long or short positions when kernel swings align with optional slope, volatility push, and regime conditions during specified session hours. Position exits occur upon opposite kernel direction flips or at session close. User inputs control session boundaries, kernel lookback and smoothing parameters, minimum slope ATR thresholds, and volatility push ratio requirements. The script uses dynamic calculations that may repaint on unconfirmed bars.

Details

Published by

woi-6ix on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

M15-H1, H4 and above

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)
  • The strategy enters trades without a stop loss

Topics

hidden-markov-modelmachine-learning-algorithmsnadaraya-watsonoptions-strategiestrading-strategy-simulation

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Show naming explanation in table headerbooltrueshowKairosStory
Enable LongsbooltrueenableLongs
Enable ShortsbooltrueenableShorts
Exit on Opposite Kernel FlipbooltrueexitOnOppositeKernelFlip
Close Position at Session EndbooltruecloseAtSessionEnd
TimezonestringAmerica/New_YorktradeTimezone
Start Hourint9startHour
Minuteint30startMinute
End Hourint15endHour
Minuteint0endMinute
SourcesourceclosekernelSource
Show Kernel LinebooltrueshowKernel
Show all 40 settings
SettingTypeDefaultVariable
Enhanced SmoothingbooltrueuseKernelSmoothing
Lookback Windowint8kernelLookback
Relative Weightingfloat8.0kernelRelativeWeight
Regression Levelint25kernelRegressionLevel
Smoothing Lagint6kernelLag
Use Slope FilterboolfalseuseSlopeFilter
Slope Lookback Barsint2slopeLookbackBars
ATR Lengthint14slopeAtrLength
Minimum Slope (ATR units)float0.05minSlopeAtr
Require Volatility PushbooltrueuseVolatilityPushFilter
Show VP MarkersbooltrueshowVolatilityPush
Confirmation Window (bars)int10vpConfirmationWindow
Fast ATR Lengthint5vpFastAtrLength
Slow ATR Lengthint20vpSlowAtrLength
Min ATR Ratiofloat1.10vpMinAtrRatio
Min Range / ATRfloat1.25vpMinRangeAtr
Volume Average Lengthint20vpVolumeLength
Min Volume Ratiofloat1.50vpMinVolumeRatio
Minimum Volatility Scoreint2vpMinScore
Min Body / ATRfloat0.80vpMinBodyAtr
Min Body / Candle Rangefloat0.65vpMinBodyRange
Bull Close Location >=float0.70vpBullCloseLocation
Bear Close Location <=float0.30vpBearCloseLocation
Use Profit / StopbooltrueuseRiskManagement
Risk ATR Lengthint14riskAtrLength
Stop ATR Multiplefloat1.5stopAtrMultiple
Profit Target (R)float0.4rewardRiskMultiple
Show Stop / TargetbooltrueshowRiskLevels
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

Donald - Test Logic Futures is an overlay strategy designed for intraday futures trading. It combines kernel regression functions with exponential moving averages to evaluate price retracements and entry timing. Trades are filtered by session execution windows

Strategy v5 TrendMoving averages Repaints
Updated 2 months ago · None stated GitHub repository of Donald - Test Logic Futures

This strategy implements a single-layer perceptron machine learning model built from scratch to generate trading signals directly on the price chart. It calculates predictions based on sample size, threshold settings, and optional volatility or volume filters.

Strategy v5 AI / machine learningTrend
Updated 2 years ago · None stated GitHub repository of Machine Learning: Perceptron-Based Strategy [5] (v.3)

This strategy overlays Supertrend on the price chart and trades only inside a set session and backtest date range. It enters long when Supertrend turns up, or after a chosen candle delay while the trend is up, and enters short on the opposite conditions. It cl

Strategy v5 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of BankNifty 5min Supertrend Based Strategy

This strategy plots an ATR Chandelier trailing stop on the price chart and tracks a directional trend state. It marks confirmed flips, weak body-rejected flips, and wick traps, and colors bars as price nears warning or danger zones around the flip trigger. Ada

Strategy v6 TrendVolatility & bands
Updated 4 weeks ago · MIT GitHub repository of Chandelier Flip Radar [WavesUnchained]

ORION: Hybrid Strategy

by eddiebelaval
7 stars

This strategy identifies volatility breakout opportunities by constructing dynamic ATR-based price boxes and detecting volatility squeezes. Trades are filtered using an exponential moving average trend condition and designated session hours. Entries trigger up

Strategy v5 Volatility & bandsBreakout
Updated 4 months ago · None stated GitHub repository of ORION: Hybrid Strategy
4 stars

This overlay strategy combines a Supertrend with a k-nearest-neighbors filter. It smooths price and the Supertrend with weighted moving averages, then uses neighbor count and lookback length to form an AI trend signal. Traders can allow long, short, or both di

Strategy v5 TrendVolatility & bands
Updated 3 years ago · None stated GitHub repository of AI Volume Supertrend Strategy

More AI / machine learning scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers