Bitcoin Macro Fair Value [Structural]//@version=6
indicator("Bitcoin Macro Fair Value ", overlay=true)
// --- Model Coefficients (Derived from Python Analysis 2019-2025) ---
intercept = input.float(3.156434, "Intercept")
c_m2 = input.float(0.132827, "Real M2 Coef")
c_corp = input.float(0.742593, "Corp Spread Coef")
c_hy = input.float(-0.617968, "HY Spread Coef")
c_dxy = input.float(0.009772, "DXY Coef")
c_real30 = input.float(0.713311, "Real 30Y Coef")
c_be30 = input.float(-1.059273, "Breakeven 30Y Coef")
c_slope = input.float(0.402220, "Slope 10Y-2Y Coef")
// --- Data Fetching ---
m2 = request.security("FRED:M2SL", "M", close)
cpi = request.security("FRED:CPIAUCSL", "M", close)
real_m2 = m2 / cpi
corp = request.security("FRED:BAMLC0A0CM", "D", close)
hy = request.security("FRED:BAMLH0A0HYM2", "D", close)
dxy = request.security("TVC:DXY", "D", close)
real30 = request.security("FRED:DFII30", "D", close)
nom30 = request.security("FRED:DGS30", "D", close)
be30 = nom30 - real30
nom10 = request.security("FRED:DGS10", "D", close)
nom2 = request.security("FRED:DGS2", "D", close)
slope = nom10 - nom2
// --- Calculation ---
log_fv = intercept + (c_m2 * real_m2) + (c_corp * corp) + (c_hy * hy) + (c_dxy * dxy) + (c_real30 * real30) + (c_be30 * be30) + (c_slope * slope)
fair_value = math.exp(log_fv)
plot(fair_value, "Macro Fair Value", color=color.new(color.blue, 0), linewidth=2)
Educational
NeuraEdge Block Trades v1.0NEURAEDGE BLOCK TRADES
═══════════════════════════════════════════════════════════════════════
We are excited to release Block Trades!
WHY THIS INDICATOR EXISTS?
Retail traders face a fundamental challenge: institutions move markets, but their activity is hidden. When smart money accumulates at support or distributes at resistance, retail traders often find themselves on the wrong side of the move.
Understanding where institutions are actively buying or selling is crucial for:
• Validating trade setups with volume confirmation
• Identifying supply and demand zones that actually hold
• Avoiding false breakouts driven by retail sentiment
• Spotting accumulation before major moves up
• Detecting distribution before major moves down
Most volume indicators simply show size without context. Block Trades was created to bridge this gap by detecting abnormally large volume bars and determining their directional bias, giving retail traders insight into institutional activity.
═══════════════════════════════════════════════════════════════════════
WHAT IT DOES:
Block Trades identifies volume spikes that likely represent institutional order flow and classifies them as buying pressure, selling pressure, or contested zones. The indicator then validates these prints against directional flow analysis and groups nearby prints into accumulation or distribution clusters.
This helps you answer critical questions:
• Is this support level being defended by institutions?
• Are smart money players distributing into this rally?
• Is heavy volume confirming my trade or warning against it?
• Where are institutional interest zones forming?
KEY FEATURES:
• Multi-tier volume detection (Large: 2x, Huge: 3x, Massive: 5x average)
• Directional classification with flow validation
• Accumulation/distribution zone detection
• Print clustering for institutional interest areas
• Confluence scoring system (0-10 points)
• Real-time statistics dashboard
• Clean, minimal chart labels
═══════════════════════════════════════════════════════════════════════
HOW IT WORKS:
VOLUME SPIKE DETECTION
The indicator monitors volume against a moving average baseline. When current volume significantly exceeds this average (default thresholds: 2x, 3x, 5x), it flags the bar as a potential institutional print.
DIRECTIONAL CLASSIFICATION
Buy Print: Large volume + closes in top 70% of range
Sell Print: Large volume + closes in bottom 70% of range
Neutral Print: Large volume + mid-range close (absorption/contested)
The close position within the bar's range reveals who won the battle. A bar with massive volume that closes near its high indicates aggressive buying. The same volume closing near the low indicates aggressive selling.
FLOW VALIDATION
Each print is validated against underlying institutional flow calculations. This filters out volume spikes that don't align with directional pressure, significantly reducing false signals. Buy prints require bullish flow, sell prints require bearish flow.
ACCUMULATION & DISTRIBUTION ZONES
When multiple prints occur at similar price levels with consistent direction:
• Repeated buy prints + bullish trend = Accumulation (institutions building positions)
• Repeated sell prints + bearish trend = Distribution (institutions unloading positions)
These zones often become powerful support/resistance levels because institutions have established significant positions there.
PRINT CLUSTERING
The indicator groups nearby prints (within configurable ATR distance) into clusters. When 3 or more prints form a cluster, it marks an institutional interest zone. These clusters frequently act as price magnets and reversal points.
PRINT CLUSTERING
The indicator groups nearby prints (within configurable ATR distance) into clusters. When 3 or more prints form a cluster, it marks an institutional interest zone. These clusters frequently act as price magnets and reversal points.
CONFLUENCE SCORING
Each print receives a confluence score (0-10 points) based on:
• Volume size (Massive: +3, Huge: +2, Large: +1)
• Flow alignment (+2 points, configurable)
• Trend alignment (+1)
• New high/low made (+1)
• Extreme close position (+1)
Prints with 5+ points receive a star marker, indicating ultra-high conviction setups.
═══════════════════════════════════════════════════════════════════════
HOW TRADERS USE IT:
USE CASE 1: TRADE VALIDATION
Your system signals a long entry at support. Check Block Trades:
• Buy prints present at this level? Institutions defending = Take the trade
• Sell prints present? Institutions distributing = Skip or wait
• No prints? Proceed with normal risk management
USE CASE 2: IDENTIFYING EXHAUSTION
Price rallies to resistance with heavy volume:
• Sell prints appear = Distribution, institutions unloading into strength
• Likely reversal coming, consider shorts or exit longs
• Confirmed by multiple sell prints = High conviction reversal setup
USE CASE 3: FINDING SUPPORT/RESISTANCE
Accumulation cluster forms at 450 level:
• Multiple buy prints over several sessions
• Institutions building positions at this price
• 450 becomes high-probability support for future pullbacks
• Use for entries or stop placement
USE CASE 4: BREAKOUT CONFIRMATION
Price breaks above key resistance:
• Buy print on breakout bar = Real institutional participation
• High confluence score (5+) = Ultra-high conviction
• Fake breakout would show sell prints or no prints
USE CASE 5: AVOIDING TRAPS
Price spikes up on huge volume:
• Sell print appears (closes low in range) = Trap
• Institutions selling into retail FOMO
• Avoid chasing, prepare for reversal
═══════════════════════════════════════════════════════════════════════
VISUAL ELEMENTS:
ON-CHART LABELS
Buy Print: Green label below bar showing size (LARGE/HUGE/MASSIVE)
Sell Print: Red label above bar showing size
Contested Print: Orange label at bar high (large volume, mid-range close)
Accumulation: Green "ACCUM" label with diamond symbol
Distribution: Red "DISTRIB" label with diamond symbol
WHAT CONTESTED MEANS:
When a bar has massive volume but closes in the middle of its range (neither top nor bottom 70%), it indicates a battle between buyers and sellers with no clear winner. This often occurs at:
• Major support/resistance levels where institutions are absorbing supply/demand
• Transition zones before a directional move
• Areas of genuine price discovery and uncertainty
Contested prints can signal absorption (institutions quietly building positions) or genuine indecision. Watch for follow-through on the next bar to determine which side won.
LABEL MODIFIERS
∆ checkmark = Flow validated (institutional flow aligns with print)
Star symbol = High confluence (5+ points, ultra-high conviction)
CLUSTER ZONES
Semi-transparent boxes marking areas where multiple prints occurred
Extend to the right to show ongoing institutional interest zones
Color-coded: green for bullish clusters, red for bearish clusters
DASHBOARD (TOP RIGHT)
• Current volume state and ratio
• Institutional flow direction
• Cumulative trend direction
• Recent print count (last 20 bars)
• Active cluster count
• Volume thresholds
STATISTICS (BOTTOM LEFT)
• Total session prints
• Buy/sell percentage split
═══════════════════════════════════════════════════════════════════════
SETTINGS:
PRINT DETECTION
• Volume Lookback Period: 20 bars (for average calculation)
• Large Print Threshold: 2.0x average
• Huge Print Threshold: 3.0x average
• Massive Print Threshold: 5.0x average
• Min Candle Size: 0.3x ATR (filters doji bars)
CLASSIFICATION
• Directional Threshold: 70% (how far in range to qualify as buy/sell)
• Show Neutral Prints: Toggle contested zones
• Require New High/Low: Optional stricter filter
INSTITUTIONAL FLOW
• Enable Flow Confluence: On/Off toggle
• Flow Confluence Weight: 2 points (adjustable 1-5)
CLUSTERING
• Enable Clustering: On/Off
• Cluster Distance: 1.0x ATR (how close prints must be)
• Min Prints for Cluster: 3 prints
• Show Cluster Zones: On/Off
DISPLAY
• Show Print Labels: Toggle all labels
• Show Accumulation/Distribution/Contested Labels: Toggle special labels
• Label Size: Tiny/Small/Normal
• Colors: Customizable buy/sell/neutral colors
FILTERS
• Minimum Volume: 0 (set threshold to ignore low volume bars)
• Session Filter: Avoid first/last 15 minutes (low liquidity)
═══════════════════════════════════════════════════════════════════════
BEST PRACTICES:
DO:
✓ Use as confluence with your primary trading system
✓ Pay attention to accumulation/distribution zones
✓ Look for high confluence prints (5+ stars)
✓ Validate breakouts with print direction
✓ Use cluster zones as future support/resistance
✓ Combine with higher timeframe analysis
✓ Works best on liquid instruments (major pairs, indices, large cap stocks)
DON'T:
✗ Trade prints as standalone buy/sell signals
✗ Ignore the directional classification (context matters)
✗ Use on low-volume instruments (prints less reliable)
✗ Chase every print without confluence confirmation
✗ Trade during low liquidity hours (first/last 15 min)
✗ Expect 100% accuracy (it's a confluence tool, not crystal ball)
OPTIMAL TIMEFRAMES:
• 5-minute to 1-hour charts for intraday trading
• 1-hour to 4-hour charts for swing trading
• Daily charts for position trading
BEST INSTRUMENTS:
• Major forex pairs (EUR/USD, GBP/USD, etc.)
• Index futures (ES, NQ, YM)
• High-volume stocks (SPY, QQQ, TSLA, AAPL, etc.)
• Major cryptocurrencies (BTC, ETH)
═══════════════════════════════════════════════════════════════════════
IMPORTANT DISCLAIMERS
METHODOLOGY DISCLAIMER
This indicator identifies abnormally large volume bars and estimates their directional bias based on price action and flow analysis. It does NOT have access to:
• Actual dark pool transaction data
• Off-exchange Alternative Trading System (ATS) prints
• Level 2 order book data
• Individual trade sizes or timestamps
• Institutional order identification
The prints detected are estimates based on publicly available volume and price data from TradingView. They indicate probable institutional activity patterns but are not confirmed block trades or dark pool executions.
USAGE DISCLAIMER
Block Trades is designed as a CONFLUENCE tool to validate trade setups - not as a standalone trading system. The indicator does not:
• Generate specific entry/exit signals
• Provide stop loss or take profit levels
• Constitute a complete trading strategy
• Guarantee profitable trades
Prints should be interpreted within the context of:
• Your overall trading strategy
• Market structure and trend
• Support/resistance levels
• Risk management rules
• Multiple timeframe analysis
RISK DISCLAIMER
Trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. This indicator is a tool for technical analysis only and does NOT constitute financial advice, investment advice, trading advice, or a recommendation to buy or sell any securities or financial instruments.
You should not make any investment decision without conducting your own research and due diligence. The accuracy, completeness, and timeliness of the information provided by this indicator is not guaranteed. No representation is being made that using this indicator will guarantee profits or prevent losses.
By using this indicator, you acknowledge that you understand and accept all risks associated with trading, and you agree that the developer is not liable for any losses you may incur.
═══════════════════════════════════════════════════════════════════════
ALERTS
Available alert conditions:
• Massive Buy Print
• Massive Sell Print
• Huge Buy Print
• Huge Sell Print
• Accumulation Detected
• Distribution Detected
• High Confluence Buy (5+ points)
• High Confluence Sell (5+ points)
Happy Trading!
Naveen Prabhu with EMA//@version=6
indicator('Naveen Prabhu with EMA', overlay = true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500)
a = input(2, title = 'Key Vaule. \'This changes the sensitivity\'')
c = input(5, title = 'ATR Period')
h = input(false, title = 'Signals from Heikin Ashi Candles')
BULLISH_LEG = 1
BEARISH_LEG = 0
BULLISH = +1
BEARISH = -1
GREEN = #089981
RED = #F23645
BLUE = #2157f3
GRAY = #878b94
MONO_BULLISH = #b2b5be
MONO_BEARISH = #5d606b
HISTORICAL = 'Historical'
PRESENT = 'Present'
COLORED = 'Colored'
MONOCHROME = 'Monochrome'
ALL = 'All'
BOS = 'BOS'
CHOCH = 'CHoCH'
TINY = size.tiny
SMALL = size.small
NORMAL = size.normal
ATR = 'Atr'
RANGE = 'Cumulative Mean Range'
CLOSE = 'Close'
HIGHLOW = 'High/Low'
SOLID = '⎯⎯⎯'
DASHED = '----'
DOTTED = '····'
SMART_GROUP = 'Smart Money Concepts'
INTERNAL_GROUP = 'Real Time Internal Structure'
SWING_GROUP = 'Real Time Swing Structure'
BLOCKS_GROUP = 'Order Blocks'
EQUAL_GROUP = 'EQH/EQL'
GAPS_GROUP = 'Fair Value Gaps'
LEVELS_GROUP = 'Highs & Lows MTF'
ZONES_GROUP = 'Premium & Discount Zones'
modeTooltip = 'Allows to display historical Structure or only the recent ones'
styleTooltip = 'Indicator color theme'
showTrendTooltip = 'Display additional candles with a color reflecting the current trend detected by structure'
showInternalsTooltip = 'Display internal market structure'
internalFilterConfluenceTooltip = 'Filter non significant internal structure breakouts'
showStructureTooltip = 'Display swing market Structure'
showSwingsTooltip = 'Display swing point as labels on the chart'
showHighLowSwingsTooltip = 'Highlight most recent strong and weak high/low points on the chart'
showInternalOrderBlocksTooltip = 'Display internal order blocks on the chart Number of internal order blocks to display on the chart'
showSwingOrderBlocksTooltip = 'Display swing order blocks on the chart Number of internal swing blocks to display on the chart'
orderBlockFilterTooltip = 'Method used to filter out volatile order blocks It is recommended to use the cumulative mean range method when a low amount of data is available'
orderBlockMitigationTooltip = 'Select what values to use for order block mitigation'
showEqualHighsLowsTooltip = 'Display equal highs and equal lows on the chart'
equalHighsLowsLengthTooltip = 'Number of bars used to confirm equal highs and equal lows'
equalHighsLowsThresholdTooltip = 'Sensitivity threshold in a range (0, 1) used for the detection of equal highs & lows Lower values will return fewer but more pertinent results'
showFairValueGapsTooltip = 'Display fair values gaps on the chart'
fairValueGapsThresholdTooltip = 'Filter out non significant fair value gaps'
fairValueGapsTimeframeTooltip = 'Fair value gaps timeframe'
fairValueGapsExtendTooltip = 'Determine how many bars to extend the Fair Value Gap boxes on chart'
showPremiumDiscountZonesTooltip = 'Display premium, discount, and equilibrium zones on chart'
modeInput = input.string( HISTORICAL, 'Mode', group = SMART_GROUP, tooltip = modeTooltip, options = )
styleInput = input.string( COLORED, 'Style', group = SMART_GROUP, tooltip = styleTooltip,options = )
showTrendInput = input( false, 'Color Candles', group = SMART_GROUP, tooltip = showTrendTooltip)
showInternalsInput = input( false, 'Show Internal Structure', group = INTERNAL_GROUP, tooltip = showInternalsTooltip)
showInternalBullInput = input.string( ALL, 'Bullish Structure', group = INTERNAL_GROUP, inline = 'ibull', options = )
internalBullColorInput = input( GREEN, '', group = INTERNAL_GROUP, inline = 'ibull')
showInternalBearInput = input.string( ALL, 'Bearish Structure' , group = INTERNAL_GROUP, inline = 'ibear', options = )
internalBearColorInput = input( RED, '', group = INTERNAL_GROUP, inline = 'ibear')
internalFilterConfluenceInput = input( false, 'Confluence Filter', group = INTERNAL_GROUP, tooltip = internalFilterConfluenceTooltip)
internalStructureSize = input.string( TINY, 'Internal Label Size', group = INTERNAL_GROUP, options = )
showStructureInput = input( false, 'Show Swing Structure', group = SWING_GROUP, tooltip = showStructureTooltip)
showSwingBullInput = input.string( ALL, 'Bullish Structure', group = SWING_GROUP, inline = 'bull', options = )
swingBullColorInput = input( GREEN, '', group = SWING_GROUP, inline = 'bull')
showSwingBearInput = input.string( ALL, 'Bearish Structure', group = SWING_GROUP, inline = 'bear', options = )
swingBearColorInput = input( RED, '', group = SWING_GROUP, inline = 'bear')
swingStructureSize = input.string( SMALL, 'Swing Label Size', group = SWING_GROUP, options = )
showSwingsInput = input( false, 'Show Swings Points', group = SWING_GROUP, tooltip = showSwingsTooltip,inline = 'swings')
swingsLengthInput = input.int( 50, '', group = SWING_GROUP, minval = 10, inline = 'swings')
showHighLowSwingsInput = input( false, 'Show Strong/Weak High/Low',group = SWING_GROUP, tooltip = showHighLowSwingsTooltip)
showInternalOrderBlocksInput = input( true, 'Internal Order Blocks' , group = BLOCKS_GROUP, tooltip = showInternalOrderBlocksTooltip, inline = 'iob')
internalOrderBlocksSizeInput = input.int( 5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'iob')
showSwingOrderBlocksInput = input( true, 'Swing Order Blocks', group = BLOCKS_GROUP, tooltip = showSwingOrderBlocksTooltip, inline = 'ob')
swingOrderBlocksSizeInput = input.int( 5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'ob')
orderBlockFilterInput = input.string( 'Atr', 'Order Block Filter', group = BLOCKS_GROUP, tooltip = orderBlockFilterTooltip, options = )
orderBlockMitigationInput = input.string( HIGHLOW, 'Order Block Mitigation', group = BLOCKS_GROUP, tooltip = orderBlockMitigationTooltip, options = )
internalBullishOrderBlockColor = input.color(color.new(GREEN, 80), 'Internal Bullish OB', group = BLOCKS_GROUP)
internalBearishOrderBlockColor = input.color(color.new(#f77c80, 80), 'Internal Bearish OB', group = BLOCKS_GROUP)
swingBullishOrderBlockColor = input.color(color.new(GREEN, 80), 'Bullish OB', group = BLOCKS_GROUP)
swingBearishOrderBlockColor = input.color(color.new(#b22833, 80), 'Bearish OB', group = BLOCKS_GROUP)
showEqualHighsLowsInput = input( false, 'Equal High/Low', group = EQUAL_GROUP, tooltip = showEqualHighsLowsTooltip)
equalHighsLowsLengthInput = input.int( 3, 'Bars Confirmation', group = EQUAL_GROUP, tooltip = equalHighsLowsLengthTooltip, minval = 1)
equalHighsLowsThresholdInput = input.float( 0.1, 'Threshold', group = EQUAL_GROUP, tooltip = equalHighsLowsThresholdTooltip, minval = 0, maxval = 0.5, step = 0.1)
equalHighsLowsSizeInput = input.string( TINY, 'Label Size', group = EQUAL_GROUP, options = )
showFairValueGapsInput = input( false, 'Fair Value Gaps', group = GAPS_GROUP, tooltip = showFairValueGapsTooltip)
fairValueGapsThresholdInput = input( true, 'Auto Threshold', group = GAPS_GROUP, tooltip = fairValueGapsThresholdTooltip)
fairValueGapsTimeframeInput = input.timeframe('', 'Timeframe', group = GAPS_GROUP, tooltip = fairValueGapsTimeframeTooltip)
fairValueGapsBullColorInput = input.color(color.new(#00ff68, 70), 'Bullish FVG' , group = GAPS_GROUP)
fairValueGapsBearColorInput = input.color(color.new(#ff0008, 70), 'Bearish FVG' , group = GAPS_GROUP)
fairValueGapsExtendInput = input.int( 1, 'Extend FVG', group = GAPS_GROUP, tooltip = fairValueGapsExtendTooltip, minval = 0)
showDailyLevelsInput = input( false, 'Daily', group = LEVELS_GROUP, inline = 'daily')
dailyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'daily', options = )
dailyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'daily')
showWeeklyLevelsInput = input( false, 'Weekly', group = LEVELS_GROUP, inline = 'weekly')
weeklyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'weekly', options = )
weeklyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'weekly')
showMonthlyLevelsInput = input( false, 'Monthly', group = LEVELS_GROUP, inline = 'monthly')
monthlyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'monthly', options = )
monthlyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'monthly')
showPremiumDiscountZonesInput = input( false, 'Premium/Discount Zones', group = ZONES_GROUP , tooltip = showPremiumDiscountZonesTooltip)
premiumZoneColorInput = input.color( RED, 'Premium Zone', group = ZONES_GROUP)
equilibriumZoneColorInput = input.color( GRAY, 'Equilibrium Zone', group = ZONES_GROUP)
discountZoneColorInput = input.color( GREEN, 'Discount Zone', group = ZONES_GROUP)
type alerts
bool internalBullishBOS = false
bool internalBearishBOS = false
bool internalBullishCHoCH = false
bool internalBearishCHoCH = false
bool swingBullishBOS = false
bool swingBearishBOS = false
bool swingBullishCHoCH = false
bool swingBearishCHoCH = false
bool internalBullishOrderBlock = false
bool internalBearishOrderBlock = false
bool swingBullishOrderBlock = false
bool swingBearishOrderBlock = false
bool equalHighs = false
bool equalLows = false
bool bullishFairValueGap = false
bool bearishFairValueGap = false
type trailingExtremes
float top
float bottom
int barTime
int barIndex
int lastTopTime
int lastBottomTime
type fairValueGap
float top
float bottom
int bias
box topBox
box bottomBox
type trend
int bias
type equalDisplay
line l_ine = na
label l_abel = na
type pivot
float currentLevel
float lastLevel
bool crossed
int barTime = time
int barIndex = bar_index
type orderBlock
float barHigh
float barLow
int barTime
int bias
// @variable current swing pivot high
var pivot swingHigh = pivot.new(na,na,false)
// @variable current swing pivot low
var pivot swingLow = pivot.new(na,na,false)
// @variable current internal pivot high
var pivot internalHigh = pivot.new(na,na,false)
// @variable current internal pivot low
var pivot internalLow = pivot.new(na,na,false)
// @variable current equal high pivot
var pivot equalHigh = pivot.new(na,na,false)
// @variable current equal low pivot
var pivot equalLow = pivot.new(na,na,false)
// @variable swing trend bias
var trend swingTrend = trend.new(0)
// @variable internal trend bias
var trend internalTrend = trend.new(0)
// @variable equal high display
var equalDisplay equalHighDisplay = equalDisplay.new()
// @variable equal low display
var equalDisplay equalLowDisplay = equalDisplay.new()
// @variable storage for fairValueGap UDTs
var array fairValueGaps = array.new()
// @variable storage for parsed highs
var array parsedHighs = array.new()
// @variable storage for parsed lows
var array parsedLows = array.new()
// @variable storage for raw highs
var array highs = array.new()
// @variable storage for raw lows
var array lows = array.new()
// @variable storage for bar time values
var array times = array.new()
// @variable last trailing swing high and low
var trailingExtremes trailing = trailingExtremes.new()
// @variable storage for orderBlock UDTs (swing order blocks)
var array swingOrderBlocks = array.new()
// @variable storage for orderBlock UDTs (internal order blocks)
var array internalOrderBlocks = array.new()
// @variable storage for swing order blocks boxes
var array swingOrderBlocksBoxes = array.new()
// @variable storage for internal order blocks boxes
var array internalOrderBlocksBoxes = array.new()
// @variable color for swing bullish structures
var swingBullishColor = styleInput == MONOCHROME ? MONO_BULLISH : swingBullColorInput
// @variable color for swing bearish structures
var swingBearishColor = styleInput == MONOCHROME ? MONO_BEARISH : swingBearColorInput
// @variable color for bullish fair value gaps
var fairValueGapBullishColor = styleInput == MONOCHROME ? color.new(MONO_BULLISH,70) : fairValueGapsBullColorInput
// @variable color for bearish fair value gaps
var fairValueGapBearishColor = styleInput == MONOCHROME ? color.new(MONO_BEARISH,70) : fairValueGapsBearColorInput
// @variable color for premium zone
var premiumZoneColor = styleInput == MONOCHROME ? MONO_BEARISH : premiumZoneColorInput
// @variable color for discount zone
var discountZoneColor = styleInput == MONOCHROME ? MONO_BULLISH : discountZoneColorInput
// @variable bar index on current script iteration
varip int currentBarIndex = bar_index
// @variable bar index on last script iteration
varip int lastBarIndex = bar_index
// @variable alerts in current bar
alerts currentAlerts = alerts.new()
// @variable time at start of chart
var initialTime = time
// we create the needed boxes for displaying order blocks at the first execution
if barstate.isfirst
if showSwingOrderBlocksInput
for index = 1 to swingOrderBlocksSizeInput
swingOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
if showInternalOrderBlocksInput
for index = 1 to internalOrderBlocksSizeInput
internalOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
// @variable source to use in bearish order blocks mitigation
bearishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE ? close : high
// @variable source to use in bullish order blocks mitigation
bullishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE ? close : low
// @variable default volatility measure
atrMeasure = ta.atr(200)
// @variable parsed volatility measure by user settings
volatilityMeasure = orderBlockFilterInput == ATR ? atrMeasure : ta.cum(ta.tr)/bar_index
// @variable true if current bar is a high volatility bar
highVolatilityBar = (high - low) >= (2 * volatilityMeasure)
// @variable parsed high
parsedHigh = highVolatilityBar ? low : high
// @variable parsed low
parsedLow = highVolatilityBar ? high : low
// we store current values into the arrays at each bar
parsedHighs.push(parsedHigh)
parsedLows.push(parsedLow)
highs.push(high)
lows.push(low)
times.push(time)
leg(int size) =>
var leg = 0
newLegHigh = high > ta.highest( size)
newLegLow = low < ta.lowest( size)
if newLegHigh
leg := BEARISH_LEG
else if newLegLow
leg := BULLISH_LEG
leg
startOfNewLeg(int leg) => ta.change(leg) != 0
startOfBearishLeg(int leg) => ta.change(leg) == -1
startOfBullishLeg(int leg) => ta.change(leg) == +1
drawLabel(int labelTime, float labelPrice, string tag, color labelColor, string labelStyle) =>
var label l_abel = na
if modeInput == PRESENT
l_abel.delete()
l_abel := label.new(chart.point.new(labelTime,na,labelPrice),tag,xloc.bar_time,color=color(na),textcolor=labelColor,style = labelStyle,size = size.small)
drawEqualHighLow(pivot p_ivot, float level, int size, bool equalHigh) =>
equalDisplay e_qualDisplay = equalHigh ? equalHighDisplay : equalLowDisplay
string tag = 'EQL'
color equalColor = swingBullishColor
string labelStyle = label.style_label_up
if equalHigh
tag := 'EQH'
equalColor := swingBearishColor
labelStyle := label.style_label_down
if modeInput == PRESENT
line.delete( e_qualDisplay.l_ine)
label.delete( e_qualDisplay.l_abel)
e_qualDisplay.l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time ,na,level), xloc = xloc.bar_time, color = equalColor, style = line.style_dotted)
labelPosition = math.round(0.5*(p_ivot.barIndex + bar_index - size))
e_qualDisplay.l_abel := label.new(chart.point.new(na,labelPosition,level), tag, xloc.bar_index, color = color(na), textcolor = equalColor, style = labelStyle, size = equalHighsLowsSizeInput)
getCurrentStructure(int size,bool equalHighLow = false, bool internal = false) =>
currentLeg = leg(size)
newPivot = startOfNewLeg(currentLeg)
pivotLow = startOfBullishLeg(currentLeg)
pivotHigh = startOfBearishLeg(currentLeg)
if newPivot
if pivotLow
pivot p_ivot = equalHighLow ? equalLow : internal ? internalLow : swingLow
if equalHighLow and math.abs(p_ivot.currentLevel - low ) < equalHighsLowsThresholdInput * atrMeasure
drawEqualHighLow(p_ivot, low , size, false)
p_ivot.lastLevel := p_ivot.currentLevel
p_ivot.currentLevel := low
p_ivot.crossed := false
p_ivot.barTime := time
p_ivot.barIndex := bar_index
if not equalHighLow and not internal
trailing.bottom := p_ivot.currentLevel
trailing.barTime := p_ivot.barTime
trailing.barIndex := p_ivot.barIndex
trailing.lastBottomTime := p_ivot.barTime
if showSwingsInput and not internal and not equalHighLow
drawLabel(time , p_ivot.currentLevel, p_ivot.currentLevel < p_ivot.lastLevel ? 'LL' : 'HL', swingBullishColor, label.style_label_up)
else
pivot p_ivot = equalHighLow ? equalHigh : internal ? internalHigh : swingHigh
if equalHighLow and math.abs(p_ivot.currentLevel - high ) < equalHighsLowsThresholdInput * atrMeasure
drawEqualHighLow(p_ivot,high ,size,true)
p_ivot.lastLevel := p_ivot.currentLevel
p_ivot.currentLevel := high
p_ivot.crossed := false
p_ivot.barTime := time
p_ivot.barIndex := bar_index
if not equalHighLow and not internal
trailing.top := p_ivot.currentLevel
trailing.barTime := p_ivot.barTime
trailing.barIndex := p_ivot.barIndex
trailing.lastTopTime := p_ivot.barTime
if showSwingsInput and not internal and not equalHighLow
drawLabel(time , p_ivot.currentLevel, p_ivot.currentLevel > p_ivot.lastLevel ? 'HH' : 'LH', swingBearishColor, label.style_label_down)
drawStructure(pivot p_ivot, string tag, color structureColor, string lineStyle, string labelStyle, string labelSize) =>
var line l_ine = line.new(na,na,na,na,xloc = xloc.bar_time)
var label l_abel = label.new(na,na)
if modeInput == PRESENT
l_ine.delete()
l_abel.delete()
l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time,na,p_ivot.currentLevel), xloc.bar_time, color=structureColor, style=lineStyle)
l_abel := label.new(chart.point.new(na,math.round(0.5*(p_ivot.barIndex+bar_index)),p_ivot.currentLevel), tag, xloc.bar_index, color=color(na), textcolor=structureColor, style=labelStyle, size = labelSize)
deleteOrderBlocks(bool internal = false) =>
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
for in orderBlocks
bool crossedOderBlock = false
if bearishOrderBlockMitigationSource > eachOrderBlock.barHigh and eachOrderBlock.bias == BEARISH
crossedOderBlock := true
if internal
currentAlerts.internalBearishOrderBlock := true
else
currentAlerts.swingBearishOrderBlock := true
else if bullishOrderBlockMitigationSource < eachOrderBlock.barLow and eachOrderBlock.bias == BULLISH
crossedOderBlock := true
if internal
currentAlerts.internalBullishOrderBlock := true
else
currentAlerts.swingBullishOrderBlock := true
if crossedOderBlock
orderBlocks.remove(index)
storeOrdeBlock(pivot p_ivot,bool internal = false,int bias) =>
if (not internal and showSwingOrderBlocksInput) or (internal and showInternalOrderBlocksInput)
array a_rray = na
int parsedIndex = na
if bias == BEARISH
a_rray := parsedHighs.slice(p_ivot.barIndex,bar_index)
parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.max())
else
a_rray := parsedLows.slice(p_ivot.barIndex,bar_index)
parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.min())
orderBlock o_rderBlock = orderBlock.new(parsedHighs.get(parsedIndex), parsedLows.get(parsedIndex), times.get(parsedIndex),bias)
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
if orderBlocks.size() >= 100
orderBlocks.pop()
orderBlocks.unshift(o_rderBlock)
drawOrderBlocks(bool internal = false) =>
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
orderBlocksSize = orderBlocks.size()
if orderBlocksSize > 0
maxOrderBlocks = internal ? internalOrderBlocksSizeInput : swingOrderBlocksSizeInput
array parsedOrdeBlocks = orderBlocks.slice(0, math.min(maxOrderBlocks,orderBlocksSize))
array b_oxes = internal ? internalOrderBlocksBoxes : swingOrderBlocksBoxes
for in parsedOrdeBlocks
orderBlockColor = styleInput == MONOCHROME ? (eachOrderBlock.bias == BEARISH ? color.new(MONO_BEARISH,80) : color.new(MONO_BULLISH,80)) : internal ? (eachOrderBlock.bias == BEARISH ? internalBearishOrderBlockColor : internalBullishOrderBlockColor) : (eachOrderBlock.bias == BEARISH ? swingBearishOrderBlockColor : swingBullishOrderBlockColor)
box b_ox = b_oxes.get(index)
b_ox.set_top_left_point( chart.point.new(eachOrderBlock.barTime,na,eachOrderBlock.barHigh))
b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,eachOrderBlock.barLow))
b_ox.set_border_color( internal ? na : orderBlockColor)
b_ox.set_bgcolor( orderBlockColor)
displayStructure(bool internal = false) =>
var bullishBar = true
var bearishBar = true
if internalFilterConfluenceInput
bullishBar := high - math.max(close, open) > math.min(close, open - low)
bearishBar := high - math.max(close, open) < math.min(close, open - low)
pivot p_ivot = internal ? internalHigh : swingHigh
trend t_rend = internal ? internalTrend : swingTrend
lineStyle = internal ? line.style_dashed : line.style_solid
labelSize = internal ? internalStructureSize : swingStructureSize
extraCondition = internal ? internalHigh.currentLevel != swingHigh.currentLevel and bullishBar : true
bullishColor = styleInput == MONOCHROME ? MONO_BULLISH : internal ? internalBullColorInput : swingBullColorInput
if ta.crossover(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
string tag = t_rend.bias == BEARISH ? CHOCH : BOS
if internal
currentAlerts.internalBullishCHoCH := tag == CHOCH
currentAlerts.internalBullishBOS := tag == BOS
else
currentAlerts.swingBullishCHoCH := tag == CHOCH
currentAlerts.swingBullishBOS := tag == BOS
p_ivot.crossed := true
t_rend.bias := BULLISH
displayCondition = internal ? showInternalsInput and (showInternalBullInput == ALL or (showInternalBullInput == BOS and tag != CHOCH) or (showInternalBullInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBullInput == ALL or (showSwingBullInput == BOS and tag != CHOCH) or (showSwingBullInput == CHOCH and tag == CHOCH))
if displayCondition
drawStructure(p_ivot,tag,bullishColor,lineStyle,label.style_label_down,labelSize)
if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
storeOrdeBlock(p_ivot,internal,BULLISH)
p_ivot := internal ? internalLow : swingLow
extraCondition := internal ? internalLow.currentLevel != swingLow.currentLevel and bearishBar : true
bearishColor = styleInput == MONOCHROME ? MONO_BEARISH : internal ? internalBearColorInput : swingBearColorInput
if ta.crossunder(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
string tag = t_rend.bias == BULLISH ? CHOCH : BOS
if internal
currentAlerts.internalBearishCHoCH := tag == CHOCH
currentAlerts.internalBearishBOS := tag == BOS
else
currentAlerts.swingBearishCHoCH := tag == CHOCH
currentAlerts.swingBearishBOS := tag == BOS
p_ivot.crossed := true
t_rend.bias := BEARISH
displayCondition = internal ? showInternalsInput and (showInternalBearInput == ALL or (showInternalBearInput == BOS and tag != CHOCH) or (showInternalBearInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBearInput == ALL or (showSwingBearInput == BOS and tag != CHOCH) or (showSwingBearInput == CHOCH and tag == CHOCH))
if displayCondition
drawStructure(p_ivot,tag,bearishColor,lineStyle,label.style_label_up,labelSize)
if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
storeOrdeBlock(p_ivot,internal,BEARISH)
fairValueGapBox(leftTime,rightTime,topPrice,bottomPrice,boxColor) => box.new(chart.point.new(leftTime,na,topPrice),chart.point.new(rightTime + fairValueGapsExtendInput * (time-time ),na,bottomPrice), xloc=xloc.bar_time, border_color = boxColor, bgcolor = boxColor)
deleteFairValueGaps() =>
for in fairValueGaps
if (low < eachFairValueGap.bottom and eachFairValueGap.bias == BULLISH) or (high > eachFairValueGap.top and eachFairValueGap.bias == BEARISH)
eachFairValueGap.topBox.delete()
eachFairValueGap.bottomBox.delete()
fairValueGaps.remove(index)
// @function draw fair value gaps
// @returns fairValueGap ID
drawFairValueGaps() =>
= request.security(syminfo.tickerid, fairValueGapsTimeframeInput, [close , open , time , high , low , time , high , low ],lookahead = barmerge.lookahead_on)
barDeltaPercent = (lastClose - lastOpen) / (lastOpen * 100)
newTimeframe = timeframe.change(fairValueGapsTimeframeInput)
threshold = fairValueGapsThresholdInput ? ta.cum(math.abs(newTimeframe ? barDeltaPercent : 0)) / bar_index * 2 : 0
bullishFairValueGap = currentLow > last2High and lastClose > last2High and barDeltaPercent > threshold and newTimeframe
bearishFairValueGap = currentHigh < last2Low and lastClose < last2Low and -barDeltaPercent > threshold and newTimeframe
if bullishFairValueGap
currentAlerts.bullishFairValueGap := true
fairValueGaps.unshift(fairValueGap.new(currentLow,last2High,BULLISH,fairValueGapBox(lastTime,currentTime,currentLow,math.avg(currentLow,last2High),fairValueGapBullishColor),fairValueGapBox(lastTime,currentTime,math.avg(currentLow,last2High),last2High,fairValueGapBullishColor)))
if bearishFairValueGap
currentAlerts.bearishFairValueGap := true
fairValueGaps.unshift(fairValueGap.new(currentHigh,last2Low,BEARISH,fairValueGapBox(lastTime,currentTime,currentHigh,math.avg(currentHigh,last2Low),fairValueGapBearishColor),fairValueGapBox(lastTime,currentTime,math.avg(currentHigh,last2Low),last2Low,fairValueGapBearishColor)))
getStyle(string style) =>
switch style
SOLID => line.style_solid
DASHED => line.style_dashed
DOTTED => line.style_dotted
drawLevels(string timeframe, bool sameTimeframe, string style, color levelColor) =>
= request.security(syminfo.tickerid, timeframe, [high , low , time , time],lookahead = barmerge.lookahead_on)
float parsedTop = sameTimeframe ? high : topLevel
float parsedBottom = sameTimeframe ? low : bottomLevel
int parsedLeftTime = sameTimeframe ? time : leftTime
int parsedRightTime = sameTimeframe ? time : rightTime
int parsedTopTime = time
int parsedBottomTime = time
if not sameTimeframe
int leftIndex = times.binary_search_rightmost(parsedLeftTime)
int rightIndex = times.binary_search_rightmost(parsedRightTime)
array timeArray = times.slice(leftIndex,rightIndex)
array topArray = highs.slice(leftIndex,rightIndex)
array bottomArray = lows.slice(leftIndex,rightIndex)
parsedTopTime := timeArray.size() > 0 ? timeArray.get(topArray.indexof(topArray.max())) : initialTime
parsedBottomTime := timeArray.size() > 0 ? timeArray.get(bottomArray.indexof(bottomArray.min())) : initialTime
var line topLine = line.new(na, na, na, na, xloc = xloc.bar_time, color = levelColor, style = getStyle(style))
var line bottomLine = line.new(na, na, na, na, xloc = xloc.bar_time, color = levelColor, style = getStyle(style))
var label topLabel = label.new(na, na, xloc = xloc.bar_time, text = str.format('P{0}H',timeframe), color=color(na), textcolor = levelColor, size = size.small, style = label.style_label_left)
var label bottomLabel = label.new(na, na, xloc = xloc.bar_time, text = str.format('P{0}L',timeframe), color=color(na), textcolor = levelColor, size = size.small, style = label.style_label_left)
topLine.set_first_point( chart.point.new(parsedTopTime,na,parsedTop))
topLine.set_second_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedTop))
topLabel.set_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedTop))
bottomLine.set_first_point( chart.point.new(parsedBottomTime,na,parsedBottom))
bottomLine.set_second_point(chart.point.new(last_bar_time + 20 * (time-time ),na,parsedBottom))
bottomLabel.set_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedBottom))
higherTimeframe(string timeframe) => timeframe.in_seconds() > timeframe.in_seconds(timeframe)
updateTrailingExtremes() =>
trailing.top := math.max(high,trailing.top)
trailing.lastTopTime := trailing.top == high ? time : trailing.lastTopTime
trailing.bottom := math.min(low,trailing.bottom)
trailing.lastBottomTime := trailing.bottom == low ? time : trailing.lastBottomTime
drawHighLowSwings() =>
var line topLine = line.new(na, na, na, na, color = swingBearishColor, xloc = xloc.bar_time)
var line bottomLine = line.new(na, na, na, na, color = swingBullishColor, xloc = xloc.bar_time)
var label topLabel = label.new(na, na, color=color(na), textcolor = swingBearishColor, xloc = xloc.bar_time, style = label.style_label_down, size = size.tiny)
var label bottomLabel = label.new(na, na, color=color(na), textcolor = swingBullishColor, xloc = xloc.bar_time, style = label.style_label_up, size = size.tiny)
rightTimeBar = last_bar_time + 20 * (time - time )
topLine.set_first_point( chart.point.new(trailing.lastTopTime, na, trailing.top))
topLine.set_second_point( chart.point.new(rightTimeBar, na, trailing.top))
topLabel.set_point( chart.point.new(rightTimeBar, na, trailing.top))
topLabel.set_text( swingTrend.bias == BEARISH ? 'Strong High' : 'Weak High')
bottomLine.set_first_point( chart.point.new(trailing.lastBottomTime, na, trailing.bottom))
bottomLine.set_second_point(chart.point.new(rightTimeBar, na, trailing.bottom))
bottomLabel.set_point( chart.point.new(rightTimeBar, na, trailing.bottom))
bottomLabel.set_text( swingTrend.bias == BULLISH ? 'Strong Low' : 'Weak Low')
drawZone(float labelLevel, int labelIndex, float top, float bottom, string tag, color zoneColor, string style) =>
var label l_abel = label.new(na,na,text = tag, color=color(na),textcolor = zoneColor, style = style, size = size.small)
var box b_ox = box.new(na,na,na,na,bgcolor = color.new(zoneColor,80),border_color = color(na), xloc = xloc.bar_time)
b_ox.set_top_left_point( chart.point.new(trailing.barTime,na,top))
b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,bottom))
l_abel.set_point( chart.point.new(na,labelIndex,labelLevel))
// @function draw premium/discount zones
// @returns void
drawPremiumDiscountZones() =>
drawZone(trailing.top, math.round(0.5*(trailing.barIndex + last_bar_index)), trailing.top, 0.95*trailing.top + 0.05*trailing.bottom, 'Premium', premiumZoneColor, label.style_label_down)
equilibriumLevel = math.avg(trailing.top, trailing.bottom)
drawZone(equilibriumLevel, last_bar_index, 0.525*trailing.top + 0.475*trailing.bottom, 0.525*trailing.bottom + 0.475*trailing.top, 'Equilibrium', equilibriumZoneColorInput, label.style_label_left)
drawZone(trailing.bottom, math.round(0.5*(trailing.barIndex + last_bar_index)), 0.95*trailing.bottom + 0.05*trailing.top, trailing.bottom, 'Discount', discountZoneColor, label.style_label_up)
parsedOpen = showTrendInput ? open : na
candleColor = internalTrend.bias == BULLISH ? swingBullishColor : swingBearishColor
plotcandle(parsedOpen,high,low,close,color = candleColor, wickcolor = candleColor, bordercolor = candleColor)
if showHighLowSwingsInput or showPremiumDiscountZonesInput
updateTrailingExtremes()
if showHighLowSwingsInput
drawHighLowSwings()
if showPremiumDiscountZonesInput
drawPremiumDiscountZones()
if showFairValueGapsInput
deleteFairValueGaps()
getCurrentStructure(swingsLengthInput,false)
getCurrentStructure(5,false,true)
if showEqualHighsLowsInput
getCurrentStructure(equalHighsLowsLengthInput,true)
if showInternalsInput or showInternalOrderBlocksInput or showTrendInput
displayStructure(true)
if showStructureInput or showSwingOrderBlocksInput or showHighLowSwingsInput
displayStructure()
if showInternalOrderBlocksInput
deleteOrderBlocks(true)
if showSwingOrderBlocksInput
deleteOrderBlocks()
if showFairValueGapsInput
drawFairValueGaps()
if barstate.islastconfirmedhistory or barstate.islast
if showInternalOrderBlocksInput
drawOrderBlocks(true)
if showSwingOrderBlocksInput
drawOrderBlocks()
lastBarIndex := currentBarIndex
currentBarIndex := bar_index
newBar = currentBarIndex != lastBarIndex
if barstate.islastconfirmedhistory or (barstate.isrealtime and newBar)
if showDailyLevelsInput and not higherTimeframe('D')
drawLevels('D',timeframe.isdaily,dailyLevelsStyleInput,dailyLevelsColorInput)
if showWeeklyLevelsInput and not higherTimeframe('W')
drawLevels('W',timeframe.isweekly,weeklyLevelsStyleInput,weeklyLevelsColorInput)
if showMonthlyLevelsInput and not higherTimeframe('M')
drawLevels('M',timeframe.ismonthly,monthlyLevelsStyleInput,monthlyLevelsColorInput)
xATR = ta.atr(c)
nLoss = a * xATR
src = h ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close, lookahead = barmerge.lookahead_off) : close
xATRTrailingStop = 0.0
iff_1 = src > nz(xATRTrailingStop , 0) ? src - nLoss : src + nLoss
iff_2 = src < nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? math.min(nz(xATRTrailingStop ), src + nLoss) : iff_1
xATRTrailingStop := src > nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? math.max(nz(xATRTrailingStop ), src - nLoss) : iff_2
pos = 0
iff_3 = src > nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? -1 : nz(pos , 0)
pos := src < nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? 1 : iff_3
xcolor = pos == -1 ? color.red : pos == 1 ? color.green : color.blue
ema = ta.ema(src, 1)
above = ta.crossover(ema, xATRTrailingStop)
below = ta.crossover(xATRTrailingStop, ema)
buy = src > xATRTrailingStop and above
sell = src < xATRTrailingStop and below
barbuy = src > xATRTrailingStop
barsell = src < xATRTrailingStop
//---------------------------------------------------------------------------------------------------------------------}
//ALERTS
//---------------------------------------------------------------------------------------------------------------------{
alertcondition(currentAlerts.internalBullishBOS, 'Internal Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(currentAlerts.internalBullishCHoCH, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(currentAlerts.internalBearishBOS, 'Internal Bearish BOS', 'Internal Bearish BOS formed')
alertcondition(currentAlerts.internalBearishCHoCH, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH formed')
alertcondition(currentAlerts.swingBullishBOS, 'Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(currentAlerts.swingBullishCHoCH, 'Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(currentAlerts.swingBearishBOS, 'Bearish BOS', 'Bearish BOS formed')
alertcondition(currentAlerts.swingBearishCHoCH, 'Bearish CHoCH', 'Bearish CHoCH formed')
alertcondition(currentAlerts.internalBullishOrderBlock, 'Bullish Internal OB Breakout', 'Price broke bullish internal OB')
alertcondition(currentAlerts.internalBearishOrderBlock, 'Bearish Internal OB Breakout', 'Price broke bearish internal OB')
alertcondition(currentAlerts.swingBullishOrderBlock, 'Bullish Swing OB Breakout', 'Price broke bullish swing OB')
alertcondition(currentAlerts.swingBearishOrderBlock, 'Bearish Swing OB Breakout', 'Price broke bearish swing OB')
alertcondition(currentAlerts.equalHighs, 'Equal Highs', 'Equal highs detected')
alertcondition(currentAlerts.equalLows, 'Equal Lows', 'Equal lows detected')
alertcondition(currentAlerts.bullishFairValueGap, 'Bullish FVG', 'Bullish FVG formed')
alertcondition(currentAlerts.bearishFairValueGap, 'Bearish FVG', 'Bearish FVG formed')
alertcondition(buy, 'UT Long', 'UT Long')
alertcondition(sell, 'UT Short', 'UT Short')
plotshape(buy, title = 'Buy', text = 'Buy', style = shape.labelup, location = location.belowbar, color = color.new(color.green, 0), textcolor = color.new(color.white, 0), size = size.tiny)
plotshape(sell, title = 'Sell', text = 'Sell', style = shape.labeldown, location = location.abovebar, color = color.new(color.red, 0), textcolor = color.new(color.white, 0), size = size.tiny)
//--------------------------------------------------------------------------------------
// EMA ADDITIONS (Editable)
//--------------------------------------------------------------------------------------
ema5Len = input.int(5, "5 EMA Length", minval = 1)
ema9Len = input.int(9, "9 EMA Length", minval = 1)
ema5 = ta.ema(src, ema5Len)
ema9 = ta.ema(src, ema9Len)
plot(ema5, "EMA 5", color = color.red, linewidth = 2)
plot(ema9, "EMA 9", color = color.blue, linewidth = 2)
barcolor(barbuy ? color.green : na)
barcolor(barsell ? color.red : na)
Lorentzian Harmonic Flow - Adaptive ML⚡ LORENTZIAN HARMONIC FLOW — ADAPTIVE ML COMPLETE SYSTEM
THEORETICAL FOUNDATION: TEMPORAL RELATIVITY MEETS MACHINE LEARNING
The Lorentzian Harmonic Flow Adaptive ML system represents a paradigm shift in technical analysis by addressing a fundamental limitation that plagues traditional indicators: they assume time flows uniformly across all market conditions. In reality, markets experience time compression during volatile breakouts and time dilation during consolidation. A 50-period moving average calculated during a quiet overnight session captures vastly different market information than the same calculation during a high-volume news event.
This indicator solves this problem through Lorentzian spacetime modeling , borrowed directly from Einstein's special relativity. By calculating a dynamic gamma factor (γ) that measures market velocity relative to a volatility-based "speed of light," every calculation adapts its effective lookback period to the market's intrinsic clock. Combined with a dual-memory architecture, multi-regime detection, and Bayesian strategy selection, this creates a system that genuinely learns which approaches work in which market conditions.
CRITICAL DISTINCTION: TRUE ADAPTIVE LEARNING VS STATIC CLASSIFICATION
Before diving into the system architecture, it's essential to understand how this indicator fundamentally differs from traditional "Lorentzian" implementations, particularly the well-known Lorentzian Classification indicator.
THE ORIGINAL LORENTZIAN CLASSIFICATION APPROACH:
The pioneering Lorentzian Classification indicator (Jdehorty, 2022) introduced the financial community to Lorentzian distance metrics for pattern matching. However, it used offline training methodology :
• External Training: Required Python scripts or external ML tools to train the model on historical data
• Static Model: Once trained, the model parameters remained fixed
• No Real-Time Learning: The indicator classified patterns but didn't learn from outcomes
• Look-Ahead Bias Risk: Offline training could inadvertently use future data
• Manual Retraining: To adapt to new market conditions, users had to retrain externally and reload parameters
This was groundbreaking for bringing ML concepts to Pine Script, but it wasn't truly adaptive. The model was a snapshot—trained once, deployed, static.
THIS SYSTEM: TRUE ONLINE LEARNING
The Lorentzian Harmonic Flow Adaptive ML system represents a complete architectural departure :
✅ FULLY SELF-CONTAINED:
• Zero External Dependencies: No Python scripts, no external training tools, no data exports
• 100% Pine Script: Entire learning pipeline executes within TradingView
• One-Click Deployment: Load indicator, it begins learning immediately
• No Manual Configuration: System builds its own training data in real-time
✅ GENUINE FORWARD-WALK LEARNING:
• Real-Time Adaptation: Every trade outcome updates the model
• Forward-Only Logic: System uses only past confirmed data—zero look-ahead bias
• Continuous Evolution: Parameters adapt bar-by-bar based on rolling performance
• Regime-Specific Memory: Learns which patterns work in which conditions independently
✅ GETS BETTER WITH TIME:
• Week 1: Bootstrap mode—gathering initial data across regimes
• Month 2-3: Statistical significance emerges, parameter adaptation begins
• Month 4+: Mature learning, regime-specific optimization, confident selection
• Year 2+: Deep pattern library, proven parameter sets, robust to regime shifts
✅ NO RETRAINING REQUIRED:
• Automatic Adaptation: When market structure changes, system detects via performance degradation
• Memory Refresh: Old patterns naturally decay, new patterns replace them
• Parameter Evolution: Thresholds and multipliers adjust to current conditions
• Regime Awareness: If new regime emerges, enters bootstrap mode automatically
THE FUNDAMENTAL DIFFERENCE:
Traditional Lorentzian Classification:
"Here are patterns from the past. Current state matches pattern X, which historically preceded move Y. Signal fired."
→ Static knowledge, fixed rules, periodic retraining required
LHF Adaptive ML:
"In Trending Bull regime, Strategy B has 58% win rate and 1.4 Sharpe over last 30 trades. In High Vol Range, Strategy C performs better with 61% win rate and 1.8 Sharpe. Current state is Trending Bull, so I select Strategy B. If Strategy B starts failing, I'll adapt parameters or switch strategies. I'm learning which patterns matter in which contexts, and I improve every trade."
→ Dynamic learning, contextual adaptation, self-improving system
WHY THIS MATTERS:
Markets are non-stationary. A model trained on 2023 data may fail in 2024 when Fed policy shifts, volatility regime changes, or market structure evolves. Static models require constant human intervention—retraining, re-optimization, parameter updates.
This system learns continuously . It doesn't need you to tell it when markets changed. It discovers regime shifts through performance feedback, adapts parameters accordingly, and rebuilds its pattern library organically. The system running in Month 12 is fundamentally smarter than the system in Month 1—not because you retrained it, but because it learned from 1,000+ real outcomes.
This is the difference between pattern recognition (static ML) and reinforcement learning (adaptive ML). One classifies, the other learns and improves.
PART 1: LORENTZIAN TEMPORAL DYNAMICS
Markets don't experience time uniformly. During explosive volatility, price can compress weeks of movement into minutes. During consolidation, time dilates. Traditional indicators ignore this, using fixed periods regardless of market state.
The Lorentzian approach models market time using the Lorentz factor from special relativity:
γ = 1 / √(1 - v²/c²)
Where:
• v (velocity): Trend momentum normalized by ATR, calculated as (close - close ) / (N × ATR)
• c (speed limit): Realized volatility + volatility bursts, multiplied by c_multiplier parameter
• γ (gamma): Time dilation factor that compresses or expands effective lookback periods
When trend velocity approaches the volatility "speed limit," gamma spikes above 1.0, compressing time. Every calculation length becomes: base_period / γ. This creates shorter, more responsive periods during explosive moves and longer, more stable periods during quiet consolidation.
The system raises gamma to an optional power (gamma_power parameter) for fine control over compression strength, then applies this temporal scaling to every calculation in the indicator. This isn't metaphor—it's quantitative adaptation to the market's intrinsic clock.
PART 2: LORENTZIAN KERNEL SMOOTHING
Traditional moving averages use uniform weights (SMA) or exponential decay (EMA). The Lorentzian kernel uses heavy-tailed weighting:
K(distance, γ) = 1 / (1 + (distance/γ)²)
This Cauchy-like distribution gives more influence to recent extremes than Gaussian assumptions suggest, capturing the fat-tailed nature of financial returns. For any calculation requiring smoothing, the system loops through historical bars, computes Lorentzian kernel weights based on temporal distance and current gamma, then produces weighted averages.
This creates adaptive smoothing that responds to local volatility structure rather than imposing rigid assumptions about price distribution.
PART 3: HARMONIC FLOW (Multi-Timeframe Momentum)
The core directional signal comes from Harmonic Flow (HFL) , which blends three gamma-compressed Lorentzian smooths:
• Short Horizon: base_period × short_ratio / γ (default: 34 × 0.5 / γ ≈ 17 bars, faster with high γ)
• Mid Horizon: base_period × mid_ratio / γ (default: 34 × 1.0 / γ ≈ 34 bars, anchor timeframe)
• Long Horizon: base_period × long_ratio / γ (default: 34 × 2.5 / γ ≈ 85 bars, structural trend)
Each produces a Lorentzian-weighted smooth, converted to a z-score (distance from smooth normalized by ATR). These z-scores are then weighted-averaged:
HFL = (w_short × z_short + w_mid × z_mid + w_long × z_long) / (w_short + w_mid + w_long)
Default weights (0.45, 0.35, 0.20) favor recent momentum while respecting longer structure. Scalpers can increase short weight; swing traders can emphasize long weight. The result is a directional momentum indicator that captures multi-timeframe flow in compressed time.
From HFL, the system derives:
• Flow Velocity: HFL - HFL (momentum acceleration)
• Flow Acceleration: Second derivative (turning points)
• Temporal Compression Index (TCI): base_period / compressed_length (shows how much time is compressed)
PART 4: DUAL MEMORY ARCHITECTURE
Markets have memory—current conditions resonate with past regimes. But memory operates on two timescales, inspiring this indicator's dual-memory design:
SHORT-TERM MEMORY (STM):
• Capacity: 100 patterns (configurable 50-200)
• Decay Rate: 0.980 (50% weight after ~35 bars)
• Update Frequency: Every 10 bars
• Purpose: Capture current regime's tactical patterns
• Storage: Recent market states with 10-bar forward outcomes
• Analogy: Hippocampus (rapid encoding, fast fade)
LONG-TERM MEMORY (LTM):
• Capacity: 512 patterns (configurable 256-1024)
• Decay Rate: 0.997 (50% weight after ~230 bars)
• Quality Gate: Only high-quality patterns admitted (adaptive threshold per regime)
• Purpose: Strategic pattern library validated across regimes
• Storage: Validated patterns from weeks/months of history
• Analogy: Neocortex (slow consolidation, persistent storage)
Each memory stores 6-dimensional feature vectors:
1. HFL (harmonic flow strength)
2. Flow Velocity (momentum)
3. Flow Acceleration (turning points)
4. Volatility (realized vol EMA)
5. Entropy (market uncertainty)
6. Gamma (time compression state)
Plus the actual outcome (10-bar forward return).
K-NEAREST NEIGHBORS (KNN) PATTERN MATCHING:
When evaluating current market state, the system queries both memories using Lorentzian distance :
distance = Σ (1 - K(|feature_current - feature_memory|, γ))
This calculates similarity across all 6 dimensions using the same Lorentzian kernel, weighted by current gamma. The system finds K nearest neighbors (default: 8), weights each by:
• Similarity: Lorentzian kernel distance
• Age: Exponential decay based on bars since pattern
• Regime: Only patterns from similar regimes count
The weighted average of these neighbors' outcomes becomes the prediction. High-confidence predictions require both high similarity and agreement between multiple neighbors.
REGIME-AWARE BLENDING:
STM and LTM predictions are blended adaptively:
• High Vol Range regime: Trust STM 70% (recent matters in chaos)
• Trending regimes: Trust LTM 70% (structure matters in trends)
• Normal regimes: 50/50 blend
Agreement metric: When STM and LTM strongly disagree, the system flags low confidence—often indicating regime transition or novel market conditions requiring caution.
PART 5: FIVE-REGIME MARKET CLASSIFICATION
Traditional regime detection stops at "trending vs ranging." This system detects five distinct market states using linear regression slope and volatility analysis:
REGIME 0: TRENDING BULL ↗
• Detection: LR slope > trend_threshold (default: 0.3)
• Characteristics: Sustained positive HFL, elevated gamma, low entropy
• Best Strategy: B (Flow Momentum)
• Trading Behavior: Follow momentum, trail stops, pyramid winners
REGIME 1: TRENDING BEAR ↘
• Detection: LR slope < -trend_threshold
• Characteristics: Sustained negative HFL, elevated gamma, low entropy
• Best Strategy: B (Flow Momentum)
• Trading Behavior: Follow momentum short, aggressive exits on reversal
REGIME 2: HIGH VOL RANGE ↔
• Detection: |slope| < threshold AND vol_ratio > vol_expansion_threshold (default: 1.5)
• Characteristics: Oscillating HFL, high gamma spikes, high entropy
• Best Strategies: A (Squeeze Breakout) or C (Memory Pattern)
• Trading Behavior: Fade extremes, tight stops, quick profits
REGIME 3: LOW VOL RANGE —
• Detection: |slope| < threshold AND vol_ratio < vol_expansion_threshold
• Characteristics: Low HFL magnitude, gamma ≈ 1, squeeze conditions
• Best Strategy: A (Squeeze Breakout)
• Trading Behavior: Wait for breakout, wide stops on breakout entry
REGIME 4: TRANSITION ⚡
• Detection: Trend reversal OR volatility spike > 1.5× threshold
• Characteristics: Erratic gamma, high entropy, conflicting signals
• Best Strategy: None (often unfavorable)
• Trading Behavior: Stand aside, wait for clarity
Each regime gets a confidence score (0-1) measuring how clearly defined it is. Low confidence indicates messy, ambiguous conditions.
PART 6: THREE INDEPENDENT TRADING STRATEGIES
Rather than one signal logic, the system implements three distinct approaches:
STRATEGY A: SQUEEZE BREAKOUT
• Logic: Bollinger Bands squeeze release + HFL direction + flow velocity confirmation
• Calculation: Compares BB width to Keltner Channel width; fires when BB expands beyond KC
• Strength Score: 70 + compression_strength × 0.3 (tighter squeeze = higher score)
• Best Regimes: Low Vol Range (3), Transition exit (4→0 or 4→1)
• Pattern: Volatility contraction → directional expansion
• Philosophy: Calm before the storm; compression precedes explosion
STRATEGY B: LORENTZIAN FLOW MOMENTUM
• Logic: Strong HFL (×flow_mult) + positive velocity + gamma > 1.1 + NOT squeezing
• Calculation: |HFL × flow_mult| > 0.12, velocity confirms direction, gamma shows acceleration
• Strength Score: |HFL × flow_mult| × 80 + gamma × 10
• Best Regimes: Trending Bull (0), Trending Bear (1)
• Pattern: Established momentum → acceleration in compressed time
• Philosophy: Trend is friend when spacetime curves
STRATEGY C: MEMORY PATTERN MATCHING
• Logic: Dual KNN prediction > threshold + high confidence + agreement + HFL confirms
• Calculation: |memory_pred| > 0.005, memory_conf > 1.0, agreement > 0.5, HFL direction matches
• Strength Score: |prediction| × 800 × agreement
• Best Regimes: High Vol Range (2), sometimes others with sufficient pattern library
• Pattern: Historical similarity → outcome resonance
• Philosophy: Markets rhyme; learn from validated patterns
Each strategy generates independent strength scores. In multi-strategy mode (enabled by default), the system selects one strategy per regime based on risk-adjusted performance. In weighted mode (multi-strategy disabled), all three fire simultaneously with configurable weights.
PART 7: ADAPTIVE LEARNING & BAYESIAN SELECTION
This is where machine learning meets trading. The system maintains 15 independent performance matrices :
3 strategies × 5 regimes = 15 tracking systems
For each combination, it tracks:
• Trade Count: Number of completed trades
• Win Count: Profitable outcomes
• Total Return: Sum of percentage returns
• Squared Returns: For variance/Sharpe calculation
• Equity Curve: Virtual P&L assuming 10% risk per trade
• Peak Equity: All-time high for drawdown calculation
• Max Drawdown: Peak-to-trough decline
RISK-ADJUSTED SCORING:
For current regime, the system scores each strategy:
Sharpe Ratio: (mean_return / std_dev) × √252
Calmar Ratio: total_return / max_drawdown
Win Rate: wins / trades
Combined Score = 0.6 × Sharpe + 0.3 × Calmar + 0.1 × Win_Rate
The strategy with highest score is selected. This is similar to Thompson Sampling (multi-armed bandits) but uses deterministic selection rather than probabilistic sampling due to Pine Script limitations.
BOOTSTRAP MODE (Critical for Understanding):
For the first min_regime_samples trades (default: 10) in each regime:
• Status: "🔥 BOOTSTRAP (X/10)" displayed in dashboard
• Behavior: All signals allowed (gathering data)
• Regime Filter: Disabled (can't judge with insufficient data)
• Purpose: Avoid cold-start problem, build statistical foundation
After reaching threshold:
• Status: "✅ FAVORABLE" (score > 0.5) or "⚠️ UNFAVORABLE" (score ≤ 0.5)
• Behavior: Only trade favorable regimes (if enable_regime_filter = true)
• Learning: Parameters adapt based on outcomes
This solves a critical problem: you can't know which strategy works in a regime without data, but you can't get data without trading. Bootstrap mode gathers initial data safely, then switches to selective mode once statistical confidence emerges.
PARAMETER ADAPTATION (Per Regime):
Three parameters adapt independently for each regime based on outcomes:
1. SIGNAL QUALITY THRESHOLD (30-90):
• Starts: base_quality_threshold (default: 60)
• Adaptation:
Win Rate < 45% → RAISE threshold by learning_rate × 10 (be pickier)
Win Rate > 55% → LOWER threshold by learning_rate × 5 (take more)
• Effect: System becomes more selective in losing regimes, more aggressive in winning regimes
2. LTM QUALITY GATE (0.2-0.8):
• Starts: 0.4 (if adaptive gate enabled)
• Adaptation:
Sharpe < 0.5 → RAISE gate by learning_rate (demand better patterns)
Sharpe > 1.5 → LOWER gate by learning_rate × 0.5 (accept more patterns)
• Effect: LTM fills with high-quality patterns from winning regimes
3. FLOW MULTIPLIER (0.5-2.0):
• Starts: 1.0
• Adaptation:
Strong win (+2%+) → MULTIPLY by (1 + learning_rate × 0.1)
Strong loss (-2%+) → MULTIPLY by (1 - learning_rate × 0.1)
• Effect: Amplifies signal strength in profitable regimes, dampens in unprofitable
Each regime evolves independently. Trending Bull might develop threshold=55, gate=0.35, mult=1.3 while High Vol Range develops threshold=70, gate=0.50, mult=0.9.
PART 8: SHADOW PORTFOLIO VALIDATION
To validate learning objectively, the system runs three virtual portfolios :
Shadow Portfolio A: Trades only Strategy A signals
Shadow Portfolio B: Trades only Strategy B signals
Shadow Portfolio C: Trades only Strategy C signals
When any signal fires:
1. Open virtual position for corresponding strategy
2. On exit, calculate P&L (10% risk per trade)
3. Update equity, win count, profit factor
Dashboard displays:
• Equity: Current virtual balance (starts $10,000)
• Win%: Overall win rate across all regimes
• PF: Profit Factor (gross_profit / gross_loss)
This transparency shows which strategies actually perform, validates the selection logic, and prevents overfitting. If Shadow C shows $12,500 equity while A and B show $9,800, it confirms Strategy C's edge.
PART 9: HISTORICAL PRE-TRAINING
The system includes historical pre-training to avoid cold-start:
On Chart Load (if enabled):
1. Scan past pretrain_bars (default: 200)
2. Calculate historical HFL, gamma, velocity, acceleration, volatility, entropy
3. Compute 10-bar forward returns as outcomes
4. Populate STM with recent patterns
5. Populate LTM with high-quality patterns (quality > 0.4)
Effect:
• Without pre-training: Memories empty, no predictions for weeks, pure bootstrap
• With pre-training: System starts with pattern library, predictions from day one
Pre-training uses only past data (no future peeking) and fills memories with validated outcomes. This dramatically accelerates learning without compromising integrity.
PART 10: COMPREHENSIVE INPUT SYSTEM
The indicator provides 50+ inputs organized into logical groups. Here are the key parameters and their market-specific guidance:
🧠 ADAPTIVE LEARNING SYSTEM:
Enable Adaptive Learning (true/false):
• Function: Master switch for regime-specific strategy selection and parameter adaptation
• Enabled: System learns which strategies work in which regimes (recommended)
• Disabled: All strategies fire simultaneously with fixed weights (simpler, less adaptive)
• Recommendation: Keep enabled for all markets; system needs 2-3 months to mature
Learning Rate (0.01-0.20):
• Function: Speed of parameter adaptation based on outcomes
• Stocks/ETFs: 0.03-0.05 (slower, more stable)
• Crypto: 0.05-0.08 (faster, adapts to volatility)
• Forex: 0.04-0.06 (moderate)
• Timeframes:
1-5min scalping: 0.08-0.10 (rapid adaptation)
15min-1H day trading: 0.05-0.07 (balanced)
4H-Daily swing: 0.03-0.05 (conservative)
• Tradeoff: Higher = responsive but may overfit; Lower = stable but slower to adapt
Min Samples Per Regime (5-30):
• Function: Trades required before exiting bootstrap mode
• Active trading (>5 signals/day): 8-10 trades
• Moderate (1-5 signals/day): 10-15 trades
• Swing (few signals/week): 5-8 trades
• Logic: Bootstrap mode until this threshold; then uses Sharpe/Calmar for regime filtering
• Tradeoff: Lower = faster exit (risky, less data); Higher = more validation (safer, slower)
🌍 REGIME DETECTION:
Regime Lookback Period (20-200):
• Function: Bars used for linear regression to classify regime
• By Timeframe:
1-5min: 30-50 bars (~2-4 hour context)
15min: 40-60 bars (daily context)
1H: 50-100 bars (weekly context)
4H: 100-150 bars (monthly context)
Daily: 50-75 bars (quarterly context)
• By Market:
Crypto: 40-60 (faster regime changes)
Forex: 50-75 (moderate stability)
Stocks: 60-100 (slower structural trends)
• Tradeoff: Shorter = more regime switches (reactive); Longer = fewer switches (stable)
Trend Strength Threshold (0.1-0.8):
• Function: Minimum normalized LR slope to classify as trending vs ranging
• Lower (0.1-0.2): More markets classified as trending
• Higher (0.4-0.6): Only strong trends qualify
• Recommendations:
Choppy markets (BTC, small caps): 0.25-0.35
Smooth trends (major FX pairs): 0.30-0.40
Strong trends (indices during bull): 0.20-0.30
• Effect: Controls sensitivity of trending vs ranging classification
Vol Expansion Factor (1.2-3.0):
• Function: Volatility ratio to classify high-vol regimes (current_vol / avg_vol)
• By Asset:
Bitcoin: 1.4-1.6 (frequent vol spikes)
Altcoins: 1.3-1.5 (very volatile)
Major FX (EUR/USD): 1.6-2.0 (stable baseline)
Stocks (SPY): 1.5-1.8 (moderate)
Penny stocks: 1.3-1.4 (always volatile)
• Impact: Higher = fewer "High Vol Range" classifications; Lower = more sensitive to volatility spikes
🎯 SIGNAL GENERATION:
Base Quality Threshold (30-90):
• Function: Starting signal strength requirement (adapts per regime)
• THIS IS YOUR MAIN SIGNAL FREQUENCY CONTROL
• Conservative (70-80): Fewer, higher-quality signals
• Balanced (55-65): Moderate signal flow
• Aggressive (40-50): More signals, more noise
• By Trading Style:
Scalping (1-5min): 50-60
Day trading (15min-1H): 60-70
Swing (4H-Daily): 65-75
• Adaptive Behavior: System raises this in losing regimes (pickier), lowers in winning regimes (take more)
Min Confidence (0.1-0.9):
• Function: Minimum confidence score to fire signal
• Calculation: (Signal_Strength / 100) × Regime_Confidence
• Recommendations:
High-frequency (scalping): 0.2-0.3 (permissive)
Day trading: 0.3-0.4 (balanced)
Swing/position: 0.4-0.6 (selective)
• Interaction: During Transition regime (low regime confidence), even strong signals may fail confidence check; creates natural regime filtering
Only Trade Favorable Regimes (true/false):
• Function: Block signals in unfavorable regimes (where all strategies have negative risk-adjusted scores)
• Enabled (Recommended): Only trades when best strategy has positive Sharpe in current regime; auto-disables during bootstrap; protects capital
• Disabled: Always allows signals regardless of historical performance; use for manual regime assessment
• Bootstrap: Auto-allows trading until min_regime_samples reached, then switches to performance-based filtering
Min Bars Between Signals (1-20):
• Function: Prevents signal spam by enforcing minimum spacing
• By Timeframe:
1min: 3-5 bars (3-5 minutes)
5min: 3-6 bars (15-30 minutes)
15min: 4-8 bars (1-2 hours)
1H: 5-10 bars (5-10 hours)
4H: 3-6 bars (12-24 hours)
Daily: 2-5 bars (2-5 days)
• Logic: After signal fires, no new signals for X bars
• Tradeoff: Lower = more reactive (may overtrade); Higher = more patient (may miss reversals)
🌀 LORENTZIAN CORE:
Base Period (10-100):
• Function: Core time period for flow calculation (gets compressed by gamma)
• THIS IS YOUR PRIMARY TIMEFRAME KNOB
• By Timeframe:
1-5min scalping: 20-30 (fast response)
15min-1H day: 30-40 (balanced)
4H swing: 40-55 (smooth)
Daily position: 50-75 (very smooth)
• By Market Character:
Choppy (crypto, small caps): 25-35 (faster)
Smooth (major FX, indices): 35-50 (moderate)
Slow (bonds, utilities): 45-65 (slower)
• Gamma Effect: Actual length = base_period / gamma; High gamma compresses to ~20 bars, low gamma expands to ~50 bars
• Default 34 (Fibonacci) works well across most assets
Velocity Period (5-50):
• Function: Window for trend velocity calculation: (price_now - price ) / (N × ATR)
• By Timeframe:
1-5min scalping: 8-12 (fast momentum)
15min-1H day: 12-18 (balanced)
4H swing: 14-21 (smooth trend)
Daily: 18-30 (structural trend)
• By Market:
Crypto (fast moves): 10-14
Stocks (moderate): 14-20
Forex (smooth): 18-25
• Impact: Feeds into gamma calculation (v/c ratio); shorter = more sensitive to velocity spikes → higher gamma
• Relationship: Typically vel_period ≈ base_period / 2 to 2/3
Speed-of-Market (c) (0.5-3.0):
• Function: "Speed limit" for gamma calculation: c = realized_vol + vol_burst × c_multiplier
• By Asset Volatility:
High vol (BTC, TSLA): 1.0-1.3 (lower c = more compression)
Medium vol (SPY, EUR/USD): 1.3-1.6 (balanced)
Low vol (bonds, utilities): 1.6-2.5 (higher c = less compression)
• What It Does:
Lower c → velocity hits "speed limit" sooner → higher gamma → more compression
Higher c → velocity rarely hits limit → gamma stays near 1 → less adaptation
• Effect on Signals: More compression (low c) = faster regime detection, more responsive; Less compression (high c) = smoother, less adaptive
• Tuning: Start at 1.4; if gamma always ~1.0, lower to 1.0-1.2; if gamma spikes >5 often, raise to 1.6-2.0
Gamma Power (0.5-2.0):
• Function: Exponent applied to gamma: final_gamma = gamma^power
• Compression Strength:
0.5-0.8: Softens compression (gamma 4 → 2)
1.0: Linear (gamma 4 → 4)
1.2-2.0: Amplifies compression (gamma 4 → 16)
• Use Cases:
Reduce power (<1.0) if adaptive lengths swing too wildly or getting whipsawed
Increase power (>1.0) for more aggressive regime adaptation in fast markets
• Most users should leave at 1.0; only adjust if gamma behavior needs tuning
Max Kernel Lookback (20-200):
• Function: Computational limit for Lorentzian smoothing (performance control)
• Recommendations:
Fast PC / simple chart: 80-100
Slow PC / complex chart: 40-60
Mobile / lots of indicators: 30-50
• Impact: Each kernel smoothing loops through this many bars; higher = more accurate but slower
• Default 60 balances accuracy and speed; lower to 40-50 if indicator is slow
🎼 HARMONIC FLOW:
Short Horizon (0.2-1.0):
• Function: Fast timeframe multiplier: short_length = base_period × short_ratio / gamma
• Default: 0.5 (captures 2× faster flow than base)
• By Style:
Scalping: 0.3-0.4 (very fast)
Day trading: 0.4-0.6 (moderate)
Swing: 0.5-0.7 (balanced)
• Effect: Lower = more weight on micro-moves; Higher = smooths out fast fluctuations
Mid Horizon (0.5-2.0):
• Function: Medium timeframe multiplier: mid_length = base_period × mid_ratio / gamma
• Default: 1.0 (equals base_period, anchor timeframe)
• Usually keep at 1.0 unless specific strategy needs fine-tuning
Long Horizon (1.0-5.0):
• Function: Slow timeframe multiplier: long_length = base_period × long_ratio / gamma
• Default: 2.5 (captures trend/structure)
• By Style:
Scalping: 1.5-2.0 (less long-term influence)
Day trading: 2.0-3.0 (balanced)
Swing: 2.5-4.0 (strong trend component)
• Effect: Higher = more emphasis on larger structure; Lower = more reactive to recent price action
Short Weight (0-1):
Mid Weight (0-1):
Long Weight (0-1):
• Function: Relative importance in HFL calculation (should sum to 1.0)
• Defaults: Short: 0.45, Mid: 0.35, Long: 0.20 (day trading balanced)
• Preset Configurations:
SCALPING (fast response):
Short: 0.60, Mid: 0.30, Long: 0.10
DAY TRADING (balanced):
Short: 0.45, Mid: 0.35, Long: 0.20
SWING (trend-following):
Short: 0.25, Mid: 0.35, Long: 0.40
• Effect: More short weight = responsive but noisier; More long weight = smoother but laggier
🧠 DUAL MEMORY SYSTEM:
Enable Pattern Memory (true/false):
• Function: Master switch for KNN pattern matching via dual memory
• Enabled (Recommended): Strategy C (Memory Pattern) can fire; memory predictions influence all strategies; prediction arcs shown; heatmaps available
• Disabled: Only Strategy A and B available; faster performance (less computation); pure technical analysis (no pattern matching)
• Keep enabled for full system capabilities; disable only if CPU-constrained or testing pure flow signals
STM Size (50-200):
• Function: Short-Term Memory capacity (recent pattern storage)
• Characteristics: Fast decay (0.980), captures current regime, updates every 10 bars, tactical pattern matching
• Sizing:
Active markets (crypto): 80-120
Moderate (stocks): 100-150
Slow (bonds): 50-100
• By Timeframe:
1-15min: 60-100 (captures few hours of patterns)
1H: 80-120 (captures days)
4H-Daily: 100-150 (captures weeks/months)
• Tradeoff: More = better recent pattern coverage; Less = faster computation
• Default 100 is solid for most use cases
LTM Size (256-1024):
• Function: Long-Term Memory capacity (validated pattern storage)
• Characteristics: Slow decay (0.997), only high-quality patterns (gated), regime-specific recall, strategic pattern library
• Sizing:
Fast PC: 512-768
Medium PC: 384-512
Slow PC/Mobile: 256-384
• By Data Needs:
High-frequency (lots of patterns): 512-1024
Moderate activity: 384-512
Low-frequency (swing): 256-384
• Performance Impact: Each KNN search loops through entire LTM; 512 = good balance of coverage and speed; if slow, drop to 256-384
• Fills over weeks/months with validated patterns
STM Decay (0.95-0.995):
• Function: Short-Term Memory age decay rate: age_weight = decay^bars_since_pattern
• Decay Rates:
0.950: Aggressive fade (50% weight after 14 bars)
0.970: Moderate fade (50% after 23 bars)
0.980: Balanced (50% after 35 bars)
0.990: Slow fade (50% after 69 bars)
• By Timeframe:
1-5min: 0.95-0.97 (fast markets, old patterns irrelevant)
15min-1H: 0.97-0.98 (balanced)
4H-Daily: 0.98-0.99 (slower decay)
• Philosophy: STM should emphasize RECENT patterns; lower decay = only very recent matters; 0.980 works well for most cases
LTM Decay (0.99-0.999):
• Function: Long-Term Memory age decay rate
• Decay Rates:
0.990: 50% weight after 69 bars
0.995: 50% weight after 138 bars
0.997: 50% weight after 231 bars
0.999: 50% weight after 693 bars
• Philosophy: LTM should retain value for LONG periods; pattern from 6 months ago might still matter
• Usage:
Fast-changing markets: 0.990-0.995
Stable markets: 0.995-0.998
Structural patterns: 0.998-0.999
• Warning: Be careful with very high decay (>0.998); market structure changes, old patterns may mislead
• 0.997 balances long-term memory with regime evolution
K Neighbors (3-21):
• Function: Number of similar patterns to query in KNN search
• By Sample Size:
Small dataset (<100 patterns): 3-5
Medium dataset (100-300): 5-8
Large dataset (300-1000): 8-13
Very large (>1000): 13-21
• Tradeoff:
Fewer K (3-5): More reactive to closest matches; noisier; outlier-sensitive; better when patterns very distinct
More K (13-21): Smoother, more stable predictions; may dilute strong signals; better when patterns overlap
• Rule of Thumb: K ≈ √(memory_size) / 3; For STM=100, LTM=512: K ≈ 8-10 ideal
Adaptive Quality Gate (true/false):
• Function: Adapts LTM entry threshold per regime based on Sharpe ratio
• Enabled: Quality gate adapts: Low Sharpe → RAISE gate (demand better patterns); High Sharpe → LOWER gate (accept more patterns); each regime has independent gate
• Disabled: Fixed quality gate (0.4 default) for all regimes
• Recommended: Keep ENABLED; helps LTM focus on proven pattern types per regime; prevents weak patterns from polluting memory
🎯 MULTI-STRATEGY SYSTEM:
Enable Strategy Learning (true/false):
• Function: Core learning feature for regime-specific strategy selection
• Enabled: Tracks 3 strategies × 5 regimes = 15 performance matrices; selects best strategy per regime via Sharpe/Calmar/WinRate; adaptive strategy switching
• Disabled: All strategies fire simultaneously (weighted combination); no regime-specific selection; simpler but less adaptive
• Recommended: ENABLED (this is the core of the adaptive system); disable only for testing or simplification
Strategy A Weight (0-1):
• Function: Weight for Strategy A (Squeeze Breakout) when multi-strategy disabled
• Characteristics: Fires on Bollinger squeeze release; best in Low Vol Range, Transition; compression → expansion pattern
• When Multi-Strategy OFF: Default 0.33 (equal weight); increase to 0.4-0.5 for choppy ranges with breakouts; decrease to 0.2-0.3 for trending markets
• When Multi-Strategy ON: This is ignored (system auto-selects based on performance)
Strategy B Weight (0-1):
• Function: Weight for Strategy B (Lorentzian Flow) when multi-strategy disabled
• Characteristics: Fires on strong HFL + velocity + gamma; best in Trending Bull/Bear; momentum → acceleration pattern
• When Multi-Strategy OFF: Default 0.33; increase to 0.4-0.5 for trending markets; decrease to 0.2-0.3 for choppy/ranging markets
• When Multi-Strategy ON: Ignored (auto-selected)
Strategy C Weight (0-1):
• Function: Weight for Strategy C (Memory Pattern) when multi-strategy disabled
• Characteristics: Fires when dual KNN predicts strong move; best in High Vol Range; requires memory system enabled + sufficient data
• When Multi-Strategy OFF: Default 0.34; increase to 0.4-0.6 if strong pattern repetition and LTM has >200 patterns; decrease to 0.2-0.3 if new to system; set to 0.0 if memory disabled
• When Multi-Strategy ON: Ignored (auto-selected)
📚 PRE-TRAINING:
Historical Pre-Training (true/false):
• Function: Bootstrap feature that fills memory on chart load
• Enabled: Scans past bars to populate STM/LTM before live trading; calculates historical outcomes (10-bar forward returns); builds initial pattern library; system starts with context, not blank slate
• Disabled: Memories only populate in real-time; takes weeks to build pattern library
• Recommended: ENABLED (critical for avoiding "cold start" problem); disable only for testing clean learning
Training Bars (50-500):
• Function: How many historical bars to scan on load (limited by available history)
• Recommendations:
1-5min charts: 200-300 (few hours of history)
15min-1H: 200-400 (days/weeks)
4H: 300-500 (months)
Daily: 200-400 (years)
• Performance:
100 bars: ~1 second
300 bars: ~2-3 seconds
500 bars: ~4-5 seconds
• Sweet Spot: 200-300 (enough patterns without slow load)
• If chart loads slowly: Reduce to 100-150
🎨 VISUALIZATION:
Show Regime Background (true/false):
• Function: Color-code background by current regime
• Colors: Trending Bull (green tint), Trending Bear (red tint), High Vol Range (orange tint), Low Vol Range (blue tint), Transition (purple tint)
• Helps visually track regime changes
Show Flow Bands (true/false):
• Function: Plot upper/lower bands based on HFL strength
• Shows dynamic support/resistance zones; green fill = bullish flow; red fill = bearish flow
• Useful for visual trend confirmation
Show Confidence Meter (true/false):
• Function: Plot signal confidence (0-100) in separate pane
• Calculation: (Signal_Strength / 100) × Regime_Confidence
• Gold line = current confidence; dashed line = minimum threshold
• Signals fire when confidence exceeds threshold
Show Prediction Arc (true/false):
• Function: Dashed line projecting expected price move based on memory prediction
• NOT a price target - a probability vector; steep arc = strong expected move; flat arc = weak/uncertain prediction
• Green = bullish prediction; red = bearish prediction
Show Signals (true/false):
• Function: Triangle markers at entry points
• ▲ Green = Long signal; ▼ Red = Short signal
• Markers show on bar close (non-repainting)
🏆 DASHBOARD:
Show Dashboard (true/false):
• Function: Main info panel showing all system metrics
• Sections: Lorentzian Core, Regime, Dual Memory, Adaptive Parameters, Regime Performance, Shadow Portfolios, Current Signal Status
• Essential for understanding system state
Dashboard Position: Top Left, Top Right, Bottom Left, Bottom Right
Individual Section Toggles:
• System Stats: Lorentzian Core section (Gamma, v/c, HFL, TCI)
• Memory Stats: Dual Memory section (STM/LTM predictions, agreement)
• Shadow Portfolios: Shadow Portfolio table (equity, win%, PF)
• Adaptive Params: Adaptive Parameters section (threshold, quality gate, flow mult)
🔥 HEATMAPS:
Show Dual Heatmaps (true/false):
• Function: Visual pattern density maps for STM and LTM
• Layout: X-axis = pattern age (left=recent, right=old); Y-axis = outcome direction (top=bearish, bottom=bullish); Color intensity = pattern count; Color hue = bullish (green) vs bearish (red)
• Warning: Can clutter chart; disable if not using
Heatmap Position: Screen position for heatmaps (STM at selected position, LTM offset)
Resolution (5-15):
• Function: Grid resolution (bins)
• Higher = more detailed but smaller cells; Lower = clearer but less granular
• 10 is good balance; reduce to 6-8 if hard to read
PART 11: DASHBOARD METRICS EXPLAINED
The comprehensive dashboard provides real-time transparency into every aspect of the adaptive system:
⚡ LORENTZIAN CORE SECTION:
Gamma (γ):
• Range: 1.0 to ~10.0 (capped)
• Interpretation:
γ ≈ 1.0-1.2: Normal market time, low velocity
γ = 1.5-2.5: Moderate compression, trending
γ = 3.0-5.0: High compression, explosive moves
γ > 5.0: Extreme compression, parabolic volatility
• Usage: High gamma = system operating in compressed time; expect shorter effective periods and faster adaptation
v/c (Velocity / Speed Limit):
• Range: 0.0 to 0.999 (approaches but never reaches 1.0)
• Interpretation:
v/c < 0.3: Slow market, low momentum
v/c = 0.4-0.7: Moderate trending
v/c > 0.7: Approaching "speed limit," high velocity
v/c > 0.9: Parabolic move, system at limit
• Color Coding: Red (>0.7), Gold (0.4-0.7), Green (<0.4)
• Usage: High v/c warns of extreme conditions where trend may exhaust
HFL (Harmonic Flow):
• Range: Typically -3.0 to +3.0 (can exceed in extremes)
• Interpretation:
HFL > 0: Bullish flow
HFL < 0: Bearish flow
|HFL| > 0.5: Strong directional bias
|HFL| < 0.2: Weak, indecisive
• Color: Green (positive), Red (negative)
• Usage: Primary directional indicator; strategies often require HFL confirmation
TCI (Temporal Compression Index):
• Calculation: base_period / compressed_length
• Interpretation:
TCI ≈ 1.0: No compression, normal time
TCI = 1.5-2.5: Moderate compression
TCI > 3.0: Significant compression
• Usage: Shows how much time is being compressed; mirrors gamma but more intuitive
╔═══ REGIME SECTION ═══╗
Current:
• Display: Regime name with icon (Trending Bull ↗, Trending Bear ↘, High Vol Range ↔, Low Vol Range —, Transition ⚡)
• Color: Gold for visibility
• Usage: Know which regime you're in; check regime performance to see expected strategy behavior
Confidence:
• Range: 0-100%
• Interpretation:
>70%: Very clear regime definition
40-70%: Moderate clarity
<40%: Ambiguous, mixed conditions
• Color: Green (>70%), Gold (40-70%), Red (<40%)
• Usage: High confidence = trust regime classification; low confidence = regime may be transitioning
Mode:
• States:
🔥 BOOTSTRAP (X/10): Still gathering data for this regime
✅ FAVORABLE: Best strategy has positive risk-adjusted score (>0.5)
⚠️ UNFAVORABLE: All strategies have negative scores (≤0.5)
• Color: Orange (bootstrap), Green (favorable), Red (unfavorable)
• Critical Importance: This tells you whether the system will trade or stand aside (if regime filter enabled)
╔═══ DUAL MEMORY KNN SECTION ═══╗
STM (Size):
• Display: Number of patterns currently in STM (0 to stm_size)
• Interpretation: Should fill to capacity within hours/days; if not filling, check that memory is enabled
STM Pred:
• Range: Typically -0.05 to +0.05 (representing -5% to +5% expected 10-bar move)
• Color: Green (positive), Red (negative)
• Usage: STM's prediction based on recent patterns; emphasis on current regime
LTM (Size):
• Display: Number of patterns in LTM (0 to ltm_size)
• Interpretation: Fills slowly (weeks/months); only validated high-quality patterns; check quality gate if not filling
LTM Pred:
• Range: Similar to STM pred
• Color: Green (positive), Red (negative)
• Usage: LTM's prediction based on long-term validated patterns; more strategic than tactical
Agreement:
• Display:
✅ XX%: Strong agreement (>70%) - both memories aligned
⚠️ XX%: Moderate agreement (40-70%) - some disagreement
❌ XX%: Conflict (<40%) - memories strongly disagree
• Color: Green (>70%), Gold (40-70%), Red (<40%)
• Critical Usage: Low agreement often precedes regime change or signals novel conditions; Strategy C won't fire with low agreement
╔═══ ADAPTIVE PARAMS SECTION ═══╗
Threshold:
• Display: Current regime's signal quality threshold (30-90)
• Interpretation: Higher = pickier; lower = more permissive
• Watch For: If steadily rising in a regime, system is struggling (low win rate); if falling, system is confident
• Default: Starts at base_quality_threshold (usually 60)
Quality:
• Display: Current regime's LTM quality gate (0.2-0.8)
• Interpretation: Minimum quality score for pattern to enter LTM
• Watch For: If rising, system demanding higher-quality patterns; if falling, accepting more diverse patterns
• Default: Starts at 0.4
Flow Mult:
• Display: Current regime's flow multiplier (0.5-2.0)
• Interpretation: Amplifies or dampens HFL for Strategy B
• Watch For: If >1.2, system found strong edge in flow signals; if <0.8, flow signals underperforming
• Default: Starts at 1.0
Learning:
• Display: ✅ ON or ❌ OFF
• Shows whether adaptive learning is enabled
• Color: Green (on), Red (off)
╔═══ REGIME PERFORMANCE SECTION ═══╗
This table shows ONLY the current regime's statistics:
S (Strategy):
• Display: A, B, or C
• Color: Gold if selected strategy; gray if not
• Shows which strategies have data in this regime
Trades:
• Display: Number of completed trades for this pair
• Interpretation: Blank or low numbers mean bootstrap mode; >10 means statistical significance building
Win%:
• Display: Win rate percentage
• Color: Green (>55%), White (45-55%), Red (<45%)
• Interpretation: 52%+ is good; 58%+ is excellent; <45% means struggling
• Note: Short-term variance is normal; judge after 20+ trades
Sharpe:
• Display: Annualized Sharpe ratio
• Color: Green (>1.0), White (0-1.0), Red (<0)
• Interpretation:
>2.0: Exceptional (rare)
1.0-2.0: Good
0.5-1.0: Acceptable
0-0.5: Marginal
<0: Losing
• Usage: Primary metric for strategy selection (60% weight in score)
╔═══ SHADOW PORTFOLIOS SECTION ═══╗
Shows virtual equity tracking across ALL regimes (not just current):
S (Strategy):
• Display: A, B, or C
• Color: Gold if currently selected strategy; gray otherwise
Equity:
• Display: Current virtual balance (starts $10,000)
• Color: Green (>$10,000), White ($9,500-$10,000), Red (<$9,500)
• Interpretation: Which strategy is actually making virtual money across all conditions
• Note: 10% risk per trade assumed
Win%:
• Display: Overall win rate across all regimes
• Color: Green (>55%), White (45-55%), Red (<45%)
• Interpretation: Aggregate performance; strategy may do well in some regimes and poorly in others
PF (Profit Factor):
• Display: Gross profit / gross loss
• Color: Green (>1.5), White (1.0-1.5), Red (<1.0)
• Interpretation:
>2.0: Excellent
1.5-2.0: Good
1.2-1.5: Acceptable
1.0-1.2: Marginal
<1.0: Losing
• Usage: Confirms win rate; high PF with moderate win rate means winners >> losers
╔═══ STATUS BAR ═══╗
Display States:
• 🟢 LONG: Currently in long position (green background)
• 🔴 SHORT: Currently in short position (red background)
• ⬆️ LONG SIGNAL: Long signal present but not yet confirmed (waiting for bar close)
• ⬇️ SHORT SIGNAL: Short signal present but not yet confirmed
• ⚪ NEUTRAL: No position, no signal (white background)
Usage: Immediate visual confirmation of system state; check before manually entering/exiting
PART 12: VISUAL ELEMENT INTERPRETATION
REGIME BACKGROUND COLORS:
Green Tint: Trending Bull regime - expect Strategy B (Flow) to dominate; focus on long momentum
Red Tint: Trending Bear regime - expect Strategy B (Flow) shorts; focus on short momentum
Orange Tint: High Vol Range - expect Strategy A (Squeeze) or C (Memory); trade breakouts or patterns
Blue Tint: Low Vol Range - expect Strategy A (Squeeze); wait for compression release
Purple Tint: Transition regime - often unfavorable; system may stand aside; high uncertainty
Usage: Quick visual regime identification without reading dashboard
FLOW BANDS:
Upper Band: close + HFL × ATR × 1.5
Lower Band: close - HFL × ATR × 1.5
Green Fill: HFL positive (bullish flow); bands act as dynamic support/resistance in uptrend
Red Fill: HFL negative (bearish flow); bands act as dynamic resistance/support in downtrend
Usage:
• Bullish flow: Price bouncing off lower band = trend continuation; breaking below = possible reversal
• Bearish flow: Price rejecting upper band = trend continuation; breaking above = possible reversal
CONFIDENCE METER (Separate Pane):
Gold Line: Current signal confidence (0-100)
Dashed Line: Minimum confidence threshold
Interpretation:
• Line above threshold: Signal likely to fire if strength sufficient
• Line below threshold: Even if signal logic met, won't fire (insufficient confidence)
• Gradual rise: Signal building strength
• Sharp spike: Sudden conviction (check if sustainable)
Usage: Real-time signal probability; helps anticipate upcoming entries
PREDICTION ARC:
Dashed Line: Projects from current close to expected price 8 bars forward
Green Arc: Bullish memory prediction
Red Arc: Bearish memory prediction
Steep Arc: High conviction (strong expected move)
Flat Arc: Low conviction (weak/uncertain move)
Important: NOT a price target; this is a probability vector based on KNN outcomes; actual price may differ
Usage: Directional bias from pattern matching; confirms or contradicts flow signals
SIGNAL MARKERS:
▲ Green Triangle (below bar):
• Long signal confirmed on bar close
• Entry on next bar open
• Non-repainting (appears after bar closes)
▼ Red Triangle (above bar):
• Short signal confirmed on bar close
• Entry on next bar open
• Non-repainting
Size: Tiny (unobtrusive)
Text: "L" or "S" in marker
Usage: Historical signal record; alerts should fire on these; verify against dashboard status
DUAL HEATMAPS (If Enabled):
STM HEATMAP:
• X-axis: Pattern age (left = recent, right = older, typically 0-50 bars)
• Y-axis: Outcome direction (top = bearish outcomes, bottom = bullish outcomes)
• Color Intensity: Brightness = pattern count in that cell
• Color Hue: Green tint (bullish), Red tint (bearish), Gray (neutral)
Interpretation:
• Dense bottom-left: Many recent bullish patterns (bullish regime)
• Dense top-left: Many recent bearish patterns (bearish regime)
• Scattered: Mixed outcomes, ranging regime
• Empty areas: Few patterns (low data)
LTM HEATMAP:
• Similar layout but X-axis spans wider age range (0-500+ bars)
• Shows long-term pattern distribution
• Denser = more validated patterns
Comparison Usage:
• If STM and LTM heatmaps look similar: Current regime matches historical patterns (high agreement)
• If STM bottom-heavy but LTM top-heavy: Recent bullish activity contradicts historical bearish patterns (low agreement, transition signal)
PART 13: DEVELOPMENT STORY
The creation of the Lorentzian Harmonic Flow Adaptive ML system represents over six months of intensive research, mathematical exploration, and iterative refinement. What began as a theoretical investigation into applying special relativity to market time evolved into a complete adaptive learning framework.
THE CHALLENGE:
The fundamental problem was this: markets don't experience time uniformly, yet every indicator treats a 50-period calculation the same whether markets are exploding or sleeping. Traditional adaptive indicators adjust parameters based on volatility, but this is reactive—by the time you measure high volatility, the explosive move is over. What was needed was a framework that measured the market's intrinsic velocity relative to its own structural limits, then compressed time itself proportionally.
THE LORENTZIAN INSIGHT:
Einstein's special relativity provides exactly this framework through the Lorentz factor. When an object approaches the speed of light, time dilates—but from the object's reference frame, it experiences time compression. By treating price velocity as analogous to relativistic velocity and volatility structure as the "speed limit," we could calculate a gamma factor that compressed lookback periods during explosive moves.
The mathematics were straightforward in theory but devilishly complex in implementation. Pine Script has no native support for dynamically-sized arrays or recursive functions, forcing creative workarounds. The Lorentzian kernel smoothing required nested loops through historical bars, calculating kernel weights on the fly—a computational nightmare. Early versions crashed or produced bizarre artifacts (negative gamma values, infinite loops during volatility spikes).
Optimization took weeks. Limiting kernel lookback to 60 bars while still maintaining smoothing quality. Pre-calculating gamma once per bar and reusing it across all calculations. Caching intermediate results. The final implementation balances mathematical purity with computational reality.
THE MEMORY ARCHITECTURE:
With temporal compression working, the next challenge was pattern memory. Simple moving average systems have no memory—they forget yesterday's patterns immediately. But markets are non-stationary; what worked last month may not work today. The solution: dual-memory architecture inspired by cognitive neuroscience.
Short-Term Memory (STM) would capture tactical patterns—the hippocampus of the system. Fast encoding, fast decay, always current. Long-Term Memory (LTM) would store validated strategic patterns—the neocortex. Slow consolidation, persistent storage, regime-spanning wisdom.
The KNN implementation nearly broke me. Calculating Lorentzian distance across 6 dimensions for 500+ patterns per query, applying age decay, filtering by regime, finding K nearest neighbors without native sorting functions—all while maintaining sub-second execution. The breakthrough came from realizing we could use destructive sorting (marking found neighbors as "infinite distance") rather than maintaining separate data structures.
Pre-training was another beast. To populate memory with historical patterns, the system needed to scan hundreds of past bars, calculate forward outcomes, and insert patterns—all on chart load without timing out. The solution: cap at 200 bars, optimize loops, pre-calculate features. Now it works seamlessly.
THE REGIME DETECTION:
Five-regime classification emerged from empirical observation. Traditional trending/ranging dichotomy missed too much nuance. Markets have at least four distinct states: trending up, trending down, volatile range, quiet range—plus a chaotic transition state. Linear regression slope quantifies trend; volatility ratio quantifies expansion; combining them creates five natural clusters.
But classification is useless without regime-specific learning. That meant tracking 15 separate performance matrices (3 strategies × 5 regimes), computing Sharpe ratios and Calmar ratios for sparse data, implementing Bayesian-like strategy selection. The bootstrap mode logic alone took dozens of iterations—too strict and you never get data, too permissive and you blow up accounts during learning.
THE ADAPTIVE LAYER:
Parameter adaptation was conceptually elegant but practically treacherous. Each regime needed independent thresholds, quality gates, and multipliers that adapted based on outcomes. But naive gradient descent caused oscillations—win a few trades, lower threshold, take worse signals, lose trades, raise threshold, miss good signals. The solution: exponential smoothing via learning rate (α) and separate scoring for selection vs adaptation.
Shadow portfolios provided objective validation. By running virtual accounts for all strategies simultaneously, we could see which would have won even when not selected. This caught numerous bugs where selection logic was sound but execution was flawed, or vice versa.
THE DASHBOARD & VISUALIZATION:
A learning system is useless if users can't understand what it's doing. The dashboard went through five complete redesigns. Early versions were information dumps—too much data, no hierarchy, impossible to scan. The final version uses visual hierarchy (section headers, color coding, strategic whitespace) and progressive disclosure (show current regime first, then performance, then parameters).
The dual heatmaps were a late addition but proved invaluable for pattern visualization. Seeing STM cluster in one corner while LTM distributed broadly immediately signals regime novelty. Traders grasp this visually faster than reading disagreement percentages.
THE TESTING GAUNTLET:
Testing adaptive systems is uniquely challenging. Static backtest results mean nothing—the system should improve over time. Early "tests" showed abysmal performance because bootstrap periods were included. The breakthrough: measure pre-learning baseline vs post-learning performance. A system going from 48% win rate (first 50 trades) to 56% win rate (trades 100-200) is succeeding even if absolute performance seems modest.
Edge cases broke everything repeatedly. What happens when a regime never appears in historical data? When all strategies fail simultaneously? When memory fills with only bearish patterns during a bull run? Each required careful handling—bootstrap modes, forced diversification, quality gates.
THE DOCUMENTATION:
This isn't an indicator you throw on a chart with default settings and trade immediately. It's a learning system that requires understanding. The input tooltips alone contain over 10,000 words of guidance—market-specific recommendations, timeframe-specific settings, tradeoff explanations. Every parameter needed not just a description but a philosophical justification and practical tuning guide.
The code comments span 500+ lines explaining theory, implementation decisions, edge cases. Future maintainers (including myself in six months) need to understand not just what the code does but why certain approaches were chosen over alternatives.
WHAT ALMOST DIDN'T WORK:
The entire project nearly collapsed twice. First, when initial Lorentzian smoothing produced complete noise—hours of debugging revealed a simple indexing error where I was accessing instead of in the kernel loop. One character, entire system broken.
Second, when memory predictions showed zero correlation with outcomes. Turned out the KNN distance metric was dominated by the gamma dimension (values 1-10) drowning out normalized features (values -1 to 1). Solution: apply kernel transformation to all dimensions, not just final distance. Obvious in retrospect, maddening at the time.
THE PHILOSOPHY:
This system embodies a specific philosophy: markets are learnable but non-stationary. No single strategy works forever, but regime-specific patterns persist. Time isn't uniform, memory isn't perfect, prediction isn't possible—but probabilistic edges exist for those willing to track them rigorously.
It rejects the premise that indicators should give universal advice. Instead, it says: "In this regime, based on similar past states, Strategy B has a 58% win rate and 1.4 Sharpe. Strategy A has 45% and 0.2 Sharpe. I recommend B. But we're still in bootstrap for Strategy C, so I'm gathering data. Check back in 5 trades."
That humility—knowing what it knows and what it doesn't—is what makes it robust.
PART 14: PROFESSIONAL USAGE PROTOCOL
PHASE 1: DEPLOYMENT (Week 1-4)
Initial Setup:
1. Load indicator on primary trading chart with default settings
2. Verify historical pre-training enabled (should see ~200 patterns in STM/LTM on first load)
3. Enable all dashboard sections for maximum transparency
4. Set alerts but DO NOT trade real money
Observation Checklist:
• Dashboard Validation:
✓ Lorentzian Core shows reasonable gamma (1-5 range, not stuck at 1.0 or spiking to 10)
✓ HFL oscillates with price action (not flat or random)
✓ Regime classifications make intuitive sense
✓ Confidence scores vary appropriately
• Memory System:
✓ STM fills within first few hours/days of real-time bars
✓ LTM grows gradually (few patterns per day, quality-gated)
✓ Predictions show directional bias (not always 0.0)
✓ Agreement metric fluctuates with regime changes
• Bootstrap Tracking:
✓ Dashboard shows "🔥 BOOTSTRAP (X/10)" for each regime
✓ Trade counts increment on regime-specific signals
✓ Different regimes reach threshold at different rates
Paper Trading:
• Take EVERY signal (ignore unfavorable warnings during bootstrap)
• Log each trade: entry price, regime, selected strategy, outcome
• Calculate your actual P&L assuming proper risk management (1-2% risk per trade)
• Do NOT judge system performance yet—focus on understanding behavior
Troubleshooting:
• No signals for days:
- Check base_quality_threshold (try lowering to 50-55)
- Verify enable_regime_filter not blocking all regimes
- Confirm signal confidence threshold not too high (try 0.25)
• Signals every bar:
- Raise base_quality_threshold to 65-70
- Increase min_bars_between to 8-10
- Check if gamma spiking excessively (raise c_multiplier)
• Memory not filling:
- Confirm enable_memory = true
- Verify historical pre-training completed (check STM size after load)
- May need to wait 10 bars for first real-time update
PHASE 2: VALIDATION (Week 5-12)
Statistical Emergence:
By week 5-8, most regimes should exit bootstrap. Look for:
✓ Regime Performance Clarity:
- At least 2-3 strategies showing positive Sharpe in their favored regimes
- Clear separation (Strategy B strong in Trending, Strategy A strong in Low Vol Range, etc.)
- Win rates stabilizing around 50-60% for winning strategies
✓ Shadow Portfolio Divergence:
- Virtual portfolios showing clear winners ($10K → $11K+) and losers ($10K → $9K-)
- Profit factors >1.3 for top strategy
- System selection aligning with best shadow portfolio
✓ Parameter Adaptation:
- Thresholds varying per regime (not stuck at initial values)
- Quality gates adapting (some regimes higher, some lower)
- Flow multipliers showing regime-specific optimization
Validation Questions:
1. Do patterns make intuitive sense?
- Strategy B (Flow) dominating Trending Bull/Bear? ✓ Expected
- Strategy A (Squeeze) succeeding in Low Vol Range? ✓ Expected
- Strategy C (Memory) working in High Vol Range? ✓ Expected
- Random strategy winning everywhere? ✗ Problem
2. Is unfavorable filtering working?
- Regimes with negative Sharpe showing "⚠️ UNFAVORABLE"? ✓ System protecting capital
- Transition regime often unfavorable? ✓ Expected
- All regimes perpetually unfavorable? ✗ Settings too strict or asset unsuitable
3. Are memories agreeing appropriately?
- High agreement during stable regimes? ✓ Expected
- Low agreement during transitions? ✓ Expected (novel conditions)
- Perpetual conflict? ✗ Check memory sizes or decay rates
Fine-Tuning (If Needed):
Too Many Signals in Losing Regimes:
→ Increase learning_rate to 0.07-0.08 (faster adaptation)
→ Raise base_quality_threshold by 5-10 points
→ Enable regime filter if disabled
Missing Profitable Setups:
→ Lower base_quality_threshold by 5-10 points
→ Reduce min_confidence to 0.25-0.30
→ Check if bootstrap mode blocking trades (let it complete)
Excessive Parameter Swings:
→ Reduce learning_rate to 0.03-0.04
→ Increase min_regime_samples to 15-20 (more data before adaptation)
Memory Disagreement Too Frequent:
→ Increase LTM size to 768-1024 (broader pattern library)
→ Lower adaptive_quality_gate requirement (allow more patterns)
→ Increase K neighbors to 10-12 (smoother predictions)
PHASE 3: LIVE TRADING (Month 4+)
Pre-Launch Checklist:
1. ✓ At least 3 regimes show positive Sharpe (>0.8)
2. ✓ Top shadow portfolio shows >53% win rate and >1.3 profit factor
3. ✓ Parameters have stabilized (not changing more than 10% per month)
4. ✓ You understand every dashboard metric and can explain regime/strategy behavior
5. ✓ You have proper risk management plan independent of this system
Position Sizing:
Conservative (Recommended for Month 4-6):
• Risk per trade: 0.5-1.0% of account
• Max concurrent positions: 1-2
• Total exposure: 10-25% of intended full size
Moderate (Month 7-12):
• Risk per trade: 1.0-1.5% of account
• Max concurrent positions: 2-3
• Total exposure: 25-50% of intended size
Full Scale (Year 2+):
• Risk per trade: 1.5-2.0% of account
• Max concurrent positions: 3-5
• Total exposure: 100% (still following risk limits)
Entry Execution:
On Signal Confirmation:
1. Verify dashboard shows signal type (▲ LONG or ▼ SHORT)
2. Check regime mode (avoid if "⚠️ UNFAVORABLE" unless testing)
3. Note selected strategy (A/B/C) and its regime Sharpe
4. Verify memory agreement if Strategy C selected (want >60%)
Entry Method:
• Market entry: Next bar open after signal (for exact backtest replication)
• Limit entry: Slight improvement (2-3 ticks) if confident in direction
Stop Loss Placement:
• Strategy A (Squeeze): Beyond opposite band or recent swing point
• Strategy B (Flow): 1.5-2.0 ATR from entry against direction
• Strategy C (Memory): Based on predicted move magnitude (tighter if pred > 2%)
Exit Management:
System Exit Signals:
• Opposite signal fires: Immediate exit, potential reversal entry
• 20 bars no exit signal: System implies position stale, consider exiting
• Regime changes to unfavorable: Tighten stop, consider partial exit
Manual Exit Conditions:
• Stop loss hit: Take loss, log for validation (system expects some losses)
• Profit target hit: If using fixed targets (2-3R typical)
• Major news event: Flatten during high-impact news (system can't predict these)
Warning Signs (Exit Criteria):
🚨 Stop Trading If:
1. All regimes show negative Sharpe for 4+ weeks (market structure changed)
2. Your results >20% worse than shadow portfolios (execution problem)
3. Parameters hitting extremes (thresholds >85 or <35 across all regimes)
4. Memory agreement <30% for extended periods (unprecedented conditions)
5. Account drawdown >20% (risk management failure, system or otherwise)
⚠️ Reduce Size If:
1. Win rate drops 10%+ from peak (temporary regime shift)
2. Selected strategy underperforming another by >30% (selection lag)
3. Consecutive losses >5 (variance or problem, reduce until clarity)
4. Major market regime change (Fed policy shift, war, etc. - let system re-adapt)
PART 15: THEORETICAL IMPLICATIONS & LIMITATIONS
WHAT THIS SYSTEM REPRESENTS:
Contextual Bandits:
The regime-specific strategy selection implements a contextual multi-armed bandit problem. Each strategy is an "arm," each regime is a "context," and we select arms to maximize expected reward given context. This is reinforcement learning applied to trading.
Experience Replay:
The dual-memory architecture mirrors DeepMind's DQN breakthrough. STM = recent experience buffer; LTM = validated experience replay. This prevents catastrophic forgetting while enabling rapid adaptation—a key challenge in neural network training.
Meta-Learning:
The system learns how to learn. Parameter adaptation adjusts the system's own sensitivity and selectivity based on outcomes. This is "learning to learn"—optimizing the optimization process itself.
Non-Stationary Optimization:
Traditional backtesting assumes stationarity (past patterns persist). This system assumes non-stationarity and continuously adapts. The goal isn't finding "the best parameters" but tracking the moving optimum.
Regime-Conditional Policies:
Rather than a single strategy for all conditions, this implements regime-specific policies. This is contextual decision-making—environment state determines action selection.
FINAL WISDOM:
"The market is a complex adaptive system. To trade it successfully, one must also adapt. This indicator provides the framework—memory, learning, regime awareness—but wisdom comes from understanding when to trade, when to stand aside, and when to defer to conditions the system hasn't yet learned. The edge isn't in the algorithm alone; it's in the partnership between mathematical rigor and human judgment."
— Inspired by the intersection of Einstein's relativity, Kahneman's behavioral economics, and decades of quantitative trading research
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
SNP420_Five_to_Five_INDIFor consistent 9-5 traders.
Use for your traidingroutine.
Change colours and time for your strategy.
Peace and love! SNP420
FVG/IFVG Indicator (Blastoise's 85% Win-Rate Model)📈 Blastoise Trading Model — Liquidity + FVG + MSS
This indicator automates Blastoise's 85% Win-Rate Trading Strategy, built around high-probability intraday setups on NQ and ES using Draw on Liquidity (DOL), Market Structure Shifts (MSS), and Fair Value Gaps (FVG)
🔍 What It Does:
- Auto-Identifies All DOLs:
Marks Internal/External Highs & Lows, Asia High/Low, London High/Low, and News Data High/Low
- NY Session Logic (9:30 AM):
Activates only during the NY session to ensure volume and trend reliability
Waits for the first nearby DOL to get swept, then reads market reaction to generate a bias
- Automatic Bias Detection:
Example: If price takes out a DOL high and holds below = Bearish Bias
Example: If price takes out a DOL high and holds above = Bullish Bias into Next DOL
- Smart Entry Model with FVGs/IFVGs:
Once bias is set, the indicator scans all timeframes for valid FVG setups with the given bias
Once it finds the setup, it'll display the complete entry setup, including entry zone, stop loss, and price targets so you know EXACTLY when to get in
- Real-Time Setup Checklist:
Confirms DOL sweep, bias, volume, FVG/IFVG entry model, and MSS status.
Setup Rating Score (1–10) based on how many confirmations are present
- MSS Integration (Optional but Powerful):
Confirms Market Structure Shifts for reversals after DOL sweeps and updates the setup rating
Manee Algo: Trinity Levels Suite [Dashboard]MANEE ALGO: TRINITY LEVELS SUITE Institutional Grade Analysis • Unified Dashboard • Multi-Asset Capable
The Manee Algo Trinity Suite is a comprehensive, all-in-one technical analysis toolkit designed for professional Intraday and Swing traders on Nifty, BankNifty, and Stocks. This script consolidates three powerful institutional logic systems into a single, clean interface, replacing the need for multiple indicators.
💎 INCLUDED ALGORITHMS
This suite combines three distinct trading edges:
1. Manee Hub Logic (Volatility & Equilibrium)
CPP (Custom Pivot Points): Calculates dynamic support and resistance based on Daily, Weekly, or Monthly aggregate data.
Range Breakout (RB): Uses statistical offset values specific to Indian Indices (Nifty/BankNifty) to project breakout targets from the daily opening range.
Reference Pivots: Advanced geometry allowing back-testing or forward-testing from a specific user-defined reference date.
2. Trade All System (Dynamic Price Steps) A smart, price-action-based model that adapts automatically to the asset class.
Auto-Detection: Automatically switches logic between Index and Stocks.
Dynamic Step Calculation: For stocks, the distance between levels adjusts based on the stock price (e.g., a ₹2000 stock uses different spacing than a ₹4000 stock).
Levels: Generates H1/H2 (Resistance) and L1/L2 (Support) relative to the previous close.
3. 6 Stars Level (Momentum Breakout) A pure momentum strategy derived from the Previous Day's Range (PDR).
Logic: Uses PDH (High) and PDL (Low) to calculate a central Stop Loss (Midline).
Execution: Projects expansion targets (Target 1 & 2) for both Long and Short scenarios. Perfect for capturing morning opening momentum.
🚀 KEY FEATURES
🎛 Real-Time Dashboard: A non-intrusive table displays critical Entry, Stop Loss, and Target levels for all active tools in one corner of your screen.
✨ Zero Clutter: Toggle on-chart labels ON or OFF. You can hide the messy lines and trade purely using the clean Data Dashboard.
🛠 Modular Control: Enable or disable any of the three systems individually via settings. Only see what you need.
⚙️ SETTINGS GUIDE
Enable/Disable: Use the checkboxes to turn specific strategies on or off.
Dashboard: You can move the dashboard table to any corner of the screen (Top Right, Bottom Right, etc.).
Symbol Selection: For the "Trade All" system, ensure you select "Nifty", "BankNifty", or "Stocks" to get the correct calculation.
🔒 ACCESS & SUBSCRIPTION
This is an Invite-Only script. To request access or a trial, please send a private message or leave a comment below.
Disclaimer: This tool is for educational and analytical purposes only. Past performance does not guarantee future results. Trading involves substantial risk.
MTFX Daily RangeThe MTFX Daily Range plots the Previous Day’s High, Low, Close, and Midpoint directly onto your intraday chart, along with a full suite of fractal extensions above and below the range. All levels print live with price, giving you a real-time road map without lag or repainting.
🔹 Key Features
Core levels: PDH, PDL, PDC, Midpoint, Current Open.
Fractal extensions: ±0.25, ±0.75, ±1.00, ±1.25, ±1.50, ±2.00 — capturing sweeps, expansions, and exhaustion zones.
Customisable styles: Colours, line widths, and visibility can be adjusted.
Toggle control: Levels can be switched on/off to keep charts clean.
Alerts: Wick breaks and candle closes at PD levels for instant structural awareness.
🔹 Why Fractals Matter
Most PD scripts stop at the high and low. This one goes further:
Why Most Traders Struggle With Previous Day Levels
You've seen it happen: price approaches yesterday's high, you take a breakout trade, and it immediately reverses. Or you set support at previous day's low, only to watch price slice through it like butter.
The problem? Most traders only look at PDH and PDL. They're missing the fractal structure that reveals where price actually respects levels.
The Fractal Advantage:
Markets aren't random - they're fractal. The same patterns repeat across different scales. The MTFX Daily Range indicator maps these fractal relationships using the previous day's range as the base measurement.
Contextual precision: Know instantly if price is contained, probing liquidity, or breaking out.
Exit planning: Fractals act as natural TP zones.
🔹 Benefits of Combining Daily Range with MTFX Asia Session Indicator:
Layered conviction: Asia defines the session narrative, PD Range anchors the higher‑timeframe structure.
Sweep logic: Asia sweeps at PDH/PDL are far more meaningful.
Complete narrative: Asia gives timing, PD gives structure — together they keep you out of noise.
Like this indicator? Boost it and follow for updates! 🚀
Published by Mummytrades_FX.
Checklist Trade-Setup (TRAIVEND)
This tool professionalizes your trade execution and ensures maximum discipline in the market. It serves as a visual reassurance to minimize emotional errors and objectify the trading process.
Benefits for your trading:
Prevention of Overtrading & Revenge Trading:
You only trade when your criteria are met. No checkmarks mean no trade. This filter forces patience, protects your capital from impulsive decisions born of boredom or frustration, and ensures you only take valid setups.
Objectivity instead of Uncertainty:
Through clearly defined criteria (e.g., MSS, FVG, Liq-Sweep), you eliminate hesitation before entry. The decision is no longer based on feelings, but on facts. Once the checklist is confirmed, you have clear permission for execution.
Psychological Stability within the Trade:
In volatile phases, glancing at the checklist helps maintain calm. It visually reminds you that the entry was rule-compliant. This strengthens trust in the setup and prevents you from closing positions too early out of fear.
How it works:
This is a manual overlay tool designed for process optimization. Up to 10 individual criteria can be defined via the settings and validated using checkboxes. There is no automatic signaling; the tool serves strict adherence to one's own trading rules (Compliance).
Killzones boxThe indicator displays all trading sessions without any additional settings. It automatically adjusts the time from standard to daylight saving time.
Infinity 26📈 Infinity 26 – Long-Term Investment Signal Indicator
Infinity 26 is a long-term trend-based investment indicator designed to identify high-quality buy and exit points using weekly or monthly candles.
It filters out market noise and focuses only on strong, long-term momentum shifts—making it ideal for wealth creation and slow, steady portfolio growth.
🔹 Key Features
Buy Signals: Automatically highlights strong trend-reversal points where long-term investors can accumulate.
Exit Signals: Shows when the long-term trend weakens, helping protect gains and reduce major drawdowns.
Weekly & Monthly Optimized: Best results when used on 1-week or 1-month timeframe for long-term investing.
Clear Trend Structure: Helps you stay invested during major bull trends and avoid emotional short-term decisions.
Noise-Free: Designed for long-horizon investors—no overtrading, no frequent whipsaws.
🔹 Best For
Long-term investors
Swing-to-position traders
Wealth creation strategies
Portfolio-based investing
🔹 How It Helps You
✔ Avoid wrong entries
✔ Capture major uptrend moves
✔ Reduce risk with timely exits
✔ Build wealth with simple, rule-based signals
Session Lines (US & Europe, Anchored and Adaptive)A sleek indicator that marks the London (blue) and New York (red) trading sessions with perfectly aligned vertical lines both open and close times.
Lines automatically scale with your chart, adapt to any timeframe, and fade smoothly on higher intervals to keep your layout clean and professional.
111 Robin Levels [StoneFace - Testing]111 Robin Levels
Overview The 111 Robin Levels indicator is a precision trading tool designed to plot dynamic Fibonacci extension and retracement levels based on key trading session ranges. It automatically detects specific time windows (Asia, London, and key hourly candles) and projects significant reaction levels used in the "Robin" trading methodology.
Key Features
Multi-Session Support: Easily toggle between key trading windows:
Asia Session (20:00 - 00:00 NY)
London Session (02:30 - 04:00 NY)
3 AM Candle (03:00 - 04:00 NY)
6 AM Candle (06:00 - 07:00 NY)
9 AM Candle (09:00 - 10:00 NY)
Dynamic Fibonacci Levels:
1.111 Extensions: Automatically plots the +/- 1.111 expansion levels from the session range, often used to identify stop hunts or reversals.
Highlights the 0.37 and 0.55 levels with a customizable shaded background for clear visualization of internal reaction zones.
Mirrored Sets: Capable of generating multiple sets of extensions (e.g., 2.111, 3.111) based on user configuration for trending markets.
Smart Visualization:
Dynamic Extension: Lines for the current day extend dynamically (Current Bar + 3) for real-time visibility but cap at 17:00 NY to prevent chart clutter.
Historical Accuracy: Past session lines remain fixed at the 17:00 NY daily close.
Full Customization: Control line styles (Solid, Dotted, Dashed), widths, colors, and fill transparency to match your charting theme.
How It Works
Once a selected session completes, the indicator calculates the High and Low of that specific time period. It immediately projects the 1.111 expansion levels and the internal 0.37/0.55 zones. Users can adjust the "Set Visible Ranges" setting to project further expansions (Sets 2, 3, 4, etc.) for days with high volatility.
Settings
Session to Display: Select the specific session or candle time you wish to analyze.
Set Visible Ranges: Define how many upper and lower extension sets are displayed.
Style: Customize colors for the 1.111 levels and the 37/55 zones, adjust fill transparency, and select your preferred line style.
Static K-means Clustering | InvestorUnknownStatic K-Means Clustering is a machine-learning-driven market regime classifier designed for traders who want a data-driven structure instead of subjective indicators or manually drawn zones.
This script performs offline (static) K-means training on your chosen historical window. Using four engineered features:
RSI (Momentum)
CCI (Price deviation / Mean reversion)
CMF (Money flow / Strength)
MACD Histogram (Trend acceleration)
It groups past market conditions into K distinct clusters (regimes). After training, every new bar is assigned to the nearest cluster via Euclidean distance in 4-dimensional standardized feature space.
This allows you to create models like:
Regime-based long/short filters
Volatility phase detectors
Trend vs. chop separation
Mean-reversion vs. breakout classification
Volume-enhanced money-flow regime shifts
Full machine-learning trading systems based solely on regimes
Note:
This script is not a universal ML strategy out of the box.
The user must engineer the feature set to match their trading style and target market.
K-means is a tool, not a ready made system, this script provides the framework.
Core Idea
K-means clustering takes raw, unlabeled market observations and attempts to discover structure by grouping similar bars together.
// STEP 1 — DATA POINTS ON A COORDINATE PLANE
// We start with raw, unlabeled data scattered in 2D space (x/y).
// At this point, nothing is grouped—these are just observations.
// K-means will try to discover structure by grouping nearby points.
//
// y ↑
// |
// 12 | •
// | •
// 10 | •
// | •
// 8 | • •
// |
// 6 | •
// |
// 4 | •
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
//
//
// STEP 2 — RANDOMLY PLACE INITIAL CENTROIDS
// The algorithm begins by placing K centroids at random positions.
// These centroids act as the temporary “representatives” of clusters.
// Their starting positions heavily influence the first assignment step.
//
// y ↑
// |
// 12 | •
// | •
// 10 | • C2 ×
// | •
// 8 | • •
// |
// 6 | C1 × •
// |
// 4 | •
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
//
//
// STEP 3 — ASSIGN POINTS TO NEAREST CENTROID
// Each point is compared to all centroids.
// Using simple Euclidean distance, each point joins the cluster
// of the centroid it is closest to.
// This creates a temporary grouping of the data.
//
// (Coloring concept shown using labels)
//
// - Points closer to C1 → Cluster 1
// - Points closer to C2 → Cluster 2
//
// y ↑
// |
// 12 | 2
// | 1
// 10 | 1 C2 ×
// | 2
// 8 | 1 2
// |
// 6 | C1 × 2
// |
// 4 | 1
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
// (1 = assigned to Cluster 1, 2 = assigned to Cluster 2)
// At this stage, clusters are formed purely by distance.
Your chosen historical window becomes the static training dataset , and after fitting, the centroids never change again.
This makes the model:
Predictable
Repeatable
Consistent across backtests
Fast for live use (no recalculation of centroids every bar)
Static Training Window
You select a period with:
Training Start
Training End
Only bars inside this range are used to fit the K-means model. This window defines:
the market regime examples
the statistical distributions (means/std) for each feature
how the centroids will be positioned post-trainin
Bars before training = fully transparent
Training bars = gray
Post-training bars = full colored regimes
Feature Engineering (4D Input Vector)
Every bar during training becomes a 4-dimensional point:
This combination balances: momentum, volatility, mean-reversion, trend acceleration giving the algorithm a richer "market fingerprint" per bar.
Standardization
To prevent any feature from dominating due to scale differences (e.g., CMF near zero vs CCI ±200), all features are standardized:
standardize(value, mean, std) =>
(value - mean) / std
Centroid Initialization
Centroids start at diverse coordinates using various curves:
linear
sinusoidal
sign-preserving quadratic
tanh compression
init_centroids() =>
// Spread centroids across using different shapes per feature
for c = 0 to k_clusters - 1
frac = k_clusters == 1 ? 0.0 : c / (k_clusters - 1.0) // 0 → 1
v = frac * 2 - 1 // -1 → +1
array.set(cent_rsi, c, v) // linear
array.set(cent_cci, c, math.sin(v)) // sinusoidal
array.set(cent_cmf, c, v * v * (v < 0 ? -1 : 1)) // quadratic sign-preserving
array.set(cent_mac, c, tanh(v)) // compressed
This makes initial cluster spread “random” even though true randomness is hardly achieved in pinescript.
K-Means Iterative Refinement
The algorithm repeats these steps:
(A) Assignment Step, Each bar is assigned to the nearest centroid via Euclidean distance in 4D:
distance = sqrt(dx² + dy² + dz² + dw²)
(B) Update Step, Centroids update to the mean of points assigned to them. This repeats iterations times (configurable).
LIVE REGIME CLASSIFICATION
After training, each new bar is:
Standardized using the training mean/std
Compared to all centroids
Assigned to the nearest cluster
Bar color updates based on cluster
No re-training occurs. This ensures:
No lookahead bias
Clean historical testing
Stable regimes over time
CLUSTER BEHAVIOR & TRADING LOGIC
Clusters (0, 1, 2, 3…) hold no inherent meaning. The user defines what each cluster does.
Example of custom actions:
Cluster 0 → Cash
Cluster 1 → Long
Cluster 2 → Short
Cluster 3+ → Cash (noise regime)
This flexibility means:
One trader might have cluster 0 as consolidation.
Another might repurpose it as a breakout-loading zone.
A third might ignore 3 clusters entirely.
Example on ETHUSD
Important Note:
Any change of parameters or chart timeframe or ticker can cause the “order” of clusters to change
The script does NOT assume any cluster equals any actionable bias, user decides.
PERFORMANCE METRICS & ROC TABLE
The indicator computes average 1-bar ROC for each cluster in:
Training set
Test (live) set
This helps measure:
Cluster profitability consistency
Regime forward predictability
Whether a regime is noise, trend, or reversion-biased
EQUITY SIMULATION & FEES
Designed for close-to-close realistic backtesting.
Position = cluster of previous bar
Fees applied only on regime switches. Meaning:
Staying long → no fee
Switching long→short → fee applied
Switching any→cash → fee applied
Fee input is percentage, but script already converts internally.
Disclaimers
⚠️ This indicator uses machine-learning but does not predict the future. It classifies similarity to past regimes, nothing more.
⚠️ Backtest results are not indicative of future performance.
⚠️ Clusters have no inherent “bullish” or “bearish” meaning. You must interpret them based on your testing and your own feature engineering.
[CASH] Crypto And Stocks Helper (MultiPack w. Alerts)ATTENTION! I'm not a good scripter. I have just learned a little basics for this project, stolen code from other public scripts and modified it, and gotten help from AI LLM's.
If you want recognition from stolen code please tell me to give you the credit you deserve.
The script is not completely finished yet and contains alot of errors but my friends and family wants access so I made it public.
_________________________________________________________________________________
CASH has multiple indicators (a true all-in-one multipack), guides and alerts to help you make better trades/investments. It has:
- Bitcoin Bull Market Support Band
- Dollar Volume
- 5 SMA and 5 EMA
- HODL Trend (a.k.a SuperTrend) indicator
- RSI, Volume and Divergence indicators w. alerts
More to come as well, like Backburner and a POC line from Volume Profile.
Everything is fully customizable, appearance and off/on etc.
More information and explainations along with my guides you can find in settings under "Input" and "Style".
🔥 SMC Reversal Engine v3.5 – Clean FVG + DashboardSMC Reversal Engine v3.5 – Clean FVG + Dashboard
The SMC Reversal Engine is a precision-built Smart Money Concepts tool designed to help traders understand market structure the single most important foundation in reading price action. It reveals how institutions move liquidity, where structure shifts occur, and how Fair Value Gaps (FVGs) align with these changes to signal potential reversals or continuations.
Understanding How It Works
At its core, the script detects CHoCH (Change of Character) and BOS (Break of Structure)—the two key turning points in institutional order flow. A CHoCH shows that the market has reversed intent (for example, from bearish to bullish), while a BOS confirms a continuation of the current trend. Together, they form the backbone of structure-based trading.
To refine this logic, the engine uses fractal pivots clusters of candles that confirm swing highs and lows. Fractals filter out noise, identifying points where price truly changes direction. The script lets you set this sensitivity manually or automatically adapts it depending on the timeframe. Lower fractal sensitivity captures smaller intraday swings for scalpers, while higher sensitivity locks onto major swing structures for swing and position traders.
The dashboard gives you a real-time reading of the trend, the last high and low, and what the market is likely to do next—for example, “Expect HL” or “Wait for LH.” It even tracks the accuracy of these structure predictions over time, giving an educational feedback loop to help you learn price behavior.
Fair Value Gaps and Tap Entries
Fair Value Gaps (FVGs) mark moments when price moves too quickly, leaving inefficiencies that institutions often revisit. When price taps into an FVG, it often acts as a high-probability entry zone for reversals or continuations. The script automatically detects, extends, and deletes old FVGs, keeping only relevant zones visible for a clean chart.
Traders can enable markTapEntry to visually confirm when an FVG gets filled. This is a simple but powerful trigger that often aligns with CHoCH or BOS moments.
Recommended Settings for Different Traders
For Scalpers, use a lower HTF structure such as 1 minute or 5 minutes. Keep Auto Fractals on for faster reaction, and limit FVG zones to 2–3. This gives you a clean, real-time reflection of order flow.
For Intraday Traders, 15-minute to 1-hour structure gives the perfect balance between reactivity and stability. Fractal sensitivity around 3–5 captures the most actionable levels without excessive noise.
For Swing Traders, use 4-hour, 1-day, or even 3-day structure. The chart becomes smoother, showing higher-order CHoCH and BOS that define true institutional transitions. Combine this with EMA confirmation for higher conviction.
For Position or Macro Traders, select Weekly or Monthly structure. The dynamic label system expands automatically to keep more historical BOS/CHoCH points visible, allowing you to see long-term shifts clearly.
Educational Value
This indicator is built to teach traders how to see structure the way professionals and smart money do. You’ll learn to recognize how markets transition from one phase to another from accumulation to manipulation to expansion. Each CHoCH or BOS helps you decode where liquidity is being taken and where new intent begins.
The included SMC Quick Guide explains each structural cue right on your chart. Within days of using it, you’ll start noticing patterns that reveal how price really moves, instead of guessing based on indicators.
Settings and How to Use Them
Everything in the SMC Reversal Engine is designed to adapt to your trading style and help you read structure like a professional.
When you open the Inputs Panel, you’ll see sections like Fractal Settings, FVG Settings, Buy/Sell Confirmation, and Educational Tools.
Under Fractal Settings, you can choose the higher timeframe (HTF) that defines structure—from minutes to weeks. The Auto Fractal Sensitivity option automatically adjusts how tight or wide swing points are detected. Lower sensitivity captures short-term fluctuations (great for scalpers), while higher values filter noise and isolate major swing highs and lows (perfect for swing traders).
The Fair Value Gap (FVG) options manage imbalance zones—the footprints of institutional orders. You can show or hide these zones, extend them into the future, and control how long they remain before auto-deletion. The Mark Entry When FVG is Tapped option places a small label when price revisits the gap—a potential entry signal that aligns with smart money logic.
EMA Confirmation adds a layer of confluence. The script can automatically scale EMA lengths based on timeframe, or you can input your preferred values (for example, 9/21 for intraday, 50/200 for swing). Require EMA Crossover Confirmation helps filter false moves, keeping you trading only with aligned momentum.
The Educational section gives traders visual reinforcement. When enabled, you’ll see tags like HH (Higher High), HL (Higher Low), LH (Lower High), and LL (Lower Low). These show structure shifts in real time, helping you learn visually what market structure really means. The Cheat Sheet panel summarizes each term, always visible in the corner for quick reference.
Early Top Warnings use wick size and RSI divergence to signal when price may be overextended—a useful heads-up before potential CHoCH formations.
Finally, the Narrative and Accuracy System translates structure into simple English—messages like Trend Bullish → Wait for HL or BOS Bearish → Expect LL. Over time, you can monitor how accurate these expectations have been, training your pattern recognition and confidence.
Pro Tips for Getting the Most Out of the SMC Reversal Engine
1. Start on Higher Timeframes First: Begin on the 4H or Daily chart where structure is cleaner and signals have more weight. Then scale down for entries once you grasp directional intent.
2. Use FVGs for Context, Not Just Entries: Observe how price behaves around unfilled FVGs—they often act as magnets or barriers, offering insight into where liquidity lies.
3. Combine With HTF Bias: Always trade in the direction of your higher timeframe trend. A bullish weekly BOS means lower timeframes should ideally align bullishly for optimal setups.
4. Clean Charts = Clear Mind: Use Minimal Mode when focusing on price action, then toggle the educational tools back on to review structure for learning.
5. Don’t Chase Every CHoCH or BOS: Focus on significant breaks that align with broader context and liquidity sweeps, not minor fluctuations.
6. Accuracy Rate Is a Feedback Tool: Use the accuracy stat as a reflection of consistency—not a trade trigger.
7. Build Narrative Awareness: Read the on-chart narrative messages to reinforce structured thinking and stay disciplined.
8. Practice Replay Mode: Step through past structures to visually connect CHoCH, BOS, and FVG behavior. It’s one of the best ways to train pattern recognition.
Summary
* Detects CHoCH and BOS automatically with fractal precision
* Identifies and manages Fair Value Gaps (FVGs) in real time
* Displays a smart dashboard with accuracy tracking
* Adapts label visibility dynamically by timeframe
* Perfect for both learning and trading with institutional clarity
This tool isn’t about predicting the market—it’s about understanding it. Once you can read structure, everything else in trading becomes secondary.
MAGIC MA BANDSMagic MA Bands — Dynamic Trend Zones Instead of Lines
Magic MA Bands help traders visualize dynamic support and resistance zones rather than relying on a single moving average line. Instead of treating the MA as an exact reaction level, this tool creates a band or zone where price is statistically more likely to react, reverse, or continue trending.
🧠 How It Works
The script plots:
Upper Band (default: 50 EMA using High values)
Lower Band (default: 50 EMA using Low values)
Optional Midline MA (default: 200 SMA for long-term trend)
The area between the upper and lower bands becomes a trend cushion, helping traders identify:
Dynamic support/resistance zones
Trend strength and continuation probability
Ideal pullback entry regions
🎯 Trend Interpretation Guide
Use Case Recommended Setting
Short-Term Trend 20/21 EMA or SMA
Medium-Term Trend 50 EMA / SMA
Long-Term Trend 200 SMA / EMA (Midline Optional)
All parameters are fully customisable so the user can define their preferred structure based on their trading style, asset volatility, or timeframe.
✔️ Best For:
Trend traders
Swing trading
Pullback-based entries
Institutional-style zone analysis
Market Sentiment + S/R KPRThis script is having VWAP and moving average cross overs. and also support and resistence.
Stacked SpaghettiStacked Spaghetti - Stacked EMA Confirmation indicator (5, 9, 21) based on Tyler Goedtel's (TG Capital) Trading Model in conjunction with the Bollinger Bands. Creates a cleaner chart with easy to read colored dots when all 3 EMAs are stacked Bullish or Bearish. This creates a cleaner and easier to read "quick scan" as you change between time frames for bias. Dot colors are customizable.
𝗔𝗹𝗴𝗼𝗔𝘂𝗿𝗮 "AlgoAura is a technical analysis tool designed to assist traders in identifying potential market trends and managing risk. It combines trend identification, signal generation, and dynamic risk management into a single, customizable indicator.
🔹 Key Features:
• Trend Identification Algorithm: Utilizes a custom 'Algo Sniper' function to filter price data and highlight potential trend direction.
• Entry Signals: Plots non-repainting buy and sell signals on the chart to indicate potential entry points.
• Dynamic Stop-Loss & Take-Profit: Automatically calculates and plots stop-loss and take-profit levels for each signal. It supports both manual (ATR-based) and automatic settings.
• Customizable Info Table: Displays real-time data including current price, entry, stop-loss, take-profit, risk/reward ratio, and trend strength. All colors and parameters in the table are fully adjustable.
• Full Visual Customization: Users can easily change the colors of signals, lines, and table elements to match their charting preferences.
🔹 How it Works:
The indicator calculates a smoothed price range and applies a filter to reduce market noise. When the filtered price direction changes, a signal is generated. Stop-loss levels are calculated based on user-defined risk (ATR) or an automatic pip value. Take-profit levels are also user-defined or can be set to automatic random values.
🔹 Disclaimer:
This script is for educational and informational purposes only. It does not constitute investment advice. Past performance is not indicative of future results. I am not responsible for any financial losses incurred while using this script. Please be aware of the risks involved in trading and trade with caution.
CBS Strategy with Trailing Stop _ IK3-Candle High/Low Breakout Strategy – Clean, Powerful, Fully Customizable (Pine Script v6)
A simple yet effective momentum breakout strategy that triggers trades when price closes above the highest high or below the lowest low of the previous 3 completed candles.
Perfect for trending markets (stocks, forex, crypto, indices) on any timeframe.
Key Features:
• Pure price-action breakout logic (no repainting)
• Long & Short entries with visual triangle signals
• Built-in Stop Loss & Take Profit (fixed % or ATR-based)
• Optional Trailing Stop (percentage or ATR multiplier)
• All risk parameters fully adjustable from the settings panel
• Clean on-chart visualization of SL, TP, and active trailing stop levels
• Works on all instruments and timeframes
Default Settings (2:1 Reward/Risk):
• Stop Loss: 1.5%
• Take Profit: 3.0%
• Trailing Stop: 1.0% (optional)
How to Use:
1. Add to chart
2. Adjust risk settings to match your style (fixed % or ATR)
3. Enable/disable trailing stop as needed
4. Backtest and optimize per instrument/timeframe
Fully open-source • No external libraries • Pine Script v6
Great for swing trading, intraday breakouts, or as a base for further enhancements.
Happy trading!






















