Since the first time I wrote the first part of this tutorial to create a bot to buy and sell Bitcoins and other cryptocurrencies using the Bitcoin Market API, the currency’s appreciation has reached historic levels. In 2017 we celebrated the mark of U $ 15 thousand for 1 BTC and in 2021 we are already at U $ 56 thousand.
In the first part I focused on the fundamental concepts, creation and configuration of the account in the exchange, creation of the project and codification of the market monitoring algorithm. Now we will encode our bot so that it can buy and sell cryptocurrencies.
Attention: past earnings are not a guarantee of future earnings. Cryptocurrencies are risky investments and therefore you can lose a lot of money even though you believe you know how to operate in this market. I AM NOT responsible and I will never be responsible for your losses, I just teach you how to create computer programs, I do not advise investments, ok?
1 – Adjusting the API module
Open your project again (I suggest using Visual Studio Code) and go to your api.js file, which is our module that will store the client classes for the Bitcoin Market API. If you have not done the first part of the tutorial, you can download it in the previous post , in the form at the end of it.
Right at the beginning of the api.js file, we will modify the original to add two new modules that will be needed, the crypto and the querystring (the axios is from the previous tutorial):
The first serves to encrypt messages and the second to concatenate variables in the HTTP querystring format. We will need both because the endpoint that we are going to access to make transactions requires encryption and for some operations we must send data in the body of a POST.
The crypto module is native, but for the querystring module to work correctly we need to install it in the project using NPM via console (install now, if you haven’t already.
The settings passed by parameter are the API key, the API secret, the PIN of your account and the currency that will trade with this bot (BTC, BCH and LTC in the case of the Bitcoin Market). Note that KEY, SECRET and PIN I taught you how to obtain in the previous post, within your area of exchange trader. Do not share this data with anyone!
Here I am defining several operations that the API allows us to perform, just configuring the calls and passing them to a call function that is not implemented. It is worth mentioning what each operation does:
- getAccountInfo : takes information from your account, especially your current balance in each currency, including BRL;
- placeBuyOrder : create a new purchase order in the trading book. If there is availability (coins are being sold at the price you wish to pay), the order will be executed immediately. Otherwise, she goes to the book and her balance is blocked to honor the purchase;
- placeSellOrder : creates a new sales order in the trading book. If there is availability (you have purchase orders at the price you want to sell), the order will be executed immediately. Otherwise, it goes to the book and its balance in the cryptocurrency is blocked to honor the sale;
You may have noticed that several calls concatenate ‘BRL’ to the acronym of the cryptocurrency that we are going to trade, generating strings like BRLBTC, which is what we call a ‘coin pair’ or ‘currency pair’, which indicates that you are trading Reais for Bitcoins.
You should also have noticed that on some occasions I use Template Strings to force numeric variables to be strings, which is the format that the API asks for in many cases.
In the same way as in the case of the information API class, our call is async and we will have to use await to deal with its asynchronicity. Speaking of which …
2 – Buying Bitcoins in Node.js
Once your bot is monitoring the market and you have implemented the trading APIs, you should define the logic for buying and selling cryptocurrencies. There is no rule here, except that you should try to buy low and sell high, to profit from the currency fluctuation.
To begin, let’s create a very simple rule, based on an observation of the Bitcoin candlestick chart at the time of writing this post:
Now after performing the ticker to get the current market information, I check the cheapest selling price of Bitcoin today. If it is less than the number I defined as good for purchase (170000), I order it. Note that you can create all kinds of intelligence to calculate this number, such as checking the spread over the last 24 hours to infer variation, checking sales volume and purchases made to infer up or down trends, etc.
Once the price is within the range considered acceptable, it is time to create the purchase order in the trading book. The first parameter is how many bitcoins you want to buy (1, but can be fractions with up to 5 decimal places) and the second parameter is the maximum price you want to pay for a bitcoin unit (170000). Several things can happen at this point.
If you do not have enough balance, you will have an error as a return. In the event that there is no sales order compatible with the price you wish to pay, your purchase will not be made immediately. It will stop at the book, your balance will be blocked, and it will run as soon as someone is selling for the amount you want to buy (or cheaper). In these cases of future execution, you are being executed, and you generally pay a lower commission fee to the exchange.
If you have a balance and there is a sales order on the market compatible with your purchase order, it will be executed immediately. Your BRL (R $) balance will be settled, you will receive a BTC balance and pay the executor’s commission, which is usually higher than the executor’s fee (the seller whose order was already in the book before yours) .