Metadata-Version: 2.4
Name: candleAggregator
Version: 0.0.138
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, and Renko 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 |

---

## 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`.

```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

# Export to pandas DataFrame
df_candles = time_agg.to_dataframe()
print(df_candles.tail())
```

---

## 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
