QOS 行情 API - 示例代码 - 提供实时行情API、K线数据API - 外汇API、美股API、港股API、加密货币数据API - 金融高频数据接口 - 免费试用

订阅 QOS API,您即可 实时获取最新的股票、外汇、期货、加密货币数据,助力交易决策更快一步。我们的 实时行情数据 采用 WebSocket 高速推送,超低延迟,确保市场信息的精准与高效。QOS API 专为 交易所、开发者、量化团队、金融科技公司 及 专业机构 量身打造,提供 全面的金融市场 Tick 数据解决方案,覆盖 外汇、港股、美股、商品期货、加密货币 等多个领域。

选择您喜欢的编程语言查看示例代码,如果需要更多请点击右下角联系客服。

Python
Java
PHP
Go
HTTP-获取实时快照
HTTP-获取K线
WS-订阅实时行情
import requests
import json

# 官网:https://qos.hk
# 免费api key注册申请:https://qos.hk
url = "https://api.qos.hk/snapshot?key=your-api-key"

payload = json.dumps({
  "codes": [
    "US:AAPL",
    "HK:700,9988",
    "SH:600519,600518",
    "SZ:000001,002594",
    "CF:BTCUSDT,ETHUSDT"
  ]
})
headers = {
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
import requests
import json

# 官网:https://qos.hk
# 免费api key注册申请:https://qos.hk
url = "https://api.qos.hk/kline?key=your-api-key"

payload = json.dumps({
  "kline_reqs": [
    {
      "c": "US:AAPL,TSLA",
      "co": 1,
      "a": 0,
      "kt": 1001
    },
    {
      "c": "SH:600519",
      "co": 1,
      "a": 0,
      "kt": 1001
    },
    {
      "c": "SZ:000001",
      "co": 1,
      "a": 0,
      "kt": 1001
    },
    {
      "c": "HK:700",
      "co": 1,
      "a": 0,
      "kt": 1001
    },
    {
      "c": "CF:BTCUSDT",
      "co": 2,
      "a": 0,
      "kt": 1001
    }
  ]
})
headers = {
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)			
			
import websocket
import time
import threading
import json

# WebSocket URL(根据实际情况替换)
url = "wss://api.qos.hk/ws"
# API Key(替换为你的API Key)
# 官网:https://qos.hk
# 免费api key注册申请:https://qos.hk
api_key = "your-api-key"

def on_message(ws, message):
    print("接收到消息:", message)

def on_error(ws, error):
    print("错误:", error)

def on_close(ws, close_status_code, close_msg):
    print("连接关闭")

def on_open(ws):
    # 发送初始订阅行情快照消息
    subscribe_message_1 = json.dumps({
        "type": "S",
        "codes": [
            "US:AAPL",
            "HK:700,9988",
            "CF:BTCUSDT",
            "SZ:000001",
            "SH:600519"
        ],
        "reqid": 1
    })
    ws.send(subscribe_message_1)

    # 2秒后发送第二个订阅命令
    def send_second_subscription():
        time.sleep(1)
        subscribe_message_2 = json.dumps({
            "type": "T",
            "codes": [
                "US:AAPL",
                "HK:700,9988",
                "CF:BTCUSDT",
                "SZ:000001",
                "SH:600519"
            ],
            "reqid": 1
        })
        ws.send(subscribe_message_2)
        
        time.sleep(1)
        
        subscribe_message_2 = json.dumps({
            "type": "D",
            "codes": [
                "US:AAPL",
                "HK:700,9988",
                "CF:BTCUSDT",
                "SZ:000001",
                "SH:600519"
            ],
            "reqid": 1
        })
        ws.send(subscribe_message_2)
        
        time.sleep(1)
        
        subscribe_message_2 = json.dumps({
            "type": "K",
            "codes": [
                "CF:BTCUSDT",
            ],
            "kt":1001,
            "reqid": 1
        })
        ws.send(subscribe_message_2)

    threading.Thread(target=send_second_subscription).start()
    
    # 发送心跳包(每20秒)
    def send_heartbeat():
        while True:
            time.sleep(20)
            heartbeat_message = json.dumps({"type":"H"})
            ws.send(heartbeat_message)
            print("发送心跳包")

    threading.Thread(target=send_heartbeat, daemon=True).start()

# 创建WebSocket连接
ws = websocket.WebSocketApp(url + "?key=" + api_key,
                            on_message=on_message,
                            on_error=on_error,
                            on_close=on_close,
                            on_open=on_open)

# 运行WebSocket连接
ws.run_forever()
			
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpSnapshot {
    public static void main(String[] args) {
        try {
            HttpClient client = HttpClient.newHttpClient();
            // official website: https://qos.hk
            // Free API key registration application: https://qos.hk
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(new URI("https://api.qos.hk/snapshot?key=your-api-key"))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString("""
                    {
                        "codes": [
                            "US:AAPL",
                            "HK:700,9988",
                            "SH:600519,600518",
                            "SZ:000001,002594",
                            "CF:BTCUSDT,ETHUSDT"
                        ]
                    }
                    """))
                    .build();

            HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());

            System.out.println(response.body());
        } catch (Exception e) {
            System.out.println("error:" + e.getMessage());
            e.printStackTrace();
        }
    }
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpKline {
    public static void main(String[] args) {
        try {
            HttpClient client = HttpClient.newHttpClient();
            // official website:https://qos.hk
            // Free API key registration application.https://qos.hk
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(new URI("https://api.qos.hk/kline?key=your-api-key"))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString("""
                    {
                        "kline_reqs":[
                            {"c":"US:AAPL,TSLA","co":1,"a":0,"kt":1001},
                            {"c":"SH:600519","co":1,"a":0,"kt":1001},
                            {"c":"SZ:000001","co":1,"a":0,"kt":1001},
                            {"c":"HK:700","co":1,"a":0,"kt":1001},
                            {"c":"CF:BTCUSDT","co":2,"a":0,"kt":1001}
                        ]
                    }
                    """))
                    .build();

            HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());

            System.out.println(response.body());
        } catch (Exception e) {
            System.out.println("error:" + e.getMessage());
            e.printStackTrace();
        }
    }
}
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;

public class WSSClient {
    public static void main(String[] args) {
        try {
            // WebSocket URL
            //官网:https://qos.hk
            //免费api key注册申请:https://qos.hk
            String url = "wss://api.qos.hk/ws?key=your-api-key";

            WebSocketClient client = new WebSocketClient(new URI(url)) {
                @Override
                public void onOpen(ServerHandshake handshake) {
                    System.out.println("WebSocket 连接成功!");

                    send("""
                    {"type":"S","codes":["US:AAPL","HK:700,9988","CF:BTCUSDT","SZ:000001","SH:600519"],"reqid":1}
                    """);

                    new Thread(() -> {
                        try {
                            Thread.sleep(1000);
                            send("""
                            {"type":"T","codes":["US:AAPL","HK:700,9988","CF:BTCUSDT","SZ:000001","SH:600519"],"reqid":1}
                            """);
                            Thread.sleep(1000);
                            send("""
                            {"type":"D","codes":["US:AAPL","HK:700,9988","CF:BTCUSDT","SZ:000001","SH:600519"],"reqid":1}
                            """);
                            Thread.sleep(1000);
                            send("""
                            {"type":"K","codes":["CF:BTCUSDT"],"kt":1001,"reqid":1}
                            """);

                        } catch (InterruptedException e) {
                            System.err.println("WebSocket send error: " + e.getMessage());
                        }
                    }).start();

                    // 启动心跳,每 20 秒发送一次
                    Timer timer = new Timer(true);
                    timer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            send("""
                            {"type":"H"}
                            """);
                            System.out.println("发送心跳包");
                        }
                    }, 20000, 20000);
                }

                @Override
                public void onMessage(String message) {
                    System.out.println("收到消息: " + message);
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    System.out.println("WebSocket 连接关闭: " + reason);
                }

                @Override
                public void onError(Exception ex) {
                    System.out.println("WebSocket 错误: " + ex.getMessage());
                }
            };

            client.connect();

        }catch (URISyntaxException e) {
            System.err.println("WebSocket URL 格式错误: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("WebSocket 连接失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
<?php

$curl = curl_init();
//官网:https://qos.hk
//免费api key注册申请:https://qos.hk
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.qos.hk/snapshot?key=your-api-key',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
    "codes": [
        "US:TQQQ",
        "HK:700,9988",
        "SH:600519,600518",
        "SZ:000001,002594",
        "CF:BTCUSDT,ETHUSDT"
    ]
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
?>
<?php

$curl = curl_init();
//官网:https://qos.hk
//免费api key注册申请:https://qos.hk
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.qos.hk/kline?key=your-api-key',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
    "kline_reqs":[
        {"c":"US:AAPL,TSLA","co":1,"a":0,"kt":1001},
        {"c":"SH:600519","co":1,"a":0,"kt":1001},
        {"c":"SZ:000001","co":1,"a":0,"kt":1001},
        {"c":"HK:700","co":1,"a":0,"kt":1001},
        {"c":"CF:BTCUSDT","co":2,"a":0,"kt":1001}
    ]
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
?>
<?php
require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Timer;
//官网:https://qos.hk
//免费api key注册申请:https://qos.hk
$worker = new Worker('http://0.0.0.0:8081');
$worker->onWorkerStart = function() {
    $ws_connection = new AsyncTcpConnection("ws://qos.hk:443/ws?key=Your-API-Key");
    
    $ws_connection->transport = 'ssl';
    
    $ws_connection->onConnect = function($connection) {
        echo "[" . date('Y-m-d H:i:s') . "]Connected to WSS server\n";
        // 启动定时器,每20秒发送一次心跳
        $timer_id = Timer::add(20, function() use ($connection) {
            $heartbeat = json_encode(['type' => 'H']);
            $connection->send($heartbeat);
            echo "[" . date('Y-m-d H:i:s') . "] Sent heartbeat: {$heartbeat}\n";
        });
        
        // 将定时器ID保存到连接对象中,以便后续清理
        $connection->timer_id = $timer_id;
        
	// 发送第1个订阅
	$connection->send('{"type": "K","codes": ["CF:ETHUSDT,BTCUSDT"],"kt":1001}');
        
        // 1秒后发送第2个订阅
        Timer::add(1, function() use ($connection) {
            $connection->send('{"type": "T","codes": ["US:AAPL,TSLA"]}');
            echo "[" . date('Y-m-d H:i:s') . "] Sent sub msg\n";
        }, null, false);
        
        // 2秒后发送第3个订阅
        Timer::add(2, function() use ($connection) {
            $connection->send('{"type": "S","codes": ["HK:700","SZ:000001","SH:600519"]}');
            echo "[" . date('Y-m-d H:i:s') . "] Sent sub msg\n";
        }, null, false);
        
        // 3秒后发送第4个订阅
        Timer::add(3, function() use ($connection) {
            $connection->send('{"type": "D","codes": ["HK:700","SZ:000001","SH:600519"]}');
            echo "[" . date('Y-m-d H:i:s') . "] Sent sub msg\n";
        }, null, false);

    };
    
    $ws_connection->onMessage = function($connection, $data) {
        echo "Received: $data\n";
    };
    
    $ws_connection->onClose = function($connection) {
        echo "Connection closed, reconnecting...\n";
        $connection->reConnect(5);
    };
    
    $ws_connection->onError = function($connection, $code, $msg) {
        echo "Error: $msg\n";
    };
    
    $ws_connection->connect();
};

Worker::runAll();
?>
package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"
)

func main() {
   	//官网:https://qos.hk
  	//免费api key注册申请:https://qos.hk
	url := "https://api.qos.hk/snapshot?key=your-api-key"
	method := "POST"

	payload := strings.NewReader(`{
		"codes": [
			"US:AAPL,TSLA",
			"HK:700,9988",
			"SH:600519,600518",
			"SZ:000001,002594",
			"CF:BTCUSDT"
		]
	}`)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(body))
}
package main

import (
	"fmt"
	"io"
	"net/http"
	"strings"
)

func main() {
	//官网:https://qos.hk
	//免费api key注册申请:https://qos.hk
	url := "https://api.qos.hk/kline?key=your-api-key"
	method := "POST"

	payload := strings.NewReader(`{
		"kline_reqs":[
			{"c":"US:AAPL,TSLA","co":1,"a":0,"kt":1001},
			{"c":"SH:600519","co":1,"a":0,"kt":1001},
			{"c":"SZ:000001","co":1,"a":0,"kt":1001},
			{"c":"HK:700","co":1,"a":0,"kt":1001},
			{"c":"CF:BTCUSDT","co":2,"a":0,"kt":1001}
		]
	}`)

	client := &http.Client{}
	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		fmt.Println(err)
		return
	}
	req.Header.Add("Content-Type", "application/json")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(body))
}
package main

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"time"
)

func main() {
	url := "wss://api.qos.hk/ws"
	//官网:https://qos.hk
        //免费api key注册申请:https://qos.hk
	apiKey := "your-api-key" //替换你的api key

	// 建立WebSocket连接
	conn, _, err := websocket.DefaultDialer.Dial(url+"?key="+apiKey, nil)
	if err != nil {
		log.Fatal("连接WebSocket失败:", err)
	}
	defer conn.Close()

	// 发送订阅行情快照消息
	subscribeMessage := `{"type":"S","codes":["US:AAPL","HK:700,9988","CF:BTCUSDT","SZ:000001","SH:600519"],"reqid":1}`
	err = conn.WriteMessage(websocket.TextMessage, []byte(subscribeMessage))
	if err != nil {
		log.Fatal("发送订阅消息失败:", err)
	}

	go func() {
		time.Sleep(1 * time.Second)
    // 发送订阅最新成交
		subscribeMessage = `{"type":"T","codes":["US:AAPL","HK:700,9988","CF:BTCUSDT","SZ:000001","SH:600519"],"reqid":1}`
		err = conn.WriteMessage(websocket.TextMessage, []byte(subscribeMessage))
		if err != nil {
			log.Fatal("发送订阅消息失败:", err)
		}

		time.Sleep(2 * time.Second)
    // 发送订阅深度盘口
		subscribeMessage = `{"type":"D","codes":["US:AAPL","HK:700,9988","CF:BTCUSDT","SZ:000001","SH:600519"],"reqid":1}`
		err = conn.WriteMessage(websocket.TextMessage, []byte(subscribeMessage))
		if err != nil {
			log.Fatal("发送订阅消息失败:", err)
		}
		
		time.Sleep(3 * time.Second)
    // 发送订阅K线
		subscribeMessage = `{"type":"K","codes":["CF:BTCUSDT"],"kt":1001,reqid":1}`
		err = conn.WriteMessage(websocket.TextMessage, []byte(subscribeMessage))
		if err != nil {
			log.Fatal("发送订阅消息失败:", err)
		}
	}()

	// 发送心跳包
	go func() {
		for {
			heartbeatMessage := `{"type":"H"}`
			err := conn.WriteMessage(websocket.TextMessage, []byte(heartbeatMessage))
			if err != nil {
				log.Fatal("发送心跳包失败:", err)
			}
			time.Sleep(20 * time.Second) // 每20秒发送一次心跳包
		}
	}()

	// 读取并打印消息
	for {
		_, msg, err := conn.ReadMessage()
		if err != nil {
			log.Fatal("读取消息失败:", err)
		}
		fmt.Println("接收到消息:", string(msg))
	}

	// 保持连接
	time.Sleep(120 * time.Second) // 保持连接120秒
}

联系客服

联系客服

Telegram: @stock_quote_api

联系客服