Skip to main content

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

  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

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

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

uniswap_v3_quoter-1.0.4.tar.gz (43.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

uniswap_v3_quoter-1.0.4-py3-none-any.whl (78.9 kB view details)

Uploaded Python 3

File details

Details for the file uniswap_v3_quoter-1.0.4.tar.gz.

File metadata

  • Download URL: uniswap_v3_quoter-1.0.4.tar.gz
  • Upload date:
  • Size: 43.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for uniswap_v3_quoter-1.0.4.tar.gz
Algorithm Hash digest
SHA256 c576b46ea3010ff0398387ee9597578eacf9d670efd64a3d790422b2355643f6
MD5 0a69e48c5262eac26f4d7520d59e4235
BLAKE2b-256 a6c2eb5d6e64152d75b740f8cffe3bf119cb301f931104f41386731f64398931

See more details on using hashes here.

File details

Details for the file uniswap_v3_quoter-1.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for uniswap_v3_quoter-1.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 e2ef13e828a017ba767fb6c8825d6d246577c7dbbbba1e5d266fae114cc5b9c0
MD5 a97f77fa7425027b9663905e49940612
BLAKE2b-256 a1a143a55b296776ba20351d28995e1909e5e106186a07c15289d66f3fc0d4aa

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page