168 lines
6.1 KiB
Python
168 lines
6.1 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Example usage of Binance connector.
|
|
"""
|
|
|
|
import asyncio
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# Add COBY to path
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
|
|
from connectors.binance_connector import BinanceConnector
|
|
from utils.logging import setup_logging, get_logger
|
|
from models.core import OrderBookSnapshot, TradeEvent
|
|
|
|
# Setup logging
|
|
setup_logging(level='INFO', console_output=True)
|
|
logger = get_logger(__name__)
|
|
|
|
|
|
class BinanceExample:
|
|
"""Example Binance connector usage"""
|
|
|
|
def __init__(self):
|
|
self.connector = BinanceConnector()
|
|
self.orderbook_count = 0
|
|
self.trade_count = 0
|
|
|
|
# Add data callbacks
|
|
self.connector.add_data_callback(self.on_data_received)
|
|
self.connector.add_status_callback(self.on_status_changed)
|
|
|
|
def on_data_received(self, data):
|
|
"""Handle received data"""
|
|
if isinstance(data, OrderBookSnapshot):
|
|
self.orderbook_count += 1
|
|
logger.info(
|
|
f"📊 Order Book {self.orderbook_count}: {data.symbol} - "
|
|
f"Mid: ${data.mid_price:.2f}, Spread: ${data.spread:.2f}, "
|
|
f"Bids: {len(data.bids)}, Asks: {len(data.asks)}"
|
|
)
|
|
|
|
elif isinstance(data, TradeEvent):
|
|
self.trade_count += 1
|
|
logger.info(
|
|
f"💰 Trade {self.trade_count}: {data.symbol} - "
|
|
f"{data.side.upper()} {data.size} @ ${data.price:.2f}"
|
|
)
|
|
|
|
def on_status_changed(self, exchange, status):
|
|
"""Handle status changes"""
|
|
logger.info(f"🔄 {exchange} status changed to: {status.value}")
|
|
|
|
async def run_example(self):
|
|
"""Run the example"""
|
|
try:
|
|
logger.info("🚀 Starting Binance connector example")
|
|
|
|
# Connect to Binance
|
|
logger.info("🔌 Connecting to Binance...")
|
|
connected = await self.connector.connect()
|
|
|
|
if not connected:
|
|
logger.error("❌ Failed to connect to Binance")
|
|
return
|
|
|
|
logger.info("✅ Connected to Binance successfully")
|
|
|
|
# Get available symbols
|
|
logger.info("📋 Getting available symbols...")
|
|
symbols = await self.connector.get_symbols()
|
|
logger.info(f"📋 Found {len(symbols)} trading symbols")
|
|
|
|
# Show some popular symbols
|
|
popular_symbols = ['BTCUSDT', 'ETHUSDT', 'ADAUSDT', 'BNBUSDT']
|
|
available_popular = [s for s in popular_symbols if s in symbols]
|
|
logger.info(f"📋 Popular symbols available: {available_popular}")
|
|
|
|
# Get order book snapshot
|
|
if 'BTCUSDT' in symbols:
|
|
logger.info("📊 Getting BTC order book snapshot...")
|
|
orderbook = await self.connector.get_orderbook_snapshot('BTCUSDT', depth=10)
|
|
if orderbook:
|
|
logger.info(
|
|
f"📊 BTC Order Book: Mid=${orderbook.mid_price:.2f}, "
|
|
f"Spread=${orderbook.spread:.2f}"
|
|
)
|
|
|
|
# Subscribe to real-time data
|
|
logger.info("🔔 Subscribing to real-time data...")
|
|
|
|
# Subscribe to BTC order book and trades
|
|
if 'BTCUSDT' in symbols:
|
|
await self.connector.subscribe_orderbook('BTCUSDT')
|
|
await self.connector.subscribe_trades('BTCUSDT')
|
|
logger.info("✅ Subscribed to BTCUSDT order book and trades")
|
|
|
|
# Subscribe to ETH order book
|
|
if 'ETHUSDT' in symbols:
|
|
await self.connector.subscribe_orderbook('ETHUSDT')
|
|
logger.info("✅ Subscribed to ETHUSDT order book")
|
|
|
|
# Let it run for a while
|
|
logger.info("⏳ Collecting data for 30 seconds...")
|
|
await asyncio.sleep(30)
|
|
|
|
# Show statistics
|
|
stats = self.connector.get_binance_stats()
|
|
logger.info("📈 Final Statistics:")
|
|
logger.info(f" 📊 Order books received: {self.orderbook_count}")
|
|
logger.info(f" 💰 Trades received: {self.trade_count}")
|
|
logger.info(f" 📡 Total messages: {stats['message_count']}")
|
|
logger.info(f" ❌ Errors: {stats['error_count']}")
|
|
logger.info(f" 🔗 Active streams: {stats['active_streams']}")
|
|
logger.info(f" 📋 Subscriptions: {list(stats['subscriptions'].keys())}")
|
|
|
|
# Unsubscribe and disconnect
|
|
logger.info("🔌 Cleaning up...")
|
|
|
|
if 'BTCUSDT' in self.connector.subscriptions:
|
|
await self.connector.unsubscribe_orderbook('BTCUSDT')
|
|
await self.connector.unsubscribe_trades('BTCUSDT')
|
|
|
|
if 'ETHUSDT' in self.connector.subscriptions:
|
|
await self.connector.unsubscribe_orderbook('ETHUSDT')
|
|
|
|
await self.connector.disconnect()
|
|
logger.info("✅ Disconnected successfully")
|
|
|
|
except KeyboardInterrupt:
|
|
logger.info("⏹️ Interrupted by user")
|
|
except Exception as e:
|
|
logger.error(f"❌ Example failed: {e}")
|
|
finally:
|
|
# Ensure cleanup
|
|
try:
|
|
await self.connector.disconnect()
|
|
except:
|
|
pass
|
|
|
|
|
|
async def main():
|
|
"""Main function"""
|
|
example = BinanceExample()
|
|
await example.run_example()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("Binance Connector Example")
|
|
print("=" * 25)
|
|
print("This example will:")
|
|
print("1. Connect to Binance WebSocket")
|
|
print("2. Get available trading symbols")
|
|
print("3. Subscribe to real-time order book and trade data")
|
|
print("4. Display received data for 30 seconds")
|
|
print("5. Show statistics and disconnect")
|
|
print()
|
|
print("Press Ctrl+C to stop early")
|
|
print("=" * 25)
|
|
|
|
try:
|
|
asyncio.run(main())
|
|
except KeyboardInterrupt:
|
|
print("\n👋 Example stopped by user")
|
|
except Exception as e:
|
|
print(f"\n❌ Example failed: {e}")
|
|
sys.exit(1) |