add: bot bond selling
This commit is contained in:
233
bot bond sell.py
233
bot bond sell.py
@@ -1,32 +1,3 @@
|
|||||||
#!/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
|
|
||||||
from collections import deque
|
|
||||||
from enum import Enum
|
|
||||||
import time
|
|
||||||
import socket
|
|
||||||
import json
|
|
||||||
|
|
||||||
# ~~~~~============== CONFIGURATION ==============~~~~~
|
|
||||||
# Replace "REPLACEME" with your team name!
|
|
||||||
team_name = "HanyangFloorFunction"
|
|
||||||
|
|
||||||
# ~~~~~============== 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()
|
||||||
|
|
||||||
@@ -43,9 +14,9 @@ def main():
|
|||||||
# unlikely it will be traded against. Maybe there is a better price to
|
# unlikely it will be traded against. Maybe there is a better price to
|
||||||
# pick? Also, you will need to send more orders over time.
|
# pick? Also, you will need to send more orders over time.
|
||||||
# --- BOND 마켓 메이킹 설정 ---
|
# --- BOND 마켓 메이킹 설정 ---
|
||||||
FAIR_VALUE = 1000 # BOND fair value (고정, 설명서 명시)
|
FAIR_VALUE = 1000 # BOND fair value (고정)
|
||||||
ORDER_SIZE = 10 # 주문당 수량
|
ORDER_SIZE = 100 # 한 번에 최대한 많이 (포지션 한도 = 100)
|
||||||
MAX_POSITION = 100 # 포지션 한도 (설명서: BOND limit = 100)
|
MAX_POSITION = 100 # 최대 포지션 한도
|
||||||
REFRESH_INTERVAL = 5.0 # 주문 갱신 주기 (초)
|
REFRESH_INTERVAL = 5.0 # 주문 갱신 주기 (초)
|
||||||
|
|
||||||
position = 0 # 현재 BOND 포지션
|
position = 0 # 현재 BOND 포지션
|
||||||
@@ -53,57 +24,50 @@ def main():
|
|||||||
active_orders = {} # {order_id: {"dir": ..., "price": ...}}
|
active_orders = {} # {order_id: {"dir": ..., "price": ...}}
|
||||||
market_open = False # 시장 open 여부 (open 전에는 주문 불가)
|
market_open = False # 시장 open 여부 (open 전에는 주문 불가)
|
||||||
|
|
||||||
# 호가창에서 파악한 BOND 최우선 bid/ask
|
|
||||||
bond_best_bid = None
|
|
||||||
bond_best_ask = None
|
|
||||||
|
|
||||||
def next_id():
|
def next_id():
|
||||||
nonlocal order_id
|
nonlocal order_id
|
||||||
order_id += 1
|
order_id += 1
|
||||||
return order_id
|
return order_id
|
||||||
|
|
||||||
def cancel_all_bond_orders():
|
def cancel_all_bond_orders():
|
||||||
"""활성 BOND 주문 전부 취소"""
|
"""BOND 주문 전부 한 번에 취소 (mass_cancel 사용)"""
|
||||||
for oid in list(active_orders.keys()):
|
exchange.send_mass_cancel_message(symbol="BOND")
|
||||||
exchange.send_cancel_message(oid)
|
active_orders.clear()
|
||||||
active_orders.pop(oid, None)
|
|
||||||
|
|
||||||
def place_bond_orders():
|
def place_bond_orders():
|
||||||
"""호가창 기반으로 경쟁자보다 1틱 더 좋은 가격에 주문"""
|
"""포지션 한도 안에서 bid/ask 양방향 주문"""
|
||||||
if not market_open:
|
if not market_open:
|
||||||
return
|
return
|
||||||
|
|
||||||
cancel_all_bond_orders()
|
cancel_all_bond_orders()
|
||||||
|
|
||||||
# 호가창 정보가 없으면 기본값 사용
|
# 포지션이 음수면 매수 가격을 올려서 빨리 사들임
|
||||||
best_bid = bond_best_bid if bond_best_bid is not None else 999
|
# 포지션이 양수면 매도 가격을 내려서 빨리 팖
|
||||||
best_ask = bond_best_ask if bond_best_ask is not None else 1001
|
skew = position // 10 # 포지션 10마다 1틱 조정
|
||||||
|
|
||||||
# 경쟁자보다 1틱 더 좋은 가격, 단 fair value를 절대 넘지 않음
|
buy_price = min(FAIR_VALUE - 1 + skew, FAIR_VALUE - 1) # 최대 999
|
||||||
# 매수: 경쟁자 bid + 1 (단, fair value - 1 이하)
|
sell_price = max(FAIR_VALUE + 1 + skew, FAIR_VALUE + 1) # 최소 1001
|
||||||
# 매도: 경쟁자 ask - 1 (단, fair value + 1 이상)
|
|
||||||
buy_price = min(best_bid + 1, FAIR_VALUE - 1) # 최대 999
|
|
||||||
sell_price = max(best_ask - 1, FAIR_VALUE + 1) # 최소 1001
|
|
||||||
|
|
||||||
print(f" BOND 주문 → 매수: {buy_price}, 매도: {sell_price}")
|
buy_size = min(ORDER_SIZE, MAX_POSITION - position)
|
||||||
|
sell_size = min(ORDER_SIZE, MAX_POSITION + position)
|
||||||
|
|
||||||
# 포지션이 한도에 걸리면 한쪽 방향 주문 스킵
|
if buy_size > 0:
|
||||||
if position < MAX_POSITION:
|
|
||||||
bid = next_id()
|
bid = next_id()
|
||||||
exchange.send_add_message(
|
exchange.send_add_message(
|
||||||
order_id=bid, symbol="BOND",
|
order_id=bid, symbol="BOND",
|
||||||
dir=Dir.BUY, price=buy_price, size=ORDER_SIZE
|
dir=Dir.BUY, price=buy_price, size=buy_size
|
||||||
)
|
)
|
||||||
active_orders[bid] = {"dir": Dir.BUY, "price": buy_price}
|
active_orders[bid] = {"dir": Dir.BUY, "price": buy_price}
|
||||||
|
|
||||||
if position > -MAX_POSITION:
|
if sell_size > 0:
|
||||||
ask = next_id()
|
ask = next_id()
|
||||||
exchange.send_add_message(
|
exchange.send_add_message(
|
||||||
order_id=ask, symbol="BOND",
|
order_id=ask, symbol="BOND",
|
||||||
dir=Dir.SELL, price=sell_price, size=ORDER_SIZE
|
dir=Dir.SELL, price=sell_price, size=sell_size
|
||||||
)
|
)
|
||||||
active_orders[ask] = {"dir": Dir.SELL, "price": sell_price}
|
active_orders[ask] = {"dir": Dir.SELL, "price": sell_price}
|
||||||
|
|
||||||
|
print(f" BOND 주문 → 매수: {buy_price} x{buy_size}, 매도: {sell_price} x{sell_size}, 포지션: {position}")
|
||||||
# Set up some variables to track the bid and ask price of a symbol. Right
|
# Set up some variables to track the bid and ask price of a symbol. Right
|
||||||
# now this doesn't track much information, but it's enough to get a sense
|
# now this doesn't track much information, but it's enough to get a sense
|
||||||
# of the VALE market.
|
# of the VALE market.
|
||||||
@@ -156,20 +120,8 @@ def main():
|
|||||||
position += qty
|
position += qty
|
||||||
else:
|
else:
|
||||||
position -= qty
|
position -= qty
|
||||||
print(f" → BOND position: {position}")
|
|
||||||
place_bond_orders()
|
place_bond_orders()
|
||||||
elif message["type"] == "book":
|
elif message["type"] == "book":
|
||||||
if message["symbol"] == "BOND":
|
|
||||||
# BOND 호가창 업데이트 → 가격 재계산 후 주문 갱신
|
|
||||||
bond_best_bid = message["buy"][0][0] if message["buy"] else None
|
|
||||||
bond_best_ask = message["sell"][0][0] if message["sell"] else None
|
|
||||||
|
|
||||||
# 호가창이 바뀔 때마다 주문 갱신 (단, rate limit 주의)
|
|
||||||
now = time.time()
|
|
||||||
if now - last_refresh > REFRESH_INTERVAL:
|
|
||||||
last_refresh = now
|
|
||||||
place_bond_orders()
|
|
||||||
|
|
||||||
if message["symbol"] == "VALE":
|
if message["symbol"] == "VALE":
|
||||||
|
|
||||||
def best_price(side):
|
def best_price(side):
|
||||||
@@ -190,147 +142,8 @@ def main():
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 주기적으로 BOND 주문 갱신 (주문 만료 방지)
|
||||||
# ~~~~~============== 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):
|
|
||||||
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):
|
|
||||||
"""Read a single message from the exchange"""
|
|
||||||
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
|
|
||||||
):
|
|
||||||
"""Add a new order"""
|
|
||||||
self._write_message(
|
|
||||||
{
|
|
||||||
"type": "add",
|
|
||||||
"order_id": order_id,
|
|
||||||
"symbol": symbol,
|
|
||||||
"dir": dir,
|
|
||||||
"price": price,
|
|
||||||
"size": size,
|
|
||||||
"tif": "DAY", # 설명서 필수 필드: DAY or IOC
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
def send_convert_message(self, order_id: int, symbol: str, dir: Dir, size: int):
|
|
||||||
"""Convert between related symbols"""
|
|
||||||
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()
|
now = time.time()
|
||||||
self.message_timestamps.append(now)
|
if now - last_refresh > REFRESH_INTERVAL:
|
||||||
if len(
|
last_refresh = now
|
||||||
self.message_timestamps
|
place_bond_orders()
|
||||||
) == 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.",
|
|
||||||
)
|
|
||||||
|
|
||||||
# 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.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__":
|
|
||||||
# Check that [team_name] has been updated.
|
|
||||||
assert team_name != "REPLAC" + "EME", (
|
|
||||||
"Please put your team name in the variable [team_name]."
|
|
||||||
)
|
|
||||||
|
|
||||||
main()
|
|
||||||
Reference in New Issue
Block a user