Coding a Binance Trading Bot that detects new coins the moment they are listed

Have you noticed how many new coins tend to skyrocket temporarily the moment they are added to the Binance Exchange? Wouldn’t it be great if you could take advantage of that initial pump? This Binance Trading bot that I’ve been working on aims to do just that. The bot scans the Binance exchance and buys a coin as soon as it’s been listed on Binance.

It’s fresh out of the oven so I’m pretty excited to see how it performs, and it comes with all the bells and whistles: from trailing stop loss to test mode and more.

 

UPDATE: 

This open source crypto trading algorithm had multiple updates in the past couple of months. Catch up on the latest in the video below.

Requirements

  • A Binance account (obviously)
  • Some python skills
  • A bit of time

Making a start

First things first, if you don’t have a Binance account, or would like to create a separate account to run the bot on, go ahead and  create one here . You can use my referral link to get 5% off your trading fees. With a Binance account created, we’re going to Generate some API Keys.

To get your mainnet keys, navigate over your account, and click on API management.

On the API management page, give a label to your API key and click create API.

Once your key and secret have been generated make sure to save these, as you will only be shown the secret once. You’ll need to regenerate your keys if you haven’t saved the secret.

Now let’s give it the permissions that we require to run the bot on it. We’re only going to do Spot trading, so we only need to select Enable Reading and Enable Spot & Margin Trading. 

Coding the crypto trading bot

First of all, I’ve open sourced the code and it’s available on GitHub, if you would like to have a look yourself or simply download the source. Keep on reading to understand how it works. 

Install dependencies

The easiest way to do so is to launch your cmd/terminal and run the following commands using pip. Note that on Macs you may have to use pip3 instead.

Naturally, you need to have pip and python already installed on your machine.

Create credentials file

Create a directory called auth and inside this directory create a new .yml file called auth.yml. Inside the file,, duplicate the exact format below and replace the dummy text with your Binance actual key and secret. The crypto trading bot will need those in order to place trade on the Binance exchange.

Create an authentication file

In the same directory, go ahead and create a new file called binance_auth.py we’re going to use this file to connect to the Binance client via the Binance API.

Create a config file

This is the file that tells our trading bot what to do, and how to trade. We’re going to create a few configurable options so that we can optimise our strategy. In the main directory (a level up from the auth directory) create a config.yml file like so:

Have a look at the comments for more details regarding each config option.

Load Config

Let’s create a file that will help us load the configuration that we just created and call it load_config.py

Store orders

In order to be able to keep track of our orders and order details such as the price, time, volume and symbol, every trade we make must be logged in a local file. Your live trades will appear on the Binance reports, but test trades won’t, so a local file is the best way to keep track of test mode gains and losses. Go ahead and create a store_order.py file in the main directory The functions below will help us load and store both test and live trades.

if you’re enjoying this content please sign up below for more

Create a trade client

The purpose of this file is to help perform two important operation for our crypto trading bot. Therefore it contains two functions that will be called in the main file. The first function will convert the volume of our paired coin to that of the coin we’re about to buy. If you remember the configuration options under the config file, you’ll recall an option called PAIRING. This tells our trading bot what to pair the base asset with. For example if pairing is set to USDT the bot will only place trades on coinUSDT (ie: BTCUSDT).

The first function ensures that the volume of the trade in USDT is converted to its equivalent in the base asset. For example 15USDT would convert to around 0.000330 BTC – and  this is the value that Binance needs to know in order to automatically place a trade for us.

The second function creates an order request with the symbol-pair, volume and side (BUY or SELL).

In the main directory, create a file called trade_client.py and define the two functions like so:

The reason our conversion function looks a little more complex than you would probably expect is because Binance is quite particular with the format of the volume order. For example, while BTCUSDT can have an accuracy of up to 6 decimal points, many other coins have different step-sizes. For instance the accuracy for a XRPUSDT trade is only 1 decimal point (ie: 1.1). Sending a request on XRPUSDT with any other format (1.1000) would return an error.

Coding the crypto trading bot logic

This is it, now that we have all the necessary infrastructure it’s time to write the buy and sell logic, and execute it. 

Inside our main directory we’re going to create a main.py file. The first step is to import all the files we’ve created and any other dependencies. and define our Binance client like so:

Next, we’re going to write two functions. One that will return a list of all the tradeable coins on Binance, and a second functions that will return the list once again and also compare any differences between the two lists. If new coins are found in the second list, we’ll return those too.

Ok now we need a function for our trading bot to return us the latest price for a coin on Binance.

At this point we have all the necessary functions to buy, sell, perform logic trades and store any trade data that we want locally. All that’s left now is to bring all this together in a logical manner and execute the script.

We’re going to define a main() function, where we’re going to start by performing sell checks, and the moving into buy checks. This last block of code is significantly longer than what we’ve seen above, so spend some time and study the comments and logic behind it.

And there you have it, you should now be able to buy new coins just as they are being listed on the Binance exchange with this neat crypto trading bot. Good luck!

Did you enjoy this article? Sign up below for more awesome content!

If you found this article useful, please consider buying me a coffee here, or donating via the Brave browser. Thanks!

61 thoughts on “Coding a Binance Trading Bot that detects new coins the moment they are listed

  1. What do I actually run? main.py?

    If I do that it seems to work but this is the status that I got after a while:

    New coins detected: [{‘symbol’: ‘FORUSDT’, ‘price’: ‘0.12880000’}, {‘symbol’: ‘REQUSDT’, ‘price’: ‘0.40160000’}, {‘symbol’: ‘GHSTUSDT’, ‘price’: ‘2.35000000’}, {‘symbol’: ‘TRURUB’, ‘price’: ‘50.00000000’}, {‘symbol’: ‘FISBRL’, ‘price’: ‘11.93000000’}]
    New coin[‘symbol’] detected, but FORUSDT is currently in portfolio
    New coin[‘symbol’] detected, but REQUSDT is currently in portfolio
    New coin[‘symbol’] detected, but GHSTUSDT is currently in portfolio
    New coin[‘symbol’] detected, but TRURUB is currently in portfolio
    New coin[‘symbol’] detected, but FISBRL is currently in portfolio

    There also does not appear to be a log, for example trades.txt as in the volatility trader.

  2. Once I have installed python with pip, I just press the main.py file (after putting in my personal API and Secret key in Binance_auth file) while Binance is logged in on the browser yeah?

  3. Hey thanks for the code. After configuration I was running the main.py in test mode, however it just says working… What should be the outcome when I am running it in testmode?

  4. Hi,

    Thanks for your work, i just started the script, let’s see what happens..

    If i may offer 2 suggestions for your guide:

    1. Maybe add an explanation on how to actually run the script, i am not familiar with python and didn’t really know how to do it. I used “python main.py”, it should be correct..

    2. In the auth.yml file, i didn’t touch the “binance_tld” line since you didn’t mention it in the guide and well, it suprisingly didn’t work:p Maybe add that you are supposed to add “com” in the guide or a comment in the code.

    Thanks again,
    John

    1. Hi John,

      How did you run the script? I mean what software did you use to run the main.py? I am a python newbie and don’t understand how to run python script all that well.

      Thanks
      Faris

  5. Have this up and looks to be working well, just sitting patiently for any new listings! Will let you know how it does when that happens.

    Question, in the “fix order issues and cascading API crash” commit from a few days ago, you reset the TP to equal SL and TSL to equal TTP in the config.yml- do you mind explaining the reasoning?

    Cheers!

    1. Hey, the config.yml is more of an example of how to customize the strategy. You should input your own values in for better results. As for the API crash, still looking into why that is

  6. I keep getting this error when trying to run it: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

    Any idea why?

  7. Hi,
    Nice job and idea.
    I have a suggestion for you that I think it may help:
    Have you consider not to r/w the order’s file and keep it in memory to improve time?
    And maybe even remove the print statements?

  8. Hi,
    Nice job and idea.
    Have you considered, in order to improve the speed, not to r/w the orders in a file but keep them in memory?
    Maybe even not doing the print statements could help?!

    1. Thanks. I’ve actually updated the script so now it runs at the minimum interval supported by Binance that won’t result in a temp IP ban – 0.1s per iteration

  9. File \site-packages\requests\adapters.py”, line 516, in send
    raise ConnectionError(e, request=request)
    requests.exceptions.ConnectionError: HTTPSConnectionPool(host=’api.binance.binance_tld’, port=443): Max retries exceeded with url: /api/v3/ping (Caused by NewConnectionError(‘: Failed to establish a new connection: [Errno 11001] getaddrinfo failed’))

    What can cause this?

    Thank you.

  10. Hi there, thank you for this guide! I have a question about when you run this bot. Do you run it 5 mins before the coin is listed? 10 mins before? Does Binance automatically log you out after a certain amount of time?

  11. Hi, any explanation on the RUN_EVERY variable ? I guess it is the waiting time between two iteration, but what is the minimum allowed value authorized by Binance ?
    Ty

  12. Hi, I’m Ryuu.
    First of all, I would like to thank you for sharing the code with everyone.
    Then I want to ask you this thing, I’m new.

    I ran the latest source code on github, but the run result is only repeat as below:

    >time to get updated list of coins: 0.20345091819763184
    current amount of threads: 2

    Or I need to create the order.json file first to get the correct result?, but I don’t know how to create the content of this json file.

    Thank you.

  13. Hi,
    I cant figured out how to solve this.
    Chrome 95 is not avaible and IDK how to downgrade my ChromeDriver.
    Already install the Chromeriver for 94.0.4606.61 but not the solution.

    selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 95
    Current browser version is 94.0.4606.61 with binary path C:\Program Files (x86)\Google\Chrome\Application\chrome.exe

    Some Help

  14. I am getting this error, but it still says it is working:
    [0930/053707.821:INFO:CONSOLE(303)] “Refused to execute inline script because it violates the following Content Security Policy directive: “script-src blob: ‘self’ https://cdn.ampproject.org https://bin.bnbstatic.com https://public.bnbstatic.com ‘nonce-caae6182-f0ae-4558-8766-733bcde506da’ https://accounts.binance.com https://www.googletagmanager.com https://www.google-analytics.com https://www.google.com https://*.wistia.com https://*.wistia.net https://src.litix.io data:”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-FvCG6h3Mx+dRkp+ykkMbOOTRTJn/1nE/oam/Uh2jSfQ=’), or a nonce (‘nonce-…’) is required to enable inline execution.
    “, source: https://www.googletagmanager.com/gtm.js?id=GTM-M86QHGF (303)

    Here is the complete output:
    DevTools listening on ws://127.0.0.1:61571/devtools/browser/a757a216-1954-496b-b00d-78482d60c419
    [0930/053707.820:INFO:CONSOLE(42)] “Refused to execute inline script because it violates the following Content Security Policy directive: “script-src blob: ‘self’ https://cdn.ampproject.org https://bin.bnbstatic.com https://public.bnbstatic.com ‘nonce-caae6182-f0ae-4558-8766-733bcde506da’ https://accounts.binance.com https://www.googletagmanager.com https://www.google-analytics.com https://www.google.com https://*.wistia.com https://*.wistia.net https://src.litix.io data:”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-zmEsGdon+nUx95xWyX0cVWL8guqynuITuZm0O7szWs8=’), or a nonce (‘nonce-…’) is required to enable inline execution.
    “, source: https://www.googletagmanager.com/gtm.js?id=GTM-M86QHGF (42)
    [0930/053707.820:INFO:CONSOLE(303)] “Refused to execute inline script because it violates the following Content Security Policy directive: “script-src blob: ‘self’ https://cdn.ampproject.org https://bin.bnbstatic.com https://public.bnbstatic.com ‘nonce-caae6182-f0ae-4558-8766-733bcde506da’ https://accounts.binance.com https://www.googletagmanager.com https://www.google-analytics.com https://www.google.com https://*.wistia.com https://*.wistia.net https://src.litix.io data:”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-n6njHpSSxDkGfJLdaVOe7qBiS66DM8ZNrdWjzXmKSMg=’), or a nonce (‘nonce-…’) is required to enable inline execution.
    “, source: https://www.googletagmanager.com/gtm.js?id=GTM-M86QHGF (303)
    [0930/053707.821:INFO:CONSOLE(303)] “Refused to execute inline script because it violates the following Content Security Policy directive: “script-src blob: ‘self’ https://cdn.ampproject.org https://bin.bnbstatic.com https://public.bnbstatic.com ‘nonce-caae6182-f0ae-4558-8766-733bcde506da’ https://accounts.binance.com https://www.googletagmanager.com https://www.google-analytics.com https://www.google.com https://*.wistia.com https://*.wistia.net https://src.litix.io data:”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-FvCG6h3Mx+dRkp+ykkMbOOTRTJn/1nE/oam/Uh2jSfQ=’), or a nonce (‘nonce-…’) is required to enable inline execution.
    “, source: https://www.googletagmanager.com/gtm.js?id=GTM-M86QHGF (303)
    working…
    (534, b’5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor s23sm1445585ioe.39 – gsmtp’)
    Checking for coin announcements every 2 hours (in a separate thread)

    Is it ok, should I add the unsafe-inline keyword or something?

    Thanks!

    1. BTW Thank you for sharing this code!!! I’m new to algotrading and I’m learning a ton just from this 😀

  15. Nice Job, Congrats!

    Would be great if your bot also take in consider the “New Listings Coins” in Binance
    And search in others 2 Exchange if this coin already exist in their list, for example could be CoinBase and Kucoin exchanges

    So the idea is…
    IF this Binance new listing coin already exist in “Coinbase” list
    THEN place a buy order in “CoinBase”…

    This strategy would help us to also buy a crypto in the moment that Binance do the announcement
    Make sense?

    For example right now Binance published “RAD” coin as “New Listing Coin” and this made that the price going up from $9.36 to more than $15

    I appreciate if you let me know your comments
    Thanks

  16. **REPORT ISSUE**

    Hi Andrei
    I hope you are very well,

    I receive this error
    Do you can check please

    Exception in thread Thread-2 (search_and_update):
    Traceback (most recent call last):
    File “C:\Users\safety\AppData\Local\Programs\Python\Python310\lib\threading.py”, line 1009, in _bootstrap_inner
    self.run()
    File “C:\Users\safety\AppData\Local\Programs\Python\Python310\lib\threading.py”, line 946, in run
    self._target(*self._args, **self._kwargs)
    File “C:\Users\safety\Pictures\binance-trading-bot-new-coins-main\new_listings_scraper.py”, line 69, in search_and_update
    latest_coin = get_last_coin()
    File “C:\Users\safety\Pictures\binance-trading-bot-new-coins-main\new_listings_scraper.py”, line 33, in get_last_coin
    uppers = ”.join(item[1] for item in enum if item[1].isupper() and (enum[enum.index(item)+1][1].isupper() or enum[enum.index(item)+1][1]==’ ‘ or enum[enum.index(item)+1][1]==’)’) )
    File “C:\Users\safety\Pictures\binance-trading-bot-new-coins-main\new_listings_scraper.py”, line 33, in
    uppers = ”.join(item[1] for item in enum if item[1].isupper() and (enum[enum.index(item)+1][1].isupper() or enum[enum.index(item)+1][1]==’ ‘ or enum[enum.index(item)+1][1]==’)’) )
    IndexError: list index out of range
    [1008/074041.997:INFO:CONSOLE(0)] “Refused to load the image ‘https://www.google.co.cr/ads/ga-audiences?t=sr&aip=1&_r=4&slf_rd=1&v=1&_v=j93&tid=UA-162512367-1&cid=758976047.1633700441&jid=1020712423&_u=IEBAAEAAAAAAAC~&z=1309621841’ because it violates the following Content Security Policy directive: “img-src ‘self’ data: blob: https://static.qa1fdg.net https://sensors.binance.cloud https://bin.bnbstatic.com https://public.bnbstatic.com https://upload-bnbstatic-com.s3.ap-northeast-1.amazonaws.com https://public-1259603563.file.myqcloud.com https://static-file-1259603563.file.myqcloud.com https://www.googletagmanager.com https://www.google-analytics.com https://googleads.g.doubleclick.net https://www.google.com https://analytics.twitter.com https://t.co https://www.facebook.com https://*.wistia.com https://*.wistia.net https://embedwistia-a.akamaihd.net“.
    “, source: https://www.binance.com/en/support/announcement/c-48 (0)

    ** Also i saw different things

    1- You use the method create_margin_order
    –That was an error? Or the idea is to put some money in margin wallet?
    Because this morning i received this error when system tried to buy “BETAUSDT”
    >> code”:-3028,”msg”:”Not a valid margin pair.

    — Now im using the method create_order to get the money from SPOT wallet

    2- in line 250 you have this code
    >> order[coin[‘symbol’]] = create_order(symbol_only+pairing, volume, ‘SELL’)

    But the “Action” is set as ‘SELL’, but in this line we need to buy the coin
    So i correct it to “BUY”
    Also similar happend the line 166
    >> sell = create_order(coin, coin[‘volume’], ‘BUY’)
    I think the idea is to SELL so i correct it

    — I would like to know your comments

    Thanks

  17. How have you been going with automating the process to purchase the token on pancake swap? I already have a bot which can make the transaction on pancake swap to your metamask and I’m happy to give you that code if it helps. Would still need to automate getting the token contract address based off the symbol and also automate the transfer ( once purchased ) to your binance account wallet. Anyways, let me know if you need help.

    cheers

    Scotch

  18. Hello,

    I had a look on your code, and it’s currently running, there is one thing I don’t understand is these lines:
    else:
    print(f”Order created with {volume} on {coin[‘symbol’]}”)

    store_order(‘order.json’, order)

    The “else” when it will be executed?
    I think there are a little error on the indentation because it doesn’t coincid with an “if,for or while” condition.
    I’m wrong?

  19. It is surprising that it is very similar to the program I have been making since a month ago.
    I am facing a problem with a recently created program. If you know, please share with me.
    First of all, I saw that open source is doing web scraping in selenium way.

    I wonder how much time difference it actually takes for new listing crpyto on the site (https://www.binance.com/en/support/announcement/c-48?navId=48)

    The program I made is web scraping using the BeautifulSoup method.
    There was a difference of about 3 minutes between the actual site post and the web scraping program

    1. When done correctly, web scraping takes less than a second to fetch the content. Just call the address periodically within 1 second.

  20. Thanks for sharing this, much appreciated! 2 questions I have

    1. What is the best way to test this bot? or we just wait for new coin and see what happens
    2. How do know how much is entry cost for the new coin?

    Thanks so much
    Serg

  21. Traceback (most recent call last):
    File “main.py”, line 1, in
    from trade_client import *
    File “/Users/Utente/Downloads/binance-trading-bot-new-coins-main/trade_client.py”, line 1, in
    from auth.binance_auth import *
    ImportError: No module named auth.binance_auth

  22. No new coins detected, checking again in 1.66667e-05 minute(s)..
    New coins detected: [{‘symbol’: ‘COINBNB’, ‘price’: ‘0.00025000’}, {‘symbol’: ‘COINUSDT’, ‘price’: ‘25.00000000’}, {‘symbol’: ‘COINTRY’, ‘price’: ‘10.09000000’}, {‘symbol’: ‘COINEUR’, ‘price’: ‘0.87850000’}]
    Preparing to buy COINBTC
    Traceback (most recent call last):
    File “/Users/giancarlofoti/Development/Projects/BOT/binance1/main.py”, line 198, in
    main()
    File “/Users/giancarlofoti/Development/Projects/BOT/binance1/main.py”, line 159, in main
    price = get_price(coin[‘symbol’], pairing)
    File “/Users/giancarlofoti/Development/Projects/BOT/binance1/main.py”, line 33, in get_price
    return client.get_ticker(symbol=coin+pairing)[‘lastPrice’]
    File “/usr/local/lib/python3.9/site-packages/binance/client.py”, line 1183, in get_ticker
    return self._get(‘ticker/24hr’, data=params, version=self.PRIVATE_API_VERSION)
    File “/usr/local/lib/python3.9/site-packages/binance/client.py”, line 371, in _get
    return self._request_api(‘get’, path, signed, version, **kwargs)
    File “/usr/local/lib/python3.9/site-packages/binance/client.py”, line 334, in _request_api
    return self._request(method, uri, signed, **kwargs)
    File “/usr/local/lib/python3.9/site-packages/binance/client.py”, line 315, in _request
    return self._handle_response(self.response)
    File “/usr/local/lib/python3.9/site-packages/binance/client.py”, line 324, in _handle_response
    raise BinanceAPIException(response, response.status_code, response.text)
    binance.exceptions.BinanceAPIException: APIError(code=-1121): Invalid symbol.

    I had entered as PAIRING: USDT but it detected the first pair of the array (BTC) bringing me the error

  23. Hello,

    Trying to run the code result with error:

    File “main.py”, line 157
    print(f’updated tp: {round(new_tp, 3)} and sl: {round(new_sl, 3)}’)
    SyntaxError: invalid syntax

    Actually if I comment this out, every line including “print” will have the same error.

    Can help resolve?

    Regards

  24. Hi
    I’ve installed the scrip on a raspberry pi running raspian but I receive this error

    Traceback (most recent call last):
    File “/home/pi/Downloads/bina/Archive/main.py”, line 1, in
    from trade_client import *
    File “/home/pi/Downloads/bina/Archive/trade_client.py”, line 1, in
    from auth.binance_auth import *
    File “/home/pi/Downloads/bina/Archive/auth/binance_auth.py”, line 3, in
    from binance.client import Client
    ModuleNotFoundError: No module named ‘binance’
    >>>

Leave a Reply

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