以下是使用 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 的完整支持,包括股票、外汇、期货和加密货币数据。通过模块化设计和清晰的代码结构,开发者可以轻松扩展和集成到自己的项目中。

CryptoRzz
1 声望0 粉丝

引用和评论

0 条评论