feat: Support python execution plugins
This commit is contained in:
1 parent
ca82042669
commit
b227fc6254
46 files changed
+4898
-33
No files matched your search
@@ -0,0 +1,191 @@
|
||||
BINANCE_USDS_FUTURES_PROD_URL="https://fapi.binance.com"
|
||||
BINANCE_USDS_FUTURES_PROD_WS_URL="wss://fstream.binance.com:443/ws"
|
||||
|
||||
BINANCE_USDS_FUTURES_DEV_URL="https://testnet.binancefuture.com"
|
||||
BINANCE_USDS_FUTURES_DEV_WS_URL="wss://stream.binancefuture.com:443/ws"
|
||||
BINANCE_USDS_FUTURES_DEV_API_KEY="b838c108cd2648e34a4f088a7fc635a9cbccf3c2faa6bcaabcb532ffacc087b0"
|
||||
BINANCE_USDS_FUTURES_DEV_SECRET_KEY="a68f0ab27403c42fa0306b6341b2ddd51d99ac42916f849404155449457d0492"
|
||||
|
||||
BINANCE_USDS_FUTURES_EXCHANGE_INFO_PATH="/fapi/v1/exchangeInfo"
|
||||
|
||||
BINANCE_USDS_FUTURES_USER_DATA_PATH="/ws/${LISTEN_KEY}"
|
||||
|
||||
BINANCE_USDS_FUTURES_DEPTH_PATH="/fapi/v1/depth"
|
||||
BINANCE_USDS_FUTURES_DEPTH_PARAMS='symbol=${SYMBOL}&limit=${LIMIT:-5}'
|
||||
|
||||
BINANCE_USDS_FUTURES_RECENT_TRADES_PATH="/fapi/v1/trades"
|
||||
BINANCE_USDS_FUTURES_RECENT_TRADES_PARAMS='symbol=${SYMBOL}&limit=${LIMIT:-500}'
|
||||
|
||||
BINANCE_USDS_FUTURES_HISTORICAL_TRADES_PATH="/fapi/v1/historicalTrades"
|
||||
BINANCE_USDS_FUTURES_HISTORICAL_TRADES_PARAMS='symbol=${SYMBOL}&limit=${LIMIT:-500}'
|
||||
|
||||
BINANCE_USDS_FUTURES_MARK_PRICE_PATH="/fapi/v1/premiumIndex"
|
||||
BINANCE_USDS_FUTURES_MARK_PRICE_PARAMS='symbol=${SYMBOL}'
|
||||
|
||||
BINANCE_USDS_FUTURES_PRICE_TICKER_PATH="/fapi/v1/ticker/price"
|
||||
BINANCE_USDS_FUTURES_PRICE_TICKER_PARAMS='symbol=${SYMBOL}'
|
||||
|
||||
BINANCE_USDS_FUTURES_BBO_PATH="/fapi/v1/ticker/bookTicker"
|
||||
BINANCE_USDS_FUTURES_BBO_PARAMS='symbol=${SYMBOL}'
|
||||
|
||||
BINANCE_USDS_FUTURES_OPEN_INTEREST_PATH="/dapi/v1/openInterest"
|
||||
BINANCE_USDS_FUTURES_OPEN_INTEREST_PARAMS='symbol=${SYMBOL}'
|
||||
|
||||
BINANCE_USDS_FUTURES_LONG_SHORT_RATIO_PATH="/futures/data/globalLongShortAccountRatio"
|
||||
BINANCE_USDS_FUTURES_LONG_SHORT_RATIO_PARAMS='symbol=${SYMBOL}&period=${PERIOD:-30}&limit=${LIMIT:-10}'
|
||||
|
||||
BINANCE_USDS_FUTURES_CREATE_ORDER_PATH="/fapi/v1/order"
|
||||
BINANCE_USDS_FUTURES_CREATE_ORDER_PARAMS='symbol=${SYMBOL}&side=${SIDE:-BUY}&type=${TYPE:-LIMIT}&timeInForce=${TIME_IN_FORCE:-GTC}&quantity=${QUANTITY:-OMIT}&price=${PRICE:-OMIT}&newClientOrderId=${NEW_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_CREATE_ORDER_METHOD="POST"
|
||||
BINANCE_USDS_FUTURES_CREATE_ORDER_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_MODIFY_ORDER_PATH="/fapi/v1/order"
|
||||
BINANCE_USDS_FUTURES_MODIFY_ORDER_PARAMS='symbol=${SYMBOL}&side=${SIDE:-BUY}&quantity=${QUANTITY:-OMIT}&price=${PRICE:-OMIT}&orderId=${ORDER_ID:-OMIT}&origClientOrderId=${ORIG_CLIENT_ORDER_ID:-OMIT}&priceMatch=${PRICE_MATCH:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_MODIFY_ORDER_METHOD="PUT"
|
||||
BINANCE_USDS_FUTURES_MODIFY_ORDER_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_CANCEL_ORDER_PATH="/fapi/v1/order"
|
||||
BINANCE_USDS_FUTURES_CANCEL_ORDER_PARAMS='symbol=${SYMBOL}&orderId=${ORDER_ID:-OMIT}&origClientOrderId=${ORIG_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_CANCEL_ORDER_METHOD="DELETE"
|
||||
BINANCE_USDS_FUTURES_CANCEL_ORDER_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_CANCEL_OPEN_ORDERS_PATH="/fapi/v1/allOpenOrders"
|
||||
BINANCE_USDS_FUTURES_CANCEL_OPEN_ORDERS_PARAMS='symbol=${SYMBOL}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_CANCEL_OPEN_ORDERS_METHOD="DELETE"
|
||||
BINANCE_USDS_FUTURES_CANCEL_OPEN_ORDERS_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_QUERY_ORDER_PATH="/fapi/v1/order"
|
||||
BINANCE_USDS_FUTURES_QUERY_ORDER_PARAMS='symbol=${SYMBOL}&orderId=${ORDER_ID:-OMIT}&origClientOrderId=${ORIG_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_QUERY_ORDER_METHOD="GET"
|
||||
BINANCE_USDS_FUTURES_QUERY_ORDER_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_QUERY_ALL_ORDERS_PATH="/fapi/v1/allOrders"
|
||||
BINANCE_USDS_FUTURES_QUERY_ALL_ORDERS_PARAMS='symbol=${SYMBOL}&orderId=${ORDER_ID:-OMIT}&startTime=${START_TIME:-OMIT}&endTime=${END_TIME:-OMIT}&limit=${LIMIT:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_QUERY_ALL_ORDERS_METHOD="GET"
|
||||
BINANCE_USDS_FUTURES_QUERY_ALL_ORDERS_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_OPEN_ORDERS_PATH="/fapi/v1/openOrders"
|
||||
BINANCE_USDS_FUTURES_OPEN_ORDERS_PARAMS='symbol=${SYMBOL:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_OPEN_ORDERS_METHOD="GET"
|
||||
BINANCE_USDS_FUTURES_OPEN_ORDERS_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_ACCOUNT_TRADES_PATH="/fapi/v1/userTrades"
|
||||
BINANCE_USDS_FUTURES_ACCOUNT_TRADES_PARAMS='symbol=${SYMBOL}&orderId=${ORDER_ID:-OMIT}&startTime=${START_TIME:-OMIT}&endTime=${END_TIME:-OMIT}&fromId=${FROM_ID:-OMIT}&limit=${LIMIT:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_ACCOUNT_TRADES_METHOD="GET"
|
||||
BINANCE_USDS_FUTURES_ACCOUNT_TRADES_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_POSITION_INFO_PATH="/fapi/v3/positionRisk"
|
||||
BINANCE_USDS_FUTURES_POSITION_INFO_PARAMS='symbol=${SYMBOL:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_USDS_FUTURES_POSITION_INFO_METHOD="GET"
|
||||
BINANCE_USDS_FUTURES_POSITION_INFO_IS_SIGNED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_LISTEN_KEY_PATH="/fapi/v1/listenKey"
|
||||
BINANCE_USDS_FUTURES_LISTEN_KEY_PARAMS=''
|
||||
BINANCE_USDS_FUTURES_LISTEN_KEY_METHOD="POST"
|
||||
BINANCE_USDS_FUTURES_LISTEN_KEY_IS_KEYED=1
|
||||
|
||||
BINANCE_USDS_FUTURES_REFRESH_LISTEN_KEY_PATH="/fapi/v1/listenKey"
|
||||
BINANCE_USDS_FUTURES_REFRESH_LISTEN_KEY_PARAMS='listenKey=${LISTEN_KEY:-OMIT}'
|
||||
BINANCE_USDS_FUTURES_REFRESH_LISTEN_KEY_METHOD="PUT"
|
||||
BINANCE_USDS_FUTURES_REFRESH_LISTEN_KEY_IS_KEYED=1
|
||||
|
||||
BINANCE_COIN_FUTURES_PROD_URL="https://dapi.binance.com"
|
||||
BINANCE_COIN_FUTURES_DEV_URL="https://testnet.binancefuture.com"
|
||||
BINANCE_COIN_FUTURES_EXCHANGE_INFO_PATH="/dapi/v1/exchangeInfo"
|
||||
BINANCE_COIN_FUTURES_DEPTH_PATH="/dapi/v1/depth"
|
||||
BINANCE_COIN_FUTURES_RECENT_TRADES_PATH="/dapi/v1/trades"
|
||||
BINANCE_COIN_FUTURES_HISTORICAL_TRADES_PATH="/dapi/v1/historicalTrades"
|
||||
BINANCE_COIN_FUTURES_MARK_PRICE_PATH="/dapi/v1/premiumIndex"
|
||||
BINANCE_COIN_FUTURES_PRICE_TICKER_PATH="/dapi/v1/ticker/price"
|
||||
BINANCE_COIN_FUTURES_BBO_PATH="/dapi/v1/ticker/bookTicker"
|
||||
BINANCE_COIN_FUTURES_OPEN_INTEREST_PATH="/dapi/v1/openInterest"
|
||||
BINANCE_COIN_FUTURES_LONG_SHORT_RATIO_PATH="/futures/data/globalLongShortAccountRatio"
|
||||
|
||||
BINANCE_PROD_URL="https://api.binance.com"
|
||||
BINANCE_PROD_WS_URL="wss://stream.binance.com:9443/ws"
|
||||
BINANCE_DEV_URL="https://testnet.binance.vision"
|
||||
BINANCE_DEV_WS_URL="wss://stream.testnet.binance.vision:9443/ws"
|
||||
BINANCE_DEV_API_KEY="QGwn9OVcpRTU76gOLV0gmQyVAJUmXW6w7H6y9tH8ctanzVnpZN1TP27liObE1Wsd"
|
||||
BINANCE_DEV_SECRET_KEY="7ohKg6X3DcsZMGaJmngC84EglsCFse9flMl8aKisa5FUY18LjGCEEdm0KEZljk9T"
|
||||
|
||||
BINANCE_EXCHANGE_INFO_PATH="/api/v3/exchangeInfo"
|
||||
|
||||
BINANCE_DEPTH_PATH="/api/v3/depth"
|
||||
BINANCE_DEPTH_PARAMS='symbol=${SYMBOL}&limit=${LIMIT:-5}'
|
||||
|
||||
BINANCE_OPEN_ORDERS_PATH="/api/v3/openOrders"
|
||||
BINANCE_OPEN_ORDERS_PARAMS='symbol=${SYMBOL:-OMIT}'
|
||||
BINANCE_OPEN_ORDERS_IS_SIGNED=1
|
||||
|
||||
BINANCE_ACCOUNT_PATH="/api/v3/account"
|
||||
BINANCE_ACCOUNT_PARAMS='recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_ACCOUNT_IS_SIGNED=1
|
||||
|
||||
BINANCE_CANCEL_OPEN_ORDERS_PATH="/api/v3/openOrders"
|
||||
BINANCE_CANCEL_OPEN_ORDERS_PARAMS='symbol=${SYMBOL}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_CANCEL_OPEN_ORDERS_METHOD="DELETE"
|
||||
BINANCE_CANCEL_OPEN_ORDERS_IS_SIGNED=1
|
||||
|
||||
BINANCE_CREATE_ORDER_PATH="/api/v3/order"
|
||||
BINANCE_CREATE_ORDER_PARAMS='symbol=${SYMBOL}&side=${SIDE:-BUY}&type=${TYPE:-LIMIT}&timeInForce=${TIME_IN_FORCE:-GTC}&quantity=${QUANTITY:-OMIT}&price=${PRICE:-OMIT}&newClientOrderId=${NEW_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_CREATE_ORDER_METHOD="POST"
|
||||
BINANCE_CREATE_ORDER_IS_SIGNED=1
|
||||
|
||||
BINANCE_CANCEL_REPLACE_PATH="/api/v3/order/cancelReplace"
|
||||
BINANCE_CANCEL_REPLACE_PARAMS='symbol=${SYMBOL}&side=${SIDE:-BUY}&type=${TYPE:-LIMIT}&timeInForce=${TIME_IN_FORCE:-GTC}&quantity=${QUANTITY:-OMIT}&price=${PRICE:-OMIT}&cancelReplaceMode=${CANCEL_REPLACE_MODE:-STOP_ON_FAILURE}&cancelNewClientOrderId=${CANCEL_NEW_CLIENT_ORDER_ID:-OMIT}&cancelOrigClientOrderId=${CANCEL_ORIG_CLIENT_ORDER_ID:-OMIT}&cancelOrderId=${CANCEL_ORDER_ID:-OMIT}&newClientOrderId=${NEW_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_CANCEL_REPLACE_METHOD="POST"
|
||||
BINANCE_CANCEL_REPLACE_IS_SIGNED=1
|
||||
|
||||
BINANCE_LISTEN_KEY_PATH="/api/v3/userDataStream"
|
||||
BINANCE_LISTEN_KEY_PARAMS=''
|
||||
BINANCE_LISTEN_KEY_METHOD="POST"
|
||||
BINANCE_LISTEN_KEY_IS_KEYED=1
|
||||
|
||||
BINANCE_REFRESH_LISTEN_KEY_PATH="/api/v3/userDataStream"
|
||||
BINANCE_REFRESH_LISTEN_KEY_PARAMS='listenKey=${LISTEN_KEY}'
|
||||
BINANCE_REFRESH_LISTEN_KEY_METHOD="PUT"
|
||||
BINANCE_REFRESH_LISTEN_KEY_IS_KEYED=1
|
||||
|
||||
BINANCE_CROSS_MARGIN_COLLATERAL_RATIO_PATH="/sapi/v1/margin/crossMarginCollateralRatio"
|
||||
BINANCE_CROSS_MARGIN_COLLATERAL_RATIO_METHOD="GET"
|
||||
BINANCE_CROSS_MARGIN_COLLATERAL_RATIO_IS_SIGNED=1
|
||||
|
||||
BINANCE_CROSS_MARGIN_PAIRS_PATH="/sapi/v1/margin/allPairs"
|
||||
BINANCE_CROSS_MARGIN_PAIRS_PARAMS='symbol=${SYMBOL:-OMIT}'
|
||||
BINANCE_CROSS_MARGIN_PAIRS_METHOD="GET"
|
||||
BINANCE_CROSS_MARGIN_PAIRS_IS_SIGNED=1
|
||||
|
||||
BINANCE_CROSS_MARGIN_ORDER_PATH="/sapi/v1/margin/order"
|
||||
BINANCE_CROSS_MARGIN_ORDER_PARAMS='symbol=${SYMBOL}&side=${SIDE}&type=${TYPE}&quantity=${QUANTITY}&price=${PRICE}&timeInForce=GTC&autoRepayAtCancel=true&sideEffectType=AUTO_BORROW_REPAY&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_CROSS_MARGIN_ORDER_METHOD="POST"
|
||||
BINANCE_CROSS_MARGIN_ORDER_IS_SIGNED=1
|
||||
|
||||
BINANCE_CROSS_MARGIN_OPEN_ORDERS_PATH="/sapi/v1/margin/openOrders"
|
||||
BINANCE_CROSS_MARGIN_OPEN_ORDERS_PARAMS='symbol=${SYMBOL}&isIsolated=${IS_ISOLATED:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_CROSS_MARGIN_OPEN_ORDERS_METHOD="GET"
|
||||
BINANCE_CROSS_MARGIN_OPEN_ORDERS_IS_SIGNED=1
|
||||
|
||||
BINANCE_CROSS_MARGIN_CANCEL_PATH="/sapi/v1/margin/order"
|
||||
BINANCE_CROSS_MARGIN_CANCEL_PARAMS='symbol=${SYMBOL}&isIsolated=${IS_ISOLATED:-OMIT}&orderId=${ORDER_ID:-OMIT}&origClientOrderId=${ORIG_CLIENT_ORDER_ID:-OMIT}&newClientOrderId=${NEW_CLIENT_ORDER_ID:-OMIT}&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_CROSS_MARGIN_CANCEL_METHOD="DELETE"
|
||||
BINANCE_CROSS_MARGIN_CANCEL_IS_SIGNED=1
|
||||
|
||||
BINANCE_CROSS_MARGIN_LISTEN_KEY_PATH="/sapi/v1/userDataStream"
|
||||
BINANCE_CROSS_MARGIN_LISTEN_KEY_PARAMS=''
|
||||
BINANCE_CROSS_MARGIN_LISTEN_KEY_METHOD="POST"
|
||||
BINANCE_CROSS_MARGIN_LISTEN_KEY_IS_KEYED=1
|
||||
|
||||
BINANCE_CROSS_MARGIN_REFRESH_LISTEN_KEY_PATH="/sapi/v1/userDataStream"
|
||||
BINANCE_CROSS_MARGIN_REFRESH_LISTEN_KEY_PARAMS='listenKey=${LISTEN_KEY}'
|
||||
BINANCE_CROSS_MARGIN_REFRESH_LISTEN_KEY_METHOD="PUT"
|
||||
BINANCE_CROSS_MARGIN_REFRESH_LISTEN_KEY_IS_KEYED=1
|
||||
|
||||
BINANCE_ISOLATED_MARGIN_SYMBOL_PATH="/sapi/v1/margin/order"
|
||||
BINANCE_ISOLATED_MARGIN_SYMBOL_PARAMS='symbol=${SYMBOL}&side=${SIDE}&type=${TYPE}&quantity=${QUANTITY}&price=${PRICE}&autoRepayAtCancel=true&recvWindow=${RECV_WINDOW:-6000}'
|
||||
BINANCE_ISOLATED_MARGIN_SYMBOL_METHOD="GET"
|
||||
BINANCE_ISOLATED_MARGIN_SYMBOL_IS_SIGNED=1
|
||||
|
||||
BINANCE_ALL_MARGIN_ASSETS_PATH="/sapi/v1/margin/allAssets"
|
||||
BINANCE_ALL_MARGIN_ASSETS_PARAMS='asset=${ASSET:-OMIT}'
|
||||
BINANCE_ALL_MARGIN_ASSETS_METHOD="GET"
|
||||
BINANCE_ALL_MARGIN_ASSETS_IS_SIGNED=1
|
||||
@@ -0,0 +1,503 @@
|
||||
import argparse
|
||||
import uuid
|
||||
import hmac
|
||||
import hashlib
|
||||
import os
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
import websocket
|
||||
import json
|
||||
import requests
|
||||
import python_execution_module as pyexe
|
||||
from string import Template
|
||||
from threading import Thread
|
||||
from typing import Any, Callable, Mapping, MutableMapping, Optional, TextIO
|
||||
|
||||
from binance_env_helper import (
|
||||
required_env_var,
|
||||
expand_vars,
|
||||
expand_defaults,
|
||||
load_env,
|
||||
)
|
||||
|
||||
|
||||
def hmac_hashing(api_secret: str, payload: str):
|
||||
m = hmac.new(api_secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256)
|
||||
return m.hexdigest()
|
||||
|
||||
|
||||
def rest_request(base_url: str, api_key: str, api_secret: str, parameters: dict = {}):
|
||||
parameters["timestamp"] = int(time.time() * 1000)
|
||||
sorted_keys = list(parameters)
|
||||
sorted_keys.sort()
|
||||
query_params = "&".join([f"{k}={parameters[k]}" for k in sorted_keys])
|
||||
signature = hmac_hashing(api_secret=api_secret, payload=query_params)
|
||||
parameters["signature"] = signature
|
||||
query_params += "&signature=" + signature
|
||||
url = base_url + "/api/v3/userDataStream" + "?" + query_params
|
||||
res = requests.post(url, headers={"X-MBX-APIKEY": api_key})
|
||||
return res.text
|
||||
|
||||
|
||||
class CircularBufferWriter:
|
||||
def __init__(self, buffer_line_count: int, sink: TextIO = sys.stdout):
|
||||
self.buffer_lines = []
|
||||
self.buffer_line_count = buffer_line_count
|
||||
self.sink = sink
|
||||
|
||||
def print(self, msg):
|
||||
if self.buffer_line_count <= 0:
|
||||
self.sink.write(msg + "\n")
|
||||
return
|
||||
for _ in range(0, len(self.buffer_lines)):
|
||||
self.sink.write("\x1b[1A\x1b[2K") # move up cursor and delete whole line
|
||||
if len(self.buffer_lines) == self.buffer_line_count:
|
||||
self.buffer_lines.pop()
|
||||
self.buffer_lines.insert(0, msg)
|
||||
lines = ""
|
||||
num_lines = len(self.buffer_lines)
|
||||
for i in range(0, num_lines):
|
||||
lines += self.buffer_lines[num_lines - i - 1] + "\n"
|
||||
self.sink.write(lines)
|
||||
|
||||
|
||||
def _get_arg_parser():
|
||||
# Cli Args
|
||||
arg_parser = argparse.ArgumentParser(description="Request market data at Binance")
|
||||
arg_parser.add_argument(
|
||||
"--streams",
|
||||
help="Streams to subscribe (e.g, btcusdt@depth5@500ms)",
|
||||
)
|
||||
arg_parser.add_argument(
|
||||
"--prod", action="store_const", const="PROD", dest="mode", help="Run at prod"
|
||||
)
|
||||
arg_parser.add_argument(
|
||||
"--dev", action="store_const", const="DEV", dest="mode", help="Run at testnet"
|
||||
)
|
||||
arg_parser.add_argument(
|
||||
"--spot",
|
||||
action="store_const",
|
||||
const="BINANCE",
|
||||
dest="venue",
|
||||
help="Run at spots",
|
||||
)
|
||||
arg_parser.add_argument("--op", help="The op to run")
|
||||
arg_parser.add_argument(
|
||||
"--param", help="Parameter(s) formatted as key=val)", nargs="+"
|
||||
)
|
||||
arg_parser.add_argument("--create-order", action="store_true", help="Create order")
|
||||
arg_parser.add_argument(
|
||||
"--usds-future",
|
||||
action="store_const",
|
||||
const="BINANCE_USDS_FUTURES",
|
||||
dest="venue",
|
||||
help="Run at usds futures",
|
||||
)
|
||||
arg_parser.add_argument("--user-data", action="store_true", help="User data")
|
||||
arg_parser.add_argument(
|
||||
"--exch-info",
|
||||
action="store_const",
|
||||
const="EXCHANGE_INFO",
|
||||
dest="op",
|
||||
help="Get exchangeInfo (REST)",
|
||||
)
|
||||
arg_parser.add_argument(
|
||||
"--list-symbols", action="store_true", help="Get symbols (REST)"
|
||||
)
|
||||
arg_parser.add_argument(
|
||||
"--listen-key",
|
||||
action="store_const",
|
||||
const="LISTEN_KEY",
|
||||
dest="op",
|
||||
help="Get listen key (needed for streams)",
|
||||
)
|
||||
arg_parser.add_argument(
|
||||
"--list-streams", action="store_true", help="List all streams"
|
||||
)
|
||||
arg_parser.add_argument(
|
||||
"--display-lines",
|
||||
help="Cap the number of lines to display from incoming messages (applies circular buffer to console output).",
|
||||
)
|
||||
arg_parser.add_argument("--url", help="The url to send requests to")
|
||||
arg_parser.set_defaults(mode="DEV", venue="BINANCE", user_data=False, op=None)
|
||||
return arg_parser
|
||||
|
||||
|
||||
def _parse_bool(s: Optional[str]):
|
||||
match s:
|
||||
case "1":
|
||||
return True
|
||||
case "true":
|
||||
return True
|
||||
case "on":
|
||||
return True
|
||||
case "y":
|
||||
return True
|
||||
case "yes":
|
||||
return True
|
||||
case _:
|
||||
return False
|
||||
|
||||
|
||||
class BinanceClient:
|
||||
def __init__(self, venue="BINANCE", mode="DEV", logger=None):
|
||||
self.venue = venue
|
||||
self.mode = mode
|
||||
self.rest_url = required_env_var(f"{venue}_{mode}_URL")
|
||||
self.ws_url = required_env_var(f"{venue}_{mode}_WS_URL")
|
||||
self._user_data_ping_thread: Optional[Thread] = None
|
||||
self.threads: list[Thread] = []
|
||||
self.logger = logger or logging.getLogger(__name__)
|
||||
self.api_key = os.environ.get(f"{self.venue}_{self.mode}_API_KEY")
|
||||
self.secret_key = os.environ.get(f"{self.venue}_{self.mode}_SECRET_KEY")
|
||||
self.orders = {}
|
||||
|
||||
def _on_open_with_ping(
|
||||
self, on_open: Optional[Callable[[websocket.WebSocket], None]]
|
||||
):
|
||||
def wrapper(ws):
|
||||
def ping_loop():
|
||||
time.sleep(10)
|
||||
# if isinstance(ws, websocket.WebSocketApp):
|
||||
# wsa: websocket.WebSocketApp = ws
|
||||
# ws = wsa.sock
|
||||
while True:
|
||||
ws.sock.ping()
|
||||
time.sleep(25)
|
||||
|
||||
self._user_data_ping_thread = Thread(target=ping_loop)
|
||||
self._user_data_ping_thread.start()
|
||||
if on_open:
|
||||
on_open(ws)
|
||||
|
||||
return wrapper
|
||||
|
||||
def _get_base_url(self, op, is_ws: bool = False, vars: Optional[Mapping] = None):
|
||||
"""Gets the base url for the request (includes host and path parts, but not query params)."""
|
||||
url_var_suffix = "WS_URL" if is_ws else "URL"
|
||||
url = os.environ.get(f"{self.venue}_{self.mode}_{url_var_suffix}") or ""
|
||||
req_path = os.environ.get(f"{self.venue}_{op}_PATH") or ""
|
||||
if vars:
|
||||
req_path = expand_vars(req_path, vars)
|
||||
if req_path:
|
||||
n = 1 if req_path.startswith("/") else 0
|
||||
n += 1 if self.rest_url.endswith("/") else 0
|
||||
match n:
|
||||
case 0:
|
||||
url += "/" + req_path
|
||||
case 1:
|
||||
url += req_path
|
||||
case 2:
|
||||
url += req_path[1:]
|
||||
return url
|
||||
|
||||
def _index_transaction(self, bts_key: int):
|
||||
exch_key = uuid.uuid1().hex
|
||||
self.orders[exch_key] = bts_key
|
||||
return exch_key
|
||||
|
||||
def _get_params_str(self, op, **kwargs):
|
||||
params = os.environ.get(f"{self.venue}_{op}_PARAMS") or ""
|
||||
params = expand_vars(params, kwargs)
|
||||
params = expand_defaults(params)
|
||||
return params
|
||||
|
||||
def _get_params_dict(self, op, **kwargs):
|
||||
params = self._get_params_str(op=op, **kwargs)
|
||||
if not params:
|
||||
return {}
|
||||
return {p[0]: p[1] for p in map(lambda x: x.split("="), params.split("&"))}
|
||||
|
||||
def _invoke(self, target: Callable[[], Any], run_in_background: bool):
|
||||
if run_in_background:
|
||||
t = Thread(target=target)
|
||||
self.threads.append(t)
|
||||
t.start()
|
||||
else:
|
||||
target()
|
||||
|
||||
def request(self, op, **kwargs):
|
||||
print(
|
||||
"Preparing request. op=%s, params=[%s]"
|
||||
% (op, ", ".join([f"{k}={v}" for k, v in kwargs.items()])),
|
||||
flush=True,
|
||||
)
|
||||
self.logger.info(
|
||||
"Preparing request. op=%s, params=[%s]"
|
||||
% (op, ", ".join([f"{k}={v}" for k, v in kwargs.items()]))
|
||||
)
|
||||
is_signed = _parse_bool(os.environ.get(f"{self.venue}_{op}_IS_SIGNED"))
|
||||
is_keyed = _parse_bool(os.environ.get(f"{self.venue}_{op}_IS_KEYED"))
|
||||
method = os.environ.get(f"{self.venue}_{op}_METHOD")
|
||||
params = self._get_params_dict(op, **kwargs)
|
||||
base_url = self._get_base_url(op, is_ws=False)
|
||||
res = None
|
||||
if is_keyed or is_signed:
|
||||
if not self.api_key:
|
||||
self.logger.error("Unable to make signed request. Api key not defined")
|
||||
return
|
||||
headers = {"Content-Type": "application/json", "X-MBX-APIKEY": self.api_key}
|
||||
if is_signed:
|
||||
if not self.secret_key:
|
||||
self.logger.error(
|
||||
"Unable to make signed request. Secret key not defined"
|
||||
)
|
||||
return
|
||||
params["timestamp"] = str(int(time.time() * 1000))
|
||||
base_url = self._get_base_url(op)
|
||||
sorted_keys = list(params)
|
||||
sorted_keys.sort()
|
||||
params_str = "&".join([f"{k}={params[k]}" for k in sorted_keys])
|
||||
signature = hmac_hashing(api_secret=self.secret_key, payload=params_str)
|
||||
params_str += "&signature=" + signature
|
||||
url = base_url + "?" + params_str
|
||||
if not method:
|
||||
method = "POST"
|
||||
headers = {"X-MBX-APIKEY": self.api_key}
|
||||
# print("ABOUT TO SEND.", flush=True)
|
||||
self.logger.info("Sending %s %s" % (method, url))
|
||||
try:
|
||||
print(
|
||||
"Requesting %s %s (%s)"
|
||||
% (
|
||||
method,
|
||||
url,
|
||||
", ".join([f"{k}={v}" for k, v in headers.items()]),
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
res = requests.request(method, url, headers=headers)
|
||||
# if res:
|
||||
print("RESULT. %s", str(res), flush=True)
|
||||
self.logger.log(
|
||||
logging.INFO if res.ok else logging.ERROR,
|
||||
"Received %i %s" % (res.status_code, str(res.text)),
|
||||
)
|
||||
except Exception as ex:
|
||||
print("OH NO %s" % str(ex), flush=True)
|
||||
self.logger.error("Request threw %s" % str(ex))
|
||||
else:
|
||||
params_str = "&".join([f"{k}={v}" for k, v in params.items()])
|
||||
url = base_url
|
||||
if params_str:
|
||||
url += "?" + params_str
|
||||
if not method:
|
||||
method = "GET"
|
||||
headers = {"Content-Type": "application/json", "X-MBX-APIKEY": self.api_key}
|
||||
self.logger.info(
|
||||
"Sending request %s %s (headers=[%s])"
|
||||
% (method, url, ", ".join([f"{k}={v}" for k, v in headers.items()]))
|
||||
)
|
||||
try:
|
||||
res = requests.request(method, url, headers=headers)
|
||||
self.logger.log(
|
||||
logging.INFO if res.ok else logging.ERROR,
|
||||
"Received response. %s" % str(res),
|
||||
)
|
||||
except Exception as e:
|
||||
self.logger.error("Request threw: %s" % str(e))
|
||||
self.logger.log(
|
||||
logging.INFO if res and res.ok else logging.ERROR,
|
||||
"Request failed. op=%s, res=\n%s",
|
||||
op,
|
||||
str(res),
|
||||
)
|
||||
return res
|
||||
|
||||
def create_order(self, req: pyexe.PyCreateOrderRequest):
|
||||
self.logger.info("Create order. %s" % str(req))
|
||||
self.request(
|
||||
op="CREATE_ORDER",
|
||||
symbol=req.exchange_security_id(),
|
||||
side="BUY" if req.is_buy() else "SELL",
|
||||
type=req.order_type(),
|
||||
price=req.price(),
|
||||
quantity=f"{req.quantity():.6f}",
|
||||
new_client_order_id=self._index_transaction(req.key()),
|
||||
)
|
||||
|
||||
def cancel_order(self, req: pyexe.PyCancelOrderRequest):
|
||||
self.request(
|
||||
op="CANCEL_ORDER",
|
||||
symbol=req.exchange_security_id(),
|
||||
side="BUY" if req.is_buy() else "SELL",
|
||||
orig_client_order_id=str(req.exchange_order_id()),
|
||||
new_client_order_id=self._index_transaction(req.key()),
|
||||
)
|
||||
|
||||
def subscribe_user_data(
|
||||
self,
|
||||
on_message: Optional[Callable[[websocket.WebSocket, Any], None]] = None,
|
||||
on_error: Optional[Callable[[websocket.WebSocket, Any], None]] = None,
|
||||
on_close: Optional[Callable[[websocket.WebSocket, Any, Any], None]] = None,
|
||||
on_open: Optional[Callable[[websocket.WebSocket], None]] = None,
|
||||
run_in_background: bool = True,
|
||||
):
|
||||
self.logger.info("Requesting listen key")
|
||||
res = self.request("LISTEN_KEY")
|
||||
if res is None:
|
||||
print("'listen_key_res' is none (this is unexpected)")
|
||||
return
|
||||
self.logger.log(
|
||||
logging.INFO if res and res.ok else logging.ERROR,
|
||||
"Received listen key. %s" % str(res),
|
||||
)
|
||||
if not res.ok:
|
||||
self.logger.error("Failed to get listen key")
|
||||
lkey = res.json().get("listenKey")
|
||||
self.logger.info("Received listen key %s" % lkey)
|
||||
url = self._get_base_url("USER_DATA", is_ws=True, vars={"LISTEN_KEY": lkey})
|
||||
ws_app = websocket.WebSocketApp(
|
||||
url=url,
|
||||
on_message=on_message,
|
||||
on_error=on_error,
|
||||
on_close=on_close,
|
||||
on_open=self._on_open_with_ping(on_open),
|
||||
)
|
||||
self.logger.info("Starting user data websocket %s" % url)
|
||||
self._invoke(
|
||||
lambda: ws_app.run_forever(ping_interval=600, ping_timeout=180),
|
||||
run_in_background,
|
||||
)
|
||||
|
||||
def subscribe_streams(
|
||||
self,
|
||||
streams,
|
||||
on_message: Optional[Callable[[websocket.WebSocket, Any], None]] = None,
|
||||
on_error: Optional[Callable[[websocket.WebSocket, Any], None]] = None,
|
||||
on_close: Optional[Callable[[websocket.WebSocket, Any, Any], None]] = None,
|
||||
run_in_background: bool = True,
|
||||
**kwargs,
|
||||
):
|
||||
def on_open(ws: websocket.WebSocket):
|
||||
self.logger.info("Stream websocket connected")
|
||||
try:
|
||||
req = {
|
||||
"method": "SUBSCRIBE",
|
||||
"params": streams,
|
||||
"id": 1,
|
||||
}
|
||||
req_str = json.dumps(req)
|
||||
self.logger.info("Requesting stream. %s", req_str)
|
||||
ws.send_text(req_str)
|
||||
except Exception as ex:
|
||||
self.logger.error("Stream request failed. %s", ex)
|
||||
self.logger.info("Disconnecting stream websocket")
|
||||
ws.close()
|
||||
|
||||
url = self._get_base_url("STREAMS", is_ws=True, **kwargs)
|
||||
|
||||
ws_app = websocket.WebSocketApp(
|
||||
url=url,
|
||||
on_open=self._on_open_with_ping(on_open),
|
||||
on_message=on_message,
|
||||
on_error=on_error,
|
||||
on_close=on_close,
|
||||
)
|
||||
self.logger.info("StreamSubscription @ %s", url)
|
||||
self._invoke(
|
||||
lambda: ws_app.run_forever(ping_interval=600, ping_timeout=180),
|
||||
run_in_background,
|
||||
)
|
||||
|
||||
|
||||
def _main():
|
||||
load_env()
|
||||
arg_parser = _get_arg_parser()
|
||||
args = arg_parser.parse_args()
|
||||
if args.list_streams:
|
||||
stream_descs = [
|
||||
"{symbol}@aggTrade",
|
||||
"{symbol}@markPrice",
|
||||
"{symbol}@markPrice@{interval} (intervals: 1s)",
|
||||
"!markPrice@arr",
|
||||
"!markPrice@arr@1s",
|
||||
"{symbol}@kline_{interval} (intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M)",
|
||||
"{pair}_{contractType}@continuousKline_{interval} (intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M)"
|
||||
"{symbol}@miniTicker",
|
||||
"!ticker@arr",
|
||||
"{symbol}@ticker",
|
||||
"!miniTicker@arr",
|
||||
"{symbol}@bookTicker",
|
||||
"!bookTicker",
|
||||
"{symbol}@forceOrder",
|
||||
"!forceOrder@arr",
|
||||
"{symbol}@depth{levels} (levels: 5, 10, 20)",
|
||||
"{symbol}@depth{levels}@{interval} (levels: 5, 10, 20)",
|
||||
" (intervals: 100ms, 500ms)",
|
||||
"{symbol}@depth",
|
||||
"{symbol}@depth@{interval} (intervals: 100ms, 500ms)",
|
||||
"{symbol}@compositeIndex",
|
||||
"!contractInfo",
|
||||
"!assetIndex@arr",
|
||||
"{assetSymbol}@assetIndex",
|
||||
]
|
||||
print("\n".join(stream_descs))
|
||||
return
|
||||
logger = logging.getLogger()
|
||||
cli = BinanceClient(args.venue, args.mode, logger=logger)
|
||||
params = {kv[0]: kv[1] for kv in map(lambda x: x.split("="), args.param or [])}
|
||||
if args.op:
|
||||
res = cli.request(args.op, **params)
|
||||
if res and res.ok:
|
||||
print(res.text)
|
||||
elif args.list_symbols:
|
||||
# Get symbols
|
||||
res = cli.request("EXCHANGE_INFO")
|
||||
if not res or not res.ok:
|
||||
return 1
|
||||
syms = {}
|
||||
res_j = json.loads(res.text)
|
||||
for sym in res_j["symbols"]:
|
||||
syms[sym["symbol"]] = sym
|
||||
sym_list = list(syms)
|
||||
sym_list.sort()
|
||||
for sym in sym_list:
|
||||
print(sym)
|
||||
elif args.user_data:
|
||||
# Subscribe user data
|
||||
writer = CircularBufferWriter(buffer_line_count=int(args.display_lines or -1))
|
||||
|
||||
def on_message(ws, msg):
|
||||
logger.debug("on_message: %s", msg)
|
||||
writer.print(msg)
|
||||
|
||||
def on_error(ws, err):
|
||||
logger.error("on_error: %s", err)
|
||||
|
||||
def on_close(ws, code, msg):
|
||||
logger.info("on_close (%d): %s", code, msg)
|
||||
|
||||
cli.subscribe_user_data(on_message, on_error, on_close)
|
||||
elif args.streams:
|
||||
# Subscribe streams
|
||||
writer = CircularBufferWriter(buffer_line_count=int(args.display_lines or -1))
|
||||
|
||||
def on_message(ws, msg):
|
||||
logger.debug("Recv: %s", msg)
|
||||
writer.print(msg)
|
||||
|
||||
def on_error(ws, err):
|
||||
logger.error("Error: %s", err)
|
||||
|
||||
def on_close(ws, code, msg):
|
||||
logger.info("Closed (%d): %s", code, msg)
|
||||
|
||||
cli.subscribe_streams(
|
||||
streams=args.streams if isinstance(args.streams, list) else [args.streams],
|
||||
on_message=on_message,
|
||||
on_error=on_error,
|
||||
on_close=on_close,
|
||||
)
|
||||
else:
|
||||
sys.stderr.write(
|
||||
"No data requested (run with --streams <stream1> <stream2> ... or --exch-info or --list-symbols)"
|
||||
)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
code = _main()
|
||||
exit(code)
|
||||
@@ -0,0 +1,100 @@
|
||||
from typing import Any, Mapping, Optional
|
||||
import dotenv
|
||||
import os
|
||||
|
||||
|
||||
def required_env_var(key):
|
||||
val = os.environ.get(key)
|
||||
if val is None:
|
||||
raise ValueError(f"{key} env var not defined")
|
||||
return val
|
||||
|
||||
|
||||
def expand_env(s: str, vars=os.environ):
|
||||
if not s:
|
||||
return ""
|
||||
beg = 0
|
||||
while True:
|
||||
beg = s.find("${", beg)
|
||||
if beg == -1 or beg > len(s) - 4:
|
||||
break
|
||||
end = s.find("}", beg + 2)
|
||||
if end == -1:
|
||||
break
|
||||
k = s[beg:end]
|
||||
v = vars.get(k) or ""
|
||||
s = s[:beg] + v + s[end + 1 :]
|
||||
beg += len(v) + 1
|
||||
return s
|
||||
|
||||
|
||||
def expand_var(req_params: str, k: str, v: Any):
|
||||
ku = str(k).upper()
|
||||
substitution = f"${{{ku}}}"
|
||||
pos = req_params.find(substitution)
|
||||
end_pos = -1
|
||||
if pos == -1:
|
||||
substitution = f"${{{ku}:"
|
||||
pos = req_params.find(substitution)
|
||||
if pos == -1:
|
||||
return req_params
|
||||
end_pos = req_params.find("}", pos + len(substitution))
|
||||
if end_pos == -1:
|
||||
return req_params
|
||||
end_pos += 1
|
||||
else:
|
||||
end_pos = pos + len(substitution)
|
||||
if end_pos == -1:
|
||||
raise ValueError(f"Invalid request params template '{req_params}'")
|
||||
req_params = req_params[:pos] + str(v) + req_params[end_pos:]
|
||||
return req_params
|
||||
|
||||
|
||||
def expand_vars(req_params: str, key_vals: Mapping):
|
||||
for k, v in key_vals.items():
|
||||
req_params = expand_var(req_params, k, v)
|
||||
return req_params
|
||||
|
||||
|
||||
def expand_defaults(req_params: str):
|
||||
i = 0
|
||||
prefix = ":-"
|
||||
while i < len(req_params):
|
||||
start = req_params.find("${", i)
|
||||
if start == -1:
|
||||
break
|
||||
stop = req_params.find("}", start)
|
||||
if stop == -1:
|
||||
raise ValueError(f"Invalid param str {req_params}")
|
||||
prefix_pos = req_params.find(prefix, start, stop)
|
||||
if prefix_pos < start:
|
||||
req_params = req_params[:start] + req_params[stop + 1 :]
|
||||
i = start
|
||||
continue
|
||||
default_val = req_params[prefix_pos + len(prefix) : stop]
|
||||
if default_val == "OMIT":
|
||||
i = req_params.rfind("&", 0, prefix_pos - 1)
|
||||
if i == -1:
|
||||
i = 0
|
||||
req_params = req_params[:i] + req_params[stop + 1 :]
|
||||
else:
|
||||
req_params = req_params[:start] + default_val + req_params[stop + 1 :]
|
||||
i = start + len(default_val) + 1
|
||||
if req_params.startswith("&"):
|
||||
req_params = req_params[1:]
|
||||
return req_params
|
||||
|
||||
|
||||
def load_env(env_path: Optional[str] = None):
|
||||
if not env_path:
|
||||
env_path = os.path.join(
|
||||
os.path.dirname(os.path.realpath(__file__)), "binance.env"
|
||||
)
|
||||
dotenv.load_dotenv(env_path, interpolate=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
req_params = required_env_var("BINANCE_CREATE_ORDER_PARAMS")
|
||||
res = expand_var(req_params, "SYMBOL", "BTCUSDT")
|
||||
res = expand_defaults(res)
|
||||
print(res)
|
||||
@@ -0,0 +1,242 @@
|
||||
import dotenv
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import sys
|
||||
import traceback
|
||||
from typing import Any, Optional
|
||||
import uuid
|
||||
import websocket
|
||||
|
||||
from binance_client import BinanceClient
|
||||
import python_execution_module as pyexe
|
||||
|
||||
|
||||
BINANCE_API_KEY = "2RJ9H02ztFGWxeY2oRpnFYZNU8mki4V1yMvKrDU08HCiEhO4VLe2ePSUFqEYTNxc"
|
||||
BINANCE_USDS_FUTURES_API_KEY = (
|
||||
"b838c108cd2648e34a4f088a7fc635a9cbccf3c2faa6bcaabcb532ffacc087b0"
|
||||
)
|
||||
BINANCE_USDS_FUTURES_SECRET_KEY = (
|
||||
"a68f0ab27403c42fa0306b6341b2ddd51d99ac42916f849404155449457d0492"
|
||||
)
|
||||
|
||||
|
||||
def to_bts_exec_type(exec_type: str, ord_status: str):
|
||||
match exec_type:
|
||||
case "TRADE_PREVENTION":
|
||||
return "REJECTED"
|
||||
case "NONE":
|
||||
return "UNDEFINED"
|
||||
case "TRADE":
|
||||
return "FILL" if ord_status == "FILLED" else "PARTIAL_FILL"
|
||||
case _:
|
||||
return exec_type
|
||||
|
||||
|
||||
def to_bts_order_status(ord_status: str):
|
||||
match ord_status:
|
||||
case "EXPIRED_IN_MATCH":
|
||||
return "EXPIRED"
|
||||
case _:
|
||||
return ord_status
|
||||
|
||||
|
||||
class DummyExecutionGateway(pyexe.ExecutionGateway):
|
||||
def __init__(self):
|
||||
super(DummyExecutionGateway, self).__init__()
|
||||
self.bridge = None
|
||||
self.client = None
|
||||
self.start_th = None
|
||||
self.ws = None
|
||||
self.orders = {}
|
||||
self.logger = logging.getLogger(__name__)
|
||||
stdout_handler = logging.StreamHandler(sys.stdout)
|
||||
stdout_handler.formatter = logging.Formatter(
|
||||
"%(asctime)s | %(levelname)7s | %(filename)s:%(lineno)s | %(message)s"
|
||||
)
|
||||
self.logger.addHandler(stdout_handler)
|
||||
self.logger.addHandler(
|
||||
logging.FileHandler(
|
||||
"/home/bts/sparkdata/data/logging.python_execution/dummy_log"
|
||||
)
|
||||
)
|
||||
self.logger.setLevel(logging.INFO)
|
||||
env_path = "/workspaces/spark/tools/binance/binance.env"
|
||||
self.logger.info("DummyExecutionGateway ctr. Loading env")
|
||||
dotenv.load_dotenv(env_path, interpolate=False)
|
||||
|
||||
def _index_transaction(self, bts_key: int):
|
||||
exch_key = uuid.uuid1().hex
|
||||
self.orders[exch_key] = bts_key
|
||||
return exch_key
|
||||
|
||||
def _on_user_data_msg_core(self, ws: websocket.WebSocket, msg: Any):
|
||||
self.logger.info("Recv usr data: %s", str(msg))
|
||||
if not msg:
|
||||
self.logger.error("Recv empty usr data msg")
|
||||
return
|
||||
if not self.bridge:
|
||||
self.logger.error("Cannot process usr data. Bridge not created")
|
||||
return
|
||||
upd = json.loads(str(msg))
|
||||
if "e" in upd:
|
||||
if upd["e"] == "executionReport":
|
||||
# Binance spots update
|
||||
bts_ord_id = self.orders.get(upd["c"])
|
||||
is_old_ord = False
|
||||
if not bts_ord_id:
|
||||
bts_ord_id = self.orders.get(upd["C"])
|
||||
if not bts_ord_id:
|
||||
self.logger.warning(
|
||||
"Received update with unknown order id: %s", msg
|
||||
)
|
||||
return
|
||||
is_old_ord = True
|
||||
er = pyexe.PyExecutionReport()
|
||||
er.set_key(bts_ord_id)
|
||||
er.set_venue("BINANCE")
|
||||
er.set_exchange_security_id(upd["s"])
|
||||
er.set_security_type("SPOT")
|
||||
er.set_exec_type(to_bts_exec_type(upd["x"], upd["X"]))
|
||||
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"])
|
||||
total_filled_qty = float(upd["z"])
|
||||
er.set_filled_quantity(total_filled_qty)
|
||||
total_filled_notional = float(upd["Z"])
|
||||
avg_filled_price = (
|
||||
total_filled_notional / total_filled_qty
|
||||
if total_filled_qty > 0
|
||||
else math.nan
|
||||
)
|
||||
er.set_avg_filled_price(avg_filled_price)
|
||||
er.set_order_status(to_bts_order_status(upd["X"]))
|
||||
er.set_order_type(upd["o"])
|
||||
match upd["X"]:
|
||||
case "CANCELED":
|
||||
if not is_old_ord:
|
||||
del self.orders[bts_ord_id]
|
||||
case "FILLED":
|
||||
del self.orders[bts_ord_id]
|
||||
case "REJECTED":
|
||||
del self.orders[bts_ord_id]
|
||||
self.bridge.on_execution_report(er)
|
||||
elif upd["e"] == "ORDER_TRADE_UPDATE":
|
||||
data = upd["o"]
|
||||
# Binance Usds Futures order update
|
||||
bts_ord_id = self.orders.get(data["c"])
|
||||
is_old_ord = False
|
||||
if not bts_ord_id:
|
||||
bts_ord_id = self.orders.get(data["C"])
|
||||
if not bts_ord_id:
|
||||
self.logger.warning(
|
||||
"Received dataate with unknown order id: %s", msg
|
||||
)
|
||||
return
|
||||
is_old_ord = True
|
||||
|
||||
def parse_float(s: Optional[str], default_val=math.nan):
|
||||
if s is not None:
|
||||
try:
|
||||
return float(s)
|
||||
except Exception:
|
||||
pass
|
||||
return default_val
|
||||
|
||||
er = pyexe.PyExecutionReport()
|
||||
er.set_key(bts_ord_id)
|
||||
er.set_venue("BINANCE_USDS_FUTURES")
|
||||
er.set_security_type("FUTURE")
|
||||
er.set_time_in_force("GTC")
|
||||
er.set_exchange_order_id(str(data.get("i") or 0))
|
||||
# er.set_exchange_order_id(data["i"])
|
||||
er.set_exchange_security_id(data["s"])
|
||||
er.set_exec_type(to_bts_exec_type(data["x"], data["X"]))
|
||||
er.set_is_buy(data["S"] == "BUY")
|
||||
er.set_price(parse_float(data["p"]))
|
||||
er.set_quantity(parse_float(data["q"]))
|
||||
er.set_last_filled_price(parse_float(data.get("L")))
|
||||
er.set_last_filled_quantity(parse_float(data["l"]))
|
||||
er.set_filled_quantity(parse_float(data["z"]))
|
||||
er.set_avg_filled_price(parse_float(data["ap"]))
|
||||
er.set_order_status(to_bts_order_status(data["X"]))
|
||||
er.set_order_type(data["o"])
|
||||
match data["X"]:
|
||||
case "CANCELED":
|
||||
if not is_old_ord:
|
||||
del self.orders[bts_ord_id]
|
||||
case "FILLED":
|
||||
del self.orders[bts_ord_id]
|
||||
case "REJECTED":
|
||||
del self.orders[bts_ord_id]
|
||||
print("Firing this exe report: %s" % str(er), flush=True)
|
||||
self.bridge.on_execution_report(er)
|
||||
|
||||
def _on_user_data_msg(self, ws: websocket.WebSocket, msg: Any):
|
||||
try:
|
||||
self._on_user_data_msg_core(ws, msg)
|
||||
except Exception:
|
||||
self.logger.error("on_user_data_msg. %s" % traceback.format_exc())
|
||||
|
||||
def _on_user_data_open(self, ws: websocket.WebSocket):
|
||||
self.ws = ws
|
||||
if self.bridge:
|
||||
self.bridge.on_is_ready(True)
|
||||
|
||||
def _on_user_data_err(self, ws: websocket.WebSocket, err: str):
|
||||
self.logger.error("on_user_data_err: %s", err)
|
||||
|
||||
def _on_user_data_close(self, ws: websocket.WebSocket, code: int, msg: str):
|
||||
self.logger.warning("on_user_data_close: %s %s", str(code), msg)
|
||||
if self.bridge:
|
||||
self.bridge.on_is_ready(False)
|
||||
|
||||
def start(self, bridge: pyexe.ExecutionGatewayBridge):
|
||||
print("DummyExecutionGateway.start")
|
||||
self.bridge = bridge
|
||||
self.client = BinanceClient(venue="BINANCE_USDS_FUTURES")
|
||||
print("DummyExecutionGateway.start. Subscribing to binance user data")
|
||||
self.client.subscribe_user_data(
|
||||
on_message=self._on_user_data_msg,
|
||||
on_open=self._on_user_data_open,
|
||||
on_close=self._on_user_data_close,
|
||||
)
|
||||
print("DummyExecutionGateway.start. Subscribed to binance user data")
|
||||
|
||||
def cancel_order(self, req: pyexe.PyCancelOrderRequest):
|
||||
if not self.client:
|
||||
self.logger.error("Cannot cancel order. BinanceClient not created.")
|
||||
return
|
||||
self.logger.info("[cancel_order.json]%s", str(req))
|
||||
try:
|
||||
self.client.request(
|
||||
"CANCEL_ORDER",
|
||||
symbol=req.exchange_security_id(),
|
||||
orig_client_order_id=req.exchange_order_id(),
|
||||
new_client_order_id=self._index_transaction(req.key()),
|
||||
)
|
||||
except Exception as ex:
|
||||
self.logger.error("Create order request threw. %s" % str(ex))
|
||||
|
||||
def create_order(self, req: pyexe.PyCreateOrderRequest):
|
||||
if not self.client:
|
||||
self.logger.error("Cannot create order. BinanceClient not created.")
|
||||
return
|
||||
print("hey bud")
|
||||
self.logger.info("[create_order.json]%s", str(req))
|
||||
side = "BUY" if req.is_buy() else "SELL"
|
||||
try:
|
||||
self.client.request(
|
||||
op="CREATE_ORDER",
|
||||
symbol=req.exchange_security_id(),
|
||||
price=req.price(),
|
||||
quantity=f"{req.quantity():.6f}",
|
||||
side=side,
|
||||
time_in_force="GTC",
|
||||
type="LIMIT",
|
||||
new_client_order_id=self._index_transaction(req.key()),
|
||||
)
|
||||
except Exception as ex:
|
||||
self.logger.error("Create order request threw. %s" % str(ex))
|
||||
@@ -0,0 +1,303 @@
|
||||
import json
|
||||
import math
|
||||
import time
|
||||
from typing import Optional
|
||||
import uuid
|
||||
from pybit.unified_trading import WebSocket, WebSocketTrading
|
||||
from py_execution_utils import load_gateway_config
|
||||
from spark_core import (
|
||||
as_bool,
|
||||
configure_logger,
|
||||
get_price_decimal_places,
|
||||
get_qty_decimal_places,
|
||||
parse_float,
|
||||
StructuredLog as SLog,
|
||||
)
|
||||
import logging
|
||||
from python_core_module import (
|
||||
PySecurity,
|
||||
PySecurityList,
|
||||
)
|
||||
from python_execution_module import (
|
||||
ExecutionGateway,
|
||||
ExecutionGatewayBridge,
|
||||
PyCreateOrderRequest,
|
||||
PyCancelReplaceOrderRequest,
|
||||
PyCancelOrderRequest,
|
||||
PyExecutionReport,
|
||||
)
|
||||
import threading
|
||||
|
||||
|
||||
class OrderData:
|
||||
def __init__(self, bts_id: int, exch_id: str, price: float, quantity: float):
|
||||
self.bts_id = bts_id
|
||||
self.exch_id = exch_id
|
||||
self.price = price
|
||||
self.quantity = quantity
|
||||
self.filled_quantity: float = 0
|
||||
self.last_filled_quantity: float = math.nan
|
||||
self.avg_filled_price: float = math.nan
|
||||
self.last_filled_price: float = math.nan
|
||||
self.exec_type = "PENDING_NEW"
|
||||
self.securities: PySecurityList = []
|
||||
|
||||
def on_update(
|
||||
self, new_filled_quantity: float, new_avg_filled_price: float, status: str
|
||||
):
|
||||
lfq = new_filled_quantity - self.filled_quantity
|
||||
if lfq > 0:
|
||||
if self.filled_quantity == 0:
|
||||
self.last_filled_quantity = new_filled_quantity
|
||||
self.last_filled_price = new_avg_filled_price
|
||||
else:
|
||||
price_diff = new_avg_filled_price - self.avg_filled_price
|
||||
lfq_weight = new_filled_quantity / (
|
||||
self.filled_quantity + new_filled_quantity
|
||||
)
|
||||
lfp = self.avg_filled_price + (price_diff / lfq_weight)
|
||||
self.last_filled_price = lfp
|
||||
self.last_filled_quantity = lfq
|
||||
self.filled_quantity = new_filled_quantity
|
||||
self.avg_filled_price = new_avg_filled_price
|
||||
match status:
|
||||
case "Filled":
|
||||
self.exec_type = "FILL"
|
||||
case "Canceled":
|
||||
self.exec_type = "CANCELED"
|
||||
case "Rejected":
|
||||
self.exec_type = "REJECTED"
|
||||
case _:
|
||||
self.exec_type = "NEW" if new_filled_quantity == 0 else "PARTIAL_FILL"
|
||||
|
||||
|
||||
class BybitExecutionGateway(ExecutionGateway):
|
||||
def __init__(self, name: str):
|
||||
super(BybitExecutionGateway, self).__init__()
|
||||
self.name = name
|
||||
self.logger = configure_logger(logging.getLogger(name), "OrderMan")
|
||||
self.logger.info("[bybit_gw_ctr.json]%s" % SLog(name=name))
|
||||
cfg = load_gateway_config(name)
|
||||
self.account: str = cfg["account"]
|
||||
self.api_key: str = cfg["api_key"]
|
||||
self.secret_key: str = cfg["secret_key"]
|
||||
self.use_testnet: bool = cfg.get("use_testnet", True)
|
||||
self.use_trace_logging: bool = cfg.get("use_trace_logging", False)
|
||||
self.stop_event = threading.Event()
|
||||
self.stream_cli: Optional[WebSocket] = None
|
||||
self.trade_cli: Optional[WebSocketTrading] = None
|
||||
# bts id -> exch id
|
||||
self.orders: dict[int, OrderData] = {}
|
||||
self.securities: dict[str, PySecurity] = {}
|
||||
|
||||
def _get_order_data(self, exch_id: str):
|
||||
for _, v in self.orders.items():
|
||||
if v.exch_id == exch_id:
|
||||
return v
|
||||
return None
|
||||
|
||||
def _on_order_ack(self, typ, msg: object):
|
||||
self.logger.info(
|
||||
'[bybit_gw_ord_ack.json]{ "typ": "%s", "msg": %s}' % (typ, msg)
|
||||
)
|
||||
|
||||
def _on_abort(
|
||||
self,
|
||||
key: int,
|
||||
req_type: str,
|
||||
rsn: str,
|
||||
):
|
||||
self.logger.error(
|
||||
'[bybit_gw_abort.json]{ "key": %d, "typ": "%s", "rsn": "%s", "ts": %d }'
|
||||
% (key, req_type, rsn, time.time_ns())
|
||||
)
|
||||
|
||||
def start_impl(self, bridge: ExecutionGatewayBridge):
|
||||
def on_order_update(msg: dict):
|
||||
def on_error(err: str):
|
||||
self.logger.error(
|
||||
'[bybit_gw_ord_upd_err.json]{ "err": "%s", "ts": %d }'
|
||||
% (err, time.time_ns())
|
||||
)
|
||||
|
||||
self.logger.info("[bybit_gw_ord_upd.json]%s" % msg)
|
||||
try:
|
||||
upds: list[dict] = msg["data"]
|
||||
for d in upds:
|
||||
er = PyExecutionReport()
|
||||
exch_id: str = d["orderLinkId"]
|
||||
ord_data: Optional[OrderData] = self._get_order_data(exch_id)
|
||||
if not ord_data:
|
||||
on_error("Did not resolve exch order id %s" % exch_id)
|
||||
return
|
||||
total_filled_qty = parse_float(d["cumExecQty"])
|
||||
avg_filled_price = parse_float(d["avgPrice"])
|
||||
status: str = d["orderStatus"]
|
||||
# brits can't spell
|
||||
if status == "Cancelled":
|
||||
status = "Canceled"
|
||||
ord_data.on_update(total_filled_qty, avg_filled_price, status)
|
||||
er.set_data(
|
||||
key=ord_data.bts_id,
|
||||
exchange_order_id=d["orderLinkId"],
|
||||
transact_id=d["seq"],
|
||||
venue="BYBIT",
|
||||
security_type="FUTURE",
|
||||
exchange_security_id=d["symbol"],
|
||||
account=self.account,
|
||||
order_type=d["orderType"],
|
||||
is_buy=d["side"] == "Buy",
|
||||
price=parse_float(d["price"]),
|
||||
quantity=parse_float(d["qty"]),
|
||||
time_in_force=d["timeInForce"],
|
||||
exec_type=ord_data.exec_type,
|
||||
order_status=status,
|
||||
last_filled_price=ord_data.last_filled_price,
|
||||
last_filled_quantity=ord_data.last_filled_quantity,
|
||||
filled_quantity=total_filled_qty,
|
||||
avg_filled_price=avg_filled_price,
|
||||
transact_time=int(d["updatedTime"]) * 1_000_000,
|
||||
)
|
||||
self.logger.info("[bybit_gw_exe_rep_out.json]%s" % er)
|
||||
bridge.on_execution_report(er)
|
||||
except Exception as e:
|
||||
self.logger.error(
|
||||
'[bybit_gw_ord_upd_err.json]{ "err": %s }' % e, exc_info=True
|
||||
)
|
||||
|
||||
def on_exe_report(msg):
|
||||
self.logger.info("[bybit_gw_exe_rep.json]%s" % msg)
|
||||
|
||||
# Stream client (receives order updates)
|
||||
params = {
|
||||
"api_key": self.api_key,
|
||||
"api_secret": self.secret_key,
|
||||
"testnet": self.use_testnet,
|
||||
"channel_type": "private",
|
||||
"trace_logging": False,
|
||||
}
|
||||
self.logger.info("[bybit_gw_stream_sub.json]%s" % json.dumps(params))
|
||||
self.stream_cli = WebSocket(**params)
|
||||
self.stream_cli.order_stream(on_order_update)
|
||||
self.stream_cli.execution_stream(on_exe_report)
|
||||
# Trade client (sends orders)
|
||||
params = {
|
||||
"api_key": self.api_key,
|
||||
"api_secret": self.secret_key,
|
||||
"testnet": True,
|
||||
}
|
||||
self.logger.info("[bybit_gw_start_trd_cli.json]%s" % json.dumps(params))
|
||||
self.trade_cli = WebSocketTrading(**params)
|
||||
params = {
|
||||
"category": "linear",
|
||||
}
|
||||
self.bridge.on_is_ready(True)
|
||||
|
||||
def start(self, bridge: ExecutionGatewayBridge):
|
||||
def start_wrapper():
|
||||
try:
|
||||
self.start_impl(bridge)
|
||||
except Exception as e:
|
||||
self.logger.error(
|
||||
'[bybit_gw_start_err.json]{ "err": "%s" }' % str(e), exc_info=True
|
||||
)
|
||||
|
||||
self.logger.info("[bybit_gw_start.json]%s" % json.dumps({"ts": time.time_ns()}))
|
||||
self.bridge = bridge
|
||||
threading.Thread(
|
||||
target=start_wrapper,
|
||||
name=f"{self.name}_main",
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
def stop(self):
|
||||
self.logger.info("[bybit_gw_stop.json]%s" % json.dumps({"ts": time.time_ns()}))
|
||||
self.stop_event.set()
|
||||
|
||||
def create_order(self, req: PyCreateOrderRequest):
|
||||
self.logger.info("[bybit_gw_crt_ord.json]%s" % str(req))
|
||||
if not self.stream_cli or not self.trade_cli or not self.bridge:
|
||||
self._on_abort(
|
||||
req.key(),
|
||||
"crt",
|
||||
"WebSocket not initialized (stream_cli: %s, trade_cli: %s, bridge: %s)"
|
||||
% as_bool(self.stream_cli, self.trade_cli, self.bridge),
|
||||
)
|
||||
return
|
||||
exch_ord_id = uuid.uuid1().hex
|
||||
bts_id = req.key()
|
||||
px = req.price()
|
||||
qty = req.quantity()
|
||||
self.orders[req.key()] = OrderData(
|
||||
bts_id=bts_id, exch_id=exch_ord_id, price=px, quantity=qty
|
||||
)
|
||||
sec_name = req.exchange_security_id()
|
||||
sec = self.securities.get(sec_name)
|
||||
if not sec:
|
||||
return
|
||||
price_decimal_places = get_price_decimal_places(sec)
|
||||
qty_decimal_places = get_qty_decimal_places(sec)
|
||||
params = {
|
||||
"orderLinkId": exch_ord_id,
|
||||
"category": "linear",
|
||||
"symbol": sec_name,
|
||||
"side": "Buy" if req.is_buy() else "Sell",
|
||||
"orderType": req.order_type().title(),
|
||||
"price": f"{price_decimal_places:.2f}",
|
||||
"qty": f"{qty_decimal_places:.2f}",
|
||||
}
|
||||
self.logger.info("[bybit_gw_create_order_msg.json]%s" % json.dumps(params))
|
||||
self.trade_cli.place_order(lambda msg: self._on_order_ack("crt", msg), **params)
|
||||
|
||||
def cancel_replace_order(self, req: PyCancelReplaceOrderRequest):
|
||||
self.logger.info("[bybit_gw_cxlrep_ord.json]%s" % req)
|
||||
if not self.stream_cli or not self.trade_cli:
|
||||
self._on_abort(req.key(), "cxlrep", "WebSocket client not created.")
|
||||
return
|
||||
bts_id = req.key()
|
||||
ord_data = self.orders.get(bts_id)
|
||||
if not ord_data:
|
||||
self._on_abort(req.key(), "cxlrep", "Did not resolve exch order id")
|
||||
return
|
||||
sec_name = req.exchange_security_id()
|
||||
sec = self.securities.get(sec_name)
|
||||
if not sec:
|
||||
return
|
||||
price_decimal_places = get_price_decimal_places(sec)
|
||||
qty_decimal_places = get_qty_decimal_places(sec)
|
||||
params = {
|
||||
"orderLinkId": ord_data.exch_id,
|
||||
"category": "linear",
|
||||
"symbol": req.exchange_security_id(),
|
||||
"price": f"{price_decimal_places:.2f}",
|
||||
"qty": f"{qty_decimal_places:.2f}",
|
||||
}
|
||||
self.trade_cli.amend_order(
|
||||
lambda msg: self._on_order_ack("cxlrep", msg), **params
|
||||
)
|
||||
|
||||
def cancel_order(self, req: PyCancelOrderRequest):
|
||||
self.logger.info("[bybit_gw_cxl_ord.json]%s" % str(req))
|
||||
if not self.stream_cli or not self.trade_cli:
|
||||
self._on_abort(req.key(), "cxl", "WebSocket client not created.")
|
||||
return
|
||||
bts_id = req.key()
|
||||
ord_data = self.orders.get(bts_id)
|
||||
if not ord_data:
|
||||
self._on_abort(req.key(), "cxl", "Did not resolve exch order id")
|
||||
return
|
||||
params = {
|
||||
"orderLinkId": ord_data.exch_id,
|
||||
"category": "linear",
|
||||
"symbol": req.exchange_security_id(),
|
||||
}
|
||||
self.trade_cli.cancel_order(
|
||||
lambda msg: self._on_order_ack("cxl", msg), **params
|
||||
)
|
||||
|
||||
def on_securities(self, securities: PySecurityList):
|
||||
self.logger.info(
|
||||
"[bybit_gw_sec.json][%s]" % ", ".join([str(sec) for sec in securities])
|
||||
)
|
||||
self.securities = {sec.name(): sec for sec in securities}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import dotenv
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import sys
|
||||
import traceback
|
||||
from typing import Any, Optional
|
||||
import uuid
|
||||
import websocket
|
||||
|
||||
from binance_client import BinanceClient
|
||||
import python_execution_module as pyexe
|
||||
|
||||
|
||||
BINANCE_API_KEY = "2RJ9H02ztFGWxeY2oRpnFYZNU8mki4V1yMvKrDU08HCiEhO4VLe2ePSUFqEYTNxc"
|
||||
BINANCE_USDS_FUTURES_API_KEY = (
|
||||
"b838c108cd2648e34a4f088a7fc635a9cbccf3c2faa6bcaabcb532ffacc087b0"
|
||||
)
|
||||
BINANCE_USDS_FUTURES_SECRET_KEY = (
|
||||
"a68f0ab27403c42fa0306b6341b2ddd51d99ac42916f849404155449457d0492"
|
||||
)
|
||||
|
||||
|
||||
def to_bts_exec_type(exec_type: str, ord_status: str):
|
||||
match exec_type:
|
||||
case "TRADE_PREVENTION":
|
||||
return "REJECTED"
|
||||
case "NONE":
|
||||
return "UNDEFINED"
|
||||
case "TRADE":
|
||||
return "FILL" if ord_status == "FILLED" else "PARTIAL_FILL"
|
||||
case _:
|
||||
return exec_type
|
||||
|
||||
|
||||
def to_bts_order_status(ord_status: str):
|
||||
match ord_status:
|
||||
case "EXPIRED_IN_MATCH":
|
||||
return "EXPIRED"
|
||||
case _:
|
||||
return ord_status
|
||||
|
||||
|
||||
class DummyExecutionGateway(pyexe.ExecutionGateway):
|
||||
def __init__(self):
|
||||
super(DummyExecutionGateway, self).__init__()
|
||||
self.bridge = None
|
||||
self.client = None
|
||||
self.start_th = None
|
||||
self.ws = None
|
||||
self.orders = {}
|
||||
self.logger = logging.getLogger(__name__)
|
||||
stdout_handler = logging.StreamHandler(sys.stdout)
|
||||
stdout_handler.formatter = logging.Formatter(
|
||||
"%(asctime)s | %(levelname)7s | %(filename)s:%(lineno)s | %(message)s"
|
||||
)
|
||||
self.logger.addHandler(stdout_handler)
|
||||
self.logger.addHandler(
|
||||
logging.FileHandler(
|
||||
"/home/bts/sparkdata/data/logging.python_execution/dummy_log"
|
||||
)
|
||||
)
|
||||
self.logger.setLevel(logging.INFO)
|
||||
env_path = "/workspaces/spark/tools/binance/binance.env"
|
||||
self.logger.info("DummyExecutionGateway ctr. Loading env")
|
||||
dotenv.load_dotenv(env_path, interpolate=False)
|
||||
|
||||
def _index_transaction(self, bts_key: int):
|
||||
exch_key = uuid.uuid1().hex
|
||||
self.orders[exch_key] = bts_key
|
||||
return exch_key
|
||||
|
||||
def _on_user_data_msg_core(self, ws: websocket.WebSocket, msg: Any):
|
||||
self.logger.info("Recv usr data: %s", str(msg))
|
||||
if not msg:
|
||||
self.logger.error("Recv empty usr data msg")
|
||||
return
|
||||
if not self.bridge:
|
||||
self.logger.error("Cannot process usr data. Bridge not created")
|
||||
return
|
||||
upd = json.loads(str(msg))
|
||||
if "e" in upd:
|
||||
if upd["e"] == "executionReport":
|
||||
# Binance spots update
|
||||
bts_ord_id = self.orders.get(upd["c"])
|
||||
is_old_ord = False
|
||||
if not bts_ord_id:
|
||||
bts_ord_id = self.orders.get(upd["C"])
|
||||
if not bts_ord_id:
|
||||
self.logger.warning(
|
||||
"Received update with unknown order id: %s", msg
|
||||
)
|
||||
return
|
||||
is_old_ord = True
|
||||
er = pyexe.PyExecutionReport()
|
||||
er.set_key(bts_ord_id)
|
||||
er.set_exchange_security_id(upd["s"])
|
||||
er.set_security_type("SPOT")
|
||||
er.set_exec_type(to_bts_exec_type(upd["x"], upd["X"]))
|
||||
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"])
|
||||
total_filled_qty = float(upd["z"])
|
||||
er.set_filled_quantity(total_filled_qty)
|
||||
total_filled_notional = float(upd["Z"])
|
||||
avg_filled_price = (
|
||||
total_filled_notional / total_filled_qty
|
||||
if total_filled_qty > 0
|
||||
else math.nan
|
||||
)
|
||||
er.set_avg_filled_price(avg_filled_price)
|
||||
er.set_order_status(to_bts_order_status(upd["X"]))
|
||||
er.set_order_type(upd["o"])
|
||||
match upd["X"]:
|
||||
case "CANCELED":
|
||||
if not is_old_ord:
|
||||
del self.orders[bts_ord_id]
|
||||
case "FILLED":
|
||||
del self.orders[bts_ord_id]
|
||||
case "REJECTED":
|
||||
del self.orders[bts_ord_id]
|
||||
self.bridge.on_execution_report(er)
|
||||
elif upd["e"] == "ORDER_TRADE_UPDATE":
|
||||
data = upd["o"]
|
||||
# Binance Usds Futures order update
|
||||
bts_ord_id = self.orders.get(data["c"])
|
||||
is_old_ord = False
|
||||
if not bts_ord_id:
|
||||
bts_ord_id = self.orders.get(data["C"])
|
||||
if not bts_ord_id:
|
||||
self.logger.warning(
|
||||
"Received dataate with unknown order id: %s", msg
|
||||
)
|
||||
return
|
||||
is_old_ord = True
|
||||
|
||||
def parse_float(s: Optional[str], default_val=math.nan):
|
||||
if s is not None:
|
||||
try:
|
||||
return float(s)
|
||||
except Exception:
|
||||
pass
|
||||
return default_val
|
||||
|
||||
er = pyexe.PyExecutionReport()
|
||||
er.set_key(bts_ord_id)
|
||||
er.set_venue("BINANCE_USDS_FUTURES")
|
||||
er.set_security_type("FUTURE")
|
||||
er.set_time_in_force("GTC")
|
||||
er.set_exchange_order_id(str(data.get("i") or 0))
|
||||
# er.set_exchange_order_id(data["i"])
|
||||
er.set_exchange_security_id(data["s"])
|
||||
er.set_exec_type(to_bts_exec_type(data["x"], data["X"]))
|
||||
er.set_is_buy(data["S"] == "BUY")
|
||||
er.set_price(parse_float(data["p"]))
|
||||
er.set_quantity(parse_float(data["q"]))
|
||||
er.set_last_filled_price(parse_float(data.get("L")))
|
||||
er.set_last_filled_quantity(parse_float(data["l"]))
|
||||
er.set_filled_quantity(parse_float(data["z"]))
|
||||
er.set_avg_filled_price(parse_float(data["ap"]))
|
||||
er.set_order_status(to_bts_order_status(data["X"]))
|
||||
er.set_order_type(data["o"])
|
||||
match data["X"]:
|
||||
case "CANCELED":
|
||||
if not is_old_ord:
|
||||
del self.orders[bts_ord_id]
|
||||
case "FILLED":
|
||||
del self.orders[bts_ord_id]
|
||||
case "REJECTED":
|
||||
del self.orders[bts_ord_id]
|
||||
print("Firing this exe report: %s" % str(er), flush=True)
|
||||
self.bridge.on_execution_report(er)
|
||||
|
||||
def _on_user_data_msg(self, ws: websocket.WebSocket, msg: Any):
|
||||
try:
|
||||
self._on_user_data_msg_core(ws, msg)
|
||||
except Exception:
|
||||
self.logger.error("on_user_data_msg. %s" % traceback.format_exc())
|
||||
|
||||
def _on_user_data_open(self, ws: websocket.WebSocket):
|
||||
self.ws = ws
|
||||
if self.bridge:
|
||||
self.bridge.on_is_ready(True)
|
||||
|
||||
def _on_user_data_err(self, ws: websocket.WebSocket, err: str):
|
||||
self.logger.error("on_user_data_err: %s", err)
|
||||
|
||||
def _on_user_data_close(self, ws: websocket.WebSocket, code: int, msg: str):
|
||||
self.logger.warning("on_user_data_close: %s %s", str(code), msg)
|
||||
if self.bridge:
|
||||
self.bridge.on_is_ready(False)
|
||||
|
||||
def start(self, bridge: pyexe.ExecutionGatewayBridge):
|
||||
print("DummyExecutionGateway.start")
|
||||
self.bridge = bridge
|
||||
self.client = BinanceClient(venue="BINANCE_USDS_FUTURES")
|
||||
print("DummyExecutionGateway.start. Subscribing to binance user data")
|
||||
self.client.subscribe_user_data(
|
||||
on_message=self._on_user_data_msg,
|
||||
on_open=self._on_user_data_open,
|
||||
on_close=self._on_user_data_close,
|
||||
)
|
||||
print("DummyExecutionGateway.start. Subscribed to binance user data")
|
||||
|
||||
def cancel_order(self, req: pyexe.PyCancelOrderRequest):
|
||||
if not self.client:
|
||||
self.logger.error("Cannot cancel order. BinanceClient not created.")
|
||||
return
|
||||
self.logger.info("[cancel_order.json]%s", str(req))
|
||||
try:
|
||||
self.client.request(
|
||||
"CANCEL_ORDER",
|
||||
symbol=req.exchange_security_id(),
|
||||
orig_client_order_id=req.exchange_order_id(),
|
||||
new_client_order_id=self._index_transaction(req.key()),
|
||||
)
|
||||
except Exception as ex:
|
||||
self.logger.error("Create order request threw. %s" % str(ex))
|
||||
|
||||
def create_order(self, req: pyexe.PyCreateOrderRequest):
|
||||
if not self.client:
|
||||
self.logger.error("Cannot create order. BinanceClient not created.")
|
||||
return
|
||||
print("hey bud")
|
||||
self.logger.info("[create_order.json]%s", str(req))
|
||||
side = "BUY" if req.is_buy() else "SELL"
|
||||
try:
|
||||
self.client.request(
|
||||
op="CREATE_ORDER",
|
||||
symbol=req.exchange_security_id(),
|
||||
price=req.price(),
|
||||
quantity=f"{req.quantity():.6f}",
|
||||
side=side,
|
||||
time_in_force="GTC",
|
||||
type="LIMIT",
|
||||
new_client_order_id=self._index_transaction(req.key()),
|
||||
)
|
||||
except Exception as ex:
|
||||
self.logger.error("Create order request threw. %s" % str(ex))
|
||||
@@ -0,0 +1,158 @@
|
||||
import json
|
||||
import math
|
||||
import string
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from typing import Callable, Optional
|
||||
import websocket
|
||||
|
||||
import python_execution_module as pyexe
|
||||
|
||||
|
||||
def as_bool(*args):
|
||||
(True if arg else False for arg in args)
|
||||
|
||||
|
||||
def to_execution_report(
|
||||
req: pyexe.PyCreateOrderRequest
|
||||
| pyexe.PyCancelReplaceOrderRequest
|
||||
| pyexe.PyCancelOrderRequest,
|
||||
sec_type: Optional[str] = None,
|
||||
dst: Optional[pyexe.PyExecutionReport] = None,
|
||||
):
|
||||
if not dst:
|
||||
dst = pyexe.PyExecutionReport()
|
||||
dst.set_key(req.key())
|
||||
dst.set_exchange_security_id(req.exchange_security_id())
|
||||
dst.set_venue(req.venue())
|
||||
dst.set_is_buy(req.is_buy())
|
||||
if sec_type:
|
||||
dst.set_security_type(sec_type)
|
||||
if isinstance(req, pyexe.PyCreateOrderRequest):
|
||||
dst.set_order_type(req.order_type())
|
||||
elif isinstance(req, pyexe.PyCancelReplaceOrderRequest):
|
||||
pass
|
||||
elif isinstance(req, pyexe.PyCancelOrderRequest):
|
||||
pass
|
||||
return dst
|
||||
|
||||
|
||||
class StructuredLog:
|
||||
def __init__(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
|
||||
def __str__(self):
|
||||
return json.dumps(self.kwargs)
|
||||
|
||||
|
||||
class LogFormatter(logging.Formatter):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def formatTime(self, record, datefmt=None):
|
||||
ct = self.converter(record.created)
|
||||
if datefmt:
|
||||
return time.strftime(datefmt, ct)
|
||||
else:
|
||||
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
|
||||
return f"{t}.{int(record.msecs * 1000):06d}" # microseconds
|
||||
|
||||
def format(self, record):
|
||||
# Simulate a unique numeric ID
|
||||
timestamp_ns = int(record.created * 1e9)
|
||||
system = "OrderMan"
|
||||
env = "dev"
|
||||
thread_id = threading.get_ident()
|
||||
filename_line = f"{record.filename}:{record.lineno}"
|
||||
timestamp = self.formatTime(record)
|
||||
|
||||
return (
|
||||
f"{timestamp}|{timestamp_ns}|{system:<7}|{record.levelname:<5}|"
|
||||
f"{os.getpid():<3}|{record.threadName:<20}|{thread_id}|"
|
||||
f"{filename_line:<30}|{env}|{record.getMessage()}"
|
||||
)
|
||||
|
||||
|
||||
def configure_logger(logger: logging.Logger):
|
||||
stdout_handler = logging.StreamHandler(sys.stdout)
|
||||
file_handler = logging.FileHandler(
|
||||
f"/home/bts/sparkdata/data/logging.sparkd/{logger.name}_log"
|
||||
)
|
||||
formatter = LogFormatter()
|
||||
stdout_handler.formatter = formatter
|
||||
file_handler.formatter = formatter
|
||||
logger.handlers.clear()
|
||||
logger.addHandler(stdout_handler)
|
||||
logger.addHandler(file_handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
return logger
|
||||
|
||||
|
||||
def parse_float(s: Optional[str], default_val=math.nan):
|
||||
if s is not None:
|
||||
try:
|
||||
return float(s)
|
||||
except Exception:
|
||||
pass
|
||||
return default_val
|
||||
|
||||
|
||||
def load_gateway_config(name: str, expand_vars: bool = True):
|
||||
s = ""
|
||||
with open(f"/home/bts/sparkdata/conf/py_{name}.json") as f:
|
||||
s = f.read()
|
||||
if expand_vars:
|
||||
s = string.Template(s).substitute(os.environ)
|
||||
return json.loads(s)
|
||||
|
||||
|
||||
def run_websocket(
|
||||
url: str,
|
||||
stop_event: threading.Event,
|
||||
logger: logging.Logger,
|
||||
on_message: Callable[[str], None],
|
||||
send_ping: Optional[Callable[[websocket.WebSocket], None]] = None,
|
||||
ping_interval_secs: Optional[int] = 25,
|
||||
):
|
||||
conn_num = 0
|
||||
if send_ping is None:
|
||||
|
||||
def send_empty_ping(ws):
|
||||
return ws.ping()
|
||||
|
||||
send_ping = send_empty_ping
|
||||
|
||||
while not stop_event.is_set():
|
||||
if conn_num > 0:
|
||||
# Gradually increase sleep time between attempts, capping at 5min.
|
||||
sleep_secs = min(conn_num * 5, 300)
|
||||
logger.warning("Reconnecting to %s in %ds." % (url, sleep_secs))
|
||||
time.sleep(sleep_secs)
|
||||
logger.info("Connecting to %s (attempt no %d)" % (url, conn_num))
|
||||
ws = websocket.create_connection(url)
|
||||
ws.settimeout(5)
|
||||
logger.info("Connected to %s. Listening for data" % url)
|
||||
if ping_interval_secs:
|
||||
|
||||
def ping_loop(orig_conn_num):
|
||||
time.sleep(ping_interval_secs)
|
||||
while not stop_event.is_set() and conn_num == orig_conn_num:
|
||||
send_ping(ws)
|
||||
time.sleep(ping_interval_secs)
|
||||
|
||||
threading.Thread(target=ping_loop(conn_num), daemon=True).start()
|
||||
try:
|
||||
msg = ws.recv()
|
||||
if isinstance(msg, bytes):
|
||||
on_message(msg.decode("utf-8"))
|
||||
elif isinstance(msg, str):
|
||||
on_message(msg)
|
||||
else:
|
||||
logger.error("Websocket recv unexpected msg type %s" % str(type(msg)))
|
||||
|
||||
except Exception:
|
||||
logging.error("Websocket recv threw.", exc_info=True)
|
||||
continue
|
||||
@@ -0,0 +1,241 @@
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
|
||||
import threading
|
||||
from threading import Thread, Lock
|
||||
from time import sleep
|
||||
from typing import Any, Callable, Mapping
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
|
||||
import python_execution_module as pyexe
|
||||
import py_execution_utils
|
||||
import dotenv
|
||||
from binance_client import BinanceClient
|
||||
import websocket
|
||||
|
||||
|
||||
BINANCE_API_KEY = "2RJ9H02ztFGWxeY2oRpnFYZNU8mki4V1yMvKrDU08HCiEhO4VLe2ePSUFqEYTNxc"
|
||||
BINANCE_USDS_FUTURES_API_KEY = (
|
||||
"b838c108cd2648e34a4f088a7fc635a9cbccf3c2faa6bcaabcb532ffacc087b0"
|
||||
)
|
||||
BINANCE_USDS_FUTURES_SECRET_KEY = (
|
||||
"a68f0ab27403c42fa0306b6341b2ddd51d99ac42916f849404155449457d0492"
|
||||
)
|
||||
|
||||
|
||||
def to_bts_exec_type(exec_type: str, ord_status: str):
|
||||
match exec_type:
|
||||
case "TRADE_PREVENTION":
|
||||
return "REJECTED"
|
||||
case "NONE":
|
||||
return "UNDEFINED"
|
||||
case "TRADE":
|
||||
return "FILL" if ord_status == "FILLED" else "PARTIAL_FILL"
|
||||
case _:
|
||||
return exec_type
|
||||
|
||||
|
||||
def to_bts_order_status(ord_status: str):
|
||||
match ord_status:
|
||||
case "EXPIRED_IN_MATCH":
|
||||
return "EXPIRED"
|
||||
case _:
|
||||
return ord_status
|
||||
|
||||
|
||||
def invoke(target: Callable[[], Any]):
|
||||
t = threading.Thread(target=target)
|
||||
t.start()
|
||||
return t
|
||||
|
||||
|
||||
class SimpleTest(pyexe.ExecutionGateway):
|
||||
def __init__(self):
|
||||
super(SimpleTest, self).__init__()
|
||||
self.bridge = None
|
||||
self.client = None
|
||||
self.create_order_reqs = []
|
||||
self.threads = []
|
||||
self.ws = None
|
||||
self.lock = Lock()
|
||||
self.orders = {}
|
||||
self.logger = logging.getLogger(__name__)
|
||||
stdout_handler = logging.StreamHandler(sys.stdout)
|
||||
stdout_handler.formatter = logging.Formatter(
|
||||
"%(asctime)s | %(levelname)7s | %(filename)s:%(lineno)s | %(message)s"
|
||||
)
|
||||
self.logger.addHandler(stdout_handler)
|
||||
self.logger.addHandler(
|
||||
logging.FileHandler(
|
||||
"/home/bts/sparkdata/data/logging.python_execution/simple_test"
|
||||
)
|
||||
)
|
||||
self.logger.setLevel(logging.INFO)
|
||||
env_path = "/workspaces/spark/tools/binance/binance.env"
|
||||
self.logger.info("SimpleTest ctr. Loading env")
|
||||
dotenv.load_dotenv(env_path, interpolate=False)
|
||||
|
||||
def _invoke(self, target: Callable[[], Any], run_in_background: bool):
|
||||
if run_in_background:
|
||||
t = threading.Thread(target=target)
|
||||
self.threads.append(t)
|
||||
t.start()
|
||||
else:
|
||||
target()
|
||||
|
||||
def _index_transaction(self, bts_key: int):
|
||||
exch_key = uuid.uuid1().hex
|
||||
self.orders[exch_key] = bts_key
|
||||
return exch_key
|
||||
|
||||
def _on_user_data_open(self, ws: websocket.WebSocket):
|
||||
self.ws = ws
|
||||
if self.bridge:
|
||||
self.bridge.on_is_ready(True)
|
||||
|
||||
def _on_user_data_close(self, code: int, msg: str):
|
||||
self.logger.warning("on_user_data_close: %s %s", str(code), msg)
|
||||
if self.bridge:
|
||||
self.bridge.on_is_ready(False)
|
||||
|
||||
def start(self, bridge: pyexe.ExecutionGatewayBridge):
|
||||
print("DummyExecutionGateway.start")
|
||||
self.bridge = bridge
|
||||
self.client = BinanceClient(venue="BINANCE_USDS_FUTURES")
|
||||
print("DummyExecutionGateway.start. Subscribing to binance user data")
|
||||
print("DummyExecutionGateway.start. Subscribed to binance user data")
|
||||
|
||||
def delayed_ready():
|
||||
self.logger.info("SimpleTest.delayed_ready")
|
||||
sleep(0.5)
|
||||
if self.bridge:
|
||||
self.logger.info(
|
||||
"SimpleTest.delayed_ready. Notifying bridge that we're ready"
|
||||
)
|
||||
self.bridge.on_is_ready(True)
|
||||
else:
|
||||
self.logger.info(
|
||||
"SimpleTest.delayed_ready. Unable to notify bridge that we're ready (bridge is None!)"
|
||||
)
|
||||
|
||||
self._invoke(delayed_ready, True)
|
||||
|
||||
def cancel_order(self, req: pyexe.PyCancelOrderRequest):
|
||||
if not self.client:
|
||||
self.logger.error("Cannot cancel order. BinanceClient not created.")
|
||||
return
|
||||
self.logger.info("[cancel_order.json]%s", str(req))
|
||||
try:
|
||||
self.client.request(
|
||||
"CANCEL_ORDER",
|
||||
symbol=req.exchange_security_id(),
|
||||
orig_client_order_id=req.exchange_order_id(),
|
||||
new_client_order_id=self._index_transaction(req.key()),
|
||||
)
|
||||
except Exception as ex:
|
||||
self.logger.error("Create order request threw. %s" % str(ex))
|
||||
|
||||
def create_order(self, req: pyexe.PyCreateOrderRequest):
|
||||
if not self.client:
|
||||
self.logger.error("Cannot create order. BinanceClient not created.")
|
||||
return
|
||||
self.logger.info("create_order (async). %s" % str(req))
|
||||
|
||||
# local_req = pyexe.PyCreateOrderRequest()
|
||||
# local_req.set_exchange_security_id(req.exchange_security_id())
|
||||
# local_req.set_key(req.key())
|
||||
def impl():
|
||||
sleep(0.7)
|
||||
with self.lock:
|
||||
self.logger.info("create_order. %s" % str(req))
|
||||
er = pyexe.PyExecutionReport()
|
||||
er.set_key(7)
|
||||
er.set_exchange_security_id("BNBUSDT")
|
||||
er.set_exec_type("NEW")
|
||||
er.set_is_buy(True)
|
||||
er.set_price(650)
|
||||
er.set_quantity(0.02)
|
||||
er.set_last_filled_price(649.50)
|
||||
er.set_last_filled_quantity(0.012)
|
||||
er.set_filled_quantity(0.012)
|
||||
er.set_avg_filled_price(649.50)
|
||||
er.set_order_status("WORKING")
|
||||
er.set_order_type("LIMIT")
|
||||
|
||||
er.set_key(req.key())
|
||||
er.set_exchange_security_id(req.exchange_security_id())
|
||||
er.set_venue(req.venue())
|
||||
er.set_exec_type("NEW")
|
||||
er.set_is_buy(req.is_buy())
|
||||
er.set_price(req.price())
|
||||
er.set_quantity(req.quantity())
|
||||
er.set_last_filled_price(
|
||||
req.price() - 0.5 if req.is_buy() else req.price() + 0.5
|
||||
)
|
||||
er.set_last_filled_quantity(0.012)
|
||||
er.set_filled_quantity(0.012)
|
||||
er.set_avg_filled_price(er.last_filled_price())
|
||||
er.set_order_status("WORKING")
|
||||
er.set_order_type(req.order_type())
|
||||
if self.bridge:
|
||||
self.bridge.on_execution_report(er)
|
||||
|
||||
self._invoke(impl, True)
|
||||
self.logger.info("[create_order.json]%s", str(req))
|
||||
side = "BUY" if req.is_buy() else "SELL"
|
||||
try:
|
||||
res = self.client.request(
|
||||
op="CREATE_ORDER",
|
||||
symbol=req.exchange_security_id(),
|
||||
price=req.price(),
|
||||
quantity=f"{req.quantity():.6f}",
|
||||
side=side,
|
||||
time_in_force="GTC",
|
||||
type="LIMIT",
|
||||
new_client_order_id=self._index_transaction(req.key()),
|
||||
)
|
||||
print(str(res), flush=True)
|
||||
except Exception as ex:
|
||||
self.logger.error("Create order request threw. %s" % str(ex))
|
||||
|
||||
|
||||
# def create_order(client: BinanceClient, price, quantity, side, logger):
|
||||
# logger.info("[create_order.json]%s %d @ %d", side, quantity, price)
|
||||
# try:
|
||||
# res = client.request(
|
||||
# op="CREATE_ORDER",
|
||||
# symbol="BNBUSDT",
|
||||
# price=price,
|
||||
# quantity=f"{quantity:.5f}",
|
||||
# side=side,
|
||||
# time_in_force="GTC",
|
||||
# type="LIMIT",
|
||||
# # new_client_order_id=self._index_transaction(req.key()),
|
||||
# )
|
||||
# if res:
|
||||
# print("%d %s" % (res.status_code, res.text), flush=True)
|
||||
# except Exception as ex:
|
||||
# logger.error("Create order request threw. %s" % str(ex))
|
||||
|
||||
|
||||
# if __name__ == "__main__":
|
||||
# print("DummyExecutionGateway.start")
|
||||
# logger = logging.getLogger(__name__)
|
||||
# logger.setLevel(logging.INFO)
|
||||
# env_path = "/workspaces/spark/tools/binance/binance.env"
|
||||
# dotenv.load_dotenv(env_path, interpolate=False)
|
||||
# client = BinanceClient(venue="BINANCE_USDS_FUTURES")
|
||||
# # req = pyexe.PyCreateOrderRequest()
|
||||
# # req.set_exchange_security_id("BNBUSDT")
|
||||
# # req.set_price(650)
|
||||
# # req.set_quantity(0.015)
|
||||
# # req.set_is_buy(True)
|
||||
# # req.set_venue("BINANCE_USDS_FUTURES")
|
||||
# # req.set_order_type("LIMIT")
|
||||
# # req.set_key(5)
|
||||
# create_order(client, 650, 0.02, "BUY", logger)
|
||||
Reference in new issue
Block a user