首页 > 编程语言 >交易簿和报价算法

交易簿和报价算法

时间:2023-03-30 16:13:12浏览次数:37  
标签:asks self top bids 交易 price 算法 报价 order

# 定义交易簿类
class OrderBook:
    def __init__(self):
        self.bids = {}  # 买方委托,按价格从高到低排序
        self.asks = {}  # 卖方委托,按价格从低到高排序
    
    def add_order(self, order):
        if order.side == 'buy':
            if order.price in self.bids:
                self.bids[order.price] += order.quantity
            else:
                self.bids[order.price] = order.quantity
            self.bids = dict(sorted(self.bids.items(), key=lambda x: x[0], reverse=True))  # 按价格从高到低排序
        elif order.side == 'sell':
            if order.price in self.asks:
                self.asks[order.price] += order.quantity
            else:
                self.asks[order.price] = order.quantity
            self.asks = dict(sorted(self.asks.items(), key=lambda x: x[0]))  # 按价格从低到高排序
    
    def remove_order(self, order):
        if order.side == 'buy':
            self.bids[order.price] -= order.quantity
            if self.bids[order.price] == 0:
                del self.bids[order.price]
        elif order.side == 'sell':
            self.asks[order.price] -= order.quantity
            if self.asks[order.price] == 0:
                del self.asks[order.price]
    
    def get_top_bid(self):
        if self.bids:
            return max(self.bids.keys())
        else:
            return None
    
    def get_top_ask(self):
        if self.asks:
            return min(self.asks.keys())
        else:
            return None

# 定义报价算法类
class MarketMaker:
    def __init__(self, order_book, spread=0.01):
        self.order_book = order_book
        self.spread = spread
    
    def get_bid_price(self):
        top_ask = self.order_book.get_top_ask()
        if top_ask:
            return top_ask - self.spread
        else:
            return None
    
    def get_ask_price(self):
        top_bid = self.order_book.get_top_bid()
        if top_bid:
            return top_bid + self.spread
        else:
            return None

 

标签:asks,self,top,bids,交易,price,算法,报价,order
From: https://www.cnblogs.com/kingkaixuan/p/17273132.html

相关文章