├── .gitignore
├── ATTRIBUTIONS.md
├── LICENSE
├── Makefile
├── README.md
├── algos
└── old_algo.py
├── assets
└── kloudtrader.png
├── back.ipynb
├── back.py
├── backtest.md
├── backtest
└── 1.py
├── changelog.md
├── libkloudtrader
├── __init__.py
├── alert_me.py
├── algorithm.py
├── analysis.py
├── archive.py
├── backtest.py
├── crypto.py
├── crypto_operations.py
├── enumerables.py
├── exceptions.py
├── logs.py
├── options.py
├── processing.py
├── stocks.py
└── test
│ ├── backtest.py
│ ├── parts.py
│ └── performance.py
├── live.py
├── pypi.md
├── requirements.txt
├── setup.py
├── tests
├── Tests.md
├── __init__.py
├── test_alert_me.py
├── test_analysis.py
├── test_crypto.py
├── test_options.py
└── test_stocks.py
└── tox.ini
/.gitignore:
--------------------------------------------------------------------------------
1 | #editor config
2 | .vscode/
3 | .DS_Store
4 | # Created by https://www.gitignore.io/api/python
5 |
6 | ### Python ###
7 | # Byte-compiled / optimized / DLL files
8 | __pycache__/
9 | *.py[cod]
10 | *$py.class
11 |
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | *.egg-info/
30 | .installed.cfg
31 | *.egg
32 | MANIFEST
33 | Pipfile
34 | Pipfile.lock
35 |
36 | # PyInstaller
37 | # Usually these files are written by a python script from a template
38 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
39 | *.manifest
40 | *.spec
41 |
42 | # Installer logs
43 | pip-log.txt
44 | pip-delete-this-directory.txt
45 |
46 | # Unit test / coverage reports
47 | htmlcov/
48 | .tox/
49 | .nox/
50 | .coverage
51 | .coverage.*
52 | .cache
53 | nosetests.xml
54 | coverage.xml
55 | *.cover
56 | .hypothesis/
57 | .pytest_cache/
58 |
59 | # Translations
60 | *.mo
61 | *.pot
62 |
63 | # Django stuff:
64 | *.log
65 | local_settings.py
66 | db.sqlite3
67 |
68 | # Flask stuff:
69 | instance/
70 | .webassets-cache
71 |
72 | # Scrapy stuff:
73 | .scrapy
74 |
75 | # Sphinx documentation
76 | docs/_build/
77 |
78 | # PyBuilder
79 | target/
80 |
81 | # Jupyter Notebook
82 | .ipynb_checkpoints
83 |
84 | # IPython
85 | profile_default/
86 | ipython_config.py
87 |
88 | # pyenv
89 | .python-version
90 |
91 | # celery beat schedule file
92 | celerybeat-schedule
93 |
94 | # SageMath parsed files
95 | *.sage.py
96 |
97 | # Environments
98 | .env
99 | .venv
100 | env/
101 | venv/
102 | ENV/
103 | env.bak/
104 | venv.bak/
105 |
106 | # Spyder project settings
107 | .spyderproject
108 | .spyproject
109 |
110 | # Rope project settings
111 | .ropeproject
112 |
113 | # mkdocs documentation
114 | /site
115 |
116 | # mypy
117 | .mypy_cache/
118 | .dmypy.json
119 | dmypy.json
120 |
121 | ### Python Patch ###
122 | .venv/
123 |
124 | ### Python.VirtualEnv Stack ###
125 | # Virtualenv
126 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
127 | [Bb]in
128 | [Ii]nclude
129 | [Ll]ib
130 | [Ll]ib64
131 | [Ll]ocal
132 | [Ss]cripts
133 | pyvenv.cfg
134 | pip-selfcheck.json
135 |
136 | #misc
137 | .vscode/
138 | .DS_Store
139 | __pycache__/
140 | .pytest_cache/
141 | libkloudtrader/.mypy_cache
142 | .mypy_cache
143 | algo.py
144 | env.sh
145 |
146 |
147 | # End of https://www.gitignore.io/api/python
148 |
149 |
150 |
--------------------------------------------------------------------------------
/ATTRIBUTIONS.md:
--------------------------------------------------------------------------------
1 | Attributions
2 |
3 | ### libkloudtrader uses the following libraries and packages:
4 | 1. [pandas](https://pandas.pydata.org/)
5 | 2. [boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
6 | 3. [requests](https://www.google.com/search?q=requests+python&rlz=1C5CHFA_enIN830IN830&oq=requests+python&aqs=chrome..69i57j69i60j69i61j0l3.7788j1j4&sourceid=chrome&ie=UTF-8)
7 | 4. [numpy](http://www.numpy.org/)
8 | 5. [empyrical](http://quantopian.github.io/empyrical/)
9 |
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2018 KloudTrader Ltd.
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 | Copyright 2018 KloudTrader Ltd
204 |
205 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
206 |
207 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
208 |
209 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
210 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | install:
2 | pipenv install --dev
3 |
4 | lint:
5 | pipenv run pylint libkloudtrader
6 |
7 | format:
8 | pipenv run yapf -i --recursive libkloudtrader
9 |
10 | test:
11 | pipenv run pytest -s -v tests/
12 |
13 | git:
14 | pipenv run yapf -i --recursive libkloudtrader
15 | git add -A
16 | git commit -m "$(message)"
17 | git push
18 |
19 | safe:
20 | pipenv run safety check
21 |
22 | typecheck:
23 | pipenv run pyre --source-directory libkloudtrader check
24 |
25 | run:
26 | pipenv run python algo.py
27 |
28 | tox:
29 | pipenv run tox
30 |
31 | algo:
32 | pipenv run python algo.py
33 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # LibKloudTrader
4 |
5 |
6 |
7 |
8 | 
9 | 
10 | 
11 | 
12 | 
13 | 
14 |
15 | KloudTrader's in-house trading framework optimized for computational finance and algortihmic trading. 📈📊📉
16 |
17 | Connect your trading models and conquer the markets.
18 |
19 |
20 |
21 | What does LibKLoudTrader offer?
22 |
23 | 1. Extremely simple to use trading APIs for U.S. Equity market.
24 |
25 | 2. All sorts of data: live market feed, historical price data, company information and much more.
26 |
27 | 3. Customized alert APIs for both sms and email.
28 |
29 | 4. A Wide range of functions for financial, technical, portfolio and risk analsyis.
30 |
31 | 5. Papertrading with virtual money upto $1 million. (Coming Soon)
32 |
33 | 6. Multi Crypto-Currency Trading and Data APIs. (Coming Soon)
34 |
35 | 7. Managed deployment of your trading algorithm on [Narwhal](https://kloudtrader.com/narwhal) without the hassle of dev-ops and tech support.
36 |
37 |
38 |
39 | Documentation for LibKloudTrader can be found here: https://docs.kloudtrader.com/
40 |
41 |
42 |
43 | For questions, feedback and contributions:
44 |
45 | 1. [KloudTrader Community on slack](https://kloudtradercommunity.slack.com/messages/CDM1PKS81/)
46 |
47 | 2. [Github Issues](https://github.com/KloudTrader/libkloudtrader/issues)
48 |
49 |
50 |
51 | Note: This is a python client. More clients (R, Julia, Golang, C#, etc) coming soon.
52 |
53 |
54 |
55 | Notes for docs:
56 | Remove close_prices, open_prices, etc
--------------------------------------------------------------------------------
/algos/old_algo.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | import numpy as np
4 | import pandas as pd
5 | import requests
6 |
7 | from libkloudtrader.equities.data import (
8 | ACCESS_TOKEN,
9 | STREAMING_API_URL,
10 | create_session,
11 | get_headers,
12 | )
13 | from libkloudtrader.alert_me import sms_and_email
14 | from streamz import Stream
15 |
16 |
17 | def df_empty(columns, dtypes, index=None):
18 | assert len(columns) == len(dtypes)
19 | df = pd.DataFrame(index=index)
20 | for c, d in zip(columns, dtypes):
21 | df[c] = pd.Series(dtype=d)
22 | return df
23 |
24 |
25 | def get_quotes(symbol, sessionid):
26 | # gets market events
27 | payload = {"sessionid": sessionid, "symbols": str(symbol.upper())}
28 | r = requests.post(
29 | STREAMING_API_URL + "/v1/markets/events",
30 | params=payload,
31 | headers=get_headers(ACCESS_TOKEN),
32 | stream=True,
33 | )
34 | print("Starting...")
35 | try:
36 | for data in r.iter_content(chunk_size=None, decode_unicode=True):
37 | # print(data)
38 | lines = data.decode("utf-8").replace("}{", "}\n{").split("\n")
39 | for line in lines:
40 | quotes = json.loads(line)
41 | # print(quotes)
42 | if quotes["type"] == "quote":
43 | # row = pd.DataFrame({"quote": float(quotes["ask"])}, index=[0])
44 | stream.emit(quotes["ask"])
45 | on_tick()
46 | except:
47 | raise Exception("Did not receive any data. Status Code: %d" %
48 | r.status_code)
49 |
50 |
51 | # price_table = pd.DataFrame(columns=["date", "quote"], index=[0])
52 | # price_table = df_empty(columns=["date", "quote"], dtypes=[np.datetime64, np.float64])
53 | price_table = pd.DataFrame(columns=["quote"])
54 | # price_table.index = pd.to_datetime(price_table.index)
55 | # import pdb; pdb.set_trace()
56 | # print(price_table)
57 | stream = Stream()
58 | # price_stream = DataFrame(stream, example=price_table)
59 |
60 |
61 | def on_tick():
62 |
63 | # print(quote["askdate"], quote["ask"])
64 | # row = row.set_index(pd.DatetimeIndex(row["date"]))
65 | # price_table = price_table.set_index(pd.DatetimeIndex(price_table["date"]))
66 | # print(row)
67 | # print(price_stream)
68 | # stream.sink(print)
69 | # rows = price_stream.window(n=5).mean()
70 | # rows.stream.sink(print)
71 | # short_mavg = price_stream.quotu.sliding_window(n=2).mean()
72 | # long_mavg = price_stream.quote.sliding_window(n=5).mean()
73 | short_mavg = stream.sliding_window(n=2)
74 | long_mavg = stream.sliding_window(n=5)
75 | prices = short_mavg.zip(long_mavg).sink(crossover_condition)
76 | # import pdb; pdb.set_trace()
77 | # short_mavg.zip(long_mavg).stream.sink(print)
78 |
79 |
80 | def crossover_condition(price):
81 | short_mavg = np.mean(list(price[0]))
82 | long_mavg = np.mean(list(price[1]))
83 | print("short:", short_mavg)
84 | print("long:", long_mavg)
85 | # pass
86 | if (long_mavg - short_mavg) > 5:
87 | alert = "buy! SMA: {}, LMA: {}".format(short_mavg, long_mavg)
88 | print(alert)
89 | sms_and_email("+919871766213", "chetan@kloudtrader.com", alert)
90 | elif (short_mavg - long_mavg) > 3:
91 | alert = "sell! SMA: {}, LMA: {}".format(short_mavg, long_mavg)
92 | print(alert)
93 | sms_and_email("+919871766213", "chetan@kloudtrader.com", alert)
94 |
95 |
96 | get_quotes("AAPL", create_session(ACCESS_TOKEN))
97 |
--------------------------------------------------------------------------------
/assets/kloudtrader.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NarrationBox/libkloudtrader/015e2779f80ba2de93be9fa6fd751412a9d5f492/assets/kloudtrader.png
--------------------------------------------------------------------------------
/back.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 5,
6 | "metadata": {},
7 | "outputs": [
8 | {
9 | "name": "stderr",
10 | "output_type": "stream",
11 | "text": [
12 | "Tuesday, October 01, 2019 03:17:53 PM IST INFO: Starting Backtest for ba from 2019-09-24 09:30:00 to 2019-09-24 15:30:00 with initial capital = 100000\n",
13 | "Tuesday, October 01, 2019 03:17:56 PM IST INFO: Received Signals from ba\n"
14 | ]
15 | }
16 | ],
17 | "source": [
18 | "from libkloudtrader.algorithm import *\n",
19 | "import libkloudtrader.analysis as analysis\n",
20 | "import pandas as pd\n",
21 | "import numpy as np\n",
22 | "\n",
23 | "\n",
24 | "\n",
25 | "def ba(backtest,data):\n",
26 | " '''\n",
27 | " data['high']=data.close.shift(1).rolling(window=5).max()\n",
28 | " data['low']=data.close.shift(1).rolling(window=5).min()\n",
29 | " data['avg']=analysis.ma(data.close,5)\n",
30 | " buy=(data.close>data.high)\n",
31 | " sell=(data.closedata.avg)\n",
34 | " if buy.tail(1).bool():\n",
35 | " backtest.buy(5)\n",
36 | " elif sell.tail(1).bool():\n",
37 | " backtest.sell(5)\n",
38 | "\n",
39 | " '''\n",
40 | " pass\n",
41 | " #rets=analysis.daily_returns(data.close)\n",
42 | " #data['volatility']=analysis.moving_volatility(rets,1)\n",
43 | " #data['slip']=data.high-data.close\n",
44 | " \n",
45 | "\n",
46 | "\n",
47 | " \n",
48 | "\n",
49 | "run_backtest(ba,['AAPL'],data=\"US_STOCKS_ohlcv\",start='2019-09-24 09:30:00',end='2019-09-24 15:30:00',data_interval='15m')"
50 | ]
51 | },
52 | {
53 | "cell_type": "code",
54 | "execution_count": null,
55 | "metadata": {},
56 | "outputs": [],
57 | "source": []
58 | }
59 | ],
60 | "metadata": {
61 | "kernelspec": {
62 | "display_name": "Python 3",
63 | "language": "python",
64 | "name": "python3"
65 | },
66 | "language_info": {
67 | "codemirror_mode": {
68 | "name": "ipython",
69 | "version": 3
70 | },
71 | "file_extension": ".py",
72 | "mimetype": "text/x-python",
73 | "name": "python",
74 | "nbconvert_exporter": "python",
75 | "pygments_lexer": "ipython3",
76 | "version": "3.7.4"
77 | }
78 | },
79 | "nbformat": 4,
80 | "nbformat_minor": 4
81 | }
82 |
--------------------------------------------------------------------------------
/back.py:
--------------------------------------------------------------------------------
1 | from libkloudtrader.algorithm import *
2 | import libkloudtrader.analysis as analysis
3 | import pandas as pd
4 | import numpy as np
5 |
6 |
7 |
8 | def ba(backtest,data):
9 |
10 | data['high']=data.close.shift(1).rolling(window=5).max()
11 | data['low']=data.close.shift(1).rolling(window=5).min()
12 | data['avg']=analysis.ma(data.close,5)
13 | buy=(data.close>data.high)
14 | sell=(data.closedata.avg)
17 | if buy.tail(1).bool():
18 | backtest.buy(5)
19 | elif sell.tail(1).bool():
20 | backtest.sell(5)
21 |
22 |
23 | #rets=analysis.daily_returns(data.close)
24 | #data['volatility']=analysis.moving_volatility(rets,1)
25 | #data['slip']=data.high-data.close
26 |
27 |
28 |
29 |
30 |
31 | run_backtest(ba,['AAPL'],data="US_STOCKS_times_and_sale",start='2019-09-24 09:30:00',end='2019-09-24 15:30:00',data_interval='15m')
--------------------------------------------------------------------------------
/backtest.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NarrationBox/libkloudtrader/015e2779f80ba2de93be9fa6fd751412a9d5f492/backtest.md
--------------------------------------------------------------------------------
/backtest/1.py:
--------------------------------------------------------------------------------
1 | import libkloudtrader.stocks as stocks
--------------------------------------------------------------------------------
/changelog.md:
--------------------------------------------------------------------------------
1 | Changelog maintained from 17/06/2019
2 |
3 |
4 | Version 0.2:
5 |
6 | S. No.| Date | Changes/Additions/Fixes |
7 | ------|-----------------|-------------------------|
8 | 1 |18/06/2019 |access tokens moved to
--------------------------------------------------------------------------------
/libkloudtrader/__init__.py:
--------------------------------------------------------------------------------
1 | """Init Libkloudtrader"""
2 |
3 | name = "libkloudtrader"
4 | __version__ = "1.0.0"
5 |
--------------------------------------------------------------------------------
/libkloudtrader/alert_me.py:
--------------------------------------------------------------------------------
1 | '''Module for SMS and Email alert functions'''
2 | #pylint: disable = line-too-long, too-many-lines, no-name-in-module, import-error, multiple-imports, pointless-string-statement, wrong-import-order
3 | import os
4 | import boto3
5 | from botocore.exceptions import ClientError
6 | from libkloudtrader.logs import start_logger
7 |
8 | logger = start_logger(__name__)
9 |
10 | #Config
11 | AWS_ACCESS_KEY_ID = os.environ['ALERT_ME_AAKI']
12 | AWS_SECRET_ACCESS_KEY = os.environ['ALERT_ME_ASAK']
13 | AWS_DEFAULT_REGION = os.environ['ALERT_ME_ADR']
14 | SNS_TOPIC_ARN = os.environ['ALERT_ME_STA']
15 |
16 |
17 | def sms(number: str, message: str) -> str:
18 | '''Send SMS'''
19 | try:
20 | logger.info("Alert Created for {}...".format(number))
21 | client = boto3.client("sns",
22 | aws_access_key_id=AWS_ACCESS_KEY_ID,
23 | aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
24 | region_name=AWS_DEFAULT_REGION)
25 | topicarn = SNS_TOPIC_ARN
26 | client.subscribe(TopicArn=topicarn, Protocol='sms', Endpoint=number)
27 | client.publish(Message=message, TopicArn=topicarn)
28 | logger.info("Alert Created for {}".format(number))
29 | return True
30 | except Exception as exception:
31 | logger.error('Oops! An error Occurred ⚠️')
32 | raise exception
33 |
34 |
35 | def email(email_id: str,
36 | message: str,
37 | sender: str = "alerts@kloudtrader.com",
38 | subject: str = "KloudTrader Narwhal Alerts") -> str:
39 | '''Send Email'''
40 | try:
41 | logger.info("Alert Created for {}...".format(email))
42 | client = boto3.client('ses', region_name=AWS_DEFAULT_REGION)
43 | client.send_email(
44 | Destination={
45 | 'ToAddresses': [
46 | email_id,
47 | ],
48 | },
49 | Message={
50 | 'Body': {
51 | 'Text': {
52 | 'Charset': "UTF-8",
53 | 'Data': message,
54 | },
55 | },
56 | 'Subject': {
57 | 'Charset': "UTF-8",
58 | 'Data': subject,
59 | },
60 | },
61 | Source=sender,
62 | )
63 | logger.info("Alert Created for {}".format(email_id))
64 | return True
65 | except ClientError as exception:
66 | logger.error('Oops! An error Occurred ⚠️')
67 | raise exception.response['Error']['Message']
68 |
69 |
70 | def sms_and_email(number: str, email_id: str, message: str) -> str:
71 | '''Send both SMS and Email at once'''
72 | try:
73 | sms(number, message)
74 | email(email_id, message)
75 | return True
76 | except Exception as exception:
77 | logger.error('Oops! An error Occurred ⚠️')
78 | raise exception
79 |
--------------------------------------------------------------------------------
/libkloudtrader/algorithm.py:
--------------------------------------------------------------------------------
1 | from typing import Any, List
2 | import random
3 | import time
4 | import datetime
5 | import numpy as np
6 | import pandas as pd
7 | import libkloudtrader.stocks as stocks
8 | from libkloudtrader.exceptions import InvalidAlgorithmMode, EmptySymbolBucket, InvalidDataFeedType
9 | from libkloudtrader.enumerables import Data_Types
10 | import libkloudtrader.processing as processing
11 | from libkloudtrader.logs import start_logger
12 | import libkloudtrader.backtest as bt
13 | import libkloudtrader.crypto as crypto
14 | import libkloudtrader.analysis as analysis
15 | from tqdm import tqdm
16 |
17 |
18 |
19 | #pd.set_option('display.max_columns', None) # or 1000
20 | #pd.set_option('display.max_rows', None) # or 1000
21 | #pd.set_option('display.max_colwidth', -1) # or 199
22 |
23 | logger = start_logger(__name__, ignore_module='libkloudtrader.analysis')
24 |
25 |
26 | def run_backtest(strategy: str,
27 | symbol_bucket: List[str],
28 | data: str,
29 | start: Any,
30 | end: Any,
31 | data_interval:str="1d",
32 | preferred_price_point: str = 'close',
33 | preferred_benchmark: str = 'SPY',
34 | initial_capital: float = 100000,
35 | commission: float = 0,
36 | slippage=True):
37 | """Backtester function"""
38 | try:
39 | logger.info(
40 | 'Starting Backtest for {} from {} to {} with initial capital = {}'.
41 | format(strategy.__name__, start, end, initial_capital))
42 | data_to_backtest_on = Data_Types[data].value
43 | for symbol in symbol_bucket:
44 | data_batch = data_to_backtest_on(symbol=symbol,
45 | start=start,
46 | end=end,interval=data_interval
47 | )
48 | batch = processing.Buffer(len(data_batch), dtype=object)
49 | backtest=bt.Backtest(capital=100000,commission=1,enable_slippage=True)
50 | for datetime, bar in data_batch.iterrows():
51 | batch.append(bar)
52 | backtest.update_bar(datetime,bar)
53 | data_batch = pd.DataFrame(batch)
54 |
55 | locals()['strategy'](backtest,data_batch)
56 |
57 | print(backtest.get_trade_log)
58 | del backtest
59 |
60 |
61 | '''
62 | for symbol in symbol_bucket:
63 | data_batch = data_to_backtest_on(symbol,
64 | start,
65 | end,
66 | interval=data_interval)
67 | for symbol in symbol_bucket:
68 |
69 |
70 | a = bt.Backtest(locals()['strategy'](data_batch),
71 | preferred_price_point)
72 | print(a.preferred_price_point)
73 |
74 | signals=locals()['strategy'](data_batch)
75 | df=pd.DataFrame()
76 | df['buy']=signals['buy']
77 | df['sell']=signals['sell']
78 | df['short']=signals['short']
79 | df['cover']=signals['cover']
80 | '''
81 | #bt = Backtest(locals()['strategy'](data_batch), strategy.__name__)
82 | #df=bt.signals
83 | #df['positions']=bt.positions
84 | #df['price']=bt.trades['price']
85 | #df['trade volume']=bt.trades['vol']
86 | #df['trade_price']=bt.trade_price
87 | #df['equity']=bt.equity
88 | #df['trades']=bt.trades
89 | #df['positions in '+symbol]=100*df['positions']
90 | #print(bt.trades)
91 |
92 | #logger.info("Received Signals from {}".format(strategy.__name__))
93 |
94 | except (KeyboardInterrupt, SystemExit):
95 | print('\n')
96 | logger.critical("User's keyboard prompt stopped {}".format(
97 | strategy.__name__))
98 | except Exception as exception:
99 | logger.critical('Exiting {}...‼️'.format(strategy.__name__))
100 | logger.error(
101 | 'Oops! Something went wrong while your algorithm was being backtested. ⚠️'
102 | )
103 | raise exception
104 | exit()
105 |
106 | #print(return_data_from_enum(a,symbol,start, end))
107 | #print(locals()[a](symbol, start, end))
108 |
109 |
110 | def run_live(strategy: str,
111 | symbol_bucket: list,
112 | data_feed_type: str,
113 | exempted_states: list = [''],
114 | exempted_days:list=[''],
115 | exempted_dates:list=[''],
116 | batch_size: int = 1000,
117 | data_feed_delay: float = 1.0,
118 | fake_feed: bool = False):
119 | try:
120 | logger.info("{} is now entering the live markets. 📈\n".format(
121 | strategy.__name__))
122 | [x.lower() for x in exempted_states]
123 | [x.lower() for x in exempted_days]
124 | if isinstance(symbol_bucket, list):
125 | symbol_bucket = np.array(symbol_bucket)
126 | elif type(symbol_bucket) not in (numpy.ndarray, list):
127 | raise TypeError('Symbol bucket must be a list or numpy array')
128 | if data_feed_type not in ('CRYPTO_live_feed', 'US_STOCKS_live_feed',
129 | 'CRYPTO_live_feed_level2'):
130 | raise InvalidDataFeedType(
131 | 'This Data Feed is not available for live trading.'
132 | )
133 | if data_feed_type in ("CRYPTO_live_feed", 'CRYPTO_live_feed_level2'):
134 | data_feed_delay = crypto.exchange_attribute('rateLimit')
135 | data_feed = Data_Types[data_feed_type].value
136 | while stocks.intraday_status()['state'] not in exempted_states: #and datetime.datetime.now().strftime("%A").lower() not in exempted_days:
137 | batch = processing.Buffer(batch_size, dtype=object)
138 | while len(batch) < batch_size:
139 | for symbol in symbol_bucket:
140 | batch.append(data_feed(symbol, fake_feed=fake_feed))
141 | data_batch = pd.DataFrame(batch)
142 | locals()['strategy'](data_batch)
143 | if len(batch) == batch_size:
144 | batch.popleft()
145 | time.sleep(data_feed_delay / 1000)
146 | except (KeyboardInterrupt, SystemExit):
147 | print('\n')
148 | logger.critical("User's keyboard prompt stopped {}".format(
149 | strategy.__name__))
150 | except Exception as exception:
151 | logger.critical('Exiting {}...‼️'.format(strategy.__name__))
152 | logger.error('Oops! Something went wrong ⚠️')
153 | raise exception
154 | exit()
155 |
156 |
157 | '''
158 | def generate_positions_and_handle_portfolio(symbol, signals, data, commission,
159 | initial_capital, quantity):
160 | try:
161 | initial_capital = float(initial_capital)
162 | positions = pd.DataFrame(index=signals.index).fillna(0.0)
163 | positions['Positions in' + " " +
164 | symbol] = (quantity * signals['signal']) + commission
165 | portfolio = positions.multiply(data['close'], axis=0)
166 | poss_diff = positions.diff()
167 | portfolio['holdings'] = (positions.multiply(data['close'],
168 | axis=0)).sum(axis=1)
169 | return portfolio
170 | except Exception as exception:
171 | raise exception
172 | '''
173 |
--------------------------------------------------------------------------------
/libkloudtrader/archive.py:
--------------------------------------------------------------------------------
1 | '''archive'''
2 | '''
3 | def hilbert_transform_inst_trendline(data):
4 | """Hilbert Transform - Instantaneous Trendline"""
5 | try:
6 | logger.info(
7 | 'Calculating Hilbert Transform - Instantaneous Trendline...')
8 | htit_data = talib.HT_TRENDLINE(data)
9 | return htit_data
10 | except Exception as exception:
11 | logger.error('Oops! An error Occurred ⚠️')
12 | raise exception
13 |
14 |
15 | def hilbert_transform_dom_cyc_per(data):
16 | """Hilbert Transform - Dominant Cycle Period"""
17 | try:
18 | logger.info('Calculating Hilbert Transform - Dominant Cycle Period')
19 | htdcp_data = talib.HT_DCPERIOD(data)
20 | return htdcp_data
21 | except Exception as exception:
22 | logger.error('Oops! An error Occurred ⚠️')
23 | raise exception
24 |
25 |
26 | def hilbert_transform_dom_cyc_phase(data):
27 | """Hilbert Transform - Dominant Cycle Phase"""
28 | try:
29 | logger.info('Calculating Hilbert Transform - Dominant Cycle Phase')
30 | htdcp_data = talib.HT_DCPHASE(data)
31 | return htdcp_data
32 | except Exception as exception:
33 | logger.error('Oops! An error Occurred ⚠️')
34 | raise exception
35 |
36 |
37 | def hilbert_transform_phasor_components(close):
38 | """Hilbert Transform - Phasor Components"""
39 | try:
40 | logger.info("Calculating Hilbert Transform - Phasor Components...")
41 | inphase_data, quadrature_data = talib.HT_PHASOR(close)
42 | df = pd.DataFrame()
43 | df['inphase'] = inphase_data
44 | df['quadrature'] = quadrature_data
45 | return df
46 | except Exception as exception:
47 | logger.error('Oops! An error Occurred ⚠️')
48 | raise exception
49 |
50 |
51 | def hilbert_transform_sine_wave(data):
52 | """Hilbert Transform - Sine Wave"""
53 | try:
54 | logger.info("Calculating Hilbert Transform - Sine Wave...")
55 | sine_data, leadsine_data = talib.HT_SINE(data)
56 | df = pd.DataFrame()
57 | df['sine'] = sine_data
58 | df['leadsine'] = leadsine_data
59 | return df
60 | except Exception as exception:
61 | logger.error('Oops! An error Occurred ⚠️')
62 | raise exception
63 |
64 |
65 | def hilbert_transform_trend_vs_cycle_mode(data):
66 | """Hilbert Transform - Trend vs cycle mode"""
67 | try:
68 | logger.info("Calculating Hilbert Transform - Trend vs cycle mode...")
69 | httc_data = talib.HT_TRENDMODE(data)
70 | return httc_data
71 | except Exception as exception:
72 | logger.error('Oops! An error Occurred ⚠️')
73 | raise exception
74 |
75 |
76 | def parabolic_sar(high, low, af_step=.02, af_max=.2):
77 | """Parabolic SAR"""
78 | try:
79 | logger.info('Calculating Parabolic SAR...')
80 | check_inputs_length(high, low)
81 | ps_data = talib.SAR(high, low, acceleration, maximum)
82 | return ps_data
83 | except Exception as exception:
84 | logger.error('Oops! An error Occurred ⚠️')
85 | raise exception
86 |
87 | def linear_regression(data, period):
88 | """Linear Regression"""
89 | try:
90 | logger.info(
91 | 'Calculating Linear Regression for period = {}'.format(period))
92 | check_period_type(period)
93 |
94 | lr_data = talib.LINEARREG(data, timeperiod=period)
95 | return lr_data
96 | except Exception as exception:
97 | logger.error('Oops! An error Occurred ⚠️')
98 | raise exception
99 |
100 |
101 | def linear_regression_angle(data, period):
102 | """Linear Regression Angle"""
103 | try:
104 | logger.info(
105 | 'Calculating Linear Regression Angle for period = {}'.format(
106 | period))
107 | check_period_type(period)
108 |
109 | lra_data = talib.LINEARREG_ANGLE(data, timeperiod=period)
110 | return lra_data
111 | except Exception as exception:
112 | logger.error('Oops! An error Occurred ⚠️')
113 | raise exception
114 |
115 |
116 | def linear_regression_intercept(data, period):
117 | """Linear Regression Intercept"""
118 | try:
119 | logger.info(
120 | 'Calculating Linear Regression Intercept for period = {}'.format(
121 | period))
122 | check_period_type(period)
123 |
124 | lri_data = talib.LINEARREG_INTERCEPT(data, timeperiod=period)
125 | return lri_data
126 | except Exception as exception:
127 | logger.error('Oops! An error Occurred ⚠️')
128 | raise exception
129 |
130 |
131 | def linear_regression_slope(data, period):
132 | """Linear Regression Slope"""
133 | try:
134 | logger.info(
135 | 'Calculating Linear Regression Slope for period = {}'.format(
136 | period))
137 | check_period_type(period)
138 |
139 | lrs_data = talib.LINEARREG_SLOPE(data, timeperiod=period)
140 | return lrs_data
141 | except Exception as exception:
142 | logger.error('Oops! An error Occurred ⚠️')
143 | raise exception
144 |
145 | def midpoint_over_period(data, period):
146 | """Midpoint over period"""
147 | try:
148 | logger.info(
149 | 'Calculating Midpoint Over Period for period = {}'.format(period))
150 | check_period_type(period)
151 |
152 | mop = talib.MIDPOINT(data, timeperiod=period)
153 | return mop
154 | except Exception as exception:
155 | logger.error('Oops! An error Occurred ⚠️')
156 | raise exception
157 |
158 |
159 | def midpoint_price_over_period(high, low, period):
160 | """Midpoint price over period"""
161 | try:
162 | logger.info(
163 | 'Calculating Midpoint Price Over Period for period = {}'.format(
164 | period))
165 | check_period_type(period)
166 |
167 | check_inputs_length(high, low)
168 | mpop = talib.MIDPRICE(high, low, timeperiod=period)
169 | return mpop
170 | except Exception as exception:
171 | logger.error('Oops! An error Occurred ⚠️')
172 | raise exception
173 |
174 | def absolute_price_oscillator(data, short_period, long_period, matype=0):
175 | """Absolute Price Oscillator"""
176 | try:
177 | logger.info(
178 | 'Calculating Absolute Price Oscillator for Short period = {} and Long period = {}'
179 | .format(short_period, long_period))
180 | for period in (short_period, long_period):
181 | check_period_type(period)
182 |
183 | apo_data = talib.APO(data, short_period, long_period, matype=matype)
184 | return apo_data
185 | except Exception as exception:
186 | logger.error('Oops! An error Occurred ⚠️')
187 | raise exception
188 |
189 | def normalized_average_true_range(high, low, close, period):
190 | try:
191 | """Normalized Average True Range"""
192 | logger.info(
193 | 'Calculating Normalized Average True Range for period = {}'.format(
194 | period))
195 | check_period_type(period)
196 | check_inputs_length(high, low, close)
197 | natr_data = talib.NATR(high, low, close, timeperiod=period)
198 | return natr_data
199 | except Exception as exception:
200 | logger.error('Oops! An error Occurred ⚠️')
201 | raise exception
202 |
203 | def true_range(high, low, close):
204 | """True Range"""
205 | try:
206 | logger.info('Calculating True Range...')
207 | check_inputs_length(high, low, close)
208 |
209 | except Exception as exception:
210 | logger.error('Oops! An error Occurred ⚠️')
211 | raise exception
212 |
213 | def balance_of_power(open, high, low, close):
214 | """Balance of Power"""
215 | try:
216 | logger.info("Calculating balance of Power...")
217 | check_inputs_length(open, high, low, close)
218 | bop_data = talib.BOP(open, high, low, close)
219 | return bop_data
220 | except Exception as exception:
221 | logger.error('Oops! An error Occurred ⚠️')
222 | raise exception
223 |
224 |
225 | def correlation_coefficient(high, low, period):
226 | """Correlation Coefficient"""
227 | try:
228 | logger.info(
229 | "Calculating Correlation Coefficient for period = {}".format(
230 | period))
231 | check_period_type(period)
232 | check_inputs_length(high, low)
233 | cor_co_data = np.corrcoef(high,low)#talib.CORREL(high, low, timeperiod=period)
234 | return cor_co_data
235 | except Exception as exception:
236 | logger.error('Oops! An error Occurred ⚠️')
237 | raise exception
238 |
239 | def chaikin_oscillator(high,
240 | low,
241 | close,
242 | volume,
243 | short_period=3,
244 | long_period=10):
245 | """Chaiking oscillator"""
246 | try:
247 | logger.info(
248 | 'Calculating Chaikin Oscillator for short period = {} and long period = {}'
249 | .format(short_period, long_period))
250 | check_inputs_length(high, low, close, volume)
251 | for period in (short_period, long_period):
252 | check_period_type(period)
253 | df = pd.DataFrame()
254 | df['chaikin_ad_line'] = talib.AD(high, low, close, volume)
255 | df['chaikin_oscillator'] = talib.ADOSC(high,
256 | low,
257 | close,
258 | volume,
259 | fastperiod=short_period,
260 | slowperiod=long_period)
261 | return df
262 | except Exception as exception:
263 | logger.error('Oops! An error Occurred ⚠️')
264 | raise exception
265 |
266 | def positive_directional_movement(high, low):
267 | """
268 | Positive Directional Movement
269 | """
270 | try:
271 | up_moves = [high[idx] - high[idx-1] for idx in range(1, len(high))]
272 | down_moves = [low[idx] - low[idx-1] for idx in range(1, len(low))]
273 |
274 | pdm = []
275 | for idx in range(0, len(up_moves)):
276 | if up_moves[idx] > down_moves[idx] and up_moves[idx] > 0:
277 | pdm.append(up_moves[idx])
278 | else:
279 | pdm.append(0)
280 |
281 | return pdm
282 | except Exception as exception:
283 | raise exception
284 |
285 | def negative_directional_movement(high, low):
286 | """
287 | Negative Directional Movement
288 | """
289 | up_moves = [high[idx] - high[idx-1] for idx in range(1, len(high))]
290 | down_moves = [low[idx] - low[idx-1] for idx in range(1, len(low))]
291 |
292 | ndm = []
293 | for idx in range(0, len(down_moves)):
294 | if down_moves[idx] > up_moves[idx] and down_moves[idx] > 0:
295 | ndm.append(down_moves[idx])
296 | else:
297 | ndm.append(0)
298 |
299 | return ndm
300 |
301 | def positive_directional_index(high, low, close, period, ignore_log=False):
302 | """positive directional index"""
303 | try:
304 | if ignore_log!=True:
305 | logger.info("Calculating Positive Directional Index for period = {}".format(period))
306 | pdi = (100 *
307 | smma(positive_directional_movement(high, low), period) /
308 | atr(close, period)
309 | )
310 | return pdi
311 | except Exception as exception:
312 | logger.error('Oops! An error Occurred ⚠️')
313 | raise exception
314 |
315 |
316 | def negative_directional_index(high, low, close, period,ignore_log=False):
317 | try:
318 | """negative directional index"""
319 | if ignore_log!=True:
320 | logger.info("Calculating Negative Directional Index for period = {}".format(period))
321 | ndi = (100 *
322 | smma(negative_directional_movement(high, low), period) /
323 | atr(close, period)
324 | )
325 | return ndi
326 | except Exception as exception:
327 | logger.error('Oops! An error Occurred ⚠️')
328 | raise exception
329 |
330 |
331 | def average_directional_index(high, low, close, period):
332 | """Average Directional Index"""
333 | try:
334 | logger.info(
335 | 'Calculating Average Directional Index for period = {}'.
336 | format(period))
337 | check_period_type(period)
338 | check_inputs_length(high, low, close)
339 |
340 | avg_di = (abs((positive_directional_index(close, high, low, period,ignore_log=True) - negative_directional_index(close, high, low, period,ignore_log=True)) /
341 | (positive_directional_index(
342 | close, high, low, period,ignore_log=True) +
343 | negative_directional_index(
344 | close, high, low, period,ignore_log=True)))
345 | )
346 | adx = 100 * smma(avg_di, period)
347 | return adx
348 | except Exception as exception:
349 | logger.error('Oops! An error Occurred ⚠️')
350 | raise exception
351 |
352 |
353 | def directional_movement_index(high, low, close, period):
354 | """Directional Movement Index"""
355 | try:
356 | logger.info(
357 | "Calculating Directional Movement Index for period = {}".format(
358 | period))
359 | check_period_type(period)
360 | check_inputs_length(high, low, close)
361 | dmo_data = talib.DX(high, low, close, timeperiod=period)
362 | return dmo_data
363 | except Exception as exception:
364 | logger.error('Oops! An error Occurred ⚠️')
365 | raise exception
366 |
367 |
368 | def minus_directional_indicator(high, low, close, period):
369 | """Minus Directional Indicator"""
370 | try:
371 | logger.info(
372 | 'Calculating Minus Directional Indicator for period = {}'.format(
373 | period))
374 | check_period_type(period)
375 | check_inputs_length(high, low, close)
376 | mdi_data = talib.MINUS_DI(high, low, close, timeperiod=period)
377 | return mdi_data
378 | except Exception as exception:
379 | logger.error('Oops! An error Occurred ⚠️')
380 | raise exception
381 |
382 |
383 | def minus_directional_movement(high, low, close, period):
384 | """Minus Directional Movement"""
385 | try:
386 | logger.info(
387 | 'Calculating Minus Directional Movement for period = {}'.format(
388 | period))
389 | check_period_type(period)
390 | check_inputs_length(high, low, close)
391 | mdm_data = talib.MINUS_DM(high, low, timeperiod=period)
392 | return mdm_data
393 | except Exception as exception:
394 | logger.error('Oops! An error Occurred ⚠️')
395 | raise exception
396 |
397 | def plus_directional_indicator(high, low, close, period):
398 | """Plus Directional Indicator"""
399 | try:
400 | logger.info(
401 | 'Calcluating Plus Directional Indicator for period = {}'.format(
402 | period))
403 | check_period_type(period)
404 | check_inputs_length(high, low, close)
405 | pdi_data = talib.PLUS_DI(high, low, close, timeperiod=period)
406 | return pdi_data
407 | except Exception as exception:
408 | logger.error('Oops! An error Occurred ⚠️')
409 | raise exception
410 |
411 |
412 | def plus_directional_movement(high, low, close, period):
413 | """Plus Directional Movement"""
414 | try:
415 | logger.info(
416 | 'Calcluating Plus Directional Movement for period = {}'.format(
417 | period))
418 | check_period_type(period)
419 | check_inputs_length(high, low, close)
420 | pdm_data = talib.PLUS_DM(high, low, timeperiod=period)
421 | return pdm_data
422 | except Exception as exception:
423 | logger.error('Oops! An error Occurred ⚠️')
424 | raise exception
425 |
426 | '''
427 |
--------------------------------------------------------------------------------
/libkloudtrader/backtest.py:
--------------------------------------------------------------------------------
1 | '''
2 | import pandas as pd
3 | from libkloudtrader.exceptions import InvalidPricePoint
4 |
5 |
6 | class Backtest():
7 | def __init__(self, locals, preferred_price_point):
8 | self.buy_signal = locals['buy']
9 | self.sell_signal = locals['sell']
10 | self.cover_signal = locals['cover']
11 | self.short_signal = locals['short']
12 | self.data_to_bakctest_on = locals['data']
13 | self.default_price = preferred_price_point
14 | if self.default_price.lower() not in ('open', 'high', 'low', 'close'):
15 | raise InvalidPricePoint(
16 | "Invalid price point. Please select a price point from 'open','high','low','close'"
17 | )
18 |
19 | @property
20 | def signals(self):
21 | df = pd.DataFrame()
22 | df['buy'] = self.buy_signal
23 | df['sell'] = self.sell_signal
24 | df['cover'] = self.cover_signal
25 | df['short'] = self.short_signal
26 | return df
27 |
28 | @property
29 | def data(self):
30 | return self.data_to_bakctest_on
31 |
32 | @property
33 | def preferred_price_point(self):
34 | return self.default_price
35 | '''
36 | import numpy as np
37 | import pandas as pd
38 |
39 | class Backtest():
40 | def __init__(self,capital:float,commission:float,enable_slippage:bool):
41 | """Init backtest"""
42 | self.capital=capital
43 | self.bar=0
44 | self.position=0
45 | self.commission=commission
46 | self.enable_slippage=enable_slippage
47 | self.slippage=0.0
48 | self.asset_price=0.0
49 | self.trades_log=pd.DataFrame(columns=['datetime','trade_type','price','fill_price','order_cost','capital','position'])
50 |
51 |
52 | def buy(self,quantity):
53 | '''emulates a buy order'''
54 | self.capital-=self.order_cost
55 | self.update_positions(quantity)
56 | self.update_trade_logs(datetime=self.bar.datetime,trade_type='Buy',price=self.asset_price,fill_price=self.fill_price,order_cost=self.order_cost,capital=self.capital,position=self.position)
57 | #print('Bought {} of stocks @ {} but price is {}'.format(quantity,self.order_cost,self.bar.close))
58 |
59 |
60 | def sell(self,quantity):
61 | '''emulates a sell order'''
62 | if self.position!=0:
63 | self.capital+=self.order_cost
64 | self.update_positions(-1*quantity)
65 | self.update_trade_logs(datetime=self.bar.datetime,trade_type='Sell',price=self.asset_price,fill_price=self.fill_price,order_cost=self.order_cost,capital=self.capital,position=self.position)
66 | #print('Sold {} of stocks @ {} but price is {}'.format(quantity,self.order_cost,self.bar.close))
67 | else:
68 | print('No position to close')
69 |
70 | def update_trade_logs(self,datetime,trade_type,price,fill_price,order_cost,capital,position):
71 | df=pd.DataFrame([{'datetime':datetime,'trade_type':trade_type,'price':price,'fill_price':fill_price,'order_cost':order_cost,'capital':capital,'position':position}])
72 | self.trades_log=self.trades_log.append(df)
73 |
74 |
75 | @property
76 | def get_trade_log(self):
77 | self.trades_log.set_index('datetime',inplace=True)
78 | return self.trades_log
79 |
80 | def update_bar(self,index,bar):
81 | self.bar=bar
82 | self.bar.datetime=index
83 | if 'price' in self.bar:
84 | self.asset_price=self.bar.price
85 | else:
86 | self.asset_price=self.bar.close
87 |
88 | def update_positions(self,quantity):
89 | self.position+=quantity
90 |
91 | @property
92 | def calculate_commission(self):
93 | return (self.commission/100)*self.fill_price
94 |
95 |
96 | @property
97 | def calculate_slippage(self):
98 | '''how is slippage calculated?'''
99 | '''slippage should not be more than 2% in most of the trades. so we generate a random percentage b/w 0-2.use that number as %age'''
100 | if self.enable_slippage:
101 | return np.random.uniform(low=0, high=0.02)*self.asset_price
102 | return 0.0
103 |
104 | @property
105 | def fill_price(self):
106 | return self.asset_price+self.calculate_slippage
107 |
108 | @property
109 | def order_cost(self):
110 | return self.fill_price+self.calculate_commission
111 |
112 |
113 | @property
114 | def getcapital(self):
115 | return self.capital
116 |
117 | @property
118 | def getbar(self):
119 | return self.bar
120 |
121 | @property
122 | def getposition(self):
123 | return self.position
124 |
125 | @property
126 | def get_portfolio(self):
127 | trade_log=self.get_trade_log
128 | portfolio=pd.DataFrame(index=trade_log.index)
129 | portfolio['holdings']=trade_log.position.multiply(trade_log.price)
130 | portfolio['cash']=trade_log.capital
131 | portfolio['total']=portfolio.cash+portfolio.holdings
132 | return portfolio
--------------------------------------------------------------------------------
/libkloudtrader/crypto.py:
--------------------------------------------------------------------------------
1 | """Trading and Data APIs for Crypto Currencies"""
2 | import requests
3 | import os
4 | from typing import Any
5 | import datetime
6 | import pandas
7 | import asyncio
8 | from libkloudtrader.exceptions import BadRequest, InvalidCredentials
9 | from libkloudtrader.logs import start_logger
10 | from libkloudtrader.crypto_operations import *
11 | """Config starts"""
12 |
13 | logger = start_logger(__name__)
14 |
15 | CRYPTO_EXCHANGE = os.environ['CRYPTO_EXCHANGE']
16 | CRYPTO_API_KEY = os.environ['CRYPTO_API_KEY']
17 | CRYPTO_API_SECRET = os.environ['CRYPTO_API_SECRET']
18 | CRYPTO_API_PASSWORD = os.environ['CRYPTO_API_PASSWORD']
19 | CRYPTO_API_UID = os.environ['CRYPTO_API_UID']
20 | CRYPTO_URL_LIVE = "https://api.kloudtrader.com/crypto/live"
21 | CRYPTO_URL_TEST = "https://api.kloudtrader.com/crypto/test"
22 |
23 |
24 | def crypto_get_headers(api_key, api_secret, exchange_password, exchange_uid):
25 | headers = {
26 | 'X-API-KEY': api_key,
27 | 'X-API-SECRET': api_secret,
28 | 'X-EXCHANGE-PASSWORD': exchange_password,
29 | 'X-EXCHANGE-UID': exchange_uid
30 | }
31 | return headers
32 |
33 |
34 | """Config ends"""
35 | """Data APis start"""
36 |
37 |
38 | def list_of_exchanges(test_mode: bool = False) -> list:
39 | """Get List of Exchanges available"""
40 | try:
41 | return ListOfExchanges(test_mode=test_mode)
42 | except Exception as exception:
43 | logger.error('Oops! An error Occurred ⚠️')
44 | raise exception
45 |
46 |
47 | def exchange_structure(exchange: str = CRYPTO_EXCHANGE) -> dict:
48 | """No Docs needed. Get the structure of an exchange"""
49 | try:
50 | check_exchange_existence(exchange=exchange)
51 | return ExchangeStructure(exchange=exchange)
52 | except Exception as exception:
53 | logger.error('Oops! An error Occurred ⚠️')
54 | raise exception
55 |
56 |
57 | def exchange_attribute(attribute: str,
58 | exchange: str = CRYPTO_EXCHANGE) -> dict:
59 | """No Docs needed. Return asked attribute of the given exchange"""
60 | try:
61 | check_exchange_existence(exchange=exchange)
62 | return ExchangeAttribute(attribute=attribute, exchange=exchange)
63 | except Exception as exception:
64 | logger.error('Oops! An error Occurred ⚠️')
65 | raise exception
66 |
67 |
68 | def markets(exchange: str = CRYPTO_EXCHANGE, rate_limit: bool = True) -> dict:
69 | """Get all the markets available in the exchange and their market structures"""
70 | try:
71 | check_exchange_existence(exchange=exchange)
72 | return asyncio.get_event_loop().run_until_complete(
73 | ExchangeMarkets(exchange=exchange, rate_limit=rate_limit))
74 | except Exception as exception:
75 | logger.error('Oops! An error Occurred ⚠️')
76 | raise exception
77 |
78 |
79 | def market_structure(symbol: str,
80 | exchange: str = CRYPTO_EXCHANGE,
81 | rate_limit: bool = True) -> dict:
82 | """Get the market structure of a particular symbol"""
83 | try:
84 | check_exchange_existence(exchange=exchange)
85 | return asyncio.get_event_loop().run_until_complete(
86 | MarketStructure(symbol=symbol,
87 | exchange=exchange,
88 | rate_limit=rate_limit))
89 | except Exception as exception:
90 | logger.error('Oops! An error Occurred ⚠️')
91 | raise exception
92 |
93 |
94 | def latest_price_info(symbol: str,
95 | exchange: str = CRYPTO_EXCHANGE,
96 | rate_limit: bool = True) -> dict:
97 | """Get quotes/ticker data for a given symbool from the given exchange"""
98 | try:
99 | check_exchange_existence(exchange=exchange)
100 | return asyncio.get_event_loop().run_until_complete(
101 | latestPriceInfo(symbol=symbol,
102 | exchange=exchange,
103 | rate_limit=rate_limit))
104 | except Exception as exception:
105 | logger.error('Oops! An error Occurred ⚠️')
106 | raise exception
107 |
108 |
109 | def latest_price_info_for_all_symbols(exchange: str = CRYPTO_EXCHANGE,
110 | rate_limit: bool = True) -> dict:
111 | """Get quotes/ticker data for all symbols listed on an exchange"""
112 | try:
113 | check_exchange_existence(exchange=exchange)
114 | return asyncio.get_event_loop().run_until_complete(
115 | latestPriceInfoForAllSymbols(exchange=exchange,
116 | rate_limit=rate_limit))
117 | except Exception as exception:
118 | logger.error('Oops! An error Occurred ⚠️')
119 | raise exception
120 |
121 |
122 | def ohlcv(symbol: str,
123 | start: Any,
124 | end: Any,
125 | interval: str = "1d",
126 | exchange: str = CRYPTO_EXCHANGE,
127 | dataframe: bool = True,
128 | rate_limit: bool = True) -> dict:
129 | """Get OHLCV/bar data.
130 | Most exchanges don't go very back in time.
131 | The very few that go need pagination which will be released soon.
132 | Some exchanges return data for today only if interval is very less like 1m, 5m, etc.
133 | Supported time interval: ["1m","5m","15m","30m","1h","1d","1w","1M"]
134 | %Y-%m-%d date format for "1d","1w","1M" and %Y-%m-%d %H:%M:%S for others
135 | """
136 | try:
137 | check_exchange_existence(exchange=exchange)
138 | return asyncio.get_event_loop().run_until_complete(
139 | getOHLCV(symbol=symbol,
140 | start=start,
141 | end=end,
142 | interval=interval,
143 | exchange=exchange,
144 | dataframe=dataframe,
145 | rate_limit=rate_limit))
146 | except Exception as exception:
147 | logger.error('Oops! An error Occurred ⚠️')
148 | raise exception
149 |
150 |
151 | def trades(symbol: str,
152 | number_of_data_points: int = 1,
153 | exchange: str = CRYPTO_EXCHANGE,
154 | rate_limit: bool = True):
155 | """Get recent trades for a particular trading symbol."""
156 | try:
157 | check_exchange_existence(exchange=exchange)
158 | return asyncio.get_event_loop().run_until_complete(
159 | latestTrades(symbol=symbol,
160 | number_of_data_points=number_of_data_points,
161 | exchange=exchange,
162 | rate_limit=rate_limit))
163 | except Exception as exception:
164 | logger.error('Oops! An error Occurred ⚠️')
165 | raise exception
166 |
167 |
168 | def latest_order_book_entry(symbol: str,
169 | exchange: str = CRYPTO_EXCHANGE,
170 | rate_limit: bool = True):
171 | """Get latest orderbook entry for a particular market trading symbol."""
172 | try:
173 | check_exchange_existence(exchange=exchange)
174 | response = asyncio.get_event_loop().run_until_complete(
175 | getOrderBook(symbol=symbol,
176 | number_of_data_points=1,
177 | exchange=exchange,
178 | rate_limit=rate_limit))
179 | latest_orderbook_entry_dict = {}
180 | latest_orderbook_entry_dict['symbol'] = symbol
181 | latest_orderbook_entry_dict['ask'] = response['asks'][0][0] if len(
182 | response['asks']) > 0 else None
183 | latest_orderbook_entry_dict['asksize'] = response['asks'][0][1] if len(
184 | response['asks']) > 0 else None
185 | latest_orderbook_entry_dict['bid'] = response['bids'][0][0] if len(
186 | response['bids']) > 0 else None
187 | latest_orderbook_entry_dict['bidsize'] = response['bids'][0][1] if len(
188 | response['bids']) > 0 else None
189 | latest_orderbook_entry_dict['datetime'] = response['datetime']
190 | latest_orderbook_entry_dict['nonce'] = response['nonce']
191 | return latest_orderbook_entry_dict
192 | except Exception as exception:
193 | logger.error('Oops! An error Occurred ⚠️')
194 | raise exception
195 |
196 |
197 | def latest_L2_order_book_entry(symbol: str,
198 | exchange: str = CRYPTO_EXCHANGE,
199 | rate_limit: bool = True):
200 | """Get latest orderbook entry for a particular market trading symbol."""
201 | try:
202 | check_exchange_existence(exchange=exchange)
203 | response = asyncio.get_event_loop().run_until_complete(
204 | getOrderBookL2(symbol=symbol,
205 | number_of_data_points=1,
206 | exchange=exchange,
207 | rate_limit=rate_limit))
208 | latest_orderbook_entry_dict = {}
209 | latest_orderbook_entry_dict['symbol'] = symbol
210 | latest_orderbook_entry_dict['ask'] = response['asks'][0][0] if len(
211 | response['asks']) > 0 else None
212 | latest_orderbook_entry_dict['asksize'] = response['asks'][0][1] if len(
213 | response['asks']) > 0 else None
214 | latest_orderbook_entry_dict['bid'] = response['bids'][0][0] if len(
215 | response['bids']) > 0 else None
216 | latest_orderbook_entry_dict['bidsize'] = response['bids'][0][1] if len(
217 | response['bids']) > 0 else None
218 | latest_orderbook_entry_dict['datetime'] = response['datetime']
219 | latest_orderbook_entry_dict['nonce'] = response['nonce']
220 | return latest_orderbook_entry_dict
221 | except Exception as exception:
222 | logger.error('Oops! An error Occurred ⚠️')
223 | raise exception
224 |
225 |
226 | def order_book(symbol: str,
227 | number_of_data_points: int = 1,
228 | exchange: str = CRYPTO_EXCHANGE,
229 | rate_limit: bool = True):
230 | """Get order book for a particular symbol."""
231 | try:
232 | check_exchange_existence(exchange=exchange)
233 | return asyncio.get_event_loop().run_until_complete(
234 | getOrderBook(symbol=symbol,
235 | number_of_data_points=number_of_data_points,
236 | exchange=exchange,
237 | rate_limit=rate_limit))
238 | except Exception as exception:
239 | logger.error('Oops! An error Occurred ⚠️')
240 | raise exception
241 |
242 |
243 | def L2_order_book(symbol: str,
244 | number_of_data_points: int = 1,
245 | exchange: str = CRYPTO_EXCHANGE,
246 | rate_limit: bool = True):
247 | """Level 2 (price-aggregated) order book for a particular symbol."""
248 | try:
249 | check_exchange_existence(exchange=exchange)
250 | return asyncio.get_event_loop().run_until_complete(
251 | getOrderBookL2(symbol=symbol,
252 | number_of_data_points=number_of_data_points,
253 | exchange=exchange,
254 | rate_limit=rate_limit))
255 | except Exception as exception:
256 | logger.error('Oops! An error Occurred ⚠️')
257 | raise exception
258 |
259 |
260 | def currencies(exchange: str = CRYPTO_EXCHANGE,
261 | rate_limit: bool = True) -> dict:
262 | """Get all Currencies available on an exchange"""
263 | try:
264 | check_exchange_existence(exchange=exchange)
265 | return asyncio.get_event_loop().run_until_complete(
266 | getCurrencies(exchange=exchange, rate_limit=rate_limit))
267 | except Exception as exception:
268 | logger.error('Oops! An error Occurred ⚠️')
269 | raise exception
270 |
271 |
272 | """Data APis end"""
273 | """User APIs start"""
274 |
275 |
276 | def user_balance(exchange: str = CRYPTO_EXCHANGE,
277 | api_key: str = CRYPTO_API_KEY,
278 | api_secret: str = CRYPTO_API_SECRET,
279 | exchange_password: Any = CRYPTO_API_PASSWORD,
280 | exchange_uid: Any = CRYPTO_API_UID,
281 | test_mode: bool = False) -> Any:
282 | """Get your account balance"""
283 | try:
284 | if test_mode == True:
285 | url = CRYPTO_URL_TEST
286 | else:
287 | url = CRYPTO_URL_LIVE
288 | response = requests.post('{}/balance/{}'.format(url, exchange),
289 | headers=crypto_get_headers(
290 | api_key, api_secret, exchange_password,
291 | exchange_uid))
292 | if response:
293 | return response.json()
294 | if response.status_code == 400:
295 | logger.error('Oops! An error Occurred ⚠️')
296 | raise BadRequest(response.text)
297 | if response.status_code == 401:
298 | logger.error('Oops! An error Occurred ⚠️')
299 | raise InvalidCredentials(response.text)
300 | except Exception as exception:
301 | logger.error('Oops! An error Occurred ⚠️')
302 | raise exception
303 |
304 |
305 | def user_ledger(currency_code: str,
306 | exchange: str = CRYPTO_EXCHANGE,
307 | api_key: str = CRYPTO_API_KEY,
308 | api_secret: str = CRYPTO_API_SECRET,
309 | exchange_password: Any = CRYPTO_API_PASSWORD,
310 | exchange_uid: Any = CRYPTO_API_UID,
311 | test_mode: bool = False) -> Any:
312 | """Get your latest ledger history"""
313 | try:
314 | if test_mode == True:
315 | url = CRYPTO_URL_TEST
316 | else:
317 | url = CRYPTO_URL_LIVE
318 | payload = {'currency_code': currency_code}
319 | response = requests.post('{}/ledger/{}'.format(url, exchange),
320 | headers=crypto_get_headers(
321 | api_key, api_secret, exchange_password,
322 | exchange_uid),
323 | json=payload)
324 | if response:
325 | return response.json()
326 | if response.status_code == 400:
327 | logger.error('Oops! An error Occurred ⚠️')
328 | raise BadRequest(response.text)
329 | if response.status_code == 401:
330 | logger.error('Oops! An error Occurred ⚠️')
331 | raise InvalidCredentials(response.text)
332 | except Exception as exception:
333 | logger.error('Oops! An error Occurred ⚠️')
334 | raise exception
335 |
336 |
337 | def user_trades(symbol: str,
338 | exchange: str = CRYPTO_EXCHANGE,
339 | api_key: str = CRYPTO_API_KEY,
340 | api_secret: str = CRYPTO_API_SECRET,
341 | exchange_password: Any = CRYPTO_API_PASSWORD,
342 | exchange_uid: Any = CRYPTO_API_UID,
343 | test_mode: bool = False):
344 | """Get your trades"""
345 | try:
346 | if test_mode == True:
347 | url = CRYPTO_URL_TEST
348 | else:
349 | url = CRYPTO_URL_LIVE
350 | payload = {'symbol': symbol.upper(), 'start': "", 'end': ""}
351 | response = requests.post('{}/my_trades/{}'.format(url, exchange),
352 | headers=crypto_get_headers(
353 | api_key, api_secret, exchange_password,
354 | exchange_uid),
355 | json=payload)
356 | if response:
357 | return response.json()
358 | if response.status_code == 400:
359 | logger.error('Oops! An error Occurred ⚠️')
360 | raise BadRequest(response.text)
361 | if response.status_code == 401:
362 | logger.error('Oops! An error Occurred ⚠️')
363 | raise InvalidCredentials(response.text)
364 | except Exception as exception:
365 | logger.error('Oops! An error Occurred ⚠️')
366 | raise exception
367 |
368 |
369 | def user_closed_orders(symbol: str,
370 | exchange: str = CRYPTO_EXCHANGE,
371 | api_key: str = CRYPTO_API_KEY,
372 | api_secret: str = CRYPTO_API_SECRET,
373 | exchange_password: Any = CRYPTO_API_PASSWORD,
374 | exchange_uid: Any = CRYPTO_API_UID,
375 | test_mode: bool = False) -> Any:
376 | """Get all of your closed orders"""
377 | try:
378 | if test_mode == True:
379 | url = CRYPTO_URL_TEST
380 | else:
381 | url = CRYPTO_URL_LIVE
382 | payload = {'symbol': symbol.upper(), 'start': "", 'end': ""}
383 | response = requests.post('{}/closed_orders/{}'.format(url, exchange),
384 | headers=crypto_get_headers(
385 | api_key, api_secret, exchange_password,
386 | exchange_uid),
387 | json=payload)
388 | if response:
389 | return response.json()
390 | if response.status_code == 400:
391 | logger.error('Oops! An error Occurred ⚠️')
392 | raise BadRequest(response.text)
393 | if response.status_code == 401:
394 | logger.error('Oops! An error Occurred ⚠️')
395 | raise InvalidCredentials(response.text)
396 | except Exception as exception:
397 | logger.error('Oops! An error Occurred ⚠️')
398 | raise exception
399 |
400 |
401 | def get_order(order_id: str,
402 | symbol: str,
403 | exchange: str = CRYPTO_EXCHANGE,
404 | api_key: str = CRYPTO_API_KEY,
405 | api_secret: str = CRYPTO_API_SECRET,
406 | exchange_password: Any = CRYPTO_API_PASSWORD,
407 | exchange_uid: Any = CRYPTO_API_UID,
408 | test_mode: bool = False) -> Any:
409 | """Get information about a specific order"""
410 | try:
411 | if test_mode == True:
412 | url = CRYPTO_URL_TEST
413 | else:
414 | url = CRYPTO_URL_LIVE
415 | payload = {'order_id': str(order_id), 'symbol': symbol.upper()}
416 | response = requests.post('{}/get_order/{}'.format(url, exchange),
417 | headers=crypto_get_headers(
418 | api_key, api_secret, exchange_password,
419 | exchange_uid),
420 | json=payload)
421 | if response:
422 | return response.json()
423 | if response.status_code == 400:
424 | logger.error('Oops! An error Occurred ⚠️')
425 | raise BadRequest(response.text)
426 | if response.status_code == 401:
427 | logger.error('Oops! An error Occurred ⚠️')
428 | raise InvalidCredentials(response.text)
429 | except Exception as exception:
430 | logger.error('Oops! An error Occurred ⚠️')
431 | raise exception
432 |
433 |
434 | def user_orders(symbol: str,
435 | exchange: str = CRYPTO_EXCHANGE,
436 | api_key: str = CRYPTO_API_KEY,
437 | api_secret: str = CRYPTO_API_SECRET,
438 | exchange_password: Any = CRYPTO_API_PASSWORD,
439 | exchange_uid: Any = CRYPTO_API_UID,
440 | test_mode: bool = False) -> Any:
441 | """Get all of your orders"""
442 | try:
443 | if test_mode == True:
444 | url = CRYPTO_URL_TEST
445 | else:
446 | url = CRYPTO_URL_LIVE
447 | payload = {'symbol': symbol.upper(), 'start': "", 'end': ""}
448 | response = requests.post('{}/get_orders/{}'.format(url, exchange),
449 | headers=crypto_get_headers(
450 | api_key, api_secret, exchange_password,
451 | exchange_uid),
452 | json=payload)
453 | if response:
454 | return response.json()
455 | if response.status_code == 400:
456 | logger.error('Oops! An error Occurred ⚠️')
457 | raise BadRequest(response.text)
458 | if response.status_code == 401:
459 | logger.error('Oops! An error Occurred ⚠️')
460 | raise InvalidCredentials(response.text)
461 | except Exception as exception:
462 | logger.error('Oops! An error Occurred ⚠️')
463 | raise exception
464 |
465 |
466 | def user_positions(exchange: str = CRYPTO_EXCHANGE,
467 | api_key: str = CRYPTO_API_KEY,
468 | api_secret: str = CRYPTO_API_SECRET,
469 | exchange_password: Any = CRYPTO_API_PASSWORD,
470 | exchange_uid: Any = CRYPTO_API_UID,
471 | test_mode: bool = False) -> Any:
472 | """get your positions"""
473 | try:
474 | if test_mode == True:
475 | url = CRYPTO_URL_TEST
476 | else:
477 | url = CRYPTO_URL_LIVE
478 | response = requests.post('{}/positions/{}'.format(url, exchange),
479 | headers=crypto_get_headers(
480 | api_key, api_secret, exchange_password,
481 | exchange_uid))
482 | if response:
483 | return response.json()
484 | if response.status_code == 400:
485 | logger.error('Oops! An error Occurred ⚠️')
486 | raise BadRequest(response.text)
487 | if response.status_code == 401:
488 | logger.error('Oops! An error Occurred ⚠️')
489 | raise InvalidCredentials(response.text)
490 | except Exception as exception:
491 | logger.error('Oops! An error Occurred ⚠️')
492 | raise exception
493 |
494 |
495 | def create_deposit_address(currency_code: str,
496 | exchange: str = CRYPTO_EXCHANGE,
497 | api_key: str = CRYPTO_API_KEY,
498 | api_secret: str = CRYPTO_API_SECRET,
499 | exchange_password: Any = CRYPTO_API_PASSWORD,
500 | exchange_uid: Any = CRYPTO_API_UID,
501 | test_mode: bool = False) -> Any:
502 | """Not in docs yet. Needs to be tested. Create a deposit address"""
503 | try:
504 | if test_mode == True:
505 | url = CRYPTO_URL_TEST
506 | else:
507 | url = CRYPTO_URL_LIVE
508 | payload = {'currency_code': currency_code}
509 | response = requests.post(
510 | '{}/create_deposit_address/{}'.format(url, exchange),
511 | headers=crypto_get_headers(api_key, api_secret, exchange_password,
512 | exchange_uid),
513 | json=payload)
514 | if response:
515 | return response.json()
516 | if response.status_code == 400:
517 | logger.error('Oops! An error Occurred ⚠️')
518 | raise BadRequest(response.text)
519 | if response.status_code == 401:
520 | logger.error('Oops! An error Occurred ⚠️')
521 | raise InvalidCredentials(response.text)
522 | except Exception as exception:
523 | logger.error('Oops! An error Occurred ⚠️')
524 | raise exception
525 |
526 |
527 | def user_deposits(currency_code: str,
528 | exchange: str = CRYPTO_EXCHANGE,
529 | api_key: str = CRYPTO_API_KEY,
530 | api_secret: str = CRYPTO_API_SECRET,
531 | exchange_password: Any = CRYPTO_API_PASSWORD,
532 | exchange_uid: Any = CRYPTO_API_UID,
533 | test_mode: bool = False) -> Any:
534 | """Not in docs yet. Needs to be tested.Get your Deposits"""
535 | try:
536 | if test_mode == True:
537 | url = CRYPTO_URL_TEST
538 | else:
539 | url = CRYPTO_URL_LIVE
540 | payload = {'currency_code': currency_code}
541 | response = requests.post('{}/deposits/{}'.format(url, exchange),
542 | headers=crypto_get_headers(
543 | api_key, api_secret, exchange_password,
544 | exchange_uid),
545 | json=payload)
546 | if response:
547 | return response.json()
548 | if response.status_code == 400:
549 | logger.error('Oops! An error Occurred ⚠️')
550 | raise BadRequest(response.text)
551 | if response.status_code == 401:
552 | logger.error('Oops! An error Occurred ⚠️')
553 | raise InvalidCredentials(response.text)
554 | except Exception as exception:
555 | logger.error('Oops! An error Occurred ⚠️')
556 | raise exception
557 |
558 |
559 | def user_deposit_address(currency_code: str,
560 | exchange: str = CRYPTO_EXCHANGE,
561 | api_key: str = CRYPTO_API_KEY,
562 | api_secret: str = CRYPTO_API_SECRET,
563 | exchange_password: Any = CRYPTO_API_PASSWORD,
564 | exchange_uid: Any = CRYPTO_API_UID,
565 | test_mode: bool = False) -> Any:
566 | """Not in docs yet. Needs to be tested.Get your Deposit addresses"""
567 | try:
568 | if test_mode == True:
569 | url = CRYPTO_URL_TEST
570 | else:
571 | url = CRYPTO_URL_LIVE
572 | payload = {'currency_code': currency_code}
573 | response = requests.post('{}/deposit_address/{}'.format(url, exchange),
574 | headers=crypto_get_headers(
575 | api_key, api_secret, exchange_password,
576 | exchange_uid),
577 | json=payload)
578 | if response:
579 | return response.json()
580 | if response.status_code == 400:
581 | logger.error('Oops! An error Occurred ⚠️')
582 | raise BadRequest(response.text)
583 | if response.status_code == 401:
584 | logger.error('Oops! An error Occurred ⚠️')
585 | raise InvalidCredentials(response.text)
586 | except Exception as exception:
587 | logger.error('Oops! An error Occurred ⚠️')
588 | raise exception
589 |
590 |
591 | def user_withdrawls(currency_code: str,
592 | exchange: str = CRYPTO_EXCHANGE,
593 | api_key: str = CRYPTO_API_KEY,
594 | api_secret: str = CRYPTO_API_SECRET,
595 | exchange_password: Any = CRYPTO_API_PASSWORD,
596 | exchange_uid: Any = CRYPTO_API_UID,
597 | test_mode: bool = False) -> Any:
598 | """Not in docs yet. Needs to be tested.Get your withdrawls"""
599 | try:
600 | if test_mode == True:
601 | url = CRYPTO_URL_TEST
602 | else:
603 | url = CRYPTO_URL_LIVE
604 | payload = {'currency_code': currency_code}
605 | response = requests.post('{}/withdrawls/{}'.format(url, exchange),
606 | headers=crypto_get_headers(
607 | api_key, api_secret, exchange_password,
608 | exchange_uid),
609 | json=payload)
610 | if response:
611 | return response.json()
612 | if response.status_code == 400:
613 | logger.error('Oops! An error Occurred ⚠️')
614 | raise BadRequest(response.text)
615 | if response.status_code == 401:
616 | logger.error('Oops! An error Occurred ⚠️')
617 | raise InvalidCredentials(response.text)
618 | except Exception as exception:
619 | logger.error('Oops! An error Occurred ⚠️')
620 | raise exception
621 |
622 |
623 | def user_transactions(currency_code: str,
624 | exchange: str = CRYPTO_EXCHANGE,
625 | api_key: str = CRYPTO_API_KEY,
626 | api_secret: str = CRYPTO_API_SECRET,
627 | exchange_password: Any = CRYPTO_API_PASSWORD,
628 | exchange_uid: Any = CRYPTO_API_UID,
629 | test_mode: bool = False) -> Any:
630 | """Get your transactions"""
631 | try:
632 | if test_mode == True:
633 | url = CRYPTO_URL_TEST
634 | else:
635 | url = CRYPTO_URL_LIVE
636 | payload = {'currency_code': currency_code}
637 | response = requests.post('{}/transactions/{}'.format(url, exchange),
638 | headers=crypto_get_headers(
639 | api_key, api_secret, exchange_password,
640 | exchange_uid),
641 | json=payload)
642 | if response:
643 | return response.json()
644 | if response.status_code == 400:
645 | logger.error('Oops! An error Occurred ⚠️')
646 | raise BadRequest(response.text)
647 | if response.status_code == 401:
648 | logger.error('Oops! An error Occurred ⚠️')
649 | raise InvalidCredentials(response.text)
650 | except Exception as exception:
651 | logger.error('Oops! An error Occurred ⚠️')
652 | raise exception
653 |
654 |
655 | '''User APIs end'''
656 | '''Trading APIs begin'''
657 |
658 |
659 | def buy(symbol: str,
660 | quantity: Any,
661 | order_type: str = "market",
662 | price: Any = None,
663 | exchange: str = CRYPTO_EXCHANGE,
664 | api_key: str = CRYPTO_API_KEY,
665 | api_secret: str = CRYPTO_API_SECRET,
666 | exchange_password: Any = CRYPTO_API_PASSWORD,
667 | exchange_uid: Any = CRYPTO_API_UID,
668 | test_mode: bool = False) -> Any:
669 | """Create a buy order"""
670 | try:
671 | if test_mode == True:
672 | url = CRYPTO_URL_TEST
673 | else:
674 | url = CRYPTO_URL_LIVE
675 | payload = {
676 | 'symbol': symbol.upper(),
677 | 'quantity': quantity,
678 | 'order_type': order_type,
679 | 'limitPrice': price
680 | }
681 | response = requests.post('{}/buy/{}'.format(url, exchange),
682 | headers=crypto_get_headers(
683 | api_key, api_secret, exchange_password,
684 | exchange_uid),
685 | json=payload)
686 | if response:
687 | return response.json()
688 | if response.status_code == 400:
689 | logger.error('Oops! An error Occurred ⚠️')
690 | raise BadRequest(response.text)
691 | if response.status_code == 401:
692 | logger.error('Oops! An error Occurred ⚠️')
693 | raise InvalidCredentials(response.text)
694 | except Exception as exception:
695 | logger.error('Oops! An error Occurred ⚠️')
696 | raise exception
697 |
698 |
699 | def sell(symbol: str,
700 | quantity: Any,
701 | order_type: str = "market",
702 | price: Any = None,
703 | exchange: str = CRYPTO_EXCHANGE,
704 | api_key: str = CRYPTO_API_KEY,
705 | api_secret: str = CRYPTO_API_SECRET,
706 | exchange_password: Any = CRYPTO_API_PASSWORD,
707 | exchange_uid: Any = CRYPTO_API_UID,
708 | test_mode: bool = False) -> Any:
709 | """Create a sell order"""
710 | try:
711 | if test_mode == True:
712 | url = CRYPTO_URL_TEST
713 | else:
714 | url = CRYPTO_URL_LIVE
715 | payload = {
716 | 'symbol': symbol.upper(),
717 | 'quantity': quantity,
718 | 'order_type': order_type,
719 | 'limitPrice': price
720 | }
721 | response = requests.post('{}/sell/{}'.format(url, exchange),
722 | headers=crypto_get_headers(
723 | api_key, api_secret, exchange_password,
724 | exchange_uid),
725 | json=payload)
726 | if response:
727 | return response.json()
728 | if response.status_code == 400:
729 | logger.error('Oops! An error Occurred ⚠️')
730 | raise BadRequest(response.text)
731 | if response.status_code == 401:
732 | logger.error('Oops! An error Occurred ⚠️')
733 | raise InvalidCredentials(response.text)
734 | except Exception as exception:
735 | logger.error('Oops! An error Occurred ⚠️')
736 | raise exception
737 |
738 |
739 | def cancel_order(order_id: str,
740 | exchange: str = CRYPTO_EXCHANGE,
741 | api_key: str = CRYPTO_API_KEY,
742 | api_secret: str = CRYPTO_API_SECRET,
743 | exchange_password: Any = CRYPTO_API_PASSWORD,
744 | exchange_uid: Any = CRYPTO_API_UID,
745 | test_mode: bool = False) -> Any:
746 | """Cancel a specific order"""
747 | try:
748 | if test_mode == True:
749 | url = CRYPTO_URL_TEST
750 | else:
751 | url = CRYPTO_URL_LIVE
752 | payload = {'order_id': order_id}
753 | response = requests.post('{}/cancel_order/{}'.format(url, exchange),
754 | headers=crypto_get_headers(
755 | api_key, api_secret, exchange_password,
756 | exchange_uid),
757 | json=payload)
758 | if response:
759 | return response.json()
760 | if response.status_code == 400:
761 | logger.error('Oops! An error Occurred ⚠️')
762 | raise BadRequest(response.text)
763 | if response.status_code == 401:
764 | logger.error('Oops! An error Occurred ⚠️')
765 | raise InvalidCredentials(response.text)
766 | except Exception as exception:
767 | logger.error('Oops! An error Occurred ⚠️')
768 | raise exception
769 |
770 |
771 | '''Functions not in documentation'''
772 |
773 |
774 | def incoming_tick_data_handler(symbol: str,
775 | number_of_data_points: int = 1,
776 | fake_feed: bool = False):
777 | latest_orderbook_entry = order_book(symbol, number_of_data_points=1)
778 | latest_trades = trades(symbol, number_of_data_points=1)
779 | latest_price=latest_price_info(symbol)
780 | latest_orderbook_entry_dict = {}
781 | latest_orderbook_entry_dict['symbol'] = symbol
782 | latest_orderbook_entry_dict['ask'] = latest_orderbook_entry['asks'][0][
783 | 0] if len(latest_orderbook_entry['asks']) > 0 else None
784 | latest_orderbook_entry_dict['asksize'] = latest_orderbook_entry['asks'][0][
785 | 1] if len(latest_orderbook_entry['asks']) > 0 else None
786 | latest_orderbook_entry_dict['bid'] = latest_orderbook_entry['bids'][0][
787 | 0] if len(latest_orderbook_entry['bids']) > 0 else None
788 | latest_orderbook_entry_dict['bidsize'] = latest_orderbook_entry['bids'][0][
789 | 1] if len(latest_orderbook_entry['bids']) > 0 else None
790 | latest_orderbook_entry_dict['quotedate'] = latest_orderbook_entry[
791 | 'datetime']
792 | latest_orderbook_entry_dict['nonce'] = latest_orderbook_entry['nonce']
793 | latest_orderbook_entry_dict['price'] = latest_trades[0]['price']
794 | latest_orderbook_entry_dict['tradesize'] = latest_trades[0]['amount']
795 | latest_orderbook_entry_dict['tradedate'] = latest_trades[0]['datetime']
796 | latest_orderbook_entry_dict['open']=latest_price['open']
797 | latest_orderbook_entry_dict['high']=latest_price['high']
798 | latest_orderbook_entry_dict['low']=latest_price['low']
799 | latest_orderbook_entry_dict['close']=latest_price['close']
800 | return latest_orderbook_entry_dict
801 |
802 |
803 | def incoming_tick_data_handler_level2(symbol: str,
804 | number_of_data_points: int = 1,
805 | fake_feed: bool = False):
806 | latest_orderbook_entry = L2_order_book(symbol, number_of_data_points=1)
807 | latest_trades = trades(symbol, number_of_data_points=1)
808 | latest_orderbook_entry_dict = {}
809 | latest_orderbook_entry_dict['symbol'] = symbol
810 | latest_orderbook_entry_dict['ask'] = latest_orderbook_entry['asks'][0][
811 | 0] if len(latest_orderbook_entry['asks']) > 0 else None
812 | latest_orderbook_entry_dict['asksize'] = latest_orderbook_entry['asks'][0][
813 | 1] if len(latest_orderbook_entry['asks']) > 0 else None
814 | latest_orderbook_entry_dict['bid'] = latest_orderbook_entry['bids'][0][
815 | 0] if len(latest_orderbook_entry['bids']) > 0 else None
816 | latest_orderbook_entry_dict['bidsize'] = latest_orderbook_entry['bids'][0][
817 | 1] if len(latest_orderbook_entry['bids']) > 0 else None
818 | latest_orderbook_entry_dict['quotedate'] = latest_orderbook_entry[
819 | 'datetime']
820 | latest_orderbook_entry_dict['nonce'] = latest_orderbook_entry['nonce']
821 | latest_orderbook_entry_dict['price'] = latest_trades[0]['price']
822 | latest_orderbook_entry_dict['tradesize'] = latest_trades[0]['amount']
823 | latest_orderbook_entry_dict['tradedate'] = latest_trades[0]['datetime']
824 | return latest_orderbook_entry_dict
825 |
--------------------------------------------------------------------------------
/libkloudtrader/crypto_operations.py:
--------------------------------------------------------------------------------
1 | from typing import Any
2 | import datetime
3 | import ccxt.async_support as ccxt
4 | import ccxt as non_async_ccxt
5 | from libkloudtrader.exceptions import InvlaidTimeInterval, FunctionalityNotSupported, BadRequest, OrderError, AccountError, AuthError, ResponseError, ExchangeError, NetworkError, InvalidCryptoExchange
6 | from libkloudtrader.logs import start_logger
7 |
8 | logger = start_logger(__name__)
9 |
10 |
11 | def check_exchange_existence(exchange: str) -> bool:
12 | try:
13 | if exchange in non_async_ccxt.exchanges:
14 | return True
15 | raise InvalidCryptoExchange('Exchange not supported as of now.')
16 | except Exception as exception:
17 | raise exception
18 |
19 |
20 | def ListOfExchanges(test_mode: bool) -> list:
21 | try:
22 | if test_mode:
23 | list_of_exchanges = non_async_ccxt.exchanges
24 | list_of_exchanges_with_test_mode = []
25 | for exchange in list_of_exchanges:
26 | initiate_exchange = getattr(non_async_ccxt, exchange)
27 | exchange_class = initiate_exchange({
28 | 'id': exchange,
29 | 'enableRateLimit': True
30 | })
31 | if 'test' in exchange_class.urls:
32 | list_of_exchanges_with_test_mode.append(exchange)
33 | return list_of_exchanges_with_test_mode
34 | return non_async_ccxt.exchanges
35 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
36 | raise BadRequest(exception)
37 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
38 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
39 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
40 | raise OrderError(exception)
41 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
42 | ccxt.AccountSuspended) as exception:
43 | raise AccountError(exception)
44 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
45 | raise AuthtError(exception)
46 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
47 | raise ResponseError(exception)
48 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
49 | ccxt.ExchangeNotAvailable) as exception:
50 | logger.info(
51 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
52 | .format(exchange))
53 | import time
54 | time.sleep(5)
55 | except ccxt.ExchangeError as exception:
56 | raise ExchangeError(exception)
57 | except Exception as exception:
58 | raise exception
59 |
60 |
61 | def ExchangeStructure(exchange: str) -> dict:
62 | """Get the structure of an exchange"""
63 | try:
64 | initiate_exchange = getattr(non_async_ccxt, exchange)
65 | exchange_class = initiate_exchange({
66 | 'id': exchange,
67 | 'enableRateLimit': True
68 | })
69 | return str(exchange_class.__dict__)
70 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
71 | raise BadRequest(exception)
72 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
73 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
74 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
75 | raise OrderError(exception)
76 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
77 | ccxt.AccountSuspended) as exception:
78 | raise AccountError(exception)
79 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
80 | raise AuthtError(exception)
81 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
82 | raise ResponseError(exception)
83 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
84 | ccxt.ExchangeNotAvailable) as exception:
85 | logger.info(
86 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
87 | .format(exchange))
88 | import time
89 | time.sleep(5)
90 | except ccxt.ExchangeError as exception:
91 | raise ExchangeError(exception)
92 | except Exception as exception:
93 | raise exception
94 |
95 |
96 | def ExchangeAttribute(exchange: str, attribute: str) -> dict:
97 | """Get an attribute of the given exchange"""
98 | try:
99 | initiate_exchange = getattr(non_async_ccxt, exchange)
100 | exchange_class = initiate_exchange({
101 | 'id': exchange,
102 | 'enableRateLimit': True
103 | })
104 | exchange_attr = getattr(exchange_class, attribute)
105 | return exchange_attr
106 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
107 | raise BadRequest(exception)
108 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
109 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
110 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
111 | raise OrderError(exception)
112 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
113 | ccxt.AccountSuspended) as exception:
114 | raise AccountError(exception)
115 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
116 | raise AuthtError(exception)
117 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
118 | raise ResponseError(exception)
119 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
120 | ccxt.ExchangeNotAvailable) as exception:
121 | logger.info(
122 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
123 | .format(exchange))
124 | import time
125 | time.sleep(5)
126 | except ccxt.ExchangeError as exception:
127 | raise ExchangeError(exception)
128 | except Exception as exception:
129 | raise exception
130 |
131 |
132 | async def ExchangeMarkets(exchange: str, rate_limit: str) -> dict:
133 | """Get all the markets on the given exchange"""
134 | try:
135 | init_exchange = getattr(ccxt, exchange)
136 | exchange_class = init_exchange({
137 | 'id': exchange,
138 | 'enableRateLimit': rate_limit
139 | })
140 | data = await exchange_class.loadMarkets(True)
141 | await exchange_class.close()
142 | return data
143 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
144 | await exchange_class.close()
145 | raise BadRequest(exception)
146 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
147 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
148 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
149 | await exchange_class.close()
150 | raise OrderError(exception)
151 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
152 | ccxt.AccountSuspended) as exception:
153 | await exchange_class.close()
154 | raise AccountError(exception)
155 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
156 | await exchange_class.close()
157 | raise AuthtError(exception)
158 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
159 | await exchange_class.close()
160 | raise ResponseError(exception)
161 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
162 | ccxt.ExchangeNotAvailable) as exception:
163 | await exchange_class.close()
164 | logger.info(
165 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
166 | .format(exchange))
167 | import time
168 | time.sleep(5)
169 | except ccxt.ExchangeError as exception:
170 | await exchange_class.close()
171 | raise ExchangeError(exception)
172 | except Exception as exception:
173 | await exchange_class.close()
174 | raise exception
175 |
176 |
177 | async def MarketStructure(symbol: str, exchange: str, rate_limit: str) -> dict:
178 | """Get market structure of a symbol"""
179 | try:
180 | init_exchange = getattr(ccxt, exchange)
181 | exchange_class = init_exchange({
182 | 'id': exchange,
183 | 'enableRateLimit': rate_limit
184 | })
185 | data = await exchange_class.loadMarkets(True)
186 | await exchange_class.close()
187 | return data[symbol]
188 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
189 | await exchange_class.close()
190 | raise BadRequest(exception)
191 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
192 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
193 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
194 | await exchange_class.close()
195 | raise OrderError(exception)
196 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
197 | ccxt.AccountSuspended) as exception:
198 | vexchange_class.close()
199 | raise AccountError(exception)
200 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
201 | await exchange_class.close()
202 | raise AuthtError(exception)
203 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
204 | await exchange_class.close()
205 | raise ResponseError(exception)
206 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
207 | ccxt.ExchangeNotAvailable) as exception:
208 | await exchange_class.close()
209 | logger.info(
210 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
211 | .format(exchange))
212 | import time
213 | time.sleep(5)
214 | except ccxt.ExchangeError as exception:
215 | await exchange_class.close()
216 | raise ExchangeError(exception)
217 | except Exception as exception:
218 | await exchange_class.close()
219 | raise exception
220 |
221 |
222 | async def getCurrencies(exchange: str, rate_limit: str) -> dict:
223 | """Get currencies on an exchange"""
224 | try:
225 | init_exchange = getattr(ccxt, exchange)
226 | exchange_class = init_exchange({
227 | 'id': exchange,
228 | 'enableRateLimit': rate_limit
229 | })
230 | if exchange_class.has['fetchCurrencies']:
231 | data = await exchange_class.fetchCurrencies()
232 | await exchange_class.close()
233 | return data
234 | await exchange_class.close()
235 | raise FunctionalityNotSupported(
236 | "Functionality not available for this exchange.")
237 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
238 | await exchange_class.close()
239 | raise BadRequest(exception)
240 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
241 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
242 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
243 | await exchange_class.close()
244 | raise OrderError(exception)
245 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
246 | ccxt.AccountSuspended) as exception:
247 | await exchange_class.close()
248 | raise AccountError(exception)
249 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
250 | await exchange_class.close()
251 | raise AuthtError(exception)
252 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
253 | await exchange_class.close()
254 | raise ResponseError(exception)
255 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
256 | ccxt.ExchangeNotAvailable) as exception:
257 | await exchange_class.close()
258 | logger.info(
259 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
260 | .format(exchange))
261 | import time
262 | time.sleep(5)
263 | except ccxt.ExchangeError as exception:
264 | await exchange_class.close()
265 | raise ExchangeError(exception)
266 | except Exception as exception:
267 | await exchange_class.close()
268 | raise exception
269 |
270 |
271 | async def latestPriceInfo(symbol: str, exchange: str, rate_limit: str) -> dict:
272 | """Get latest price info of a symbol"""
273 | try:
274 | init_exchange = getattr(ccxt, exchange)
275 | exchange_class = init_exchange({
276 | 'id': exchange,
277 | 'enableRateLimit': rate_limit
278 | })
279 | if exchange_class.has['fetchTicker']:
280 | data = await exchange_class.fetchTicker(symbol)
281 | await exchange_class.close()
282 | return data
283 | await exchange_class.close()
284 | raise FunctionalityNotSupported(
285 | "Functionality not available for this exchange.")
286 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
287 | await exchange_class.close()
288 | raise BadRequest(exception)
289 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
290 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
291 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
292 | await exchange_class.close()
293 | raise OrderError(exception)
294 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
295 | ccxt.AccountSuspended) as exception:
296 | await exchange_class.close()
297 | raise AccountError(exception)
298 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
299 | await exchange_class.close()
300 | raise AuthtError(exception)
301 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
302 | await exchange_class.close()
303 | raise ResponseError(exception)
304 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
305 | ccxt.ExchangeNotAvailable) as exception:
306 | await exchange_class.close()
307 | logger.info(
308 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
309 | .format(exchange))
310 | import time
311 | time.sleep(5)
312 | except ccxt.ExchangeError as exception:
313 | await exchange_class.close()
314 | raise ExchangeError(exception)
315 | except Exception as exception:
316 | await exchange_class.close()
317 | raise exception
318 |
319 |
320 | async def latestPriceInfoForAllSymbols(exchange: str, rate_limit: str) -> dict:
321 | """Get latest price info for all symbols on an exchange"""
322 | try:
323 | init_exchange = getattr(ccxt, exchange)
324 | exchange_class = init_exchange({
325 | 'id': exchange,
326 | 'enableRateLimit': rate_limit
327 | })
328 | if exchange_class.has['fetchTickers']:
329 | data = await exchange_class.fetchTickers()
330 | await exchange_class.close()
331 | return data
332 | await exchange_class.close()
333 | raise FunctionalityNotSupported(
334 | "Functionality not available for this exchange.")
335 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
336 | await exchange_class.close()
337 | raise BadRequest(exception)
338 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
339 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
340 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
341 | await exchange_class.close()
342 | raise OrderError(exception)
343 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
344 | ccxt.AccountSuspended) as exception:
345 | await exchange_class.close()
346 | raise AccountError(exception)
347 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
348 | await exchange_class.close()
349 | raise AuthtError(exception)
350 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
351 | await exchange_class.close()
352 | raise ResponseError(exception)
353 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
354 | ccxt.ExchangeNotAvailable) as exception:
355 | await exchange_class.close()
356 | logger.info(
357 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
358 | .format(exchange))
359 | import time
360 | time.sleep(5)
361 | except ccxt.ExchangeError as exception:
362 | await exchange_class.close()
363 | raise ExchangeError(exception)
364 | except Exception as exception:
365 | await exchange_class.close()
366 | raise exception
367 |
368 |
369 | async def latestTrades(symbol: str, number_of_data_points: int, exchange: str,
370 | rate_limit: str) -> dict:
371 | """Get latest trades"""
372 | try:
373 | init_exchange = getattr(ccxt, exchange)
374 | exchange_class = init_exchange({
375 | 'id': exchange,
376 | 'enableRateLimit': rate_limit
377 | })
378 | if exchange_class.has['fetchTrades']:
379 | data = await exchange_class.fetchTrades(
380 | symbol, limit=number_of_data_points)
381 | await exchange_class.close()
382 | return data
383 | await exchange_class.close()
384 | raise FunctionalityNotSupported(
385 | "Functionality not available for this exchange.")
386 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
387 | await exchange_class.close()
388 | raise BadRequest(exception)
389 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
390 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
391 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
392 | await exchange_class.close()
393 | raise OrderError(exception)
394 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
395 | ccxt.AccountSuspended) as exception:
396 | await exchange_class.close()
397 | raise AccountError(exception)
398 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
399 | await exchange_class.close()
400 | raise AuthtError(exception)
401 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
402 | await exchange_class.close()
403 | raise ResponseError(exception)
404 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
405 | ccxt.ExchangeNotAvailable) as exception:
406 | await exchange_class.close()
407 | logger.info(
408 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
409 | .format(exchange))
410 | import time
411 | time.sleep(5)
412 | except ccxt.ExchangeError as exception:
413 | await exchange_class.close()
414 | raise ExchangeError(exception)
415 | except Exception as exception:
416 | await exchange_class.close()
417 | raise exception
418 |
419 |
420 | async def getOHLCV(symbol: str, start: str, end: str, interval: str,
421 | exchange: str, dataframe: bool, rate_limit: str) -> list:
422 | """Get latest trades"""
423 | try:
424 | init_exchange = getattr(ccxt, exchange)
425 | exchange_class = init_exchange({
426 | 'id': exchange,
427 | 'enableRateLimit': rate_limit,
428 | 'options': {
429 | 'fetchOHLCVWarning': False
430 | }
431 | })
432 | if interval not in exchange_class.timeframes:
433 | raise InvlaidTimeInterval(
434 | "Time interval not supported by this exchange")
435 | if exchange_class.has['fetchOHLCV']:
436 | if interval in ["1d", "1w", "1M"]:
437 | converted_start = datetime.datetime.strptime(start, '%Y-%m-%d')
438 | converted_end = datetime.datetime.strptime(end, '%Y-%m-%d')
439 | date_time_diff = converted_end - converted_start
440 | interval_value = {'1d': 1, "1w": 7, "1M": 30}
441 | limit = int(date_time_diff.days) / int(
442 | interval_value[interval]) + 1
443 | since = int(converted_start.timestamp() * 1000)
444 | elif interval in ["1m", "5m", "15m", "30m", "1h"]:
445 | converted_start = datetime.datetime.strptime(
446 | start, '%Y-%m-%d %H:%M:%S')
447 | converted_end = datetime.datetime.strptime(
448 | end, '%Y-%m-%d %H:%M:%S')
449 | date_time_diff = converted_end - converted_start
450 | interval_value = {
451 | '1m': 1,
452 | "5m": 5,
453 | "15m": 15,
454 | "30m": 30,
455 | "1h": 60
456 | }
457 | limit = int(date_time_diff // datetime.timedelta(
458 | minutes=1)) / int(interval_value[interval]) + 1
459 | since = int(converted_start.timestamp() * 1000)
460 | else:
461 | await exchange_class.close()
462 | InvalidTimeInterval("Invalid Time Interval")
463 | data = await exchange_class.fetchOHLCV(symbol, interval, since,
464 | int(limit))
465 | final_list = []
466 | for values in range(len(data)):
467 | converted_date = float(data[values][0]) / 1000.0
468 | new_date = datetime.datetime.fromtimestamp(
469 | converted_date).strftime("%Y-%m-%d %H:%M:%S")
470 | new_list = {
471 | 'time': new_date,
472 | 'open': data[values][1],
473 | 'high': data[values][2],
474 | 'low': data[values][3],
475 | 'close': data[values][4],
476 | 'volume': data[values][5]
477 | }
478 | final_list.append(new_list)
479 | if dataframe:
480 | import pandas
481 | columns = ['time', 'open', 'high', 'low', 'close', 'volume']
482 | df = pandas.DataFrame(final_list, columns=columns)
483 | df['datetime'] = pandas.to_datetime(df['time'])
484 | df.set_index(['datetime'], inplace=True)
485 | del df['time']
486 | await exchange_class.close()
487 | return df
488 | await exchange_class.close()
489 | return final_list
490 | raise FunctionalityNotSupported(
491 | "Functionality not available for this exchange.")
492 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
493 | await exchange_class.close()
494 | raise BadRequest(exception)
495 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
496 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
497 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
498 | await exchange_class.close()
499 | raise OrderError(exception)
500 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
501 | ccxt.AccountSuspended) as exception:
502 | await exchange_class.close()
503 | raise AccountError(exception)
504 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
505 | await exchange_class.close()
506 | raise AuthtError(exception)
507 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
508 | exchange_class.close()
509 | raise ResponseError(exception)
510 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
511 | ccxt.ExchangeNotAvailable) as exception:
512 | await exchange_class.close()
513 | logger.info(
514 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
515 | .format(exchange))
516 | import time
517 | time.sleep(5)
518 | except ccxt.ExchangeError as exception:
519 | await exchange_class.close()
520 | raise ExchangeError(exception)
521 | except Exception as exception:
522 | await exchange_class.close()
523 | raise exception
524 |
525 |
526 | async def getOrderBook(symbol: str, number_of_data_points: int, exchange: str,
527 | rate_limit: str) -> dict:
528 | """Get order book"""
529 | try:
530 | init_exchange = getattr(ccxt, exchange)
531 | exchange_class = init_exchange({
532 | 'id': exchange,
533 | 'enableRateLimit': rate_limit
534 | })
535 | if exchange_class.has['fetchOrderBook']:
536 | data = await exchange_class.fetchOrderBook(
537 | symbol, limit=number_of_data_points)
538 | await exchange_class.close()
539 | return data
540 | raise FunctionalityNotSupported(
541 | "Functionality not available for this exchange.")
542 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
543 | await exchange_class.close()
544 | raise BadRequest(exception)
545 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
546 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
547 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
548 | await exchange_class.close()
549 | raise OrderError(exception)
550 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
551 | ccxt.AccountSuspended) as exception:
552 | await exchange_class.close()
553 | raise AccountError(exception)
554 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
555 | await exchange_class.close()
556 | raise AuthtError(exception)
557 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
558 | await exchange_class.close()
559 | raise ResponseError(exception)
560 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
561 | ccxt.ExchangeNotAvailable) as exception:
562 | await exchange_class.close()
563 | logger.info(
564 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
565 | .format(exchange))
566 | import time
567 | time.sleep(5)
568 | except ccxt.ExchangeError as exception:
569 | await exchange_class.close()
570 | raise ExchangeError(exception)
571 | except Exception as exception:
572 | await exchange_class.close()
573 | raise exception
574 |
575 |
576 | async def getOrderBookL2(symbol: str, number_of_data_points: int,
577 | exchange: str, rate_limit: str) -> dict:
578 | """Get order book"""
579 | try:
580 | init_exchange = getattr(ccxt, exchange)
581 | exchange_class = init_exchange({
582 | 'id': exchange,
583 | 'enableRateLimit': rate_limit
584 | })
585 | if exchange_class.has['fetchL2OrderBook']:
586 | data = await exchange_class.fetchL2OrderBook(
587 | symbol, limit=number_of_data_points)
588 | await exchange_class.close()
589 | return data
590 | raise FunctionalityNotSupported(
591 | "Functionality not available for this exchange.")
592 | except (ccxt.ArgumentsRequired, ccxt.BadRequest) as exception:
593 | await exchange_class.close()
594 | raise BadRequest(exception)
595 | except (ccxt.InvalidOrder, ccxt.OrderNotFound, ccxt.OrderNotCached,
596 | ccxt.CancelPending, ccxt.OrderImmediatelyFillable,
597 | ccxt.OrderNotFillable, ccxt.DuplicateOrderId) as exception:
598 | await exchange_class.close()
599 | raise OrderError(exception)
600 | except (ccxt.InsufficientFunds, ccxt.InvalidAddress, ccxt.AddressPending,
601 | ccxt.AccountSuspended) as exception:
602 | await exchange_class.close()
603 | raise AccountError(exception)
604 | except (ccxt.AuthenticationError, ccxt.PermissionDenied) as exception:
605 | await exchange_class.close()
606 | raise AuthtError(exception)
607 | except (ccxt.BadResponse, ccxt.NullResponse) as exception:
608 | await exchange_class.close()
609 | raise ResponseError(exception)
610 | except (ccxt.NetworkError, ccxt.RequestTimeout, ccxt.DDoSProtection,
611 | ccxt.ExchangeNotAvailable) as exception:
612 | await exchange_class.close()
613 | logger.info(
614 | 'Oops! Connection with {} had an issued. Will wait for 5 seconds and try to re-establish connection'
615 | .format(exchange))
616 | import time
617 | time.sleep(5)
618 | except ccxt.ExchangeError as exception:
619 | await exchange_class.close()
620 | raise ExchangeError(exception)
621 | except Exception as exception:
622 | await exchange_class.close()
623 | raise exception
624 |
--------------------------------------------------------------------------------
/libkloudtrader/enumerables.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 | from functools import partial
3 | import libkloudtrader.stocks as stocks
4 | import libkloudtrader.crypto as crypto
5 | import libkloudtrader.options as options
6 |
7 |
8 | class Data_Types(Enum):
9 | '''Data Types of backtesting and live trading'''
10 | US_STOCKS_ohlcv = partial(stocks.ohlcv)
11 | US_STOCKS_times_and_sale=partial(stocks.time_and_sale)
12 | CRYPTO_ohlcv=partial(crypto.ohlcv)
13 | US_STOCKS_live_feed = partial(stocks.incoming_tick_data_handler)
14 | CRYPTO_live_feed = partial(crypto.incoming_tick_data_handler)
15 | CRYPTO_live_feed_level2 = partial(crypto.incoming_tick_data_handler_level2)
16 |
17 |
--------------------------------------------------------------------------------
/libkloudtrader/exceptions.py:
--------------------------------------------------------------------------------
1 | class InvalidBrokerage(Exception):
2 | '''Exception for invalid brokerage'''
3 | pass
4 |
5 |
6 | class InvalidStockExchange(Exception):
7 | '''Exception for invalid stock exchange'''
8 | pass
9 |
10 |
11 | class InvalidCryptoExchange(Exception):
12 | '''Exception for invalid crypto exchange'''
13 | pass
14 |
15 |
16 | class BadRequest(Exception):
17 | '''Exception for Bad Request/bad parameters'''
18 | pass
19 |
20 |
21 | class InvalidCredentials(Exception):
22 | '''Exception for 401, Wrong Credentials'''
23 | pass
24 |
25 |
26 | class OverwriteError(Exception):
27 | '''Exception raised when trying to add elements to DoubleEndedBuffer that has allow_overwrite=False and size==maxlen'''
28 | pass
29 |
30 |
31 | class InvalidAlgorithmMode(Exception):
32 | '''Exception raised if mode for libkloudtrader.algorithm.run() is invalid'''
33 | pass
34 |
35 |
36 | class EmptySymbolBucket(Exception):
37 | '''Excption raised if symbol bucket is empty'''
38 | pass
39 |
40 |
41 | class InvalidDataFeedType(Exception):
42 | '''Exception raised if user asks for invalid data feed'''
43 | pass
44 |
45 |
46 | class AnalysisException(Exception):
47 | """Exception raised if something goes wrong in libkloudtrader.analysis"""
48 | pass
49 |
50 |
51 | class InvlaidTimeInterval(Exception):
52 | """Exception raised if input interval for historical data apis is invalid"""
53 | pass
54 |
55 |
56 | class InvalidPricePoint(Exception):
57 | """Exception raised if price point is invalid for backtesting"""
58 | pass
59 |
60 |
61 | class OrderError(Exception):
62 | '''Exception raised if any error with order arises'''
63 | pass
64 |
65 |
66 | class AccountError(Exception):
67 | '''Exception raised if any error with user's account arises'''
68 | pass
69 |
70 |
71 | class AuthError(Exception):
72 | '''Exception raised if any error with Auth'''
73 | pass
74 |
75 |
76 | class ResponseError(Exception):
77 | '''Exception raised if any error with response from the exchange'''
78 | pass
79 |
80 |
81 | class ExchangeError(Exception):
82 | '''Exception raised if a crypto exchange cannot process user request'''
83 | pass
84 |
85 |
86 | class NetworkError(Exception):
87 | '''Exception raised due to network issues on either client or exchange side'''
88 | pass
89 |
90 |
91 | class FunctionalityNotSupported(Exception):
92 | '''Exception raised if functionality is not supported by the crypto exchange'''
93 | pass
94 |
--------------------------------------------------------------------------------
/libkloudtrader/logs.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 |
4 | def start_logger(module, ignore_module=None):
5 | logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s",
6 | datefmt='%A, %B %d, %Y %I:%M:%S %p %Z',
7 | level="INFO")
8 | logging.getLogger('boto3').setLevel(logging.CRITICAL)
9 | logging.getLogger('botocore').setLevel(logging.CRITICAL)
10 | if ignore_module:
11 | logging.getLogger(ignore_module).setLevel(logging.CRITICAL)
12 | logger = logging.getLogger(module)
13 | return logger
14 |
--------------------------------------------------------------------------------
/libkloudtrader/options.py:
--------------------------------------------------------------------------------
1 | """This module contains all functions related to options"""
2 |
3 | import requests
4 | import os
5 | import typing
6 | import datetime
7 | import pandas
8 | from .exceptions import (
9 | InvalidBrokerage,
10 | InvalidStockExchange,
11 | BadRequest,
12 | InvalidCredentials,
13 | )
14 | from .logs import start_logger
15 |
16 | logger = start_logger(__name__)
17 | """Data APIs start"""
18 | """Config starts"""
19 | USER_ACCESS_TOKEN = os.environ['USER_ACCESS_TOKEN']
20 | USER_ACCOUNT_NUMBER = os.environ['USER_ACCOUNT_NUMBER']
21 | USER_BROKERAGE = os.environ['USER_BROKERAGE']
22 | TR_STREAMING_API_URL = "https://stream.tradier.com"
23 | TR_BROKERAGE_API_URL = "https://production-api.tradier.com"
24 | TR_SANDBOX_BROKERAGE_API_URL = "https://production-sandbox.tradier.com"
25 |
26 |
27 | def tr_get_headers(access_token: str) -> dict:
28 | '''headers for TR brokerage'''
29 | headers = {
30 | "Accept": "application/json",
31 | "Authorization": "Bearer " + access_token
32 | }
33 | return headers
34 |
35 |
36 | def tr_get_content_headers() -> dict:
37 | '''content headers for TR brokerage'''
38 | headers = {
39 | 'Accept': 'application/json',
40 | }
41 | return headers
42 |
43 |
44 | """Config ends"""
45 |
46 |
47 | def chains(underlying_symbol: str,
48 | expiration: str,
49 | greeks: bool = False,
50 | brokerage: typing.Any = USER_BROKERAGE,
51 | access_token: str = USER_ACCESS_TOKEN,
52 | dataframe: bool = True) -> dict:
53 | """Get options chains"""
54 | try:
55 | if brokerage == "Tradier Inc.":
56 | url = TR_BROKERAGE_API_URL
57 | elif brokerage == "miscpaper":
58 | url = TR_SANDBOX_BROKERAGE_API_URL
59 | else:
60 | logger.error('Oops! An error Occurred ⚠️')
61 | raise InvalidBrokerage
62 | params = {
63 | 'symbol': underlying_symbol.upper(),
64 | 'expiration': str(expiration),
65 | 'greeks': 'true'
66 | }
67 | response = requests.get("{}/v1/markets/options/chains".format(url),
68 | headers=tr_get_headers(access_token),
69 | params=params)
70 | if greeks:
71 | return response.json()
72 | if response:
73 | if response.json()['options'] != None:
74 | data = response.json()
75 | for i in data['options']['option']:
76 | i['trade_date'] = datetime.datetime.fromtimestamp(
77 | float(i['trade_date']) /
78 | 1000.0).strftime("%Y-%m-%d %H:%M:%S")
79 | i['bid_date'] = datetime.datetime.fromtimestamp(
80 | float(i['bid_date']) /
81 | 1000.0).strftime("%Y-%m-%d %H:%M:%S")
82 | i['ask_date'] = datetime.datetime.fromtimestamp(
83 | float(i['ask_date']) /
84 | 1000.0).strftime("%Y-%m-%d %H:%M:%S")
85 | if dataframe == False:
86 | return data['options']['option']
87 | else:
88 | data = pandas.DataFrame(data['options']['option'])
89 | dataframe = pandas.DataFrame(data)
90 | dataframe.set_index(['symbol'], inplace=True)
91 | return dataframe
92 | else:
93 | return response.json()
94 | if response.status_code == 400:
95 | logger.error('Oops! An error Occurred ⚠️')
96 | raise BadRequest(response.text)
97 | if response.status_code == 401:
98 | logger.error('Oops! An error Occurred ⚠️')
99 | raise InvalidCredentials(response.text)
100 | except Exception as exception:
101 | logger.error('Oops! An error Occurred ⚠️')
102 | raise exception
103 |
104 |
105 | def expirations(underlying_symbol: str,
106 | includeAllRoots: bool = True,
107 | strikes: bool = True,
108 | brokerage: typing.Any = USER_BROKERAGE,
109 | access_token: str = USER_ACCESS_TOKEN) -> dict:
110 | """Get expiration dates for a particular underlying."""
111 | try:
112 | if brokerage == "Tradier Inc.":
113 | url = TR_BROKERAGE_API_URL
114 | elif brokerage == "miscpaper":
115 | url = TR_SANDBOX_BROKERAGE_API_URL
116 | else:
117 | logger.error('Oops! An error Occurred ⚠️')
118 | raise InvalidBrokerage
119 | params = {
120 | 'symbol': underlying_symbol.upper(),
121 | 'includeAllRoots': includeAllRoots,
122 | 'strikes': strikes
123 | }
124 | response = requests.get(
125 | "{}/v1/markets/options/expirations".format(url),
126 | headers=tr_get_headers(access_token),
127 | params=params)
128 | if response:
129 | if response.json()['expirations'] != None:
130 | return response.json()['expirations']['expiration']
131 | else:
132 | return response.json()
133 | if response.status_code == 400:
134 | logger.error('Oops! An error Occurred ⚠️')
135 | raise BadRequest(response.text)
136 | if response.status_code == 401:
137 | logger.error('Oops! An error Occurred ⚠️')
138 | raise InvalidCredentials(response.text)
139 | except Exception as exception:
140 | logger.error('Oops! An error Occurred ⚠️')
141 | raise exception
142 |
143 |
144 | def strikes(underlying_symbol: str,
145 | expiration: str,
146 | brokerage: typing.Any = USER_BROKERAGE,
147 | access_token: str = USER_ACCESS_TOKEN) -> dict:
148 | """Get an options strike prices for a specified expiration date."""
149 | try:
150 | if brokerage == "Tradier Inc.":
151 | url = TR_BROKERAGE_API_URL
152 | elif brokerage == "miscpaper":
153 | url = TR_SANDBOX_BROKERAGE_API_URL
154 | else:
155 | logger.error('Oops! An error Occurred ⚠️')
156 | raise InvalidBrokerage
157 | params = {
158 | 'symbol': underlying_symbol.upper(),
159 | 'expiration': str(expiration)
160 | }
161 | response = requests.get("{}/v1/markets/options/strikes".format(url),
162 | headers=tr_get_headers(access_token),
163 | params=params)
164 | if response:
165 | return response.json()
166 | if response.status_code == 400:
167 | logger.error('Oops! An error Occurred ⚠️')
168 | raise BadRequest(response.text)
169 | if response.status_code == 401:
170 | logger.error('Oops! An error Occurred ⚠️')
171 | raise InvalidCredentials(response.text)
172 | except Exception as exception:
173 | logger.error('Oops! An error Occurred ⚠️')
174 | raise exception
175 |
176 |
177 | """Data APIs end"""
178 | """"Trading APIs begin"""
179 |
180 |
181 | def buy_to_open_preview(underlying_symbol: str,
182 | option_symbol: str,
183 | quantity: int,
184 | order_type: str = "market",
185 | duration: str = "gtc",
186 | price: typing.Any = None,
187 | stop: typing.Any = None,
188 | brokerage: typing.Any = USER_BROKERAGE,
189 | access_token: str = USER_ACCESS_TOKEN,
190 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
191 | """Place buy to open Options order to trade a single option."""
192 | try:
193 | if brokerage == "Tradier Inc.":
194 | url = TR_BROKERAGE_API_URL
195 | elif brokerage == "miscpaper":
196 | url = TR_SANDBOX_BROKERAGE_API_URL
197 | else:
198 | logger.error('Oops! An error Occurred ⚠️')
199 | raise InvalidBrokerage
200 | params = {
201 | 'symbol': str(underlying_symbol.upper()),
202 | 'class': 'option',
203 | 'option_symbol': str(option_symbol.upper()),
204 | 'side': 'buy_to_open',
205 | 'quantity': quantity,
206 | 'type': order_type,
207 | 'duration': duration,
208 | 'price': price,
209 | 'stop': stop,
210 | 'preview': True
211 | }
212 | response = requests.post("{}/v1/accounts/{}/orders".format(
213 | url, account_number),
214 | headers=tr_get_headers(access_token),
215 | params=params)
216 | if response:
217 | return response.json()
218 | if response.status_code == 400:
219 | logger.error('Oops! An error Occurred ⚠️')
220 | raise BadRequest(response.text)
221 | if response.status_code == 401:
222 | logger.error('Oops! An error Occurred ⚠️')
223 | raise InvalidCredentials(response.text)
224 | except Exception as exception:
225 | logger.error('Oops! An error Occurred ⚠️')
226 | raise exception
227 |
228 |
229 | def buy_to_close_preview(underlying_symbol: str,
230 | option_symbol: str,
231 | quantity: int,
232 | order_type: str = "market",
233 | duration: str = "gtc",
234 | price: typing.Any = None,
235 | stop: typing.Any = None,
236 | brokerage: typing.Any = USER_BROKERAGE,
237 | access_token: str = USER_ACCESS_TOKEN,
238 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
239 | """Place buy to close Options order to trade a single option."""
240 | try:
241 | if brokerage == "Tradier Inc.":
242 | url = TR_BROKERAGE_API_URL
243 | elif brokerage == "miscpaper":
244 | url = TR_SANDBOX_BROKERAGE_API_URL
245 | else:
246 | logger.error('Oops! An error Occurred ⚠️')
247 | raise InvalidBrokerage
248 | params = {
249 | 'symbol': underlying_symbol.upper(),
250 | 'class': 'option',
251 | 'option_symbol': option_symbol,
252 | 'side': 'buy_to_close',
253 | 'quantity': quantity,
254 | 'type': order_type,
255 | 'duration': duration,
256 | 'price': price,
257 | 'stop': stop,
258 | 'preview': True
259 | }
260 | response = requests.post("{}/v1/accounts/{}/orders".format(
261 | url, account_number),
262 | headers=tr_get_headers(access_token),
263 | params=params)
264 | if response:
265 | return response.json()
266 | if response.status_code == 400:
267 | logger.error('Oops! An error Occurred ⚠️')
268 | raise BadRequest(response.text)
269 | if response.status_code == 401:
270 | logger.error('Oops! An error Occurred ⚠️')
271 | raise InvalidCredentials(response.text)
272 | except Exception as exception:
273 | logger.error('Oops! An error Occurred ⚠️')
274 | raise exception
275 |
276 |
277 | def sell_to_open_preview(underlying_symbol: str,
278 | option_symbol: str,
279 | quantity: int,
280 | order_type: str = "market",
281 | duration: str = "gtc",
282 | price: typing.Any = None,
283 | stop: typing.Any = None,
284 | brokerage: typing.Any = USER_BROKERAGE,
285 | access_token: str = USER_ACCESS_TOKEN,
286 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
287 | """Place buy to open Options order to trade a single option."""
288 | try:
289 | if brokerage == "Tradier Inc.":
290 | url = TR_BROKERAGE_API_URL
291 | elif brokerage == "miscpaper":
292 | url = TR_SANDBOX_BROKERAGE_API_URL
293 | else:
294 | logger.error('Oops! An error Occurred ⚠️')
295 | raise InvalidBrokerage
296 | params = {
297 | 'symbol': underlying_symbol.upper(),
298 | 'class': 'option',
299 | 'option_symbol': option_symbol,
300 | 'side': 'sell_to_open',
301 | 'quantity': quantity,
302 | 'type': order_type,
303 | 'duration': duration,
304 | 'price': price,
305 | 'stop': stop,
306 | 'preview': True
307 | }
308 | response = requests.post("{}/v1/accounts/{}/orders".format(
309 | url, account_number),
310 | headers=tr_get_headers(access_token),
311 | params=params)
312 | if response:
313 | logger.error('Oops! An error Occurred ⚠️')
314 | return response.json()
315 | if response.status_code == 400:
316 | logger.error('Oops! An error Occurred ⚠️')
317 | raise BadRequest(response.text)
318 | if response.status_code == 401:
319 | logger.error('Oops! An error Occurred ⚠️')
320 | raise InvalidCredentials(response.text)
321 | except Exception as exception:
322 | logger.error('Oops! An error Occurred ⚠️')
323 | raise exception
324 |
325 |
326 | def sell_to_close_preview(underlying_symbol: str,
327 | option_symbol: str,
328 | quantity: int,
329 | order_type: str = "market",
330 | duration: str = "gtc",
331 | price: typing.Any = None,
332 | stop: typing.Any = None,
333 | brokerage: typing.Any = USER_BROKERAGE,
334 | access_token: str = USER_ACCESS_TOKEN,
335 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
336 | """Place sell to close Options order to trade a single option."""
337 | try:
338 | if brokerage == "Tradier Inc.":
339 | url = TR_BROKERAGE_API_URL
340 | elif brokerage == "miscpaper":
341 | url = TR_SANDBOX_BROKERAGE_API_URL
342 | else:
343 | logger.error('Oops! An error Occurred ⚠️')
344 | raise InvalidBrokerage
345 | params = {
346 | 'symbol': underlying_symbol.upper(),
347 | 'class': 'option',
348 | 'option_symbol': option_symbol,
349 | 'side': 'sell_to_close',
350 | 'quantity': quantity,
351 | 'type': order_type,
352 | 'duration': duration,
353 | 'price': price,
354 | 'stop': stop,
355 | 'preview': True
356 | }
357 | response = requests.post("{}/v1/accounts/{}/orders".format(
358 | url, account_number),
359 | headers=tr_get_headers(access_token),
360 | params=params)
361 | if response:
362 | return response.json()
363 | if response.status_code == 400:
364 | logger.error('Oops! An error Occurred ⚠️')
365 | raise BadRequest(response.text)
366 | if response.status_code == 401:
367 | logger.error('Oops! An error Occurred ⚠️')
368 | raise InvalidCredentials(response.text)
369 | except Exception as exception:
370 | logger.error('Oops! An error Occurred ⚠️')
371 | raise exception
372 |
373 |
374 | def buy_to_open(underlying_symbol: str,
375 | option_symbol: str,
376 | quantity: int,
377 | order_type: str = "market",
378 | duration: str = "day",
379 | price: typing.Any = None,
380 | stop: typing.Any = None,
381 | brokerage: typing.Any = USER_BROKERAGE,
382 | access_token: str = USER_ACCESS_TOKEN,
383 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
384 | """Place buy to open Options order to trade a single option."""
385 | try:
386 | if brokerage == "Tradier Inc.":
387 | url = TR_BROKERAGE_API_URL
388 | elif brokerage == "miscpaper":
389 | url = TR_SANDBOX_BROKERAGE_API_URL
390 | else:
391 | logger.error('Oops! An error Occurred ⚠️')
392 | raise InvalidBrokerage
393 | params = {
394 | 'symbol': underlying_symbol.upper(),
395 | 'class': 'option',
396 | 'option_symbol': option_symbol,
397 | 'side': 'buy_to_open',
398 | 'quantity': quantity,
399 | 'type': order_type,
400 | 'duration': duration,
401 | 'price': price,
402 | 'stop': stop
403 | }
404 | response = requests.post("{}/v1/accounts/{}/orders".format(
405 | url, account_number),
406 | headers=tr_get_headers(access_token),
407 | params=params)
408 | if response:
409 | logger.error('Oops! An error Occurred ⚠️')
410 | return response.json()
411 | if response.status_code == 400:
412 | logger.error('Oops! An error Occurred ⚠️')
413 | raise BadRequest(response.text)
414 | if response.status_code == 401:
415 | logger.error('Oops! An error Occurred ⚠️')
416 | raise InvalidCredentials(response.text)
417 | except Exception as exception:
418 | logger.error('Oops! An error Occurred ⚠️')
419 | raise exception
420 |
421 |
422 | def buy_to_close(underlying_symbol: str,
423 | option_symbol: str,
424 | quantity: int,
425 | order_type: str = "market",
426 | duration: str = "gtc",
427 | price: typing.Any = None,
428 | stop: typing.Any = None,
429 | brokerage: typing.Any = USER_BROKERAGE,
430 | access_token: str = USER_ACCESS_TOKEN,
431 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
432 | """Place buy to close Options order to trade a single option."""
433 | try:
434 | if brokerage == "Tradier Inc.":
435 | url = TR_BROKERAGE_API_URL
436 | elif brokerage == "miscpaper":
437 | url = TR_SANDBOX_BROKERAGE_API_URL
438 | else:
439 | logger.error('Oops! An error Occurred ⚠️')
440 | raise InvalidBrokerage
441 | params = {
442 | 'symbol': underlying_symbol.upper(),
443 | 'class': 'option',
444 | 'option_symbol': option_symbol,
445 | 'side': 'buy_to_close',
446 | 'quantity': quantity,
447 | 'type': order_type,
448 | 'duration': duration,
449 | 'price': price,
450 | 'stop': stop
451 | }
452 | response = requests.post("{}/v1/accounts/{}/orders".format(
453 | url, account_number),
454 | headers=tr_get_headers(access_token),
455 | params=params)
456 | if response:
457 | return response.json()
458 | if response.status_code == 400:
459 | logger.error('Oops! An error Occurred ⚠️')
460 | raise BadRequest(response.text)
461 | if response.status_code == 401:
462 | logger.error('Oops! An error Occurred ⚠️')
463 | raise InvalidCredentials(response.text)
464 | except Exception as exception:
465 | logger.error('Oops! An error Occurred ⚠️')
466 | raise exception
467 |
468 |
469 | def sell_to_open(underlying_symbol: str,
470 | option_symbol: str,
471 | quantity: int,
472 | order_type: str = "market",
473 | duration: str = "gtc",
474 | price: typing.Any = None,
475 | stop: typing.Any = None,
476 | brokerage: typing.Any = USER_BROKERAGE,
477 | access_token: str = USER_ACCESS_TOKEN,
478 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
479 | """Place sell to open Options order to trade a single option."""
480 | try:
481 | if brokerage == "Tradier Inc.":
482 | url = TR_BROKERAGE_API_URL
483 | elif brokerage == "miscpaper":
484 | url = TR_SANDBOX_BROKERAGE_API_URL
485 | else:
486 | logger.error('Oops! An error Occurred ⚠️')
487 | raise InvalidBrokerage
488 | params = {
489 | 'symbol': underlying_symbol.upper(),
490 | 'class': 'option',
491 | 'option_symbol': option_symbol,
492 | 'side': 'sell_to_open',
493 | 'quantity': quantity,
494 | 'type': order_type,
495 | 'duration': duration,
496 | 'price': price,
497 | 'stop': stop
498 | }
499 | response = requests.post("{}/v1/accounts/{}/orders".format(
500 | url, account_number),
501 | headers=tr_get_headers(access_token),
502 | params=params)
503 | if response:
504 | return response.json()
505 | if response.status_code == 400:
506 | logger.error('Oops! An error Occurred ⚠️')
507 | raise BadRequest(response.text)
508 | if response.status_code == 401:
509 | logger.error('Oops! An error Occurred ⚠️')
510 | raise InvalidCredentials(response.text)
511 | except Exception as exception:
512 | logger.error('Oops! An error Occurred ⚠️')
513 | raise exception
514 |
515 |
516 | def sell_to_close(underlying_symbol: str,
517 | option_symbol: str,
518 | quantity: int,
519 | order_type: str = "market",
520 | duration: str = "gtc",
521 | price: typing.Any = None,
522 | stop: typing.Any = None,
523 | brokerage: typing.Any = USER_BROKERAGE,
524 | access_token: str = USER_ACCESS_TOKEN,
525 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
526 | """Place sell to close Options order to trade a single option."""
527 | try:
528 | if brokerage == "Tradier Inc.":
529 | url = TR_BROKERAGE_API_URL
530 | elif brokerage == "miscpaper":
531 | url = TR_SANDBOX_BROKERAGE_API_URL
532 | else:
533 | logger.error('Oops! An error Occurred ⚠️')
534 | raise InvalidBrokerage
535 | params = {
536 | 'symbol': underlying_symbol.upper(),
537 | 'class': 'option',
538 | 'option_symbol': option_symbol,
539 | 'side': 'sell_to_close',
540 | 'quantity': quantity,
541 | 'type': order_type,
542 | 'duration': duration,
543 | 'price': price,
544 | 'stop': stop
545 | }
546 | response = requests.post("{}/v1/accounts/{}/orders".format(
547 | url, account_number),
548 | headers=tr_get_headers(access_token),
549 | params=params)
550 | if response:
551 | return response.json()
552 | if response.status_code == 400:
553 | logger.error('Oops! An error Occurred ⚠️')
554 | raise BadRequest(response.text)
555 | if response.status_code == 401:
556 | logger.error('Oops! An error Occurred ⚠️')
557 | raise InvalidCredentials(response.text)
558 | except Exception as exception:
559 | logger.error('Oops! An error Occurred ⚠️')
560 | raise exception
561 |
562 |
563 | def change_order(order_id: str,
564 | duration: str,
565 | order_type: str,
566 | price: typing.Any = None,
567 | stop: typing.Any = None,
568 | brokerage: typing.Any = USER_BROKERAGE,
569 | access_token: str = USER_ACCESS_TOKEN,
570 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
571 | '''Change an order if it is not filled yet.'''
572 | try:
573 | if brokerage == "Tradier Inc.":
574 | url = TR_BROKERAGE_API_URL
575 | elif brokerage == "miscpaper":
576 | url = TR_SANDBOX_BROKERAGE_API_URL
577 | else:
578 | raise InvalidBrokerage
579 | put_params = {
580 | 'order_id': order_id,
581 | 'type': str(order_type.lower()),
582 | 'duration': str(duration),
583 | 'price': str(price),
584 | 'stop': str(stop)
585 | }
586 | response = requests.put("{}/v1/accounts/{}/orders/{}".format(
587 | url, account_number, order_id),
588 | data=put_params,
589 | headers=tr_get_headers(access_token))
590 | if response:
591 | return response.json()
592 | if response.status_code == 400:
593 | logger.error('Oops! An error Occurred ⚠️')
594 | raise BadRequest(response.text)
595 | if response.status_code == 401:
596 | logger.error('Oops! An error Occurred ⚠️')
597 | raise InvalidCredentials(response.text)
598 | except Exception as exception:
599 | logger.error('Oops! An error Occurred ⚠️')
600 | raise exception
601 |
602 |
603 | def cancel_order(order_id: str,
604 | brokerage: typing.Any = USER_BROKERAGE,
605 | access_token: str = USER_ACCESS_TOKEN,
606 | account_number: str = USER_ACCOUNT_NUMBER) -> dict:
607 | '''Cancel an order if it is not filled yet.'''
608 | try:
609 | if brokerage == "Tradier Inc.":
610 | url = TR_BROKERAGE_API_URL
611 | elif brokerage == "miscpaper":
612 | url = TR_SANDBOX_BROKERAGE_API_URL
613 | else:
614 | logger.error('Oops! An error Occurred ⚠️')
615 | raise InvalidBrokerage
616 | response = requests.delete("{}/v1/accounts/{}/orders/{}".format(
617 | url, account_number, order_id),
618 | headers=tr_get_headers(access_token))
619 | if response:
620 | return response.json()
621 | if response.status_code == 400:
622 | logger.error('Oops! An error Occurred ⚠️')
623 | raise BadRequest(response.text)
624 | if response.status_code == 401:
625 | logger.error('Oops! An error Occurred ⚠️')
626 | raise InvalidCredentials(response.text)
627 | except Exception as exception:
628 | logger.error('Oops! An error Occurred ⚠️')
629 | raise exception
630 |
631 |
632 | """Trading APIs end"""
633 |
--------------------------------------------------------------------------------
/libkloudtrader/processing.py:
--------------------------------------------------------------------------------
1 | '''Various functions and classes to help store, process, pipeline and manipulate your streams of data'''
2 |
3 | from typing import Any
4 | from collections.abc import Sequence
5 | import numpy as np
6 | import pandas as pd
7 | import libkloudtrader.stocks as stocks
8 | from .exceptions import OverwriteError
9 |
10 |
11 | class Buffer(Sequence):
12 | '''A doubled sided/ended queue/buffer for internal data stream processing'''
13 | def __init__(self,
14 | size: int,
15 | dtype: Any = np.float32,
16 | allow_overwrite: bool = True):
17 | '''Initilization'''
18 | self.arr = np.empty(size, dtype)
19 | self.left_index = 0
20 | self.right_index = 0
21 | self.size = size
22 | self.allow_overwrite = allow_overwrite
23 |
24 | def unwrap(self):
25 | '''copies the data from the buffer to an unwrapped form'''
26 | return np.concatenate(
27 | (self.arr[self.left_index:min(self.right_index, self.size)],
28 | self.arr[:max(self.right_index - self.size, 0)]))
29 |
30 | def fix_indices(self):
31 | """Enforce the invariant that 0 <= self.left_index < self.size"""
32 | if self.left_index >= self.size:
33 | self.left_index -= self.size
34 | self.right_index -= self.size
35 | elif self.left_index < 0:
36 | self.left_index += self.size
37 | self.right_index += self.size
38 |
39 | @property
40 | def check_if_full(self) -> bool:
41 | """Check if there is no more space in the buffer"""
42 | return len(self) == self.size
43 |
44 | def __array__(self):
45 | return self.unwrap()
46 |
47 | @property
48 | def dtype(self):
49 | return self.arr.dtype
50 |
51 | @property
52 | def shape(self):
53 | return (len(self), ) + self.arr.shape[1:]
54 |
55 | @property
56 | def maxlen(self):
57 | '''maxlen/size'''
58 | return self.size
59 |
60 | @property
61 | def buffer_size(self):
62 | '''size'''
63 | return self.size
64 |
65 | def __len__(self):
66 | return self.right_index - self.left_index
67 |
68 | def __getitem__(self, item):
69 | if not isinstance(item, tuple):
70 | item_arr = np.asarray(item)
71 | if issubclass(item_arr.dtype.type, np.integer):
72 | item_arr = (item_arr + self.left_index) % self.size
73 | return self.arr[item_arr]
74 |
75 | return self.unwrap()[item]
76 |
77 | def __iter__(self):
78 | return iter(self.unwrap())
79 |
80 | def __repr__(self):
81 | '''Stdouts the buffer and size'''
82 | return ''.format(np.asarray(self))
83 |
84 | def append(self, value):
85 | '''Append element to the right like any other list/queue'''
86 | if self.check_if_full:
87 | if not self.allow_overwrite:
88 | raise OverwriteError(
89 | 'You are trying to append to a full Buffer with allow_overwrite=False'
90 | )
91 | elif not len(self):
92 | return
93 | else:
94 | self.left_index += 1
95 |
96 | self.arr[self.right_index % self.size] = value
97 | self.right_index += 1
98 | self.fix_indices()
99 |
100 | def append_left(self, value):
101 | '''append element to the left'''
102 | if self.check_if_full:
103 | if not self.allow_overwrite:
104 | raise OverwriteError(
105 | 'You are trying to append to a full Buffer with allow_overwrite=False'
106 | )
107 | elif not len(self):
108 | return
109 | else:
110 | self.right_index -= 1
111 |
112 | self.left_index -= 1
113 | self.fix_indices()
114 | self.arr[self.left_index] = value
115 |
116 | def pop(self):
117 | if len(self) == 0:
118 | raise IndexError()
119 | self.right_index -= 1
120 | self.fix_indices()
121 | res = self.arr[self.right_index % self.size]
122 | return res
123 |
124 | def popleft(self):
125 | if len(self) == 0:
126 | raise IndexError()
127 | res = self.arr[self.left_index]
128 | self.left_index += 1
129 | self.fix_indices()
130 | return res
131 |
--------------------------------------------------------------------------------
/libkloudtrader/test/backtest.py:
--------------------------------------------------------------------------------
1 | import time
2 |
3 | from cached_property import cached_property
4 | import libkloudtrader.performance as performance
5 | import libkloudtrader.parts as parts
6 | import pandas
7 |
8 | __all__ = ['Backtest']
9 |
10 |
11 | class StatEngine(object):
12 | def __init__(self, equity_fn):
13 | self._stats = [i for i in dir(performance) if not i.startswith('_')]
14 | self._equity_fn = equity_fn
15 |
16 | def __dir__(self):
17 | return dir(type(self)) + self._stats
18 |
19 | def __getattr__(self, attr):
20 | if attr in self._stats:
21 | equity = self._equity_fn()
22 | fn = getattr(performance, attr)
23 | try:
24 | return fn(equity)
25 | except:
26 | return
27 | else:
28 | raise IndexError("Calculation of '%s' statistic is not supported" %
29 | attr)
30 |
31 |
32 | class ContextWrapper(object):
33 | def __init__(self, *args, **kwargs):
34 | pass
35 |
36 |
37 | class Backtest(object):
38 | """
39 | Backtest (Pandas implementation of vectorized backtesting).
40 | Lazily attempts to extract multiple pandas.Series with signals and prices
41 | from a given namespace and combine them into equity curve.
42 | Attempts to be as smart as possible.
43 | """
44 |
45 | _data_possible_fields = ('ohlc', 'bars', 'ohlcv', 'data')
46 | _sig_mask_int = ('Buy', 'Sell', 'Short', 'Cover')
47 | _pr_mask_int = ('BuyPrice', 'SellPrice', 'ShortPrice', 'CoverPrice')
48 |
49 | def __init__(self,
50 | dataobj,
51 | name='Unknown',
52 | signal_fields=('buy', 'sell', 'short', 'cover'),
53 | price_fields=('buyprice', 'sellprice', 'shortprice',
54 | 'coverprice')):
55 | """
56 | Arguments:
57 | *dataobj* should be dict-like structure containing signal series.
58 | Easiest way to define is to create pandas.Series with exit and entry
59 | signals and pass whole local namespace (`locals()`) as dataobj.
60 | *name* is simply backtest/strategy name. Will be user for printing,
61 | potting, etc.
62 | *signal_fields* specifies names of signal Series that backtester will
63 | attempt to extract from dataobj. By default follows AmiBroker's naming
64 | convention.
65 | *price_fields* specifies names of price Series where trades will take
66 | place. If some price is not specified (NaN at signal's timestamp, or
67 | corresponding Series not present in dataobj altogather), defaults to
68 | Open price of next bar. By default follows AmiBroker's naming
69 | convention.
70 | Also, dataobj should contain dataframe with Bars of underlying
71 | instrument. We will attempt to guess its name before failing miserably.
72 | To get a hang of it, check out the examples.
73 | """
74 | self._dataobj = dict([(k.lower(), v) for k, v in dataobj.items()])
75 | self._sig_mask_ext = signal_fields
76 | self._pr_mask_ext = price_fields
77 | self.name = name
78 | self.trdplot = self.sigplot = parts.Slicer(self.plot_trades,
79 | obj=self.data)
80 | self.eqplot = parts.Slicer(self.plot_equity, obj=self.data)
81 | self.run_time = time.strftime('%Y-%d-%m %H:%M %Z', time.localtime())
82 | self.stats = StatEngine(lambda: self.equity)
83 |
84 | def __repr__(self):
85 | return "Backtest(%s, %s)" % (self.name, self.run_time)
86 |
87 | @property
88 | def dataobj(self):
89 | return self._dataobj
90 |
91 | @cached_property
92 | def signals(self):
93 | return parts.extract_frame(self.dataobj, self._sig_mask_ext,
94 | self._sig_mask_int).fillna(value=False)
95 |
96 | @cached_property
97 | def prices(self):
98 | return parts.extract_frame(self.dataobj, self._pr_mask_ext,
99 | self._pr_mask_int)
100 |
101 | @cached_property
102 | def default_price(self):
103 | return self.data.open # .shift(-1)
104 |
105 | @cached_property
106 | def trade_price(self):
107 | pr = self.prices
108 | if pr is None:
109 | return self.data.open # .shift(-1)
110 | dp = pandas.Series(dtype=float, index=pr.index)
111 | for pf, sf in zip(self._pr_mask_int, self._sig_mask_int):
112 | s = self.signals[sf]
113 | p = self.prices[pf]
114 | dp[s] = p[s]
115 | return dp.combine_first(self.default_price)
116 |
117 | @cached_property
118 | def positions(self):
119 | return parts.signals_to_positions(self.signals,
120 | mask=self._sig_mask_int)
121 |
122 | @cached_property
123 | def trades(self):
124 | p = self.positions.reindex(
125 | self.signals.index).ffill().shift().fillna(value=0)
126 | p = p[p != p.shift()]
127 | tp = self.trade_price
128 | assert p.index.tz == tp.index.tz, "Cant operate on singals and prices " \
129 | "indexed as of different timezones"
130 | t = pandas.DataFrame({'pos': p})
131 | t['price'] = tp
132 | t = t.dropna()
133 | t['vol'] = t.pos.diff()
134 | return t.dropna()
135 |
136 | @cached_property
137 | def equity(self):
138 | return parts.trades_to_equity(self.trades)
139 |
140 | @cached_property
141 | def data(self):
142 | for possible_name in self._data_possible_fields:
143 | s = self.dataobj.get(possible_name)
144 | if not s is None:
145 | return s
146 | raise Exception("Bars dataframe was not found in dataobj")
147 |
148 | @cached_property
149 | def report(self):
150 | return performance.performance_summary(self.equity)
151 |
152 | def summary(self):
153 | import yaml
154 | from pprint import pprint
155 |
156 | s = '| %s |' % self
157 | print('-' * len(s))
158 | print(s)
159 | print('-' * len(s) + '\n')
160 | print(
161 | yaml.dump(self.report,
162 | allow_unicode=True,
163 | default_flow_style=False))
164 | print('-' * len(s))
165 |
166 | def plot_equity(self, subset=None, ax=None):
167 | import matplotlib.pylab as pylab
168 | _ = None
169 | if ax is None:
170 | _, ax = pylab.subplots()
171 |
172 | if subset is None:
173 | subset = slice(None, None)
174 | assert isinstance(subset, slice)
175 | eq = self.equity[subset].cumsum()
176 |
177 | eq = self.equity.ix[subset].cumsum()
178 | ix = eq.index
179 | eq.plot(color='red', style='-', ax=ax)
180 |
181 | #eq.plot(color='red', label='strategy',ax=ax)
182 | #ix = self.ohlc.ix[eq.index[0]:eq.index[-1]].index
183 | #price = self.ohlc.C
184 | #(price[ix] - price[ix][0]).resample('W').first().dropna() \
185 | # .plot(color='black', alpha=0.5, label='underlying', ax=ax)
186 |
187 | ax.legend(loc='best')
188 | ax.set_title(str(self))
189 | ax.set_ylabel('Equity for %s' % subset)
190 | return _, ax
191 |
192 | def plot_trades(self, subset=None, ax=None):
193 | if subset is None:
194 | subset = slice(None, None)
195 | fr = self.trades.ix[subset]
196 | le = fr.price[(fr.pos > 0) & (fr.vol > 0)]
197 | se = fr.price[(fr.pos < 0) & (fr.vol < 0)]
198 | lx = fr.price[(fr.pos.shift() > 0) & (fr.vol < 0)]
199 | sx = fr.price[(fr.pos.shift() < 0) & (fr.vol > 0)]
200 |
201 | import matplotlib.pylab as pylab
202 | _ = None
203 | if ax is None:
204 | _, ax = pylab.subplots()
205 |
206 | ax.plot(le.index,
207 | le.values,
208 | '^',
209 | color='lime',
210 | markersize=12,
211 | label='long enter')
212 | ax.plot(se.index,
213 | se.values,
214 | 'v',
215 | color='red',
216 | markersize=12,
217 | label='short enter')
218 | ax.plot(lx.index,
219 | lx.values,
220 | 'o',
221 | color='lime',
222 | markersize=7,
223 | label='long exit')
224 | ax.plot(sx.index,
225 | sx.values,
226 | 'o',
227 | color='red',
228 | markersize=7,
229 | label='short exit')
230 |
231 | self.data.open.ix[subset].plot(color='black', label='price', ax=ax)
232 | ax.set_ylabel('Trades for %s' % subset)
233 | return _, ax
234 |
--------------------------------------------------------------------------------
/libkloudtrader/test/parts.py:
--------------------------------------------------------------------------------
1 | # coding: utf8
2 |
3 | # part of pybacktest package: https://github.com/ematvey/pybacktest
4 | """ Essential functions for translating signals into trades.
5 | Usable both in backtesting and production.
6 | """
7 |
8 | import pandas
9 |
10 |
11 | def signals_to_positions(signals,
12 | init_pos=0,
13 | mask=('Buy', 'Sell', 'Short', 'Cover')):
14 | """
15 | Translate signal dataframe into positions series (trade prices aren't
16 | specified.
17 | WARNING: In production, override default zero value in init_pos with
18 | extreme caution.
19 | """
20 | long_en, long_ex, short_en, short_ex = mask
21 | pos = init_pos
22 | ps = pandas.Series(0., index=signals.index)
23 | for t, sig in signals.iterrows():
24 | # check exit signals
25 | if pos != 0: # if in position
26 | if pos > 0 and sig[long_ex]: # if exit long signal
27 | pos -= sig[long_ex]
28 | elif pos < 0 and sig[short_ex]: # if exit short signal
29 | pos += sig[short_ex]
30 | # check entry (possibly right after exit)
31 | if pos == 0:
32 | if sig[long_en]:
33 | pos += sig[long_en]
34 | elif sig[short_en]:
35 | pos -= sig[short_en]
36 | ps[t] = pos
37 | return ps[ps != ps.shift()]
38 |
39 |
40 | def trades_to_equity(trd):
41 | """
42 | Convert trades dataframe (cols [vol, price, pos]) to equity diff series
43 | """
44 | def _cmp_fn(x):
45 | if x > 0:
46 | return 1
47 | elif x < 0:
48 | return -1
49 | else:
50 | return 0
51 |
52 | psig = trd.pos.apply(_cmp_fn)
53 | closepoint = psig != psig.shift()
54 |
55 | e = (trd.vol * trd.price).cumsum()[closepoint] - \
56 | (trd.pos * trd.price)[closepoint]
57 |
58 | e = e.diff()
59 | e = e.reindex(trd.index).fillna(value=0)
60 | e[e != 0] *= -1
61 | return e
62 |
63 |
64 | def extract_frame(dataobj, ext_mask, int_mask):
65 | df = {}
66 | for f_int, f_ext in zip(int_mask, ext_mask):
67 | obj = dataobj.get(f_ext)
68 | if isinstance(obj, pandas.Series):
69 | df[f_int] = obj
70 | else:
71 | df[f_int] = None
72 | if any([isinstance(x, pandas.Series) for x in list(df.values())]):
73 | return pandas.DataFrame(df)
74 | return None
75 |
76 |
77 | class Slicer(object):
78 | def __init__(self, target, obj):
79 | self.target = target
80 | self.__len__ = obj.__len__
81 |
82 | def __getitem__(self, x):
83 | return self.target(x)
84 |
--------------------------------------------------------------------------------
/libkloudtrader/test/performance.py:
--------------------------------------------------------------------------------
1 | # coding: utf8
2 |
3 | # part of pybacktest package: https://github.com/ematvey/pybacktest
4 | """ Functions for calculating performance statistics and reporting """
5 |
6 | import pandas as pd
7 | import numpy as np
8 |
9 | start = lambda eqd: eqd.index[0]
10 | end = lambda eqd: eqd.index[-1]
11 | days = lambda eqd: (eqd.index[-1] - eqd.index[0]).days
12 | trades_per_month = lambda eqd: eqd.groupby(lambda x: (x.year, x.month)).apply(
13 | lambda x: x[x != 0].count()).mean()
14 | profit = lambda eqd: eqd.sum()
15 | average = lambda eqd: eqd[eqd != 0].mean()
16 | average_gain = lambda eqd: eqd[eqd > 0].mean()
17 | average_loss = lambda eqd: eqd[eqd < 0].mean()
18 | winrate = lambda eqd: float(sum(eqd > 0)) / len(eqd)
19 | payoff = lambda eqd: eqd[eqd > 0].mean() / -eqd[eqd < 0].mean()
20 | pf = PF = lambda eqd: abs(eqd[eqd > 0].sum() / eqd[eqd < 0].sum())
21 | maxdd = lambda eqd: (eqd.cumsum().expanding().max() - eqd.cumsum()).max()
22 | rf = RF = lambda eqd: eqd.sum() / maxdd(eqd)
23 | trades = lambda eqd: len(eqd[eqd != 0])
24 | _days = lambda eqd: eqd.resample('D').sum().dropna()
25 |
26 |
27 | def sharpe(eqd):
28 | ''' daily sharpe ratio '''
29 | d = _days(eqd)
30 | return (d.mean() / d.std()) * (252**0.5)
31 |
32 |
33 | def sortino(eqd):
34 | ''' daily sortino ratio '''
35 | d = _days(eqd)
36 | return (d.mean() / d[d < 0].std()) * (252**0.5)
37 |
38 |
39 | def ulcer(eqd):
40 | eq = eqd.cumsum()
41 | return (((eq - eq.expanding().max())**2).sum() / len(eq))**0.5
42 |
43 |
44 | def upi(eqd, risk_free=0):
45 | eq = eqd[eqd != 0]
46 | return (eq.mean() - risk_free) / ulcer(eq)
47 |
48 |
49 | UPI = upi
50 |
51 |
52 | def mpi(eqd):
53 | """ Modified UPI, with enumerator resampled to months (to be able to
54 | compare short- to medium-term strategies with different trade frequencies. """
55 | return eqd.resample('M').sum().mean() / ulcer(eqd)
56 |
57 |
58 | MPI = mpi
59 |
60 |
61 | def mcmdd(eqd, runs=100, quantile=0.99, array=False):
62 | maxdds = [
63 | maxdd(eqd.take(np.random.permutation(len(eqd)))) for i in range(runs)
64 | ]
65 | if not array:
66 | return pd.Series(maxdds).quantile(quantile)
67 | else:
68 | return maxdds
69 |
70 |
71 | def holding_periods(eqd):
72 | # rather crude, but will do...
73 | return pd.Series(pd.to_datetime(eqd.index), index=eqd.index,
74 | dtype=object).diff().dropna()
75 |
76 |
77 | def performance_summary(equity_diffs, quantile=0.99, precision=4):
78 | def _format_out(v, precision=4):
79 | if isinstance(v, dict):
80 | return {k: _format_out(v) for k, v in list(v.items())}
81 | if isinstance(v, (float, np.float)):
82 | v = round(v, precision)
83 | if isinstance(v, np.generic):
84 | return np.asscalar(v)
85 | return v
86 |
87 | def force_quantile(series, q):
88 | return sorted(series.values)[int(len(series) * q)]
89 |
90 | eqd = equity_diffs[equity_diffs != 0]
91 | if getattr(eqd.index, 'tz', None) is not None:
92 | eqd = eqd.tz_convert(None)
93 | if len(eqd) == 0:
94 | return {}
95 | hold = holding_periods(equity_diffs)
96 |
97 | return _format_out({
98 | 'Backtest SUmmary': {
99 | 'Start Date': str(start(eqd)),
100 | 'End Date': str(end(eqd)),
101 | 'Day': days(eqd),
102 | 'Trades Placed': len(eqd),
103 | },
104 | 'Performance': {
105 | 'Profit': eqd.sum(),
106 | 'Averages': {
107 | 'Trade': average(eqd),
108 | 'Gain': average_gain(eqd),
109 | 'Loss': average_loss(eqd),
110 | },
111 | 'Win Rate': winrate(eqd),
112 | 'Pay Off': payoff(eqd),
113 | 'PF': PF(eqd),
114 | 'RF': RF(eqd),
115 | },
116 | 'risk/return profile': {
117 | 'sharpe':
118 | sharpe(eqd),
119 | 'sortino':
120 | sortino(eqd),
121 | 'maxdd':
122 | maxdd(eqd),
123 | 'WCDD (monte-carlo {} quantile)'.format(quantile):
124 | mcmdd(eqd, quantile=quantile),
125 | 'UPI':
126 | UPI(eqd),
127 | 'MPI':
128 | MPI(eqd),
129 | }
130 | })
131 |
--------------------------------------------------------------------------------
/live.py:
--------------------------------------------------------------------------------
1 | from libkloudtrader.algorithm import *
2 | import pandas as pd
3 | import libkloudtrader.analysis as analysis
4 |
5 | def crypto_turtle(data):
6 | data['high']=data.price.shift(1).rolling(window=5).max()
7 | data['low']=data.price.shift(1).rolling(window=5).min()
8 | data['avg']=analysis.ma(data.price,5)
9 | buy=data.price>data.high
10 | sell=data.pricedata.avg
13 | if buy.tail(1).bool():
14 | logger.info('Buy signal')
15 | if sell.tail(1).bool():
16 | logger.info('Sell signal')
17 | if short.tail(1).bool():
18 | logger.info('Short signal')
19 | if cover.tail(1).bool():
20 | logger.info('Cover signal')
21 |
22 |
23 | live_trade(crypto_turtle,symbol_bucket=['BTC/USD'],data_feed_type="CRYPTO_live_feed")
--------------------------------------------------------------------------------
/pypi.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | # LibKloudTrader
5 |
6 |
7 |
8 | 
9 |
10 | 
11 |
12 | 
13 |
14 | 
15 |
16 | 
17 |
18 | 
19 |
20 |
21 |
22 | KloudTrader's in-house trading framework optimized for computational finance and algortihmic trading. 📈📊📉
23 |
24 |
25 |
26 | Connect your trading models and conquer the markets.
27 |
28 |
29 |
30 |
31 |
32 | What does LibKLoudTrader offer?
33 |
34 |
35 |
36 | 1. Extremely simple to use trading APIs for U.S. Equity market.
37 |
38 |
39 |
40 | 2. All sorts of data: live market feed, historical price data, company information and much more.
41 |
42 |
43 |
44 | 3. Customized alert APIs for both sms and email.
45 |
46 |
47 |
48 | 4. A Wide range of functions for financial, technical, portfolio and risk analsyis.
49 |
50 |
51 |
52 | 5. Papertrading with virtual money upto $1 million. (Coming Soon)
53 |
54 |
55 |
56 | 6. Multi Crypto-Currency Trading and Data APIs. (Coming Soon)
57 |
58 |
59 |
60 | 7. Managed deployment of your trading algorithm on [Narwhal](https://kloudtrader.com/narwhal) without the hassle of dev-ops and tech support.
61 |
62 |
63 |
64 |
65 |
66 | Documentation for LibKloudTrader can be found here: https://docs.kloudtrader.com/
67 |
68 |
69 |
70 |
71 |
72 | For questions, feedback and contributions:
73 |
74 |
75 |
76 | 1. [KloudTrader Community on slack](https://kloudtradercommunity.slack.com/messages/CDM1PKS81/)
77 |
78 |
79 |
80 | 2. [Github Issues](https://github.com/KloudTrader/libkloudtrader/issues)
81 |
82 |
83 |
84 |
85 |
86 | Note: This is a python client. More clients (R, Julia, Golang, C#, etc) coming soon.
87 |
88 |
89 |
90 |
91 |
92 | Notes for docs:
93 |
94 | Remove close_prices, open_prices, etc
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | boto3==1.13.10
2 | empyrical==0.5.0
3 | pyre-check==0.0.39
4 | pytest==4.6.3
5 | pyti==0.2.2
6 | safety==1.8.7
7 | sklearn==0.0
8 | ta==0.5.22
9 | TA-Lib==0.4.17
10 | tabulate==0.8.3
11 | tox==3.13.2
12 | pylint==2.3.1
13 | pyre-check==0.0.39
14 | pytest==4.6.3
15 | pyti==0.2.2
16 | safety==1.8.7
17 | yapf==0.27.0
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.core import setup
2 |
3 | setup(
4 | name='libkloudtrader',
5 | version='1.0.0',
6 | author='KloudTrader',
7 | author_email='admin@kloudtrader.com',
8 | packages=['libkloudtrader'],
9 | url='https://github.com/KloudTrader/kloudtrader',
10 | license='LICENSE',
11 | description="KloudTrader's in-house library that makes it much easier for you to code algorithms that can trade for you.",
12 | long_description_content_type="text/markdown",
13 | long_description='pypi.md',
14 | install_requires=[
15 | "boto3",
16 | "pandas",
17 | "numpy",
18 | "empyrical",
19 | "asyncio",
20 | "ccxt"
21 | ],
22 | )
23 |
--------------------------------------------------------------------------------
/tests/Tests.md:
--------------------------------------------------------------------------------
1 | This project mostly needs unit tests.
2 |
3 | Some test cases are left which are not that urgent and shall be implemented soon.
4 |
5 | Some other test cases are mentioned below:
6 |
7 | 1. Test for Invalid access_token
8 | 2. Test fo invalid account_number
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/NarrationBox/libkloudtrader/015e2779f80ba2de93be9fa6fd751412a9d5f492/tests/__init__.py
--------------------------------------------------------------------------------
/tests/test_alert_me.py:
--------------------------------------------------------------------------------
1 | '''Tests for libkloudtrader.alert_me'''
2 |
3 | from libkloudtrader.alert_me import *
4 | """
5 | class TestAlertMe:
6 | def test_sms(self):
7 | '''Test SMS'''
8 | response=sms('+919871766213', "Test message from libkloudtrader")
9 | assert response=='Alert created'
10 |
11 | def test_email(self):
12 | '''Test Email'''
13 | response=email('chetan.malhotra@kloudtrader.com', 'Test message from libkloudtrader')
14 | assert response=='Alert created'
15 |
16 | def test_sms_and_email(self):
17 | '''Test both sms and email'''
18 | response=sms_and_email('+919871766213', 'chetanalwaysmalhotra@gmail.com', 'Test message from libkloudtrader')
19 | assert response=='Alert created'
20 | """
21 |
--------------------------------------------------------------------------------
/tests/test_analysis.py:
--------------------------------------------------------------------------------
1 | import libkloudtrader.analysis as analysis
2 |
3 | class Test_accumulation_distribution_index:
4 | pass
5 |
6 | class Test_awesome_oscillator:
7 | pass
8 |
9 | class Test_money_flow_index:
10 | pass
11 |
12 | class Test_relative_strength_index:
13 | pass
14 |
15 | class Test_stochastic_oscillator_index:
16 | pass
17 |
18 | class Test_true_strength_index:
19 | pass
20 |
21 | class Test_ultimate_oscillator:
22 | pass
23 |
24 | class Test_absolute_price_oscillator:
25 | pass
26 |
27 | class Test_aroon:
28 | pass
29 |
30 | class Test_aroon_oscillator:
31 | pass
32 |
33 | class Test_average_directional_moving_index:
34 | pass
35 |
36 | class Test_average_price:
37 | pass
38 |
39 | class Test_average_true_range:
40 | pass
41 |
42 | class Test_normalized_average_true_range:
43 | pass
44 |
45 | class Test_true_range:
46 | pass
47 |
48 | class Test_balance_of_power:
49 | pass
50 |
51 | class Test_bollinger_bands:
52 | pass
53 |
54 | class Test_chaikin_money_flow:
55 | pass
56 |
57 | class Test_chande_momentum_oscillator:
58 | pass
59 |
60 | class Test_commodity_channel_index:
61 | pass
62 |
63 | class Test_correlation_coefficient:
64 | pass
65 |
66 | class Test_cumulative_returns:
67 | pass
68 |
69 | class Test_daily_returns:
70 | pass
71 |
72 | class Test_daily_log_returns:
73 | pass
74 |
75 | class Test_detrended_price_oscillator:
76 | pass
77 |
78 | class Test_directional_movement_index:
79 | pass
80 |
81 | class Test_donchian_channel:
82 | pass
83 |
84 | class Test_double_ema:
85 | pass
86 |
87 | class Test_ease_of_movement:
88 | pass
89 |
90 | class Test_force_index:
91 | pass
92 |
93 | class Test_ema:
94 | pass
95 |
96 | class Test_ichimoku_cloud:
97 | pass
98 |
99 | class Test_kaufman_adaptive_moving_average:
100 | pass
101 |
102 | class Test_keltner_channels:
103 | pass
104 |
105 | class Test_know_sure_thing:
106 | pass
107 |
108 | class Test_linear_regression:
109 | pass
110 |
111 | class Test_linear_regression_angle:
112 | pass
113 |
114 | class Test_linear_regression_intercept:
115 | pass
116 |
117 | class Test_linear_regression_slope:
118 | pass
119 |
120 | class Test_macd:
121 | pass
122 |
123 | class Test_mass_index:
124 | pass
125 |
126 | class Test_midpoint_over_period:
127 | pass
128 |
129 | class Test_midpoint_price_over_period:
130 | pass
131 |
132 | class Test_minus_directional_indicator:
133 | pass
134 |
135 | class Test_minus_directional_movement:
136 | pass
137 |
138 | class Test_median_price:
139 | pass
140 |
141 | class Test_momentum:
142 | pass
143 |
144 | class Test_ma:
145 | pass
146 |
147 | class Test_negative_volume_index:
148 | pass
149 |
150 | class Test_hilbert_transform_inst_trendline:
151 | pass
152 |
153 | class Test_hilbert_transform_dom_cyc_per:
154 | pass
155 |
156 | class Test_hilbert_transform_dom_cyc_phase:
157 | pass
158 |
159 | class Test_hilbert_transform_phasor_components:
160 | pass
161 |
162 | class Test_hilbert_transform_sine_wave:
163 | pass
164 |
165 | class Test_hilbert_transform_trend_vs_cycle_mode:
166 | pass
167 |
168 | class Test_on_balance_volume:
169 | pass
170 |
171 | class Test_parabolic_sar:
172 | pass
173 |
174 | class Test_percentage_price_oscillator:
175 | pass
176 |
177 | class Test_plus_directional_indicator:
178 | pass
179 |
180 | class Test_plus_directional_movement:
181 | pass
182 |
183 | class Test_rate_of_change:
184 | pass
185 |
186 | class Test_sma:
187 | pass
188 |
189 | class Test_standard_deviation:
190 | pass
191 |
192 | class Test_stochastic_rsi:
193 | pass
194 |
195 | class Test_time_series_forecast:
196 | pass
197 |
198 | class Test_trix:
199 | pass
200 |
201 | class Test_triangular_ma:
202 | pass
203 |
204 | class Test_triple_ema:
205 | pass
206 |
207 | class Test_typical_price:
208 | pass
209 |
210 | class Test_variance:
211 | pass
212 |
213 | class Test_vortex_indicator:
214 | pass
215 |
216 | class Test_vortex_indicator:
217 | pass
218 |
219 | class Test_weighted_close_price:
220 | pass
221 |
222 | class Test_williams_r:
223 | pass
224 |
225 | class Test_wma:
226 | pass
227 |
228 | class Test_two_crows:
229 | pass
230 |
231 | class Test_annual_return:
232 | pass
233 |
234 | class Test_returns:
235 | pass
236 |
237 | class Test_daily_volatility:
238 | pass
239 |
240 | class Test_annual_volatility:
241 | pass
242 |
243 | class Test_volatility:
244 | pass
245 |
246 | class Test_moving_volatility:
247 | pass
248 |
249 | class Test_chaikin_oscillator:
250 | pass
251 |
252 | class Test_coppock_curve:
253 | pass
254 |
255 | class Test_hull_moving_average:
256 | pass
257 |
258 | class Test_volume_price_trend:
259 | pass
260 |
261 | class Test_volume_adjusted_moving_average:
262 | pass
263 |
264 | class Test_sharpe_ratio:
265 | pass
266 |
267 | class Test_annual_sharpe_ratio:
268 | pass
269 |
270 | class Test_vwap:
271 | pass
272 |
273 | class Test_sortino_ratio:
274 | pass
275 |
276 | class Test_calmar_ratio:
277 | pass
278 |
279 | class Test_skewness:
280 | pass
281 |
282 | class Test_kurtosis:
283 | pass
284 |
285 | class Test_omega_ratio:
286 | pass
287 |
288 | class Test_tail_ratio:
289 | pass
290 |
291 | class Test_alpha:
292 | pass
293 |
294 | class Test_beta:
295 | pass
296 |
297 | class Test_adjusted_returns:
298 | pass
299 |
300 | class Test_information_ratio:
301 | pass
302 |
303 | class Test_cagr:
304 | pass
305 |
306 | class Test_downside_risk:
307 | pass
308 |
309 | class Test_value_at_risk:
310 | pass
311 |
312 |
--------------------------------------------------------------------------------
/tests/test_crypto.py:
--------------------------------------------------------------------------------
1 | import libkloudtrader.crypto as crypto
2 | import pandas
3 |
4 |
5 | class Test_list_of_exchanges:
6 | def test_return_type(self):
7 | '''test return type'''
8 | data=crypto.list_of_exchanges()
9 | data2=crypto.list_of_exchanges(test_mode=True)
10 | assert isinstance(data,list) and isinstance(data2,list) and not 'message' in data
11 |
12 | class Test_exchange_strucutre:
13 | def test_return_type(self):
14 | '''test return type'''
15 | data=crypto.exchange_structure()
16 | assert isinstance(data,str)
17 |
18 | class Test_exchange_attribute:
19 | def test_return_type(self):
20 | '''test return type'''
21 | data=crypto.exchange_attribute(attribute="id")
22 | assert isinstance(data,str) and not 'message' in data
23 |
24 | def test_returned_data(self):
25 | '''test returned data'''
26 | data=crypto.exchange_attribute(attribute="id")
27 | assert data==crypto.CRYPTO_EXCHANGE
28 |
29 | class Test_markets:
30 | def test_return_type(self):
31 | '''test return type'''
32 | data=crypto.markets()
33 | assert isinstance(data,dict) and not 'message' in data
34 |
35 | class Test_market_structure:
36 | def test_return_type(self):
37 | '''test return type'''
38 | data=crypto.market_structure('BTC/USD')
39 | assert isinstance(data,dict) and not 'message' in data
40 |
41 | def test_retured_data(self):
42 | '''test returned data'''
43 | data=crypto.market_structure('BTC/USD')
44 | assert 'precision','percentage' in data
45 |
46 | class Test_quotes:
47 | def test_return_type(self):
48 | '''test return type'''
49 | data=crypto.latest_price_info('BTC/USD')
50 | assert isinstance(data,dict) and not 'message' in data
51 |
52 | def test_retured_data(self):
53 | '''test returned data'''
54 | data=crypto.latest_price_info('BTC/USD')
55 | assert 'high','low' in data
56 |
57 |
58 | class Test_quotes_for_all_symbols:
59 | def test_return_type(self):
60 | '''test return type'''
61 | data=crypto.latest_price_info_for_all_symbols(exchange="binance")
62 | assert isinstance(data,dict) and not 'message' in data
63 |
64 | class Test_ohlcv:
65 | def test_return_type(self):
66 | '''test return type'''
67 | data=crypto.ohlcv(symbol='BTC/USD',start="2018-01-01",end="2018-04-01",dataframe=False)
68 | data2=crypto.ohlcv(symbol='BTC/USD',start="2019-01-01 17:30:00",end="2019-01-01 17:35:00",interval='1m',dataframe=False)
69 | assert isinstance(data,list) and isinstance(data2,list)
70 |
71 | def test_return_pandas_type(self):
72 | '''test pandas return type'''
73 | data=crypto.ohlcv(symbol='BTC/USD',start="2018-01-01",end="2018-04-01")
74 | data2=crypto.ohlcv(symbol='BTC/USD',start="2019-01-01 17:30:00",end="2019-01-01 17:35:00",interval='1m')
75 | assert isinstance(data,pandas.DataFrame) and isinstance(data2,pandas.DataFrame)
76 |
77 |
78 |
79 | def test_invalid_date(self):
80 | pass
81 |
82 | def test_invalid_date_format(self):
83 | pass
84 |
85 | class Test_trades:
86 | def test_return_type(self):
87 | '''test return type'''
88 | data=crypto.trades('ETH/BTC',exchange="binance",number_of_data_points=5)
89 | assert isinstance(data,list) and not 'message' in data
90 |
91 | def test_number_data_points(self):
92 | '''test number of data points'''
93 | data=crypto.trades('ETH/BTC',exchange="binance",number_of_data_points=5)
94 | assert len(data)==5
95 |
96 | class Test_order_book:
97 | def test_return_type(self):
98 | '''test return type'''
99 | data=crypto.order_book('BTC/USD',number_of_data_points=5)
100 | assert isinstance(data,dict) and not 'message' in data
101 |
102 | def test_returned_data(self):
103 | '''test returned data'''
104 | data=crypto.order_book('BTC/USD',number_of_data_points=5)
105 | assert 'bids','asks' in data
106 |
107 |
108 | class Test_L2_order_book:
109 | def test_return_type(self):
110 | '''test return type'''
111 | data=crypto.L2_order_book('BTC/USD',number_of_data_points=5)
112 | assert isinstance(data,dict) and not 'message' in data
113 |
114 | def test_returned_data(self):
115 | '''test returned data'''
116 | data=crypto.L2_order_book('BTC/USD',number_of_data_points=5)
117 | assert 'bids','asks' in data
118 |
119 |
120 | class Test_currencies:
121 | def test_return_type(self):
122 | '''test return type'''
123 | data=crypto.currencies(exchange="kraken")
124 | assert isinstance(data,dict) and not 'message' in data
125 |
126 | """
127 | class Test_user_balance:
128 | def test_return_type(self):
129 | '''test return type'''
130 | data=crypto.user_balance(test_mode=True)
131 | assert isinstance(data,dict) and not 'message' in data
132 |
133 | def test_returned_data(self):
134 | '''test returned data'''
135 | data=crypto.user_balance(test_mode=True)
136 | assert 'info' in data
137 |
138 | class Test_user_trades:
139 | def test_return_type(self):
140 | '''test return type'''
141 | data=crypto.user_trades('BTC/USD',test_mode=True)
142 | assert isinstance(data,list) and not 'message' in data
143 |
144 | def test_returned_data(self):
145 | '''test returned data'''
146 | data=crypto.user_trades('BTC/USD',test_mode=True)
147 | assert 'id','info' in data[0]
148 |
149 | class Test_user_closed_orders:
150 | def test_return_type(self):
151 | '''test return type'''
152 | data=crypto.user_closed_orders('BTC/USD',test_mode=True)
153 | assert isinstance(data,list) and not 'message' in data
154 |
155 | def test_returned_data(self):
156 | '''test returned data'''
157 | data=crypto.user_closed_orders('BTC/USD',test_mode=True)
158 | assert 'id','info' in data[0]
159 |
160 | class Test_get_order:
161 | def test_return_type(self):
162 | '''test return type'''
163 | data=crypto.get_order(order_id="55d7e42e-3a6c-41f7-a692-9bdcd23dce70",symbol='BTC/USD',test_mode=True)
164 | assert isinstance(data,dict) and not 'message' in data
165 |
166 | def test_returned_data(self):
167 | '''test returned data'''
168 | data=crypto.get_order(order_id="55d7e42e-3a6c-41f7-a692-9bdcd23dce70",symbol='BTC/USD',test_mode=True)
169 | assert 'id','info' in data
170 |
171 | class Test_user_orders:
172 | def test_return_type(self):
173 | '''test return type'''
174 | data=crypto.user_orders('BTC/USD',test_mode=True)
175 | assert isinstance(data,list) and not 'message' in data
176 |
177 | def test_returned_data(self):
178 | '''test returned data'''
179 | data=crypto.user_orders('BTC/USD',test_mode=True)
180 | assert 'id','info' in data[0]
181 |
182 | class Test_create_deposit_address:
183 | pass
184 |
185 | class Test_user_deposits:
186 | pass
187 |
188 | class Test_user_deposit_address:
189 | pass
190 |
191 | class Test_user_withdrawls:
192 | pass
193 |
194 | class Test_user_transactions:
195 | def test_return_type(self):
196 | '''test return type'''
197 | data=crypto.user_transactions('USD',test_mode=True)
198 | assert isinstance(data,list) and not 'message' in data
199 | """
--------------------------------------------------------------------------------
/tests/test_options.py:
--------------------------------------------------------------------------------
1 | import libkloudtrader.options as options
2 | import pandas
3 |
4 | class TestChains:
5 | def test_return_type(self):
6 | '''test return type'''
7 | expiration=options.expirations(underlying_symbol='AAPL')[0]['date']
8 | data=options.chains(underlying_symbol="AAPL",expiration=expiration,dataframe=False)
9 | assert isinstance(data,list)
10 |
11 | def test_dataframe_return_type(self):
12 | '''test dataframe return type'''
13 | expiration=options.expirations(underlying_symbol='AAPL')[0]['date']
14 | data=options.chains(underlying_symbol="AAPL",expiration=expiration)
15 | assert isinstance(data,pandas.DataFrame)
16 |
17 | def test_data(self):
18 | '''test returned data'''
19 | expiration=options.expirations(underlying_symbol='AAPL')[0]['date']
20 | data=options.chains(underlying_symbol="AAPL",expiration=expiration,dataframe=False)
21 | assert 'description','high'in data[0]
22 |
23 | def test_wrong_symbl(self):
24 | pass
25 |
26 | def test_Wrong_date(self):
27 | pass
28 |
29 |
30 | class TestExpirations:
31 | def test_return_type(seld):
32 | '''test return type'''
33 | data=options.expirations(underlying_symbol="AAPL")
34 | assert isinstance(data,list)
35 |
36 | def test_data(self):
37 | '''test returned data'''
38 | data=options.expirations(underlying_symbol="AAPL")
39 | assert 'data','strikes' in data[0]
40 |
41 | def test_wrong_symbol(self):
42 | '''test wrong underlying symbol'''
43 | data=options.expirations(underlying_symbol="AAPL##RRWSSDJKF")
44 | assert data['expirations']==None
45 |
46 | class TestStrikes:
47 | def test_return_type(self):
48 | '''test return type'''
49 | expiration=options.expirations(underlying_symbol='AAPL')[0]['date']
50 | data=options.strikes(underlying_symbol="AAPL",expiration=expiration)
51 | assert isinstance(data,dict)
52 |
53 | def test_data(self):
54 | '''test returned data'''
55 | expiration=options.expirations(underlying_symbol='AAPL')[0]['date']
56 | data=options.strikes(underlying_symbol="AAPL",expiration=expiration)
57 | assert 'strike' in data['strikes']
58 |
59 | class TestBuyToOpen:
60 | pass
61 |
62 | class TestBuyToClose:
63 | pass
64 |
65 | class TestSellToOpen:
66 | pass
67 |
68 | class TestSellToClose:
69 | pass
--------------------------------------------------------------------------------
/tests/test_stocks.py:
--------------------------------------------------------------------------------
1 | '''This module contains tests for stocks module'''
2 |
3 | import sys
4 | import datetime
5 | sys.path.append('./libkloudtrader')
6 | import pandas
7 | import libkloudtrader.stocks as stocks
8 |
9 | class TestLatestPriceInfo:
10 | def test_type(self):
11 | """Test return type"""
12 | data = stocks.latest_price_info('AAPl')
13 | assert isinstance(data, dict)
14 |
15 | def test_pandas_type(self):
16 | """Test return type"""
17 | data = stocks.latest_price_info('AAPl', dataframe=True)
18 | assert isinstance(data, pandas.DataFrame)
19 |
20 | def test_data(self):
21 | """Test if data is correct"""
22 | data = stocks.latest_price_info('AAPl')
23 | assert 'last','change' in data
24 |
25 | def test_multiple_symbols(self):
26 | """Test multiple symbols as input"""
27 | data=stocks.latest_price_info('AAPL,SPY,GOOG,GE')
28 | for i in data:
29 | assert 'last','change' in data
30 |
31 | class TestCreateSession:
32 | def test_return_type(self):
33 | """Test return type and data"""
34 | data=stocks.create_session()
35 | assert isinstance(data,str)
36 |
37 | class TestLatestQuote:
38 | def test_return_type_and_data(self):
39 | """Test return type and data"""
40 | data=stocks.latest_quote('aapl')
41 | assert isinstance(data,dict) and 'bidsz','ask' in data
42 |
43 | def test_wrong_symbol_input(self):
44 | """Test non existing symbol as input"""
45 | pass
46 |
47 | class TestLatestTrade:
48 | def test_return_type_and_data(self):
49 | """Test return type and data"""
50 | data=stocks.latest_trade('aapl')
51 | assert isinstance(data,dict) and 'last','type' in data
52 |
53 | def test_wrong_symbol_input(self):
54 | """Test non existing symbol as input"""
55 | pass
56 |
57 | class TestIntradaySummary:
58 | def test_return_type_and_data(self):
59 | """Test return type and data"""
60 | data=stocks.intraday_summary('aapl')
61 | assert isinstance(data,dict) and 'open','low' in data
62 |
63 | def test_wrong_symbol_input(self):
64 | """Test non existing symbol as input"""
65 | pass
66 |
67 | class TestOHLCV:
68 | def test_type(self):
69 | """Test return type"""
70 | data = stocks.ohlcv('AAPl',start="2018-01-01",end="2019-01-01",dataframe=False)
71 | assert isinstance(data, dict)
72 |
73 | def test_pandas_type(self):
74 | """Test return Type"""
75 | data=stocks.ohlcv('AAPl',start="2018-01-01",end="2019-01-01")
76 | assert isinstance(data, pandas.DataFrame)
77 |
78 | def test_data(self):
79 | """Test data returned"""
80 | data=stocks.ohlcv('AAPl',start="2018-01-01",end="2019-01-01",dataframe=False)
81 | assert 'day' in data['history']
82 |
83 | def test_wrong_date(self):
84 | """Exception for wrong date"""
85 | pass
86 |
87 | def test_multiple_symbols(self):
88 | """No data retured with multiple symbols"""
89 | pass
90 |
91 | def test_number_returned_data_points(self):
92 | """Test number of data of points returned based on start and end"""
93 | pass
94 |
95 | def test_fake_symbol(self):
96 | """Test when a symbol is given that does not exists"""
97 | pass
98 | '''
99 | class TesthistoricalTickData:
100 | def setup(self):
101 | self.start=datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
102 | d = datetime.datetime.today() - datetime.timedelta(days=3)
103 | self.end=d.strftime("%Y-%m-%d %H:%M:%S")
104 | def test_type(self):
105 | """Test return type"""
106 | data = stocks.tick_data('AAPL',start=self.start,end=self.end)
107 | assert isinstance(data, dict)
108 |
109 | def test_pandas_type(self):
110 | """Test return Type"""
111 | data=stocks.tick_data('AAPL',start=self.start,end=self.end,dataframe=True)
112 | assert isinstance(data, pandas.DataFrame)
113 |
114 | def test_data(self):
115 | """Test data returned"""
116 | data=stocks.tick_data('AAPL',start=self.start,end=self.end)
117 | assert 'data' in data['series']
118 |
119 | def test_date_older_than_allowed(self):
120 | """Test for date input older than 5 days."""
121 | pass
122 |
123 | def test_multiple_symbols(self):
124 | """No data retured with multiple symbols"""
125 | pass
126 |
127 | def test_number_returned_data_points(self):
128 | """Test number of data of points returned based on start and end"""
129 | pass
130 |
131 | def test_fake_symbol(self):
132 | """Test when a symbol is given that does not exists"""
133 | pass
134 |
135 | class Test1minBarData:
136 | def setup(self):
137 | self.start=datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
138 | d = datetime.datetime.today() - datetime.timedelta(days=3)
139 | self.end=d.strftime("%Y-%m-%d %H:%M:%S")
140 | print(self.start)
141 | def test_type(self):
142 | """Test return type"""
143 | data = stocks.min1_bar_data('AAPL',start=self.start,end=self.end)
144 | assert isinstance(data, dict)
145 |
146 | def test_pandas_type(self):
147 | """Test return Type"""
148 | data=stocks.min1_bar_data('AAPL',start=self.start,end=self.end,dataframe=True)
149 | assert isinstance(data, pandas.DataFrame)
150 |
151 | def test_data(self):
152 | """Test data returned"""
153 | data=stocks.min1_bar_data('AAPL',start=self.start,end=self.end)
154 | assert 'data' in data['series']
155 |
156 | def test_date_older_than_allowed(self):
157 | """Test for date input older than 20 days with open filter and 10 days with all filter"""
158 | pass
159 |
160 | def test_multiple_symbols(self):
161 | """No data retured with multiple symbols"""
162 | pass
163 |
164 | def test_number_returned_data_points(self):
165 | """Test number of data of points returned based on start and end"""
166 | pass
167 |
168 | def test_fake_symbol(self):
169 | """Test when a symbol is given that does not exists"""
170 | pass
171 |
172 | class Test5minBarData:
173 | def setup(self):
174 | self.start=datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
175 | d = datetime.datetime.today() - datetime.timedelta(days=8)
176 | self.end=d.strftime("%Y-%m-%d %H:%M:%S")
177 | def test_type(self):
178 | """Test return type"""
179 | data = stocks.min5_bar_data('AAPL',start=self.start,end=self.end)
180 | assert isinstance(data, dict)
181 |
182 | def test_pandas_type(self):
183 | """Test return Type"""
184 | data=stocks.min5_bar_data('AAPL',start=self.start,end=self.end,dataframe=True)
185 | assert isinstance(data, pandas.DataFrame)
186 |
187 | def test_data(self):
188 | """Test data returned"""
189 | data=stocks.min5_bar_data('AAPL',start=self.start,end=self.end)
190 | assert 'data' in data['series']
191 |
192 | def test_date_older_than_allowed(self):
193 | """Test for date input older than 40 days with open filter and 18 days with all filter"""
194 | pass
195 |
196 | def test_multiple_symbols(self):
197 | """No data retured with multiple symbols"""
198 | pass
199 |
200 | def test_number_returned_data_points(self):
201 | """Test number of data of points returned based on start and end"""
202 | pass
203 |
204 | def test_fake_symbol(self):
205 | """Test when a symbol is given that does not exists"""
206 | pass
207 |
208 | class Test15minBarData:
209 | def setup(self):
210 | self.start=datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S")
211 | d = datetime.datetime.today() - datetime.timedelta(days=10)
212 | self.end=d.strftime("%Y-%m-%d %H:%M:%S")
213 | def test_type(self):
214 | """Test return type"""
215 | data = stocks.min15_bar_data('AAPL',start=self.start,end=self.end)
216 | assert isinstance(data, dict)
217 |
218 | def test_pandas_type(self):
219 | """Test return Type"""
220 | data=stocks.min15_bar_data('AAPL',start=self.start,end=self.end,dataframe=True)
221 | assert isinstance(data, pandas.DataFrame)
222 |
223 | def test_data(self):
224 | """Test data returned"""
225 | data=stocks.min15_bar_data('AAPL',start=self.start,end=self.end)
226 | assert 'data' in data['series']
227 |
228 | def test_date_older_than_allowed(self):
229 | """Test for date input older than 40 days with open filter and 18 days with all filter"""
230 | pass
231 |
232 | def test_multiple_symbols(self):
233 | """No data retured with multiple symbols"""
234 | pass
235 |
236 | def test_number_returned_data_points(self):
237 | """Test number of data of points returned based on start and end"""
238 | pass
239 |
240 | def test_fake_symbol(self):
241 | """Test when a symbol is given that does not exists"""
242 | pass
243 | '''
244 | class TestStreamLiveQuotes:
245 | def test_return_type_and_data(self):
246 | """Test return type and data"""
247 | for data in stocks.stream_live_quotes('aapl'):
248 | assert isinstance(data,dict) and 'bidsz','ask' in data
249 | break
250 |
251 | def test_wrong_symbol_input(self):
252 | """Test non existing symbol as input"""
253 | pass
254 |
255 | class TestStreamLiveTrades:
256 | def test_return_type_and_data(self):
257 | """Test return type and data"""
258 | for data in stocks.stream_live_trades('aapl'):
259 | assert isinstance(data,dict) and 'last','type' in data
260 | break
261 |
262 | def test_wrong_symbol_input(self):
263 | """Test non existing symbol as input"""
264 | pass
265 |
266 | class TestStreamLiveSummary:
267 | def test_return_type_and_data(self):
268 | """Test return type and data"""
269 | for data in stocks.stream_live_summary('aapl'):
270 | assert isinstance(data,dict) and 'open','low' in data
271 | break
272 |
273 | def test_wrong_symbol_input(self):
274 | """Test non existing symbol as input"""
275 | pass
276 |
277 |
278 | class TestListOfCompanies:
279 | '''
280 | def test_return_type(self):
281 | """Test return Type"""
282 | list_of_exchanges=['all','nyse','nasdaq','amex']
283 | for x in list_of_exchanges:
284 | data=stocks.list_of_companies(x)
285 | assert isinstance(data,pandas.DataFrame)
286 | '''
287 | def test_data(self):
288 | """Test columns in the returned dataframe"""
289 | pass
290 |
291 | class TestIntradayStatus:
292 | def test_return_type(self):
293 | """Test return type"""
294 | data=stocks.intraday_status()
295 | assert isinstance(data,dict)
296 |
297 | def test_data(self):
298 | """Test return data"""
299 | data=stocks.intraday_status()
300 | assert 'date' and 'next_state' in data
301 |
302 | class TestMarketCalendar:
303 | def test_return_type(self):
304 | """Test return type"""
305 | data=stocks.market_calendar(7,2019)
306 | assert isinstance(data,dict)
307 |
308 | def test_wrong_inputs(self):
309 | """Test wrong inputs"""
310 | pass
311 |
312 | class TestSymbolSearch:
313 | def test_return_type(self):
314 | """Test return type"""
315 | data=stocks.symbol_search('apple')
316 | assert isinstance(data,dict)
317 |
318 | def test_wrong_input(self):
319 | """Test wrong input"""
320 | pass
321 |
322 | class TestSymbolLookup:
323 | def test_return_type(self):
324 | """Test return type"""
325 | data=stocks.symbol_lookup('aap')
326 | assert isinstance(data,dict)
327 |
328 | def test_wrong_input(self):
329 | """Test wrong input"""
330 | pass
331 |
332 | class TestShortableSecurities:
333 | def test_return_type(self):
334 | """Test return type"""
335 | data=stocks.shortable_securities(dataframe=False)
336 | assert isinstance(data,dict)
337 |
338 | def test_pandas_return_type(self):
339 | """Test datframe = True return type"""
340 | data=stocks.shortable_securities()
341 | assert isinstance(data,pandas.DataFrame)
342 |
343 | def test_data(self):
344 | """Test returned data"""
345 | data=stocks.shortable_securities(dataframe=False)
346 | assert 'security' in data['securities']
347 |
348 | class TestCheckIfShortable:
349 | def test_return_type_and_return_data_for_right_symbol(self):
350 | """Test return type and data"""
351 | data=stocks.check_if_shortable('GOOG')
352 | assert isinstance(data,bool) and data==True
353 |
354 | def test_return_type_and_return_data_for_wrong_symbol(self):
355 | """Test return type and data"""
356 | data=stocks.check_if_shortable('RTADSS45')
357 | assert isinstance(data,bool) and data==False
358 |
359 |
360 | class TestCompanyFundamentals:
361 | def test_return_type(self):
362 | """Test return type and data"""
363 | data=stocks.company_fundamentals('AAPL')
364 | assert isinstance(data,list)
365 |
366 | def test_wrong_symbol(self):
367 | """Test wrong symbol"""
368 | pass
369 |
370 | class TestCorporateCalendar:
371 | def test_return_type(self):
372 | """Test return type and data"""
373 | data=stocks.corporate_calendar('AAPL')
374 | assert isinstance(data,list)
375 |
376 | def test_wrong_symbol(self):
377 | """Test wrong symbol"""
378 | pass
379 |
380 | class TestCorporateActions:
381 | def test_return_type(self):
382 | """Test return type and data"""
383 | data=stocks.dividend_information('AAPL')
384 | assert isinstance(data,list)
385 |
386 | def test_wrong_symbol(self):
387 | """Test wrong symbol"""
388 | pass
389 |
390 | class TestDividendInformation:
391 | def test_return_type(self):
392 | """Test return type and data"""
393 | data=stocks.dividend_information('AAPL')
394 | assert isinstance(data,list)
395 |
396 | def test_wrong_symbol(self):
397 | """Test wrong symbol"""
398 | pass
399 |
400 | class TestCorporateActions:
401 | def test_return_type(self):
402 | """Test return type and data"""
403 | data=stocks.corporate_actions('AAPL')
404 | assert isinstance(data,list)
405 |
406 | def test_wrong_symbol(self):
407 | """Test wrong symbol"""
408 | pass
409 |
410 | class TestOperationRatio:
411 | def test_return_type(self):
412 | """Test return type and data"""
413 | data=stocks.operation_ratio('AAPL')
414 | assert isinstance(data,list)
415 |
416 | def test_wrong_symbol(self):
417 | """Test wrong symbol"""
418 | pass
419 |
420 | class TestCorporateFiancials:
421 | def test_return_type(self):
422 | """Test return type and data"""
423 | data=stocks.corporate_financials('AAPL')
424 | assert isinstance(data,list)
425 |
426 | def test_wrong_symbol(self):
427 | """Test wrong symbol"""
428 | pass
429 |
430 | class TestPriceStatistics:
431 | def test_return_type(self):
432 | """Test return type and data"""
433 | data=stocks.price_statistics('AAPL')
434 | assert isinstance(data,list)
435 |
436 | def test_wrong_symbol(self):
437 | """Test wrong symbol"""
438 | pass
439 |
440 |
441 | class TestBuyPreview:
442 | pass
443 |
444 | class TestBuyToCoverPreview:
445 | pass
446 |
447 | class TestSellPreview:
448 | pass
449 |
450 | class TestSellShortPreview:
451 | pass
452 |
453 | class TestBuy:
454 | pass
455 |
456 | class TestBuyToCover:
457 | pass
458 |
459 | class TestSell:
460 | pass
461 |
462 | class TestShortSell:
463 | pass
464 |
465 | class TestChangeOrder:
466 | pass
467 |
468 | class TestCancelOrder:
469 | pass
470 |
471 |
472 | class TestUserProfile:
473 | def test_return_type(self):
474 | '''test return type'''
475 | data=stocks.user_profile()
476 | assert isinstance(data,dict)
477 |
478 | def test_returned_data(self):
479 | '''test returned data'''
480 | data=stocks.user_profile()
481 | assert 'account'in data['profile']
482 |
483 | class TestAccountBalance:
484 | def test_return_type(self):
485 | '''test return type'''
486 | data=stocks.account_balance()
487 | assert isinstance(data,dict)
488 |
489 | def test_returned_data(self):
490 | '''test returned data'''
491 | data=stocks.account_balance()
492 | assert 'option_short_value','equity' in data['balances']
493 |
494 | class TestAccountHistory:
495 | def test_return_type(self):
496 | '''test return type'''
497 | data=stocks.account_history()
498 | assert isinstance(data,dict)
499 |
500 | def test_returned_data(self):
501 | '''test returned data'''
502 | data=stocks.account_history()
503 | assert 'event' in data['history']
504 |
505 | class TestAccountPositions:
506 | def test_return_type(self):
507 | '''test return type'''
508 | data=stocks.account_positions()
509 | assert isinstance(data,dict)
510 |
511 | class TestAccountClosedPositions:
512 | def test_return_type(self):
513 | '''test return type'''
514 | data=stocks.account_closed_positions()
515 | assert isinstance(data,dict)
516 |
517 | class TestAccountOrders:
518 | def test_return_type(self):
519 | '''test return type'''
520 | data=stocks.account_orders()
521 | assert isinstance(data,dict)
522 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py37,py35
3 |
4 | [testenv]
5 | # install pytest in the virtualenv where commands will be executed
6 | deps = pytest
7 | commands =
8 | python -V
9 | setenv=
10 | USER_ACCESS_TOKEN={env:USER_ACCESS_TOKEN:}
11 | USER_ACCOUNT_NUMBER={env:USER_ACCOUNT_NUMBER:}
12 | USER_BROKERAGE={env:USER_BROKERAGE:}
13 | CRYPTO_API_KEY={env:CRYPTO_API_KEY:}
14 | CRYPTO_API_PASSWORD={env:CRYPTO_API_PASSWORD:}
15 | CRYPTO_API_SECRET={env:CRYPTO_API_SECRET:}
16 | CRYPTO_API_UID={env:CRYPTO_API_UID:}
17 | CRYPTO_EXCHANGE={env:CRYPTO_EXCHANGE:}
18 | CRYPTO_PASSWORD=(:env:CRYPTO_PASSWORD:}
19 | AWS_ACCESS_KEY_ID={:env:AWS_ACCESS_KEY_ID:}
20 | AWS_DEFAULT_REGION={:env:AWS_DEFAULT_REGION:}
21 | AWS_SECRET_ACCESS_KEY={:env:AWS_SECRET_ACCESS_KEY:}
--------------------------------------------------------------------------------