Crypto News

Coding a crypto trading algorithm that analyses Reddit sentiment

It’s been an interesting two weeks since I decided to let my crypto trading algorithm handle my portfolio based on Reddit posts sentiment. While probably not the best decision to give the Reddit hivemind control over my finances (well a portion of them anyway, I’m not advocating financial suicide), I am hoping to answer the age-old question – “Should you use reddit as crypto financial advice?” 

 So I  built a cryptocurrency trading algorithm that analyses Reddit posts sentiment and places trades on coins that are talked about in a positive manner on Reddit. I’ve been running this bot continuously for almost 2 weeks now, and last week I shared a performance report, with an overall 4.1% profit during the first week. Though that could be attributed to the bullish market in the past week.

This crypto trading bot (like all the others I’ve created before) is open-sourced on GitHub, but for those of you wanting to approach this more as a learning exercise, this week’s article is a complete guide on how the bot actually works and what the code does. So grab yourself a cup of coffee, set your phone on Airplane mode and burn some incense, as we’re about to dive into the heart of the beast.

Requirements:

  • some python knowledge
  • a Binance account
  • a personal reddit app.

This article will mainly focus on the code-base itself, so for the Binance and Reddit requirements set-up see this post here. That post also covers the .yml config files which we’re not going to go through in great detail on here.

Configure

Start by creating a few configuration files: config.yml, keywords.yml and auth.yml. These files will contain the necesarry parameters to tell your crypto trading bot how to behave. See the article linked above for more information on configuration files.

Authenticate

In order to keep things easy to understand, we’re going to store the authentication part of the script in different files, to keep the main file as clean as possible.

binance_auth.py pulls your Binance creds from the auth.yml file, authenticates and returns the Binance Client for the trading algorithm to use for placing orders.

reddit_auth.py – This file does a couple of things. First of all it uses the praw library to authenticate us with the Reddit API through our Reddit App. It also loads and returns our config and keywords options from our config.yml and keywords.yml. 

Helper functions

Storing trades

We need our bot to remember the trades it placed for a couple of reasons. We need to be able to track the profit of every trade placed, as well as check that a coin hasn’t already been bought, in order to stop repeat buying if that’s your thing.

store_order.py contains two functions, that will be called in the main program. store_order will dump the orders in a json file, while load_order is used to update the file with new orders. Note that we’re passing the file and order as arguments.

Handling orders

trade_client.py is another helper file that does a few important things. Most of the functions in this file can be used on any crypto trading algorithm that works with Binance. Have a look at the code below, and we’ll dig into it after.

The first thing we’re doing is loading the client and authenticating with Binance. – client = load_binance_creds(‘auth/auth.yml’)

Next up, we want our crypto trading bot to know the latest price of each coin analysed and detected on Reddit. get_price(coin)  will be called in the main program.

The next function is instrumental for every crypto trading bot. convert_volume takes the coin, price and quantity as arguments in order to convert  your input amount into the coin you’re about to buy. For example, let’s say that in your config file you want the bot to place trades of 100 USDT in size in BTC.

The convert_volume function will then get the latest price on BTCUSDT and return the equivalent of 100 USDT in bitcoin – so around 0.0030 at the time of writing. It also returns this number with the correct accuracy for each symbol. While BTC can have up to 6 decimal places of accuracy, XRP only has 1. Feeding the Binance client the wrong format will result in an error so this is important to get right.

The last function creates an order on Binance with our specified parameters.

The main file

This is where everything is brought together, along with some additional logic to analyse the posts sentiment and how to handle the orders. I’ve broken this file down into two parts so it doesn’t look too daunting.

reddit, config and keywords call their respective functions in order to initialise the Reddit client and configurations. Next up we write a get_post() function that will fetch reddit posts based on our criteria in the config.yml file. Stickied posts are excluded by default. 

store_posts, load_posts and compare_posts work with a json file to make sure that existing posts are not being analysed twice. When new posts are fetched, they are compared with that’s currently in our json file. If they are the same, there’s no point in analysing them again.

find_keywords looks at the posts in our json file and determines if any of the crypto keywords we defined in keywords.yml are in the posts’ body or title and then returns posts with matching keywords.

 analyse_posts adds sentiment scores to all of the posts returned by find_keywords and determines whether it’s positive, negative or neutral sentiment using the nlk pre-trained SIA model.

But in order for our crypto trading algorithm to work properly and to only place orders on Binance when it makes sense, we need to ensure that the Reddit sentiment analysis returns as an average. The bot therefore, needs to categorise posts by the keyword detected in them an get the average sentiment of all of these posts. 

Let’s say there are 8 posts matching the Bitcoin – we need to know the average sentiment for all these posts and that’s exactly what get_avg_sentiment does.

The second part of the script puts all of this together and ensures that all the functions run in the correct order. Everything is wrapped in a while True: loop and therefore will keep on executing until manually stopped or an unhandled exception creeps up.

There is some conditional logic to differentiate between live and test mode, and to ignore posts that are already stored in the json file. 

That’s it, run it and let the Reddit hivemind rule your portfolio. Obligatory not financial advice and use this at your own risk.

Did you enjoy this article? Subscribe for more awesome content and updates on this project.

If you appreciate my content and would like to see more, you can support me by donating here or via the Brave Browser. This is much appreciated as it helps me to keep the content free and open source. Thank you!

The post Coding a crypto trading algorithm that analyses Reddit sentiment appeared first on Automated Cryptocurrency Trading.

Read more: https://www.cryptomaton.org/2021/07/10/coding-a-crypto-trading-algorithm-that-analyses-reddit-sentiment/

Text source: Automated Cryptocurrency Trading

Disclaimer: Financial information and news are not financial advice, read the disclaimer.
Buy & sell Crypto in minutes

Join BINANCE!

The world's largest crypto exchange

You're just steps away from receiving your reward.

The most complete Crypto News Center.

Search Stories:

Latest top stories