mexcdevelop / mexc-api-sdk

MIT License
173 stars 70 forks source link

ERORR IN CONNECTING AND INITITE TRADE VIA MEXC EXCHANGER #49

Open Dotijo opened 11 months ago

Dotijo commented 11 months ago

import requests import json import time import hashlib import hmac

API_KEY='my api key here' SECRET_KEY='my secret key here'

def create_signed_request(api_key, secret_key, method, endpoint, params={}): base_url = 'https://www.mexc.com' request_url = f"{base_url}{endpoint}" timestamp = int(time.time() * 1000) params['api_key'] = api_key params['req_time'] = timestamp sorted_params = sorted(params.items()) query_string = "&".join([f"{k}={v}" for k, v in sorted_params])

if method == 'GET':
    to_sign = f"{method}{request_url}?{query_string}"
else:
    to_sign = f"{method}{request_url}"

signature = hmac.new(secret_key.encode(), to_sign.encode(), hashlib.sha256).hexdigest()
headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
    'Cookie': 'locale=en_US',
    'Authorization': f"{signature}",
}
if method == 'GET':
    response = requests.get(request_url, headers=headers)
else:
    response = requests.post(request_url, headers=headers, data=query_string)

return response.json()

def place_market_order(api_key, secret_key, symbol, quantity, trade_type): endpoint = '/open/api/v2/order/place' method = 'POST'

params = {
    'symbol': symbol,
    'trade_type': trade_type,
    'order_type': 'MARKET',
    'quantity': quantity,
}

response = create_signed_request(api_key, secret_key, method, endpoint, params)

if 'data' in response and 'order_id' in response['data']:
    order_id = response['data']['order_id']
    print(f"Order placed with ID: {order_id}")
    return order_id
else:
    print("Error in place_market_order response:", response)
    return None

def check_order_status(api_key, secret_key, order_id): endpoint = '/open/api/v2/order/query' method = 'GET'

params = {
    'order_id': order_id,
}

response = create_signed_request(api_key, secret_key, method, endpoint, params)
return response
response = create_signed_request(api_key, secret_key, method, endpoint, params)
if 'data' in response and 'order_id' in response['data']:
    order_id = response['data']['order_id']
    return order_id
else:
    print("Error in place_market_order response:", response)
    return None

def wait_for_order_completion(order_id):

Wait for the order to be completed

while True:
    order_status_response = check_order_status(API_KEY, SECRET_KEY, order_id)

    # Check if the response contains 'data' and 'status' fields
    if 'data' in order_status_response and 'status' in order_status_response['data']:
        if order_status_response['data']['status'] == 'FILLED':
            print(f"Order with ID {order_id} filled.")
            break
        elif order_status_response['data']['status'] == 'CANCELED':
            print(f"Order with ID {order_id} canceled.")
            break
    else:
        print(f"Error in order {order_id} status response:", order_status_response)
        break

    time.sleep(2)  # Wait for 2 seconds

def condition_1_check():

XRP TO ETH TO USDT CONDITION @*@*@@

Trading_capital = 100
#PRICE FOR XRT_USDT @*@*@*@*@
response = requests.get(f"https://www.mexc.com/open/api/v2/market/ticker?symbol=XRP_USDT")
result = response.json()
if result.get('code') == 200:
    data = result.get('data', [])
    if data:
        xrpusdt_price = float(data[0].get('last'))

#Obtaining price for (XRP_ETH)@**@*@*
response = requests.get(f"https://www.mexc.com/open/api/v2/market/ticker?symbol=XRP_ETH")
result2=response.json()
if(result2.get('code') == 200):
        data=result2.get('data',[])
        if data:
            xrpeth_price=float(data[0].get('last'))
#Obtaining price for (ETH/USDT)@*@**@
response = requests.get(f"https://www.mexc.com/open/api/v2/market/ticker?symbol=ETH_USDT")
result3=response.json()
if(result3.get('code') == 200):
        data=result3.get('data',[])
        if data:
            ethusdt_price=float(data[0].get('last'))
#Calculating opportunity@*@**@*@

#Volume of trading XRP@@**@*@**@*
xrp_purchase=float(Trading_capital/xrpusdt_price)
#Volume of ETH gotting with XRP@**@*@
eth_purchase=float(xrp_purchase * xrpeth_price)
#Volume of USDT Gotting with ETH@*@*@
usdt_realised=float(eth_purchase * ethusdt_price)
diff1=float(usdt_realised - Trading_capital)
print("XRP TO ETH PROFIT: ", diff1)
if diff1 > 0.2:
    print("ARBITRAGE OPPORTUNITY FOUND FOR XRP TO ETH TO USDT ")
    return True  # Return True if valid

def condition_2_check():

ETH TO XRP TO USDT @*@*@@@@

Trading_capital = 100

response = requests.get(f"https://www.mexc.com/open/api/v2/market/ticker?symbol=XRP_USDT")
result = response.json()
if result.get('code') == 200:
    data = result.get('data', [])
    if data:
        xrpusdt_price = float(data[0].get('last'))

#Obtaining price for (XRP_ETH)@**@*@*
response = requests.get(f"https://www.mexc.com/open/api/v2/market/ticker?symbol=XRP_ETH")
result2=response.json()
if(result2.get('code') == 200):
        data=result2.get('data',[])
        if data:
            xrpeth_price=float(data[0].get('last'))
#Obtaining price for (ETH/USDT)@*@**@
response = requests.get(f"https://www.mexc.com/open/api/v2/market/ticker?symbol=ETH_USDT")
result3=response.json()
if(result3.get('code') == 200):
        data=result3.get('data',[])
        if data:
            ethusdt_price=float(data[0].get('last'))
#calculating the profit possibilities@*@***@*@
eth_purch=float(Trading_capital/ethusdt_price)
xrp_purch=float(eth_purch/xrpeth_price)
real_amount=float(xrp_purch*xrpusdt_price)
diff2=float(real_amount-Trading_capital)
print("ETH TO XRP PROFIT: ", diff2)
if diff2 > 0.2:
    print("ARBITRAGE OPPORTUNITY FOUND FOR ETH TO XRP TO USDT ")
    return True  # Return True if valid

def main_function(): while True:

Check all two conditions

    condition_1 = condition_1_check()
    condition_2 = condition_2_check()

    # If condition 1 is satisfied, perform action     
    if condition_1:

        API_KEY='mx0vglixsKMIKdcN3U'
        SECRET_KEY='54752033b70b7d31f3d9cfe3982229df2dbefcd539b02c7884e28ac4e747e9b9b3ee6bf0f6c7acba'

        XRT_USDT_SYMBOL = 'XRT_USDT'
        XRT_AMOUNT_USDT = 100

        # Step 1: Buy XRT with USDT using a market order
        buy_xrt_response = place_market_order(API_KEY, SECRET_KEY, XRT_USDT_SYMBOL, XRT_AMOUNT_USDT, 'BID')

        # Check if the response contains 'data' and 'order_id' fields
        if 'data' in buy_xrt_response and 'order_id' in buy_xrt_response['data']:
            buy_xrt_order_id = buy_xrt_response['data']['order_id']
            print(f"Buy XRT order placed with ID: {buy_xrt_order_id}")
        else:
            print("Error in buy XRT response:")
            print(json.dumps(buy_xrt_response, indent=4))  # Print the entire response for debugging
            exit()

        # Step 2: Wait for the buy XRT order to be completed
        wait_for_order_completion(buy_xrt_response['data']['order_id'])

        # Get the quantity of XRT bought
        xrt_quantity_bought = float(buy_xrt_response['data'].get('deal_quantity', 0))

        # Replace with the symbol of the trading pair XRT/ETH
        XRT_ETH_SYMBOL = 'XRT_ETH'

        # Step 3: Sell XRT to ETH using a market order
        sell_xrt_response = place_market_order(API_KEY, SECRET_KEY, XRT_ETH_SYMBOL, xrt_quantity_bought, 'ASK')

        # Check if the response contains 'data' and 'order_id' fields
        if 'data' in sell_xrt_response and 'order_id' in sell_xrt_response['data']:
            sell_xrt_order_id = sell_xrt_response['data']['order_id']
            print(f"Sell XRT order placed with ID: {sell_xrt_order_id}")
        else:
            print("Error in sell XRT response:", sell_xrt_response)
            exit()

        # Step 4: Wait for the sell XRT order to be completed
        wait_for_order_completion(sell_xrt_response['data']['order_id'])

        # Get the quantity of ETH bought
        eth_quantity_bought = xrt_quantity_bought / float(sell_xrt_response['data']['deal_price'])

        # Replace with the symbol of the trading pair ETH/USDT
        ETH_USDT_SYMBOL = 'ETH_USDT'

        # Step 5: Sell ETH to USDT using a market order
        sell_eth_response = place_market_order(API_KEY, SECRET_KEY, ETH_USDT_SYMBOL, eth_quantity_bought, 'ASK')

        # Check if the response contains 'data' and 'order_id' fields
        if 'data' in sell_eth_response and 'order_id' in sell_eth_response['data']:
            sell_eth_order_id = sell_eth_response['data']['order_id']
            print(f"Sell ETH order placed with ID: {sell_eth_order_id}")
        else:
            print("Error in sell ETH response:", sell_eth_response)
            exit()

        # Step 6: Wait for the sell ETH order to be completed
        wait_for_order_completion(sell_eth_response['data']['order_id'])

    # If the condition is not satisfied, wait for some time before checking again
    time.sleep(1)  # Wait for 1 second before checking again

    if condition_2:
        ETH_USDT_SYMBOL = 'ETH_USDT'
        ETH_AMOUNT_USDT = 100
        # Step 1: Buy ETH with USDT using a market order
        buy_eth_response = place_market_order(API_KEY,SECRET_KEY,ETH_USDT_SYMBOL,ETH_AMOUNT_USDT,'BID')
        # Check if the response contains 'data' and 'order_id' fields
        if 'data' in buy_eth_response and 'order_id' in buy_eth_response['data']:
            buy_eth_order_id = buy_eth_response['data']['order_id']
            print(f"Buy ETH order placed with ID: {buy_eth_order_id}")
        else:
            print("Error in buy ETH response:")
            print(json.dumps(buy_eth_response, indent=4))
            # Print the entire response for debugging
            return  # Exit the function or handle the error appropriately
            # Step 2: Wait for the buy ETH order to be complete
            wait_for_order_completion(buy_eth_response['data']['order_id'])
            # Get the quantity
            eth_quantity_bought =float(buy_eth_response['data'].get('deal_quantity', 0))
            # Replace with the symbol of the trading pair XRP/ETH
            XRP_ETH_SYMBOL = 'XRP_ETH'
            # Step 3: Buy XRP with Ethereum using a market order
            buy_xrp_response = place_market_order(API_KEY, SECRET_KEY, XRP_ETH_SYMBOL, eth_quantity_bought, 'BID')
            # Check if the response contains 'data' and 'order_id' fields
            if 'data' in buy_xrp_response and 'order_id' in buy_xrp_response['data']:
                buy_xrp_order_id = buy_xrp_response['data']['order_id']
                print(f"Buy XRP order placed with ID: {buy_xrp_order_id}")
            else:
                    print("Error in buy XRP response:", buy_xrp_response)
                    return  # Exit the function or handle the error appropriately

        # Step 4: Wait for the buy XRP order to be completed
    wait_for_order_completion(buy_xrp_response['data']['order_id'])

    # Replace with the symbol of the trading pair XRP/USDT
    XRP_USDT_SYMBOL = 'XRP_USDT'
    # Step 5: Sell XRP to USDT using a market order
    sell_xrp_response = place_market_order(API_KEY, SECRET_KEY, XRP_USDT_SYMBOL, eth_quantity_bought, 'ASK')

    # Check if the response contains 'data' and 'order_id' fields
    if 'data' in sell_xrp_response and 'order_id' in sell_xrp_response['data']:
        sell_xrp_order_id = sell_xrp_response['data']['order_id']
        print(f"Sell XRP order placed with ID: {sell_xrp_order_id}")
    else:
        print("Error in sell XRP response:", sell_xrp_response)
        return  # Exit the function or handle the error appropriately

    # Step 6: Wait for the sell XRP order to be completed
    wait_for_order_completion(sell_xrp_response['data']['order_id'])

# If the condition is not satisfied, wait for some time before checking again
time.sleep(1)  # Wait for 1 second before checking again

Run the main function indefinitely

print("NO ARBITRAGE OPPORTUNITY........................")
time.sleep(1)  # Wait for 1 seconds

main_function()