ccxt-tiktape 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
5
+ .venv/
6
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TikTape
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: ccxt-tiktape
3
+ Version: 0.1.1
4
+ Summary: Full Hyperliquid OHLCV history in CCXT: a drop-in ccxt.hyperliquid subclass served by TikTape, past the 5000-candle limit.
5
+ Project-URL: Homepage, https://tiktape.xyz/?utm_source=pypi&utm_medium=package&utm_campaign=ccxt-tiktape
6
+ Project-URL: Source, https://github.com/tiktape/ccxt-tiktape
7
+ Project-URL: Issues, https://github.com/tiktape/ccxt-tiktape/issues
8
+ Project-URL: API reference, https://tiktape.xyz/openapi.yaml
9
+ Author-email: TikTape <evan@tiktape.xyz>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: backtesting,candles,ccxt,crypto,funding-rate,historical-data,hyperliquid,ohlcv
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Financial and Insurance Industry
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Office/Business :: Financial :: Investment
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: ccxt>=4.4
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=7; extra == 'test'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # ccxt-tiktape
26
+
27
+ Full Hyperliquid OHLCV history in [CCXT](https://github.com/ccxt/ccxt), past the
28
+ 5000-candle limit.
29
+
30
+ `ccxt.hyperliquid().fetch_ohlcv()` only reaches the most recent 5000 candles per
31
+ interval: about 3.5 days of 1m bars. `ccxt-tiktape` is a drop-in subclass of
32
+ `ccxt.hyperliquid` whose `fetch_ohlcv()` is served by the
33
+ [TikTape](https://tiktape.xyz/?utm_source=pypi&utm_medium=readme&utm_campaign=ccxt-tiktape)
34
+ archive instead, with the same symbols, timeframes and return format. Everything
35
+ else (markets, tickers, funding rate history, order books) still comes from
36
+ Hyperliquid's public API through CCXT.
37
+
38
+ **Get a free API key (30 days of history, no card):
39
+ [tiktape.xyz](https://tiktape.xyz/?utm_source=pypi&utm_medium=readme&utm_campaign=ccxt-tiktape#freeKeyCard).**
40
+ Paid keys unlock the full archive.
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install ccxt-tiktape
46
+ ```
47
+
48
+ ## Quick start
49
+
50
+ ```python
51
+ import os
52
+ import ccxt_tiktape
53
+
54
+ exchange = ccxt_tiktape.tiktape({"apiKey": os.environ["TIKTAPE_API_KEY"]})
55
+
56
+ # 1m candles from 7 days ago: older than the 5000 bars ccxt.hyperliquid can reach.
57
+ since = exchange.milliseconds() - 7 * 24 * 60 * 60 * 1000
58
+ candles = exchange.fetch_ohlcv(
59
+ "BTC/USDC:USDC", "1m", since=since, limit=10_000, params={"paginate": True}
60
+ )
61
+
62
+ print(len(candles), "candles from", exchange.iso8601(candles[0][0]))
63
+ # 10000 candles from 2026-11-16T05:12:00.000Z
64
+ ```
65
+
66
+ Rows are standard CCXT candles: `[open_time_ms, open, high, low, close, volume]`,
67
+ ascending, floats.
68
+
69
+ ### Swap it into existing code
70
+
71
+ ```python
72
+ import ccxt
73
+ import ccxt_tiktape # registers ccxt.tiktape
74
+
75
+ exchange = ccxt.tiktape({"apiKey": "tt_..."}) # was: ccxt.hyperliquid()
76
+ exchange.load_markets() # Hyperliquid markets, unchanged
77
+ exchange.fetch_ohlcv("ETH/USDC:USDC", "1h", since=..., limit=1000)
78
+ exchange.fetch_funding_rate_history("ETH/USDC:USDC", since=...) # Hyperliquid API
79
+ ```
80
+
81
+ ### Parameters
82
+
83
+ | Argument | Meaning |
84
+ |---|---|
85
+ | `symbol` | Any Hyperliquid perp (`BTC/USDC:USDC`) or spot market CCXT knows |
86
+ | `timeframe` | `1m 3m 5m 15m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w 1M` |
87
+ | `since` | Earliest candle open time, ms |
88
+ | `limit` | Number of candles (default 500; up to 10000 per request) |
89
+ | `params["until"]` | Latest candle open time, exclusive, ms |
90
+ | `params["paginate"]` | `True` to follow pages from `since` until `until`/now or `limit` |
91
+
92
+ Requests are spaced 1 s apart by default (free tier: 60 requests per minute, 10000
93
+ per month). On a paid key, lower it with
94
+ `ccxt_tiktape.tiktape({"apiKey": ..., "options": {"tiktapeRateLimit": 250}})`.
95
+
96
+ ### Errors
97
+
98
+ | HTTP | CCXT error |
99
+ |---|---|
100
+ | 401 missing or invalid key | `AuthenticationError` |
101
+ | 403 data older than your key's history window | `PermissionDenied` |
102
+ | 429 rate limit or monthly quota | `RateLimitExceeded` |
103
+ | 400 unsupported market or parameter | `BadSymbol` / `BadRequest` |
104
+
105
+ ## Freqtrade
106
+
107
+ Freqtrade cannot load third-party CCXT classes directly. Download candles with
108
+ this package and write them in Freqtrade's data format (for example
109
+ `user_data/data/hyperliquid/BTC_USDC_USDC-1m-futures.feather`), then backtest
110
+ from files.
111
+
112
+ ## Free sample dataset
113
+
114
+ BTC and ETH 1h/1d candles plus hourly funding (Aug-Oct 2026), CC-BY-4.0:
115
+ [download from GitHub releases](https://github.com/tiktape/ccxt-tiktape/releases/tag/sample-dataset-2026-11).
116
+
117
+ ## Development
118
+
119
+ ```bash
120
+ pip install -e ".[test]"
121
+ pytest
122
+ ```
123
+
124
+ Releases are tagged `vX.Y.Z` and published to PyPI by GitHub Actions with trusted
125
+ publishing.
126
+
127
+ ## License
128
+
129
+ MIT. Market data is subject to the [TikTape terms](https://tiktape.xyz/terms-and-conditions).
@@ -0,0 +1,105 @@
1
+ # ccxt-tiktape
2
+
3
+ Full Hyperliquid OHLCV history in [CCXT](https://github.com/ccxt/ccxt), past the
4
+ 5000-candle limit.
5
+
6
+ `ccxt.hyperliquid().fetch_ohlcv()` only reaches the most recent 5000 candles per
7
+ interval: about 3.5 days of 1m bars. `ccxt-tiktape` is a drop-in subclass of
8
+ `ccxt.hyperliquid` whose `fetch_ohlcv()` is served by the
9
+ [TikTape](https://tiktape.xyz/?utm_source=pypi&utm_medium=readme&utm_campaign=ccxt-tiktape)
10
+ archive instead, with the same symbols, timeframes and return format. Everything
11
+ else (markets, tickers, funding rate history, order books) still comes from
12
+ Hyperliquid's public API through CCXT.
13
+
14
+ **Get a free API key (30 days of history, no card):
15
+ [tiktape.xyz](https://tiktape.xyz/?utm_source=pypi&utm_medium=readme&utm_campaign=ccxt-tiktape#freeKeyCard).**
16
+ Paid keys unlock the full archive.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install ccxt-tiktape
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```python
27
+ import os
28
+ import ccxt_tiktape
29
+
30
+ exchange = ccxt_tiktape.tiktape({"apiKey": os.environ["TIKTAPE_API_KEY"]})
31
+
32
+ # 1m candles from 7 days ago: older than the 5000 bars ccxt.hyperliquid can reach.
33
+ since = exchange.milliseconds() - 7 * 24 * 60 * 60 * 1000
34
+ candles = exchange.fetch_ohlcv(
35
+ "BTC/USDC:USDC", "1m", since=since, limit=10_000, params={"paginate": True}
36
+ )
37
+
38
+ print(len(candles), "candles from", exchange.iso8601(candles[0][0]))
39
+ # 10000 candles from 2026-11-16T05:12:00.000Z
40
+ ```
41
+
42
+ Rows are standard CCXT candles: `[open_time_ms, open, high, low, close, volume]`,
43
+ ascending, floats.
44
+
45
+ ### Swap it into existing code
46
+
47
+ ```python
48
+ import ccxt
49
+ import ccxt_tiktape # registers ccxt.tiktape
50
+
51
+ exchange = ccxt.tiktape({"apiKey": "tt_..."}) # was: ccxt.hyperliquid()
52
+ exchange.load_markets() # Hyperliquid markets, unchanged
53
+ exchange.fetch_ohlcv("ETH/USDC:USDC", "1h", since=..., limit=1000)
54
+ exchange.fetch_funding_rate_history("ETH/USDC:USDC", since=...) # Hyperliquid API
55
+ ```
56
+
57
+ ### Parameters
58
+
59
+ | Argument | Meaning |
60
+ |---|---|
61
+ | `symbol` | Any Hyperliquid perp (`BTC/USDC:USDC`) or spot market CCXT knows |
62
+ | `timeframe` | `1m 3m 5m 15m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w 1M` |
63
+ | `since` | Earliest candle open time, ms |
64
+ | `limit` | Number of candles (default 500; up to 10000 per request) |
65
+ | `params["until"]` | Latest candle open time, exclusive, ms |
66
+ | `params["paginate"]` | `True` to follow pages from `since` until `until`/now or `limit` |
67
+
68
+ Requests are spaced 1 s apart by default (free tier: 60 requests per minute, 10000
69
+ per month). On a paid key, lower it with
70
+ `ccxt_tiktape.tiktape({"apiKey": ..., "options": {"tiktapeRateLimit": 250}})`.
71
+
72
+ ### Errors
73
+
74
+ | HTTP | CCXT error |
75
+ |---|---|
76
+ | 401 missing or invalid key | `AuthenticationError` |
77
+ | 403 data older than your key's history window | `PermissionDenied` |
78
+ | 429 rate limit or monthly quota | `RateLimitExceeded` |
79
+ | 400 unsupported market or parameter | `BadSymbol` / `BadRequest` |
80
+
81
+ ## Freqtrade
82
+
83
+ Freqtrade cannot load third-party CCXT classes directly. Download candles with
84
+ this package and write them in Freqtrade's data format (for example
85
+ `user_data/data/hyperliquid/BTC_USDC_USDC-1m-futures.feather`), then backtest
86
+ from files.
87
+
88
+ ## Free sample dataset
89
+
90
+ BTC and ETH 1h/1d candles plus hourly funding (Aug-Oct 2026), CC-BY-4.0:
91
+ [download from GitHub releases](https://github.com/tiktape/ccxt-tiktape/releases/tag/sample-dataset-2026-11).
92
+
93
+ ## Development
94
+
95
+ ```bash
96
+ pip install -e ".[test]"
97
+ pytest
98
+ ```
99
+
100
+ Releases are tagged `vX.Y.Z` and published to PyPI by GitHub Actions with trusted
101
+ publishing.
102
+
103
+ ## License
104
+
105
+ MIT. Market data is subject to the [TikTape terms](https://tiktape.xyz/terms-and-conditions).
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ccxt-tiktape"
7
+ dynamic = ["version"]
8
+ description = "Full Hyperliquid OHLCV history in CCXT: a drop-in ccxt.hyperliquid subclass served by TikTape, past the 5000-candle limit."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "TikTape", email = "evan@tiktape.xyz" }]
14
+ keywords = ["ccxt", "hyperliquid", "ohlcv", "candles", "historical-data", "backtesting", "crypto", "funding-rate"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Intended Audience :: Financial and Insurance Industry",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Topic :: Office/Business :: Financial :: Investment",
22
+ ]
23
+ dependencies = ["ccxt>=4.4"]
24
+
25
+ [project.optional-dependencies]
26
+ test = ["pytest>=7"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://tiktape.xyz/?utm_source=pypi&utm_medium=package&utm_campaign=ccxt-tiktape"
30
+ Source = "https://github.com/tiktape/ccxt-tiktape"
31
+ Issues = "https://github.com/tiktape/ccxt-tiktape/issues"
32
+ "API reference" = "https://tiktape.xyz/openapi.yaml"
33
+
34
+ [tool.hatch.version]
35
+ path = "src/ccxt_tiktape/__init__.py"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/ccxt_tiktape"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+
43
+ [tool.hatch.build.targets.sdist]
44
+ exclude = ["sample-dataset", ".github"]
@@ -0,0 +1,9 @@
1
+ """ccxt-tiktape: full Hyperliquid OHLCV history through CCXT, served by TikTape."""
2
+
3
+ __version__ = "0.1.1"
4
+
5
+ from .tiktape import FREE_KEY_URL, TIKTAPE_BASE_URL, tiktape # noqa: E402
6
+
7
+ TikTape = tiktape
8
+
9
+ __all__ = ["tiktape", "TikTape", "TIKTAPE_BASE_URL", "FREE_KEY_URL", "__version__"]
@@ -0,0 +1,256 @@
1
+ """TikTape exchange class: Hyperliquid through CCXT, with full OHLCV history.
2
+
3
+ ``tiktape`` subclasses CCXT's ``hyperliquid`` exchange. Markets, tickers,
4
+ funding rates and every other public method come from Hyperliquid's own API
5
+ through CCXT. ``fetch_ohlcv`` is served by the TikTape API instead, which is not
6
+ capped at Hyperliquid's most recent 5000 candles.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import calendar
12
+ import json
13
+ import time
14
+ from datetime import datetime, timezone
15
+ from typing import Any, Optional
16
+
17
+ import ccxt
18
+ from ccxt.base.errors import (
19
+ AuthenticationError,
20
+ BadRequest,
21
+ BadSymbol,
22
+ ExchangeError,
23
+ PermissionDenied,
24
+ RateLimitExceeded,
25
+ )
26
+
27
+ from . import __version__
28
+
29
+ TIKTAPE_BASE_URL = "https://tiktape.xyz"
30
+ FREE_KEY_URL = "https://tiktape.xyz/?utm_source=pypi&utm_medium=package&utm_campaign=ccxt-tiktape#freeKeyCard"
31
+
32
+ # Server-side maximum for one /api/v1/ohlcv request.
33
+ MAX_LIMIT = 10000
34
+ DEFAULT_LIMIT = 500
35
+ DEFAULT_TIMEOUT_MS = 30000
36
+
37
+ TIMEFRAMES = {
38
+ "1m": "1m",
39
+ "3m": "3m",
40
+ "5m": "5m",
41
+ "15m": "15m",
42
+ "30m": "30m",
43
+ "1h": "1h",
44
+ "2h": "2h",
45
+ "4h": "4h",
46
+ "6h": "6h",
47
+ "8h": "8h",
48
+ "12h": "12h",
49
+ "1d": "1d",
50
+ "3d": "3d",
51
+ "1w": "1w",
52
+ "1M": "1M",
53
+ }
54
+
55
+
56
+ def _month_open(close_ms: int) -> int:
57
+ """Open time of the calendar month (UTC) that a monthly candle closes in."""
58
+ dt = datetime.fromtimestamp(close_ms / 1000, tz=timezone.utc)
59
+ return calendar.timegm((dt.year, dt.month, 1, 0, 0, 0)) * 1000
60
+
61
+
62
+ class tiktape(ccxt.hyperliquid): # noqa: N801 - CCXT exchange classes are lowercase
63
+ def describe(self) -> dict:
64
+ return self.deep_extend(
65
+ super().describe(),
66
+ {
67
+ "id": "tiktape",
68
+ "name": "TikTape (Hyperliquid)",
69
+ "version": "v1",
70
+ "timeframes": TIMEFRAMES,
71
+ "requiredCredentials": {"apiKey": False, "secret": False},
72
+ "urls": {
73
+ "tiktape": TIKTAPE_BASE_URL,
74
+ "doc": [
75
+ "https://tiktape.xyz/openapi.yaml",
76
+ "https://github.com/tiktape/ccxt-tiktape",
77
+ ],
78
+ },
79
+ "options": {
80
+ # Minimum milliseconds between TikTape requests. The free tier
81
+ # allows 60 requests per minute; lower this on a paid key.
82
+ "tiktapeRateLimit": 1000,
83
+ },
84
+ },
85
+ )
86
+
87
+ def __init__(self, config: Optional[dict] = None):
88
+ config = dict(config or {})
89
+ # A 10000-candle page can exceed CCXT's 10 s default on a cold server.
90
+ config.setdefault("timeout", DEFAULT_TIMEOUT_MS)
91
+ super().__init__(config)
92
+ self._tiktape_last_request = 0.0
93
+
94
+ # ------------------------------------------------------------------ OHLCV
95
+
96
+ def fetch_ohlcv(
97
+ self,
98
+ symbol: str,
99
+ timeframe: str = "1m",
100
+ since: Optional[int] = None,
101
+ limit: Optional[int] = None,
102
+ params: dict = {},
103
+ ) -> list:
104
+ """Fetch OHLCV candles for a Hyperliquid market from TikTape.
105
+
106
+ Same contract as CCXT: ``since`` is the earliest candle open time in
107
+ milliseconds, rows are ``[open_time_ms, open, high, low, close, volume]``
108
+ in ascending order. Extra ``params``:
109
+
110
+ - ``until``: latest candle open time (exclusive), in milliseconds.
111
+ - ``paginate``: when ``True``, follow pages from ``since`` until
112
+ ``until`` (or now) or until ``limit`` candles are collected.
113
+ """
114
+ if not self.apiKey:
115
+ raise AuthenticationError(
116
+ self.id + " fetch_ohlcv() requires an apiKey. Get a free 30-day key at " + FREE_KEY_URL
117
+ )
118
+ if timeframe not in TIMEFRAMES:
119
+ raise BadRequest(self.id + " fetch_ohlcv() does not support timeframe " + str(timeframe))
120
+ self.load_markets()
121
+ market = self.market(symbol)
122
+ coin = self.tiktape_coin(market)
123
+ params = dict(params or {})
124
+ until = params.pop("until", None)
125
+ paginate = bool(params.pop("paginate", False))
126
+
127
+ if not paginate:
128
+ request_limit = limit or DEFAULT_LIMIT
129
+ if since is not None:
130
+ # An unaligned `since` matches one partial candle that _finish drops.
131
+ request_limit += 1
132
+ request_limit = min(request_limit, MAX_LIMIT)
133
+ rows = self._tiktape_request(coin, timeframe, since, until, request_limit)
134
+ return self._finish(rows, market, timeframe, since, until, limit)
135
+
136
+ if since is None:
137
+ raise BadRequest(self.id + " fetch_ohlcv() with paginate=True requires since")
138
+ end = until if until is not None else self.milliseconds()
139
+ duration = self.parse_timeframe(timeframe) * 1000
140
+ collected: list = []
141
+ cursor = since
142
+ while cursor < end and (limit is None or len(collected) < limit):
143
+ rows = self._tiktape_request(coin, timeframe, cursor, end, MAX_LIMIT)
144
+ page = self._finish(rows, market, timeframe, cursor, end, None)
145
+ page = [r for r in page if not collected or r[0] > collected[-1][0]]
146
+ if not page:
147
+ break
148
+ collected.extend(page)
149
+ cursor = page[-1][0] + duration
150
+ if len(rows) < MAX_LIMIT:
151
+ break
152
+ if limit is not None:
153
+ collected = collected[:limit]
154
+ return collected
155
+
156
+ def tiktape_coin(self, market: dict) -> str:
157
+ """TikTape ``coin`` parameter for a CCXT market (same as Hyperliquid's)."""
158
+ if market.get("swap"):
159
+ base = self.safe_string(market, "baseName")
160
+ if base:
161
+ return base
162
+ return market["id"]
163
+
164
+ def _finish(self, rows, market, timeframe, since, until, limit) -> list:
165
+ duration = self.parse_timeframe(timeframe) * 1000
166
+ candles = []
167
+ for row in rows:
168
+ close_ms = int(row[0])
169
+ if timeframe == "1M":
170
+ open_ms = _month_open(close_ms)
171
+ else:
172
+ open_ms = close_ms + 1 - duration
173
+ if since is not None and open_ms < since:
174
+ continue
175
+ if until is not None and open_ms >= until:
176
+ continue
177
+ candles.append(
178
+ [open_ms, float(row[1]), float(row[2]), float(row[3]), float(row[4]), float(row[5])]
179
+ )
180
+ candles.sort(key=lambda c: c[0])
181
+ if limit is not None:
182
+ candles = candles[:limit] if since is not None else candles[-limit:]
183
+ return candles
184
+
185
+ def _tiktape_request(self, coin, timeframe, since, until, limit) -> list:
186
+ query = {"coin": coin, "interval": TIMEFRAMES[timeframe], "limit": limit}
187
+ # TikTape filters on candle close time; a candle opening at `since`
188
+ # closes after it, so `since` works as the inclusive start unchanged.
189
+ if since is not None:
190
+ query["startTime"] = int(since)
191
+ if until is not None:
192
+ query["endTime"] = int(until)
193
+ url = self.urls["tiktape"] + "/api/v1/ohlcv?" + self.urlencode(query)
194
+ headers = {
195
+ "X-API-Key": self.apiKey,
196
+ "Accept": "application/json",
197
+ "User-Agent": "ccxt-tiktape/" + __version__,
198
+ }
199
+ self._tiktape_throttle()
200
+ response = self.fetch(url, "GET", headers)
201
+ if not isinstance(response, dict):
202
+ raise ExchangeError(self.id + " unexpected response: " + str(response)[:200])
203
+ return response.get("data") or []
204
+
205
+ def _tiktape_throttle(self) -> None:
206
+ if not self.enableRateLimit:
207
+ return
208
+ gap = self.safe_number(self.options, "tiktapeRateLimit", 0) / 1000.0
209
+ wait = self._tiktape_last_request + gap - time.monotonic()
210
+ if wait > 0:
211
+ time.sleep(wait)
212
+ self._tiktape_last_request = time.monotonic()
213
+
214
+ # ----------------------------------------------------------------- errors
215
+
216
+ def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
217
+ if not url.startswith(self.urls["tiktape"]):
218
+ return super().handle_errors(
219
+ code, reason, url, method, headers, body, response, requestHeaders, requestBody
220
+ )
221
+ if code < 400:
222
+ return None
223
+ message = None
224
+ if isinstance(response, dict):
225
+ message = response.get("error")
226
+ if message is None and body:
227
+ try:
228
+ parsed = json.loads(body)
229
+ message = parsed.get("error") if isinstance(parsed, dict) else parsed
230
+ except ValueError:
231
+ message = body.strip()
232
+ detail = self.id + " " + str(message or reason)
233
+ if code == 401:
234
+ raise AuthenticationError(detail + ". Get a free 30-day key at " + FREE_KEY_URL)
235
+ if code == 403:
236
+ raise PermissionDenied(detail)
237
+ if code == 429:
238
+ raise RateLimitExceeded(detail)
239
+ if code == 400:
240
+ if message and "coin" in str(message):
241
+ raise BadSymbol(detail)
242
+ raise BadRequest(detail)
243
+ raise ExchangeError(detail)
244
+
245
+
246
+ def _register() -> None:
247
+ """Make ``ccxt.tiktape`` available after ``import ccxt_tiktape``."""
248
+ if not hasattr(ccxt, "tiktape"):
249
+ setattr(ccxt, "tiktape", tiktape)
250
+ if "tiktape" not in ccxt.exchanges:
251
+ ccxt.exchanges.append("tiktape")
252
+
253
+
254
+ _register()
255
+
256
+ __all__: list[Any] = ["tiktape", "TIKTAPE_BASE_URL", "FREE_KEY_URL"]
@@ -0,0 +1,180 @@
1
+ import json
2
+ from urllib.parse import parse_qs, urlparse
3
+
4
+ import ccxt
5
+ import pytest
6
+ from ccxt.base.errors import AuthenticationError, BadRequest, BadSymbol, PermissionDenied, RateLimitExceeded
7
+
8
+ import ccxt_tiktape
9
+ from ccxt_tiktape.tiktape import MAX_LIMIT
10
+
11
+ HOUR = 3600 * 1000
12
+ MARKETS = {
13
+ "BTC/USDC:USDC": {
14
+ "id": "0",
15
+ "symbol": "BTC/USDC:USDC",
16
+ "base": "BTC",
17
+ "quote": "USDC",
18
+ "settle": "USDC",
19
+ "baseName": "BTC",
20
+ "swap": True,
21
+ "spot": False,
22
+ "type": "swap",
23
+ },
24
+ "PURR/USDC": {
25
+ "id": "PURR/USDC",
26
+ "symbol": "PURR/USDC",
27
+ "base": "PURR",
28
+ "quote": "USDC",
29
+ "baseName": "PURR",
30
+ "swap": False,
31
+ "spot": True,
32
+ "type": "spot",
33
+ },
34
+ }
35
+
36
+
37
+ def candle(close_ms, price=100.0):
38
+ p = str(price)
39
+ return [close_ms, p, p, p, p, "1.5"]
40
+
41
+
42
+ class FakeTikTape(ccxt_tiktape.tiktape):
43
+ """Exchange with markets preloaded and HTTP replaced by canned pages."""
44
+
45
+ def __init__(self, pages=None, **config):
46
+ config.setdefault("apiKey", "tt_test")
47
+ super().__init__(config)
48
+ self.set_markets(MARKETS)
49
+ self.pages = list(pages or [])
50
+ self.requests = []
51
+ self.enableRateLimit = False
52
+
53
+ def load_markets(self, reload=False, params={}):
54
+ return self.markets
55
+
56
+ def fetch(self, url, method="GET", headers=None, body=None):
57
+ self.requests.append((url, headers))
58
+ page = self.pages.pop(0)
59
+ if isinstance(page, tuple):
60
+ code, payload = page
61
+ text = json.dumps(payload)
62
+ self.handle_errors(code, "error", url, method, {}, text, payload, headers, body)
63
+ raise AssertionError("handle_errors did not raise")
64
+ return {"data": page, "count": len(page)}
65
+
66
+ def query(self, i=-1):
67
+ return {k: v[0] for k, v in parse_qs(urlparse(self.requests[i][0]).query).items()}
68
+
69
+
70
+ def test_import_registers_with_ccxt():
71
+ assert ccxt.tiktape is ccxt_tiktape.tiktape
72
+ assert "tiktape" in ccxt.exchanges
73
+ assert issubclass(ccxt_tiktape.tiktape, ccxt.hyperliquid)
74
+ assert ccxt_tiktape.TikTape is ccxt_tiktape.tiktape
75
+
76
+
77
+ def test_converts_close_time_and_strings_to_ccxt_rows():
78
+ ex = FakeTikTape(pages=[[candle(10 * HOUR - 1, 1.25), candle(11 * HOUR - 1, 2.5)]])
79
+ rows = ex.fetch_ohlcv("BTC/USDC:USDC", "1h", since=9 * HOUR, limit=2)
80
+ assert rows == [[9 * HOUR, 1.25, 1.25, 1.25, 1.25, 1.5], [10 * HOUR, 2.5, 2.5, 2.5, 2.5, 1.5]]
81
+ q = ex.query()
82
+ assert q["coin"] == "BTC"
83
+ assert q["interval"] == "1h"
84
+ assert q["startTime"] == str(9 * HOUR)
85
+ assert q["limit"] == "3"
86
+ assert ex.requests[0][1]["X-API-Key"] == "tt_test"
87
+
88
+
89
+ def test_drops_candle_opening_before_unaligned_since():
90
+ ex = FakeTikTape(pages=[[candle(10 * HOUR - 1), candle(11 * HOUR - 1)]])
91
+ rows = ex.fetch_ohlcv("BTC/USDC:USDC", "1h", since=9 * HOUR + 1, limit=5)
92
+ assert [r[0] for r in rows] == [10 * HOUR]
93
+
94
+
95
+ def test_limit_without_since_keeps_latest():
96
+ ex = FakeTikTape(pages=[[candle(h * HOUR - 1) for h in range(1, 6)]])
97
+ rows = ex.fetch_ohlcv("BTC/USDC:USDC", "1h", limit=2)
98
+ assert [r[0] for r in rows] == [3 * HOUR, 4 * HOUR]
99
+ assert "startTime" not in ex.query()
100
+
101
+
102
+ def test_until_is_exclusive_on_open_time():
103
+ ex = FakeTikTape(pages=[[candle(h * HOUR - 1) for h in range(1, 4)]])
104
+ rows = ex.fetch_ohlcv("BTC/USDC:USDC", "1h", since=0, params={"until": 2 * HOUR})
105
+ assert [r[0] for r in rows] == [0, HOUR]
106
+ assert ex.query()["endTime"] == str(2 * HOUR)
107
+
108
+
109
+ def test_monthly_candles_open_on_first_of_month():
110
+ # 2026-02-28T23:59:59.999Z closes the February candle.
111
+ ex = FakeTikTape(pages=[[candle(1772323199999)]])
112
+ rows = ex.fetch_ohlcv("BTC/USDC:USDC", "1M", limit=1)
113
+ assert rows[0][0] == 1769904000000 # 2026-02-01T00:00:00Z
114
+
115
+
116
+ def test_spot_market_uses_market_id():
117
+ ex = FakeTikTape(pages=[[candle(HOUR - 1)]])
118
+ ex.fetch_ohlcv("PURR/USDC", "1h", limit=1)
119
+ assert ex.query()["coin"] == "PURR/USDC"
120
+
121
+
122
+ def test_paginate_follows_pages_until_short_page():
123
+ first = [candle((h + 1) * HOUR - 1) for h in range(MAX_LIMIT)]
124
+ second = [candle((h + 1) * HOUR - 1) for h in range(MAX_LIMIT, MAX_LIMIT + 5)]
125
+ ex = FakeTikTape(pages=[first, second])
126
+ rows = ex.fetch_ohlcv(
127
+ "BTC/USDC:USDC", "1h", since=0, params={"paginate": True, "until": (MAX_LIMIT + 10) * HOUR}
128
+ )
129
+ assert len(rows) == MAX_LIMIT + 5
130
+ assert rows[0][0] == 0 and rows[-1][0] == (MAX_LIMIT + 4) * HOUR
131
+ assert ex.query(1)["startTime"] == str(MAX_LIMIT * HOUR)
132
+
133
+
134
+ def test_paginate_respects_limit():
135
+ first = [candle((h + 1) * HOUR - 1) for h in range(MAX_LIMIT)]
136
+ ex = FakeTikTape(pages=[first, first])
137
+ rows = ex.fetch_ohlcv("BTC/USDC:USDC", "1h", since=0, limit=7, params={"paginate": True})
138
+ assert len(rows) == 7
139
+ assert len(ex.requests) == 1
140
+
141
+
142
+ def test_paginate_requires_since():
143
+ with pytest.raises(BadRequest):
144
+ FakeTikTape().fetch_ohlcv("BTC/USDC:USDC", "1h", params={"paginate": True})
145
+
146
+
147
+ def test_missing_api_key_points_to_free_key():
148
+ ex = FakeTikTape(apiKey="")
149
+ with pytest.raises(AuthenticationError, match="free 30-day key"):
150
+ ex.fetch_ohlcv("BTC/USDC:USDC", "1h")
151
+
152
+
153
+ def test_unsupported_timeframe():
154
+ with pytest.raises(BadRequest):
155
+ FakeTikTape().fetch_ohlcv("BTC/USDC:USDC", "7m")
156
+
157
+
158
+ @pytest.mark.parametrize(
159
+ "code,payload,error",
160
+ [
161
+ (401, "invalid or missing API key", AuthenticationError),
162
+ (403, {"error": "free API keys can read only the most recent 30 days", "code": "history_limit"}, PermissionDenied),
163
+ (429, "rate limit exceeded", RateLimitExceeded),
164
+ (400, {"error": "unsupported coin: XYZ"}, BadSymbol),
165
+ (400, {"error": "limit must be 1-10000"}, BadRequest),
166
+ ],
167
+ )
168
+ def test_http_errors_map_to_ccxt_errors(code, payload, error):
169
+ ex = FakeTikTape(pages=[(code, payload)])
170
+ with pytest.raises(error):
171
+ ex.fetch_ohlcv("BTC/USDC:USDC", "1h", limit=1)
172
+
173
+
174
+ def test_timeframes_include_6h():
175
+ assert "6h" in ccxt_tiktape.tiktape().timeframes
176
+
177
+
178
+ def test_default_timeout_is_raised_but_overridable():
179
+ assert ccxt_tiktape.tiktape().timeout == 30000
180
+ assert ccxt_tiktape.tiktape({"timeout": 5000}).timeout == 5000