add many change

This commit is contained in:
2026-05-09 14:04:07 +09:00
parent d17815f727
commit f015d73e87
5 changed files with 156 additions and 209 deletions

View File

@@ -1,97 +0,0 @@
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."
)

View File

@@ -1,52 +0,0 @@
import time
from collections import deque
from ETC import ExchangeConnection, Dir
class OrderManager:
def __init__(self, exchange: ExchangeConnection):
self.exchange = exchange
self._order_size = 0
# 최근 500개의 전송 시간만 기록하는 데크
self._send_timestamps = deque(maxlen=500)
def next_order(self):
self._order_size += 1
return self._order_size
def _attempt_send(self, action_type: str, **kwargs) -> bool:
"""
주문 전송을 시도합니다.
제한에 걸려 무시되면 False를, 정상 전송되면 True를 반환합니다.
"""
now = time.time()
# 최근 500개를 이미 보냈다면, 가장 오래된 주문(0번 인덱스)의 시간을 확인
if len(self._send_timestamps) == 500:
elapsed = now - self._send_timestamps[0]
if elapsed < 1.01:
# 1.01초 내에 500개를 이미 보냈으므로 이 요청은 무시합니다.
# (print문은 필요시 주석 해제하여 로깅 용도로 사용하세요)
# print("전송 제한 초과! 주문이 무시되었습니다.")
return False
# 전송 조건 통과 시 실제 통신 수행
if action_type == "add":
self.exchange.send_add_message(**kwargs)
elif action_type == "cancel":
self.exchange.send_cancel_message(**kwargs)
elif action_type == "convert":
self.exchange.send_convert_message(**kwargs)
# 전송한 시간 기록
self._send_timestamps.append(now)
return True
def sell(self, symbol: str, dir: Dir, price: int, size: int):
return self._attempt_send("add", order_id=self.next_order(), symbol=symbol, dir=dir, price=price, size=size)
def buy(self, symbol: str, dir: Dir, price: int, size: int):
return self._attempt_send("add", order_id=self.next_order(), symbol=symbol, dir=dir, price=price, size=size)
def cancel(self, order_id: int):
return self._attempt_send("cancel", order_id=order_id)