用python3連oanda的模擬交易api時現HTTP Error 401: UNAUTHORIZED,新手求教:
import urllib.parse
import urllib.request
url = 'https://api-fxpractice.oanda....'
access_token = 'a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380'
account_id = 'cawa11'
values = {'accountId':account_id}
headers = {'授權':'承載'access_token}
data = urllib.parse.urlencode(values).encode("utf-8")
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()
報錯:
Traceback(最近一次呼叫最後一次):
檔案“C:UserslenovoDesktopbb.py”,第 36 行,在
檔案“C:Python34liburllibrequest.py”,第 161 行,在 urlopen
雷雷檔案“C:Python34liburllibrequest.py”,第 469 行,開啟
雷雷檔案“C:Python34liburllibrequest.py”,第 579 行,在 http_response
雷雷檔案“C:Python34liburllibrequest.py”,第 507 行,錯誤
雷雷檔案“C:Python34liburllibrequest.py”,第 441 行,在 _call_chain
雷雷檔案“C:Python34liburllibrequest.py”,第 587 行,位於 http_error_default
# 雷雷urllib.error.HTTPError:HTTP 錯誤 401:未經授權
雷雷
問題已解決,謝謝各位關注:
import requests
import json
instruments = 'EUR_USD'
account_id = 'cawa11'
access_token = 'a554db3a48ac8180a6996a 4ce05e4380'
params = {'instruments':instruments,'accountId':account_id }
headers = {'Authorization':'Bearer '+access_token}
r = requests.get("https://api-fxpractice.oanda.com/v1/prices",headers = headers, params=params)
price = r.json()
print(price'prices'['instrument'].replace('_','/'),':',round((price'prices'['ask']+price'prices '['bid'])/2,4))
輸出:EUR/USD : 1.0905