-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.py
executable file
·161 lines (82 loc) · 3.09 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
from common.dataloader import *
from common.orderbook import *
import datetime
import math
import matplotlib as mpl
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import os
import pytz
def sym_log(x):
if x>0:
return math.log(1+x)
else:
return -math.log(1-x)
if __name__=="__main__":
INITIAL_TIME = datetime.datetime(2019, 12, 3, 9, 10, 0, 0, tzinfo=pytz.UTC)
FINAL_TIME = datetime.datetime(2019, 12, 3, 9, 15, 0, 0, tzinfo=pytz.UTC)
fpath = "data/raw_socket_capture_sample.json"
product_id = "BTC-GBP"
it = stream_data_coinbase_l2update(fpath, product_id = product_id)
ob = OrderBook(decimal_places_price = 2, decimal_places_volume=8)
prices = []
timestamps = []
idx_x = 0
for n, elem in enumerate(it):
# READ ORDERBOOK
if elem['type'] == "snapshot":
print("RESETTING")
ob.reset(bids = elem['bids'], asks = elem['asks'])
elem['time'] = np.nan
continue
elif elem['type']=="l2update":
for _type, price, volume in elem['changes']:
if _type=="buy": _type="bids"
elif _type=="sell": _type="asks"
ob.update(_type, price, volume)
# We use 'receved_at' instead of 'time' since not all lines have the 'time' key
if elem['received_at']<INITIAL_TIME:
print("Skipping",elem['received_at'])
continue
if elem['received_at']>FINAL_TIME:
print("Final timestamp reached")
break
###################
timestamps.append(elem['time'])
ob.remember_values()
if n%100==0:
print("%s" % (elem['time']))
## Done, organize data in pandas dataframe
total_depth, bids_mask = ob.get_depth_snapshot()
total_depth.set_index(np.array(timestamps), inplace=True)
bids_mask.set_index(np.array(timestamps), inplace=True)
bids = (total_depth * bids_mask).iloc[:,::-1].cumsum(axis=1).iloc[:,::-1]
asks = (total_depth * (1-bids_mask)).cumsum(axis=1)
total_depth = bids+asks
total_depth = total_depth.sort_index().transpose().sort_index().ffill()
## Now let's plot total_depth
# Concatenating colormaps
# I also corrected the color code (green -> bids, red -> asks)
top = plt.cm.get_cmap('Reds',2048)
bottom = plt.cm.get_cmap('Greens',2048)
newcolors = np.vstack(( top(np.linspace(1, 0, 2048)), bottom(np.linspace(0, 1, 2048))))
cmap = mpl.colors.ListedColormap(newcolors)
# Yes, you can apply vector operations here. No, it's not faster. Yes, I benchmarked it.
# Yes, you can use a logaritmic color scale in pcolor_mesh. No, it won't work since we have negative values.
# No, we cannot use the absolute value since we'd lose the color information (green/red).
total_depth = total_depth.applymap(sym_log)
X = total_depth.columns.tolist()
Y = np.array(total_depth.index)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
myFmt = mdates.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_formatter(myFmt)
ax.pcolormesh(X, Y, np.array(total_depth), cmap = cmap, norm = plt.Normalize(-5,5))
ax.set_ylim(5610,5660)
ax.set_xlabel("Time (GMT)")
ax.set_ylabel("Price")
plt.show()