FIX: Removed Normalize Contract Function-Not Needed.

This commit is contained in:
Adeel Khan committed 2025-07-14 22:35:36 +00:00
1 parent 3739532947
commit 026a8af893
1 file changed
+14 -129
@@ -27,22 +27,6 @@ import requests
logger = logging.getLogger("bybit_md_provider")
def normalize_contract_name(contract: str) -> str:
logger.info(f"Normalizing contract: input={contract}")
if "-" in contract: # Preserve delivery futures (e.g., BTC-26SEP25)
logger.info(f"Normalizing contract: output={contract} (unchanged, delivery future)")
return contract
if contract.endswith("PERP"):
result = contract[:-4] + "_PERP"
logger.info(f"Normalizing contract: output={result}")
return result
if len(contract) > 4:
result = contract[:-4] + "_" + contract[-4:]
logger.info(f"Normalizing contract: output={result}")
return result
logger.info(f"Normalizing contract: output={contract} (unchanged)")
return contract
def get_metadata(contracts: Iterable[str], use_testnet: bool = True) -> Dict[str, Dict]:
"""Fetch metadata for all linear contracts and filter for specified contracts."""
metadata_dict = {}
@@ -151,18 +135,6 @@ def fetch_futures_specs(contracts: Iterable[str], use_testnet: bool = True) -> D
logger.error(f"Failed to fetch futures contract specs: {e}", exc_info=True)
return specs_dict
def get_spot_specs(contracts: Iterable[str]) -> Dict[str, Dict]:
default_specs = {
"tick_unit": 1,
"tick_base": 10,
"cash_per_point": 0.1,
"qty_tick_unit": 1,
"qty_tick_base": 10000
}
specs_dict = {contract: {"specs": default_specs} for contract in contracts}
logger.info(f"Using default specs for spot contracts: {default_specs}")
return specs_dict
def get_expiration(contract: Dict) -> str:
"""Extract expiration from metadata or use default if none."""
if contract.get("status") == "Expired":
@@ -202,7 +174,6 @@ class BybitMdProvider(MdProvider):
super().__init__()
self._config: Optional[dict] = None
self.ws_futures = None
# self.ws_spot = None # Commented out spot WebSocket
self.ws_thread: Optional[threading.Thread] = None
self.bridge: Optional[MdBridge] = None
self.stop_event = threading.Event()
@@ -225,10 +196,6 @@ class BybitMdProvider(MdProvider):
def futures(self):
return self.config.get("futures", [])
@property
def spots(self):
return self.config.get("spots", [])
def start_impl(self, bridge: MdBridge):
configure_logger(logger, "md", level="INFO", **self.config.get("logging", {})) # Enforce INFO level
self.bridge = bridge
@@ -237,7 +204,6 @@ class BybitMdProvider(MdProvider):
# Load futures contracts dynamically from API based on base symbols
futures_contracts = get_futures_contracts(self.futures, self.use_testnet)
logger.info(f"futures_contracts: {futures_contracts}")
# spot_contracts = list(map(lambda s: s + "USDT", self.spots)) # Commented out spot contracts
# Fetch metadata for all specified futures contracts
metadata = get_metadata(futures_contracts, self.use_testnet)
@@ -248,10 +214,8 @@ class BybitMdProvider(MdProvider):
futures_specs = fetch_futures_specs(futures_contracts, self.use_testnet)
logger.info(f"Fetched futures specs for {len(futures_specs)} contracts")
logger.info(f"futures_specs: {futures_specs}")
# spot_specs = get_spot_specs(spot_contracts) # Commented out spot specs
sec_list_futures = PySecurityList()
# sec_list_spots = PySecurityList() # Commented out spot security list
for contract in futures_contracts:
meta = metadata.get(contract, {})
@@ -282,7 +246,7 @@ class BybitMdProvider(MdProvider):
specs = futures_specs.get(contract, {}).get("specs", {})
if not specs:
logger.warning(f"No specs found for contract: {contract}, using defaults")
specs = {"tick_unit": 1, "tick_base": 10, "cash_per_point": 0.1, "qty_tick_unit": 1, "qty_tick_base": 10000}
specs = {"tick_unit": 1, "tick_base": 10, "cash_per_point": 1, "qty_tick_unit": 1, "qty_tick_base": 10000}
try:
qty_info = get_quantity_info(
@@ -298,7 +262,7 @@ class BybitMdProvider(MdProvider):
price_info=get_price_info(
tick_unit=specs.get("tick_unit", 1),
tick_base=specs.get("tick_base", 10),
cash_per_point=specs.get("cash_per_point", 0.1)
cash_per_point=specs.get("cash_per_point", 1)
),
qty_info=qty_info
)
@@ -328,63 +292,11 @@ class BybitMdProvider(MdProvider):
logger.error(f"Error processing metadata for {contract}: {e}", exc_info=True)
continue
# for contract in spot_contracts: # Commented out spot security creation
# normalized_contract = normalize_contract_name(contract)
# try:
# asset, quote = normalized_contract.split("_")
# quote = "USDT"
# except ValueError as e:
# logger.error(f"Failed to split normalized spot contract {normalized_contract}: {e}")
# continue
# specs = spot_specs.get(contract, {}).get("specs", {})
#
# try:
# qty_info = get_quantity_info(
# tick_unit=specs.get("qty_tick_unit", 1),
# tick_base=specs.get("qty_tick_base", 10000)
# )
# except Exception as e:
# logger.error(f"Failed to get quantity info for spot contract: {contract}, error: {e}")
# continue
#
# try:
# spec = get_contract_spec(
# price_info=get_price_info(
# tick_unit=specs.get("tick_unit", 1),
# tick_base=specs.get("tick_base", 10),
# cash_per_point=specs.get("cash_per_point", 0.1)
# ),
# qty_info=qty_info
# )
# except Exception as e:
# logger.error(f"Failed to get contract spec for spot contract: {contract}, error: {e}")
# continue
#
# try:
# sec = get_security(
# venue="Bybit",
# name=contract,
# asset=asset,
# group=asset,
# currency=quote,
# expiration=None,
# option_kind=None,
# strike=None,
# spec=spec,
# )
# sec_list_spots.append(sec)
# logger.info(f"Created SPOT security: {contract} (market_type=SPOT, expiration=None) with specs: {specs}")
# except Exception as e:
# logger.error(f"Failed to create SPOT security for contract: {contract}, error: {e}", exc_info=True)
# continue
combined_sec_list = PySecurityList()
for sec in sec_list_futures:
combined_sec_list.append(sec)
# for sec in sec_list_spots: # Commented out spot securities
# combined_sec_list.append(sec)
bridge.on_securities(combined_sec_list)
logger.info(f"Sent securities list: {len(sec_list_futures)} futures, 0 spots")
logger.info(f"Sent securities list: {len(sec_list_futures)} futures")
try:
self.ws_futures = WebSocket(
@@ -403,23 +315,6 @@ class BybitMdProvider(MdProvider):
logger.info(f"Subscribed to orderbook.50.{contract} (futures)")
except Exception as e:
logger.error(f"Failed to subscribe to orderbook for {contract} (futures): {e}")
# self.ws_spot = WebSocket( # Commented out spot WebSocket
# testnet=self.use_testnet,
# channel_type="spot",
# ping_interval=20,
# )
# logger.info("Connecting to Bybit WebSocket (spot)")
#
# for contract in spot_contracts:
# try:
# self.ws_spot.orderbook_stream(
# symbol=contract,
# depth=50,
# callback=lambda data: self._on_book_update(data, source="spot")
# )
# logger.info(f"Subscribed to orderbook.50.{contract} (spot)")
# except Exception as e:
# logger.error(f"Failed to subscribe to orderbook for {contract} (spot): {e}")
logger.info("Subscribed to orderbook channels on Bybit futures WS.")
for t in threading.enumerate():
logger.debug(f"Thread (start): Name={t.name}, Alive={t.is_alive()}, Daemon={t.daemon}, Target={t._target}")
@@ -462,7 +357,7 @@ class BybitMdProvider(MdProvider):
sorted_asks += [(np.float64('nan'), np.float64('nan'))]
logger.info(f"📘 BOOK DATA for {contract} (source={source}): bids={sorted_bids} asks={sorted_asks}")
book = PyBook()
market_type = "SPOT" if source == "spot" else "FUTURE"
market_type = "FUTURE" # Only futures now
logger.debug(f"Assigned market_type={market_type} for contract={contract} (source={source})")
book.set_data(
contract,
@@ -484,37 +379,27 @@ class BybitMdProvider(MdProvider):
def stop(self):
logger.info("Stopping BybitMdProvider...")
self.stop_event.set()
logger.debug("Threads before stopping WebSocket:")
for t in threading.enumerate():
logger.debug(f"Thread(stop): {t.name}, Alive: {t.is_alive()}, Daemon: {t.daemon}, Target={t._target}")
for ws, ws_type in [(self.ws_futures, "futures")]: # Commented out spot WebSocket
# , (self.ws_spot, "spot")
if ws:
try:
ws.exit()
logger.info(f"WebSocket ({ws_type}) exit called")
for t in threading.enumerate():
if t.name in ['Thread-1 (<lambda>)', 'Thread-2 (_send_ping)'] and t.is_alive():
logger.info(f"Joining pybit thread: {t.name} ({ws_type})")
t.join(timeout=1.0)
except Exception as e:
logger.error(f"Error while closing WebSocket ({ws_type}): {e}", exc_info=True)
ws = None
if self.ws_futures:
try:
self.ws_futures.exit()
logger.info("WebSocket (futures) exit called")
for t in threading.enumerate():
if t.name in ['Thread-1 (<lambda>)', 'Thread-2 (_send_ping)'] and t.is_alive():
logger.info(f"Joining pybit thread: {t.name} (futures)")
t.join(timeout=1.0)
except Exception as e:
logger.error(f"Error while closing WebSocket (futures): {e}", exc_info=True)
self.ws_futures = None
# self.ws_spot = None # Commented out spot WebSocket
if self.ws_thread:
self.ws_thread.join()
self.bridge = None
logger.info("✔ Stopped BybitMdProvider.")
logger.debug("Threads after stop:")
for t in threading.enumerate():
logger.debug(f"Thread(after stop): {t.name}, Alive: {t.is_alive()}, Daemon: {t.daemon}, Target={t._target}")
import os
os._exit(0)