AllTick API Docs
服务状态
  • 欢迎
  • 接入流程
    • 流程说明
    • 行情地址说明
      • HTTP 行情 API 地址说明
      • Websocket 行情 API 地址说明
    • Token 申请
    • 接口限制说明
      • HTTP 接口限制
      • Websocket 接口限制
      • 错误码说明
    • 通用标准头说明
      • HTTP 通用标准头
      • Websocket 通用标准头
    • 产品 Code 列表
      • A股
      • 港股
      • 美股
      • 加密货币(数字币)
      • 商品(贵金属)
      • 外汇
  • REST API
    • HTTP 请求示例
    • HTTP接口API
      • GET 单产品历史K线查询(最高、最低、开盘、收盘价)
      • POST 批量查询产品最新2根K线(最高、最低、开盘、收盘价)
      • GET 最新盘口(最新深度、Order Book)查询
      • GET 最新成交价(最新tick、当前价、最新价)批量查询
      • GET 股票产品基础信息批量查询
      • 涨跌幅、休市、假期、涨停跌停、新股上市和退市
  • Websocket API
    • Websocket 请求示例
    • Websocket接口API
      • 最新成交价(实时逐笔Tick数据、当前价、最新价)批量订阅
      • 最新盘口(实时逐笔深度、Order Book)订阅
      • 取消报价订阅
      • 心跳
      • K线推送(不支持)
  • FAQs
    • 基础使用
      • AllTick 提供哪些类型的金融数据?
      • 如何获取AllTick的API密钥?
      • AllTick的数据更新频率是多少?
      • 如何在我的应用程序中集成AllTick的数据?
      • AllTick支持哪些编程语言进行API调用?
      • 我可以使用AllTick的数据进行商业用途吗?
      • 如何联系AllTick的客户支持?
      • AllTick的API有请求限制吗?
      • 如何报告数据问题或API故障?
      • AllTick提供实时数据还是延迟数据?
    • 订阅与账户管理
      • 如何注册AllTick账户?
      • AllTick有免费试用期吗?
      • 如何取消AllTick的订阅服务?
      • 我的订阅包括哪些服务?
      • 如何升级我的AllTick订阅计划?
      • 如何更改我的账户信息?
      • 我忘记了我的登录密码,该怎么办?
      • 如何保护我的AllTick账户安全?
      • 是否可以多人共享一个AllTick账户?
      • 我的订阅可以退款吗?
    • 数据使用与技术问题
      • 如何使用AllTick的WebSocket服务?
      • AllTick的API支持哪些数据格式?
      • 如何处理AllTick数据的高频更新?
      • 我在使用API时遇到了技术问题,该怎么解决?
      • 如何确保从AllTick接收的数据的准确性?
      • AllTick是否提供历史数据查询?
      • 如何限制我的数据使用量以避免超出订阅限制?
      • AllTick的API是否支持批量请求?
      • 如何获取特定金融市场的实时通知和警报?
      • AllTick是否提供数据分析和可视化工具?
由 GitBook 提供支持
在本页

这有帮助吗?

  1. Websocket API

Websocket 请求示例

上一页涨跌幅、休市、假期、涨停跌停、新股上市和退市下一页Websocket接口API

最后更新于2个月前

这有帮助吗?

/ 中文

package main

import (
	"encoding/json"
	"github.com/google/uuid"
	"github.com/gorilla/websocket"
	"log"
	"time"
)

type Symbol struct {
	Code       string `json:"code"`
	DepthLevel int    `json:"depth_level"`
}

type Data struct {
	SymbolList []Symbol `json:"symbol_list"`
}

type Request struct {
	CmdID  int    `json:"cmd_id"`
	SeqID  int    `json:"seq_id"`
	Trace  string `json:"trace"`
	Data   Data   `json:"data"`
}

/*
	Special Note:
	GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
	Token Application: https://alltick.co
	Replace "testtoken" in the URL below with your own token
	API addresses for forex, cryptocurrencies, and precious metals:
	wss://quote.alltick.io/quote-b-ws-api
	Stock API address:
	wss://quote.alltick.io/quote-stock-b-ws-api
*/
const (
	url = "wss://quote.alltick.io/quote-b-ws-api?token=testtoken"
)

func websocket_example() {

	log.Println("Connecting to server at", url)

	c, _, err := websocket.DefaultDialer.Dial(url, nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	// Send heartbeat every 10 seconds
	go func() {
		for range time.NewTicker(10 * time.Second).C {
			req := Request{
				CmdID: 22000,
				SeqID: 123,
				Trace: "3380a7a-3e1f-c3a5-5ee3-9e5be0ec8c241692805462",
				Data:  Data{},
			}
			messageBytes, err := json.Marshal(req)
			if err != nil {
				log.Println("json.Marshal error:", err)
				return
			}
			log.Println("req data:", string(messageBytes))

			err = c.WriteMessage(websocket.TextMessage, messageBytes)
			if err != nil {
				log.Println("write:", err)
			}
		}
	}()

	req := Request{
		CmdID: 22002,
		SeqID: 123,
		Trace: uuid.New().String(),
		Data: Data{SymbolList: []Symbol{
			{"GOLD", 5},
			{"AAPL.US", 5},
			{"700.HK", 5},
			{"USDJPY", 5},
		}},
	}
	messageBytes, err := json.Marshal(req)
	if err != nil {
		log.Println("json.Marshal error:", err)
		return
	}
	log.Println("req data:", string(messageBytes))

	err = c.WriteMessage(websocket.TextMessage, messageBytes)
	if err != nil {
		log.Println("write:", err)
	}

	req.CmdID = 22004
	messageBytes, err = json.Marshal(req)
	if err != nil {
		log.Println("json.Marshal error:", err)
		return
	}
	log.Println("req data:", string(messageBytes))

	err = c.WriteMessage(websocket.TextMessage, messageBytes)
	if err != nil {
		log.Println("write:", err)
	}

	rece_count := 0
	for {
		_, message, err := c.ReadMessage()

		if err != nil {
			log.Println("read:", err)
			break
		} else {
			log.Println("Received message:", string(message))
		}

		rece_count++
		if rece_count%10000 == 0 {
			log.Println("count:", rece_count, " Received message:", string(message))
		}
	}

}
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.websocket.*;

// Special Note:
// GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
// Token Application: https://alltick.co
// Replace "testtoken" in the URL below with your own token
// API addresses for forex, cryptocurrencies, and precious metals:
// wss://quote.alltick.io/quote-b-ws-api
// Stock API address:
// wss://quote.alltick.io/quote-stock-b-ws-api

@ClientEndpoint
public class WebSocketJavaExample {

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected to server");
        this.session = session;
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("Received message: " + message);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("Disconnected from server");
    }

    @OnError
    public void onError(Throwable throwable) {
        System.err.println("Error: " + throwable.getMessage());
    }

    public void sendMessage(String message) throws Exception {
        this.session.getBasicRemote().sendText(message);
    }

    public static void main(String[] args) throws Exception, URISyntaxException, DeploymentException, IOException, IllegalArgumentException, SecurityException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // Special Note:
        // GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
        // Token Application: https://alltick.co
        // Replace "testtoken" in the URL below with your own token
        // API addresses for forex, cryptocurrencies, and precious metals:
        // wss://quote.alltick.io/quote-b-ws-api
        // Stock API address:
        // wss://quote.alltick.io/quote-stock-b-ws-api

        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        URI uri = new URI("wss://quote.alltick.io/quote-stock-b-ws-api?token=testtoken"); // Replace with your websocket endpoint URL

        WebSocketJavaExample client = new WebSocketJavaExample();

        container.connectToServer(client, uri);

        // Send messages to the server using the sendMessage() method
        // If you want to run for a long time, in addition to sending subscriptions, you also need to modify the code to send heartbeats regularly to prevent disconnection. Refer to the interface documentation for details
        client.sendMessage("{\"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}]}}");

        // Wait for the client to be disconnected from the server (or until the user presses Enter)
        System.in.read(); // Wait for user input before closing the program
    }
}
<?php
require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Protocols\Ws;
use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;

// Special Note:
// GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
// Token Application: https://alltick.co
// Replace "testtoken" in the URL below with your own token
// API addresses for forex, cryptocurrencies, and precious metals:
// wss://quote.alltick.io/quote-b-ws-api
// Stock API address:
// wss://quote.alltick.io/quote-stock-b-ws-api

$worker = new Worker();
// When the process starts
$worker->onWorkerStart = function()
{
    // Connect to remote websocket server using the websocket protocol
    $ws_connection = new AsyncTcpConnection("ws://quote.alltick.io/quote-stock-b-ws-api?token=testtoken");
    // Send a websocket heartbeat opcode (0x9) to the server every 55 seconds
    $ws_connection->websocketPingInterval = 10;
    $ws_connection->websocketType = Ws::BINARY_TYPE_BLOB; // BINARY_TYPE_BLOB for text, BINARY_TYPE_ARRAYBUFFER for binary
    // After the TCP handshake is completed
    $ws_connection->onConnect = function($connection){
        echo "TCP connected\n";
        // Send subscription request
        $connection->send('{"cmd_id":22002,"seq_id":123,"trace":"3baaa938-f92c-4a74-a228-fd49d5e2f8bc-1678419657806","data":{"symbol_list":[{"code":"700.HK","depth_level":5},{"code":"AAPL.US","depth_level":5}]}}');
    };
    // After the websocket handshake is completed
    $ws_connection->onWebSocketConnect = function(AsyncTcpConnection $con, $response) {
        echo $response;
    };
    // When a message is received from the remote websocket server
    $ws_connection->onMessage = function($connection, $data){
        echo "Received: $data\n";
    };
    // When an error occurs, usually due to failure to connect to the remote websocket server
    $ws_connection->onError = function($connection, $code, $msg){
        echo "Error: $msg\n";
    };
    // When the connection to the remote websocket server is closed
    $ws_connection->onClose = function($connection){
        echo "Connection closed and trying to reconnect\n";
        // If the connection is closed, reconnect after 1 second
        $connection->reConnect(1);
    };
    // After setting up all the callbacks above, initiate the connection
    $ws_connection->connect();
};
Worker::runAll();
?>
import json
import websocket    # pip install websocket-client

'''
# Special Note:
# GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
# Token Application: https://alltick.co
# Replace "testtoken" in the URL below with your own token
# API addresses for forex, cryptocurrencies, and precious metals:
# wss://quote.alltick.io/quote-b-ws-api
# Stock API address:
# wss://quote.alltick.io/quote-stock-b-ws-api
'''

class Feed(object):

    def __init__(self):
        self.url = 'wss://quote.alltick.io/quote-stock-b-ws-api?token=testtoken'  # Enter your websocket URL here
        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!')

        # Start subscribing (an example)
        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,
                    }
                ]
            }
        }

        # If you want to run for a long time, you need to modify the code to send heartbeats periodically to avoid disconnection, please refer to the API documentation for details
        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 arguments.
        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
        """
        # Parse the received 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()

AllTick网站

官方网站:

English
Websocket 行情 API 地址说明
https://alltick.co/