Zephyrnet Logo

This bot can trade Bitcoin whenever Elon Musk tweets about it

Date:

Yes! In this article we are going to build a customizable trading bot, that can buy and sell Bitcoins on Binance based on the tweet sentiment whenever Elon musk tweets.

Question: Can you tell us the motivation behind this bot?

Answer: Sure, why not?!

Source: Blockchain Research Lab
Source: Blockchain Research Lab

Can you see the price movement? They’re calling it, the “Musk Effect”.

Disclaimer: It is purely built only for fun and educational purpose. This post doesn’t encourage or criticize anyone or about anything. The goal was to just demonstrate the technical implantation of a trading bot. Its not a financial advice or recommendation.

Before we jump into the implementation part, let’s get prepared for it.

  • NodeJS : To run this bot, you need to have NodeJS installed on your machine. If you haven’t done it yet, use this link.
  • Twitter Developer Account: For getting the Bearer token to make valid requests to Twitter API.
  • Binance Testnet Keys: The keys are required to place orders programatically on the Binance Testnet exchange. It can be obtained by signing in with your GitHub account.

Let’s create a new directory for this bot and switch our current directory to it. I’m gonna call it the “musk-bot”.

mkdir musk-bot && cd musk-bot

Initialize a new project by running npm init .

The dependencies used in this project is as follows:

  • axios: To make http requests to the Twitter API
  • dotenv: To read values of the environment variables
  • node-binance-api: To place orders on the Binance Exchange (testnet)
  • sentiment: To retrieve the sentiment of the tweet.

We need to install the dependencies required.

npm install axios dotenv node-binance-api sentiment --save 

To increase some consistency in the bot, I decided storing the trade logs and last processed tweetId in the filesystem. So we need to create two more files in the project directory.

touch trade.logs tweetId.txt 

Sweet!👏 Now it’s time for the implementation.

The way our bot works is pretty simple and straightforward.

  • First it fetches up-to 10 tweets from the last processed tweet. When we start the bot for the first time, it fetches the last 10 tweets from the given twitter user Id.
  • We will maintain an array of words which is required to check which tweets are needed for processing.The tweets without that words are neglected. In our case the word array will be something like ['btc', 'bitcoin'] . There can be some hyperlinks in the tweets that contains the words present in the array, so we will remove the hyper links from the tweet using Regex before checking it against the array of words.
  • Extract the sentiment score from the tweet. If neutral or it doesn’t break the threshold, we ignore it.
  • If the tweet breaks the positive/negative threshold score (can be defined in a file, check implementation for more details), we will place a buy/sell order based on the sentiment.
  • Then we will record the trade log and the lastProcessedTweetId in a file.
  • If all the 10 tweets doesn’t contain any tweets related to the words in word array, then we simply update the lastProcessedTweetId to the most recent tweet present in the tweet array returned by the Twitter API (ie., lastProcessedTweetId = tweets[0].id)and wait for the next iteration (sliding window technique).

Create a new file called app.js in the project root directory and add the following contents.

Now we need to create the configuration files to customize this bot. Create a file called config.js to store the basic configurations of this bot.

module.exports = {BASE: "BTC",QUOTE: "USDT",//buys BTC using 30% of USDT balance
BUY_PERCENT: 30,
//sells 35% of BTC
SELL_PERCENT: 35,
//bot checks for these words in the tweets
shouldInclude: ["btc", "bitcoin"],
//UserId of the twitter user. It can be obtained from this API
twitterUserId: "elon_musk_id_goes_here",
//Frequency to check for new tweets (in minutes)
interval : 2
};

As mentioned this bot is customizable. It is not restricted only to trade bitcoin or to poll the tweets of Elon Musk. You can change these parameters as per your requirements.

Now let’s create another file .env to store the environment variables.

BEARER_TOKEN = <TWITTER_BEARER_TOKEN>
BINANCE_API_KEY= <BINANCE_TESTNET_API_KEY>
BINANCE_SECRET= <BINANCE_TESTNET_SECRET_KEY>

Almost there! We need to create a helper function to place orders on the Binance testnet exchange. Create a new folder called helpers inside the project directory and add the following contents to a new file: placeOrder.js

The above script will work based on the specified option.

  • If the action passed to the function is BUY then, the script will calculate the BUY_PERCENT (its 30 in our case), from the total USDT balance and places a MARKET BUY order in the given market (BTCUSDT).
  • If the action is SELL due to negative sentiment, then the script sells around SELL PERCENT (35%) of the total holdings for the market price.

For the testing purpose I added my Twitter userId in the config.js file and started the bot by running the node app command.

Simultaneously I posted a positive tweet stating that bitcoin is great .The output is as follows:

Trading Bot Output 1

trades.log file had the following trade data inserted.

25/06/2021, 00:06:02 - Bought 0.04739 BTC for 1656.069314602 USDT. OrderID : 5005343

Cool ✨ Later, I posted some negative and neutral tweets.The results were perfect!

Trading Bot Output 2

You can see that our bot had ignored the tweet that had a neutral sentiment and placed a Sell Order for the negative tweet. It works as expected.

I also tried with Elon Musk’s account as well for making sure that the bot calculates the sentiment as required.For that I was required to make some configurations to get some old tweets from his account and process them with our bot. Here are the sentiment results from our BOT.

Results [
{
"text": "#Bitcoin 💔 ",
"sentiment": "NEGATIVE"
}
]
...Results [
{
text: '@Cointelegraph This is inaccurate. Tesla only sold ~10% of holdings to confirm BTC could be liquidated easily without moving market.n' +
'n' +
'When there’s confirmation of reasonable (~50%) clean energy usage by miners with positive future trend, Tesla will resume allowing Bitcoin transactions.',
sentiment: 'POSITIVE'
}
]
...

You can see that the sentiments are properly assessed by our bot 💥

Source code for this bot can be found here on GitHub.

Yes I agree that this bot is very simple and as always, there is a plenty of room for improvement. But the main goal is to showcase how we can leverage Twitter API and place orders using Binance API. This bot is absolutely fun, and it helps us to learn something new and interesting. You can try to change the config file and play around with this bot. If you find any issues or wish to share your thoughts please feel to post them in the comments.

Happy coding! 🔥🔥

PlatoAi. Web3 Reimagined. Data Inteligence Amplifed.
Click here for Free Trial.

Source: https://medium.com/geekculture/this-bot-can-trade-bitcoin-whenever-elon-musk-tweets-about-it-614b95633663?source=rss——-8—————–cryptocurrency

spot_img

Latest Intelligence

spot_img

Chat with us

Hi there! How can I help you?