-
-
Notifications
You must be signed in to change notification settings - Fork 663
/
aggregate.py
168 lines (138 loc) · 5.89 KB
/
aggregate.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
'''
Copyright (C) 2017-2024 Bryant Moscon - bmoscon@gmail.com
Please see the LICENSE file for the terms and conditions
associated with this software.
'''
import time
from decimal import Decimal
import numpy as np
class AggregateCallback:
def __init__(self, handler):
self.handler = handler
if not callable(self.handler):
setattr(self, 'start', self.handler.start)
setattr(self, 'stop', self.handler.stop)
self.__name__ = self.handler.__class__
class Throttle(AggregateCallback):
"""
Wraps a callback and throttles updates based on `window`. Will allow
1 update per `window` interval; all others are dropped
"""
def __init__(self, handler, window=60):
super().__init__(handler)
self.window = window
self.last_update = 0
async def __call__(self, data, receipt_timestamp):
now = time.time()
if now - self.last_update > self.window:
self.last_update = now
await self.handler(data, receipt_timestamp)
class OHLCV(AggregateCallback):
"""
Aggregate trades and calculate OHLCV for time window
window is in seconds, defaults to 300 seconds (5 minutes).
This is an EXAMPLE of how one might use the Aggregation functionality.
You should probably use the candle data channel (if the exchange supports that).
"""
def __init__(self, *args, window=300):
super().__init__(*args)
self.window = window
self.last_update = time.time()
self.data = {}
def _agg(self, symbol, amount, price):
if symbol not in self.data:
self.data[symbol] = {'open': price, 'high': price, 'low': price,
'close': price, 'volume': Decimal(0), 'vwap': Decimal(0)}
self.data[symbol]['close'] = price
self.data[symbol]['volume'] += amount
if price > self.data[symbol]['high']:
self.data[symbol]['high'] = price
if price < self.data[symbol]['low']:
self.data[symbol]['low'] = price
self.data[symbol]['vwap'] += price * amount
async def __call__(self, trade, receipt_timestamp: float):
now = time.time()
if now - self.last_update > self.window:
self.last_update = now
for p in self.data:
self.data[p]['vwap'] /= self.data[p]['volume']
await self.handler(self.data)
self.data = {}
self._agg(trade.symbol, trade.amount, trade.price)
class RenkoFixed(AggregateCallback):
"""
Aggregate trades into Renko bricks with fixed size
brick size is in points, default to 10 (change to ticks later?)
"""
def __init__(self, *args, brick_size=10, **kwargs):
super().__init__(*args, **kwargs)
self.brick_size = brick_size
self.new_brick = True
self.data = {}
self.brick_open = None
self.brick_close = None
self.brick_high = None
self.brick_low = None
self.prev_direction = 0
@staticmethod
def greater_abs(minus, plus):
return minus if -minus > plus else plus
def _agg(self, symbol, price):
if symbol not in self.data:
self.brick_open = price
self.brick_high = price
self.brick_low = price
self.data[symbol] = {'brick_open': price, 'brick_close': price}
self.brick_low = np.min([self.brick_low, price])
self.brick_high = np.max([self.brick_high, price])
# Reversal brick logic
if self.prev_direction == 0:
self.minus_diff = self.brick_low - self.brick_open
self.plus_diff = self.brick_high - self.brick_open
elif self.prev_direction == 1:
self.minus_diff = self.brick_low - self.brick_open
self.plus_diff = self.brick_high - self.brick_close
elif self.prev_direction == -1:
self.minus_diff = self.brick_low - self.brick_close
self.plus_diff = self.brick_high - self.brick_open
self.greater_diff = self.greater_abs(self.minus_diff, self.plus_diff)
if abs(self.greater_diff) >= self.brick_size:
self.new_brick = True
self.new_direction = np.sign(self.greater_diff)
same = self.new_direction == self.prev_direction
if same:
self.brick_open = self.brick_close
self.data[symbol]['brick_open'] = self.brick_open
self.brick_close = price
self.data[symbol]['brick_close'] = self.brick_close
self.brick_high = self.brick_low = self.brick_close
self.prev_direction = self.new_direction
else:
self.new_brick = False
async def __call__(self, trade, receipt_timestamp: float):
if self.new_brick:
await self.handler(self.data)
self._agg(trade.symbol, trade.price)
class CustomAggregate(AggregateCallback):
def __init__(self, *args, window=30, aggregator=None, init=None, **kwargs):
"""
aggregator is a function pointer to the aggregator function. The aggregator will be called with
a dictionary of internal state (the aggregator will define it), and the data from the cryptofeed callback (trade, book, etc).
init is a function pointer that will be called at the start of each time window, with the internal state.
This can be used to clear the internal state or
do other appropriate work (if any).
"""
super().__init__(*args, **kwargs)
self.window = window
self.last_update = time.time()
self.agg = aggregator
self.init = init
self.data = {}
self.init(self.data)
async def __call__(self, dtype, receipt_timestamp: float):
now = time.time()
if now - self.last_update > self.window:
self.last_update = now
await self.handler(self.data)
self.init(self.data)
self.agg(self.data, dtype, receipt_timestamp)