|
| 1 | +import asyncio |
| 2 | +import gzip |
| 3 | +import json |
| 4 | +import urllib.error |
| 5 | +import urllib.parse |
| 6 | +from typing import Any, Dict, List, Literal, Mapping, Optional, Sequence, TypedDict, Union |
| 7 | + |
| 8 | +from tardis_dev._http import create_session |
| 9 | +from tardis_dev._options import DEFAULT_ENDPOINT |
| 10 | + |
| 11 | + |
| 12 | +InstrumentInfo = Dict[str, Any] |
| 13 | +InstrumentInfoFilterValue = Union[str, Sequence[str]] |
| 14 | + |
| 15 | + |
| 16 | +class InstrumentInfoFilter(TypedDict, total=False): |
| 17 | + baseCurrency: InstrumentInfoFilterValue |
| 18 | + quoteCurrency: InstrumentInfoFilterValue |
| 19 | + type: InstrumentInfoFilterValue |
| 20 | + contractType: InstrumentInfoFilterValue |
| 21 | + underlyingType: InstrumentInfoFilterValue |
| 22 | + active: bool |
| 23 | + availableSince: str |
| 24 | + availableTo: str |
| 25 | + |
| 26 | + |
| 27 | +class InstrumentSymbols(TypedDict): |
| 28 | + exchange: str |
| 29 | + symbols: List[str] |
| 30 | + |
| 31 | + |
| 32 | +InstrumentSymbolSelector = Literal["id", "datasetId"] |
| 33 | + |
| 34 | + |
| 35 | +def get_instrument_info( |
| 36 | + exchange: Union[str, Sequence[str]], |
| 37 | + *, |
| 38 | + filter: Optional[Mapping[str, Any]] = None, |
| 39 | + symbol: Optional[str] = None, |
| 40 | + api_key: str = "", |
| 41 | + endpoint: str = DEFAULT_ENDPOINT, |
| 42 | + timeout: int = 60, |
| 43 | + http_proxy: Optional[str] = None, |
| 44 | +) -> Union[InstrumentInfo, List[InstrumentInfo]]: |
| 45 | + try: |
| 46 | + asyncio.get_running_loop() |
| 47 | + except RuntimeError: |
| 48 | + return asyncio.run( |
| 49 | + get_instrument_info_async( |
| 50 | + exchange=exchange, |
| 51 | + filter=filter, |
| 52 | + symbol=symbol, |
| 53 | + api_key=api_key, |
| 54 | + endpoint=endpoint, |
| 55 | + timeout=timeout, |
| 56 | + http_proxy=http_proxy, |
| 57 | + ) |
| 58 | + ) |
| 59 | + |
| 60 | + raise RuntimeError( |
| 61 | + "get_instrument_info() cannot be called from a running event loop. Use get_instrument_info_async() instead." |
| 62 | + ) |
| 63 | + |
| 64 | + |
| 65 | +async def get_instrument_info_async( |
| 66 | + exchange: Union[str, Sequence[str]], |
| 67 | + *, |
| 68 | + filter: Optional[Mapping[str, Any]] = None, |
| 69 | + symbol: Optional[str] = None, |
| 70 | + api_key: str = "", |
| 71 | + endpoint: str = DEFAULT_ENDPOINT, |
| 72 | + timeout: int = 60, |
| 73 | + http_proxy: Optional[str] = None, |
| 74 | +) -> Union[InstrumentInfo, List[InstrumentInfo]]: |
| 75 | + if filter is not None and symbol is not None: |
| 76 | + raise ValueError("Provide either 'filter' or 'symbol', not both.") |
| 77 | + |
| 78 | + if symbol is not None and not isinstance(exchange, str): |
| 79 | + raise ValueError("'symbol' can only be used with a single exchange.") |
| 80 | + |
| 81 | + async with await create_session(api_key, timeout) as session: |
| 82 | + if isinstance(exchange, str): |
| 83 | + return await _get_instrument_info( |
| 84 | + session=session, |
| 85 | + exchange=exchange, |
| 86 | + filter=filter, |
| 87 | + symbol=symbol, |
| 88 | + endpoint=endpoint, |
| 89 | + http_proxy=http_proxy, |
| 90 | + ) |
| 91 | + |
| 92 | + results = await asyncio.gather( |
| 93 | + *( |
| 94 | + _get_instrument_info( |
| 95 | + session=session, |
| 96 | + exchange=exchange_id, |
| 97 | + filter=filter, |
| 98 | + endpoint=endpoint, |
| 99 | + http_proxy=http_proxy, |
| 100 | + ) |
| 101 | + for exchange_id in exchange |
| 102 | + ) |
| 103 | + ) |
| 104 | + |
| 105 | + return [instrument for instruments in results for instrument in instruments] |
| 106 | + |
| 107 | + |
| 108 | +def find_instrument_symbols( |
| 109 | + exchanges: Sequence[str], |
| 110 | + filter: Mapping[str, Any], |
| 111 | + *, |
| 112 | + selector: InstrumentSymbolSelector = "id", |
| 113 | + api_key: str = "", |
| 114 | + endpoint: str = DEFAULT_ENDPOINT, |
| 115 | + timeout: int = 60, |
| 116 | + http_proxy: Optional[str] = None, |
| 117 | +) -> List[InstrumentSymbols]: |
| 118 | + try: |
| 119 | + asyncio.get_running_loop() |
| 120 | + except RuntimeError: |
| 121 | + return asyncio.run( |
| 122 | + find_instrument_symbols_async( |
| 123 | + exchanges=exchanges, |
| 124 | + filter=filter, |
| 125 | + selector=selector, |
| 126 | + api_key=api_key, |
| 127 | + endpoint=endpoint, |
| 128 | + timeout=timeout, |
| 129 | + http_proxy=http_proxy, |
| 130 | + ) |
| 131 | + ) |
| 132 | + |
| 133 | + raise RuntimeError( |
| 134 | + "find_instrument_symbols() cannot be called from a running event loop. Use find_instrument_symbols_async() instead." |
| 135 | + ) |
| 136 | + |
| 137 | + |
| 138 | +async def find_instrument_symbols_async( |
| 139 | + exchanges: Sequence[str], |
| 140 | + filter: Mapping[str, Any], |
| 141 | + *, |
| 142 | + selector: InstrumentSymbolSelector = "id", |
| 143 | + api_key: str = "", |
| 144 | + endpoint: str = DEFAULT_ENDPOINT, |
| 145 | + timeout: int = 60, |
| 146 | + http_proxy: Optional[str] = None, |
| 147 | +) -> List[InstrumentSymbols]: |
| 148 | + _validate_selector(selector) |
| 149 | + |
| 150 | + async with await create_session(api_key, timeout) as session: |
| 151 | + return await asyncio.gather( |
| 152 | + *( |
| 153 | + _find_instrument_symbols_for_exchange( |
| 154 | + session=session, |
| 155 | + exchange=exchange, |
| 156 | + filter=filter, |
| 157 | + selector=selector, |
| 158 | + endpoint=endpoint, |
| 159 | + http_proxy=http_proxy, |
| 160 | + ) |
| 161 | + for exchange in exchanges |
| 162 | + ) |
| 163 | + ) |
| 164 | + |
| 165 | + |
| 166 | +def _validate_selector(selector: str) -> None: |
| 167 | + if selector not in ("id", "datasetId"): |
| 168 | + raise ValueError("Invalid 'selector' argument. Supported values are 'id' and 'datasetId'.") |
| 169 | + |
| 170 | + |
| 171 | +async def _find_instrument_symbols_for_exchange( |
| 172 | + *, |
| 173 | + session, |
| 174 | + exchange: str, |
| 175 | + filter: Mapping[str, Any], |
| 176 | + selector: InstrumentSymbolSelector, |
| 177 | + endpoint: str, |
| 178 | + http_proxy: Optional[str], |
| 179 | +) -> InstrumentSymbols: |
| 180 | + instruments = await _get_instrument_info( |
| 181 | + session=session, |
| 182 | + exchange=exchange, |
| 183 | + filter=filter, |
| 184 | + symbol=None, |
| 185 | + endpoint=endpoint, |
| 186 | + http_proxy=http_proxy, |
| 187 | + ) |
| 188 | + |
| 189 | + return { |
| 190 | + "exchange": exchange, |
| 191 | + "symbols": [_get_symbol(instrument, selector) for instrument in instruments], |
| 192 | + } |
| 193 | + |
| 194 | + |
| 195 | +async def _get_instrument_info( |
| 196 | + *, |
| 197 | + session, |
| 198 | + exchange: str, |
| 199 | + filter: Optional[Mapping[str, Any]], |
| 200 | + symbol: Optional[str] = None, |
| 201 | + endpoint: str, |
| 202 | + http_proxy: Optional[str], |
| 203 | +) -> Union[InstrumentInfo, List[InstrumentInfo]]: |
| 204 | + url = _get_instrument_info_url(endpoint, exchange, filter, symbol) |
| 205 | + |
| 206 | + async with session.get(url, proxy=http_proxy) as response: |
| 207 | + body = await response.read() |
| 208 | + if response.headers.get("Content-Encoding") == "gzip": |
| 209 | + body = gzip.decompress(body) |
| 210 | + |
| 211 | + if response.status != 200: |
| 212 | + error_text = body.decode("utf-8", errors="replace") |
| 213 | + raise urllib.error.HTTPError(url, code=response.status, msg=error_text, hdrs=None, fp=None) |
| 214 | + |
| 215 | + return json.loads(body.decode("utf-8")) |
| 216 | + |
| 217 | + |
| 218 | +def _get_instrument_info_url( |
| 219 | + endpoint: str, |
| 220 | + exchange: str, |
| 221 | + filter: Optional[Mapping[str, Any]], |
| 222 | + symbol: Optional[str], |
| 223 | +) -> str: |
| 224 | + url = f"{endpoint}/instruments/{urllib.parse.quote(exchange, safe='')}" |
| 225 | + if symbol is not None: |
| 226 | + return f"{url}/{urllib.parse.quote(symbol, safe='')}" |
| 227 | + |
| 228 | + if filter is not None: |
| 229 | + encoded_filter = urllib.parse.quote(json.dumps(filter, separators=(",", ":"))) |
| 230 | + return f"{url}?filter={encoded_filter}" |
| 231 | + |
| 232 | + return url |
| 233 | + |
| 234 | + |
| 235 | +def _get_symbol(instrument: Mapping[str, Any], selector: InstrumentSymbolSelector) -> str: |
| 236 | + if selector == "datasetId": |
| 237 | + return instrument.get("datasetId") or instrument["id"] |
| 238 | + |
| 239 | + return instrument["id"] |
0 commit comments