├── .gitignore ├── LICENSE ├── README.rst ├── cryptowatch ├── __init__.py ├── api_client.py └── exceptions.py ├── docs ├── Makefile ├── conf.py ├── cryptowatch.rst ├── exceptions.rst ├── general.rst ├── index.rst └── overview.rst ├── requirements.txt ├── requirements_test.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── conftest.py └── test_api_client.py └── version.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # My ignores 2 | ENV*/ 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | env/ 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # SageMath parsed files 83 | *.sage.py 84 | 85 | # dotenv 86 | .env 87 | 88 | # virtualenv 89 | .venv 90 | venv/ 91 | ENV/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 uoshvis 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. 22 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ================== 2 | python-cryptowatch 3 | ================== 4 | 5 | This is an unofficial Python wrapper for the `Cryptowatch public Data API `_. 6 | Cryptowatch is a cryptocurrency charting and trading platform owned by `Kraken exchange `_. 7 | 8 | 9 | Source code 10 | https://github.com/uoshvis/python-cryptowatch 11 | 12 | Documentation 13 | https://python-cryptowatch.readthedocs.io/en/latest/ 14 | 15 | 16 | Quick Start 17 | ----------- 18 | 19 | .. code:: python 20 | 21 | from cryptowatch.api_client import Client 22 | client = Client() 23 | 24 | # get assets 25 | assets = client.get_assets() 26 | 27 | # get markets which have btc as base or quote 28 | assets_btc = client.get_assets('btc') 29 | 30 | """ 31 | Returns a market's OHLC candlestick data. 32 | This represents a 1-hour candle starting at 1594087200 (Tuesday, 33 | 7 July 2020 02:00:00 GMT) and ending at 1602179348 (Thursday, 34 | 8 October 2020 17:49:08 GMT). 35 | """ 36 | 37 | data = { 38 | 'exchange': 'gdax', 39 | 'pair': 'btcusd', 40 | 'route': 'ohlc', 41 | 'params': { 42 | 'before': 1602179348, 43 | 'after': 1594087200, 44 | 'periods': '3600'} 45 | } 46 | 47 | market = client.get_markets(data=data) 48 | 49 | For more `check out the documentation `_. 50 | -------------------------------------------------------------------------------- /cryptowatch/__init__.py: -------------------------------------------------------------------------------- 1 | """An unofficial Python wrapper for the Cryptowatch public API 2 | .. moduleauthor:: uoshvis 3 | """ 4 | -------------------------------------------------------------------------------- /cryptowatch/api_client.py: -------------------------------------------------------------------------------- 1 | """Module related to the client interface to cryptowat.ch API.""" 2 | 3 | from urllib.parse import quote_plus, urlencode 4 | import requests 5 | from cryptowatch.exceptions import ( 6 | CryptowatchAPIException, 7 | CryptowatchResponseException 8 | ) 9 | 10 | 11 | class Client(object): 12 | """The public client to the cryptowat.ch api.""" 13 | 14 | API_URL = 'https://api.cryptowat.ch' 15 | ROUTES_MARKET = ['price', 'summary', 'orderbook', 'trades', 'ohlc'] 16 | ROUTES_PARAMS = ['trades', 'ohlc'] 17 | ROUTES_AGGREGATE = ['prices', 'summaries'] 18 | 19 | def __init__(self): 20 | self.uri = 'https://api.cryptowat.ch' 21 | self.session = self._init_session() 22 | 23 | @staticmethod 24 | def _init_session(): 25 | session = requests.Session() 26 | session.headers.update({'Accept': 'application/json', 27 | 'User-Agent': 'cryptowatch/python'}) 28 | return session 29 | 30 | @staticmethod 31 | def _encode_params(**kwargs): 32 | data = kwargs.get('data', None) 33 | payload = {} 34 | if "params" in data and 'apikey' in data['params']: 35 | payload['apikey'] = data['params']['apikey'] 36 | if data['route'] == 'trades': 37 | params = data['params'] 38 | if 'limit' in params: 39 | payload['limit'] = params['limit'] 40 | if 'since' in params: 41 | payload['since'] = params['since'] 42 | elif data['route'] == 'ohlc': 43 | params = data['params'] 44 | if 'before' in params: 45 | payload['before'] = params['before'] 46 | if 'after' in params: 47 | payload['after'] = params['after'] 48 | if 'periods' in params: 49 | payload['periods'] = params['periods'] 50 | 51 | return urlencode(payload, quote_via=quote_plus) 52 | 53 | def _request(self, method, uri): 54 | response = getattr(self.session, method)(uri) 55 | return self._handle_response(response) 56 | 57 | def _create_uri(self, path, symbol): 58 | uri = self.API_URL + '/' + path 59 | if symbol: 60 | uri += '/' + symbol 61 | return uri 62 | 63 | def _request_api(self, method, path, symbol): 64 | uri = self._create_uri(path, symbol) 65 | return self._request(method, uri) 66 | 67 | def _get(self, path, symbol=None): 68 | return self._request_api('get', path, symbol) 69 | 70 | @staticmethod 71 | def _handle_response(response): 72 | if not str(response.status_code).startswith('2'): 73 | raise CryptowatchAPIException(response) 74 | try: 75 | return response.json() 76 | except ValueError: 77 | raise CryptowatchResponseException('Invalid Response: %s' % response.text) 78 | 79 | def get_assets(self, asset=None): 80 | """An asset can be a crypto or fiat currency. 81 | 82 | **Index** 83 | 84 | .. code-block:: python 85 | 86 | get_assets() 87 | 88 | :returns: API response 89 | 90 | .. code-block:: python 91 | 92 | { 93 | "result": [ 94 | { 95 | "symbol": "aud", 96 | "name": "Australian Dollar", 97 | "fiat": true, 98 | "route": "https://api.cryptowat.ch/assets/aud" 99 | }, 100 | { 101 | "symbol": "etc", 102 | "name": "Ethereum Classic", 103 | "fiat": false, 104 | "route": "https://api.cryptowat.ch/assets/etc" 105 | }, 106 | ... 107 | ] 108 | } 109 | 110 | **Asset** 111 | 112 | Returns a single asset. 113 | Lists all markets which have this asset as a base or quote. 114 | 115 | .. code-block:: python 116 | 117 | get_assets('btc') 118 | 119 | :returns: API response 120 | 121 | .. code-block:: python 122 | 123 | { 124 | "result": { 125 | "symbol": "btc", 126 | "name": "Bitcoin", 127 | "fiat": false, 128 | "markets": { 129 | "base": [ 130 | { 131 | "exchange": "bitfinex", 132 | "pair": "btcusd", 133 | "active": true, 134 | "route": "https://api.cryptowat.ch/markets/bitfinex/btcusd" 135 | }, 136 | { 137 | "exchange": "gdax", 138 | "pair": "btcusd", 139 | "route": "https://api.cryptowat.ch/markets/gdax/btcusd" 140 | }, 141 | ... 142 | ], 143 | "quote": [ 144 | { 145 | "exchange": "bitfinex", 146 | "pair": "ltcbtc", 147 | "active": true, 148 | "route": "https://api.cryptowat.ch/markets/bitfinex/ltcbtc" 149 | }, 150 | { 151 | "exchange": "bitfinex", 152 | "pair": "ethbtc", 153 | "active": true, 154 | "route": "https://api.cryptowat.ch/markets/bitfinex/ethbtc" 155 | }, 156 | ... 157 | ] 158 | } 159 | } 160 | } 161 | 162 | """ 163 | 164 | if asset: 165 | return self._get('assets', asset) 166 | 167 | return self._get('assets') 168 | 169 | def get_pairs(self, pair=None): 170 | """A pair of assets. Each pair has a base and a quote. 171 | For example, btceur has base btc and quote eur. 172 | 173 | **Index** 174 | 175 | All pairs (in no particular order). 176 | 177 | .. code-block:: python 178 | 179 | get_pairs() 180 | 181 | :returns: API response 182 | 183 | .. code-block:: python 184 | 185 | { 186 | "result": [ 187 | { 188 | "symbol": "xmrusd", 189 | "id": 82, 190 | "base": { 191 | "symbol": "xmr", 192 | "name": "Monero", 193 | "fiat": false, 194 | "route": "https://api.cryptowat.ch/assets/xmr" 195 | }, 196 | "quote": { 197 | "symbol": "usd", 198 | "name": "United States dollar", 199 | "fiat": true, 200 | "route": "https://api.cryptowat.ch/assets/usd" 201 | }, 202 | "route": "https://api.cryptowat.ch/pairs/xmrusd" 203 | }, 204 | { 205 | "symbol": "ltcusd", 206 | "id": 189, 207 | "base": { 208 | "symbol": "ltc", 209 | "name": "Litecoin", 210 | "fiat": false, 211 | "route": "https://api.cryptowat.ch/assets/ltc" 212 | }, 213 | "quote": { 214 | "symbol": "usd", 215 | "name": "United States dollar", 216 | "fiat": true, 217 | "route": "https://api.cryptowat.ch/assets/usd" 218 | }, 219 | "route": "https://api.cryptowat.ch/pairs/ltcusd" 220 | }, 221 | ... 222 | ] 223 | } 224 | 225 | **Pair** 226 | 227 | Returns a single pair. Lists all markets for this pair. 228 | 229 | .. code-block:: python 230 | 231 | get_pairs('ethbtc') 232 | 233 | :returns: API response 234 | 235 | .. code-block:: python 236 | 237 | { 238 | "result": { 239 | "symbol": "ethbtc", 240 | "id": 23, 241 | "base": { 242 | "symbol": "eth", 243 | "name": "Ethereum", 244 | "isFiat": false, 245 | "route": "https://api.cryptowat.ch/assets/eth" 246 | }, 247 | "quote": { 248 | "symbol": "btc", 249 | "name": "Bitcoin", 250 | "isFiat": false, 251 | "route": "https://api.cryptowat.ch/assets/btc" 252 | }, 253 | "route": "https://api.cryptowat.ch/pairs/ethbtc", 254 | "markets": [ 255 | { 256 | "exchange": "bitfinex", 257 | "pair": "ethbtc", 258 | "active": true, 259 | "route": "https://api.cryptowat.ch/markets/bitfinex/ethbtc" 260 | }, 261 | { 262 | "exchange": "gdax", 263 | "pair": "ethbtc", 264 | "active": true, 265 | "route": "https://api.cryptowat.ch/markets/gdax/ethbtc" 266 | }, 267 | ... 268 | ] 269 | } 270 | } 271 | 272 | """ 273 | 274 | if pair: 275 | return self._get('pairs', pair) 276 | 277 | return self._get('pairs') 278 | 279 | def get_exchanges(self, exchange=None): 280 | """Exchanges are where all the action happens! 281 | 282 | **Index** 283 | 284 | Returns a list of all supported exchanges. 285 | 286 | .. code-block:: python 287 | 288 | get_exchanges() 289 | 290 | :returns: API response 291 | 292 | .. code-block:: python 293 | 294 | { 295 | "result": [ 296 | { 297 | "symbol": "bitfinex", 298 | "name": "Bitfinex", 299 | "active": true, 300 | "route": "https://api.cryptowat.ch/exchanges/bitfinex" 301 | }, 302 | { 303 | "symbol": "gdax", 304 | "name": "GDAX", 305 | "active": true, 306 | "route": "https://api.cryptowat.ch/exchanges/gdax" 307 | }, 308 | ... 309 | ] 310 | } 311 | 312 | **Exchange** 313 | 314 | Returns a single exchange, with associated routes. 315 | 316 | .. code-block:: python 317 | 318 | get_exchanges('kraken') 319 | 320 | :returns: API response 321 | 322 | .. code-block:: python 323 | 324 | { 325 | "result": { 326 | "id": "kraken", 327 | "name": "Kraken", 328 | "active": true, 329 | "routes": { 330 | "markets": "https://api.cryptowat.ch/markets/kraken" 331 | } 332 | } 333 | } 334 | 335 | """ 336 | if exchange: 337 | return self._get('exchanges', exchange) 338 | 339 | return self._get('exchanges') 340 | 341 | def get_markets(self, path=None, **kwargs): 342 | 343 | """ 344 | A market is a pair listed on an exchange. 345 | For example, pair btceur on exchange kraken is a market. 346 | 347 | **Index** 348 | 349 | Returns a list of all supported markets. 350 | 351 | .. code-block:: python 352 | 353 | get_markets() 354 | 355 | :returns: API response 356 | 357 | .. code-block:: python 358 | 359 | { 360 | "result": [ 361 | { 362 | "exchange": "bitfinex", 363 | "pair": "btcusd", 364 | "active": true, 365 | "route": "https://api.cryptowat.ch/markets/bitfinex/btcusd" 366 | }, 367 | { 368 | "exchange": "bitfinex", 369 | "pair": "ltcusd" 370 | "active": true, 371 | "route": "https://api.cryptowat.ch/markets/bitfinex/ltcusd" 372 | }, 373 | { 374 | "exchange": "bitfinex", 375 | "pair": "ltcbtc" 376 | "active": true, 377 | "route": "https://api.cryptowat.ch/markets/bitfinex/ltcbtc" 378 | }, 379 | ... 380 | ] 381 | } 382 | 383 | To get the supported markets for only a specific exchange: 384 | 385 | .. code-block:: python 386 | 387 | get_markets('kraken') 388 | 389 | **Market** 390 | 391 | Returns a single market, with associated routes. 392 | 393 | :param exchange: required 394 | :type exchange: str 395 | :param pair: required 396 | :type pair: str 397 | 398 | .. code-block:: python 399 | 400 | data = { 401 | 'exchange': 'gdax', 402 | 'pair': 'btcusd' 403 | } 404 | 405 | .. code-block:: python 406 | 407 | get_markets(data=data) 408 | 409 | :returns: API response 410 | 411 | .. code-block:: python 412 | 413 | { 414 | "result": { 415 | "exchange": "gdax", 416 | "pair": "btcusd", 417 | "active": true, 418 | "routes": { 419 | "price": "https://api.cryptowat.ch/markets/gdax/btcusd/price", 420 | "summary": "https://api.cryptowat.ch/markets/gdax/btcusd/summary", 421 | "orderbook": "https://api.cryptowat.ch/markets/gdax/btcusd/orderbook", 422 | "trades": "https://api.cryptowat.ch/markets/gdax/btcusd/trades", 423 | "ohlc": "https://api.cryptowat.ch/markets/gdax/btcusd/ohlc" 424 | } 425 | } 426 | } 427 | 428 | **Price** 429 | 430 | Returns a market’s last price. 431 | 432 | :param exchange: required 433 | :type exchange: str 434 | :param pair: required 435 | :type pair: str 436 | :param route: 'price' 437 | :type route: str 438 | 439 | .. code-block:: python 440 | 441 | data = { 442 | 'exchange': 'gdax', 443 | 'pair': 'btcusd', 444 | 'route': 'price' 445 | } 446 | 447 | .. code-block:: python 448 | 449 | get_markets(data=data) 450 | 451 | :returns: API response 452 | 453 | .. code-block:: python 454 | 455 | { 456 | "result": { 457 | "price": 780.63 458 | } 459 | } 460 | 461 | **Summary** 462 | 463 | Returns a market’s last price as well as other stats 464 | based on a 24-hour sliding window. 465 | 466 | :param exchange: required 467 | :type exchange: str 468 | :param pair: required 469 | :type pair: str 470 | :param route: 'summary' 471 | :type route: str 472 | 473 | .. code-block:: python 474 | 475 | data = { 476 | 'exchange': 'gdax', 477 | 'pair': 'btcusd', 478 | 'route': 'summary' 479 | } 480 | 481 | .. code-block:: python 482 | 483 | get_markets(data=data) 484 | 485 | :returns: API response 486 | 487 | .. code-block:: python 488 | 489 | { 490 | "result": { 491 | "price":{ 492 | "last": 780.31, 493 | "high": 790.34, 494 | "low": 772.76, 495 | "change": { 496 | "percentage": 0.0014373838, 497 | "absolute": 1.12 498 | } 499 | }, 500 | "volume": 5345.0415 501 | } 502 | } 503 | 504 | **Trades** 505 | 506 | Returns a market’s most recent trades, incrementing chronologically. 507 | 508 | :param exchange: required 509 | :type exchange: str 510 | :param pair: required 511 | :type pair: str 512 | :param route: 'trades' 513 | :type route: str 514 | :param params: supported params 515 | :type params: dict 516 | :param params.limit: limit amount of trades returned 517 | :type params.limit: int (defaults to 50) 518 | :param params.since: only return trades at or after this time. 519 | :type params.since: UNIX timestamp 520 | 521 | .. code-block:: python 522 | 523 | data = { 524 | 'exchange': 'gdax', 525 | 'pair': 'btcusd', 526 | 'route': 'trades', 527 | 'params': {'limit': 10, 'since': 1481663244 } 528 | } 529 | .. code-block:: python 530 | 531 | get_markets(data=data) 532 | 533 | :returns: API response 534 | 535 | .. code-block:: python 536 | 537 | { 538 | "result": [ 539 | [ 540 | 0, 541 | 1481676478, 542 | 734.39, 543 | 0.1249 544 | ], 545 | [ 546 | 0, 547 | 1481676537, 548 | 734.394, 549 | 0.0744 550 | ], 551 | [ 552 | 0, 553 | 1481676581, 554 | 734.396, 555 | 0.1 556 | ], 557 | [ 558 | 0, 559 | 1481676602, 560 | 733.45, 561 | 0.061 562 | ], 563 | ... 564 | ] 565 | } 566 | 567 | Trades are lists of numbers in this order: 568 | 569 | .. code-block:: python 570 | 571 | [ ID, Timestamp, Price, Amount ] 572 | 573 | **Order Book** 574 | 575 | To get market's order book use 'orderbook' route. 576 | 577 | :param exchange: required 578 | :type exchange: str 579 | :param pair: required 580 | :type pair: str 581 | :param route: 'orderbook' 582 | :type route: str 583 | 584 | .. code-block:: python 585 | 586 | data = { 587 | 'exchange': 'gdax', 588 | 'pair': 'btcusd', 589 | 'route': 'orderbook' 590 | } 591 | 592 | :returns: API response 593 | 594 | .. code-block:: python 595 | 596 | { 597 | "result": { 598 | "asks": [ 599 | [ 600 | 733.73, 601 | 2.251 602 | ], 603 | [ 604 | 733.731, 605 | 7.829 606 | ], 607 | [ 608 | 733.899, 609 | 1.417 610 | ], 611 | ... 612 | ], 613 | "bids": [ 614 | [ 615 | 733.62, 616 | 0.273 617 | ], 618 | ... 619 | ] 620 | ] 621 | } 622 | 623 | Orders are lists of numbers in this order: 624 | 625 | .. code-block:: python 626 | 627 | [ Price, Amount ] 628 | 629 | **OHLC** 630 | 631 | Returns a market’s OHLC candlestick data. 632 | Returns data as lists of lists of numbers for each time period integer. 633 | 634 | :param exchange: required 635 | :type exchange: str 636 | :param pair: required 637 | :type pair: str 638 | :param route: 'ohlc' 639 | :type route: str 640 | :param params: supported params 641 | :type params: dict 642 | :param params.before: Only return candles opening before this time 643 | :type params.before: int (defaults to 50) 644 | :param params.after: Only return candles opening after this time 645 | :type params.after: UNIX timestamp 646 | :param params.periods: return these time periods 647 | :type params.periods: Comma-separated integers 60,180,108000 648 | 649 | .. code-block:: python 650 | 651 | data = { 652 | 'exchange': 'gdax', 653 | 'pair': 'btcusd', 654 | 'route': 'ohlc' 655 | 'params': { 656 | 'before': 1481663244, 657 | 'after': 1481663244, 658 | 'periods': '60,180' 659 | } 660 | } 661 | 662 | .. code-block:: python 663 | 664 | get_markets(data=data) 665 | 666 | Return values are in list: 667 | 668 | .. code-block:: python 669 | 670 | [ CloseTime, OpenPrice, HighPrice, LowPrice, ClosePrice, Volume, QuoteVolume] 671 | 672 | """ 673 | 674 | data = kwargs.get('data', None) 675 | if data and isinstance(data, dict): 676 | if 'exchange' in data: 677 | path = data['exchange'] 678 | if 'pair' in data: 679 | path += '/' + data['pair'] 680 | if 'route' in data and data['route'] in self.ROUTES_MARKET: 681 | path += '/' + data['route'] 682 | if data['route'] in self.ROUTES_PARAMS and 'params' in data: 683 | path += '?' + self._encode_params(path=path, data=data) 684 | if path: 685 | return self._get('markets', path) 686 | 687 | return self._get('markets') 688 | 689 | def get_aggregates(self, *args): 690 | """Retrieves the prices and summaries of all markets 691 | on the site in a single request. 692 | 693 | **Prices** 694 | 695 | To get the current price for all supported markets use: 696 | 697 | .. code-block:: python 698 | 699 | get_aggregates('prices') 700 | 701 | :returns: API response 702 | 703 | .. code-block:: python 704 | 705 | { 706 | "result": { 707 | { 708 | "bitfinex:bfxbtc": 0.00067133, 709 | "bitfinex:bfxusd": 0.52929, 710 | "bitfinex:btcusd": 776.73, 711 | ... 712 | } 713 | } 714 | } 715 | 716 | **Summaries** 717 | 718 | To get the market summary for all supported markets use: 719 | 720 | .. code-block:: python 721 | 722 | get_aggregates('summaries') 723 | 724 | :returns: API response 725 | 726 | .. code-block:: python 727 | 728 | { 729 | "result": { 730 | { 731 | "bitfinex:bfxbtc": { 732 | "price": { 733 | "last": 0.00067133, 734 | "high": 0.0006886, 735 | "low": 0.00066753, 736 | "change": { 737 | "percentage": -0.02351996, 738 | "absolute": -1.6169972e-05 739 | } 740 | }, 741 | "volume":84041.625 742 | }, 743 | "bitfinex:bfxusd": { 744 | ... 745 | }, 746 | "bitfinex:btcusd": { 747 | ... 748 | }, 749 | ... 750 | } 751 | } 752 | } 753 | 754 | """ 755 | if not args or args[0] not in self.ROUTES_AGGREGATE: 756 | raise ValueError('Use either "prices", or "summaries"') 757 | return self._get('markets', args[0]) 758 | -------------------------------------------------------------------------------- /cryptowatch/exceptions.py: -------------------------------------------------------------------------------- 1 | """Custom exceptions module.""" 2 | 3 | 4 | class CryptowatchAPIException(Exception): 5 | """Raised when the API response is not 2xx.""" 6 | 7 | def __init__(self, response): 8 | super(CryptowatchAPIException, self).__init__() 9 | self.status_code = response.status_code 10 | self.reason = response.reason 11 | self.response = response 12 | 13 | def __str__(self): 14 | return 'APIError(code=%s): %s' % (self.status_code, self.reason) 15 | 16 | 17 | class CryptowatchResponseException(Exception): 18 | """Raised for an invalid json response from the API""" 19 | 20 | def __init__(self, message): 21 | super(CryptowatchResponseException, self).__init__() 22 | self.message = message 23 | 24 | def __str__(self): 25 | return 'CryptowatchResponseException: %s' % self.message 26 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = python-cryptowatch 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # python-cryptowatch documentation build configuration file, created by 5 | # sphinx-quickstart on Mon Dec 11 14:14:38 2017. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | import os 21 | import sys 22 | sys.path.insert(0, os.path.abspath('..')) 23 | # import sphinx_rtd_theme 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # 29 | # needs_sphinx = '1.0' 30 | 31 | # Add any Sphinx extension module names here, as strings. They can be 32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 33 | # ones. 34 | extensions = ['sphinx.ext.autodoc', 35 | 'sphinx.ext.todo', 36 | 'sphinx.ext.coverage', 37 | 'sphinx.ext.githubpages'] 38 | 39 | # Add any paths that contain templates here, relative to this directory. 40 | templates_path = ['_templates'] 41 | 42 | # The suffix(es) of source filenames. 43 | # You can specify multiple suffix as a list of string: 44 | # 45 | # source_suffix = ['.rst', '.md'] 46 | source_suffix = '.rst' 47 | 48 | # The master toctree document. 49 | master_doc = 'index' 50 | 51 | # General information about the project. 52 | project = 'python-cryptowatch' 53 | copyright = '2017, uoshvis' 54 | author = 'uoshvis' 55 | 56 | # The version info for the project you're documenting, acts as replacement for 57 | # |version| and |release|, also used in various other places throughout the 58 | # built documents. 59 | # 60 | # The short X.Y version. 61 | version = '0.0.1' 62 | # The full version, including alpha/beta/rc tags. 63 | release = '0.0.1' 64 | 65 | # The language for content autogenerated by Sphinx. Refer to documentation 66 | # for a list of supported languages. 67 | # 68 | # This is also used if you do content translation via gettext catalogs. 69 | # Usually you set "language" from the command line for these cases. 70 | language = None 71 | 72 | # List of patterns, relative to source directory, that match files and 73 | # directories to ignore when looking for source files. 74 | # This patterns also effect to html_static_path and html_extra_path 75 | exclude_patterns = ['_build'] 76 | 77 | # The name of the Pygments (syntax highlighting) style to use. 78 | pygments_style = 'sphinx' 79 | 80 | # If true, `todo` and `todoList` produce output, else they produce nothing. 81 | todo_include_todos = False 82 | 83 | 84 | # -- Options for HTML output ---------------------------------------------- 85 | 86 | # The theme to use for HTML and HTML Help pages. See the documentation for 87 | # a list of builtin themes. 88 | # 89 | html_theme = 'sphinx_rtd_theme' 90 | 91 | # Theme options are theme-specific and customize the look and feel of a theme 92 | # further. For a list of options available for each theme, see the 93 | # documentation. 94 | # 95 | # html_theme_options = {} 96 | 97 | # Add any paths that contain custom static files (such as style sheets) here, 98 | # relative to this directory. They are copied after the builtin static files, 99 | # so a file named "default.css" will overwrite the builtin "default.css". 100 | html_static_path = ['_static'] 101 | 102 | # Custom sidebar templates, must be a dictionary that maps document names 103 | # to template names. 104 | # 105 | # This is required for the alabaster theme 106 | # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars 107 | html_sidebars = { 108 | '**': [ 109 | 'relations.html', # needs 'show_related': True theme option to display 110 | 'searchbox.html', 111 | ] 112 | } 113 | 114 | 115 | # -- Options for HTMLHelp output ------------------------------------------ 116 | 117 | # Output file base name for HTML help builder. 118 | htmlhelp_basename = 'python-cryptowatchdoc' 119 | 120 | 121 | # -- Options for LaTeX output --------------------------------------------- 122 | 123 | latex_elements = { 124 | # The paper size ('letterpaper' or 'a4paper'). 125 | # 126 | # 'papersize': 'letterpaper', 127 | 128 | # The font size ('10pt', '11pt' or '12pt'). 129 | # 130 | # 'pointsize': '10pt', 131 | 132 | # Additional stuff for the LaTeX preamble. 133 | # 134 | # 'preamble': '', 135 | 136 | # Latex figure (float) alignment 137 | # 138 | # 'figure_align': 'htbp', 139 | } 140 | 141 | # Grouping the document tree into LaTeX files. List of tuples 142 | # (source start file, target name, title, 143 | # author, documentclass [howto, manual, or own class]). 144 | latex_documents = [ 145 | (master_doc, 'python-cryptowatch.tex', 'python-cryptowatch Documentation', 146 | 'uoshvis', 'manual'), 147 | ] 148 | 149 | 150 | # -- Options for manual page output --------------------------------------- 151 | 152 | # One entry per manual page. List of tuples 153 | # (source start file, name, description, authors, manual section). 154 | man_pages = [ 155 | (master_doc, 'python-cryptowatch', 'python-cryptowatch Documentation', 156 | [author], 1) 157 | ] 158 | 159 | 160 | # -- Options for Texinfo output ------------------------------------------- 161 | 162 | # Grouping the document tree into Texinfo files. List of tuples 163 | # (source start file, target name, title, author, 164 | # dir menu entry, description, category) 165 | texinfo_documents = [ 166 | (master_doc, 'python-cryptowatch', 'python-cryptowatch Documentation', 167 | author, 'python-cryptowatch', 'One line description of project.', 168 | 'Miscellaneous'), 169 | ] 170 | 171 | 172 | 173 | -------------------------------------------------------------------------------- /docs/cryptowatch.rst: -------------------------------------------------------------------------------- 1 | Cryptowatch API 2 | =============== 3 | 4 | api_client module 5 | ---------------------- 6 | 7 | .. automodule:: cryptowatch.api_client 8 | :members: 9 | :undoc-members: 10 | :show-inheritance: 11 | -------------------------------------------------------------------------------- /docs/exceptions.rst: -------------------------------------------------------------------------------- 1 | Exceptions 2 | ========== 3 | 4 | CryptowatchAPIException 5 | ----------------------- 6 | 7 | On an API call error a binance.exceptions.BinanceAPIException will be raised. 8 | 9 | The exception provides access to the 10 | 11 | - `status_code` - response status code 12 | - `reason` - response reason 13 | - `response` - response object 14 | 15 | 16 | CryptowatchResponseException 17 | ---------------------------- 18 | 19 | Raised if a non JSON response is returned 20 | -------------------------------------------------------------------------------- /docs/general.rst: -------------------------------------------------------------------------------- 1 | Available Endpoints 2 | =================== 3 | 4 | `Get assets `_ 5 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 6 | 7 | .. code:: python 8 | 9 | client.get_assets() 10 | 11 | 12 | `Get pairs `_ 13 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 14 | 15 | .. code:: python 16 | 17 | client.get_pairs() 18 | 19 | `Get exchanges `_ 20 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 21 | 22 | .. code:: python 23 | 24 | client.get_exchanges() 25 | 26 | `Get markets `_ 27 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 28 | 29 | .. code:: python 30 | 31 | client.get_markets() 32 | 33 | `Get aggregates `_ 34 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 35 | 36 | .. code:: python 37 | 38 | client.get_aggregates() 39 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. python-cryptowatch documentation master file, created by 2 | sphinx-quickstart on Mon Dec 11 14:14:38 2017. 3 | 4 | 5 | .. include:: ../README.rst 6 | 7 | Contents 8 | ======== 9 | 10 | .. toctree:: 11 | :maxdepth: 2 12 | 13 | overview 14 | general 15 | exceptions 16 | 17 | cryptowatch 18 | 19 | Indices and tables 20 | ================== 21 | 22 | * :ref:`genindex` 23 | * :ref:`modindex` 24 | * :ref:`search` 25 | -------------------------------------------------------------------------------- /docs/overview.rst: -------------------------------------------------------------------------------- 1 | Getting Started 2 | =============== 3 | 4 | Initialise the client 5 | --------------------- 6 | 7 | .. code:: python 8 | 9 | from cryptowatch.api_client import Client 10 | client = Client() 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pytest==3.4.1 2 | requests>=2.20.0 3 | requests-mock==1.4.0 4 | urllib3==1.26.19 5 | -------------------------------------------------------------------------------- /requirements_test.txt: -------------------------------------------------------------------------------- 1 | pytest==3.4.1 2 | requests-mock==1.4.0 3 | pylint==1.8.2 -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | test=pytest 3 | 4 | [tool:pytest] 5 | addopts=--ignore=docs 6 | 7 | 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """Package setup file.""" 2 | import os 3 | 4 | try: # for pip >= 10 5 | from pip._internal.req import parse_requirements 6 | except ImportError: # for pip <= 9.0.3 7 | from pip.req import parse_requirements 8 | 9 | from setuptools import find_packages, setup 10 | 11 | 12 | def get_version(): 13 | """Return the current version.""" 14 | curr_dir = os.path.dirname(os.path.realpath(__file__)) 15 | with open(os.path.join(curr_dir, 'version.txt')) as version_file: 16 | return version_file.read().strip() 17 | 18 | 19 | def get_requirements(file): 20 | """Return a list of requirements from a file.""" 21 | requirements = parse_requirements(file, session=False) 22 | requirements = list(requirements) 23 | try: 24 | requirements = [str(ir.req) for ir in requirements] 25 | except: 26 | requirements = [str(ir.requirement) for ir in requirements] 27 | return requirements 28 | 29 | setup( 30 | name='cryptowatch', 31 | version=get_version(), 32 | description='Unofficial wrapper for for the Cryptowatch public Data API.', 33 | author='uoshvis', 34 | url='https://github.com/uoshvis/python-cryptowatch', 35 | packages=find_packages(), 36 | include_package_data=True, 37 | install_requires=get_requirements('requirements.txt'), 38 | setup_requires=[ 39 | 'pytest-runner', 40 | 'pytest-pylint' 41 | ], 42 | tests_require=get_requirements('requirements_test.txt'), 43 | platforms='any' 44 | ) 45 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uoshvis/python-cryptowatch/3a718f20ac4e520b776ea55080dcdcf802c139dc/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | """Test fixtures.""" 2 | import pytest 3 | 4 | 5 | @pytest.fixture 6 | def assets_keys(scope='module'): 7 | """Mock keys fixture.""" 8 | return ['result', 'allowance'] 9 | -------------------------------------------------------------------------------- /tests/test_api_client.py: -------------------------------------------------------------------------------- 1 | """Unit tests related to the api_client module.""" 2 | import pytest 3 | 4 | import requests_mock 5 | from cryptowatch.api_client import Client 6 | from cryptowatch.exceptions import (CryptowatchAPIException, 7 | CryptowatchResponseException) 8 | 9 | client = Client() 10 | 11 | 12 | def test_get_assets(assets_keys, symbol=None): 13 | """Test an API call to get assets' info """ 14 | response = client.get_assets(symbol) 15 | assert isinstance(response, dict) 16 | assert set(assets_keys).issubset(response.keys()) 17 | 18 | 19 | def test_get_assets_symbol(assets_keys, symbol='btc'): 20 | """Test an API call to get assets' info """ 21 | response = client.get_assets(symbol) 22 | assert isinstance(response, dict) 23 | assert set(assets_keys).issubset(response.keys()) 24 | assert symbol == response['result']['symbol'] 25 | 26 | 27 | def test_get_pairs(assets_keys, pair=None): 28 | """Test an API call to get pairs info """ 29 | response = client.get_pairs(pair) 30 | assert isinstance(response, dict) 31 | assert set(assets_keys).issubset(response.keys()) 32 | 33 | 34 | def test_get_pairs_details(assets_keys, pair='btceur'): 35 | """Test an API call to get pair info """ 36 | response = client.get_pairs(pair) 37 | assert isinstance(response, dict) 38 | assert set(assets_keys).issubset(response.keys()) 39 | assert pair == response['result']['symbol'] 40 | 41 | 42 | def test_api_exception(symbol='invalid'): 43 | """Test API response Exception""" 44 | with pytest.raises(CryptowatchAPIException): 45 | client.get_assets(symbol) 46 | 47 | 48 | def test_invalid_json(symbol='btc'): 49 | """Test Invalid response Exception""" 50 | 51 | with pytest.raises(CryptowatchResponseException): 52 | with requests_mock.mock() as m: 53 | m.get('https://api.cryptowat.ch/assets/btc', text='') 54 | client.get_assets(symbol) 55 | 56 | 57 | def test_get_markets(assets_keys): 58 | """Test an API call to get markets' info """ 59 | response = client.get_markets() 60 | assert isinstance(response, dict) 61 | assert set(assets_keys).issubset(response.keys()) 62 | 63 | 64 | def test_get_single_exchange_market(assets_keys, exchange='gdax'): 65 | """Test an API call to get single exchange info """ 66 | response = client.get_markets(exchange) 67 | assert isinstance(response, dict) 68 | assert set(assets_keys).issubset(response.keys()) 69 | 70 | 71 | def test_get_single_market(assets_keys): 72 | """Test an API call to get market detail """ 73 | data = { 74 | 'exchange': 'gdax', 75 | 'pair': 'btcusd' 76 | } 77 | response = client.get_markets(data=data) 78 | assert isinstance(response, dict) 79 | assert set(assets_keys).issubset(response.keys()) 80 | 81 | 82 | def test_get_price(assets_keys): 83 | """Test an API call to get assets' info """ 84 | data = { 85 | 'exchange': 'gdax', 86 | 'pair': 'btcusd', 87 | 'route': 'price' 88 | } 89 | response = client.get_markets(data=data) 90 | assert isinstance(response, dict) 91 | assert set(assets_keys).issubset(response.keys()) 92 | 93 | 94 | @pytest.mark.parametrize('route', [ 95 | 'prices', 96 | 'summaries', 97 | ]) 98 | def test_routes(assets_keys, route): 99 | """It returns a dict and contains expected keys""" 100 | response = client.get_aggregates(route) 101 | assert isinstance(response, dict) 102 | assert set(assets_keys).issubset(response.keys()) 103 | 104 | 105 | def test_get_agg_summaries_exception(): 106 | """It raises ValueError with an incorrect argument.""" 107 | with pytest.raises(ValueError): 108 | client.get_aggregates('test') 109 | 110 | 111 | def test_get_agg_summaries_exception_no_arg(): 112 | """It raises ValueError when no argument is passed.""" 113 | with pytest.raises(ValueError): 114 | client.get_aggregates() 115 | -------------------------------------------------------------------------------- /version.txt: -------------------------------------------------------------------------------- 1 | 0.0.1 --------------------------------------------------------------------------------