2024-11-23 stan

订单簿深度查询命令分析笔记

一、命令概述

1.1 CMD_ORDER_BOOK

用于查询原始订单簿数据,按照价格优先、时间优先排序返回指定数量的订单信息。

1.2 CMD_ORDER_BOOK_DEPTH

用于查询市场深度数据,支持价格区间合并,主要用于行情展示和交易决策。

二、业务逻辑流程

2.1 CMD_ORDER_BOOK流程

graph TD
A[接收请求参数] --> B[参数校验]
B --> C[获取市场订单簿]
C --> D[根据side获取asks/bids迭代器]
D --> E[按照offset跳过指定数量订单]
E --> F[获取limit数量的订单信息]
F --> G[返回结果]

2.2 CMD_ORDER_BOOK_DEPTH流程

graph TD
A[接收请求参数] --> B[参数校验]
B --> C[检查缓存]
C --> |命中缓存| D[返回缓存结果]
C --> |未命中缓存| E[根据interval判断处理方式]
E --> |interval=0| F[获取原始深度]
E --> |interval>0| G[获取合并深度]
F --> H[构建结果缓存]
G --> H
H --> I[返回结果]

三、数据结构与接口

3.1 核心数据结构

// 市场结构
typedef struct market_t {
    char *name;
    skiplist_t *asks;  // 卖单队列
    skiplist_t *bids;  // 买单队列
} market_t;

// 订单结构
typedef struct order_t {
    uint64_t id;
    uint32_t type;
    uint32_t side;
    mpd_t *price;
    mpd_t *amount;
    mpd_t *left;
} order_t;

// 缓存结构
struct cache_val {
    double time;
    json_t *result;
};

3.2 主要接口

// 市场接口
market_t *get_market(const char *market);
json_t *get_order_info(order_t *order);

// 深度计算
json_t *get_depth(market_t *market, size_t limit);
json_t *get_depth_merge(market_t *market, size_t limit, mpd_t *interval);

// 缓存处理
bool process_cache(nw_ses *ses, rpc_pkg *pkg, sds *cache_key);
int add_cache(sds cache_key, json_t *result);

四、算法实现与性能分析

4.1 订单簿查询算法

// 遍历指定数量的订单
skiplist_iter *iter = skiplist_get_iterator(order_list);
for (size_t i = 0; i < offset; i++) {
    if (skiplist_next(iter) == NULL)
        break;
}

while ((node = skiplist_next(iter)) != NULL && index < limit) {
    order_t *order = node->value;
    json_array_append_new(orders, get_order_info(order));
    index++;
}