Created
March 18, 2023 13:32
-
-
Save lawrence910426/43a8e000c2e96063fa1d2c293bfe93fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright 2021 Optiver Asia Pacific Pty. Ltd. | |
# | |
# This file is part of Ready Trader Go. | |
# | |
# Ready Trader Go is free software: you can redistribute it and/or | |
# modify it under the terms of the GNU Affero General Public License | |
# as published by the Free Software Foundation, either version 3 of | |
# the License, or (at your option) any later version. | |
# | |
# Ready Trader Go is distributed in the hope that it will be useful, | |
# but WITHOUT ANY WARRANTY; without even the implied warranty of | |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
# GNU Affero General Public License for more details. | |
# | |
# You should have received a copy of the GNU Affero General Public | |
# License along with Ready Trader Go. If not, see | |
# <https://www.gnu.org/licenses/>. | |
import asyncio | |
import itertools | |
import time | |
import collections | |
from typing import List | |
from typing import Deque | |
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 AutoTrader(BaseAutoTrader): | |
"""Example Auto-trader. | |
When it starts this auto-trader places ten-lot bid and ask orders at the | |
current best-bid and best-ask prices respectively. Thereafter, if it has | |
a long position (it has bought more lots than it has sold) it reduces its | |
bid and ask prices. Conversely, if it has a short position (it has sold | |
more lots than it has bought) then it increases its bid and ask prices. | |
""" | |
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, self.asks = {}, {} # { order_id: (price, remain volume) } | |
self.position = 0 | |
self.bid_info, self.ask_info = {}, {} # { price: order_id } | |
self.pending_bids = self.pending_asks = 0 | |
self.events: Deque[float] = collections.deque() | |
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) | |
def place_bid(self, price: int, volume: int) -> None: | |
"""Place a new bid order at the given price and volume.""" | |
order_id = next(self.order_ids) | |
volume = min(volume, POSITION_LIMIT - self.position - self.pending_bids) | |
if volume > 0: | |
if not self.speed_limit(): | |
return | |
self.send_insert_order(order_id, Side.BUY, price, volume, Lifespan.GOOD_FOR_DAY) | |
self.bids[order_id] = (price, volume) | |
self.pending_bids += volume | |
self.bid_info[price] = order_id | |
def place_ask(self, price: int, volume: int) -> None: | |
"""Place a new ask order at the given price and volume.""" | |
order_id = next(self.order_ids) | |
volume = min(volume, POSITION_LIMIT + self.position - self.pending_asks) | |
if volume > 0: | |
if not self.speed_limit(): | |
return | |
self.send_insert_order(order_id, Side.SELL, price, volume, Lifespan.GOOD_FOR_DAY) | |
self.asks[order_id] = (price, volume) | |
self.pending_asks += volume | |
self.ask_info[price] = order_id | |
return order_id | |
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: | |
if bid_prices[0] == 0 or ask_prices[0] == 0: | |
return # Futures has no liquidity now. | |
adjust_max_position = 0 | |
adjust_max_position = -TICK_SIZE_IN_CENTS if self.position == +POSITION_LIMIT else adjust_max_position | |
adjust_max_position = +TICK_SIZE_IN_CENTS if self.position == -POSITION_LIMIT else adjust_max_position | |
new_bid_price = [bid_prices[0] + adjust_max_position - TICK_SIZE_IN_CENTS * i for i in range(1, 4)] | |
new_ask_price = [ask_prices[0] + adjust_max_position + TICK_SIZE_IN_CENTS * i for i in range(1, 4)] | |
new_volume = [50, 75, 100] | |
# Cancel the orders not in the new price range. | |
for price, order_id in self.bid_info.items(): | |
if price not in new_bid_price: | |
if self.speed_limit(): | |
self.send_cancel_order(order_id) | |
for price, order_id in self.ask_info.items(): | |
if price not in new_ask_price: | |
if self.speed_limit(): | |
self.send_cancel_order(order_id) | |
# Add the orders not in the new price range. | |
for i in range(len(new_volume)): | |
price, vol = new_bid_price[i], new_volume[i] | |
if price not in self.bid_info: | |
self.place_bid(price, vol) | |
for i in range(len(new_volume)): | |
price, vol = new_ask_price[i], new_volume[i] | |
if price not in self.ask_info: | |
self.place_ask(price, vol) | |
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 | |
self.pending_bids -= volume | |
price, remain_vol = self.bids[client_order_id] | |
self.bids[client_order_id] = price, remain_vol - volume | |
self.speed_limit(True) | |
self.send_hedge_order(next(self.order_ids), Side.ASK, MIN_BID_NEAREST_TICK, volume) | |
if client_order_id in self.asks: | |
self.position -= volume | |
self.pending_asks -= volume | |
price, remain_vol = self.asks[client_order_id] | |
self.asks[client_order_id] = price, remain_vol - volume | |
self.speed_limit(True) | |
self.send_hedge_order(next(self.order_ids), Side.BID, MAX_ASK_NEAREST_TICK, volume) | |
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) | |
# The order has been cancelled. | |
if remaining_volume == 0: | |
if client_order_id in self.bids: | |
price, volume = self.bids[client_order_id] | |
self.pending_bids -= volume | |
self.bid_info.pop(price) | |
if client_order_id in self.asks: | |
price, volume = self.asks[client_order_id] | |
self.pending_asks -= volume | |
self.ask_info.pop(price) | |
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) | |
def speed_limit(self, emergency=False): | |
"""Called on every market operation to limit the speed of the strategy.""" | |
if emergency: | |
self.logger.info("emergency market operation") | |
self.events.append(time.time()) | |
return | |
# Sleep until the cooldown is completed. | |
max_queue_length = 30 | |
while len(self.events) > max_queue_length: | |
if self.events[0] + 1 < time.time(): | |
self.events.popleft() | |
else: | |
return False | |
# Add the new operation to deque. | |
self.events.append(time.time()) | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment