I'm trying to place a stop-limit order on MEXC using their API, but I keep encountering an error. The error message I'm receiving is:
HTTP error occurred: 400 Client Error: Bad Request for url: https://api.mexc.com/api/v3/order
{"code":700013,"msg":"Invalid content Type."}
Below is the script I am using to place the order:
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()
I have ensured that the Content-Type is set to 'application/x-www-form-urlencoded' as suggested in various documentation. Despite this, I still get the invalid content type error.
Could someone please help me identify what I might be doing wrong? Any suggestions or corrections would be greatly appreciated.
Thank you in advance!
requests.post
curl
- so you could use pages like CurlConverter.com to convert it to Python. But sometimes it may create wrong code.POST /api/v3/order?symbol=MXUSDT&...
and it means it doesn't send it asform
but as query string (which needsparams='
instead ofdata=