【Web3初识系列】如何连接 Binance Smart Chain通过交易对绘制 k 线?

2024-06-22 18:52

本文主要是介绍【Web3初识系列】如何连接 Binance Smart Chain通过交易对绘制 k 线?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

连接 Binance Smart Chain通过交易对绘制 k 线

安装 web3

pip install web3

连接到 Binance Smart Chain

使用公共的 BSC 节点 URL。

from web3 import Web3# 连接到 BSC 公共节点
bsc_url = "https://bsc-dataseed.binance.org/"
web3 = Web3(Web3.HTTPProvider(bsc_url))# 检查连接是否成功
if web3.is_connected():print("Successfully connected to Binance Smart Chain")
else:print("Failed to connect to Binance Smart Chain")# 获取链上信息,例如当前区块号
block_number = web3.eth.block_number
print(f"Current block number: {block_number}")

获取代币的合约实例

需要代币合约的 ABI 和 地址。

# PPIG 代币合约的 ABI 
token_abi = '''
[{"constant": true,"inputs": [],"name": "name","outputs": [{"name": "", "type": "string"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [],"name": "symbol","outputs": [{"name": "", "type": "string"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [],"name": "decimals","outputs": [{"name": "", "type": "uint8"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [{"name": "_owner", "type": "address"}],"name": "balanceOf","outputs": [{"name": "balance", "type": "uint256"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [],"name": "totalSupply","outputs": [{"name": "", "type": "uint256"}],"payable": false,"stateMutability": "view","type": "function"}
]
'''# 创建代币合约实例
token_contract = web3.eth.contract(address=token_address, abi=token_abi)# 获取代币信息
token_name = token_contract.functions.name().call()
token_symbol = token_contract.functions.symbol().call()
token_decimals = token_contract.functions.decimals().call()
token_total_supply = token_contract.functions.totalSupply().call()print(f"Token Name: {token_name}")
print(f"Token Symbol: {token_symbol}")
print(f"Token Decimals: {token_decimals}")
print(f"Token Total Supply: {web3.from_wei(token_total_supply, 'ether')} {token_symbol}")

监听特定事件

监听 PPIG 交易对的 Swap 事件。

# 添加 Geth POA 中间件(如果使用的是 PoA 网络)
web3.middleware_onion.inject(geth_poa_middleware, layer=0)# PPIG/WBNB 交易对合约的 ABI
pair_abi = '''
[{"anonymous": false,"inputs": [{"indexed": true, "name": "sender", "type": "address"},{"indexed": false, "name": "amount0In", "type": "uint256"},{"indexed": false, "name": "amount1In", "type": "uint256"},{"indexed": false, "name": "amount0Out", "type": "uint256"},{"indexed": false, "name": "amount1Out", "type": "uint256"},{"indexed": true, "name": "to", "type": "address"}],"name": "Swap","type": "event"}
]
'''# 创建交易对合约实例
pair_contract = web3.eth.contract(address=pair_address, abi=pair_abi)# 创建 Swap 事件过滤器
swap_event_filter = pair_contract.events.Swap.create_filter(fromBlock='latest')# 处理事件的回调函数
def handle_event(event):print(event)# 提取事件数据timestamp = web3.eth.get_block(event['blockNumber'])['timestamp']dt_object = datetime.fromtimestamp(timestamp)amount0In = web3.from_wei(event['args']['amount0In'], 'ether')amount1In = web3.from_wei(event['args']['amount1In'], 'ether')amount0Out = web3.from_wei(event['args']['amount0Out'], 'ether')amount1Out = web3.from_wei(event['args']['amount1Out'], 'ether')# 根据具体需求处理数据,这里只是打印出来print(f"Time: {dt_object}, amount0In: {amount0In}, amount1In: {amount1In}, amount0Out: {amount0Out}, amount1Out: {amount1Out}")# 轮询新事件
def log_loop(event_filter, poll_interval):while True:for event in event_filter.get_new_entries():handle_event(event)time.sleep(poll_interval)

生成 K 线图

收集一段时间后,我们可以使用 Pandas 和 Matplotlib 生成 K 线图。

import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetimedata = {'timestamp': [datetime(2024, 6, 19, 12, 0), datetime(2024, 6, 19, 12, 5), datetime(2024, 6, 19, 12, 10)],'price': [10, 12, 11],'volume': [100, 150, 120]
}df = pd.DataFrame(data)# 设置时间为索引
df.set_index('timestamp', inplace=True)# 生成 K 线图
plt.figure(figsize=(10, 5))
plt.plot(df.index, df['price'], marker='o')
plt.title('PPIG/WBNB Price')
plt.xlabel('Time')
plt.ylabel('Price')
plt.grid()
plt.show()

注意事项

生成k线时,使用到了模拟数据,在实际的环境中注意换成实时数据包装。

这篇关于【Web3初识系列】如何连接 Binance Smart Chain通过交易对绘制 k 线?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1085129

相关文章

MySQL 多表连接操作方法(INNER JOIN、LEFT JOIN、RIGHT JOIN、FULL OUTER JOIN)

《MySQL多表连接操作方法(INNERJOIN、LEFTJOIN、RIGHTJOIN、FULLOUTERJOIN)》多表连接是一种将两个或多个表中的数据组合在一起的SQL操作,通过连接,... 目录一、 什么是多表连接?二、 mysql 支持的连接类型三、 多表连接的语法四、实战示例 数据准备五、连接的性

MySQL中的分组和多表连接详解

《MySQL中的分组和多表连接详解》:本文主要介绍MySQL中的分组和多表连接的相关操作,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录mysql中的分组和多表连接一、MySQL的分组(group javascriptby )二、多表连接(表连接会产生大量的数据垃圾)MySQL中的

MySQL中的交叉连接、自然连接和内连接查询详解

《MySQL中的交叉连接、自然连接和内连接查询详解》:本文主要介绍MySQL中的交叉连接、自然连接和内连接查询,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、引入二、交php叉连接(cross join)三、自然连接(naturalandroid join)四

python连接本地SQL server详细图文教程

《python连接本地SQLserver详细图文教程》在数据分析领域,经常需要从数据库中获取数据进行分析和处理,下面:本文主要介绍python连接本地SQLserver的相关资料,文中通过代码... 目录一.设置本地账号1.新建用户2.开启双重验证3,开启TCP/IP本地服务二js.python连接实例1.

SpringBoot首笔交易慢问题排查与优化方案

《SpringBoot首笔交易慢问题排查与优化方案》在我们的微服务项目中,遇到这样的问题:应用启动后,第一笔交易响应耗时高达4、5秒,而后续请求均能在毫秒级完成,这不仅触发监控告警,也极大影响了用户体... 目录问题背景排查步骤1. 日志分析2. 性能工具定位优化方案:提前预热各种资源1. Flowable

Ubuntu中远程连接Mysql数据库的详细图文教程

《Ubuntu中远程连接Mysql数据库的详细图文教程》Ubuntu是一个以桌面应用为主的Linux发行版操作系统,这篇文章主要为大家详细介绍了Ubuntu中远程连接Mysql数据库的详细图文教程,有... 目录1、版本2、检查有没有mysql2.1 查询是否安装了Mysql包2.2 查看Mysql版本2.

Python3.6连接MySQL的详细步骤

《Python3.6连接MySQL的详细步骤》在现代Web开发和数据处理中,Python与数据库的交互是必不可少的一部分,MySQL作为最流行的开源关系型数据库管理系统之一,与Python的结合可以实... 目录环境准备安装python 3.6安装mysql安装pymysql库连接到MySQL建立连接执行S

Spring Boot 整合 MyBatis 连接数据库及常见问题

《SpringBoot整合MyBatis连接数据库及常见问题》MyBatis是一个优秀的持久层框架,支持定制化SQL、存储过程以及高级映射,下面详细介绍如何在SpringBoot项目中整合My... 目录一、基本配置1. 添加依赖2. 配置数据库连接二、项目结构三、核心组件实现(示例)1. 实体类2. Ma

电脑win32spl.dll文件丢失咋办? win32spl.dll丢失无法连接打印机修复技巧

《电脑win32spl.dll文件丢失咋办?win32spl.dll丢失无法连接打印机修复技巧》电脑突然提示win32spl.dll文件丢失,打印机死活连不上,今天就来给大家详细讲解一下这个问题的解... 不知道大家在使用电脑的时候是否遇到过关于win32spl.dll文件丢失的问题,win32spl.dl

Windows Server服务器上配置FileZilla后,FTP连接不上?

《WindowsServer服务器上配置FileZilla后,FTP连接不上?》WindowsServer服务器上配置FileZilla后,FTP连接错误和操作超时的问题,应该如何解决?首先,通过... 目录在Windohttp://www.chinasem.cnws防火墙开启的情况下,遇到的错误如下:无法与