Binance Buy or Sell Request
9 views (last 30 days)
Show older comments
hey everyone
another thing I really need your help is sending a request for Binance API.
well, I think it is not only my question because it many times asked around the net in the Matlab community.
in Binance there are two API, one for the real trade and another for the test trade(demo account).
here is my Matlab code,
unfortunately, it doesn't work. with this piece of code, I try to place a buy or sell order but a bad type result sends back.
% Set up authentication:
APIKey = '12a2fff338b41101ed886dd1c0ef4f35e96fe0233c23616daed4f2dbd1389526';
APISecret = '3d52b16aa7a0c6cd12fd11e09a955967cfeb839ff729357a0ca272351da75873';
symbol = 'BTCUSDT';
type = 'limit'; % or 'market'
side = 'sell'; % or 'buy'
amount = 1.0;
price = 60540; % or None
options = weboptions('RequestMethod',apiMethod, 'MediaType','application/json');
Body = struct('symbol', symbol, ...
'type', type, ...
'side', side, ...
'amount', char(num2str(amount)), ...
'price', char(num2str(price)), ...
'APIKey', APIKey,...
'APISecret', APISecret);
webaddress = 'https://testnet.binance.vision/api/v3/order/';
response = webwrite(webaddress, Body, options);
and here is the Python code
def place_trade(symbol, side, order_type, quantity):
# Setup header with API_KEY
headers = {'X-MBX-APIKEY': settings.API_KEY}
# Params require symbol, side, type, quantity and timestamp (for market orders)
params = {
'symbol': symbol,
'side': side,
'type': order_type,
'quantity': quantity,
'timestamp': int(time.time() * 1000)
}
# Encode params into url
url = 'https://api.binance.us/api/v3/order/test?' + urllib.parse.urlencode(params)
# Create a HMAC SHA256 signature
secret = bytes(settings.SECRET_KEY.encode('utf-8'))
signature = hmac.new(secret, urllib.parse.urlencode(params).encode('utf-8'), hashlib.sha256).hexdigest()
# Add signature to url
url += f'&signature={signature}'
# Encode params
data = urllib.parse.urlencode(params).encode('ascii')
# Make a POST request
req = urllib.request.Request(url, data, headers)
# Open request and convert to string and then to json
response = urllib.request.urlopen(req) # <- line with error
response_str = response.read().decode('utf-8')
response_json = json.loads(response_str)
print(response_json)
place_trade(symbol='BTCUSD', side='BUY', order_type='MARKET', quantity=1)
I really appreciate your time and helps.
0 Comments
Answers (0)
See Also
Categories
Find more on Transaction Cost Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!