Python量化交易:如何接入金融行情数据?
本文为大家介绍如何使用Python调用已经封装好的高频数据API。这里以Alltick的tick数据接口作为演示。下面是代码示例。
请求K线数据
import time
import requests
import json
# Extra headers
test_headers = {
'Content-Type':'application/json'
}
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co
将如下JSON进行url的encode,复制到http的查询字符串的query字段里
{"trace":"python_http_test1","data":{"code":"AAPL.US","kline_type":1,"kline_timestamp_end":0,"query_kline_num":2,"adjust_type":0}}
'''
test_url1 = 'https://quote.tradeswitcher.com/quote-stock-b-api/kline?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806&query=%7B%22trace%22%3A%22python_http_test1%22%2C%22data%22%3A%7B%22code%22%3A%22AAPL.US%22%2C%22kline_type%22%3A1%2C%22kline_timestamp_end%22%3A0%2C%22query_kline_num%22%3A2%2C%22adjust_type%22%3A0%7D%7D'
resp1 = requests.get(url=test_url1, headers=test_headers)
# Decoded text returned by the request
text1 = resp1.text
print(text1)
请求最新报价成交数据
import time
import requests
import json
# Extra headers
test_headers = {
'Content-Type':'application/json'
}
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co
将如下JSON进行url的encode,复制到http的查询字符串的query字段里
{"trace":"python_http_test2","data":{"symbol_list":[{"code": "700.HK"},{"code": "UNH.US"},{"code": "600416.SH"}]}}
'''
test_url1 = 'https://quote.tradeswitcher.com/quote-stock-b-api/trade-tick?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806&query=%7B%22trace%22%3A%22python_http_test2%22%2C%22data%22%3A%7B%22symbol_list%22%3A%5B%7B%22code%22%3A%20%22700.HK%22%7D%2C%7B%22code%22%3A%20%22UNH.US%22%7D%2C%7B%22code%22%3A%20%22600416.SH%22%7D%5D%7D%7D'
resp1 = requests.get(url=test_url1, headers=test_headers)
# Decoded text returned by the request
text1 = resp1.text
print(text1)
上面代码中symbol_list是可以同时传入多个的,分别传入不同的市场的产品也是可以的。
获取最新盘口报价数据
import time
import requests
import json
# Extra headers
test_headers = {
'Content-Type':'application/json'
}
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co
将如下JSON进行url的encode,复制到http的查询字符串的query字段里
{"trace":"python_http_test2","data":{"symbol_list":[{"code": "700.HK"},{"code": "UNH.US"},{"code": "600416.SH"}]}}
'''
test_url1 = 'https://quote.tradeswitcher.com/quote-stock-b-api/depth-tick?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806&query=%7B%22trace%22%3A%22python_http_test2%22%2C%22data%22%3A%7B%22symbol_list%22%3A%5B%7B%22code%22%3A%20%22700.HK%22%7D%2C%7B%22code%22%3A%20%22UNH.US%22%7D%2C%7B%22code%22%3A%20%22600416.SH%22%7D%5D%7D%7D'
resp1 = requests.get(url=test_url1, headers=test_headers)
# Decoded text returned by the request
text1 = resp1.text
print(text1)
同上,symbol_list支持传入多个值。
通过Websocket订阅实时行情数据
import json
import websocket # pip install websocket-client
'''
github:https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
申请免费token:https://alltick.co/register
官网:https://alltick.co
'''
class Feed(object):
def __init__(self):
self.url = 'wss://quote.tradeswitcher.com/quote-stock-b-ws-api?token=e945d7d9-9e6e-4721-922a-7251a9d311d0-1678159756806' # 这里输入websocket的url
self.ws = None
def on_open(self, ws):
"""
Callback object which is called at opening websocket.
1 argument:
@ ws: the WebSocketApp object
"""
print('A new WebSocketApp is opened!')
# 开始订阅(举个例子)
sub_param = {
"cmd_id": 22002,
"seq_id": 123,
"trace":"3baaa938-f92c-4a74-a228-fd49d5e2f8bc-1678419657806",
"data":{
"symbol_list":[
{
"code": "700.HK",
"depth_level": 5,
},
{
"code": "UNH.US",
"depth_level": 5,
},
{
"code": "600416.SH",
"depth_level": 5,
}
]
}
}
#如果希望长时间运行,除了需要发送订阅之外,还需要修改代码,定时发送心跳,避免连接断开,具体查看接口文档
sub_str = json.dumps(sub_param)
ws.send(sub_str)
print("depth quote are subscribed!")
def on_data(self, ws, string, type, continue_flag):
"""
4 argument.
The 1st argument is this class object.
The 2nd argument is utf-8 string which we get from the server.
The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.
The 4th argument is continue flag. If 0, the data continue
"""
def on_message(self, ws, message):
"""
Callback object which is called when received data.
2 arguments:
@ ws: the WebSocketApp object
@ message: utf-8 data received from the server
"""
# 对收到的message进行解析
result = eval(message)
print(result)
def on_error(self, ws, error):
"""
Callback object which is called when got an error.
2 arguments:
@ ws: the WebSocketApp object
@ error: exception object
"""
print(error)
def on_close(self, ws, close_status_code, close_msg):
"""
Callback object which is called when the connection is closed.
2 arguments:
@ ws: the WebSocketApp object
@ close_status_code
@ close_msg
"""
print('The connection is closed!')
def start(self):
self.ws = websocket.WebSocketApp(
self.url,
on_open=self.on_open,
on_message=self.on_message,
on_data=self.on_data,
on_error=self.on_error,
on_close=self.on_close,
)
self.ws.run_forever()
if __name__ == "__main__":
feed = Feed()
feed.start()
上面的代码中symbol_list代表你要订阅的产品列表,可以同时传入多个市场的多个产品, cmd_id=22002是订阅盘口数据,当cmd_id=22004时订阅的是成交报价,一旦订阅成功,实时股票行情数据就会源源不断的推送过来,并且是及时的。
Alltick实时行情数据接口
Alltick提供的数据接口涵盖各类资产,港股、美股以及加密货币的数据都有:
市场 | API |
港股 | 实时行情数据 |
实时十档盘口数据 | |
实时K线数据 | |
美股 | 实时行情数据 |
实时一档盘口数 | |
实时K线数据 | |
A股 | 沪深A股实时行情数据 |
沪深实时五档盘口数据 | |
沪深实时K线数据 | |
加密货币 | 实时行情数据 |
实时多档盘口数据 | |
实时K线数据 | |
外汇 | 实时行情数据 |
实时五档盘口数据 | |
实时K线数据 | |
贵金属 | 实时行情数据 |
实时五档盘口数据 | |
实时K线数据 |
【Github】https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
This message is used to verify that this feed (feedId:73354678354150400) belongs to me (userId:73035829013371904). Join me in enjoying the next generation information browser https://follow.is.
Very good article. I will be experiencing some of these issues ass well.. https://glassiuk.wordpress.com
An impressive share! I have just forwarded this onto a friend who has been conducting a little research on this.
And he actually bought me breakfast because I discovered it for him…
lol. So allow me to rewoird this…. Thanks forr the meal!!
But yeah, thanks for spending some time to discuss this issue hee on your internet site. https://glassi-info.blogspot.com/2025/08/deposits-and-withdrawals-methods-in.html
Thanks for one’s marvelous posting!I certainly enjoyed reading it, you could be a great author.I will be sure to bookmark your blog
annd will eventuall come basck later on. I wat to
encourage yoou too definitely continue your great work,
hve a nice holiday weekend! https://glassi-app.blogspot.com/2025/08/how-to-download-glassi-casino-app-for.html
I am extremely impressed with your writing skills as well as with the layout oon your weblog.
Is this a paid theme or did you cusomize it yourself? Either way keep up the nice quality writing, it iss raqre to see a great blog like this one nowadays. https://jobs.Jaylock-ph.com/companies/tonebet-casino/
I love our blog.. vrry nice cllors & theme. Did you design this website yourself or did you hire someone to do iit for you?
Plz reply as I’m looking to design my own blog and would like to find out where u got this from.
kudos https://Empowerhunt.com/employer/tonebet-casino/
Wonderful site. A lot of helpfl info here. I’m sending iit to
swveral buddies ans additionally sharing in delicious.
And obviously, thanks to your effort! http://shandurtravels.com/companies/tonebet-casino/
top australian online pokies, real money australian online pokies and understanding united statesn pokies, or
spin palace withdrawal canada
my web site :: gamesys gambling Sites
online casino games australia free, casino united kingdom chance and craps gambling uk, or canadian south oaks gambling screen portugal (Cole) apps
online wind river casino table games (Hermine) usa bonus, casino ratings canada
and understanding united statesn pokies, or top 10 poker sites
united states
top casino in canada for real money, money poker online usa and hausaos
dojo slot online real money no deposit bonus, or canadian google play casino apps (Margie) guide 2021 review
best no deposit casino usa, canadian blackjack online free and united
kingdom Casino Psychology club, or deposit 10 play with 50 slots uk
wettquoten
Feel free to surf to my web-site :: Wetten Buchmacher
wetten steuer österreich
my blog; wette deutschland england
wettquoten vergleich
Here is my webpage :: sportwetten lizenz schleswig holstein
sportwetten anbieter paypal
Visit my web page – basketball punkte wetten (Delbert)
sportwetten über unter strategie
My web-site; Deutschland ungarn Wettquote
sportwetten vergleich deutschland
Check out my webpage; alle buchmacher, Elizabet,
live wetten im stadion
Visit my web page wettbüRo lizenz
wettbüro hamburg
My web page … Sichere Kombiwetten
wettprognosen heute
My webpage – besten sportwetten apps
wer ist der beste wettanbieter
Take a look at my web blog: Buchmacher Kappe
sportwetten steuern schweiz
Stop by my web page: im wettbüro des teufels
portugal deutschland wettquoten
Feel free to visit my webpage … wettbüro emden (Kit)
em spiele Live Wetten Verbot
beste online sportwetten
Here is my blog post Esport Wetten Strategie;
Wp.Supover.Com,
beste online Sportwetten anbieter (https://www.mayahairhospital.com) kombiwetten
**mind vault**
mind vault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking
sportwetten Beste Anbieter
anbieter international
kombiwette spiel abgesagt
My web page; wir wetten bonus
wettbüro baden baden
My web blog … wetten Quoten vergleich
wettbüro berlin reinickendorf
Also visit my web site … Sportwetten Live Wetten
beste app für wetten
Look at my web-site … Tipster Wettbüro
sportwetten tipps von experten
Also visit my web site … wetten dass Wettkönig gewinn
sportwetten ohne oasis paysafecard
Visit my homepage … die besten wettanbieter (Garry)
legale wettanbieter deutschland
My page sportwetten strategien ihren wetterfolg
neue sportwetten anbieter
My page Wetten bonus angebote
Hi there to every , since I am truly eager of reading this weblog’s post to be updated regularly.
It contains nice information.
Take a look at my web-site bingo number generator with sayings (Randy)
sportwette bonus
Here is my website – beste Wett tipps Für heute
internet wetten
Feel free to visit my blog; Sportwetten tippen
wettbüro cottbus
Here is my blog: sportwetten live ergebnisse (Laurel)
wettanbieter beste quoten (Faustino)
wetten heute