commit
This commit is contained in:
584
new_prac.py
584
new_prac.py
@@ -1,8 +1,4 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# ~~~~~============== HOW TO RUN ==============~~~~~
|
|
||||||
# 1) Configure things in CONFIGURATION section
|
|
||||||
# 2) Change permissions: chmod +x bot.py
|
|
||||||
# 3) Run in loop: while true; do ./bot.py --test prod-like; sleep 1; done
|
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
from collections import deque
|
from collections import deque
|
||||||
@@ -13,204 +9,54 @@ import json
|
|||||||
from state import StateManager
|
from state import StateManager
|
||||||
from order import OrderManager
|
from order import OrderManager
|
||||||
|
|
||||||
# ~~~~~============== CONFIGURATION ==============~~~~~
|
|
||||||
# Replace "REPLACEME" with your team name!
|
|
||||||
team_name = "HanyangFloorFunction"
|
team_name = "HanyangFloorFunction"
|
||||||
|
|
||||||
# ~~~~~============== MAIN LOOP ==============~~~~~
|
MAX_ARBS = 5
|
||||||
|
XLF_SIZE = 50
|
||||||
# You should put your code here! We provide some starter code as an example,
|
VALE_SIZE = 50
|
||||||
# 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:", hello_message)
|
||||||
|
|
||||||
# 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_ORDER_SIZE = 50
|
|
||||||
STOCK_ORDER_SIZE = 10 # GS/MS/WFC 마켓 메이킹 주문량
|
|
||||||
STOCK_SPREAD = 1 # GS/MS/WFC 마켓 메이킹 스프레드 (mid ± 1)
|
|
||||||
STOCK_MAX_POSITION = 50 # GS/MS/WFC 포지션 한도
|
|
||||||
XLF_CONVERSION_FEE = 100
|
|
||||||
XLF_MIN_PROFIT = 50 # 수익 클 때만 XLF 차익거래
|
|
||||||
XLF_COOLDOWN = 3.0
|
|
||||||
VALE_CONVERSION_FEE = 10
|
|
||||||
VALE_MIN_PROFIT = 1
|
|
||||||
VALE_ARB_SIZE = 10
|
|
||||||
REFRESH_INTERVAL = 5.0
|
|
||||||
|
|
||||||
# XLF state machine
|
|
||||||
xlf_state = "IDLE"
|
|
||||||
xlf_pending = {}
|
|
||||||
xlf_direction = None
|
|
||||||
xlf_arb_size = 0
|
|
||||||
xlf_convert_oid = None
|
|
||||||
xlf_last_fail = 0.0
|
|
||||||
|
|
||||||
# VALE state machine
|
|
||||||
vale_state = "IDLE"
|
|
||||||
vale_pending = {}
|
|
||||||
vale_direction = None
|
|
||||||
vale_arb_size = 0
|
|
||||||
vale_convert_oid = None
|
|
||||||
|
|
||||||
state = StateManager()
|
state = StateManager()
|
||||||
om = OrderManager(exchange)
|
om = OrderManager(exchange)
|
||||||
|
|
||||||
market_open = False
|
market_open = False
|
||||||
|
xlf_pending = {}
|
||||||
# BOND 전용 active orders
|
|
||||||
bond_orders = {} # {order_id: {"dir": ..., "price": ..., "size": ...}}
|
|
||||||
# GS/MS/WFC 마켓 메이킹 active orders
|
|
||||||
stock_orders = {} # {order_id: {"symbol": ..., "dir": ..., "price": ..., "size": ...}}
|
|
||||||
|
|
||||||
last_refresh = time.time()
|
|
||||||
last_stock_refresh = time.time()
|
|
||||||
|
|
||||||
# hello 메시지에서 기존 포지션 로드 (재접속 시 필수) ← 들여쓰기 수정
|
|
||||||
for sym_info in hello_message["symbols"]:
|
|
||||||
sym = sym_info["symbol"]
|
|
||||||
pos = sym_info["position"]
|
|
||||||
if sym in om.positions:
|
|
||||||
om.positions[sym] = pos
|
|
||||||
om.future_positions[sym] = pos
|
|
||||||
print(f" 초기 포지션 로드: {om.positions}")
|
|
||||||
|
|
||||||
def next_id():
|
def next_id():
|
||||||
return om.next_order()
|
return om.next_order()
|
||||||
|
|
||||||
# ── BOND 마켓 메이킹 ──────────────────────────────────────────
|
# ---------------- BOND ----------------
|
||||||
|
|
||||||
def cancel_bond_sell_orders():
|
|
||||||
for oid in list(bond_orders.keys()):
|
|
||||||
info = bond_orders[oid]
|
|
||||||
if info["dir"] == Dir.SELL:
|
|
||||||
om.future_positions["BOND"] += info.get("size", 0)
|
|
||||||
om.cancel(oid)
|
|
||||||
bond_orders.pop(oid, None)
|
|
||||||
|
|
||||||
def cancel_all_bond_orders():
|
|
||||||
for oid in list(bond_orders.keys()):
|
|
||||||
info = bond_orders[oid]
|
|
||||||
size = info.get("size", 0)
|
|
||||||
if info["dir"] == Dir.BUY:
|
|
||||||
om.future_positions["BOND"] -= size
|
|
||||||
else:
|
|
||||||
om.future_positions["BOND"] += size
|
|
||||||
om.cancel(oid)
|
|
||||||
bond_orders.pop(oid, None)
|
|
||||||
|
|
||||||
def place_bond_orders():
|
def place_bond_orders():
|
||||||
if not market_open:
|
if not market_open:
|
||||||
return
|
return
|
||||||
cancel_all_bond_orders()
|
|
||||||
|
|
||||||
pos = om.positions["BOND"]
|
bid = state.bid_prices["BOND"]
|
||||||
base = BOND_ORDER_SIZE
|
ask = state.ask_prices["BOND"]
|
||||||
adj = abs(pos) // 5
|
|
||||||
|
|
||||||
if pos < 0:
|
if bid is None or ask is None:
|
||||||
buy_sz = min(base + adj, 100 - pos)
|
return
|
||||||
sell_sz = max(base - adj, 1)
|
|
||||||
elif pos > 0:
|
|
||||||
buy_sz = max(base - adj, 1)
|
|
||||||
sell_sz = min(base + adj, 100 + pos)
|
|
||||||
else:
|
|
||||||
buy_sz = sell_sz = base
|
|
||||||
|
|
||||||
buy_sz = max(0, min(buy_sz, 100 - pos))
|
buy_price = bid + 1
|
||||||
sell_sz = max(0, min(sell_sz, 100 + pos))
|
sell_price = ask - 1
|
||||||
|
|
||||||
if buy_sz > 0:
|
size = 100
|
||||||
bid = next_id()
|
|
||||||
exchange.send_add_message(bid, "BOND", Dir.BUY, 999, buy_sz)
|
|
||||||
om.future_positions["BOND"] += buy_sz
|
|
||||||
bond_orders[bid] = {"dir": Dir.BUY, "price": 999, "size": buy_sz}
|
|
||||||
|
|
||||||
if sell_sz > 0:
|
exchange.send_add_message(next_id(), "BOND", Dir.BUY, buy_price, size)
|
||||||
ask = next_id()
|
exchange.send_add_message(next_id(), "BOND", Dir.SELL, sell_price, size)
|
||||||
exchange.send_add_message(ask, "BOND", Dir.SELL, 1001, sell_sz)
|
|
||||||
om.future_positions["BOND"] -= sell_sz
|
|
||||||
bond_orders[ask] = {"dir": Dir.SELL, "price": 1001, "size": sell_sz}
|
|
||||||
|
|
||||||
print(f" BOND 주문 → 매수:999 x{buy_sz}, 매도:1001 x{sell_sz}, 포지션:{pos}")
|
# ---------------- XLF ----------------
|
||||||
|
def try_xlf_arb():
|
||||||
# ── GS/MS/WFC 마켓 메이킹 ────────────────────────────────────
|
|
||||||
|
|
||||||
def cancel_stock_orders(symbol=None):
|
|
||||||
"""symbol=None이면 전부 취소, 아니면 해당 심볼만"""
|
|
||||||
for oid in list(stock_orders.keys()):
|
|
||||||
info = stock_orders[oid]
|
|
||||||
if symbol is None or info["symbol"] == symbol:
|
|
||||||
size = info.get("size", 0)
|
|
||||||
s = info["symbol"]
|
|
||||||
if info["dir"] == Dir.BUY:
|
|
||||||
om.future_positions[s] -= size
|
|
||||||
else:
|
|
||||||
om.future_positions[s] += size
|
|
||||||
om.cancel(oid)
|
|
||||||
stock_orders.pop(oid, None)
|
|
||||||
|
|
||||||
def place_stock_orders(sym):
|
|
||||||
"""mid price 기준 ±1 스프레드로 마켓 메이킹"""
|
|
||||||
if not market_open:
|
if not market_open:
|
||||||
return
|
return
|
||||||
|
|
||||||
bid_price = state.bid_prices[sym]
|
if len(xlf_pending) >= MAX_ARBS:
|
||||||
ask_price = state.ask_prices[sym]
|
|
||||||
if bid_price is None or ask_price is None:
|
|
||||||
return
|
|
||||||
|
|
||||||
mid = (bid_price + ask_price) // 2
|
|
||||||
our_bid = mid - STOCK_SPREAD
|
|
||||||
our_ask = mid + STOCK_SPREAD
|
|
||||||
|
|
||||||
pos = om.positions[sym]
|
|
||||||
limit = STOCK_MAX_POSITION
|
|
||||||
|
|
||||||
cancel_stock_orders(sym)
|
|
||||||
|
|
||||||
buy_sz = max(0, min(STOCK_ORDER_SIZE, limit - pos))
|
|
||||||
sell_sz = max(0, min(STOCK_ORDER_SIZE, limit + pos))
|
|
||||||
|
|
||||||
if buy_sz > 0 and our_bid > 0:
|
|
||||||
bid = next_id()
|
|
||||||
exchange.send_add_message(bid, sym, Dir.BUY, our_bid, buy_sz)
|
|
||||||
om.future_positions[sym] += buy_sz
|
|
||||||
stock_orders[bid] = {"symbol": sym, "dir": Dir.BUY, "price": our_bid, "size": buy_sz}
|
|
||||||
|
|
||||||
if sell_sz > 0:
|
|
||||||
ask = next_id()
|
|
||||||
exchange.send_add_message(ask, sym, Dir.SELL, our_ask, sell_sz)
|
|
||||||
om.future_positions[sym] -= sell_sz
|
|
||||||
stock_orders[ask] = {"symbol": sym, "dir": Dir.SELL, "price": our_ask, "size": sell_sz}
|
|
||||||
|
|
||||||
# ── XLF 차익거래 ─────────────────────────────────────────────
|
|
||||||
|
|
||||||
def try_xlf_arb():
|
|
||||||
# nonlocal에 xlf_last_fail 추가 ← 수정
|
|
||||||
nonlocal xlf_state, xlf_direction, xlf_pending, xlf_arb_size, xlf_convert_oid, xlf_last_fail
|
|
||||||
|
|
||||||
if not market_open or xlf_state != "IDLE":
|
|
||||||
return
|
|
||||||
if time.time() - xlf_last_fail < XLF_COOLDOWN:
|
|
||||||
return
|
return
|
||||||
|
|
||||||
bond_ask = state.ask_prices["BOND"]
|
bond_ask = state.ask_prices["BOND"]
|
||||||
@@ -218,6 +64,7 @@ def main():
|
|||||||
ms_ask = state.ask_prices["MS"]
|
ms_ask = state.ask_prices["MS"]
|
||||||
wfc_ask = state.ask_prices["WFC"]
|
wfc_ask = state.ask_prices["WFC"]
|
||||||
xlf_bid = state.bid_prices["XLF"]
|
xlf_bid = state.bid_prices["XLF"]
|
||||||
|
|
||||||
bond_bid = state.bid_prices["BOND"]
|
bond_bid = state.bid_prices["BOND"]
|
||||||
gs_bid = state.bid_prices["GS"]
|
gs_bid = state.bid_prices["GS"]
|
||||||
ms_bid = state.bid_prices["MS"]
|
ms_bid = state.bid_prices["MS"]
|
||||||
@@ -231,61 +78,24 @@ 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
|
||||||
|
|
||||||
def basket_has_room():
|
profit1 = xlf_bid * 10 - basket_ask - 100
|
||||||
return (
|
profit2 = basket_bid - xlf_ask * 10 - 100
|
||||||
om.positions["BOND"] + 3 <= 100 and
|
|
||||||
om.positions["GS"] + 2 <= 100 and
|
|
||||||
om.positions["MS"] + 3 <= 100 and
|
|
||||||
om.positions["WFC"] + 2 <= 100
|
|
||||||
)
|
|
||||||
|
|
||||||
profit1 = xlf_bid * 10 - basket_ask - XLF_CONVERSION_FEE
|
# 🔥 공격 (손해도 감수)
|
||||||
if profit1 > XLF_MIN_PROFIT and om.check_pos_limit("XLF") and basket_has_room():
|
if profit1 > -50:
|
||||||
print(f" XLF 차익(바스켓→XLF) 시작, 예상수익:{profit1}")
|
|
||||||
cancel_all_bond_orders()
|
|
||||||
cancel_stock_orders()
|
|
||||||
xlf_state = "BUYING_BASKET"; xlf_direction = "BASKET_TO_XLF"; xlf_arb_size = 10
|
|
||||||
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(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
|
|
||||||
|
|
||||||
profit2 = basket_bid - xlf_ask * 10 - XLF_CONVERSION_FEE
|
elif profit2 > -50:
|
||||||
if profit2 > XLF_MIN_PROFIT and om.check_pos_limit("XLF"):
|
|
||||||
print(f" XLF 차익(XLF→바스켓) 시작, 예상수익:{profit2}")
|
|
||||||
cancel_all_bond_orders()
|
|
||||||
cancel_stock_orders()
|
|
||||||
xlf_state = "BUYING_XLF"; xlf_direction = "XLF_TO_BASKET"; xlf_arb_size = 10
|
|
||||||
xlf_pending.clear()
|
|
||||||
oid = next_id()
|
oid = next_id()
|
||||||
exchange.send_add_message(oid, "XLF", Dir.BUY, xlf_ask, 10)
|
exchange.send_add_message(oid, "XLF", Dir.BUY, xlf_ask, XLF_SIZE)
|
||||||
xlf_pending[oid] = 10
|
xlf_pending[oid] = XLF_SIZE
|
||||||
|
|
||||||
def handle_xlf_fill(order_id, symbol, dir_, qty):
|
|
||||||
nonlocal xlf_state, xlf_pending, xlf_convert_oid
|
|
||||||
if order_id not in xlf_pending:
|
|
||||||
return
|
|
||||||
xlf_pending[order_id] -= qty
|
|
||||||
if xlf_pending[order_id] <= 0:
|
|
||||||
del xlf_pending[order_id]
|
|
||||||
if xlf_state == "BUYING_BASKET" and not xlf_pending:
|
|
||||||
print(" 바스켓 매수 완료 → XLF 변환 시작")
|
|
||||||
xlf_state = "CONVERTING"
|
|
||||||
xlf_convert_oid = next_id()
|
|
||||||
exchange.send_convert_message(xlf_convert_oid, "XLF", Dir.BUY, xlf_arb_size)
|
|
||||||
elif xlf_state == "BUYING_XLF" and not xlf_pending:
|
|
||||||
print(" XLF 매수 완료 → 바스켓 변환 시작")
|
|
||||||
xlf_state = "CONVERTING"
|
|
||||||
xlf_convert_oid = next_id()
|
|
||||||
exchange.send_convert_message(xlf_convert_oid, "XLF", Dir.SELL, xlf_arb_size)
|
|
||||||
|
|
||||||
# ── VALE 차익거래 ─────────────────────────────────────────────
|
|
||||||
|
|
||||||
|
# ---------------- VALE ----------------
|
||||||
def try_vale_arb():
|
def try_vale_arb():
|
||||||
nonlocal vale_state, vale_direction, vale_pending, vale_arb_size, vale_convert_oid
|
if not market_open:
|
||||||
if not market_open or vale_state != "IDLE":
|
|
||||||
return
|
return
|
||||||
|
|
||||||
vale_bid = state.bid_prices["VALE"]
|
vale_bid = state.bid_prices["VALE"]
|
||||||
@@ -296,236 +106,55 @@ def main():
|
|||||||
if None in [vale_bid, vale_ask, valbz_bid, valbz_ask]:
|
if None in [vale_bid, vale_ask, valbz_bid, valbz_ask]:
|
||||||
return
|
return
|
||||||
|
|
||||||
valbz_pos = om.positions["VALBZ"]
|
profit1 = vale_bid - valbz_ask - 10
|
||||||
vale_pos = om.positions["VALE"]
|
profit2 = valbz_bid - vale_ask - 10
|
||||||
|
|
||||||
profit1 = vale_bid - valbz_ask - VALE_CONVERSION_FEE
|
if profit1 > -5:
|
||||||
arb_size1 = min(VALE_ARB_SIZE, 10 - valbz_pos)
|
exchange.send_add_message(next_id(), "VALBZ", Dir.BUY, valbz_ask, VALE_SIZE)
|
||||||
if profit1 > VALE_MIN_PROFIT and arb_size1 > 0:
|
|
||||||
print(f" VALE 차익(VALBZ→VALE) 시작, 예상수익:{profit1 * arb_size1}, size:{arb_size1}")
|
|
||||||
vale_state = "BUYING_VALBZ"; vale_direction = "VALBZ_TO_VALE"; vale_arb_size = arb_size1
|
|
||||||
vale_pending.clear()
|
|
||||||
oid = next_id()
|
|
||||||
exchange.send_add_message(oid, "VALBZ", Dir.BUY, valbz_ask, arb_size1)
|
|
||||||
vale_pending[oid] = arb_size1
|
|
||||||
return
|
|
||||||
|
|
||||||
profit2 = valbz_bid - vale_ask - VALE_CONVERSION_FEE
|
elif profit2 > -5:
|
||||||
arb_size2 = min(VALE_ARB_SIZE, 10 - vale_pos)
|
exchange.send_add_message(next_id(), "VALE", Dir.BUY, vale_ask, VALE_SIZE)
|
||||||
if profit2 > VALE_MIN_PROFIT and arb_size2 > 0:
|
|
||||||
print(f" VALE 차익(VALE→VALBZ) 시작, 예상수익:{profit2 * arb_size2}, size:{arb_size2}")
|
|
||||||
vale_state = "BUYING_VALE"; vale_direction = "VALE_TO_VALBZ"; vale_arb_size = arb_size2
|
|
||||||
vale_pending.clear()
|
|
||||||
oid = next_id()
|
|
||||||
exchange.send_add_message(oid, "VALE", Dir.BUY, vale_ask, arb_size2)
|
|
||||||
vale_pending[oid] = arb_size2
|
|
||||||
|
|
||||||
def handle_vale_fill(order_id, symbol, dir_, qty):
|
# ---------------- MAIN LOOP ----------------
|
||||||
nonlocal vale_state, vale_pending, vale_convert_oid
|
|
||||||
if order_id not in vale_pending:
|
|
||||||
return
|
|
||||||
vale_pending[order_id] -= qty
|
|
||||||
if vale_pending[order_id] <= 0:
|
|
||||||
del vale_pending[order_id]
|
|
||||||
if vale_state == "BUYING_VALBZ" and not vale_pending:
|
|
||||||
print(" VALBZ 매수 완료 → VALE 변환 시작")
|
|
||||||
vale_state = "CONVERTING"
|
|
||||||
vale_convert_oid = next_id()
|
|
||||||
exchange.send_convert_message(vale_convert_oid, "VALE", Dir.BUY, vale_arb_size)
|
|
||||||
elif vale_state == "BUYING_VALE" and not vale_pending:
|
|
||||||
print(" VALE 매수 완료 → VALBZ 변환 시작")
|
|
||||||
vale_state = "CONVERTING"
|
|
||||||
vale_convert_oid = next_id()
|
|
||||||
exchange.send_convert_message(vale_convert_oid, "VALE", Dir.SELL, vale_arb_size)
|
|
||||||
|
|
||||||
# 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()
|
|
||||||
|
|
||||||
# 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("Round ended")
|
||||||
break
|
break
|
||||||
|
|
||||||
elif message["type"] == "open":
|
elif message["type"] == "open":
|
||||||
# 시장이 열렸을 때 주문 시작 (open 전에 주문하면 reject됨)
|
print("Market opened")
|
||||||
print("Market opened:", message)
|
|
||||||
market_open = True
|
market_open = True
|
||||||
place_bond_orders()
|
place_bond_orders()
|
||||||
|
|
||||||
elif message["type"] == "error":
|
|
||||||
print(message)
|
|
||||||
|
|
||||||
elif message["type"] == "reject":
|
|
||||||
print(message)
|
|
||||||
oid = message.get("order_id")
|
|
||||||
bond_orders.pop(oid, None)
|
|
||||||
stock_orders.pop(oid, None)
|
|
||||||
if oid in xlf_pending:
|
|
||||||
print(" XLF 주문 reject → IDLE 복귀")
|
|
||||||
xlf_state = "IDLE"; xlf_pending.clear(); xlf_direction = None
|
|
||||||
xlf_last_fail = time.time()
|
|
||||||
place_bond_orders()
|
|
||||||
if oid in vale_pending:
|
|
||||||
print(" VALE 주문 reject → IDLE 복귀")
|
|
||||||
vale_state = "IDLE"; vale_pending.clear(); vale_direction = None
|
|
||||||
|
|
||||||
elif message["type"] == "ack":
|
|
||||||
ack_oid = message.get("order_id")
|
|
||||||
|
|
||||||
if xlf_state == "CONVERTING" and ack_oid == xlf_convert_oid:
|
|
||||||
print(" XLF 변환 완료 → 매도 시작")
|
|
||||||
if xlf_direction == "BASKET_TO_XLF":
|
|
||||||
om.positions["BOND"] -= 3; om.positions["GS"] -= 2
|
|
||||||
om.positions["MS"] -= 3; om.positions["WFC"] -= 2
|
|
||||||
om.positions["XLF"] += xlf_arb_size
|
|
||||||
om.future_positions["BOND"] -= 3; om.future_positions["GS"] -= 2
|
|
||||||
om.future_positions["MS"] -= 3; om.future_positions["WFC"] -= 2
|
|
||||||
om.future_positions["XLF"] += xlf_arb_size
|
|
||||||
xlf_state = "SELLING_XLF"
|
|
||||||
oid = next_id()
|
|
||||||
exchange.send_add_message(oid, "XLF", Dir.SELL, state.bid_prices["XLF"], xlf_arb_size)
|
|
||||||
xlf_pending[oid] = xlf_arb_size
|
|
||||||
elif xlf_direction == "XLF_TO_BASKET":
|
|
||||||
om.positions["XLF"] -= xlf_arb_size
|
|
||||||
om.positions["BOND"] += 3; om.positions["GS"] += 2
|
|
||||||
om.positions["MS"] += 3; om.positions["WFC"] += 2
|
|
||||||
om.future_positions["XLF"] -= xlf_arb_size
|
|
||||||
om.future_positions["BOND"] += 3; om.future_positions["GS"] += 2
|
|
||||||
om.future_positions["MS"] += 3; om.future_positions["WFC"] += 2
|
|
||||||
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[oid] = qty
|
|
||||||
|
|
||||||
elif vale_state == "CONVERTING" and ack_oid == vale_convert_oid:
|
|
||||||
print(" VALE 변환 완료 → 매도 시작")
|
|
||||||
if vale_direction == "VALBZ_TO_VALE":
|
|
||||||
om.positions["VALBZ"] -= vale_arb_size
|
|
||||||
om.positions["VALE"] += vale_arb_size
|
|
||||||
om.future_positions["VALBZ"] -= vale_arb_size
|
|
||||||
om.future_positions["VALE"] += vale_arb_size
|
|
||||||
vale_state = "SELLING_VALE"
|
|
||||||
oid = next_id()
|
|
||||||
exchange.send_add_message(oid, "VALE", Dir.SELL, state.bid_prices["VALE"], vale_arb_size)
|
|
||||||
vale_pending[oid] = vale_arb_size
|
|
||||||
elif vale_direction == "VALE_TO_VALBZ":
|
|
||||||
om.positions["VALE"] -= vale_arb_size
|
|
||||||
om.positions["VALBZ"] += vale_arb_size
|
|
||||||
om.future_positions["VALE"] -= vale_arb_size
|
|
||||||
om.future_positions["VALBZ"] += vale_arb_size
|
|
||||||
vale_state = "SELLING_VALBZ"
|
|
||||||
oid = next_id()
|
|
||||||
exchange.send_add_message(oid, "VALBZ", Dir.SELL, state.bid_prices["VALBZ"], vale_arb_size)
|
|
||||||
vale_pending[oid] = vale_arb_size
|
|
||||||
|
|
||||||
elif message["type"] == "fill":
|
elif message["type"] == "fill":
|
||||||
print(message)
|
|
||||||
qty = message["size"]
|
|
||||||
sym = message["symbol"]
|
sym = message["symbol"]
|
||||||
|
qty = message["size"]
|
||||||
dir_ = message["dir"]
|
dir_ = message["dir"]
|
||||||
oid = message["order_id"]
|
|
||||||
|
|
||||||
if dir_ == Dir.BUY:
|
if dir_ == Dir.BUY:
|
||||||
om.update_position(sym, oid, qty)
|
om.update_position(sym, message["order_id"], qty)
|
||||||
else:
|
else:
|
||||||
om.update_position(sym, oid, -qty)
|
om.update_position(sym, message["order_id"], -qty)
|
||||||
|
|
||||||
print(f" 포지션 → {om.positions}")
|
print("Position:", om.positions)
|
||||||
|
|
||||||
# BOND 체결 → 재주문
|
|
||||||
if sym == "BOND" and oid in bond_orders:
|
|
||||||
bond_orders.pop(oid, None)
|
|
||||||
place_bond_orders()
|
|
||||||
|
|
||||||
# GS/MS/WFC 체결 → 해당 심볼 재주문
|
|
||||||
if sym in ("GS", "MS", "WFC") and oid in stock_orders:
|
|
||||||
stock_orders.pop(oid, None)
|
|
||||||
place_stock_orders(sym)
|
|
||||||
|
|
||||||
# XLF state machine
|
|
||||||
handle_xlf_fill(oid, sym, dir_, qty)
|
|
||||||
if xlf_state in ("SELLING_XLF", "SELLING_BASKET") and not xlf_pending:
|
|
||||||
print(" XLF 차익거래 완료 → IDLE 복귀")
|
|
||||||
xlf_state = "IDLE"; xlf_direction = None
|
|
||||||
place_bond_orders()
|
|
||||||
for s in ("GS", "MS", "WFC"):
|
|
||||||
place_stock_orders(s)
|
|
||||||
|
|
||||||
# VALE state machine
|
|
||||||
handle_vale_fill(oid, sym, dir_, qty)
|
|
||||||
if vale_state in ("SELLING_VALE", "SELLING_VALBZ") and not vale_pending:
|
|
||||||
print(" VALE 차익거래 완료 → IDLE 복귀")
|
|
||||||
vale_state = "IDLE"; vale_direction = None
|
|
||||||
|
|
||||||
elif message["type"] == "book":
|
elif message["type"] == "book":
|
||||||
sym = message["symbol"]
|
sym = message["symbol"]
|
||||||
|
|
||||||
state.update_bid_ask_price(
|
state.update_bid_ask_price(
|
||||||
sym,
|
sym,
|
||||||
message["buy"][0][0] if message["buy"] else None,
|
message["buy"][0][0] if message["buy"] else None,
|
||||||
message["sell"][0][0] if message["sell"] 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": state.bid_prices["VALE"],
|
|
||||||
"vale_ask_price": state.ask_prices["VALE"],
|
|
||||||
})
|
|
||||||
|
|
||||||
# XLF 차익거래 시도
|
|
||||||
if sym in ["BOND", "GS", "MS", "WFC", "XLF"]:
|
|
||||||
try_xlf_arb()
|
try_xlf_arb()
|
||||||
|
|
||||||
# VALE 차익거래 시도
|
|
||||||
if sym in ["VALE", "VALBZ"]:
|
|
||||||
try_vale_arb()
|
try_vale_arb()
|
||||||
|
|
||||||
# GS/MS/WFC 마켓 메이킹 갱신 (2초마다)
|
|
||||||
if sym in ("GS", "MS", "WFC") and xlf_state == "IDLE":
|
|
||||||
now = time.time()
|
|
||||||
if now - last_stock_refresh > 2.0:
|
|
||||||
last_stock_refresh = now
|
|
||||||
place_stock_orders(sym)
|
|
||||||
|
|
||||||
# 주기적으로 BOND 주문 갱신
|
|
||||||
now = time.time()
|
|
||||||
if now - last_refresh > REFRESH_INTERVAL:
|
|
||||||
last_refresh = now
|
|
||||||
place_bond_orders()
|
place_bond_orders()
|
||||||
|
|
||||||
|
|
||||||
# ~~~~~============== 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"
|
||||||
@@ -533,132 +162,43 @@ class Dir(str, Enum):
|
|||||||
|
|
||||||
class ExchangeConnection:
|
class ExchangeConnection:
|
||||||
def __init__(self, args):
|
def __init__(self, args):
|
||||||
self.message_timestamps = deque(maxlen=500)
|
|
||||||
self.exchange_hostname = args.exchange_hostname
|
self.exchange_hostname = args.exchange_hostname
|
||||||
self.port = args.port
|
self.port = args.port
|
||||||
exchange_socket = self._connect(add_socket_timeout=args.add_socket_timeout)
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
self.reader = exchange_socket.makefile("r", 1)
|
sock.connect((self.exchange_hostname, self.port))
|
||||||
self.writer = exchange_socket
|
self.reader = sock.makefile("r", 1)
|
||||||
|
self.writer = sock
|
||||||
self._write_message({"type": "hello", "team": team_name.upper()})
|
self._write({"type": "hello", "team": team_name})
|
||||||
|
|
||||||
def read_message(self):
|
def read_message(self):
|
||||||
"""Read a single message from the exchange"""
|
msg = json.loads(self.reader.readline())
|
||||||
message = json.loads(self.reader.readline())
|
if "dir" in msg:
|
||||||
if "dir" in message:
|
msg["dir"] = Dir(msg["dir"])
|
||||||
message["dir"] = Dir(message["dir"])
|
return msg
|
||||||
return message
|
|
||||||
|
|
||||||
def send_add_message(
|
def send_add_message(self, order_id, symbol, dir, price, size):
|
||||||
self, order_id: int, symbol: str, dir: Dir, price: int, size: int
|
self._write({
|
||||||
):
|
|
||||||
"""Add a new order"""
|
|
||||||
self._write_message(
|
|
||||||
{
|
|
||||||
"type": "add",
|
"type": "add",
|
||||||
"order_id": order_id,
|
"order_id": order_id,
|
||||||
"symbol": symbol,
|
"symbol": symbol,
|
||||||
"dir": dir,
|
"dir": dir,
|
||||||
"price": price,
|
"price": price,
|
||||||
"size": size,
|
"size": size,
|
||||||
"tif": "DAY", # 설명서 필수 필드: DAY or IOC
|
"tif": "DAY"
|
||||||
}
|
})
|
||||||
)
|
|
||||||
|
|
||||||
def send_convert_message(self, order_id: int, symbol: str, dir: Dir, size: int):
|
def _write(self, msg):
|
||||||
"""Convert between related symbols"""
|
self.writer.send((json.dumps(msg) + "\n").encode())
|
||||||
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."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_arguments():
|
def parse_arguments():
|
||||||
test_exchange_port_offsets = {"prod-like": 0, "slower": 1, "empty": 2}
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--test", required=True)
|
||||||
parser = argparse.ArgumentParser(description="Trade on an ETC exchange!")
|
|
||||||
exchange_address_group = parser.add_mutually_exclusive_group(required=True)
|
|
||||||
exchange_address_group.add_argument(
|
|
||||||
"--production", action="store_true", help="Connect to the production exchange."
|
|
||||||
)
|
|
||||||
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
|
|
||||||
|
|
||||||
if args.production:
|
|
||||||
args.exchange_hostname = "production"
|
|
||||||
args.port = 25000
|
|
||||||
elif args.test:
|
|
||||||
args.exchange_hostname = "test-exch-" + team_name
|
args.exchange_hostname = "test-exch-" + team_name
|
||||||
args.port = 22000 + test_exchange_port_offsets[args.test]
|
args.port = 22000
|
||||||
if args.test == "empty":
|
|
||||||
args.add_socket_timeout = False
|
|
||||||
elif args.specific_address:
|
|
||||||
args.exchange_hostname, port = args.specific_address.split(":")
|
|
||||||
args.port = int(port)
|
|
||||||
|
|
||||||
return args
|
return args
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# Check that [team_name] has been updated.
|
|
||||||
assert team_name != "REPLAC" + "EME", (
|
|
||||||
"Please put your team name in the variable [team_name]."
|
|
||||||
)
|
|
||||||
|
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user