Files
spark/src/lib_python_execution

lib_python_execution

This library binds c++ execution gateways to python modules which can be loaded at runtime.

Dependencies

Notes

  • Because this is python, order/security enums are represented as strings

    • Parsing is NOT case sensitive (though it is conventional to use UPPER_CASE strings)
    • Type name prefixes (SECURITY_TYPE_, VENUE_, SIDE_ etc.) are NOT required
    • Having said that, we recommend UPPER_CASE strings without the type prefix. Here are a few examples:
    Enum Examples
    OrderType "LIMIT", "MARKET"
    OrderStatus "NEW", "PARTIALLY_FILLED", "FILLED", "CANCELED"
    SecurityType "SPOT", "FUTURE", "OPTION"
    Venue "BYBIT", "GATEIO", "DERIBIT", "COINBASE"
    Side "BUY", "SELL"
  • All .py files in the python_execution_gateways dir are copied to a special plugins directory at build time, so they may be loaded at runtime.

  • For intellisense, symlink the .so and .pyi files in the python_execution_gateways dir

    These files are excluded from source control via .gitignore, so don't worry about accidentally checking them in

# Run in src/lib_python_execution/python_execution_gateways
ln -s ../../../build/sparkd-debug-clang/src/lib_python_execution/stubs/python_execution_module.pyi .
ln -s ../../../build/sparkd-debug-clang/src/lib_python_execution/python_execution_module.cpython-310-x86_64-linux-gnu.so .

Example

import json
import logging
import threading
from typing import Optional
import python_execution_module as pyexe
from py_execution_utils import configure_logger, run_websocket


class ExecutionGatewayExample(pyexe.ExecutionGateway):
    def __init__(self):
        super(ExecutionGatewayExample, self).__init__()
        self.bridge: Optional[pyexe.ExecutionGatewayBridge] = None
        self.stop_event = threading.Event()
        # Logs to file /home/bts/sparkdata/data/logging.sparkd/<name>_log
        # (name is 'py_execution_example' in this case).
        self.logger = configure_logger(logging.getLogger("py_execution_example"))

    def start_impl(self, bridge: pyexe.ExecutionGatewayBridge):
        def on_message(msg: str):
            # This example assumes msg has a particular structure. Obviously, each exchange is
            # different, so this isn't a one-size-fits-all solution.
            data = json.loads(msg)
            event = data.get("e")
            if event == "executionReport":
                upd = json.loads(str(msg))
                er = pyexe.PyExecutionReport()
                # TODO: Resolve exch key to bts key
                # er.set_key(bts_key)
                er.set_exchange_security_id(upd["s"])
                er.set_security_type("SPOT")
                er.set_is_buy(upd["S"] == "BUY")
                er.set_price(float(upd["p"]))
                er.set_quantity(float(upd["q"]))
                er.set_last_filled_price(upd["L"])
                er.set_last_filled_quantity(upd["l"])
                # ...
                # TODO: Fill in remaining fields
                bridge.on_execution_report(er)
            else:
                self.logger.error("Unknown event %s. Full msg %s" % (event, msg))

        run_websocket(
            "wss://some_exch.com/ws", self.stop_event, self.logger, on_message
        )

    def start(self, bridge: pyexe.ExecutionGatewayBridge):
        # Connect to the exchange, subscribe to order updates, etc. Don't block this thread.
        # Spawn new thread(s) for long running operations websocket msg loops, ping loops, etc.
        self.logger.info("Starting ExecutionGatewayExample")
        self.bridge = bridge
        self.ws_thread = threading.Thread(target=lambda: self.start_impl(bridge))
        self.ws_thread.start()

    def stop(self):
        self.logger.info("Stopping ExecutionGatewayExample")
        self.stop_event.set()

    def create_order(self, req: pyexe.PyCreateOrderRequest):
        self.logger.info("create_order. %s" % str(req))
        # TODO: Send REST or ws request

    def cancel_replace_order(self, req: pyexe.PyCancelReplaceOrderRequest):
        self.logger.info("cancel_replace_order. %s" % str(req))
        # TODO: Send REST or ws request

    def cancel_order(self, req: pyexe.PyCancelOrderRequest):
        self.logger.info("cancel_order. %s" % str(req))
        # TODO: Send REST or ws request