I need you to create a kScript v2 trading indicator. kScript v2 uses a PER-BAR EXECUTION MODEL that automatically handles time series creation.

CRITICAL kScript v2 CONCEPTS:

EXECUTION MODEL:
- Code runs automatically for EVERY bar in the dataset
- Three phases: Initialization (once) → Calculation (per bar) → Plotting (per bar)
- ALWAYS start with //@version=2

VARIABLE SYSTEM - TWO TYPES ONLY:

**timeseries**: Immutable, historical data with bracket notation access
- MUST be declared in GLOBAL SCOPE ONLY
- Access: [0] = current bar, [1] = previous bar, [n] = n bars ago
- Declaration: `timeseries varName = ...`

**var**: Ephemeral per-bar variables
- Can be declared anywhere (global, inside if/for/while, inside func)
- NO historical access (no var[1])
- Recalculated each bar
- Declaration: `var varName = ...`

MANDATORY STRUCTURE:
```javascript
//@version=2
define("Name", "onchart"|"offchart", showAxis);  // or kwargs: define(title="Name", position="offchart", axis=true)
var inputs = input("key", "type", defaultValue, "label");  // or kwargs: input(name="key", type="type", defaultValue=val, label="Label")
timeseries data = ohlcv(currentSymbol, currentExchange);  // or source("ohlcv", currentSymbol, currentExchange)
// calculations
plotLine(data, ["color"], width);  // positional or kwargs depending on function
```

FUNCTION PARAMETER STYLES:
- define() accepts BOTH positional and kwargs: define(title=..., position=..., axis=..., customTitle=...)
- input() accepts BOTH positional and kwargs: input(name=..., type=..., defaultValue=..., label=...)
- source() and data functions typically use positional
- Indicator functions may use either style - check documentation

USER-DEFINED FUNCTIONS (func keyword):
CRITICAL CONSTRAINTS:
- CANNOT accept timeseries as parameters - ONLY value types (number, string, boolean, color)
- MUST access timeseries from global scope directly
- CANNOT declare new timeseries inside function body
- MUST be declared in global scope
- MUST have explicit return statement

CORRECT:
```javascript
timeseries closePrice = ohlcvData.close;  // Global
timeseries rsiValue = rsi(closePrice, 14);  // Global

func detectDivergence(lookback) {  // Only value parameter
    // Access global timeseries directly
    var priceRising = closePrice[0] > closePrice[lookback];
    var rsiRising = rsiValue[0] > rsiValue[lookback];
    return priceRising && !rsiRising;
}

var divergence = detectDivergence(5);  // Pass only value
```

WRONG:
```javascript
func detectDivergence(priceTS, rsiTS, lookback) {  // CANNOT pass timeseries
    var priceRising = priceTS[0] > priceTS[lookback];
    var rsiRising = rsiTS[0] > rsiTS[lookback];
    return priceRising && !rsiRising;
}
var divergence = detectDivergence(closePrice, rsiValue, 5);  // WRONG
```

DATA SOURCES WITH FIELD ACCESS:
- ohlcv(): Fields: .open, .high, .low, .close, .volume
- buy_sell_volume(): Fields: .buy, .sell
- liquidations(): Fields: .buy, .sell
- open_interest(): Fields: .open, .high, .low, .close
- funding_rate(): Single value (no fields)
- orderbook(): Use with orderbook functions

Example:
```javascript
timeseries ohlcvData = ohlcv(currentSymbol, currentExchange);
timeseries closePrice = ohlcvData.close;  // Field access
timeseries volume = ohlcvData.volume;
```

CONTROL FLOW:
```javascript
for (var i = 0; i < 10; i = i + 1) {  // Must use i = i + 1, not i++
    // loop body
}
while (condition) {
    // loop body
}
if (condition) { 
    // true branch
} else { 
    // false branch
}
```

COMPLETE FUNCTION REFERENCE:

**Script Definition:**
- define(title, position, axis, customTitle?, format?) OR define(title="...", position="...", axis=true, customTitle="...", format="...")
  - position: "onchart" or "offchart"
  - axis: boolean for independent Y-axis
  - format: "price" | "abbreviated" | "percentage" (optional)
    - "price" (default): shows raw values without abbreviation
    - "abbreviated": uses K/M/B notation (e.g., 10M for 10,000,000)
    - "percentage": adds % symbol after values

- input(name, type, defaultValue?, label?, constraints?) OR input(name="...", type="...", defaultValue=..., label="...")
  - type: "number", "boolean", "color", "string", "select"

- source(dataType, symbol, exchange) - returns TimeSeries
- print(message) - debug output

**Data Sources (return TimeSeries):**
- ohlcv(symbol, exchange)
- orderbook(symbol, exchange)
- buy_sell_volume(symbol, exchange)
- funding_rate(symbol, exchange)
- liquidations(symbol, exchange)
- open_interest(symbol, exchange)

**Moving Averages:**
- sma(series, period, priceIndex?) → number
- ema(series, period, priceIndex?) → number

**Oscillators:**
- rsi(source, period, priceIndex?) → TimeSeries (0-100)
- cci(series, period?, constant?) → number
- stochastic(series, kPeriod?, kSmoothing?, dPeriod?) → [K, D]

**Trend Indicators:**
- adx(series, period?) → [ADX, DI+, DI-]
- ichimoku(series, conversionPeriod?, basePeriod?, laggingSpanPeriod?, displacement?) → [Tenkan, Kijun, SpanA, SpanB, Chikou]
- macd(series, fastPeriod?, slowPeriod?, signalPeriod?) → [MACD, Signal, Histogram]
- psar(series, start?, increment?, maxValue?) → number

**Volume Indicators:**
- mfi(series, period?) → number (0-100)
- obv(series) → number

**Utilities:**
- lowest(series, priceIndex, length) → number
- highest(series, priceIndex, length) → number
- sum(series, priceIndex, period) → number
- stddev(series, priceIndex, period, mean?) → number
- donchian(series, period?) → number
- crossover(seriesA, seriesB) → boolean
- crossunder(seriesA, seriesB) → boolean
- cross(seriesA, seriesB) → boolean

**Orderbook Functions (all return numbers):**
- sumBids(series, depthPct?)
- sumAsks(series, depthPct?)
- maxBidAmount(series, depthPct?)
- maxAskAmount(series, depthPct?)
- minBidAmount(series, depthPct?)
- minAskAmount(series, depthPct?)

**Plotting:**
- plotLine(series, colors, width, fill?, smooth?, lineStyle?, glow?)
  - lineStyle: "solid" (default) | "dashed" | "dotted"
  - glow: boolean | number — soft halo around the stroke. true = default blur in series color; number = blur radius in px (clamped 0–30, 0 disables)
- plotBar(series, colors, width, glow?)
- plotCandle(series, colors, width, glow?)
- plotShape(series, shape, colors, width, fill?, glow?, opacity?)
  - shape: "circle", "triangle", "cross", "diamond"
- plotPriceLabel(price, text?, type?, position?, tooltip?, svgPath?, url?, iconSize?, anchorX?, anchorY?, color?, backgroundColor?, fontFamily?, fontWeight?, size?, opacity?)
  - Renders a per-bar label anchored at a price level.
  - type: "callout" (default, text box + leader line + dot) | "simple" (centered text box) | "icon-only" (SVG path or image; requires svgPath or url)
  - position: "left" | "center" (default) | "right" — horizontal placement relative to the bar
  - tooltip: hover string; use "\n" for line breaks
  - svgPath: SVG path "d" attribute for icon-only rendering (Path2D — only path commands)
  - url: image URL for icon-only — supports static images and animated GIF / WebP, so labels can render looping or animated icons
  - iconSize: CSS px (clamped 4–128, default 16)
  - anchorX/anchorY: anchor of icon relative to its (x, y) point
  - color/backgroundColor/fontFamily/fontWeight/size/opacity: text styling (size clamped 1–30, fontWeight 100–800, opacity 0–1)

**Math Namespace:**
- math.abs(value), math.max(a, b), math.min(a, b), math.sqrt(value)
- math.pow(base, exponent), math.round(value), math.floor(value), math.ceil(value)
- math.sin(value), math.cos(value), math.tan(value)
- math.log(value), math.exp(value)
- Constants: math.PI, math.E, math.SQRT2, math.LN2, math.LN10

COLOR CONSTANTS:
"red", "green", "blue", "yellow", "orange", "purple", "gray", "black", "white",
"silver", "maroon", "fuchsia", "lime", "olive", "navy", "teal", "aqua"
Or hex: "#FF0000", "#00FF00", "#0000FF", etc.

CRITICAL RETURN TYPE DISTINCTIONS:

Functions returning TimeSeries (use 'timeseries' declaration):
- ohlcv(), orderbook(), buy_sell_volume(), etc. (data sources)


Functions returning numbers (use 'var' declaration):
- rsi(source, period) → number
- sma(series, period, priceIndex) → number
- ema(series, period, priceIndex) → number
- cci(series, period, constant) → number
- All orderbook functions (sumBids, sumAsks, etc.) → number
- All utility functions (lowest, highest, sum, etc.) → number
- crossover(), crossunder() → boolean

Functions returning arrays (use 'var' declaration):
- stochastic() → [K, D]
- adx() → [ADX, DI+, DI-]
- macd() → [MACD, Signal, Histogram]
- ichimoku() → [5 values]

CRITICAL PITFALLS TO AVOID:
- NEVER pass timeseries as function parameters - access from global scope only
- NEVER declare timeseries inside functions, loops, or conditionals - global only
- NEVER use var[1] - var has no historical access
- ALWAYS declare timeseries before functions that use them
- ALWAYS return a value from func definitions
- NEVER declare variables without immediate assignment
- For loops MUST use i = i + 1 syntax (not i++)
- Functions can ONLY accept value types: number, string, boolean, color
- Order matters: declare timeseries before functions that reference them

CORRECT COMPLETE EXAMPLE:
```javascript
//@version=2

// 1. Definition (positional or kwargs)
define("MACD with Volume", "offchart", true);
// OR: define(title="MACD with Volume", position="offchart", axis=true);

// 2. Inputs (positional or kwargs)
var fastPeriod = input("fast", "number", 12, "Fast Period");
var slowPeriod = input("slow", "number", 26, "Slow Period");
var signalPeriod = input("signal", "number", 9, "Signal Period");
var showHistogram = input("histogram", "boolean", true, "Show Histogram");
// OR: var fastPeriod = input(name="fast", type="number", defaultValue=12, label="Fast Period");

// 3. Data sources - MUST be global timeseries
timeseries ohlcvData = ohlcv(currentSymbol, currentExchange);
timeseries closePrice = ohlcvData.close;
timeseries volume = ohlcvData.volume;

// 4. Indicator calculations
var macdValues = macd(ohlcvData, fastPeriod, slowPeriod, signalPeriod);
timeseries smaVolume = sma(volume, 20);

// 5. Functions - access global timeseries, accept only values
func isHighVolume(threshold) {
    // Access volume from global scope
    return volume[0] > smaVolume[0] * threshold;
}

func detectCrossover() {
    // Access macdValues from global scope
    // Assuming macdValues returns [macd, signal, histogram]
    return macdValues[0] > macdValues[1] && macdValues[0] < macdValues[1];
}

// 6. Per-bar calculations
var volumeSpike = isHighVolume(1.5);
var bullishCross = detectCrossover();

// 7. Plotting
plotLine(macdValues, ["blue", "red"], 2);

if (showHistogram) {
    plotBar(macdValues, ["green", "red"], 1);
}

if (volumeSpike && bullishCross) {
    plotShape(macdValues, "circle", ["yellow"], 3, true);
}

// 8. Debug
print("MACD Value: " + macdValues[0]);
```

Please create a kScript v2 indicator with the following requirements:

**Indicator name and purpose:**
[User fills in: e.g., "RSI Divergence Scanner" - detects price/RSI divergences]

**Required data sources:**
[User fills in: e.g., OHLCV data, orderbook data, funding rates, etc.]

**Desired calculations/signals:**
[User fills in: e.g., Calculate 14-period RSI, detect when price makes new high but RSI doesn't]

**Visual requirements:**
[User fills in: e.g., Purple line for RSI, red/green horizontal lines at 70/30, yellow circles for divergences]

**Any specific conditions or alerts:**
[User fills in: e.g., Mark divergences only when RSI is above 70 or below 30]

Create syntactically correct kScript v2 code following all rules above. Ensure:
- All timeseries are declared globally before any functions
- Functions only accept value parameters, not timeseries
- Use proper field access (.close, .volume, etc.)
- Include appropriate input parameters for user customization
- Add clear comments explaining the logic