一、什么是数据接口,数据AP接口
API数据接口是一种让不同的软件应用程序能够互相交流和共享数据的方式。它就像一本规定书,告诉开发者们如何进行数据传输和交互。通过使用API数据接口,API数据接口就像是一个桥梁,连接着不同的应用程序。它定义了一套规则和标准,确保这些应用程序可以相互理解和交流。
随着时间的推移,数据API接口已成为重要的生产要素之一,实时数据也很重要,这其中还包括股票、外汇数据,以及它们的k线数据、tick数据等,数据API接口并融入经济价值的创造过程中。
二、数据AP接口分类
1、RESTful API:REST(Representational State Transfer,表现层状态转移)是一种基于HTTP协议的API设计风格。
2、SOAP API:SOAP(Simple Object Access Protocol,简单对象访问协议)是一种基于XML的API设计风格。
3、GraphQL API:GraphQL是一种用于API的查询语言和服务端运行时。
三、实时股票行情数据接口API调用方法
以AllTick的API为例,这家的Tick数据经过封装,可随时方便调用。
官网:实时行情Tick数据 - 外汇、美股、港股、加密货币CFD数据API - 金融高频数据接口 - AllTick
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()