Skip to content

Instantly share code, notes, and snippets.

@solalatus
Created February 13, 2019 15:47
Show Gist options
  • Save solalatus/1d1338eb36be80dc89b1aad7ab449aa5 to your computer and use it in GitHub Desktop.
Save solalatus/1d1338eb36be80dc89b1aad7ab449aa5 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import threading
import time
#import queue
#import logging
from unittest import TestCase
from HFTOrderbook.lob import LimitOrderBook, Order
#I define a dict here that I will use globally to store the results
results_dict ={}
#I regularly tend to use verb phrases for functions and nouns for objects and classes
#nicety, but helps to orient yourself
def simulate_orderbook(n, name):
#I use the trick to access the variable in a global namespace,
#that is outside of this function, and expose this inside the function also
#this is not a threading based solution, just plain python function call stuff
# See Python namespacing
global results_dict
lob = LimitOrderBook()
for i in range(n):
bid_order = Order(uid=i, is_bid=True, size=5, price=100)
ask_order = Order(uid=i, is_bid=False, size=5, price=200)
lob.process(bid_order)
lob.process(ask_order)
#TO ensure that I do not overwrite the contents generated by the other thread,
#I use the thread's given name parameter as key in a global dict
# Ugly but works
results_dict[name]=lob._orders
t1=threading.Thread(target = simulate_orderbook, name='thread1',
args=(100000, 'thread1'))
t2=threading.Thread(target = simulate_orderbook, name='thread2',
args=(100000, 'thread2'))
t1.start()
t2.start()
#Let's halt the main process till thread2 finishes
#- maybe I am not using this fully right, but seems to work
t2.join()
#waiting for thread1 to surely finish.
#thread2 is surely done, that's what is ensured by the join()
time.sleep(15)
#I access the end results with the dict keys
print(results_dict.keys())
print(len(results_dict['thread1']))
print(len(results_dict['thread2']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment