#!/usr/bin/env python3 """ Demonstration of Moomoo API connector usage. """ import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import logging from datetime import datetime, timedelta from data.connectors import Interval, create_moomoo_client # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def demo_historical_data(): """Demonstrate fetching historical OHLCV data.""" print("\n=== Historical Data Demo ===") # Create client in mock mode (no API key needed) client = create_moomoo_client(mock_mode=True) # Define parameters symbol = "AAPL" interval = Interval.DAY_1 end_date = datetime.now() start_date = end_date - timedelta(days=30) print(f"Fetching {interval.value} data for {symbol}") print(f"Date range: {start_date.date()} to {end_date.date()}") try: # Fetch data ohlcv_data = client.get_ohlcv( symbol=symbol, interval=interval, start_date=start_date, end_date=end_date, limit=10 # Limit to 10 data points for demo ) print(f"Retrieved {len(ohlcv_data)} data points:") for i, point in enumerate(ohlcv_data[:3]): # Show first 3 print(f" {i+1}. {point.timestamp.date()}: " f"O={point.open:.2f}, H={point.high:.2f}, " f"L={point.low:.2f}, C={point.close:.2f}, " f"V={point.volume:,.0f}") if len(ohlcv_data) > 3: print(f" ... and {len(ohlcv_data) - 3} more") # Show some metrics if ohlcv_data: closes = [point.close for point in ohlcv_data] avg_close = sum(closes) / len(closes) print(f"\nAverage closing price: ${avg_close:.2f}") except Exception as e: print(f"Error fetching historical data: {e}") def demo_instrument_info(): """Demonstrate fetching instrument metadata.""" print("\n=== Instrument Info Demo ===") client = create_moomoo_client(mock_mode=True) symbol = "TSLA" print(f"Fetching instrument info for {symbol}") try: info = client.get_instrument_info(symbol) print(f"Symbol: {info.symbol}") print(f"Name: {info.name}") print(f"Exchange: {info.exchange}") print(f"Currency: {info.currency}") print(f"Lot Size: {info.lot_size}") print(f"Min Price Increment: {info.min_price_increment}") print(f"Trading Hours: {info.trading_hours}") print(f"Tradable: {info.is_tradable}") except Exception as e: print(f"Error fetching instrument info: {e}") def demo_real_time_subscription(): """Demonstrate real-time subscription (mock).""" print("\n=== Real-time Subscription Demo ===") client = create_moomoo_client(mock_mode=True) def on_ohlcv_update(ohlcv): print(f"[{ohlcv.timestamp.time()}] {ohlcv.symbol} {ohlcv.interval.value}: " f"C={ohlcv.close:.2f}, V={ohlcv.volume:,.0f}") # Subscribe to mock real-time updates symbols = ["AAPL", "GOOGL"] interval = Interval.MINUTE_1 print(f"Subscribing to {', '.join(symbols)} for {interval.value} updates") print("Mock updates will arrive every second for 5 seconds...") client.subscribe_ohlcv(symbols, interval, on_ohlcv_update) # Let it run for a few seconds import time time.sleep(5) # Unsubscribe client.unsubscribe(symbols) print("Unsubscribed.") def demo_health_metrics(): """Demonstrate health metrics.""" print("\n=== Health Metrics Demo ===") client = create_moomoo_client(mock_mode=True) # Make some requests to generate metrics try: client.get_instrument_info("MSFT") client.get_ohlcv( symbol="MSFT", interval=Interval.DAY_1, start_date=datetime.now() - timedelta(days=7), end_date=datetime.now(), limit=5 ) except: pass metrics = client.get_health_metrics() print("Client Health Metrics:") for key, value in metrics.items(): print(f" {key}: {value}") def main(): """Run all demos.""" print("Moomoo API Connector Demonstration") print("=" * 40) demo_historical_data() demo_instrument_info() demo_real_time_subscription() demo_health_metrics() print("\n" + "=" * 40) print("Demo complete!") if __name__ == "__main__": main()