如何使用Matplotlib绘制订单簿深度图(Order Book Depth Chart)
订单簿深度图绘制调整方案
问题原因
你当前的代码存在两个核心问题:
- 直方图
plt.hist是用于统计数据分布频率的工具,和订单深度图的业务逻辑完全不匹配,不需要使用 - 深度图展示的是累计挂单量,而非单个价位的独立挂单量,你之前直接用单个价位的量画柱状图不符合要求
调整后代码
import matplotlib import numpy as np from utilities import get_order_book import matplotlib.pyplot as plt if __name__ == '__main__': pair = 'BTC/USDT' asks, bids = get_order_book(pair) # 处理卖单数据:按价格升序排序,计算累计挂单量 asks_sorted = sorted(asks, key=lambda x: x[0]) ask_prices = [item[0] for item in asks_sorted] ask_cum_qty = np.cumsum([item[1] for item in asks_sorted]) # 处理买单数据:按价格降序排序,计算累计挂单量 bids_sorted = sorted(bids, key=lambda x: -x[0]) bid_prices = [item[0] for item in bids_sorted] bid_cum_qty = np.cumsum([item[1] for item in bids_sorted]) # 绘制深度图 plt.figure(figsize=(12, 6)) # 卖单用红色填充 plt.fill_between(ask_prices, ask_cum_qty, color='#ff4c4c', alpha=0.6, label='卖单(Asks)') # 买单用绿色填充 plt.fill_between(bid_prices, bid_cum_qty, color='#4caf50', alpha=0.6, label='买单(Bids)') # 图表样式优化 plt.xlabel('价格(USDT)') plt.ylabel('累计挂单量(BTC)') plt.title(f'{pair} 订单簿深度图') plt.legend() plt.grid(alpha=0.3) plt.show()
实现说明
- 卖单数据按价格从低到高排序,累计量随价格升高逐步增加,对应深度图右侧的红色区域
- 买单数据按价格从高到低排序,累计量随价格降低逐步增加,对应深度图左侧的绿色区域
- 用
fill_between绘制填充区域,符合常规交易软件的深度图展示效果,如果需要阶梯样式的深度图,把fill_between替换为plt.step即可。
内容的提问来源于stack exchange,提问作者Volatil3
相关产品推荐
相关产品推荐

