├── .gitignore
├── LICENSE
├── README.md
├── ViaBTCAPI
├── ViaBTCAPI.py
└── __init__.py
├── examples
├── ViaBTCAPI
├── example.py
├── exchange_info.py
├── print_balances.py
├── print_recent_trades.py
├── show_orderbook.py
├── test_trading.py
└── update_balance.py
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 | .vscode/**
106 |
--------------------------------------------------------------------------------
/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 [yyyy] [name of copyright owner]
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # python-viabtc-api
2 | API Wrapper for [ViaBTC exchange server](https://github.com/testnet-exchange/viabtc_exchange_server) - open source cryptocurrency exchange engine. Also works with the [original exchange server](http://github.com/viabtc/viabtc_exchange_server).
3 |
4 | [
](https://morejust.foundation/?from=python-viabtc-api)
5 |
6 | ## Installation
7 |
8 | This API is very simple. The installation is just the downloading sources from github
9 |
10 | ``` bash
11 | git clone https://github.com/testnet-exchange/python-viabtc-api
12 | cd python-viabtc-api
13 | pip3 install -r requirements.txt
14 | ```
15 |
16 | ## Usage
17 |
18 | The basic usage:
19 |
20 | ``` python
21 | from ViaBTCAPI.ViaBTCAPI import ViaBTCAPI
22 |
23 | exchange_url = "http://localhost:8080/" # choose to your exchange url
24 | api = ViaBTCAPI(exchange_url)
25 |
26 | resp = api.market_list()
27 | market_names = [m["name"] for m in resp["result"]]
28 | print("Exchange markets: ", market_names)
29 |
30 | print()
31 | print("Orderbooks:")
32 | for market in market_names:
33 | ob = api.order_depth(market=market)
34 | print(market, ob["result"])
35 | ```
36 |
37 | More usage code examples you can find in [examples](https://github.com/testnet-exchange/python-viabtc-api/blob/master/examples) folder. Read the code first, it may contain some hardcoded constants that should be changed.
38 |
39 | ---
40 |
41 | # Working with the exchange server
42 |
43 | Since [I](https://github.com/ohld) have had a lot of troubles with the original exchange server by ViaBTC, I've decided to write this tutorial for beginners. I hope that helps.
44 |
45 | ## Install exchange
46 |
47 | For me the easiest way to install the exchange was found in [bitlum](https://github.com/bitlum)'s fork of the original [ViaBTC](https://github.com/viabtc/viabtc_exchange_server) repository. You need `docker` and `docker-compose` (up-to-date) to launch this installation script.
48 |
49 | ``` bash
50 | git clone https://github.com/testnet-exchange/viabtc_exchange_server
51 | cd viabtc_exchange_server/docker
52 | sudo docker-compose up
53 | ```
54 |
55 | That's it! It successfully run on Ubuntu and Debian servers, but failed on macOS (there were some disk path errors that I balieve can be easily fixed if you are familiar with docker or stackoverflow).
56 |
57 | ## Connect to exchange local network
58 |
59 | `Docker-compose` creates the local net for all dockers images. Take a look at [docker-compose file](https://github.com/bitlum/viabtc_exchange_server/blob/master/docker/docker-compose.yml): you may notice the local ip addresses near every docker container. We will use the address of `accesshttp` container to make API requests.
60 |
61 | As all of that stuff is happening on the remote server's local network, we need to make some port forwarding from it to out development machine (in my case this is my macbook laptop):
62 |
63 | ``` bash
64 | ssh user@ -L 8080:192.168.18.45:8080 -N -f
65 | ```
66 |
67 | where `192.168.18.45` is the ip address of `accesshttp` container and `8080` is its port.
68 |
69 | And now you can send API requests to `exchange_url = "http://localhost:8080"`
70 |
71 | ----
72 |
73 | I spent a few hours to figure out how to run the exchange and make requests to it. If this tutorial helped you, smash the star button at the top of the page. And fell free to make Pull Requests with some additional functionallity.
74 |
75 | *Happy Coding!*
76 |
77 | [
](https://morejust.foundation/?from=python-viabtc-api)
78 |
--------------------------------------------------------------------------------
/ViaBTCAPI/ViaBTCAPI.py:
--------------------------------------------------------------------------------
1 | # author: okhlopkov.com
2 | # please consider using python3
3 |
4 | import random
5 | import requests
6 |
7 | class ViaBTCAPI(object):
8 | headers = {'content-type': 'application/json'}
9 | base_params = {"jsonrpc": "2.0", "id": 0}
10 |
11 | SELL_STR = "SELL"
12 | BUY_STR = "BUY"
13 |
14 | def __init__(self, exchange_url, _use_first_random_op_id=True):
15 | self.exchange_url = exchange_url
16 |
17 | # operation id should be unique for each operation
18 | self._op_id = 0
19 | if _use_first_random_op_id:
20 | self._op_id = random.randint(0, 1000000)
21 |
22 |
23 | def _execute(self, method, params):
24 | return requests.post(
25 | self.exchange_url,
26 | json={
27 | "method": method,
28 | "params": params,
29 | **self.base_params},
30 | headers=self.headers
31 | ).json()
32 |
33 | def _get_side_code(self, side):
34 | _side = 1 if side == self.SELL_STR else 2 if side == self.BUY_STR else 0
35 | if _side == 0:
36 | raise Exception("Only 'side={}' and 'side={}' allowed.".format(self.SELL_STR, self.BUY_STR))
37 | return _side
38 |
39 | def balance_query(self, user_id=1, asset=None):
40 | if asset is None:
41 | return self._execute("balance.query", [user_id])
42 | return self._execute("balance.query", [user_id, asset])
43 |
44 | def balance_history(
45 | self,
46 | user_id=1,
47 | asset="BTC",
48 | business_type="",
49 | start_time=0,
50 | end_time=0,
51 | offset=0,
52 | limit=10
53 | ):
54 | return self._execute(
55 | "balance.history",
56 | [user_id, asset, "", start_time, end_time, offset, limit]
57 | )
58 |
59 | def balance_update(self, user_id=1, asset="BTC", amount=1.1, business_type="", detail={}):
60 | self._op_id += 1
61 | return self._execute(
62 | "balance.update",
63 | [user_id, asset, business_type, self._op_id, str(amount), detail]
64 | )
65 |
66 | def asset_list(self):
67 | return self._execute("asset.list", [])
68 |
69 | def asset_summary(self):
70 | return self._execute("asset.summary", [])
71 |
72 | def order_put_limit(
73 | self,
74 | user_id=1,
75 | market="BTCETH",
76 | side="SELL",
77 | amount=100,
78 | price=1,
79 | taker_fee_rate=0.0001,
80 | maker_fee_rate=0.0001,
81 | source=""
82 | ):
83 | _side = self._get_side_code(side)
84 | return self._execute(
85 | "order.put_limit",
86 | [user_id, market, _side, str(amount), str(price),
87 | str(taker_fee_rate), str(maker_fee_rate), source]
88 | )
89 |
90 | def order_put_market(self):
91 | raise Exception("Not Implemented")
92 |
93 | def order_cancel(self, user_id, market, order_id):
94 | return self._execute("order.cancel", [user_id, market, order_id])
95 |
96 | def order_deals(self, order_id=1, offset=0, limit=10):
97 | return self._execute("order.deals", [order_id, offset, limit])
98 |
99 | def order_book(self, market="BTCETH", limit=10, side="SELL"):
100 | raise Exception("Official docs are wrong. See: https://github.com/viabtc/viabtc_exchange_server/issues/123")
101 | # _side = self._get_side_code(side)
102 | # return self._execute("order.book", [market, side, 0, limit])
103 |
104 | def order_depth(self, market="BTCETH", limit=10):
105 | return self._execute("order.depth", [market, limit, "0"])
106 |
107 | def order_pending(self, user_id=1, market='BTCETH', offset=0, limit=0):
108 | return self._execute("order.pending", [user_id, market, offset, limit])
109 |
110 | def order_pending_detail(self):
111 | raise Exception("Not Implemented")
112 |
113 | def order_finished(self):
114 | raise Exception("Not Implemented")
115 |
116 | def order_finished_detail(self):
117 | raise Exception("Not Implemented")
118 |
119 | def market_last(self, market):
120 | return self._execute("market.last", [market])
121 |
122 | def market_deals(self, market, limit=10000, last_id=0):
123 | return self._execute("market.deals", [market, limit, last_id])
124 |
125 | def market_user_deals(self, user_id, market, offset, limit):
126 | raise Exception("Not Implemented")
127 |
128 | def market_kline(self, market, start, end, interval):
129 | return self._execute("market.kline", [start, end, interval])
130 |
131 | def market_status(self, market="BTCETH", period=86400):
132 | return self._execute("market.status", [market, period])
133 |
134 | def market_status_today(self, market="BTCETH"):
135 | return self._execute("market.status_today", [market])
136 |
137 | def market_list(self):
138 | return self._execute("market.list", [])
139 |
140 | def market_summary(self, market):
141 | return self._execute("market.summary", [market])
142 |
143 |
--------------------------------------------------------------------------------
/ViaBTCAPI/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ohld/python-viabtc-api/be7be15944004498be8da9e4435020d97408a352/ViaBTCAPI/__init__.py
--------------------------------------------------------------------------------
/examples/ViaBTCAPI:
--------------------------------------------------------------------------------
1 | ../ViaBTCAPI
--------------------------------------------------------------------------------
/examples/example.py:
--------------------------------------------------------------------------------
1 | from ViaBTCAPI.ViaBTCAPI import ViaBTCAPI
2 |
3 | EXCHANGE_URL = "http://localhost:8080/" # choose to your exchange url
4 | api = ViaBTCAPI(EXCHANGE_URL)
5 |
6 | # consts
7 | user_id = 2
8 | asset = "BTC"
9 | market = "BTCETH"
10 | side = "BUY"
11 |
12 | print("\n", "update balance")
13 | print(api.balance_update(user_id=user_id, asset=asset, amount=100.123))
14 |
15 | print("\n", "get balance")
16 | print(api.balance_query(user_id=user_id, asset=asset))
17 |
18 | print("\n", "see balance change history")
19 | print(api.balance_history(user_id=user_id, asset=asset))
20 |
21 | print("\n", "put order")
22 | print(api.order_put_limit(
23 | user_id=user_id, market=market, side=side, amount=100, price=1.5,
24 | taker_fee_rate=0.0001, maker_fee_rate=0.0001
25 | ))
26 |
27 | print("\n", "get orderbook")
28 | print(api.order_depth(market=market, limit=10))
29 |
30 | print("\n", "get all exchange assets summary")
31 | print(api.asset_summary())
--------------------------------------------------------------------------------
/examples/exchange_info.py:
--------------------------------------------------------------------------------
1 | """
2 | This script will show the information about the exchange on address {EXCHANGE_URL}.
3 | You can use it for an exchange API debug or just to monitor activity on your exchange.
4 |
5 | USAGE:
6 | You need to change EXCHANGE_URL to your ViaBTC exchange server's `accesshttp` port.
7 | Or you can just pass the URL as command line argument list this:
8 | ```
9 | python3 exchange_info.py http://localhost:8080/
10 | ```
11 |
12 | Author: @okhlopkov
13 | """
14 |
15 | import sys
16 | from ViaBTCAPI.ViaBTCAPI import ViaBTCAPI
17 |
18 | EXCHANGE_URL = "http://localhost:8080/"
19 | if len(sys.argv) > 1:
20 | EXCHANGE_URL = sys.argv[1]
21 |
22 | api = ViaBTCAPI(EXCHANGE_URL)
23 |
24 | print("Exchange address: {}".format(EXCHANGE_URL))
25 |
26 | print("\n{0}\nMarkets\n{0}".format("-" * 50))
27 |
28 | resp = api.market_list()
29 | market_names = [m["name"] for m in resp["result"]]
30 | print("Exchange markets: ", market_names)
31 |
32 | for market in market_names:
33 | last = api.market_last(market)
34 | print(market, last["result"])
35 |
36 | print("\nMarket summary:")
37 | for market in market_names:
38 | info = api.market_summary(market)
39 | print(market, info["result"])
40 |
41 | print("\nMarket status last week:")
42 | for market in market_names:
43 | status = api.market_status(market, period=86400 * 7)
44 | print(market, status["result"])
45 |
46 | print("\nMarket status last 24h:")
47 | for market in market_names:
48 | status = api.market_status_today(market)
49 | print(market, status["result"])
50 |
51 | # Don't know how to call this method, see:
52 | # https://github.com/viabtc/viabtc_exchange_server/issues/125
53 | # print("\nMarket KLine:")
54 | # for market in market_names:
55 | # kline = api.market_kline(market, 0, 0, 0)
56 | # print(market, kline["result"])
57 |
58 |
59 |
60 |
61 | print("\n{0}\nOrders\n{0}".format("-" * 50))
62 |
63 | print("\nOrderbooks:")
64 | for market in market_names:
65 | ob = api.order_depth(market=market)
66 | print(market, ob["result"])
67 |
68 | print("\nExecuted orders:")
69 | for market in market_names:
70 | history = api.market_deals(market=market, limit=100, last_id=0)
71 | print(market, history["result"])
72 |
73 |
74 |
75 |
76 | print("\n{0}\nAssets\n{0}".format("-" * 50))
77 |
78 | asset_list = api.asset_list()
79 | print("\nAssets on exchange:")
80 | for asset in asset_list["result"]:
81 | print(asset)
82 |
83 | resp = api.asset_summary()
84 | for a in resp["result"]:
85 | print("{}:\ttotal: {}\tusers has: {}".format(a["name"], a["total_balance"], a["available_count"]))
86 |
87 |
--------------------------------------------------------------------------------
/examples/print_balances.py:
--------------------------------------------------------------------------------
1 | # pass user ids as a cli arguments to shor their balances
2 | # works perfectly with 'watch' utility:
3 | # $ watch python3 print_balances.py 1 2 3
4 |
5 | import sys
6 | from ViaBTCAPI.ViaBTCAPI import ViaBTCAPI
7 |
8 | EXCHANGE_URL = "http://localhost:8080/" # choose to your exchange url
9 | api = ViaBTCAPI(EXCHANGE_URL)
10 |
11 | if len(sys.argv) == 1:
12 | print("Pass user_ids as arguments")
13 | exit()
14 |
15 | user_ids = [int(i) for i in sys.argv[1:]]
16 |
17 | for user_id in user_ids:
18 | balances = api.balance_query(user_id)
19 | bal_str = ""
20 | for asset in balances["result"]:
21 | a = balances["result"][asset]
22 | bal_str += "{0}:\t {1:0.5f} ({2:0.5f})\t ".format(asset, float(a["available"]), float(a["freeze"]))
23 | print("{}:\t {}".format(user_id, bal_str))
--------------------------------------------------------------------------------
/examples/print_recent_trades.py:
--------------------------------------------------------------------------------
1 | # Show recent trades that were executed.
2 | # Very usefull in development debug.
3 |
4 | from ViaBTCAPI.ViaBTCAPI import ViaBTCAPI
5 |
6 | EXCHANGE_URL = "http://localhost:8080/" # choose to your exchange url
7 | api = ViaBTCAPI(EXCHANGE_URL)
8 |
9 | print_last_deals = 20
10 | result = api.market_deals("TESTNET3RINKEBY", limit=print_last_deals)
11 | for order in result['result']:
12 | print(order)
--------------------------------------------------------------------------------
/examples/show_orderbook.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from ViaBTCAPI.ViaBTCAPI import ViaBTCAPI
3 |
4 | MARKET_NAME = "TESTNET3RINKEBY"
5 | EXCHANGE_URL = "http://localhost:8080/" # choose to your exchange url
6 | api = ViaBTCAPI(EXCHANGE_URL)
7 |
8 | ob = api.order_depth(market=MARKET_NAME)["result"]
9 | bids = ob["bids"]
10 | asks = ob["asks"]
11 | for price, volume in bids[::-1]:
12 | print("BID\t price: {}\t volume: {}".format(price, volume))
13 |
14 | for price, volume in asks:
15 | print("ASK\t price: {}\t volume: {}".format(price, volume))
16 |
--------------------------------------------------------------------------------
/examples/test_trading.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from ViaBTCAPI.ViaBTCAPI import ViaBTCAPI
3 |
4 | EXCHANGE_URL = "http://localhost:8080/"
5 | USER_ID = 1
6 | USER_ID_2 = 2
7 | UPDATE_MONEY = 0.1
8 | ORDER_PRICE = 0.1
9 |
10 | if len(sys.argv) > 1:
11 | EXCHANGE_URL = sys.argv[1]
12 |
13 | api = ViaBTCAPI(EXCHANGE_URL)
14 |
15 | # get consts from exchange
16 | resp = api.market_list()
17 | m = resp["result"][0]
18 | market, stock, money = m["name"], m["stock"], m["money"]
19 |
20 | # balance change
21 | r = api.balance_query(user_id=USER_ID, asset=money)
22 | balance_before = float(r["result"][money]["available"])
23 |
24 | _ = api.balance_update(user_id=USER_ID, asset=money, amount=UPDATE_MONEY)
25 |
26 | r = api.balance_query(user_id=USER_ID, asset=money)
27 | balance_after = float(r["result"][money]["available"])
28 |
29 | assert(balance_after == balance_before + UPDATE_MONEY)
30 |
31 |
32 | # limit order creation
33 | r = api.order_put_limit(
34 | user_id=USER_ID, market=market, side='BUY', amount=UPDATE_MONEY, price=ORDER_PRICE,
35 | taker_fee_rate=0, maker_fee_rate=0)
36 |
37 | r = api.order_depth(market=market, limit=10)
38 | bid_prices = [float(b[0]) for b in r["result"]["bids"]]
39 | assert(ORDER_PRICE in bid_prices)
40 | bid_volume = [float(b[1]) for b in r["result"]["bids"] if float(b[0]) == ORDER_PRICE][0]
41 |
42 |
43 | # create the second user and execute the order
44 | _ = api.balance_update(user_id=USER_ID_2, asset=stock, amount=bid_volume)
45 | r = api.order_put_limit(
46 | user_id=USER_ID_2, market=market, side='SELL', amount=bid_volume, price=ORDER_PRICE,
47 | taker_fee_rate=0, maker_fee_rate=0)
48 |
49 | r = api.order_depth(market=market, limit=10)
50 | prices = [float(b[0]) for b in r["result"]["bids"] + r["result"]["asks"]]
51 | assert(ORDER_PRICE not in prices)
52 |
53 | # reset balances
54 | for user_id in [USER_ID, USER_ID_2]:
55 | for asset in [money, stock]:
56 | r = api.balance_query(user_id=user_id, asset=asset)
57 | balance_current = float(r["result"][asset]["available"])
58 | r = api.balance_update(user_id=user_id, asset=asset, amount=(-1) * balance_current)
59 |
60 | print("All tests have been passed!")
61 |
--------------------------------------------------------------------------------
/examples/update_balance.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from ViaBTCAPI.ViaBTCAPI import ViaBTCAPI
3 |
4 | EXCHANGE_URL = "http://localhost:8080/" # choose to your exchange url
5 | api = ViaBTCAPI(EXCHANGE_URL)
6 |
7 | if len(sys.argv) - 1 != 3:
8 | print("USAGE: {} ".format(sys.argv[0]))
9 | exit()
10 |
11 | user_id = int(sys.argv[1])
12 | asset = str(sys.argv[2])
13 | amount = str(sys.argv[3])
14 |
15 | resp = api.balance_update(user_id, asset, amount)
16 | print(resp["result"]["status"])
17 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | requests>=2.20.0
2 |
--------------------------------------------------------------------------------