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
  • Background updates: Tự động fetch và cập nhật pool state theo interval
  • 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}")

High-Frequency Trading

Để sử dụng cho HFT, 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
├── quoter.py               # Main quoter logic
├── config.py               # Configuration
├── requirements.txt
├── example.py              # Examples
└── 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

  • On-chain call: ~1000ms (gọi RPC lên QuoterV2)
  • Python local quote: < 1ms (sau khi có state trong cache)
  • State update: ~100-200ms (với multicall)

Với background updates mỗi 500ms, bạn có thể quote hàng nghìn lần/giây với state gần real-time.

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.

Testing

# So sánh với on-chain QuoterV2
python example.py

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-0.1.0.tar.gz (35.5 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-0.1.0-py3-none-any.whl (62.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: uniswap_v3_quoter-0.1.0.tar.gz
  • Upload date:
  • Size: 35.5 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-0.1.0.tar.gz
Algorithm Hash digest
SHA256 2bd3d4cc22455d662e21c01da40a81b76faa1371eb5a2576f1ad446ae3bdaff9
MD5 4b172cecbc815dd2578aac0eda507d07
BLAKE2b-256 70e3ac2f61e0452455271af5c0d03932a9d1f733a8b38a2190b1a675ef8af029

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for uniswap_v3_quoter-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b8dc81c5e7a22c9c6f27c4b01696522e99faac034878a321940eb12ad7df23b3
MD5 9e809d8cc61652d64687538087b2418b
BLAKE2b-256 316fb1296c309e59c7569b1e83389464228af27037c266cd0f65338bd423f385

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