Files
JSETC/order.py
2026-05-09 15:25:55 +09:00

152 lines
4.9 KiB
Python

import time
from collections import deque
from enum import Enum
class Dir(str, Enum):
BUY = "BUY"
SELL = "SELL"
class OrderManager:
def __init__(self, exchange: "ExchangeConnection"):
symbols = ["BOND", "VALBZ", "VALE", "GS", "MS", "WFC", "XLF"]
self.POSITIONS_LIMIT = {
"BOND": 100,
"VALBZ": 10,
"VALE": 10,
"GS": 100,
"MS": 100,
"WFC": 100,
"XLF": 100,
}
self.exchange = exchange
self._order_size = 0
# 최근 500개의 전송 시간만 기록하는 데크
self._send_timestamps = deque(maxlen=500)
self.orders = {}
self.positions = {s: 0 for s in symbols}
self.future_positions = {s: 0 for s in symbols}
def add_order(self, order_id: int, symbol: str, quantity: int):
self.orders[order_id] = {"symbol": symbol, "quantity": quantity}
def get_order(self, order_id: int):
return self.orders.get(order_id)
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":
size = kwargs["size"]
dir = kwargs["dir"]
if dir == Dir.SELL:
size = -size
if (
self.future_positions[kwargs["symbol"]] + size
> self.POSITIONS_LIMIT[kwargs["symbol"]]
):
return False
self.future_positions[kwargs["symbol"]] += size
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 buy_convert(self, symbol: str, size: int):
if symbol == "VALE":
self.future_positions["VALE"] -= size
self.future_positions["VALBZ"] += size
self.positions["VALE"] -= size
self.positions["VALBZ"] += size
return self.exchange.send_convert_message(
order_id=self.next_order(),
symbol=symbol,
dir="BUY",
size=size,
)
def sell_convert(self, symbol: str, size: int):
if symbol == "VALE":
self.future_positions["VALE"] += size
self.future_positions["VALBZ"] -= size
self.positions["VALE"] += size
self.positions["VALBZ"] -= size
return self.exchange.send_convert_message(
order_id=self.next_order(),
symbol=symbol,
dir="SELL",
size=size,
)
def convert(self, symbol: str, dir: str, size: int):
return self._attempt_send(
"convert",
order_id=self.next_order(),
symbol=symbol,
dir=dir,
size=size,
)
def cancel(self, order_id: int):
return self._attempt_send("cancel", order_id=order_id)
def update_position(self, symbol: str, order_id: int, quantity: int):
self.positions[symbol] = self.positions.get(symbol, 0) + quantity
if order_id in self.orders:
new_size = self.orders[order_id]["quantity"] + quantity
if new_size <= 0:
del self.orders[order_id]
else:
self.orders[order_id]["quantity"] = new_size
def check_pos_limit(self, symbol: str) -> bool:
return abs(self.positions[symbol]) < self.POSITIONS_LIMIT[symbol]