250 lines
8.0 KiB
Python
250 lines
8.0 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Test Bybit ETH futures trading with live environment
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import time
|
|
import logging
|
|
|
|
# Add the project root to the path
|
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
# Load environment variables
|
|
try:
|
|
from dotenv import load_dotenv
|
|
load_dotenv()
|
|
except ImportError:
|
|
if os.path.exists('.env'):
|
|
with open('.env', 'r') as f:
|
|
for line in f:
|
|
if line.strip() and not line.startswith('#'):
|
|
key, value = line.strip().split('=', 1)
|
|
os.environ[key] = value
|
|
|
|
from core.exchanges.bybit_interface import BybitInterface
|
|
|
|
# Configure logging
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def test_eth_futures_trading():
|
|
"""Test ETH futures trading with live environment"""
|
|
print("=" * 60)
|
|
print("BYBIT ETH FUTURES LIVE TRADING TEST")
|
|
print("=" * 60)
|
|
print("⚠️ This uses LIVE environment with real money!")
|
|
print("⚠️ Test amount: 0.001 ETH (very small)")
|
|
print("=" * 60)
|
|
|
|
# Check if API credentials are set
|
|
api_key = os.getenv('BYBIT_API_KEY')
|
|
api_secret = os.getenv('BYBIT_API_SECRET')
|
|
|
|
if not api_key or not api_secret:
|
|
print("❌ API credentials not found in environment")
|
|
return False
|
|
|
|
# Create Bybit interface with live environment
|
|
bybit = BybitInterface(
|
|
api_key=api_key,
|
|
api_secret=api_secret,
|
|
test_mode=False # Use live environment
|
|
)
|
|
|
|
symbol = 'ETHUSDT'
|
|
test_quantity = 0.01 # Minimum order size for ETH futures
|
|
|
|
# Test 1: Connection
|
|
print(f"\n📡 Testing connection to Bybit live environment...")
|
|
try:
|
|
if not bybit.connect():
|
|
print("❌ Failed to connect to Bybit")
|
|
return False
|
|
print("✅ Successfully connected to Bybit live environment")
|
|
except Exception as e:
|
|
print(f"❌ Connection error: {e}")
|
|
return False
|
|
|
|
# Test 2: Get account balance
|
|
print(f"\n💰 Checking account balance...")
|
|
try:
|
|
usdt_balance = bybit.get_balance('USDT')
|
|
print(f"USDT Balance: ${usdt_balance:.2f}")
|
|
|
|
if usdt_balance < 5:
|
|
print("❌ Insufficient USDT balance for testing (need at least $5)")
|
|
return False
|
|
|
|
print("✅ Sufficient balance for testing")
|
|
except Exception as e:
|
|
print(f"❌ Balance check error: {e}")
|
|
return False
|
|
|
|
# Test 3: Get current ETH price
|
|
print(f"\n📈 Getting current ETH price...")
|
|
try:
|
|
ticker = bybit.get_ticker(symbol)
|
|
if not ticker:
|
|
print("❌ Failed to get ticker")
|
|
return False
|
|
|
|
current_price = ticker['last_price']
|
|
print(f"Current ETH price: ${current_price:.2f}")
|
|
print(f"Test order value: ${current_price * test_quantity:.2f}")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Ticker error: {e}")
|
|
return False
|
|
|
|
# Test 4: Check existing positions
|
|
print(f"\n📊 Checking existing positions...")
|
|
try:
|
|
positions = bybit.get_positions(symbol)
|
|
if positions:
|
|
print(f"Found {len(positions)} existing positions:")
|
|
for pos in positions:
|
|
print(f" {pos['symbol']}: {pos['side']} {pos['size']} @ ${pos['entry_price']:.2f}")
|
|
print(f" PnL: ${pos['unrealized_pnl']:.2f}")
|
|
else:
|
|
print("No existing positions found")
|
|
except Exception as e:
|
|
print(f"❌ Position check error: {e}")
|
|
return False
|
|
|
|
# Test 5: Ask user confirmation before trading
|
|
print(f"\n⚠️ TRADING CONFIRMATION")
|
|
print(f" Symbol: {symbol}")
|
|
print(f" Quantity: {test_quantity} ETH")
|
|
print(f" Estimated cost: ${current_price * test_quantity:.2f}")
|
|
print(f" Environment: LIVE (real money)")
|
|
|
|
response = input("\nDo you want to proceed with the live trading test? (y/N): ").lower()
|
|
if response != 'y' and response != 'yes':
|
|
print("❌ Trading test cancelled by user")
|
|
return False
|
|
|
|
# Test 6: Open a small long position
|
|
print(f"\n🚀 Opening small long position...")
|
|
try:
|
|
order = bybit.place_order(
|
|
symbol=symbol,
|
|
side='buy',
|
|
order_type='market',
|
|
quantity=test_quantity
|
|
)
|
|
|
|
if 'error' in order:
|
|
print(f"❌ Order failed: {order['error']}")
|
|
return False
|
|
|
|
print("✅ Long position opened successfully:")
|
|
print(f" Order ID: {order['order_id']}")
|
|
print(f" Symbol: {order['symbol']}")
|
|
print(f" Side: {order['side']}")
|
|
print(f" Quantity: {order['quantity']}")
|
|
print(f" Status: {order['status']}")
|
|
|
|
order_id = order['order_id']
|
|
|
|
except Exception as e:
|
|
print(f"❌ Order placement error: {e}")
|
|
return False
|
|
|
|
# Test 7: Wait a moment and check position
|
|
print(f"\n⏳ Waiting 3 seconds for position to be reflected...")
|
|
time.sleep(3)
|
|
|
|
try:
|
|
positions = bybit.get_positions(symbol)
|
|
if positions:
|
|
position = positions[0]
|
|
print("✅ Position confirmed:")
|
|
print(f" Symbol: {position['symbol']}")
|
|
print(f" Side: {position['side']}")
|
|
print(f" Size: {position['size']}")
|
|
print(f" Entry Price: ${position['entry_price']:.2f}")
|
|
print(f" Current PnL: ${position['unrealized_pnl']:.2f}")
|
|
print(f" Leverage: {position['leverage']}x")
|
|
else:
|
|
print("⚠️ No position found (may already be closed)")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Position check error: {e}")
|
|
|
|
# Test 8: Close the position
|
|
print(f"\n🔄 Closing the position...")
|
|
try:
|
|
close_order = bybit.close_position(symbol)
|
|
|
|
if 'error' in close_order:
|
|
print(f"❌ Close order failed: {close_order['error']}")
|
|
return False
|
|
|
|
print("✅ Position closed successfully:")
|
|
print(f" Order ID: {close_order['order_id']}")
|
|
print(f" Symbol: {close_order['symbol']}")
|
|
print(f" Side: {close_order['side']}")
|
|
print(f" Quantity: {close_order['quantity']}")
|
|
print(f" Status: {close_order['status']}")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Close position error: {e}")
|
|
return False
|
|
|
|
# Test 9: Final position check
|
|
print(f"\n📊 Final position check...")
|
|
time.sleep(2)
|
|
|
|
try:
|
|
positions = bybit.get_positions(symbol)
|
|
if positions:
|
|
position = positions[0]
|
|
print("⚠️ Position still exists:")
|
|
print(f" Size: {position['size']}")
|
|
print(f" PnL: ${position['unrealized_pnl']:.2f}")
|
|
else:
|
|
print("✅ No open positions - trading test completed successfully")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Final position check error: {e}")
|
|
|
|
# Test 10: Final balance check
|
|
print(f"\n💰 Final balance check...")
|
|
try:
|
|
final_balance = bybit.get_balance('USDT')
|
|
print(f"Final USDT Balance: ${final_balance:.2f}")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Final balance check error: {e}")
|
|
|
|
return True
|
|
|
|
def main():
|
|
"""Main function"""
|
|
print("🚀 Starting Bybit ETH Futures Live Trading Test...")
|
|
|
|
success = test_eth_futures_trading()
|
|
|
|
if success:
|
|
print("\n" + "=" * 60)
|
|
print("✅ BYBIT ETH FUTURES TRADING TEST COMPLETED")
|
|
print("=" * 60)
|
|
print("🎯 Your Bybit integration is fully functional!")
|
|
print("🔄 Position opening and closing works correctly")
|
|
print("💰 Account balance integration works")
|
|
print("📊 All trading functions are operational")
|
|
print("=" * 60)
|
|
else:
|
|
print("\n💥 Trading test failed!")
|
|
|
|
return success
|
|
|
|
if __name__ == "__main__":
|
|
success = main()
|
|
sys.exit(0 if success else 1)
|