繁体   English   中英

使用 Python API 访问交易平台

[英]API access to trading platform using Python

我是使用 API 和 Python 获取数据的新手。 我想从我的交易平台中提取数据。 他们提供了以下说明:

http://www.questrade.com/api/documentation/getting-started

我在第 4 步之前没问题,并且有一个访问令牌。 我需要第 5 步的帮助。如何翻译此请求:

GET /v1/accounts HTTP/1.1
Host: https://api01.iq.questrade.com
Authorization: Bearer C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp

进入 Python 代码? 我试过了

import requests
r = requests.get('https://api01.iq.questrade.com/v1/accounts', headers={'Authorization': 'access_token myToken'})

我在阅读本文后尝试过: python request with authentication (access_token)

任何帮助将不胜感激。 谢谢。

正如您所指出的,在第 4 步之后,您应该会收到一个访问令牌,如下所示:

{
    “access_token”: ”C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp”,
    “token_type”: ”Bearer”,
    “expires_in”: 300,
    “refresh_token”: ”aSBe7wAAdx88QTbwut0tiu3SYic3ox8F”,
    “api_server”: ”https://api01.iq.questrade.com”
}

要进行后续 API 调用,您需要按如下方式构建 URI:

uri = [api_server]/v1/[rest_operation]

e.g.
uri = "https://api01.iq.questrade.com/v1/time"

Note: Make sure you use the same [api_server] that you received in your json object from step 4, otherwise your calls will not work with the given access_token

接下来,按如下方式构建您的标头:

headers = {'Authorization': [token_type] + ' ' + [access_token]}

e.g.
headers = {'Authorization': 'Bearer C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp'}

最后,让您的请求调用如下

r = requests.get(uri, headers=headers)
response = r.json()

希望这有帮助!

注意:您可以在 GitHub 上找到一个 Questrade API Python 包装器,它为您处理上述所有内容。 https://github.com/pcinat/QuestradeAPI_PythonWrapper

改进彼得的回复(谢谢彼得!)首先使用您从 QT 网站获得的令牌来获取 access_token 并分配一个 api_server 来处理您的请求。

# replace XXXXXXXX with the token given to you in your questrade account

import requests

r = requests.get('https://login.questrade.com/oauth2/token?grant_type=refresh_token&refresh_token=XXXXXXXX')

access_token = str(r.json()['access_token'])
refresh_token= str(r.json()['refresh_token']) # you will need this refresh_token to obtain another access_token when it expires
api_server= str(r.json()['api_server'])
token_type= str(r.json()['token_type'])
api_server= str(r.json()['api_server'])
expires_in = str(r.json()['expires_in'])

# uri = api_server+'v1/'+[action] - let's try checking the server's time:
uri = api_server+'v1/'+'time'
headers = {'Authorization': token_type +' '+access_token}
# will look sth like this
 
#    headers will look sth like    {'Authorization': 'Bearer ix7rAhcXx83judEVUa8egpK2JqhPD2_z0'}
#        uri will look sth like    'https://api05.iq.questrade.com/v1/time'

# you can test now with
r = requests.get(uri, headers=headers)
response = r.json()
print(response)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM