Compare commits

..

4 Commits

Author SHA1 Message Date
kingchenc a93af60796 release: bump 0.5.2 -> 0.5.3 (#174)
Version bump publishing the **Fibonacci** family (10 tools across A5a + A5b, catalogue 377 indicators / twenty-four families):

`FibRetracement`, `FibExtension`, `FibProjection`, `AutoFib`, `GoldenPocket`, `FibConfluence`, `FibFan`, `FibArcs`, `FibChannel`, `FibTimeZones`.

Version strings + lockfiles only (Cargo.toml, pyproject.toml, package.json + 6 npm platform manifests, both package-lock.json, Cargo.lock); CHANGELOG `[0.5.3]` section + compare URLs.
2026-06-04 01:25:31 +02:00
kingchenc 5a1d607807 feat(indicators): A5b Fibonacci tools (geometric) (#172)
Completes the **Fibonacci** family with the four geometric/time tools (catalogue 373 -> 377). All extend the internal `pattern_swing` ZigZag tracker with a per-pivot bar index and a current-bar counter (additive — the chart/harmonic detectors are unaffected), and emit `Candle -> struct` outputs via custom Python/Node/WASM bindings.

| Tool | Output |
|------|--------|
| `FibFan` | three trendlines fanning from a swing start through its 38.2/50/61.8% retracement levels, extended to the current bar |
| `FibArcs` | semicircular retracement levels centred on the swing end, normalised by the leg's bar-width (chart-scale-free) |
| `FibChannel` | a sloped base trendline plus parallel lines at Fibonacci multiples of the channel width |
| `FibTimeZones` | markers at Fibonacci bar-distances (1/2/3/5/8/...) from the latest swing pivot |

The geometric tools are novel as streaming indicators; each normalises its geometry to the swing leg's bar-width so the output is chart-scale-free. Formulas are documented in each module and deep-dive.

Fully wired: core (100% unit-tested branches incl. the new `pattern_swing` bar tracking), Python/Node/WASM struct bindings, fuzz, reference + streaming-vs-batch tests.

Verification: `cargo test --workspace` green, clippy `-D warnings` clean, node 454 tests, python 768 tests.
2026-06-04 01:12:09 +02:00
kingchenc ea9da12d86 docs(governance): document continuity and succession plan (#173)
Add a Continuity and succession section to GOVERNANCE.md (trusted-contact emergency access to credentials enabling continuity within a week). Closes OpenSSF Silver access_continuity.
2026-06-04 01:09:52 +02:00
kingchenc 716eb40206 feat(indicators): A5a Fibonacci tools (price-level) (#171)
Adds the six price-level Fibonacci tools as a new **Fibonacci** family (catalogue 367 -> 373, twenty-four families). All build on the internal `pattern_swing` ZigZag tracker, are parameter-free (baked 5% swing threshold), and emit `Candle -> struct` outputs via custom Python/Node/WASM bindings.

| Tool | Output |
|------|--------|
| `FibRetracement` | seven levels (0/23.6/38.2/50/61.8/78.6/100%) of the last swing leg |
| `FibExtension` | five extension ratios (127.2/141.4/161.8/200/261.8%) projected beyond the leg |
| `FibProjection` | A-B-C measured-move target zone (61.8/100/161.8/261.8%) |
| `AutoFib` | retracement anchored on the dominant (largest-magnitude) recent leg |
| `GoldenPocket` | the 0.618-0.65 optimal-trade-entry band (low/mid/high) |
| `FibConfluence` | densest cluster of retracement levels across recent legs (price + strength) |

Fully wired: core (100% unit-tested branches), Python/Node/WASM struct bindings, fuzz driver, reference + streaming-vs-batch tests, README/docs counter. The four geometric/time tools (Fan, Arcs, Channel, Time Zones) follow in A5b.

Verification: `cargo test --workspace` green, clippy `-D warnings` clean, node 450 tests, python 760 tests.
2026-06-04 00:47:00 +02:00
38 changed files with 4435 additions and 70 deletions
+14 -1
View File
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.5.3] - 2026-06-04
- **Fibonacci Time Zones** — vertical markers at Fibonacci bar-distances (1/2/3/5/8/...) from the latest swing pivot (`FIB_TIME_ZONES`).
- **Fibonacci Channel** — a sloped base trendline plus parallel lines at Fibonacci multiples of the channel width (`FIB_CHANNEL`).
- **Fibonacci Arcs** — semicircular retracement levels centred on the swing end, normalised by leg bar-width (`FIB_ARCS`).
- **Fibonacci Fan** — three trendlines fanning from a swing start through its 38.2/50/61.8% retracement levels (`FIB_FAN`).
- **Fibonacci Confluence** — densest cluster of retracement levels across recent swing legs (price + strength) (`FIB_CONFLUENCE`).
- **Golden Pocket** — the 0.618-0.65 optimal-trade-entry band of the most recent swing leg (`GOLDEN_POCKET`).
- **Auto-Fibonacci** — retracement anchored on the dominant (largest-magnitude) leg among recent swings (`AUTO_FIB`).
- **Fibonacci Projection** — measured-move target zone from the last three pivots (A-B-C), projecting A->B from C (`FIB_PROJECTION`).
- **Fibonacci Extension** — projects the latest swing leg to the canonical extension ratios (127.2/141.4/161.8/200/261.8%) (`FIB_EXTENSION`).
- **Fibonacci Retracement** — seven retracement levels (0/23.6/38.2/50/61.8/78.6/100%) of the most recent confirmed swing leg (`FIB_RETRACEMENT`).
## [0.5.2] - 2026-06-03
### Added
@@ -1205,7 +1217,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
optional Binance live feed.
- Bindings for Python, Node.js, and WebAssembly.
[Unreleased]: https://github.com/wickra-lib/wickra/compare/v0.5.2...HEAD
[Unreleased]: https://github.com/wickra-lib/wickra/compare/v0.5.3...HEAD
[0.5.3]: https://github.com/wickra-lib/wickra/compare/v0.5.2...v0.5.3
[0.5.2]: https://github.com/wickra-lib/wickra/compare/v0.5.1...v0.5.2
[0.5.1]: https://github.com/wickra-lib/wickra/compare/v0.5.0...v0.5.1
[0.5.0]: https://github.com/wickra-lib/wickra/compare/v0.4.7...v0.5.0
Generated
+6 -6
View File
@@ -1867,7 +1867,7 @@ dependencies = [
[[package]]
name = "wickra"
version = "0.5.2"
version = "0.5.3"
dependencies = [
"approx",
"criterion",
@@ -1878,7 +1878,7 @@ dependencies = [
[[package]]
name = "wickra-core"
version = "0.5.2"
version = "0.5.3"
dependencies = [
"approx",
"proptest",
@@ -1888,7 +1888,7 @@ dependencies = [
[[package]]
name = "wickra-data"
version = "0.5.2"
version = "0.5.3"
dependencies = [
"approx",
"csv",
@@ -1915,7 +1915,7 @@ dependencies = [
[[package]]
name = "wickra-node"
version = "0.5.2"
version = "0.5.3"
dependencies = [
"napi",
"napi-build",
@@ -1925,7 +1925,7 @@ dependencies = [
[[package]]
name = "wickra-python"
version = "0.5.2"
version = "0.5.3"
dependencies = [
"numpy",
"pyo3",
@@ -1934,7 +1934,7 @@ dependencies = [
[[package]]
name = "wickra-wasm"
version = "0.5.2"
version = "0.5.3"
dependencies = [
"console_error_panic_hook",
"js-sys",
+2 -2
View File
@@ -12,7 +12,7 @@ members = [
exclude = ["fuzz"]
[workspace.package]
version = "0.5.2"
version = "0.5.3"
authors = ["kingchenc <support@wickra.org>"]
edition = "2021"
rust-version = "1.86"
@@ -24,7 +24,7 @@ keywords = ["finance", "trading", "indicators", "technical-analysis", "ta"]
categories = ["finance", "mathematics", "science"]
[workspace.dependencies]
wickra-core = { path = "crates/wickra-core", version = "0.5.2" }
wickra-core = { path = "crates/wickra-core", version = "0.5.3" }
thiserror = "2"
rayon = "1.10"
+21
View File
@@ -39,6 +39,27 @@ contributors who have demonstrated sustained, high-quality involvement, at the
current maintainer's discretion. If the project grows to multiple maintainers,
this document will be updated to describe shared decision-making.
## Continuity and succession
The project is designed to survive the loss of any single individual, so that
issues can be triaged, proposed changes accepted, and releases published within
one week of confirmed loss of the maintainer:
- **Credentials.** All credentials required to operate the project — the
`wickra-lib` GitHub organization, the publishing tokens for crates.io, PyPI
and npm, and the `wickra.org` domain registrar — are stored in a password
manager. A trusted contact (a family member) holds **emergency access** to
that password manager and can obtain these credentials if the maintainer can
no longer continue.
- **Continuity actions.** With that access, the trusted contact (or a delegate
they appoint) can create and close issues, accept pull requests, and publish
releases through the existing CI/CD workflows.
- **Account recovery.** The maintainer's GitHub account has recovery configured,
and ownership of the `wickra-lib` organization can be transferred to a new
maintainer.
- **Legal rights.** Legal rights to the project name and DNS are covered by the
maintainer's estate arrangements.
## Code of conduct
All participants are expected to follow the
+5 -4
View File
@@ -1,5 +1,5 @@
<p align="center">
<a href="https://wickra.org"><img src="https://raw.githubusercontent.com/wickra-lib/.github/main/profile/wickra-banner.webp?v=367" alt="Wickra — streaming-first technical indicators" width="100%"></a>
<a href="https://wickra.org"><img src="https://raw.githubusercontent.com/wickra-lib/.github/main/profile/wickra-banner.webp?v=377" alt="Wickra — streaming-first technical indicators" width="100%"></a>
</p>
[![CI](https://github.com/wickra-lib/wickra/actions/workflows/ci.yml/badge.svg)](https://github.com/wickra-lib/wickra/actions/workflows/ci.yml)
@@ -48,7 +48,7 @@ Full documentation lives at **[docs.wickra.org](https://docs.wickra.org)**:
[Node](https://docs.wickra.org/Quickstart-Node),
[WASM](https://docs.wickra.org/Quickstart-WASM).
- **Indicators** — a per-indicator deep dive (formula, parameters, warmup) for
every one of the 367 indicators; start at the
every one of the 377 indicators; start at the
[indicators overview](https://docs.wickra.org/Indicators-Overview).
- **Reference** — [warmup periods](https://docs.wickra.org/Warmup-Periods),
[streaming vs batch](https://docs.wickra.org/Streaming-vs-Batch),
@@ -136,7 +136,7 @@ python -m benchmarks.compare_libraries
## Indicators
367 streaming-first indicators across twenty-three families. Every one passes the
377 streaming-first indicators across twenty-four families. Every one passes the
`batch == streaming` equivalence test, reference-value tests, and reset
semantics tests. Each has a per-indicator deep dive (formula, parameters,
warmup) at [docs.wickra.org](https://docs.wickra.org/Indicators-Overview).
@@ -160,6 +160,7 @@ warmup) at [docs.wickra.org](https://docs.wickra.org/Indicators-Overview).
| Candlestick Patterns | Doji, Hammer, Inverted Hammer, Hanging Man, Shooting Star, Engulfing, Harami, Morning/Evening Star, Three White Soldiers/Black Crows, Piercing Line/Dark Cloud Cover, Marubozu, Tweezer, Spinning Top, Three Inside Up/Down, Three Outside Up/Down, Two Crows, Upside Gap Two Crows, Identical Three Crows, Three Line Strike, Three Stars in the South, Abandoned Baby, Advance Block, Belt-hold, Breakaway, Counterattack, Doji Star, Dragonfly Doji, Gravestone Doji, Long-Legged Doji, Rickshaw Man, Evening Doji Star, Morning Doji Star, Gap Side-by-Side White, High-Wave, Hikkake, Modified Hikkake, Homing Pigeon, On-Neck, In-Neck, Thrusting, Separating Lines, Kicking, Kicking by Length, Ladder Bottom, Mat Hold, Matching Low, Long Line, Short Line, Rising Three Methods, Falling Three Methods, Upside Gap Three Methods, Downside Gap Three Methods, Stalled Pattern, Stick Sandwich, Takuri, Closing Marubozu, Opening Marubozu, Tasuki Gap, Unique Three River, Concealing Baby Swallow |
| Chart Patterns | Double Top / Bottom, Triple Top / Bottom, Head and Shoulders, Triangle (asc/desc/sym), Wedge (rising/falling), Flag / Pennant, Rectangle / Range, Cup and Handle |
| Harmonic Patterns | AB=CD, Gartley, Butterfly, Bat, Crab, Shark, Cypher, Three Drives |
| Fibonacci | Fibonacci Retracement, Fibonacci Extension, Fibonacci Projection, Auto-Fibonacci, Golden Pocket, Fibonacci Confluence, Fibonacci Fan, Fibonacci Arcs, Fibonacci Channel, Fibonacci Time Zones |
| Microstructure | Order-Book Imbalance (Top-1 / Top-N / Full), Microprice, Quoted Spread, Depth Slope, Signed Volume, Cumulative Volume Delta, Trade Imbalance, Effective Spread, Realized Spread, Kyle's Lambda, Footprint |
| Derivatives | Funding Rate, Funding Rate Mean, Funding Rate Z-Score, Funding Basis, Open-Interest Delta, OI / Price Divergence, OI-Weighted Price, Long/Short Ratio, Taker Buy/Sell Ratio, Liquidation Features, Term-Structure Basis, Calendar Spread |
| Market Profile | Value Area (POC / VAH / VAL), Volume Profile (histogram), TPO Profile, Initial Balance, Opening Range |
@@ -244,7 +245,7 @@ A Python live-trading example using the public `websockets` package lives at
```
wickra/
├── crates/
│ ├── wickra-core/ core engine + all 367 indicators
│ ├── wickra-core/ core engine + all 377 indicators
│ ├── wickra/ top-level facade crate (publishes on crates.io) + benches/
│ └── wickra-data/ CSV reader, tick aggregator, live exchange feeds
├── bindings/
@@ -385,6 +385,16 @@ const multi = {
// Family 13: Ichimoku & alternative charts
Ichimoku: { make: () => new wickra.Ichimoku(9, 26, 52, 26), fields: ['tenkan', 'kijun', 'senkouA', 'senkouB', 'chikou'], step: (ind, i) => ind.update(high[i], low[i], close[i]), batch: (ind) => ind.batch(high, low, close) },
HeikinAshi: { make: () => new wickra.HeikinAshi(), fields: ['open', 'high', 'low', 'close'], step: (ind, i) => ind.update(open[i], high[i], low[i], close[i]), batch: (ind) => ind.batch(open, high, low, close) },
FibRetracement: { make: () => new wickra.FibRetracement(), fields: ['level0', 'level236', 'level382', 'level500', 'level618', 'level786', 'level1000'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
FibExtension: { make: () => new wickra.FibExtension(), fields: ['level1272', 'level1414', 'level1618', 'level2000', 'level2618'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
FibProjection: { make: () => new wickra.FibProjection(), fields: ['level618', 'level1000', 'level1618', 'level2618'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
AutoFib: { make: () => new wickra.AutoFib(), fields: ['level0', 'level236', 'level382', 'level500', 'level618', 'level786', 'level1000'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
GoldenPocket: { make: () => new wickra.GoldenPocket(), fields: ['low', 'mid', 'high'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
FibConfluence: { make: () => new wickra.FibConfluence(), fields: ['price', 'strength'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
FibFan: { make: () => new wickra.FibFan(), fields: ['fan382', 'fan500', 'fan618'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
FibArcs: { make: () => new wickra.FibArcs(), fields: ['arc382', 'arc500', 'arc618'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
FibChannel: { make: () => new wickra.FibChannel(), fields: ['base', 'level618', 'level1000', 'level1618'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
FibTimeZones: { make: () => new wickra.FibTimeZones(), fields: ['onZone', 'barsToNext'], step: (ind, i) => ind.update(high[i], low[i]), batch: (ind) => ind.batch(high, low) },
};
for (const [name, d] of Object.entries(multi)) {
+150
View File
@@ -362,6 +362,66 @@ export interface OvernightIntradayReturnValue {
overnight: number
intraday: number
}
export interface FibRetracementValue {
level0: number
level236: number
level382: number
level500: number
level618: number
level786: number
level1000: number
}
export interface FibExtensionValue {
level1272: number
level1414: number
level1618: number
level2000: number
level2618: number
}
export interface FibProjectionValue {
level618: number
level1000: number
level1618: number
level2618: number
}
export interface AutoFibValue {
level0: number
level236: number
level382: number
level500: number
level618: number
level786: number
level1000: number
}
export interface GoldenPocketValue {
low: number
mid: number
high: number
}
export interface FibConfluenceValue {
price: number
strength: number
}
export interface FibFanValue {
fan382: number
fan500: number
fan618: number
}
export interface FibArcsValue {
arc382: number
arc500: number
arc618: number
}
export interface FibChannelValue {
base: number
level618: number
level1000: number
level1618: number
}
export interface FibTimeZonesValue {
onZone: number
barsToNext: number
}
export type SmaNode = SMA
export declare class SMA {
constructor(period: number)
@@ -3832,3 +3892,93 @@ export declare class OvernightIntradayReturn {
isReady(): boolean
warmupPeriod(): number
}
export type FibRetracementNode = FibRetracement
export declare class FibRetracement {
constructor()
update(high: number, low: number): FibRetracementValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FibExtensionNode = FibExtension
export declare class FibExtension {
constructor()
update(high: number, low: number): FibExtensionValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FibProjectionNode = FibProjection
export declare class FibProjection {
constructor()
update(high: number, low: number): FibProjectionValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type AutoFibNode = AutoFib
export declare class AutoFib {
constructor()
update(high: number, low: number): AutoFibValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type GoldenPocketNode = GoldenPocket
export declare class GoldenPocket {
constructor()
update(high: number, low: number): GoldenPocketValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FibConfluenceNode = FibConfluence
export declare class FibConfluence {
constructor()
update(high: number, low: number): FibConfluenceValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FibFanNode = FibFan
export declare class FibFan {
constructor()
update(high: number, low: number): FibFanValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FibArcsNode = FibArcs
export declare class FibArcs {
constructor()
update(high: number, low: number): FibArcsValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FibChannelNode = FibChannel
export declare class FibChannel {
constructor()
update(high: number, low: number): FibChannelValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
export type FibTimeZonesNode = FibTimeZones
export declare class FibTimeZones {
constructor()
update(high: number, low: number): FibTimeZonesValue | null
batch(high: Array<number>, low: Array<number>): Array<number>
reset(): void
isReady(): boolean
warmupPeriod(): number
}
+11 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "wickra-darwin-arm64",
"version": "0.5.2",
"version": "0.5.3",
"description": "Native binding for wickra (macOS Apple Silicon). Installed automatically as an optional dependency of wickra on matching platforms.",
"main": "wickra.darwin-arm64.node",
"files": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "wickra-darwin-x64",
"version": "0.5.2",
"version": "0.5.3",
"description": "Native binding for wickra (macOS Intel). Installed automatically as an optional dependency of wickra on matching platforms.",
"main": "wickra.darwin-x64.node",
"files": [
@@ -1,6 +1,6 @@
{
"name": "wickra-linux-arm64-gnu",
"version": "0.5.2",
"version": "0.5.3",
"description": "Native binding for wickra (linux arm64 GNU). Installed automatically as an optional dependency of wickra on matching platforms.",
"main": "wickra.linux-arm64-gnu.node",
"files": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "wickra-linux-x64-gnu",
"version": "0.5.2",
"version": "0.5.3",
"description": "Native binding for wickra (linux x64 GNU). Installed automatically as an optional dependency of wickra on matching platforms.",
"main": "wickra.linux-x64-gnu.node",
"files": [
@@ -1,6 +1,6 @@
{
"name": "wickra-win32-arm64-msvc",
"version": "0.5.2",
"version": "0.5.3",
"description": "Native binding for wickra (Windows arm64 MSVC). Installed automatically as an optional dependency of wickra on matching platforms.",
"main": "wickra.win32-arm64-msvc.node",
"files": [
@@ -1,6 +1,6 @@
{
"name": "wickra-win32-x64-msvc",
"version": "0.5.2",
"version": "0.5.3",
"description": "Native binding for wickra (Windows x64 MSVC). Installed automatically as an optional dependency of wickra on matching platforms.",
"main": "wickra.win32-x64-msvc.node",
"files": [
+20 -20
View File
@@ -1,12 +1,12 @@
{
"name": "wickra",
"version": "0.5.2",
"version": "0.5.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "wickra",
"version": "0.5.2",
"version": "0.5.3",
"license": "MIT OR Apache-2.0",
"devDependencies": {
"@napi-rs/cli": "^2.18.0"
@@ -15,12 +15,12 @@
"node": ">= 18"
},
"optionalDependencies": {
"wickra-darwin-arm64": "0.5.2",
"wickra-darwin-x64": "0.5.2",
"wickra-linux-arm64-gnu": "0.5.2",
"wickra-linux-x64-gnu": "0.5.2",
"wickra-win32-arm64-msvc": "0.5.2",
"wickra-win32-x64-msvc": "0.5.2"
"wickra-darwin-arm64": "0.5.3",
"wickra-darwin-x64": "0.5.3",
"wickra-linux-arm64-gnu": "0.5.3",
"wickra-linux-x64-gnu": "0.5.3",
"wickra-win32-arm64-msvc": "0.5.3",
"wickra-win32-x64-msvc": "0.5.3"
}
},
"node_modules/@napi-rs/cli": {
@@ -41,8 +41,8 @@
}
},
"node_modules/wickra-darwin-arm64": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/wickra-darwin-arm64/-/wickra-darwin-arm64-0.5.2.tgz",
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/wickra-darwin-arm64/-/wickra-darwin-arm64-0.5.3.tgz",
"integrity": "sha512-4eZiBR/yGUdr4nzhEUFy2i69XgNx64iI2ax/LPamsThgylC0KpHOZKK19QzJ2d9KbK4C8nMjME5FLuR+4GNEwQ==",
"cpu": [
"arm64"
@@ -57,8 +57,8 @@
}
},
"node_modules/wickra-darwin-x64": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/wickra-darwin-x64/-/wickra-darwin-x64-0.5.2.tgz",
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/wickra-darwin-x64/-/wickra-darwin-x64-0.5.3.tgz",
"integrity": "sha512-6hf8zI3QPjTFp4zCpmgUwDvNtu6jHqNUHKD5e55POo0CgA52HkpyxSPtVm8TGTIZDI7kPjlbOdBM8CJ76mmXwA==",
"cpu": [
"x64"
@@ -73,8 +73,8 @@
}
},
"node_modules/wickra-linux-arm64-gnu": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/wickra-linux-arm64-gnu/-/wickra-linux-arm64-gnu-0.5.2.tgz",
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/wickra-linux-arm64-gnu/-/wickra-linux-arm64-gnu-0.5.3.tgz",
"integrity": "sha512-kSe6y0xBMSiqdPLXNjwop5WZdHtvdBNKSEBCwZ4hFq33p4apW25/wrlzv9/oDuyD4kuPabJEhCCnFOplh58CUg==",
"cpu": [
"arm64"
@@ -89,8 +89,8 @@
}
},
"node_modules/wickra-linux-x64-gnu": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/wickra-linux-x64-gnu/-/wickra-linux-x64-gnu-0.5.2.tgz",
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/wickra-linux-x64-gnu/-/wickra-linux-x64-gnu-0.5.3.tgz",
"integrity": "sha512-tWBWS4qz7hxM4xnpFb59bhf6TaLwXq0Z3jEa/2l7r8PiHA94g8r8S53NRMiT+4yiL5hSWe/nUiC/YXdRrhEZ4g==",
"cpu": [
"x64"
@@ -105,8 +105,8 @@
}
},
"node_modules/wickra-win32-arm64-msvc": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/wickra-win32-arm64-msvc/-/wickra-win32-arm64-msvc-0.5.2.tgz",
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/wickra-win32-arm64-msvc/-/wickra-win32-arm64-msvc-0.5.3.tgz",
"integrity": "sha512-EXIckHxAtF75PUGDKRzXyqMe9ldP0JjSdu68WFN6iJfp+McYrGu6h40TEJlQ/oUEIoPqiZB/xhVyo/el5Lg7zw==",
"cpu": [
"arm64"
@@ -121,8 +121,8 @@
}
},
"node_modules/wickra-win32-x64-msvc": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/wickra-win32-x64-msvc/-/wickra-win32-x64-msvc-0.5.2.tgz",
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/wickra-win32-x64-msvc/-/wickra-win32-x64-msvc-0.5.3.tgz",
"integrity": "sha512-Yfsqq1Xwp6hdxMyLze411vNdo7BDwI6+lPSe7A9XdqyPecNDbtKwYLpsal2r8EHbNzqM+R8XnuRtUaEQS5VlUQ==",
"cpu": [
"x64"
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "wickra",
"version": "0.5.2",
"version": "0.5.3",
"description": "Streaming-first technical indicators: incremental, fast, install-free. Node bindings powered by Rust.",
"author": "kingchenc <support@wickra.org>",
"main": "index.js",
@@ -47,12 +47,12 @@
"node": ">= 18"
},
"optionalDependencies": {
"wickra-linux-x64-gnu": "0.5.2",
"wickra-linux-arm64-gnu": "0.5.2",
"wickra-darwin-x64": "0.5.2",
"wickra-darwin-arm64": "0.5.2",
"wickra-win32-x64-msvc": "0.5.2",
"wickra-win32-arm64-msvc": "0.5.2"
"wickra-linux-x64-gnu": "0.5.3",
"wickra-linux-arm64-gnu": "0.5.3",
"wickra-darwin-x64": "0.5.3",
"wickra-darwin-arm64": "0.5.3",
"wickra-win32-x64-msvc": "0.5.3",
"wickra-win32-arm64-msvc": "0.5.3"
},
"scripts": {
"build": "napi build --platform --release",
+728
View File
@@ -14030,3 +14030,731 @@ impl OvernightIntradayReturnNode {
self.inner.warmup_period() as u32
}
}
// ============================== Fibonacci ==============================
/// Build a candle for the swing-based Fibonacci tools from a `high`/`low` pair;
/// only the high and low drive the swing tracker, so open/close are the midpoint.
fn swing_cnd(high: f64, low: f64) -> napi::Result<wc::Candle> {
cnd(high, low, f64::midpoint(high, low), 0.0)
}
#[napi(object)]
pub struct FibRetracementValue {
pub level_0: f64,
pub level_236: f64,
pub level_382: f64,
pub level_500: f64,
pub level_618: f64,
pub level_786: f64,
pub level_1000: f64,
}
#[napi(js_name = "FibRetracement")]
pub struct FibRetracementNode {
inner: wc::FibRetracement,
}
#[napi]
impl FibRetracementNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FibRetracement::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<FibRetracementValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| FibRetracementValue {
level_0: o.level_0,
level_236: o.level_236,
level_382: o.level_382,
level_500: o.level_500,
level_618: o.level_618,
level_786: o.level_786,
level_1000: o.level_1000,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 7];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 7] = o.level_0;
out[i * 7 + 1] = o.level_236;
out[i * 7 + 2] = o.level_382;
out[i * 7 + 3] = o.level_500;
out[i * 7 + 4] = o.level_618;
out[i * 7 + 5] = o.level_786;
out[i * 7 + 6] = o.level_1000;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
#[napi(object)]
pub struct FibExtensionValue {
pub level_1272: f64,
pub level_1414: f64,
pub level_1618: f64,
pub level_2000: f64,
pub level_2618: f64,
}
#[napi(js_name = "FibExtension")]
pub struct FibExtensionNode {
inner: wc::FibExtension,
}
#[napi]
impl FibExtensionNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FibExtension::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<FibExtensionValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| FibExtensionValue {
level_1272: o.level_1272,
level_1414: o.level_1414,
level_1618: o.level_1618,
level_2000: o.level_2000,
level_2618: o.level_2618,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 5];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 5] = o.level_1272;
out[i * 5 + 1] = o.level_1414;
out[i * 5 + 2] = o.level_1618;
out[i * 5 + 3] = o.level_2000;
out[i * 5 + 4] = o.level_2618;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
#[napi(object)]
pub struct FibProjectionValue {
pub level_618: f64,
pub level_1000: f64,
pub level_1618: f64,
pub level_2618: f64,
}
#[napi(js_name = "FibProjection")]
pub struct FibProjectionNode {
inner: wc::FibProjection,
}
#[napi]
impl FibProjectionNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FibProjection::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<FibProjectionValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| FibProjectionValue {
level_618: o.level_618,
level_1000: o.level_1000,
level_1618: o.level_1618,
level_2618: o.level_2618,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 4];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 4] = o.level_618;
out[i * 4 + 1] = o.level_1000;
out[i * 4 + 2] = o.level_1618;
out[i * 4 + 3] = o.level_2618;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
#[napi(object)]
pub struct AutoFibValue {
pub level_0: f64,
pub level_236: f64,
pub level_382: f64,
pub level_500: f64,
pub level_618: f64,
pub level_786: f64,
pub level_1000: f64,
}
#[napi(js_name = "AutoFib")]
pub struct AutoFibNode {
inner: wc::AutoFib,
}
#[napi]
impl AutoFibNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::AutoFib::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<AutoFibValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| AutoFibValue {
level_0: o.level_0,
level_236: o.level_236,
level_382: o.level_382,
level_500: o.level_500,
level_618: o.level_618,
level_786: o.level_786,
level_1000: o.level_1000,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 7];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 7] = o.level_0;
out[i * 7 + 1] = o.level_236;
out[i * 7 + 2] = o.level_382;
out[i * 7 + 3] = o.level_500;
out[i * 7 + 4] = o.level_618;
out[i * 7 + 5] = o.level_786;
out[i * 7 + 6] = o.level_1000;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
#[napi(object)]
pub struct GoldenPocketValue {
pub low: f64,
pub mid: f64,
pub high: f64,
}
#[napi(js_name = "GoldenPocket")]
pub struct GoldenPocketNode {
inner: wc::GoldenPocket,
}
#[napi]
impl GoldenPocketNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::GoldenPocket::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<GoldenPocketValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| GoldenPocketValue {
low: o.low,
mid: o.mid,
high: o.high,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 3] = o.low;
out[i * 3 + 1] = o.mid;
out[i * 3 + 2] = o.high;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
#[napi(object)]
pub struct FibConfluenceValue {
pub price: f64,
pub strength: f64,
}
#[napi(js_name = "FibConfluence")]
pub struct FibConfluenceNode {
inner: wc::FibConfluence,
}
#[napi]
impl FibConfluenceNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FibConfluence::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<FibConfluenceValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| FibConfluenceValue {
price: o.price,
strength: o.strength,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 2];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 2] = o.price;
out[i * 2 + 1] = o.strength;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
impl Default for FibRetracementNode {
fn default() -> Self {
Self::new()
}
}
impl Default for FibExtensionNode {
fn default() -> Self {
Self::new()
}
}
impl Default for FibProjectionNode {
fn default() -> Self {
Self::new()
}
}
impl Default for AutoFibNode {
fn default() -> Self {
Self::new()
}
}
impl Default for GoldenPocketNode {
fn default() -> Self {
Self::new()
}
}
impl Default for FibConfluenceNode {
fn default() -> Self {
Self::new()
}
}
#[napi(object)]
pub struct FibFanValue {
pub fan_382: f64,
pub fan_500: f64,
pub fan_618: f64,
}
#[napi(js_name = "FibFan")]
pub struct FibFanNode {
inner: wc::FibFan,
}
#[napi]
impl FibFanNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FibFan::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<FibFanValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| FibFanValue {
fan_382: o.fan_382,
fan_500: o.fan_500,
fan_618: o.fan_618,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 3] = o.fan_382;
out[i * 3 + 1] = o.fan_500;
out[i * 3 + 2] = o.fan_618;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
impl Default for FibFanNode {
fn default() -> Self {
Self::new()
}
}
#[napi(object)]
pub struct FibArcsValue {
pub arc_382: f64,
pub arc_500: f64,
pub arc_618: f64,
}
#[napi(js_name = "FibArcs")]
pub struct FibArcsNode {
inner: wc::FibArcs,
}
#[napi]
impl FibArcsNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FibArcs::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<FibArcsValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| FibArcsValue {
arc_382: o.arc_382,
arc_500: o.arc_500,
arc_618: o.arc_618,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 3] = o.arc_382;
out[i * 3 + 1] = o.arc_500;
out[i * 3 + 2] = o.arc_618;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
impl Default for FibArcsNode {
fn default() -> Self {
Self::new()
}
}
#[napi(object)]
pub struct FibChannelValue {
pub base: f64,
pub level_618: f64,
pub level_1000: f64,
pub level_1618: f64,
}
#[napi(js_name = "FibChannel")]
pub struct FibChannelNode {
inner: wc::FibChannel,
}
#[napi]
impl FibChannelNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FibChannel::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<FibChannelValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| FibChannelValue {
base: o.base,
level_618: o.level_618,
level_1000: o.level_1000,
level_1618: o.level_1618,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 4];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 4] = o.base;
out[i * 4 + 1] = o.level_618;
out[i * 4 + 2] = o.level_1000;
out[i * 4 + 3] = o.level_1618;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
impl Default for FibChannelNode {
fn default() -> Self {
Self::new()
}
}
#[napi(object)]
pub struct FibTimeZonesValue {
pub on_zone: f64,
pub bars_to_next: f64,
}
#[napi(js_name = "FibTimeZones")]
pub struct FibTimeZonesNode {
inner: wc::FibTimeZones,
}
#[napi]
impl FibTimeZonesNode {
#[napi(constructor)]
pub fn new() -> Self {
Self {
inner: wc::FibTimeZones::new(),
}
}
#[napi]
pub fn update(&mut self, high: f64, low: f64) -> napi::Result<Option<FibTimeZonesValue>> {
Ok(self
.inner
.update(swing_cnd(high, low)?)
.map(|o| FibTimeZonesValue {
on_zone: o.on_zone,
bars_to_next: o.bars_to_next,
}))
}
#[napi]
pub fn batch(&mut self, high: Vec<f64>, low: Vec<f64>) -> napi::Result<Vec<f64>> {
if high.len() != low.len() {
return Err(NapiError::from_reason(
"high and low must be equal length".to_string(),
));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 2];
for i in 0..n {
if let Some(o) = self.inner.update(swing_cnd(high[i], low[i])?) {
out[i * 2] = o.on_zone;
out[i * 2 + 1] = o.bars_to_next;
}
}
Ok(out)
}
#[napi]
pub fn reset(&mut self) {
self.inner.reset();
}
#[napi(js_name = "isReady")]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[napi(js_name = "warmupPeriod")]
pub fn warmup_period(&self) -> u32 {
self.inner.warmup_period() as u32
}
}
impl Default for FibTimeZonesNode {
fn default() -> Self {
Self::new()
}
}
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "maturin"
[project]
name = "wickra"
version = "0.5.2"
version = "0.5.3"
description = "Streaming-first technical indicators: incremental, fast, install-free."
readme = "README.md"
license = "MIT OR Apache-2.0"
+22
View File
@@ -339,6 +339,17 @@ from ._wickra import (
Butterfly,
Gartley,
Abcd,
# Fibonacci
FibTimeZones,
FibChannel,
FibArcs,
FibFan,
FibConfluence,
GoldenPocket,
AutoFib,
FibProjection,
FibExtension,
FibRetracement,
# Microstructure: order book
OrderBookImbalanceTop1,
OrderBookImbalanceTopN,
@@ -734,6 +745,17 @@ __all__ = [
"Butterfly",
"Gartley",
"Abcd",
# Fibonacci
"FibTimeZones",
"FibChannel",
"FibArcs",
"FibFan",
"FibConfluence",
"GoldenPocket",
"AutoFib",
"FibProjection",
"FibExtension",
"FibRetracement",
# Microstructure: order book
"OrderBookImbalanceTop1",
"OrderBookImbalanceTopN",
+727
View File
@@ -49,6 +49,8 @@ const NON_CONTIGUOUS: &str = "array must be C-contiguous; pass np.ascontiguousar
/// `(pp, r1, r2, r3, s1, s2, s3)` pivot levels returned by Classic/Fibonacci pivots.
type PivotLevels = (f64, f64, f64, f64, f64, f64, f64);
/// The five Fibonacci-extension levels returned by `FibExtension`.
type FibExtLevels = (f64, f64, f64, f64, f64);
/// `(pp, r1, r2, s1, s2)` pivot levels returned by Woodie pivots.
type WoodieLevels = (f64, f64, f64, f64, f64);
/// `(tenkan, kijun, senkou_a, senkou_b, chikou)` Ichimoku lines, each optional during warmup.
@@ -17846,6 +17848,720 @@ impl PyOvernightIntradayReturn {
}
}
// ============================== Fibonacci ==============================
/// Build a candle for the swing-based Fibonacci tools from a `high`/`low` pair.
/// Only the high and low drive the swing tracker, so open and close are pinned
/// to the midpoint to keep the OHLC invariants valid.
fn swing_candle(high: f64, low: f64) -> Result<wc::Candle, wc::Error> {
let mid = f64::midpoint(high, low);
wc::Candle::new(mid, high, low, mid, 0.0, 0)
}
#[pyclass(
name = "FibRetracement",
module = "wickra._wickra",
skip_from_py_object
)]
#[derive(Clone)]
struct PyFibRetracement {
inner: wc::FibRetracement,
}
#[pymethods]
impl PyFibRetracement {
#[new]
fn new() -> Self {
Self {
inner: wc::FibRetracement::new(),
}
}
/// Returns `(level_0, …, level_1000)` (seven levels) or None during warmup.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<PivotLevels>> {
let c = extract_candle(candle)?;
Ok(self.inner.update(c).map(|o| {
(
o.level_0,
o.level_236,
o.level_382,
o.level_500,
o.level_618,
o.level_786,
o.level_1000,
)
}))
}
/// Batch over numpy columns high, low. Returns shape `(n, 7)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 7];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 7] = o.level_0;
out[i * 7 + 1] = o.level_236;
out[i * 7 + 2] = o.level_382;
out[i * 7 + 3] = o.level_500;
out[i * 7 + 4] = o.level_618;
out[i * 7 + 5] = o.level_786;
out[i * 7 + 6] = o.level_1000;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 7), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"FibRetracement()".to_string()
}
}
#[pyclass(name = "FibExtension", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFibExtension {
inner: wc::FibExtension,
}
#[pymethods]
impl PyFibExtension {
#[new]
fn new() -> Self {
Self {
inner: wc::FibExtension::new(),
}
}
/// Returns `(level_1272, level_1414, level_1618, level_2000, level_2618)` or None.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<FibExtLevels>> {
let c = extract_candle(candle)?;
Ok(self.inner.update(c).map(|o| {
(
o.level_1272,
o.level_1414,
o.level_1618,
o.level_2000,
o.level_2618,
)
}))
}
/// Batch over numpy columns high, low. Returns shape `(n, 5)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 5];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 5] = o.level_1272;
out[i * 5 + 1] = o.level_1414;
out[i * 5 + 2] = o.level_1618;
out[i * 5 + 3] = o.level_2000;
out[i * 5 + 4] = o.level_2618;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 5), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"FibExtension()".to_string()
}
}
#[pyclass(name = "FibProjection", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFibProjection {
inner: wc::FibProjection,
}
#[pymethods]
impl PyFibProjection {
#[new]
fn new() -> Self {
Self {
inner: wc::FibProjection::new(),
}
}
/// Returns `(level_618, level_1000, level_1618, level_2618)` or None during warmup.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64, f64, f64)>> {
let c = extract_candle(candle)?;
Ok(self
.inner
.update(c)
.map(|o| (o.level_618, o.level_1000, o.level_1618, o.level_2618)))
}
/// Batch over numpy columns high, low. Returns shape `(n, 4)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 4];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 4] = o.level_618;
out[i * 4 + 1] = o.level_1000;
out[i * 4 + 2] = o.level_1618;
out[i * 4 + 3] = o.level_2618;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 4), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"FibProjection()".to_string()
}
}
#[pyclass(name = "AutoFib", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyAutoFib {
inner: wc::AutoFib,
}
#[pymethods]
impl PyAutoFib {
#[new]
fn new() -> Self {
Self {
inner: wc::AutoFib::new(),
}
}
/// Returns `(level_0, …, level_1000)` for the dominant leg, or None during warmup.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<PivotLevels>> {
let c = extract_candle(candle)?;
Ok(self.inner.update(c).map(|o| {
(
o.level_0,
o.level_236,
o.level_382,
o.level_500,
o.level_618,
o.level_786,
o.level_1000,
)
}))
}
/// Batch over numpy columns high, low. Returns shape `(n, 7)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 7];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 7] = o.level_0;
out[i * 7 + 1] = o.level_236;
out[i * 7 + 2] = o.level_382;
out[i * 7 + 3] = o.level_500;
out[i * 7 + 4] = o.level_618;
out[i * 7 + 5] = o.level_786;
out[i * 7 + 6] = o.level_1000;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 7), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"AutoFib()".to_string()
}
}
#[pyclass(name = "GoldenPocket", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyGoldenPocket {
inner: wc::GoldenPocket,
}
#[pymethods]
impl PyGoldenPocket {
#[new]
fn new() -> Self {
Self {
inner: wc::GoldenPocket::new(),
}
}
/// Returns `(low, mid, high)` of the golden-pocket band, or None during warmup.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64, f64)>> {
let c = extract_candle(candle)?;
Ok(self.inner.update(c).map(|o| (o.low, o.mid, o.high)))
}
/// Batch over numpy columns high, low. Returns shape `(n, 3)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 3] = o.low;
out[i * 3 + 1] = o.mid;
out[i * 3 + 2] = o.high;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 3), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"GoldenPocket()".to_string()
}
}
#[pyclass(name = "FibConfluence", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFibConfluence {
inner: wc::FibConfluence,
}
#[pymethods]
impl PyFibConfluence {
#[new]
fn new() -> Self {
Self {
inner: wc::FibConfluence::new(),
}
}
/// Returns `(price, strength)` of the densest cluster, or None during warmup.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64)>> {
let c = extract_candle(candle)?;
Ok(self.inner.update(c).map(|o| (o.price, o.strength)))
}
/// Batch over numpy columns high, low. Returns shape `(n, 2)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 2];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 2] = o.price;
out[i * 2 + 1] = o.strength;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 2), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"FibConfluence()".to_string()
}
}
#[pyclass(name = "FibFan", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFibFan {
inner: wc::FibFan,
}
#[pymethods]
impl PyFibFan {
#[new]
fn new() -> Self {
Self {
inner: wc::FibFan::new(),
}
}
/// Returns `(fan_382, fan_500, fan_618)` at the current bar, or None.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64, f64)>> {
let c = extract_candle(candle)?;
Ok(self
.inner
.update(c)
.map(|o| (o.fan_382, o.fan_500, o.fan_618)))
}
/// Batch over numpy columns high, low. Returns shape `(n, 3)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 3] = o.fan_382;
out[i * 3 + 1] = o.fan_500;
out[i * 3 + 2] = o.fan_618;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 3), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"FibFan()".to_string()
}
}
#[pyclass(name = "FibArcs", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFibArcs {
inner: wc::FibArcs,
}
#[pymethods]
impl PyFibArcs {
#[new]
fn new() -> Self {
Self {
inner: wc::FibArcs::new(),
}
}
/// Returns `(arc_382, arc_500, arc_618)` at the current bar, or None.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64, f64)>> {
let c = extract_candle(candle)?;
Ok(self
.inner
.update(c)
.map(|o| (o.arc_382, o.arc_500, o.arc_618)))
}
/// Batch over numpy columns high, low. Returns shape `(n, 3)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 3] = o.arc_382;
out[i * 3 + 1] = o.arc_500;
out[i * 3 + 2] = o.arc_618;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 3), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"FibArcs()".to_string()
}
}
#[pyclass(name = "FibChannel", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFibChannel {
inner: wc::FibChannel,
}
#[pymethods]
impl PyFibChannel {
#[new]
fn new() -> Self {
Self {
inner: wc::FibChannel::new(),
}
}
/// Returns `(base, level_618, level_1000, level_1618)` at the current bar, or None.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64, f64, f64)>> {
let c = extract_candle(candle)?;
Ok(self
.inner
.update(c)
.map(|o| (o.base, o.level_618, o.level_1000, o.level_1618)))
}
/// Batch over numpy columns high, low. Returns shape `(n, 4)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 4];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 4] = o.base;
out[i * 4 + 1] = o.level_618;
out[i * 4 + 2] = o.level_1000;
out[i * 4 + 3] = o.level_1618;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 4), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"FibChannel()".to_string()
}
}
#[pyclass(name = "FibTimeZones", module = "wickra._wickra", skip_from_py_object)]
#[derive(Clone)]
struct PyFibTimeZones {
inner: wc::FibTimeZones,
}
#[pymethods]
impl PyFibTimeZones {
#[new]
fn new() -> Self {
Self {
inner: wc::FibTimeZones::new(),
}
}
/// Returns `(on_zone, bars_to_next)` at the current bar, or None during warmup.
fn update(&mut self, candle: &Bound<'_, PyAny>) -> PyResult<Option<(f64, f64)>> {
let c = extract_candle(candle)?;
Ok(self.inner.update(c).map(|o| (o.on_zone, o.bars_to_next)))
}
/// Batch over numpy columns high, low. Returns shape `(n, 2)`.
fn batch<'py>(
&mut self,
py: Python<'py>,
high: PyReadonlyArray1<'py, f64>,
low: PyReadonlyArray1<'py, f64>,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
let h = high
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
let l = low
.as_slice()
.map_err(|_| PyValueError::new_err(NON_CONTIGUOUS))?;
if h.len() != l.len() {
return Err(PyValueError::new_err("high and low must be equal length"));
}
let n = h.len();
let mut out = vec![f64::NAN; n * 2];
for i in 0..n {
if let Some(o) = self
.inner
.update(swing_candle(h[i], l[i]).map_err(map_err)?)
{
out[i * 2] = o.on_zone;
out[i * 2 + 1] = o.bars_to_next;
}
}
Ok(numpy::ndarray::Array2::from_shape_vec((n, 2), out)
.expect("shape consistent")
.into_pyarray(py))
}
fn reset(&mut self) {
self.inner.reset();
}
fn is_ready(&self) -> bool {
self.inner.is_ready()
}
fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
fn __repr__(&self) -> String {
"FibTimeZones()".to_string()
}
}
#[pymodule]
#[allow(clippy::too_many_lines)]
fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
@@ -18228,5 +18944,16 @@ fn _wickra(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<PyShark>()?;
m.add_class::<PyCypher>()?;
m.add_class::<PyThreeDrives>()?;
// Fibonacci.
m.add_class::<PyFibRetracement>()?;
m.add_class::<PyFibExtension>()?;
m.add_class::<PyFibProjection>()?;
m.add_class::<PyAutoFib>()?;
m.add_class::<PyGoldenPocket>()?;
m.add_class::<PyFibConfluence>()?;
m.add_class::<PyFibFan>()?;
m.add_class::<PyFibArcs>()?;
m.add_class::<PyFibChannel>()?;
m.add_class::<PyFibTimeZones>()?;
Ok(())
}
@@ -860,6 +860,56 @@ def test_candle_scalar_streaming_matches_batch(name, ohlcv):
# --- Candle-input, multi-output indicators --------------------------------
MULTI = {
"FibFan": (
lambda: ta.FibFan(),
lambda ind, h, l, c, v: ind.batch(h, l),
3,
),
"FibArcs": (
lambda: ta.FibArcs(),
lambda ind, h, l, c, v: ind.batch(h, l),
3,
),
"FibChannel": (
lambda: ta.FibChannel(),
lambda ind, h, l, c, v: ind.batch(h, l),
4,
),
"FibTimeZones": (
lambda: ta.FibTimeZones(),
lambda ind, h, l, c, v: ind.batch(h, l),
2,
),
"FibRetracement": (
lambda: ta.FibRetracement(),
lambda ind, h, l, c, v: ind.batch(h, l),
7,
),
"FibExtension": (
lambda: ta.FibExtension(),
lambda ind, h, l, c, v: ind.batch(h, l),
5,
),
"FibProjection": (
lambda: ta.FibProjection(),
lambda ind, h, l, c, v: ind.batch(h, l),
4,
),
"AutoFib": (
lambda: ta.AutoFib(),
lambda ind, h, l, c, v: ind.batch(h, l),
7,
),
"GoldenPocket": (
lambda: ta.GoldenPocket(),
lambda ind, h, l, c, v: ind.batch(h, l),
3,
),
"FibConfluence": (
lambda: ta.FibConfluence(),
lambda ind, h, l, c, v: ind.batch(h, l),
2,
),
"Vortex": (
lambda: ta.Vortex(14),
lambda ind, h, l, c, v: ind.batch(h, l, c),
@@ -2578,6 +2628,85 @@ def test_three_drives_reference():
assert t.update((109.08, 136.0, 109.08, 109.08, 1.0, 4)) == pytest.approx(0.0)
assert t.update((122.4, 134.64, 122.4, 122.4, 1.0, 5)) == pytest.approx(-1.0)
def test_fib_retracement_reference():
t = ta.FibRetracement()
assert t.update((199.8, 200.0, 199.8, 199.8, 1.0, 0)) is None
assert t.update((100.0, 198.0, 100.0, 100.0, 1.0, 1)) is None
assert t.update((101.0, 110.0, 101.0, 101.0, 1.0, 2)) == pytest.approx((100.0, 123.6, 138.2, 150.0, 161.8, 178.6, 200.0))
def test_fib_extension_reference():
t = ta.FibExtension()
assert t.update((199.8, 200.0, 199.8, 199.8, 1.0, 0)) is None
assert t.update((100.0, 198.0, 100.0, 100.0, 1.0, 1)) is None
assert t.update((101.0, 110.0, 101.0, 101.0, 1.0, 2)) == pytest.approx((72.8, 58.6, 38.2, 0.0, -61.8))
def test_fib_projection_reference():
t = ta.FibProjection()
assert t.update((199.8, 200.0, 199.8, 199.8, 1.0, 0)) is None
assert t.update((160.0, 198.0, 160.0, 160.0, 1.0, 1)) is None
assert t.update((161.6, 190.0, 161.6, 161.6, 1.0, 2)) is None
assert t.update((171.0, 188.1, 171.0, 171.0, 1.0, 3)) == pytest.approx((165.28, 150.0, 125.28, 85.28))
def test_auto_fib_reference():
t = ta.AutoFib()
assert t.update((199.8, 200.0, 199.8, 199.8, 1.0, 0)) is None
assert t.update((100.0, 198.0, 100.0, 100.0, 1.0, 1)) is None
assert t.update((101.0, 110.0, 101.0, 101.0, 1.0, 2)) == pytest.approx((100.0, 123.6, 138.2, 150.0, 161.8, 178.6, 200.0))
def test_golden_pocket_reference():
t = ta.GoldenPocket()
assert t.update((199.8, 200.0, 199.8, 199.8, 1.0, 0)) is None
assert t.update((100.0, 198.0, 100.0, 100.0, 1.0, 1)) is None
assert t.update((101.0, 110.0, 101.0, 101.0, 1.0, 2)) == pytest.approx((161.8, 163.4, 165.0))
def test_fib_confluence_reference():
t = ta.FibConfluence()
assert t.update((199.8, 200.0, 199.8, 199.8, 1.0, 0)) is None
assert t.update((100.0, 198.0, 100.0, 100.0, 1.0, 1)) is None
assert t.update((101.0, 160.0, 101.0, 101.0, 1.0, 2)) is None
assert t.update((144.0, 158.4, 144.0, 144.0, 1.0, 3)) == pytest.approx((137.64, 2.0))
def test_fib_fan_reference():
t = ta.FibFan()
assert t.update((199.0, 200.0, 199.0, 199.0, 1.0, 0)) is None
assert t.update((160.0, 190.0, 160.0, 160.0, 1.0, 1)) is None
assert t.update((100.0, 150.0, 100.0, 100.0, 1.0, 2)) is None
assert t.update((105.0, 110.0, 105.0, 105.0, 1.0, 3)) == pytest.approx((142.7, 125.0, 107.3))
def test_fib_arcs_reference():
t = ta.FibArcs()
assert t.update((199.0, 200.0, 199.0, 199.0, 1.0, 0)) is None
assert t.update((160.0, 190.0, 160.0, 160.0, 1.0, 1)) is None
assert t.update((100.0, 150.0, 100.0, 100.0, 1.0, 2)) is None
assert t.update((105.0, 110.0, 105.0, 105.0, 1.0, 3)) == pytest.approx((133.082181, 143.30127, 153.52037))
def test_fib_channel_reference():
t = ta.FibChannel()
assert t.update((199.0, 200.0, 199.0, 199.0, 1.0, 0)) is None
assert t.update((100.0, 190.0, 100.0, 100.0, 1.0, 1)) is None
assert t.update((108.0, 110.0, 108.0, 108.0, 1.0, 2)) is None
assert t.update((210.0, 220.0, 210.0, 210.0, 1.0, 3)) is None
assert t.update((150.0, 200.0, 150.0, 150.0, 1.0, 4)) == pytest.approx((226.666667, 160.746667, 120.0, 54.08))
def test_fib_time_zones_reference():
t = ta.FibTimeZones()
assert t.update((199.0, 200.0, 199.0, 199.0, 1.0, 0)) is None
assert t.update((150.0, 190.0, 150.0, 150.0, 1.0, 1)) == pytest.approx((1.0, 1.0))
assert t.update((151.0, 155.0, 151.0, 151.0, 1.0, 2)) == pytest.approx((1.0, 1.0))
assert t.update((151.0, 155.0, 151.0, 151.0, 1.0, 3)) == pytest.approx((1.0, 2.0))
assert t.update((151.0, 155.0, 151.0, 151.0, 1.0, 4)) == pytest.approx((0.0, 1.0))
assert t.update((151.0, 155.0, 151.0, 151.0, 1.0, 5)) == pytest.approx((1.0, 3.0))
# --- Lifecycle ------------------------------------------------------------
+628
View File
@@ -10629,3 +10629,631 @@ impl WasmOvernightIntradayReturn {
self.inner.warmup_period()
}
}
// ============================== Fibonacci ==============================
/// Candle for the swing-based Fibonacci tools: only high/low drive the tracker,
/// so open/close are pinned to the midpoint.
fn swing_make_candle(high: f64, low: f64) -> Result<wc::Candle, JsError> {
make_candle(high, low, f64::midpoint(high, low), 0.0)
}
#[wasm_bindgen(js_name = FibRetracement)]
pub struct WasmFibRetracement {
inner: wc::FibRetracement,
}
impl Default for WasmFibRetracement {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FibRetracement)]
impl WasmFibRetracement {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFibRetracement {
Self {
inner: wc::FibRetracement::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"level0".into(), &o.level_0.into()).ok();
Reflect::set(&obj, &"level236".into(), &o.level_236.into()).ok();
Reflect::set(&obj, &"level382".into(), &o.level_382.into()).ok();
Reflect::set(&obj, &"level500".into(), &o.level_500.into()).ok();
Reflect::set(&obj, &"level618".into(), &o.level_618.into()).ok();
Reflect::set(&obj, &"level786".into(), &o.level_786.into()).ok();
Reflect::set(&obj, &"level1000".into(), &o.level_1000.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 7];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 7] = o.level_0;
out[i * 7 + 1] = o.level_236;
out[i * 7 + 2] = o.level_382;
out[i * 7 + 3] = o.level_500;
out[i * 7 + 4] = o.level_618;
out[i * 7 + 5] = o.level_786;
out[i * 7 + 6] = o.level_1000;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = FibExtension)]
pub struct WasmFibExtension {
inner: wc::FibExtension,
}
impl Default for WasmFibExtension {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FibExtension)]
impl WasmFibExtension {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFibExtension {
Self {
inner: wc::FibExtension::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"level1272".into(), &o.level_1272.into()).ok();
Reflect::set(&obj, &"level1414".into(), &o.level_1414.into()).ok();
Reflect::set(&obj, &"level1618".into(), &o.level_1618.into()).ok();
Reflect::set(&obj, &"level2000".into(), &o.level_2000.into()).ok();
Reflect::set(&obj, &"level2618".into(), &o.level_2618.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 5];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 5] = o.level_1272;
out[i * 5 + 1] = o.level_1414;
out[i * 5 + 2] = o.level_1618;
out[i * 5 + 3] = o.level_2000;
out[i * 5 + 4] = o.level_2618;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = FibProjection)]
pub struct WasmFibProjection {
inner: wc::FibProjection,
}
impl Default for WasmFibProjection {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FibProjection)]
impl WasmFibProjection {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFibProjection {
Self {
inner: wc::FibProjection::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"level618".into(), &o.level_618.into()).ok();
Reflect::set(&obj, &"level1000".into(), &o.level_1000.into()).ok();
Reflect::set(&obj, &"level1618".into(), &o.level_1618.into()).ok();
Reflect::set(&obj, &"level2618".into(), &o.level_2618.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 4];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 4] = o.level_618;
out[i * 4 + 1] = o.level_1000;
out[i * 4 + 2] = o.level_1618;
out[i * 4 + 3] = o.level_2618;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = AutoFib)]
pub struct WasmAutoFib {
inner: wc::AutoFib,
}
impl Default for WasmAutoFib {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = AutoFib)]
impl WasmAutoFib {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmAutoFib {
Self {
inner: wc::AutoFib::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"level0".into(), &o.level_0.into()).ok();
Reflect::set(&obj, &"level236".into(), &o.level_236.into()).ok();
Reflect::set(&obj, &"level382".into(), &o.level_382.into()).ok();
Reflect::set(&obj, &"level500".into(), &o.level_500.into()).ok();
Reflect::set(&obj, &"level618".into(), &o.level_618.into()).ok();
Reflect::set(&obj, &"level786".into(), &o.level_786.into()).ok();
Reflect::set(&obj, &"level1000".into(), &o.level_1000.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 7];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 7] = o.level_0;
out[i * 7 + 1] = o.level_236;
out[i * 7 + 2] = o.level_382;
out[i * 7 + 3] = o.level_500;
out[i * 7 + 4] = o.level_618;
out[i * 7 + 5] = o.level_786;
out[i * 7 + 6] = o.level_1000;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = GoldenPocket)]
pub struct WasmGoldenPocket {
inner: wc::GoldenPocket,
}
impl Default for WasmGoldenPocket {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = GoldenPocket)]
impl WasmGoldenPocket {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmGoldenPocket {
Self {
inner: wc::GoldenPocket::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"low".into(), &o.low.into()).ok();
Reflect::set(&obj, &"mid".into(), &o.mid.into()).ok();
Reflect::set(&obj, &"high".into(), &o.high.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 3] = o.low;
out[i * 3 + 1] = o.mid;
out[i * 3 + 2] = o.high;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = FibConfluence)]
pub struct WasmFibConfluence {
inner: wc::FibConfluence,
}
impl Default for WasmFibConfluence {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FibConfluence)]
impl WasmFibConfluence {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFibConfluence {
Self {
inner: wc::FibConfluence::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"price".into(), &o.price.into()).ok();
Reflect::set(&obj, &"strength".into(), &o.strength.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 2];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 2] = o.price;
out[i * 2 + 1] = o.strength;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = FibFan)]
pub struct WasmFibFan {
inner: wc::FibFan,
}
impl Default for WasmFibFan {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FibFan)]
impl WasmFibFan {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFibFan {
Self {
inner: wc::FibFan::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"fan382".into(), &o.fan_382.into()).ok();
Reflect::set(&obj, &"fan500".into(), &o.fan_500.into()).ok();
Reflect::set(&obj, &"fan618".into(), &o.fan_618.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 3] = o.fan_382;
out[i * 3 + 1] = o.fan_500;
out[i * 3 + 2] = o.fan_618;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = FibArcs)]
pub struct WasmFibArcs {
inner: wc::FibArcs,
}
impl Default for WasmFibArcs {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FibArcs)]
impl WasmFibArcs {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFibArcs {
Self {
inner: wc::FibArcs::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"arc382".into(), &o.arc_382.into()).ok();
Reflect::set(&obj, &"arc500".into(), &o.arc_500.into()).ok();
Reflect::set(&obj, &"arc618".into(), &o.arc_618.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 3];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 3] = o.arc_382;
out[i * 3 + 1] = o.arc_500;
out[i * 3 + 2] = o.arc_618;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = FibChannel)]
pub struct WasmFibChannel {
inner: wc::FibChannel,
}
impl Default for WasmFibChannel {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FibChannel)]
impl WasmFibChannel {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFibChannel {
Self {
inner: wc::FibChannel::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"base".into(), &o.base.into()).ok();
Reflect::set(&obj, &"level618".into(), &o.level_618.into()).ok();
Reflect::set(&obj, &"level1000".into(), &o.level_1000.into()).ok();
Reflect::set(&obj, &"level1618".into(), &o.level_1618.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 4];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 4] = o.base;
out[i * 4 + 1] = o.level_618;
out[i * 4 + 2] = o.level_1000;
out[i * 4 + 3] = o.level_1618;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
#[wasm_bindgen(js_name = FibTimeZones)]
pub struct WasmFibTimeZones {
inner: wc::FibTimeZones,
}
impl Default for WasmFibTimeZones {
fn default() -> Self {
Self::new()
}
}
#[wasm_bindgen(js_class = FibTimeZones)]
impl WasmFibTimeZones {
#[wasm_bindgen(constructor)]
pub fn new() -> WasmFibTimeZones {
Self {
inner: wc::FibTimeZones::new(),
}
}
pub fn update(&mut self, high: f64, low: f64) -> Result<JsValue, JsError> {
let c = swing_make_candle(high, low)?;
Ok(match self.inner.update(c) {
Some(o) => {
let obj = Object::new();
Reflect::set(&obj, &"onZone".into(), &o.on_zone.into()).ok();
Reflect::set(&obj, &"barsToNext".into(), &o.bars_to_next.into()).ok();
obj.into()
}
None => JsValue::NULL,
})
}
pub fn batch(&mut self, high: &[f64], low: &[f64]) -> Result<Float64Array, JsError> {
if high.len() != low.len() {
return Err(JsError::new("high and low must be equal length"));
}
let n = high.len();
let mut out = vec![f64::NAN; n * 2];
for i in 0..n {
if let Some(o) = self.inner.update(swing_make_candle(high[i], low[i])?) {
out[i * 2] = o.on_zone;
out[i * 2 + 1] = o.bars_to_next;
}
}
Ok(Float64Array::from(out.as_slice()))
}
pub fn reset(&mut self) {
self.inner.reset();
}
#[wasm_bindgen(js_name = isReady)]
pub fn is_ready(&self) -> bool {
self.inner.is_ready()
}
#[wasm_bindgen(js_name = warmupPeriod)]
pub fn warmup_period(&self) -> usize {
self.inner.warmup_period()
}
}
@@ -0,0 +1,176 @@
//! Auto-Fibonacci — retracement of the most significant recent swing leg.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// How many recent pivots to consider when picking the dominant leg.
const PIVOT_HISTORY: usize = 6;
/// The seven canonical retracement ratios, in ascending order.
const RATIOS: [f64; 7] = [0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0];
/// Auto-Fibonacci retracement levels for the dominant recent swing leg.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AutoFibOutput {
/// 0.0% — the dominant leg's end.
pub level_0: f64,
/// 23.6% retracement.
pub level_236: f64,
/// 38.2% retracement.
pub level_382: f64,
/// 50% retracement.
pub level_500: f64,
/// 61.8% retracement.
pub level_618: f64,
/// 78.6% retracement.
pub level_786: f64,
/// 100% — the dominant leg's start.
pub level_1000: f64,
}
/// Auto-Fibonacci (`AutoFib`).
///
/// Like [`crate::indicators::FibRetracement`], but instead of always using the
/// immediate last leg it scans the last six confirmed pivots and anchors the
/// retracement on the single largest-magnitude leg among them — the dominant
/// swing the market is most likely respecting.
///
/// Parameter-free; construction is infallible. Returns `None` until two pivots
/// have confirmed.
///
/// See `crates/wickra-core/src/indicators/auto_fib.rs`.
#[derive(Debug, Clone)]
pub struct AutoFib {
swing: SwingTracker,
}
impl AutoFib {
/// Construct a new Auto-Fibonacci tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, PIVOT_HISTORY),
}
}
fn levels(&self) -> Option<AutoFibOutput> {
let dominant = self.swing.pivots().windows(2).max_by(|x, y| {
(x[0].price - x[1].price)
.abs()
.total_cmp(&(y[0].price - y[1].price).abs())
})?;
let (start, end) = (dominant[0].price, dominant[1].price);
let level = |r: f64| end + r * (start - end);
Some(AutoFibOutput {
level_0: level(RATIOS[0]),
level_236: level(RATIOS[1]),
level_382: level(RATIOS[2]),
level_500: level(RATIOS[3]),
level_618: level(RATIOS[4]),
level_786: level(RATIOS[5]),
level_1000: level(RATIOS[6]),
})
}
}
impl Default for AutoFib {
fn default() -> Self {
Self::new()
}
}
impl Indicator for AutoFib {
type Input = Candle;
type Output = AutoFibOutput;
fn update(&mut self, candle: Candle) -> Option<AutoFibOutput> {
self.swing.update(candle);
self.levels()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 2
}
fn name(&self) -> &'static str {
"AutoFib"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::indicators::pattern_swing::candles_for_pivots;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn accessors_and_metadata() {
let indicator = AutoFib::new();
assert_eq!(indicator.name(), "AutoFib");
assert_eq!(indicator.warmup_period(), 2);
assert!(!indicator.is_ready());
assert!(!AutoFib::default().is_ready());
}
#[test]
fn no_output_before_two_pivots() {
let mut indicator = AutoFib::new();
let outputs: Vec<_> = candles_for_pivots(&[120.0])
.into_iter()
.map(|c| indicator.update(c))
.collect();
assert!(outputs.iter().all(Option::is_none));
}
#[test]
fn anchors_on_the_largest_leg() {
// Pivots: 130 -> 120 (small, 10) -> 220 (large, 100) -> 200 (small, 20).
// The dominant leg is 120 -> 220; its retracement spans [120, 220].
let mut indicator = AutoFib::new();
let mut last = None;
for candle in candles_for_pivots(&[130.0, 120.0, 220.0, 200.0]) {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
// Largest leg 120 -> 220: 0% on 220 (end), 100% on 120 (start).
assert_relative_eq!(v.level_0, 220.0);
assert_relative_eq!(v.level_1000, 120.0);
assert_relative_eq!(v.level_500, 170.0);
assert_relative_eq!(v.level_618, 220.0 + 0.618 * (120.0 - 220.0));
}
#[test]
fn reset_clears_state() {
let mut indicator = AutoFib::new();
for candle in candles_for_pivots(&[200.0, 100.0]) {
let _ = indicator.update(candle);
}
assert!(indicator.is_ready());
indicator.reset();
assert!(!indicator.is_ready());
let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
assert!(indicator.update(c).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = candles_for_pivots(&[130.0, 120.0, 220.0, 200.0]);
let mut a = AutoFib::new();
let mut b = AutoFib::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,198 @@
//! Fibonacci Arcs — semicircular retracement levels centred on the swing end,
//! decaying back toward it as time elapses.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// The three arc ratios drawn (38.2% / 50% / 61.8%).
const RATIOS: [f64; 3] = [0.382, 0.5, 0.618];
/// Fibonacci Arc prices evaluated at the current bar.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FibArcsOutput {
/// Price of the 38.2% arc at the current bar.
pub arc_382: f64,
/// Price of the 50% arc at the current bar.
pub arc_500: f64,
/// Price of the 61.8% arc at the current bar.
pub arc_618: f64,
}
/// Fibonacci Arcs (`FibArcs`).
///
/// Three arcs centred on the end of the most recent confirmed swing leg. Time is
/// normalised by the leg's bar-width so the construction is chart-scale-free: at
/// the leg's end bar each arc sits exactly on its retracement level, and as time
/// elapses the arc curves back toward the swing-end price, reaching it one leg
/// width later.
///
/// ```text
/// u = (cur - end_bar) / (end_bar - start_bar)
/// arc(r) = end + (start - end) * r * sqrt(max(0, 1 - u^2))
/// ```
///
/// Parameter-free; construction is infallible. Returns `None` until the first
/// leg is complete.
///
/// See `crates/wickra-core/src/indicators/fib_arcs.rs`.
#[derive(Debug, Clone)]
pub struct FibArcs {
swing: SwingTracker,
}
impl FibArcs {
/// Construct a new Fibonacci Arcs tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, 2),
}
}
fn arcs(&self) -> Option<FibArcsOutput> {
let pivots = self.swing.pivots();
let start = pivots.first()?;
let end = pivots.get(1)?;
// Consecutive pivots occur at strictly increasing bars → span >= 1 bar.
let span_bars = (end.bar - start.bar) as f64;
let u = (self.swing.current_bar() - end.bar) as f64 / span_bars;
let curve = (1.0 - u * u).max(0.0).sqrt();
let arc = |r: f64| end.price + (start.price - end.price) * r * curve;
Some(FibArcsOutput {
arc_382: arc(RATIOS[0]),
arc_500: arc(RATIOS[1]),
arc_618: arc(RATIOS[2]),
})
}
}
impl Default for FibArcs {
fn default() -> Self {
Self::new()
}
}
impl Indicator for FibArcs {
type Input = Candle;
type Output = FibArcsOutput;
fn update(&mut self, candle: Candle) -> Option<FibArcsOutput> {
self.swing.update(candle);
self.arcs()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 2
}
fn name(&self) -> &'static str {
"FibArcs"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(high: f64, low: f64, ts: i64) -> Candle {
Candle::new(low, high, low, low, 1.0, ts).unwrap()
}
/// Leg start=200 (bar 0) -> end=100 (bar 2), confirmed at bar 3 so the arc is
/// first reported with `u = (3 - 2) / (2 - 0) = 0.5`.
fn down_leg() -> Vec<Candle> {
vec![
c(200.0, 199.0, 0),
c(190.0, 160.0, 1), // confirm high @200
c(150.0, 100.0, 2), // extend low to 100 (bar 2)
c(110.0, 105.0, 3), // confirm low @100 -> two pivots
]
}
#[test]
fn accessors_and_metadata() {
let indicator = FibArcs::new();
assert_eq!(indicator.name(), "FibArcs");
assert_eq!(indicator.warmup_period(), 2);
assert!(!indicator.is_ready());
assert!(!FibArcs::default().is_ready());
}
#[test]
fn no_output_before_two_pivots() {
let mut indicator = FibArcs::new();
let outputs: Vec<_> = [c(200.0, 199.0, 0), c(190.0, 150.0, 1)]
.into_iter()
.map(|x| indicator.update(x))
.collect();
assert!(outputs.iter().all(Option::is_none));
assert!(!indicator.is_ready());
}
#[test]
fn arcs_curve_back_toward_the_swing_end() {
let mut indicator = FibArcs::new();
let mut last = None;
for candle in down_leg() {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
// u = 0.5 → curve = sqrt(0.75); arc(r) = 100 + 100 * r * curve.
let curve = 0.75_f64.sqrt();
assert_relative_eq!(v.arc_382, 100.0 + 100.0 * 0.382 * curve);
assert_relative_eq!(v.arc_500, 100.0 + 100.0 * 0.5 * curve);
assert_relative_eq!(v.arc_618, 100.0 + 100.0 * 0.618 * curve);
}
#[test]
fn arc_clamps_to_zero_beyond_one_leg_width() {
// Extend far past the end pivot so u > 1; the curve clamps to 0 and the
// arcs collapse onto the swing-end price.
let mut indicator = FibArcs::new();
for candle in down_leg() {
let _ = indicator.update(candle);
}
// Feed flat bars that neither extend nor confirm a new pivot.
let mut last = None;
for ts in 4..12 {
last = indicator.update(c(108.0, 106.0, ts));
}
let v = last.unwrap();
assert_relative_eq!(v.arc_382, 100.0);
assert_relative_eq!(v.arc_618, 100.0);
}
#[test]
fn reset_clears_state() {
let mut indicator = FibArcs::new();
for candle in down_leg() {
let _ = indicator.update(candle);
}
indicator.reset();
assert!(!indicator.is_ready());
assert!(indicator.update(c(100.0, 99.5, 0)).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = down_leg();
let mut a = FibArcs::new();
let mut b = FibArcs::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,192 @@
//! Fibonacci Channel — a sloped base trendline plus parallel lines offset by
//! Fibonacci multiples of the channel width.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// The parallel-line ratios above the base (61.8% / 100% / 161.8% of the width).
const RATIOS: [f64; 3] = [0.618, 1.0, 1.618];
/// Fibonacci Channel line prices evaluated at the current bar.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FibChannelOutput {
/// The base trendline price at the current bar.
pub base: f64,
/// Base + 61.8% of the channel width.
pub level_618: f64,
/// Base + 100% of the width — the opposite channel boundary.
pub level_1000: f64,
/// Base + 161.8% of the width.
pub level_1618: f64,
}
/// Fibonacci Channel (`FibChannel`).
///
/// From the last three confirmed pivots, the two same-direction outer pivots
/// define a sloped base trendline and the opposite middle pivot sets the channel
/// width (its signed distance from the base line). Parallel lines are then offset
/// by Fibonacci multiples of that width and reported at the current bar.
///
/// ```text
/// slope = (p2 - p0) / (bar2 - bar0)
/// base(bar) = p0 + slope * (bar - bar0)
/// width = p1 - base(bar1)
/// level(r) = base(cur) + r * width
/// ```
///
/// Parameter-free; construction is infallible. Returns `None` until three pivots
/// have confirmed.
///
/// See `crates/wickra-core/src/indicators/fib_channel.rs`.
#[derive(Debug, Clone)]
pub struct FibChannel {
swing: SwingTracker,
}
impl FibChannel {
/// Construct a new Fibonacci Channel tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, 3),
}
}
fn channel(&self) -> Option<FibChannelOutput> {
let pivots = self.swing.pivots();
let p0 = pivots.first()?;
let p1 = pivots.get(1)?;
let p2 = pivots.get(2)?;
// p0 and p2 are the same-direction outer pivots; their bars differ
// strictly, so the slope denominator is non-zero.
let slope = (p2.price - p0.price) / (p2.bar - p0.bar) as f64;
let base_at = |bar: usize| p0.price + slope * (bar - p0.bar) as f64;
let width = p1.price - base_at(p1.bar);
let base = base_at(self.swing.current_bar());
Some(FibChannelOutput {
base,
level_618: base + RATIOS[0] * width,
level_1000: base + RATIOS[1] * width,
level_1618: base + RATIOS[2] * width,
})
}
}
impl Default for FibChannel {
fn default() -> Self {
Self::new()
}
}
impl Indicator for FibChannel {
type Input = Candle;
type Output = FibChannelOutput;
fn update(&mut self, candle: Candle) -> Option<FibChannelOutput> {
self.swing.update(candle);
self.channel()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
3
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 3
}
fn name(&self) -> &'static str {
"FibChannel"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(high: f64, low: f64, ts: i64) -> Candle {
Candle::new(low, high, low, low, 1.0, ts).unwrap()
}
/// Pivots: high 200 (bar 0), low 100 (bar 1), high 220 (bar 3); confirmed at
/// bar 4 so the channel is first reported at current bar 4.
fn three_pivots() -> Vec<Candle> {
vec![
c(200.0, 199.0, 0),
c(190.0, 100.0, 1), // confirm high @200, low candidate @100
c(110.0, 108.0, 2), // confirm low @100, high candidate @110
c(220.0, 210.0, 3), // extend high to 220 (bar 3)
c(200.0, 150.0, 4), // confirm high @220 -> three pivots
]
}
#[test]
fn accessors_and_metadata() {
let indicator = FibChannel::new();
assert_eq!(indicator.name(), "FibChannel");
assert_eq!(indicator.warmup_period(), 3);
assert!(!indicator.is_ready());
assert!(!FibChannel::default().is_ready());
}
#[test]
fn no_output_before_three_pivots() {
let mut indicator = FibChannel::new();
let outputs: Vec<_> = [c(200.0, 199.0, 0), c(190.0, 100.0, 1), c(110.0, 108.0, 2)]
.into_iter()
.map(|x| indicator.update(x))
.collect();
// Only two pivots confirm within these three bars.
assert!(outputs.iter().all(Option::is_none));
assert!(!indicator.is_ready());
}
#[test]
fn channel_levels_from_three_pivots() {
let mut indicator = FibChannel::new();
let mut last = None;
for candle in three_pivots() {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
// Base through highs (0,200) and (3,220); width from low (1,100); cur = 4.
let slope = (220.0 - 200.0) / 3.0;
let base_cur = 200.0 + slope * 4.0;
let width = 100.0 - (200.0 + slope * 1.0);
assert_relative_eq!(v.base, base_cur);
assert_relative_eq!(v.level_1000, base_cur + width);
assert_relative_eq!(v.level_618, base_cur + 0.618 * width);
assert_relative_eq!(v.level_1618, base_cur + 1.618 * width);
}
#[test]
fn reset_clears_state() {
let mut indicator = FibChannel::new();
for candle in three_pivots() {
let _ = indicator.update(candle);
}
assert!(indicator.is_ready());
indicator.reset();
assert!(!indicator.is_ready());
assert!(indicator.update(c(100.0, 99.5, 0)).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = three_pivots();
let mut a = FibChannel::new();
let mut b = FibChannel::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,181 @@
//! Fibonacci Confluence — the strongest retracement cluster across recent legs.
use crate::indicators::pattern_swing::{
approx_equal, SwingTracker, LEVEL_TOLERANCE, SWING_THRESHOLD,
};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// How many recent pivots to consider; six pivots yield up to five legs.
const PIVOT_HISTORY: usize = 6;
/// The retracement ratios contributed by each leg to the confluence search.
const RATIOS: [f64; 3] = [0.382, 0.5, 0.618];
/// The strongest Fibonacci confluence zone found across recent swing legs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FibConfluenceOutput {
/// Mean price of the densest cluster of retracement levels.
pub price: f64,
/// Number of retracement levels that fall inside the cluster (its strength).
pub strength: f64,
}
/// Fibonacci Confluence (`FibConfluence`).
///
/// Computes the 38.2% / 50% / 61.8% retracement prices of every leg among the
/// last six confirmed pivots, then reports the densest price cluster — where
/// levels from different legs stack up, the zone the market is most likely to
/// react to. `price` is the cluster mean; `strength` is how many levels it
/// gathers.
///
/// Parameter-free; construction is infallible. Returns `None` until at least two
/// legs (three pivots) exist.
///
/// See `crates/wickra-core/src/indicators/fib_confluence.rs`.
#[derive(Debug, Clone)]
pub struct FibConfluence {
swing: SwingTracker,
}
impl FibConfluence {
/// Construct a new Fibonacci Confluence tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, PIVOT_HISTORY),
}
}
fn confluence(&self) -> Option<FibConfluenceOutput> {
let pivots = self.swing.pivots();
if pivots.len() < 3 {
return None;
}
let levels: Vec<f64> = pivots
.windows(2)
.flat_map(|leg| {
let (start, end) = (leg[0].price, leg[1].price);
RATIOS.map(|r| end + r * (start - end))
})
.collect();
// The `len < 3` guard guarantees at least two legs, hence a non-empty
// level set, so `max_by` always yields a cluster.
let (count, total) = levels
.iter()
.map(|&center| {
let members: Vec<f64> = levels
.iter()
.copied()
.filter(|&x| approx_equal(x, center, LEVEL_TOLERANCE))
.collect();
(members.len(), members.iter().sum::<f64>())
})
.max_by(|a, b| a.0.cmp(&b.0))
.expect("at least two legs guarantee a non-empty level set");
Some(FibConfluenceOutput {
price: total / count as f64,
strength: count as f64,
})
}
}
impl Default for FibConfluence {
fn default() -> Self {
Self::new()
}
}
impl Indicator for FibConfluence {
type Input = Candle;
type Output = FibConfluenceOutput;
fn update(&mut self, candle: Candle) -> Option<FibConfluenceOutput> {
self.swing.update(candle);
self.confluence()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
3
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 3
}
fn name(&self) -> &'static str {
"FibConfluence"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::indicators::pattern_swing::candles_for_pivots;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn accessors_and_metadata() {
let indicator = FibConfluence::new();
assert_eq!(indicator.name(), "FibConfluence");
assert_eq!(indicator.warmup_period(), 3);
assert!(!indicator.is_ready());
assert!(!FibConfluence::default().is_ready());
}
#[test]
fn no_output_before_two_legs() {
let mut indicator = FibConfluence::new();
let outputs: Vec<_> = candles_for_pivots(&[200.0, 100.0])
.into_iter()
.map(|c| indicator.update(c))
.collect();
assert!(outputs.iter().all(Option::is_none));
assert!(!indicator.is_ready());
}
#[test]
fn picks_the_densest_cluster() {
// Legs 200->100 and 100->160. The 38.2% of each (138.2 and ~137.08)
// sit within 3% of each other and form the densest cluster (strength 2).
let mut indicator = FibConfluence::new();
let mut last = None;
for candle in candles_for_pivots(&[200.0, 100.0, 160.0]) {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
assert_relative_eq!(v.strength, 2.0);
let want = (138.2 + (160.0 + 0.382 * (100.0 - 160.0))) / 2.0;
assert_relative_eq!(v.price, want, epsilon = 1e-9);
}
#[test]
fn reset_clears_state() {
let mut indicator = FibConfluence::new();
for candle in candles_for_pivots(&[200.0, 100.0, 160.0]) {
let _ = indicator.update(candle);
}
assert!(indicator.is_ready());
indicator.reset();
assert!(!indicator.is_ready());
let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
assert!(indicator.update(c).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = candles_for_pivots(&[200.0, 100.0, 160.0, 120.0]);
let mut a = FibConfluence::new();
let mut b = FibConfluence::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,171 @@
//! Fibonacci Extension of the most recent confirmed swing leg.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// The five canonical extension ratios, in ascending order. Each is a multiple
/// of the swing leg measured from its origin, so `1.0` sits on the leg's end and
/// every ratio here projects further in the direction of the move.
const RATIOS: [f64; 5] = [1.272, 1.414, 1.618, 2.0, 2.618];
/// Fibonacci Extension levels for the most recent swing leg.
///
/// Each field is the price reached if the move continues to the matching
/// multiple of the leg, measured from the leg's start.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FibExtensionOutput {
/// 127.2% extension.
pub level_1272: f64,
/// 141.4% extension.
pub level_1414: f64,
/// 161.8% extension — the "golden" extension.
pub level_1618: f64,
/// 200% extension.
pub level_2000: f64,
/// 261.8% extension.
pub level_2618: f64,
}
/// Fibonacci Extension (`FibExtension`).
///
/// Tracks confirmed swing pivots with a baked-in 5% reversal threshold and, once
/// two pivots exist, projects the leg between them to the canonical extension
/// ratios — the price targets a continuation of the move would reach.
///
/// Parameter-free; construction is infallible. Returns `None` until the first
/// leg is complete.
///
/// See `crates/wickra-core/src/indicators/fib_extension.rs`.
#[derive(Debug, Clone)]
pub struct FibExtension {
swing: SwingTracker,
}
impl FibExtension {
/// Construct a new Fibonacci Extension tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, 2),
}
}
/// Extension price at ratio `e` for a leg from `start` to `end`: the total
/// move is `e` times the leg, measured from `start`.
fn level(start: f64, end: f64, e: f64) -> f64 {
start + e * (end - start)
}
fn levels(&self) -> Option<FibExtensionOutput> {
let pivots = self.swing.pivots();
let [start, end] = [pivots.first()?.price, pivots.get(1)?.price];
Some(FibExtensionOutput {
level_1272: Self::level(start, end, RATIOS[0]),
level_1414: Self::level(start, end, RATIOS[1]),
level_1618: Self::level(start, end, RATIOS[2]),
level_2000: Self::level(start, end, RATIOS[3]),
level_2618: Self::level(start, end, RATIOS[4]),
})
}
}
impl Default for FibExtension {
fn default() -> Self {
Self::new()
}
}
impl Indicator for FibExtension {
type Input = Candle;
type Output = FibExtensionOutput;
fn update(&mut self, candle: Candle) -> Option<FibExtensionOutput> {
self.swing.update(candle);
self.levels()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 2
}
fn name(&self) -> &'static str {
"FibExtension"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::indicators::pattern_swing::candles_for_pivots;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn accessors_and_metadata() {
let indicator = FibExtension::new();
assert_eq!(indicator.name(), "FibExtension");
assert_eq!(indicator.warmup_period(), 2);
assert!(!indicator.is_ready());
assert!(!FibExtension::default().is_ready());
}
#[test]
fn no_output_before_two_pivots() {
let mut indicator = FibExtension::new();
let outputs: Vec<_> = candles_for_pivots(&[120.0])
.into_iter()
.map(|c| indicator.update(c))
.collect();
assert!(outputs.iter().all(Option::is_none));
}
#[test]
fn extension_levels_of_a_down_leg() {
// Leg start = 200 (high), end = 100 (low): a 100-point drop continued.
let mut indicator = FibExtension::new();
let mut last = None;
for candle in candles_for_pivots(&[200.0, 100.0]) {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
// 161.8% extension projects 1.618 * (-100) below the 200 origin.
assert_relative_eq!(v.level_1272, 200.0 - 127.2);
assert_relative_eq!(v.level_1414, 200.0 - 141.4);
assert_relative_eq!(v.level_1618, 200.0 - 161.8);
assert_relative_eq!(v.level_2000, 0.0);
assert_relative_eq!(v.level_2618, 200.0 - 261.8);
}
#[test]
fn reset_clears_state() {
let mut indicator = FibExtension::new();
for candle in candles_for_pivots(&[200.0, 100.0]) {
let _ = indicator.update(candle);
}
indicator.reset();
assert!(!indicator.is_ready());
let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
assert!(indicator.update(c).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = candles_for_pivots(&[200.0, 100.0, 150.0]);
let mut a = FibExtension::new();
let mut b = FibExtension::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,180 @@
//! Fibonacci Fan — trendlines fanning from a swing start through the
//! retracement levels at the swing end, extended to the current bar.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// The three fan ratios drawn (38.2% / 50% / 61.8%).
const RATIOS: [f64; 3] = [0.382, 0.5, 0.618];
/// Fibonacci Fan line prices evaluated at the current bar.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FibFanOutput {
/// Price of the 38.2% fan line at the current bar.
pub fan_382: f64,
/// Price of the 50% fan line at the current bar.
pub fan_500: f64,
/// Price of the 61.8% fan line at the current bar.
pub fan_618: f64,
}
/// Fibonacci Fan (`FibFan`).
///
/// Anchored at the start of the most recent confirmed swing leg, three lines fan
/// out through the 38.2% / 50% / 61.8% retracement levels located at the leg's
/// end bar, then extend to the current bar. Each line's price is reported as the
/// fan opens with elapsed time.
///
/// ```text
/// line(r) = start + r * (end - start) * (cur - start_bar) / (end_bar - start_bar)
/// ```
///
/// Parameter-free; construction is infallible. Returns `None` until the first
/// leg is complete.
///
/// See `crates/wickra-core/src/indicators/fib_fan.rs`.
#[derive(Debug, Clone)]
pub struct FibFan {
swing: SwingTracker,
}
impl FibFan {
/// Construct a new Fibonacci Fan tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, 2),
}
}
fn fan(&self) -> Option<FibFanOutput> {
let pivots = self.swing.pivots();
let start = pivots.first()?;
let end = pivots.get(1)?;
// Consecutive pivots occur at strictly increasing bars, so the span is
// always at least one bar — no division by zero.
let span_bars = (end.bar - start.bar) as f64;
let elapsed = (self.swing.current_bar() - start.bar) as f64;
let progress = elapsed / span_bars;
let line = |r: f64| start.price + r * (end.price - start.price) * progress;
Some(FibFanOutput {
fan_382: line(RATIOS[0]),
fan_500: line(RATIOS[1]),
fan_618: line(RATIOS[2]),
})
}
}
impl Default for FibFan {
fn default() -> Self {
Self::new()
}
}
impl Indicator for FibFan {
type Input = Candle;
type Output = FibFanOutput;
fn update(&mut self, candle: Candle) -> Option<FibFanOutput> {
self.swing.update(candle);
self.fan()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 2
}
fn name(&self) -> &'static str {
"FibFan"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(high: f64, low: f64, ts: i64) -> Candle {
Candle::new(low, high, low, low, 1.0, ts).unwrap()
}
/// Drive a leg start=200 (bar 0) -> end=100 (bar 2), confirmed at bar 3, so
/// the fan is first reported at bar 3 with `progress = 3 / 2 = 1.5`.
fn down_leg() -> Vec<Candle> {
vec![
c(200.0, 199.0, 0), // bootstrap high @200 (bar 0)
c(190.0, 160.0, 1), // confirm high @200, low candidate @160
c(150.0, 100.0, 2), // extend low to 100 (bar 2)
c(110.0, 105.0, 3), // confirm low @100 -> two pivots
]
}
#[test]
fn accessors_and_metadata() {
let indicator = FibFan::new();
assert_eq!(indicator.name(), "FibFan");
assert_eq!(indicator.warmup_period(), 2);
assert!(!indicator.is_ready());
assert!(!FibFan::default().is_ready());
}
#[test]
fn no_output_before_two_pivots() {
let mut indicator = FibFan::new();
// Only the high confirms here; no end pivot yet.
let outputs: Vec<_> = [c(200.0, 199.0, 0), c(190.0, 150.0, 1)]
.into_iter()
.map(|x| indicator.update(x))
.collect();
assert!(outputs.iter().all(Option::is_none));
assert!(!indicator.is_ready());
}
#[test]
fn fan_lines_open_with_elapsed_time() {
let mut indicator = FibFan::new();
let mut last = None;
for candle in down_leg() {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
// progress = (3 - 0) / (2 - 0) = 1.5; line(r) = 200 + r*(-100)*1.5.
assert_relative_eq!(v.fan_382, 200.0 - 0.382 * 150.0);
assert_relative_eq!(v.fan_500, 125.0);
assert_relative_eq!(v.fan_618, 200.0 - 0.618 * 150.0);
}
#[test]
fn reset_clears_state() {
let mut indicator = FibFan::new();
for candle in down_leg() {
let _ = indicator.update(candle);
}
assert!(indicator.is_ready());
indicator.reset();
assert!(!indicator.is_ready());
assert!(indicator.update(c(100.0, 99.5, 0)).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = down_leg();
let mut a = FibFan::new();
let mut b = FibFan::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,165 @@
//! Fibonacci Projection — a measured move from the last three swing pivots.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// The four canonical projection ratios, in ascending order. Each scales the
/// A→B leg and projects it from C; `1.0` is the classic AB=CD measured move.
const RATIOS: [f64; 4] = [0.618, 1.0, 1.618, 2.618];
/// Fibonacci Projection levels (the C→D target zone of a measured move).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FibProjectionOutput {
/// 61.8% projection of the A→B leg from C.
pub level_618: f64,
/// 100% projection — the AB=CD measured move.
pub level_1000: f64,
/// 161.8% projection.
pub level_1618: f64,
/// 261.8% projection.
pub level_2618: f64,
}
/// Fibonacci Projection (`FibProjection`).
///
/// Reads the last three confirmed swing pivots as the points A, B and C of a
/// measured move and projects the A→B leg from C at the canonical ratios — the
/// price targets for the C→D leg.
///
/// Parameter-free; construction is infallible. Returns `None` until three
/// pivots have confirmed.
///
/// See `crates/wickra-core/src/indicators/fib_projection.rs`.
#[derive(Debug, Clone)]
pub struct FibProjection {
swing: SwingTracker,
}
impl FibProjection {
/// Construct a new Fibonacci Projection tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, 3),
}
}
fn levels(&self) -> Option<FibProjectionOutput> {
let pivots = self.swing.pivots();
let [a, b, c] = [
pivots.first()?.price,
pivots.get(1)?.price,
pivots.get(2)?.price,
];
let project = |p: f64| c + p * (b - a);
Some(FibProjectionOutput {
level_618: project(RATIOS[0]),
level_1000: project(RATIOS[1]),
level_1618: project(RATIOS[2]),
level_2618: project(RATIOS[3]),
})
}
}
impl Default for FibProjection {
fn default() -> Self {
Self::new()
}
}
impl Indicator for FibProjection {
type Input = Candle;
type Output = FibProjectionOutput;
fn update(&mut self, candle: Candle) -> Option<FibProjectionOutput> {
self.swing.update(candle);
self.levels()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
3
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 3
}
fn name(&self) -> &'static str {
"FibProjection"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::indicators::pattern_swing::candles_for_pivots;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn accessors_and_metadata() {
let indicator = FibProjection::new();
assert_eq!(indicator.name(), "FibProjection");
assert_eq!(indicator.warmup_period(), 3);
assert!(!indicator.is_ready());
assert!(!FibProjection::default().is_ready());
}
#[test]
fn no_output_before_three_pivots() {
let mut indicator = FibProjection::new();
let outputs: Vec<_> = candles_for_pivots(&[200.0, 100.0])
.into_iter()
.map(|c| indicator.update(c))
.collect();
assert!(outputs.iter().all(Option::is_none));
assert!(!indicator.is_ready());
}
#[test]
fn measured_move_from_three_pivots() {
// A = 200 (high), B = 160 (low), C = 190 (high). A->B = -40, projected
// down from C.
let mut indicator = FibProjection::new();
let mut last = None;
for candle in candles_for_pivots(&[200.0, 160.0, 190.0]) {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
let (a, b, c) = (200.0, 160.0, 190.0);
assert_relative_eq!(v.level_618, c + 0.618 * (b - a));
assert_relative_eq!(v.level_1000, c + (b - a));
assert_relative_eq!(v.level_1618, c + 1.618 * (b - a));
assert_relative_eq!(v.level_2618, c + 2.618 * (b - a));
}
#[test]
fn reset_clears_state() {
let mut indicator = FibProjection::new();
for candle in candles_for_pivots(&[200.0, 160.0, 190.0]) {
let _ = indicator.update(candle);
}
assert!(indicator.is_ready());
indicator.reset();
assert!(!indicator.is_ready());
let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
assert!(indicator.update(c).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = candles_for_pivots(&[200.0, 160.0, 190.0, 150.0]);
let mut a = FibProjection::new();
let mut b = FibProjection::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,201 @@
//! Fibonacci Retracement of the most recent confirmed swing leg.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// The seven canonical retracement ratios, in ascending order. `0.0` marks the
/// most recent swing extreme (the end of the leg) and `1.0` the swing origin
/// (its start); the interior ratios are the classic Fibonacci pullbacks.
const RATIOS: [f64; 7] = [0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0];
/// Fibonacci Retracement levels for the most recent swing leg.
///
/// Each field is the price at the matching retracement ratio, measured from the
/// leg's end (`level_0`, the latest confirmed extreme) back toward its start
/// (`level_1000`, the prior pivot).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FibRetracementOutput {
/// 0.0% — the most recent confirmed swing extreme.
pub level_0: f64,
/// 23.6% retracement.
pub level_236: f64,
/// 38.2% retracement.
pub level_382: f64,
/// 50% retracement (not a Fibonacci ratio, but conventionally drawn).
pub level_500: f64,
/// 61.8% retracement — the "golden ratio" pullback.
pub level_618: f64,
/// 78.6% retracement.
pub level_786: f64,
/// 100% — the swing origin.
pub level_1000: f64,
}
/// Fibonacci Retracement (`FibRetracement`).
///
/// Tracks confirmed swing pivots with a baked-in 5% reversal threshold (the
/// same non-repainting logic as [`crate::indicators::ZigZag`]) and, once two
/// pivots exist, reports the seven retracement levels of the leg between them.
///
/// The levels are recomputed each time a new pivot confirms; between
/// confirmations [`Indicator::update`] returns the locked levels of the current
/// leg. Before the first leg is complete it returns `None`.
///
/// Parameter-free: the threshold is a compile-time constant, mirroring the
/// chart- and harmonic-pattern detectors, so construction is infallible.
///
/// See `crates/wickra-core/src/indicators/fib_retracement.rs`.
#[derive(Debug, Clone)]
pub struct FibRetracement {
swing: SwingTracker,
}
impl FibRetracement {
/// Construct a new Fibonacci Retracement tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, 2),
}
}
/// Retracement price at ratio `r` for a leg from `start` to `end`: `0.0`
/// sits on `end`, `1.0` on `start`.
fn level(start: f64, end: f64, r: f64) -> f64 {
end + r * (start - end)
}
fn levels(&self) -> Option<FibRetracementOutput> {
let pivots = self.swing.pivots();
let [start, end] = [pivots.first()?.price, pivots.get(1)?.price];
Some(FibRetracementOutput {
level_0: Self::level(start, end, RATIOS[0]),
level_236: Self::level(start, end, RATIOS[1]),
level_382: Self::level(start, end, RATIOS[2]),
level_500: Self::level(start, end, RATIOS[3]),
level_618: Self::level(start, end, RATIOS[4]),
level_786: Self::level(start, end, RATIOS[5]),
level_1000: Self::level(start, end, RATIOS[6]),
})
}
}
impl Default for FibRetracement {
fn default() -> Self {
Self::new()
}
}
impl Indicator for FibRetracement {
type Input = Candle;
type Output = FibRetracementOutput;
fn update(&mut self, candle: Candle) -> Option<FibRetracementOutput> {
self.swing.update(candle);
self.levels()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 2
}
fn name(&self) -> &'static str {
"FibRetracement"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::indicators::pattern_swing::candles_for_pivots;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn accessors_and_metadata() {
let indicator = FibRetracement::new();
assert_eq!(indicator.name(), "FibRetracement");
assert_eq!(indicator.warmup_period(), 2);
assert!(!indicator.is_ready());
assert!(!FibRetracement::default().is_ready());
}
#[test]
fn no_output_before_two_pivots() {
let mut indicator = FibRetracement::new();
// A single confirmed pivot is not enough to define a leg.
let candles = candles_for_pivots(&[120.0]);
let outputs: Vec<_> = candles.into_iter().map(|c| indicator.update(c)).collect();
assert!(outputs.iter().all(Option::is_none));
assert!(!indicator.is_ready());
}
#[test]
fn retracement_levels_of_a_down_leg() {
// Leg start = 200 (high), end = 100 (low): a 100-point drop.
let mut indicator = FibRetracement::new();
let mut last = None;
for candle in candles_for_pivots(&[200.0, 100.0]) {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
// 0% on the low (end), 100% on the high (start).
assert_relative_eq!(v.level_0, 100.0);
assert_relative_eq!(v.level_1000, 200.0);
// 61.8% retracement of a 100-point drop, measured up from the low.
assert_relative_eq!(v.level_618, 161.8);
assert_relative_eq!(v.level_500, 150.0);
assert_relative_eq!(v.level_382, 138.2);
assert_relative_eq!(v.level_236, 123.6);
assert_relative_eq!(v.level_786, 178.6);
}
#[test]
fn levels_refresh_on_a_new_leg() {
// Four pivots, cap = 2: once the third and fourth confirm, the reported
// leg shifts to the latest pair (130 high -> 90 low).
let mut indicator = FibRetracement::new();
let mut last = None;
for candle in candles_for_pivots(&[200.0, 100.0, 130.0, 90.0]) {
last = indicator.update(candle);
}
let v = last.unwrap();
assert_relative_eq!(v.level_0, 90.0);
assert_relative_eq!(v.level_1000, 130.0);
assert_relative_eq!(v.level_618, 90.0 + 0.618 * 40.0);
}
#[test]
fn reset_clears_state() {
let mut indicator = FibRetracement::new();
for candle in candles_for_pivots(&[200.0, 100.0]) {
let _ = indicator.update(candle);
}
assert!(indicator.is_ready());
indicator.reset();
assert!(!indicator.is_ready());
let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
assert!(indicator.update(c).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = candles_for_pivots(&[200.0, 100.0, 150.0]);
let mut a = FibRetracement::new();
let mut b = FibRetracement::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,181 @@
//! Fibonacci Time Zones — vertical markers at Fibonacci bar-distances from the
//! most recent swing pivot.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Where the current bar sits relative to the Fibonacci time-zone grid anchored
/// on the most recent confirmed pivot.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FibTimeZonesOutput {
/// `1.0` when the current bar lands on a Fibonacci time zone (a bar distance
/// of 1, 2, 3, 5, 8, 13, … from the anchor pivot), otherwise `0.0`.
pub on_zone: f64,
/// Number of bars until the next Fibonacci time zone (`0` is never returned —
/// when on a zone this is the gap to the following one).
pub bars_to_next: f64,
}
/// Fibonacci Time Zones (`FibTimeZones`).
///
/// Anchored on the most recent confirmed swing pivot, the Fibonacci sequence
/// `1, 2, 3, 5, 8, 13, …` marks bars at which trend changes are classically
/// anticipated. Reports whether the current bar is on a zone and how many bars
/// remain until the next one.
///
/// Parameter-free; construction is infallible. Returns `None` until the first
/// pivot has confirmed.
///
/// See `crates/wickra-core/src/indicators/fib_time_zones.rs`.
#[derive(Debug, Clone)]
pub struct FibTimeZones {
swing: SwingTracker,
}
impl FibTimeZones {
/// Construct a new Fibonacci Time Zones tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, 2),
}
}
fn zones(&self) -> Option<FibTimeZonesOutput> {
let anchor = self.swing.pivots().last()?;
let distance = self.swing.current_bar() - anchor.bar;
// Walk the time-zone sequence 1, 2, 3, 5, 8, … : `lo` advances through the
// members, `on_zone` records a hit, and the loop exits with `lo` holding
// the smallest member strictly greater than `distance`.
let (mut lo, mut hi) = (1usize, 2usize);
let mut on_zone = false;
while lo <= distance {
if lo == distance {
on_zone = true;
}
let next = lo + hi;
lo = hi;
hi = next;
}
Some(FibTimeZonesOutput {
on_zone: f64::from(u8::from(on_zone)),
bars_to_next: (lo - distance) as f64,
})
}
}
impl Default for FibTimeZones {
fn default() -> Self {
Self::new()
}
}
impl Indicator for FibTimeZones {
type Input = Candle;
type Output = FibTimeZonesOutput;
fn update(&mut self, candle: Candle) -> Option<FibTimeZonesOutput> {
self.swing.update(candle);
self.zones()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
!self.swing.pivots().is_empty()
}
fn name(&self) -> &'static str {
"FibTimeZones"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(high: f64, low: f64, ts: i64) -> Candle {
Candle::new(low, high, low, low, 1.0, ts).unwrap()
}
/// One pivot confirms at bar 0 (high @200, confirmed at bar 1); subsequent
/// flat bars neither extend nor confirm, so the anchor stays at bar 0 and the
/// distance equals the current bar index.
fn anchored_run() -> Vec<Candle> {
let mut bars = vec![c(200.0, 199.0, 0), c(190.0, 150.0, 1)];
for ts in 2..=5 {
bars.push(c(155.0, 151.0, ts));
}
bars
}
#[test]
fn accessors_and_metadata() {
let indicator = FibTimeZones::new();
assert_eq!(indicator.name(), "FibTimeZones");
assert_eq!(indicator.warmup_period(), 2);
assert!(!indicator.is_ready());
assert!(!FibTimeZones::default().is_ready());
}
#[test]
fn no_output_before_first_pivot() {
let mut indicator = FibTimeZones::new();
// The bootstrap bar confirms nothing.
assert!(indicator.update(c(200.0, 199.0, 0)).is_none());
assert!(!indicator.is_ready());
}
#[test]
fn flags_zones_and_counts_to_next() {
let mut indicator = FibTimeZones::new();
let out: Vec<_> = anchored_run()
.into_iter()
.map(|x| indicator.update(x))
.collect();
assert!(out[0].is_none()); // bootstrap, no pivot yet
assert!(indicator.is_ready());
// out[i] is reported at current bar i; anchor at bar 0 → distance = i.
let d1 = out[1].unwrap(); // distance 1 → a zone
assert_relative_eq!(d1.on_zone, 1.0);
assert_relative_eq!(d1.bars_to_next, 1.0); // next zone at 2
let d4 = out[4].unwrap(); // distance 4 → not a zone
assert_relative_eq!(d4.on_zone, 0.0);
assert_relative_eq!(d4.bars_to_next, 1.0); // next zone at 5
let d5 = out[5].unwrap(); // distance 5 → a zone
assert_relative_eq!(d5.on_zone, 1.0);
assert_relative_eq!(d5.bars_to_next, 3.0); // next zone at 8
}
#[test]
fn reset_clears_state() {
let mut indicator = FibTimeZones::new();
for candle in anchored_run() {
let _ = indicator.update(candle);
}
assert!(indicator.is_ready());
indicator.reset();
assert!(!indicator.is_ready());
assert!(indicator.update(c(100.0, 99.5, 0)).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = anchored_run();
let mut a = FibTimeZones::new();
let mut b = FibTimeZones::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
@@ -0,0 +1,175 @@
//! Golden Pocket — the 0.618-0.65 optimal-trade-entry zone of the last swing.
use crate::indicators::pattern_swing::{SwingTracker, SWING_THRESHOLD};
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Lower bound of the golden pocket (the 61.8% retracement).
const RATIO_LOW: f64 = 0.618;
/// Upper bound of the golden pocket (the 65% retracement).
const RATIO_HIGH: f64 = 0.65;
/// The golden-pocket zone of the most recent swing leg.
///
/// `low`/`high` bracket the 0.618-0.65 retracement band (sorted, so `low <=
/// high` regardless of swing direction); `mid` is their midpoint.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GoldenPocketOutput {
/// Lower price of the golden-pocket band.
pub low: f64,
/// Midpoint of the band.
pub mid: f64,
/// Upper price of the golden-pocket band.
pub high: f64,
}
/// Golden Pocket (`GoldenPocket`).
///
/// The 0.618-0.65 retracement band of the most recent confirmed swing leg — the
/// "optimal trade entry" zone many swing traders watch for continuation.
///
/// Parameter-free; construction is infallible. Returns `None` until the first
/// leg is complete.
///
/// See `crates/wickra-core/src/indicators/golden_pocket.rs`.
#[derive(Debug, Clone)]
pub struct GoldenPocket {
swing: SwingTracker,
}
impl GoldenPocket {
/// Construct a new Golden Pocket tracker.
#[must_use]
pub const fn new() -> Self {
Self {
swing: SwingTracker::new(SWING_THRESHOLD, 2),
}
}
fn zone(&self) -> Option<GoldenPocketOutput> {
let pivots = self.swing.pivots();
let [start, end] = [pivots.first()?.price, pivots.get(1)?.price];
let span = start - end;
let edge_low = end + RATIO_LOW * span;
let edge_high = end + RATIO_HIGH * span;
let low = edge_low.min(edge_high);
let high = edge_low.max(edge_high);
Some(GoldenPocketOutput {
low,
mid: f64::midpoint(low, high),
high,
})
}
}
impl Default for GoldenPocket {
fn default() -> Self {
Self::new()
}
}
impl Indicator for GoldenPocket {
type Input = Candle;
type Output = GoldenPocketOutput;
fn update(&mut self, candle: Candle) -> Option<GoldenPocketOutput> {
self.swing.update(candle);
self.zone()
}
fn reset(&mut self) {
self.swing.reset();
}
fn warmup_period(&self) -> usize {
2
}
fn is_ready(&self) -> bool {
self.swing.pivots().len() >= 2
}
fn name(&self) -> &'static str {
"GoldenPocket"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::indicators::pattern_swing::candles_for_pivots;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn accessors_and_metadata() {
let indicator = GoldenPocket::new();
assert_eq!(indicator.name(), "GoldenPocket");
assert_eq!(indicator.warmup_period(), 2);
assert!(!indicator.is_ready());
assert!(!GoldenPocket::default().is_ready());
}
#[test]
fn no_output_before_two_pivots() {
let mut indicator = GoldenPocket::new();
let outputs: Vec<_> = candles_for_pivots(&[120.0])
.into_iter()
.map(|c| indicator.update(c))
.collect();
assert!(outputs.iter().all(Option::is_none));
}
#[test]
fn zone_of_a_down_leg() {
// Leg 200 (high) -> 100 (low), span = 100.
let mut indicator = GoldenPocket::new();
let mut last = None;
for candle in candles_for_pivots(&[200.0, 100.0]) {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(indicator.is_ready());
// 61.8% = 161.8, 65% = 165 → sorted band [161.8, 165], mid 163.4.
assert_relative_eq!(v.low, 161.8);
assert_relative_eq!(v.high, 165.0);
assert_relative_eq!(v.mid, 163.4);
}
#[test]
fn band_is_sorted_for_an_up_leg() {
// Latest leg 100 (low) -> 250 (high): span negative, edges flip, but
// low <= high must still hold.
let mut indicator = GoldenPocket::new();
let mut last = None;
for candle in candles_for_pivots(&[200.0, 100.0, 250.0]) {
last = indicator.update(candle);
}
let v = last.unwrap();
assert!(v.low <= v.high);
assert_relative_eq!(v.mid, f64::midpoint(v.low, v.high));
}
#[test]
fn reset_clears_state() {
let mut indicator = GoldenPocket::new();
for candle in candles_for_pivots(&[200.0, 100.0]) {
let _ = indicator.update(candle);
}
indicator.reset();
assert!(!indicator.is_ready());
let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
assert!(indicator.update(c).is_none());
}
#[test]
fn batch_equals_streaming() {
let candles = candles_for_pivots(&[200.0, 100.0, 150.0]);
let mut a = GoldenPocket::new();
let mut b = GoldenPocket::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}
+36 -1
View File
@@ -34,6 +34,7 @@ mod aroon_oscillator;
mod atr;
mod atr_bands;
mod atr_trailing_stop;
mod auto_fib;
mod autocorrelation;
mod average_daily_range;
mod average_drawdown;
@@ -110,6 +111,14 @@ mod evening_doji_star;
mod evwma;
mod falling_three_methods;
mod fama;
mod fib_arcs;
mod fib_channel;
mod fib_confluence;
mod fib_extension;
mod fib_fan;
mod fib_projection;
mod fib_retracement;
mod fib_time_zones;
mod fibonacci_pivots;
mod fisher_transform;
mod flag_pennant;
@@ -125,6 +134,7 @@ mod gain_loss_ratio;
mod gap_side_by_side_white;
mod garman_klass;
mod gartley;
mod golden_pocket;
mod granger_causality;
mod gravestone_doji;
mod hammer;
@@ -401,6 +411,7 @@ pub use aroon_oscillator::AroonOscillator;
pub use atr::Atr;
pub use atr_bands::{AtrBands, AtrBandsOutput};
pub use atr_trailing_stop::AtrTrailingStop;
pub use auto_fib::{AutoFib, AutoFibOutput};
pub use autocorrelation::Autocorrelation;
pub use average_daily_range::AverageDailyRange;
pub use average_drawdown::AverageDrawdown;
@@ -477,6 +488,14 @@ pub use evening_doji_star::EveningDojiStar;
pub use evwma::Evwma;
pub use falling_three_methods::FallingThreeMethods;
pub use fama::Fama;
pub use fib_arcs::{FibArcs, FibArcsOutput};
pub use fib_channel::{FibChannel, FibChannelOutput};
pub use fib_confluence::{FibConfluence, FibConfluenceOutput};
pub use fib_extension::{FibExtension, FibExtensionOutput};
pub use fib_fan::{FibFan, FibFanOutput};
pub use fib_projection::{FibProjection, FibProjectionOutput};
pub use fib_retracement::{FibRetracement, FibRetracementOutput};
pub use fib_time_zones::{FibTimeZones, FibTimeZonesOutput};
pub use fibonacci_pivots::{FibonacciPivots, FibonacciPivotsOutput};
pub use fisher_transform::FisherTransform;
pub use flag_pennant::FlagPennant;
@@ -492,6 +511,7 @@ pub use gain_loss_ratio::GainLossRatio;
pub use gap_side_by_side_white::GapSideBySideWhite;
pub use garman_klass::GarmanKlassVolatility;
pub use gartley::Gartley;
pub use golden_pocket::{GoldenPocket, GoldenPocketOutput};
pub use granger_causality::GrangerCausality;
pub use gravestone_doji::GravestoneDoji;
pub use hammer::Hammer;
@@ -1222,6 +1242,21 @@ pub const FAMILIES: &[(&str, &[&str])] = &[
"ThreeDrives",
],
),
(
"Fibonacci",
&[
"FibRetracement",
"FibExtension",
"FibProjection",
"AutoFib",
"GoldenPocket",
"FibConfluence",
"FibFan",
"FibArcs",
"FibChannel",
"FibTimeZones",
],
),
];
#[cfg(test)]
@@ -1250,6 +1285,6 @@ mod family_tests {
// the actual indicator count is the early-warning signal that an
// indicator was added without being assigned a family.
let total: usize = FAMILIES.iter().map(|(_, ns)| ns.len()).sum();
assert_eq!(total, 367, "FAMILIES total drifted from indicator count");
assert_eq!(total, 377, "FAMILIES total drifted from indicator count");
}
}
@@ -27,14 +27,19 @@ pub(crate) const SWING_THRESHOLD: f64 = 0.05;
/// flat boundary of a rectangle.
pub(crate) const LEVEL_TOLERANCE: f64 = 0.03;
/// A confirmed swing pivot: the extreme price the swing turned from and its
/// direction (`+1.0` for a swing high, `-1.0` for a swing low).
/// A confirmed swing pivot: the extreme price the swing turned from, its
/// direction (`+1.0` for a swing high, `-1.0` for a swing low) and the bar index
/// at which that extreme occurred.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Pivot {
/// Price of the confirmed swing extreme.
pub price: f64,
/// `+1.0` if the pivot is a swing high, `-1.0` if it is a swing low.
pub direction: f64,
/// Zero-based index of the candle at which the swing extreme occurred (not
/// the later bar that confirmed it). Used by the geometric Fibonacci tools
/// (fan, arcs, channel, time zones) to place trendlines and time offsets.
pub bar: usize,
}
/// Non-repainting percent-threshold swing tracker with a bounded pivot history.
@@ -50,6 +55,8 @@ pub(crate) struct Pivot {
pub(crate) struct SwingTracker {
threshold: f64,
cap: usize,
/// Number of candles fed so far; the current bar index is `bars_seen - 1`.
bars_seen: usize,
state: Option<State>,
pivots: Vec<Pivot>,
}
@@ -61,6 +68,8 @@ struct State {
direction: f64,
/// The running candidate extreme price.
extreme: f64,
/// Bar index at which the running extreme was last set.
extreme_bar: usize,
}
impl SwingTracker {
@@ -75,6 +84,7 @@ impl SwingTracker {
Self {
threshold,
cap,
bars_seen: 0,
state: None,
pivots: Vec::new(),
}
@@ -82,11 +92,14 @@ impl SwingTracker {
/// Feed one candle. Returns `true` when a new pivot was confirmed this bar.
pub(crate) fn update(&mut self, candle: Candle) -> bool {
let bar = self.bars_seen;
self.bars_seen += 1;
let Some(s) = self.state else {
// Bootstrap: seed an uptrend tracking the first candle's high.
self.state = Some(State {
direction: 1.0,
extreme: candle.high,
extreme_bar: bar,
});
return false;
};
@@ -97,6 +110,7 @@ impl SwingTracker {
self.state = Some(State {
direction: 1.0,
extreme: candle.high,
extreme_bar: bar,
});
return false;
}
@@ -105,10 +119,12 @@ impl SwingTracker {
self.push(Pivot {
price: s.extreme,
direction: 1.0,
bar: s.extreme_bar,
});
self.state = Some(State {
direction: -1.0,
extreme: candle.low,
extreme_bar: bar,
});
return true;
}
@@ -119,6 +135,7 @@ impl SwingTracker {
self.state = Some(State {
direction: -1.0,
extreme: candle.low,
extreme_bar: bar,
});
return false;
}
@@ -127,10 +144,12 @@ impl SwingTracker {
self.push(Pivot {
price: s.extreme,
direction: -1.0,
bar: s.extreme_bar,
});
self.state = Some(State {
direction: 1.0,
extreme: candle.high,
extreme_bar: bar,
});
return true;
}
@@ -138,6 +157,12 @@ impl SwingTracker {
}
}
/// Zero-based index of the most recently fed candle. Saturates at `0` before
/// any candle has been seen.
pub(crate) fn current_bar(&self) -> usize {
self.bars_seen.saturating_sub(1)
}
fn push(&mut self, pivot: Pivot) {
self.pivots.push(pivot);
if self.pivots.len() > self.cap {
@@ -152,6 +177,7 @@ impl SwingTracker {
/// Clear all state, returning the tracker to its just-constructed condition.
pub(crate) fn reset(&mut self) {
self.bars_seen = 0;
self.state = None;
self.pivots.clear();
}
@@ -312,9 +338,11 @@ mod tests {
assert!(t.update(c_hl(101.0, 100.0, 2)));
assert_eq!(
t.pivots().last().copied(),
// The high extreme was set at bar 1, confirmed at bar 2.
Some(Pivot {
price: 120.0,
direction: 1.0,
bar: 1,
})
);
// Now in a downtrend: a lower low extends the candidate low.
@@ -323,9 +351,11 @@ mod tests {
assert!(t.update(c_hl(100.0, 99.0, 4)));
assert_eq!(
t.pivots().last().copied(),
// The low extreme was set at bar 3, confirmed at bar 4.
Some(Pivot {
price: 90.0,
direction: -1.0,
bar: 3,
})
);
}
@@ -382,18 +412,22 @@ mod tests {
Pivot {
price: 100.0,
direction: -1.0,
bar: 0,
},
Pivot {
price: 120.0,
direction: 1.0,
bar: 0,
},
Pivot {
price: 110.0,
direction: -1.0,
bar: 0,
},
Pivot {
price: 121.0,
direction: 1.0,
bar: 0,
},
];
assert_eq!(recent_legs(&ending_high), (120.0, 121.0, 100.0, 110.0));
@@ -402,18 +436,22 @@ mod tests {
Pivot {
price: 120.0,
direction: 1.0,
bar: 0,
},
Pivot {
price: 100.0,
direction: -1.0,
bar: 0,
},
Pivot {
price: 110.0,
direction: 1.0,
bar: 0,
},
Pivot {
price: 99.0,
direction: -1.0,
bar: 0,
},
];
assert_eq!(recent_legs(&ending_low), (120.0, 110.0, 100.0, 99.0));
@@ -425,26 +463,32 @@ mod tests {
Pivot {
price: 50.0,
direction: 1.0,
bar: 0,
},
Pivot {
price: 100.0,
direction: -1.0,
bar: 0,
}, // X
Pivot {
price: 140.0,
direction: 1.0,
bar: 0,
}, // A
Pivot {
price: 115.0,
direction: -1.0,
bar: 0,
}, // B
Pivot {
price: 128.0,
direction: 1.0,
bar: 0,
}, // C
Pivot {
price: 108.0,
direction: -1.0,
bar: 0,
}, // D (low → bullish)
];
let p = xabcd(&pivots);
@@ -483,4 +527,16 @@ mod tests {
assert!(approx_equal(0.0, 0.0, 0.01)); // both zero
assert!(approx_equal(-50.0, -49.0, 0.05)); // negative magnitudes
}
#[test]
fn tracks_extreme_bar_and_current_bar() {
let mut t = SwingTracker::new(0.10, 6);
// Before any candle, the current bar saturates at 0.
assert_eq!(t.current_bar(), 0);
let _ = t.update(c_hl(100.0, 99.5, 0));
let _ = t.update(c_hl(120.0, 119.5, 1)); // candidate high at bar 1
let _ = t.update(c_hl(101.0, 90.0, 2)); // confirm high @120 (extreme bar 1)
assert_eq!(t.current_bar(), 2);
assert_eq!(t.pivots().last().unwrap().bar, 1);
}
}
+13 -10
View File
@@ -60,12 +60,12 @@ pub use indicators::{
AcceleratorOscillator, AdOscillator, AdVolumeLine, AdaptiveCycle, Adl, AdvanceBlock,
AdvanceDecline, AdvanceDeclineRatio, Adx, AdxOutput, Adxr, Alligator, AlligatorOutput, Alma,
Alpha, AnchoredRsi, AnchoredVwap, Apo, Aroon, AroonOscillator, AroonOutput, Atr, AtrBands,
AtrBandsOutput, AtrTrailingStop, Autocorrelation, AverageDailyRange, AverageDrawdown, AvgPrice,
AwesomeOscillator, AwesomeOscillatorHistogram, BalanceOfPower, Bat, BeltHold, Beta,
BetaNeutralSpread, BollingerBands, BollingerBandwidth, BollingerOutput, BreadthThrust,
Breakaway, BullishPercentIndex, Butterfly, CalendarSpread, CalmarRatio, Camarilla,
CamarillaPivotsOutput, Cci, CenterOfGravity, Cfo, ChaikinMoneyFlow, ChaikinOscillator,
ChaikinVolatility, ChandeKrollStop, ChandeKrollStopOutput, ChandelierExit,
AtrBandsOutput, AtrTrailingStop, AutoFib, AutoFibOutput, Autocorrelation, AverageDailyRange,
AverageDrawdown, AvgPrice, AwesomeOscillator, AwesomeOscillatorHistogram, BalanceOfPower, Bat,
BeltHold, Beta, BetaNeutralSpread, BollingerBands, BollingerBandwidth, BollingerOutput,
BreadthThrust, Breakaway, BullishPercentIndex, Butterfly, CalendarSpread, CalmarRatio,
Camarilla, CamarillaPivotsOutput, Cci, CenterOfGravity, Cfo, ChaikinMoneyFlow,
ChaikinOscillator, ChaikinVolatility, ChandeKrollStop, ChandeKrollStopOutput, ChandelierExit,
ChandelierExitOutput, ChoppinessIndex, ClassicPivots, ClassicPivotsOutput, ClosingMarubozu,
Cmo, CoefficientOfVariation, Cointegration, CointegrationOutput, ConcealingBabySwallow,
ConditionalValueAtRisk, ConnorsRsi, Coppock, Counterattack, Crab, CumulativeVolumeDelta,
@@ -76,10 +76,13 @@ pub use indicators::{
DoubleTopBottom, DownsideGapThreeMethods, Dpo, DragonflyDoji, DrawdownDuration, Dx,
EaseOfMovement, EffectiveSpread, EhlersStochastic, ElderImpulse, Ema,
EmpiricalModeDecomposition, Engulfing, EveningDojiStar, Evwma, FallingThreeMethods, Fama,
FibonacciPivots, FibonacciPivotsOutput, FisherTransform, FlagPennant, Footprint,
FootprintOutput, ForceIndex, FractalChaosBands, FractalChaosBandsOutput, Frama, FundingBasis,
FundingRate, FundingRateMean, FundingRateZScore, GainLossRatio, GapSideBySideWhite,
GarmanKlassVolatility, Gartley, GrangerCausality, GravestoneDoji, Hammer, HangingMan, Harami,
FibArcs, FibArcsOutput, FibChannel, FibChannelOutput, FibConfluence, FibConfluenceOutput,
FibExtension, FibExtensionOutput, FibFan, FibFanOutput, FibProjection, FibProjectionOutput,
FibRetracement, FibRetracementOutput, FibTimeZones, FibTimeZonesOutput, FibonacciPivots,
FibonacciPivotsOutput, FisherTransform, FlagPennant, Footprint, FootprintOutput, ForceIndex,
FractalChaosBands, FractalChaosBandsOutput, Frama, FundingBasis, FundingRate, FundingRateMean,
FundingRateZScore, GainLossRatio, GapSideBySideWhite, GarmanKlassVolatility, Gartley,
GoldenPocket, GoldenPocketOutput, GrangerCausality, GravestoneDoji, Hammer, HangingMan, Harami,
HeadAndShoulders, HeikinAshi, HeikinAshiOutput, HiLoActivator, HighLowIndex, HighWave, Hikkake,
HikkakeModified, HilbertDominantCycle, HistoricalVolatility, Hma, HomingPigeon, HtDcPhase,
HtPhasor, HtPhasorOutput, HtTrendMode, HurstChannel, HurstChannelOutput, HurstExponent,
+1 -1
View File
@@ -8,7 +8,7 @@ That includes:
[Python](https://docs.wickra.org/Quickstart-Python),
[Node](https://docs.wickra.org/Quickstart-Node), and
[WASM](https://docs.wickra.org/Quickstart-WASM).
- A per-indicator deep dive for every one of the **367 indicators** across
- A per-indicator deep dive for every one of the **377 indicators** across
the sixteen families (Moving Averages, Momentum Oscillators, Trend &
Directional, Price Oscillators, Volatility & Bands, Bands & Channels,
Trailing Stops, Volume, Price Statistics, Ehlers / Cycle DSP, Pivots &
+7 -7
View File
@@ -17,7 +17,7 @@
},
"../../bindings/node": {
"name": "wickra",
"version": "0.5.2",
"version": "0.5.3",
"license": "MIT OR Apache-2.0",
"devDependencies": {
"@napi-rs/cli": "^2.18.0"
@@ -26,12 +26,12 @@
"node": ">= 18"
},
"optionalDependencies": {
"wickra-darwin-arm64": "0.5.2",
"wickra-darwin-x64": "0.5.2",
"wickra-linux-arm64-gnu": "0.5.2",
"wickra-linux-x64-gnu": "0.5.2",
"wickra-win32-arm64-msvc": "0.5.2",
"wickra-win32-x64-msvc": "0.5.2"
"wickra-darwin-arm64": "0.5.3",
"wickra-darwin-x64": "0.5.3",
"wickra-linux-arm64-gnu": "0.5.3",
"wickra-linux-x64-gnu": "0.5.3",
"wickra-win32-arm64-msvc": "0.5.3",
"wickra-win32-x64-msvc": "0.5.3"
}
},
"node_modules/wickra": {
+13 -1
View File
@@ -22,7 +22,7 @@
//! WeightedClose.
use libfuzzer_sys::fuzz_target;
use wickra_core::{AbandonedBaby, Abcd, AccelerationBands, AcceleratorOscillator, AdOscillator, Adl, AdvanceBlock, Adx, Adxr, Alligator, AnchoredVwap, Aroon, AroonOscillator, Atr, AtrBands, AtrTrailingStop, AverageDailyRange, AwesomeOscillator, AwesomeOscillatorHistogram, BalanceOfPower, Bat, BatchExt, BeltHold, Breakaway, Butterfly, Camarilla, Candle, Cci, ChaikinMoneyFlow, ChaikinOscillator, ChaikinVolatility, ChandeKrollStop, ChandelierExit, ChoppinessIndex, ClassicPivots, ClosingMarubozu, ConcealingBabySwallow, Counterattack, Crab, CupAndHandle, Cypher, DayOfWeekProfile, DemandIndex, DemarkPivots, Doji, DojiStar, Donchian, DonchianStop, DoubleTopBottom, DownsideGapThreeMethods, DragonflyDoji, Dx, EaseOfMovement, Engulfing, EveningDojiStar, Evwma, FallingThreeMethods, FibonacciPivots, FlagPennant, ForceIndex, FractalChaosBands, GapSideBySideWhite, GarmanKlassVolatility, Gartley, GravestoneDoji, Hammer, HangingMan, Harami, HeadAndShoulders, HeikinAshi, HiLoActivator, HighWave, Hikkake, HikkakeModified, HomingPigeon, HurstChannel, Ichimoku, IdenticalThreeCrows, InNeck, Indicator, Inertia, InitialBalance, IntradayVolatilityProfile, InvertedHammer, Keltner, Kicking, KickingByLength, Kvo, LadderBottom, LongLeggedDoji, LongLine, MarketFacilitationIndex, Marubozu, MassIndex, MatHold, MatchingLow, AvgPrice, MedianPrice, Mfi, MidPrice, MinusDi, MinusDm, MorningDojiStar, MorningEveningStar, Natr, Nvi, Obv, OnNeck, OpeningMarubozu, OpeningRange, OvernightGap, OvernightIntradayReturn, ParkinsonVolatility, Pgo, PiercingDarkCloud, PlusDi, PlusDm, Psar, Pvi, RectangleRange, RickshawMan, RisingThreeMethods, RogersSatchellVolatility, RollingVwap, Rvi, Rwi, SarExt, SeasonalZScore, SeparatingLines, SessionHighLow, SessionRange, SessionVwap, Shark, ShootingStar, ShortLine, Smi, SpinningTop, StalledPattern, StarcBands, StickSandwich, Stochastic, SuperTrend, Takuri, TasukiGap, TdCombo, TdCountdown, TdDeMarker, TdDifferential, TdLines, TdOpen, TdPressure, TdRangeProjection, TdRei, TdRiskLevel, TdSequential, TdSetup, ThreeDrives, ThreeInside, ThreeLineStrike, ThreeOutside, ThreeSoldiersOrCrows, ThreeStarsInSouth, Thrusting, TimeOfDayReturnProfile, TpoProfile, Triangle, TripleTopBottom, TrueRange, Tsv, TtmSqueeze, TurnOfMonth, Tweezer, TwoCrows, TypicalPrice, UltimateOscillator, UniqueThreeRiver, UpsideGapThreeMethods, UpsideGapTwoCrows, ValueArea, VoltyStop, VolumeByTimeProfile, VolumeOscillator, VolumePriceTrend, VolumeProfile, Vortex, Vwap, VwapStdDevBands, Vwma, Vzo, WaveTrend, Wedge, WeightedClose, WilliamsFractals, WilliamsR, WoodiePivots, YangZhangVolatility, YoyoExit, ZigZag};
use wickra_core::{AbandonedBaby, Abcd, AccelerationBands, AcceleratorOscillator, AdOscillator, Adl, AdvanceBlock, Adx, Adxr, Alligator, AnchoredVwap, Aroon, AroonOscillator, Atr, AtrBands, AtrTrailingStop, AutoFib, AverageDailyRange, AwesomeOscillator, AwesomeOscillatorHistogram, BalanceOfPower, Bat, BatchExt, BeltHold, Breakaway, Butterfly, Camarilla, Candle, Cci, ChaikinMoneyFlow, ChaikinOscillator, ChaikinVolatility, ChandeKrollStop, ChandelierExit, ChoppinessIndex, ClassicPivots, ClosingMarubozu, ConcealingBabySwallow, Counterattack, Crab, CupAndHandle, Cypher, DayOfWeekProfile, DemandIndex, DemarkPivots, Doji, DojiStar, Donchian, DonchianStop, DoubleTopBottom, DownsideGapThreeMethods, DragonflyDoji, Dx, EaseOfMovement, Engulfing, EveningDojiStar, Evwma, FallingThreeMethods, FibArcs, FibChannel, FibConfluence, FibExtension, FibFan, FibProjection, FibRetracement, FibTimeZones, FibonacciPivots, FlagPennant, ForceIndex, FractalChaosBands, GapSideBySideWhite, GarmanKlassVolatility, Gartley, GoldenPocket, GravestoneDoji, Hammer, HangingMan, Harami, HeadAndShoulders, HeikinAshi, HiLoActivator, HighWave, Hikkake, HikkakeModified, HomingPigeon, HurstChannel, Ichimoku, IdenticalThreeCrows, InNeck, Indicator, Inertia, InitialBalance, IntradayVolatilityProfile, InvertedHammer, Keltner, Kicking, KickingByLength, Kvo, LadderBottom, LongLeggedDoji, LongLine, MarketFacilitationIndex, Marubozu, MassIndex, MatHold, MatchingLow, AvgPrice, MedianPrice, Mfi, MidPrice, MinusDi, MinusDm, MorningDojiStar, MorningEveningStar, Natr, Nvi, Obv, OnNeck, OpeningMarubozu, OpeningRange, OvernightGap, OvernightIntradayReturn, ParkinsonVolatility, Pgo, PiercingDarkCloud, PlusDi, PlusDm, Psar, Pvi, RectangleRange, RickshawMan, RisingThreeMethods, RogersSatchellVolatility, RollingVwap, Rvi, Rwi, SarExt, SeasonalZScore, SeparatingLines, SessionHighLow, SessionRange, SessionVwap, Shark, ShootingStar, ShortLine, Smi, SpinningTop, StalledPattern, StarcBands, StickSandwich, Stochastic, SuperTrend, Takuri, TasukiGap, TdCombo, TdCountdown, TdDeMarker, TdDifferential, TdLines, TdOpen, TdPressure, TdRangeProjection, TdRei, TdRiskLevel, TdSequential, TdSetup, ThreeDrives, ThreeInside, ThreeLineStrike, ThreeOutside, ThreeSoldiersOrCrows, ThreeStarsInSouth, Thrusting, TimeOfDayReturnProfile, TpoProfile, Triangle, TripleTopBottom, TrueRange, Tsv, TtmSqueeze, TurnOfMonth, Tweezer, TwoCrows, TypicalPrice, UltimateOscillator, UniqueThreeRiver, UpsideGapThreeMethods, UpsideGapTwoCrows, ValueArea, VoltyStop, VolumeByTimeProfile, VolumeOscillator, VolumePriceTrend, VolumeProfile, Vortex, Vwap, VwapStdDevBands, Vwma, Vzo, WaveTrend, Wedge, WeightedClose, WilliamsFractals, WilliamsR, WoodiePivots, YangZhangVolatility, YoyoExit, ZigZag};
/// Convert a flat `f64` stream into a `Vec<Candle>` by chunking it into
/// `[open, high, low, close, volume]` groups. Tuples that fail OHLCV
@@ -392,4 +392,16 @@ fuzz_target!(|data: Vec<f64>| {
drive(Gartley::new, &candles);
drive(Abcd::new, &candles);
// --- Fibonacci (multi-output) ---
drive(FibTimeZones::new, &candles);
drive(FibChannel::new, &candles);
drive(FibArcs::new, &candles);
drive(FibFan::new, &candles);
drive(FibConfluence::new, &candles);
drive(GoldenPocket::new, &candles);
drive(AutoFib::new, &candles);
drive(FibProjection::new, &candles);
drive(FibExtension::new, &candles);
drive(FibRetracement::new, &candles);
});