PHP查询实时股票行情

记录一个实时行情接口,通过PHP查询实时股票行情

php 复制代码
<?php

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

$params = '{"trace":"1111111111111111111111111","data":{"code":"AAPL.US","kline_type":1,"kline_timestamp_end":0,"query_kline_num":10,"adjust_type":0}}';

$url = 'https://quote.tradeswitcher.com/quote-stock-b-api/kline?token=testtoken';
$method = 'GET';

$opts = array(CURLOPT_TIMEOUT => 10, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false);

/* Set specific parameters based on request type */
switch (strtoupper($method)) {
    case 'GET':
        $opts[CURLOPT_URL] = $url.'&query='.rawurlencode($params);
        $opts[CURLOPT_CUSTOMREQUEST] = 'GET';
        break;
    default:
}

/* Initialize and execute curl request */
$ch = curl_init();
curl_setopt_array($ch, $opts);
$data = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    $data = null;
}

echo $data;
?>

这段代码的逻辑可以分为以下几个主要步骤:

  1. 参数设置:首先,定义了一个 JSON 字符串,包含了要查询的股票(如苹果公司的代码 "AAPL.US")和一些其他参数(如 K 线类型、时间戳等)。

  2. 构建请求 URL:指定了请求的 URL,包含 API 端点和一个令牌(token)。该 URL 用于向远程服务发送请求以获取股票的 K 线数据。

  3. 设置 cURL 选项:配置了 cURL 请求的选项,包括:

    • 超时时间设为 10 秒。
    • 返回结果为字符串而不是直接输出。
    • 禁用 SSL 证书验证(可能是为了简化测试环境的设置)。
  4. 请求方法处理:根据指定的请求方法(在此为 GET),将构造好的参数添加到 URL 中。

  5. 执行 cURL 请求

    • 初始化 cURL 会话。
    • 设置请求选项并执行请求。
    • 捕获任何可能的错误。
  6. 输出结果:关闭 cURL 会话后,检查是否有错误。如果没有错误,则输出从 API 返回的数据;如果有错误,则将数据设置为 null。

下面通过Websocket订阅实时股票价格

php 复制代码
<?php
require_once __DIR__ . '/vendor/autoload.php';

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

// 接口基本信息:
// GitHub: https://github.com/alltick/realtime-forex-crypto-stock-tick-finance-websocket-api
// 官网:https://alltick.co
// 备用网址:https://alltick.io


$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.tradeswitcher.com/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();
?>

这段代码的逻辑可以概括为以下几个关键步骤:

  1. 引入库:使用 Workerman 库来处理 WebSocket 连接和相关功能。

  2. 创建 Worker:实例化一个 Worker 对象,负责管理和启动进程。

  3. 连接设置

    • 在 Worker 启动时,建立与远程 WebSocket 服务器的连接。
    • 配置心跳机制,以定期发送心跳消息保持连接活跃。
  4. 事件处理

    • 连接成功:一旦连接建立,发送订阅请求,告知服务器希望接收哪些金融数据(如特定股票的市场信息)。
    • 接收消息:处理服务器返回的数据,并输出到控制台。
    • 错误处理:在连接出现错误时,输出错误信息。
    • 连接关闭:当连接关闭时,尝试在短暂延迟后重新连接。
  5. 启动 Worker,开始处理所有的事件和消息。

相关推荐
JaguarJack15 小时前
FrankenPHP 原生支持 Windows 了
后端·php·服务端
BingoGo15 小时前
FrankenPHP 原生支持 Windows 了
后端·php
JaguarJack2 天前
PHP 的异步编程 该怎么选择
后端·php·服务端
BingoGo2 天前
PHP 的异步编程 该怎么选择
后端·php
JaguarJack2 天前
为什么 PHP 闭包要加 static?
后端·php·服务端
ServBay3 天前
垃圾堆里编码?真的不要怪 PHP 不行
后端·php
用户962377954483 天前
CTF 伪协议
php
BingoGo6 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack6 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo7 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php