JSN API MATLAB POST request
이전 댓글 표시
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!
답변 (3개)
Kojiro Saito
2017년 6월 7일
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
Noah van Hartesveldt
2019년 5월 7일
Hello,
This solution seems to work, except now returns the error of unauthorized, since I was not sure where to add in the authorization bearer token header. Is there a way to add in this type of header using webwrite?
Thanks,
Noah
Abolfazl Nejatian
2021년 5월 8일
Dear Kojiro,
I have a similare question with diffrent goal.
I need to send some photos to the Telegram API.
here is the document of telegram for sending photos,
and here is the python example of my goal
import requests
import json
bot_token = 'BOT TOKEN'
chat_id = "CHAT ID"
file = r"C:\Users\name\OneDrive\Desktop\Capture.PNG"
files = {
'photo': open(file, 'rb')
}
message = ('https://api.telegram.org/bot'+ bot_token + '/sendPhoto?chat_id='
+ chat_id)
send = requests.post(message, files = files)
the problem is i dont know how to convert dictionary in matlab.
if you could reform this python code to the matlab, I will appreciate your help.
thank in advance for your time
Kojiro Saito
2021년 5월 11일
Abolfazl Nejatian
2021년 5월 21일
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
Abolfazl Nejatian
2021년 5월 21일
i created a new topic for this question.
if you want you can answer there
Elbi Mutluoglu
2020년 1월 22일
0 개 추천
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
Kojiro Saito
2020년 1월 31일
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);
balaji p
2021년 2월 14일
0 개 추천
curl "https://api.kite.trade/orders/151220000000000/trades" -H "Authorization:token <key>:<token>"
Can you help with the command?
카테고리
도움말 센터 및 File Exchange에서 RESTful API에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!