File size: 4,203 Bytes
33062e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# twelvedata_api.py
import requests
import os

class TwelveDataAPI:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.twelvedata.com"

    def _make_request(self, endpoint, params):
        url = f"{self.base_url}/{endpoint}"
        params['apikey'] = self.api_key
        try:
            response = requests.get(url, params=params)
            response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
            return response.json()
        except requests.exceptions.HTTPError as errh:
            print(f"Http Error: {errh}")
            return {"error": f"HTTP Error: {errh}"}
        except requests.exceptions.ConnectionError as errc:
            print(f"Error Connecting: {errc}")
            return {"error": f"Error Connecting: {errc}"}
        except requests.exceptions.Timeout as errt:
            print(f"Timeout Error: {errt}")
            return {"error": f"Timeout Error: {errt}"}
        except requests.exceptions.RequestException as err:
            print(f"Something went wrong: {err}")
            return {"error": f"Something went wrong: {err}"}

    def get_stocks(self, symbol: str, exchange: str = "NASDAQ", country: str = "USA"):
        """
        Tìm kiếm và liệt kê các cổ phiếu có mã tương tự.
        Args:
            symbol (str): Mã cổ phiếu để tìm kiếm.
        Returns:
            dict: Kết quả tìm kiếm từ TwelveData.
        """
        print(f"Calling TwelveData /stocks for symbol: {symbol}")
        return self._make_request("stocks", {"symbol": symbol, "exchange": exchange, "country": country})

    def get_time_series(self, symbol: str, interval: str = "1day", outputsize: int = 30):
        """
        Lấy thông tin time-series của một cổ phiếu cụ thể.
        Args:
            symbol (str): Mã cổ phiếu (ví dụ: VNINDEX, AAPL).
            interval (str): Khoảng thời gian (ví dụ: "1min", "5min", "1day", "1week"). Mặc định "1day".
            outputsize (int): Số lượng điểm dữ liệu trả về. Mặc định 30.
        Returns:
            dict: Dữ liệu time-series từ TwelveData.
        """
        print(f"Calling TwelveData /time-series for symbol: {symbol}, interval: {interval}, outputsize: {outputsize}")
        outputsize = int(outputsize)
        if outputsize > 120:
            outputsize = 120
        if outputsize < 1:
            outputsize = 1
        return self._make_request("time_series", {
            "symbol": symbol,
            "interval": interval,
            "outputsize": outputsize
        })

    def currency_conversion(self, amount: float, symbol: str):
        """
        Tìm thông tin quy đổi tiền tệ giữa 2 đơn vị.
        Args:
            amount (float): Số lượng tiền cần quy đổi.
            symbol (str): Cặp tiền tệ (ví dụ: USD/VND, EUR/GBP).
        Returns:
            dict: Kết quả quy đổi tiền tệ từ TwelveData.
        """
        print(f"Calling TwelveData /currency_conversion for amount: {amount}, symbol: {symbol}")
        return self._make_request("currency_conversion", {
            "amount": amount,
            "symbol": symbol
        })

    def get_all_stocks(self, exchange: str = "NASDAQ"):
        """
        Lấy danh sách tất cả các cổ phiếu từ một sàn giao dịch cụ thể để cache.
        Lưu ý: API miễn phí có thể giới hạn, chúng ta lấy ví dụ sàn NASDAQ.
        Args:
            exchange (str): Sàn giao dịch để lấy mã.
        Returns:
            dict: Danh sách cổ phiếu.
        """
        print(f"Calling TwelveData /stocks for ALL stocks")
        # API có thể trả về rất nhiều dữ liệu, nên giới hạn trong demo
        return self._make_request("stocks", {"exchange": exchange})

    def get_forex_pairs(self):
        """
        Lấy tất cả các cặp quy đổi tiền tệ có sẵn.
        Returns:
            dict: Danh sách các cặp tiền tệ.
        """
        print("Calling TwelveData /forex_pairs")
        return self._make_request("forex_pairs", {})