Skip to content

Commit 878f403

Browse files
author
mohammadoshkooh
committed
matching engine
0 parents  commit 878f403

File tree

4 files changed

+152
-0
lines changed

4 files changed

+152
-0
lines changed

heap.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Heap:
2+
3+
def heapify(self, heap, n, i, heap_type):
4+
"""
5+
6+
:param heap_type: max or min
7+
:param heap:
8+
:param n: number of nodes
9+
:param i: current node
10+
:return:
11+
"""
12+
largest = i # Initialize largest as root
13+
left = 2 * i + 1
14+
right = 2 * i + 2
15+
16+
if heap_type == 'max':
17+
# See if left child of root exists and is greater than root
18+
if left < n and heap[largest] > heap[left]:
19+
largest = left
20+
21+
# See if right child of root exists and is greater than root
22+
if right < n and heap[largest] > heap[right]:
23+
largest = right
24+
25+
elif heap_type == 'min':
26+
# See if left child of root exists and is greater than root
27+
if left < n and heap[largest] < heap[left]:
28+
largest = left
29+
30+
# See if right child of root exists and is greater than root
31+
if right < n and heap[largest] < heap[right]:
32+
largest = right
33+
34+
# Change root, if needed
35+
if largest != i:
36+
heap[i], heap[largest] = heap[largest], heap[i] # swap
37+
38+
# Heapify the root
39+
self.heapify(heap, n, largest, heap_type)
40+
41+
def heapsort(self, heap, heap_type):
42+
""" Create a sorted heap"""
43+
length = len(heap)
44+
45+
# Build a max heap.
46+
for i in range(length // 2 - 1, -1, -1):
47+
self.heapify(heap, length, i, heap_type)
48+
49+
# One by one extract elements
50+
for i in range(length - 1, 0, -1):
51+
heap[i], heap[0] = heap[0], heap[i] # swap
52+
self.heapify(heap, i, 0, heap_type)

main.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# This is a sample Python script.
2+
3+
# Press Shift+F10 to execute it or replace it with your code.
4+
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
5+
6+
7+
def print_hi(name):
8+
# Use a breakpoint in the code line below to debug your script.
9+
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
10+
11+
12+
# Press the green button in the gutter to run the script.
13+
if __name__ == '__main__':
14+
print_hi('PyCharm')
15+
16+
17+
# See PyCharm help at https://www.jetbrains.com/help/pycharm/

matching_engine.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import heapq
2+
import json
3+
4+
from heap import Heap
5+
6+
7+
class MatchingEngine():
8+
9+
def __init__(self, **kwargs):
10+
# create a heap instance
11+
self.heap = Heap()
12+
13+
# Creating empty heap
14+
super().__init__(**kwargs)
15+
self.seller_min_heap = [] # min heap
16+
heapq.heapify(self.seller_min_heap)
17+
18+
self.buyers_max_heap = [] # max heap
19+
heapq.heapify(self.buyers_max_heap)
20+
21+
# load
22+
with open('app/api/sellers_data.json') as file:
23+
sellers_data = json.load(file)
24+
for element in sellers_data:
25+
heapq.heappush(self.seller_min_heap, (element.get('price'), element))
26+
27+
with open('app/api/buyers_data.json') as file:
28+
buyers_data = json.load(file)
29+
for element in buyers_data:
30+
heapq.heappush(self.buyers_max_heap, (element.get('price'), element))
31+
32+
self.heap.heapsort(self.buyers_max_heap, heap_type='max')
33+
self.heap.heapsort(self.seller_min_heap, heap_type='min')
34+
35+
def matching_engine(self, data):
36+
request_type = data['type']
37+
current_heap = self.seller_min_heap if request_type == 'sell' else self.buyers_max_heap
38+
other_heap = self.buyers_max_heap if request_type == 'sell' else self.seller_min_heap
39+
40+
def comparison():
41+
if request_type == 'sell':
42+
return other_heap[0][1].get('price') >= data['price']
43+
elif request_type == 'buy':
44+
return other_heap[0][1].get('price') <= data['price']
45+
46+
while other_heap[0][1].get('amount') > 0:
47+
if comparison():
48+
if other_heap[0][1].get('amount') <= data['amount']:
49+
data['amount'] -= other_heap[0][1].get('amount')
50+
heapq.heappop(other_heap)
51+
else:
52+
other_heap[0][1].update(
53+
amount=other_heap[0][1].get('amount') - data['amount'])
54+
break
55+
else:
56+
heapq.heappush(current_heap, (data['price'], data))
57+
self.heap.heapsort(current_heap, heap_type='max')
58+
break
59+
60+
@staticmethod
61+
def get_data(self):
62+
serialized_data = input()
63+
data = serialized_data
64+
data['amount'] = float(data['amount'])
65+
self.matching_engine(data)
66+

test.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import requests
2+
3+
# while True:
4+
# api_url = "http://127.0.0.1:8000/api/test/"
5+
# response = requests.get(api_url)
6+
# print(response.text)
7+
8+
9+
from fastapi import FastAPI
10+
11+
app = FastAPI()
12+
13+
14+
@app.get("/")
15+
async def root():
16+
print('f')
17+
return {"message": "Hello World"}

0 commit comments

Comments
 (0)