├── ctapi ├── test │ ├── __init__.py │ └── ctapi_tests.py ├── __init__.py └── ctapi.py ├── requirements.txt ├── setup.cfg ├── LICENSE ├── getMyBalances.py ├── setup.py ├── README.md └── .gitignore /ctapi/test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /ctapi/__init__.py: -------------------------------------------------------------------------------- 1 | from .ctapi import * 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | PyYAML==5.4.1 2 | requests==2.25.1 3 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | 4 | [metadata] 5 | description-file = README.md 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 tbl42 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 | -------------------------------------------------------------------------------- /getMyBalances.py: -------------------------------------------------------------------------------- 1 | import json 2 | import yaml 3 | 4 | from ctapi import CTAPI 5 | 6 | if __name__ == "__main__": 7 | 8 | with open("secrets.yml") as f: 9 | secrets = yaml.load(f) 10 | f.close() 11 | 12 | # api = CTAPI(secrets['key'], secrets['secret'], debug=True) 13 | api = CTAPI(secrets['key'], secrets['secret']) 14 | balances = api.getBalance() 15 | 16 | if balances['result']['success']: 17 | sum = 0 18 | print "+-------+------------+------------+------------+" 19 | print "| SYM | amount | price_fiat | value_fiat |" 20 | print "+-------+------------+------------+------------+" 21 | for b in balances['result']['details']: 22 | details = balances['result']['details'][b] 23 | if float(details['value_fiat']) > 0.01: 24 | sum = sum + float(details['value_fiat']) 25 | print "| %5s | %10.2f | %10.2f | %10.2f |" % (b, float(details['amount']), 26 | float(details['price_fiat']), float(details['value_fiat']) ) 27 | 28 | print "+-------+------------+------------+------------+" 29 | print "" 30 | print "Sum: %15.2f EUR" % (sum) 31 | print "=" * 24 32 | else: 33 | print "got no balances" 34 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup, find_packages 4 | 5 | setup( 6 | name='python-ctapi', 7 | version='0.3.1', 8 | packages=['ctapi'], 9 | install_requires=[ 10 | 'requests==2.22.0', 11 | 'PyYAML==5.1.2', 12 | ], 13 | 14 | author='tehtbl', 15 | author_email='cyberworker@posteo.de', 16 | url='https://github.com/tehtbl/python-ctapi', 17 | description='Python Interface for CoinTracking.info API', 18 | long_description=open('README.md').read(), 19 | keywords='CoinTracking info btc api coin tracking', 20 | license='MIT', 21 | 22 | classifiers=[ 23 | 'Programming Language :: Python', 24 | 'Programming Language :: Python :: 2', 25 | 'Programming Language :: Python :: 2.7', 26 | 'Programming Language :: Python :: 3', 27 | 'Programming Language :: Python :: 3.4', 28 | 'Programming Language :: Python :: 3.5', 29 | 'Programming Language :: Python :: 3.6', 30 | 'Programming Language :: Python :: 3.7', 31 | 'Operating System :: OS Independent', 32 | 'License :: OSI Approved :: MIT License', 33 | 'Intended Audience :: Developers', 34 | 'Topic :: Office/Business :: Financial', 35 | ] 36 | 37 | ) 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-ctapi 2 | Python interface for [CoinTracking.info API](https://cointracking.info/api/api.php). 3 | 4 | I am not associated to cointracking.info -- use at your own risk! 5 | 6 | # Requirements: 7 | * requests 8 | 9 | # Install 10 | `python setup.py install` 11 | 12 | `pip install python-ctapi` 13 | 14 | # How to Use 15 | This is an example about how you can use the library 16 | 17 | ``` 18 | #!/usr/bin/env python2 19 | 20 | from ctapi import CTAPI 21 | 22 | api_key = 23 | api_secret = 24 | 25 | # api = CTAPI(api_key, api_secret, debug=True) 26 | api = CTAPI(api_key, api_secret) 27 | trades = api.getTrades() 28 | 29 | if trades['success']: 30 | for t in trades['result']: 31 | print trades['result'][t] 32 | else: 33 | print "got no orders" 34 | 35 | print api.getBalance() 36 | print api.getHistoricalSummary() 37 | print api.getHistoricalCurrency() 38 | print api.getGroupedBalance() 39 | print api.getGains() 40 | ``` 41 | 42 | # Running Tests 43 | **be aware of the API requests limit of 20 req/h** 44 | 45 | `venv/bin/python -m unittest -v ctapi.test.ctapi_tests` 46 | 47 | # Contribute 48 | Do you have an idea or found a bug in python-ctapi? Please file an issue and make a PR! :) 49 | 50 | ## Support Me 51 | If you like the API and wanna support its developer, use the following referral link when registering at cointracking: https://cointracking.info?ref=T161519 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | test.py 104 | .idea/ 105 | secrets.yml 106 | 107 | venv3 108 | -------------------------------------------------------------------------------- /ctapi/test/ctapi_tests.py: -------------------------------------------------------------------------------- 1 | import json 2 | import yaml 3 | import unittest 4 | 5 | from ctapi import CTAPI 6 | 7 | try: 8 | open("secrets.yml").close() 9 | IS_CI_ENV = False 10 | except Exception: 11 | IS_CI_ENV = True 12 | 13 | 14 | def test_basic_response(unit_test, result, method_name): 15 | unit_test.assertTrue(result['success'], "%s failed" % method_name) 16 | unit_test.assertTrue(result['result'] is not None, "result not present in response") 17 | unit_test.assertTrue(isinstance(result['result'], dict), "result is not a dict") 18 | # unit_test.assertTrue(result['result']['method'] is method_name, "result method is wrong") 19 | 20 | 21 | @unittest.skipIf(IS_CI_ENV, 'no account secrets uploaded in CI envieonment, TODO') 22 | class TestCTAPIBasicTests(unittest.TestCase): 23 | """ 24 | Integration tests for the CoinTracking API 25 | 26 | * These will fail in the absence of an internet connection or if CoinTracking API goes down 27 | * They require a valid API key and secret issued by CoinTracking 28 | * They also require the presence of a JSON file called secrets.yml 29 | 30 | It is structured as such: 31 | --- 32 | key: '123' 33 | secret: '456' 34 | """ 35 | 36 | def setUp(self): 37 | with open("secrets.yml") as f: 38 | self.secrets = yaml.load(f) 39 | f.close() 40 | 41 | # self.api = CTAPI(secrets['key'], secrets['secret'], debug=True) 42 | self.api = CTAPI(self.secrets['key'], self.secrets['secret']) 43 | 44 | def test_handles_invalid_key_or_secret(self): 45 | self.api = CTAPI('invalidkey', self.secrets['secret']) 46 | actual = self.api.getBalance() 47 | self.assertFalse(actual['success'], 'Invalid key, valid secret') 48 | 49 | self.api = CTAPI(None, self.secrets['secret']) 50 | actual = self.api.getBalance() 51 | self.assertFalse(actual['success'], 'None key, valid secret') 52 | 53 | self.api = CTAPI(self.secrets['key'], 'invalidsecret') 54 | actual = self.api.getBalance() 55 | self.assertFalse(actual['success'], 'valid key, invalid secret') 56 | 57 | self.api = CTAPI(self.secrets['key'], None) 58 | actual = self.api.getBalance() 59 | self.assertFalse(actual['success'], 'valid key, None secret') 60 | 61 | self.api = CTAPI('invalidkey', 'invalidsecret') 62 | actual = self.api.getBalance() 63 | self.assertFalse(actual['success'], 'invalid key, invalid secret') 64 | 65 | def test_getTrades(self): 66 | actual = self.api.getTrades() 67 | test_basic_response(self, actual, "getTrades") 68 | 69 | def test_getBalance(self): 70 | actual = self.api.getBalance() 71 | test_basic_response(self, actual, "getBalance") 72 | 73 | def test_getHistoricalSummary(self): 74 | actual = self.api.getHistoricalSummary() 75 | test_basic_response(self, actual, "getHistoricalSummary") 76 | 77 | def test_getHistoricalCurrency(self): 78 | actual = self.api.getHistoricalCurrency() 79 | test_basic_response(self, actual, "getHistoricalCurrency") 80 | 81 | def test_getGroupedBalance(self): 82 | actual = self.api.getGroupedBalance() 83 | test_basic_response(self, actual, "getGroupedBalance") 84 | 85 | def test_getGains(self): 86 | actual = self.api.getGains() 87 | test_basic_response(self, actual, "getGains") 88 | 89 | 90 | if __name__ == '__main__': 91 | unittest.main() 92 | -------------------------------------------------------------------------------- /ctapi/ctapi.py: -------------------------------------------------------------------------------- 1 | """ 2 | See https://cointracking.info/api/api.php 3 | """ 4 | 5 | try: 6 | from urllib import urlencode 7 | from urlparse import urljoin 8 | except ImportError: 9 | from urllib.parse import urlencode 10 | from urllib.parse import urljoin 11 | 12 | import time 13 | import hmac 14 | import logging 15 | import hashlib 16 | 17 | import requests 18 | 19 | __author__ = "tehtbl" 20 | __copyright__ = "(C) 2018 https://github.com/tehtbl" 21 | __version__ = '0.3.1' 22 | 23 | # set logging 24 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') 25 | logging.getLogger('requests.packages.urllib3').setLevel(logging.INFO) 26 | logging.getLogger('urllib3.connectionpool').setLevel(logging.INFO) 27 | logger = logging.getLogger(__name__) 28 | 29 | # disable unsecure SSL warning 30 | requests.packages.urllib3.disable_warnings() 31 | 32 | URI_API = 'https://cointracking.info/api/v1/' 33 | 34 | 35 | # 36 | # API object 37 | # 38 | class CTAPI(object): 39 | """ 40 | requesting CoinTracking API with API key and API secret 41 | 42 | Documentation: https://cointracking.info/api/api.php 43 | """ 44 | 45 | # 46 | # init 47 | # 48 | def __init__(self, api_key=None, api_secret=None, debug=False): 49 | # if not self.api_key or not self.api_secret: 50 | 51 | self.api_key = api_key 52 | self.api_secret = api_secret 53 | self.debug = debug 54 | 55 | if self.debug: 56 | import http.client 57 | http.client.HTTPConnection.debuglevel = 1 58 | logging.getLogger('requests.packages.urllib3').setLevel(logging.DEBUG) 59 | logger.setLevel(logging.DEBUG) 60 | else: 61 | logger.setLevel(logging.INFO) 62 | 63 | logger.debug("creating instance of CoinTracking API with api_key %s" % self.api_key) 64 | 65 | # 66 | # encode parameters for url 67 | # 68 | def _encode_params_url(self, params): 69 | """ 70 | encoding URL parameters 71 | 72 | :params: Request parameters to be encoded 73 | """ 74 | 75 | encoded_string = '' 76 | 77 | if params: 78 | # for key, value in sorted(params.items()): 79 | for key, value in params.items(): 80 | encoded_string += str(key) + '=' + str(value) + '&' 81 | encoded_string = encoded_string[:-1] 82 | 83 | return encoded_string 84 | 85 | # 86 | # make query to API 87 | # 88 | def _api_query(self, method, params={}): 89 | """ 90 | Queries CoinTracking.info 91 | 92 | :method: Request method 93 | :params: Request parameters 94 | :return: JSON response from Bittrex 95 | """ 96 | 97 | global URI_API 98 | 99 | params.update({ 100 | 'method': method, 101 | 'nonce': '%d' % int(time.time() * 10), 102 | }) 103 | 104 | if not self.api_secret: 105 | return { 106 | 'success': False, 107 | 'message': 'no valid secret key', 108 | } 109 | 110 | params_string = self._encode_params_url(params) 111 | params_signed = hmac.new(self.api_secret.encode(), msg=params_string.encode(), digestmod=hashlib.sha512).hexdigest() 112 | 113 | hdrs = { 114 | 'Key': self.api_key, 115 | 'Sign': params_signed, 116 | 'Connection': 'close', 117 | 'User-Agent': 'python-ctapi/%s (https://github.com/tehtbl/python-ctapi)' % (__version__), 118 | } 119 | 120 | logger.debug("=" * 30) 121 | logger.debug(params) 122 | logger.debug(params_string) 123 | logger.debug(params_signed) 124 | logger.debug(hdrs) 125 | logger.debug("=" * 30) 126 | 127 | try: 128 | new_params = {} 129 | for k in params.keys(): 130 | new_params[k] = (None, str(params[k])) 131 | 132 | r = requests.post(URI_API, headers=hdrs, files=new_params, verify=False) 133 | ret_json = r.json() 134 | 135 | return { 136 | 'success': ret_json['success'], 137 | 'result': ret_json 138 | } 139 | except Exception as e: 140 | return { 141 | 'success': False, 142 | 'message': "error connecting to API: %s" % str(e) 143 | } 144 | 145 | ########################################################################### 146 | # API methods 147 | ########################################################################### 148 | 149 | # 150 | # getTrades 151 | # 152 | def getTrades(self, **args): 153 | """ 154 | Used to get all your CoinTracking trades and transactions. 155 | Similar to the Trade List at https://cointracking.info/trades_full.php 156 | """ 157 | 158 | params = { 159 | 'limit': 5, 160 | 'order': 'DESC', 161 | } 162 | params.update(args) 163 | 164 | return self._api_query('getTrades', params) 165 | 166 | # 167 | # getBalance 168 | # 169 | def getBalance(self): 170 | """ 171 | Used to get your current CoinTracking account and coin balance. 172 | Similar to the Current Balance at https://cointracking.info/current_balance.php 173 | """ 174 | 175 | return self._api_query('getBalance') 176 | 177 | # 178 | # getHistoricalSummary 179 | # 180 | def getHistoricalSummary(self, **args): 181 | """ 182 | Used to get all historical values for all your coins, currencies, commodities, and the total account value. 183 | Similar to the Daily Balance at https://cointracking.info/overview.php or the Trade Statistics at https://cointracking.info/stats.php 184 | """ 185 | 186 | params = { 187 | 'btc': 0, 188 | } 189 | params.update(args) 190 | 191 | return self._api_query('getHistoricalSummary', params) 192 | 193 | # 194 | # getHistoricalCurrency 195 | # 196 | def getHistoricalCurrency(self, **args): 197 | """ 198 | Used to get all historical amounts and values for a specific currency/coin or for all currencies/coins. 199 | Similar to the Daily Balance at https://cointracking.info/overview.php or the Trade Statistics at https://cointracking.info/stats.php 200 | """ 201 | 202 | params = { 203 | 'currency': 'ETH', 204 | } 205 | params.update(args) 206 | 207 | return self._api_query('getHistoricalCurrency', params) 208 | 209 | # 210 | # getGroupedBalance 211 | # 212 | def getGroupedBalance(self, **args): 213 | """ 214 | Used to get the current balance grouped by exchange, trade-group or transaction type. 215 | Similar to the Balance by Exchange at https://cointracking.info/balance_by_exchange.php 216 | """ 217 | 218 | params = { 219 | 'group': 'exchange', 220 | } 221 | params.update(args) 222 | 223 | return self._api_query('getGroupedBalance', params) 224 | 225 | # 226 | # getGains 227 | # 228 | def getGains(self, **args): 229 | """ 230 | Used to get Returns your current realized and unrealized gains data. 231 | Similar to the Realized and Unrealized Gains at https://cointracking.info/gains.php 232 | """ 233 | 234 | params = { 235 | 'method': 'FIFO', 236 | } 237 | params.update(args) 238 | 239 | return self._api_query('getGains', params) 240 | 241 | 242 | # 243 | # getLedger 244 | # 245 | def getLedger(self, **args): 246 | """ 247 | Used to get Returns your Ledger 248 | """ 249 | 250 | params = { 251 | 'show_advanced': '1', 252 | } 253 | params.update(args) 254 | 255 | return self._api_query('getLedger', params) 256 | --------------------------------------------------------------------------------