├── src └── main │ ├── resources │ ├── application.properties │ ├── logback.xml │ └── log4j.properties │ └── java │ └── com │ └── easypump │ ├── exceptions │ ├── DustTradeException.java │ ├── InvalidCreditionals.java │ └── InsufficientFundsException.java │ ├── config │ └── AppConfig.java │ ├── main │ └── Main.java │ ├── engine │ └── PumpEngine.java │ └── exchange │ └── bittrex │ └── BittrexApi.java ├── .gitignore ├── README.md ├── pom.xml └── LICENSE /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/java/com/easypump/exceptions/DustTradeException.java: -------------------------------------------------------------------------------- 1 | package com.easypump.exceptions; 2 | 3 | public class DustTradeException extends Exception { 4 | 5 | /** 6 | * 7 | */ 8 | private static final long serialVersionUID = 696082365529925269L; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/easypump/exceptions/InvalidCreditionals.java: -------------------------------------------------------------------------------- 1 | package com.easypump.exceptions; 2 | 3 | public class InvalidCreditionals extends Exception { 4 | 5 | /** 6 | * 7 | */ 8 | private static final long serialVersionUID = -2314745752050828670L; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/easypump/exceptions/InsufficientFundsException.java: -------------------------------------------------------------------------------- 1 | package com.easypump.exceptions; 2 | 3 | public class InsufficientFundsException extends Exception { 4 | 5 | /** 6 | * 7 | */ 8 | private static final long serialVersionUID = -8843422480818474910L; 9 | 10 | 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/easypump/config/AppConfig.java: -------------------------------------------------------------------------------- 1 | package com.easypump.config; 2 | 3 | import org.springframework.context.annotation.ComponentScan; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | @Configuration 7 | @ComponentScan(basePackages = "com.easypump") 8 | public class AppConfig { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # it's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.jar 19 | *.rar 20 | *.tar 21 | *.zip 22 | 23 | # Logs and databases # 24 | ###################### 25 | *.log 26 | *.sql 27 | *.sqlite 28 | 29 | # OS generated files # 30 | ###################### 31 | .DS_Store 32 | .DS_Store? 33 | ._* 34 | .Spotlight-V100 35 | .Trashes 36 | ehthumbs.db 37 | Thumbs.db 38 | 39 | # IDE files # 40 | ############# 41 | nbproject 42 | .~lock.* 43 | .buildpath 44 | .idea 45 | .project 46 | .settings 47 | composer.lock 48 | target 49 | .classpath 50 | dependency-reduced-pom.xml 51 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | # Root logger option 2 | log4j.rootLogger=INFO, stdout 3 | 4 | # Redirect log messages to console 5 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 6 | log4j.appender.stdout.Target=System.out 7 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 8 | log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 9 | log4j.appender.stdout.encoding=UTF-8 10 | 11 | # Redirect log messages to a log file, support file rolling. 12 | log4j.appender.file=org.apache.log4j.RollingFileAppender 13 | log4j.appender.file.File=C:\\log4j-application.log 14 | log4j.appender.file.MaxFileSize=5MB 15 | log4j.appender.file.MaxBackupIndex=10 16 | log4j.appender.file.layout=org.apache.log4j.PatternLayout 17 | log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 18 | log4j.appender.file.encoding=UTF-8 -------------------------------------------------------------------------------- /src/main/java/com/easypump/main/Main.java: -------------------------------------------------------------------------------- 1 | package com.easypump.main; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.context.annotation.AnnotationConfigApplicationContext; 6 | import org.springframework.context.support.AbstractApplicationContext; 7 | 8 | import com.easypump.config.AppConfig; 9 | import com.easypump.engine.PumpEngine; 10 | 11 | public class Main { 12 | 13 | final static Logger logger = LoggerFactory.getLogger(Main.class); 14 | 15 | public static void main (String [] args) 16 | { 17 | @SuppressWarnings({ "resource"}) 18 | AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); 19 | 20 | PumpEngine engine = (PumpEngine)context.getBean(PumpEngine.class); 21 | engine.setArgs(args); 22 | try { 23 | engine.startPump(); 24 | } catch (Exception e) { 25 | logger.error("Exception Occured while doing buy/sell transaction", e); 26 | } 27 | 28 | System.out.println("\n\n\nHope you will make a profit in this pump ;)"); 29 | System.out.println("if you could make a proit using this app please conside doing some donation with 1$ or 2$ to BTC address 1PfnwEdmU3Ki9htakiv4tciPXzo49RRkai \nit will help us doing more features in the future"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Easy Pump 2 | 3 | This app is used to speed up the buy/sell actions of crypto currencies during the pump period 4 | 5 | usually the pump period is not more than one minute so buy and sell actions should be placed very fast in order to be able to make a profit 6 | 7 | that is why I've created this app in order to make the buy and sell actions done in less than 5 seconds. (it depends in your network traffic) 8 | 9 | ## Limitation 10 | - Currently this app supports bittrex exchange only, in future versions it will supprot other exchanges 11 | - This app requires API Key and Secret, you may get them from the Exchange 12 | - This app doesn't have GUI interface, instead it runs from command line 13 | 14 | ## How to compile ? 15 | - Computer should have JAVA version 1.8 or latest version, you may download and install it from https://java.com/en/download/ 16 | - download the latest execuatable Jar file from release page https://github.com/rgf2004/easypump/releases or compile it yourself using mvn install command 17 | 18 | ## How to run ? 19 | 20 | 1- this app takes the following parameters: 21 | - exchange api key. 22 | - exhcange secret key. 23 | - amount of BTC that will be used 24 | - profit percentage 25 | 26 | ``` 27 | example : java -jar easy-pump-0.0.1-SNAPSHOT.jar fba4d194540e4b998f570cdwef0cdwecew3o b090f44028f54wrgregee12922cc04d 0.5 20 28 | ``` 29 | 30 | in this example you ask the app to use creditainls passed as api key and secret to buy a specific coin, app will ask about it later, with BTC amount 0.5 and to make the sell price = buy price + 20% as profit 31 | 32 | 2- when app loads in memory it will prompt the user to enter the desired coin 33 | coin should be passed as it is in exchange with "btc" keyword 34 | 35 | for example: 36 | eth for Ethereum 37 | dash for Dash 38 | xvg for Verge 39 | 40 | you can get coin name from the exchange 41 | 42 | 43 | 3- once the user enters the coin name the app will do the following: 44 | - it tries to get the current ASK price from the exchange 45 | - it calcuated the quantity that can be bought using the available BTC amount passed to this app. 46 | - it places the buy order for this coin 47 | - it monitors the exchange till this order is completed 48 | - once order is completed it will calculate the sell price based on the profit percentage passed to it. 49 | - it places the sell order for this coin using the propsed sell price and same quantity has been bought in the earlier buy order. 50 | 51 | 52 | 53 | ## Contribution 54 | 55 | We are glad about every contribution to the project. Dont hesitate to open an issue, if you found a bug (with or without fix) or have an idea for a new feature! 56 | 57 | If you want to share your own code, please follow these steps: 58 | - create a fork of this repository 59 | - add a new branch for your changings 60 | - add your changes to the code 61 | - dont forget to mention the issue number in the commit messages (just write something like ``` #```) 62 | - open a pull request and try to describe what the change is for 63 | - done :) 64 | 65 | ## Donations :moneybag: 66 | 67 | If you want you can donate to: 68 | 69 | ``` 70 | - [ Bitcoin ] 1PfnwEdmU3Ki9htakiv4tciPXzo49RRkai 71 | ``` 72 | -------------------------------------------------------------------------------- /src/main/java/com/easypump/engine/PumpEngine.java: -------------------------------------------------------------------------------- 1 | package com.easypump.engine; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.RoundingMode; 5 | import java.util.Arrays; 6 | import java.util.Scanner; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.stereotype.Service; 12 | 13 | import com.easypump.exchange.bittrex.BittrexApi; 14 | 15 | @Service 16 | public class PumpEngine { 17 | 18 | final static Logger logger = LoggerFactory.getLogger(PumpEngine.class); 19 | 20 | private BigDecimal safeFactor = BigDecimal.valueOf(1.01); 21 | 22 | @Autowired 23 | private BittrexApi bittrexApi; 24 | 25 | private String[] args; 26 | 27 | private String apiKey; 28 | private String apiSecret; 29 | private String coinName; 30 | 31 | private BigDecimal btcValue; 32 | private BigDecimal profitPercentage; 33 | 34 | private BigDecimal buyFacotr; 35 | 36 | public void setArgs(String[] args) { 37 | this.args = args; 38 | } 39 | 40 | public void startPump() throws Exception { 41 | 42 | String msg; 43 | logger.info("Passed Parameters [{}]", Arrays.toString(args)); 44 | 45 | validateAndParseArgs(); 46 | 47 | logger.info("Waiting for Coin Name [example : eth]"); 48 | Scanner sc = new Scanner(System.in); 49 | coinName = sc.next(); 50 | sc.close(); 51 | 52 | msg = String.format("Coin Name : BTC-%s, BTC Amount %.8f, Profit Percentage %f", coinName.toUpperCase(), 53 | btcValue, profitPercentage); 54 | logger.info(msg); 55 | 56 | logger.info("################################### Start Pump Engine ###################################"); 57 | BigDecimal currentBid = bittrexApi.getCoinLimit(coinName); 58 | BigDecimal proposedBid = currentBid.multiply(buyFacotr); 59 | BigDecimal quantity = btcValue.divide(proposedBid.multiply(safeFactor), RoundingMode.DOWN); 60 | BigDecimal proposedAsk = currentBid 61 | .multiply(profitPercentage.add(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(100))); 62 | 63 | msg = String.format("Current Bid %.8f, Proposed Quantity %.8f, Proposed Ask %.8f", proposedBid, quantity, 64 | proposedAsk); 65 | logger.info(msg); 66 | 67 | String buyOrderId = bittrexApi.placeBuyOrder(apiKey, apiSecret, coinName, quantity, proposedBid); 68 | logger.info("Buy Order UUID {}", buyOrderId); 69 | 70 | bittrexApi.waitOpenOrderToClose(apiKey, apiSecret, buyOrderId); 71 | logger.info("Buy Order UUID {} closed, Engine will place sell order id", buyOrderId); 72 | 73 | String sellOrderId = bittrexApi.placeSellOrder(apiKey, apiSecret, coinName, quantity, proposedAsk); 74 | 75 | logger.info("Sell Order UUID {}", sellOrderId); 76 | logger.info("################################### Sell Order Placed ###################################"); 77 | 78 | } 79 | 80 | public void validateAndParseArgs() throws Exception { 81 | if (this.args.length < 4) { 82 | logger.info( 83 | "Invalid Parameters : [API Key] [API Secret] [BTC Amount] [Profit Percentage]"); 84 | logger.info("Example : 2f32827101 1ce239fod 0.02 40 eth 1.1"); 85 | throw new Exception("Invalid arguments..."); 86 | } 87 | 88 | apiKey = this.args[0]; 89 | apiSecret = this.args[1]; 90 | 91 | btcValue = BigDecimal.valueOf(Double.parseDouble(this.args[2])); 92 | profitPercentage = BigDecimal.valueOf(Double.parseDouble(this.args[3])); 93 | 94 | if (this.args.length >= 5) 95 | buyFacotr = BigDecimal.valueOf(Double.parseDouble(this.args[4])); 96 | else 97 | buyFacotr = BigDecimal.valueOf(1.0); 98 | 99 | } 100 | 101 | } 102 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.easypump 5 | easy-pump 6 | 0.0.1-SNAPSHOT 7 | Easy Pump Engine 8 | Easy Pump Engine 9 | 10 | 11 | 1.8 12 | 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.3.RELEASE 18 | 19 | 20 | 21 | 22 | 23 | org.slf4j 24 | slf4j-api 25 | 26 | 27 | org.slf4j 28 | log4j-over-slf4j 29 | 30 | 31 | org.slf4j 32 | jcl-over-slf4j 33 | 34 | 35 | org.slf4j 36 | jul-to-slf4j 37 | 38 | 39 | ch.qos.logback 40 | logback-classic 41 | 42 | 43 | 44 | org.apache.commons 45 | commons-dbcp2 46 | 47 | 48 | org.apache.commons 49 | commons-lang3 50 | 3.0 51 | 52 | 53 | 54 | 55 | commons-logging 56 | commons-logging 57 | 1.1.3 58 | 59 | 60 | 61 | org.springframework 62 | spring-context 63 | 64 | 65 | org.springframework 66 | spring-context-support 67 | 68 | 69 | org.springframework 70 | spring-core 71 | 72 | 73 | org.springframework 74 | spring-jdbc 75 | 76 | 77 | org.springframework 78 | spring-beans 79 | 80 | 81 | org.springframework 82 | spring-orm 83 | 84 | 85 | org.springframework 86 | spring-instrument 87 | 88 | 89 | org.springframework 90 | spring-web 91 | 92 | 93 | org.springframework 94 | spring-test 95 | 96 | 97 | org.springframework 98 | spring-aop 99 | 100 | 101 | 102 | com.fasterxml.jackson.core 103 | jackson-core 104 | 105 | 106 | com.fasterxml.jackson.core 107 | jackson-annotations 108 | 109 | 110 | com.fasterxml.jackson.core 111 | jackson-databind 112 | 113 | 114 | 115 | com.google.code.gson 116 | gson 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | org.springframework.boot 125 | spring-boot-maven-plugin 126 | 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/main/java/com/easypump/exchange/bittrex/BittrexApi.java: -------------------------------------------------------------------------------- 1 | package com.easypump.exchange.bittrex; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.ArrayList; 5 | import java.util.Date; 6 | import java.util.List; 7 | 8 | import javax.crypto.Mac; 9 | import javax.crypto.spec.SecretKeySpec; 10 | 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.http.HttpEntity; 14 | import org.springframework.http.HttpHeaders; 15 | import org.springframework.stereotype.Service; 16 | import org.springframework.web.client.RestTemplate; 17 | 18 | import com.easypump.exceptions.DustTradeException; 19 | import com.easypump.exceptions.InsufficientFundsException; 20 | import com.easypump.exceptions.InvalidCreditionals; 21 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 22 | import com.google.gson.Gson; 23 | import com.google.gson.GsonBuilder; 24 | 25 | @Service 26 | public class BittrexApi { 27 | 28 | final static Logger logger = LoggerFactory.getLogger(BittrexApi.class); 29 | 30 | private final static String BITTREX_URL = "https://bittrex.com/api/v1.1/"; 31 | 32 | private final long CHECK_SLEEP_INTERVAL_MILLISECOND = 100; 33 | 34 | RestTemplate restTemplate = new RestTemplate(); 35 | Gson gson = new GsonBuilder().create(); 36 | 37 | 38 | public BigDecimal getCoinLimit(String coinName) throws Exception { 39 | 40 | String marketName = "btc-" + coinName.toLowerCase(); 41 | 42 | StringBuilder url = new StringBuilder(BITTREX_URL + "public/getticker?market=").append(marketName); 43 | 44 | String response = restTemplate.postForObject(url.toString(), null, String.class); 45 | 46 | MarketSummaryResponse marketResponse = gson.fromJson(response, MarketSummaryResponse.class); 47 | 48 | if (!marketResponse.isSuccess()) 49 | throw new Exception("Error While Getting Orders - " + marketResponse.getMessage()); 50 | 51 | return BigDecimal.valueOf(marketResponse.getResult().get(0).getBid()); 52 | 53 | } 54 | 55 | public String placeBuyOrder(String apiKey, String apiSecret, String coinName, BigDecimal quantity, BigDecimal rate) 56 | throws Exception { 57 | 58 | long nonce = new Date().getTime(); 59 | 60 | String marketName = "btc-" + coinName.toLowerCase(); 61 | 62 | StringBuilder url = new StringBuilder(BITTREX_URL + "market/buylimit?apikey=").append(apiKey).append("&market=") 63 | .append(marketName).append("&quantity=").append(quantity.doubleValue()).append("&rate=") 64 | .append(rate.doubleValue()).append("&nonce=").append(nonce); 65 | 66 | HttpHeaders headers = new HttpHeaders(); 67 | 68 | try { 69 | headers.add("apisign", encode(apiSecret, url.toString())); 70 | } catch (Exception e) { 71 | logger.error("Error while setting header ", e); 72 | } 73 | 74 | HttpEntity request = new HttpEntity(headers); 75 | 76 | String response = restTemplate.postForObject(url.toString(), request, String.class); 77 | 78 | OrderResponse orderResponse = gson.fromJson(response, OrderResponse.class); 79 | 80 | if (!orderResponse.isSuccess()) { 81 | if ("INSUFFICIENT_FUNDS".equals(orderResponse.getMessage())) { 82 | throw new InsufficientFundsException(); 83 | } else if ("DUST_TRADE_DISALLOWED_MIN_VALUE_50K_SAT".equals(orderResponse.getMessage())) { 84 | throw new DustTradeException(); 85 | } else if ("APIKEY_INVALID".equals(orderResponse.getMessage())) 86 | { 87 | throw new InvalidCreditionals(); 88 | } 89 | else { 90 | logger.error("Error Occured with response {}", response); 91 | throw new Exception(); 92 | } 93 | } 94 | 95 | return orderResponse.getResult().getUuid(); 96 | } 97 | 98 | public String placeSellOrder(String apiKey, String apiSecret, String coinName, BigDecimal quantity, BigDecimal rate) 99 | throws Exception { 100 | 101 | long nonce = new Date().getTime(); 102 | 103 | String marketName = "btc-" + coinName.toLowerCase(); 104 | 105 | StringBuilder url = new StringBuilder(BITTREX_URL + "market/selllimit?apikey=").append(apiKey) 106 | .append("&market=").append(marketName).append("&quantity=").append(quantity.doubleValue()) 107 | .append("&rate=").append(rate.doubleValue()).append("&nonce=").append(nonce); 108 | 109 | HttpHeaders headers = new HttpHeaders(); 110 | 111 | try { 112 | headers.add("apisign", encode(apiSecret, url.toString())); 113 | } catch (Exception e) { 114 | logger.error("Error while setting header ", e); 115 | } 116 | 117 | HttpEntity request = new HttpEntity(headers); 118 | 119 | String response = restTemplate.postForObject(url.toString(), request, String.class); 120 | 121 | OrderResponse orderResponse = gson.fromJson(response, OrderResponse.class); 122 | 123 | if (!orderResponse.isSuccess()) { 124 | 125 | logger.error("Error while setting header with response {}", response); 126 | throw new Exception(); 127 | 128 | } 129 | 130 | return orderResponse.getResult().getUuid(); 131 | } 132 | 133 | public void waitOpenOrderToClose(String apiKey, String apiSecret, String uuid) { 134 | boolean isOpen = true; 135 | do { 136 | isOpen = isOrderOpen(apiKey, apiSecret, uuid); 137 | 138 | if (isOpen == true) { 139 | try { 140 | Thread.sleep(CHECK_SLEEP_INTERVAL_MILLISECOND); 141 | } catch (InterruptedException e) { 142 | logger.error("Error occured", e); 143 | } 144 | } 145 | } while (isOpen == true); 146 | } 147 | 148 | private boolean isOrderOpen(String apiKey, String apiSecret, String uuid) { 149 | 150 | long nonce = new Date().getTime(); 151 | 152 | StringBuilder url = new StringBuilder(BITTREX_URL + "account/getorder?apikey=").append(apiKey).append("&uuid=") 153 | .append(uuid).append("&nonce=").append(nonce); 154 | 155 | HttpHeaders headers = new HttpHeaders(); 156 | 157 | try { 158 | headers.add("apisign", encode(apiSecret, url.toString())); 159 | } catch (Exception e) { 160 | logger.error("Error while setting header ", e); 161 | } 162 | 163 | HttpEntity request = new HttpEntity(headers); 164 | 165 | String response = restTemplate.postForObject(url.toString(), request, String.class); 166 | 167 | OrderStatusResponse orderStatusResponse = gson.fromJson(response, OrderStatusResponse.class); 168 | 169 | return orderStatusResponse.getResult().isIsOpen(); 170 | 171 | } 172 | 173 | private String encode(String key, String data) throws Exception { 174 | 175 | byte[] byteKey = key.getBytes("UTF-8"); 176 | final String HMAC_SHA512 = "HmacSHA512"; 177 | Mac sha512_HMAC = Mac.getInstance(HMAC_SHA512); 178 | SecretKeySpec keySpec = new SecretKeySpec(byteKey, HMAC_SHA512); 179 | sha512_HMAC.init(keySpec); 180 | byte[] mac_data = sha512_HMAC.doFinal(data.getBytes("UTF-8")); 181 | String result = bytesToHex(mac_data); 182 | return result; 183 | 184 | } 185 | 186 | private String bytesToHex(byte[] bytes) { 187 | final char[] hexArray = "0123456789ABCDEF".toCharArray(); 188 | char[] hexChars = new char[bytes.length * 2]; 189 | for (int j = 0; j < bytes.length; j++) { 190 | int v = bytes[j] & 0xFF; 191 | hexChars[j * 2] = hexArray[v >>> 4]; 192 | hexChars[j * 2 + 1] = hexArray[v & 0x0F]; 193 | } 194 | return new String(hexChars); 195 | } 196 | 197 | } 198 | 199 | @JsonIgnoreProperties(ignoreUnknown = true) 200 | class OrderStatusResponse { 201 | 202 | private boolean success; 203 | private String message; 204 | private OrderStatusResult result; 205 | 206 | public boolean isSuccess() { 207 | return success; 208 | } 209 | 210 | public void setSuccess(boolean success) { 211 | this.success = success; 212 | } 213 | 214 | public String getMessage() { 215 | return message; 216 | } 217 | 218 | public void setMessage(String message) { 219 | this.message = message; 220 | } 221 | 222 | public OrderStatusResult getResult() { 223 | return result; 224 | } 225 | 226 | public void setResult(OrderStatusResult result) { 227 | this.result = result; 228 | } 229 | 230 | class OrderStatusResult { 231 | 232 | boolean IsOpen; 233 | 234 | public boolean isIsOpen() { 235 | return IsOpen; 236 | } 237 | 238 | public void setIsOpen(boolean isOpen) { 239 | IsOpen = isOpen; 240 | } 241 | 242 | } 243 | 244 | } 245 | 246 | @JsonIgnoreProperties(ignoreUnknown = true) 247 | class OrderResponse { 248 | 249 | private boolean success; 250 | private String message; 251 | private OrderUUIDResult result; 252 | 253 | public boolean isSuccess() { 254 | return success; 255 | } 256 | 257 | public void setSuccess(boolean success) { 258 | this.success = success; 259 | } 260 | 261 | public String getMessage() { 262 | return message; 263 | } 264 | 265 | public void setMessage(String message) { 266 | this.message = message; 267 | } 268 | 269 | public OrderUUIDResult getResult() { 270 | return result; 271 | } 272 | 273 | public void setResult(OrderUUIDResult result) { 274 | this.result = result; 275 | } 276 | 277 | class OrderUUIDResult { 278 | 279 | String uuid; 280 | 281 | public String getUuid() { 282 | return uuid; 283 | } 284 | 285 | public void setUuid(String uuid) { 286 | this.uuid = uuid; 287 | } 288 | 289 | } 290 | 291 | } 292 | 293 | @JsonIgnoreProperties(ignoreUnknown = true) 294 | class MarketSummaryResponse { 295 | 296 | private boolean success; 297 | private String message; 298 | private List result = new ArrayList<>(); 299 | 300 | public boolean isSuccess() { 301 | return success; 302 | } 303 | 304 | public void setSuccess(boolean success) { 305 | this.success = success; 306 | } 307 | 308 | public String getMessage() { 309 | return message; 310 | } 311 | 312 | public void setMessage(String message) { 313 | this.message = message; 314 | } 315 | 316 | public List getResult() { 317 | return result; 318 | } 319 | 320 | public void setResult(List result) { 321 | this.result = result; 322 | } 323 | 324 | class MarketDetailsResult { 325 | private String MarketName; 326 | private double High; 327 | private double Low; 328 | private double Volume; 329 | private double Last; 330 | private double BaseVolume; 331 | private String TimeStamp; 332 | private double Bid; 333 | private double Ask; 334 | private long OpenBuyOrders; 335 | private long OpenSellOrders; 336 | private double PrevDay; 337 | private String Created; 338 | 339 | public String getMarketName() { 340 | return MarketName; 341 | } 342 | 343 | public void setMarketName(String marketName) { 344 | MarketName = marketName; 345 | } 346 | 347 | public double getHigh() { 348 | return High; 349 | } 350 | 351 | public void setHigh(double high) { 352 | High = high; 353 | } 354 | 355 | public double getLow() { 356 | return Low; 357 | } 358 | 359 | public void setLow(double low) { 360 | Low = low; 361 | } 362 | 363 | public double getVolume() { 364 | return Volume; 365 | } 366 | 367 | public void setVolume(double volume) { 368 | Volume = volume; 369 | } 370 | 371 | public double getLast() { 372 | return Last; 373 | } 374 | 375 | public void setLast(double last) { 376 | Last = last; 377 | } 378 | 379 | public double getBaseVolume() { 380 | return BaseVolume; 381 | } 382 | 383 | public void setBaseVolume(double baseVolume) { 384 | BaseVolume = baseVolume; 385 | } 386 | 387 | public String getTimeStamp() { 388 | return TimeStamp; 389 | } 390 | 391 | public void setTimeStamp(String timeStamp) { 392 | TimeStamp = timeStamp; 393 | } 394 | 395 | public double getBid() { 396 | return Bid; 397 | } 398 | 399 | public void setBid(double bid) { 400 | Bid = bid; 401 | } 402 | 403 | public double getAsk() { 404 | return Ask; 405 | } 406 | 407 | public void setAsk(double ask) { 408 | Ask = ask; 409 | } 410 | 411 | public long getOpenBuyOrders() { 412 | return OpenBuyOrders; 413 | } 414 | 415 | public void setOpenBuyOrders(long openBuyOrders) { 416 | OpenBuyOrders = openBuyOrders; 417 | } 418 | 419 | public long getOpenSellOrders() { 420 | return OpenSellOrders; 421 | } 422 | 423 | public void setOpenSellOrders(long openSellOrders) { 424 | OpenSellOrders = openSellOrders; 425 | } 426 | 427 | public double getPrevDay() { 428 | return PrevDay; 429 | } 430 | 431 | public void setPrevDay(double prevDay) { 432 | PrevDay = prevDay; 433 | } 434 | 435 | public String getCreated() { 436 | return Created; 437 | } 438 | 439 | public void setCreated(String created) { 440 | Created = created; 441 | } 442 | 443 | @Override 444 | public String toString() { 445 | 446 | return String.format( 447 | "MarketDetails [MarketName=%s, High=%.8f, Low=%.8f, Volume=%.8f, Last=%.8f, Ask=%.8f, OpenBuyOrders=%d, OpenSellOrders=%d, PrevDay=%.8f, Created=%s]", 448 | MarketName, High, Low, Volume, Last, Ask, OpenBuyOrders, OpenSellOrders, PrevDay, Created); 449 | 450 | } 451 | } 452 | 453 | } 454 | --------------------------------------------------------------------------------