Metadata-Version: 2.4
Name: pybinbot
Version: 2.1.13
Summary: Utility functions for the binbot project.
Author-email: Carlos Wu <carkodw@gmail.com>
Requires-Python: >=3.15
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic[email]>=2.0.0
Requires-Dist: numpy==2.5.4
Requires-Dist: pandas==3.1.1
Requires-Dist: pandas-stubs==3.1.0.261029
Requires-Dist: requests>=2.32.5
Requires-Dist: kucoin-universal-sdk>=1.3.2
Requires-Dist: aiohttp<3.15,>=3.14.1
Requires-Dist: websocket-client>=1.9.0
Requires-Dist: python-dotenv>=1.2.1
Requires-Dist: python-telegram-bot>=22.1
Requires-Dist: pandera>=0.29.0
Provides-Extra: dev
Requires-Dist: pytest>=9.0.2; extra == "dev"
Requires-Dist: ruff>=0.11.12; extra == "dev"
Requires-Dist: mypy>=1.19.1; extra == "dev"
Requires-Dist: types-requests>=2.32.4.20260107; extra == "dev"
Requires-Dist: types-python-dateutil; extra == "dev"
Requires-Dist: httpx>=0.28.1; extra == "dev"
Requires-Dist: pytest-asyncio>=1.3.0; extra == "dev"
Dynamic: license-file

# PyBinbot

Utility functions for the binbot project. Most of the code here is not runnable, there's no server or individual scripts, you simply move code to here when it's used in both binbot and binquant.

``pybinbot`` is the public API module for the distribution.

This module re-exports the internal ``shared`` and ``models`` packages and the most commonly used helpers and enums so consumers can simply::

        from pybinbot import round_numbers, ExchangeId

Python 3.15 or newer is required. Pandas and NumPy use matching version pins in
pybinbot, binbot, and binquant. Import these libraries directly:

```python
import numpy as np
import pandas as pd
```


## Installation

```bash
uv sync --extra dev
```

`--extra dev` also installs development tools like ruff and mypy

## Futures order triggers

`KucoinFutures.place_futures_order()` defaults every conditional order to KuCoin's
last traded price (`stopPriceType=TP`) when `stop_price_type` is omitted or `None`.
This applies to both buy and sell orders, stop-market and stop-limit orders, and
opening and reducing orders. Explicit mark/index trigger types remain supported.
Orders without `stop` do not send a trigger-price type. Trigger levels, limit
prices, quantities, leverage, and fill handling are unchanged.

Last price can fluctuate more than mark price, but selecting it does not guarantee
the highest selling price or lowest buying price; fills depend on the order book.

`KucoinFutures.get_ticker_price(symbol)` returns the last traded contract price
from the futures ticker. The spot client exposes the same method for spot prices;
`KucoinFutures.get_mark_price(symbol)` remains available for mark prices.

## Stored CVD data

`BinbotApi` exposes the recorded KuCoin futures CVD endpoints:

```python
symbol_cvd = await api.get_cvd_symbol("RUMUSDTM", limit=15)
market_cvd = await api.get_cvd_aggregate(limit=15)
```

`CvdSymbolResponse`, `CvdAggregateResponse` and `CvdPoint` are public exports.
Symbol observations are one-minute buckets; aggregate observations are
15-minute buckets. Both are oldest first and retain the current/partial,
coverage, gap, universe or contract multiplier change, reset, and checkpoint
freshness fields. Missing values remain `None`, and empty collections remain
empty. Timestamp fields require time zones and numeric observations must be
finite. The endpoint responses are bare snapshots rather than
`StandardResponse` envelopes. Request and validation errors propagate to the
caller; a failed request never becomes a zero-valued reading.

Publish a new PyPI release before consuming these methods in binquant or
binbot, then upgrade each consumer's minimum dependency and lockfile to that
release.

## Telegram delivery

Import `TelegramDelivery` from `pybinbot.shared.telegram_delivery`. Initialization
loads the application's `.env` and reads `TELEGRAM_BOT_KEY` and `TELEGRAM_USER_ID`,
without overriding existing environment variables. Credentials may also be
passed explicitly.

Use `send_once(message)` for a synchronous attempt with a short timeout and no
retry or cooldown. Use `await send(message)` for asynchronous delivery with
rate-limit retries and optional spacing configured at initialization. Both use
HTML formatting and disable link previews. Delivery does not persist messages.
The Telegram library is installed as a dependency of pybinbot.


## Publishing

1. Save your changes and do the usual Git flow (add, commit, don't push the changes yet).
2. Bump the version, choose one of these:

```bash
make bump-patch
```
or 

```bash
make bump-minor
```

or

```bash
make bump-major
```

3. Git tag the version for Github. This will read the bump version. There's a convenience command:
```
make tag
```

4. `git commit --amend`. This is to put these new changes in the previous commit so we don't dup uncessary commits. Then `git push`


For further commands take a look at the `Makefile` such as testing `make test`

## Strategy calculations

Reusable pattern detection, signal gates and strategy risk calculations live in
`pybinbot.strategy`:

- `price_crossings`: six-hour candle-range and gap crossings for chop gates.
- `swing_protection`: recent confirmed swings for bounded protective prices.
- `beta`: rolling and latest return beta against BTC.
- `breadth`: breadth-momentum reversals and BTC-trend confirmation.

Import directly from the relevant module, for example:

```python
from pybinbot.strategy.beta import rolling_beta
from pybinbot.strategy.price_crossings import price_crossings_six_hours
from pybinbot.strategy.swing_protection import recent_swing_protection
```

The published `pybinbot.shared.beta`, `pybinbot.shared.breadth` and
`pybinbot.shared.price_crossings` paths remain as import aliases. Existing
package-level beta and breadth exports also remain available. General candle
processing, indicators, timestamps, exchange types and delivery utilities remain
in `pybinbot.shared`. New reusable strategy calculations belong in
`pybinbot.strategy`.

## Recent swing protection

`pybinbot.strategy.swing_protection.recent_swing_protection` evaluates the latest
confirmed, unbroken swing on completed 15m, 5m or 1m candles. Callers descend in
that order when a candidate is unsuitable. The maximum search window is three
hours, optionally narrowed to one hour or to the start of the current setup.
The reference price must remain on the protected side of the unbuffered swing.
A forming candle cannot confirm a swing, but a wick touching or crossing the
swing invalidates it even when the current price subsequently recovers.
The selector rejects swing candles wider than 3% and stop distances over 2.5%
after the buffer and outward tick rounding. It never clips a distant swing or
searches older swings to force a result. Entry callers skip when all timeframes
fail; live callers retain existing protection and only apply tighter stops.

`refine_swing_protection` manages the whole timeframe decision. If 1m history
is gapped or unreliable, it returns the nearest trustworthy coarser swing.
Missing timestamps, duplicates, stale bars, zero-volume bars, or frequent price
gaps make a source unreliable. Price gaps are non-overlapping candle ranges
separated by more than 0.1% and two price-precision ticks; more than 20% of
transitions, with at least two gaps, rejects the timeframe.

The 3% candle-width threshold prompts refinement. It can be relaxed for a
coarser fallback after finer data fails, while the buffered stop-distance cap,
three-hour swing age, confirmation and unbroken-swing requirements still apply.
If no coarser swing fits, the result has no placement. A missing timeframe in
the input mapping requests that interval; an empty list means the read finished
without usable data. Live callers can therefore keep exchange reads off the
protective exit path while this decision remains shared with entry strategies.
