How To Write A Trading Bot For The Bitcoin-Exchange

A Trading Bot For The Bitcoin-Exchange Main Logo

How To Write A Trading Bot For The Bitcoin-Exchange

Find a silver bullet algorithmic trade – the idea is not new and, most likely, doomed to failure. But, if suddenly you have an insight that prevents sleep, then why not check it in practice.

Immediately we admitting that we will not reveal any secrets by this post.


For starters, why bitcoin?

With bitcoin, it’s easy to work. Registration on the exchange, the generation of keys, replenishment of the account in various ways and everything, you can trade. You do not even need a contract with the broker. All interaction occurs on top of HTTP, via rest or something like that. This is the first reason.

Traditionally, methods of forecasting market value are divided into two groups: fundamental analysis and technical.

The fundamental analysis implies the search for a “fair price”. If this price is lower than the current one, then the financial instrument is overvalued, if lower – it is underestimated. Revalued sell, undervalued – buy. The simplest example of a fundamental analysis is the use of the P / E multiplier (price/earnings ratio), equal to the ratio of the market value of the stock to the annual profit received per share. Take the value of the stock and divide it into the company’s earnings for this share. The obtained number is compared with the average for the industry. The coefficient is very popular, it is shown on all financial sites such as Yes, Yahoo is still a little alive. The profit is published once a quarter, so the fundamental analysis works well for large time intervals, months and years.

This example is for stocks. For bitcoin, you can use controversial considerations about the complexity of mining, the growth dynamics of hash rate and so on. Honestly, I do not believe in the performance of this.
But technical analysis is based on the idea that the charts contain all the necessary information for the forecast. And it is the graphics that show the market changes first. And already behind them, there are news and readings are changing.

  • And when using technical analysis, the nature of the goods does not matter. You can work out the principles in the technical analysis of the cost of potatoes and use them when trading gold. We will, for example, bitcoin check the ideas for trading on the NYSE or NASDAQ. This is the second reason for choosing bitcoin. It is also the reason for using technical analysis.

The third reason is bitcoin is cool. You can think of it as anything, but it’s definitely cool.

Then, what “idea” are we talking about?

We can give a few examples, realistic and not very much:

  • Search for news on Twitter for keywords and determine their emotional coloring. Depending on this, make decisions. These are not the ones. analysis, but the idea is good.
  • Try to guess the suddenly appeared large orders to guess the actions of insiders and repeat after them.
  • Determine the “swing”, the movement of the course within a certain corridor. LINK
  • If the third order for sale is even – buy for everything.


For starters, we would like to define several terms. We will talk about bitcoin and, since bitcoin-exchanges are distinguished by their work from the “adult” exchanges, we will try to use the general concepts that are characteristic for the first and second.

The order is the same as the exchange application. The warrant tells the stock exchange of your intention to buy or sell some quantity of bitcoin at some price. When this price is reached, the order is executed, the transaction goes through. Stuck is very important and not as simple as it seems. With respect to bitcoin in general and to the WEX exchange in particular, orders are only limit pending orders (limit pending order). Market orders for sale on we are limited, but with a minimum price. Market to buy – with a maximum price. More information can be read from the wiki.

A glass (depth of market, order book) is a collection of all limit orders. In Russian.

The bid is the price of demand, the highest price at which the buyer agrees to buy. Further.

Ask – the offer price, the lowest price at which the seller agrees to sell. Further.

On some exchanges ask and bid can be confused, so you should always pay attention to their values. The bid is always less than ask.

Spread is the gap between the lowest purchase price and the highest selling price. Read more.


We have two options:

  • Use historical data.
  • Collect the data yourself.

History would be a good thing, but if you need not only prices and turnovers, but also, for example, issued warrants, then historical data is unlikely to be found.
In our case, the robot uses technical analysis, which is usually used at small intervals of time. Our bot will conduct transactions during the day, so the data can be collected a day, and then analyze them.

Again two options:

  • Raw data.
  • Finished coefficients.

It is better to combine this and that. We, most likely, will need three things from the exchange: the prices (purchases, sales, the last deal), turnover (when at what price many bought or sold) and the state of the glass. Prices and turnovers can be written raw. But the glass is difficult to describe. A “raw” glass can be stored as it is. Or just calculate and save only the desired coefficients.


This is the most interesting and the most creative stage. Therefore, we will not talk much about him. we will show only one chart.

A Trading Bot For The Bitcoin-Exchange Photo 1

Schedule for 24 hours. Step – 2 seconds. This is due to the fact that the exchange caches a part of the data for 2 seconds. The red line here depicts the course, at the last price. Green – the coefficient signaling the purchase. Black – about the sale.

If you buy on green highs and sell on black, then most trades will be profitable.

Writing a Bot

Suppose that we found a direct relationship between the parity of the third sell order and the subsequent growth. Now we are sure if the third order is even, then you should buy. Immediately ask forgiveness from go and python lovers, but we will write to java.

WEX ( or has an API. It consists of three parts: public, allows you to receive general information without authentication; trade, intended for operations with orders; push – appeared recently, sends alerts in real-time. This API is entirely covered by the wexapi library.

Sources at

Wexapi is in maven central, so the library can be connected as a dependency in grade:

compile 'com.github.artfultom:wexapi:2.0.0-RELEASE'

or in maven:


First, you need to create a client:

WexClient client = new WexClient("", key, secret);

Key and secret are used for the trading API, generated in the personal office of the exchange. Of course, they should be kept secret and not commit to GitHub.

Then, with the help of this client, you can receive public data. Information about trades on the pair BTC-used for the last 24 hours:

Map<String, Ticker> tickerMap = client.publicApi().getTicker("btc_usd").execute();
Ticker ticker = tickerMap.get("btc_usd");

A glass with a limit of 1000 orders:

Map<String, Depth> depthMap = client.publicApi().getDepth("btc_usd").setLimit(1000).execute();
Depth depth = depthMap.get("btc_usd");

The public API is cached by the exchange. The documentation says 2 seconds, it’s almost like that.

In the trading API, there is one unpleasant moment – the minimum transaction size. For BTC-used, it equals 0.001 BTC. Given that the operations for this pair have an accuracy of 3 decimal places, then if you have 0.0009 BTC in your account, you can not do anything with them through the API.

But through the site, you can. The most common operation of the trading API is likely to be:

price.setScale(3, RoundingMode.DOWN),
amount.setScale(decimalPlaces, RoundingMode.DOWN)

As you might guess, this is a sale. And the necessary here BigDecimal greatly complicates simple arithmetic operations. But who is easy now?

There are also a couple of methods that work through the push-notification service:

client.pushApi (). subscribeToTrade ("btc_usd", trades -> {
// see the deals

client.pushApi (). subscribeToDepth ("btc_usd", depth -> {
// see the order


  1. Stop Loss and Take Profit.
    Stop loss (stop loss) – closing the deal when a certain level of price loss is reached.
    Take profit is the closing of the transaction when a certain level of profit is reached.
    When you open each position, you must be sure of what profit you expect and what loss is ready.
  2. Today it works, but tomorrow the market will necessarily change.
    Some algorithms are good for a sideways trend, flat – the period when the price for a long time sticks in some price range), others only with growth or only with a fall. In any case, if the trend is changed, a profitable algorithm may begin to lose money.
  3. Bitcoin-exchanges are different.
    The first thing that catches your eye – bitcoin-exchanges work around the clock. The MICEX, NYSE, and others have a trading session. Therefore, bitcoin does not make sense for methods that use gaps (gap) – a break in the graph, the difference between the closing price of the previous session and the opening price of the current one). One should be attentive to such things if one reads literature on technical analysis, applying it to bitcoin. And vice versa.


From the literature on technical analysis, it is usually advisable to consult literature like “Technical Analysis by Jack D. Schwager”, but for starters, it is better to take advantage of the free courses of broker companies. They allow you to orient yourself in the material, throw everything and go to do something really useful. Happy trading!

Leave a Reply