Codementor Events

How to Build a Simple Cryptocurrency Trading Bot in Node.js

Published May 16, 2018Last updated Nov 12, 2018

Creating a cryptocurrency trading bot is a great exercise for improving your development experience. Furthermore, you can commercialize it and capitalize on the rapid growth of cryptocurrencies for increasing your wealth.

This article will just scratch the surface of building a cryptocurrency trading bot in Node.js. Of course, you can always learn how to build something advanced from experts like Elliotminns, who is an experienced software engineer from the U.S.
Here are some objectives we want the trading bot to achieve:

• Connect to GDAX and use its API
• Get current cryptocurrency prices
• Make trades based on the stipulated rules

Let’s get started

We’ll assume that readers already have basic understanding of JavaScript and NodeJs, MongoDB, and Docker.

You should also have an account with GDAX, which is an amazing Coinbase-supported platform that offers a comprehensive trading API.

To set up the project, you’ll need to create a folder and create a file on it.

Here is how you can do that on the command line (on a Windows machine).

mkdir cryptobot
cd cryptobot
edit index.js
npm init

Then, you’ll need to include the GDAX node library package as one of your dependencies in the package.json file.

npm install gdax

Let’s get our hands dirtier with some code.

Using GDAX public API Keys

GDAX has a public API that you can access without registering an account.
Let’s use its public API to see the cryptocurrencies it offers for trading.

const GDAX = require("gdax");
const publicClient = new GDAX.PublicClient();
 
const callback = (error, response, data) => {
  if (error)
 	return console.dir(error);
 
  return console.dir(data);
}
publicClient.getProducts(callback);

If you run the above code, your result will look like the following.

gdax1.png

As you can see above, the PublicClient method requires a callback to avoid any promises being returned.

The callback function accepts three arguments:

error: produces an error message if anything goes amiss.
response: this is a generic HTTP response abstraction argument.
data: this is the information provided by the GDAX API.

The getProducts is a public API method that is used to list the cryptocurrencies GDAX offers.

There are also some other public methods like getCurrencies and getProductHistoricalRates.

Here is how the getCurrencies method can be used.

const GDAX = require("gdax");
const publicClient = new GDAX.PublicClient();
 
const callback = (error, response, data) => {
  if (error)
 	return console.dir(error);
 
  return console.dir(data);
}
//publicClient.getProducts(callback);

publicClient.getCurrencies(callback);
 

Here is the output.

gdax2.png

For example, let’s use the getProductHistoricalRates method to get Bitcoin’s historical prices.

const GDAX = require("gdax");
const publicClient = new GDAX.PublicClient();
 
const callback = (error, response, data) => {
  if (error)
 	return console.dir(error);
 
  return console.dir(data);
}
 
//publicClient.getProducts(callback);
 
//publicClient.getCurrencies(callback);
 
publicClient.getProductHistoricRates('BTC-USD', callback);
 
publicClient.getProductHistoricRates(
  'BTC-USD',
  { granularity: 3600 },
  callback
);

Here is the output.
gdax3.png

Using GDAX private API Keys

After registering an account with GDAX, you’ll get access to its private API that offers more functionalities in building the cryptocurrency trading bot.

To create a private API key, go to your GDAX account settings section. After generating an API key, you’ll be provided with three critical pieces of information:

Key –it’s automatically generated for you.
Secret—it’s also randomly created for you.
Passphrase—you’ll need to provide it to offer added security to your API access. Although

GDAX keeps the salted hash of your passphrase, it’s unable to recover it in case you forget.

You’ll also need to specify the API access URL; or else, it will default to https://api.gdax.com.

Here is the code for authenticating the API keys.

const gdaxKey = "INSERT_YOUR_GDAX_KEY";

const gdaxSecret = "INSERT_YOUR_GDAX_SECRET";

const passPhrase = "INSERT_YOUR_GDAX_PASSPHRASE";

const apiURI = 'https://api.gdax.com';
const authenticatedClient = new GDAX.AuthenticatedClient(gdaxKey, gdaxSecret, passPhrase, apiURI);

The AuthenticatedClient method is inheriting all the API methods from the PublicClient method. Therefore, if you are accessing both the GDAX public and private API, just create one client.

Furthermore, like the PublicClient method, every private API method also requires a callback function to be passed as an argument.

For example, if you want to get a list of all trading accounts, you can use the getAccounts method.

authenticatedClient.getAccounts(callback);

After getting information about your accounts, you can make an individual query to every account to get more specific details.

const INDIVIDUAL_ACCOUNT = "INSERT_ACCOUNT_ID";

authenticatedClient.getAccount(INDIVIDUAL ACCOUNT, callback);
 

Getting current prices

Instead of flooding GDAX with requests, something is strongly discouraged, you can get information about the current prices of cryptocurrencies using its WebsocketClient.

After making a websocket connection with the GDAX servers, you’ll be able to listen to the exchange of messages taking place, and appropriately filter the specific information you require.

For example, let’s say we need information about Bitcoin.

const BTC_USD = 'BTC-USD';
const websocket = new GDAX.WebsocketClient([BTC_USD]);

const websocketCallback = (data) => console.dir(data);
websocket.on('message', websocketCallback);

Getting the current Bitcoin price from the generated output requires that we make modifications to the above code.

To achieve this, we need to filter the orders that are filled and/or done. This way, we’ll get information about the sale that has just closed and get the price information accompanying that order.

Got it?

Here is the improved code that retrieves current Bitcoin prices.

const websocketCallback = (data) => {

 	if (!(data.type === 'done' && data.reason === 'filled'))

     	return;
 	console.dir(data);

}

Placing buy and sell orders

Is this the section you’ve been waiting for?

Since you have all the information about your accounts and you can retrieve the changes in

Ethereum price, placing buy and sell orders is possible.

Here is an example of code for placing buy orders.

function placeBuy(buyData) {

  const buyParams = {

    	'price': buyData.price,

    	'size': buyData.size,

    	'product_id': BTC_USD,

  };
  this.buyOrderId = authedClient.buy(buyParams, callback);

}

Here is the code for placing sell orders.

function placeSell(buyData) {

  const sellParams = {

    	'price': buyData.price,

    	'size': buyData.size,

        'product_id': BTC_USD,

  };
  this.sellOrderId = authedClient.sell(sellParams,  callback);

}

That is it!

Conclusion

The trading bot we’ve created above is very simple and cannot guarantee profitable trading.

Some of the key features it misses are backtesting capabilities, robust trading strategies, and roadmap for deployment in actual trading conditions.

If you go ahead and use the bot in trading, you may experience losses. Therefore, if you want a hands-on experience in creating an advanced trading bot, ensure you include the missing functionalities, or learn from a professional on how to do it.

All the best.

Discover and read more posts from Dr. Michael Garbade
get started
post comments2Replies
akshay codewexy
3 years ago

can i have a kowledge from you ,how can we make algorithm in node.js for trading bot ??

Abdul-Samii Ajala
6 years ago

Great