98 lines
3.1 KiB
Python
98 lines
3.1 KiB
Python
from collections import deque
|
|
from enum import Enum
|
|
import time
|
|
import socket
|
|
import json
|
|
import order
|
|
|
|
team_name = "HanyangFloorFunction"
|
|
|
|
class Dir(str, Enum):
|
|
BUY = "BUY"
|
|
SELL = "SELL"
|
|
|
|
class ExchangeConnection:
|
|
def __init__(self, args):
|
|
self.message_timestamps = deque(maxlen=500)
|
|
self.exchange_hostname = args.exchange_hostname
|
|
self.port = args.port
|
|
exchange_socket = self._connect(add_socket_timeout=args.add_socket_timeout)
|
|
self.reader = exchange_socket.makefile("r", 1)
|
|
self.writer = exchange_socket
|
|
|
|
self._write_message({"type": "hello", "team": team_name.upper()})
|
|
|
|
def read_message(self):
|
|
"""Read a single message from the exchange"""
|
|
message = json.loads(self.reader.readline())
|
|
if "dir" in message:
|
|
message["dir"] = Dir(message["dir"])
|
|
return message
|
|
|
|
def send_add_message(
|
|
self, order_id: int, symbol: str, dir: Dir, price: int, size: int
|
|
):
|
|
"""Add a new order"""
|
|
self._write_message(
|
|
{
|
|
"type": "add",
|
|
"order_id": order_id,
|
|
"symbol": symbol,
|
|
"dir": dir,
|
|
"price": price,
|
|
"size": size,
|
|
}
|
|
)
|
|
|
|
def send_convert_message(self, order_id: int, symbol: str, dir: Dir, size: int):
|
|
"""Convert between related symbols"""
|
|
self._write_message(
|
|
{
|
|
"type": "convert",
|
|
"order_id": order_id,
|
|
"symbol": symbol,
|
|
"dir": dir,
|
|
"size": size,
|
|
}
|
|
)
|
|
|
|
def send_cancel_message(self, order_id: int):
|
|
"""Cancel an existing order"""
|
|
self._write_message({"type": "cancel", "order_id": order_id})
|
|
|
|
def _connect(self, add_socket_timeout):
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
if add_socket_timeout:
|
|
# Automatically raise an exception if no data has been recieved for
|
|
# multiple seconds. This should not be enabled on an "empty" test
|
|
# exchange.
|
|
s.settimeout(5)
|
|
s.connect((self.exchange_hostname, self.port))
|
|
return s
|
|
|
|
def _write_message(self, message):
|
|
what_to_write = json.dumps(message)
|
|
if not what_to_write.endswith("\n"):
|
|
what_to_write = what_to_write + "\n"
|
|
|
|
length_to_send = len(what_to_write)
|
|
total_sent = 0
|
|
while total_sent < length_to_send:
|
|
sent_this_time = self.writer.send(
|
|
what_to_write[total_sent:].encode("utf-8")
|
|
)
|
|
if sent_this_time == 0:
|
|
raise Exception("Unable to send data to exchange")
|
|
total_sent += sent_this_time
|
|
|
|
now = time.time()
|
|
self.message_timestamps.append(now)
|
|
if len(
|
|
self.message_timestamps
|
|
) == self.message_timestamps.maxlen and self.message_timestamps[0] > (now - 1):
|
|
print(
|
|
"WARNING: You are sending messages too frequently. The exchange will start ignoring your messages. Make sure you are not sending a message in response to every exchange message."
|
|
)
|
|
|