How To Write Your Own Bot For Cryptocurrency Exchange In 5 Mins

How To Write Your Own Bot For Cryptocurrency Exchange Main Logo

How To Write Your Own Bot For Cryptocurrency Exchange In 5 Mins

Hello everyone. Today we are going to write a simple bot for a cryptocurrency exchange. If you have followed us along then you might know that it’s our third bot for the stock exchange.

But this one is going to be the simplest one as it mostly focuses on providing a more detail information on how to start with a bot creation and implementation it into the cryptocurrency exchange.

Stage number 1: The Cryptocurrency Exchange

How To Write Your Own Bot For Cryptocurrency Exchange Photo 1 (1)

We are going to be using an EXMO International Cryptocurrency Exchange. As it one of the most popular in Europe and North America and capable of accepting all type of currency.

But one of the main things that we choose it is that it has ready-made solutions for working with their API. This will certainly facilitate our work.

  • Of course, on the stock exchange, you need to register and deposit some money. We, for example, contributed $ 5.
  • Further, in your personal account, you will receive keys for accessing the API.

We are going to be using the client for Node.js (so you’ll need to install Node.js and NPM).

On your computer, create a new folder and a file in which our trading bot will be (exmo/index.js for example), open the console and make the latest standard preparations.

If you don’t know how to access to your Power Shell on Windows or Terminal on Mac please refer to this and this links.

Then, by using “cd” command in your terminal window, we accessing our newly created folder, so that we can implement the following commands:

npm install exmo-api

While the packages are being installed, create another file, call it exmo.js and fill it with this content.

var CryptoJS = require("crypto-js")
http = require('http'),
querystring = require('querystring'),
request = require('request'),
config = {
url: ''

function sign(message){
return CryptoJS.HmacSHA512(message, config.secret).toString(CryptoJS.enc.hex);

exports.init_exmo = function (cfg) {
config.key = cfg.key;
config.secret = cfg.secret;
config.nonce = Math.floor(new Date().getTime()*1000);

exports.api_query = function(method_name, data, callback){
data.nonce = config.nonce++;
var post_data = querystring.stringify(data);

var options = {
url: config.url + method_name,
method: 'POST',
headers: {
'Key': config.key,
'Sign': sign(post_data)

request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {

exports.api_query2 = function(method_name, data, callback){
data.nonce = config.nonce++;
var post_data = querystring.stringify(data);

var post_options = {
host: '',
port: '80',
path: '/v1/' + method_name,
method: 'POST',
headers: {
'Key': config.key,
'Sign': sign(post_data),
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(post_data)
var post_req = http.request(post_options, function(res) {
res.on('data', function (chunk) {


exports.test = function(){
return config.key;

This file contains the API address, the connection of additional libraries that we need to work with the API and the main function for querying the API.

That all, we have all prepared and now we can immediately start creating a personal bot for making money.

Stage number 2: Code

How To Write Your Own Bot For Cryptocurrency Exchange Photo 2

Open our index.js and connect the exmo.js file:

const exmo = require("./exmo");

Then we go to the exchange in the private office to where we created our keys to access the api.

Copy them and save them in variables:

const apiKey = 'Your Key';
const apiSecret = 'Your secret';

Now create two variables:

  • currency1 is what we buy;
  • currency2 – the currency for which we buy.

We want to buy bitcoins for USD dollars:

const currency1 = 'BTC';
const currency2 = 'USD';

Further important point – we create a variable with the minimum amount of the bet. The exchange does not allow buying less than this amount.

Go to the address search for your pair (for us it’s BTC_USD) and look at the first parameter – min_quantity – 0.001

const currency1MinQuantity = 0.001;

And a few more variables: number of minutes through which a failed buy order will be canceled currency1

const orderLifeTime = 3;

Exchange Commission (0.002 = 0.2%)

const stockFee = 0.002;

The time period (in minutes) for calculating the average price (this is needed for our algorithm)

const avgPricePeriod = 1;

The amount of currency2 for buying currency1 with a one-time transaction (We threw $ 5 – and we will operate)

const canSpend = 5;

The desired amount of profit per transaction (0.001 = 0.1%)

const profit = 0.001;

If the time of the exchange differs from the current one

const stockTimeOffset = 0;

For convenience, join our pair through _

let currentPair = currency1+'_'+currency2;

Initialize the connection

exmo.init_exmo({key:apiKey, secret:apiSecret});

For the test, you can request information about yourself:

exmo.api_query("user_info", { }, result => console.log(result););

Go to the console and start

node index.js

If everything is done correctly, you will see the information for you!

Everything works and you can go to the most interesting – the function that will generate money for us.

So, we already said above that our algorithm will be simple, now you will understand how much.

  • The trick is to take the history of completed transactions for any period – we have the avgPricePeriod variable for this – and calculate the average price for which currency1 was sold. For this average price, we will expose our warrant.

Now, we have to write our trade () function

function trade(){}

First, we get a list of our open orders:

1) Сheck whether we have open orders for our pair using the api-method user_open_orders. If there are, and they are for sale,

Then we are just waiting for them to be performed (sometimes until the end of time).

If there are purchase orders, we simply store them

exmo.api_query ("user_open_orders", {}, result => {

let res = JSON.parse (result);

if (res [currentPair] == undefined) console.log ('There are no open frames');

let buyOrders = [];

for (let i in res [currentPair]) {
console.log (res [currentPair] [i]);
if (res [currentPair] [i] .type == 'sell') {
console.log ('Exit, wait until all orders for sale are completed / closed');
} else {
buyOrders.push (res [currentPair] [i]);

2) Check if we have open purchase orders.

We go through all the orders and get a history of them using the order_trades method, passing there the id order.

There can be 3 options:

if (buyOrders.length> 0) {
for (let key in buyOrders) {
console.log ('Check what happens with the pending order', buyOrders [key] ['order_id']);

exmo.api_query ('order_trades', {"order_id": buyOrders [key] ['order_id']}, result => {
let res = JSON.parse (result);

1) we can buy the necessary currency not entirely, but parts of the seller’s orders.
Therefore, if we have already bought at the desired price, then we wait when we will buy the whole amount.

if (res.result! == false) {
console.log ('Exit, we continue to hope to buy currency by that rate, by which the part has already been bought');

2) with the second option we need to check whether our order hangs too long. Prices change quickly and, probably, the average price is no longer relevant. For this, we have set the variable orderLifeTime, where we specify how much our order should hang in minutes.

If time is up, then cancel the order using the order_cancel method, passing it the id order.

let timePassed = (new Date (). getTime () / 1000) + stockTimeOffset * 60 * 60 - (buyOrders [key] ['created']);
if (timePassed> orderLifeTime * 60) {
exmo.api_query ('order_cancel', {"order_id": buyOrders [key] ['order_id']}, res => {
let result = JSON.parse (res);
if (result.error) console.log (result.error);

console.log (`Cancel order for $ {orderLifeTime} minutes failed to buy $ {currency1}`);
} else {

3) if the time has not yet come, we just hope that we can buy at our price.

console.log (`Exit, we continue to hope to buy currency at the rate specified earlier, $ {timePassed} seconds' passed from the time the order was created);
} else {

Everything, with open orders, we sorted out, now our robot knows what to do with orders when they create. Half of the case is done.

We receive information about our account using the user_info method:

let res = JSON.parse(result);

For convenience, we will write the balances for our pairs:

let balance = res.balances[currency1];
let balance2 = res.balances[currency2];

Let’s check if there is currency1, which can be sold.

if(balance >= currency1MinQuantity){}

If so, we need to calculate the selling rate.

It is necessary to sell all the currency that was bought, for the amount that was bought plus profit after deduction of the commission fee.

An important point! We have fewer currencies than we bought – the exchange took a commission.

let wannaGet = canSpend + canSpend * (stockFee+profit);
console.log('sell', balance, wannaGet, (wannaGet/balance));

When creating orders, the order_create method needs to pass parameters:

  • the pair is our current pair for trading;
  • quantity – quantity;
  • price – price;
  • type – a type of the created order (buy/sell);

We want to sell – in the type, we specify sell.

let options = {
"pair": currentPair,
"quantity": balance,
"price": wannaGet / balance,
"type": 'sell'

And send the request, if everything is correct, you will see the entry “Created a sell order”

exmo.api_query ("order_create", options, (result) => {
if (result.error) console.log (result.error);

console.log ("Created a sell order", currency1, result.order_id);

If we had a currency, we simply created a warrant for its sale.

Now go to the most interesting block: case, if we do not have currency1 (BTC) and we want to buy it for our currency2 (USD).

First, let’s see if there is enough money on the balance in the currency2.

if(balance2 >= canSpend){}

If there is, then we need to get the average price for which currency1 (BTC) is sold for the period of time that we specified in avgPricePeriod.

Some Info:
Exmo has a ticker method with statistics and trading volumes for currency pairs. The statistics show the average price for the last 24 hours. However, the difference between the average price and the one that trades are now trading may be very different.

Because of this, we can wait a long time for the execution of a warrant for sale.

  • Exmo has a trades method, it returns a list of transactions for a currency pair.
  • We will take the perfect deals for the avgPricePeriod of interest to us, and from them, we will calculate the average price.
  • This is not an ideal option, but it will show the real prices for which they sell and buy.

For example, at the time of writing, the average price of BTC_USD is 8314, while the purchase on the exchange is at a price of 7970.

If we place an order at the average price, it will immediately be executed at the minimum price, which is indicated in the sell orders.

But adding profit and exchange commission, we are more likely to wait for a very long time to sell.

So, let’s look at the trades method and ask for statistics on our pair current pair:

exmo.api_query("trades",{"pair":currentPair}, result => {

let res = JSON.parse(result);
let prices = [];
let summ = 0;

We will go over all the results and leave only those that are suitable for our time period.

for(deal in res[currentPair]){
let timePassed = (new Date().getTime() / 1000) + stockTimeOffset * 60 * 60 - res[currentPair][deal].date;

if(timePassed < avgPricePeriod * 60){
summ += parseInt(res[currentPair][deal].price);

And we will calculate the average price.

let avgPrice = summ2 / prices.length;

The average price we have, but we need to slightly adjust it – subtract the stockFee stock exchange commission and add the desired profit. Thus, having received a price below the average market price, we will buy a bit more currency, since the exchange subsequently takes away its part;

let needPrice = avgPrice - avgPrice * (stockFee + profit);

We get the final quantity that we need to buy.

let ammount = canSpend / needPrice;
console.log('Buy', ammount, needPrice);

We check whether it is possible to buy such a quantity of currency (whether the minimum purchase amount is violated).

if(ammount >= currency1MinQuantity){}

If our quantity is larger, then we form parameters for the order_create method, only this time with the buy type.

let options = {
"pair": currentPair,
"quantity": ammount,
"price": needPrice,
** "type": 'buy' **

exmo.api_query ('order_create', options, res => {
let result = JSON.parse (res);
if (result.error) console.log (result.error);
console.log ('Order for purchase', result.order_id);

} else {
console.log ('Exit, not enough money to create an order');

} else {
console.log ('Exit, not enough money');

Now we need to put our function on the timer (range – every 5 seconds, for example) and can run.

var timerId = setTimeout(function tick() {
timerId = setTimeout(tick, 5000);
}, 5000);

node index.js

Congratulations, you wrote your first trading bot: you can modify the algorithm and earn a lot of money) I’m joking.

How much money can you earn that way?
In one operation with $ 5, we earn about 2-3 cents. This is due to the primitive nature of the algorithm, which works if the price fluctuates within a certain range (which is almost always not the case with crypto-exchanges). For a day there are about 10-20 operations (in good hands). You can count yourself.

Here is the link to the GitHub with the full version of the bot and comments.

P.S: For those who did not work with the Node.js, your script will naturally work while the console is open.

For your robot to work 24/7, you need some VPS: there you put Nodejs, NPM and, for example, PM2. With this utility, the script will continue to work, even if the console is closed.