TSLA Cycle Timing - 122-Day Reversal Map (Adaptive Framework)This indicator is a timing map built specifically for Tesla (TSLA) on the Daily chart. It plots a repeating set of vertical, color-coded timing markers inside a 122-bar cycle (commonly treated as ~122 trading days on the Daily timeframe). These markers highlight reversal “zones”—areas where TSLA has historically shown a tendency to pivot from high-to-low and low-to-high within the cycle.
The script includes:
23 TSLA-derived set points (Points 1–23): the core timing map used to mark the most repeatable reversal areas.
Two optional “Inversion Points” (INV A / INV B): manual markers you can enable when TSLA’s high/low sequence appears to flip due to a structural deviation.
One additional optional marker (OPT C) for user customization.
This is not an auto-buy/sell system. It is a cycle-structure framework designed to help you anticipate when a reversal is more likely to occur, so you can combine it with your own confirmation tools (price action, trend context, support/resistance, volume, etc.).
Definitions (How this script interprets highs/lows)
In the context of cycle mapping:
A High Point is the highest price reached between two neighboring high pivots.
A Low Point is the lowest price reached between two neighboring low pivots.
The vertical lines are timing markers, not “guaranteed pivot candles.” Price may top/bottom slightly before or after a line. That’s why the script includes an optional ± window (in bars) to visualize a small tolerance zone around each marker.
How it works (Conceptually)
The script defines a repeating cycle length (default 122 bars).
Inside each cycle, each point has an offset measured in bars from the cycle start.
For every cycle instance (past, current, and optional future cycles), the script draws:
a vertical dotted line at each enabled point offset
optional ± window bands around the line
optional labels (numbers for set points and “INV” labels for inversion points)
Because this is a Tesla-specific map, the default offsets for Points 1–23 are preconfigured based on TSLA’s observed structure, and the remaining optional points are user-controlled.
How to Use (Important)
1) Use the Daily chart first
This model is designed around TSLA’s Daily cycle behavior. Start with:
Symbol: TSLA
Timeframe: 1D
If you use other timeframes, the cycle “tempo” can change and may require different offsets.
2) Identify the cycle start (anchor)
Cycle mapping depends on where the current cycle is anchored.
Use “Bars Back to Current Cycle Start” to shift the cycle start so that the script’s point sequence aligns with your most recent known cycle beginning. Once aligned, the points should repeat near each 122-bar interval.
3) Read the vertical markers as reversal zones
The colored vertical lines represent areas where reversals have historically occurred, not a promise that price must reverse exactly on the line.
A practical approach:
Use the marker as a “heads-up” zone
Wait for confirmation (trend break, candle structure, momentum shift, key level reaction, etc.)
4) Understand “set points” vs “Inversion Points”
Set Points (1–23)
These are the primary TSLA reversal zones that tend to recur within the 122-bar structure. Specific numbered points often appear near the same relative position inside each cycle.
Inversion Points (INV A / INV B)
Occasionally, TSLA’s cycle behavior can flip—meaning the expected high-to-low (or low-to-high) progression temporarily swaps order. This is what I refer to as an inversion.
When you see a cycle behaving “backwards” relative to the usual sequence:
Enable INV A and/or INV B
Place their offsets at the bar locations where the flip becomes obvious
Use these markers as manual annotations so your cycle notes stay consistent even when TSLA deviates from its typical rhythm
These inversion markers do not force the script to predict a flip—they allow you to document it cleanly.
5) Use the ± Window Bands to manage real-world variance
Markets don’t pivot on perfect timestamps. If a reversal tends to happen “around” a point:
Enable ± Window Bands
Set Window ± Bars (commonly 1–3 bars on 1D)
This gives a realistic visual tolerance zone around each timing marker.
Settings Guide (Practical)
Cycle Length (bars): 122 (TSLA Daily baseline)
Lookback Bars: increase to study more history, decrease for performance
Future Cycles: use sparingly; future markers are guidance zones, not guarantees
Past Cycles: Lines Only: recommended ON for stable performance
Labels at Top: helps keep the chart clean and readable
Final Notes / Limitations
This is a historical timing framework designed to map TSLA’s repeating reversal structure. It helps estimate when reversal pressure tends to appear, but it does not replace risk management or confirmation. Cycle behavior can stretch, compress, or invert during unusual volatility regimes—hence the inclusion of optional inversion markers.
Индикаторы и стратегии
Daily ATR + DeltaThis indicator shows last value of ATR with this parameters: Length 14, Smoothing RMA, Timeframe 1 day i Wait for timeframe closes.
Also, it shows Delta in percentage.
Delta is calculated in this way: -((the last one-minute closing price of the previous day's stock exchange)-(last price at the moment))/(value of ATR) * 100
Notice:
If you are in postmarket or premarket, delta will be also calculated from the "the last one-minute closing prices of the previous day's stock exchange" not from the "the last one-minute closing price of the todays stock exchange".
You dont need to have indicator Average True Range for this indicator to be working.
StO Price Action - Impulse CandleShort Summary
- Highlights impulse candles based on relative momentum
- Compares current or previous closed candles against prior price movement
- Uses a configurable momentum factor to filter significant impulses
- Designed to make strong directional candles visually stand out
Full Description
Overview
- Identifies impulse candles with strong momentum
- Focuses on candle-to-candle expansion rather than trend or structure
- Intended to visually emphasize moments of acceleration in price
- Works as a complementary tool to price action and volatility analysis
Impulse Candle Logic
- Impulse candles are detected by comparing the current candle range to previous candles
- A candle is considered an impulse when its range exceeds prior movement by a defined factor
- The comparison basis can be (current forming Candle, previous fully closed Candle)
Momentum Factor
- The momentum factor defines how much stronger a candle must be compared to earlier candles
- Higher values filter out smaller moves and highlight only extreme impulses
- Lower values allow more frequent impulse detection
- Helps adapt the indicator to different instruments and volatility regimes
Range Calculation
- Two range calculation modes are available:
- Open / Close (Body range):
- Measures body-based momentum
- Focuses on directional conviction
- High / Low (Candle range):
- Measures full volatility expansion
- Includes wicks and intrabar extremes
Visualization
- Impulse candles are highlighted using a customizable bar color
- Designed to remain minimal and unobtrusive
Alerts
- Optional alert can be enabled after detected impulse candles
- Useful for monitoring momentum shifts without constant screen time
Usage
- Suitable for breakout detection and momentum confirmation
- Helps identify volatility expansion phases
- Can be used for entry timing or trade management
Notes
- This indicator does not predict direction on its own
- Impulse candles may occur in both trending and ranging markets
- Best used in combination with structure, levels or higher-timeframe context
- Momentum thresholds should be adjusted per market and timeframe
Fixed Price Levels with Zones (1000 / 750 / 500 / 250)idywbdiawunadnaw oidnawidnawodnaw wadaw dawd awdaw
Gold 2-Week Futures LevelsYou may change the color at bottom of script and i used 1h to mark out my levels, you may change it to fit your time frame.
MACD 12-26-9 with Slope, Convergence & Divergence1. Core Indicator: MACD (12-26-9)
The script uses the standard MACD:
Fast EMA: 12
Slow EMA: 26
Signal EMA: 9
It plots:
MACD Line → short-term vs long-term momentum
Signal Line → smoothed MACD
Histogram → distance between MACD and Signal
2. Histogram Slope (Momentum Acceleration)
What it is
The slope measures how fast the MACD histogram is changing.
histSlope = hist - hist
What it tells you
Positive slope → momentum accelerating
Negative slope → momentum slowing
Slope flip → early momentum shift (often before MACD cross)
Why it matters
MACD crosses are lagging.
Histogram slope gives early warning of momentum changes.
3. Convergence & Divergence (MACD vs Signal)
How it’s calculated
The script measures the distance between the MACD and Signal lines:
distance = abs(macdLine - signalLine)
Convergence → distance is shrinking
Divergence → distance is expanding
Interpretation
Convergence = compression / energy building
Divergence = expansion / trend strength or exhaustion
This is not price divergence, but internal momentum structure.
4. MACD Perimeter Threshold (Momentum Filter)
What it is
Horizontal bands above and below zero that define a “noise zone”.
Inside perimeter → weak / choppy momentum
Outside perimeter → strong momentum
Why it’s useful
Filters low-quality MACD crosses
Identifies compression → expansion
Helps spot trend exhaustion when momentum fades outside the band
5. Visual Encoding (What you see)
Histogram colors
Bright green / red → strong acceleration
Dull green / maroon → weakening momentum
Gray → indecision
MACD line color
Yellow → converging (compression)
Orange → diverging (expansion)
Blue → neutral
Markers
Up triangle → bullish convergence
Down triangle → bearish divergence
6. How traders use this indicator
Trend continuation
MACD above zero
Histogram positive
Slope rising
Divergence expanding
➡ Strong trend continuation
Pullback entries
Trend intact
Histogram pulls back toward zero
Slope turns up again
➡ High-probability re-entry
Breakout anticipation
Long convergence
Histogram flattening
Sudden slope expansion
➡ Breakout likely
Exhaustion warning
Large divergence
Histogram slope weakens
Momentum fails to expand
➡ Trend may stall or reverse
7. Best use cases
Works best as a momentum confirmation tool
Combine with:
Market structure
Support / resistance
Moving averages
Volume or Force Index
SpatialIndexYou can start using this now by inserthing this at the top of your indicator/strategy/library.
import ArunaReborn/SpatialIndex/1 as SI
Overview
SpatialIndex is a high-performance Pine Script library that implements price-bucketed spatial indexing for efficient proximity queries on large datasets. Instead of scanning through hundreds or thousands of items linearly (O(n)), this library provides O(k) bucket lookup where k is typically just a handful of buckets, dramatically improving performance for price-based filtering operations.
This library works with any data type through index-based references, making it universally applicable for support/resistance levels, pivot points, order zones, pattern detection points, Fair Value Gaps, and any other price-based data that needs frequent proximity queries.
Why This Library Exists
The Problem
When building advanced technical indicators that track large numbers of price levels (support/resistance zones, pivot points, order blocks, etc.), you often need to answer questions like:
- *"Which levels are within 5% of the current price?"*
- *"What zones overlap with this price range?"*
- *"Are there any significant levels near my entry point?"*
The naive approach is to loop through every single item and check its price. For 500 levels across multiple timeframes, this means 500 comparisons every bar . On instruments with thousands of historical bars, this quickly becomes a performance bottleneck that can cause scripts to time out or lag.
The Solution
SpatialIndex solves this by organizing items into price buckets —like filing cabinets organized by price range. When you query for items near $50,000, the library only looks in the relevant buckets (e.g., $49,000-$51,000 range), ignoring all other price regions entirely.
Performance Example:
- Linear scan: Check 500 items = 500 comparisons per query
- Spatial index: Check 3-5 buckets with ~10 items each = 30-50 comparisons per query
- Result: 10-16x faster queries
Key Features
Core Capabilities
- ✅ Generic Design : Works with any data type via index references
- ✅ Multiple Index Strategies : Fixed bucket size or ATR-based dynamic sizing
- ✅ Range Support : Index items that span price ranges (zones, gaps, channels)
- ✅ Efficient Queries : O(k) bucket lookup instead of O(n) linear scan
- ✅ Multiple Query Types : Proximity percentage, fixed range, exact price with tolerance
- ✅ Dynamic Updates : Add, remove, update items in O(1) time
- ✅ Batch Operations : Efficient bulk removal and reindexing
- ✅ Query Caching : Optional caching for repeated queries within same bar
- ✅ Statistics & Debugging : Built-in stats and diagnostic functions
### Advanced Features
- ATR-Based Bucketing : Automatically adjusts bucket sizes based on volatility
- Multi-Bucket Spanning : Items that span ranges are indexed in all overlapping buckets
- Reindexing Support : Handles array removals with automatic index shifting
- Cache Management : Configurable query caching with automatic invalidation
- Empty Bucket Cleanup : Automatically removes empty buckets to minimize memory
How It Works
The Bucketing Concept
Think of price space as divided into discrete buckets, like a histogram:
```
Price Range: $98-$100 $100-$102 $102-$104 $104-$106 $106-$108
Bucket Key: 49 50 51 52 53
Items:
```
When you query for items near $103:
1. Calculate which buckets overlap the $101.50-$104.50 range (keys 50, 51, 52)
2. Return items from only those buckets:
3. Never check items in buckets 49 or 53
Bucket Size Selection
Fixed Size Mode:
```pine
var SI.SpatialBucket index = SI.newSpatialBucket(2.0) // $2 per bucket
```
- Good for: Instruments with stable price ranges
- Example: For stocks trading at $100, 2.0 = 2% increments
ATR-Based Mode:
```pine
float atr = ta.atr(14)
var SI.SpatialBucket index = SI.newSpatialBucketATR(1.0, atr) // 1x ATR per bucket
SI.updateATR(index, atr) // Update each bar
```
- Good for: Instruments with varying volatility
- Adapts automatically to market conditions
- 1.0 multiplier = one bucket spans one ATR unit
Optimal Bucket Size:
The library includes a helper function to calculate optimal size:
```pine
float optimalSize = SI.calculateOptimalBucketSize(close, 5.0) // For 5% proximity queries
```
This ensures queries span approximately 3 buckets for optimal performance.
Index-Based Architecture
The library doesn't store your actual data—it only stores indices that point to your external arrays:
```pine
// Your data
var array levels = array.new()
var array types = array.new()
var array ages = array.new()
// Your index
var SI.SpatialBucket index = SI.newSpatialBucket(2.0)
// Add a level
array.push(levels, 50000.0)
array.push(types, "support")
array.push(ages, 0)
SI.add(index, array.size(levels) - 1, 50000.0) // Store index 0
// Query near current price
SI.QueryResult result = SI.queryProximity(index, close, 5.0)
for idx in result.indices
float level = array.get(levels, idx)
string type = array.get(types, idx)
// Work with your actual data
```
This design means:
- ✅ Works with any data structure you define
- ✅ No data duplication
- ✅ Minimal memory footprint
- ✅ Full control over your data
---
Usage Guide
Basic Setup
```pine
// Import library
import username/SpatialIndex/1 as SI
// Create index
var SI.SpatialBucket index = SI.newSpatialBucket(2.0)
// Your data arrays
var array supportLevels = array.new()
var array touchCounts = array.new()
```
Adding Items
Single Price Point:
```pine
// Add a support level at $50,000
array.push(supportLevels, 50000.0)
array.push(touchCounts, 1)
int levelIdx = array.size(supportLevels) - 1
SI.add(index, levelIdx, 50000.0)
```
Price Range (Zones/Gaps):
```pine
// Add a resistance zone from $51,000 to $52,000
array.push(zoneBottoms, 51000.0)
array.push(zoneTops, 52000.0)
int zoneIdx = array.size(zoneBottoms) - 1
SI.addRange(index, zoneIdx, 51000.0, 52000.0) // Indexed in all overlapping buckets
```
Querying Items
Proximity Query (Percentage):
```pine
// Find all levels within 5% of current price
SI.QueryResult result = SI.queryProximity(index, close, 5.0)
if array.size(result.indices) > 0
for idx in result.indices
float level = array.get(supportLevels, idx)
// Process nearby level
```
Fixed Range Query:
```pine
// Find all items between $49,000 and $51,000
SI.QueryResult result = SI.queryRange(index, 49000.0, 51000.0)
```
Exact Price with Tolerance:
```pine
// Find items at exactly $50,000 +/- $100
SI.QueryResult result = SI.queryAt(index, 50000.0, 100.0)
```
Removing Items
Safe Removal Pattern:
```pine
SI.QueryResult result = SI.queryProximity(index, close, 5.0)
if array.size(result.indices) > 0
// IMPORTANT: Sort descending to safely remove from arrays
array sorted = SI.sortIndicesDescending(result)
for idx in sorted
// Remove from index
SI.remove(index, idx)
// Remove from your data arrays
array.remove(supportLevels, idx)
array.remove(touchCounts, idx)
// Reindex to maintain consistency
SI.reindexAfterRemoval(index, idx)
```
Batch Removal (More Efficient):
```pine
// Collect indices to remove
array toRemove = array.new()
for i = 0 to array.size(supportLevels) - 1
if array.get(touchCounts, i) > 10 // Remove old levels
array.push(toRemove, i)
// Remove in descending order from data arrays
array sorted = array.copy(toRemove)
array.sort(sorted, order.descending)
for idx in sorted
SI.remove(index, idx)
array.remove(supportLevels, idx)
array.remove(touchCounts, idx)
// Batch reindex (much faster than individual reindexing)
SI.reindexAfterBatchRemoval(index, toRemove)
```
Updating Items
```pine
// Update a level's price (e.g., after refinement)
float newPrice = 50100.0
SI.update(index, levelIdx, newPrice)
array.set(supportLevels, levelIdx, newPrice)
// Update a zone's range
SI.updateRange(index, zoneIdx, 51000.0, 52500.0)
array.set(zoneBottoms, zoneIdx, 51000.0)
array.set(zoneTops, zoneIdx, 52500.0)
```
Query Caching
For repeated queries within the same bar:
```pine
// Create cache (persistent)
var SI.CachedQuery cache = SI.newCachedQuery()
// Cached query (returns cached result if parameters match)
SI.QueryResult result = SI.queryProximityCached(
index,
cache,
close,
5.0, // proximity%
1 // cache duration in bars
)
// Invalidate cache when index changes significantly
if bigChangeDetected
SI.invalidateCache(cache)
```
---
Practical Examples
Example 1: Support/Resistance Finder
```pine
//@version=6
indicator("S/R with Spatial Index", overlay=true)
import username/SpatialIndex/1 as SI
// Data storage
var array levels = array.new()
var array types = array.new() // "support" or "resistance"
var array touches = array.new()
var array ages = array.new()
// Spatial index
var SI.SpatialBucket index = SI.newSpatialBucket(close * 0.02) // 2% buckets
// Detect pivots
bool isPivotHigh = ta.pivothigh(high, 5, 5)
bool isPivotLow = ta.pivotlow(low, 5, 5)
// Add new levels
if isPivotHigh
array.push(levels, high )
array.push(types, "resistance")
array.push(touches, 1)
array.push(ages, 0)
SI.add(index, array.size(levels) - 1, high )
if isPivotLow
array.push(levels, low )
array.push(types, "support")
array.push(touches, 1)
array.push(ages, 0)
SI.add(index, array.size(levels) - 1, low )
// Find nearby levels (fast!)
SI.QueryResult nearby = SI.queryProximity(index, close, 3.0) // Within 3%
// Process nearby levels
for idx in nearby.indices
float level = array.get(levels, idx)
string type = array.get(types, idx)
// Check for touch
if type == "support" and low <= level and low > level
array.set(touches, idx, array.get(touches, idx) + 1)
else if type == "resistance" and high >= level and high < level
array.set(touches, idx, array.get(touches, idx) + 1)
// Age and cleanup old levels
for i = array.size(ages) - 1 to 0
array.set(ages, i, array.get(ages, i) + 1)
// Remove levels older than 500 bars or with 5+ touches
if array.get(ages, i) > 500 or array.get(touches, i) >= 5
SI.remove(index, i)
array.remove(levels, i)
array.remove(types, i)
array.remove(touches, i)
array.remove(ages, i)
SI.reindexAfterRemoval(index, i)
// Visualization
for idx in nearby.indices
line.new(bar_index, array.get(levels, idx), bar_index + 10, array.get(levels, idx),
color=array.get(types, idx) == "support" ? color.green : color.red)
```
Example 2: Multi-Timeframe Zone Detector
```pine
//@version=6
indicator("MTF Zones", overlay=true)
import username/SpatialIndex/1 as SI
// Store zones from multiple timeframes
var array zoneBottoms = array.new()
var array zoneTops = array.new()
var array zoneTimeframes = array.new()
// ATR-based spatial index for adaptive bucketing
var SI.SpatialBucket index = SI.newSpatialBucketATR(1.0, ta.atr(14))
SI.updateATR(index, ta.atr(14)) // Update bucket size with volatility
// Request higher timeframe data
= request.security(syminfo.tickerid, "240", )
// Detect HTF zones
if not na(htf_high) and not na(htf_low)
float zoneTop = htf_high
float zoneBottom = htf_low * 0.995 // 0.5% zone thickness
// Check if zone already exists nearby
SI.QueryResult existing = SI.queryRange(index, zoneBottom, zoneTop)
if array.size(existing.indices) == 0 // No overlapping zones
// Add new zone
array.push(zoneBottoms, zoneBottom)
array.push(zoneTops, zoneTop)
array.push(zoneTimeframes, "4H")
int idx = array.size(zoneBottoms) - 1
SI.addRange(index, idx, zoneBottom, zoneTop)
// Query zones near current price
SI.QueryResult nearbyZones = SI.queryProximity(index, close, 2.0) // Within 2%
// Highlight nearby zones
for idx in nearbyZones.indices
box.new(bar_index - 50, array.get(zoneBottoms, idx),
bar_index, array.get(zoneTops, idx),
bgcolor=color.new(color.blue, 90))
```
### Example 3: Performance Comparison
```pine
//@version=6
indicator("Spatial Index Performance Test")
import username/SpatialIndex/1 as SI
// Generate 500 random levels
var array levels = array.new()
var SI.SpatialBucket index = SI.newSpatialBucket(close * 0.02)
if bar_index == 0
for i = 0 to 499
float randomLevel = close * (0.9 + math.random() * 0.2) // +/- 10%
array.push(levels, randomLevel)
SI.add(index, i, randomLevel)
// Method 1: Linear scan (naive approach)
int linearCount = 0
float proximityPct = 5.0
float lowBand = close * (1 - proximityPct/100)
float highBand = close * (1 + proximityPct/100)
for i = 0 to array.size(levels) - 1
float level = array.get(levels, i)
if level >= lowBand and level <= highBand
linearCount += 1
// Method 2: Spatial index query
SI.QueryResult result = SI.queryProximity(index, close, proximityPct)
int spatialCount = array.size(result.indices)
// Compare performance
plot(result.queryCount, "Items Examined (Spatial)", color=color.green)
plot(linearCount, "Items Examined (Linear)", color=color.red)
plot(spatialCount, "Results Found", color=color.blue)
// Spatial index typically examines 10-50 items vs 500 for linear scan!
```
API Reference Summary
Initialization
- `newSpatialBucket(bucketSize)` - Fixed bucket size
- `newSpatialBucketATR(atrMultiplier, atrValue)` - ATR-based buckets
- `updateATR(sb, newATR)` - Update ATR for dynamic sizing
Adding Items
- `add(sb, itemIndex, price)` - Add item at single price point
- `addRange(sb, itemIndex, priceBottom, priceTop)` - Add item spanning range
Querying
- `queryProximity(sb, refPrice, proximityPercent)` - Query by percentage
- `queryRange(sb, priceBottom, priceTop)` - Query fixed range
- `queryAt(sb, price, tolerance)` - Query exact price with tolerance
- `queryProximityCached(sb, cache, refPrice, pct, duration)` - Cached query
Removing & Updating
- `remove(sb, itemIndex)` - Remove item
- `update(sb, itemIndex, newPrice)` - Update item price
- `updateRange(sb, itemIndex, newBottom, newTop)` - Update item range
- `reindexAfterRemoval(sb, removedIndex)` - Reindex after single removal
- `reindexAfterBatchRemoval(sb, removedIndices)` - Batch reindex
- `clear(sb)` - Remove all items
Utilities
- `size(sb)` - Get item count
- `isEmpty(sb)` - Check if empty
- `contains(sb, itemIndex)` - Check if item exists
- `getStats(sb)` - Get debug statistics string
- `calculateOptimalBucketSize(price, pct)` - Calculate optimal bucket size
- `sortIndicesDescending(result)` - Sort for safe removal
- `sortIndicesAscending(result)` - Sort ascending
Performance Characteristics
Time Complexity
- Add : O(1) for single point, O(m) for range spanning m buckets
- Remove : O(1) lookup + O(b) bucket cleanup where b = buckets item spans
- Query : O(k) where k = buckets in range (typically 3-5) vs O(n) linear scan
- Update : O(1) removal + O(1) addition = O(1) total
Space Complexity
- Memory per item : ~8 bytes for index reference + map overhead
- Bucket overhead : Proportional to price range coverage
- Typical usage : For 500 items with 50 active buckets ≈ 4-8KB total
Scalability
- ✅ 100 items : ~5-10x faster than linear scan
- ✅ 500 items : ~10-15x faster
- ✅ 1000+ items : ~15-20x faster
- ⚠️ Performance degrades if bucket size is too small (too many buckets)
- ⚠️ Performance degrades if bucket size is too large (too many items per bucket)
Best Practices
Bucket Size Selection
1. Start with 2-5% of asset price for percentage-based queries
2. Use ATR-based mode for volatile assets or multi-symbol scripts
3. Test bucket size using `calculateOptimalBucketSize()` function
4. Monitor with `getStats()` to ensure reasonable bucket count
Memory Management
1. Clear old items regularly to prevent unbounded growth
2. Use age tracking to remove stale data
3. Set maximum item limits based on your needs
4. Batch removals are more efficient than individual removals
Query Optimization
1. Use caching for repeated queries within same bar
2. Invalidate cache when index changes significantly
3. Sort results descending before removal iteration
4. Batch operations when possible (reindexing, removal)
Data Consistency
1. Always reindex after removal to maintain index alignment
2. Remove from arrays in descending order to avoid index shifting issues
3. Use batch reindex for multiple simultaneous removals
4. Keep external arrays and index in sync at all times
Limitations & Caveats
Known Limitations
- Not suitable for exact price matching : Use tolerance with `queryAt()`
- Bucket size affects performance : Too small = many buckets, too large = many items per bucket
- Memory usage : Scales with price range coverage and item count
- Reindexing overhead : Removing items mid-array requires index shifting
When NOT to Use
- ❌ Datasets with < 50 items (linear scan is simpler)
- ❌ Items that change price every bar (constant reindexing overhead)
- ❌ When you need ALL items every time (no benefit over arrays)
- ❌ Exact price level matching without tolerance (use maps instead)
When TO Use
- ✅ Large datasets (100+ items) with occasional queries
- ✅ Proximity-based filtering (% of price, ATR-based ranges)
- ✅ Multi-timeframe level tracking
- ✅ Zone/range overlap detection
- ✅ Price-based spatial filtering
---
Technical Details
Bucketing Algorithm
Items are assigned to buckets using integer division:
```
bucketKey = floor((price - basePrice) / bucketSize)
```
For ATR-based mode:
```
effectiveBucketSize = atrValue × atrMultiplier
bucketKey = floor((price - basePrice) / effectiveBucketSize)
```
Range Indexing
Items spanning price ranges are indexed in all overlapping buckets to ensure accurate range queries. The midpoint bucket is designated as the "primary bucket" for removal operations.
Index Consistency
The library maintains two maps:
1. `buckets`: Maps bucket keys → IntArray wrappers containing item indices
2. `itemToBucket`: Maps item indices → primary bucket key (for O(1) removal)
This dual-mapping ensures both fast queries and fast removal while maintaining consistency.
Implementation Note: Pine Script doesn't allow nested collections (map containing arrays directly), so the library uses an `IntArray` wrapper type to hold arrays within the map structure. This is an internal implementation detail that doesn't affect usage.
---
Version History
Version 1.0
- Initial release
Credits & License
License : Mozilla Public License 2.0 (TradingView default)
Library Type : Open-source educational resource
This library is designed as a public domain utility for the Pine Script community. As per TradingView library rules, this code can be freely reused by other authors. If you use this library in your scripts, please provide appropriate credit as required by House Rules.
Summary
SpatialIndex is a specialized library that solves a specific problem: fast proximity queries on large price-based datasets . If you're building indicators that track hundreds of levels, zones, or price points and need to frequently filter by proximity to current price, this library can provide 10-20x performance improvements over naive linear scanning.
The index-based architecture makes it universally applicable to any data type, and the ATR-based bucketing ensures it adapts to market conditions automatically. Combined with query caching and batch operations, it provides a complete solution for spatial data management in Pine Script.
Use this library when speed matters and your dataset is large.
Relative Strength SpreadSPY vs IWM Relative Strength Spread Indicator
The SPY vs IWM Relative Strength Spread indicator measures leadership between large-cap and small-cap equities by comparing the percent performance of SPY (S&P 500) against IWM (Russell 2000) over a user-defined lookback period.
The indicator plots a zero-centered histogram in a separate pane, making relative strength shifts immediately visible.
How It Works
The indicator calculates the percent change of SPY and IWM over the same lookback window.
It then subtracts IWM’s percent change from SPY’s percent change.
The result is plotted as a histogram pinned to the 0% line.
This design removes long-term drift and ensures that:
Positive values indicate SPY is outperforming IWM
Negative values indicate IWM is outperforming SPY
How to Read the Histogram
Above Zero (Green Bars)
Large-cap stocks are leading → typically associated with risk-on stability and institutional flow into SPY-weighted names.
Below Zero (Red Bars)
Small-cap stocks are leading → often signals risk appetite expansion and speculative participation.
Crosses of the Zero Line
Mark potential leadership transitions between large caps and small caps.
Why This Indicator Is Useful
Identifies market regime shifts (risk-on vs risk-off behavior)
Confirms or filters trend strength in equities
Helps time rotations between large-cap and small-cap exposure
Works consistently across all timeframes
Because the calculation is based on percent change, the histogram remains normalized and comparable regardless of price level or timeframe.
Best Use Cases
As a market internals / breadth confirmation tool
As a bias filter for SPY, IWM, or index futures
To spot early leadership changes before price trends fully develop
Week High/LowThis indicator plots the Previous Week High and Low as two horizontal dashed lines.
It is designed to appear only on the Daily (D) and Weekly (W) timeframes, ensuring a clean higher-timeframe context without lower-timeframe noise.
The levels are calculated from the completed weekly candle and automatically update at the start of each new week.
These levels serve as weekly liquidity references, commonly used to assess premium/discount zones, potential stop-run areas, and higher-timeframe market reactions.
Frankfurt-USPremarket Open (0800-1000) CETThe scripts draws 2 horizontal lines:
1. 08:00 a.m. Frankfurt Open
2. 10:00 a.m. US-Premarket Open
Trading Sessions (London / New York / Tokyo / Sydney)Trading sessions for all assets with (time zone) adjustable trading sessions.
ezzy Golden Cross mit Target und StopA simple crossover system based on SMA 50 and SMA 200 including percentage target and stop loss.
ezzy_goldencross This strategy is a simple crossover trading strategy using SMA 50 and SMA 200 (long only). I also implemented a percentage profit target and stop loss.
Single Year Historical ProjectionBasic year projection onto chart from a previous year, good for reference previous years movements.
Enjoy
Volume Profile: Date-Range ObservationI have refined the strategy developed by kv4coins , incorporating an additional option for the observation date range. Previously, when seeking a fixed date range—particularly to track data from the onset of an event-driven trigger up to the present—it was somewhat cumbersome. To address this, I added a new date selection feature to accommodate the need for observing specific time periods.
MB-MACD## Description
**MB-MACD** is a custom Pine Script indicator designed to enhance momentum analysis by combining a volume-based "Main Buy Ratio" (MB) calculation with a traditional MACD oscillator. The MB Ratio estimates institutional buying pressure by apportioning volume based on the candle's range and close position, providing a unique proxy for "smart money" flow. This smoothed MB value is then used as the source for MACD computation, allowing for divergence detection between price action, the MB line, and the MACD Histogram.
Key features include:
- **MB Line**: A histogram-style plot showing smoothed buy/sell ratio, colored bullishly (teal) or bearishly (pink) based on direction.
- **MACD Histogram**: Standard MACD applied to the MB source, with optional smoothing.
- **Divergence Detection**: Identifies bullish and bearish divergences on both the MB line and MACD Histogram, with configurable filters for momentum decay and zero-line alignment.
- **Visualization Options**: Display divergence lines and labels in the indicator pane or synced as an overlay on the main chart for better context.
- **Alerts**: Triggers for bullish or bearish divergences to notify users of potential reversal setups.
This indicator is particularly useful for swing traders and momentum followers looking to spot hidden divergences that may signal trend reversals or continuations. It emphasizes risk management by highlighting where price and momentum decouple, but remember: divergences are probabilistic signals and should be confirmed with other tools.
As this is a community-shared script, I encourage users to test it thoroughly and provide feedback. If you spot any bugs, calculation errors, or improvements (e.g., edge cases with low-volume symbols or performance issues on certain timeframes), please comment below or reach out—your input helps refine it for everyone!
## User Manual
### Introduction
The **MB-MACD** indicator integrates volume analysis with MACD to detect divergences in price and momentum. The core innovation is the "Main Buy Ratio" (MB), which approximates buying vs. selling volume within each bar based on its range and close position. This MB value is smoothed and fed into a MACD calculation, enabling divergence scans on both the MB line and the resulting MACD Histogram.
Divergences occur when price makes higher highs/lower lows, but the oscillator (MB or Histogram) fails to confirm—often signaling potential reversals. The script offers flexible display options, filters to reduce false positives, and alerts for real-time notifications.
**Important Notes:**
- This is not financial advice; use it for educational purposes and backtest on your symbols/timeframes.
- Works best on liquid stocks or indices with reliable volume data (e.g., daily or higher timeframes).
- Performance may vary on low-volume assets or during after-hours trading.
- If you encounter issues (e.g., no divergences detected or rendering errors), check your chart settings and report them in the comments for community debugging.
### Inputs Explanation
The inputs are grouped for ease of configuration. Adjust them via the indicator's settings panel in TradingView.
#### Core Parameters
- **Show MB Line** (Default: True): Enables/disables the MB Ratio histogram plot.
- **Show MACD Histogram** (Default: True): Enables/disables the MACD line and histogram plots.
- **MB Smoothing (SMA)** (Default: 10, Min: 1): Length for smoothing the raw MB Ratio using a Simple Moving Average (SMA). Higher values reduce noise but may lag.
- **Pivot Lookback Length** (Default: 5, Min: 2): Bars to look back/forward for detecting price pivots (highs/lows) used in divergence logic.
- **Max Lines Kept** (Default: 100, Min: 10): Limits the number of divergence lines/labels to prevent chart clutter.
#### Display Settings
- **Show Lines (Indicator Pane)** (Default: True): Draws divergence lines on the MB line in the indicator pane.
- **Show Labels (Indicator Pane)** (Default: True): Adds labels (e.g., "L" for line divergence) at divergence points in the pane.
- **Show Hist Divergence Lines** (Default: True): Draws dashed lines for MACD Histogram divergences in the pane.
- **Show Hist Divergence Labels** (Default: True): Adds labels (e.g., "H" for histogram divergence) in the pane.
- **Sync Lines to Main Chart (Overlay)** (Default: True): Mirrors divergence lines and labels onto the main price chart for context (slightly offset for visibility).
#### Filters & Tolerance
- **Peak Alignment Tolerance (Bars)** (Default: 5, Min: 0): Allows flexibility in matching oscillator peaks/valleys to price pivots (e.g., within ±5 bars).
- **Max Divergence Distance (Bars)** (Default: 20, Min: 5): Maximum bars between two pivots for a valid divergence; prevents detecting overly distant signals.
- **Enable Momentum Decay Filter** (Default: True): For Histogram divergences, requires the current peak/valley to have a smaller absolute value than the previous (indicating convergence/decay).
- **Enable Zero-Side Filter** (Default: False): Ensures both peaks/valleys in a divergence are on the same side of the zero line (e.g., both positive or both negative).
#### MACD Settings
- **MACD Fast Length** (Default: 12): Fast EMA length for MACD.
- **MACD Slow Length** (Default: 26): Slow EMA length for MACD.
- **MACD Signal Length** (Default: 9): Smoothing length for the MACD signal line.
- **MACD Source Smoothing** (Default: 3, Min: 1): Additional SMA smoothing applied to the MB Ratio before MACD calculation.
### How It Works
1. **MB Ratio Calculation**: For each bar, the script computes the position of the close within the high-low range (0-1). This scales the volume into "buy" and "sell" portions, then derives a net ratio (-100% to +100%). It's smoothed via SMA for the final MB line.
2. **MACD Application**: The (optionally smoothed) raw MB is used as the MACD source, producing a MACD line, signal line, and histogram.
3. **Pivot Detection**: Uses Pine's `ta.pivothigh`/`ta.pivotlow` to find price highs/lows over the lookback period.
4. **Divergence Scanning**:
- **Bearish (on Highs)**: Price makes a higher high, but MB/Hist makes a lower high.
- **Bullish (on Lows)**: Price makes a lower low, but MB/Hist makes a higher low (closer to zero).
- Scans nearby bars for oscillator matches and applies filters.
5. **Rendering**: Lines/labels are drawn in the indicator pane or overlaid on the chart. Colors: Teal for bullish, Pink/Maroon for bearish.
6. **Cleanup**: Automatically removes old lines/labels to stay under the max limit.
### Interpreting the Outputs
- **MB Line (Columns)**: Positive (teal) indicates net buying pressure; negative (pink) shows selling. Watch for crossovers above/below zero as momentum shifts.
- **MACD Histogram (Area)**: Green/teal for positive momentum; red/maroon for negative. Widening bars suggest strengthening trends; narrowing indicates weakening.
- **Divergence Lines/Labels**:
- Solid lines: MB line divergences (thicker, labeled "L").
- Dashed lines: Histogram divergences (thinner, labeled "H").
- Bullish: Teal lines sloping up (potential bottom reversal).
- Bearish: Pink lines sloping down (potential top reversal).
- **Overlay on Chart**: Lines connect price pivots (or offset slightly for Histogram). Use this to visualize how divergences align with candlesticks.
- **Zero Line**: Gray horizontal line; divergences filtered by side if enabled.
**Example Usage**:
- On a daily stock chart, enable overlays and watch for a bullish "L" or "H" label near a price low—could signal a buy if confirmed by volume breakout.
- In a downtrend, bearish divergences on highs might warn of further downside.
### Alerts
- **Bullish Divergence (L or H)**: Triggers on any detected bullish divergence (MB or Histogram).
- **Bearish Divergence (L or H)**: Triggers on bearish divergences.
- Set up via TradingView's alert menu: Select the indicator, choose the condition, and customize the message (e.g., includes ticker).
### Troubleshooting / Known Issues
- **No Divergences Shown**: Increase "Peak Alignment Tolerance" or reduce filters. Ensure pivot length suits your timeframe (shorter for intraday).
- **Too Many Lines/Labels**: Lower "Max Lines Kept" or increase "Max Divergence Distance" to filter distant signals.
- **Performance on Low-Volume Symbols**: MB Ratio may be unreliable; test on high-volume assets first.
- **Rendering Errors**: If lines don't appear, check chart zoom or ensure "force_overlay=true" isn't conflicting with other indicators.
- **NaN/Undefined Values**: Rare on live data but possible in historical backtests; report with symbol/timeframe for fixes.
### Feedback and Contributions
This script is open for community improvement! If you find bugs (e.g., false positives in divergences, calculation edge cases, or UI glitches), or have suggestions (like additional filters or visualizations), please share in the comments. Your feedback helps make it better—let's debug and enhance it together!
CVD-MACD### CVD-MACD (Research)
The CVD-MACD is a research-oriented indicator that combines Cumulative Volume Delta (CVD) with the classic MACD framework to provide insights into market momentum and potential reversals. Unlike a standard MACD based on price, this version uses CVD (the running total of buy vs. sell volume delta) as its input source, offering a volume-driven perspective on trend strength and divergences.
Key Features:
- **CVD-Based MACD Calculation**: Computes MACD using CVD instead of price, highlighting volume imbalances that may precede price moves.
- **Dual Divergence Detection**: Identifies bullish/bearish divergences on both the MACD line and histogram, with configurable pivot lookbacks and filters (e.g., momentum decay and zero-side consistency).
- **Visual Flexibility**: Toggle divergences in the indicator pane or overlaid on the main chart, with optional raw CVD line for reference.
- **Alerts**: Built-in conditions for bullish and bearish divergences to notify users of potential setups.
###This indicator is designed for research and experimentation—it's not financial advice. It performs best on liquid assets with reliable volume data (e.g., stocks, futures). I've shared this to gather community feedback: please test it thoroughly and point out any bugs, inefficiencies, or improvements! For example, if you spot issues with divergence detection on certain timeframes or symbols, let me know in the comments. Your input will help refine it.
Inspired by volume analysis techniques; open to collaborations or forks.
## User Manual for CVD-MACD (Research)
### Overview
The CVD-MACD indicator transforms traditional MACD by using Cumulative Volume Delta (CVD) as the base input. CVD accumulates the net delta between estimated buy and sell volume per bar, providing a volume-centric view of momentum. The indicator plots a MACD line, signal line, and histogram, while also detecting divergences on both the MACD line and histogram for potential reversal signals.
This manual covers setup, interpretation, and troubleshooting.
Note: This is a research tool—backtest and validate on your own data before using in live trading.
### Installation and Setup
1. **Add to Chart**: Search for "CVD-MACD (Research)" in TradingView's indicator library or paste the script into the Pine Editor and add it to your chart.
2. **Compatibility**: Works on any timeframe and symbol with volume data. Best on daily/intraday charts for stocks, forex, or futures. Avoid illiquid symbols where volume may be unreliable.
3. **Customization**: All inputs are configurable via the indicator's settings panel. Defaults are optimized for general use but can be tuned based on asset volatility.
### Input Parameters
The inputs are grouped for ease of use:
#### MACD Settings
- **Fast EMA (CVD)** (default: 12): Length of the fast EMA applied to CVD. Shorter values make it more responsive to recent volume changes.
- **Slow EMA (CVD)** (default: 26): Length of the slow EMA on CVD. Longer values smooth out noise for trend identification.
- **Signal EMA** (default: 9): Smoothing period for the signal line (EMA of the MACD line).
#### Divergence Logic (MACD Line)
- **Pivot Lookback (MACD Line)** (default: 5): Bars to look left/right for detecting pivots on the MACD line. Higher values detect larger swings but may miss smaller divergences.
- **Max Lookback Range (MACD Line)** (default: 50): Maximum bars between two pivots to consider a divergence valid. Prevents detecting outdated signals.
- **Enable Momentum Decay Filter (Histogram)** (default: false): When enabled, requires the histogram to show decaying momentum (absolute value decreasing) for MACD-line divergences to trigger.
#### Histogram Divergence
- **Pivot Lookback (Histogram)** (default: 5): Similar to above, but for histogram pivots.
- **Max Lookback Range (Histogram)** (default: 50): Max bars for histogram divergence detection.
- **Show Histogram Divergences in Indicator Pane** (default: true): Displays dashed lines and "H" labels for histogram divergences in the sub-window.
- **Show Histogram Divergences on Main Chart** (default: true): Overlays histogram divergences on the price chart with semi-transparent lines and labels.
- **Require Histogram to Stay on Same Side of Zero** (default: true): Filters divergences to only those where the histogram doesn't cross zero between pivots, ensuring consistent momentum direction.
#### Visuals (Dual View)
- **Show MACD-Line Divergences (Indicator Pane)** (default: true): Draws solid lines and "L" labels for MACD-line divergences in the sub-window.
- **Show MACD-Line Divergences (Main Chart)** (default: true): Overlays MACD-line divergences on the price chart.
- **Show Raw CVD Line** (default: false): Plots the underlying CVD as a faint gray line for reference.
### How to Interpret the Indicator
1. **Core Plots**:
- **MACD Line** (blue): Difference between fast and slow CVD EMAs. Above zero indicates building buy volume momentum; below zero shows sell dominance.
- **Signal Line** (orange): EMA of the MACD line. Crossovers can signal potential entries/exits (e.g., MACD above signal = bullish).
- **Histogram** (columns): MACD minus signal. Green shades for positive/expanding bars (bullish momentum); red for negative/contracting (bearish). Fading colors indicate weakening momentum.
- **Zero Line** (gray horizontal): Reference for bullish (above) vs. bearish (below) territory.
- **Raw CVD** (optional gray line): The cumulative buy-sell delta. Rising = net buying; falling = net selling.
2. **Divergences**:
- **Bullish (Green Lines/Labels)**: Occur when price makes lower lows, but MACD line or histogram makes higher lows. Suggests weakening downside momentum and potential reversal up. Look for "L" (MACD line) or "H" (histogram) labels.
- **Bearish (Red Lines/Labels)**: Price higher highs vs. MACD/histogram lower highs. Indicates fading upside and possible downturn.
- **Dual View**: Divergences appear in the indicator pane (sub-window) for clean analysis and overlaid on the main chart for price context. Histogram divergences use dashed lines to distinguish from MACD-line (solid).
- **Filters**: Momentum decay ensures only "hidden" or weakening divergences trigger. Zero-side filter prevents false signals from oscillating histograms.
3. **Alerts**:
- **Bullish Divergence (L or H)**: Triggers on either MACD-line or histogram bullish divergence. Message: "CVD-MACD Bullish Divergence detected on {{ticker}}".
- **Bearish Divergence (L or H)**: Similar for bearish. Use TradingView's alert setup to notify via email/SMS/webhook.
- Tip: Combine with price action (e.g., support/resistance) for confirmation.
### Usage Tips and Strategies
- **Trend Confirmation**: Use in uptrends for bullish divergences (pullback buys) or downtrends for bearish (short entries).
- **Timeframe Selection**: Higher timeframes (e.g., daily) for swing trading; lower (e.g., 15-min) for intraday. Adjust pivot lookbacks accordingly (shorter for faster charts).
- **Combination Ideas**: Pair with RSI for overbought/oversold confirmation or VWAP for intraday volume context.
- **Risk Management**: Divergences are probabilistic—not guarantees. Always use stop-losses based on recent swings.
- **Performance Notes**: Backtest on historical data via TradingView's Strategy Tester. CVD relies on accurate volume; test on exchanges like NYSE/NASDAQ.
### Known Limitations and Troubleshooting
- **Volume Dependency**: CVD estimation assumes linear buy/sell distribution based on bar position—may be less accurate on thin markets or during gaps.
- **Repainting**: Pivots and divergences can repaint as new data arrives (common in pivot-based indicators). Use on closed bars for reliability.
- **Resource Usage**: High max_bars_back (5000) ensures deep history; reduce if chart loads slowly.
- **No Signals on Low-Volume Bars**: If CVD flatlines, check symbol volume—some crypto/forex pairs have inconsistent data.
- **Community Feedback**: If you encounter bugs (e.g., false divergences on specific symbols/timeframes), missing alerts, or calculation errors, please comment below with details like symbol, timeframe, and screenshots. Suggestions for enhancements (e.g., more filters or visuals) are welcome!
If you have questions or find issues, drop a comment—let's improve this together!
Gold Pin Bar Pivot Alerts - FixedThis script is designed for the high volatility of Gold (XAU/USD). It identifies Pin Bars with body less than 30% of the candle's total range, and the candle occuring at a structural Pivot High or Pivot Low
Gtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingviewtradingview






















