├── .gitignore ├── .gitkeep ├── LICENSE ├── README.md ├── exchangearbitragebot ├── __init__.py ├── exchange_arbitrage.py ├── exchange_arbitrage_README.md └── exchanges │ ├── __init__.py │ ├── binance.py │ ├── theocean.py │ └── theocean_README.md └── setup.py /.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 | -------------------------------------------------------------------------------- /.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ortap/ExchangeArbitrageBot/6b045b24f795bc6d9bc72aa57ee5281a0b8ddbd4/.gitkeep -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Exchange Arbitrage Bot between Binance and The Ocean 2 | 3 | A Python implementation of a bot that places trades based on arbitrage opportunities between Binance and The Ocean. 4 | This program is meant to accompany [Lesson 3: Introduction to Arbitration Strategies](https://medium.com/the-ocean-trade/algorithmic-trading-101-lesson-3-introduction-to-arbitrage-strategies-76e546b99691). 5 | 6 | Sample Scenario Functionality: 7 | For a given token pair, if the lowest ask in exchange A is smaller than the highest bid in exchange B, the bot will buy from exchange A and sell to exchange B. 8 | 9 | ## Installation 10 | To install the bot and its dependencies, navigate to the `ExchangeArbitrageBot` directory (note the capitalizations). Then, enter the following command: 11 | ``` 12 | pip install . 13 | ``` 14 | 15 | Note: Please read the disclaimer, associated read me files and explanation of methods before running the bot. 16 | 17 | To run the Arbitrage Bot, navigate to the `exchangearbitragebot` directory and enter the following command: 18 | ``` 19 | python exchange_arbitrage.py 20 | ``` 21 | 22 | ## Requirements 23 | - Web3 Provider (such as Parity) is needed 24 | - Required environment variables 25 | - OCEAN_API_KEY 26 | - OCEAN_API_SECRET 27 | - ETHEREUM_ADDRESS 28 | - BINANCE_API_KEY 29 | - BINANCE_API_SECRET 30 | 31 | ## Explanation of Methods and Definitions (mini Wiki) 32 | - [Explanation of exchange_arbitrage.py](../master/exchangearbitragebot/exchange_arbitrage_README.md) 33 | - [Explanation of theocean.py](../master/exchangearbitragebot/exchanges/theocean_README.md) 34 | 35 | ## DISCLAIMER 36 | #### USE THE PROGRAM AT YOUR OWN RISK. YOU ARE RESPONSIBLE FOR YOUR OWN MONEY. 37 | #### IN NO EVENT SHALL THE AUTHORS OR THEIR AFFILIATES 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 PROGRAM OR THE USE OR OTHER DEALINGS IN THE PROGRAM. 38 | 39 | -------------------------------------------------------------------------------- /exchangearbitragebot/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ortap/ExchangeArbitrageBot/6b045b24f795bc6d9bc72aa57ee5281a0b8ddbd4/exchangearbitragebot/__init__.py -------------------------------------------------------------------------------- /exchangearbitragebot/exchange_arbitrage.py: -------------------------------------------------------------------------------- 1 | from time import strftime 2 | from exchanges import binance, theocean 3 | 4 | class ExchangeArbitrage(object): 5 | 6 | def __init__(self, tokenpair): 7 | self.minProfit = 0.00005 # Vary this based on tokens being traded and personal preferances 8 | self.tokenpair = tokenpair 9 | self.tokens = [tokenpair[i:i+3] for i in range(0, len(tokenpair), 3)] 10 | self.tokenA = self.tokens[0] 11 | self.tokenB = self.tokens[1] 12 | self.binance = binance.Exchange() 13 | self.theocean = theocean.Exchange() 14 | 15 | def start_arbitrage(self): 16 | print(strftime('Date: %b %d %Y Time: %H:%M:%S')) 17 | print('Starting Exchange Arbitrage between Binance and The Ocean') 18 | try: 19 | if self.check_balance(): 20 | arb_scenario = self.check_orderBook() 21 | if arb_scenario['scenario']: 22 | self.place_order(arb_scenario['scenario'], arb_scenario['ask'], arb_scenario['bid'], arb_scenario['amount'] ) 23 | else: 24 | print('Arbitrage Scenario:', arb_scenario['scenario'], '-- No arbitrage opportunities or insufficient funds') 25 | except Exception as error: 26 | print(str(error)) 27 | 28 | def check_balance(self): 29 | self.binance_balance = [float(self.binance.get_balance(self.tokenA)), float(self.binance.get_balance(self.tokenB))] 30 | self.theocean_balance = [self.theocean.get_balance(self.tokenA), self.theocean.get_balance(self.tokenB)] 31 | self.binance.balancetokA = self.binance_balance[0] 32 | self.binance.balancetokB = self.binance_balance[1] 33 | self.theocean.balancetokA = self.theocean_balance[0] 34 | self.theocean.balancetokB = self.theocean_balance[1] 35 | print('Binance Balance:' + self.tokenA + '=', self.binance_balance[0], '; ' + self.tokenB + '=', self.binance_balance[1]) 36 | print('Ocean Balance:' + self.tokenA + '=', self.theocean_balance[0], '; ' + self.tokenB + '=', self.theocean_balance[1]) 37 | return True 38 | 39 | def check_orderBook(self): 40 | # Binance 41 | self.binance_orderbook_innermost = self.binance.get_ticker_orderBook_innermost(self.tokenpair) 42 | # Binance best bid price & amount 43 | binance_bestbid_price = self.binance_orderbook_innermost[0][0] 44 | binance_bestbid_amount = self.binance_orderbook_innermost[0][1] 45 | # Binance best ask price & amount 46 | binance_bestask_price = self.binance_orderbook_innermost[1][0] 47 | binance_bestask_amount = self.binance_orderbook_innermost[1][1] 48 | 49 | # The Ocean 50 | self.ocean_orderbook_innermost = self.theocean.get_ticker_orderBook_innermost(self.tokenpair) 51 | # Binance best bid price & amount 52 | ocean_bestbid_price = self.ocean_orderbook_innermost[0][0] 53 | ocean_bestbid_amount = self.ocean_orderbook_innermost[0][1] 54 | # Binance best ask price & amount 55 | ocean_bestask_price = self.ocean_orderbook_innermost[1][0] 56 | ocean_bestask_amount = self.ocean_orderbook_innermost[1][1] 57 | 58 | # If Scenario 1 > 0: 59 | # If the highest bid price at Binance is greater than lowest ask price 60 | # at Ocean, then buy from Ocean and sell to Binance 61 | scenario1 = binance_bestbid_price - ocean_bestask_price 62 | 63 | # If Scenario 2 > 0: 64 | # If the highest bid price at Ocean is greater than lowest ask price 65 | # at Binance, then buy from Binance and sell to Ocean 66 | scenario2 = ocean_bestbid_price - binance_bestask_price 67 | 68 | if scenario1 > 0: 69 | maxAmount = self.get_max_amount(self.binance_orderbook_innermost[0], self.ocean_orderbook_innermost[1], 1) 70 | print('Max Amount for Scenario 1: {0}'.format(maxAmount)) 71 | fee = self.binance.feeRatio * maxAmount * binance_bestbid_price + self.theocean.feeRatio * maxAmount * ocean_bestask_price 72 | if abs(scenario1) * maxAmount - fee > self.minProfit: 73 | print("Binance's Bid Price: {0} is greater than TheOcean's Ask Price:{1}. Will Execute Scenario 1.".format(binance_bestbid_price, ocean_bestask_price)) 74 | return {'scenario': 1, 'ask': ocean_bestask_price, 'bid': binance_bestbid_price, 'amount': maxAmount} 75 | else: 76 | return {'scenario': 0} 77 | elif scenario2 > 0: 78 | maxAmount = self.get_max_amount(self.ocean_orderbook_innermost[0], self.binance_orderbook_innermost[1], 2) 79 | print('Max Amount for Scenario 2: {0}'.format(maxAmount)) 80 | fee = self.binance.feeRatio * maxAmount * binance_bestask_price + self.theocean.feeRatio * maxAmount * ocean_bestbid_price 81 | if abs(scenario2) * maxAmount - fee > self.minProfit: 82 | print("TheOcean's Bid Price: {0} is greater than Binance's Ask Price:{1}. Will Execute Scenario 2.".format(ocean_bestbid_price, binance_bestask_price)) 83 | return {'scenario': 2, 'ask': binance_bestask_price, 'bid': ocean_bestbid_price, 'amount': maxAmount} 84 | else: 85 | return {'scenario': 0} 86 | 87 | # Edge cases and alternate scenarios are a still work in progress. 88 | # Following are couple of scenarios that need to be implemented 89 | 90 | # Scenario 3: 91 | # If both scenario1 and scenario2 return positive, 92 | # unlikely scenario as it will require bestbid to be greater than 93 | # bestask on the ocean 94 | if scenario1 > 0 and scenario2 > 0: 95 | if abs(scenario1) > abs(scenario2): 96 | pass 97 | elif abs(scenario1) < abs(scenario2): 98 | pass 99 | # Scenario 4: 100 | # If both scenario1 and scenario2 return negative, 101 | # there are no arbitrage opportunities 102 | elif scenario1 < 0 and scenario2 < 0: 103 | if abs(scenario1) > abs(scenario2): 104 | pass 105 | elif abs(scenario1) < abs(scenario2): 106 | pass 107 | 108 | def get_max_amount(self, bidOrder, askOrder, scenario): 109 | amount = 0 110 | # Buy from the Ocean, Sell to Binance 111 | if scenario == 1: 112 | maxamtA = self.theocean.balancetokA / ((1 + self.theocean.feeRatio) * askOrder[0]) 113 | maxamtB = self.binance.balancetokB / ((1 + self.binance.feeRatio) * bidOrder[0]) 114 | amount = min(maxamtA, maxamtB, askOrder[1], bidOrder[1]) 115 | # Buy from Binance, Sell to the Ocean 116 | elif scenario == 2: 117 | maxamtA = self.binance.balancetokA / ((1 + self.binance.feeRatio) * askOrder[0]) 118 | maxamtB = self.theocean.balancetokB / ((1 + self.theocean.feeRatio) * bidOrder[0]) 119 | amount = min(maxamtA, maxamtB, askOrder[1], bidOrder[1]) 120 | return amount 121 | 122 | def place_order(self, scenario, ask, bid, amount): 123 | print(strftime('Placing orders. Date: %b %d %Y Time: %H:%M:%S')) 124 | if scenario == 1: 125 | print('Buying {0} amount of {1} at TheOcean for the price of {2} and Selling to Binance for the price of {3} \n \n'.format(amount, self.tokenA, self.ocean_orderbook_innermost[1][0], self.binance_orderbook_innermost[0][0])) 126 | self.theocean.place_order(self.tokenpair, 'buy', amount, ask) 127 | self.binance.place_order(self.tokenpair, 'sell', amount, bid) 128 | elif scenario == 2: 129 | print('Buying {0} amount of {1} at Binance for the price of {2} and Selling to TheOcean for the price of {3} \n \n'.format(amount, self.tokenA, self.binance_orderbook_innermost[1][0], self.ocean_orderbook_innermost[0][0])) 130 | self.binance.place_order(self.tokenpair, 'buy', amount, ask) 131 | self.theocean.place_order(self.tokenpair, 'sell', amount, bid) 132 | 133 | if __name__ == '__main__': 134 | engine = ExchangeArbitrage('ZRXETH', True) 135 | print(engine.start_arbitrage()) 136 | -------------------------------------------------------------------------------- /exchangearbitragebot/exchange_arbitrage_README.md: -------------------------------------------------------------------------------- 1 | # Explanation of Important Methods and Definitions in exchange_arbitrage.py 2 | 3 | This program requires importing of two modules binance.py and theocean.py that contain calls to different API endpoints for posting trades and for attaining information regarding orderBook, account details and user history. 4 | 5 | **Note: This program assumes instantaneous settlement and execution times and does not account for any latency. In reality, there exists latency in both settlement and execution when slippages may occur.** 6 | 7 | ### ____init____ method 8 | 9 | `self.minProfit` should be adjusted by the user based on the tokens being traded and other user preferences 10 | 11 | Aside: Empty __init__.py files have been placed in the directories so that the directories containing it can be treated as modules. Constructors and other variables maybe initialized there based on user convenience. 12 | 13 | ### start_arbitrage method 14 | 15 | There are three scenarios that this program currently tackles: 16 | - Scenario 1: The highest bid price at Binance is greater than the lowest ask price at The Ocean 17 | - Scenario 2: The highest bid price at The Ocean is greater than the lowest ask price at Binance 18 | - Scenario 0: No Arbitrage opportunities or insufficient wallet balances 19 | 20 | The method calls the check_balance and the check_orderBook methods to determine the scenario and execute trades based on it. 21 | 22 | ### check_balance method 23 | 24 | Returns wallet balances from respective exchanges as floats. 25 | 26 | ### check_orderBook method 27 | 28 | This method determines the viability of executing trades based on information from the two orderbooks (Binance and The Ocean), their fees and maximum amount (`get_max_amount` method) that can be traded. 29 | 30 | Detailed below are the scenarios and corresponding actions determined in this method. 31 | - Scenario 1: If the highest bid price at Binance is greater than lowest ask price at Ocean, then buy from Ocean and sell to Binance. 32 | - Scenario 2: If the highest bid price at Ocean is greater than lowest ask price at Binance, then buy from Binance and sell to Ocean 33 | - Trades are executed only if the fee adjusted return is greater than the user defined `minProfit` 34 | 35 | ### get_max_amount method 36 | 37 | This method returns the maximum amount that can be traded based on wallet balances and fees defined by `feeRatio`(defined in the imported modules). 38 | For example: The max amount (maxAmt) that can be bought given a token balance (tokBal) can be denoted by the following equation: 39 | 40 | ![equation](http://latex.codecogs.com/gif.latex?maxAmt%20%5Ctimes%20askPrice%20+%20maxAmt%20%5Ctimes%20askPrice%20%5Ctimes%20feeRatio%20%3D%20tokBal) 41 | 42 | Solving for maxAmt: 43 | 44 | ![equation](http://latex.codecogs.com/gif.latex?maxAmt%20%3D%20%5Cfrac%7BtokBal%7D%7B%281+feeRatio%29%20%5Ctimes%20askPrice%7D) 45 | 46 | For the purposes of this bot, a rudimentary fee model has been used where a fixed `feeRatio` is applied for both the takers and makers. The `feeRatio` variable should be changed to incorporate discounts, gas costs and user defined tolerances for better execution of trades and accurate reflection of returns. 47 | 48 | ### Snippet of exchange_arbitrage.py 49 | 50 | ```python 51 | from time import strftime 52 | from exchanges import binance, theocean 53 | 54 | class ExchangeArbitrage(object): 55 | 56 | def __init__(self, tokenpair): 57 | self.minProfit = 0.00005 # Vary this based on tokens being traded and personal preferances 58 | self.tokenpair = tokenpair 59 | self.tokens = [tokenpair[i:i+3] for i in range(0, len(tokenpair), 3)] 60 | self.tokenA = self.tokens[0] 61 | self.tokenB = self.tokens[1] 62 | self.binance = binance.Exchange() 63 | self.theocean = theocean.Exchange() 64 | 65 | def start_arbitrage(self): 66 | print(strftime('Date: %b %d %Y Time: %H:%M:%S')) 67 | print('Starting Exchange Arbitrage between Binance and The Ocean') 68 | try: 69 | if self.check_balance(): 70 | arb_scenario = self.check_orderBook() 71 | if arb_scenario['scenario']: 72 | self.place_order(arb_scenario['scenario'], arb_scenario['ask'], arb_scenario['bid'], arb_scenario['amount'] ) 73 | else: 74 | print('Arbitrage Scenario:', arb_scenario['scenario'], '-- No arbitrage opportunities or insufficient funds') 75 | except Exception as error: 76 | print(str(error)) 77 | 78 | def check_balance(self): 79 | self.binance_balance = [float(self.binance.get_balance(self.tokenA)), float(self.binance.get_balance(self.tokenB))] 80 | self.theocean_balance = [self.theocean.get_balance(self.tokenA), self.theocean.get_balance(self.tokenB)] 81 | self.binance.balancetokA = self.binance_balance[0] 82 | self.binance.balancetokB = self.binance_balance[1] 83 | self.theocean.balancetokA = self.theocean_balance[0] 84 | self.theocean.balancetokB = self.theocean_balance[1] 85 | print('Binance Balance:' + self.tokenA + '=', self.binance_balance[0], '; ' + self.tokenB + '=', self.binance_balance[1]) 86 | print('Ocean Balance:' + self.tokenA + '=', self.theocean_balance[0], '; ' + self.tokenB + '=', self.theocean_balance[1]) 87 | return True 88 | 89 | def check_orderBook(self): 90 | # Binance 91 | self.binance_orderbook_innermost = self.binance.get_ticker_orderBook_innermost(self.tokenpair) 92 | # Binance best bid price & amount 93 | binance_bestbid_price = self.binance_orderbook_innermost[0][0] 94 | binance_bestbid_amount = self.binance_orderbook_innermost[0][1] 95 | # Binance best ask price & amount 96 | binance_bestask_price = self.binance_orderbook_innermost[1][0] 97 | binance_bestask_amount = self.binance_orderbook_innermost[1][1] 98 | 99 | # The Ocean 100 | self.ocean_orderbook_innermost = self.theocean.get_ticker_orderBook_innermost(self.tokenpair) 101 | # Binance best bid price & amount 102 | ocean_bestbid_price = self.ocean_orderbook_innermost[0][0] 103 | ocean_bestbid_amount = self.ocean_orderbook_innermost[0][1] 104 | # Binance best ask price & amount 105 | ocean_bestask_price = self.ocean_orderbook_innermost[1][0] 106 | ocean_bestask_amount = self.ocean_orderbook_innermost[1][1] 107 | 108 | # If Scenario 1 > 0: 109 | # If the highest bid price at Binance is greater than lowest ask price 110 | # at Ocean, then buy from Ocean and sell to Binance 111 | scenario1 = binance_bestbid_price - ocean_bestask_price 112 | 113 | # If Scenario 2 > 0: 114 | # If the highest bid price at Ocean is greater than lowest ask price 115 | # at Binance, then buy from Binance and sell to Ocean 116 | scenario2 = ocean_bestbid_price - binance_bestask_price 117 | 118 | if scenario1 > 0: 119 | maxAmount = self.get_max_amount(self.binance_orderbook_innermost[0], self.ocean_orderbook_innermost[1], 1) 120 | print('Max Amount for Scenario 1: {0}'.format(maxAmount)) 121 | fee = self.binance.feeRatio * maxAmount * binance_bestbid_price + self.theocean.feeRatio * maxAmount * ocean_bestask_price 122 | if abs(scenario1) * maxAmount - fee > self.minProfit: 123 | print("Binance's Bid Price: {0} is greater than TheOcean's Ask Price:{1}. Will Execute Scenario 1.".format(binance_bestbid_price, ocean_bestask_price)) 124 | return {'scenario': 1, 'ask': ocean_bestask_price, 'bid': binance_bestbid_price, 'amount': maxAmount} 125 | else: 126 | return {'scenario': 0} 127 | elif scenario2 > 0: 128 | maxAmount = self.get_max_amount(self.ocean_orderbook_innermost[0], self.binance_orderbook_innermost[1], 2) 129 | print('Max Amount for Scenario 2: {0}'.format(maxAmount)) 130 | fee = self.binance.feeRatio * maxAmount * binance_bestask_price + self.theocean.feeRatio * maxAmount * ocean_bestbid_price 131 | if abs(scenario2) * maxAmount - fee > self.minProfit: 132 | print("TheOcean's Bid Price: {0} is greater than Binance's Ask Price:{1}. Will Execute Scenario 2.".format(ocean_bestbid_price, binance_bestask_price)) 133 | return {'scenario': 2, 'ask': binance_bestask_price, 'bid': ocean_bestbid_price, 'amount': maxAmount} 134 | else: 135 | return {'scenario': 0} 136 | 137 | # Edge cases and alternate scenarios are a still work in progress. 138 | # Following are couple of scenarios that need to be implemented 139 | 140 | # Scenario 3: 141 | # If both scenario1 and scenario2 return positive, 142 | # unlikely scenario as it will require bestbid to be greater than 143 | # bestask on the ocean 144 | if scenario1 > 0 and scenario2 > 0: 145 | if abs(scenario1) > abs(scenario2): 146 | pass 147 | elif abs(scenario1) < abs(scenario2): 148 | pass 149 | # Scenario 4: 150 | # If both scenario1 and scenario2 return negative, 151 | # there are no arbitrage opportunities 152 | elif scenario1 < 0 and scenario2 < 0: 153 | if abs(scenario1) > abs(scenario2): 154 | pass 155 | elif abs(scenario1) < abs(scenario2): 156 | pass 157 | 158 | def get_max_amount(self, bidOrder, askOrder, scenario): 159 | amount = 0 160 | # Buy from the Ocean, Sell to Binance 161 | if scenario == 1: 162 | maxamtA = self.theocean.balancetokA / ((1 + self.theocean.feeRatio) * askOrder[0]) 163 | maxamtB = self.binance.balancetokB / ((1 + self.binance.feeRatio) * bidOrder[0]) 164 | amount = min(maxamtA, maxamtB, askOrder[1], bidOrder[1]) 165 | # Buy from Binance, Sell to the Ocean 166 | elif scenario == 2: 167 | maxamtA = self.binance.balancetokA / ((1 + self.binance.feeRatio) * askOrder[0]) 168 | maxamtB = self.theocean.balancetokB / ((1 + self.theocean.feeRatio) * bidOrder[0]) 169 | amount = min(maxamtA, maxamtB, askOrder[1], bidOrder[1]) 170 | return amount 171 | 172 | def place_order(self, scenario, ask, bid, amount): 173 | print(strftime('Placing orders. Date: %b %d %Y Time: %H:%M:%S')) 174 | if scenario == 1: 175 | print('Buying {0} amount of {1} at TheOcean for the price of {2} and Selling to Binance for the price of {3} \n \n'.format(amount, self.tokenA, self.ocean_orderbook_innermost[1][0], self.binance_orderbook_innermost[0][0])) 176 | self.theocean.place_order(self.tokenpair, 'buy', amount, ask) 177 | self.binance.place_order(self.tokenpair, 'sell', amount, bid) 178 | elif scenario == 2: 179 | print('Buying {0} amount of {1} at Binance for the price of {2} and Selling to TheOcean for the price of {3} \n \n'.format(amount, self.tokenA, self.binance_orderbook_innermost[1][0], self.ocean_orderbook_innermost[0][0])) 180 | self.binance.place_order(self.tokenpair, 'buy', amount, ask) 181 | self.theocean.place_order(self.tokenpair, 'sell', amount, bid) 182 | 183 | if __name__ == '__main__': 184 | engine = ExchangeArbitrage('ZRXETH', True) 185 | print(engine.start_arbitrage()) 186 | ``` 187 | -------------------------------------------------------------------------------- /exchangearbitragebot/exchanges/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ortap/ExchangeArbitrageBot/6b045b24f795bc6d9bc72aa57ee5281a0b8ddbd4/exchangearbitragebot/exchanges/__init__.py -------------------------------------------------------------------------------- /exchangearbitragebot/exchanges/binance.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | import hmac 4 | import hashlib 5 | import time 6 | import os 7 | try: 8 | from urllib import urlencode 9 | except ImportError: # for compatibility with py3 10 | from urllib.parse import urlencode 11 | 12 | 13 | class Exchange: 14 | 15 | def __init__(self): 16 | self.API_URL = 'https://www.binance.com/api/v1' 17 | self.API_URL_V3 = 'https://www.binance.com/api/v3' 18 | self.API_KEY = os.environ['BINANCE_API_KEY'] # 19 | self.API_SECRET = os.environ['BINANCE_API_SECRET'] # 20 | self.feeRatio = 0.001 21 | 22 | def unauthenticated_request(self, method, URL, body={}): 23 | query = urlencode(body) 24 | url = "%s?%s" % (URL, query) 25 | return requests.request(method, url, timeout=30, verify=True).json() 26 | 27 | def signOrder(self, body={}): 28 | data = body.copy() 29 | 30 | ts = str(int(1000 * time.time())) 31 | data.update({"timestamp": ts}) 32 | 33 | h = urlencode(data) 34 | b = bytearray() 35 | b.extend(self.API_SECRET.encode()) 36 | signature = hmac.new(b, msg=h.encode('utf-8'), 37 | digestmod=hashlib.sha256).hexdigest() 38 | data.update({"signature": signature}) 39 | return data 40 | 41 | def authenticated_request(self, method, URL, body={}): 42 | body.update({"recvWindow": 120000}) 43 | query = urlencode(self.signOrder(body)) 44 | url = URL + "?" + query 45 | header = {"X-MBX-APIKEY": self.API_KEY} 46 | return requests.request(method, url, headers=header, 47 | timeout=30, verify=True).json() 48 | 49 | def get_ticker_history(self, tokenpair): 50 | path = "%s/historicalTrades" % self.API_URL 51 | body = {"symbol": tokenpair, "limit": 50} 52 | return self.unauthenticated_request('GET', path, body) 53 | 54 | def get_trades(self, tokenpair): 55 | path = "%s/trades" % self.API_URL 56 | body = {"symbol": tokenpair, "limit": 50} 57 | return self.unauthenticated_request('GET', path, body) 58 | 59 | def get_candlesticks(self, tokenpair): 60 | path = "%s/klines" % self.API_URL 61 | body = {"symbol": tokenpair} 62 | return self.unauthenticated_request('GET', path, body) 63 | 64 | def get_ticker_lastPrice(self, tokenpair): 65 | path = "%s/ticker/allPrices" % self.API_URL 66 | body = {"symbol": tokenpair} 67 | return self.unauthenticated_request('GET', path, body) 68 | 69 | def get_ticker_order_book(self, tokenpair): 70 | path = "%s/depth" % self.API_URL 71 | body = {"symbol": tokenpair, "limit": 50} 72 | order_book = self.unauthenticated_request('GET', path, body) 73 | # order_book = json.loads(ob_request) 74 | return order_book 75 | 76 | def get_ticker_orderBook_innermost(self, tokenpair): 77 | orderBook = self.get_ticker_order_book(tokenpair) 78 | bestbid = [float(orderBook['bids'][0][0]), 79 | float(orderBook['bids'][0][1])] 80 | bestask = [float(orderBook['asks'][0][0]), 81 | float(orderBook['asks'][0][1])] 82 | return bestbid, bestask 83 | 84 | def get_user_history(self, tokenpair): 85 | path = "%s/allOrders" % self.API_URL_V3 86 | body = {"symbol": tokenpair} 87 | return self.authenticated_request('GET', path, body) 88 | 89 | def get_account(self): 90 | path = self.API_URL_V3 + "/account" 91 | return self.authenticated_request('GET', path, {}) 92 | 93 | def get_balance(self, tokensymbol): 94 | balances = self.get_account() 95 | balances['balances'] = {item['asset']: item for item in balances['balances']} 96 | return balances['balances'][tokensymbol]['free'] 97 | 98 | def place_order(self, tokenpair, side, amount, price=None): 99 | path = "%s/order" % self.API_URL_V3 100 | body = {} 101 | 102 | if price is not None: 103 | body["type"] = "LIMIT" 104 | price = "{:.8f}".format(price) 105 | body["price"] = price 106 | body["timeInForce"] = "GTC" 107 | else: 108 | body["type"] = "MARKET" 109 | 110 | body["tokenpair"] = tokenpair 111 | body["side"] = side 112 | body["amount"] = '%.8f' % amount 113 | return self.authenticated_request('POST', path, body) 114 | 115 | def cancel_order(self, tokenpair, orderId): 116 | path = "%s/order" % self.API_URL_V3 117 | body = {"symbol": tokenpair, "orderId": orderId} 118 | return self.authenticated_request('DELETE', path, body) 119 | 120 | def get_open_orders(self, tokenpair): 121 | path = "%s/openOrders" % self.API_URL_V3 122 | body = {'symbol': tokenpair} 123 | open_orders = self.authenticated_request('GET', path, body) 124 | openOrders = json.loads(open_orders.text) 125 | return openOrders 126 | 127 | def cancel_allOrders(self): 128 | tokenpairs = ['ZRXETH', 'REPETH', 'GNTETH'] 129 | openOrders = self.get_open_orders() 130 | for i in range(len(tokenpairs)): 131 | tokenpair = tokenpairs[i] 132 | for j in range(len(openOrders)): 133 | orderId = openOrders[j]['orderId'] 134 | cancelorder = self.cancel_order(tokenpair, orderId) 135 | return cancelorder 136 | return tokenpair 137 | print('All open orders successfully canceled for the defined tokenpairs') 138 | 139 | 140 | if __name__ == "__main__": 141 | binance = Exchange() 142 | print(binance.get_ticker_orderBook_innermost('ZRXETH')) 143 | ### 144 | -------------------------------------------------------------------------------- /exchangearbitragebot/exchanges/theocean.py: -------------------------------------------------------------------------------- 1 | from web3 import Web3, HTTPProvider 2 | import json 3 | import requests 4 | import hmac 5 | import hashlib 6 | import base64 7 | import time 8 | import os 9 | 10 | 11 | class TokenContracts: 12 | ZRX = '0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570' 13 | ETH = '0xd0a1e359811322d97991e03f863a0c30c2cf029c' 14 | GNT = '0xef7fff64389b814a946f3e92105513705ca6b990' 15 | MKR = '0x1dad4783cf3fe3085c1426157ab175a6119a04ba' 16 | REP = '0xb18845c260f680d5b9d84649638813e342e4f8c9' 17 | 18 | def ZRXETH(): 19 | baseTokenAddress = TokenContracts.ZRX 20 | quoteTokenAddress = TokenContracts.ETH 21 | return baseTokenAddress, quoteTokenAddress 22 | 23 | def GNTETH(): 24 | baseTokenAddress = TokenContracts.GNT 25 | quoteTokenAddress = TokenContracts.ETH 26 | return baseTokenAddress, quoteTokenAddress 27 | 28 | def REPETH(): 29 | baseTokenAddress = TokenContracts.REP 30 | quoteTokenAddress = TokenContracts.ETH 31 | return baseTokenAddress, quoteTokenAddress 32 | 33 | def MKRETH(): 34 | baseTokenAddress = TokenContracts.MKR 35 | quoteTokenAddress = TokenContracts.ETH 36 | return baseTokenAddress, quoteTokenAddress 37 | 38 | def GNTZRX(): 39 | baseTokenAddress = TokenContracts.GNT 40 | quoteTokenAddress = TokenContracts.ZRX 41 | return baseTokenAddress, quoteTokenAddress 42 | 43 | def MKRZRX(): 44 | baseTokenAddress = TokenContracts.MKR 45 | quoteTokenAddress = TokenContracts.ZRX 46 | return baseTokenAddress, quoteTokenAddress 47 | 48 | def REPZRX(): 49 | baseTokenAddress = TokenContracts.REP 50 | quoteTokenAddress = TokenContracts.ZRX 51 | return baseTokenAddress, quoteTokenAddress 52 | 53 | dictionary = { 54 | 'ZRXETH': ZRXETH, 55 | 'GNTETH': GNTETH, 56 | 'REPETH': REPETH, 57 | 'MKRETH': MKRETH, 58 | 'GNTZRX': GNTZRX, 59 | 'MKRZRX': MKRZRX, 60 | 'REPZRX': REPZRX 61 | } 62 | checksum_dict = { 63 | 'ZRX': Web3.toChecksumAddress(ZRX), 64 | 'ETH': Web3.toChecksumAddress(ETH), 65 | 'GNT': Web3.toChecksumAddress(GNT), 66 | 'MKR': Web3.toChecksumAddress(MKR), 67 | 'REP': Web3.toChecksumAddress(REP) 68 | } 69 | 70 | 71 | class Exchange: 72 | def __init__(self): 73 | self.API_URL = 'https://api.staging.theocean.trade/api/v0' # 'https://api.dev.theocean.trade/api/v0' # 74 | self.WEB3_URL = 'http://localhost:8545' 75 | self.API_KEY = os.environ['OCEAN_API_KEY'] # 76 | self.API_SECRET = os.environ['OCEAN_API_SECRET'] # 77 | self.ETHEREUM_ADDRESS = os.environ['ETHEREUM_ADDRESS'] # 78 | self.feeRatio = 0.001 79 | self.async = True 80 | self.web3 = Web3(HTTPProvider(self.WEB3_URL)) 81 | self.TokenContracts = TokenContracts 82 | 83 | # add send requests method that do not require authentication 84 | # def send_request(self, URL, method): 85 | 86 | def authenticated_request(self, URL, method, body): 87 | timestamp = str(int(round(time.time() * 1000))) 88 | prehash = self.API_KEY + timestamp + method + json.dumps( 89 | body, separators=(',', ':')) 90 | signature = base64.b64encode( 91 | hmac.new( 92 | self.API_SECRET.encode('utf-8'), 93 | msg=prehash.encode('utf-8'), 94 | digestmod=hashlib.sha256).digest()) 95 | headers = { 96 | 'TOX-ACCESS-KEY': self.API_KEY, 97 | 'TOX-ACCESS-SIGN': signature, 98 | 'TOX-ACCESS-TIMESTAMP': timestamp 99 | } 100 | request = requests.request(method, URL, headers=headers, json=body) 101 | 102 | return request 103 | 104 | def signOrder(self, order): 105 | signed_order = order 106 | signed_order['maker'] = self.ETHEREUM_ADDRESS 107 | values = [ 108 | Web3.toChecksumAddress(signed_order['exchangeContractAddress']), 109 | Web3.toChecksumAddress(signed_order['maker']), 110 | Web3.toChecksumAddress(signed_order['taker']), 111 | Web3.toChecksumAddress(signed_order['makerTokenAddress']), 112 | Web3.toChecksumAddress(signed_order['takerTokenAddress']), 113 | Web3.toChecksumAddress(signed_order['feeRecipient']), 114 | int(signed_order['makerTokenAmount']), 115 | int(signed_order['takerTokenAmount']), 116 | int(signed_order['makerFee']), 117 | int(signed_order['takerFee']), 118 | int(signed_order['expirationUnixTimestampSec']), 119 | int(signed_order['salt']) 120 | ] 121 | types = [ 122 | 'address', 'address', 'address', 'address', 'address', 'address', 123 | 'uint256', 'uint256', 'uint256', 'uint256', 'uint256', 'uint256' 124 | ] 125 | orderHash = Web3.soliditySha3(types, values).hex() 126 | # print(orderHash) 127 | signed_order['orderHash'] = orderHash 128 | sig = Web3.toChecksumAddress(self.ETHEREUM_ADDRESS.lower()) 129 | # print(sig) 130 | hex_signature = self.web3.eth.sign(sig, hexstr=orderHash).hex() 131 | # print(hex_signature) 132 | sig = Web3.toBytes(hexstr=hex_signature) 133 | v, r, s = Web3.toInt(sig[-1]), Web3.toHex(sig[:32]), Web3.toHex( 134 | sig[32:64]) 135 | ecSignature = {'v': v, 'r': r, 's': s} 136 | signed_order['ecSignature'] = ecSignature 137 | 138 | signed_order['exchangeContractAddress'] = signed_order[ 139 | 'exchangeContractAddress'].lower() 140 | signed_order['maker'] = signed_order['maker'].lower() 141 | signed_order['taker'] = signed_order['taker'].lower() 142 | signed_order['makerTokenAddress'] = signed_order[ 143 | 'makerTokenAddress'].lower() 144 | signed_order['takerTokenAddress'] = signed_order[ 145 | 'takerTokenAddress'].lower() 146 | signed_order['feeRecipient'] = signed_order['feeRecipient'].lower() 147 | 148 | return signed_order 149 | 150 | def new_market_order(self, baseTokenAddress, quoteTokenAddress, side, 151 | orderAmount, feeOption='feeInNative'): 152 | RESERVE_MARKET_ORDER = self.API_URL + '/market_order/reserve' 153 | PLACE_MARKET_ORDER = self.API_URL + '/market_order/place' 154 | USER_HISTORY = self.API_URL + '/user_history' 155 | 156 | reserve_body = { 157 | 'walletAddress': self.ETHEREUM_ADDRESS.lower(), 158 | 'baseTokenAddress': baseTokenAddress, 159 | 'quoteTokenAddress': quoteTokenAddress, 160 | 'side': side, 161 | 'orderAmount': orderAmount, 162 | 'feeOption': feeOption 163 | } 164 | # print(reserve_body) 165 | reserve_request = self.authenticated_request(RESERVE_MARKET_ORDER, 166 | 'POST', reserve_body) 167 | print(reserve_request.text) 168 | signed_order = self.signOrder( 169 | json.loads(reserve_request.text)['unsignedOrder']) 170 | market_order_ID = json.loads(reserve_request.text)['marketOrderID'] 171 | 172 | place_body = { 173 | 'marketOrderID': market_order_ID, 174 | 'signedOrder': signed_order 175 | } 176 | 177 | place_request = self.authenticated_request(PLACE_MARKET_ORDER, 'POST', 178 | place_body) 179 | print(place_request.text) 180 | 181 | history_request = self.authenticated_request(USER_HISTORY, 'GET', {}) 182 | # print(history_request.text) 183 | 184 | def place_order(self, tokenpair, side, amount, price=None): 185 | func = self.TokenContracts.dictionary.get(tokenpair) 186 | pairaddresses = func() 187 | baseTokenAddress = pairaddresses[0] 188 | quoteTokenAddress = pairaddresses[1] 189 | if price is not None: 190 | return self.new_limit_order(baseTokenAddress, quoteTokenAddress, side, 191 | amount, price) 192 | elif price is None: 193 | return self.new_market_order(baseTokenAddress, quoteTokenAddress, side, 194 | amount) 195 | else: 196 | print('Invalid type') 197 | 198 | def get_user_history(self): 199 | USER_HISTORY = self.API_URL + '/user_history' 200 | history_request = self.authenticated_request(USER_HISTORY, 'GET', {}) 201 | history = json.loads(history_request.text) 202 | return history 203 | 204 | def cancel_order(self, orderHash): 205 | CANCEL_ORDER = self.API_URL + '/order/' + orderHash 206 | delete_request = self.authenticated_request(CANCEL_ORDER, 'DELETE', {}) 207 | # print(delete_request.text) 208 | print('Order successfully canceled') 209 | 210 | def cancel_allOrders(self): 211 | history = self.get_user_history() 212 | for i in range(len(history)): 213 | if int(history[i]['openAmount']) != 0: 214 | orderHash = history[i]['orderHash'] 215 | self.cancel_order(orderHash) 216 | i += 1 217 | else: 218 | i += 1 219 | print('All open orders successfully canceled') 220 | 221 | def get_balance(self, tokensymbol): 222 | token_t_abi = json.loads( 223 | '[{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]' 224 | ) 225 | address_tokensymbol = TokenContracts.checksum_dict.get(tokensymbol) 226 | token = self.web3.eth.contract( 227 | address_tokensymbol, 228 | abi=token_t_abi, 229 | ) 230 | balance = token.call().balanceOf(self.ETHEREUM_ADDRESS)/10**18 231 | return balance 232 | 233 | def get_ticker_history(self, tokenpair): 234 | pass 235 | 236 | def get_ticker_lastPrice(self, tokenpair): 237 | func = TokenContracts.dictionary.get(tokenpair) 238 | pairaddresses = func() 239 | TICKER = self.API_URL + '/ticker' 240 | 241 | ticker_request = requests.get( 242 | TICKER, 243 | params={ 244 | 'baseTokenAddress': pairaddresses[0], 245 | 'quoteTokenAddress': pairaddresses[1] 246 | }) 247 | last_price = json.loads(ticker_request.text)['last'] 248 | return last_price 249 | 250 | def get_ticker_orderBook(self, tokenpair): 251 | func = TokenContracts.dictionary.get(tokenpair) 252 | pairaddresses = func() 253 | ORDERBOOK = self.API_URL + '/order_book' 254 | ob_request = requests.get( 255 | ORDERBOOK, 256 | params={ 257 | 'baseTokenAddress': pairaddresses[0], 258 | 'quoteTokenAddress': pairaddresses[1] 259 | }) 260 | order_book = json.loads(ob_request.text) 261 | return order_book 262 | 263 | def get_ticker_orderBook_innermost(self, tokenpair): 264 | orderBook = self.get_ticker_orderBook(tokenpair) 265 | bestbid = [float(orderBook['bids'][0]['price']), 266 | float(orderBook['bids'][0]['availableAmount'])/float(10**18)] 267 | bestask = [float(orderBook['asks'][0]['price']), 268 | float(orderBook['asks'][0]['availableAmount'])/float(10**18)] 269 | return bestbid, bestask 270 | 271 | 272 | if __name__ == "__main__": 273 | ocean = Exchange() 274 | print(ocean.get_user_history()) 275 | print(ocean.get_ticker_orderBook_innermost('ZRXETH')) 276 | ### 277 | -------------------------------------------------------------------------------- /exchangearbitragebot/exchanges/theocean_README.md: -------------------------------------------------------------------------------- 1 | # Explanation of Important Methods and Definitions in theocean.py 2 | 3 | This module contains two classes: `TokenContracts` and `Exchange`. 4 | 5 | ## TokenContracts class 6 | 7 | Contains a dictionary of tokens, token pairs and their contract addresses for use by methods within the `Exchange` class. 8 | 9 | ## Exchange class 10 | 11 | Contains methods and definitions for The Ocean exchange that are required for the exchange arbitrage bot. 12 | 13 | ### ____init____ method 14 | 15 | - `API_URL` may change overtime and should be altered accordingly. 16 | - User's `API_KEY`, `API_SECRET` and `ETHEREUM_ADDRESSES` should be stored as environment variables. User may also input these variables directly (less secure). 17 | - `feeRatio` is defined here as 0.1% for both makers and takers. This may be altered based on user preference to include Ocean tokens, discounts and user defined tolerances. 18 | - a http based `web3` provider (such as parity) is required for getting wallet balances and for signing requests. An alternative signer method/function may be implemented to bypass requirement of a web3 provider. 19 | 20 | ### Snippet of theocean.py 21 | ```python 22 | from web3 import Web3, HTTPProvider 23 | import json 24 | import requests 25 | import hmac 26 | import hashlib 27 | import base64 28 | import time 29 | import os 30 | 31 | 32 | class TokenContracts: 33 | ZRX = '0x6ff6c0ff1d68b964901f986d4c9fa3ac68346570' 34 | ETH = '0xd0a1e359811322d97991e03f863a0c30c2cf029c' 35 | GNT = '0xef7fff64389b814a946f3e92105513705ca6b990' 36 | MKR = '0x1dad4783cf3fe3085c1426157ab175a6119a04ba' 37 | REP = '0xb18845c260f680d5b9d84649638813e342e4f8c9' 38 | 39 | def ZRXETH(): 40 | baseTokenAddress = TokenContracts.ZRX 41 | quoteTokenAddress = TokenContracts.ETH 42 | return baseTokenAddress, quoteTokenAddress 43 | 44 | def GNTETH(): 45 | baseTokenAddress = TokenContracts.GNT 46 | quoteTokenAddress = TokenContracts.ETH 47 | return baseTokenAddress, quoteTokenAddress 48 | 49 | def REPETH(): 50 | baseTokenAddress = TokenContracts.REP 51 | quoteTokenAddress = TokenContracts.ETH 52 | return baseTokenAddress, quoteTokenAddress 53 | 54 | def MKRETH(): 55 | baseTokenAddress = TokenContracts.MKR 56 | quoteTokenAddress = TokenContracts.ETH 57 | return baseTokenAddress, quoteTokenAddress 58 | 59 | def GNTZRX(): 60 | baseTokenAddress = TokenContracts.GNT 61 | quoteTokenAddress = TokenContracts.ZRX 62 | return baseTokenAddress, quoteTokenAddress 63 | 64 | def MKRZRX(): 65 | baseTokenAddress = TokenContracts.MKR 66 | quoteTokenAddress = TokenContracts.ZRX 67 | return baseTokenAddress, quoteTokenAddress 68 | 69 | def REPZRX(): 70 | baseTokenAddress = TokenContracts.REP 71 | quoteTokenAddress = TokenContracts.ZRX 72 | return baseTokenAddress, quoteTokenAddress 73 | 74 | dictionary = { 75 | 'ZRXETH': ZRXETH, 76 | 'GNTETH': GNTETH, 77 | 'REPETH': REPETH, 78 | 'MKRETH': MKRETH, 79 | 'GNTZRX': GNTZRX, 80 | 'MKRZRX': MKRZRX, 81 | 'REPZRX': REPZRX 82 | } 83 | checksum_dict = { 84 | 'ZRX': Web3.toChecksumAddress(ZRX), 85 | 'ETH': Web3.toChecksumAddress(ETH), 86 | 'GNT': Web3.toChecksumAddress(GNT), 87 | 'MKR': Web3.toChecksumAddress(MKR), 88 | 'REP': Web3.toChecksumAddress(REP) 89 | } 90 | 91 | 92 | class Exchange: 93 | def __init__(self): 94 | self.API_URL = 'https://api.staging.theocean.trade/api/v0' # 'https://api.dev.theocean.trade/api/v0' # 95 | self.WEB3_URL = 'http://localhost:8545' 96 | self.API_KEY = os.environ['OCEAN_API_KEY'] # 97 | self.API_SECRET = os.environ['OCEAN_API_SECRET'] # 98 | self.ETHEREUM_ADDRESS = os.environ['ETHEREUM_ADDRESS'] # 99 | self.feeRatio = 0.001 100 | self.async = True 101 | self.web3 = Web3(HTTPProvider(self.WEB3_URL)) 102 | self.TokenContracts = TokenContracts 103 | 104 | # add send requests method that do not require authentication 105 | # def send_request(self, URL, method): 106 | 107 | def authenticated_request(self, URL, method, body): 108 | timestamp = str(int(round(time.time() * 1000))) 109 | prehash = self.API_KEY + timestamp + method + json.dumps( 110 | body, separators=(',', ':')) 111 | signature = base64.b64encode( 112 | hmac.new( 113 | self.API_SECRET.encode('utf-8'), 114 | msg=prehash.encode('utf-8'), 115 | digestmod=hashlib.sha256).digest()) 116 | headers = { 117 | 'TOX-ACCESS-KEY': self.API_KEY, 118 | 'TOX-ACCESS-SIGN': signature, 119 | 'TOX-ACCESS-TIMESTAMP': timestamp 120 | } 121 | request = requests.request(method, URL, headers=headers, json=body) 122 | 123 | return request 124 | 125 | def signOrder(self, order): 126 | signed_order = order 127 | signed_order['maker'] = self.ETHEREUM_ADDRESS 128 | values = [ 129 | Web3.toChecksumAddress(signed_order['exchangeContractAddress']), 130 | Web3.toChecksumAddress(signed_order['maker']), 131 | Web3.toChecksumAddress(signed_order['taker']), 132 | Web3.toChecksumAddress(signed_order['makerTokenAddress']), 133 | Web3.toChecksumAddress(signed_order['takerTokenAddress']), 134 | Web3.toChecksumAddress(signed_order['feeRecipient']), 135 | int(signed_order['makerTokenAmount']), 136 | int(signed_order['takerTokenAmount']), 137 | int(signed_order['makerFee']), 138 | int(signed_order['takerFee']), 139 | int(signed_order['expirationUnixTimestampSec']), 140 | int(signed_order['salt']) 141 | ] 142 | types = [ 143 | 'address', 'address', 'address', 'address', 'address', 'address', 144 | 'uint256', 'uint256', 'uint256', 'uint256', 'uint256', 'uint256' 145 | ] 146 | orderHash = Web3.soliditySha3(types, values).hex() 147 | # print(orderHash) 148 | signed_order['orderHash'] = orderHash 149 | sig = Web3.toChecksumAddress(self.ETHEREUM_ADDRESS.lower()) 150 | # print(sig) 151 | hex_signature = self.web3.eth.sign(sig, hexstr=orderHash).hex() 152 | # print(hex_signature) 153 | sig = Web3.toBytes(hexstr=hex_signature) 154 | v, r, s = Web3.toInt(sig[-1]), Web3.toHex(sig[:32]), Web3.toHex( 155 | sig[32:64]) 156 | ecSignature = {'v': v, 'r': r, 's': s} 157 | signed_order['ecSignature'] = ecSignature 158 | 159 | signed_order['exchangeContractAddress'] = signed_order[ 160 | 'exchangeContractAddress'].lower() 161 | signed_order['maker'] = signed_order['maker'].lower() 162 | signed_order['taker'] = signed_order['taker'].lower() 163 | signed_order['makerTokenAddress'] = signed_order[ 164 | 'makerTokenAddress'].lower() 165 | signed_order['takerTokenAddress'] = signed_order[ 166 | 'takerTokenAddress'].lower() 167 | signed_order['feeRecipient'] = signed_order['feeRecipient'].lower() 168 | 169 | return signed_order 170 | 171 | def new_market_order(self, baseTokenAddress, quoteTokenAddress, side, 172 | orderAmount, feeOption='feeInNative'): 173 | RESERVE_MARKET_ORDER = self.API_URL + '/market_order/reserve' 174 | PLACE_MARKET_ORDER = self.API_URL + '/market_order/place' 175 | USER_HISTORY = self.API_URL + '/user_history' 176 | 177 | reserve_body = { 178 | 'walletAddress': self.ETHEREUM_ADDRESS.lower(), 179 | 'baseTokenAddress': baseTokenAddress, 180 | 'quoteTokenAddress': quoteTokenAddress, 181 | 'side': side, 182 | 'orderAmount': orderAmount, 183 | 'feeOption': feeOption 184 | } 185 | # print(reserve_body) 186 | reserve_request = self.authenticated_request(RESERVE_MARKET_ORDER, 187 | 'POST', reserve_body) 188 | print(reserve_request.text) 189 | signed_order = self.signOrder( 190 | json.loads(reserve_request.text)['unsignedOrder']) 191 | market_order_ID = json.loads(reserve_request.text)['marketOrderID'] 192 | 193 | place_body = { 194 | 'marketOrderID': market_order_ID, 195 | 'signedOrder': signed_order 196 | } 197 | 198 | place_request = self.authenticated_request(PLACE_MARKET_ORDER, 'POST', 199 | place_body) 200 | print(place_request.text) 201 | 202 | history_request = self.authenticated_request(USER_HISTORY, 'GET', {}) 203 | # print(history_request.text) 204 | 205 | def place_order(self, tokenpair, side, amount, price=None): 206 | func = self.TokenContracts.dictionary.get(tokenpair) 207 | pairaddresses = func() 208 | baseTokenAddress = pairaddresses[0] 209 | quoteTokenAddress = pairaddresses[1] 210 | if price is not None: 211 | return self.new_limit_order(baseTokenAddress, quoteTokenAddress, side, 212 | amount, price) 213 | elif price is None: 214 | return self.new_market_order(baseTokenAddress, quoteTokenAddress, side, 215 | amount) 216 | else: 217 | print('Invalid type') 218 | 219 | def get_user_history(self): 220 | USER_HISTORY = self.API_URL + '/user_history' 221 | history_request = self.authenticated_request(USER_HISTORY, 'GET', {}) 222 | history = json.loads(history_request.text) 223 | return history 224 | 225 | def cancel_order(self, orderHash): 226 | CANCEL_ORDER = self.API_URL + '/order/' + orderHash 227 | delete_request = self.authenticated_request(CANCEL_ORDER, 'DELETE', {}) 228 | # print(delete_request.text) 229 | print('Order successfully canceled') 230 | 231 | def cancel_allOrders(self): 232 | history = self.get_user_history() 233 | for i in range(len(history)): 234 | if int(history[i]['openAmount']) != 0: 235 | orderHash = history[i]['orderHash'] 236 | self.cancel_order(orderHash) 237 | i += 1 238 | else: 239 | i += 1 240 | print('All open orders successfully canceled') 241 | 242 | def get_balance(self, tokensymbol): 243 | token_t_abi = json.loads( 244 | '[{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]' 245 | ) 246 | address_tokensymbol = TokenContracts.checksum_dict.get(tokensymbol) 247 | token = self.web3.eth.contract( 248 | address_tokensymbol, 249 | abi=token_t_abi, 250 | ) 251 | balance = token.call().balanceOf(self.ETHEREUM_ADDRESS)/10**18 252 | return balance 253 | 254 | def get_ticker_history(self, tokenpair): 255 | pass 256 | 257 | def get_ticker_lastPrice(self, tokenpair): 258 | func = TokenContracts.dictionary.get(tokenpair) 259 | pairaddresses = func() 260 | TICKER = self.API_URL + '/ticker' 261 | 262 | ticker_request = requests.get( 263 | TICKER, 264 | params={ 265 | 'baseTokenAddress': pairaddresses[0], 266 | 'quoteTokenAddress': pairaddresses[1] 267 | }) 268 | last_price = json.loads(ticker_request.text)['last'] 269 | return last_price 270 | 271 | def get_ticker_orderBook(self, tokenpair): 272 | func = TokenContracts.dictionary.get(tokenpair) 273 | pairaddresses = func() 274 | ORDERBOOK = self.API_URL + '/order_book' 275 | ob_request = requests.get( 276 | ORDERBOOK, 277 | params={ 278 | 'baseTokenAddress': pairaddresses[0], 279 | 'quoteTokenAddress': pairaddresses[1] 280 | }) 281 | order_book = json.loads(ob_request.text) 282 | return order_book 283 | 284 | def get_ticker_orderBook_innermost(self, tokenpair): 285 | orderBook = self.get_ticker_orderBook(tokenpair) 286 | bestbid = [float(orderBook['bids'][0]['price']), 287 | float(orderBook['bids'][0]['availableAmount'])/float(10**18)] 288 | bestask = [float(orderBook['asks'][0]['price']), 289 | float(orderBook['asks'][0]['availableAmount'])/float(10**18)] 290 | return bestbid, bestask 291 | 292 | 293 | if __name__ == "__main__": 294 | ocean = Exchange() 295 | print(ocean.get_user_history()) 296 | print(ocean.get_ticker_orderBook_innermost('ZRXETH')) 297 | ### 298 | 299 | ``` -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from setuptools import setup 3 | 4 | setup(name='theocean_python', 5 | version='0.0.1', 6 | description='', 7 | classifiers=[ 8 | 'Programming Language :: Python :: 3.6', 9 | ], 10 | url='https://gitlab.the0cean.net/shailesh/ExchangeArbitrageBot', 11 | author='Shailesh', 12 | author_email='shailesh@theocean.trade', 13 | license='MPL-2.0', 14 | packages=['exchangearbitragebot'], 15 | install_requires=[ 16 | 'web3', 17 | 'requests', 18 | 'urllib3' 19 | ], 20 | zip_safe=False) 21 | --------------------------------------------------------------------------------