博客 / 詳情

返回

node對接期貨行情數據API 碳排放 貴金屬 外匯API

以下是使用 Node.js 對接 StockTV API 的項目實現。我們將使用 axios 進行 HTTP 請求,並使用 ws 庫處理 WebSocket 連接。


項目結構

stocktv-api-node/
│
├── src/
│   ├── StockAPI.js
│   ├── ForexAPI.js
│   ├── FuturesAPI.js
│   ├── CryptoAPI.js
│   └── ApiClient.js
│
├── tests/
│   ├── StockAPI.test.js
│   ├── ForexAPI.test.js
│   ├── FuturesAPI.test.js
│   └── CryptoAPI.test.js
│
├── package.json
├── README.md
└── index.js

1. 安裝依賴

在項目根目錄下運行以下命令初始化項目並安裝依賴:

npm init -y
npm install axios ws
npm install --save-dev jest

2. 創建基礎工具類

src/ApiClient.js 中,創建一個基礎工具類來處理 API 請求:

const axios = require('axios');

class ApiClient {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseUrl = "https://api.stocktv.top";
        this.client = axios.create({
            baseURL: this.baseUrl,
            timeout: 10000, // 10秒超時
        });
    }

    async get(endpoint, params = {}) {
        try {
            const response = await this.client.get(`/${endpoint}`, {
                params: {
                    key: this.apiKey,
                    ...params,
                },
            });
            return response.data;
        } catch (error) {
            throw new Error(`API request failed: ${error.message}`);
        }
    }
}

module.exports = ApiClient;

3. 實現股票 API

src/StockAPI.js 中,實現股票相關的 API:

const ApiClient = require('./ApiClient');

class StockAPI extends ApiClient {
    async getStockList(countryId, pageSize = 10, page = 1) {
        return this.get('stock/stocks', {
            countryId,
            pageSize,
            page,
        });
    }

    async getIndices(countryId, flag = null) {
        const params = { countryId };
        if (flag) params.flag = flag;
        return this.get('stock/indices', params);
    }

    async getKline(pid, interval) {
        return this.get('stock/kline', {
            pid,
            interval,
        });
    }
}

module.exports = StockAPI;

4. 實現外匯 API

src/ForexAPI.js 中,實現外匯相關的 API:

const ApiClient = require('./ApiClient');

class ForexAPI extends ApiClient {
    async getCurrencyList() {
        return this.get('market/currencyList');
    }

    async getRealTimeRates(countryType = null) {
        const params = {};
        if (countryType) params.countryType = countryType;
        return this.get('market/currency', params);
    }
}

module.exports = ForexAPI;

5. 實現期貨 API

src/FuturesAPI.js 中,實現期貨相關的 API:

const ApiClient = require('./ApiClient');

class FuturesAPI extends ApiClient {
    async getFuturesList() {
        return this.get('futures/list');
    }

    async getFuturesMarket(symbol) {
        return this.get('futures/querySymbol', { symbol });
    }
}

module.exports = FuturesAPI;

6. 實現加密貨幣 API

src/CryptoAPI.js 中,實現加密貨幣相關的 API:

const ApiClient = require('./ApiClient');

class CryptoAPI extends ApiClient {
    async getCoinInfo() {
        return this.get('crypto/getCoinInfo');
    }

    async getTickerPrice(symbols) {
        return this.get('crypto/tickerPrice', { symbols });
    }
}

module.exports = CryptoAPI;

7. WebSocket 支持

使用 ws 庫實現 WebSocket 連接:

const WebSocket = require('ws');

class StockTVWebSocket {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.wsUrl = `wss://ws-api.stocktv.top/connect?key=${apiKey}`;
    }

    connect() {
        const ws = new WebSocket(this.wsUrl);

        ws.on('open', () => {
            console.log('WebSocket connected');
        });

        ws.on('message', (data) => {
            console.log('Received:', data.toString());
        });

        ws.on('close', () => {
            console.log('WebSocket disconnected');
        });

        ws.on('error', (error) => {
            console.error('WebSocket error:', error);
        });
    }
}

module.exports = StockTVWebSocket;

8. 測試代碼

tests/StockAPI.test.js 中,編寫測試代碼:

const StockAPI = require('../src/StockAPI');

describe('StockAPI', () => {
    let stockAPI;

    beforeAll(() => {
        stockAPI = new StockAPI('your_api_key_here');
    });

    test('getStockList returns data', async () => {
        const data = await stockAPI.getStockList(14, 10, 1);
        expect(data).toHaveProperty('data');
    });
});

運行測試:

npx jest

9. 使用示例

index.js 中,編寫示例代碼:

const StockAPI = require('./src/StockAPI');
const StockTVWebSocket = require('./src/StockTVWebSocket');

const apiKey = 'your_api_key_here';

// HTTP API 示例
(async () => {
    const stockAPI = new StockAPI(apiKey);
    try {
        const stockList = await stockAPI.getStockList(14, 10, 1);
        console.log('Stock List:', stockList);
    } catch (error) {
        console.error('Error:', error.message);
    }
})();

// WebSocket 示例
const wsClient = new StockTVWebSocket(apiKey);
wsClient.connect();

10. README.md

在項目根目錄下創建 README.md 文件:

# StockTV API Node.js Client

A Node.js client for accessing StockTV's global financial data APIs.

## Installation

npm install stocktv-api-node


## Usage

const StockAPI = require('stocktv-api-node').StockAPI;

const apiKey = "your_api_key_here";
const stockAPI = new StockAPI(apiKey);

(async () => {

const stockList = await stockAPI.getStockList(14, 10, 1);
console.log(stockList);

})();


## 總結

這個 Node.js 項目提供了對 StockTV API 的完整支持,包括股票、外匯、期貨和加密貨幣數據。通過模塊化設計和清晰的代碼結構,開發者可以輕鬆擴展和集成到自己的項目中。
user avatar xiangjiaochihuanggua 頭像 buxia97 頭像 weirdo_5f6c401c6cc86 頭像 light_5cfbb652e97ce 頭像 huashenjianlingshouhuni 頭像 zhuomoxiansheng_5f1901de6fd23 頭像 hooray 頭像
7 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.