Stories

Detail Return Return

印度尼西亞數據源 PHP 對接文檔 - Stories Detail

一、環境要求與配置

1. 系統要求

  • PHP ≥ 7.4
  • 擴展:cURL、JSON、OpenSSL
  • Composer(推薦)

2. 安裝依賴

composer require guzzlehttp/guzzle

3. 基礎配置類

<?php
// config/StockTVConfig.php
class StockTVConfig {
    const BASE_URL = 'https://api.stocktv.top';
    const WS_URL = 'wss://ws-api.stocktv.top/connect';
    
    private $apiKey;
    private $countryId = 42; // 印尼國家ID
    
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
    }
    
    public function getApiKey() {
        return $this->apiKey;
    }
    
    public function getBaseUrl() {
        return self::BASE_URL;
    }
    
    public function getWsUrl() {
        return self::WS_URL;
    }
    
    public function getCountryId() {
        return $this->countryId;
    }
}
?>

二、HTTP API 客户端實現

1. 基礎客户端類

<?php
// src/StockTVClient.php
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class StockTVClient {
    private $client;
    private $config;
    
    public function __construct(StockTVConfig $config) {
        $this->config = $config;
        $this->client = new Client([
            'base_uri' => $config->getBaseUrl(),
            'timeout'  => 30,
            'verify' => true,
        ]);
    }
    
    private function makeRequest($method, $endpoint, $params = []) {
        try {
            // 添加API密鑰
            $params['key'] = $this->config->getApiKey();
            
            $response = $this->client->request($method, $endpoint, [
                'query' => $params
            ]);
            
            return json_decode($response->getBody(), true);
            
        } catch (RequestException $e) {
            return $this->handleError($e);
        }
    }
    
    private function handleError($exception) {
        $statusCode = $exception->getResponse() ? $exception->getResponse()->getStatusCode() : 500;
        
        $errorMap = [
            401 => 'API密鑰無效',
            429 => '請求頻率超限',
            500 => '服務器內部錯誤',
        ];
        
        return [
            'code' => $statusCode,
            'message' => $errorMap[$statusCode] ?? '未知錯誤',
            'error' => $exception->getMessage()
        ];
    }
}
?>

2. 股票數據接口實現

<?php
// src/StockDataService.php
class StockDataService extends StockTVClient {
    
    /**
     * 獲取印尼股票列表
     */
    public function getStockList($pageSize = 10, $page = 1) {
        $params = [
            'countryId' => $this->config->getCountryId(),
            'pageSize' => $pageSize,
            'page' => $page
        ];
        
        return $this->makeRequest('GET', '/stock/stocks', $params);
    }
    
    /**
     * 查詢特定股票
     */
    public function queryStock($symbol = null, $pid = null) {
        $params = [];
        if ($symbol) $params['symbol'] = $symbol;
        if ($pid) $params['id'] = $pid;
        
        return $this->makeRequest('GET', '/stock/queryStocks', $params);
    }
    
    /**
     * 獲取股票K線數據
     */
    public function getKlineData($pid, $interval = 'PT15M') {
        $params = [
            'pid' => $pid,
            'interval' => $interval
        ];
        
        return $this->makeRequest('GET', '/stock/kline', $params);
    }
    
    /**
     * 獲取印尼指數數據
     */
    public function getIndices() {
        $params = [
            'countryId' => $this->config->getCountryId()
        ];
        
        return $this->makeRequest('GET', '/stock/indices', $params);
    }
}
?>

3. 公司信息服務

<?php
// src/CompanyService.php
class CompanyService extends StockTVClient {
    
    /**
     * 獲取公司列表
     */
    public function getCompanyList($pageSize = 10, $page = 1) {
        $params = [
            'countryId' => $this->config->getCountryId(),
            'pageSize' => $pageSize,
            'page' => $page
        ];
        
        return $this->makeRequest('GET', '/stock/companies', $params);
    }
    
    /**
     * 通過URL獲取公司詳情
     */
    public function getCompanyByUrl($url) {
        $params = ['url' => $url];
        return $this->makeRequest('GET', '/stock/companyUrl', $params);
    }
}
?>

三、WebSocket 實時數據對接

1. WebSocket 客户端

<?php
// src/WebSocketClient.php
use Ratchet\Client\WebSocket;
use Ratchet\RFC6455\Messaging\MessageInterface;

class StockTVWebSocketClient {
    private $config;
    private $connection;
    
    public function __construct(StockTVConfig $config) {
        $this->config = $config;
    }
    
    public function connect() {
        $wsUrl = $this->config->getWsUrl() . '?key=' . $this->config->getApiKey();
        
        \Ratchet\Client\connect($wsUrl)->then(
            function(WebSocket $conn) {
                $this->connection = $conn;
                
                // 連接成功回調
                $conn->on('message', function(MessageInterface $msg) {
                    $this->handleMessage($msg);
                });
                
                $conn->on('close', function($code = null, $reason = null) {
                    $this->handleClose($code, $reason);
                });
                
                // 發送心跳包
                $this->startHeartbeat();
                
            },
            function(\Exception $e) {
                echo "連接失敗: {$e->getMessage()}\n";
            }
        );
    }
    
    private function handleMessage(MessageInterface $msg) {
        $data = json_decode($msg->__toString(), true);
        
        if (isset($data['pid'])) {
            // 處理實時行情數據
            $this->processMarketData($data);
        }
    }
    
    private function processMarketData($data) {
        echo "收到行情數據: PID={$data['pid']}, 價格={$data['last_numeric']}\n";
        
        // 這裏可以添加業務邏輯處理
        // 例如:存入數據庫、觸發交易策略等
    }
    
    private function startHeartbeat() {
        // 每30秒發送心跳
        swoole_timer_tick(30000, function() {
            if ($this->connection) {
                $this->connection->send(json_encode(['action' => 'ping']));
            }
        });
    }
    
    public function subscribe($pids) {
        $message = [
            'action' => 'subscribe',
            'pids' => $pids
        ];
        
        if ($this->connection) {
            $this->connection->send(json_encode($message));
        }
    }
}
?>

四、使用示例

1. 初始化配置

<?php
// index.php
require_once 'config/StockTVConfig.php';
require_once 'src/StockTVClient.php';
require_once 'src/StockDataService.php';
require_once 'src/CompanyService.php';

// 初始化配置
$config = new StockTVConfig('您的API_KEY');
$stockService = new StockDataService($config);
$companyService = new CompanyService($config);

// 獲取股票列表
$stocks = $stockService->getStockList(20, 1);
if ($stocks['code'] == 200) {
    foreach ($stocks['data']['records'] as $stock) {
        echo "股票: {$stock['symbol']} - {$stock['name']} \n";
        echo "最新價: {$stock['last']} \n";
        echo "漲跌幅: {$stock['chgPct']}% \n\n";
    }
}

// 獲取K線數據
$klineData = $stockService->getKlineData(7310, 'PT1H');
if ($klineData['code'] == 200) {
    foreach ($klineData['data'] as $kline) {
        echo "時間: " . date('Y-m-d H:i:s', $kline['time']/1000) . "\n";
        echo "開盤: {$kline['open']}, 收盤: {$kline['close']}\n";
    }
}
?>

2. 實時數據訂閲示例

<?php
// realtime.php
require_once 'src/WebSocketClient.php';

$config = new StockTVConfig('您的API_KEY');
$wsClient = new StockTVWebSocketClient($config);

// 連接WebSocket
$wsClient->connect();

// 訂閲特定股票(需要先獲取PID)
$pidsToSubscribe = [7310, 41602, 50123];
$wsClient->subscribe($pidsToSubscribe);

// 保持腳本運行
while (true) {
    sleep(1);
}
?>

五、錯誤處理與日誌

1. 日誌記錄類

<?php
// src/Logger.php
class Logger {
    const LOG_FILE = 'logs/stocktv.log';
    
    public static function info($message, $context = []) {
        self::writeLog('INFO', $message, $context);
    }
    
    public static function error($message, $context = []) {
        self::writeLog('ERROR', $message, $context);
    }
    
    private static function writeLog($level, $message, $context) {
        $logEntry = sprintf(
            "[%s] %s: %s %s\n",
            date('Y-m-d H:i:s'),
            $level,
            $message,
            !empty($context) ? json_encode($context) : ''
        );
        
        // 確保日誌目錄存在
        if (!is_dir('logs')) {
            mkdir('logs', 0755, true);
        }
        
        file_put_contents(self::LOG_FILE, $logEntry, FILE_APPEND | LOCK_EX);
    }
}
?>

2. 增強的錯誤處理

// 在StockTVClient中添加日誌
private function makeRequest($method, $endpoint, $params = []) {
    try {
        Logger::info("API請求開始", [
            'endpoint' => $endpoint,
            'params' => $params
        ]);
        
        $response = $this->client->request($method, $endpoint, [
            'query' => $params
        ]);
        
        $result = json_decode($response->getBody(), true);
        
        Logger::info("API請求成功", [
            'endpoint' => $endpoint,
            'code' => $result['code'] ?? null
        ]);
        
        return $result;
        
    } catch (RequestException $e) {
        $errorData = $this->handleError($e);
        Logger::error("API請求失敗", $errorData);
        return $errorData;
    }
}

六、性能優化建議

1. 緩存機制

<?php
// src/CacheService.php
class CacheService {
    private $redis;
    
    public function __construct() {
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
    }
    
    public function getWithCache($key, $callback, $ttl = 300) {
        $cached = $this->redis->get($key);
        if ($cached !== false) {
            return json_decode($cached, true);
        }
        
        $result = $callback();
        if ($result && $result['code'] == 200) {
            $this->redis->setex($key, $ttl, json_encode($result));
        }
        
        return $result;
    }
}

// 使用示例
$cacheService = new CacheService();
$stocks = $cacheService->getWithCache(
    'indonesia_stocks_page_1',
    function() use ($stockService) {
        return $stockService->getStockList(20, 1);
    },
    600 // 10分鐘緩存
);
?>

七、部署説明

1. 目錄結構

project/
├── config/
│   └── StockTVConfig.php
├── src/
│   ├── StockTVClient.php
│   ├── StockDataService.php
│   ├── CompanyService.php
│   ├── WebSocketClient.php
│   ├── Logger.php
│   └── CacheService.php
├── logs/
├── vendor/
├── composer.json
└── index.php

2. 環境變量配置

創建 .env 文件:

STOCKTV_API_KEY=your_api_key_here
STOCKTV_COUNTRY_ID=42
REDIS_HOST=127.0.0.1
REDIS_PORT=6379

通過本PHP對接方案,您可以快速集成StockTV的印尼金融市場數據到您的應用中。建議在生產環境中添加監控和告警機制,確保數據服務的穩定性。

user avatar nihaojob Avatar kobe_fans_zxc Avatar zzger Avatar woniuseo Avatar guixiangyyds Avatar ligaai Avatar huizhudev Avatar weidewei Avatar kongsq Avatar youyoufei Avatar licin Avatar xiao2 Avatar
Favorites 87 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.