Altcoin [High Risk] Live Trading Bot with Python using the Binance API
HTML-код
- Опубликовано: 18 май 2024
- Thanks for watching :-)
This video is showing how to construct an automated cryptocurrency trading bot which is making buying decisions based on the top performing Coin (over the last 24 h) on the whole Binance platform. These coins are most probably Altcoins and bear a huge amount of risk. Please really see this as an experiment.
Get the Notebook/Source code by becoming a Tier-2 Channel member:
/ algovibes
Set up Binance API video and getminutedata function explained:
• Introduction To Automa...
How the BinanceSocketManager works:
• How To Build a Simple ...
Getting the stream run outside Jupyter (in an IDE or raw python):
• How To Build a Cryptoc...
(around minute 9)
If you want to support me you can register for Binance with this link, but don't feel forced to:
www.binance.com/en/register?r...
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.
00:00 - 01:36 Introduction / Strategy explanation / Disclaimer
01:36 - 02:22 Set up (libraries etc.)
02:22 - 05:50 Get skyrocketing cryptos: Filters
05:50 - 06:30 Struggling with parentheses (Skip this)
06:30 - 11:58 Get the top performing crypto
11:58 - 12:59 Get minute data for the top crypto
12:59 - 14:10 Trading dollar amounts with Binance
14:10 - 22:40 Strategy Option I: NOT using Socket Manager
22:40 - 23:30 Running the bot Option I
23:30 - 26:56 Strategy: Using the Socket Manager
26:56 - 27:35 Outcome of the first trade
27:35 - 28:53 Running the bot Option II
28:53 - 30:19 Some Trades the Bot made this morning
Hi everyone,
I made a slight mistake. Thanks a lot Abdul and Sevi for pointing that out!
When getting the top symbols you have to do a typecast to float as the values are provided as string values.
In the function right after defining all_pairs:
all_pairs['priceChangePercent'] = all_pairs['priceChangePercent'].astype(float)
Apologies for the inconveniences!
Great stuff, but what if you are not a coder, and you still want to get rich.... :) been watching crypto for 5 years and never enough brave to buy huge ammount of it... :-/
Been watching a few of your recent videos and I love that you're explaining the code to help understand why you're doing it, been wanting to learn python for a long time and you've pushed me to do it, great content!
Thanks for your feedback mate, appreciate it :-)
The way you fixed the connection closed issue was awesome, thanks for including that!
Thanks for watching :-)
As always !! very interesting !! keep going !
Thank you :-)
This is so interesting! Thank you for your content. And thanks for the youtube algorithm. :) New subscriber here!
Thank you very much man! Happy to have you on board.
Great video! Just as a remark, when you sort for the top symbol you should first convert the entries in the column 'priceChangePercent' to a numeric one (like float), since the API returns Strings. (You can see the problem at 7:20 with the bottom negative entries.)
I forgot that. Thank you very much for pointing that out. I have added a pinned comment and referenced you there. Again: Thank you! :-)
You are just awesome bro. I am happy to have met with your channel.
You are for leaving that comment :-) Happy to have you on board!
You are always amazing , this type of video is just pure gem , thank you very much indeed
Thanks for the kind words buddy :-)
Continue doing this, I’m new subscriber
Thanks for subscribing man. I really appreciate it!
Awesome video! It took me some trial and error, but I was able to get it to make a few purchases.
Thanks mate. So, did you make profits? =D
Thank you so much for sharing precious information, learning so much from your videos!
Thanks for watching my stuff buddy
Thank you for yet another great video.
Greeting from Nederland
Welcome buddy, greetings back to 🇳🇱
nice strategy. I really enjoy your content.
Thanks buddy :-)
Great as always. I think a trailing stop order will be a nice tweak to this strategy.
Thank you :-) Yep, also possible!
I love and learn from your contents a lot. Thank you for these great contents. BTW, are you planning to do some stuff about Machine Learning as specially Reinforcement Learning? I think many of your fans would love to see this content too.
Hi buddy, thanks a lot for your feedback. I am planning on Reinforcement Learning for the upcoming year. I cannot promise anything but it is on my list. Before that I wanted to play around with a MPL strategy classifying the return directions.
Hey. Great video. I would suggest to include volume as filter to exclude coins with low volume which mostly are quite new to the market and therefore can be risky.
Hi man, thank you! On the one hand a nice suggestion but on the other hand these could be the best performing coins.
Awesome! For the long time i did not see a tutorial like this. Man youre a gold mine! believe me i can say this regarding on my experience!
Thank you so much man. Appreciate your comment!
this is amaizing ,thank's!!
Thanks for your comment mate :-)
Excellent idea 👍
Thanks for your comment buddy :-)
Would be awesome if you'd also do a quick summary with win / lose ratio at the end, because the PNL of the trades aren't obvious in the Trade History.
Much love for these kind of videos, where you show "skin in the game" instead of "just" backtesting. Keep it up! :)
Hey man, thanks a lot for your kind words. That's a very good suggestion!
Anyhow it doesn't always make sense since with showing the actual trades I just want to show the executed trades as examples.
It would make sense for a cryptobot running over a longer time horizon.
I have some things in mind for the upcoming months and I will implement a PnL there!
Yo this is for the algo gods. interesting stuff
Thank you my friend. That is surely a support for me :-)
Great video!
Thank you very much! :-)
Super Video!
Thank you :-)
This was really good, I love these videos. How would you go about doing multiple altcoins in parallel?
Thank you very much :-) Well I would probably just pull the lets say top three and include multiple streams in the function or the function call. I will cover something in that direction in one of the upcoming videos.
You could break out the buy/hold to a method and call each coin in a thread
Thanks a lot
Welcome buddy, thanks for watching :-)
This looks awesome, dude. i believe ya'll like First Inu. This token will be the next SHIB, I'm telling you for sure.
lol I am not quite sure if this comment is actually a real one or one of those pumping bots :D
@@Algovibes definitely a bot lol
Great Video, simple strategy with potential, and excellent execution turning the idea into code.
Thanks for your feedback mate, appreciate it!
hey love the content!! just getting started with python :) how old are you?
Awesome, thank you very much! Well let's say I am not in my 20s anymore :-(
hey, such a nice video. what editor you are using in this video? this live view looks cool. :)
Thanks man, Jupyter Notebook :D
Another invaluable video! How can people support you if they already have a Binance account? Do you have a crypto wallet for donations?
Thanks mate. Nah, the only support I need right now is engagement on the channel. Anyhow I have the Super Thanks feature activated on my videos.
Thanks for this particular video. Pls is it possible for you to pass on the notebook? Thanks
Sure mate! Code accèss:
ruclips.net/channel/UC87aeHqMrlR6ED0w2SVi5nwjoin
Looking forward to welcome you there!
Fantastic video- one question that is really puzzling me before going into this: are there any fees when you buy or sell a cryptos on binance ? I mean every time you pull a sell or buy order is it for free ?
Thanks.
of course not, you can see the fee column on 29:21
but they are negligible tbh
0.075% per trade. The commission asset is BNB which is recommended as you safe some money each trade.
hey dude. i really like your videos, thank you :)
i am getting into python atm. do you have any tipps? in the end i wanted to make a telegram or discord bot. i like the idea of a trading bot also a lot :)
so for now i am stuck at my udemy though :D so any tipps are welcomed. and yeah, thank you for your videos :)
ach so, kann es sein, dass du deutsch als muttersprache hast? ;)
Thanks for your kind words man. I really appreciate it.
I made a video on that topic, might be helpful for you:
ruclips.net/video/qCZiENV83rE/видео.html
Und ja, bin ich (:
@@Algovibes hab ich gesehen und mir vorhin reingezogen. Auf masterlevel werd ich das wohl nicht mehr bringen 😂
Ich bin noch so „Stage 1“ mit dem „nix kapieren“ und RUclips/Udemy Videos. ;) aber ich bleib auf jeden Fall hier am Ball.
Besten Dank.
Hi. First of all many thanks for great content! Very appreciated your effort. I have question regardign coding 2 line cross. Can you help with it? Meaning I need to know how to write comparation and set buy order if lets say green line cross red line but from top to down, not from down to up. many thanks again! regards
I actually planned on a video covering SMA / EMA cross strategies. Is that what you were looking for?
@@Algovibes thank you for reply, no, I needed it for Kertnel+RSI gragh, but it doesn't really matter for me. I think your sma ema cross code I can use as well just by changing names. I simply need how to write this crossing code so program will understand thst line crossed from up to down but not opposite.
@@MrKanan13 Just use the status of the lines from the iteration before. So if before x > y and now x < y, you know x crossed over y down. (But watch out since these indicators can be quite gittery, so you might get a lot of mixed signals)
@@sevir408 I used similar coding like this:
**************************
if(red - aqua >= 3):
Rule#1 = True
if((aqua -red >=1) and Rule#1):
if(not buy):
print(time.time())
print("Buy order")
buy = True
sell = False
Rule#1 = False
quantity = round(float(client.get_asset_balance("USDT")['free'])/get_quan(),5)
try:
order = client.create_order(
symbol=symbol,
side="BUY",
type="MARKET",
quantity=quantity)
print(order)
except Exception as ex:
print("Some exception occured while placing buy order", ex)
**********************
But it does not work properly.
Hi, thanks a lot for the video. How would you backtest this?
That is a pretty good question. Ad hoc: Pull the price data (best case: 1 h data) for ALL relevant cryptos. Check which one was performing best over the last 24 hours and then check performance over the last 2h. Then check how this asset was performing after that. Technically quite challenging. Would take me some time to implement that.
How can I try it with a virtual wallet? Have you already done it in another video? Great content!
Well you need a trading platform to trade. But anyhow I recommend to store cryptos in your wallet once you done with trading.
My friend, you should get a patreon or something like that. Greetings from Wessermarch, Deutschland
Nah...maybe one day but I want to focus on RUclips. You can use the Super Thanks feature to support me financially :D
Greetings back ❤️
Thank you for the video.
If one attempts to download 2h candlesticks instead of 1m ones, what is the best way of keeping them up-to-date? It does not make sense to pepper the API with constant requests and the candlesticks are updated once in 2 hours. What is the best way of structuring a function to request those regularly?
Thanks for watching man. You could livestream (BSM or Websocket - covered both approaches in my newer videos) the prices and resample them on the 2h timeframe. I have shown how to do resampling in my newest video.
ruclips.net/video/HB1CLz0Z1NY/видео.html
@@Algovibes Thanks a lot for the advice, Alex! Cheers
Thank you for sharing. I have one quick question. Is there any API that support live simulation trading the stock or cryptocurrency? I want to try what you did on my own but I'm not prepared enough to use real money so I want to know how to test strategy in live trading.(not backtest)
Hi buddy,
What about just using the official API and just don't execute real orders but e.g. store the values in an array or similar? Wouldn't that be enough?
@@Algovibes Will try! Thank for responding and I'm looking forward to watching your new videos!
@@Algovibes Can you explain how i can implement that?
what editor is that, which is showing the output from those binance library functions?
You mean the code environment? That's Jupyter Notebook.
This was really good, How would you go about doing multiple altcoins in parallel?
Thanks for your feedback buddy! You mean considering multiple data streams?
@@Algovibes i need first 3 gainers.
@@farhan6516 any feedback on this?
Thanks so much for you videos! I'm trying to add an additional screening function to this bot to remove illiquid coins (
Thanks for watching man :-)
Ad hoc I would think of checking out the market depth:
depth = client.get_order_book(symbol='BNBBTC')
Source:
python-binance.readthedocs.io/en/latest/
Gutes Video! Bist du Datascientist?
Danke mein bester!
great stuff bro, is there a repo for the code bro?
Thanks man! Unfortunately not. Sorry!
Maybe better to take not top change symbol but one that enter top10 and upped then more.
Also pretty nice. I will work on a similar topic for sure in the future.
Do you have more information about the win/loss ratio of this trading strategy? Seems like a nice bot and not super hard to set up XD
Didn't test it further: No. But would quite interesting - I agree.
Is it possible to to create/run a bot on Binance futures? I can only see SPOT and Margin within the documention.
Not 100% sure but seems to be possible:
www.binance.com/en/support/announcement/6bc47f8b8a05445cb07b30454fec4084
new subscriber for youu! If we do same things as you do, we have a trading bot?
Thanks mate. Well you might have a trading bot even though there are some more things to consider such as a "real" deployment so that it can run overnight etc. But in general you shouldn't see my bots as a ready-to-use bot.
I keep getting precision errors I guess float casting is cutting off some of the price especially for a coin like SHIB which is 6 decimal places out
Yep this is a good point. The 2 digit rounding won't work on very huge coins and also not on very small coins.
Any reason not to use the python library binance-connector, which is mentioned in the binance api documentation?
Nope. The library is very well documented so I was going for this.
I have another pretty obvious question - were you able to make profit over time using these bots? what's preventing everyone from using something like this?
Good question! In general you shouldn't see my bots as a way to make money. Just see me as someone who is interested in programming stuff like that. I made some good trades with this BUT I didn't test it over the long term.
what's the difference using the Socket Manager and not using the Socket Manager. I was able to get it to work without using the Socket Manager on with raw python. the explanation on the other video (at around 9th minute) when you moved to other steps got confusing so I don't quite get how to execute it when using the socket manager
That's a good question. Using the socket manager you are getting a data stream which you could btw even use without having a Binance account. You are not doing API calls. That is the recommended way. The historicals way is also possible but if you are running that for a longer time you will see a lot of upcoming errors due to excessive API requests.
But I am actually showing how to use both approaches in this video.
Hope I could shed some light on this.
hi, can you please answer me, i want to trade the top coin, but i notice that in binance top gainers the change percent is great than if you get live data like you show us in this video even with all pairs, and some pairs are not showen, please answer me, and thank you
Hi man, sure. Can you elaborate?
Is it possible to build a telegram bot that notifies me of the positions( trades) of the top traders based on pnl on binance and ftx?
Interesting suggestion indeed. But I am quite sure this data is not (publicly) available. Correct me if I am wrong!
Hi, create_order function would not work for me because it said I had the wrong amount of parameters even though I copied this code exactly. I then used order_market_buy and order_market_sell functions instead of create_order. This worked, bought FORTHUSDT, printed the close, target & stop prices, but the program then crashed saying "None of [Index(['s', 'E', 'p'], dtype='object')] are in the [columns]" in regards to the createframe function. Do you have any idea why this is?
Please use the approach shown in this video here:
ruclips.net/video/OX5eDJDtqhc/видео.html
Machst du auch Aufträge zugunsten von Kunden?
Zumindest noch nicht. Ich arbeite Vollzeit und mache RUclips nebenbei. Für sowas hätte ich keine Zeit. Großer, derzeit vielleicht noch unrealistischer Traum, ist allerdings mal komplett auf eigenen Beinen zu stehen. Dann wäre sowas durchaus möglich.
Hey, thanks for the code, i am getting an error, how exactly should i solve this?
"await" allowed only within async functionPylance
(function) strategy_socket: (buy_amt, SL=0.985, Target=1.02, open_position=False) -> Any
This happens when calling the second option
I was able to make it work, but when selling i get the followingÇ
KeyError: "None of [Index(['s', 'E', 'p'], dtype='object')] are in the [columns]"
Any ideas?
Please just take the approach shown in this video to pull live data:
ruclips.net/video/OX5eDJDtqhc/видео.html
Would be awesome if you provide me feedback if that is working out for you,.
how can you solve this error
"await allowed only within async function"??
Don't we need to revert " open_position=False" right before the break of the "strategy" method?
No. Why do you think so?
@@Algovibes Because Im a programming noob and couldn't get my head around the strategy() method, plus I'm trying to add in a bunch of stuff of my own, like trailing take profit and buy conditions that calculate current long and short term trends, based two sets of middle average values. I get it now, you are breaking the 'while open_position = True" loop upon selling, thus restarting the whole "strategy(): if:" loop which takes the default value of "open_position = False" .
Thank you so much for making these videos, they motivate me to tackle things, that are hard af to grasp, but thats the only way to learn.
I can use this for any exchange that offers api ?
Basically yes.
Could you do the same in trading stocks please?
Like buying penny stocks? Well that would be very cool as well.
@@Algovibes Yeah cool
Can you review technical analysis python Library : pip install ta
Already did some stuff with it. Used it e.g. here:
ruclips.net/video/rYfe9Bg2GcY/видео.html
@@Algovibes thx algovibes
When we calculate the ethereum qty , we want to buy 200 dollars, why does the qty show 0. How should we proceed to set a decimal amount?
python's round function rounds to 0 decimal places by default. If you want to change that, either avoid round at all or provide a second argument to round specifying the number of decimal places you want to have. You can experiment with this using 'round(1.2345, 2)' which will result in '1.23'
Herr Vorragend explained it 100% correctly (that name tho :D)
Sorry to bug you here as well, but i have defined socket like you have, and i get this error: local variable 'socket' referenced before assignment. I'm actually not quite sure what this means. Can you help?
Hi man,
can you please pass me a timestamp in the video where you are referring to?
@@Algovibes Ah, yes, sorry. 25:38 is the timestamp. I get this error in Jupyter:
---> 20 await socket.__aenter__()
21 msg = await socket.recv()
22 df = createframe(msg)
UnboundLocalError: local variable 'socket' referenced before assignment
впечатляет
Spasibo :-)
How to execute a request on more than one api at the same time?
Could you elaborate?
queue with fifo and threading libraries. But be aware that you can lose your account since the api calls have some internal limits. You can byspass that as well but this is another day's topic.
My program runs for a while but I get this error
KeyError: "None of [Index(['s', 'E', 'p'], dtype='object')] are in the [columns]
Yep. Please check out this video and in specific the pinned comment:
ruclips.net/video/OX5eDJDtqhc/видео.html
@@Algovibes Hello thanks for everything you do I did watch the video and read the comment. I added the if statement like you suggested and also made it a async function but I think I am doing something wrong would you mind sharing your fix to this as I cant seem to figure it out.
Thanks !
the last line "await strategy(200) i'm gettin this error : "await" allowed only with async function , can you help me pls?
Sure. Explained it here at around minute 9.
ruclips.net/video/nQkaJ207xYI/видео.html
Also please check out my newer videos in the cryptobot playlist. There you will find other approaches such as using Websocket instead of the Binance Socket Manager.
Timestamp for this request was 1000ms ahead of the server's time. ?
Can you elaborate?
Do you actively run trading bots ?
Yes!
we appreciate your work
can you plz send us the codes
thank you so much
Thanks buddy. This video is close to my engagement goal. Probably will publish source code within the next 2-3 months.
Please can u make a crypto bot which uses scalping method n make a good profit ??
Yep. I was planning on that. Do you have any more specifics where you would be interested in?
@@Algovibes I am a newbie in this so I would just suggest as much as Ik as a public opinion u should take scalping method in consideration because as much as Ik this would make the best python bot ever n would help many others it should be intraday and show the progress of 100 dollars in 5 days just the report it would help to understand the profits take ur time n make a legendary thing ty for looking into this
Problem with scalping is always the fees
@@sevir408 if we have our own bot no fees
@@sevir408 use BNB for fees :)
ValueError: Length mismatch: Expected axis has 0 elements, new values have 6 elements
KeyError: "None of [Index(['s', 'E', 'p'], dtype='object')] are in the [columns]"
Can you help me with this errors. thank you
Would need more elaboration on that. When does this happen (timestamp would be helpful)?
how to do to tell it to buy at -1 tick?
Can you elaborate?
@@Algovibes but I'm sorry, i'm just thinking... since the trend is visible it might be beneficial to do checks on Parabolic SAR (must compare current value and a previous value, see if > or
APIError(code=-2010): Account has insufficient balance for requested action.
Im having some rounding problems with this code... Any tips?
Pretty straightforward: You need to make sure you have enough USDT in your wallet. Other possibility is, that a trade just has been executed and not sold. Just manually sell it then.
@@Algovibes Got it to work now, thank u for your help man! :D
Hi, first of all thank you for the great content, I am really enjoying your Binance trading bot series. I was testing your code and found an error. The way you are finding the top performing Coins is only giving coins which are changed less than 10%. Somehow it is not showing the coins which are changed more than that. Maybe you need to convert the priceChangePercent column to float and then apply the condition. I tried doing that using df['priceChangePercent'] = df['priceChangePercent'].astype(float), but it is giving me SettingWithCopy Warning. Can you tell if I am missing something here.?
Hi Abdul, thanks a lot for your kind comment and pointing out this mistake!
I just forgot about that. I pinned a comment referencing to you. Thank you very much!
what is the win/lose in %?
I can't tell. But I am planning to do a bit more long term consideration.
@@Algovibes how cant you tell? You could just look at the balance before and after trading for a bit
@@tank7474 I know. But I am currently not running the bot.
Boss token and hodl, no algorithm needed
lol :D
So, how's the balance now?
I cried so much that I wasn't able to see it.
@@Algovibes Tears of joy I assume?
this is gold. thank you very much. but for dear love of God fking sake, STOP swalloing in the freaking mic man
This comment had me dying laughing :D Sorry mate, I didn't notice that. Next video I will try to turn down the voice sensitivity on my mic.
@@Algovibes hey no prob man 😁 i was curious about how you would take this 😁 i.m glad u laughed
I want code please
It's directly in front of you 😛
great video mate, very informative! do you have any social media I can contact you on? just have a couple of questions regarding the bot
Thanks mate :-)
Here I am, how can I help you with?
Very cool video. Thanks. Only I can't start the bot.
At the final stage when I perform
while True:
strategy
Anaconda renders this error:
NameError Traceback (most recent call last)
in
1 while True:
----> 2 strategy (20)
in strategy (byu_amt, SL, Target, open_position)
7 assset = get_top_symbol ()
8 df = getminutedata (asset, '1m', '120')
----> 9 qty = round (buy_amt / df.Close.iloc [-1])
10 if ((df.Close.pct_change () + 1). Cumprod ()). Iloc [-1]> 1:
11 order = client.create_order (symbol = asset,
NameError: name 'buy_amt' is not defined
What could be the problem? Help me please.
Hi buddy, thanks a lot for your comment. It's just a simple typo. The argument in your function definition is "byu_amt". Should be buy_amt.
@@Algovibes thanks for your answer. And also after the second big part (after bsm = BinanceSocketManager(client) ), appears an error 'await' outside async function:
File "", line 20
await socket._aenter_()
^
SyntaxError: 'await' outside async function
@@Algovibes
sorry for the inconvenience. there was an error again after first while True:
strategy(200):
TypeError Traceback (most recent call last)
in
1 while True:
----> 2 strategy(200)
in strategy(buy_amt, SL, Target, open_position)
7 assset = get_top_symbol()
8 df = getminutedata(asset, '1m', '120')
----> 9 qty = round(buy_amt/df.Close.iloc[-1])
10 if ((df.Close.pct_change() + 1).cumprod()).iloc[-1] > 1:
11 order = client.create_order(symbol=asset,
TypeError: unsupported operand type(s) for /: 'int' and 'str'
bro can i buy shorce code? pls share your email. thank you
Unfortunately not. But the code is literally free. Just invest some time in typing the stuff instead of wasting your money :D