diff --git a/bot_x.py b/bot_x.py new file mode 100644 index 0000000..0e175c4 --- /dev/null +++ b/bot_x.py @@ -0,0 +1,684 @@ +#!/usr/bin/env python3 + +import argparse +from collections import deque +from enum import Enum +import time +import socket +import json +from state import StateManager +from order import OrderManager + + +class PriceHistory: + def __init__(self, maxlen=100): + self.prices = deque(maxlen=maxlen) + + def add(self, price): + if price is not None: + self.prices.append(price) + + def get_all(self): + return list(self.prices) + + def __len__(self): + return len(self.prices) + + +class TechnicalAnalyzer: + @staticmethod + def calculate_ema(prices, period): + if len(prices) < period: + return None + alpha = 2 / (period + 1) + ema = prices[0] + for price in prices[1:]: + ema = alpha * price + (1 - alpha) * ema + return ema + + @staticmethod + def calculate_rsi(prices, period=14): + if len(prices) < period + 1: + return None + gains = [] + losses = [] + for i in range(1, len(prices)): + diff = prices[i] - prices[i - 1] + if diff > 0: + gains.append(diff) + losses.append(0) + else: + gains.append(0) + losses.append(abs(diff)) + avg_gain = sum(gains[-period:]) / period + avg_loss = sum(losses[-period:]) / period + if avg_loss == 0: + return 100 + rs = avg_gain / avg_loss + return 100 - (100 / (1 + rs)) + + +class CrossEMAStrategy: + def __init__(self, fast_period=10, slow_period=30, rsi_period=14, + oversold=30, overbought=70, size=5): + self.fast_period = fast_period + self.slow_period = slow_period + self.rsi_period = rsi_period + self.oversold = oversold + self.overbought = overbought + self.size = size + self.price_histories = {} + self.last_signal = {} + + def register_symbol(self, symbol): + if symbol not in self.price_histories: + maxlen = max(self.slow_period, self.rsi_period) + 10 + self.price_histories[symbol] = PriceHistory(maxlen=maxlen) + self.last_signal[symbol] = None + + def update(self, symbol, price): + self.register_symbol(symbol) + self.price_histories[symbol].add(price) + + def get_signal(self, symbol): + history = self.price_histories[symbol] + prices = history.get_all() + + if len(prices) < self.slow_period: + return None, None, None + + fast_ema = TechnicalAnalyzer.calculate_ema(prices, self.fast_period) + slow_ema = TechnicalAnalyzer.calculate_ema(prices, self.slow_period) + rsi = TechnicalAnalyzer.calculate_rsi(prices, self.rsi_period) + + if fast_ema is None or slow_ema is None: + return None, None, None + + prev_fast = TechnicalAnalyzer.calculate_ema(prices[:-1], self.fast_period) + prev_slow = TechnicalAnalyzer.calculate_ema(prices[:-1], self.slow_period) + + if prev_fast is None or prev_slow is None: + return None, None, None + + signal = None + + if prev_fast <= prev_slow and fast_ema > slow_ema: + signal = "LONG" + elif prev_fast >= prev_slow and fast_ema < slow_ema: + signal = "SHORT" + + return signal, rsi, (fast_ema, slow_ema) + + def should_trade(self, symbol, rsi): + if rsi is None: + return True + if self.last_signal.get(symbol) == "LONG" and rsi > self.overbought: + return True + if self.last_signal.get(symbol) == "SHORT" and rsi < self.oversold: + return True + return False + + +team_name = "HanyangFloorFunction" + + +def main(): + args = parse_arguments() + + exchange = ExchangeConnection(args=args) + + hello_message = exchange.read_message() + print("First message from exchange:", hello_message) + + BOND_FAIR_VALUE = 1000 + BOND_ORDER_SIZE = 50 + XLF_CONVERSION_FEE = 100 + VALE_CONVERSION_FEE = 10 + VALE_ARB_SIZE = 10 + REFRESH_INTERVAL = 5.0 + + FAST_EMA_PERIOD = 10 + SLOW_EMA_PERIOD = 30 + EMA_SIZE = 5 + + xlf_state = "IDLE" + xlf_pending = {} + xlf_direction = None + xlf_arb_size = 0 + + vale_state = "IDLE" + vale_pending = {} + vale_direction = None + vale_arb_size = 0 + + state = StateManager() + om = OrderManager(exchange) + market_open = False + active_orders = {} + + last_refresh = time.time() + + cross_ema = CrossEMAStrategy( + fast_period=FAST_EMA_PERIOD, + slow_period=SLOW_EMA_PERIOD, + size=EMA_SIZE + ) + + symbols_for_ema = ["VALE", "VALBZ", "GS", "MS", "WFC", "XLF"] + for sym in symbols_for_ema: + cross_ema.register_symbol(sym) + + active_ema_orders = {} + + def next_id(): + return om.next_order() + + def cancel_all_bond_orders(): + for oid in list(active_orders.keys()): + om.cancel(oid) + active_orders.pop(oid, None) + + def cancel_ema_orders_for_symbol(symbol): + to_cancel = [oid for oid, info in active_ema_orders.items() if info["symbol"] == symbol] + for oid in to_cancel: + om.cancel(oid) + active_ema_orders.pop(oid, None) + + def place_bond_orders(): + if not market_open: + return + + 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 + adjustment = abs(position) // 5 + + if position < 0: + buy_size = min(base_size + adjustment, 100 - position) + sell_size = max(base_size - adjustment, 1) + elif position > 0: + buy_size = max(base_size - adjustment, 1) + sell_size = min(base_size + adjustment, 100 + position) + else: + buy_size = base_size + sell_size = base_size + + buy_size = max(0, min(buy_size, 100 - position)) + sell_size = max(0, min(sell_size, 100 + position)) + + if buy_size > 0: + bid = next_id() + exchange.send_add_message( + order_id=bid, symbol="BOND", + dir=Dir.BUY, price=buy_price, size=buy_size + ) + active_orders[bid] = {"dir": Dir.BUY, "price": buy_price} + + if sell_size > 0: + ask = next_id() + exchange.send_add_message( + order_id=ask, symbol="BOND", + dir=Dir.SELL, price=sell_price, size=sell_size + ) + active_orders[ask] = {"dir": Dir.SELL, "price": sell_price} + + print(f" BOND 주문 → 매수:{buy_price} x{buy_size}, 매도:{sell_price} x{sell_size}, 포지션:{position}") + + def try_xlf_arb(): + nonlocal xlf_state, xlf_direction, xlf_pending, xlf_arb_size + + 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 + + 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 + + profit1 = xlf_bid * 10 - basket_ask - XLF_CONVERSION_FEE + if profit1 > 0 and om.check_pos_limit("XLF"): + print(f" XLF 차익(바스켓→XLF) 시작, 예상수익:{profit1}") + cancel_all_bond_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)]: + oid = next_id() + exchange.send_add_message(oid, sym, Dir.BUY, state.ask_prices[sym], qty) + xlf_pending[oid] = qty + return + + profit2 = basket_bid - xlf_ask * 10 - XLF_CONVERSION_FEE + if profit2 > 0 and om.check_pos_limit("XLF"): + print(f" XLF 차익(XLF→바스켓) 시작, 예상수익:{profit2}") + cancel_all_bond_orders() + xlf_state = "BUYING_XLF" + xlf_direction = "XLF_TO_BASKET" + xlf_arb_size = 10 + xlf_pending.clear() + oid = next_id() + exchange.send_add_message(oid, "XLF", Dir.BUY, xlf_ask, 10) + xlf_pending[oid] = 10 + + def handle_xlf_fill(order_id, symbol, dir_, qty): + nonlocal xlf_state, xlf_pending + + 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" + exchange.send_convert_message(next_id(), "XLF", Dir.BUY, xlf_arb_size) + + elif xlf_state == "BUYING_XLF" and not xlf_pending: + print(" XLF 매수 완료 → 바스켓 변환 시작") + xlf_state = "CONVERTING" + exchange.send_convert_message(next_id(), "XLF", Dir.SELL, xlf_arb_size) + + def try_vale_arb(): + nonlocal vale_state, vale_direction, vale_pending, vale_arb_size + + if not market_open or vale_state != "IDLE": + return + + vale_bid = state.bid_prices["VALE"] + vale_ask = state.ask_prices["VALE"] + valbz_bid = state.bid_prices["VALBZ"] + valbz_ask = state.ask_prices["VALBZ"] + + if None in [vale_bid, vale_ask, valbz_bid, valbz_ask]: + return + + valbz_pos = om.positions["VALBZ"] + vale_pos = om.positions["VALE"] + + profit1 = vale_bid - valbz_ask - VALE_CONVERSION_FEE + arb_size1 = min(VALE_ARB_SIZE, 10 - valbz_pos) + if profit1 > 0 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 + arb_size2 = min(VALE_ARB_SIZE, 10 - vale_pos) + if profit2 > 0 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): + nonlocal vale_state, vale_pending + + 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" + exchange.send_convert_message(next_id(), "VALE", Dir.BUY, vale_arb_size) + + elif vale_state == "BUYING_VALE" and not vale_pending: + print(" VALE 매수 완료 → VALBZ 변환 시작") + vale_state = "CONVERTING" + exchange.send_convert_message(next_id(), "VALE", Dir.SELL, vale_arb_size) + + def try_ema_trade(): + if not market_open: + return + if xlf_state != "IDLE" or vale_state != "IDLE": + return + + for symbol in symbols_for_ema: + mid_price = state.get_mid_price(symbol) + if mid_price is None: + continue + + cross_ema.update(symbol, mid_price) + signal, rsi, ema_values = cross_ema.get_signal(symbol) + + if signal is None: + continue + + current_pos = om.positions[symbol] + limit = om.POSITIONS_LIMIT.get(symbol, 100) + remaining_capacity = limit - current_pos if signal == "LONG" else limit + current_pos + + if remaining_capacity <= 0: + continue + + size = min(cross_ema.size, remaining_capacity) + cancel_ema_orders_for_symbol(symbol) + + if signal == "LONG": + bid_price = state.bid_prices[symbol] + if bid_price is not None and om.check_pos_limit(symbol): + oid = next_id() + exchange.send_add_message(oid, symbol, Dir.BUY, bid_price + 1, size) + active_ema_orders[oid] = {"symbol": symbol, "dir": "LONG"} + cross_ema.last_signal[symbol] = "LONG" + print(f" CrossEMA: {symbol} LONG (bid:{bid_price}, rsi:{rsi:.1f}, ema:{ema_values})") + + elif signal == "SHORT": + ask_price = state.ask_prices[symbol] + if ask_price is not None and om.check_pos_limit(symbol): + oid = next_id() + exchange.send_add_message(oid, symbol, Dir.SELL, ask_price - 1, size) + active_ema_orders[oid] = {"symbol": symbol, "dir": "SHORT"} + cross_ema.last_signal[symbol] = "SHORT" + print(f" CrossEMA: {symbol} SHORT (ask:{ask_price}, rsi:{rsi:.1f}, ema:{ema_values})") + + vale_last_print_time = time.time() + + while True: + message = exchange.read_message() + + if message["type"] == "close": + print("The round has ended") + break + + elif message["type"] == "open": + print("Market opened:", message) + market_open = True + place_bond_orders() + + elif message["type"] == "error": + print(message) + + elif message["type"] == "reject": + print(message) + oid = message.get("order_id") + active_orders.pop(oid, None) + active_ema_orders.pop(oid, None) + if oid in xlf_pending: + print(" XLF 주문 reject → IDLE 복귀") + xlf_state = "IDLE" + xlf_pending.clear() + xlf_direction = None + 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": + if xlf_state == "CONVERTING": + 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 + 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 + 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": + print(" VALE 변환 완료 → 매도 시작") + if vale_direction == "VALBZ_TO_VALE": + om.positions["VALBZ"] -= vale_arb_size + om.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 + 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": + print(message) + qty = message["size"] + sym = message["symbol"] + dir_ = message["dir"] + oid = message["order_id"] + + if dir_ == Dir.BUY: + om.update_position(sym, oid, qty) + else: + om.update_position(sym, oid, -qty) + + print(f" 포지션 → {om.positions}") + + if sym == "BOND" and oid in active_orders: + active_orders.pop(oid, None) + place_bond_orders() + + if oid in active_ema_orders: + active_ema_orders.pop(oid, None) + + 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() + + 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": + 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": state.bid_prices["VALE"], + "vale_ask_price": state.ask_prices["VALE"], + }) + + if sym in ["BOND", "GS", "MS", "WFC", "XLF"]: + try_xlf_arb() + + if sym in ["VALE", "VALBZ"]: + try_vale_arb() + + if sym in symbols_for_ema: + try_ema_trade() + + now = time.time() + if now - last_refresh > REFRESH_INTERVAL: + last_refresh = now + place_bond_orders() + + +class Dir(str, Enum): + BUY = "BUY" + SELL = "SELL" + + +class ExchangeConnection: + def __init__(self, args): + self.message_timestamps = deque(maxlen=500) + self.exchange_hostname = args.exchange_hostname + self.port = args.port + exchange_socket = self._connect(add_socket_timeout=args.add_socket_timeout) + self.reader = exchange_socket.makefile("r", 1) + self.writer = exchange_socket + + self._write_message({"type": "hello", "team": team_name.upper()}) + + def read_message(self): + message = json.loads(self.reader.readline()) + if "dir" in message: + message["dir"] = Dir(message["dir"]) + return message + + def send_add_message( + self, order_id: int, symbol: str, dir: Dir, price: int, size: int + ): + self._write_message( + { + "type": "add", + "order_id": order_id, + "symbol": symbol, + "dir": dir, + "price": price, + "size": size, + "tif": "DAY", + } + ) + + def send_convert_message(self, order_id: int, symbol: str, dir: Dir, size: int): + self._write_message( + { + "type": "convert", + "order_id": order_id, + "symbol": symbol, + "dir": dir, + "size": size, + } + ) + + def send_cancel_message(self, order_id: int): + 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: + 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(): + test_exchange_port_offsets = {"prod-like": 0, "slower": 1, "empty": 2} + + 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.", + ) + + exchange_address_group.add_argument( + "--specific-address", type=str, metavar="HOST:PORT", help=argparse.SUPPRESS + ) + + 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.port = 22000 + test_exchange_port_offsets[args.test] + 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 + + +if __name__ == "__main__": + assert team_name != "REPLAC" + "EME", ( + "Please put your team name in the variable [team_name]." + ) + + main()