FiniteStateMachine🟩  OVERVIEW 
A flexible framework for creating, testing and implementing a Finite State Machine (FSM) in your script. FSMs use rules to control how states change in response to events. 
This is the first Finite State Machine library on TradingView and it's quite a different way to think about your script's logic. Advantages of using this vs hardcoding all your logic include: 
 •  Explicit logic : You can see all rules easily side-by-side.
 •  Validation : Tables show your rules and validation results right on the chart.
 •  Dual approach : Simple matrix for straightforward transitions; map implementation for concurrent scenarios. You can combine them for complex needs.
 •  Type safety : Shows how to use enums for robustness while maintaining string compatibility.
 •  Real-world examples : Includes both conceptual (traffic lights) and practical (trading strategy) demonstrations.
 •  Priority control : Explicit control over which rules take precedence when multiple conditions are met.
 •  Wildcard system : Flexible pattern matching for states and events.
The library seems complex, but it's not really. Your conditions, events, and their potential interactions are complex. The FSM makes them all explicit, which is some work. However, like all "good" pain in life, this is front-loaded, and *saves* pain later, in the form of unintended interactions and bugs that are very hard to find and fix.
🟩  SIMPLE FSM (MATRIX-BASED) 
The simple FSM uses a matrix to define transition rules with the structure: state > event > state. We look up the current state, check if the event in that row matches, and if it does, output the resulting state.
Each row in the matrix defines one rule, and the first matching row, counting from the top down, is applied.
A limitation of this method is that you can supply only ONE event.
You can design layered rules using widlcards. Use an empty string "" or the special string "ANY" for any state or event wildcard.
The matrix FSM is foruse where you have clear, sequential state transitions triggered by single events. Think traffic lights, or any logic where only one thing can happen at a time.
The demo for this FSM is of traffic lights.
🟩  CONCURRENT FSM (MAP-BASED) 
The map FSM uses a more complex structure where each state is a key in the map, and its value is an array of event rules. Each rule maps a named condition to an output (event or next state).
This FSM can handle multiple conditions simultaneously. Rules added first have higher priority.
Adding more rules to existing states combines the entries in the map (if you use the supplied helper function) rather than overwriting them.
This FSM is for more complex scenarios where multiple conditions can be true simultaneously, and you need to control which takes precedence. Like trading strategies, or any system with concurrent conditions.
The demo for this FSM is a trading strategy.
🟩  HOW TO USE 
Pine Script libraries contain reusable code for importing into indicators. You do not need to copy any code out of here. Just import the library and call the function you want.
For example, for version 1 of this library, import it like this:
 
import SimpleCryptoLife/FiniteStateMachine/1
 
See the EXAMPLE USAGE sections within the library for examples of calling the functions.
For more information on libraries and incorporating them into your scripts, see the  Libraries  section of the Pine Script User Manual. 
🟩  TECHNICAL IMPLEMENTATION 
Both FSM implementations support wildcards using blank strings "" or the special string "ANY". Wildcards match in this priority order:
 • Exact state + exact event match
 • Exact state + empty event (event wildcard)  
 • Empty state + exact event (state wildcard)
 • Empty state + empty event (full wildcard)
When multiple rules match the same state + event combination, the FIRST rule encountered takes priority. In the matrix FSM, this means row order determines priority. In the map FSM, it's the order you add rules to each state.
The library uses user-defined types for the map FSM:
 •  o_eventRule : Maps a condition name to an output
 •  o_eventRuleWrapper : Wraps an array of rules (since maps can't contain arrays directly)
Everything uses strings for maximum library compatibility, though the examples show how to use enums for type safety by converting them to strings.
Unlike normal maps where adding a duplicate key overwrites the value, this library's `m_addRuleToEventMap()` method *combines* rules, making it intuitive to build rule sets without breaking them.
🟩  VALIDATION & ERROR HANDLING 
The library includes comprehensive validation functions that catch common FSM design errors:
 Error detection: 
 • Empty next states
 • Invalid states not in the states array  
 • Duplicate rules
 • Conflicting transitions
 • Unreachable states (no entry/exit rules)
 Warning detection: 
 • Redundant wildcards
 • Empty states/events (potential unintended wildcards)
 • Duplicate conditions within states
You can display validation results in tables on the chart, with tooltips providing detailed explanations. The helper functions to display the tables are exported so you can call them from your own script.
🟩  PRACTICAL EXAMPLES 
The library includes four comprehensive demos:
 Traffic Light Demo (Simple FSM) : Uses the matrix FSM to cycle through traffic light states (red → red+amber → green → amber → red) with timer events. Includes pseudo-random "break" events and repair logic to demonstrate wildcards and priority handling.
 Trading Strategy Demo (Concurrent FSM) : Implements a realistic long-only trading strategy using BOTH FSM types:
 • Map FSM converts multiple technical conditions (EMA crosses, gaps, fractals, RSI) into prioritised events
 • Matrix FSM handles state transitions (idle → setup → entry → position → exit → re-entry)
 • Includes position management, stop losses, and re-entry logic
 Error Demonstrations : Both FSM types include error demos with intentionally malformed rules to showcase the validation system's capabilities.
🟩  BRING ON THE FUNCTIONS 
 f_printFSMMatrix(_mat_rules, _a_states, _tablePosition) 
  Prints a table of states and rules to the specified position on the chart. Works only with the matrix-based FSM.
  Parameters:
     _mat_rules (matrix) 
     _a_states (array) 
     _tablePosition (simple string) 
  Returns: The table of states and rules.
 method m_loadMatrixRulesFromText(_mat_rules, _rulesText) 
  Loads rules into a rules matrix from a multiline string where each line is of the form "current state | event | next state" (ignores empty lines and trims whitespace).
This is the most human-readable way to define rules because it's a visually aligned, table-like format.
  Namespace types: matrix
  Parameters:
     _mat_rules (matrix) 
     _rulesText (string) 
  Returns: No explicit return. The matrix is modified as a side-effect.
 method m_addRuleToMatrix(_mat_rules, _currentState, _event, _nextState) 
  Adds a single rule to the rules matrix. This can also be quite readble if you use short variable names and careful spacing.
  Namespace types: matrix
  Parameters:
     _mat_rules (matrix) 
     _currentState (string) 
     _event (string) 
     _nextState (string) 
  Returns: No explicit return. The matrix is modified as a side-effect.
 method m_validateRulesMatrix(_mat_rules, _a_states, _showTable, _tablePosition) 
  Validates a rules matrix and a states array to check that they are well formed. Works only with the matrix-based FSM.
Checks: matrix has exactly 3 columns; no empty next states; all states defined in array; no duplicate states; no duplicate rules; all states have entry/exit rules; no conflicting transitions; no redundant wildcards. To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the rules and states are ready.
  Namespace types: matrix
  Parameters:
     _mat_rules (matrix) 
     _a_states (array) 
     _showTable (bool) 
     _tablePosition (simple string) 
  Returns: `true` if the rules and states are valid; `false` if errors or warnings exist.
 method m_getStateFromMatrix(_mat_rules, _currentState, _event, _strictInput, _strictTransitions) 
  Returns the next state based on the current state and event, or `na` if no matching transition is found. Empty (not na) entries are treated as wildcards if `strictInput` is false.
Priority: exact match > event wildcard > state wildcard > full wildcard.
  Namespace types: matrix
  Parameters:
     _mat_rules (matrix) 
     _currentState (string) 
     _event (string) 
     _strictInput (bool) 
     _strictTransitions (bool) 
  Returns: The next state or `na`.
 method m_addRuleToEventMap(_map_eventRules, _state, _condName, _output) 
  Adds a single event rule to the event rules map. If the state key already exists, appends the new rule to the existing array (if different). If the state key doesn't exist, creates a new entry.
  Namespace types: map
  Parameters:
     _map_eventRules (map) 
     _state (string) 
     _condName (string) 
     _output (string) 
  Returns: No explicit return. The map is modified as a side-effect.
 method m_addEventRulesToMapFromText(_map_eventRules, _configText) 
  Loads event rules from a multiline text string into a map structure.
Format: "state | condName > output | condName > output | ..." . Pairs are ordered by priority. You can have multiple rules on the same line for one state.
Supports wildcards: Use an empty string ("") or the special string "ANY" for state or condName to create wildcard rules.
Examples: " | condName > output" (state wildcard), "state |  > output" (condition wildcard), " |  > output" (full wildcard).
Splits lines by \n, extracts state as key, creates/appends to array with new o_eventRule(condName, output).
Call once, e.g., on barstate.isfirst for best performance.
  Namespace types: map
  Parameters:
     _map_eventRules (map) 
     _configText (string) 
  Returns: No explicit return. The map is modified as a side-effect.
 f_printFSMMap(_map_eventRules, _a_states, _tablePosition) 
  Prints a table of map-based event rules to the specified position on the chart.
  Parameters:
     _map_eventRules (map) 
     _a_states (array) 
     _tablePosition (simple string) 
  Returns: The table of map-based event rules.
 method m_validateEventRulesMap(_map_eventRules, _a_states, _a_validEvents, _showTable, _tablePosition) 
  Validates an event rules map to check that it's well formed.
Checks: map is not empty; wrappers contain non-empty arrays; no duplicate condition names per state; no empty fields in o_eventRule objects; optionally validates outputs against matrix events.
NOTE: Both "" and "ANY" are treated identically as wildcards for both states and conditions.
To avoid slowing down the script unnecessarily, call this method once (perhaps using `barstate.isfirst`), when the map is ready.
  Namespace types: map
  Parameters:
     _map_eventRules (map) 
     _a_states (array) 
     _a_validEvents (array) 
     _showTable (bool) 
     _tablePosition (simple string) 
  Returns: `true` if the event rules map is valid; `false` if errors or warnings exist.
 method m_getEventFromConditionsMap(_currentState, _a_activeConditions, _map_eventRules) 
  Returns a single event or state string based on the current state and active conditions.
Uses a map of event rules where rules are pre-sorted by implicit priority via load order.
Supports wildcards using empty string ("") or "ANY" for flexible rule matching.
Priority: exact match > condition wildcard > state wildcard > full wildcard.
  Namespace types: series string, simple string, input string, const string
  Parameters:
     _currentState (string) 
     _a_activeConditions (array) 
     _map_eventRules (map) 
  Returns: The output string (event or state) for the first matching condition, or na if no match found.
 o_eventRule 
  o_eventRule defines a condition-to-output mapping for the concurrent FSM.
  Fields:
     condName (series string) : The name of the condition to check.
     output (series string) : The output (event or state) when the condition is true.
 o_eventRuleWrapper 
  o_eventRuleWrapper wraps an array of o_eventRule for use as map values (maps cannot contain collections directly).
  Fields:
     a_rules (array) : Array of o_eventRule objects for a specific state.
Cari dalam skrip untuk "entry"
TURT Donchian Ladder v3.13How to trade TURT+ with the v3.13 script
1) Pick the system & arm the entry
	•	In the script, choose System = S1 (20D) or S2 (55D).
The HUD always shows both rails for reference, but the ladder (Entry/+Adds) uses the system you pick.
	•	Your Entry is shown as Pivot + 0.1×N (rounded).
	•	Place a stop-limit “parent” order at that Entry price. (Classic Turtle uses an entry stop; I suggest a tight limit offset so you don’t chase a blow-through.)
	•	Initial stop = N2 = Entry − 2×N (rounded). Put that in immediately.
If you like only confirming on a bar close, leave confirmClose = true and place the parent after the close that breaks out. If you want intrabar fills, set confirmClose = false and keep the stop-limit active intraday.
2) Size it the way you planned
	•	Set acctEquity / riskCapPct / posCapUSD / entryFrac / entryRiskFrac / sizingMode.
	•	HUD gives Rec Entry Qty (when flat) and, once in, it shows:
	•	Next Rung (price)
	•	Suggested AddShares (honors RiskCap & PosCap)
	•	Proj Stop if Add (ratcheted N2)
	•	A limiter note (RiskCap or PosCap) if you’re constrained.
3) After entry fills, stage the ADDs (only at fixed +N steps)
	•	Adds are NOT “every Donchian break.” You add only at:
	•	Add-1 = Entry + 0.5×N
	•	Add-2 = Entry + 1.0×N
	•	Add-3 = Entry + 1.5×N (optional)
	•	Use the HUD’s Suggested AddShares for each rung (it respects your RiskCap/PosCap).
	•	Place stop-limit orders for each add (either immediately as a contingent OTO chain that arms only after Entry fills, or you arm each add when price approaches—your choice).
	•	On each add fill, ratchet the catastrophic stop for the entire position to Last-Add − 2×N (the script and HUD show Proj Stop if Add so you know where it will land). Never move it lower.
Pro tip: If your broker supports OTO/OTOCO:
	•	OTO parent = Entry stop-limit.
	•	On fill, fire an OCO with the N2 stop (no target), and also stage child stop-limits for Add-1 / Add-2 / Add-3 with the correct sizes. If your broker can’t chain that deep, just use the script’s alerts (Entry/Add-1/Add-2/Add-3/Exits) to place/adjust orders quickly.
4) Exits (two layers)
	•	Catastrophic (always on): the N2 stop you’re ratcheting (Last-Add − 2×N).
	•	Trend exits (runner):
	•	S1: 10-low close (HUD shows it).
	•	S2: 20-low close (HUD shows it).
	•	Profit-taking (optional): sell ~50% at +2.5R to +3R vs current N2; let the runner trail with 10-low/20-low. You can keep N2 as a hard backstop.
5) Should you pre-set everything or buy live?
Both work; pick the style that fits you:
Preset (Turtle-pure, rules-based)
	•	✅ You won’t miss the breakout; minimal discretion.
	•	✅ Broker handles fills even if you’re away.
	•	⚠️ You may get the occasional intraday “poke” (use confirmClose + place after close if you want fewer).
Buy on break manually
	•	✅ Lets you check tape/volume or any extra gates before clicking.
	•	⚠️ Higher chance of slippage or of simply missing the trigger.
A nice hybrid: place the Entry order, then arm Add-1/2/3 when price is nearing each rung and the HUD shows Suggested AddShares > 0 (green risk read).
⸻
6) Quick checklist per trade
	1.	System: S1 or S2?
	2.	Levels: Entry / Add-1 / Add-2 / Add-3 / 10-low / 20-low / N2 (rounded).
	3.	Sizing: confirm RiskCap/PosCap; HUD shows Suggested AddShares and limiter.
	4.	Orders:
	•	Parent Entry stop-limit.
	•	N2 stop (rounded).
	•	Stage adds (stop-limits) with sizes from HUD.
	5.	On fill: ratchet stop to Last-Add − 2×N; adjust remaining adds and sizes.
⸻
7) Example with your MU position (pattern)
	•	You’re already in: set entryQty and entryPman in the inputs to match your fill.
	•	HUD now focuses on Next Rung, Suggested AddShares, and Proj Stop if Add.
	•	If Suggested AddShares = 0 and limiter says RiskCap or PosCap, you’ll still see the next rung price and Proj Stop if Add so you can decide whether to override.
⸻
Bottom line
	•	Entry: buy the Donchian breakout + 0.1N with a stop-limit (Turtle style).
	•	Adds: only at +0.5N steps, sized by HUD; not on every future Donchian break.
	•	Stops: keep (and ratchet) the N2 catastrophic; trail runner on 10-low / 20-low.
If you want, tell me your broker/platform and I’ll map this to exact order ticket types (stop-limit/OTO/OCO) and a tiny checklist you can keep next to your screen.
Position Size CalculatorPosition Size Calculator 
This open-source Pine Script® indicator helps traders manage risk by calculating position size, margin, and risk/reward based on account size, leverage, entry, stop-loss, and take-profit. It features a customizable table and optional chart lines/labels for clear trade planning across stocks, forex, crypto, and futures.
 What It Does 
- Position Size: Computes units to trade based on risk percentage and stop-loss distance, capped by leverage.
- Margin: Calculates initial margin in base currency and USD, with account size percentage.
- Risk/Reward: Shows risk-reward ratio, percentage price movements, and USD gains/losses.
- Visualization: Displays results in a table and optional chart lines/labels with customizable styles.
 How It Works 
- Precision: Adjusts price formatting using syminfo.mintick for accuracy across assets.
- Calculations: Position size = accountSize * (riskPercent / 100) / |entry - stoploss|, capped by accountSize * leverage / entry. Margin = positionSize / leverage. Risk-reward = |takeprofit - entry| / |stoploss - entry|.
- Display: Table shows metrics; optional lines/labels plot entry, stop-loss, and take-profit with percentage and USD details.
 How to Use 
- Set Inputs:
1- Account Size (USD): Your capital (e.g., 1000).
2- % Risk per Trade: Risk tolerance (e.g., 1%).
3- Leverage: Broker leverage (e.g., 1x, 10x).
4- Entry, Stop Loss, Take Profit: Trade prices.
5- Show Lines and Labels: Enable chart overlays.
- Customize: Adjust table position, colors, and line styles (Solid, Dashed, Dotted).
- View Results: Table shows position size, margin, and risk/reward. Chart lines/labels (if enabled) display prices, percentages, and USD outcomes.
- Apply: Use metrics for trade execution; modify code for custom features.
Notes
- Ensure valid inputs (entry ≠ stop-loss, both positive) to avoid “N/A”.
- Open-source: Inspect or extend the code for your needs.
- Contact the author via TradingView for feedback.
HawkEye EMA Cloud
# HawkEye EMA Cloud - Enhanced Multi-Timeframe EMA Analysis
## Overview
The HawkEye EMA Cloud is an advanced technical analysis indicator that visualizes multiple Exponential Moving Average (EMA) relationships through dynamic color-coded cloud formations. This enhanced version builds upon the original Ripster EMA Clouds concept with full customization capabilities.
## Credits
**Original Author:** Ripster47 (Ripster EMA Clouds)  
**Enhanced Version:** HawkEye EMA Cloud with advanced customization features
## Key Features
### 🎨 **Full Color Customization**
- Individual bullish and bearish colors for each of the 5 EMA clouds
- Customizable rising and falling colors for EMA lines
- Adjustable opacity levels (0-100%) for each cloud independently
### 📊 **Multi-Layer EMA Analysis**
- **5 Configurable EMA Cloud Pairs:**
  - Cloud 1: 8/9 EMAs (default)
  - Cloud 2: 5/12 EMAs (default)
  - Cloud 3: 34/50 EMAs (default)
  - Cloud 4: 72/89 EMAs (default)
  - Cloud 5: 180/200 EMAs (default)
### ⚙️ **Advanced Customization Options**
- Toggle individual clouds on/off
- Adjustable EMA periods for all timeframes
- Optional EMA line display with color coding
- Leading period offset for cloud projection
- Choice between EMA and SMA calculations
- Configurable source data (HL2, Close, Open, etc.)
## How It Works
### Cloud Formation
Each cloud is formed by the area between two EMAs of different periods. The cloud color dynamically changes based on:
- **Bullish (Green/Custom):** When the shorter EMA is above the longer EMA
- **Bearish (Red/Custom):** When the shorter EMA is below the longer EMA
### Multiple Timeframe Analysis
The indicator provides a comprehensive view of trend strength across multiple timeframes:
- **Short-term:** Clouds 1-2 (faster EMAs)
- **Medium-term:** Cloud 3 (intermediate EMAs)  
- **Long-term:** Clouds 4-5 (slower EMAs)
## Trading Applications
### Trend Identification
- **Strong Uptrend:** Multiple clouds stacked bullishly with price above
- **Strong Downtrend:** Multiple clouds stacked bearishly with price below
- **Consolidation:** Mixed cloud colors indicating sideways movement
### Entry Signals
- **Bullish Entry:** Price breaking above bearish clouds turning bullish
- **Bearish Entry:** Price breaking below bullish clouds turning bearish
- **Confluence:** Multiple cloud confirmations strengthen signal reliability
### Support/Resistance Levels
- Cloud boundaries often act as dynamic support and resistance
- Thicker clouds (higher opacity) may provide stronger S/R levels
- Multiple cloud intersections create significant price levels
## Customization Guide
### Color Schemes
Create your own visual style by customizing:
1. **Bullish/Bearish colors** for each cloud pair
2. **Rising/Falling colors** for EMA lines
3. **Opacity levels** to layer clouds effectively
### Recommended Settings
- **Day Trading:** Focus on Clouds 1-2 with higher opacity
- **Swing Trading:** Use Clouds 1-3 with moderate opacity  
- **Position Trading:** Emphasize Clouds 3-5 with lower opacity
## Technical Specifications
- **Version:** Pine Script v6
- **Type:** Overlay indicator
- **Calculations:** Real-time EMA computations
- **Performance:** Optimized for all timeframes
- **Alerts:** Configurable long/short alerts available
## Risk Disclaimer
This indicator is for educational and informational purposes only. Always combine with proper risk management and additional analysis before making trading decisions. Past performance does not guarantee future results.
---
*Enhanced and customized version of the original Ripster EMA Clouds by Ripster47. This modification adds comprehensive color customization and enhanced user control while preserving the core analytical framework.*
AltCoin & MemeCoin Index Correlation [Eddie_Bitcoin]🧠 Philosophy of the Strategy 
The AltCoin & MemeCoin Index Correlation Strategy by Eddie_Bitcoin is a carefully engineered trend-following system built specifically for the highly volatile and sentiment-driven world of altcoins and memecoins.
This strategy recognizes that crypto markets—especially niche sectors like memecoins—are not only influenced by individual price action but also by the relative strength or weakness of their broader sector. Hence, it attempts to improve the reliability of trading signals by requiring alignment between a specific coin’s trend and its sector-wide index trend.
Rather than treating each crypto asset in isolation, this strategy dynamically incorporates real-time dominance metrics from custom indices (OTHERS.D and MEME.D) and combines them with local price action through dual exponential moving average (EMA) crossovers. Only when both the asset and its sector are moving in the same direction does it allow for trade entries—making it a confluence-based system rather than a single-signal strategy.
It supports risk-aware capital allocation, partial exits, configurable stop loss and take profit levels, and a scalable equity-compounding model.
 ✅ Why did I choose OTHERS.D and MEME.D as reference indices? 
I selected OTHERS.D and MEME.D because they offer a sector-focused view of crypto market dynamics, especially relevant when trading altcoins and memecoins.
🔹 OTHERS.D tracks the market dominance of all cryptocurrencies outside the top 10 by market cap.
This excludes not only BTC and ETH, but also major stablecoins like USDT and USDC, making it a cleaner indicator of risk appetite across true altcoins.
🔹 This is particularly useful for detecting "Altcoin Season"—periods where capital rotates away from Bitcoin and flows into smaller-cap coins.
A rising OTHERS.D often signals the start of broader altcoin rallies.
🔹 MEME.D, on the other hand, captures the speculative behavior of memecoin segments, which are often driven by retail hype and social media activity.
It's perfect for timing momentum shifts in high-risk, high-reward tokens.
By using these indices, the strategy aligns entries with broader sector trends, filtering out noise and increasing the probability of catching true directional moves, especially in phases of capital rotation and altcoin risk-on behavior.
 📐 How It Works — Core Logic and Execution Model 
At its heart, this strategy employs dual EMA crossover detection—one pair for the asset being traded and one pair for the selected market index.
A trade is only executed when both EMA crossovers agree on the direction. For example:
Long Entry: Coin's fast EMA > slow EMA and Index's fast EMA > slow EMA
Short Entry: Coin's fast EMA < slow EMA and Index's fast EMA < slow EMA
You can disable the index filter and trade solely based on the asset’s trend just to make a comparison and see if improves a classic EMA crossover strategy.
 Additionally, the strategy includes: 
- Adaptive position sizing, based on fixed capital or current equity (compound mode)
- Take Profit and Stop Loss in percentage terms
- Smart partial exits when trend momentum fades
- Date filtering for precise backtesting over specific timeframes
- Real-time performance stats, equity tracking, and visual cues on chart
 ⚙️ Parameters & Customization 
🔁 EMA Settings
Each EMA pair is customizable:
Coin Fast EMA: Default = 47
Coin Slow EMA: Default = 50
Index Fast EMA: Default = 47
Index Slow EMA: Default = 50
These control the sensitivity of the trend detection. A wider spread gives smoother, slower entries; a narrower spread makes it more responsive.
🧭 Index Reference
The correlation mechanism uses CryptoCap sector dominance indexes:
OTHERS.D: Dominance of all coins EXCLUDING Top 10 ones 
MEME.D: Dominance of all Meme coins 
These are dynamically calculated using:
OTHERS_D = OTHERS_cap / TOTAL_cap * 100
MEME_D = MEME_cap / TOTAL_cap * 100
You can select:
Reference Index: OTHERS.D or MEME.D
Or disable the index reference completely (Don't Use Index Reference)
💰 Position Sizing & Risk Management
Two capital allocation models are supported:
- Fixed % of initial capital (default)
- Compound profits, which scales positions as equity grows
Settings:
- Compound profits?: true/false
- % of equity: Between 1% and 200% (default = 10%)
This is critical for users who want to balance growth with risk.
🎯 Take Profit / Stop Loss
Customizable thresholds determine automatic exits:
- TakeProfit: Default = 99999 (disabled)
- StopLoss: Default = 5 (%)
These exits are percentage-based and operate off the entry price vs. current close.
📉 Trend Weakening Exit (Scale Out)
If the position is in profit but the trend weakens (e.g., EMA color signals trend loss), the strategy can partially close a configurable portion of the position:
- Scale Position on Weak Trend?: true/false
- Scaled Percentage: % to close (default = 65%)
This feature is useful for preserving profits without exiting completely.
📆 Date Filter
Useful for segmenting performance over specific timeframes (e.g., bull vs bear markets):
- Filter Date Range of Backtest: ON/OFF
- Start Date and End Date: Custom time range
OTHER PARAMETERS EXPLANATION (Strategy "Properties" Tab):
- Initial Capital is set to 100 USD
- Commission is set to 0.055% (The ones I have on Bybit)
- Slippage is set to 3 ticks 
- Margin (short and long) are set to 0.001% to avoid "overspending" your initial capital allocation
 📊 Visual Feedback and Debug Tools 
📈 EMA Trend Visualization
The slow EMA line is dynamically color-coded to visually display the alignment between the asset trend and the index trend:
Lime: Coin and index both bullish
Teal: Only coin bullish
Maroon: Only index bullish
Red: Both bearish
This allows for immediate visual confirmation of current trend strength.
💬 Real-Time PnL Labels
When a trade closes, a label shows:
 Previous trade return in % (first value is the effective PL)
Green background for profit, Red for losses.
 📑 Summary Table Overlay 
This table appears in a corner of the chart (user-defined) and shows live performance data including:
Trade direction (yellow long, purple short)
Emojis: 💚 for current profit, 😡 for current loss
Total number of trades
Win rate
Max drawdown
Duration in days
Current trade profit/loss (absolute and %)
Cumulative PnL (absolute and %)
APR (Annualized Percentage Return)
Each metric is color-coded:
Green for strong results
Yellow/orange for average
Red/maroon for poor performance
You can select where this appears:
Top Left
Top Right
Bottom Left
Bottom Right (default)
📚 Interpretation of Key Metrics
Equity Multiplier: How many times initial capital has grown (e.g., “1.75x”)
Net Profit: Total gains including open positions
Max Drawdown: Largest peak-to-valley drop in strategy equity
APR: Annualized return calculated based on equity growth and days elapsed
Win Rate: % of profitable trades
PnL %: Percentage profit on the most recent trade
 🧠 Advanced Logic & Safety Features 
🛑 “Don’t Re-Enter” Filter
If a trade is closed due to StopLoss without a confirmed reversal, the strategy avoids re-entering in that same direction until conditions improve. This prevents false reversals and repetitive losses in sideways markets.
🧷 Equity Protection
No new trades are initiated if equity falls below initial_capital / 30. This avoids overleveraging or continuing to trade when capital preservation is critical.
 Keep in mind that past results in no way guarantee future performance. 
Eddie Bitcoin
Pasrsifal.RegressionTrendStateSummary 
The Parsifal.Regression.Trend.State Indicator analyzes the leading coefficients of linear and quadratic regressions of price (against time). It also considers their first- and second-order changes. These features are aggregated into a Trend-State background, shown as a gradient color. In addition, the indicator generates fast and slow signals that can be used as potential entry- or exit triggers.
This tool is designed for advanced trend-following strategies, leveraging information from multiple trendline features.
 Background 
Trendlines provide insight into the state of a trend or the “trendiness” of a price process. While moving averages or pivot-based lines can serve as envelopes and breakout levels, they are often too lagging for swing traders, who need tools that adapt more closely to price swings, ideally using trendlines, around which the price process swings continuously.
Regression lines address this by cutting directly through the data, making them a natural anchor for observing how price winds around a central trendline within a chosen lookback period.
 Regression Trendlines  
•	 Linear Regression: 
o	Minimizes distance to all closing values over the lookback period.
o	The slope represents the short-term linear trend.
o	The change of slope indicates trend acceleration or deceleration.
o	Linear regression lags during phases of rapid market shifts.
•	 Quadratic Regression: 
o	Fits a second-degree polynomial to minimize deviation from closing prices.
o	The convexity term (leading coefficient) reflects curvature:
	Positive convexity → accelerating uptrend or fading downtrend.
	Negative convexity → accelerating downtrend or fading uptrend.
o	The change of convexity detects early shifts in momentum and often reacts faster than slope features.
 Features Extracted 
The indicator evaluates six features:
•	 Linear features:  slope, first derivative of slope, second derivative of slope.
•	 Quadratic features:  convexity term, first derivative of the convexity term, second derivative of the convexity term.
•	 Linear features:  capture broad, background trend behavior.
•	 Quadratic features:  detect deviations, accelerations, and smaller-scale dynamics.
Quadratic terms generally react first to market changes, while linear terms provide stability and context.
 Dynamics of Market Moves as seen by linear and quadratic regressions 
•	 At the start of a rapid move: 
The change of convexity reacts first, capturing the shift in dynamics before other features. The convexity term then follows, while linear slope features lag further behind. Because convexity measures deviation from linearity, it reflects accelerating momentum more effectively than slope.
•	 At the end of a rapid move: 
Again, the change of convexity responds first to fading momentum, signaling the transition from above-linear to below-linear dynamics. Even while a strong trend persists, the change of convexity may flip sign early, offering a warning of weakening strength. The convexity term itself adjusts more slowly but may still turn before the price process does. Linear features lag the most, typically only flipping after price has already reversed, thereby smoothing out the rapid, more sensitive reactions of quadratic terms.
________________________________________
 Parsifal Regression.Trend.State Method 
 1.	Feature Mapping: 
Each feature is mapped to a range between -1 and 1, preserving zero-crossings (critical for sign interpretation).
 2.	Aggregation: 
A heuristic linear combination*) produces a background information value, visualized as a gradient color scale:
o	Deep green → strong positive trend.
o	Deep red → strong negative trend.
o	Yellow → neutral or transitional states.
 3.	Signals:  
o	 Fast signal (oscillator):  ranges from -1 to 1, reflecting short-term trend state.
o	 Slow signal (smoothed):  moving average of the fast signal.
o	Their interactions (crossovers, zero-crossings) provide actionable trading triggers.
 How to Use 
The  Trend-State background gradient  provides intuitive visual feedback on the aggregated regression features (slope, convexity, and their changes). Because these features reflect not only current trend strength but also their acceleration or deceleration, the color transitions help anticipate evolving market states:
•	 Solid Green:  All features near their highs. Indicates a strong, accelerating uptrend. May also reflect explosive or hyperbolic upside moves (including gaps).
•	 Fading Solid Green:  A recently strong uptrend is losing momentum. Price may shift into a slower uptrend, consolidation, or even a reversal.
•	 Fading Green → Yellow:  Often appears as a dirty yellow or a rapidly mixing pattern of green and red. Signals that the uptrend is weakening toward neutrality or beginning to turn negative.
•	 Yellow → Deepening Red:  Two possible scenarios:
o	Coming from a strong uptrend → suggests a sharp fade, though the trend may still technically be up.
o	Coming from a weaker uptrend or sideways market → suggests the start of an accelerating downtrend.
•	 Solid Red:  All features near their lows. Indicates a strong, accelerating downtrend. May also reflect crash-type conditions or downside gaps.
•	 Fading Solid Red:  A recently strong downtrend is losing strength. Market may move into a slower decline, consolidation, or early reversal upward.
•	 Fading Red → Yellow : The downtrend is weakening toward neutral, with potential for a bullish shift. 
•	 Yellow → Increasing Green:  Two possible scenarios:
o	Coming from a strong downtrend, it reflects a sharp fade of bearish momentum, though the market may still technically be trending down.
o	Coming from a weaker downtrend or sideways movement, it suggests the start of an accelerating uptrend.
 Note:  Market evolution does not always follow this neat “color cycle.” It may jump between states, skip stages, or reverse abruptly depending on market conditions. This makes the background coloring particularly valuable as a contextual map of current and evolving price dynamics.
 Signal Crossovers: 
Although the fast signal is very similar (but not identical) to the background coloring, it provides a numerical representation indicating a bullish interpretation for rising values and bearish for falling. 
o	 High-confidence entries: 
	Fast signal rising from < -0.7 and crossing above the slow signal → potential long entry.
	Fast signal falling from > +0.7 and crossing below the slow signal → potential short entry.
o	 Low-confidence entries: 
	Crossovers near zero may still provide a valid trigger but may be noisy and should be confirmed with other signals.
o	 Zero-crossings: 
	Indicate broader state changes, useful for conservative positioning or option strategies. For confirmation of a Fast signal 0-crossing, wait for the Slow signal to cross as well.
________________________________________
*)  Note on Aggregation 
While the indicator currently uses a heuristic linear combination of features, alternatives such as Principal Component Analysis (PCA) could provide a more formal aggregation. However, while in the absence of matrix algebra, the required eigenvalue decomposition can be approximated, its computational expense does not justify the marginal higher insight in this case. The current heuristic approach offers a practical balance of clarity, speed, and accuracy.
Painel Técnico (4H x 1D) — Clean UI + Alertas BrenoG📋 Main Functions
1️⃣ Analysis in two fixed timeframes
4 hours and 1 day analyzed in parallel.
Each column in the table displays the data for its respective timeframe.
2️⃣ Entry point based on oversold conditions
The “entry point” is not the current price, but rather the last candle that went into oversold territory (RSI ≤ configured threshold).
If there has been no recent oversold condition, the current price is used as a fallback.
All calculations (Buy Zone, Stops, TPs) are based on this point.
3️⃣ Buy Zone
Defined as:
java
Copiar
Editar
Low Zone  = entry * (1 - width%)
High Zone = entry
Always visible in the table, but alerts can be set to trigger only if RSI is oversold at the moment of entry.
4️⃣ Automatic Stops
Moderate Stop and Conservative Stop, calculated as a % below the entry point.
Displayed in the table with black text on a gray background for emphasis.
Alerts trigger when price crosses below these levels.
5️⃣ Take Profits (TP1–TP4)
Calculated from the entry point:
By percentage (usePercentTP = true) or
By fixed prices (usePercentTP = false).
The table displays:
Target price
% gain over the entry point
They only appear when RSI > 50 and EMA50 > EMA200 (the “alignment” condition).
Alerts trigger only on breakouts upward.
6️⃣ Context Indicators
RSI → shows numeric value and green/red color.
MACD → indicates if the MACD line is above or below the signal line.
EMAs 50/200 → indicates “Golden Cross” or “Death Cross”.
Price vs EMA200 → dedicated row showing “Above” or “Below EMA 200” with green/red color.
7️⃣ Visual Panel
Semi–transparent dark gray background, thin borders.
Colored header:
Blue for 4H
Orange for 1D
Rows separated by data type for easy reading.
Configurable font size (tiny to large).
Table position configurable (top_left, top_right, etc.).
8️⃣ Integrated Alerts
Entry/Exit of Buy Zone
Touch of each TP
Touch of each Stop
RSI entering Oversold
All alerts are separated by timeframe with clear, fixed messages.
📌 Simple Summary:
It’s an intelligent panel that combines multi–timeframe technical analysis, automatic calculation of entries/stops/TPs based on oversold conditions, and ready–to–use alerts — all presented in a visual, compact, and fully configurable format.
Mig Trade Model - Kill Zones
Key features:
Liquidity Hunt Detection: Spots aggressive moves that "hunt" stops beyond recent swing highs/lows.
Consolidation Filter: Requires 1-3 small-range candles after a hunt before confirming with a strong candle.
Bias Application: Uses daily open/close to auto-detect bias or allows manual override.
Kill Zone Restriction: Limits signals to London (default: 7-10 AM UTC) and NY (default: 12-3 PM UTC) sessions for better relevance in active markets.
This strategy is inspired by smart money concepts (SMC) and ICT (Inner Circle Trader) methodologies, aiming to capture venom-like "stings" in price action where liquidity is grabbed before reversals.
How It Works
ATR Calculation: Uses a user-defined ATR length (default: 14) to measure volatility, which scales candle body and range thresholds.
Bias Determination:
Auto: Compares daily close to open (bullish if close > open).
Manual: User selects "Bullish" or "Bearish."
Strong Candles:
Bullish: Green candle with body > 2x ATR (configurable).
Bearish: Red candle with body > 2x ATR.
Small Range Candles:
Candles where high-low < 0.5x ATR (configurable).
Liquidity Hunt:
Bullish Hunt: Strong bearish candle making a new low below the past swing low (default: 10 bars).
Bearish Hunt: Strong bullish candle making a new high above the past swing high.
Signal Generation:
After a hunt, counts 1-3 small-range candles.
Confirms with a strong candle in the opposite direction (e.g., strong bullish after bearish hunt).
Resets if >3 small candles or an opposing strong candle appears.
Kill Zone Filter:
Checks if the current bar's time (in UTC) falls within London or NY Kill Zones.
Only allows final "Buy" (bullish entry) or "Sell" (bearish entry) if bias matches and in Kill Zone.
Plots:
Yellow circle (below): Bullish liquidity hunt.
Orange circle (above): Bearish liquidity hunt.
Blue diamond (below): Raw bullish signal.
Purple diamond (above): Raw bearish signal.
Green triangle up ("Buy"): Filtered bullish entry.
Red triangle down ("Sell"): Filtered bearish entry.
Inputs
Bias: "Auto" (default), "Bullish", or "Bearish" – Controls signal direction based on daily trend.
ATR Length: 14 (default) – Period for ATR calculation.
Swing Length for Liquidity Hunt: 10 (default) – Bars to look back for swing highs/lows.
Strong Candle Body Multiplier (x ATR): 2.0 (default) – Threshold for strong candle bodies.
Small Range Multiplier (x ATR): 0.5 (default) – Threshold for small-range candles.
London Kill Zone Start/End Hour (UTC): 7/10 (default) – Customize London session hours.
NY Kill Zone Start/End Hour (UTC): 12/15 (default) – Customize New York session hours.
Usage Tips
Timeframe: Best on lower timeframes (e.g., 5-15 min) for intraday trading, especially forex pairs like EURUSD or GBPUSD.
Timezone Adjustment: Inputs are in UTC. If your chart is in a different timezone (e.g., EST = UTC-5), adjust hours accordingly (e.g., London: 2-5 AM EST → 7-10 UTC).
Risk Management: Use with stop-loss (e.g., beyond the hunt low/high) and take-profit based on ATR multiples. Not financial advice—backtest thoroughly.
Customization: Tweak multipliers for different assets; higher for volatile cryptos, lower for stocks.
Limitations: Relies on historical data; may generate false signals in ranging markets. Combine with other indicators like volume or support/resistance.
This indicator is for educational purposes. Always use discretion and proper risk management in live trading. If you find it useful, feel free to share feedback or suggestions!
SMC_CommonLibrary   "SMC_Common" 
Common types and utilities for Smart Money Concepts indicators
 get_future_time(bars_ahead) 
  Parameters:
     bars_ahead (int) 
 get_time_at_offset(offset) 
  Parameters:
     offset (int) 
 get_mid_time(time1, time2) 
  Parameters:
     time1 (int) 
     time2 (int) 
 timeframe_to_string(tf) 
  Parameters:
     tf (string) 
 is_psychological_level(price) 
  Parameters:
     price (float) 
 detect_swing_high(src_high, lookback) 
  Parameters:
     src_high (float) 
     lookback (int) 
 detect_swing_low(src_low, lookback) 
  Parameters:
     src_low (float) 
     lookback (int) 
 detect_fvg(h, l, min_size) 
  Parameters:
     h (float) 
     l (float) 
     min_size (float) 
 analyze_volume(vol, volume_ma) 
  Parameters:
     vol (float) 
     volume_ma (float) 
 create_label(x, y, label_text, bg_color, label_size, use_time) 
  Parameters:
     x (int) 
     y (float) 
     label_text (string) 
     bg_color (color) 
     label_size (string) 
     use_time (bool) 
 SwingPoint 
  Fields:
     price (series float) 
     bar_index (series int) 
     bar_time (series int) 
     swing_type (series string) 
     strength (series int) 
     is_major (series bool) 
     timeframe (series string) 
 LiquidityLevel 
  Fields:
     price (series float) 
     bar_index (series int) 
     bar_time (series int) 
     liq_type (series string) 
     touch_count (series int) 
     is_swept (series bool) 
     quality_score (series float) 
     level_type (series string) 
 OrderBlock 
  Fields:
     start_bar (series int) 
     end_bar (series int) 
     start_time (series int) 
     end_time (series int) 
     top (series float) 
     bottom (series float) 
     ob_type (series string) 
     has_liquidity_sweep (series bool) 
     has_fvg (series bool) 
     is_mitigated (series bool) 
     is_breaker (series bool) 
     timeframe (series string) 
     mitigation_level (series float) 
 StructureBreak 
  Fields:
     level (series float) 
     break_bar (series int) 
     break_time (series int) 
     break_type (series string) 
     direction (series string) 
     is_confirmed (series bool) 
     source_swing_bar (series int) 
     source_time (series int) 
 SignalData 
  Fields:
     signal_type (series string) 
     entry_price (series float) 
     stop_loss (series float) 
     take_profit (series float) 
     risk_reward_ratio (series float) 
     confluence_count (series int) 
     confidence_score (series float) 
     strength (series string)
BTC 1m Chop Top/Bottom Reversal (Stable Entries)Strategy Description: BTC 5m Chop Top/Bottom Reversal (Stable Entries)
This strategy is engineered to capture precise reversal points during Bitcoin’s choppy or sideways price action on the 5-minute timeframe. It identifies short-term tops and bottoms using a confluence of volatility bands, momentum indicators, and price structure, optimized for high-probability scalping and intraday reversals.
Core Logic:
Volatility Filter: Uses an EMA with ATR bands to define overextended price zones.
Momentum Divergence: Confirms reversals using RSI and MACD histogram shifts.
Price Action Filter: Requires candle confirmation in the direction of the trade.
Locked Signal Logic: Prevents repaints and disappearing trades by confirming signals only once per bar.
Trade Parameters:
Short Entry: Above upper band + overbought RSI + weakening MACD + bearish candle
Long Entry: Below lower band + oversold RSI + strengthening MACD + bullish candle
Take Profit: ±0.75%
Stop Loss: ±0.4%
This setup is tuned for traders using tight risk control and leverage, where execution precision and minimal drawdown tolerance are critical.
Smart Order Blocks [Pro Version]Here’s a **clear, detailed "How It Works" explanation** for this indicator:
---
## ✅ **Smart Order Blocks \  – How It Works**
### **Purpose**
This indicator detects **Order Blocks (OBs)** based on **pivot highs and lows**, and automatically marks **Bullish** and **Bearish OB zones** on the chart with optional extensions and alerts. It is designed to help traders identify **institutional price levels** where liquidity is often engineered for future price moves.
---
### **Customization Options**
✔ **Source** → Choose between Wicks or Bodies for OB calculation.
✔ **Pivot Settings** → Adjust sensitivity for detecting pivots.
✔ **Extend OBs** → Keep zones visible until tapped, or fix a specific width.
✔ **Show Labels** → Displays OB type and strength on chart.
✔ **Colors** → Configure Bullish, Bearish, and Invalid OB colors.
---
### **Practical Usage**
* **Entry Strategy**:
  * Wait for price to **revisit a Bullish OB** in an uptrend → Long entry.
  * Wait for price to **revisit a Bearish OB** in a downtrend → Short entry.
* Combine with:
  * **Market Structure (HH/HL or LH/LL)**.
  * **Confirmation signals** (e.g., candlestick pattern, break of structure).
  * **Risk Management** → Stop loss outside OB zone.
---
### ✅ **Summary in One Sentence**
The indicator automatically identifies **institutional OB zones**, shows their strength, extends them until mitigated, and alerts you when price interacts with these key liquidity levels, helping you trade like Smart Money.
---
Gann Single Square Swing Trading System with Gann AnglesGann Single Square Swing Trading System 
This script automatically detects "squares" - geometric patterns where price movement equals time movement. When price moves the same distance as the number of bars (time), it creates powerful support/resistance levels based on Gann theory.
Key Visual Elements
•	Box: The detected square pattern
•	Dark Blue Line (50%): Most important trading level
•	Green Lines: Profit target levels (125%, 150%)
•	Red Lines: Stop loss levels (-25%, -50%)
•	Colored Angle Lines: Gann angles for trend direction
•	Quality Score: Blue label showing setup strength (aim for 70%+)
Simple Trading Rules
LONG Trades (Green 🟢 Square)
1.	Entry: Buy when price touches the dark blue 50% line from above
2.	Stop Loss: Place below the red -25% line
3.	Take Profit: Exit at green 125% line (first target) or 150% line (second target)
SHORT Trades (Red 🔴 Square)
1.	Entry: Sell when price touches the dark blue 50% line from below
2.	Stop Loss: Place above the red -25% line
3.	Take Profit: Exit at green 125% line (first target) or 150% line (second target)
Entry Checklist
✅ Square quality score > 70%
✅ Price touches 50% level (dark blue line)
✅ Volume above average (if volume filter enabled)
✅ Clear square formation visible
Alerts
The script generates automatic alerts when price reaches the 50% trading level. Enable alerts in TradingView to get notified of setups.
Bottom Line: Wait for the alert → Check quality score → Enter at 50% level → Set stop at red line → Take profit at green line.
US Index First 30m Candle Strategy (10m Chart)Strategy Description for Publishing 
Title: US Index First 30-Minute Candle Strategy (10m Chart)
 Overview: 
This Pine Script implements a trading strategy designed to capitalize on price movements within the first 30 minutes of the U.S. stock market opening. It is specifically tailored for use on a 15-minute chart and is optimized for trading U.S. indices during regular market hours.
 Features: 
Session Time Configuration: The strategy operates within the U.S. market hours, specifically from 9:30 AM to 4:00 PM (Eastern Time).
First 30-Minute Candle Aggregation: The script identifies the high and low of the first 30-minute candle, which is considered a critical time frame for market momentum.
Single Trade Per Day: To minimize risk, the strategy is designed to execute only one trade per day based on the established range of the first 30 minutes.
Dynamic Trade Conditions: Buy and sell signals are generated when the price breaks above the high or below the low of the first 30-minute candle, with defined stop-loss and take-profit levels based on a customizable risk-reward ratio.
How It Works:
 Initialization:  
At the start of each trading day, the script resets the high and low values for the first 30 minutes.
 Range Locking:  After the first 30 minutes, the high and low values are locked, allowing for trade entries based on these levels.
Trade Execution:
 Long Entry:  Triggered when the price moves above the locked high.
 Short Entry:  Triggered when the price drops below the locked low.
 Risk Management:  Each trade comes with a stop-loss and take-profit mechanism to manage potential losses and secure profits.
 Visuals: 
The script also plots the locked high and low levels on the chart, providing a visual reference for traders.
 Conclusion: 
This strategy leverages the volatility often seen in the first 30 minutes of trading, aiming to capture significant price movements while maintaining a disciplined trading approach. It is suitable for traders looking to implement a systematic strategy based on early market behavior.
 Usage: 
To use this strategy, simply add the script to your TradingView chart, set your desired parameters, and monitor for trade signals during the specified market hours. Adjust the risk-reward ratio as needed to align with your trading style.
Mickey's EMAMickey’s EMA  is a lightweight, overlay indicator that combines two Exponential Moving Averages (EMAs) with automatic entry, stop-loss and target visual signals—plus dynamic JSON alerts for seamless webhook integration. It’s designed for both day-traders and swing-traders who want clear, on-chart cues and fully-customizable risk parameters.
 🔍 Overview 
 
 Dual EMAs  (fast & slow) to capture trend changes.
 Automated “BUY” / “SELL”  markers at every EMA crossover.
 Customizable Stop-Loss %  and  Target %  levels, plotted as ❌ and 🎯 bubbles.
 “SL Hit (Custom)”  if the opposite EMA crossover occurs before price touches your stop level.
 JSON-formatted alerts  containing ticker, instrument type, timeframe, trend (“CE” for bullish, “PE” for bearish), and price—ready for webhooks.
 
 ⚙️ Inputs 
| Setting                  | Default | Description                                     |
| ------------------------ | ------- | ----------------------------------------------- |
| **Fast EMA Length**      | 20      | Period for the faster EMA.                      |
| **Slow EMA Length**      | 200     | Period for the slower EMA.                      |
| **Price Source**         | Close   | Data series to calculate EMAs on.               |
| **Custom Stop Loss %**   | 0.1%    | Stop-loss level as a percentage of entry price. |
| **Target %**             | 0.5%    | Profit-target level as a percentage of entry.   |
| **Show Entry/SL/Target** | ON      | Toggle all entry, SL and target visuals.        |
 📊 What It Plots 
 
 Fast EMA (blue)  &  Slow EMA (white)  overlayed on price.
 BUY 🟢  label below bar when Fast EMA crosses above Slow EMA.
 SELL 🔴  label above bar when Fast EMA crosses below Slow EMA.
 ❌ (Custom)  bubble at entry price if an opposite EMA crossover occurs before price hits your custom stop-loss.
 ❌ bubble at the stop-loss price when price actually breaches the stop level.
 🎯 bubble at target price when price first reaches your profit-target level.
 
 🔔 Alerts & Webhooks 
 
 On-screen alert conditions “Mickey’s EMA → BUY” and “Mickey’s EMA → SELL” appear in the Create-Alert dialog.
 Dynamic JSON payload sent via alert() when a crossover fires, e.g.:
 
 
{
  "script": "AAPL",
  "scriptType": "equity",
  "instrumentType": "NASDAQ",
  "timeframe": "5",
  "trend": "CE",
  "price": 174.25
}
 
Use these alerts to integrate with bots, chat systems, manual, or any webhook-driven workflow.
 🚀 Why Use Mickey’s EMA? 
 
 Clarity & Precision:  All signals appear exactly at the EMA or price-level of interest.
 Custom Risk Management:  Define your own stop-loss and target percentages.
 Seamless Automation:  Dynamic JSON alerts mean zero manual setup for webhooks.
 Versatile:  Equally effective on intraday charts or daily/weekly timeframes.
 
Add Mickey’s EMA to your TradingView chart today and get instant, aesthetically-pleasing guidance on trend entries, risk exits, and profit targets—all in one elegant overlay.
Chaikin Oscillator Enhanced📊 What Is the Chaikin Oscillator?
The Chaikin Oscillator is a momentum indicator that helps traders understand the strength of buying and selling pressure in the market, based on volume and price movement.
It is calculated as the difference between two moving averages (short-term and long-term) of the Accumulation/Distribution Line (A/D Line). This line combines price and volume to show whether money is flowing into or out of an asset.
________________________________________
🧠 Simple Concept
•	When big traders are buying, they usually do so with volume support—the Chaikin Oscillator picks this up.
•	When volume is rising but price is falling, or vice versa, it shows hidden strength or weakness.
So, this indicator helps you see what the smart money is doing, even if the price isn’t moving much.
________________________________________
🛠️ How It Works
•	Oscillator Value Above Zero → More buying pressure (bullish).
•	Oscillator Value Below Zero → More selling pressure (bearish).
•	Crossing above zero → A potential buy signal.
•	Crossing below zero → A potential sell signal.
The histogram (vertical bars) in the indicator changes color:
•	Green bars = Positive momentum.
•	Red bars = Negative momentum.
________________________________________
🎯 How Traders Use It for Entry and Exit
✅ For Entries:
•	Buy Entry: When the oscillator crosses above the zero line and the bars turn green, it means buyers are stepping in with volume.
•	For better confirmation, combine it with price breaking above a resistance level.
❌ For Exits or Shorts:
•	Sell Exit or Short Entry: When the oscillator crosses below the zero line and bars turn red, it suggests selling pressure is growing.
•	If the price is also below support, it’s a stronger signal.
________________________________________
🔍 Example Use Case:
1.	You’re watching a stock or crypto that's been going sideways.
2.	Suddenly, the Chaikin Oscillator crosses above zero, and green bars appear.
3.	That’s your early clue that big buyers might be entering.
4.	If price confirms this with a breakout, you can enter a long position.
________________________________________
🌐 Where Is It Useful?
The Chaikin Oscillator is great for:
•	Stocks (especially volume-heavy large caps)
•	ETFs
•	Cryptocurrency (on exchanges that provide volume data)
•	Forex – less reliable unless volume is proxy-based
⚠️ Important: It won’t work well on instruments where volume data is missing or unreliable (like some CFDs or synthetic assets).
________________________________________
🧭 Pro Tips for Using It:
•	Combine it with support/resistance, moving averages, or candlestick patterns.
•	Avoid trading only based on this indicator—use it as confirmation.
•	Use the alerts (added in the script) so you don’t miss key movements.
________________________________________
HMA Crossover + ATR + Curvature (Long & Short)📏 Hull Moving Averages (Trend Filters)
- fastHMA = ta.hma(close, fastLength)
- slowHMA = ta.hma(close, slowLength)
These two HMAs act as dynamic trend indicators:
- A bullish crossover of fast over slow HMA signals a potential long setup.
- A bearish crossunder triggers short interest.
⚡️ Curvature (Acceleration Filter)
- curv = ta.change(ta.change(fastHMA))
This calculates the second-order change (akin to the second derivative) of the fast HMA — effectively the acceleration of the trend. It serves as a filter:
- For long entries: curv > curvThresh (positive acceleration)
- For short entries: curv < -curvThresh (negative acceleration)
It helps eliminate weak or stagnating moves by requiring momentum behind the crossover.
📈 Volatility-Based Risk Management (ATR)
- atr = ta.atr(atrLength)
- stopLoss = atr * atrMult
- trailStop = atr * trailMult
These define your:
- Initial stop loss: scaled to recent volatility using ATR and atrMult.
- Trailing stop: also ATR-scaled, to lock in gains dynamically as price moves favorably.
💰 Position Sizing via Risk Percent
- capital = strategy.equity
- riskCapital = capital * (riskPercent / 100)
- qty = riskCapital / stopLoss
This dynamically calculates the position size (qty) such that if the stop loss is hit, the loss does not exceed the predefined percentage of account equity. It’s a volatility-adjusted position sizing method, keeping your risk consistent regardless of market conditions.
📌 Execution Logic
- Long Entry: on bullish HMA crossover with rising curvature.
- Short Entry: on bearish crossover with falling curvature.
- Exits: use ATR-based trailing stops.
- Position is closed when trend conditions reverse (e.g., bearish crossover exits the long).
This framework gives you:
- Trend-following logic (via HMAs)
- Momentum confirmation (via curvature)
- Volatility-aware execution and exits (via ATR)
- Risk-controlled dynamic sizing
Want to get surgical and test what happens if we use curvature on the difference between HMAs instead? That might give some cool insights into trend strength transitions.
Previous Daily High/LowThe previous day’s high and low are critical price levels that traders use to identify potential support, resistance, and intraday trading opportunities. These levels represent the highest and lowest prices reached during the prior trading session and often act as reference points for future price action.
Why Are Previous Daily High/Low Important?
Support & Resistance Zones
The previous day’s low often acts as support (buyers defend this level).
The previous day’s high often acts as resistance (sellers defend this level).
Breakout Trading
A move above the previous high suggests bullish momentum.
A move below the previous low suggests bearish momentum.
Mean Reversion Trading
Traders fade moves toward these levels, expecting reversals.
Example: Buying near the previous low in an uptrend.
Institutional Order Flow
Market makers and algos often reference these levels for liquidity.
How to Use Previous Daily High/Low in Trading
1. Breakout Strategy
Long Entry: Price breaks & closes above previous high → bullish continuation.
Short Entry: Price breaks & closes below previous low → bearish continuation.
2. Reversal Strategy
Long at Previous Low: If price pulls back to the prior day’s low in an uptrend.
Short at Previous High: If price rallies to the prior day’s high in a downtrend.
3. Range-Bound Markets
Buy near previous low, sell near previous high if price oscillates between them.
Example Trade Setup
Scenario: Price opens near the previous day’s high.
Bullish Case: A breakout above it targets next resistance.
Bearish Case: Rejection at the high signals a pullback.
StochFusion – Multi D-LineStochFusion – Multi D-Line 
 An advanced fusion of four Stochastic %D lines into one powerful oscillator. 
 
 What it does:   
Combines four user-weighted Stochastic %D lines—from fastest (9,3) to slowest (60,10)—into a single “Fusion” line that captures both short-term and long-term momentum in one view.
 How to use:   
   
   Adjust the four weights (0–10) to emphasize the speed of each %D component.  
   Watch the Fusion line crossing key zones:  
     – Above 80 → overbought condition, potential short entry.  
     – Below 20 → oversold condition, potential long entry.  
     – Around 50 → neutral/midline, watch for trend shifts.  
   
 Applications:   
   
   Entry/exit filter: Only take trades when the Fusion line confirms zone exits.  
   Trend confirmation: Analyze slope and cross of the midline for momentum strength.  
   Multi-timeframe alignment: Use on different chart resolutions to find confluence.  
   
 Tips & Tricks:   
   
   Default weights   give more influence to slower %D—good for trend-focused strategies.  
   Equal weights   provide a balanced oscillator that mimics an ensemble average.  
   Experiment: Increase the fastest weight to capture early reversal signals.  
   
 Developed by:  TradeQUO — inspired by DayTraderRadio John  
 
 “The best momentum indicator is the one you adapt to your own trading rhythm.” 
EMA 200 Monitor - Bybit CoinsEMA 200 Monitor - Bybit Coins
📊 OVERVIEW
The EMA 200 Monitor - Bybit Coins is an advanced indicator that automatically monitors 30 of the top cryptocurrencies traded on Bybit, alerting you when they are close to the 200-period Exponential Moving Average on the 4-hour timeframe.
This indicator was developed especially for traders who use the EMA 200 as a key support/resistance level in their swing trading and position trading strategies.
🎯 WHAT IT'S FOR
Multi-Asset Monitoring: Simultaneous monitoring of 30 cryptocurrencies without having to switch between charts
Opportunity Identification: Detects when coins are approaching the 200 EMA, a crucial technical level
Automated Alerts: Real-time notifications when a coin reaches the configured proximity
Time Efficiency: Eliminates the need to manually check chart collections
⚙️ HOW IT WORKS
Main Functionality
The indicator uses the request.security() function to fetch price data and calculate the 200 EMA of each monitored asset. With each new bar, the script:
Calculates the distance between the current price and the 200 EMA for each coin
Identifies proximity based on the configured percentage (default: 2%)
Displays results in a table organized on the chart
Generates automatic alerts when proximity is detected
Monitored Coins
Major : BTC, ETH, BNB, ADA, XRP, SOL, DOT, DOGE, AVAX
DeFi : UNI, LINK, ATOM, ICP, NEAR, OP, ARB, INJ
Memecoins : SHIB, PEPE, WIF, BONK, FLOKI
Emerging : SUI, TON, APT, POL (ex-MATIC)
📋 AVAILABLE SETTINGS
Adjustable Parameters
EMA Length (Default: 200): Exponential Moving Average Period
Proximity Percentage (Default: 2%): Distance in percentage to consider "close"
Show Table (Default: Active): Show/hide results table
Table Position: Position of the table on the chart (9 options available)
Color System
🔴 Red: Distance ≤ 1% (very close)
🟠 Orange: Distance ≤ 1.5% (close)
🟡 Yellow: Distance ≤ 2% (approaching)
🚀 HOW TO USE
Initial Configuration
Add the indicator to the 4-hour timeframe chart
Set the parameters according to your strategy
Position the table where there is no graphic preference
Setting Alerts
Click "Create Alert" in TradingView
Select the "EMA 200 Monitor" indicator
Set the notification frequency and method
Activate the alert to receive automatic notifications
Results Interpretation
The table shows:
Coin: Asset name (e.g. BTC, ETH)
Price: Current currency quote
EMA 200: Current value of the moving average
Distance: Percentage of proximity to the core code
💡 STRATEGIES TO USE
Reversal Trading
Entry: When price touches or approaches the EMA 200
Stop: Below/above the EMA with a safety margin
Target: Previous resistance/support levels
Breakout Trading
Monitoring: Watch for currencies consolidating near the EMA 200
Entry: When the media is finally broken
Confirmation: Volume and close above/below the EMA
Swing Trading
Identification: Use the monitor to detect setups in formation
Timing: Wait for the EMA 200 to approach for detailed analysis
Management: Use the EMA as a reference for stops dynamics
⚠️ IMPORTANT CONSIDERATIONS
Technical Limitations
Request Bybit data: Access to exchange symbols required
Specific timeframe: Optimized for 4-hour analysis
Minimum delay: Data updated with each new bar
Usage Recommendations
Combine with technical analysis: Use together with other indicators
Confirm the configuration: Check the graphic patterns before trading
Manage risk: Always use stop loss and adequate position sizing
Backtesting: Test your strategy before applying with real capital
Disclaimer
This indicator is a technical analysis tool and does not constitute investment advice. Always do your own analysis and manage detailed information about the risks of your operations.
🔧 TECHNICAL INFORMATION
Pine Script version: v6
Type: Indicator (overlay=true)
Compatibility: All TradingView plans
Resources used: request.security(), arrays, tables
Performance: Optimized for multiple simultaneous queries
📈 COMPETITIVE ADVANTAGES
✅ Simultaneous monitoring of 30 major assets ✅ Clear visual interface with intuitive core system ✅ Customizable alerts for different details ✅ Optimized code for maximum performance ✅ Flexible configuration adaptable to different strategies ✅ Real-time update without the need for manual refresh
Developed for traders who value efficiency and accuracy in identifying market opportunities based on the EMA 20
Momentum Fusion v1Momentum Fusion v1  
Overview
Momentum Fusion v1 (MFusion) is a multi-oscillator indicator that combines several components to analyze market momentum and trend strength. It incorporates modified versions of classic indicators such as PVI (Positive Volume Index), NVI (Negative Volume Index), MFI (Money Flow Index), RSI, Stochastic, and Bollinger Bands Oscillator. The indicator displays a histogram that changes color based on momentum strength and includes "FUSION🔥" signal labels when extreme values are reached.
Indicator Settings
Parameters:
EMA Length – Smoothing period for the moving average (default: 255).
Smoothing Period – Internal calculation smoothing parameter (default: 15).
BB Multiplier – Standard deviation multiplier for Bollinger Bands (default: 2.0).
Show verde / marron / media lines – Toggles the display of auxiliary lines.
Show FUSION🔥 label – Enables/disables signal labels.
Indicator Components
1. PVI (Positive Volume Index)
Formula:
pvi := volume > volume  ? nz(pvi ) + (close - close ) / close  * sval : nz(pvi )
Description:
PVI increases when volume rises compared to the previous bar and accounts for price percentage change. The stronger the price movement with increasing volume, the higher the PVI value.
2. NVI (Negative Volume Index)
Formula:
nvi := volume < volume  ? nz(nvi ) + (close - close ) / close  * sval : nz(nvi )
Description:
NVI tracks price movements during declining volume. If the price rises on low volume, it may indicate a "stealth" trend.
3. Money Flow Index (MFI)
Formula:
100 - 100 / (1 + up / dn)
Description:
An oscillator measuring money flow strength. Values above 80 suggest overbought conditions, while values below 20 indicate oversold conditions.
4. Stochastic Oscillator
Formula:
k = 100 * (close - lowest(low, length)) / (highest(high, length) - lowest(low, length))
Description:
A classic stochastic oscillator showing price position relative to the selected period's range.
5. Bollinger Bands Oscillator
Formula:
(tprice - BB midline) / (upper BB - lower BB) * 100
Description:
Indicates the price position relative to Bollinger Bands in percentage terms.
Key Lines & Histogram
1. Verde (Green Line)
Calculation:
verde = marron + oscp (normalized PVI)
Interpretation:
Higher values indicate stronger bullish momentum. A FUSION🔥 signal appears when the value reaches 750+.
2. Marron (Brown Line)
Calculation:
marron = (RSI + MFI + Bollinger Osc + Stochastic / 3) / 2
Interpretation:
A composite oscillator combining multiple indicators. Higher values suggest overbought conditions.
3. Media (Red Line)
Calculation:
media = EMA of marron with smoothing period
Interpretation:
Acts as a signal line for trend confirmation.
4. Histogram
Calculation:
histo = verde - marron
Colors:
Bright green (>100) – Strong bullish momentum.
Light green (>0) – Moderate bullish momentum.
Orange (<0) – Bearish momentum.
Red (<-100) – Strong bearish momentum.
Signals & Alerts
1. FUSION🔥 (Strong Momentum)
Condition:
verde >= 750
Visualization:
A "FUSION🔥" label appears below the chart.
Alert:
Can be set to trigger notifications when the condition is met.
2. Background Aura
Condition:
verde > 850
Visualization:
The chart background turns teal, indicating extreme momentum.
Usage Recommendations
FUSION🔥 Signal – Can be used as a long entry point when confirmed by other indicators.
Histogram:
1. Green bars – Potential long entry.
2. Red/orange bars – Potential short entry.
3. Media & Marron Crossover – Can serve as an additional trend filter.
4. Suitable for a 5-15 minute time frame
Conclusion
Momentum Fusion v1 is a powerful tool for momentum analysis, combining multiple indicators into a unified system. It is suitable for:
Trend traders (catching strong movements).
Scalpers (identifying short-term impulses).
Swing traders (filtering entry points).
The indicator features customizable settings and visual signals, making it adaptable to various trading styles.
3 EMA + SupertrendThree EMAs: Helps you identify the general trend direction and potential crossovers.
When the Fast EMA crosses above the Medium or Slow EMAs, it may indicate a bullish trend, and vice versa for bearish trends.
Supertrend: Works as a trend filter. You can use it to identify overall market conditions:
When the Supertrend is green, it indicates an uptrend.
When the Supertrend is red, it indicates a downtrend.
Combination: The EMAs help you confirm the trend, and the Supertrend can act as a filter or confirmation tool for your entries and exits.
Potential Strategy Idea:
Long Entry: When the Fast EMA crosses above the Medium EMA, and the Supertrend is green.
Short Entry: When the Fast EMA crosses below the Medium EMA, and the Supertrend is red.
Exit: You can use either the Supertrend turning from green to red (for long exits) or vice versa.
Lyapunov Market Instability (LMI)Lyapunov Market Instability (LMI) 
 What is Lyapunov Market Instability? 
 Lyapunov Market Instability (LMI)  is a revolutionary indicator that brings chaos theory from theoretical physics into practical trading. By calculating Lyapunov exponents—a measure of how rapidly nearby trajectories diverge in phase space—LMI quantifies market sensitivity to initial conditions. This isn't another oscillator or trend indicator; it's a mathematical lens that reveals whether markets are in chaotic (trending) or stable (ranging) regimes.
Inspired by the meditative color field paintings of Mark Rothko, this indicator transforms complex chaos mathematics into an intuitive visual experience. The elegant simplicity of the visualization belies the sophisticated theory underneath—just as Rothko's seemingly simple color blocks contain profound depth.
 Theoretical Foundation (Chaos Theory & Lyapunov Exponents) 
In dynamical systems, the Lyapunov exponent (λ) measures the rate of separation of infinitesimally close trajectories:
 λ > 0:  System is chaotic—small changes lead to dramatically different outcomes (butterfly effect)
 λ < 0:  System is stable—trajectories converge, perturbations die out
 λ ≈ 0:  Edge of chaos—transition between regimes
Phase Space Reconstruction
Using  Takens' embedding theorem , we reconstruct market dynamics in higher dimensions:
 Time-delay embedding:  Create vectors from price at different lags
 Nearest neighbor search:  Find historically similar market states
 Trajectory evolution:  Track how these similar states diverged over time
 Divergence rate:  Calculate average exponential separation
 Market Application 
 Chaotic markets (λ > threshold):  Strong trends emerge, momentum dominates, use breakout strategies
 Stable markets (λ < threshold):  Mean reversion dominates, fade extremes, range-bound strategies work
 Transition zones:  Market regime about to change, reduce position size, wait for confirmation
 How LMI Works 
 1. Phase Space Construction 
Each point in time is embedded as a vector using historical prices at specific delays (τ). This reveals the market's hidden attractor structure.
 2. Lyapunov Calculation 
For each current state, we:
- Find similar historical states within epsilon (ε) distance
- Track how these initially similar states evolved
- Measure exponential divergence rate
- Average across multiple trajectories for robustness
 3. Signal Generation 
 Chaos signals:  When λ crosses above threshold, market enters trending regime
 Stability signals:  When λ crosses below threshold, market enters ranging regime
 Divergence detection:  Price/Lyapunov divergences signal potential reversals
 4. Rothko Visualization 
 Color fields:  Background zones represent market states with Rothko-inspired palettes
 Glowing line:  Lyapunov exponent with intensity reflecting market state
 Minimalist design:  Focus on essential information without clutter
 Inputs: 
 📐 Lyapunov Parameters 
 Embedding Dimension (default: 3) 
 Dimensions for phase space reconstruction 
 2-3:  Simple dynamics (crypto/forex) - captures basic momentum patterns
 4-5:  Complex dynamics (stocks/indices) - captures intricate market structures
Higher dimensions need exponentially more data but reveal deeper patterns
 Time Delay τ (default: 1) 
 Lag between phase space coordinates 
 1: High-frequency (1m-15m charts)  - captures rapid market shifts
 2-3: Medium frequency (1H-4H)  - balances noise and signal
 4-5: Low frequency (Daily+)  - focuses on major regime changes
Match to your timeframe's natural cycle
 Initial Separation ε (default: 0.001) 
 Neighborhood size for finding similar states 
 0.0001-0.0005:  Highly liquid markets (major forex pairs)
 0.0005-0.002:  Normal markets (large-cap stocks)
 0.002-0.01:  Volatile markets (crypto, small-caps)
Smaller = more sensitive to chaos onset
 Evolution Steps (default: 10) 
 How far to track trajectory divergence 
 5-10:  Fast signals for scalping - quick regime detection
 10-20:  Balanced for day trading - reliable signals
 20-30:  Slow signals for swing trading - major regime shifts only
 Nearest Neighbors (default: 5) 
 Phase space points for averaging 
 3-4:  Noisy/fast markets - adapts quickly
 5-6:  Balanced (recommended) - smooth yet responsive
 7-10:  Smooth/slow markets - very stable signals
 📊 Signal Parameters 
 Chaos Threshold (default: 0.05) 
 Lyapunov value above which market is chaotic 
 0.01-0.03:  Sensitive - more chaos signals, earlier detection
 0.05:  Balanced - optimal for most markets
 0.1-0.2:  Conservative - only strong trends trigger
 Stability Threshold (default: -0.05) 
 Lyapunov value below which market is stable 
 -0.01 to -0.03:  Sensitive - quick stability detection
 -0.05:  Balanced - reliable ranging signals
 -0.1 to -0.2:  Conservative - only deep stability
 Signal Smoothing (default: 3) 
 EMA period for noise reduction 
 1-2:  Raw signals for experienced traders
 3-5:  Balanced - recommended for most
 6-10:  Very smooth for position traders
 🎨 Rothko Visualization 
 Rothko Classic:  Deep reds for chaos, midnight blues for stability
 Orange/Red:  Warm sunset tones throughout
 Blue/Black:  Cool, meditative ocean depths
 Purple/Grey:  Subtle, sophisticated palette
 Visual Options: 
 Market Zones : Background fields showing regime areas
 Transitions:  Arrows marking regime changes
 Divergences:  Labels for price/Lyapunov divergences
 Dashboard:  Real-time state and trading signals
 Guide:  Educational panel explaining the theory
 Visual Logic & Interpretation 
 Main Elements 
 Lyapunov Line:  The heart of the indicator
 Above chaos threshold:  Market is trending, follow momentum
 Below stability threshold:  Market is ranging, fade extremes
 Between thresholds:  Transition zone, reduce risk
 Background Zones:  Rothko-inspired color fields
 Red zone:  Chaotic regime (trending)
 Gray zone:  Transition (uncertain)
 Blue zone:  Stable regime (ranging)
 Transition Markers: 
 Up triangle:  Entering chaos - start trend following
 Down triangle:  Entering stability - start mean reversion
 Divergence Signals: 
 Bullish:  Price makes low but Lyapunov rising (stability breaking down)
 Bearish:  Price makes high but Lyapunov falling (chaos dissipating)
 Dashboard Information 
 Market State:  Current regime (Chaotic/Stable/Transitioning)
 Trading Bias:  Specific strategy recommendation
 Lyapunov λ:  Raw value for precision
 Signal Strength:  Confidence in current regime
 Last Change:  Bars since last regime shift
 Action:  Clear trading directive
 Trading Strategies 
 In Chaotic Regime (λ > threshold) 
 Follow trends aggressively:  Breakouts have high success rate
 Use momentum strategies:  Moving average crossovers work well
 Wider stops:  Expect larger swings
 Pyramid into winners:  Trends tend to persist
 In Stable Regime (λ < threshold) 
 Fade extremes:  Mean reversion dominates
 Use oscillators:  RSI, Stochastic work well
 Tighter stops:  Smaller expected moves
 Scale out at targets:  Trends don't persist
 In Transition Zone 
 Reduce position size:  Uncertainty is high
Wait for confirmation:  Let regime establish
 Use options:  Volatility strategies may work
 Monitor closely:  Quick changes possible
 Advanced Techniques 
- Multi-Timeframe Analysis
- Higher timeframe LMI for regime context
- Lower timeframe for entry timing
- Alignment = highest probability trades
- Divergence Trading
- Most powerful at regime boundaries
- Combine with support/resistance
- Use for early reversal detection
- Volatility Correlation
- Chaos often precedes volatility expansion
- Stability often precedes volatility contraction
- Use for options strategies
 Originality & Innovation 
 LMI  represents a genuine breakthrough in applying chaos theory to markets:
 True Lyapunov Calculation:  Not a simplified proxy but actual phase space reconstruction and divergence measurement
 Rothko Aesthetic:  Transforms complex math into meditative visual experience
 Regime Detection:  Identifies market state changes before price makes them obvious
 Practical Application:  Clear, actionable signals from theoretical physics
This is not a combination of existing indicators or a visual makeover of standard tools. It's a fundamental rethinking of how we measure and visualize market dynamics.
 Best Practices 
 Start with defaults:  Parameters are optimized for broad market conditions
 Match to your timeframe:  Adjust tau and evolution steps
 Confirm with price action:  LMI shows regime, not direction
 Use appropriate strategies:  Chaos = trend, Stability = reversion
 Respect transitions:  Reduce risk during regime changes
 Alerts Available 
 Chaos Entry:  Market entering chaotic regime - prepare for trends
 Stability Entry:  Market entering stable regime - prepare for ranges
 Bullish Divergence:  Potential bottom forming
 Bearish Divergence:  Potential top forming
 Chart Information 
Script Name: Lyapunov Market Instability (LMI) Recommended Use: All markets, all timeframes  Best Performance:  Liquid markets with clear regimes
 Academic References 
 Takens, F. (1981).  "Detecting strange attractors in turbulence"
 Wolf, A. et al. (1985).  "Determining Lyapunov exponents from a time series"
 Rosenstein, M. et al. (1993).  "A practical method for calculating largest Lyapunov exponents"
 Note:  After completing this indicator, I discovered @loxx's 2022 "Lyapunov Hodrick-Prescott Oscillator w/ DSL". While both explore Lyapunov exponents, they represent independent implementations with different methodologies and applications. This indicator uses phase space reconstruction for regime detection, while his combines Lyapunov concepts with HP filtering.
 Disclaimer 
This indicator is for research and educational purposes only. It does not constitute financial advice or provide direct buy/sell signals. Chaos theory reveals market character, not future prices. Always use proper risk management and combine with your own analysis. Past performance does not guarantee future results.
See markets through the lens of chaos. Trade the regime, not the noise.
Bringing theoretical physics to practical trading through the meditative aesthetics of Mark Rothko
Trade with insight. Trade with anticipation.
—  Dskyz , for DAFE Trading Systems
Opening Range BreakoutOPENING RANGE BREAKOUT (ORB) INDICATOR
DESCRIPTION
The Opening Range Breakout indicator is a powerful technical analysis tool designed specifically for US equity markets. It identifies and visualizes the opening range established during the first configurable minutes of each trading day (starting at 9:30 AM EST), then provides clear signals when price breaks out of or rejects from these key levels.
This indicator combines multiple timeframe analysis capabilities with precise breakout detection to help traders identify high-probability trading opportunities based on opening range dynamics.
KEY FEATURES
Configurable Opening Range:
• Set opening range duration from 5 minutes to 4 hours
• Automatically adjusts calculations based on your chart timeframe
• Works on any timeframe (1m, 5m, 15m, 1h, etc.)
Multi-Day Range Display:
• Shows up to 50 days of historical opening ranges
• Each day's range properly contained within its trading session
• Range lines extend from market open (9:30 AM) to market close (4:00 PM EST)
Clear Signal System:
• Green arrows (⬆): Bullish breakouts and rejections
• Red arrows (⬇): Bearish breakouts and rejections
• Two signal types: Close breakouts (normal size) and wick rejections (small size)
Visual Range Highlighting:
• Opening range period highlighted with colored box
• Customizable colors for range fill, borders, and midline
• Clean, professional appearance with configurable line styles
SIGNAL TYPES
Bullish Signals (Green ⬆):
1. Close Breakout Above Range (Normal Size): 5-minute candle closes above the opening range high
2. Wick Rejection from Below (Small Size): Price wicks below the opening range low but closes back inside the range
Bearish Signals (Red ⬇):
1. Close Breakout Below Range (Normal Size): 5-minute candle closes below the opening range low
2. Wick Rejection from Above (Small Size): Price wicks above the opening range high but closes back inside the range
CONFIGURATION OPTIONS
Range Settings:
• Opening Range Minutes: Duration of opening range (default: 30 minutes)
• Lookback Days: Number of historical days to display (default: 20 days)
Visual Customization:
• Range Color: Fill color for the opening range area
• Border Color: Color for range high/low lines
• Midline Color: Color for the range midpoint line
• Opening Range Highlight Color: Color for the opening period box
• Line Style: Solid, Dashed, or Dotted lines
• Line Width: 1-4 pixel width options
Display Options:
• Show Midline: Toggle midpoint line display
• Show Range Labels: Toggle price level labels
• Arrow Distance: Adjust arrow positioning (0.1-2.0%)
USAGE GUIDE
Basic Setup:
1. Add the indicator to your chart (works best on 5-minute timeframe)
2. Configure your preferred opening range duration (15m, 30m, or 60m are popular choices)
3. Adjust lookback days based on your analysis needs
4. Customize colors and line styles to match your chart theme
Trading Applications:
Breakout Trading:
• Long Entry: Green arrow (close breakout above range) + confirmation
• Short Entry: Red arrow (close breakout below range) + confirmation
• Stop Loss: Opposite side of the opening range
• Target: 1-2x the range size or key support/resistance levels
Range Rejection Trading:
• Reversal Setups: Small arrows indicate failed breakouts
• Mean Reversion: Trade back toward range midline
• Support/Resistance: Use range levels as key price zones
Multi-Day Analysis:
• Identify recurring support/resistance levels
• Analyze range expansion/contraction patterns
• Compare current day's activity to recent history
BEST PRACTICES
1. Timeframe Selection: 5-minute charts provide optimal signal clarity
2. Range Duration: 30-minute opening range is most commonly used, but adjust based on:
   - Market volatility
   - Stock characteristics
   - Trading style preference
3. Confirmation: Use additional indicators or price action for trade confirmation
4. Risk Management: Always use appropriate position sizing and stop losses
MARKET SESSIONS
The indicator is specifically designed for US equity markets:
• Market Open: 9:30 AM EST
• Market Close: 4:00 PM EST
• Opening Range: Calculated from market open
• Range Lines: Extend throughout the trading day only
PERFORMANCE NOTES
• Optimized for real-time trading with minimal lag
• Automatically manages memory by cleaning old ranges
• Efficiently handles multiple timeframes and range calculations
KNOWN ISSUES & WORKAROUNDS
Historical Buffer Error:
Issue: Occasionally, you may encounter an error: "The requested historical offset (XXX) is beyond the historical buffer's limit (770)"
Workaround:
1. Switch to a different timeframe temporarily
2. Switch back to your original timeframe
3. The indicator will reload and function normally
This is a Pine Script limitation related to historical data access and doesn't affect the indicator's core functionality.
COMPATIBILITY
• Pine Script Version: v6
• Chart Types: All chart types supported
• Timeframes: All timeframes (optimized for 1m-1h)
• Markets: Designed for US equity markets during regular trading hours
TIPS FOR MAXIMUM EFFECTIVENESS
1. Combine with Volume: High volume on breakouts increases reliability
2. Market Context: Consider overall market direction and volatility
3. News Awareness: Be cautious around earnings and major announcements
4. Range Quality: Wider ranges often provide better breakout opportunities
5. Time of Day: Early breakouts (first 1-2 hours) often have higher follow-through
This indicator is provided for educational and informational purposes. Always conduct your own analysis and manage risk appropriately.






















