Metadata-Version: 2.4
Name: uniswap-v3-quoter
Version: 1.0.2
Summary: Python implementation of Uniswap V3 QuoterV2 for high-frequency trading
Home-page: https://github.com/yourusername/v3-python-quoter
Author: V3 Python Quoter Contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/yourusername/v3-python-quoter
Project-URL: Documentation, https://github.com/yourusername/v3-python-quoter/blob/main/README.md
Project-URL: Repository, https://github.com/yourusername/v3-python-quoter
Project-URL: Bug Tracker, https://github.com/yourusername/v3-python-quoter/issues
Keywords: uniswap,uniswap-v3,pancakeswap,defi,dex,quoter,trading,ethereum,bsc,web3
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: web3>=6.0.0
Requires-Dist: eth-abi>=4.0.0
Requires-Dist: eth-utils>=2.0.0
Requires-Dist: eth-typing>=3.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.1; extra == "dev"
Provides-Extra: performance
Requires-Dist: orjson>=3.9.0; extra == "performance"
Requires-Dist: cytoolz>=0.12.0; extra == "performance"
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# Uniswap V3 Python Quoter

Python implementation của logic quote swap Uniswap V3, được tối ưu cho high-frequency trading trên BSC (PancakeSwap V3).

## Tính năng

- ✅ **Quote nhanh**: Tính toán quote ở local thay vì gọi RPC, giảm latency từ ~1s xuống < 1ms
- ✅ **WebSocket realtime updates**: Cập nhật pool state theo Swap events với latency < 10ms
- ✅ **Background updates**: Tự động fetch và cập nhật pool state theo interval (polling)
- ✅ **Chính xác 100%**: Port trực tiếp từ Solidity, đảm bảo kết quả giống on-chain
- ✅ **Multicall support**: Batch RPC calls để fetch state nhanh hơn
- ✅ **Thread-safe**: An toàn khi sử dụng với multi-threading

## Cài đặt

### Từ PyPI (Khuyến nghị)

```bash
pip install uniswap-v3-quoter
```

### Từ source

```bash
git clone https://github.com/yourusername/v3-python-quoter.git
cd v3-python-quoter
pip install -e .
```

### Performance extras (optional)

Để tối ưu performance, cài thêm các dependencies:

```bash
pip install uniswap-v3-quoter[performance]
```

## Sử dụng cơ bản

```python
from web3 import Web3
from uniswap_v3_quoter import QuoterV3, StateFetcher

# Kết nối đến BSC
w3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))

# Khởi tạo quoter
multicall3_address = "0xcA11bde05977b3631167028862bE2a173976CA11"  # Multicall3 on BSC
state_fetcher = StateFetcher(w3, multicall3_address)
quoter = QuoterV3(w3, state_fetcher)

# Thêm pool cần quote
pool_address = "0x..."  # Địa chỉ pool PancakeSwap V3
pool_state = quoter.add_pool(pool_address)

# Quote swap
amount_in = 1 * 10**18  # 1 token (18 decimals)
amount_out = quoter.quote_exact_input_single(
    pool_address=pool_address,
    zero_for_one=True,  # Swap token0 -> token1
    amount_in=amount_in,
)

print(f"Amount out: {amount_out / 10**18}")
```

## WebSocket Realtime Updates

Để có state updates với latency thấp nhất, sử dụng WebSocket subscriber:

```python
from web3 import Web3
from uniswap_v3_quoter import QuoterV3, StateFetcher, WebSocketSubscriber

# Kết nối đến BSC
w3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))

# Setup WebSocket subscriber
ws_subscriber = WebSocketSubscriber(
    wss_url="wss://bsc-mainnet.nodereal.io/ws/v1/YOUR_API_KEY"
)

# Khởi tạo StateFetcher với WebSocket
multicall3_address = "0xcA11bde05977b3631167028862bE2a173976CA11"
state_fetcher = StateFetcher(w3, multicall3_address, ws_subscriber)
quoter = QuoterV3(w3, state_fetcher)

# Thêm pool (tự động subscribe WebSocket!)
pool_address = "0x..."
quoter.add_pool(pool_address)

# Start WebSocket
state_fetcher.start_websocket()

# Pool state sẽ tự động update khi có Swap event
# Quote với state realtime, latency < 10ms
amount_out = quoter.quote_exact_input_single(
    pool_address=pool_address,
    zero_for_one=True,
    amount_in=1 * 10**18,
)

# Cleanup khi done
state_fetcher.stop_websocket()
```

### Custom Callback (Optional)

Nếu muốn xử lý Swap events với custom logic:

```python
def on_swap_event(swap_data):
    # Gọi callback gốc để update state
    state_fetcher.update_from_swap_event(swap_data)
    
    # Custom logic
    print(f"Swap detected! New tick: {swap_data.tick}")
    print(f"Amount0: {swap_data.amount0}")
    print(f"Amount1: {swap_data.amount1}")

# Override callback
ws_subscriber.set_callback(on_swap_event)
```

## High-Frequency Trading

### Method 1: WebSocket (Khuyến nghị cho HFT)

```python
# WebSocket cho latency thấp nhất (< 10ms)
ws_subscriber = WebSocketSubscriber(wss_url="wss://...")
state_fetcher = StateFetcher(w3, multicall3_address, ws_subscriber)
quoter = QuoterV3(w3, state_fetcher)

quoter.add_pool(pool_address)
state_fetcher.start_websocket()

# Quote liên tục với state realtime
for i in range(1000):
    amount_out = quoter.quote_exact_input_single(
        pool_address=pool_address,
        zero_for_one=True,
        amount_in=amount_in,
    )
    # Process quote...
```

### Method 2: Background Polling

Để sử dụng cho HFT với polling, enable background updates:

```python
# Start background updates (cập nhật mỗi 500ms)
state_fetcher.start_background_update(
    pool_addresses=[pool_address],
    interval=0.5,  # 500ms
)

# Bây giờ có thể quote liên tục với latency < 1ms
for i in range(1000):
    amount_out = quoter.quote_exact_input_single(
        pool_address=pool_address,
        zero_for_one=True,
        amount_in=amount_in,
    )
    # Process quote...
```

## Cấu trúc thư mục

```
v3-python-quoter/
├── uniswap_math/            # Math libraries (FullMath, TickMath, etc.)
│   ├── full_math.py
│   ├── tick_math.py
│   ├── sqrt_price_math.py
│   ├── swap_math.py
│   ├── tick_bitmap.py
│   └── liquidity_math.py
├── state/                   # State management
│   ├── pool_state.py       # PoolState class
│   ├── state_fetcher.py    # StateFetcher với multicall
│   └── ws_subscriber.py    # WebSocket subscriber
├── quoter.py               # Main quoter logic
├── config.py               # Configuration
├── requirements.txt
├── example.py              # Examples
├── example_websocket.py    # WebSocket example
└── README.md
```

## Logic hoạt động

1. **Fetch state**: Sử dụng multicall để fetch pool state từ blockchain (slot0, liquidity, ticks, tickBitmap)
2. **Cache in memory**: Lưu state trong memory
3. **Background updates**: Interval thread tự động update state
4. **Local quote**: Tính toán quote từ cached state, giống hệt logic của `UniswapV3Pool.swap()`

### Swap Loop Logic

```
1. Initialize: sqrt_price, tick, liquidity từ pool state
2. Loop while amount_remaining > 0:
   a. Tìm tick tiếp theo trong tickBitmap
   b. Tính swap step (amount_in, amount_out, fee)
   c. Update amount_remaining, amount_calculated
   d. Nếu cross tick: update liquidity
   e. Update current price và tick
3. Return amount_out
```

## Performance

### Quote Performance
- **On-chain call**: ~1000ms (gọi RPC lên QuoterV2)
- **Python local quote**: < 1ms (sau khi có state trong cache)

### State Update Performance
- **WebSocket events**: < 10ms latency (event-driven, chỉ update khi có swap)
- **Multicall polling**: ~100-200ms (polling liên tục)

### Comparison: WebSocket vs Polling

| Method        | Latency   | RPC Usage | Best For                 |
| ------------- | --------- | --------- | ------------------------ |
| **WebSocket** | < 10ms    | Minimal   | HFT, realtime quotes     |
| **Polling**   | 100-200ms | Constant  | Monitoring, non-critical |

**Khuyến nghị**: Sử dụng WebSocket cho HFT để có latency thấp nhất và giảm RPC usage.

## Lưu ý

1. **Tick data**: Mặc định chỉ fetch tick data trong range cần thiết. Nếu price move ra ngoài range, cần fetch thêm.
2. **Pool address**: Cần biết pool address trước. Có thể compute từ factory address + token addresses + fee.
3. **BSC = PancakeSwap V3**: BSC không có Uniswap V3 official, mà là PancakeSwap V3 (fork).
4. **Độ chính xác**: Python `int` hỗ trợ arbitrary precision, phù hợp cho uint256.

## Examples

### Basic Usage
```bash
python example.py
```

### WebSocket Realtime Updates
```bash
python example_websocket.py
```

Xem thêm documentation trong `docs/` folder.

## License

MIT License (same as Uniswap V3)

## Credits

- Uniswap V3 Core: https://github.com/Uniswap/v3-core
- Uniswap V3 Periphery: https://github.com/Uniswap/v3-periphery

