Metadata-Version: 2.4
Name: candleAggregator
Version: 0.0.141
Summary: Candle aggregation library
License: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: Cython>=3.3.0
Requires-Dist: numpy>=2.5.3
Requires-Dist: pandas>=3.0.5
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pyrefly>=1; extra == "dev"
Requires-Dist: mypy>=2.3.0; extra == "dev"

# candleAggregator

High-performance, Cython-accelerated tick-to-candle aggregators supporting time, tick-count, range, Renko, Three Line Break, QRenko, and Factor-Threshold models.

Designed for real-time market data pipelines (Binance WebSockets, MetaTrader 5 (MT5), Interactive Brokers, FIX, Kafka) and ultra-fast historical tick backtesting (150M+ to 600M+ ticks/sec).

---

## Installation

```bash
pip3 install .
pip3 install -e .          # editable dev install
pip3 install -e ".[dev]"   # editable + testing tools
```

Verify installed version:
```bash
python3 -c "import candleAggregator; print(candleAggregator.__version__)"
```

---

## Available Aggregators

| Aggregator | Parameter | Trigger / Formation Rule | Ideal Use Case |
| :--- | :--- | :--- | :--- |
| `TimeCandleAggregator` / `CandleAggregator` | `interval_minutes: float` | Fixed time buckets (`0.5` min = 30s, `1.0` min, `60.0` min = 1h) | Standard multi-timeframe charts, scheduling |
| `TickCountCandleAggregator` | `threshold: int` | Fixed number of ticks per bar (e.g. 100 ticks) | Volume/activity-weighted volatility analysis |
| `RangeCandleAggregator` | `range_val: float` | Closes bar when `high - low >= range_val` | Breakout strategies, eliminating sideways chop |
| `RenkoCandleAggregator` | `brick_size: float` | Directional price bricks with fixed brick step | Pure price action trend following & noise filtering |
| `ThreeLineBreakCandleAggregator` | `interval_minutes: float = 5.0, line_count: int = 3` | Time-bar closes breaking previous line extreme (continuation) or $N$-line extreme (reversal) | Structural trend following, breakout confirmation |
| `QRenkoCandleAggregator` | `shift: float, offset: float, range_size: float, tick_size: float` | QuantVue/NinjaTrader asymmetric continuation shift, reversal threshold, and open offset | Advanced custom Renko bar trading and strategy modeling |
| `FactorThresholdCandleAggregator` | `threshold: float, multiplier: float = 100.0` | Closes candle when integer-scaled price is divisible by `threshold` factor | Key psychological price levels, round numbers, grid trading |

---

## Examples

Each aggregator is demonstrated below with a distinct, real-world data source and strategy use case.

### 1. `RenkoCandleAggregator` — Live Binance WebSocket Streaming

Renko filters out temporal noise by only printing new bricks when the market moves by `brick_size`.

> [!WARNING]
> **Multiple Bricks Per Update**: When using small `brick_size` values or during rapid price spikes/gaps, a single incoming tick can cause `RenkoCandleAggregator.update()` to generate **multiple candles at once** in a single call. If an event loop calculates or renders indicators assuming only one new candle was added per tick trigger, indicators might be inaccurately displayed or accessed. If your strategy or visualization depends on strict single-bar transitions per event, consider using `QRenkoCandleAggregator`, where this does not occur.

```python
import asyncio
import json
import websockets
from candleAggregator import RenkoCandleAggregator

# 10.0 USDT brick size for BTCUSDT
renko = RenkoCandleAggregator(brick_size=10.0)

async def stream_binance(symbol="btcusdt"):
    url = f"wss://stream.binance.com:9443/ws/{symbol.lower()}@trade"
    print(f"Connecting to Binance {symbol.upper()} trade stream...")
    
    async with websockets.connect(url) as ws:
        while True:
            msg = json.loads(await ws.recv())
            price = float(msg["p"])
            trade_time_ms = int(msg["T"])
            t_ns = trade_time_ms * 1_000_000
            raw_t = msg["T"]

            # Feed tick to Renko aggregator
            new_brick = renko.update(price, raw_t, t_ns)

            if new_brick:
                print(f"[RENKO BRICK #{len(renko.close)}] "
                      f"Open: {renko.open[-1]:.2f} | "
                      f"High: {renko.high[-1]:.2f} | "
                      f"Low: {renko.low[-1]:.2f} | "
                      f"Close: {renko.close[-1]:.2f} | "
                      f"Ticks: {renko.counts[-1]}")
            else:
                # Optionally track in-progress brick
                # print(f"Current tick: {price}, live range: [{renko.l:.2f} - {renko.h:.2f}]")
                pass

if __name__ == "__main__":
    asyncio.run(stream_binance("btcusdt"))
```

---

### 2. `RangeCandleAggregator` — MetaTrader 5 (MT5) Real-Time Tick Polling

Range bars normalize volatility: each bar spans exactly `range_val` price movement regardless of how long it takes. This example connects to MetaTrader 5 and processes Forex ticks (`EURUSD`).

```python
import time
import MetaTrader5 as mt5
from candleAggregator import RangeCandleAggregator

symbol = "EURUSD"
range_val = 0.0010  # 10 pips

agg = RangeCandleAggregator(range_val=range_val)

if not mt5.initialize():
    raise SystemExit(f"MT5 initialization failed: {mt5.last_error()}")

print(f"Streaming {symbol} ticks from MT5...")
last_time_msc = 0

try:
    while True:
        # Fetch latest ticks since last timestamp
        ticks = mt5.copy_ticks_from(symbol, last_time_msc, 50, mt5.COPY_TICKS_ALL)
        
        if ticks is not None and len(ticks) > 0:
            for tick in ticks:
                t_msc = int(tick['time_msc'])
                if t_msc <= last_time_msc:
                    continue
                last_time_msc = t_msc
                
                price = float(tick['bid'])  # or (tick['bid'] + tick['ask']) / 2
                t_ns = t_msc * 1_000_000
                raw_t = tick['time']

                new_candle = agg.update(price, raw_t, t_ns)
                if new_candle:
                    print(f"[RANGE BAR] Closed bar #{len(agg.close)}: "
                          f"O={agg.open[-1]:.5f}, H={agg.high[-1]:.5f}, "
                          f"L={agg.low[-1]:.5f}, C={agg.close[-1]:.5f}, "
                          f"Range={agg.high[-1] - agg.low[-1]:.5f}")
        
        time.sleep(0.01)  # 10ms poll
finally:
    mt5.shutdown()
```

---

### 3. `TickCountCandleAggregator` — Bybit / KuCoin WebSocket Tick Stream

Tick bars form after a set number of transactions, making them ideal for high-frequency liquidity analysis.

```python
import asyncio
import json
import websockets
from candleAggregator import TickCountCandleAggregator

# 100 ticks per candle
tick_agg = TickCountCandleAggregator(threshold=100)

async def stream_bybit(symbol="BTCUSDT"):
    url = "wss://stream.bybit.com/v5/public/spot"
    async with websockets.connect(url) as ws:
        # Subscribe to trades
        sub_msg = {"op": "subscribe", "args": [f"publicTrade.{symbol}"]}
        await ws.send(json.dumps(sub_msg))
        
        while True:
            res = json.loads(await ws.recv())
            if "data" in res:
                for trade in res["data"]:
                    price = float(trade["p"])
                    t_ms = int(trade["T"])
                    t_ns = t_ms * 1_000_000
                    
                    new_bar = tick_agg.update(price, trade["T"], t_ns)
                    if new_bar:
                        print(f"[100-TICK BAR #{len(tick_agg.close)}] "
                              f"Close: {tick_agg.close[-1]:.2f} | "
                              f"Avg Price: {tick_agg.avg[-1]:.2f} | "
                              f"Total Ticks: {tick_agg.counts[-1]}")

if __name__ == "__main__":
    asyncio.run(stream_bybit())
```

---

### 4. `TimeCandleAggregator` — Broker Historical Tick Replay & Backtest

Aggregating raw CSV/Parquet historical tick archives into custom timeframe candles (e.g. 30-second or 5-minute bars).

```python
import pandas as pd
from candleAggregator import TimeCandleAggregator

# 0.5 min = 30 seconds
time_agg = TimeCandleAggregator(interval_minutes=0.5)

# Load tick history
df = pd.read_csv("data/ticks.csv", engine="pyarrow")
prices = df["Bid"].values
raw_t = df["Timestamp"].to_numpy()
ts_ns = pd.to_datetime(df["Timestamp"]).values.astype("datetime64[ns]").astype("int64")

# Stream through replay
for i in range(len(prices)):
    closed = time_agg.update(prices[i], raw_t[i], ts_ns[i])
    if closed:
        pass  # Real-time event simulation

time_agg.finalize()  # Close active partial candle

### 5. `ThreeLineBreakCandleAggregator` — Structural Trend Reversal Analysis
```python
import numpy as np
import pandas as pd
from candleAggregator import ThreeLineBreakCandleAggregator

# 5-minute periodic base bars, 3-line reversal rule
tlb = ThreeLineBreakCandleAggregator(interval_minutes=5.0, line_count=3)

df = pd.read_csv("data/ticks.csv")
prices = df["Bid"].values.astype(np.float64)
raw_t = df["Timestamp"].to_numpy()
ts_ns = pd.to_datetime(df["Timestamp"]).values.astype("datetime64[ns]").astype("int64")

for i in range(len(prices)):
    new_line = tlb.update(prices[i], raw_t[i], ts_ns[i])
    if new_line:
        direction_str = "BULLISH (UP)" if tlb.directions[-1] == 1 else "BEARISH (DOWN)"
        print(f"[{direction_str} LINE #{len(tlb.close)}] "
              f"O={tlb.open[-1]:.4f}, H={tlb.high[-1]:.4f}, "
              f"L={tlb.low[-1]:.4f}, C={tlb.close[-1]:.4f}, "
              f"Avg={tlb.avg[-1]:.4f}")

tlb.flush()
```

### 6. `QRenkoCandleAggregator` — NinjaTrader / QuantVue Style Custom Renko
```python
from candleAggregator import QRenkoCandleAggregator

# shift=10 ticks, offset=40 ticks, range_size=20 ticks, tick_size=0.01 (e.g. USDJPY)
qrenko = QRenkoCandleAggregator(shift=10.0, offset=40.0, range_size=20.0, tick_size=0.01)

# Stream tick-by-tick
new_bar = qrenko.update(price, raw_t, t_ns)

# Or ultra-fast batch processing
qrenko.update_batch(prices, ts_ns)
```

### 7. `FactorThresholdCandleAggregator` — Divisible Price Levels & Psychological Grid Bars
```python
from candleAggregator import FactorThresholdCandleAggregator

# Closes candles whenever price crosses a 0.05 divisible level (multiplier=100.0)
factor_agg = FactorThresholdCandleAggregator(threshold=0.05, multiplier=100.0)

# Stream tick-by-tick
new_bar = factor_agg.update(price, raw_t, t_ns)

# Or ultra-fast batch processing
factor_agg.update_batch(prices, ts_ns)
```

---

## Vectorized Batch Mode (`update_batch`)

For backtesting large datasets without a Python loop, use `.update_batch(prices, t_ns)`:
- Pure C / Cython loop executed with GIL released (`nogil`).
- Achieves 150M+ to 600M+ ticks/sec.

```python
import numpy as np
import pandas as pd
from candleAggregator import RangeCandleAggregator

df = pd.read_csv("data/ticks.csv")
prices = df["Bid"].values.astype(np.float64)
ts_ns = pd.to_datetime(df["Timestamp"]).values.astype("datetime64[ns]").astype("int64")

agg = RangeCandleAggregator(range_val=0.01)

# Ultra-fast batch update (single call)
agg.update_batch(prices, ts_ns)

# Zero-copy NumPy arrays
print(f"Processed {len(prices)} ticks -> {len(agg.close)} completed candles")
print("Latest 5 Closes:", agg.close[-5:])
print("Latest 5 Highs: ", agg.high[-5:])

# Direct export to DataFrame
candles_df = agg.to_dataframe()
```

---

## Data Access & Properties

All aggregators provide zero-copy NumPy array slice properties and backwards-compatible dictionary access:

- `agg.open`, `agg.high`, `agg.low`, `agg.close`: 1D NumPy `float64` arrays of completed candles.
- `agg.opens`, `agg.highs`, `agg.lows`, `agg.closes_array`: Plural array aliases.
- `agg.closes`: Python `list` of closing prices.
- `agg.open_times`, `agg.close_times`: 1D NumPy `int64` arrays of epoch nanoseconds.
- `agg.counts`: 1D NumPy `int64` array of tick counts per candle.
- `agg.avg`: 1D NumPy `float64` array of volume-weighted or tick-average price.
- `agg.candles`: Dictionary of lists (`open`, `high`, `low`, `close`, `count`, etc.).
- `agg.to_dataframe()`: Converts completed candles to a pandas DataFrame.
- `agg.to_arrays()`: Returns copies of completed candle NumPy arrays.

### In-Progress (Active) Candle Inspection

You can inspect the currently unclosed candle at any time during streaming:
- `agg.o`: Open price of in-progress candle
- `agg.h`: Current high price
- `agg.l`: Current low price
- `agg.c`: Current close/latest price
- `agg.ot`: Open timestamp of current candle
- `agg.ct`: Latest tick timestamp
- `agg.tick_count`: Number of ticks in current candle
