Login

Lost your password?
Don't have an account? Sign Up

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

https://www.ethereum4all.live

47 comments

  1. Algovibes

    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 ❤️

    1. Hans Vanderschot

      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

    2. yns.m.l

      @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

  2. Henry Dikeman

    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

  3. Martín Giannechini Merello

    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!

  4. Clément Felley

    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

  5. Patrick Walsh

    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?

  6. Kelli Clark

    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!! 🙂

  7. Assaf Cohen

    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!

    1. Algovibes

      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.

  8. Adrian Rubio Jimenez

    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:)

  9. Yohannes Cahyadi

    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’)

  10. Kurt Schatteman

    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.

  11. ludwig matheus

    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!

    1. Algovibes

      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”.

  12. Pietro Lenzi

    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]

    1. Algovibes

      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.

  13. Kaveh B

    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

    1. Kaveh B

      @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?

  14. remi

    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.

    1. Algovibes

      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.

  15. Roberto

    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

  16. Stefan Fredin

    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!

  17. Joel Alarcón Barrientos

    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!

  18. CHITUS?⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻

    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!

Leave a Comment

Your email address will not be published. Required fields are marked *

*
*