From 565fad946febe717ace23dcd18d76f5bbd42ad22 Mon Sep 17 00:00:00 2001 From: yilv <874448085@qq.com> Date: Tue, 3 Mar 2026 15:26:09 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20iTick=20Python=20S?= =?UTF-8?q?DK=20=E5=88=9D=E5=A7=8B=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现 REST API 客户端,支持股票、加密货币、外汇、期货、基金和指数数据 - 实现 WebSocket 客户端,支持实时数据订阅 - 添加异常处理、工具函数和常量定义 - 包含安装配置和示例代码 - 添加文档爬虫工具用于生成离线文档 --- crawler.py | 271 +++++++++++++++++++++++++++++++++++++++++ examples/demo_rest.py | 26 ++++ examples/demo_ws.py | 45 +++++++ itick/__init__.py | 5 + itick/client.py | 76 ++++++++++++ itick/constants.py | 35 ++++++ itick/exceptions.py | 19 +++ itick/rest/__init__.py | 0 itick/rest/base.py | 48 ++++++++ itick/rest/crypto.py | 33 +++++ itick/rest/forex.py | 18 +++ itick/rest/fund.py | 18 +++ itick/rest/future.py | 18 +++ itick/rest/indices.py | 18 +++ itick/rest/stock.py | 42 +++++++ itick/rest/symbol.py | 22 ++++ itick/socket.py | 133 ++++++++++++++++++++ itick/utils.py | 5 + setup.py | 14 +++ 19 files changed, 846 insertions(+) create mode 100644 crawler.py create mode 100644 examples/demo_rest.py create mode 100644 examples/demo_ws.py create mode 100644 itick/__init__.py create mode 100644 itick/client.py create mode 100644 itick/constants.py create mode 100644 itick/exceptions.py create mode 100644 itick/rest/__init__.py create mode 100644 itick/rest/base.py create mode 100644 itick/rest/crypto.py create mode 100644 itick/rest/forex.py create mode 100644 itick/rest/fund.py create mode 100644 itick/rest/future.py create mode 100644 itick/rest/indices.py create mode 100644 itick/rest/stock.py create mode 100644 itick/rest/symbol.py create mode 100644 itick/socket.py create mode 100644 itick/utils.py create mode 100644 setup.py diff --git a/crawler.py b/crawler.py new file mode 100644 index 0000000..f612525 --- /dev/null +++ b/crawler.py @@ -0,0 +1,271 @@ +import requests +from bs4 import BeautifulSoup +from markdownify import markdownify as md +import os +import time +from urllib.parse import urljoin, urlparse +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry + +BASE_URL = "https://docs.itick.org/zh-cn" +OUTPUT_DIR = "docs" + +def setup(): + if not os.path.exists(OUTPUT_DIR): + os.makedirs(OUTPUT_DIR) + +def get_session(): + session = requests.Session() + retry = Retry(connect=3, backoff_factor=0.5) + adapter = HTTPAdapter(max_retries=retry) + session.mount('http://', adapter) + session.mount('https://', adapter) + return session + +def get_soup(url, session=None): + headers = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" + } + try: + if session: + response = session.get(url, headers=headers, timeout=10) + else: + response = requests.get(url, headers=headers, timeout=10) + response.raise_for_status() + return BeautifulSoup(response.content, "lxml") + except Exception as e: + print(f"Error fetching {url}: {e}") + return None + +def process_html(soup): + # 1. 提取正文 + # 尝试找到包含文章内容的容器 + article = soup.select_one('article.container') + if not article: + article = soup.select_one('main.section') + + if not article: + return soup.body + + # 2. 清理无关元素 + for selector in [ + 'aside', + '.bread-crumbs', + '.select-key-box', + 'footer', + '.surroundList', # 底部导航 + 'style', + 'script', + '.text-hidden', # 隐藏的 SEO 标题 + '.code-title', # 复制代码按钮 + '.response-result-title-btns', # 响应结果切换按钮 + '.response-result-title-info', # 响应结果复制按钮 + '.iconfont.icon-copy' # 所有的复制图标 + ]: + for tag in article.select(selector): + tag.decompose() + + # 3. 转换参数列表为表格 (.query-params) + for params_box in article.select('.query-params'): + table = soup.new_tag('table') + + # Thead + thead = soup.new_tag('thead') + tr = soup.new_tag('tr') + headers = ['参数名', '类型', '必填', '说明'] + for h in headers: + th = soup.new_tag('th') + th.string = h + tr.append(th) + thead.append(tr) + table.append(thead) + + # Tbody + tbody = soup.new_tag('tbody') + fields = params_box.select('.custom-field') + + if not fields: + continue + + for field in fields: + tr = soup.new_tag('tr') + + # Name + name_el = field.select_one('.field-name') + td_name = soup.new_tag('td') + td_name.string = name_el.get_text(strip=True) if name_el else '' + tr.append(td_name) + + # Type + type_el = field.select_one('.field-type') + td_type = soup.new_tag('td') + td_type.string = type_el.get_text(strip=True) if type_el else '' + tr.append(td_type) + + # Required + req_el = field.select_one('.field-required') + td_req = soup.new_tag('td') + td_req.string = req_el.get_text(strip=True) if req_el else '' + tr.append(td_req) + + # Description + desc_el = field.select_one('.field-content') + td_desc = soup.new_tag('td') + + desc_text = "" + if desc_el: + desc_text = desc_el.get_text(strip=True) + + # 检查 dropdown options + select_box = field.select_one('.custom-select') + if select_box: + options = [opt.get_text(strip=True) for opt in select_box.select('.custom-option span')] + # 去重 + options = list(dict.fromkeys(options)) + if options: + desc_text += f" (可选值: {', '.join(options)})" + + td_desc.string = desc_text + tr.append(td_desc) + + tbody.append(tr) + + table.append(tbody) + params_box.replace_with(table) + + # 3.5 转换响应参数为表格 + for header in article.find_all(['h2', 'h3']): + if "响应参数" in header.get_text(): + content_div = header.find_next_sibling('div') + if content_div and content_div.select('.custom-field'): + table = soup.new_tag('table') + thead = soup.new_tag('thead') + tr = soup.new_tag('tr') + for h in ['参数名', '类型', '说明']: + th = soup.new_tag('th') + th.string = h + tr.append(th) + thead.append(tr) + table.append(thead) + + tbody = soup.new_tag('tbody') + for field in content_div.select('.custom-field'): + tr = soup.new_tag('tr') + + name_el = field.select_one('.field-name') + td_name = soup.new_tag('td') + td_name.string = name_el.get_text(strip=True) if name_el else '' + tr.append(td_name) + + type_el = field.select_one('.field-type') + td_type = soup.new_tag('td') + td_type.string = type_el.get_text(strip=True) if type_el else '' + tr.append(td_type) + + desc_el = field.select_one('.field-content') + td_desc = soup.new_tag('td') + td_desc.string = desc_el.get_text(strip=True) if desc_el else '' + tr.append(td_desc) + + tbody.append(tr) + + table.append(tbody) + content_div.replace_with(table) + + # 4. 转换查询 URL 盒子 (.query-box) + for query_box in article.select('.query-box'): + method = query_box.select_one('.method') + url = query_box.select_one('.url') + + if method and url: + # 使用 pre code 块展示 + code_block = soup.new_tag('pre') + code = soup.new_tag('code') + code.string = f"{method.get_text(strip=True)} {url.get_text(strip=True)}" + code_block.append(code) + query_box.replace_with(code_block) + + # 5. 处理响应结果区域 (.response-result) + # 移除多余的容器,只保留代码块 + for resp_box in article.select('.response-result'): + content = resp_box.select_one('.response-result-content') + if content: + # 直接把 content 里的 pre 拿出来,替换整个 box + pre = content.select_one('pre') + if pre: + resp_box.replace_with(pre) + else: + resp_box.replace_with(content) + + return article + +def main(): + setup() + session = get_session() + + print(f"Fetching {BASE_URL}...") + soup = get_soup(BASE_URL, session) + if not soup: + return + + # Extract all documentation links from the sidebar + links = [] + sidebar = soup.select_one('aside.menu-box') + if sidebar: + for a in sidebar.select('a.menu-item'): + href = a.get('href') + if href and not href.startswith('http') and not href.startswith('#'): + full_url = urljoin(BASE_URL, href) + # Ensure we only crawl the docs part and not external links + if '/zh-cn' in full_url: + links.append(full_url) + + # Remove duplicates + links = list(set(links)) + print(f"Found {len(links)} pages to crawl.") + + # Crawl each page + for i, link in enumerate(links): + print(f"[{i+1}/{len(links)}] Crawling {link}...") + page_soup = get_soup(link, session) + if not page_soup: + continue + + # Process and optimize HTML + content_html = process_html(page_soup) + + if content_html: + # Convert to Markdown + markdown = md(str(content_html), heading_style="ATX", strip=['script', 'style']) + + # Post-processing markdown + # Remove multiple newlines + while '\n\n\n' in markdown: + markdown = markdown.replace('\n\n\n', '\n\n') + + # Save to file + parsed_url = urlparse(link) + path = parsed_url.path.strip('/') + if path.startswith('zh-cn/'): + path = path[6:] # Remove 'zh-cn/' prefix + if not path: + path = "index" + + file_path = os.path.join(OUTPUT_DIR, f"{path}.md") + + # Ensure directory exists + os.makedirs(os.path.dirname(file_path), exist_ok=True) + + with open(file_path, "w", encoding="utf-8") as f: + f.write(f"# Source: {link}\n\n") + f.write(markdown) + + print(f"Saved to {file_path}") + + # Be nice to the server + time.sleep(0.5) + + print("Crawling completed.") + +if __name__ == "__main__": + main() diff --git a/examples/demo_rest.py b/examples/demo_rest.py new file mode 100644 index 0000000..1faf413 --- /dev/null +++ b/examples/demo_rest.py @@ -0,0 +1,26 @@ +from itick import Client, Environment +from itick.exceptions import APIError + +def main(): + # Initialize client + # Replace with your actual token + client = Client(token="YOUR_TOKEN", environment=Environment.FREE) + + try: + # Example 1: Get Crypto Quote + print("Fetching Crypto Quote...") + quote = client.crypto.get_quote(region="BA", code="BTCUSDT") + print("Quote:", quote) + + # Example 2: Get Stock Kline + print("\nFetching Stock Kline...") + kline = client.stock.get_kline(region="HK", code="700", period=1) + print("Kline:", kline) + + except APIError as e: + print(f"API Error: {e}") + except Exception as e: + print(f"Error: {e}") + +if __name__ == "__main__": + main() diff --git a/examples/demo_ws.py b/examples/demo_ws.py new file mode 100644 index 0000000..21e2ab4 --- /dev/null +++ b/examples/demo_ws.py @@ -0,0 +1,45 @@ +import asyncio +import logging +from itick import SocketClient, Environment, Product + +# Configure logging +logging.basicConfig(level=logging.INFO) + +async def main(): + token = "YOUR_TOKEN" + + def on_message(msg): + print(f"Received: {msg}") + + def on_error(err): + print(f"Error: {err}") + + # Create WebSocket client for Crypto + client = SocketClient( + token=token, + product=Product.CRYPTO, + environment=Environment.FREE, + on_message=on_message, + on_error=on_error + ) + + try: + await client.connect() + + # Wait a bit for connection and auth + await asyncio.sleep(2) + + # Subscribe + print("Subscribing...") + await client.subscribe(symbols=["BTCUSDT$BA"], data_types=["quote", "tick"]) + + # Run for 10 seconds + await asyncio.sleep(10) + + except Exception as e: + print(f"Main Error: {e}") + finally: + await client.close() + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/itick/__init__.py b/itick/__init__.py new file mode 100644 index 0000000..8e0fe98 --- /dev/null +++ b/itick/__init__.py @@ -0,0 +1,5 @@ +from .client import Client +from .socket import SocketClient +from .constants import Environment, Product, KlinePeriod + +__all__ = ['Client', 'SocketClient', 'Environment', 'Product', 'KlinePeriod'] diff --git a/itick/client.py b/itick/client.py new file mode 100644 index 0000000..a6ea7d1 --- /dev/null +++ b/itick/client.py @@ -0,0 +1,76 @@ +import requests +from .constants import Environment, BASE_URLS +from .exceptions import APIError, AuthError, ITickError +from .rest.crypto import Crypto +from .rest.stock import Stock +from .rest.forex import Forex +from .rest.fund import Fund +from .rest.future import Future +from .rest.indices import Indices +from .rest.symbol import Symbol + +class Client: + def __init__(self, token, environment=Environment.LIVE): + self.token = token + self.environment = environment + self.base_url = BASE_URLS.get(environment) + if not self.base_url: + raise ITickError("Invalid environment") + + self.session = requests.Session() + self.session.headers.update({ + "token": self.token, + "accept": "application/json" + }) + + def _request(self, method, endpoint, params=None, data=None): + url = f"{self.base_url}{endpoint}" + try: + response = self.session.request(method, url, params=params, json=data) + response.raise_for_status() + + res_json = response.json() + + # Check for API error code + # Assuming code 0 is success for REST based on docs + code = res_json.get("code") + if code is not None and code != 0: + msg = res_json.get("msg", "Unknown error") + if code == 401 or msg == "auth failed": # Example check + raise AuthError(f"Authentication failed: {msg}") + raise APIError(code, msg, res_json.get("data")) + + return res_json.get("data") + + except requests.exceptions.RequestException as e: + raise ITickError(f"Request failed: {str(e)}") + except ValueError: + raise ITickError("Invalid JSON response") + + @property + def crypto(self): + return Crypto(self) + + @property + def stock(self): + return Stock(self) + + @property + def forex(self): + return Forex(self) + + @property + def fund(self): + return Fund(self) + + @property + def future(self): + return Future(self) + + @property + def indices(self): + return Indices(self) + + @property + def symbol(self): + return Symbol(self) diff --git a/itick/constants.py b/itick/constants.py new file mode 100644 index 0000000..af1d8d0 --- /dev/null +++ b/itick/constants.py @@ -0,0 +1,35 @@ +from enum import Enum + +class Environment(Enum): + LIVE = "live" + FREE = "free" + +class Product(Enum): + CRYPTO = "crypto" + FOREX = "forex" + INDICES = "indices" + STOCK = "stock" + FUTURE = "future" + FUND = "fund" + +class KlinePeriod(Enum): + ONE_MINUTE = 1 + FIVE_MINUTES = 2 + FIFTEEN_MINUTES = 3 + THIRTY_MINUTES = 4 + ONE_HOUR = 5 + TWO_HOURS = 6 # Crypto only + FOUR_HOURS = 7 # Crypto only + ONE_DAY = 8 + ONE_WEEK = 9 + ONE_MONTH = 10 + +BASE_URLS = { + Environment.LIVE: "https://api.itick.org", + Environment.FREE: "https://api-free.itick.org" +} + +WS_URLS = { + Environment.LIVE: "wss://api.itick.org", + Environment.FREE: "wss://api-free.itick.org" +} diff --git a/itick/exceptions.py b/itick/exceptions.py new file mode 100644 index 0000000..f48eadf --- /dev/null +++ b/itick/exceptions.py @@ -0,0 +1,19 @@ +class ITickError(Exception): + """Base exception for iTick SDK""" + pass + +class APIError(ITickError): + """Exception for API errors""" + def __init__(self, code, msg, data=None): + self.code = code + self.msg = msg + self.data = data + super().__init__(f"API Error {code}: {msg}") + +class AuthError(ITickError): + """Exception for Authentication errors""" + pass + +class ConnectionError(ITickError): + """Exception for connection errors""" + pass diff --git a/itick/rest/__init__.py b/itick/rest/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/itick/rest/base.py b/itick/rest/base.py new file mode 100644 index 0000000..a2b7d18 --- /dev/null +++ b/itick/rest/base.py @@ -0,0 +1,48 @@ +class BaseProduct: + def __init__(self, client): + self.client = client + self.product_path = "" + + def _get(self, endpoint, params=None): + return self.client._request("GET", f"/{self.product_path}{endpoint}", params=params) + + def get_quotes(self, region, codes): + """ + Get real-time quotes for multiple products + :param region: Market region + :param codes: List of product codes or comma-separated string + """ + if isinstance(codes, list): + codes = ",".join(codes) + return self._get("/quotes", params={"region": region, "codes": codes}) + + def get_depths(self, region, codes): + """ + Get market depths for multiple products + :param region: Market region + :param codes: List of product codes or comma-separated string + """ + if isinstance(codes, list): + codes = ",".join(codes) + return self._get("/depths", params={"region": region, "codes": codes}) + + def get_ticks(self, region, codes): + """ + Get latest trade ticks for multiple products + :param region: Market region + :param codes: List of product codes or comma-separated string + """ + if isinstance(codes, list): + codes = ",".join(codes) + return self._get("/ticks", params={"region": region, "codes": codes}) + + def get_klines(self, region, codes, period): + """ + Get K-line data for multiple products + :param region: Market region + :param codes: List of product codes or comma-separated string + :param period: K-line period + """ + if isinstance(codes, list): + codes = ",".join(codes) + return self._get("/klines", params={"region": region, "codes": codes, "period": period}) diff --git a/itick/rest/crypto.py b/itick/rest/crypto.py new file mode 100644 index 0000000..4795aff --- /dev/null +++ b/itick/rest/crypto.py @@ -0,0 +1,33 @@ +from .base import BaseProduct + +class Crypto(BaseProduct): + def __init__(self, client): + super().__init__(client) + self.product_path = "crypto" + + def get_quote(self, region, code): + """ + Get real-time quote for crypto + :param region: Market region (e.g., 'BA') + :param code: Product code (e.g., 'BTCUSDT') + """ + return self._get("/quote", params={"region": region, "code": code}) + + def get_depth(self, region, code): + """ + Get market depth + """ + return self._get("/depth", params={"region": region, "code": code}) + + def get_tick(self, region, code): + """ + Get latest trade tick + """ + return self._get("/tick", params={"region": region, "code": code}) + + def get_kline(self, region, code, period): + """ + Get K-line data + :param period: 1, 2, 3, etc. (See docs) + """ + return self._get("/kline", params={"region": region, "code": code, "period": period}) diff --git a/itick/rest/forex.py b/itick/rest/forex.py new file mode 100644 index 0000000..6924267 --- /dev/null +++ b/itick/rest/forex.py @@ -0,0 +1,18 @@ +from .base import BaseProduct + +class Forex(BaseProduct): + def __init__(self, client): + self.client = client + self.product_path = "forex" + + def get_quote(self, region, code): + return self._get("/quote", params={"region": region, "code": code}) + + def get_depth(self, region, code): + return self._get("/depth", params={"region": region, "code": code}) + + def get_tick(self, region, code): + return self._get("/tick", params={"region": region, "code": code}) + + def get_kline(self, region, code, period): + return self._get("/kline", params={"region": region, "code": code, "period": period}) diff --git a/itick/rest/fund.py b/itick/rest/fund.py new file mode 100644 index 0000000..58a0d7f --- /dev/null +++ b/itick/rest/fund.py @@ -0,0 +1,18 @@ +from .base import BaseProduct + +class Fund(BaseProduct): + def __init__(self, client): + self.client = client + self.product_path = "fund" + + def get_quote(self, region, code): + return self._get("/quote", params={"region": region, "code": code}) + + def get_depth(self, region, code): + return self._get("/depth", params={"region": region, "code": code}) + + def get_tick(self, region, code): + return self._get("/tick", params={"region": region, "code": code}) + + def get_kline(self, region, code, period): + return self._get("/kline", params={"region": region, "code": code, "period": period}) diff --git a/itick/rest/future.py b/itick/rest/future.py new file mode 100644 index 0000000..50e7883 --- /dev/null +++ b/itick/rest/future.py @@ -0,0 +1,18 @@ +from .base import BaseProduct + +class Future(BaseProduct): + def __init__(self, client): + self.client = client + self.product_path = "future" + + def get_quote(self, region, code): + return self._get("/quote", params={"region": region, "code": code}) + + def get_depth(self, region, code): + return self._get("/depth", params={"region": region, "code": code}) + + def get_tick(self, region, code): + return self._get("/tick", params={"region": region, "code": code}) + + def get_kline(self, region, code, period): + return self._get("/kline", params={"region": region, "code": code, "period": period}) diff --git a/itick/rest/indices.py b/itick/rest/indices.py new file mode 100644 index 0000000..d042119 --- /dev/null +++ b/itick/rest/indices.py @@ -0,0 +1,18 @@ +from .base import BaseProduct + +class Indices(BaseProduct): + def __init__(self, client): + self.client = client + self.product_path = "indices" + + def get_quote(self, region, code): + return self._get("/quote", params={"region": region, "code": code}) + + def get_depth(self, region, code): + return self._get("/depth", params={"region": region, "code": code}) + + def get_tick(self, region, code): + return self._get("/tick", params={"region": region, "code": code}) + + def get_kline(self, region, code, period): + return self._get("/kline", params={"region": region, "code": code, "period": period}) diff --git a/itick/rest/stock.py b/itick/rest/stock.py new file mode 100644 index 0000000..950122c --- /dev/null +++ b/itick/rest/stock.py @@ -0,0 +1,42 @@ +from .base import BaseProduct + +class Stock(BaseProduct): + def __init__(self, client): + super().__init__(client) + self.product_path = "stock" + + def get_quote(self, region, code): + return self._get("/quote", params={"region": region, "code": code}) + + def get_depth(self, region, code): + return self._get("/depth", params={"region": region, "code": code}) + + def get_tick(self, region, code): + return self._get("/tick", params={"region": region, "code": code}) + + def get_kline(self, region, code, period): + return self._get("/kline", params={"region": region, "code": code, "period": period}) + + def get_info(self, region, code, type="stock"): + """ + Get stock information + :param region: Market region + :param code: Product code + :param type: Market type (default: "stock") + """ + return self._get("/info", params={"type": type, "region": region, "code": code}) + + def get_ipo(self, region, type="upcoming"): + """ + Get stock IPO information + :param region: Market region + :param type: "upcoming" or "recent" + """ + return self._get("/ipo", params={"type": type, "region": region}) + + def get_split(self, region): + """ + Get stock split information + :param region: Market region + """ + return self._get("/split", params={"region": region}) diff --git a/itick/rest/symbol.py b/itick/rest/symbol.py new file mode 100644 index 0000000..ee98283 --- /dev/null +++ b/itick/rest/symbol.py @@ -0,0 +1,22 @@ +class Symbol: + def __init__(self, client): + self.client = client + + def get_list(self, type, region, code=None): + """ + Get product list + :param type: Product type (stock, forex, indices, crypto, future, fund) + :param region: Market region + :param code: Product code (optional) + """ + params = {"type": type, "region": region} + if code: + params["code"] = code + return self.client._request("GET", "/symbol/list", params=params) + + def get_holidays(self, region_code): + """ + Get market holidays + :param region_code: Region code (e.g., 'HK', 'US') + """ + return self.client._request("GET", "/symbol/v2/holidays", params={"code": region_code}) diff --git a/itick/socket.py b/itick/socket.py new file mode 100644 index 0000000..f2b936b --- /dev/null +++ b/itick/socket.py @@ -0,0 +1,133 @@ +import asyncio +import json +import logging +import websockets +from .constants import Environment, WS_URLS, Product +from .exceptions import ITickError, AuthError, ConnectionError +from .utils import get_timestamp + +logger = logging.getLogger(__name__) + +class SocketClient: + def __init__(self, token, product, environment=Environment.LIVE, on_message=None, on_error=None): + """ + :param token: API Token + :param product: Product enum or string (e.g., 'crypto', 'stock') + :param environment: Environment.LIVE or Environment.FREE + :param on_message: Callback for normal messages + :param on_error: Callback for errors + """ + self.token = token + self.product = product.value if isinstance(product, Product) else product + self.environment = environment + self.base_url = WS_URLS.get(environment) + self.url = f"{self.base_url}/{self.product}" + + self.on_message_callback = on_message + self.on_error_callback = on_error + + self.ws = None + self.running = False + self.authenticated = False + self._lock = asyncio.Lock() + + async def connect(self): + """Connect to the WebSocket server""" + headers = {"token": self.token} + try: + logger.info(f"Connecting to {self.url}...") + self.ws = await websockets.connect(self.url, extra_headers=headers) + self.running = True + logger.info("Connected.") + + # Start listener and heartbeat + asyncio.create_task(self._listen()) + asyncio.create_task(self._heartbeat()) + + except Exception as e: + logger.error(f"Connection failed: {e}") + if self.on_error_callback: + self.on_error_callback(ConnectionError(str(e))) + raise + + async def subscribe(self, symbols, data_types): + """ + Subscribe to data + :param symbols: List of symbols (e.g., ["BTCUSDT$BA"]) or comma-separated string + :param data_types: List of types (e.g., ["quote", "depth"]) or comma-separated string + """ + if not self.ws or not self.running: + raise ConnectionError("WebSocket is not connected") + + if isinstance(symbols, list): + symbols = ",".join(symbols) + if isinstance(data_types, list): + data_types = ",".join(data_types) + + msg = { + "ac": "subscribe", + "params": symbols, + "types": data_types + } + await self._send(msg) + + async def _send(self, data): + if self.ws: + await self.ws.send(json.dumps(data)) + + async def _listen(self): + while self.running and self.ws: + try: + message = await self.ws.recv() + data = json.loads(message) + + # Handle system messages + if "resAc" in data: + res_ac = data.get("resAc") + if res_ac == "auth": + if data.get("code") == 1: + self.authenticated = True + logger.info("Authenticated successfully") + else: + logger.error(f"Authentication failed: {data.get('msg')}") + if self.on_error_callback: + self.on_error_callback(AuthError(data.get("msg"))) + # Should probably close? + elif res_ac == "pong": + # logger.debug("Pong received") + pass + elif res_ac == "subscribe": + if data.get("code") != 1: + logger.error(f"Subscription failed: {data.get('msg')}") + + # User callback + if self.on_message_callback: + self.on_message_callback(data) + + except websockets.exceptions.ConnectionClosed: + logger.warning("Connection closed") + self.running = False + break + except Exception as e: + logger.error(f"Error in listener: {e}") + if self.on_error_callback: + self.on_error_callback(e) + + async def _heartbeat(self): + while self.running: + await asyncio.sleep(30) + if self.ws and self.running: + try: + ping_msg = { + "ac": "ping", + "params": str(get_timestamp()) + } + await self._send(ping_msg) + except Exception as e: + logger.error(f"Heartbeat failed: {e}") + break + + async def close(self): + self.running = False + if self.ws: + await self.ws.close() diff --git a/itick/utils.py b/itick/utils.py new file mode 100644 index 0000000..9219f7e --- /dev/null +++ b/itick/utils.py @@ -0,0 +1,5 @@ +import time + +def get_timestamp(): + """Get current timestamp in milliseconds""" + return int(time.time() * 1000) diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..1e5cb50 --- /dev/null +++ b/setup.py @@ -0,0 +1,14 @@ +from setuptools import setup, find_packages + +setup( + name="itick-python", + version="0.1.0", + description="Python SDK for iTick Market Data API", + author="iTick", + packages=find_packages(), + install_requires=[ + "requests>=2.25.0", + "websockets>=10.0", + ], + python_requires=">=3.7", +)