Files
gogo2/test_deribit_integration.py
Dobromir Popov 4a55c5ff03 deribit
2025-07-14 17:56:09 +03:00

171 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""
Test Deribit Integration
Test the new DeribitInterface and ExchangeFactory
"""
import os
import sys
import logging
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Add project paths
sys.path.append(os.path.join(os.path.dirname(__file__), 'NN'))
sys.path.append(os.path.join(os.path.dirname(__file__), 'core'))
from NN.exchanges.exchange_factory import ExchangeFactory
from NN.exchanges.deribit_interface import DeribitInterface
from core.config import get_config
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def test_deribit_credentials():
"""Test Deribit API credentials"""
api_key = os.getenv('DERIBIT_API_CLIENTID')
api_secret = os.getenv('DERIBIT_API_SECRET')
logger.info(f"Deribit API Key: {'*' * 8 + api_key[-4:] if api_key and len(api_key) > 4 else 'Not set'}")
logger.info(f"Deribit API Secret: {'*' * 8 + api_secret[-4:] if api_secret and len(api_secret) > 4 else 'Not set'}")
return bool(api_key and api_secret)
def test_deribit_interface():
"""Test DeribitInterface directly"""
logger.info("Testing DeribitInterface directly...")
try:
# Create Deribit interface
deribit = DeribitInterface(test_mode=True)
# Test connection
if deribit.connect():
logger.info("✓ Successfully connected to Deribit testnet")
# Test getting instruments
btc_instruments = deribit.get_instruments('BTC')
logger.info(f"✓ Found {len(btc_instruments)} BTC instruments")
# Test getting ticker
ticker = deribit.get_ticker('BTC-PERPETUAL')
if ticker:
logger.info(f"✓ BTC-PERPETUAL ticker: ${ticker.get('last_price', 'N/A')}")
# Test getting account summary (if authenticated)
account = deribit.get_account_summary('BTC')
if account:
logger.info(f"✓ BTC account balance: {account.get('available_funds', 'N/A')}")
return True
else:
logger.error("✗ Failed to connect to Deribit")
return False
except Exception as e:
logger.error(f"✗ Error testing DeribitInterface: {e}")
return False
def test_exchange_factory():
"""Test ExchangeFactory with config"""
logger.info("Testing ExchangeFactory...")
try:
# Load config
config = get_config()
exchanges_config = config.get('exchanges', {})
logger.info(f"Primary exchange: {exchanges_config.get('primary', 'Not set')}")
# Test creating primary exchange
primary_exchange = ExchangeFactory.get_primary_exchange(exchanges_config)
if primary_exchange:
logger.info(f"✓ Successfully created primary exchange: {type(primary_exchange).__name__}")
# Test basic operations
if hasattr(primary_exchange, 'get_ticker'):
ticker = primary_exchange.get_ticker('BTC-PERPETUAL')
if ticker:
logger.info(f"✓ Primary exchange ticker test successful")
return True
else:
logger.error("✗ Failed to create primary exchange")
return False
except Exception as e:
logger.error(f"✗ Error testing ExchangeFactory: {e}")
return False
def test_multiple_exchanges():
"""Test creating multiple exchanges"""
logger.info("Testing multiple exchanges...")
try:
config = get_config()
exchanges_config = config.get('exchanges', {})
# Create all configured exchanges
exchanges = ExchangeFactory.create_multiple_exchanges(exchanges_config)
logger.info(f"✓ Created {len(exchanges)} exchange interfaces:")
for name, exchange in exchanges.items():
logger.info(f" - {name}: {type(exchange).__name__}")
return len(exchanges) > 0
except Exception as e:
logger.error(f"✗ Error testing multiple exchanges: {e}")
return False
def main():
"""Run all tests"""
logger.info("=" * 50)
logger.info("TESTING DERIBIT INTEGRATION")
logger.info("=" * 50)
tests = [
("Credentials", test_deribit_credentials),
("DeribitInterface", test_deribit_interface),
("ExchangeFactory", test_exchange_factory),
("Multiple Exchanges", test_multiple_exchanges)
]
results = []
for test_name, test_func in tests:
logger.info(f"\n--- Testing {test_name} ---")
try:
result = test_func()
results.append((test_name, result))
status = "PASS" if result else "FAIL"
logger.info(f"{test_name}: {status}")
except Exception as e:
logger.error(f"{test_name}: ERROR - {e}")
results.append((test_name, False))
# Summary
logger.info("\n" + "=" * 50)
logger.info("TEST SUMMARY")
logger.info("=" * 50)
passed = sum(1 for _, result in results if result)
total = len(results)
for test_name, result in results:
status = "✓ PASS" if result else "✗ FAIL"
logger.info(f"{status}: {test_name}")
logger.info(f"\nOverall: {passed}/{total} tests passed")
if passed == total:
logger.info("🎉 All tests passed! Deribit integration is working.")
return True
else:
logger.error("❌ Some tests failed. Check the logs above.")
return False
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)