from collections import deque
from typing import Dict, List, Deque, Optional
from sortedcontainers import SortedDict
import numpy as np
import pandas as pd
from .order import Order
from .utils import *
from ...calculation.math import accurate_round
class OrderBook:
def __init__(self, current_time, date: int = None, record_deleted: bool = False):
self.bid_levels: Dict[float, Deque[Order]] = {} # 买盘列表
self.ask_levels: Dict[float, Deque[Order]] = {} # 卖盘列表
self.bid_volumes: SortedDict[float, int] = SortedDict() # 买量
self.ask_volumes: SortedDict[float, int] = SortedDict() # 卖量
self.bid_volumes_pure: SortedDict[float, int] = SortedDict() # 纯净买量
self.ask_volumes_pure: SortedDict[float, int] = SortedDict() # 纯净卖量
self.historical_order = [] # 历史订单列表
self.historical_deleted_order = [] # 历史删除订单列表
self.record_deleted = record_deleted
self.historical_transaction = pd.DataFrame([],
columns=["time", "price", "vol", "bid_uid", "ask_uid",
"is_ours", "our_direction", "our_cashflow",
"BSFlag", "bid_total", "ask_total"]) # 成交序列
self._historical_orderbook = []
self.date = date
self.start_time = 0
self.end_time = current_time
self.period_prices = []
self.our_active_orders = []
self.our_orders = []
self.our_transactions = pd.DataFrame(columns=["uid", "is_buy", "price", "matched_quantity",
"time", "exposure_change"])
self.our_period_holdings_change = 0
self._PRE_AUCTION_TIME = 91500000
self._PRE_AUCTION_MATCH_TIME = 92500000
self._OPEN_TIME = 93000000
self._AFTER_AUCTION_TIME = 145700000
self._AFTER_AUCTION_MATCH_TIME = 150000000
self.morning_auction = False
self.afternoon_auction = False
def submit_order(self, uid, is_delete, is_buy, time_submitted, price,
quantity=0, is_ours=False, is_market=None, ApplSeqNum=None):
if is_delete:
idx, existing_order = self.get_order(uid, price, is_buy)
if existing_order is None:
return
if existing_order.active:
existing_order.time_finished = time_submitted if existing_order.matched_quantity > 0 else None
if is_buy:
del self.bid_levels[price][idx]
else:
del self.ask_levels[price][idx]
self.volumes_calc(is_buy, existing_order.price, existing_order.remaining_quantity)
existing_order.active = False
self.historical_order.append(existing_order)
self._our_order_arrange(existing_order)
if self.record_deleted:
cancellation_order = Order(uid=uid, is_buy=is_buy,
quantity=existing_order.quantity - existing_order.matched_quantity,
price=price, time_submitted=time_submitted, is_delete=is_delete,
is_ours=is_ours, is_market=is_market, active=False, ApplSeqNum=ApplSeqNum)
cancellation_order.time_finished = time_submitted if existing_order.matched_quantity > 0 else None
self.historical_deleted_order.append(cancellation_order)
elif quantity > 0:
if is_buy:
if price not in self.bid_levels:
self.bid_levels[price] = deque()
if price not in self.bid_volumes:
self.bid_volumes[price] = 0
self.bid_levels[price].append(Order(uid=uid, is_buy=is_buy, quantity=quantity, price=price,
time_submitted=time_submitted, is_ours=is_ours, is_market=is_market,
ApplSeqNum=ApplSeqNum))
self.bid_volumes[price] += quantity
else:
if price not in self.ask_levels:
self.ask_levels[price] = deque()
if price not in self.ask_volumes:
self.ask_volumes[price] = 0
self.ask_levels[price].append(Order(uid=uid, is_buy=is_buy, quantity=quantity, price=price,
time_submitted=time_submitted, is_ours=is_ours, is_market=is_market,
ApplSeqNum=ApplSeqNum))
self.ask_volumes[price] += quantity
if is_ours:
self.our_active_orders.append((uid, is_buy, price, quantity, time_submitted))
self.trade_matching(time_submitted, uid)
def auction_matching(self): # 集合竞价撮合
if self.end_time < self._OPEN_TIME: # 盘前集合竞价
if not self.morning_auction and self.end_time >= self._PRE_AUCTION_MATCH_TIME: # 盘前集中成交
self._auction_process()
self.morning_auction = True
elif self._AFTER_AUCTION_TIME < self.end_time: # 盘后集合竞价
if not self.afternoon_auction and self.end_time >= self._AFTER_AUCTION_MATCH_TIME: # 盘后集中成交
self._auction_process()
self.afternoon_auction = True
def trade_matching(self, time_submitted, latest_uid): # 连续竞价撮合
if self._OPEN_TIME <= self.end_time <= self._AFTER_AUCTION_TIME:
while self.best_bid >= self.best_ask and len(self.ask_volumes) > 0 and len(self.bid_volumes) > 0:
bid = self.bid_levels[self.bid_volumes.peekitem(-1)[0]][0]
ask = self.ask_levels[self.ask_volumes.peekitem(0)[0]][0]
# 1: 主买, -1: 主卖
if bid.time_submitted > ask.time_submitted:
bs_flag = 1
elif bid.time_submitted < ask.time_submitted:
bs_flag = -1
else:
bs_flag = 1 if bid.uid == latest_uid else -1
vol = min(bid.remaining_quantity, ask.remaining_quantity)
is_ours, our_direction = check_our_orders(ask, bid)
trade_price = ask.price if bs_flag == 1 else bid.price
bid.trade_money += accurate_round(trade_price * vol, 2)
ask.trade_money += accurate_round(trade_price * vol, 2)
self.historical_transaction.loc[len(self.historical_transaction)] = [time_submitted, trade_price,
vol, bid.uid, ask.uid, is_ours,
our_direction,
our_direction * vol * trade_price,
bs_flag,
bid.quantity, ask.quantity]
self.period_prices.append(trade_price)
if is_ours:
self.our_period_holdings_change += vol if our_direction == 1 else -vol
bid.matched_quantity += vol
ask.matched_quantity += vol
self.volumes_calc(True, bid.price, vol)
self.volumes_calc(False, ask.price, vol)
self._our_transaction_record(bid, trade_price, vol, time_submitted)
self._our_transaction_record(ask, trade_price, vol, time_submitted)
没有合适的资源?快使用搜索试试~ 我知道了~
撮合引擎代码 处理低价股票的排队问题
共35个文件
py:17个
pyc:16个
csv:2个
0 下载量 76 浏览量
2023-12-22
17:07:33
上传
评论
收藏 29.4MB ZIP 举报
温馨提示
处理低价股票的排队问题,低价股票因为价格变动比较小,会导致订单薄很厚 ,排队很长,所以会有排队排不到成交不了的情况,导致有风险敞口。现在想设计一款算法,使得敞口存续时间最小,输入每几秒的盘口情况,输出敞口存续时间最小的盘口(即在何位置挂单、挂多少数量的单) 需要用到撮合引擎来生成订单薄
资源推荐
资源详情
资源评论
收起资源包目录
simulate_trading_platform.zip (35个子文件)
simulate_trading_platform
data
688093
688093.SH_T.csv 69.2MB
688093.SH_O.csv 154.66MB
demo_simple.py 3KB
tec_toolbox
__init__.py 62B
calculation
__init__.py 43B
math.py 257B
__pycache__
__init__.cpython-311.pyc 253B
math.cpython-311.pyc 882B
__pycache__
__init__.cpython-311.pyc 262B
intraday_simulation
__init__.py 86B
portfolio
__init__.py 155B
output.py 11KB
manager.py 11KB
__pycache__
strategy.cpython-311.pyc 8KB
output.cpython-311.pyc 17KB
__init__.cpython-311.pyc 401B
manager.cpython-311.pyc 19KB
order_place.cpython-311.pyc 2KB
execution.cpython-311.pyc 1KB
order_place.py 1KB
execution.py 678B
strategy.py 6KB
__pycache__
__init__.cpython-311.pyc 304B
market
utils.py 5KB
__init__.py 193B
orderbook.py 23KB
order.py 2KB
orderflow_handling.py 9KB
simulator.py 5KB
__pycache__
__init__.cpython-311.pyc 448B
utils.cpython-311.pyc 5KB
orderflow_handling.cpython-311.pyc 12KB
order.cpython-311.pyc 4KB
orderbook.cpython-311.pyc 37KB
simulator.cpython-311.pyc 7KB
共 35 条
- 1
资源评论
点云-激光雷达-Slam-三维牙齿
- 粉丝: 1427
- 资源: 13
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功