Python implementation of Uniswap V3 QuoterV2 for high-frequency trading
Project description
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ị)
pip install uniswap-v3-quoter
Từ source
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:
pip install uniswap-v3-quoter[performance]
Sử dụng cơ bản
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:
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:
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)
# 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:
# 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
- Fetch state: Sử dụng multicall để fetch pool state từ blockchain (slot0, liquidity, ticks, tickBitmap)
- Cache in memory: Lưu state trong memory
- Background updates: Interval thread tự động update state
- 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 ý
- 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.
- Pool address: Cần biết pool address trước. Có thể compute từ factory address + token addresses + fee.
- BSC = PancakeSwap V3: BSC không có Uniswap V3 official, mà là PancakeSwap V3 (fork).
- Độ chính xác: Python
inthỗ trợ arbitrary precision, phù hợp cho uint256.
Examples
Basic Usage
python example.py
WebSocket Realtime Updates
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
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file uniswap_v3_quoter-1.0.6.tar.gz.
File metadata
- Download URL: uniswap_v3_quoter-1.0.6.tar.gz
- Upload date:
- Size: 33.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
27e5ef0b4b1af2ae88a07e2732fdd3cb277e0b7151e83536b45f7bbfcbcc47d3
|
|
| MD5 |
bae7972038db906cdd57471504402f32
|
|
| BLAKE2b-256 |
aea9802beb32cc53fd1964cc25cb83e80a5fc6abebd7289503ac21ecbcf3f7f7
|
File details
Details for the file uniswap_v3_quoter-1.0.6-py3-none-any.whl.
File metadata
- Download URL: uniswap_v3_quoter-1.0.6-py3-none-any.whl
- Upload date:
- Size: 28.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f26a47c7c9dfe244ef31caecb1f125fd35197cecf739b136f5fbe0c042a451b7
|
|
| MD5 |
433e549299dd4bcbf7dc936f45d9fa43
|
|
| BLAKE2b-256 |
b00738311f12161f0dc8c4e5c70c0fde50b109ebe564d9f23e08039f3d2965ef
|