-
Notifications
You must be signed in to change notification settings - Fork 18
/
momentumArbitrage.py
190 lines (156 loc) · 8.8 KB
/
momentumArbitrage.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import asyncio
import itertools
from typing import List
from enum import Enum
from math import ceil, floor
from ready_trader_go import BaseAutoTrader, Instrument, Lifespan, MAXIMUM_ASK, MINIMUM_BID, Side
LOT_SIZE = 10
POSITION_LIMIT = 100
TICK_SIZE_IN_CENTS = 100
MIN_BID_NEAREST_TICK = (MINIMUM_BID + TICK_SIZE_IN_CENTS) // TICK_SIZE_IN_CENTS * TICK_SIZE_IN_CENTS
MAX_ASK_NEAREST_TICK = MAXIMUM_ASK // TICK_SIZE_IN_CENTS * TICK_SIZE_IN_CENTS
class Momentum(Enum):
Up = "up"
Down = "down"
class AutoTrader(BaseAutoTrader):
def __init__(self, loop: asyncio.AbstractEventLoop, team_name: str, secret: str):
"""Initialise a new instance of the AutoTrader class."""
super().__init__(loop, team_name, secret)
self.order_ids = itertools.count(1)
self.bids = set()
self.asks = set()
self.ask_id = self.ask_price = self.bid_id = self.bid_price = self.position = self.hedge_position = 0
self.future_price = 0
self.momentum = None
self.hedge_bids = set()
self.hedge_asks = set()
def on_error_message(self, client_order_id: int, error_message: bytes) -> None:
"""Called when the exchange detects an error.
If the error pertains to a particular order, then the client_order_id
will identify that order, otherwise the client_order_id will be zero.
"""
self.logger.warning("error with order %d: %s", client_order_id, error_message.decode())
if client_order_id != 0 and (client_order_id in self.bids or client_order_id in self.asks):
self.on_order_status_message(client_order_id, 0, 0, 0)
def on_hedge_filled_message(self, client_order_id: int, price: int, volume: int) -> None:
"""Called when one of your hedge orders is filled.
The price is the average price at which the order was (partially) filled,
which may be better than the order's limit price. The volume is
the number of lots filled at that price.
"""
self.logger.info("received hedge filled for order %d with average price %d and volume %d", client_order_id,
price, volume)
if client_order_id in self.hedge_bids:
self.hedge_position += volume
elif client_order_id in self.hedge_asks:
self.hedge_position -= volume
if abs(self.hedge_position) > 100:
print("momentumarb2", self.hedge_position)
def on_order_book_update_message(self, instrument: int, sequence_number: int, ask_prices: List[int],
ask_volumes: List[int], bid_prices: List[int], bid_volumes: List[int]) -> None:
"""Called periodically to report the status of an order book.
The sequence number can be used to detect missed or out-of-order
messages. The five best available ask (i.e. sell) and bid (i.e. buy)
prices are reported along with the volume available at each of those
price levels.
"""
self.logger.info("received order book for instrument %d with sequence number %d", instrument,
sequence_number)
if instrument == Instrument.FUTURE:
self.future_price = future_price = (ask_prices[0] + bid_prices[0]) // 2
if instrument == Instrument.ETF and self.future_price != 0:
etf_price = (ask_prices[0] + bid_prices[0]) // 2
new_bid_price = bid_prices[0] + 100 if bid_prices[0] != 0 else 0
new_ask_price = ask_prices[0] - 100 if ask_prices[0] != 0 else 0
if sum(bid_volumes) >= sum(ask_volumes):
self.momentum = Momentum.Up
else:
self.momentum = Momentum.Down
if self.bid_id != 0 and new_bid_price not in (self.bid_price, 0):
self.send_cancel_order(self.bid_id)
self.bid_id = 0
if self.ask_id != 0 and new_ask_price not in (self.ask_price, 0):
self.send_cancel_order(self.ask_id)
self.ask_id = 0
if self.bid_id == 0 and new_bid_price != 0 and etf_price < self.future_price and self.position <= POSITION_LIMIT - (LOT_SIZE * len(self.bids) + LOT_SIZE):
bid_size = LOT_SIZE
if self.position < 0:
for order in self.asks:
self.send_cancel_order(order)
bid_size += -self.position
self.bid_id = next(self.order_ids)
self.bid_price = new_bid_price
self.send_insert_order(self.bid_id, Side.BUY, new_bid_price, bid_size, Lifespan.GOOD_FOR_DAY)
self.bids.add(self.bid_id)
if self.ask_id == 0 and new_ask_price != 0 and etf_price > self.future_price and self.position >= -POSITION_LIMIT + (LOT_SIZE * len(self.asks) + LOT_SIZE):
ask_size = LOT_SIZE
if self.position > 0:
for order in self.bids:
self.send_cancel_order(order)
ask_size += self.position
self.ask_id = next(self.order_ids)
self.ask_price = new_ask_price
self.send_insert_order(self.ask_id, Side.SELL, new_ask_price, ask_size, Lifespan.GOOD_FOR_DAY)
self.asks.add(self.ask_id)
def on_order_filled_message(self, client_order_id: int, price: int, volume: int) -> None:
"""Called when one of your orders is filled, partially or fully.
The price is the price at which the order was (partially) filled,
which may be better than the order's limit price. The volume is
the number of lots filled at that price.
"""
self.logger.info("received order filled for order %d with price %d and volume %d", client_order_id,
price, volume)
if client_order_id in self.bids:
self.position += volume
elif client_order_id in self.asks:
self.position -= volume
target_hedge_position = self.hedge_position
if self.momentum == Momentum.Up:
if self.position >= 0:
target_hedge_position = max(-POSITION_LIMIT, -self.position + 10)
else:
target_hedge_position = min(POSITION_LIMIT, -self.position + 10)
elif self.momentum == Momentum.Down:
if self.position >= 0:
target_hedge_position = max(-POSITION_LIMIT, -self.position - 10)
else:
target_hedge_position = min(POSITION_LIMIT, -self.position - 10)
hedge_volume = target_hedge_position - self.hedge_position
if hedge_volume != 0:
order_id = next(self.order_ids)
if hedge_volume > 0:
self.send_hedge_order(order_id, Side.BID, MAX_ASK_NEAREST_TICK, hedge_volume)
self.hedge_bids.add(order_id)
elif hedge_volume < 0:
self.send_hedge_order(order_id, Side.ASK, MIN_BID_NEAREST_TICK, -hedge_volume)
self.hedge_asks.add(order_id)
def on_order_status_message(self, client_order_id: int, fill_volume: int, remaining_volume: int,
fees: int) -> None:
"""Called when the status of one of your orders changes.
The fill_volume is the number of lots already traded, remaining_volume
is the number of lots yet to be traded and fees is the total fees for
this order. Remember that you pay fees for being a market taker, but
you receive fees for being a market maker, so fees can be negative.
If an order is cancelled its remaining volume will be zero.
"""
self.logger.info("received order status for order %d with fill volume %d remaining %d and fees %d",
client_order_id, fill_volume, remaining_volume, fees)
if remaining_volume == 0:
if client_order_id == self.bid_id:
self.bid_id = 0
elif client_order_id == self.ask_id:
self.ask_id = 0
# It could be either a bid or an ask
self.bids.discard(client_order_id)
self.asks.discard(client_order_id)
def on_trade_ticks_message(self, instrument: int, sequence_number: int, ask_prices: List[int],
ask_volumes: List[int], bid_prices: List[int], bid_volumes: List[int]) -> None:
"""Called periodically when there is trading activity on the market.
The five best ask (i.e. sell) and bid (i.e. buy) prices at which there
has been trading activity are reported along with the aggregated volume
traded at each of those price levels.
If there are less than five prices on a side, then zeros will appear at
the end of both the prices and volumes arrays.
"""
self.logger.info("received trade ticks for instrument %d with sequence number %d", instrument,
sequence_number)