mexcdevelop / mexc-api-sdk Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
RuntimeError: Error: connect ETIMEDOUT 199.16.156.71:443
how do i add this to a project that I need to the cloud if i have it only as a local folder?
Whenever I try to sign request for BEP20(BSC)
network using Base.signRequest
, request fails with invalid signature error. If I try different network like TRC20
for exactly same request, it passes.
{"code":700002,"msg":"Signature for this request is not valid."}
I suspect this is caused by parenthesis in the network name, but I was not able to figure out which format server expects.
I have tried to encode them as URL before passing the whole URL to Base.signRequest, but still no success.
I installed mexc-api-sdk
pip install mexc_sdk-1.0.0-py3-none-any.whl
when i try run this :
from mexc_sdk import Spot
I got an error:
Traceback (most recent call last): File "D:\all\Programming\arbitrage_screener_tg\exchanges_api.py", line 3, in <module> from mexc_sdk import Spot File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\mexc_sdk\__init__.py", line 502, in <module> from ._jsii import * File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\mexc_sdk\_jsii\__init__.py", line 11, in <module> __jsii_assembly__ = jsii.JSIIAssembly.load( ^^^^^^^^^^^^^^^^^^^^^^^ File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\jsii\_runtime.py", line 55, in load _kernel.load(assembly.name, assembly.version, os.fspath(assembly_path)) File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\jsii\_kernel\__init__.py", line 299, in load self.provider.load(LoadRequest(name=name, version=version, tarball=tarball)) File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\jsii\_kernel\providers\process.py", line 352, in load return self._process.send(request, LoadResponse) ^^^^^^^^^^^^^ File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\jsii\_utils.py", line 23, in wrapped stored.append(fgetter(self)) ^^^^^^^^^^^^^ File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\jsii\_kernel\providers\process.py", line 347, in _process process.start() File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\jsii\_kernel\providers\process.py", line 260, in start self._process = subprocess.Popen( ^^^^^^^^^^^^^^^^^ File "C:\Users\dkala\AppData\Local\Programs\Python\Python311\Lib\subprocess.py", line 1024, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "C:\Users\dkala\AppData\Local\Programs\Python\Python311\Lib\subprocess.py", line 1493, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: [WinError 2] Не удается найти указанный файл Exception ignored in: <function _NodeProcess.__del__ at 0x000002BB5A3A9A80> Traceback (most recent call last): File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\jsii\_kernel\providers\process.py", line 228, in __del__ self.stop() File "D:\all\Programming\arbitrage_screener_tg\venv\Lib\site-packages\jsii\_kernel\providers\process.py", line 291, in stop assert self._process.stdin is not None ^^^^^^^^^^^^^ AttributeError: '_NodeProcess' object has no attribute '_process'
What I need to do to fix this?
Hi Guys
I found this repo and all the code in the main branch have been reverted.
So where is the stable develop branch?
I have an error that I can't understand it
When i request to api/v1/private/account/assets
I give the bellow error or give 500
error and this route don't work for me.
{
"success": false,
"code": 500,
"message": "Internal error!"
}
�����������V*.MNN-.V�JK�)N�QJ�OIU�250�Q���'��yJ�y%�Ey�9
�EE�E�J���������.�s98���
Also it would be cool to have batch delete which was in v2 as DELETE /open/api/v2/order/cancel
(up to 20 orders).
Maybe it exists but I can't find it in the documentation or in crypto libs.
can not find module "mexc-sdk/mexcsdk"
Hello, I use next subscriber for getting klines of one symbol BTC_USDT
{ "method":"sub.kline", "param":{ "symbol":"BTC_USDT", "interval":"Min1" } }
This subscriber works ok
I try to use this subscriber:
{ "method":"sub.kline", "param":{ "symbols":['BTC_USDT', 'ETH_USDT', 'LTC_USDT'], "interval":"Min1" } }
But I get error:
{ channel: 'rs.error', data: 'Contract [null] not exists', ts: 1684060854633 }
How must I make a subscriber for getting klines of multiple symbols 'BTC_USDT', 'ETH_USDT', 'LTC_USDT'?
The API docs for futures transaction (websocket and http) define the "open" position (data["O"]
) field value as either "1" (open) or "2" (closed). However the example in the http docs show the value as "3". I was hoping you could confirm the possible values for the contract transaction open field and their meaning?
https://mxcdevelop.github.io/apidocs/contract_v1_en/#get-contract-transaction-data
Parameter | Data Type | Description
-- | -- | --
p | decimal | transaction price
v | decimal | volume
T | int | transaction direction,1:purchase,2:sell
O | int | open position?, 1: Yes,2: No, vol is the additional position when O is 1
M | int | Is it auto-transact ? 1: Yes,2: No
t | long | transaction time
Sample response from docs:
Request
curl "https://contract.mexc.com/api/v1/contract/deals/BTC_USDT"
Response
{
"success": true,
"code": 0,
"data": [
{
"p": 31199,
"v": 18,
"T": 1,
"O": 3,
"M": 2,
"t": 1609831235985
},
{
"p": 31199,
"v": 15,
"T": 2,
"O": 3,
"M": 1,
"t": 1609831234759
}
]
}
A sample from the websocket contains "3" as the open position value:
< {"channel":"rs.sub.deal","data":"success","ts":1666181088488}
< {"symbol":"BTC_USDT","data":{"p":19160.4,"v":808,"T":1,"O":3,"M":1,"t":1666181088780},"channel":"push.deal","ts":1666181088781}
< {"symbol":"BTC_USDT","data":{"p":19160.4,"v":600,"T":1,"O":3,"M":1,"t":1666181088802},"channel":"push.deal","ts":1666181088802}
< {"symbol":"BTC_USDT","data":{"p":19160.3,"v":1634,"T":2,"O":3,"M":1,"t":1666181089249},"channel":"push.deal","ts":1666181089249}
< {"symbol":"BTC_USDT","data":{"p":19160.3,"v":184,"T":2,"O":3,"M":1,"t":1666181089270},"channel":"push.deal","ts":1666181089270}
< {"symbol":"BTC_USDT","data":{"p":19160.3,"v":225,"T":2,"O":3,"M":1,"t":1666181089284},"channel":"push.deal","ts":1666181089284}
< {"symbol":"BTC_USDT","data":{"p":19160.4,"v":300,"T":1,"O":1,"M":2,"t":1666181090716},"channel":"push.deal","ts":1666181090716}
< {"symbol":"BTC_USDT","data":{"p":19160.3,"v":1249,"T":1,"O":3,"M":1,"t":1666181090791},"channel":"push.deal","ts":1666181090791}
< {"symbol":"BTC_USDT","data":{"p":19160.3,"v":3015,"T":1,"O":3,"M":1,"t":1666181090807},"channel":"push.deal","ts":1666181090807}
< {"symbol":"BTC_USDT","data":{"p":19160.3,"v":3430,"T":1,"O":3,"M":1,"t":1666181090823},"channel":"push.deal","ts":1666181090823}
// these are three consecutive pushes after sending a BUY LIMIT order
// initial USDT balance when sending order, was "31.5433752502"
{
"c": "[email protected]",
"d": {
"a": "USDT",
"c": 1680208095208,
"f": "31.5433752502", // free balance does not change!
"fd": "-31.258238011",
"l": "0", // locked balance should be "31.258238011"
"ld": "31.258238011",
"o": "ENTRUST_PLACE"
},
"t": 1680208095213
},
{
"c": "[email protected]",
"d": {
"a": "USDT",
"c": 1680208095226,
"f": "31.5434047324", // still no change!
"fd": "0.0000294822",
"l": "-30.260235258", // how can locked balance be negative?
"ld": "-30.260235258",
"o": "ENTRUST"
},
"t": 1680208095230
},
{
"c": "[email protected]",
"d": {
"a": "USDT",
"c": 1680208095242,
"f": "31.5738305751", // order fully executed; wrong balance
"fd": "0.0304258427",
"l": "-31.258238011", // should be zero
"ld": "-0.998002753",
"o": "ENTRUST"
},
"t": 1680208095244
}
Sometimes /api/v3/depth request provides invalid (crossed) book BID > ASK:
18 Apr 18:34:39 (UTC) BTCUSDT: {"lastUpdateId":1036364564,"bids":[["40790.35","6.737136"],["40788.40","0.834924"],["40787.66","6.512868"],["40785.85","0.007980"],["40785.49","0.976608"],["40785.45","1.030200"],["40784.80","0.000312"],["40784.60","0.014952"],["40784.56","1.727460"],["40784.54","0.098064"],["40784.52","0.098064"],["40783.55","0.329112"],["40782.99","0.298020"],["40782.14","0.397176"],["40781.55","0.009144"],["40781.37","0.262524"],["40781.32","0.298332"],["40780.77","0.024000"],["40780.58","0.060000"],["40780.35","0.009192"]],
"asks":[["40789.41","0.631392"],["40790.37","0.181428"],["40790.38","0.604788"],["40790.60","0.000444"],["40791.91","1.020000"],["40792.64","0.000444"],["40793.18","1.036812"],["40793.89","0.057372"],["40793.99","0.043716"],["40794.73","0.063852"],["40794.88","1.020000"],["40794.91","0.054684"],["40795.93","0.054180"],["40796.35","0.024000"],["40797.11","0.628716"],["40797.89","0.552000"],["40799.81","0.028272"],["40829.45","0.073486"],["40830.34","0.000363"],["40831.37","0.020839"]]}
Is this by design?
Hello,
I'm unable to receive the hightest bid and lowest ask prices through web socket. Will you add this feature as the other markets did?
often a pair goes into a hidden trading zone and there is no way to determine that it ended up there. The status of the pair itself remains 'ENABLED'
I install mexc-api-sdk
pip install C:\lib\mexc_sdk-1.0.0-py3-none-any.whl
when i try run this :
from mexc_sdk import Spot
spot = Spot(api_key='yyyyyyyyyyyyyy', apiSecret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
i get error:
File "D:\project\aa.py", line 1, in
from mexc_sdk import Spot
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\site-packages\mexc_sdk_init_.py", line 502, in
from .jsii import *
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\site-packages\mexc_sdk_jsii_init.py", line 11, in
jsii_assembly = jsii.JSIIAssembly.load(
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\site-packages\jsii_runtime.py", line 53, in load
kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\site-packages\jsii_kernel_init.py", line 300, in load
self.provider.load(LoadRequest(name=name, version=version, tarball=tarball))
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\site-packages\jsii_kernel\providers\process.py", line 344, in load
return self._process.send(request, LoadResponse)
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\site-packages\jsii_utils.py", line 24, in wrapped
stored.append(fgetter(self))
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\site-packages\jsii_kernel\providers\process.py", line 339, in _process
process.start()
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\site-packages\jsii_kernel\providers\process.py", line 252, in start
self._process = subprocess.Popen(
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\subprocess.py", line 1022, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\electra\AppData\Local\Programs\Python\Python311\Lib\subprocess.py", line 1491, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] Не удается найти указанный файл
Below is the code am having isue executing having pasted my API KEY and the SECRET KEY:
import time
import requests
import hashlib
import hmac
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 get_account_balance(api_key, secret_key):
endpoint = '/open/api/v2/account/info'
method = 'GET'
response = create_signed_request(api_key, secret_key, method, endpoint)
if 'code' in response and response['code'] == '200':
return response['data']['spot']['list']
else:
print("Error in getting account balance:", response)
return None
def main():
# Read API key and secret key from the user
API_KEY='my api key is pasted here'
SECRET_KEY='my secret key pasted here'
# Get account balance
account_balance = get_account_balance(API_KEY, SECRET_KEY)
if account_balance:
print("Account Balance:")
for balance in account_balance:
asset = balance['currency']
free_balance = balance['available']
locked_balance = balance['frozen']
print(f"{asset}: Free={free_balance}, Locked={locked_balance}")
else:
print("Failed to retrieve account balance.")
if name == "main":
main()
Where is your spot websocket api doc? It is not shown here
How i can create market order on futures market?
import time
import requests
import hashlib
import hmac
import json
def create_signed_request(api_key, secret_key, method, endpoint, params={}):
base_url = 'https://api.example.com'
#50 Replace with the API base URL
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])
# Fix the ternary if-else statement
to_sign = f"{method}{request_url}?{query_string}" if method == 'GET' else f"{method}{request_url}"
signature = hmac.new(secret_key.encode(), to_sign.encode(), hashlib.sha256).hexdigest()
headers = {
'X-API-KEY': api_key,
'Content-Type': 'application/json',
'Authorization': f"{signature}",
}
if method == 'GET':
response = requests.get(request_url, headers=headers)
else:
response = requests.post(request_url, headers=headers, data=json.dumps(params))
if response.status_code == 200:
return response.json() # Return the JSON response
else:
print(f"Failed to retrieve data. Status Code: {response.status_code}")
return None
def main():
# Read API key and secret key from the user
API_KEY = 'my api key here'
SECRET_KEY = 'my secret key here'
# Example parameters for the /api/v3/rebate/referCode endpoint
params = {
'param1': 'value1',
'param2': 'value2',
}
# Make the signed request to the /api/v3/rebate/referCode endpoint
response = create_signed_request(API_KEY, SECRET_KEY, 'POST', '/api/v3/rebate/referCode', params=params)
if response:
print("Response:")
print(json.dumps(response, indent=4))
else:
print("Failed to retrieve data.")
if name == "main":
main()
Hi
I get this messages after run - from mexc_sdk.src.mexc_sdk import Spot or from mexc_sdk import Spot
Please help
Traceback (most recent call last):
File "G:\PythonConnectToAPI\MexcCoinInfo.py", line 1, in
from mexc_sdk.src.mexc_sdk import Spot
File "G:\PythonConnectToAPI\venv\lib\site-packages\mexc_sdk_init_.py", line 502, in
from .jsii import *
File "G:\PythonConnectToAPI\venv\lib\site-packages\mexc_sdk_jsii_init.py", line 11, in
jsii_assembly = jsii.JSIIAssembly.load(
File "G:\PythonConnectToAPI\venv\lib\site-packages\jsii_runtime.py", line 55, in load
kernel.load(assembly.name, assembly.version, os.fspath(assembly_path))
File "G:\PythonConnectToAPI\venv\lib\site-packages\jsii_kernel_init.py", line 299, in load
self.provider.load(LoadRequest(name=name, version=version, tarball=tarball))
File "G:\PythonConnectToAPI\venv\lib\site-packages\jsii_kernel\providers\process.py", line 352, in load
return self._process.send(request, LoadResponse)
File "G:\PythonConnectToAPI\venv\lib\site-packages\jsii_utils.py", line 23, in wrapped
stored.append(fgetter(self))
File "G:\PythonConnectToAPI\venv\lib\site-packages\jsii_kernel\providers\process.py", line 347, in _process
process.start()
File "G:\PythonConnectToAPI\venv\lib\site-packages\jsii_kernel\providers\process.py", line 260, in start
self._process = subprocess.Popen(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
Exception ignored in: <function _NodeProcess.del at 0x00000242CFF756C0>
Traceback (most recent call last):
File "G:\PythonConnectToAPI\venv\lib\site-packages\jsii_kernel\providers\process.py", line 228, in del
self.stop()
File "G:\PythonConnectToAPI\venv\lib\site-packages\jsii_kernel\providers\process.py", line 291, in stop
assert self._process.stdin is not None
AttributeError: '_NodeProcess' object has no attribute '_process'
https://api.mexc.com/api/v3/aggTrades?symbol=BTCUSDT&startTime=1681622015000&endTime=1681625555000 gives no trades
startTime = 1681622015000 = Sun Apr 16 2023 05:13:35 GMT+0000
endTime = 1681625555000 = Sun Apr 16 2023 06:12:35 GMT+0000
It works if startTime and endTime are recent values but not if going just a few hours back in time
I often 502 error take from your nginx server for 24 hour. I think some server down, or we, as clients, do not have any information on the API v3 document for this error.
Can you explain this error.
Ex:
``[502 Bad Gateway] during [GET] to [https://api.mexc.com/api/v3/ticker/24hr?symbol=POLOUSDT] [MexcClient#getdata(String)]: [
<title>502 Bad Gateway</title>Hello Mexc Developer Team,
I have installed the package from https://pypi.org/project/mexc/ to use MEXC API. But when i import that in vscode to program in python, i got this Error :
ModuleNotFoundError: No module named 'mexc_sdk'
I have searched and tried some solutions from the internet but none worked.
Would you Please give me some help?
import time
import requests
import hashlib
import hmac
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])
to_sign = f"{method}{request_url}?{query_string}"
if method == 'GET' else 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 main():
# Read API key and secret key from the user
API_KEY = 'my api key here'
SECRET_KEY = 'my secret key here'
# Get account balance
account_balance = create_signed_request(API_KEY, SECRET_KEY, 'GET', '/account/v1/balance')
if account_balance:
print("Account Balance:")
for balance in account_balance:
asset = balance['currency']
free_balance = balance['available']
locked_balance = balance['frozen']
print(f"{asset}: Free={free_balance}, Locked={locked_balance}")
else:
print("Failed to retrieve account balance.")
if name == "main":
main()
to subscribe to a single symbol, you need to make a request like:
webSocket.send("{\"op\":\"sub.symbol\",\"symbol\":\"BTC_USDT\"}");
but I need to subscribe to a list of symbols, how to do it?
TAR_BAD_ARCHIVE: Unrecognized archive format??????
can not use?
Hello MEC, I have a problem using the MEXC API in both of my IDEs, VSCode and also PyCharm. Please can you point me at a page which describes how to install the MEXC API package into Python.
def get_exchange():
exchange_id = 'mexc'
exchange_class = getattr(ccxt, exchange_id)
return exchange_class({
'apiKey': 'API KEY',
'secret': 'SECRET KEY',
# Add any additional required parameters
})
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
print("NO ARBITRAGE OPPORTUNITY........................")
time.sleep(1) # Wait for 1 seconds
main_function()
Hi! I'm trying the python API sdk, and I found that the function "account_info" is not working.
I always get the same response from the server:
with status code 400:
{"code":700002,"msg":"Signature for this request is not valid."}
Anyone else with the same problem?
Thanks!
I am using react NextJS's api route to make a client using mexc's sdk. This is my code:
import * as Mexc from "../../../../mexc-sdk"
export const GET = async (request) => {
const client = Mexc.Spot(process.env.NEXT_PUBLIC_MEXC_ACCESSKEY, process.env.MEXC_SECRETKEY, { baseURL: 'https://api.mexc.com' })
// console.log(client)
return new Response("Yo.", { status: 200 })
}
But whenever I fetch this api route, it gives me this error:
Hi,
I was trying to place market orders with mexc api accessed via cctx library but it shows the following error. Error was reported to cctx as well, see ccxt/ccxt#12696 (comment)
"BadRequest mexc3 {"msg":"api market order is disabled","code":30019}"
Just to let you know that limit orders are working fine.
Thanks
Bacha
is there api to get permission?like binance,
GET /sapi/v1/account/apiRestrictions,returns
{
"ipRestrict": false, // 是否限制ip访问
"createTime": 1623840271000, // 创建时间
"enableInternalTransfer": true, // 此选项授权此密钥在您的母账户和子账户之间划转资金
"enableFutures": false, // 合约交易权限,需注意开通合约账户之前创建的API Key不支持合约API功能
"enablePortfolioMarginTrading":true, // 统一账户交易权限
"enableVanillaOptions": false, // 欧式期权交易权限
"permitsUniversalTransfer": true, // 授权该密钥可用于专用的万向划转接口,用以操作其支持的多种类型资金划转。各业务自身的划转接口使用权限,不受本授权影响
"enableReading": true,
"enableSpotAndMarginTrading": false, // 现货和杠杆交易权限
"enableWithdrawals": false, // 此选项允许通过此api提现。开启提现选项必须添加IP访问限制过滤器
"enableMargin": false, // 此选项在全仓账户完成划转后可编辑
"tradingAuthorityExpirationTime": 1628985600000 // 现货和杠杆交易权限到期时间,如果没有则不返回该字段
}
I installed the mexc-api-sdk.
I ran this in python 3.11
from mexc_sdk import Spot
spot = Spot(api_key='api key', apiSecret='secret')
Both of my keys are correct and valid.
I get this:
spot = Spot(api_key='api key', apiSecret='secrret')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Z\AppData\Local\Programs\Python\Python311\Lib\site-packages\jsii-1.80.0-py3.11.egg\jsii_runtime.py", line 112, in call
inst = super().call(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Spot.init() got an unexpected keyword argument 'apiSecret'
How can I fix this?
I want to request the interface(/open/api/v2/order/deals), but I need to use the data of the trading pair interface as a parameter(/open/api/v2/market/api_symbols). There are too many trading pairs.
This interface has to be requested many times, which is a very long process. Can you provide an interface to let me know which symbol are Valid?, which symbol are invalid?
#gh-33 pertains to 'ModuleNotFoundError' with this mexc_sdk
this StackOverflow post also pertains to the same error
/Library/Frameworks/Python.framework/Versions/3.11/bin/python3
/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages
from mexc_sdk import Spot
ModuleNotFoundError: No module named 'mexc_sdk'
pip install mexc-sdk
yieldsRequirement already satisfied: mexc-sdk in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (0.0.1)
python3 --version
yields the correct updated version in the terminal.tar.gz
file in the dist/python
directory.I try to withdraw to another mexc account address with withdraw API and i got this errror
{"code":10212,"msg":"This withdrawal address is not on the commonly used address list or has been invalidated"}
why it's happened?
File "D:\software\python\lib\site-packages\jsii-1.84.0-py3.8.egg\jsii_kernel_init_.py", line 399, in invoke
response = self.provider.invoke(
File "D:\software\python\lib\site-packages\jsii-1.84.0-py3.8.egg\jsii_kernel\providers\process.py", line 378, in invoke
return self._process.send(request, InvokeResponse)
File "D:\software\python\lib\site-packages\jsii-1.84.0-py3.8.egg\jsii_kernel\providers\process.py", line 340, in send
raise RuntimeError(resp.error) from JavaScriptError(resp.stack)
RuntimeError: Error: connect ETIMEDOUT 174.36.228.136:443
when using the url below
GET /api/v3/myTrades
When transmitting startTime
older than 7 days, no data is returned.
Please fix, I really need to receive older orders
order_eth_xrt = exchange.create_order(symbol_eth_xrp, type='market', side='sell', amount=eth_amount)
There is no documentation about format of values in options{}. So fucntions pay no attention to start and end times wich i pass to it, so I cant use the lib any more
def klines(
self,
symbol: builtins.str,
interval: builtins.str,
options: typing.Any = None,
) -> typing.Any:
'''Kline/Candlestick Data.
:param symbol: -
:param interval: -
:param options: ``[options.startTime] [options.endTime] [options.limit] -Default 500; max 1000. ex: 500``.
'''
I made a little module which has a function that creates a client. When I execute the module's function by itself it works, but when I use it from somewhere else like a nextjs page, it gives me a cors error, anyone know how to disable CORS so the function works properly?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.