How To Build a Simple Cryptocurrency Live Trading Bot with Python using the Binance API
This video is about getting live cryptocurrency data via the Binance Socket Manager and store them in a database followed by analyzing this data and build a simple trend following trading strategy with the live data.
Get the Notebook/Source code by becoming a Tier-2 Channel member:
Let me know if you find content like this valuable. I will continue to implement some technical indicators and Machine Learning on Cryptocurrencies. I personally think that is pretty interesting. Nevertheless don't worry I am anyhow also covering stock trading topics 🙂
Disclaimer: This video is not an investment advice and is for educational and entertainment purposes only! Cryptocurrency and automated trading is bearing a high amount of risk which might result in a total loss of your invested capital.
If you want to support me you can register for Binance with this link, but don't feel forced to:
More information on the Binance Socket Manager:
Alternatively you can use the websocket library and pick the stream provided in the official Binance API documentation:
Set up Binance API video:
Python & SQL:
Cumulating returns:
Video on Trendfollowing:
00:00 – 01:38 Introduction / Disclaimer
01:38 – 05:05 Requesting data using the Binance Socket Manager
05:05 – 08:28 Data Cleaning / Manipulation
08:28 – 11:31 Getting Live Data into a SQLite DataBase
11:31 – 14:30 Requesting Live Data from the SQL DB
14:30 – 16:22 Explanation of Trendfollowing strategy
16:22 – 26:25 Coding the Trading Bot (simplified)
26:25 – 29:41 Test the Bot with real money trade
#Python #Tradingbot #Crypto #Binance
Code source:
password: S58MYqi3Xw
PLEASE READ(January 2022)❗
This video is picked up by the Algorithm again. Thanks for your interest and support.
Secondly most of the viewers understood that this is a technical implementation of a simple strategy and NOT a recommendation to trade this strategy. For those who doesn’t please keep that in mind 🙂
FAQs / Most common problems:
1.
SyntaxError: ‘await’ outside function
I have provided a solution to solve this in this video:
https://youtu.be/nQkaJ207xYI
2.
The stream stops and something like “None in the columns” is popping up:
https://youtu.be/OX5eDJDtqhc
Solved below the videos pinned comment (Reason behind that is, if you are not getting a ping from the server an empty data frame without columns is created).
3.
If you don’t feel comfortable using the Binance Socket Manager or you are using Python 3.10. I recommend to use a Websocket stream. I have covered it among other newer videos in the crpytobot playlist here:
https://youtu.be/8p240qonj0E
4.
I have covered a lot of other concepts like cloud deployment, other trading approaches, not using SQL or using e.g. technical indicators. Please check out the cryptobot playlist here:
https://youtube.com/playlist?list=PL9ATnizYJ7f8_opOpLnekEZNsNVUVbCZN
There is more to come so if you are interested in that please considering leaving a sub.
Thanks for watching and your support! Much appreciated ❤️
It is still saying ‘async with’ outside function
Hello, can we configure for chztry, can you help me for this. Thank you.
Unfortunately I got stuck with this workaround…Therefore I couldn’t finish it.
I’ve used this (and commented out the pieces which were not yet touched in the video):
async def main():
while True:
await socket.__aenter__()
msg = await socket.recv()
print(msg)
# frame = createframe(msg)
# frame.to_sql(pair, engine, if_exists=’append’, index=False)
# print(frame)
asyncio.run(main())
Got RuntimeError: Task cb=[_release_waiter(()]>)() at C:Users..AppDataLocalProgramsPythonPython39libasynciotasks.py:416]> got Future attached to a different loop
sys:1: RuntimeWarning: coroutine ‘ReconnectingWebsocket._read_loop’ was never awaited
@Jessica Lewis You will have to go furhter on in the Video and create the “def creatframe”. If you have done this, just copy the “def createframe” infront of the loop where it is executed and you should be good to go
You can always tell who the true educators are and who the snake oil salesmen are from what they promise and what they teach. You’re a true educator, great choice of the simple trading strategy. Subscribed
Thanks a lot for your kind words man, I appreciate it. This is super important to me!
Hi. Thanks for this video, it’s really interesting indeed. As you requested feedback, please keep providing real world examples like this but as you said maybe coding a bit more difficult (and probably reliable) trading strategies such as MACD crossover. I saw your video on macd but would be good to see one example using macd in real time to place trades. Loving your channel so far!
Hi buddy, thanks a lot for your feedback.
I already did that. Be invited to check out the cryptobot playlist.
isn’t MACD proven to be unusable nowadays? At least on the stock market I believe it is due to automated trading funds saturating.
Great content, thanks for sharing. An interesting exercise from a risk management perspective would be to take half profit at 0.15% and the other half at 0.3% so that the profit potential is slightly higher than the stop loss
You keep the stop loss at -0.15%. If you reach the first target before the stop loss, you increase the stop loss to the entry price, so that at worst you locked in your 0.15% gain
And losses what about them?
Thanks for your comment and also thanks for sharing your thoughts! Yes definitely, I am just taking some parameters here to show the base concept.
Hi Algovibes! I really enjoyed your video! I really liked how well you explain everything and make it easy to understand! I believe cryptocurrency is the future and am fascinated with algorithmic crypto trading! Please keep up the good work! I have watched a lot of videos on the subject using python and yours are the best I think! Would you consider making a trading bot video that uses other types of indicators such as MACD or CCI?
Hi buddy, thank you very much for your kind comment 🙂
Yes, I will and I partly already have.
Be invited to check this out:
https://youtu.be/nQkaJ207xYI
This is fantastic!!! I’ve only done a small bit of coding and so am still quite new to it and you have spelled this out so perfectly and explained everything so well, it has fully engaged me and inspired me!! Thank you so much!! And for myself, I love the fact that it’s crypto!! 🙂
Hi Kelli, appreciate both your positivity and your kind words. Be invited to check out the other videos in the cryptobot playlist:
https://youtube.com/playlist?list=PL9ATnizYJ7f8_opOpLnekEZNsNVUVbCZN
First of all, I want to thank you for doing this. It’s a great video and is obviously very relevant for what’s happening these days.
I do have some comments:
1. Your script currently doesn’t show actual profit/loss as the transaction fees are not taken into account, if you’re doing a lot of transaction a day it will make an impact.
2. When you say something “this doesn’t look like a good time to trend-trade” I’d really like to know why, what did you see that made you make that claim?
Again, great video, thanks!
Thanks a lot for watching and your comment.
Regarding 1 -> True. As the commission is constant with 0.075% per trade you can just subtract it from your profits.
Regarding 2 -> As this is an only positive trend following strategy the market was dropping ongoing I made that claim.
You provided a clear explanation of the code and aims and the script was great. Keep up the great work and thank you.
Thank YOU for watching, the feedback and your kind words 🙂
Very useful videos. I was exactly looking for this kind of techniques mixing data analysis ideas and simple investment strategies. Thanks a lot! I am waiting for the next related videos you will make:)
Hey Adrian, thanks a lot for your comment. Be invited to check out the Crypobot playlist – I already built a lot of stuff there.
Hi thank you for the awesome video! I want to ask something:
when we run the print(msg) command ( @5:17), you explain that we only take the ‘s’ (symbol), ‘p’ (price), and ‘E'(time). Can you help explain what the other outputs are? (‘t’, ‘q’, ‘b’, ‘a’, ‘T’)
Hi buddy, thanks a lot for your kind comment. Appreciate it 🙂
Your question is answered here:
https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md
Just scroll down to Trade streams.
Love the content on your channel, especially the crypto related stuff. Looking forward to see how you would apply TA to this live data.
Thanks and keep up the good work!
Thank you very much for your kind words and your feedback 🙂 Appreciate it.
Thanks a lot for this very interesting video combining Python and Crypto.
You explain it well and your code is clean.
Just subscribed 🙂
Catching up on your previous content will take a while, but I think it’s worth it.
Thank you very much for subscribing and your kind words!
Looking forward to know what you think about the other vids 🙂
Hello professor, another question, can you download the information from binance in longer periods, for example every 1 min? what would be the change in the code? if it works, how can it be stoppep manually?
And professor, reading one of the previous questions about the repetition of records that occurs in the “while” loop in the database, you said that we could use an “if”, could you kindly write the syntax of this “if”? Thank you!
Hi student 😀
Jokes aside.
Yes you can do that with an API call. I have done that in my newest video. The stream is always grabbing realtime data.
Instead of an if I would probably just set a waiting time of – say – one second in the while loop to avoid this “overflow”.
Hi, I was wondering: if you use ‘if cumret[-1] > entry’ and entry is set as a positive value “0.001” we are actually entering when price has just risen. Shouldn’t we use ‘if cumret[-1]
Thanks for your kind words man 🙂
Just that we are on the same page: But that should be the goal right? So we want to enter the trade when the asset is rising. That’s a “momentum” strategy not a reversal.
Definitely interested in your videos, you have a very clearn and easy to understand way of teaching.
I have a question for you, if I wanted to run a strategy with multiple coins, is it a waste of resources to have the websocket save data for the whole market?
Also what do you think the best way to implement manual controls would be, a simple example an on/off, would running a seperate process on telegram or discord be okay. Or is there a better way in your opinion?
Lastly, I would like to thank you for this content. It’s truly amazing
@Algovibes thank you so much for your detailed responses. I plan on going through all your videos one by one regardless.
Im currently stuck in this video so I need to master this one first, do you manage a community by any chance?
First of all thanks a lot for your kind words man!
Secondly I already have content on these questions.
Multiple symbols using BSM:
https://youtu.be/C-SL4Tf25eg
Multiple symbols using WebSocket and csv storage:
https://youtu.be/mDNIAkEZChg
Multiple symbols using WebSocket and SQL (also manual choice of buying as these are just signals)
https://youtu.be/8p240qonj0E
Would be happy for a feedback below these videos! 🙂
Great video. Also the sqlite incorporation is a handy tip.
According the documention a binance api stream / websocket disconnects after 24h, what’s the best way to deal with this? Since the last thing you want is missing data in your dataframe when applying calculations like moving averages and stuff.
Thanks for your comment mate 🙂
That’s a very good point.
There are some ways to deal with that: Incorporate a time tracker, so that after 24h a new connection is triggered or conditional check for a signal (pong) from the server. I will see that I am covering this problem in future videos e.g. when I am running a longer term strategy in the cloud.
Hi, just yerderday I was wondering how feasible something like this could be!
I’ll probably end up doing something similar, but I’d first have it running for some time without money to analize the results and see how the bot would behaved in a real environment.
To do so, is there a way I can implement real fees and other issues I might incur into? For example, I’m talking about the inability to buy the fraction I want because it would be too small
Hi buddy, thanks for your comment!
Can’t you just implement the buying logic in the data stream and add the potential profit to an array or similar?
Not sure if I’ll ever have the time to learn enough python to do something like this. But watching you TEACH was great! You are very instructive and have a calming way of teaching. I subbed for future me’s sake!
What an awesome comment. Thank you buddy.
I’m introducing myself in python since two months ago and seeing things like this motivates me to keep learning. The best of all is that with your explanations I can figure out what is going on, but in a very basic way anyway.
Thank you very much for sharing and teaching your knowledge with the web. Greetings from Chile!
Hey Joel,
that’s awesome to read. Thanks a lot for your comment and I am sending you my best regards to Chile!
Hi. Thanks for this video, it’s really interesting indeed. As you requested feedback, please keep providing real world examples like this but as you said maybe coding a bit more difficult (and probably reliable) trading strategies such as MACD crossover. I saw your video on macd but would be good to see one example using macd in real time to place trades. Loving your channel so far!
your name tho 😀
Besides that thanks a lot for your kind words man. I played a bit around with MACD in two of my videos in the cryptobot playlist. Be kindly invited to check that out!