capcha and credentials stored in json. test intgration
This commit is contained in:
37
core/mexc_webclient/mexc_credentials.json
Normal file
37
core/mexc_webclient/mexc_credentials.json
Normal file
@ -0,0 +1,37 @@
|
||||
|
||||
{
|
||||
"note": "No CAPTCHA tokens were found in the latest run. Manual extraction of cookies may be required from mexc_requests_20250703_024032.json.",
|
||||
"credentials": {
|
||||
"cookies": {
|
||||
"bm_sv": "D92603BBC020E9C2CD11B2EBC8F22050~YAAQJKVf1NW5K7CXAQAAwtMVzRzHARcY60jrPVzy9G79fN3SY4z988SWHHxQlbPpyZHOj76c20AjCnS0QwveqzB08zcRoauoIe/sP3svlaIso9PIdWay0KIIVUe1XsiTJRfTm/DmS+QdrOuJb09rbfWLcEJF4/0QK7VY0UTzPTI2V3CMtxnmYjd1+tjfYsvt1R6O+Mw9mYjb7SjhRmiP/exY2UgZdLTJiqd+iWkc5Wejy5m6g5duOfRGtiA9mfs=~1",
|
||||
"bm_sz": "98D80FE4B23FE6352AE5194DA699FDDB~YAAQJKVf1GK4K7CXAQAAeQ0UzRw+aXiY5/Ujp+sZm0a4j+XAJFn6fKT4oph8YqIKF6uHSgXkFY3mBt8WWY98Y2w1QzOEFRkje8HTUYQgJsV59y5DIOTZKC6wutPD/bKdVi9ZKtk4CWbHIIRuCrnU1Nw2jqj5E0hsorhKGh8GeVsAeoao8FWovgdYD6u8Qpbr9aL5YZgVEIqJx6WmWLmcIg+wA8UFj8751Fl0B3/AGxY2pACUPjonPKNuX/UDYA5e98plOYUnYLyQMEGIapSrWKo1VXhKBDPLNedJ/Q2gOCGEGlj/u1Fs407QxxXwCvRSegL91y6modtL5JGoFucV1pYc4pgTwEAEdJfcLCEBaButTbaHI9T3SneqgCoGeatMMaqz0GHbvMD7fBQofARBqzN1L6aGlmmAISMzI3wx/SnsfXBl~3228228~3294529",
|
||||
"_abck": "0288E759712AF333A6EE15F66BC2A662~-1~YAAQJKVf1GC4K7CXAQAAeQ0UzQ77TfyX5SOWTgdW3DVqNFrTLz2fhLo2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3&tt=90n&bcn=%2F%2F684dd311.akstat.io%2F&ld=1c9o\"",
|
||||
"mexc_fingerprint_visitorId": "tv1xchuZQbx9N0aBztUG",
|
||||
"_ga_L6XJCQTK75": "GS2.1.s1751492192$o1$g1$t1751492248$j4$l0$h0",
|
||||
"uc_token": "WEB66f893ede865e5d927efdea4a82e655ad5190239c247997d744ef9cd075f6f1e",
|
||||
"u_id": "WEB66f893ede865e5d927efdea4a82e655ad5190239c247997d744ef9cd075f6f1e",
|
||||
"_fbp": "fb.1.1751492193579.314807866777158389",
|
||||
"mxc_exchange_layout": "BA",
|
||||
"sensorsdata2015jssdkcross": "%7B%22distinct_id%22%3A%2221a8728990b84f4fa3ae64c8004b4aaa%22%2C%22first_id%22%3A%22197cd11dc751be-0dd66c04c69e96-26011f51-3686400-197cd11dc76189d%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%2C%22%24latest_landing_page%22%3A%22https%3A%2F%2Fwww.mexc.com%2Fen-GB%2Flogin%3Fprevious%3D%252Ffutures%252FETH_USDT%253Ftype%253Dlinear_swap%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMTk3Y2QxMWRjNzUxYmUtMGRkNjZjMDRjNjllOTYtMjYwMTFmNTEtMzY4NjQwMC0xOTdjZDExZGM3NjE4OWQiLCIkaWRlbnRpdHlfbG9naW5faWQiOiIyMWE4NzI4OTkwYjg0ZjRmYTNhZTY0YzgwMDRiNGFhYSJ9%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%24identity_login_id%22%2C%22value%22%3A%2221a8728990b84f4fa3ae64c8004b4aaa%22%7D%2C%22%24device_id%22%3A%22197cd11dc751be-0dd66c04c69e96-26011f51-3686400-197cd11dc76189d%22%7D",
|
||||
"mxc_theme_main": "dark",
|
||||
"mexc_fingerprint_requestId": "1751492199306.WMvKJd",
|
||||
"_ym_visorc": "b",
|
||||
"mexc_clearance_modal_show_date": "2025-07-03-undefined",
|
||||
"ak_bmsc": "35C21AA65F819E0BF9BEBDD10DCF7B70~000000000000000000000000000000~YAAQJKVf1BK2K7CXAQAAPAISzRwQdUOUs1H3HPAdl4COMFQAl+aEPzppLbdgrwA7wXbP/LZpxsYCFflUHDppYKUjzXyTZ9tIojSF3/6CW3OCiPhQo/qhf6XPbC4oQHpCNWaC9GJWEs/CGesQdfeBbhkXdfh+JpgmgCF788+x8IveDE9+9qaL/3QZRy+E7zlKjjvmMxBpahRy+ktY9/KMrCY2etyvtm91KUclr4k8HjkhtNJOlthWgUyiANXJtfbNUMgt+Hqgqa7QzSUfAEpxIXQ1CuROoY9LbU292LRN5TbtBy/uNv6qORT38rKsnpi7TGmyFSB9pj3YsoSzIuAUxYXSh4hXRgAoUQm3Yh5WdLp4ONeyZC1LIb8VCY5xXRy/VbfaHH1w7FodY1HpfHGKSiGHSNwqoiUmMPx13Rgjsgki4mE7bwFmG2H5WAilRIOZA5OkndEqGrOuiNTON7l6+g6mH0MzZ+/+3AjnfF2sXxFuV9itcs9x",
|
||||
"mxc_theme_upcolor": "upgreen",
|
||||
"_vid_t": "mQUFl49q1yLZhrL4tvOtFF38e+hGW5QoMS+eXKVD9Q4vQau6icnyipsdyGLW/FBukiO2ItK7EtzPIPMFrE5SbIeLSm1NKc/j+ZmobhX063QAlskf1x1J",
|
||||
"_ym_isad": "2",
|
||||
"_ym_d": "1751492196",
|
||||
"_ym_uid": "1751492196843266888",
|
||||
"bm_mi": "02862693F007017AEFD6639269A60D08~YAAQJKVf1Am2K7CXAQAAIf4RzRzNGqZ7Q3BC0kAAp/0sCOhHxxvEWTb7mBl8p7LUz0W6RZbw5Etz03Tvqu3H6+sb+yu1o0duU+bDflt7WLVSOfG5cA3im8Jeo6wZhqmxTu6gGXuBgxhrHw/RGCgcknxuZQiRM9cbM6LlZIAYiugFm2xzmO/1QcpjDhs4S8d880rv6TkMedlkYGwdgccAmvbaRVSmX9d5Yukm+hY+5GWuyKMeOjpatAhcgjShjpSDwYSpyQE7vVZLBp7TECIjI9uoWzR8A87YHScKYEuE08tb8YtGdG3O6g70NzasSX0JF3XTCjrVZA==~1",
|
||||
"_ga": "GA1.1.626437359.1751492192",
|
||||
"NEXT_LOCALE": "en-GB",
|
||||
"x-mxc-fingerprint": "tv1xchuZQbx9N0aBztUG",
|
||||
"CLIENT_LANG": "en-GB",
|
||||
"sajssdk_2015_cross_new_user": "1"
|
||||
},
|
||||
"captcha_token_open": "geetest eyJsb3ROdW1iZXIiOiI4NWFhM2Q3YjJkYmE0Mjk3YTQwODY0YmFhODZiMzA5NyIsImNhcHRjaGFPdXRwdXQiOiJaVkwzS3FWaWxnbEZjQWdXOENIQVgxMUVBLVVPUnE1aURQSldzcmlubDFqelBhRTNiUGlEc0VrVTJUR0xuUzRHV2k0N2JDa1hyREMwSktPWmwxX1dERkQwNWdSN1NkbFJ1Z2NDY0JmTGdLVlNBTEI0OUNrR200enZZcnZ3MUlkdnQ5RThRZURYQ2E0empLczdZMHByS3JEWV9SQW93S0d4OXltS0MxMlY0SHRzNFNYMUV1YnI1ZV9yUXZCcTZJZTZsNFVJMS1DTnc5RUhBaXRXOGU2TVZ6OFFqaGlUMndRM1F3eGxEWkpmZnF6M3VucUl5RTZXUnFSUEx1T0RQQUZkVlB3S3AzcWJTQ3JXcG5CTUFKOXFuXzV2UDlXNm1pR3FaRHZvSTY2cWRzcHlDWUMyWTV1RzJ0ZjZfRHRJaXhTTnhLWUU3cTlfcU1WR2ZJUzlHUXh6ZWg2Mkp2eG02SHZLdjFmXzJMa3FlcVkwRk94S2RxaVpyN2NkNjAxMHE5UlFJVDZLdmNZdU1Hcm04M2d4SnY1bXp4VkZCZWZFWXZfRjZGWGpnWXRMMmhWSDlQME42bHFXQk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NUb2tlbiI6IjRmZDFhZmU5NzI3MTk0ZGI3MDNlMDg2NWQ0ZDZjZTIyYWzMwMzUyNzQ5NzVjMDIwNDFiNTY3Y2Y3MDdhYjM1OTMiLCJnZW5UaW1lIjoiMTc1MTQ5ODY5MiJ9"
|
||||
}
|
||||
}
|
346
core/mexc_webclient/test_mexc_futures_webclient.py
Normal file
346
core/mexc_webclient/test_mexc_futures_webclient.py
Normal file
@ -0,0 +1,346 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test MEXC Futures Web Client
|
||||
|
||||
This script demonstrates how to use the MEXC Futures Web Client
|
||||
for futures trading that isn't supported by their official API.
|
||||
|
||||
IMPORTANT: This requires extracting cookies from your browser session.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import uuid
|
||||
|
||||
# Add the project root to path
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from mexc_futures_client import MEXCFuturesWebClient
|
||||
from session_manager import MEXCSessionManager
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Constants
|
||||
SYMBOL = "ETH_USDT"
|
||||
LEVERAGE = 300
|
||||
CREDENTIALS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mexc_credentials.json')
|
||||
|
||||
# Read credentials from mexc_credentials.json in JSON format
|
||||
def load_credentials():
|
||||
credentials_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mexc_credentials.json')
|
||||
cookies = {}
|
||||
captcha_token_open = ''
|
||||
captcha_token_close = ''
|
||||
try:
|
||||
with open(credentials_file, 'r') as f:
|
||||
data = json.load(f)
|
||||
cookies = data.get('credentials', {}).get('cookies', {})
|
||||
captcha_token_open = data.get('credentials', {}).get('captcha_token_open', '')
|
||||
captcha_token_close = data.get('credentials', {}).get('captcha_token_close', '')
|
||||
logger.info(f"Loaded credentials from {credentials_file}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading credentials: {e}")
|
||||
return cookies, captcha_token_open, captcha_token_close
|
||||
|
||||
def test_basic_connection():
|
||||
"""Test basic connection and authentication"""
|
||||
logger.info("Testing MEXC Futures Web Client")
|
||||
|
||||
# Initialize session manager
|
||||
session_manager = MEXCSessionManager()
|
||||
|
||||
# Try to load saved session first
|
||||
cookies = session_manager.load_session()
|
||||
|
||||
if not cookies:
|
||||
# Explicitly load the cookies from the file we have
|
||||
cookies_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'mexc_cookies_20250703_003625.json')
|
||||
if os.path.exists(cookies_file):
|
||||
try:
|
||||
with open(cookies_file, 'r') as f:
|
||||
cookies = json.load(f)
|
||||
logger.info(f"Loaded cookies from {cookies_file}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to load cookies from {cookies_file}: {e}")
|
||||
cookies = None
|
||||
else:
|
||||
logger.error(f"Cookies file not found at {cookies_file}")
|
||||
cookies = None
|
||||
|
||||
if not cookies:
|
||||
print("\nNo saved session found. You need to extract cookies from your browser.")
|
||||
session_manager.print_cookie_extraction_guide()
|
||||
|
||||
print("\nPaste your cookie header or cURL command (or press Enter to exit):")
|
||||
user_input = input().strip()
|
||||
|
||||
if not user_input:
|
||||
print("No input provided. Exiting.")
|
||||
return False
|
||||
|
||||
# Extract cookies from user input
|
||||
if user_input.startswith('curl'):
|
||||
cookies = session_manager.extract_from_curl_command(user_input)
|
||||
else:
|
||||
cookies = session_manager.extract_cookies_from_network_tab(user_input)
|
||||
|
||||
if not cookies:
|
||||
logger.error("Failed to extract cookies from input")
|
||||
return False
|
||||
|
||||
# Validate and save session
|
||||
if session_manager.validate_session_cookies(cookies):
|
||||
session_manager.save_session(cookies)
|
||||
logger.info("Session saved for future use")
|
||||
else:
|
||||
logger.warning("Extracted cookies may be incomplete")
|
||||
|
||||
# Initialize the web client
|
||||
client = MEXCFuturesWebClient(api_key='', api_secret='', user_id='', base_url='https://www.mexc.com', headless=True)
|
||||
# Load cookies into the client's session
|
||||
for name, value in cookies.items():
|
||||
client.session.cookies.set(name, value)
|
||||
|
||||
# Update headers to include additional parameters from captured requests
|
||||
client.session.headers.update({
|
||||
'trochilus-trace-id': f"{uuid.uuid4()}-{int(time.time() * 1000) % 10000:04d}",
|
||||
'trochilus-uid': cookies.get('u_id', ''),
|
||||
'Referer': 'https://www.mexc.com/en-GB/futures/ETH_USDT?type=linear_swap',
|
||||
'Language': 'English',
|
||||
'X-Language': 'en-GB'
|
||||
})
|
||||
|
||||
if not client.is_authenticated:
|
||||
logger.error("Failed to authenticate with extracted cookies")
|
||||
return False
|
||||
|
||||
logger.info("Successfully authenticated with MEXC")
|
||||
logger.info(f"User ID: {client.user_id}")
|
||||
logger.info(f"Auth Token: {client.auth_token[:20]}..." if client.auth_token else "No auth token")
|
||||
|
||||
return True
|
||||
|
||||
def test_captcha_verification(client: MEXCFuturesWebClient):
|
||||
"""Test captcha verification system"""
|
||||
logger.info("Testing captcha verification...")
|
||||
|
||||
# Test captcha for ETH_USDT long position with 200x leverage
|
||||
success = client.verify_captcha('ETH_USDT', 'openlong', '200X')
|
||||
|
||||
if success:
|
||||
logger.info("Captcha verification successful")
|
||||
else:
|
||||
logger.warning("Captcha verification failed - this may be normal if no position is being opened")
|
||||
|
||||
return success
|
||||
|
||||
def test_position_opening(client: MEXCFuturesWebClient, dry_run: bool = True):
|
||||
"""Test opening a position (dry run by default)"""
|
||||
if dry_run:
|
||||
logger.info("DRY RUN: Testing position opening (no actual trade)")
|
||||
else:
|
||||
logger.warning("LIVE TRADING: Opening actual position!")
|
||||
|
||||
symbol = 'ETH_USDT'
|
||||
volume = 1 # Small test position
|
||||
leverage = 200
|
||||
|
||||
logger.info(f"Attempting to open long position: {symbol}, Volume: {volume}, Leverage: {leverage}x")
|
||||
|
||||
if not dry_run:
|
||||
result = client.open_long_position(symbol, volume, leverage)
|
||||
|
||||
if result['success']:
|
||||
logger.info(f"Position opened successfully!")
|
||||
logger.info(f"Order ID: {result['order_id']}")
|
||||
logger.info(f"Timestamp: {result['timestamp']}")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Failed to open position: {result['error']}")
|
||||
return False
|
||||
else:
|
||||
logger.info("DRY RUN: Would attempt to open position here")
|
||||
# Test just the captcha verification part
|
||||
return client.verify_captcha(symbol, 'openlong', f'{leverage}X')
|
||||
|
||||
def test_position_opening_live(client):
|
||||
symbol = "ETH_USDT"
|
||||
volume = 1 # Small volume for testing
|
||||
leverage = 200
|
||||
|
||||
logger.info(f"LIVE TRADING: Opening actual position!")
|
||||
logger.info(f"Attempting to open long position: {symbol}, Volume: {volume}, Leverage: {leverage}x")
|
||||
|
||||
result = client.open_long_position(symbol, volume, leverage)
|
||||
if result.get('success'):
|
||||
logger.info(f"Successfully opened position: {result}")
|
||||
else:
|
||||
logger.error(f"Failed to open position: {result.get('error', 'Unknown error')}")
|
||||
|
||||
def interactive_menu(client: MEXCFuturesWebClient):
|
||||
"""Interactive menu for testing different functions"""
|
||||
while True:
|
||||
print("\n" + "="*50)
|
||||
print("MEXC Futures Web Client Test Menu")
|
||||
print("="*50)
|
||||
print("1. Test captcha verification")
|
||||
print("2. Test position opening (DRY RUN)")
|
||||
print("3. Test position opening (LIVE - BE CAREFUL!)")
|
||||
print("4. Test position closing (DRY RUN)")
|
||||
print("5. Show session info")
|
||||
print("6. Refresh session")
|
||||
print("0. Exit")
|
||||
|
||||
choice = input("\nEnter choice (0-6): ").strip()
|
||||
|
||||
if choice == "1":
|
||||
test_captcha_verification(client)
|
||||
|
||||
elif choice == "2":
|
||||
test_position_opening(client, dry_run=True)
|
||||
|
||||
elif choice == "3":
|
||||
test_position_opening_live(client)
|
||||
|
||||
elif choice == "4":
|
||||
logger.info("DRY RUN: Position closing test")
|
||||
success = client.verify_captcha('ETH_USDT', 'closelong', '200X')
|
||||
if success:
|
||||
logger.info("DRY RUN: Would close position here")
|
||||
else:
|
||||
logger.warning("Captcha verification failed for position closing")
|
||||
|
||||
elif choice == "5":
|
||||
print(f"\nSession Information:")
|
||||
print(f"Authenticated: {client.is_authenticated}")
|
||||
print(f"User ID: {client.user_id}")
|
||||
print(f"Auth Token: {client.auth_token[:20]}..." if client.auth_token else "None")
|
||||
print(f"Fingerprint: {client.fingerprint}")
|
||||
print(f"Visitor ID: {client.visitor_id}")
|
||||
|
||||
elif choice == "6":
|
||||
session_manager = MEXCSessionManager()
|
||||
session_manager.print_cookie_extraction_guide()
|
||||
|
||||
elif choice == "0":
|
||||
print("Goodbye!")
|
||||
break
|
||||
|
||||
else:
|
||||
print("Invalid choice. Please try again.")
|
||||
|
||||
def main():
|
||||
"""Main test function"""
|
||||
print("MEXC Futures Web Client Test")
|
||||
print("WARNING: This is experimental software for futures trading")
|
||||
print("Use at your own risk and test with small amounts first!")
|
||||
|
||||
# Load cookies and tokens
|
||||
cookies, captcha_token_open, captcha_token_close = load_credentials()
|
||||
if not cookies:
|
||||
logger.error("Failed to load cookies from credentials file")
|
||||
sys.exit(1)
|
||||
|
||||
# Initialize client with loaded cookies and tokens
|
||||
client = MEXCFuturesWebClient(api_key='', api_secret='', user_id='')
|
||||
# Load cookies into the client's session
|
||||
for name, value in cookies.items():
|
||||
client.session.cookies.set(name, value)
|
||||
# Set captcha tokens
|
||||
client.captcha_token_open = captcha_token_open
|
||||
client.captcha_token_close = captcha_token_close
|
||||
|
||||
# Try to load credentials from the new JSON file
|
||||
try:
|
||||
with open(CREDENTIALS_FILE, 'r') as f:
|
||||
credentials_data = json.load(f)
|
||||
cookies = credentials_data['credentials']['cookies']
|
||||
captcha_token_open = credentials_data['credentials']['captcha_token_open']
|
||||
captcha_token_close = credentials_data['credentials']['captcha_token_close']
|
||||
client.load_session_cookies(cookies)
|
||||
client.session_manager.save_captcha_token(captcha_token_open) # Assuming this is for opening
|
||||
|
||||
except FileNotFoundError:
|
||||
logger.error(f"Credentials file not found at {CREDENTIALS_FILE}")
|
||||
return False
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"Error loading credentials: {e}")
|
||||
return False
|
||||
except KeyError as e:
|
||||
logger.error(f"Missing key in credentials file: {e}")
|
||||
return False
|
||||
|
||||
if not client.is_authenticated:
|
||||
logger.error("Client not authenticated. Please ensure valid cookies and tokens are in mexc_credentials.json")
|
||||
return False
|
||||
|
||||
# Test connection and authentication
|
||||
logger.info("Successfully authenticated with MEXC")
|
||||
|
||||
# Set leverage
|
||||
leverage_response = client.update_leverage(symbol=SYMBOL, leverage=LEVERAGE)
|
||||
if leverage_response and leverage_response.get('code') == 200:
|
||||
logger.info(f"Leverage set to {LEVERAGE}x for {SYMBOL}")
|
||||
else:
|
||||
logger.error(f"Failed to set leverage: {leverage_response}")
|
||||
sys.exit(1)
|
||||
|
||||
# Get current price
|
||||
ticker = client.get_ticker_data(symbol=SYMBOL)
|
||||
if ticker and ticker.get('code') == 200:
|
||||
current_price = float(ticker['data']['last'])
|
||||
logger.info(f"Current {SYMBOL} price: {current_price}")
|
||||
else:
|
||||
logger.error(f"Failed to get ticker data: {ticker}")
|
||||
sys.exit(1)
|
||||
|
||||
# Calculate order size for a small test trade (e.g., $10 worth)
|
||||
trade_usdt = 10.0
|
||||
order_qty = round((trade_usdt / current_price) * LEVERAGE, 3)
|
||||
logger.info(f"Calculated order quantity: {order_qty} {SYMBOL} for ~${trade_usdt} at {LEVERAGE}x")
|
||||
|
||||
# Test 1: Open LONG position
|
||||
logger.info(f"Opening LONG position for {SYMBOL} at {current_price} with qty {order_qty}")
|
||||
open_long_order = client.create_order(
|
||||
symbol=SYMBOL,
|
||||
side=1, # 1 for BUY
|
||||
position_side=1, # 1 for LONG
|
||||
order_type=1, # 1 for LIMIT
|
||||
price=current_price,
|
||||
vol=order_qty
|
||||
)
|
||||
if open_long_order and open_long_order.get('code') == 200:
|
||||
logger.info(f"✅ Successfully opened LONG position: {open_long_order['data']}")
|
||||
else:
|
||||
logger.error(f"❌ Failed to open LONG position: {open_long_order}")
|
||||
sys.exit(1)
|
||||
|
||||
# Test 2: Close LONG position
|
||||
logger.info(f"Closing LONG position for {SYMBOL}")
|
||||
close_long_order = client.create_order(
|
||||
symbol=SYMBOL,
|
||||
side=2, # 2 for SELL
|
||||
position_side=1, # 1 for LONG
|
||||
order_type=1, # 1 for LIMIT
|
||||
price=current_price,
|
||||
vol=order_qty,
|
||||
reduce_only=True
|
||||
)
|
||||
if close_long_order and close_long_order.get('code') == 200:
|
||||
logger.info(f"✅ Successfully closed LONG position: {close_long_order['data']}")
|
||||
else:
|
||||
logger.error(f"❌ Failed to close LONG position: {close_long_order}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.info("All tests completed successfully!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
Reference in New Issue
Block a user