Files
ccxt_with_mt5/test/test.py
lz_db 0fab423a18 add
2025-11-16 12:31:03 +08:00

188 lines
7.2 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
import ccxt
import sys
import json
def test_mt5_comprehensive():
print("=== MT5 Comprehensive Test ===")
try:
# 创建 MT5 实例
exchange = ccxt.mt5({
'apiKey': '76888962',
'secret': 'LZ-trade666888',
'verbose': True, # 启用详细日志
'hostname': '43.167.188.220:5000',
'options': {
# 'server': '147.160.254.81:443', # 使用服务器名称
# 或者
'host': '18.163.85.196',
'port': 443,
},
})
# 测试连接
print("\n🔗 Testing connection...")
try:
token = exchange.get_token()
print(f"✅ Connected successfully! Token: {token[:20]}...")
except Exception as e:
print(f"❌ Connection failed: {e}")
return False
# print("\n💰 Testing ping...")
# try:
# ping = exchange.ping_server()
# print(ping)
# except Exception as e:
# print(f"⚠️ ping fetch failed: {e}")
# 先加载市场数据
# print("\n📊 Loading markets first...")
# try:
# markets = exchange.load_markets()
# print(f"✅ Markets loaded: {len(markets)} symbols")
# except Exception as e:
# print(f"⚠️ Markets load failed: {e}")
# 测试余额
# print("\n💰 Testing balance...")
# try:
# balance = exchange.fetch_balance()
# print(f"✅ Balance fetched: {balance}")
# except Exception as e:
# print(f"⚠️ Balance fetch failed: {e}")
# print("\n💰 Testing AccountDetails...")
# try:
# account_details = exchange.fetch_account_details()
# print(f"✅ AccountDetails fetched: {account_details}")
# except Exception as e:
# print(f"⚠️ AccountDetails fetch failed: {e}")
# 测试交易对
# print("\n📊 Testing markets...")
# try:
# markets = exchange.fetch_markets()
# print(f"✅ Markets fetched: {len(markets)} symbols")
# if markets:
# for i, market in enumerate(markets[:3]):
# print(f" {i+1}. {market['symbol']}")
# except Exception as e:
# print(f"⚠️ Markets fetch failed: {e}")
# 测试行情
# print("\n💰 Testing ticker...")
# try:
# ticker = exchange.fetch_ticker('BTCUSD')
# print(ticker)
# # print(f"✅ Ticker fetched: {ticker['symbol']} - Bid: {ticker['bid']}, Ask: {ticker['ask']}")
# except Exception as e:
# print(f"⚠️ Ticker fetch failed: {e}")
# print("\n💰 Testing order_book...")
# try:
# order_book = exchange.fetch_ticker('BTCUSD')
# print(order_book)
# except Exception as e:
# print(f"⚠️ order_book fetch failed: {e}")
# 测试时区
# print("\n💰 Testing server_timezone...")
# try:
# timezone = exchange.server_timezone()
# print(timezone)
# # print(f"✅ Ticker fetched: {ticker['symbol']} - Bid: {ticker['bid']}, Ask: {ticker['ask']}")
# except Exception as e:
# print(f"⚠️ server_timezone fetch failed: {e}")
# 测试市场观察行情 - 使用不同的符号测试
# print("\n📊 Testing market watch ticker...")
# test_symbols = ['XAUUSD+'] # 多试几个符号
# for symbol in test_symbols:
# try:
# market_watch = exchange.fetch_ticker_with_market_watch(symbol)
# print(f"✅ Market watch ticker for {symbol}:")
# print(f" High: {market_watch['high']}")
# print(f" Low: {market_watch['low']}")
# print(f" Open: {market_watch['open']}")
# print(f" Close: {market_watch['close']}")
# break # 成功一个就停止
# except Exception as e:
# print(f"⚠️ Market watch for {symbol} failed: {e}")
# 测试K线数据
# print("\n🕯 Testing XAUUSD+...")
# try:
# ohlcv = exchange.fetch_ohlcv('XAUUSD+', '1h', limit=3) # 使用 XAUUSD+ 测试
# print(f"✅ XAUUSD+ fetched: {len(ohlcv)} bars")
# for i, candle in enumerate(ohlcv):
# print(f" Bar {i+1}: Time={candle[0]}, O={candle[1]}, H={candle[2]}, L={candle[3]}, C={candle[4]}, V={candle[5]}")
# except Exception as e:
# print(f"⚠️ XAUUSD+ failed: {e}")
# 测试订单查询
# print("\n📋 Testing open orders...")
# try:
# open_orders = exchange.fetch_open_orders()
# print(f"✅ Open orders: {len(open_orders)}")
# # for order in open_orders:
# # print(f" Order: {order['ticket']} - {order['symbol']} - {order['orderType']} - {order['lots']}")
# except Exception as e:
# print(f"⚠️ Open orders failed: {e}")
# 测试持仓查询
# print("\n📊 Testing positions...")
# try:
# positions = exchange.fetch_positions()
# print(f"✅ Positions fetched: {len(positions)} positions")
# for i, position in enumerate(positions):
# print(f"\n📈 Position {i+1}:")
# print(f" ID: {position['id']}")
# print(f" Symbol: {position['symbol']}")
# print(f" Side: {position['side']}")
# print(f" Contracts: {position['contracts']}")
# print(f" Entry Price: {position['entryPrice']}")
# print(f" Unrealized PnL: {position['unrealizedPnl']}")
# print(f" Stop Loss: {position['stopLossPrice']}")
# print(f" Take Profit: {position['takeProfitPrice']}")
# print(f" Timestamp: {position['timestamp']}")
# except Exception as e:
# print(f"❌ Positions failed: {e}")
# import traceback
# traceback.print_exc()
# 测试单个持仓查询(如果有持仓的话)
# if positions:
# first_symbol = positions[0]['symbol']
# print(f"\n🎯 Testing single position for {first_symbol}...")
# try:
# single_position = exchange.fetch_position(first_symbol)
# print(f"✅ Single position fetched:")
# print(f" Symbol: {single_position['symbol']}")
# print(f" Side: {single_position['side']}")
# print(f" Contracts: {single_position['contracts']}")
# except Exception as e:
# print(f"⚠️ Single position failed: {e}")
# print("\n🎉 Positions test completed!")
# print("\n🎉 Comprehensive test completed!")
return True
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
return False
if __name__ == "__main__":
success = test_mt5_comprehensive()
sys.exit(0 if success else 1)