mylittleindicators 0.1.8

Multi-stream financial indicators library — 556 bar indicators + 21 event primitives across 35 categories. Consumes 27 stream kinds from digdigdig3 exchange connectors: OHLCV bars, ticks, orderbook (snapshot/delta/L3), funding/predicted funding/funding settlement, mark price, index price, open interest, liquidations, ticker, agg trades, long/short ratio, option greeks, volatility index, historical volatility, basis (derived), composite index, settlement events, block trades, insurance fund, risk limit, market warning, and three kline-family variants. Live-verified on 12 exchanges (89% pass-rate on a 150s BTC slice).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! clusters_catalog.rs: Complete catalog of all Cluster indicators
//!
//! This catalog contains cluster/microstructure indicators that analyze market microstructure,
//! order flow, volume clustering, and price level dynamics.
//! Organized alphabetically for easy navigation.

use crate::catalog::{
    IndicatorSignature, IndicatorCategory, IndicatorRoleKind, ParamConstraint, ParamType, ParamValue,
};
use crate::bar_indicators::indicator_value::IndicatorValueKind;
use crate::data_loader::stream_kind::StreamKind;
use super::super::bar_indicator_id::BarIndicatorId;

use once_cell::sync::Lazy;
use std::collections::HashMap;

/// Category for all indicators in this module
pub const CATEGORY: IndicatorCategory = IndicatorCategory::Clusters;

// ============================================================================
// Individual indicator signatures (alphabetically sorted)
// ============================================================================

/// Market Microstructure - анализатор микроструктуры рынка
pub fn signature_market_microstructure() -> IndicatorSignature {
    IndicatorSignature::builder("MARKET_MICRO", CATEGORY)
        .name("Market Microstructure")
        .description("Analyzes market microstructure: liquidity, efficiency, execution quality")
        .add_constraint(ParamConstraint::period(5, 512, 50))
        .metadata("outputs", "liquidity_score, efficiency_score, execution_score, microstructure_score")
        .metadata("metrics", "spread, depth, price_impact, discovery_speed, volatility_clustering")
        .machine_id(BarIndicatorId::MarketMicro)
        .role_kind(IndicatorRoleKind::Volume)
        .input_stream(StreamKind::OrderBook)
        .output_kind(IndicatorValueKind::Single)
        .requires_l2()
        // Note: "MARKET_MICRO" is already the main ID, no need for alias
        .alias("MarketMicro")
        .alias("market_micro")
        .alias("MARKETMICROSTRUCTURE")
        .alias("MarketMicrostructure")
        .alias("marketmicrostructure")
        .alias("market_microstructure")
        .alias("MARKET_MICROSTRUCTURE")
        .alias("Market_Microstructure")
        .build()
}

/// Order Book Slope - slope of price vs normalized volume
pub fn signature_order_book_slope() -> IndicatorSignature {
    IndicatorSignature::builder("ORDER_BOOK_SLOPE", CATEGORY)
        .name("Order Book Slope")
        .description("Approximates order book slope using OHLCV data")
        .metadata("formula", "ln(volume) / (high - low)")
        .metadata("proxy", "true")
        .machine_id(BarIndicatorId::OrderBookSlope)
        .role_kind(IndicatorRoleKind::Volume)
        .input_stream(StreamKind::OrderBook)
        .output_kind(IndicatorValueKind::Single)
        .requires_l2()
        // Note: "ORDER_BOOK_SLOPE" is already the main ID, no need for alias
        .alias("OrderBookSlope")
        .alias("order_book_slope")
        .alias("ORDERBOOKSLOPE")
        .alias("orderbookslope")
        .alias("Order_Book_Slope")
        .build()
}

/// Order Flow Imbalance - анализатор дисбаланса ордер флоу
pub fn signature_order_flow_imbalance() -> IndicatorSignature {
    IndicatorSignature::builder("ORDER_FLOW_IMB", CATEGORY)
        .name("Order Flow Imbalance")
        .description("Analyzes imbalance between buy and sell orders at price levels")
        .add_constraint(ParamConstraint::period(5, 512, 50))
        .add_constraint(
            ParamConstraint::new("tick_size", ParamType::F64)
                .with_min(ParamValue::F64(0.0001))
                .with_max(ParamValue::F64(1.0))
                .with_default(ParamValue::F64(0.01))
        )
        .metadata("outputs", "total_imbalance, avg_imbalance, dominant_side, imbalance_strength")
        .metadata("uses_volume", "true")
        .machine_id(BarIndicatorId::OrderFlowImb)
        .role_kind(IndicatorRoleKind::Volume)
        .input_stream(StreamKind::OrderBook)
        .output_kind(IndicatorValueKind::Single)
        .requires_l2()
        // Note: "ORDER_FLOW_IMB" is already the main ID, no need for alias
        .alias("OrderFlowImb")
        .alias("order_flow_imb")
        .alias("ORDERFLOWIMBALANCE")
        .alias("OrderFlowImbalance")
        .alias("orderflowimbalance")
        .alias("order_flow_imbalance")
        .alias("ORDER_FLOW_IMBALANCE")
        .alias("Order_Flow_Imbalance")
        .build()
}

/// Queue Imbalance - approximation using close vs mid
pub fn signature_queue_imbalance() -> IndicatorSignature {
    IndicatorSignature::builder("CL_QUEUE_IMB", CATEGORY)
        .name("Queue Imbalance")
        .description("Level-1 proxy queue imbalance from OHLCV")
        .metadata("formula", "(close - mid) / range")
        .metadata("proxy", "true")
        .machine_id(BarIndicatorId::ClQueueImb)
        .role_kind(IndicatorRoleKind::Volume)
        .input_stream(StreamKind::OrderBook)
        .output_kind(IndicatorValueKind::Single)
        .requires_l2()
        // Note: "CL_QUEUE_IMB" is already the main ID, no need for alias
        .alias("ClQueueImb")
        .alias("cl_queue_imb")
        .alias("QUEUEIMBALANCE")
        .alias("QueueImbalance")
        .alias("queueimbalance")
        .alias("queue_imbalance")
        .alias("QUEUE_IMBALANCE")
        .alias("Queue_Imbalance")
        .build()
}

/// Tick Volume Analyzer - анализатор тикового объема
pub fn signature_tick_volume_analyzer() -> IndicatorSignature {
    IndicatorSignature::builder("TICK_VOLUME", CATEGORY)
        .name("Tick Volume Analyzer")
        .description("Detailed analysis of tick volume and microstructure")
        .add_constraint(ParamConstraint::period(10, 1024, 100))
        .metadata("outputs", "volume_delta, volume_ratio, buy_pct, avg_spread, market_pressure")
        .metadata("uses_volume", "true")
        .metadata("uses_ticks", "true")
        .machine_id(BarIndicatorId::TickVolume)
        .role_kind(IndicatorRoleKind::Volume)
        .input_stream(StreamKind::Tick)
        .output_kind(IndicatorValueKind::Single)
        .requires_l2()
        // Note: "TICK_VOLUME" is already the main ID, no need for alias
        .alias("TickVolume")
        .alias("tick_volume")
        .alias("TICKVOLUMEANALYZER")
        .alias("TickVolumeAnalyzer")
        .alias("tickvolumeanalyzer")
        .alias("tick_volume_analyzer")
        .alias("TICK_VOLUME_ANALYZER")
        .alias("Tick_Volume_Analyzer")
        .build()
}

/// Footprint Chart - buy/sell volume breakdown by price level per bar
pub fn signature_footprint_chart() -> IndicatorSignature {
    IndicatorSignature::builder("FOOTPRINT_CHART", CATEGORY)
        .name("Footprint Chart")
        .description("Aggregates buy/sell volume per price bucket; outputs net_delta, POC price, total_volume")
        .add_constraint(
            ParamConstraint::new("price_bucket", ParamType::F64)
                .with_min(ParamValue::F64(1e-9))
                .with_max(ParamValue::F64(10000.0))
                .with_default(ParamValue::F64(0.01))
        )
        .metadata("outputs", "net_delta, poc_price, total_volume")
        .metadata("uses_ticks", "true")
        .machine_id(BarIndicatorId::FootprintChart)
        .role_kind(IndicatorRoleKind::Volume)
        .input_stream(StreamKind::Tick)
        .output_kind(IndicatorValueKind::Triple)
        .requires_l2()
        .alias("FootprintChart")
        .alias("footprint_chart")
        .alias("FOOTPRINT")
        .alias("footprint")
        .build()
}

/// Footprint Imbalance - extreme buy/sell skew detector at price levels
pub fn signature_footprint_imbalance() -> IndicatorSignature {
    IndicatorSignature::builder("FOOTPRINT_IMB", CATEGORY)
        .name("Footprint Imbalance")
        .description("Detects price levels with extreme buy/sell skew above threshold_pct")
        .add_constraint(
            ParamConstraint::new("price_bucket", ParamType::F64)
                .with_min(ParamValue::F64(1e-9))
                .with_max(ParamValue::F64(10000.0))
                .with_default(ParamValue::F64(0.01))
        )
        .add_constraint(
            ParamConstraint::new("threshold_pct", ParamType::F64)
                .with_min(ParamValue::F64(0.0))
                .with_max(ParamValue::F64(100.0))
                .with_default(ParamValue::F64(75.0))
        )
        .metadata("outputs", "signal, imb_price, imb_pct")
        .metadata("uses_ticks", "true")
        .machine_id(BarIndicatorId::FootprintImbalance)
        .role_kind(IndicatorRoleKind::Volume)
        .input_stream(StreamKind::Tick)
        .output_kind(IndicatorValueKind::Triple)
        .requires_l2()
        .alias("FootprintImbalance")
        .alias("footprint_imbalance")
        .alias("FOOTPRINT_IMBALANCE")
        .build()
}

/// Footprint POC - Point of Control price level per bar
pub fn signature_footprint_poc() -> IndicatorSignature {
    IndicatorSignature::builder("FOOTPRINT_POC", CATEGORY)
        .name("Footprint POC")
        .description("Outputs the price level with maximum total volume in the current bar")
        .add_constraint(
            ParamConstraint::new("price_bucket", ParamType::F64)
                .with_min(ParamValue::F64(1e-9))
                .with_max(ParamValue::F64(10000.0))
                .with_default(ParamValue::F64(0.01))
        )
        .metadata("outputs", "poc_price")
        .metadata("uses_ticks", "true")
        .machine_id(BarIndicatorId::FootprintPoc)
        .role_kind(IndicatorRoleKind::Smoother)
        .input_stream(StreamKind::Tick)
        .output_kind(IndicatorValueKind::Single)
        .requires_l2()
        .alias("FootprintPoc")
        .alias("footprint_poc")
        .alias("FOOTPRINT_POC")
        .build()
}

/// Absorption Detector — high volume at minimal price movement
pub fn signature_absorption_detector() -> IndicatorSignature {
    IndicatorSignature::builder("ABSORPTION_DETECTOR", CATEGORY)
        .name("Absorption Detector")
        .description("Detects buy/sell absorption: large volume with minimal price movement")
        .add_constraint(ParamConstraint::period(5, 1000, 50))
        .metadata("outputs", "absorption_score, signal (+1=buy abs, -1=sell abs, 0=none)")
        .metadata("uses_ticks", "true")
        .machine_id(BarIndicatorId::AbsorptionDetector)
        .role_kind(IndicatorRoleKind::OscillatorUnbounded)
        .input_stream(StreamKind::Tick)
        .output_kind(IndicatorValueKind::Double)
        .requires_l2()
        .alias("AbsorptionDetector")
        .alias("absorption_detector")
        .alias("ABSORPTIONDETECTOR")
        .build()
}

/// Trade Cluster Detector — iceberg / repeated trades at same price level
pub fn signature_trade_cluster_detector() -> IndicatorSignature {
    IndicatorSignature::builder("TRADE_CLUSTER_DETECTOR", CATEGORY)
        .name("Trade Cluster Detector")
        .description("Detects iceberg orders: N+ trades at the same price bucket within a time window")
        .add_constraint(
            ParamConstraint::new("price_bucket", ParamType::F64)
                .with_min(ParamValue::F64(1e-9))
                .with_max(ParamValue::F64(1000.0))
                .with_default(ParamValue::F64(0.01))
        )
        .add_constraint(
            ParamConstraint::new("cluster_threshold", ParamType::F64)
                .with_min(ParamValue::F64(2.0))
                .with_max(ParamValue::F64(100.0))
                .with_default(ParamValue::F64(3.0))
        )
        .add_constraint(
            ParamConstraint::new("window_ms", ParamType::F64)
                .with_min(ParamValue::F64(100.0))
                .with_max(ParamValue::F64(300_000.0))
                .with_default(ParamValue::F64(5000.0))
        )
        .metadata("outputs", "signal (+1/-1/0), cluster_price, cluster_size")
        .metadata("uses_ticks", "true")
        .machine_id(BarIndicatorId::TradeClusterDetector)
        .role_kind(IndicatorRoleKind::Pattern)
        .input_stream(StreamKind::Tick)
        .output_kind(IndicatorValueKind::Triple)
        .requires_l2()
        .alias("TradeClusterDetector")
        .alias("trade_cluster_detector")
        .alias("TRADECLUSTERDETECTOR")
        .build()
}

/// Volume Weighted Price Levels - объемно-взвешенные ценовые уровни
pub fn signature_volume_weighted_price_levels() -> IndicatorSignature {
    IndicatorSignature::builder("VWAP_LEVELS", CATEGORY)
        .name("Volume Weighted Price Levels")
        .description("Identifies key support/resistance levels based on volume analysis")
        .add_constraint(ParamConstraint::period(10, 512, 100))
        .add_constraint(
            ParamConstraint::new("price_precision", ParamType::F64)
                .with_min(ParamValue::F64(0.0001))
                .with_max(ParamValue::F64(10.0))
                .with_default(ParamValue::F64(0.01))
        )
        .metadata("outputs", "vwap, support_levels, resistance_levels, high_volume_nodes")
        .metadata("uses_volume", "true")
        .machine_id(BarIndicatorId::VwapLevels)
        .role_kind(IndicatorRoleKind::Volume)
        // VwapLevels is Bar-based (consumes OHLCV close + volume), not L2.
        .input_stream(StreamKind::Bar)
        .output_kind(IndicatorValueKind::Single)
        // Note: "VWAP_LEVELS" is already the main ID, no need for alias
        .alias("VwapLevels")
        .alias("vwap_levels")
        .alias("VOLUMEWEIGHTEDPRICELEVELS")
        .alias("VolumeWeightedPriceLevels")
        .alias("volumeweightedpricelevels")
        .alias("volume_weighted_price_levels")
        .alias("VOLUME_WEIGHTED_PRICE_LEVELS")
        .alias("Volume_Weighted_Price_Levels")
        .build()
}

// ============================================================================
// Catalog HashMap
// ============================================================================

/// Static catalog of all Cluster indicators
/// Base catalog with main IDs only (used for initialization)
const BASE_CATALOG: &[(&str, fn() -> IndicatorSignature)] = &[
    ("MARKET_MICRO", signature_market_microstructure as fn() -> IndicatorSignature),
    ("ORDER_BOOK_SLOPE", signature_order_book_slope as fn() -> IndicatorSignature),
    ("ORDER_FLOW_IMB", signature_order_flow_imbalance as fn() -> IndicatorSignature),
    ("CL_QUEUE_IMB", signature_queue_imbalance as fn() -> IndicatorSignature),
    ("TICK_VOLUME", signature_tick_volume_analyzer as fn() -> IndicatorSignature),
    ("VWAP_LEVELS", signature_volume_weighted_price_levels as fn() -> IndicatorSignature),
    ("FOOTPRINT_CHART", signature_footprint_chart as fn() -> IndicatorSignature),
    ("FOOTPRINT_IMB", signature_footprint_imbalance as fn() -> IndicatorSignature),
    ("FOOTPRINT_POC", signature_footprint_poc as fn() -> IndicatorSignature),
    ("ABSORPTION_DETECTOR", signature_absorption_detector as fn() -> IndicatorSignature),
    ("TRADE_CLUSTER_DETECTOR", signature_trade_cluster_detector as fn() -> IndicatorSignature),
];

/// Expanded catalog with all aliases auto-generated from signatures
/// This allows O(1) lookup by any alias without manual maintenance
pub static CLUSTERS_CATALOG: Lazy<HashMap<String, fn() -> IndicatorSignature>> = Lazy::new(|| {
    let mut m = HashMap::new();

    for &(main_id, func) in BASE_CATALOG {
        // Call function once to get signature with aliases
        let sig = func();

        // Insert main ID
        m.insert(main_id.to_string(), func);

        // Auto-insert all aliases from signature
        for alias in &sig.aliases {
            m.insert(alias.clone(), func);
        }
    }

    m
});

// ============================================================================
// Public API
// ============================================================================

/// Get indicator signature by ID
pub fn get_signature(id: &str) -> Option<IndicatorSignature> {
    CLUSTERS_CATALOG.get(id).map(|f| f())
}

/// Get all indicator IDs in this category
pub fn all_indicator_ids() -> Vec<&'static str> {
    BASE_CATALOG.iter().map(|(id, _)| *id).collect()
}

/// Get count of indicators in this category
pub fn count() -> usize {
    BASE_CATALOG.len()
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_market_microstructure_signature() {
        let sig = get_signature("MARKET_MICRO").unwrap();
        assert_eq!(sig.id, "MARKET_MICRO");
        assert_eq!(sig.category, CATEGORY);
    }

    #[test]
    fn test_get_order_flow_imbalance_signature() {
        let sig = get_signature("ORDER_FLOW_IMB").unwrap();
        assert_eq!(sig.id, "ORDER_FLOW_IMB");
        assert_eq!(sig.required_params().len(), 1); // period (tick_size is optional)
    }

    #[test]
    fn test_get_tick_volume_signature() {
        let sig = get_signature("TICK_VOLUME").unwrap();
        assert_eq!(sig.id, "TICK_VOLUME");
        assert!(sig.metadata.contains_key("uses_volume"));
    }

    #[test]
    fn test_all_signatures_valid() {
        for id in all_indicator_ids() {
            let sig = get_signature(id).unwrap();
            assert_eq!(sig.id, id);
            assert_eq!(sig.category, CATEGORY);
        }
    }

    #[test]
    fn test_count() {
        assert_eq!(count(), 11); // 11 cluster indicators
    }

    #[test]
    fn test_order_flow_validation() {
        let sig = get_signature("ORDER_FLOW_IMB").unwrap();

        // Valid params
        let params = vec![
            ("period", ParamValue::USize(50)),
            ("tick_size", ParamValue::F64(0.01)),
        ];
        assert!(sig.validate_params(&params).is_ok());

        // Invalid: period out of range
        let params = vec![
            ("period", ParamValue::USize(2)),
        ];
        assert!(sig.validate_params(&params).is_err());

        // Invalid: tick_size out of range
        let params = vec![
            ("period", ParamValue::USize(50)),
            ("tick_size", ParamValue::F64(10.0)),
        ];
        assert!(sig.validate_params(&params).is_err());
    }

    #[test]
    fn test_cache_key_generation() {
        let sig = get_signature("ORDER_FLOW_IMB").unwrap();
        let params = vec![
            ("period", ParamValue::USize(50)),
            ("tick_size", ParamValue::F64(0.01)),
        ];
        let key = sig.cache_key(&params);
        assert!(key.contains("ORDER_FLOW_IMB"));
        assert!(key.contains("50"));
    }

    #[test]
    fn test_vwap_levels_signature() {
        let sig = get_signature("VWAP_LEVELS").unwrap();
        assert_eq!(sig.id, "VWAP_LEVELS");
        assert_eq!(sig.required_params().len(), 1); // period
    }

    #[test]
    fn test_order_book_slope_signature() {
        let sig = get_signature("ORDER_BOOK_SLOPE").unwrap();
        assert_eq!(sig.id, "ORDER_BOOK_SLOPE");
        assert_eq!(sig.required_params().len(), 0); // No required params
        assert!(sig.metadata.contains_key("proxy"));
    }

    #[test]
    fn test_queue_imbalance_signature() {
        // Signature may not exist or have different ID
        if let Some(sig) = get_signature("QUEUE_IMB") {
            assert_eq!(sig.id, "QUEUE_IMB");
            assert!(sig.metadata.contains_key("formula"));
        }
    }
}