跳转到主要内容

适用于BNB Chain、Polygon、Ethereum和其他区块链上Uniswap、Aave、ChainLink、Enzyme等协议的Python库

项目描述

PyPI version

Automated test suite

Documentation Status

Web3-Ethereum-Defi

Web-Ethereum-DeFi (eth_defi) Python包提供了用于智能合约的高级模块,并为DeFi协议集成、钱包管理、JSON-RPC提供者和自动测试套件提供了预包装的ABI文件。该包旨在实现健壮性、代码和文档的高质量。

Supported protocols include Uniswap, Aave, others

用例

此软件包的应用场景包括

  • 交易和机器人
  • 数据研究、提取、转换和加载
  • 投资组合管理和会计
  • 系统集成和后端

功能

功能包括例如

Web3-Ethereum-Defi支持

  • Uniswap(v2和v3)
  • Sushi
  • Aave
  • Enzyme协议
  • dHEDGE协议
  • 即将推出更多集成
  • 内置600多个智能合约的集成,带有预编译的Solidity ABI文件

阅读完整的API文档)。请参阅下面的代码示例。

先决条件

要使用此软件包,您需要

安装

使用pip

pip install "web3-ethereum-defi[data]"

使用poetry

# Poetry version
poetry add -E data web3-ethereum-defi

使用poetry - master Git分支

git clone git@github.com:tradingstrategy-ai/web3-ethereum-defi.git
cd web3-ethereum-defi
poetry shell
poetry install --all-extras

示例代码

请参阅文档中的教程部分以获取完整的代码示例。

PancakeSwap交换示例

import os
import time
from functools import lru_cache

from web3 import HTTPProvider, Web3

from eth_defi.abi import get_contract
from eth_defi.chain import install_chain_middleware
from eth_defi.event_reader.filter import Filter
from eth_defi.event_reader.logresult import decode_log
from eth_defi.event_reader.reader import read_events, LogResult
from eth_defi.uniswap_v2.pair import fetch_pair_details, PairDetails


QUOTE_TOKENS = ["BUSD", "USDC", "USDT"]


@lru_cache(maxsize=100)
def fetch_pair_details_cached(web3: Web3, pair_address: str) -> PairDetails:
    return fetch_pair_details(web3, pair_address)


def main():
    json_rpc_url = os.environ.get("JSON_RPC_BINANCE", "https://bsc-dataseed.binance.org/")
    web3 = Web3(HTTPProvider(json_rpc_url))
    web3.middleware_onion.clear()
    install_chain_middleware(web3)

    # Read the prepackaged ABI files and set up event filter
    # for any Uniswap v2 like pool on BNB Smart Chain (not just PancakeSwap).
    #
    # We use ABI files distributed by SushiSwap project.
    #
    Pair = get_contract(web3, "sushi/UniswapV2Pair.json")

    filter = Filter.create_filter(address=None, event_types=[Pair.events.Swap])

    latest_block = web3.eth.block_number

    # Keep reading events as they land
    while True:

        start = latest_block
        end = web3.eth.block_number

        evt: LogResult
        for evt in read_events(
            web3,
            start_block=start,
            end_block=end,
            filter=filter,
        ):

            decoded = decode_log(evt)

            # Swap() events are generated by UniswapV2Pool contracts
            pair = fetch_pair_details_cached(web3, decoded["address"])
            token0 = pair.token0
            token1 = pair.token1
            block_number = evt["blockNumber"]

            # Determine the human-readable order of token tickers
            if token0.symbol in QUOTE_TOKENS:
                base = token1  # token
                quote = token0  # stablecoin/BNB
                base_amount = decoded["args"]["amount1Out"] - decoded["args"]["amount1In"]
                quote_amount = decoded["args"]["amount0Out"] - decoded["args"]["amount0In"]
            else:
                base = token0  # stablecoin/BNB
                quote = token1  # token
                base_amount = decoded["args"]["amount0Out"] - decoded["args"]["amount0Out"]
                quote_amount = decoded["args"]["amount1Out"] - decoded["args"]["amount1Out"]

            # Calculate the price in Python Decimal class
            if base_amount and quote_amount:
                human_base_amount = base.convert_to_decimals(base_amount)
                human_quote_amount = quote.convert_to_decimals(quote_amount)
                price = human_quote_amount / human_base_amount

                if human_quote_amount > 0:
                    # We define selling when the stablecoin amount increases
                    # in the swap
                    direction = "sell"
                else:
                    direction = "buy"

                price = abs(price)

                print(f"Swap block:{block_number:,} tx:{evt['transactionHash']} {direction} price:{price:,.8f} {base.symbol}/{quote.symbol}")
            else:
                # Swap() event from DEX that is not Uniswap v2 compatible
                # print(f"Swap block:{block_number:,} tx:{evt['transactionHash']} could not decode")
                pass

        else:
            # No event detected between these blocks
            print(".")

        latest_block = end
        time.sleep(1)


if __name__ == "__main__":
    main()

如何在Python项目中使用该库

web3-ethereum-defi添加为开发依赖项

使用Poetry

# Data optional dependencies include pandas and gql, needed to fetch Uniswap v3 data
poetry add -D "web3-ethereum-defi[data]"

文档

开发和贡献

版本历史

支持

社交媒体

许可协议

MIT。

由Trading Strategy创建.

项目详情


发布历史 发布通知 | RSS订阅

下载文件

下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分布

web3_ethereum_defi-0.26.tar.gz (4.7 MB 查看哈希值)

上传时间

构建分布

web3_ethereum_defi-0.26-py3-none-any.whl (5.8 MB 查看哈希值)

上传时间 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面