ADD: GATEIO md_provider with default contract specs
This commit is contained in:
1 parent
c470984bd2
commit
80f4b4bc1c
4 files changed
+245
-2
No files matched your search
@@ -0,0 +1,29 @@
|
||||
# Gate.io WebSocket configuration
|
||||
WS_URL = "wss://fx-ws-testnet.gateio.ws/v4/ws/usdt" # Testnet url for perp futures
|
||||
|
||||
# API credentials
|
||||
API_KEY = "e4a0c6b198549042b13faa7645640d60"
|
||||
API_SECRET = "527c37877efc247bb0b6158cf3d5d18b84db720da894307f1e2ab88df3aaf0ee"
|
||||
|
||||
# Futures contract to subscribe to:
|
||||
|
||||
CONTRACTS = ['MELON_USDT', 'CAKE_USDT', 'ETH_USDT', 'KLAY_USDT', 'RON_USDT',
|
||||
'MANA_USDT', 'BZZ_USDT', 'KEEP_USDT', 'OMG_USDT', 'GMX_USDT', 'ICP_USDT',
|
||||
'LRC_USDT', 'MINA_USDT', 'ZIL_USDT', 'TURBO_USDT', 'OP_USDT', 'ZRX_USDT',
|
||||
'VET_USDT', 'AR_USDT', 'IMX_USDT', 'HIGH_USDT', 'ARB_USDT', 'YFI_USDT',
|
||||
'NEAR_USDT', 'OXY_USDT', 'WAVES_USDT', 'AMP_USDT', 'CELO_USDT', 'CRV_USDT',
|
||||
'FIL_USDT', 'PEOPLE_USDT', 'IOTX_USDT', 'ATOM_USDT', 'NOT_USDT', 'HBAR_USDT',
|
||||
'GMT_USDT', 'KAVA_USDT', 'WIF_USDT', 'UNI_USDT', 'GALA_USDT', 'AAVE_USDT',
|
||||
'CRU_USDT', 'PEPE_USDT', 'TWT_USDT', 'IRIS_USDT', 'APE_USDT', 'BNB_USDT',
|
||||
'ATLAS_USDT', 'BCHA_USDT', 'ETHW_USDT', 'DOT_USDT', 'TONCOIN_USDT', 'DOGS_USDT',
|
||||
'MER_USDT', 'ADA_USDT', 'TRIBE_USDT', 'THETA_USDT', 'BTC_USDT', 'ORDI_USDT',
|
||||
'ANKR_USDT', 'KIN_USDT', 'AMPL_USDT', 'TRX_USDT', 'SAND_USDT', 'SERO_USDT',
|
||||
'LUNC_USDT', 'BAT_USDT', 'KSM_USDT', 'SOL_USDT', 'AXS_USDT', 'BCD_USDT',
|
||||
'TIA_USDT', 'WOO_USDT', 'QTUM_USDT', 'OLDLUNA_USDT', 'AVAX_USDT', 'EOS_USDT',
|
||||
'SNX_USDT', 'MKR_USDT', 'ZKS_USDT', 'XRP_USDT', 'STEP_USDT', 'COMP_USDT',
|
||||
'UST_USDT', 'WSB_USDT', 'LINK_USDT', 'LUNA_USDT', 'ETC_USDT', 'JST_USDT',
|
||||
'LON_USDT', 'PEARL_USDT', 'BTT_USDT', 'XLM_USDT', 'GRT_USDT', 'STX_USDT',
|
||||
'NU_USDT', 'ALGO_USDT', 'ROSE_USDT', 'SHIB_USDT', 'BSV_USDT', 'ENJ_USDT',
|
||||
'USTC_USDT', 'NEO_USDT', 'FLOW_USDT', 'RUNE_USDT', 'FIL6_USDT', 'APT_USDT',
|
||||
'DOGE_USDT', 'CHZ_USDT', '1INCH_USDT', 'CSPR_USDT', 'XEC_USDT', 'ENS_USDT',
|
||||
'IOST_USDT', 'LDO_USDT', 'XTZ_USDT']
|
||||
@@ -0,0 +1,184 @@
|
||||
import json
|
||||
import time
|
||||
import logging
|
||||
import sys
|
||||
import threading
|
||||
from websocket import create_connection, WebSocketConnectionClosedException
|
||||
from typing import Optional, Any
|
||||
import python_md_module as pymd
|
||||
from config import WS_URL, CONTRACTS
|
||||
from py_md_utils import (
|
||||
get_contract_spec,
|
||||
get_price_info,
|
||||
get_quantity_info,
|
||||
get_security,
|
||||
get_book_side,
|
||||
)
|
||||
|
||||
|
||||
# Logging setup
|
||||
LOG_PATH = "/home/bts/sparkdata/data/gateio_md_provider.log"
|
||||
logging.basicConfig(
|
||||
filename=LOG_PATH,
|
||||
level=logging.DEBUG,
|
||||
format="%(asctime)s|%(levelname)s|%(message)s",
|
||||
)
|
||||
console = logging.StreamHandler(sys.stdout)#sends logs to the terminal too
|
||||
console.setLevel(logging.INFO)#only sends info and higher (np debug)
|
||||
formatter = logging.Formatter("%(asctime)s|%(levelname)s|%(message)s")#format for terminal logs
|
||||
console.setFormatter(formatter)#attaching to console handler to root logger, so both are written
|
||||
logging.getLogger().addHandler(console)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class GateIoMdProvider(pymd.MdProvider):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.ws = None
|
||||
self.stop_event = threading.Event()
|
||||
self.sink = None
|
||||
|
||||
def send_ping(self):
|
||||
"""Send ping messages every 15 seconds to keep connection alive."""
|
||||
while not self.stop_event.is_set():
|
||||
try:
|
||||
ping_msg = {
|
||||
"time": int(time.time() * 1000),
|
||||
"channel": "futures.ping",
|
||||
"event": "",
|
||||
"payload": []
|
||||
}
|
||||
self.ws.send(json.dumps(ping_msg))
|
||||
logging.debug("Sent ping")
|
||||
except Exception as e:
|
||||
logging.error(f"Ping error: {e}", exc_info=True)
|
||||
break
|
||||
time.sleep(15)
|
||||
|
||||
def start(self, sink: pymd.MdSink):
|
||||
self.sink = sink
|
||||
logging.info(f"Connecting to {WS_URL}")
|
||||
self.ws = create_connection(WS_URL)
|
||||
self.ws.settimeout(5)
|
||||
logging.info("Connected.")
|
||||
|
||||
|
||||
# Start ping thread
|
||||
self.ping_thread = threading.Thread(target=self.send_ping, daemon=True)
|
||||
self.ping_thread.start()
|
||||
logging.info("Started ping thread")
|
||||
|
||||
|
||||
# 1) Send security info
|
||||
sec_list = pymd.PySecurityList()
|
||||
for contract in CONTRACTS:
|
||||
asset, quote = contract.split("_")
|
||||
spec = get_contract_spec(
|
||||
price_info=get_price_info(tick_unit=1, tick_base=10, cash_per_point=0.1), # BTC_USDT: 0.1 USDT tick
|
||||
qty_info=get_quantity_info(tick_unit=1, tick_base=10000), # 1 contract = 0.0001 BTC
|
||||
)
|
||||
sec = get_security(
|
||||
venue="GateIO",
|
||||
name=contract,
|
||||
asset=asset,
|
||||
group=asset,
|
||||
currency=quote,
|
||||
expiration=None,
|
||||
option_kind=None,
|
||||
strike=None,
|
||||
spec=spec,
|
||||
)
|
||||
sec_list.append(sec)
|
||||
logging.info(f"Created security: {contract}")
|
||||
sink.on_securities(sec_list)
|
||||
logging.info("Sent securities list--sink.on_securities called.")
|
||||
|
||||
# 2) Subscribe to order books
|
||||
for contract in CONTRACTS:
|
||||
sub_msg = {
|
||||
"time": int(time.time() * 1000), # Milliseconds
|
||||
"channel": "futures.order_book",
|
||||
"event": "subscribe",
|
||||
"payload": [contract, "5", "0"]
|
||||
}
|
||||
self.ws.send(json.dumps(sub_msg))
|
||||
logging.info(f"✔ Sent subscribe for {contract}: {sub_msg}")
|
||||
|
||||
# 3) Listen for incoming messages in main thread
|
||||
logging.info("▶ Listening for data")
|
||||
try:
|
||||
while not self.stop_event.is_set():
|
||||
try:
|
||||
msg = self.ws.recv()
|
||||
except Exception as e:
|
||||
logging.debug(f"⚠ recv() error or timeout: {e}")
|
||||
continue
|
||||
|
||||
logging.debug(f"⟵ raw WS: {msg}")
|
||||
try:
|
||||
data = json.loads(msg)
|
||||
logging.debug(f"Parsed JSON: {data}")
|
||||
except Exception as e:
|
||||
logging.error(f"JSON parse error: {e}", exc_info=True)
|
||||
continue
|
||||
|
||||
event = data.get("event")
|
||||
channel = data.get("channel")
|
||||
|
||||
# Handle subscription acknowledgements
|
||||
if event == "subscribe":
|
||||
logging.info(f"🔔 Subscribe ACK: {data}")
|
||||
continue
|
||||
|
||||
# Handle order book updates
|
||||
if channel == "futures.order_book" and event in ["all", "update"]:
|
||||
logging.info(f"Handling '{event}' event")
|
||||
payload = data.get("result", {})#result has the t, contract, id, bids, asks and l
|
||||
if isinstance(payload, dict) and ("bids" in payload or "asks" in payload):
|
||||
contract = payload.get("contract", "<no-contract>")
|
||||
bids = [(float(l["p"]), float(l["s"])) for l in payload.get("bids", [])]
|
||||
asks = [(float(l["p"]), float(l["s"])) for l in payload.get("asks", [])]
|
||||
logging.debug(f"📘 BOOK DATA for {contract}: bids={bids} asks={asks}")
|
||||
|
||||
book = pymd.PyBook()
|
||||
book.set_venue("GateIO")
|
||||
book.set_security_type("SPOT")
|
||||
book.set_exchange_security_id(contract)
|
||||
book.set_bids(get_book_side(bids, True))
|
||||
book.set_asks(get_book_side(asks, False))
|
||||
|
||||
book_list = pymd.PyBookList()
|
||||
book_list.append(book)
|
||||
self.sink.on_books(book_list)
|
||||
logging.info(f"✔ on_books called for {contract}")
|
||||
else:
|
||||
logging.debug("… no bids/asks in payload; skipping")
|
||||
|
||||
except WebSocketConnectionClosedException:
|
||||
logging.info("WebSocket closed.")
|
||||
except Exception as e:
|
||||
logging.error("Fatal error in listen loop:", exc_info=True)
|
||||
finally:
|
||||
self.stop()
|
||||
|
||||
def stop(self):
|
||||
"""Disconnect and cleanup."""
|
||||
logging.info("Stopping GateIoMdProvider...")
|
||||
self.stop_event.set()
|
||||
|
||||
if self.ping_thread and self.ping_thread.is_alive():
|
||||
self.ping_thread.join()
|
||||
logging.info("Ping thread stopped")
|
||||
|
||||
if self.ws:
|
||||
try:
|
||||
self.ws.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.ws = None
|
||||
|
||||
self.sink = None
|
||||
logging.info("✔ Stopped GateIoMdProvider.")
|
||||
|
||||
Reference in new issue
Block a user