How to code a Binance Trading bot that detects the most volatile coins on Binance

I have to admit I’m quite excited about this bot and I can’t wait to test it out. The bot that I’m about to walk you through is able to analyse the changes in price across all coins on Binance and place trades on the most volatile ones. In addition to that, this Binance trading algorithm will also keep track of all the coins bought and sell them according to your specified Stop Loss and Take Profit. 

Requirements

  • a Binance account
  • a GitHub account
  • Binance Testnet & MainnetAPI keys
  • a few python libraries
  • some knowledge of Python

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. 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. We’ll start with the mainnet keys and then the testnet keys.

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

Testnet Keys

Head over to testnet.binance.vision in order to create a testnet account.

Log In with GitHub and authenticate with your GitHub account. If you don’t have a GitHub account, simpy head over to GitHub and create one first. Once you’re logged in with your GitHub, click on Generate HMAC_SHA256 Key.

 

Give your key a description and click Generate.

Now it’s important that you SAVE your API Key and Secret displayed as for security reasons, this is the only time you will be able to see them. Simply regenerate the keys if you haven’t saved them.

Coding the Binance trading bot

UPDATE: continue following the guide below to learn how to configure the bot, but please refer to the GitHub repo for the latest version of the script.

With the Binance account and keys out of the way it’s time for the exciting part – coding our trading bot in Python! Let’s start by clearly defining the parameters of this bot:

Defining Params

  • The bot will listen to changes in price accross all Coins on Binance*
  • By default we’re only picking USDT pairs
  • We’re excluding Margin (like BTCDOWNUSDT) and Fiat pairs
  • The bot checks if the any coin has gone up by more than 3% in the last 5 minutes
  • The bot will buy 100 USDT of the most volatile coins on Binance
  • The bot will sell at 6% profit or 3% stop loss

These are all easily configurable, and I encourage you to play with these parameters around. 

Making a start on the code

Importing modules

The first thing we want to do is import the modules that we need for the script. Quick sidenote here, python-binance needs to be installed via pip by using the pip install python-binance command. If you don’t have pip on your machine, this other guide I wrote, contains some more info on how to install pip on your machine.

Configuring the Binance Client

We now need to store the Binance API keys in our script. In order to be able to easily switch between Test and Mainnet, there is a short conditional statement that will feed the Binance Client the correct keys for out bot depending on the value inside the TESTNET variable. Set this to True if you want to use the testnet, or (at your own risk) set this to False to use the Mainnet. Using the mainnet you will trade using real money from your account so be particularly careful here if you choose to do so.

Another thing to note here is the syntax for your api keys. In the code above, I am using the os.getenv method in order to call API keys that I have stored on my machine. You don’t have to do this if you’re not planning to make your code public, so simply re-write the syntax for your keys as api_key_test = “YOUR_API_KEY”

Defining user inputs

It’s time to define our user inputs – or the parameters on which our Binance trading bot will place our trades. You can modify these to change the parameters of the algorithm in order to test different strategies, by default we going with the following:

  • PAIR_WITH defines the coin (or fiat) that each crypto is paired to. I have only tested this USDT, as most coins are paired to it.
  • QUANTITY represents the size of your trade, by default in USDT. Be extra careful with the QUANTITY if you change PAIR_WITH to BNB for example.
  • FIATS is a list of fiat currencies and margin symbols that I’m excluding. Anything added here will be excluded from the coins output and won’t be traded with.
  • TIME_DIFFERENCE by default we’re checking the difference in price for each coin on Binance in the last 5 minutes, you can change this value for different results. This also dictates how often each code iteration executes.
  • CHANGE_IN_PRICE the threshold at which the bot will decide to buy a coin. By default, if a coin has moved by more than 3% in the last 5 minutes, we consider that a strong buying signal. 
  • STOP LOSS and TAKE PROFIT define in % how to sell the coins that the Binance algorithm bought.

Load Binance bot portfolio

The next step is check if the bot has placed any trades already, and if so to load the bot portfolio. By default, the bot will save each trade in a json file in the same directory as the script, so that we can keep track of trades and sell when TP or SL are reached

Get the current price for each coin listed on Binance

It’s time for our algorithm to read the price for each coin. The get_price() function will the return the price of each coin that meets our criteria.

Wait and fetch the price again

The next function will wait according to the time defined in the TIME_DIFFERENCE variable and will return any coin that has moved by more than the CHANGE_IN_PRICE – by default 3%.

Convert the volume from USDT to each of coins returned

The next step is to convert our QUANTITY of 100USDT (default) into the respective quantity for each coin that we’re about to buy. Because Binance is a bit particular with the format of the volume, our trading bot needs to know the step size for each coin. For example BTC supports a step size of 6 decimal points while XRP only supports one. So if we want to buy XRP, we need to make sure that the volume formatting is correct. Trying to buy 1.000 XRP would fail, while 1.0 would be executed.

Place the trade

Now that we have the volatile coins from Binance as well as the correct format for the volume it’s time to let our Binance trading bot to place some trades for us.

Update portfolio

You nearly did it so hand in there! The next step is to update our portfolio by saving the details of each trade into the json file that we’re checking for at the beginning of each iteration. By default, we’re saving the symbol, orderId, timestamp, buying price and volume for each coin.

You can add more info if you wish by looking at the format of client.get_all_orders(symbol=coin, limit=1) and add other information you deem necessary.

Execute sell orders

This function (the last one too!) checks if any of the coins we own in our bot portfolio should be sold due to SL or TP being reached. Note what we’re using our Spot account so we can only sell what we own.  We cannot place sell orders if a coin is going down and we don’t own it. But I would be curious to see how the Binance trading bot performs on a Futures account. 

Putting it all together

The last piece in our code brings all the functions together and makes the code to keep on executing until you stop it. 

That’s it. You have a fully functioning Binance trading bot that detects the most volatile coins on Binance, buys and sells according to each coin’s performance.

Did you enjoy this article? Please consider subscribing to the newsletter for more awesome content.

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!

111 thoughts on “How to code a Binance Trading bot that detects the most volatile coins on Binance

  1. Good day, this article is amazing, please I am really interested in setting this up but I know nothing about coding. How do I go about it?

      1. This is greeeeat. Thank you very much for your hard work.
        I faced a problem.. this error: NoneType object has no attribute ‘encode’.

  2. It finds a pair moving but i get this error: APIError(code=-1021): Timestamp for this request was 1000ms ahead of the server’s time.

    1. Had s similar error. If using Win10, go to Control Panel > Clock, Language, and Region > Date and Time > Internet Time tab > Change settings > Check that the Synchronize with an internet time server is ticked > select time.nist.gov > OK

  3. Great stuff! But noticed that the last_price for ETH-USD is showing as ~150 which surely is incorrect since ETH is trading around ~3800

  4. Hey men! I never cease to be amazed at programming and its uses, it is an excellent use. I am a beginner in the subject, and surely my error is very basic, but when I try to execute after following the steps in windows phyton gives me this error

    SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \ UXXXXXXXX escape

    1. Hey you’re welcome! Glad it’s helpful πŸ™‚

      That’s a bit of an odd one, haven’t come across this before. Have you tried running it in a Python compiler like Atom?

  5. Hi Andrei, thanks for this beautiful piece of code.

    I have tried to run this on testnet, excluding BTCUSDT and ETHUSDT pairs in order to get to other coins that made 3% in 5 minutes, as it looks to me that the first to get in the list is the one to be bought. I am currently learning to code, so I may not know what I am talking here πŸ˜‰

    All seems to run well on testnet for me until sell_coins() is called, at that time I get “TypeError: ‘NoneType’ object is not subscriptable”, which I guess is wrong indexing, or the object it is indexing does not have the correct attributes and the json output looks like this: { “BNBUSDT”: null }, as BNB was bought previously.

    I am not sure if this is the case only on testnet, but how do I fix this?

    Here is the print from terminal: https://pastebin.com/9gB1ftXV

    1. Hi there!

      I’m unable to replicate your issue but could you try changing the way you store information from the last order in the update portfiolio function to be:

      'symbol': orders[coin][-1]['symbol'],
      'orderid': orders[coin][-1]['orderId'],
      'timestamp': orders[coin][-1]['time'],
      'bought_at': last_price[coin]['price'],
      'volume': volume[coin]

      Let me know if this fixes your issue

      1. Tested and I got the same error. I will run the bot from my laptop and latest commit. Thanks for helping out.

        1. This is the json I saved from before. Bought BTC and later BNB, then tried to sell BNB, got the same error.

          {
          “BTCUSDT”: {
          “symbol”: “BTCUSDT”,
          “orderid”: 1557333,
          “timestamp”: 1620546409628,
          “bought_at”: “57874.69000000”,
          “volume”: 0.001728
          },
          “BNBUSDT”: null
          }

      2. I think I got a similiar error. Im using your latest version from Github. I was on Mainnet and sadly not in the IDE so I didn’t see the error message when the bot crashed. But I had a buy that went through successfully and then it crashed, I think when it tried to execute the sell.

        I am testing now in testnet with your suggested fixes, will update this if I get a new trade

        1. as an addition: my “coins_bought” json file es empty even though it executed one trade (or am I opening it wrong? I just opened it with a text editor, in only has {} in it)

      3. Yeah, i’ve got the same issue. Saw your reply on github that you found a solution to this problem, i’m waiting for the update. Thank you!

  6. Thanks for the script! I’m printing out prices in get_price() and, strangely, on the testnet only six pair-quotes are given and only BTC seems to move at all. The ETH price is also clearly off. Is this a limitation of the test net? Or is something not working in the script? Since the prices don’t move, nothing else happens. Did I possibly configure it in the wrong way?

    BNBUSDT 585.47000000
    BTCUSDT 58783.65000000
    ETHUSDT 190.57000000
    LTCUSDT 200.00000000
    TRXUSDT 0.12642000
    XRPUSDT 1.15080000

    BNBUSDT 585.47000000
    BTCUSDT 58766.47000000
    ETHUSDT 190.57000000
    LTCUSDT 200.00000000
    TRXUSDT 0.12642000
    XRPUSDT 1.15080000

    1. In case someone else has the same question: apparently the wrong quotes and the limitation to six pairs are a limitation of the testnet. I commented the actual order parts out and used the mainnet to see what happens “readonly”, the quotes and calculations appear to work correctly.

    2. No you configuration is correct judging by your output. The testnet is quite restrictive and also slow! I have been running my instance on the mainnet and the numbers and % increases seem fine so it’s more likely the testnet πŸ™‚

  7. Another quick feedback:

    I changed the pricechange to 1% to get test orders quicker. I am not 100% sure, but I think its kind of weird that the bot thinks that there were no pairs that changed by 1 % in the first 20 minutes because my intuiton tells me that there should be plenty.

    It also reported a 25% price increase in BNB/USDT that i can’t find on the charts (such an increase would be massive news as well)

    I’m using your latest commit from github.

    No coins moved more than 1% in the last 5 minute(s)
    not enough time has passed yet…
    No coins moved more than 1% in the last 5 minute(s)
    not enough time has passed yet…
    No coins moved more than 1% in the last 5 minute(s)
    not enough time has passed yet…
    No coins moved more than 1% in the last 5 minute(s)
    not enough time has passed yet…
    No coins moved more than 1% in the last 5 minute(s)
    not enough time has passed yet…
    No coins moved more than 1% in the last 5 minute(s)
    not enough time has passed yet…
    BNBUSDT has gained 25.641% in the last 5 minutes, calculating volume in USDT
    preparing to buy 0.17 BNBUSDT
    TP or SL not yet reached, not selling BNBUSDT for now…
    not enough time has passed yet…
    No coins moved more than 1% in the last 5 minute(s)
    TP or SL not yet reached, not selling BNBUSDT for now…
    not enough time has passed yet…
    No coins moved more than 1% in the last 5 minute(s)

    1. If you’re using the testnet, it only supports a very small amount of coins, and the price doesn’t seem to be updated as often as the mainnet. Not great for testing.

  8. Thanks for this bot. Looks great. Would you happen to know if this works with Binance US as well, or will it only function against Binance (not the US version)?

    Also, can the pairing be changed to USD as opposed to USDT?

    1. Yes, it should work with the US api, you just need to add an additional parameter in to the Binance Client like so client = Client(api_key, api_secret, tld='us')

  9. I am running in testnet with default settings, and something interesting occured.

    It reported BNBUSDT increase of 10.114%

    It’s nowhere near that by looking into the candle chart

    Here’s the log:

    {
    “BNBUSDT”: {
    “symbol”: “BNBUSDT”,
    “orderid”: 1798324,
    “timestamp”: 1620638361214,
    “bought_at”: “658.60000000”,
    “volume”: 0.15
    }
    }

    Why did it execute the trade?

    1. I’ve seen this before and I can only conclude that the testnet is unreliable in providing information, I’ve been letting it run on the mainnet and these issues are not present on there.

      1. I had the idea as well and found this GitHub, sadly my Python skills are way too bad to implement it myself πŸ˜€

  10. Hi,

    Thanks for sharing the bot!!

    I’ve only been running it on the Testnet, but I always get the following error,

    “TP or SL reached, selling 0.000209 BTCUSDT…
    APIError(code=-1013): Invalid quantity.”

    If I change the QUANTITY set (I’ve tried between 100 ~ 1000), the size of the trade remains the same and I still get the error.

    Thoughts?

    Cheers!

  11. Hey,

    I just tested your latest GitHub release on the Mainnet. Everything looks good, but the only sell it tried to execute so far fails due to a Lot size error, it seems like the problem is still there.

    TP or SL reached, selling 525072.0 SHIBUSDT…
    APIError(code=-1013): Filter failure: LOT_SIZE

    Since its only one coin that the bot tried to sell so far, im not sure if its a specific problem or a general one

  12. Hello, thanks for sharing and updating this. i just started trying it out but have some questions. If bot already bought some coin and my internet connection or electricity cuts out do i have to sell them manually? Does it break bot even if connection stops for 10 seconds ?

    1. Each coin bought by the bot is saved on a local file so you should be able to perform an action on the coins bought even if the script is stopped and then restarted

  13. Hey Andrei, after asking so many questions I wanted to give some feedback as well.

    I gave the bot $70 to play with and ran it on the Mainnet for 3 hours (so not even close to statistical relevance) with the standard settings (except $20 order size) , here are my thoughts:

    1: The bot bought 12 coins (some more than once) and lost around $1.50 doing so πŸ˜‰ but it’s for science!

    2: The bot works very well now, didn’t get any problems / exceptions, even with coins that failed due to Lot_Size before.

    3: The idea of tracking all coins sounds good at first, but I found out that most of my trades were coins with low market cap /24h volume. Therefore the 3% increase in 5 minutes was not a bullish signal but rather a large buy order that alone pushed the price up significantly. The bot ended up losing money on almost all these trades because these buys didn’t lead to a sustainable price increase. Furthermore, the bot like these small coins a lot. It bought for example SHIB / USDT 3 times in 3 hours and hit the stop loss every time. Is there a way to limit the tracked coins to like the top 100 – 150 or so? I feel like it could be interesting to compare the results. This would lead to less orders, but I think those orders would have a higher chance to be profitable.

    4: The 5 minute timeframe between the initial buy and the first target price / stop loss check is too high in some circumstances, especially with the low market cap coins described in #3. In the SHIB / USDT case the bot could have made a profit if it had sold earlier.
    Right now the bot execute the sell orders manually. Would it be possible to do this over the Binance API as well? It has the functuality to place OCO (one cancels other) orders (search for “New OCO (TRADE)” in https://binance-docs.github.io/apidocs/spot/en/#all-orders-user_data). That means the bot would place a limit sell & stop loss order automaticially right after buying a coin. If one of these orders gets filled, the other one is cancelled by itself. Sadly my Python skills are way too bad to try it myself, this would prevent the situation were the price rises after the buy but decreases again before 5 minutes are over. I might give it a try and see what I can do with it later, but I’m not expecting much.

    5: Of course the best thing ever would be a trailing stop loss, but afaic this is something not native to the binance API, so you would have to code it yourself (I found this example but it’s using ccxt)

    6: Thank you so much for your awesome work! Even if I don’t end up making money with this, it really helos my Python skills πŸ˜‰

    1. This is some great feedback, thanks for that.
      1. Yep I had the same happening to me as well. I ran the bot on 1 minute and 1.5 change. Like you it Picked SHIBUSDT several times and lost money in it every time.
      2. I’m sometimes getting an error that the timestamp of my request is 1000ms in the future from Binance servers so looking into this one atm.
      3. I agree, low volume coins seem to pump and immediately dump. Something like that would be useful, trying to tinker with the existing params at the moment. Ideally the bot would find volatile mooning coins that gain double digits in a matter of minutes. But’s it proving to be a bit tricky to discover those.
      4. I agree, I have adjusted my timeframe to be 1 minute and it’s much quicker to react. I have to read more about OCO as there’s something about it my brain can’t process right now haha. Would it place a limit sell and stop loss on a buy position, or how would it work?
      5. yep, this for sure. I actually built a trailing stop once for a MetaTrader5 bot, and it actually worked pretty well.
      6. You’re welcome, thank you for your feedback and especially for testing the bot alongside me. πŸ™‚

      1. hey! great to have such a quick answer!

        I just ran into a little bug / problem. After buying some Theta coins, the terminal said “Binance is being slow in returning the order, calling the API again…” about 300 times. The order was filled on binance, but the bot was stuck calling the API, which stopped its function completly for several minutes until I manually shut it down. Maybe implement some kind of exception when the API call fails for like 10 times?

        To the actual points:
        2: I had the same problem earlier. I had to change my internet time (on win 10: system settings, date & time, internet time) to time.nist.gov instead of the windows time. Since then I havn’t gotten the error.

        3: Hah if it would be easy to detect those I would be rich.. Funnily enough without even knowing that weird SHIB coin, I was once of the first to buy it, I guess it was listed on binance today and my 5 minute window perfectly aligned with the launch. Noticed it and sold that buy manually, actually made a decent profit πŸ˜€ (https://www.binance.com/de/trade/SHIB_USDT?type=spot). Sadly the bot was so impressed by this that it bought it 3 more times afterwards, running in the stop loss every time πŸ˜€

        4: Yes exactly. A OCO places a limit sell order and a stop loss order at the same time. If one of them executes, the other one is deleted automaticially. Quick example: Bot buys a coin for price $100. It then can instantly place a limit sell using the OCO API function at for example +10% / $110 and a stop loss at -5 / $95. Both orders are created at the same time and if either one of them is filled the other one cancels (hence “once cancels other” ;). since the bot could place the OCO order right after the buy, it could realize profits after a few seconds already and wouldn’t be forced to wait for whatever time was input.

        1. Hi Finn

          I am MANUALLY doing something similar to this bot strategy currently, so VERY interested in this bots progress.

          3# – I use Simple Crypto Scanner, it’s an Android app that allows me to scan 217 USDT pairs(exact same format as Andrei has done), it scans pairs every 60 seconds, but presents the information in real-time only every 5 minutes. What I do is look for -2.5% to +2.5% range eg. REEF/USDT at 16.40hrs is -2.9%, at 16.45hrs the same pair is +3.2%….IF the bot starts at +3% increases, it is highly unlikely it will ever deliver consistent profits….it MUST buy at the first sign that the pair is uptrending from -2.9% to +3.2%….that way even if the coin only adds a slight amount more to it’s price, the BULK of the price action would be caught.

          IF the aggregated coins could be shown sub 5 minutes, then that would be a huge benefit….this is scalping, and 5 minutes DISCOVERY is a luxury!.

          A trailing Stop Loss would also be a HUGE benefit!.

          1. Addendum:

            Here is a practical example of the crypto app: https://1drv.ms/u/s!ArqVf9y2kIi9lrZORTfbT8MuPCgIiA?e=864nVg STFP/USDT at 19.34 hours showed as -2.99%…..the same pair again shows at 19.36 hours at +2.74%….IF you can find these pairs at the earliest possible point there is 5%-6% profit per bot action.

            An additional point regarding coin pairings multiple use per day….if you were able to preset a time window whereby a coin pairing was not used eg. 12 hours apart, so as to avoid overkill….

          2. That’s cool, and I agree with your point regarding the 3% signal, I did some testing the past few days and most coins tend to lose their momentum after a quick jump like that and is almost always followed by a correction. I’m now checking for 0.5% increases every 20 seconds.
            And yes, it’s on my list to try building a trailing stop loss for it at some point πŸ™‚

      2. A small addition to the OCOs because I just looked up how they work because I was a bit confused as well

        You need to specify several parameters.

        For the limit sell order:
        1: Price for the limit sell order (or buy order but I guess we are only interested in the sell orders for now)

        For the Stop Order:
        1: Stop – the price at which your limit sell order for the stop loss is created
        2: Limit: – the price of your limit stop loss order
        3: Amount – well, the amount you want to sell. Obviously amount for limit sell and stop loss are the same.

        Quick example again:

        Bought a coin at $100. Set a OCO with limit sell $110, Stop $95.5 and Limit $95. If the prices goes over $110, the limit sell order executes and the stop loss part is cancalled. If the price drops below $95.5, a limit sell order at $95 is created and the initial limit sell at $110 cancelled.

        https://academy.binance.com/en/articles/what-is-an-oco-order

          1. exactly. The bot buy like always manually and places the OCO order right after. The sell side is then managed by Binance via the OCO order. You can crate OCO orders manually while trading on Binance as well (I use them regularly), the only difference is that in our case the bot would place them via the api

        1. The problem with OCO is that it uses limit prices and not market prices.
          If the price is increasing and the bot sets the limitprice to the market price, it would not trigger before the price of the asset comes down again.

        2. Hi Finn

          Did you ever progress your thoughts any further in terms of a Limit Buy / Sell / OCO version of Andrei’s bot?. It is something that has been briefly discussed over on the BVT Bot Discord Group: https://discord.gg/bJDWfyYJ if you are not already a member, come on over & let’s chat about it?.

          Regards
          Kevin

  14. Hi Andrei,
    Thank you for your script.
    I have a doubt: in line 139 I see:

    threshold_check = (float(last_price[coin][‘price’]) – float(initial_price[coin][‘price’])) / float(last_price[coin][‘price’]) * 100

    shouldn’t it be:

    threshold_check = (float(last_price[coin][‘price’]) – float(initial_price[coin][‘price’])) / float(initial_price[coin][‘price’]) * 100

    Thank you,
    Alfredo

    1. Hi Alfredo, I believe you are correct. Looks like I mixed up the numbers in the % calculation formula! I have just pushed the new update to GitHub, thanks for pointing that out!

  15. Hi Andrei,

    Thanks for a nice initiative.
    I agree with most of Finn’s suggestions and would like to add:
    Is it possible for the sell function to query the balance of the coin to sell, and if the balance is lower than the sell amount it would adjust the sell amount to actual balance?

    Also i think its better to pull all pairs to be checked from a file where one could have the 100-150 coins with the highest cap or your own custom list.

    As it is now, it mostly buy low cap coins to sell them at loss after a small pump.

    Richard

    1. Hi Richard, that is a good point. Though I have tried the query strategy and it returns the same amount that we hold. I think I may have figured out what the problem is thought. I’ve been testing a tweaked version for the past 6 hours and I’m not seeing any errors so far so it’s looking good.

    1. Hi Richard

      I understand the logic of the security that the top 100 market caps provides….but surely as this project is all about volatility, the best option would be either Andrei’s idea of all USDT coin pairings on Binance – fiat & margin pairs or allow the user to create & upload their own custom lists, that way each user has the ability to satisfy their own risk & reward strategy?.

      And, the reality is that if I wanted to consistently hit 100 bot runs daily EACH ideally generating a 3% profit return within minutes of activation….then the top 100 coins would not provide that option.

      Currently using a very similar system to what Andrei has coded the vast majority of my coin pairings range from top 100 – 250….yes the risk is that the pumps are short lived, but that is all we need IF we can enter as close to the bottom as possible, this is not about grid trading, it is purely a “smash & grab” at the most advantageous time.

  16. If you want to use a custom ticker list, you can use the following code:

    Under user inputs add:
    #Use custom tickers.txt list for filtering pairs
    CUSTOM_LIST = True

    After end of user inputs add:
    # Load custom tickerlist from file tickers.txt into array tickers
    tickers=[line.strip() for line in open(‘tickers.txt’)]

    Replace def get_price() with:
    def get_price():
    ”’Return the current price for all coins on binance”’

    initial_price = {}
    prices = client.get_all_tickers()

    for coin in prices:

    # Only return USDT pairs and exlcude margin symbols like BTCDOWNUSDT, filter by custom list if defined.

    if CUSTOM_LIST:
    if PAIR_WITH in coin[‘symbol’] and any(item in coin[‘symbol’] for item in tickers) and all(item not in coin[‘symbol’] for item in FIATS):
    initial_price[coin[‘symbol’]] = { ‘price’: coin[‘price’], ‘time’: datetime.now()}
    else:
    if PAIR_WITH in coin[‘symbol’] and all(item not in coin[‘symbol’] for item in FIATS):
    initial_price[coin[‘symbol’]] = { ‘price’: coin[‘price’], ‘time’: datetime.now()}

    return initial_price

  17. The bot is not selling anything on test net, getting this:

    TP or SL reached, selling xxxxxxx…

    APIError(code=-1013): Invalid quantity.

    Any idea on how to get this fixed?

  18. Andrei,

    I’m getting this error:
    TP or SL reached, selling 0.000174 YFIUSDT – 74800.0000 – 72524.1300 : -3.04%
    APIError(code=-1013): Invalid quantity.

    Is it a decimal error?

      1. I doubt it, with a price of 74 800 USD that would mean a minimum sell of 740 800 USD.
        I managed to sell it normaly via the web interface.

  19. Also i have been thinking about trailing stop loss, and it should not be very hard to implement.
    We need an array: highest_price {} that is initially set equal to bought_price.

    When we later check the prices, if current price is higher than highest_price, we change highest_price to current price.

    We then check current price agaist highest_price and if the difference is negative greater than trailing stop loss %, we sell.

    The highest_price should also be stored in the json file.

    What do you think Andrei?

    1. That sounds like it would work. Thought my only feedback here is that, we probably need to start off with a fixed TP (let’s say 3%), and only once the current price is approaching this threshold, we can change it over to a trailing stop, otherwise I imagine you would end up closing some trades on very small gains like 0.40%. I did a trailing stop on MetaTrader once and that’s what ended up happening.

      Or rather, we only move the stop loss in 2% increments, always following the price -2%

      1. Yes, it would need some initial values to work as intended.

        Also there is a slight issue with polling the prices at x minutes. One could be unfortunate and hit a random spike or drop in price. Hence the price should be an average based on smaller timeframes. I don’t know if 1 second is realistic, but a one minute reading should at least consist of 6 polls averaged.

        Lastly there is a bug in my custom list function. If for example ZRX is in the list, it will also accept coin BZRX because ZRX is part of its name. I have not touched Python in a long time, is this an easy fix for you, otherwise i’ll look into it.

        Great work so far πŸ™‚

        1. Should be able to fix that with an additional filter in the condition statement, I can look into it. However, I’m not sure why yet, but it seems that the custom list might not be working as intended. The script bought BARUSDT though that’s not on the list, looking into it now. Thanks for the contribution πŸ™‚

          1. It’s beacuse there is a coin called AR (Arweave) in the list. So it does a partitional match wich it should not πŸ™‚

  20. When trying to sell I get this error…..

    APIError(code=-2010): Account has insufficient balance for requested action.

    Why would this be?

    1. Could be because the script is trying to sell an amount that doesn’t take into account the commission fee. I’m working on a fix for this. Does it happen on all the sells?

      1. Yes it does. I will load some funds into BNB in the interim and allocate 100% of marin and transaction fees from BNB to see if that fixes. Cheers.

  21. Andrei, is it possible to make a function that instead of TP at 6%, checks if the last_price went higher (ex. 8% or more) and update the initial_price to that amount and restart the comparison from there to TP os SL?

    something like

    If
    last_price >= initial_price*1.06 AND if last_price >= initial_price*1.08
    def initial_price = last_price
    else
    sell_coins_limit = client.create_order
    side=’SELL’

  22. Hello,
    I am currently running the program. I had no problem in buying coins however when it reached stop loss level and initiated sell order, it couldn’t complete and gave error:
    TP or SL reached, selling 17.88 BZRXUSDT…
    APIError(code=-2010): Account has insufficient balance for requested action.

    When I looked into my account, I realized I didn’t have 17.88 BZRX, I had 17.86. The 0.02 went to fees.
    Did anyone get any similar error, how to solve this?

      1. Since it deducts the commision while buying, which is 0,1% – 5%(kickback), that is 0,095%, while calculating the sell order quantity, I deducted buy price * 0,00095 from the buy price. I’ll try it and see if it works.
        However since commision will not be same for everyone, it can be more complicated to solve this for everyone.
        Maybe if there’s a way to get the current commision percent from Binance server and deduct it using a parameter?

  23. If you keep a small amount of BNB and enable pay fees with BNB you will not have this problem. There is also a 25% discount when paying fees with BNB.

    1. Even though I have enough BNB and transactions fees enabled to use BNB, I keep getting the same error, have you found a way to solve this?

  24. Anyone found a set of params that returns a consistent gain over a period of time – even if small.

  25. I’m still getting error:
    APIError(code=-2010): Account has insufficient balance for requested action.

    I made sure to have BNB tokens available and BNB fees at transaction enabled.
    Have you guys found a way to solve this?

    1. Hi, which version of the code are you currently using? There have been some improvements to the GitHub repo that aim to solve this issue.

  26. Hi Andrei,
    it s really fun to experiment with the bot, also it s not making profit at all (but also no big loss).
    There happened a bigger change in the code yesterday, can you explain a little?
    Thanks a lot !

      1. Hi Andrei

        Is there a point whereby the project is finally completed?….there is such a huge amount of interest and excitement from within the Discord Group, testing and changes being constantly made, the updates are almost impossible to keep up with….WHEN it is completed, will you incorporate all the new updates into your original “how to” article?.

        Regards
        Kevin

  27. Hi, I don’t know why but I always have this error with testnet “APIError(code=-1022): Signature for this request is not valid.” but my api key and secret key is all good.
    Do you have an issue for this ?

  28. Hey, I’m running into my issues – I’m running it on TestNet and I’ve altered for params for testing purpose i.e. the Time changed it from 5 mins to 1 min and the gain (%) from 3% to 1% and I seem to be getting no results..

    Press Ctrl-Q to stop the script
    not enough time has passed yet…
    No coins moved more than 1% in the last 1 minute(s)
    not enough time has passed yet…
    No coins moved more than 1% in the last 1 minute(s)
    not enough time has passed yet…

  29. Thank You So Much!!! Amazing work ‘A’. However, because I am a beginner in the programing world, I have hit a milestone I am not able to fix by myself. Could you please guide me

    Press Ctrl-Q to stop the script
    Traceback (most recent call last):
    File “c:\Users\cellt\OneDrive\Desktop\RSI-Trading Bot\Binance\Binance.py”, line 255, in
    orders, last_price, volume = trade()
    File “c:\Users\cellt\OneDrive\Desktop\RSI-Trading Bot\Binance\Binance.py”, line 163, in trade
    volume, last_price = convert_volume()
    File “c:\Users\cellt\OneDrive\Desktop\RSI-Trading Bot\Binance\Binance.py”, line 128, in convert_volume
    volatile_coins, number_of_coins, last_price = wait_for_price()
    File “c:\Users\cellt\OneDrive\Desktop\RSI-Trading Bot\Binance\Binance.py”, line 100, in wait_for_price
    while initial_price[‘BNBUSD’][‘time’] > datetime.now() – timedelta(minutes=TIME_DIFFERENCE):
    KeyError: ‘BNBUSD’

    1. I think I Fixed it with your GitHub Fixes

      Thank You

      If I need further assistance, I will make sure to bother you again :))

  30. Hi.

    This tool looks amazing. I would be interested how many periods do you consider for the volatility? I mean that I did not find any standards for this, but not sure what is the usual? Is it 20?

    Thank you.
    Wooster

  31. Hi, I tried to run the bot, but the compiler returns this:

    NameError: name ‘trade’ is not defined
    Press Ctrl-Q to stop the script

    Also, yes this is my first program ever

Leave a Reply

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