This commit is contained in:
2026-05-09 13:11:45 +09:00
parent ac3d1d0db9
commit 97ca53ba7c

View File

@@ -10,6 +10,8 @@ from enum import Enum
import time import time
import socket import socket
import json import json
from state import StateManager
from order import OrderManager
# ~~~~~============== CONFIGURATION ==============~~~~~ # ~~~~~============== CONFIGURATION ==============~~~~~
# Replace "REPLACEME" with your team name! # Replace "REPLACEME" with your team name!
@@ -42,25 +44,31 @@ def main():
# Send an order for BOND at a good price, but it is low enough that it is # Send an order for BOND at a good price, but it is low enough that it is
# unlikely it will be traded against. Maybe there is a better price to # unlikely it will be traded against. Maybe there is a better price to
# pick? Also, you will need to send more orders over time. # pick? Also, you will need to send more orders over time.
# --- BOND 마켓 메이킹 설정 --- # --- 설정 ---
FAIR_VALUE = 1000 # BOND fair value (고정) BOND_FAIR_VALUE = 1000 # BOND fair value (고정)
ORDER_SIZE = 5 # 가격대별 주문 수량 BOND_ORDER_SIZE = 30 # BOND 주문 수량
MAX_POSITION = 100 # 최대 포지션 한도 BOND_MAX_POSITION = 100 # BOND 최대 포지션 한도
REFRESH_INTERVAL = 5.0 # 주문 갱신 주기 (초) XLF_CONVERSION_FEE = 100 # XLF 변환 비용 (설명서: 100)
XLF_MAX_POSITION = 100 # XLF 포지션 한도
REFRESH_INTERVAL = 5.0 # 주문 갱신 주기 (초)
# 매수: 999, 998, 997 / 매도: 1001, 1002, 1003 # XLF state machine
BUY_PRICES = [FAIR_VALUE - 1, FAIR_VALUE - 2, FAIR_VALUE - 3] # IDLE → BUYING_BASKET → CONVERTING → SELLING_XLF → IDLE (바스켓→XLF)
SELL_PRICES = [FAIR_VALUE + 1, FAIR_VALUE + 2, FAIR_VALUE + 3] # IDLE → BUYING_XLF → CONVERTING → SELLING_BASKET → IDLE (XLF→바스켓)
xlf_state = "IDLE"
xlf_pending = set() # 체결 대기 중인 주문 ID
xlf_direction = None # "BASKET_TO_XLF" or "XLF_TO_BASKET"
position = 0 # 현재 BOND 포지션 state = StateManager()
order_id = 0 # 단조 증가하는 주문 ID om = OrderManager()
active_orders = {} # {order_id: {"dir": ..., "price": ...}} market_open = False
market_open = False # 시장 open 여부 (open 전에는 주문 불가) active_orders = {} # BOND 전용 {order_id: {"dir": ..., "price": ...}}
last_refresh = time.time()
vale_last_print = time.time()
def next_id(): def next_id():
nonlocal order_id return om.next_order()
order_id += 1
return order_id
def cancel_all_bond_orders(): def cancel_all_bond_orders():
"""활성 BOND 주문 전부 취소""" """활성 BOND 주문 전부 취소"""
@@ -69,63 +77,137 @@ def main():
active_orders.pop(oid, None) active_orders.pop(oid, None)
def place_bond_orders(): def place_bond_orders():
"""여러 가격대에 분산해서 매수/매도 주문""" """포지션 한도 안에서 bid/ask 양방향 주문"""
if not market_open: if not market_open:
return return
cancel_all_bond_orders() cancel_all_bond_orders()
# 포지션에 따라 size 조정 buy_price = BOND_FAIR_VALUE - 1 # 999
base_size = ORDER_SIZE sell_price = BOND_FAIR_VALUE + 1 # 1001
position = state.get_position("BOND")
# 포지션에 따라 size 비대칭 조정
base_size = BOND_ORDER_SIZE
adjustment = abs(position) // 5 adjustment = abs(position) // 5
if position < 0: if position < 0:
buy_size = min(base_size + adjustment, MAX_POSITION) # 숏 포지션 → 매수를 더 많이
buy_size = min(base_size + adjustment, BOND_MAX_POSITION - position)
sell_size = max(base_size - adjustment, 1) sell_size = max(base_size - adjustment, 1)
elif position > 0: elif position > 0:
# 롱 포지션 → 매도를 더 많이
buy_size = max(base_size - adjustment, 1) buy_size = max(base_size - adjustment, 1)
sell_size = min(base_size + adjustment, MAX_POSITION) sell_size = min(base_size + adjustment, BOND_MAX_POSITION + position)
else: else:
buy_size = base_size buy_size = base_size
sell_size = base_size sell_size = base_size
# 999, 998, 997 세 가격대에 매수 주문 if buy_size > 0:
for buy_price in BUY_PRICES: bid = next_id()
if position < MAX_POSITION: exchange.send_add_message(
bid = next_id() order_id=bid, symbol="BOND",
exchange.send_add_message( dir=Dir.BUY, price=buy_price, size=buy_size
order_id=bid, symbol="BOND", )
dir=Dir.BUY, price=buy_price, size=buy_size active_orders[bid] = {"dir": Dir.BUY, "price": buy_price}
)
active_orders[bid] = {"dir": Dir.BUY, "price": buy_price}
# 1001, 1002, 1003 세 가격대에 매도 주문 if sell_size > 0:
for sell_price in SELL_PRICES: ask = next_id()
if position > -MAX_POSITION: exchange.send_add_message(
ask = next_id() order_id=ask, symbol="BOND",
exchange.send_add_message( dir=Dir.SELL, price=sell_price, size=sell_size
order_id=ask, symbol="BOND", )
dir=Dir.SELL, price=sell_price, size=sell_size active_orders[ask] = {"dir": Dir.SELL, "price": sell_price}
)
active_orders[ask] = {"dir": Dir.SELL, "price": sell_price}
print(f" BOND 주문 → 매수: {BUY_PRICES} x{buy_size}, 매도: {SELL_PRICES} x{sell_size}, 포지션: {position}") print(f" BOND 주문 → 매수:{buy_price} x{buy_size}, 매도:{sell_price} x{sell_size}, 포지션:{position}")
def try_xlf_arb():
"""XLF 차익거래 시도 - IDLE 상태일 때만"""
nonlocal xlf_state, xlf_direction, xlf_pending
if not market_open or xlf_state != "IDLE":
return
bond_ask = state.ask_prices["BOND"]
gs_ask = state.ask_prices["GS"]
ms_ask = state.ask_prices["MS"]
wfc_ask = state.ask_prices["WFC"]
xlf_bid = state.bid_prices["XLF"]
bond_bid = state.bid_prices["BOND"]
gs_bid = state.bid_prices["GS"]
ms_bid = state.bid_prices["MS"]
wfc_bid = state.bid_prices["WFC"]
xlf_ask = state.ask_prices["XLF"]
if None in [bond_ask, gs_ask, ms_ask, wfc_ask, xlf_bid,
bond_bid, gs_bid, ms_bid, wfc_bid, xlf_ask]:
return
# 바스켓 비용/수익 계산 (10주 기준)
basket_ask = bond_ask*3 + gs_ask*2 + ms_ask*3 + wfc_ask*2
basket_bid = bond_bid*3 + gs_bid*2 + ms_bid*3 + wfc_bid*2
# 케이스 1: 바스켓 매수 → XLF 변환 → XLF 매도
profit1 = xlf_bid * 10 - basket_ask - XLF_CONVERSION_FEE
if profit1 > 0 and state.get_position("XLF") < XLF_MAX_POSITION:
print(f" XLF 차익(바스켓→XLF) 시작, 예상수익:{profit1}")
xlf_state = "BUYING_BASKET"
xlf_direction = "BASKET_TO_XLF"
xlf_pending.clear()
# 바스켓 구성 종목 매수
for sym, qty in [("BOND", 3), ("GS", 2), ("MS", 3), ("WFC", 2)]:
oid = next_id()
exchange.send_add_message(oid, sym, Dir.BUY, state.ask_prices[sym], qty)
xlf_pending.add(oid)
return
# 케이스 2: XLF 매수 → 바스켓 변환 → 각 종목 매도
profit2 = basket_bid - xlf_ask * 10 - XLF_CONVERSION_FEE
if profit2 > 0 and state.get_position("XLF") > -XLF_MAX_POSITION:
print(f" XLF 차익(XLF→바스켓) 시작, 예상수익:{profit2}")
xlf_state = "BUYING_XLF"
xlf_direction = "XLF_TO_BASKET"
xlf_pending.clear()
oid = next_id()
exchange.send_add_message(oid, "XLF", Dir.BUY, xlf_ask, 10)
xlf_pending.add(oid)
def handle_xlf_fill(order_id: int, symbol: str, dir_: Dir, qty: int):
"""XLF state machine 체결 처리"""
nonlocal xlf_state, xlf_pending
if order_id not in xlf_pending:
return
xlf_pending.discard(order_id)
if xlf_state == "BUYING_BASKET" and not xlf_pending:
# 바스켓 전부 체결 → XLF로 변환
print(" 바스켓 매수 완료 → XLF 변환 시작")
xlf_state = "CONVERTING"
exchange.send_convert_message(next_id(), "XLF", Dir.BUY, 10)
elif xlf_state == "BUYING_XLF" and not xlf_pending:
# XLF 매수 완료 → 바스켓으로 변환
print(" XLF 매수 완료 → 바스켓 변환 시작")
xlf_state = "CONVERTING"
exchange.send_convert_message(next_id(), "XLF", Dir.SELL, 10)
# Set up some variables to track the bid and ask price of a symbol. Right # Set up some variables to track the bid and ask price of a symbol. Right
# now this doesn't track much information, but it's enough to get a sense # now this doesn't track much information, but it's enough to get a sense
# of the VALE market. # of the VALE market.
vale_bid_price, vale_ask_price = None, None
vale_last_print_time = time.time() vale_last_print_time = time.time()
last_refresh = time.time()
# Here is the main loop of the program. It will continue to read and # Here is the main loop of the program. It will continue to read and
# process messages in a loop until a "close" message is received. You # process messages in a loop until a "close" message is received. You
# should write to code handle more types of messages (and not just print # should write to code handle more types of messages (and not just print
# the message). Feel free to modify any of the starter code below. # the message). Feel free to modify any of the starter code below.
# #
# Note: a common mistake people make is to call write_message() at least # Note: a common mistake people make is to call write_message() at least
# once for every read_machine() response. # once for every read_message() response.
# #
# Every message sent to the exchange generates at least one response # Every message sent to the exchange generates at least one response
# message. Sending a message in response to every exchange message will # message. Sending a message in response to every exchange message will
@@ -143,47 +225,100 @@ def main():
if message["type"] == "close": if message["type"] == "close":
print("The round has ended") print("The round has ended")
break break
elif message["type"] == "open": elif message["type"] == "open":
# 시장이 열렸을 때 주문 시작 (open 전에 주문하면 reject됨) # 시장이 열렸을 때 주문 시작 (open 전에 주문하면 reject됨)
print("Market opened:", message) print("Market opened:", message)
market_open = True market_open = True
place_bond_orders() place_bond_orders()
elif message["type"] == "error": elif message["type"] == "error":
print(message) print(message)
elif message["type"] == "reject": elif message["type"] == "reject":
print(message) print(message)
# 거부된 주문은 active_orders에서 제거 # 거부된 주문은 active_orders에서 제거
oid = message.get("order_id") oid = message.get("order_id")
active_orders.pop(oid, None) active_orders.pop(oid, None)
xlf_pending.discard(oid)
# XLF 주문 reject 시 IDLE로 복귀
if xlf_state != "IDLE" and oid in xlf_pending:
print(f" XLF 주문 reject → IDLE 복귀")
xlf_state = "IDLE"
xlf_pending.clear()
elif message["type"] == "ack":
# 변환 ack 처리 (convert는 fill이 아닌 ack로 완료됨)
if xlf_state == "CONVERTING":
print(" 변환 완료 → 매도 시작")
if xlf_direction == "BASKET_TO_XLF":
# XLF 매도
xlf_state = "SELLING_XLF"
oid = next_id()
exchange.send_add_message(
oid, "XLF", Dir.SELL, state.bid_prices["XLF"], 10
)
xlf_pending.add(oid)
elif xlf_direction == "XLF_TO_BASKET":
# 바스켓 각 종목 매도
xlf_state = "SELLING_BASKET"
for sym, qty in [("BOND", 3), ("GS", 2), ("MS", 3), ("WFC", 2)]:
oid = next_id()
exchange.send_add_message(
oid, sym, Dir.SELL, state.bid_prices[sym], qty
)
xlf_pending.add(oid)
elif message["type"] == "fill": elif message["type"] == "fill":
print(message) print(message)
# 체결 시 포지션 업데이트 후 주문 재보충 qty = message["size"]
qty = message["size"] sym = message["symbol"]
if message["dir"] == Dir.BUY: dir_ = message["dir"]
position += qty
# 포지션 업데이트
if dir_ == Dir.BUY:
state.update_position(sym, qty)
else: else:
position -= qty state.update_position(sym, -qty)
place_bond_orders()
print(f" 포지션 → {state.positions}")
# BOND 체결 시 재주문
if sym == "BOND" and message["order_id"] in active_orders:
active_orders.pop(message["order_id"], None)
place_bond_orders()
# XLF state machine 체결 처리
handle_xlf_fill(message["order_id"], sym, dir_, qty)
# SELLING 단계에서 pending 소진 시 IDLE 복귀
if xlf_state in ("SELLING_XLF", "SELLING_BASKET"):
xlf_pending.discard(message["order_id"])
if not xlf_pending:
print(" XLF 차익거래 완료 → IDLE 복귀")
xlf_state = "IDLE"
xlf_direction = None
elif message["type"] == "book": elif message["type"] == "book":
if message["symbol"] == "VALE": sym = message["symbol"]
state.update_bid_ask_price(
def best_price(side): sym,
if message[side]: message["buy"][0][0] if message["buy"] else None,
return message[side][0][0] message["sell"][0][0] if message["sell"] else None
)
vale_bid_price = best_price("buy")
vale_ask_price = best_price("sell")
if sym == "VALE":
now = time.time() now = time.time()
if now > vale_last_print_time + 1: if now > vale_last_print_time + 1:
vale_last_print_time = now vale_last_print_time = now
print( print({
{ "vale_bid_price": state.bid_prices["VALE"],
"vale_bid_price": vale_bid_price, "vale_ask_price": state.ask_prices["VALE"],
"vale_ask_price": vale_ask_price, })
}
) # XLF 관련 심볼 호가 업데이트마다 차익거래 시도
if sym in ["BOND", "GS", "MS", "WFC", "XLF"]:
try_xlf_arb()
# 주기적으로 BOND 주문 갱신 (주문 만료 방지) # 주기적으로 BOND 주문 갱신 (주문 만료 방지)
now = time.time() now = time.time()