
My implementation of the Java library for the BTC-e exchange
After starting trading on BTC-e, I noticed a rather successful API. Its capabilities can well be directed to a good cause. Namely - to create trading bots and mobile clients. It’s clear about the bots, but the client for Android was needed pretty soon, but then they weren’t found on the market at all. And when the library was added (yes, yes, there is little code in it, but it turned out to be unfinished), although the applications appeared, there were still some kind of different ones. So, if you are interested in knowing what I did and how useful it can be to you, I ask for a cut.
Before writing, I set myself a number of tasks, namely:
GitHub was chosen for hosting, you can find links at the end of the article.
Reflections on how to put all this together led to the following class hierarchy:

The two main groups of classes are PrivateBaseClass and PublicBaseClass, for the private and public section api, respectively. PrivateBaseClass is divided into methods that return iterable and non-iterable results. They are based on CommonClass, containing things common to all. Private Network is used to work with keys when sending private requests, as well as encryption in 3DES, for storage on the device. StringCrypter helps him with this. And the TradeApi class completes the composition, which has absorbed all their capabilities and serves as a point of interaction with the user. True, no one forbids the use of separate classes like Ticker or Info, if, apart from their functionality, you do not need anything else.
For working with json, the Jackson library was chosen, and for everything else, the Apache Commons Codec.
And now, as an example, what came of all this and howto deal with it.
The algorithm will be approximately as follows: we select the method we need from the official documentation, set the parameters for it, run it, and get the results.
The very first thing you might want is to find out the prices of your favorite pairs. And it will be quite simple to do this:
The result will be:
368.98
4.216
1.02
Next in line, we will receive a balance, keys can be taken in your personal account (these, of course, are not valid):
The result will be:
0.25
If you do not want to enter the keys every time in your final implementation, but you also do not want to store them in clear form, you can use the built-in encryption. The code will be the same except for the transfer of keys. In this case, the designer will need to pass the encrypted api-key, the secret and also the password to decrypt them:
If the password is incorrect, an exception will be thrown. If a valid key and secret were installed, but after an attempt was made to install encrypted keys with the wrong password, the exception will be thrown as well, but the old keys will continue to work.
And now, perhaps the most interesting: additional features created using the official API.
Let's start with the trade. In addition to the native Trade method described in the documentation, I added a little smarter method. It uses two methods at once: Trade and Info. It automatically rounds the price to acceptable limits and throws exceptions with different messages for quick diagnosis of the cause of the error:
Result: 0
that is, we did not get anything, because it was impossible to sell 0.01 bitcoin for $ 600 at the time of writing.
The next in line pleasant priceDifference method for use in all kinds of alarms:
Result:
233.39
233.39
233.103
The method accepts the name of the pair and the price border with which it is necessary to compare the current price, as well as the delay time in milliseconds, this can be useful if the method is used in a loop, for example, to build alarms.
And finally, tryMaximumBuy (String pairName, long reuseAgeMillis) and tryMaximumSell (String pairName) remain. The most interesting of these two is the tryMaximumBuy method. He is trying to make the maximum possible purchase of currency for the selected pair. The second parameter is the time after which the data used in the method is considered obsolete and must be updated. Unfortunately, I will not be able to show an example of work, because it will not be free for me.
Of course, the possibilities of this library are not limited to this and, perhaps, you will find some other useful little things in it for yourself, for example, rounding numbers to the selected decimal place, it is useful when working with quantity and prices when buying. With the library, you can also download Javadoc describing many methods.
In conclusion, I hope that this library will be useful to you and will serve the further development of the cryptocurrency community, as well as remove the problem of keeping your set of classes for working with the exchange API up to date. I will do this.
Link to the repository with the library: github.com/alexandersjn/btc_e_assist_api
Link to the documentation for the private part of the API: btc-e.com/tapi/docs#Trade
Link to the documentation for the public part of the API: btc-e.com/api/3/ docs
Also, as an example of use, you can find a link to my android client for btc-e in the description of the library repository. You will also find its source code in my repository.
Thank you for attention.
Before writing, I set myself a number of tasks, namely:
- implement all the api features in the library;
- the name of the methods and return values must exactly match the methods from the official documentation;
- make it convenient for modification, including by other people;
- return values should be as ready as possible to use;
- add additional functionality based on api methods;
- make it compatible with Andoid.
GitHub was chosen for hosting, you can find links at the end of the article.
Reflections on how to put all this together led to the following class hierarchy:

The two main groups of classes are PrivateBaseClass and PublicBaseClass, for the private and public section api, respectively. PrivateBaseClass is divided into methods that return iterable and non-iterable results. They are based on CommonClass, containing things common to all. Private Network is used to work with keys when sending private requests, as well as encryption in 3DES, for storage on the device. StringCrypter helps him with this. And the TradeApi class completes the composition, which has absorbed all their capabilities and serves as a point of interaction with the user. True, no one forbids the use of separate classes like Ticker or Info, if, apart from their functionality, you do not need anything else.
For working with json, the Jackson library was chosen, and for everything else, the Apache Commons Codec.
And now, as an example, what came of all this and how
The algorithm will be approximately as follows: we select the method we need from the official documentation, set the parameters for it, run it, and get the results.
The very first thing you might want is to find out the prices of your favorite pairs. And it will be quite simple to do this:
TradeApi tradeApi = new TradeApi();
tradeApi.ticker.addPair("btc_usd");//добавляем пары
tradeApi.ticker.addPair("ltc_usd");
tradeApi.ticker.addPair("nmc_usd");
tradeApi.ticker.runMethod();//запускаем метод
while (tradeApi.ticker.hasNextPair()) {//если есть следующая пара
tradeApi.ticker.switchNextPair();//переключаемся на следующую пару
System.out.println(tradeApi.ticker.getCurrentLast());//выводим на экран
}
The result will be:
368.98
4.216
1.02
Next in line, we will receive a balance, keys can be taken in your personal account (these, of course, are not valid):
String aKey = "TK8HD88A-ENLZZBCW-P4L5JYVR-18K9NZZP-CYQ7WKKH";//API-ключ
String aSecret = "b7738a9f4d62da1b6ebdcd7ff2d7b5ddb93de88b71f017ae600b7ab3ed5b7015";//SECRET
TradeApi tradeApi = new TradeApi(aKey,aSecret);//передаем их конструктору
tradeApi.getInfo.runMethod();//запускаем метод, который возвращает нужную информацию
System.out.println(tradeApi.getInfo.getBalance("usd"));//выводим долларовый баланс на экран
The result will be:
0.25
If you do not want to enter the keys every time in your final implementation, but you also do not want to store them in clear form, you can use the built-in encryption. The code will be the same except for the transfer of keys. In this case, the designer will need to pass the encrypted api-key, the secret and also the password to decrypt them:
String aKey = "TK8HD88A-ENLZZBCW-P4L5JYVR-18K9NZZP-CYQ7WKKH";//API-ключ
String aSecret = "b7738a9f4d62da1b6ebdcd7ff2d7b5ddb93de88b71f017ae600b7ab3ed5b7015";//SECRET
String password = "12345";// пароль
String encryptedKey = tradeApi.encodeString(aKey, password);// шифруем ключ
String encryptedSecret = tradeApi.encodeString(aSecret, password);// шифруем секрет
tradeApi.setKeys(encryptedKey, encryptedSecret, password);//передаем конструктору зашифрованные ключ, секрет и пароль для их расшифровки
If the password is incorrect, an exception will be thrown. If a valid key and secret were installed, but after an attempt was made to install encrypted keys with the wrong password, the exception will be thrown as well, but the old keys will continue to work.
And now, perhaps the most interesting: additional features created using the official API.
Let's start with the trade. In addition to the native Trade method described in the documentation, I added a little smarter method. It uses two methods at once: Trade and Info. It automatically rounds the price to acceptable limits and throws exceptions with different messages for quick diagnosis of the cause of the error:
String aKey = "TK8HD88A-ENLZZBCW-P4L5JYVR-18K9NZZP-CYQ7WKKH";//API-ключ
String aSecret = "b7738a9f4d62da1b6ebdcd7ff2d7b5ddb93de88b71f017ae600b7ab3ed5b7015";//SECRET
TradeApi tradeApi = new TradeApi(aKey,aSecret);//передаем их конструктору
Trade trade = tradeApi.extendedTrade("btc_usd", false, "600", "0.01");//false - продажа, true - покупка :)
if (trade.isSuccess()){
System.out.println(trade.getReceived());//выводим полученное
}
Result: 0
that is, we did not get anything, because it was impossible to sell 0.01 bitcoin for $ 600 at the time of writing.
The next in line pleasant priceDifference method for use in all kinds of alarms:
TradeApi tradeApi = new TradeApi();
for (int i = 0; i < 3; i++) {
System.out.println(tradeApi.priceDifference("btc-usd", 600.0, 10000));
}
Result:
233.39
233.39
233.103
The method accepts the name of the pair and the price border with which it is necessary to compare the current price, as well as the delay time in milliseconds, this can be useful if the method is used in a loop, for example, to build alarms.
And finally, tryMaximumBuy (String pairName, long reuseAgeMillis) and tryMaximumSell (String pairName) remain. The most interesting of these two is the tryMaximumBuy method. He is trying to make the maximum possible purchase of currency for the selected pair. The second parameter is the time after which the data used in the method is considered obsolete and must be updated. Unfortunately, I will not be able to show an example of work, because it will not be free for me.
Of course, the possibilities of this library are not limited to this and, perhaps, you will find some other useful little things in it for yourself, for example, rounding numbers to the selected decimal place, it is useful when working with quantity and prices when buying. With the library, you can also download Javadoc describing many methods.
In conclusion, I hope that this library will be useful to you and will serve the further development of the cryptocurrency community, as well as remove the problem of keeping your set of classes for working with the exchange API up to date. I will do this.
Links promised at the beginning of the article
Link to the repository with the library: github.com/alexandersjn/btc_e_assist_api
Link to the documentation for the private part of the API: btc-e.com/tapi/docs#Trade
Link to the documentation for the public part of the API: btc-e.com/api/3/ docs
Also, as an example of use, you can find a link to my android client for btc-e in the description of the library repository. You will also find its source code in my repository.
Thank you for attention.