dev qol: Add trade_client_cli.py to test md/exe plugins
Independent of sparkd
This commit is contained in:
1 parent
01de13bb43
commit
06ad3a1d9e
3 files changed
+438
No files matched your search
@@ -0,0 +1,102 @@
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
|
||||
|
||||
class ConsoleTableColumn:
|
||||
def __init__(self, id, header: str, data_format=None, width=None):
|
||||
self.id = id
|
||||
self.header = header
|
||||
self.data_format = data_format
|
||||
self.width = width or len(header)
|
||||
|
||||
|
||||
class ConsoleTable:
|
||||
ESC = "\033["
|
||||
|
||||
def __init__(self, columns: list[ConsoleTableColumn], col_separator=" "):
|
||||
self.columns = columns
|
||||
self.col_separator = col_separator
|
||||
self.header_row = col_separator.join(map(lambda c: c.header, columns))
|
||||
self._pending_data = None
|
||||
self._is_running = False
|
||||
|
||||
def move_cursor(self, row, col):
|
||||
sys.stdout.write(f"{ConsoleTable.ESC}{row};{col}H")
|
||||
|
||||
def clear_screen(self):
|
||||
sys.stdout.write(f"{ConsoleTable.ESC}2J")
|
||||
|
||||
def hide_cursor(self):
|
||||
sys.stdout.write(f"{ConsoleTable.ESC}?25l")
|
||||
|
||||
def show_cursor(self):
|
||||
sys.stdout.write(f"{ConsoleTable.ESC}?25h")
|
||||
|
||||
def print_table(self, rows):
|
||||
print(self.header_row)
|
||||
print("-" * len(self.header_row))
|
||||
for row in rows:
|
||||
cells = []
|
||||
for col in self.columns:
|
||||
val = row[col.id]
|
||||
cell = f"{val:{col.data_format}}" if col.data_format else str(val)
|
||||
len_diff = col.width - len(cell)
|
||||
if len_diff > 0:
|
||||
cell += " " * len_diff
|
||||
else:
|
||||
leading_ws_count = 0
|
||||
while (
|
||||
leading_ws_count < -len_diff and cell[leading_ws_count] == " "
|
||||
):
|
||||
leading_ws_count += 1
|
||||
if leading_ws_count > 0:
|
||||
cell = cell[leading_ws_count:]
|
||||
len_diff = col.width - len(cell)
|
||||
if len_diff < 0:
|
||||
cell = cell[:len_diff]
|
||||
cells.append(cell)
|
||||
print(self.col_separator.join(cells))
|
||||
|
||||
def set_data(self, data):
|
||||
self._pending_data = data
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
self.clear_screen()
|
||||
self.hide_cursor()
|
||||
while self._is_running:
|
||||
if self._pending_data:
|
||||
# move to bottom of screen
|
||||
self.move_cursor(1, 1)
|
||||
self.print_table(self._pending_data)
|
||||
self._pending_data = None
|
||||
sys.stdout.flush()
|
||||
time.sleep(0.5)
|
||||
finally:
|
||||
self.show_cursor()
|
||||
|
||||
def run_in_background(self):
|
||||
def run_wrapper():
|
||||
self.run()
|
||||
|
||||
self._is_running = True
|
||||
threading.Thread(target=run_wrapper, daemon=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cols = [
|
||||
ConsoleTableColumn("symbol", f"{'Symbol':<10}"),
|
||||
ConsoleTableColumn("bid", f"{'Bid':>10}", data_format=">10"),
|
||||
ConsoleTableColumn("ask", f"{'Ask':>10}", data_format=">10"),
|
||||
]
|
||||
bbo_data = [
|
||||
{"symbol": "BTCUSDT", "bid": 104500.00, "ask": 105000.00},
|
||||
{"symbol": "BNBUSDT", "bid": 645.00, "ask": 650.00},
|
||||
]
|
||||
try:
|
||||
table = ConsoleTable(cols)
|
||||
table.print_table(bbo_data)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
@@ -21,6 +21,8 @@ from python_interop_module import (
|
||||
PySpot,
|
||||
)
|
||||
|
||||
FLOAT_RE = r"[+-]?(?:(?:\d+\.\d*)|(?:\.\d+)|(?:\d+))(?:[eE][+-]?\d+)?"
|
||||
|
||||
|
||||
class JsonElement:
|
||||
def __init__(self, value):
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
import argparse
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from rich.console import Console
|
||||
from typing import Optional
|
||||
|
||||
from bybit_execution_gateway import BybitExecutionGateway
|
||||
from prompt_toolkit import PromptSession
|
||||
from prompt_toolkit.completion import Completer, Completion
|
||||
from prompt_toolkit.patch_stdout import patch_stdout
|
||||
from python_interop_module import (
|
||||
ExecutionGateway,
|
||||
MdProvider,
|
||||
PyBookLevel,
|
||||
PyBookList,
|
||||
PyCreateOrderRequest,
|
||||
)
|
||||
from console_table import ConsoleTable, ConsoleTableColumn
|
||||
from fake_execution_gateway_bridge import FakeExecutionGatewayBridge
|
||||
from fake_md_bridge import FakeMdBridge
|
||||
from bybit_md_provider import BybitMdProvider
|
||||
from spark_core import (
|
||||
ConsoleLogFormatter,
|
||||
FLOAT_RE,
|
||||
)
|
||||
|
||||
# Simulated trading data
|
||||
symbols = ["BTCUSD", "ETHUSD", "AAPL", "GOOG"]
|
||||
orders = ["12345", "67890", "24680"]
|
||||
|
||||
|
||||
class TradingCompleter(Completer):
|
||||
def get_completions(self, document, complete_event):
|
||||
words = document.text_before_cursor.strip().split()
|
||||
if not words:
|
||||
# First word: suggest top-level commands
|
||||
for cmd in ["buy", "sell", "cancel", "status", "exit"]:
|
||||
yield Completion(cmd, start_position=0)
|
||||
elif words[0] in ["buy", "sell"]:
|
||||
if len(words) == 1:
|
||||
# After 'buy' or 'sell', suggest symbols
|
||||
for sym in symbols:
|
||||
yield Completion(sym, start_position=0)
|
||||
elif len(words) == 2:
|
||||
# Suggest example quantities
|
||||
for qty in ["0.1", "1.0", "10.0"]:
|
||||
yield Completion(qty, start_position=0)
|
||||
elif words[0] == "cancel":
|
||||
if len(words) == 1:
|
||||
for oid in orders:
|
||||
yield Completion(oid, start_position=0)
|
||||
|
||||
|
||||
# Logging setup
|
||||
class PromptToolkitHandler(logging.Handler):
|
||||
def emit(self, record):
|
||||
from prompt_toolkit.shortcuts import print_formatted_text
|
||||
|
||||
msg = self.format(record)
|
||||
print_formatted_text(msg)
|
||||
|
||||
|
||||
def trading_client(logger):
|
||||
i = 0
|
||||
while True:
|
||||
time.sleep(1.5)
|
||||
logger.info(f"[MarketData] Tick {i}")
|
||||
i += 1
|
||||
|
||||
|
||||
# TRADE_REQ_RE = re.compile(f"\\[a-zA-Z0-9-\\](buy|sell) ([a-zA-Z]{{3,8}}) ({FLOAT_RE}) @ ({FLOAT_RE})")
|
||||
CREATE_ORDER_RE = re.compile(
|
||||
f"(buy|sell) ([a-zA-Z]{{3,8}}) ({FLOAT_RE}) @ ({FLOAT_RE})"
|
||||
)
|
||||
CHANGE_ORDER_PRICE_RE = re.compile(
|
||||
f"(ch|change|modify) ([a-zA-Z0-9]+) (p|px|price) to ({FLOAT_RE})"
|
||||
)
|
||||
CHANGE_ORDER_QUANTITY_RE = re.compile(
|
||||
f"(ch|change|modify) ([a-zA-Z0-9]+) (q|qty|quantity) to ({FLOAT_RE})"
|
||||
)
|
||||
CHANGE_ORDER_RE = re.compile(
|
||||
f"(ch|change|modify) ([a-zA-Z0-9]+) to ({FLOAT_RE}) @ ({FLOAT_RE})"
|
||||
)
|
||||
CANCEL_SYMBOL_ORDERS_RE = re.compile("(cancel|cxl) all ([a-zA-Z0-9]+)")
|
||||
CANCEL_ORDER_RE = re.compile("(cancel|cxl) ([a-zA-Z0-9]+)")
|
||||
|
||||
|
||||
class OrderReqParser:
|
||||
def __init__(self, venue: str):
|
||||
self.id_counter = 1
|
||||
self.venue = venue
|
||||
pass
|
||||
|
||||
def parse_create_req(self, input_str: str):
|
||||
m = re.match(CREATE_ORDER_RE, input_str)
|
||||
if not m:
|
||||
return None
|
||||
grps = m.groups()
|
||||
if len(grps) != 4:
|
||||
return None
|
||||
side, sec, qty_s, px_s = grps
|
||||
qty = float(qty_s)
|
||||
px = float(px_s)
|
||||
req = PyCreateOrderRequest()
|
||||
req.set_exchange_security_id(sec)
|
||||
req.set_is_buy(side.startswith("b"))
|
||||
req.set_key(self.id_counter)
|
||||
req.set_order_type("LIMIT")
|
||||
req.set_price(px)
|
||||
req.set_quantity(qty)
|
||||
req.set_time_in_force("GTC")
|
||||
req.set_venue(self.venue)
|
||||
self.id_counter += 1
|
||||
return req
|
||||
|
||||
def parse_modify_req(self, input_str: str):
|
||||
m = re.match(CHANGE_ORDER_RE, input_str)
|
||||
if not m:
|
||||
return None
|
||||
grps = m.groups()
|
||||
if len(grps) != 4:
|
||||
return None
|
||||
|
||||
|
||||
class VenueService:
|
||||
def __init__(
|
||||
self,
|
||||
venue: str,
|
||||
logger: logging.Logger,
|
||||
is_execution_enabled=False,
|
||||
is_md_enabled=False,
|
||||
is_md_ticker_enabled=False,
|
||||
):
|
||||
self.venue = venue
|
||||
self.logger = logger
|
||||
self.md_provider: Optional[MdProvider] = None
|
||||
self.execution_gw: Optional[ExecutionGateway] = None
|
||||
if is_md_enabled:
|
||||
match venue.lower():
|
||||
case "bybit":
|
||||
self.md_provider = BybitMdProvider()
|
||||
case _:
|
||||
pass
|
||||
if is_execution_enabled:
|
||||
match venue.lower():
|
||||
case "bybit":
|
||||
self.execution_gw = BybitExecutionGateway()
|
||||
case _:
|
||||
pass
|
||||
if self.md_provider:
|
||||
self.md_provider_bridge = (
|
||||
BboSink(venue) if is_md_ticker_enabled else FakeMdBridge(logger)
|
||||
)
|
||||
if self.execution_gw:
|
||||
self.execution_gw_bridge = FakeExecutionGatewayBridge(logger)
|
||||
|
||||
def create_order(self, req):
|
||||
if self.execution_gw:
|
||||
self.execution_gw.create_order(req)
|
||||
else:
|
||||
self.logger.warning("Execution not enabled for venue '%s'" % self.venue)
|
||||
|
||||
def start(self):
|
||||
if self.md_provider:
|
||||
self.md_provider.start(self.md_provider_bridge) # type: ignore
|
||||
if self.execution_gw:
|
||||
self.execution_gw.start(self.execution_gw_bridge) # type: ignore
|
||||
|
||||
def stop(self):
|
||||
if self.md_provider:
|
||||
self.md_provider.stop()
|
||||
if self.execution_gw:
|
||||
self.execution_gw.stop()
|
||||
|
||||
def __enter__(self):
|
||||
self.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.stop()
|
||||
|
||||
|
||||
class BboSink:
|
||||
def __init__(self, name: str):
|
||||
self.name = name
|
||||
self.bbo = {}
|
||||
|
||||
def on_books(self, bks: PyBookList):
|
||||
for bk in bks:
|
||||
bids = bk.bids()
|
||||
asks = bk.asks()
|
||||
b = bids.get_level(0) if len(bids) > 0 else PyBookLevel()
|
||||
a = asks.get_level(0) if len(asks) > 0 else PyBookLevel()
|
||||
self.bbo[bk.exchange_security_id()] = b, a
|
||||
|
||||
def on_securities(self, v):
|
||||
pass
|
||||
|
||||
def on_trades(self, v):
|
||||
pass
|
||||
|
||||
|
||||
def run(
|
||||
venues: list[str],
|
||||
is_md_enabled=False,
|
||||
is_execution_enabled=False,
|
||||
is_md_ticker_enabled=False,
|
||||
):
|
||||
logger = logging.getLogger()
|
||||
# In md ticker mode, we print bbo to a static table in the console. We only log errors in
|
||||
# this mode to reduce disruptions in the table.
|
||||
logger.setLevel(logging.ERROR if is_md_ticker_enabled else logging.INFO)
|
||||
handler = PromptToolkitHandler()
|
||||
handler.setFormatter(ConsoleLogFormatter("Gen"))
|
||||
logger.addHandler(handler)
|
||||
|
||||
svcs = {
|
||||
v: VenueService(
|
||||
v,
|
||||
logger,
|
||||
is_execution_enabled=is_execution_enabled,
|
||||
is_md_enabled=is_md_enabled,
|
||||
is_md_ticker_enabled=is_md_ticker_enabled,
|
||||
)
|
||||
for v in venues
|
||||
}
|
||||
|
||||
for _, svc in svcs.items():
|
||||
svc.start()
|
||||
|
||||
if is_execution_enabled:
|
||||
session = PromptSession(
|
||||
completer=TradingCompleter(),
|
||||
bottom_toolbar=lambda: "Type a command like 'buy BTCUSD 1.0' or 'cancel <id>'",
|
||||
)
|
||||
|
||||
def parse_req(cmd):
|
||||
try:
|
||||
req = req_parser.parse_create_req(cmd)
|
||||
if req is None:
|
||||
logger.error("Failed to parse OrderReq")
|
||||
return req
|
||||
except Exception:
|
||||
logger.error("[UserInputParseError] %s", exc_info=True)
|
||||
return None
|
||||
|
||||
with patch_stdout():
|
||||
req_parser = OrderReqParser("BYBIT")
|
||||
while True:
|
||||
try:
|
||||
cmd = session.prompt("> ")
|
||||
if cmd.strip().lower() == "exit":
|
||||
break
|
||||
req = parse_req(cmd)
|
||||
if not req:
|
||||
continue
|
||||
svc = svcs.get(req.venue().lower())
|
||||
if svc:
|
||||
svc.create_order(req)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
# Allows Ctrl+C to cancel current input
|
||||
continue
|
||||
except EOFError:
|
||||
# Allows Ctrl+D to exit
|
||||
break
|
||||
else:
|
||||
ctable = ConsoleTable(
|
||||
[
|
||||
ConsoleTableColumn("symbol", f"{'Symbol':<10}"),
|
||||
ConsoleTableColumn("bid", f"{'Bid':>10}", data_format=">10"),
|
||||
ConsoleTableColumn("ask", f"{'Ask':>10}", data_format=">10"),
|
||||
]
|
||||
)
|
||||
ctable.clear_screen()
|
||||
ctable.hide_cursor()
|
||||
console = Console()
|
||||
with console.screen():
|
||||
while True:
|
||||
curr_data = {}
|
||||
for _, svc in svcs.items():
|
||||
if isinstance(svc.md_provider_bridge, BboSink):
|
||||
curr_data = [
|
||||
{
|
||||
"symbol": sym,
|
||||
"bid": bbo[0].price(),
|
||||
"ask": bbo[1].price(),
|
||||
}
|
||||
for sym, bbo in svc.md_provider_bridge.bbo.items()
|
||||
]
|
||||
ctable.move_cursor(1, 1)
|
||||
ctable.print_table(curr_data)
|
||||
sys.stdout.flush()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def _get_arg_parser():
|
||||
p = argparse.ArgumentParser(description="Run python md and execution plugins")
|
||||
p.add_argument(
|
||||
"--md", dest="is_md_enabled", action="store_true", help="Run md plugin(s)"
|
||||
)
|
||||
p.add_argument(
|
||||
"--md-ticker",
|
||||
dest="is_md_ticker_enabled",
|
||||
action="store_true",
|
||||
help="Run md plugin(s), display ticker data in table",
|
||||
)
|
||||
p.add_argument(
|
||||
"--exe",
|
||||
dest="is_execution_enabled",
|
||||
action="store_true",
|
||||
help="Run execution gateway plugin(s)",
|
||||
)
|
||||
p.add_argument(
|
||||
"venues", nargs="+", help="Venues to run (e.g., 'Bybit', 'Gateio', etc.)"
|
||||
)
|
||||
p.set_defaults(
|
||||
venues=[],
|
||||
is_md_enabled=False,
|
||||
is_execution_enabled=False,
|
||||
is_md_ticker_enabled=False,
|
||||
)
|
||||
return p
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = _get_arg_parser().parse_args()
|
||||
try:
|
||||
run(**vars(args))
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
Reference in new issue
Block a user