commit
This commit is contained in:
654
bot bond sell.py
654
bot bond sell.py
@@ -14,267 +14,127 @@ from state import StateManager
|
|||||||
from order import OrderManager
|
from order import OrderManager
|
||||||
|
|
||||||
# ~~~~~============== CONFIGURATION ==============~~~~~
|
# ~~~~~============== CONFIGURATION ==============~~~~~
|
||||||
|
# Replace "REPLACEME" with your team name!
|
||||||
team_name = "HanyangFloorFunction"
|
team_name = "HanyangFloorFunction"
|
||||||
|
|
||||||
# ~~~~~============== MAIN LOOP ==============~~~~~
|
# ~~~~~============== MAIN LOOP ==============~~~~~
|
||||||
|
|
||||||
|
# You should put your code here! We provide some starter code as an example,
|
||||||
|
# but feel free to change/remove/edit/update any of it as you'd like. If you
|
||||||
|
# have any questions about the starter code, or what to do next, please ask us!
|
||||||
|
#
|
||||||
|
# To help you get started, the sample code below tries to buy BOND for a low
|
||||||
|
# price, and it prints the current prices for VALE every second. The sample
|
||||||
|
# code is intended to be a working example, but it needs some improvement
|
||||||
|
# before it will start making good trades!
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
args = parse_arguments()
|
args = parse_arguments()
|
||||||
|
|
||||||
exchange = ExchangeConnection(args=args)
|
exchange = ExchangeConnection(args=args)
|
||||||
|
|
||||||
|
# Store and print the "hello" message received from the exchange. This
|
||||||
|
# contains useful information about your positions. Normally you start with
|
||||||
|
# all positions at zero, but if you reconnect during a round, you might
|
||||||
|
# have already bought/sold symbols and have non-zero positions.
|
||||||
hello_message = exchange.read_message()
|
hello_message = exchange.read_message()
|
||||||
print("First message from exchange:", hello_message)
|
print("First message from exchange:", hello_message)
|
||||||
|
|
||||||
# ★ 재연결 시 기존 포지션 복원
|
# Send an order for BOND at a good price, but it is low enough that it is
|
||||||
state_init = StateManager()
|
# unlikely it will be traded against. Maybe there is a better price to
|
||||||
for sym_info in hello_message.get("symbols", []):
|
# pick? Also, you will need to send more orders over time.
|
||||||
sym = sym_info["symbol"]
|
# --- 설정 ---
|
||||||
posn = sym_info["position"]
|
BOND_FAIR_VALUE = 1000 # BOND fair value (고정)
|
||||||
if posn != 0:
|
BOND_ORDER_SIZE = 30 # BOND 주문당 수량
|
||||||
state_init.update_position(sym, posn)
|
XLF_CONVERSION_FEE = 100 # XLF 변환 비용
|
||||||
print(f" [재연결] 기존 포지션 복원: {sym} = {posn}")
|
VALE_CONVERSION_FEE = 10 # VALE 변환 비용
|
||||||
|
REFRESH_INTERVAL = 5.0 # 주문 갱신 주기 (초)
|
||||||
# ==================== 설정 ====================
|
|
||||||
BOND_FAIR_VALUE = 1000
|
|
||||||
BOND_SPREAD = 2 # BOND 마켓메이킹 스프레드 ±2
|
|
||||||
BOND_ORDER_SIZE = 30
|
|
||||||
BOND_MAX_POSITION = 100
|
|
||||||
|
|
||||||
# GS/MS/WFC 마켓메이킹 설정
|
|
||||||
STOCK_SPREAD = 3 # 개별주 스프레드 ±3 (변동성이 BOND보다 크므로)
|
|
||||||
STOCK_ORDER_SIZE = 10 # 개별주 주문 수량 (보수적으로 시작)
|
|
||||||
STOCK_MAX_POSITION = 100
|
|
||||||
STOCK_REORDER_DELAY = 0.3 # 개별주 재주문 throttle (초)
|
|
||||||
|
|
||||||
XLF_CONVERSION_FEE = 100
|
|
||||||
XLF_MAX_POSITION = 100
|
|
||||||
VALE_CONVERSION_FEE = 10
|
|
||||||
VALE_MAX_POSITION = 10
|
|
||||||
|
|
||||||
REFRESH_INTERVAL = 5.0 # 전체 주문 갱신 주기
|
|
||||||
|
|
||||||
# ==================== 상태 변수 ====================
|
|
||||||
|
|
||||||
# XLF state machine
|
# XLF state machine
|
||||||
xlf_state = "IDLE"
|
xlf_state = "IDLE"
|
||||||
xlf_pending = {} # order_id -> remaining qty
|
xlf_pending = {}
|
||||||
xlf_direction = None
|
xlf_direction = None
|
||||||
xlf_convert_oid = None
|
|
||||||
|
|
||||||
# VALE state machine
|
# VALE state machine
|
||||||
vale_state = "IDLE"
|
vale_state = "IDLE"
|
||||||
vale_pending = {}
|
vale_pending = {}
|
||||||
vale_direction = None
|
vale_direction = None
|
||||||
vale_convert_oid = None
|
|
||||||
|
|
||||||
state = state_init
|
state = StateManager()
|
||||||
om = OrderManager()
|
om = OrderManager(exchange)
|
||||||
market_open = False
|
market_open = False
|
||||||
|
active_orders = {} # BOND 전용 {order_id: {"dir": ..., "price": ...}}
|
||||||
# 마켓메이킹 주문 추적: order_id -> {"sym": ..., "dir": ..., "price": ...}
|
|
||||||
active_mm_orders = {}
|
|
||||||
|
|
||||||
last_refresh = time.time()
|
last_refresh = time.time()
|
||||||
last_mm_fill_time = {} # sym -> 마지막 체결 시각 (throttle용)
|
vale_last_print = time.time()
|
||||||
BOND_REORDER_DELAY = 0.2
|
|
||||||
|
|
||||||
# 개별주 implied fair value (book 업데이트마다 갱신)
|
|
||||||
implied_fairs = {"GS": None, "MS": None, "WFC": None}
|
|
||||||
|
|
||||||
def next_id():
|
def next_id():
|
||||||
return om.next_order()
|
return om.next_order()
|
||||||
|
|
||||||
# ==================== fair value 추정 ====================
|
def cancel_all_bond_orders():
|
||||||
|
"""활성 BOND 주문 전부 취소"""
|
||||||
def update_implied_fairs():
|
for oid in list(active_orders.keys()):
|
||||||
"""
|
om.cancel(oid)
|
||||||
XLF 바스켓 구성으로 GS/MS/WFC implied fair value 추정.
|
active_orders.pop(oid, None)
|
||||||
XLF_mid * 10 = BOND*3 + GS*2 + MS*3 + WFC*2
|
|
||||||
BOND = 1000(고정) 이므로 잔여분을 현재 mid 비율로 배분.
|
|
||||||
"""
|
|
||||||
xlf_bid = state.bid_prices.get("XLF")
|
|
||||||
xlf_ask = state.ask_prices.get("XLF")
|
|
||||||
gs_bid = state.bid_prices.get("GS")
|
|
||||||
gs_ask = state.ask_prices.get("GS")
|
|
||||||
ms_bid = state.bid_prices.get("MS")
|
|
||||||
ms_ask = state.ask_prices.get("MS")
|
|
||||||
wfc_bid = state.bid_prices.get("WFC")
|
|
||||||
wfc_ask = state.ask_prices.get("WFC")
|
|
||||||
|
|
||||||
if None in [xlf_bid, xlf_ask, gs_bid, gs_ask, ms_bid, ms_ask, wfc_bid, wfc_ask]:
|
|
||||||
return
|
|
||||||
|
|
||||||
xlf_mid = (xlf_bid + xlf_ask) / 2
|
|
||||||
gs_mid = (gs_bid + gs_ask) / 2
|
|
||||||
ms_mid = (ms_bid + ms_ask) / 2
|
|
||||||
wfc_mid = (wfc_bid + wfc_ask) / 2
|
|
||||||
|
|
||||||
residual = xlf_mid * 10 - 3000 # BOND 기여분(3x1000) 제외
|
|
||||||
total = gs_mid*2 + ms_mid*3 + wfc_mid*2
|
|
||||||
|
|
||||||
if total <= 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
implied_fairs["GS"] = round(residual * (gs_mid * 2 / total) / 2)
|
|
||||||
implied_fairs["MS"] = round(residual * (ms_mid * 3 / total) / 3)
|
|
||||||
implied_fairs["WFC"] = round(residual * (wfc_mid * 2 / total) / 2)
|
|
||||||
|
|
||||||
# ==================== 잔여 포지션 청산 ====================
|
|
||||||
|
|
||||||
def cleanup_residual_positions():
|
|
||||||
"""재연결 시 잔여 포지션 청산"""
|
|
||||||
if not market_open:
|
|
||||||
return
|
|
||||||
|
|
||||||
xlf_pos = state.get_position("XLF")
|
|
||||||
if xlf_pos != 0:
|
|
||||||
lots = abs(xlf_pos) // 10
|
|
||||||
remainder = abs(xlf_pos) % 10
|
|
||||||
direction = Dir.SELL if xlf_pos > 0 else Dir.BUY
|
|
||||||
print(f" [청산] XLF 포지션={xlf_pos}, 변환 lots={lots}, 잔여={remainder}")
|
|
||||||
if lots > 0:
|
|
||||||
exchange.send_convert_message(next_id(), "XLF", direction, lots * 10)
|
|
||||||
if remainder > 0:
|
|
||||||
oid = next_id()
|
|
||||||
if xlf_pos > 0:
|
|
||||||
price = max((state.bid_prices.get("XLF") or 1) - 5, 1)
|
|
||||||
exchange.send_add_message_ioc(oid, "XLF", Dir.SELL, price, remainder)
|
|
||||||
else:
|
|
||||||
price = (state.ask_prices.get("XLF") or 99999) + 5
|
|
||||||
exchange.send_add_message_ioc(oid, "XLF", Dir.BUY, price, remainder)
|
|
||||||
|
|
||||||
for sym in ["GS", "MS", "WFC", "VALE", "VALBZ"]:
|
|
||||||
pos = state.get_position(sym)
|
|
||||||
if pos == 0:
|
|
||||||
continue
|
|
||||||
print(f" [청산] {sym} 포지션={pos}")
|
|
||||||
oid = next_id()
|
|
||||||
if pos > 0:
|
|
||||||
price = max((state.bid_prices.get(sym) or 1) - 5, 1)
|
|
||||||
exchange.send_add_message_ioc(oid, sym, Dir.SELL, price, abs(pos))
|
|
||||||
else:
|
|
||||||
price = (state.ask_prices.get(sym) or 99999) + 5
|
|
||||||
exchange.send_add_message_ioc(oid, sym, Dir.BUY, price, abs(pos))
|
|
||||||
|
|
||||||
# ==================== 마켓메이킹 주문 ====================
|
|
||||||
|
|
||||||
def cancel_mm_orders_for(sym):
|
|
||||||
to_cancel = [oid for oid, info in active_mm_orders.items() if info["sym"] == sym]
|
|
||||||
for oid in to_cancel:
|
|
||||||
exchange.send_cancel_message(oid)
|
|
||||||
active_mm_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_mm_orders_for("BOND")
|
|
||||||
|
|
||||||
position = state.get_position("BOND")
|
cancel_all_bond_orders()
|
||||||
|
|
||||||
|
buy_price = BOND_FAIR_VALUE - 1
|
||||||
|
sell_price = BOND_FAIR_VALUE + 1
|
||||||
|
position = om.positions["BOND"]
|
||||||
|
|
||||||
base_size = BOND_ORDER_SIZE
|
base_size = BOND_ORDER_SIZE
|
||||||
adj = abs(position) // 5
|
adjustment = abs(position) // 5
|
||||||
|
|
||||||
if position < 0:
|
if position < 0:
|
||||||
buy_size = min(base_size + adj, BOND_MAX_POSITION - position)
|
buy_size = min(base_size + adjustment, 100 - position)
|
||||||
sell_size = max(base_size - adj, 1)
|
sell_size = max(base_size - adjustment, 1)
|
||||||
elif position > 0:
|
elif position > 0:
|
||||||
buy_size = max(base_size - adj, 1)
|
buy_size = max(base_size - adjustment, 1)
|
||||||
sell_size = min(base_size + adj, BOND_MAX_POSITION + position)
|
sell_size = min(base_size + adjustment, 100 + position)
|
||||||
else:
|
else:
|
||||||
buy_size = base_size
|
buy_size = base_size
|
||||||
sell_size = base_size
|
sell_size = base_size
|
||||||
|
|
||||||
buy_size = min(buy_size, BOND_MAX_POSITION - max(position, 0))
|
bid = next_id()
|
||||||
sell_size = min(sell_size, BOND_MAX_POSITION + min(position, 0))
|
if exchange.send_add_message(
|
||||||
|
order_id=bid, symbol="BOND",
|
||||||
|
dir=Dir.BUY, price=buy_price, size=buy_size
|
||||||
|
) is not False:
|
||||||
|
active_orders[bid] = {"dir": Dir.BUY, "price": buy_price}
|
||||||
|
|
||||||
buy_price = BOND_FAIR_VALUE - BOND_SPREAD
|
ask = next_id()
|
||||||
sell_price = BOND_FAIR_VALUE + BOND_SPREAD
|
if exchange.send_add_message(
|
||||||
|
order_id=ask, symbol="BOND",
|
||||||
if buy_size > 0:
|
dir=Dir.SELL, price=sell_price, size=sell_size
|
||||||
oid = next_id()
|
) is not False:
|
||||||
exchange.send_add_message(oid, "BOND", Dir.BUY, buy_price, buy_size)
|
active_orders[ask] = {"dir": Dir.SELL, "price": sell_price}
|
||||||
active_mm_orders[oid] = {"sym": "BOND", "dir": Dir.BUY, "price": buy_price}
|
|
||||||
|
|
||||||
if sell_size > 0:
|
|
||||||
oid = next_id()
|
|
||||||
exchange.send_add_message(oid, "BOND", Dir.SELL, sell_price, sell_size)
|
|
||||||
active_mm_orders[oid] = {"sym": "BOND", "dir": Dir.SELL, "price": sell_price}
|
|
||||||
|
|
||||||
print(f" BOND 주문 → 매수:{buy_price} x{buy_size}, 매도:{sell_price} x{sell_size}, 포지션:{position}")
|
print(f" BOND 주문 → 매수:{buy_price} x{buy_size}, 매도:{sell_price} x{sell_size}, 포지션:{position}")
|
||||||
|
|
||||||
def place_stock_orders(sym):
|
|
||||||
"""
|
|
||||||
GS/MS/WFC 마켓메이킹.
|
|
||||||
implied fair value 주변 ±STOCK_SPREAD에서 양방향 DAY 주문.
|
|
||||||
"""
|
|
||||||
if not market_open:
|
|
||||||
return
|
|
||||||
|
|
||||||
fair = implied_fairs.get(sym)
|
|
||||||
if fair is None or fair <= 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
cancel_mm_orders_for(sym)
|
|
||||||
|
|
||||||
position = state.get_position(sym)
|
|
||||||
base_size = STOCK_ORDER_SIZE
|
|
||||||
adj = abs(position) // 10
|
|
||||||
|
|
||||||
if position < 0:
|
|
||||||
buy_size = min(base_size + adj, STOCK_MAX_POSITION - position)
|
|
||||||
sell_size = max(base_size - adj, 1)
|
|
||||||
elif position > 0:
|
|
||||||
buy_size = max(base_size - adj, 1)
|
|
||||||
sell_size = min(base_size + adj, STOCK_MAX_POSITION + position)
|
|
||||||
else:
|
|
||||||
buy_size = base_size
|
|
||||||
sell_size = base_size
|
|
||||||
|
|
||||||
buy_size = min(buy_size, STOCK_MAX_POSITION - max(position, 0))
|
|
||||||
sell_size = min(sell_size, STOCK_MAX_POSITION + min(position, 0))
|
|
||||||
|
|
||||||
buy_price = int(fair) - STOCK_SPREAD
|
|
||||||
sell_price = int(fair) + STOCK_SPREAD
|
|
||||||
|
|
||||||
if buy_price <= 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
if buy_size > 0:
|
|
||||||
oid = next_id()
|
|
||||||
exchange.send_add_message(oid, sym, Dir.BUY, buy_price, buy_size)
|
|
||||||
active_mm_orders[oid] = {"sym": sym, "dir": Dir.BUY, "price": buy_price}
|
|
||||||
|
|
||||||
if sell_size > 0:
|
|
||||||
oid = next_id()
|
|
||||||
exchange.send_add_message(oid, sym, Dir.SELL, sell_price, sell_size)
|
|
||||||
active_mm_orders[oid] = {"sym": sym, "dir": Dir.SELL, "price": sell_price}
|
|
||||||
|
|
||||||
print(f" {sym} 주문 → fair:{fair}, 매수:{buy_price}x{buy_size}, 매도:{sell_price}x{sell_size}, 포지션:{position}")
|
|
||||||
|
|
||||||
def refresh_all_mm():
|
|
||||||
"""모든 마켓메이킹 주문 갱신"""
|
|
||||||
place_bond_orders()
|
|
||||||
update_implied_fairs()
|
|
||||||
for sym in ["GS", "MS", "WFC"]:
|
|
||||||
place_stock_orders(sym)
|
|
||||||
|
|
||||||
# ==================== XLF 차익거래 ====================
|
|
||||||
|
|
||||||
def try_xlf_arb():
|
def try_xlf_arb():
|
||||||
nonlocal xlf_state, xlf_direction, xlf_pending, xlf_convert_oid
|
"""XLF 차익거래 시도 - IDLE 상태일 때만"""
|
||||||
|
nonlocal xlf_state, xlf_direction, xlf_pending
|
||||||
|
|
||||||
if not market_open or xlf_state != "IDLE":
|
if not market_open or xlf_state != "IDLE":
|
||||||
return
|
return
|
||||||
|
|
||||||
bond_ask = state.ask_prices.get("BOND")
|
bond_ask = state.ask_prices["BOND"]
|
||||||
gs_ask = state.ask_prices.get("GS")
|
gs_ask = state.ask_prices["GS"]
|
||||||
ms_ask = state.ask_prices.get("MS")
|
ms_ask = state.ask_prices["MS"]
|
||||||
wfc_ask = state.ask_prices.get("WFC")
|
wfc_ask = state.ask_prices["WFC"]
|
||||||
xlf_bid = state.bid_prices.get("XLF")
|
xlf_bid = state.bid_prices["XLF"]
|
||||||
bond_bid = state.bid_prices.get("BOND")
|
bond_bid = state.bid_prices["BOND"]
|
||||||
gs_bid = state.bid_prices.get("GS")
|
gs_bid = state.bid_prices["GS"]
|
||||||
ms_bid = state.bid_prices.get("MS")
|
ms_bid = state.bid_prices["MS"]
|
||||||
wfc_bid = state.bid_prices.get("WFC")
|
wfc_bid = state.bid_prices["WFC"]
|
||||||
xlf_ask = state.ask_prices.get("XLF")
|
xlf_ask = state.ask_prices["XLF"]
|
||||||
|
|
||||||
if None in [bond_ask, gs_ask, ms_ask, wfc_ask, xlf_bid,
|
if None in [bond_ask, gs_ask, ms_ask, wfc_ask, xlf_bid,
|
||||||
bond_bid, gs_bid, ms_bid, wfc_bid, xlf_ask]:
|
bond_bid, gs_bid, ms_bid, wfc_bid, xlf_ask]:
|
||||||
@@ -282,283 +142,236 @@ def main():
|
|||||||
|
|
||||||
basket_ask = bond_ask*3 + gs_ask*2 + ms_ask*3 + wfc_ask*2
|
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
|
basket_bid = bond_bid*3 + gs_bid*2 + ms_bid*3 + wfc_bid*2
|
||||||
pos_xlf = state.get_position("XLF")
|
|
||||||
|
|
||||||
# 케이스 1: 바스켓 매수 → XLF 변환 → XLF 매도
|
# 케이스 1: 바스켓 매수 → XLF 변환 → XLF 매도
|
||||||
profit1 = xlf_bid * 10 - basket_ask - XLF_CONVERSION_FEE
|
profit1 = xlf_bid * 10 - basket_ask - XLF_CONVERSION_FEE
|
||||||
if profit1 > 0 and pos_xlf < XLF_MAX_POSITION:
|
if profit1 > 0 and om.check_pos_limit("XLF"):
|
||||||
print(f" XLF 차익(바스켓->XLF) 시작, 예상수익:{profit1}")
|
print(f" XLF 차익(바스켓→XLF) 시작, 예상수익:{profit1}")
|
||||||
xlf_state = "BUYING_BASKET"
|
xlf_state = "BUYING_BASKET"
|
||||||
xlf_direction = "BASKET_TO_XLF"
|
xlf_direction = "BASKET_TO_XLF"
|
||||||
xlf_pending.clear()
|
xlf_pending.clear()
|
||||||
for sym, qty in [("BOND", 3), ("GS", 2), ("MS", 3), ("WFC", 2)]:
|
for sym, qty in [("BOND", 3), ("GS", 2), ("MS", 3), ("WFC", 2)]:
|
||||||
oid = next_id()
|
oid = next_id()
|
||||||
exchange.send_add_message_ioc(oid, sym, Dir.BUY, state.ask_prices[sym], qty)
|
exchange.send_add_message(oid, sym, Dir.BUY, state.ask_prices[sym], qty)
|
||||||
xlf_pending[oid] = qty
|
xlf_pending[oid] = qty
|
||||||
return
|
return
|
||||||
|
|
||||||
# 케이스 2: XLF 매수 → 바스켓 변환 → 각 종목 매도
|
# 케이스 2: XLF 매수 → 바스켓 변환 → 각 종목 매도
|
||||||
profit2 = basket_bid - xlf_ask * 10 - XLF_CONVERSION_FEE
|
profit2 = basket_bid - xlf_ask * 10 - XLF_CONVERSION_FEE
|
||||||
if profit2 > 0 and pos_xlf > -XLF_MAX_POSITION:
|
if profit2 > 0 and om.check_pos_limit("XLF"):
|
||||||
print(f" XLF 차익(XLF->바스켓) 시작, 예상수익:{profit2}")
|
print(f" XLF 차익(XLF→바스켓) 시작, 예상수익:{profit2}")
|
||||||
xlf_state = "BUYING_XLF"
|
xlf_state = "BUYING_XLF"
|
||||||
xlf_direction = "XLF_TO_BASKET"
|
xlf_direction = "XLF_TO_BASKET"
|
||||||
xlf_pending.clear()
|
xlf_pending.clear()
|
||||||
oid = next_id()
|
oid = next_id()
|
||||||
exchange.send_add_message_ioc(oid, "XLF", Dir.BUY, xlf_ask, 10)
|
exchange.send_add_message(oid, "XLF", Dir.BUY, xlf_ask, 10)
|
||||||
xlf_pending[oid] = 10
|
xlf_pending[oid] = 10
|
||||||
|
|
||||||
def handle_xlf_fill(order_id, symbol, dir_, qty):
|
def handle_xlf_fill(order_id, symbol, dir_, qty):
|
||||||
nonlocal xlf_state, xlf_pending, xlf_convert_oid
|
"""XLF state machine 체결 처리"""
|
||||||
|
nonlocal xlf_state, xlf_pending
|
||||||
|
|
||||||
if order_id not in xlf_pending:
|
if order_id not in xlf_pending:
|
||||||
return
|
return
|
||||||
xlf_pending[order_id] = max(0, xlf_pending[order_id] - qty)
|
|
||||||
if xlf_pending[order_id] == 0:
|
xlf_pending[order_id] -= qty
|
||||||
|
if xlf_pending[order_id] <= 0:
|
||||||
del xlf_pending[order_id]
|
del xlf_pending[order_id]
|
||||||
|
|
||||||
if xlf_state == "BUYING_BASKET" and not xlf_pending:
|
if xlf_state == "BUYING_BASKET" and not xlf_pending:
|
||||||
print(" 바스켓 매수 완료 -> XLF 변환 시작")
|
print(" 바스켓 매수 완료 → XLF 변환 시작")
|
||||||
xlf_state = "CONVERTING"
|
xlf_state = "CONVERTING"
|
||||||
xlf_convert_oid = next_id()
|
exchange.send_convert_message(next_id(), "XLF", Dir.BUY, 10)
|
||||||
exchange.send_convert_message(xlf_convert_oid, "XLF", Dir.BUY, 10)
|
|
||||||
|
|
||||||
elif xlf_state == "BUYING_XLF" and not xlf_pending:
|
elif xlf_state == "BUYING_XLF" and not xlf_pending:
|
||||||
print(" XLF 매수 완료 -> 바스켓 변환 시작")
|
print(" XLF 매수 완료 → 바스켓 변환 시작")
|
||||||
xlf_state = "CONVERTING"
|
xlf_state = "CONVERTING"
|
||||||
xlf_convert_oid = next_id()
|
exchange.send_convert_message(next_id(), "XLF", Dir.SELL, 10)
|
||||||
exchange.send_convert_message(xlf_convert_oid, "XLF", Dir.SELL, 10)
|
|
||||||
|
|
||||||
def handle_xlf_out(order_id):
|
|
||||||
nonlocal xlf_state, xlf_pending, xlf_direction
|
|
||||||
|
|
||||||
if order_id not in xlf_pending:
|
|
||||||
return
|
|
||||||
remaining = xlf_pending.pop(order_id, 0)
|
|
||||||
if not xlf_pending and xlf_state in ("BUYING_BASKET", "BUYING_XLF"):
|
|
||||||
print(f" XLF 주문 out (미체결/부분체결) -> IDLE 복귀. 남은:{remaining}")
|
|
||||||
xlf_state = "IDLE"
|
|
||||||
xlf_direction = None
|
|
||||||
|
|
||||||
# ==================== VALE 차익거래 ====================
|
|
||||||
|
|
||||||
def try_vale_arb():
|
def try_vale_arb():
|
||||||
nonlocal vale_state, vale_direction, vale_pending, vale_convert_oid
|
"""VALE/VALBZ 차익거래 시도 - IDLE 상태일 때만"""
|
||||||
|
nonlocal vale_state, vale_direction, vale_pending
|
||||||
|
|
||||||
if not market_open or vale_state != "IDLE":
|
if not market_open or vale_state != "IDLE":
|
||||||
return
|
return
|
||||||
|
|
||||||
vale_bid = state.bid_prices.get("VALE")
|
vale_bid = state.bid_prices["VALE"]
|
||||||
vale_ask = state.ask_prices.get("VALE")
|
vale_ask = state.ask_prices["VALE"]
|
||||||
valbz_bid = state.bid_prices.get("VALBZ")
|
valbz_bid = state.bid_prices["VALBZ"]
|
||||||
valbz_ask = state.ask_prices.get("VALBZ")
|
valbz_ask = state.ask_prices["VALBZ"]
|
||||||
|
|
||||||
if None in [vale_bid, vale_ask, valbz_bid, valbz_ask]:
|
if None in [vale_bid, vale_ask, valbz_bid, valbz_ask]:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# 케이스 1: VALE가 비쌀 때 → VALBZ 매수 → VALE 변환 → VALE 매도
|
||||||
profit1 = vale_bid - valbz_ask - VALE_CONVERSION_FEE
|
profit1 = vale_bid - valbz_ask - VALE_CONVERSION_FEE
|
||||||
if profit1 > 0 and state.get_position("VALBZ") < VALE_MAX_POSITION:
|
if profit1 > 0 and om.check_pos_limit("VALBZ"):
|
||||||
print(f" VALE 차익(VALBZ->VALE) 시작, 예상수익:{profit1}")
|
print(f" VALE 차익(VALBZ→VALE) 시작, 예상수익:{profit1}")
|
||||||
vale_state = "BUYING_VALBZ"
|
vale_state = "BUYING_VALBZ"
|
||||||
vale_direction = "VALBZ_TO_VALE"
|
vale_direction = "VALBZ_TO_VALE"
|
||||||
vale_pending.clear()
|
vale_pending.clear()
|
||||||
oid = next_id()
|
oid = next_id()
|
||||||
exchange.send_add_message_ioc(oid, "VALBZ", Dir.BUY, valbz_ask, 1)
|
exchange.send_add_message(oid, "VALBZ", Dir.BUY, valbz_ask, 1)
|
||||||
vale_pending[oid] = 1
|
vale_pending[oid] = 1
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# 케이스 2: VALBZ가 비쌀 때 → VALE 매수 → VALBZ 변환 → VALBZ 매도
|
||||||
profit2 = valbz_bid - vale_ask - VALE_CONVERSION_FEE
|
profit2 = valbz_bid - vale_ask - VALE_CONVERSION_FEE
|
||||||
if profit2 > 0 and state.get_position("VALE") < VALE_MAX_POSITION:
|
if profit2 > 0 and om.check_pos_limit("VALE"):
|
||||||
print(f" VALE 차익(VALE->VALBZ) 시작, 예상수익:{profit2}")
|
print(f" VALE 차익(VALE→VALBZ) 시작, 예상수익:{profit2}")
|
||||||
vale_state = "BUYING_VALE"
|
vale_state = "BUYING_VALE"
|
||||||
vale_direction = "VALE_TO_VALBZ"
|
vale_direction = "VALE_TO_VALBZ"
|
||||||
vale_pending.clear()
|
vale_pending.clear()
|
||||||
oid = next_id()
|
oid = next_id()
|
||||||
exchange.send_add_message_ioc(oid, "VALE", Dir.BUY, vale_ask, 1)
|
exchange.send_add_message(oid, "VALE", Dir.BUY, vale_ask, 1)
|
||||||
vale_pending[oid] = 1
|
vale_pending[oid] = 1
|
||||||
|
|
||||||
def handle_vale_fill(order_id, symbol, dir_, qty):
|
def handle_vale_fill(order_id, symbol, dir_, qty):
|
||||||
nonlocal vale_state, vale_pending, vale_convert_oid
|
"""VALE state machine 체결 처리"""
|
||||||
|
nonlocal vale_state, vale_pending
|
||||||
|
|
||||||
if order_id not in vale_pending:
|
if order_id not in vale_pending:
|
||||||
return
|
return
|
||||||
vale_pending[order_id] = max(0, vale_pending[order_id] - qty)
|
|
||||||
if vale_pending[order_id] == 0:
|
vale_pending[order_id] -= qty
|
||||||
|
if vale_pending[order_id] <= 0:
|
||||||
del vale_pending[order_id]
|
del vale_pending[order_id]
|
||||||
|
|
||||||
if vale_state == "BUYING_VALBZ" and not vale_pending:
|
if vale_state == "BUYING_VALBZ" and not vale_pending:
|
||||||
print(" VALBZ 매수 완료 -> VALE 변환 시작")
|
print(" VALBZ 매수 완료 → VALE 변환 시작")
|
||||||
vale_state = "CONVERTING"
|
vale_state = "CONVERTING"
|
||||||
vale_convert_oid = next_id()
|
exchange.send_convert_message(next_id(), "VALE", Dir.BUY, 1)
|
||||||
exchange.send_convert_message(vale_convert_oid, "VALE", Dir.BUY, 1)
|
|
||||||
|
|
||||||
elif vale_state == "BUYING_VALE" and not vale_pending:
|
elif vale_state == "BUYING_VALE" and not vale_pending:
|
||||||
print(" VALE 매수 완료 -> VALBZ 변환 시작")
|
print(" VALE 매수 완료 → VALBZ 변환 시작")
|
||||||
vale_state = "CONVERTING"
|
vale_state = "CONVERTING"
|
||||||
vale_convert_oid = next_id()
|
exchange.send_convert_message(next_id(), "VALE", Dir.SELL, 1)
|
||||||
exchange.send_convert_message(vale_convert_oid, "VALE", Dir.SELL, 1)
|
|
||||||
|
|
||||||
def handle_vale_out(order_id):
|
|
||||||
nonlocal vale_state, vale_pending, vale_direction
|
|
||||||
|
|
||||||
if order_id not in vale_pending:
|
|
||||||
return
|
|
||||||
remaining = vale_pending.pop(order_id, 0)
|
|
||||||
if not vale_pending and vale_state in ("BUYING_VALBZ", "BUYING_VALE"):
|
|
||||||
print(f" VALE 주문 out (미체결) -> IDLE 복귀. 남은:{remaining}")
|
|
||||||
vale_state = "IDLE"
|
|
||||||
vale_direction = None
|
|
||||||
|
|
||||||
# ==================== 메인 루프 ====================
|
|
||||||
|
|
||||||
|
# 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_last_print_time = time.time()
|
vale_last_print_time = 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_message() response.
|
||||||
|
#
|
||||||
|
# Every message sent to the exchange generates at least one response
|
||||||
|
# message. Sending a message in response to every exchange message will
|
||||||
|
# cause a feedback loop where your bot's messages will quickly be
|
||||||
|
# rate-limited and ignored. Please, don't do that!
|
||||||
while True:
|
while True:
|
||||||
message = exchange.read_message()
|
message = exchange.read_message()
|
||||||
|
|
||||||
|
# Some of the message types below happen infrequently and contain
|
||||||
|
# important information to help you understand what your bot is doing,
|
||||||
|
# so they are printed in full. We recommend not always printing every
|
||||||
|
# message because it can be a lot of information to read. Instead, let
|
||||||
|
# your code handle the messages and just print the information
|
||||||
|
# important for you!
|
||||||
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됨)
|
||||||
print("Market opened:", message)
|
print("Market opened:", message)
|
||||||
market_open = True
|
market_open = True
|
||||||
cleanup_residual_positions()
|
place_bond_orders()
|
||||||
refresh_all_mm()
|
|
||||||
|
|
||||||
elif message["type"] == "error":
|
elif message["type"] == "error":
|
||||||
print("ERROR:", message)
|
print(message)
|
||||||
|
|
||||||
elif message["type"] == "reject":
|
elif message["type"] == "reject":
|
||||||
print("REJECT:", message)
|
print(message)
|
||||||
oid = message.get("order_id")
|
oid = message.get("order_id")
|
||||||
active_mm_orders.pop(oid, None)
|
active_orders.pop(oid, None)
|
||||||
|
|
||||||
if oid in xlf_pending:
|
if oid in xlf_pending:
|
||||||
print(" XLF 주문 reject -> IDLE 복귀")
|
print(" XLF 주문 reject → IDLE 복귀")
|
||||||
xlf_state = "IDLE"
|
xlf_state = "IDLE"
|
||||||
xlf_pending.clear()
|
xlf_pending.clear()
|
||||||
xlf_direction = None
|
xlf_direction = None
|
||||||
xlf_convert_oid = None
|
|
||||||
|
|
||||||
if oid in vale_pending:
|
if oid in vale_pending:
|
||||||
print(" VALE 주문 reject -> IDLE 복귀")
|
print(" VALE 주문 reject → IDLE 복귀")
|
||||||
vale_state = "IDLE"
|
vale_state = "IDLE"
|
||||||
vale_pending.clear()
|
vale_pending.clear()
|
||||||
vale_direction = None
|
vale_direction = None
|
||||||
vale_convert_oid = None
|
|
||||||
|
|
||||||
elif message["type"] == "ack":
|
elif message["type"] == "ack":
|
||||||
oid = message.get("order_id")
|
# XLF 변환 ack 처리
|
||||||
|
if xlf_state == "CONVERTING":
|
||||||
if xlf_state == "CONVERTING" and oid == xlf_convert_oid:
|
print(" XLF 변환 완료 → 매도 시작")
|
||||||
print(" XLF 변환 완료 -> 매도 시작")
|
|
||||||
if xlf_direction == "BASKET_TO_XLF":
|
if xlf_direction == "BASKET_TO_XLF":
|
||||||
xlf_state = "SELLING_XLF"
|
xlf_state = "SELLING_XLF"
|
||||||
bid_now = state.bid_prices.get("XLF")
|
oid = next_id()
|
||||||
if bid_now:
|
exchange.send_add_message(
|
||||||
sell_oid = next_id()
|
oid, "XLF", Dir.SELL, state.bid_prices["XLF"], 10
|
||||||
exchange.send_add_message_ioc(sell_oid, "XLF", Dir.SELL, bid_now, 10)
|
)
|
||||||
xlf_pending[sell_oid] = 10
|
xlf_pending[oid] = 10
|
||||||
else:
|
|
||||||
xlf_state = "IDLE"
|
|
||||||
xlf_direction = None
|
|
||||||
|
|
||||||
elif xlf_direction == "XLF_TO_BASKET":
|
elif xlf_direction == "XLF_TO_BASKET":
|
||||||
xlf_state = "SELLING_BASKET"
|
xlf_state = "SELLING_BASKET"
|
||||||
for sym, qty in [("BOND", 3), ("GS", 2), ("MS", 3), ("WFC", 2)]:
|
for sym, qty in [("BOND", 3), ("GS", 2), ("MS", 3), ("WFC", 2)]:
|
||||||
bid_now = state.bid_prices.get(sym)
|
oid = next_id()
|
||||||
if bid_now:
|
exchange.send_add_message(
|
||||||
sell_oid = next_id()
|
oid, sym, Dir.SELL, state.bid_prices[sym], qty
|
||||||
exchange.send_add_message_ioc(sell_oid, sym, Dir.SELL, bid_now, qty)
|
)
|
||||||
xlf_pending[sell_oid] = qty
|
xlf_pending[oid] = qty
|
||||||
if not xlf_pending:
|
|
||||||
xlf_state = "IDLE"
|
|
||||||
xlf_direction = None
|
|
||||||
|
|
||||||
elif vale_state == "CONVERTING" and oid == vale_convert_oid:
|
# VALE 변환 ack 처리
|
||||||
print(" VALE 변환 완료 -> 매도 시작")
|
elif vale_state == "CONVERTING":
|
||||||
|
print(" VALE 변환 완료 → 매도 시작")
|
||||||
if vale_direction == "VALBZ_TO_VALE":
|
if vale_direction == "VALBZ_TO_VALE":
|
||||||
vale_state = "SELLING_VALE"
|
vale_state = "SELLING_VALE"
|
||||||
bid_now = state.bid_prices.get("VALE")
|
oid = next_id()
|
||||||
if bid_now:
|
exchange.send_add_message(
|
||||||
sell_oid = next_id()
|
oid, "VALE", Dir.SELL, state.bid_prices["VALE"], 1
|
||||||
exchange.send_add_message_ioc(sell_oid, "VALE", Dir.SELL, bid_now, 1)
|
)
|
||||||
vale_pending[sell_oid] = 1
|
vale_pending[oid] = 1
|
||||||
else:
|
|
||||||
vale_state = "IDLE"
|
|
||||||
vale_direction = None
|
|
||||||
|
|
||||||
elif vale_direction == "VALE_TO_VALBZ":
|
elif vale_direction == "VALE_TO_VALBZ":
|
||||||
vale_state = "SELLING_VALBZ"
|
vale_state = "SELLING_VALBZ"
|
||||||
bid_now = state.bid_prices.get("VALBZ")
|
oid = next_id()
|
||||||
if bid_now:
|
exchange.send_add_message(
|
||||||
sell_oid = next_id()
|
oid, "VALBZ", Dir.SELL, state.bid_prices["VALBZ"], 1
|
||||||
exchange.send_add_message_ioc(sell_oid, "VALBZ", Dir.SELL, bid_now, 1)
|
)
|
||||||
vale_pending[sell_oid] = 1
|
vale_pending[oid] = 1
|
||||||
else:
|
|
||||||
vale_state = "IDLE"
|
|
||||||
vale_direction = None
|
|
||||||
|
|
||||||
elif message["type"] == "out":
|
|
||||||
oid = message.get("order_id")
|
|
||||||
active_mm_orders.pop(oid, None)
|
|
||||||
handle_xlf_out(oid)
|
|
||||||
handle_vale_out(oid)
|
|
||||||
|
|
||||||
if xlf_state in ("SELLING_XLF", "SELLING_BASKET") and not xlf_pending:
|
|
||||||
print(" XLF 차익거래 완료 -> IDLE 복귀")
|
|
||||||
xlf_state = "IDLE"
|
|
||||||
xlf_direction = None
|
|
||||||
xlf_convert_oid = None
|
|
||||||
|
|
||||||
if vale_state in ("SELLING_VALE", "SELLING_VALBZ") and not vale_pending:
|
|
||||||
print(" VALE 차익거래 완료 -> IDLE 복귀")
|
|
||||||
vale_state = "IDLE"
|
|
||||||
vale_direction = None
|
|
||||||
vale_convert_oid = None
|
|
||||||
|
|
||||||
elif message["type"] == "fill":
|
elif message["type"] == "fill":
|
||||||
|
print(message)
|
||||||
qty = message["size"]
|
qty = message["size"]
|
||||||
sym = message["symbol"]
|
sym = message["symbol"]
|
||||||
dir_ = message["dir"]
|
dir_ = message["dir"]
|
||||||
oid = message["order_id"]
|
oid = message["order_id"]
|
||||||
|
|
||||||
|
# 포지션 업데이트
|
||||||
if dir_ == Dir.BUY:
|
if dir_ == Dir.BUY:
|
||||||
state.update_position(sym, qty)
|
om.update_position(sym, oid, qty)
|
||||||
else:
|
else:
|
||||||
state.update_position(sym, -qty)
|
om.update_position(sym, oid, -qty)
|
||||||
|
|
||||||
print(f" FILL {sym} {dir_} x{qty} @ {message['price']} | 포지션:{state.positions}")
|
print(f" 포지션 → {om.positions}")
|
||||||
|
|
||||||
# 마켓메이킹 주문 체결 -> 해당 심볼 재주문 (throttle 적용)
|
# BOND 체결 시 무조건 재주문
|
||||||
if oid in active_mm_orders:
|
if sym == "BOND" and oid in active_orders:
|
||||||
filled_sym = active_mm_orders.pop(oid)["sym"]
|
active_orders.pop(oid, None)
|
||||||
now = time.time()
|
|
||||||
last_t = last_mm_fill_time.get(filled_sym, 0.0)
|
|
||||||
delay = BOND_REORDER_DELAY if filled_sym == "BOND" else STOCK_REORDER_DELAY
|
|
||||||
|
|
||||||
if now - last_t > delay:
|
|
||||||
last_mm_fill_time[filled_sym] = now
|
|
||||||
if filled_sym == "BOND":
|
|
||||||
place_bond_orders()
|
place_bond_orders()
|
||||||
elif filled_sym in ("GS", "MS", "WFC"):
|
|
||||||
update_implied_fairs()
|
|
||||||
place_stock_orders(filled_sym)
|
|
||||||
|
|
||||||
|
# XLF state machine 체결 처리
|
||||||
handle_xlf_fill(oid, sym, dir_, qty)
|
handle_xlf_fill(oid, sym, dir_, qty)
|
||||||
if xlf_state in ("SELLING_XLF", "SELLING_BASKET") and not xlf_pending:
|
if xlf_state in ("SELLING_XLF", "SELLING_BASKET") and not xlf_pending:
|
||||||
print(" XLF 차익거래 완료 -> IDLE 복귀")
|
print(" XLF 차익거래 완료 → IDLE 복귀")
|
||||||
xlf_state = "IDLE"
|
xlf_state = "IDLE"
|
||||||
xlf_direction = None
|
xlf_direction = None
|
||||||
xlf_convert_oid = None
|
|
||||||
|
|
||||||
|
# VALE state machine 체결 처리
|
||||||
handle_vale_fill(oid, sym, dir_, qty)
|
handle_vale_fill(oid, sym, dir_, qty)
|
||||||
if vale_state in ("SELLING_VALE", "SELLING_VALBZ") and not vale_pending:
|
if vale_state in ("SELLING_VALE", "SELLING_VALBZ") and not vale_pending:
|
||||||
print(" VALE 차익거래 완료 -> IDLE 복귀")
|
print(" VALE 차익거래 완료 → IDLE 복귀")
|
||||||
vale_state = "IDLE"
|
vale_state = "IDLE"
|
||||||
vale_direction = None
|
vale_direction = None
|
||||||
vale_convert_oid = None
|
|
||||||
|
|
||||||
elif message["type"] == "book":
|
elif message["type"] == "book":
|
||||||
sym = message["symbol"]
|
sym = message["symbol"]
|
||||||
@@ -573,37 +386,32 @@ def main():
|
|||||||
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": state.bid_prices.get("VALE"),
|
"vale_bid_price": state.bid_prices["VALE"],
|
||||||
"vale_ask": state.ask_prices.get("VALE"),
|
"vale_ask_price": state.ask_prices["VALE"],
|
||||||
"valbz_bid": state.bid_prices.get("VALBZ"),
|
|
||||||
"valbz_ask": state.ask_prices.get("VALBZ"),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
# XLF 관련 심볼 호가 업데이트마다 차익거래 시도
|
||||||
if sym in ["BOND", "GS", "MS", "WFC", "XLF"]:
|
if sym in ["BOND", "GS", "MS", "WFC", "XLF"]:
|
||||||
update_implied_fairs()
|
|
||||||
try_xlf_arb()
|
try_xlf_arb()
|
||||||
|
|
||||||
# fair value가 크게 움직이면 해당 종목 주문 즉시 갱신
|
# VALE/VALBZ 호가 업데이트마다 차익거래 시도
|
||||||
if sym in ["GS", "MS", "WFC"] and implied_fairs.get(sym) is not None:
|
|
||||||
existing = [(oid, info) for oid, info in active_mm_orders.items()
|
|
||||||
if info["sym"] == sym]
|
|
||||||
if existing:
|
|
||||||
fair = implied_fairs[sym]
|
|
||||||
prices = [info["price"] for _, info in existing]
|
|
||||||
if any(abs(p - fair) > STOCK_SPREAD * 2 for p in prices):
|
|
||||||
place_stock_orders(sym)
|
|
||||||
|
|
||||||
if sym in ["VALE", "VALBZ"]:
|
if sym in ["VALE", "VALBZ"]:
|
||||||
try_vale_arb()
|
try_vale_arb()
|
||||||
|
|
||||||
|
# 주기적으로 BOND 주문 갱신 (주문 만료 방지)
|
||||||
now = time.time()
|
now = time.time()
|
||||||
if now - last_refresh > REFRESH_INTERVAL:
|
if now - last_refresh > REFRESH_INTERVAL:
|
||||||
last_refresh = now
|
last_refresh = now
|
||||||
refresh_all_mm()
|
place_bond_orders()
|
||||||
|
|
||||||
|
|
||||||
# ~~~~~============== PROVIDED CODE ==============~~~~~
|
# ~~~~~============== PROVIDED CODE ==============~~~~~
|
||||||
|
|
||||||
|
# You probably don't need to edit anything below this line, but feel free to
|
||||||
|
# ask if you have any questions about what it is doing or how it works. If you
|
||||||
|
# do need to change anything below this line, please feel free to
|
||||||
|
|
||||||
|
|
||||||
class Dir(str, Enum):
|
class Dir(str, Enum):
|
||||||
BUY = "BUY"
|
BUY = "BUY"
|
||||||
SELL = "SELL"
|
SELL = "SELL"
|
||||||
@@ -617,40 +425,55 @@ class ExchangeConnection:
|
|||||||
exchange_socket = self._connect(add_socket_timeout=args.add_socket_timeout)
|
exchange_socket = self._connect(add_socket_timeout=args.add_socket_timeout)
|
||||||
self.reader = exchange_socket.makefile("r", 1)
|
self.reader = exchange_socket.makefile("r", 1)
|
||||||
self.writer = exchange_socket
|
self.writer = exchange_socket
|
||||||
|
|
||||||
self._write_message({"type": "hello", "team": team_name.upper()})
|
self._write_message({"type": "hello", "team": team_name.upper()})
|
||||||
|
|
||||||
def read_message(self):
|
def read_message(self):
|
||||||
|
"""Read a single message from the exchange"""
|
||||||
message = json.loads(self.reader.readline())
|
message = json.loads(self.reader.readline())
|
||||||
if "dir" in message:
|
if "dir" in message:
|
||||||
message["dir"] = Dir(message["dir"])
|
message["dir"] = Dir(message["dir"])
|
||||||
return message
|
return message
|
||||||
|
|
||||||
def send_add_message(self, order_id: int, symbol: str, dir: Dir, price: int, size: int):
|
def send_add_message(
|
||||||
"""DAY 주문 - 마켓메이킹용"""
|
self, order_id: int, symbol: str, dir: Dir, price: int, size: int
|
||||||
self._write_message({
|
):
|
||||||
"type": "add", "order_id": order_id, "symbol": symbol,
|
"""Add a new order"""
|
||||||
"dir": dir, "price": price, "size": size, "tif": "DAY",
|
self._write_message(
|
||||||
})
|
{
|
||||||
|
"type": "add",
|
||||||
def send_add_message_ioc(self, order_id: int, symbol: str, dir: Dir, price: int, size: int):
|
"order_id": order_id,
|
||||||
"""IOC 주문 - 차익거래/청산용"""
|
"symbol": symbol,
|
||||||
self._write_message({
|
"dir": dir,
|
||||||
"type": "add", "order_id": order_id, "symbol": symbol,
|
"price": price,
|
||||||
"dir": dir, "price": price, "size": size, "tif": "IOC",
|
"size": size,
|
||||||
})
|
"tif": "DAY", # 설명서 필수 필드: DAY or IOC
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
def send_convert_message(self, order_id: int, symbol: str, dir: Dir, size: int):
|
def send_convert_message(self, order_id: int, symbol: str, dir: Dir, size: int):
|
||||||
self._write_message({
|
"""Convert between related symbols"""
|
||||||
"type": "convert", "order_id": order_id,
|
self._write_message(
|
||||||
"symbol": symbol, "dir": dir, "size": size,
|
{
|
||||||
})
|
"type": "convert",
|
||||||
|
"order_id": order_id,
|
||||||
|
"symbol": symbol,
|
||||||
|
"dir": dir,
|
||||||
|
"size": size,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
def send_cancel_message(self, order_id: int):
|
def send_cancel_message(self, order_id: int):
|
||||||
|
"""Cancel an existing order"""
|
||||||
self._write_message({"type": "cancel", "order_id": order_id})
|
self._write_message({"type": "cancel", "order_id": order_id})
|
||||||
|
|
||||||
def _connect(self, add_socket_timeout):
|
def _connect(self, add_socket_timeout):
|
||||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
|
||||||
if add_socket_timeout:
|
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.settimeout(5)
|
||||||
s.connect((self.exchange_hostname, self.port))
|
s.connect((self.exchange_hostname, self.port))
|
||||||
return s
|
return s
|
||||||
@@ -658,30 +481,47 @@ class ExchangeConnection:
|
|||||||
def _write_message(self, message):
|
def _write_message(self, message):
|
||||||
what_to_write = json.dumps(message)
|
what_to_write = json.dumps(message)
|
||||||
if not what_to_write.endswith("\n"):
|
if not what_to_write.endswith("\n"):
|
||||||
what_to_write += "\n"
|
what_to_write = what_to_write + "\n"
|
||||||
|
|
||||||
length_to_send = len(what_to_write)
|
length_to_send = len(what_to_write)
|
||||||
total_sent = 0
|
total_sent = 0
|
||||||
while total_sent < length_to_send:
|
while total_sent < length_to_send:
|
||||||
sent = self.writer.send(what_to_write[total_sent:].encode("utf-8"))
|
sent_this_time = self.writer.send(
|
||||||
if sent == 0:
|
what_to_write[total_sent:].encode("utf-8")
|
||||||
|
)
|
||||||
|
if sent_this_time == 0:
|
||||||
raise Exception("Unable to send data to exchange")
|
raise Exception("Unable to send data to exchange")
|
||||||
total_sent += sent
|
total_sent += sent_this_time
|
||||||
|
|
||||||
now = time.time()
|
now = time.time()
|
||||||
self.message_timestamps.append(now)
|
self.message_timestamps.append(now)
|
||||||
if (len(self.message_timestamps) == self.message_timestamps.maxlen
|
if len(
|
||||||
and self.message_timestamps[0] > (now - 1)):
|
self.message_timestamps
|
||||||
print("WARNING: 메시지 전송 너무 빈번! Rate limit 위험.")
|
) == 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."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def parse_arguments():
|
def parse_arguments():
|
||||||
test_exchange_port_offsets = {"prod-like": 0, "slower": 1, "empty": 2}
|
test_exchange_port_offsets = {"prod-like": 0, "slower": 1, "empty": 2}
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(description="Trade on an ETC exchange!")
|
parser = argparse.ArgumentParser(description="Trade on an ETC exchange!")
|
||||||
grp = parser.add_mutually_exclusive_group(required=True)
|
exchange_address_group = parser.add_mutually_exclusive_group(required=True)
|
||||||
grp.add_argument("--production", action="store_true")
|
exchange_address_group.add_argument(
|
||||||
grp.add_argument("--test", type=str, choices=test_exchange_port_offsets.keys())
|
"--production", action="store_true", help="Connect to the production exchange."
|
||||||
grp.add_argument("--specific-address", type=str, metavar="HOST:PORT", help=argparse.SUPPRESS)
|
)
|
||||||
|
exchange_address_group.add_argument(
|
||||||
|
"--test",
|
||||||
|
type=str,
|
||||||
|
choices=test_exchange_port_offsets.keys(),
|
||||||
|
help="Connect to a test exchange.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Connect to a specific host. This is only intended to be used for debugging.
|
||||||
|
exchange_address_group.add_argument(
|
||||||
|
"--specific-address", type=str, metavar="HOST:PORT", help=argparse.SUPPRESS
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
args.add_socket_timeout = True
|
args.add_socket_timeout = True
|
||||||
@@ -702,7 +542,9 @@ def parse_arguments():
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
# Check that [team_name] has been updated.
|
||||||
assert team_name != "REPLAC" + "EME", (
|
assert team_name != "REPLAC" + "EME", (
|
||||||
"Please put your team name in the variable [team_name]."
|
"Please put your team name in the variable [team_name]."
|
||||||
)
|
)
|
||||||
|
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user