commit
This commit is contained in:
233
bot bond sell.py
233
bot bond sell.py
@@ -10,6 +10,8 @@ from enum import Enum
|
||||
import time
|
||||
import socket
|
||||
import json
|
||||
from state import StateManager
|
||||
from order import OrderManager
|
||||
|
||||
# ~~~~~============== CONFIGURATION ==============~~~~~
|
||||
# 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
|
||||
# unlikely it will be traded against. Maybe there is a better price to
|
||||
# pick? Also, you will need to send more orders over time.
|
||||
# --- BOND 마켓 메이킹 설정 ---
|
||||
FAIR_VALUE = 1000 # BOND fair value (고정)
|
||||
ORDER_SIZE = 5 # 가격대별 주문 수량
|
||||
MAX_POSITION = 100 # 최대 포지션 한도
|
||||
# --- 설정 ---
|
||||
BOND_FAIR_VALUE = 1000 # BOND fair value (고정)
|
||||
BOND_ORDER_SIZE = 30 # BOND 주문당 수량
|
||||
BOND_MAX_POSITION = 100 # BOND 최대 포지션 한도
|
||||
XLF_CONVERSION_FEE = 100 # XLF 변환 비용 (설명서: 100)
|
||||
XLF_MAX_POSITION = 100 # XLF 포지션 한도
|
||||
REFRESH_INTERVAL = 5.0 # 주문 갱신 주기 (초)
|
||||
|
||||
# 매수: 999, 998, 997 / 매도: 1001, 1002, 1003
|
||||
BUY_PRICES = [FAIR_VALUE - 1, FAIR_VALUE - 2, FAIR_VALUE - 3]
|
||||
SELL_PRICES = [FAIR_VALUE + 1, FAIR_VALUE + 2, FAIR_VALUE + 3]
|
||||
# XLF state machine
|
||||
# IDLE → BUYING_BASKET → CONVERTING → SELLING_XLF → IDLE (바스켓→XLF)
|
||||
# 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 포지션
|
||||
order_id = 0 # 단조 증가하는 주문 ID
|
||||
active_orders = {} # {order_id: {"dir": ..., "price": ...}}
|
||||
market_open = False # 시장 open 여부 (open 전에는 주문 불가)
|
||||
state = StateManager()
|
||||
om = OrderManager()
|
||||
market_open = False
|
||||
active_orders = {} # BOND 전용 {order_id: {"dir": ..., "price": ...}}
|
||||
|
||||
last_refresh = time.time()
|
||||
vale_last_print = time.time()
|
||||
|
||||
def next_id():
|
||||
nonlocal order_id
|
||||
order_id += 1
|
||||
return order_id
|
||||
return om.next_order()
|
||||
|
||||
def cancel_all_bond_orders():
|
||||
"""활성 BOND 주문 전부 취소"""
|
||||
@@ -69,29 +77,33 @@ def main():
|
||||
active_orders.pop(oid, None)
|
||||
|
||||
def place_bond_orders():
|
||||
"""여러 가격대에 분산해서 매수/매도 주문"""
|
||||
"""포지션 한도 안에서 bid/ask 양방향 주문"""
|
||||
if not market_open:
|
||||
return
|
||||
|
||||
cancel_all_bond_orders()
|
||||
|
||||
# 포지션에 따라 size 조정
|
||||
base_size = ORDER_SIZE
|
||||
buy_price = BOND_FAIR_VALUE - 1 # 999
|
||||
sell_price = BOND_FAIR_VALUE + 1 # 1001
|
||||
position = state.get_position("BOND")
|
||||
|
||||
# 포지션에 따라 size 비대칭 조정
|
||||
base_size = BOND_ORDER_SIZE
|
||||
adjustment = abs(position) // 5
|
||||
|
||||
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)
|
||||
elif position > 0:
|
||||
# 롱 포지션 → 매도를 더 많이
|
||||
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:
|
||||
buy_size = base_size
|
||||
sell_size = base_size
|
||||
|
||||
# 999, 998, 997 세 가격대에 매수 주문
|
||||
for buy_price in BUY_PRICES:
|
||||
if position < MAX_POSITION:
|
||||
if buy_size > 0:
|
||||
bid = next_id()
|
||||
exchange.send_add_message(
|
||||
order_id=bid, symbol="BOND",
|
||||
@@ -99,9 +111,7 @@ def main():
|
||||
)
|
||||
active_orders[bid] = {"dir": Dir.BUY, "price": buy_price}
|
||||
|
||||
# 1001, 1002, 1003 세 가격대에 매도 주문
|
||||
for sell_price in SELL_PRICES:
|
||||
if position > -MAX_POSITION:
|
||||
if sell_size > 0:
|
||||
ask = next_id()
|
||||
exchange.send_add_message(
|
||||
order_id=ask, symbol="BOND",
|
||||
@@ -109,23 +119,95 @@ def main():
|
||||
)
|
||||
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
|
||||
# now this doesn't track much information, but it's enough to get a sense
|
||||
# of the VALE market.
|
||||
vale_bid_price, vale_ask_price = None, None
|
||||
vale_last_print_time = time.time()
|
||||
|
||||
last_refresh = time.time()
|
||||
|
||||
# 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
|
||||
# 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.
|
||||
#
|
||||
# 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
|
||||
# message. Sending a message in response to every exchange message will
|
||||
@@ -143,47 +225,100 @@ def main():
|
||||
if message["type"] == "close":
|
||||
print("The round has ended")
|
||||
break
|
||||
|
||||
elif message["type"] == "open":
|
||||
# 시장이 열렸을 때 주문 시작 (open 전에 주문하면 reject됨)
|
||||
print("Market opened:", message)
|
||||
market_open = True
|
||||
place_bond_orders()
|
||||
|
||||
elif message["type"] == "error":
|
||||
print(message)
|
||||
|
||||
elif message["type"] == "reject":
|
||||
print(message)
|
||||
# 거부된 주문은 active_orders에서 제거
|
||||
oid = message.get("order_id")
|
||||
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":
|
||||
print(message)
|
||||
# 체결 시 포지션 업데이트 후 주문 재보충
|
||||
qty = message["size"]
|
||||
if message["dir"] == Dir.BUY:
|
||||
position += qty
|
||||
sym = message["symbol"]
|
||||
dir_ = message["dir"]
|
||||
|
||||
# 포지션 업데이트
|
||||
if dir_ == Dir.BUY:
|
||||
state.update_position(sym, qty)
|
||||
else:
|
||||
position -= qty
|
||||
state.update_position(sym, -qty)
|
||||
|
||||
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":
|
||||
if message["symbol"] == "VALE":
|
||||
|
||||
def best_price(side):
|
||||
if message[side]:
|
||||
return message[side][0][0]
|
||||
|
||||
vale_bid_price = best_price("buy")
|
||||
vale_ask_price = best_price("sell")
|
||||
sym = message["symbol"]
|
||||
state.update_bid_ask_price(
|
||||
sym,
|
||||
message["buy"][0][0] if message["buy"] else None,
|
||||
message["sell"][0][0] if message["sell"] else None
|
||||
)
|
||||
|
||||
if sym == "VALE":
|
||||
now = time.time()
|
||||
|
||||
if now > vale_last_print_time + 1:
|
||||
vale_last_print_time = now
|
||||
print(
|
||||
{
|
||||
"vale_bid_price": vale_bid_price,
|
||||
"vale_ask_price": vale_ask_price,
|
||||
}
|
||||
)
|
||||
print({
|
||||
"vale_bid_price": state.bid_prices["VALE"],
|
||||
"vale_ask_price": state.ask_prices["VALE"],
|
||||
})
|
||||
|
||||
# XLF 관련 심볼 호가 업데이트마다 차익거래 시도
|
||||
if sym in ["BOND", "GS", "MS", "WFC", "XLF"]:
|
||||
try_xlf_arb()
|
||||
|
||||
# 주기적으로 BOND 주문 갱신 (주문 만료 방지)
|
||||
now = time.time()
|
||||
|
||||
Reference in New Issue
Block a user