fix: Actually use configured logger in bybit_md_provider.py
This commit is contained in:
1 parent
112527f9ed
commit
8a0fcce90d
1 file changed
+40
-32
@@ -8,6 +8,7 @@ import signal
|
||||
from typing import Optional
|
||||
from pybit.unified_trading import WebSocket
|
||||
import python_md_module as pymd
|
||||
import python_core_module as pycore
|
||||
from bybit_conf import CONTRACTS
|
||||
from spark_core import (
|
||||
configure_logger,
|
||||
@@ -19,7 +20,8 @@ from spark_core import (
|
||||
from py_md_utils import PERP_EXP_STRING
|
||||
import requests
|
||||
|
||||
configure_logger(logging.getLogger("bybit_md_provider"), "md")
|
||||
logger = logging.getLogger("bybit_md_provider")
|
||||
configure_logger(logger, "md")
|
||||
|
||||
def normalize_contract_name(contract: str) -> str:
|
||||
if len(contract) > 4:
|
||||
@@ -61,10 +63,10 @@ def fetch_contract_specs() -> dict:
|
||||
found_contracts.add(contract)
|
||||
for contract in CONTRACTS:
|
||||
if contract not in found_contracts:
|
||||
logging.warning(f"Contract {contract} not found in API response, using default specs")
|
||||
logger.warning(f"Contract {contract} not found in API response, using default specs")
|
||||
return specs_dict
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to fetch contract specs: {e}", exc_info=True)
|
||||
logger.error(f"Failed to fetch contract specs: {e}", exc_info=True)
|
||||
return specs_dict
|
||||
|
||||
class BybitMdProvider(pymd.MdProvider):
|
||||
@@ -79,7 +81,7 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
def _setup_signal_handlers(self):
|
||||
"""Set up signal handlers for SIGINT, SIGTERM, and SIGTSTP."""
|
||||
def signal_handler(sig, frame):
|
||||
logging.info(f"Received signal {sig}, stopping...")
|
||||
logger.info(f"Received signal {sig}, stopping...")
|
||||
self.stop()
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
@@ -88,10 +90,10 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
|
||||
def start_impl(self, bridge: pymd.MdBridge):
|
||||
self.bridge = bridge
|
||||
logging.info("Starting BybitMdProvider")
|
||||
logger.info("Starting BybitMdProvider")
|
||||
|
||||
contract_specs = fetch_contract_specs()
|
||||
sec_list = pymd.PySecurityList()
|
||||
sec_list = pycore.PySecurityList()
|
||||
|
||||
for contract in CONTRACTS:
|
||||
normalized_contract = normalize_contract_name(contract)
|
||||
@@ -104,7 +106,7 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
tick_base=specs.get("qty_tick_base", 10000)
|
||||
)
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to get quantity info for contract: {contract}, error: {e}")
|
||||
logger.error(f"Failed to get quantity info for contract: {contract}, error: {e}")
|
||||
continue
|
||||
|
||||
try:
|
||||
@@ -117,7 +119,7 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
qty_info=qty_info
|
||||
)
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to get contract spec for contract: {contract}, error: {e}")
|
||||
logger.error(f"Failed to get contract spec for contract: {contract}, error: {e}")
|
||||
continue
|
||||
|
||||
try:
|
||||
@@ -133,13 +135,13 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
spec=spec,
|
||||
)
|
||||
sec_list.append(sec)
|
||||
logging.info(f"Created security: {contract} with specs: {specs}")
|
||||
logger.info(f"Created security: {contract} with specs: {specs}")
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to create security for contract: {contract}, error: {e}")
|
||||
logger.error(f"Failed to create security for contract: {contract}, error: {e}")
|
||||
continue
|
||||
|
||||
bridge.on_securities(sec_list)
|
||||
logging.info("Sent securities list--bridge.on_securities called.")
|
||||
logger.info("Sent securities list--bridge.on_securities called.")
|
||||
|
||||
try:
|
||||
self.ws = WebSocket(
|
||||
@@ -147,7 +149,7 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
channel_type="linear",
|
||||
ping_interval=20,
|
||||
)
|
||||
logging.info("Connecting to Bybit WebSocket (mainnet, linear)")
|
||||
logger.info("Connecting to Bybit WebSocket (mainnet, linear)")
|
||||
|
||||
for contract in CONTRACTS:
|
||||
try:
|
||||
@@ -156,27 +158,33 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
depth=50,
|
||||
callback=self._on_book_update
|
||||
)
|
||||
logging.info(f"Subscribed to orderbook.50.{contract}")
|
||||
logger.info(f"Subscribed to orderbook.50.{contract}")
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to subscribe to orderbook for {contract}, error: {e}")
|
||||
logger.error(f"Failed to subscribe to orderbook for {contract}, error: {e}")
|
||||
|
||||
logging.info("Subscribed to orderbook channels on Bybit unified trading WS.")
|
||||
logger.info("Subscribed to orderbook channels on Bybit unified trading WS.")
|
||||
|
||||
for t in threading.enumerate():
|
||||
logging.debug(f"Thread (start): Name={t.name}, Alive={t.is_alive()}, Daemon={t.daemon}, Target={t._target}")
|
||||
logger.debug(f"Thread (start): Name={t.name}, Alive={t.is_alive()}, Daemon={t.daemon}, Target={t._target}")
|
||||
|
||||
while not self.stop_event.is_set():
|
||||
time.sleep(0.05)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logging.info("KeyboardInterrupt received — shutting down.")
|
||||
logger.info("KeyboardInterrupt received — shutting down.")
|
||||
self.stop()
|
||||
except Exception as e:
|
||||
logging.error(f"Bybit WebSocket fatal error: {e}", exc_info=True)
|
||||
logger.error(f"Bybit WebSocket fatal error: {e}", exc_info=True)
|
||||
self.stop()
|
||||
|
||||
def start(self, bridge: pymd.MdBridge):
|
||||
self.ws_thread = threading.Thread(target=lambda: self.start_impl(bridge))
|
||||
def start_wrapper():
|
||||
try:
|
||||
self.start_impl(bridge)
|
||||
except Exception as e:
|
||||
logger.error(f"Error in BybitMdProvider start_impl: {e}", exc_info=True)
|
||||
|
||||
self.ws_thread = threading.Thread(target=start_wrapper)
|
||||
self.ws_thread.start()
|
||||
|
||||
def _on_book_update(self, data: dict):
|
||||
@@ -196,7 +204,7 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
sorted_asks = sorted(raw_asks, key=lambda x: x[0])[:5]
|
||||
sorted_asks += [(np.float64('nan'), np.float64('nan'))]
|
||||
|
||||
logging.debug(f"📘 BOOK DATA for {contract}: bids={sorted_bids} asks={sorted_asks}")
|
||||
logger.debug(f"📘 BOOK DATA for {contract}: bids={sorted_bids} asks={sorted_asks}")
|
||||
|
||||
book = pymd.PyBook()
|
||||
book.set_data(
|
||||
@@ -210,41 +218,41 @@ class BybitMdProvider(pymd.MdProvider):
|
||||
book_list.append(book)
|
||||
if self.bridge:
|
||||
self.bridge.on_books(book_list)
|
||||
logging.debug(f"✔ on_books called for {contract}")
|
||||
logger.debug(f"✔ on_books called for {contract}")
|
||||
else:
|
||||
logging.warning("Bridge is None, cannot call on_books")
|
||||
logger.warning("Bridge is None, cannot call on_books")
|
||||
except Exception as e:
|
||||
logging.error(f"Error processing book update for {contract}: {e}", exc_info=True)
|
||||
logger.error(f"Error processing book update for {contract}: {e}", exc_info=True)
|
||||
|
||||
def stop(self):
|
||||
logging.info("Stopping BybitMdProvider...")
|
||||
logger.info("Stopping BybitMdProvider...")
|
||||
self.stop_event.set()
|
||||
|
||||
logging.debug("Threads before stopping WebSocket:")
|
||||
logger.debug("Threads before stopping WebSocket:")
|
||||
for t in threading.enumerate():
|
||||
logging.debug(f"Thread(stop): {t.name}, Alive: {t.is_alive()}, Daemon: {t.daemon}, Target={t._target}")
|
||||
logger.debug(f"Thread(stop): {t.name}, Alive: {t.is_alive()}, Daemon: {t.daemon}, Target={t._target}")
|
||||
|
||||
if self.ws:
|
||||
try:
|
||||
self.ws.exit()
|
||||
logging.info("WebSocket exit called")
|
||||
logger.info("WebSocket exit called")
|
||||
# Clean up pybit threads with longer timeout
|
||||
for t in threading.enumerate():
|
||||
if t.name in ['Thread-1 (<lambda>)', 'Thread-2 (_send_ping)'] and t.is_alive():
|
||||
logging.info(f"Joining pybit thread: {t.name}")
|
||||
logger.info(f"Joining pybit thread: {t.name}")
|
||||
t.join(timeout=1.0)
|
||||
except Exception as e:
|
||||
logging.error(f"Error while closing WebSocket: {e}", exc_info=True)
|
||||
logger.error(f"Error while closing WebSocket: {e}", exc_info=True)
|
||||
self.ws = None
|
||||
|
||||
if self.ws_thread:
|
||||
self.ws_thread.join()
|
||||
self.bridge = None
|
||||
logging.info("✔ Stopped BybitMdProvider.")
|
||||
logger.info("✔ Stopped BybitMdProvider.")
|
||||
|
||||
logging.debug("Threads after stop:")
|
||||
logger.debug("Threads after stop:")
|
||||
for t in threading.enumerate():
|
||||
logging.debug(f"Thread(after stop): {t.name}, Alive: {t.is_alive()}, Daemon: {t.daemon}, Target={t._target}")
|
||||
logger.debug(f"Thread(after stop): {t.name}, Alive: {t.is_alive()}, Daemon: {t.daemon}, Target={t._target}")
|
||||
|
||||
import os
|
||||
os._exit(0)
|
||||
Reference in new issue
Block a user