Last active
February 16, 2019 15:26
-
-
Save dlbas/6120c8c82d8b593640568395637534a9 to your computer and use it in GitHub Desktop.
Order matching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque, namedtuple | |
from random import randint, random | |
class Order: | |
def __init__(self, sum, price, type): | |
self.sum = sum | |
self.price = price | |
self.type = type | |
self.status = 'new' | |
def __str__(self): | |
return f'[{self.status}|{self.type}] {self.sum}@{self.price}' | |
book = {'sell': deque(), 'buy': deque()} | |
for i in range(10): | |
book['buy'].append(Order(randint(50, 100), 1 + random(), 'buy')) | |
book['sell'].append(Order(randint(50, 100), 2 + random(), 'sell')) | |
def trade_orders(order1, order2): | |
trade_amount = min(order1.sum, order2.sum) | |
order1.sum -= trade_amount | |
order2.sum -= trade_amount | |
if order1.sum == 0: | |
order1.status = 'completed' | |
if order2.sum == 0: | |
order2.status = 'completed' | |
return order1, order2 | |
def place_order(order): | |
counter_type = 'buy' if order.type == 'sell' else 'sell' | |
counter_orders = book.get(counter_type, []) | |
for i, o in enumerate(counter_orders): | |
if counter_type == 'sell' and o.price <= order.price: | |
trade_orders(order, counter_orders[i]) | |
elif counter_type == 'buy' and o.price >= order.price: | |
trade_orders(order, counter_orders[i]) | |
if order.status == 'completed': | |
return | |
else: | |
book[counter_type].append(order) | |
place_order(Order(128, 2.5, 'buy')) | |
print(*(str(o) for o in book['sell'] if o.status == 'completed')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment