簡體   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