如何使用MEXC API正确下止损限价单

问题描述 投票:0回答:1

我尝试使用他们的 API 在 MEXC 上下止损限价单,但我一直遇到错误。我收到的错误消息是:

HTTP error occurred: 400 Client Error: Bad Request for url: https://api.mexc.com/api/v3/order
{"code":700013,"msg":"Invalid content Type."}

下面是我用来下订单的脚本:

import requests
import time
import hmac
import hashlib

# Your MEXC API key and secret
API_KEY = 'your_api_key'
API_SECRET = 'your_api_secret'

# Base URL for MEXC API
BASE_URL = 'https://api.mexc.com/api/v3'

# Function to create the signature for the request
def create_signature(query_string, secret):
    return hmac.new(secret.encode(), query_string.encode(), hashlib.sha256).hexdigest()

# Function to place a stop-limit order
def place_stop_limit_order():
    endpoint = '/order'
    timestamp = int(time.time() * 1000)
    
    # Parameters for the stop-limit order
    params = {
        'symbol': 'ETHUSDC',
        'side': 'BUY',
        'type': 'STOP_LOSS_LIMIT',   # Order type
        'quantity': '0.01',         # Quantity to buy
        'price': '4000.01',          # Limit price
        'stopPrice': '4000',         # Stop price
        'timeInForce': 'GTC',        # Time in force
        'timestamp': timestamp
    }

    query_string = '&'.join([f"{key}={value}" for key, value in sorted(params.items())])
    signature = create_signature(query_string, API_SECRET)
    
    headers = {
        'X-MEXC-APIKEY': API_KEY,
        'Content-Type': 'application/x-www-form-urlencoded'  # Correct content type
    }

    # Adding signature to the query string
    query_string += f"&signature={signature}"

    # Make the request to place the order
    response = requests.post(BASE_URL + endpoint, headers=headers, data=query_string)
    try:
        response.raise_for_status()  # Raise an HTTPError for bad responses (4xx and 5xx)
    except requests.exceptions.HTTPError as err:
        print(f"HTTP error occurred: {err}")  # Print HTTP error
        print(response.text)  # Print the response content
    except Exception as err:
        print(f"Other error occurred: {err}")  # Print other errors

    return response.json()

# Main function to place the stop-limit order
def main():
    result = place_stop_limit_order()
    print(f"Order placed: {result}")

if __name__ == "__main__":
    main()

我已确保按照各种文档中的建议将 Content-Type 设置为“application/x-www-form-urlencoded”。尽管如此,我仍然收到无效内容类型错误。

有人可以帮我确定我可能做错了什么吗?任何建议或更正将不胜感激。

提前谢谢您!

python cryptocurrency
1个回答
0
投票

/api/v3/order 的文档? 显示示例

POST /api/v3/order?symbol=MXUSDT&...

这意味着它不会将其发送为

form
而是作为
query string

这需要

params=
而不是
data=

response = requests.post(..., params=query_string)

© www.soinside.com 2019 - 2024. All rights reserved.