JSN API MATLAB POST request

16 views (last 30 days)
Daniel Baeriswyl
Daniel Baeriswyl on 31 May 2017
Commented: Abolfazl Nejatian on 21 May 2021
I have problems making a request with a json file in Matlab (using JSONlab)
the request has to be:
$ body=$(cat << EOF
{
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
EOF
)
curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <AUTHENTICATION TOKEN>" \
-d "$body" \
"https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders"$
then I do this in Matlab
Auth_Header = http_createHeader('Authorization',['Bearer <AUTHENTICATION TOKEN>']);
Body = ['&units=','100','&instrument=','EUR_USD','&timeInForce=','FOK','&type=','MARKET','&positionFill=','DEFAULT'];
RawOrderInfo = loadjson(urlread2('https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders',...
'POST', Body ,Auth_Header)
I know that something with my body is wrong. Can anyone help me and tell me whats wrong with my loadjson request ?
I get a server response: errorMessage: 'Unsupported ContentType: application/x-www-form-urlencoded'
Thank you!

Answers (3)

Kojiro Saito
Kojiro Saito on 7 Jun 2017
You're also using urlread2?
I think you should add "Content-Type" header.
Auth_Header = http_createHeader({'Authorization', 'Content-Type'} ,{['Bearer <AUTHENTICATION TOKEN>'], 'application/json'});
Also, if you use MATLAB R2015a or later, it's better to use webwrite.
url = 'https://api-fxtrade.oanda.com/v3/accounts/<ACCOUNT>/orders';
options = weboptions('RequestMethod','post', 'MediaType','application/json');
Body = struct('units', '100', ...
'instrument', 'EUR_USD', ...
'timeInForce', 'FOK', ...
'type', 'MARKET', ...
'positionFill', 'DEFAULT');
Body = struct('order', Body);
response = webwrite(url, Body, options);
Hope it works.
  5 Comments
Abolfazl Nejatian
Abolfazl Nejatian on 21 May 2021
Dear Kojiro
Thank you for your help.
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 greatly appreciate your help.
kind regards,
Abolfazl Nejatian

Sign in to comment.


Elbi Mutluoglu
Elbi Mutluoglu on 22 Jan 2020
curl -XPOST "Content-type: application/json" -d '{ "secret": "your_secret" }' 'https://baseURL/locationHistory/versionNumber/register?key=Your_API_Key'
How can I send this via matlab?
  1 Comment
Kojiro Saito
Kojiro Saito on 31 Jan 2020
Try this.
opts = weboptions('ContentType', 'json');
url = 'https://baseURL/locationHistory/versionNumber/register?key=Your_API_Key';
fieldName = 'secret';
fieldValue = 'your_secret';
response = webwrite(url, fieldName, fieldValue, opts);

Sign in to comment.


balaji p
balaji p on 14 Feb 2021
curl "https://api.kite.trade/orders/151220000000000/trades" -H "Authorization:token <key>:<token>"
Can you help with the command?

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!