Giter Site home page Giter Site logo

cyberpunkmetalhead / binance-volatility-trading-bot Goto Github PK

View Code? Open in Web Editor NEW
3.4K 146.0 775.0 110 KB

This is a fully functioning Binance trading bot that measures the volatility of every coin on Binance and places trades with the highest gaining coins If you like this project consider donating though the Brave browser to allow me to continuously improve the script.

License: MIT License

Python 100.00%

binance-volatility-trading-bot's Issues

Proper Implementation of Windowed % Increase Checking

The current code for checking for X% increase (or Z% decrease) over a Y amount of time doesn't make too much sense as it only checks at the bounds, ie it can miss increases that happen during this time period.

I'll implement this when I have the time, but basically:

keep a circular queue Q of length Y * M (eg Y in minutes, M is how many times a minute to sample the prices)
M times a minute: 
    add the current price to Q, pushing the oldest price if necessary

    lowest_price, cor_low_index = min(Q) # lowest price in Y minute window with corresponding index
    highest_price, cor_high_index = max(Q) # highest price in Y minute window with corresponding index

    # index check makes sure price is going up not down
    if ((highest_price - lowest_price) / lowest_price) * 100 >= X and cor_high_index > cor_low_index:
        # BUY coin; hit increase condition
    elif ((highest_price - lowest_price) / lowest_price) * 100 >= Z and cor_high_index < cor_low_index:
        # SELL coin as SL hit

and similarly for TP and whatnot.

This ensures that if the price goes up, say, 5% in 3 minutes rather than in 5 minutes then the bot will still jump on board. This also makes sure that you sell as soon as your SL is hit and not (in the worst case) 5 minutes afterwards when it had the chance to drop even more.

The windowed idea is great for detecting "spikes" but it just needs a bit more algorithmic massaging to get it to be correctly implemented. This more frequent checking is absolutely essential for SL though. I would set M=60 checks/min ie 1 a second. Y = 5 minutes works well.

This is a better approach than what is suggested in #65 (ie to decrease check time to seconds)

Sell before buy

Hi.

Currently, buy operation is executed first.
With limited funds, it would be better to sell first and be able to buy in same cycle.

APIERROR code 2015

APIError(code=-2015): Invalid API-key, IP, or permissions for action.

I'm guessing this is for binance.com only and not binance.us?
Is there a way to get it to work with binance.us?

APIError(code=-2010)

some transactions have more decimals than supported for some trades, a rounding function should fix this

(TESTNET) Only 6 USDT symbols found

To be clear, this is based on TESTNET data.

The following is a list of all symbols returned from client.get_all_tickers()

BNBBUSD, BTCBUSD, ETHBUSD, LTCBUSD, TRXBUSD, XRPBUSD
BNBUSDT, BTCUSDT, ETHUSDT, LTCUSDT, TRXUSDT, XRPUSDT
BNBBTC, ETHBTC, LTCBTC, TRXBTC, XRPBTC
LTCBNB, TRXBNB, XRPBNB

Should there be so few symbols available to test with?
If so, this makes it difficult to test changes as I primarily see "No coins moved more than 3% in the last 5 minute(s)".

Testnet error or script? bnb price fetch

I just tried it now on Testnet. It can't get the correct price of bnb I guess, I got this same message for 10 minutes now, the price changed for sure, it was above 560.

'TP or SL not yet reached, not selling BNBUSDT for now 558.23 - 558.23 : 0.00% '

Is this another testnet error or something might've gone wrong?

Moving average

Hi.

Nice work, thanks.

What do you think about adding MA?
Bot can query binance every 1m for instance and consider price from n last queries.

IndexError: list index out of range

For some reason I'm getting this error sometimes which throws the bot out of the loop:

Traceback (most recent call last):
File "", line 299, in
update_porfolio(orders, last_price, volume)
File "", line 267, in update_porfolio
'symbol': orders[coin][0]['symbol'],
IndexError: list index out of range

Any idea what it may be?

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

I believe this issue comes from the fact that Binance (sometimes) don't let you sell 100% of some coins.

Untitled

For example I bought 15 CTXCUSDT but can only sell 14.95 of 'em.

One workaround I propose is just sell near 100% of the actual amount the bot bought earlier.

Define this in the user input section

ACTUAL_SELL_RATIO = 99

And In the sell_coins() function:

      try:
            sell_coins_limit = client.create_order(
                symbol=coin,
                side='SELL',
                type='MARKET',
                quantity=(coins_bought[coin]['volume'] * ACTUAL_SELL_RATIO  / 100) 
            )

Also, fuck Binance.

EDIT: The workaround above causes another issues of APIError(code=-1013): Filter failure: LOT_SIZE. So please propose another solution.

Question about test order

This code references placing real orders if the test order does not throw:

if TESTNET :
# create test order before pushing an actual order
test_order = client.create_test_order(symbol=coin, side='BUY', type='MARKET', quantity=volume[coin])
# try to create a real order if the test orders did not raise an exception
try:
buy_limit = client.create_order(
symbol = coin,
side = 'BUY',
type = 'MARKET',
quantity = volume[coin]
)
# error handling here in case position cannot be placed
except Exception as e:
print(e)

In my test runs the throw crashes the app, is this expected behavior? I wouldn't expect to handle this code with a uncaught exception but instead log the exception

e.g.

if TESTNET:
    # create test order before pushing an actual order
    try:
        test_order = client.create_test_order(symbol=coin, side='BUY', type='MARKET', quantity=volume[coin])

    except Exception as e:
        print(f'An error occurred placing the test order {e}')

    #try to create a real order if the test orders did not raise an exception
    try:
        buy_limit = client.create_order(
            symbol = coin,
            side = 'BUY',
            type = 'MARKET',
            quantity = volume[coin]
        )

     # error handling here in case position cannot be placed
      except Exception as e:
          print(e)

List index out of range for orders[coin]

When update_portfolio is called, I very often get a list index out of range error and the program crashes.

  File "app.py", line 286, in <module>
    update_porfolio(orders, last_price, volume)
  File "app.py", line 228, in update_porfolio
    'symbol': orders[coin][0]['symbol'],
IndexError: list index out of range

Using my debugger, it looks like some currencies that the bot tries to buy are in the orders dict, but some don't end up going in there and are just empty.

image

I'm guessing it's an issue where the client is retrieving orders too quickly before they place on Binance's end?

crash on sell_coins

testnet

TP or SL reached, selling 0.02 BNBUSDT...
Traceback (most recent call last):
  File "Binance Detect Moonings.py", line 320, in <module>
    coins_sold = sell_coins()
  File "Binance Detect Moonings.py", line 247, in sell_coins
    test_order = client.create_test_order(symbol=coin, side='SELL', type='MARKET', quantity=coins_bought[coin]['volume'])
  File "/usr/local/lib/python3.6/dist-packages/binance/client.py", line 1762, in create_test_order
    return self._post('order/test', True, data=params)
  File "/usr/local/lib/python3.6/dist-packages/binance/client.py", line 368, in _post
    return self._request_api('post', path, signed, version, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/binance/client.py", line 328, in _request_api
    return self._request(method, uri, signed, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/binance/client.py", line 309, in _request
    return self._handle_response(self.response)
  File "/usr/local/lib/python3.6/dist-packages/binance/client.py", line 318, in _handle_response
    raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError(code=-1013): Filter failure: MIN_NOTIONAL

Add code for custom tickerlist from file tickers.txt

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

Add after end of user inputs:
#Load custom tickerlist from file tickers.txt into array tickers
tickers=[line.strip() for line in open('tickers.txt')]

Replace get_prices():

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

Can't sell because of the wrong calculated volume.

I use the livenet with 15$.

The bot bought :

Binance_PAFM66Irh0

in the .json file :

cmd_J2F5MYYQpk

when trying to sell I get insufficient amount :

cmd_DBLvnx89Tm

Binance took fees directly on the coin which decreased my volume :
image

A solution would be to check our wallet and if the volume of a coin in our wallet is below what we should have we replace it with the volume in the wallet

Suggestion - Test with Historical Live Data

Hi,
As I learned from #18 , the TESTNET data is very limited.
It would be nice to be able to run the bot against past LIVE data for more results and also not have to wait 5 minutes each time for small changes.

Suggestion: Stop buying when the bot has bought enough of the initial amount.

For example I have 200 USDT in the spot wallet and just want the bot to spend 100 USDT. I think the simplest solution is just to check the total amount in the existing portfolio before making the purchase decision. At the current version the bot has the potential to spend all of the wallet under right conditions.

I would definitely create a pull request If I knew bit of python. Unfortunately this suggestion is the best I can do. Hope this helps.

'NoneType' object has no attribute 'encode'

I get the following when the script tries to buy:

RLCUSDT has gained 9.972% in the last 5 minutes, calculating volume in USDT
CTXCUSDT has gained 7.022% in the last 5 minutes, calculating volume in USDT
TRBUSDT has gained 3.737% in the last 5 minutes, calculating volume in USDT
preparing to buy 9.17 RLCUSDT
'NoneType' object has no attribute 'encode'
preparing to buy 175.99 CTXCUSDT
'NoneType' object has no attribute 'encode'
preparing to buy 0.77 TRBUSDT
'NoneType' object has no attribute 'encode'

The coins_bought.json is there but only has "{}" written in it

IndexError: list index out of range for QUANTITY=10

Script is vanilla except for QUANTITY=10, here's the traceback:

Traceback (most recent call last):
  File "bot.py", line 284, in <module>
    update_porfolio(orders, last_price, volume)
  File "bot.py", line 226, in update_porfolio
    'symbol': orders[coin][0]['symbol'],
IndexError: list index out of range

Last echo from the script:

preparing to buy 0.089 WNXMUSDT

The script does not close the order after this.

Suggestion - show warning for live vs TESTNET

Another handy sanity check/debug idea. Could even use ANSI escape codes to make it stand out with colours!

image

else:
     print('WARNING - Using live funds!')
     client = Client(api_key_live, api_secret_live)

Binance API Exception Filter Failure: MIN_NOTIONAL

BTCUSDT has gained 8.354% in the last 5 minutes, calculating volume in USDT
 preparing to buy 0.000162 BTCUSDT
Traceback (most recent call last):
  File "Mooning.py", line 335, in <module>
    orders, last_price, volume = buy()
  File "Mooning.py", line 209, in buy
    test_order = client.create_test_order(symbol=coin, side='BUY', type='MARKET', quantity=volume[coin])
  File "/home/maxxxel/.local/lib/python3.7/site-packages/binance/client.py", line 1762, in create_test_order
    return self._post('order/test', True, data=params)
  File "/home/maxxxel/.local/lib/python3.7/site-packages/binance/client.py", line 368, in _post
    return self._request_api('post', path, signed, version, **kwargs)
  File "/home/maxxxel/.local/lib/python3.7/site-packages/binance/client.py", line 328, in _request_api
    return self._request(method, uri, signed, **kwargs)
  File "/home/maxxxel/.local/lib/python3.7/site-packages/binance/client.py", line 309, in _request
    return self._handle_response(self.response)
  File "/home/maxxxel/.local/lib/python3.7/site-packages/binance/client.py", line 318, in _handle_response
    raise BinanceAPIException(response, response.status_code, response.text)
binance.exceptions.BinanceAPIException: APIError(code=-1013): Filter failure: MIN_NOTIONAL

Max time to hold

Suggestion for a parameter that sets the max number of different coins that can be held, so that the bot not runs amok and spends all your funds on a ton of coins.

Also a parameter that sells the coin if held for longer than x minutes/hours could be useful for getting rid of stale coins that does not move.

Binance.us support

Will all of the calls work with binance.us?
As far as I can tell in the API docs, you just have to pass tld='us' when creating a new client. I can test in a day or two if you aren't able to.

Adding Telegram Bot in order to receive updates

Hey guys,

It would be great to have a telegram bot sending messages in order to keep yourself updated.
What do you think?
I could implement the solution in the next few days but not sure if it's a useful feature except for me.

IndexError: list index out of range

 ETHUSDT has gained 21.425% in the last 5 minutes, calculating volume in USDT
 preparing to buy 0.26192 ETHUSDT
Traceback (most recent call last):
  File "/Users/miguelstevens/Desktop/bot/Binance Detect Moonings.py", line 299, in <module>
    update_porfolio(orders, last_price, volume)
  File "/Users/miguelstevens/Desktop/bot/Binance Detect Moonings.py", line 267, in update_porfolio
    'symbol': orders[coin][0]['symbol'],
IndexError: list index out of range

Received this error, the console has been open for about an hour, all default settings are there, using testnet as well.

Suggestion - show wait time

Found this handy for debug/sanity

print(f'not enough time has passed yet... Waiting {TIME_DIFFERENCE} minute(s)')

image

Coins should be deleted rather than made null/None

After a coin is sold via the bot, it updates coins_bought by updating it's entry in the list to None, and it saves in the JSON file as null.

We should probably have a null check to see if the entry in coins_bought is null? I just had another crash as the bot tried to use get a previously sold coin's TP/SL by checking coins_bought, but of course the entry was None and as it tried to access some property, it threw an exception.

I'd make a pull request, but I haven't forked this repository.

Additional time difference

Is there a reason there isnt a second time difference?
In the scenario where it placed an order and it succesfully bought the coin it would make more sense to check the price for this coin/s more often than the initial time difference where it looks for a trend.

Syntax Error

syntax error - "Line 134 print(f'not enough time has passed yet...')"

any fix?

Suggestion - implement rolling profit take

Instead of taking profits on 6% gain, what about creating a new stop loss on 3% original gain? In that scenario, the order would not be sold on 6% but carry on until it hits 3% gain.

Every 5 minutes when the script checks if the price raised, it could create new stop loss instead of waiting/selling the ticker.

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

For some reason I don't understand yet - it could not sell the 2563 CKBUSDT it bought... through the binance interface i could only sell 2560 (but in the history it did buy 2563) ... does that make any sense?

CKBUSDT has gained 5.143% in the last 5 minutes, calculating volume in USDT
 preparing to buy 2563 CKBUSDT
TP or SL reached, selling 2563 CKBUSDT...
APIError(code=-2010): Account has insufficient balance for requested action.

get_all_tickers Connection Error

Hello,

when the bot is left running for some time very often an error is received deep into python request libraries:

Traceback (most recent call last):
File "C:\Users\Evgeni\Desktop\crypto\Binance-volatility-trading-bot\Binance Detect Moonings.py", line 323, in
orders, last_price, volume = buy()
File "C:\Users\Evgeni\Desktop\crypto\Binance-volatility-trading-bot\Binance Detect Moonings.py", line 190, in buy
volume, last_price = convert_volume()
File "C:\Users\Evgeni\Desktop\crypto\Binance-volatility-trading-bot\Binance Detect Moonings.py", line 154, in convert_volume
volatile_coins, number_of_coins, last_price = wait_for_price()
File "C:\Users\Evgeni\Desktop\crypto\Binance-volatility-trading-bot\Binance Detect Moonings.py", line 132, in wait_for_price
last_price = get_price()
File "C:\Users\Evgeni\Desktop\crypto\Binance-volatility-trading-bot\Binance Detect Moonings.py", line 107, in get_price
prices = client.get_all_tickers()
File "C:\Users\Evgeni\AppData\Local\Programs\Python\Python39\lib\site-packages\binance\client.py", line 568, in get_all_tickers
return self._get('ticker/price', version=self.PRIVATE_API_VERSION)
File "C:\Users\Evgeni\AppData\Local\Programs\Python\Python39\lib\site-packages\binance\client.py", line 365, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "C:\Users\Evgeni\AppData\Local\Programs\Python\Python39\lib\site-packages\binance\client.py", line 328, in _request_api
return self._request(method, uri, signed, **kwargs)
File "C:\Users\Evgeni\AppData\Local\Programs\Python\Python39\lib\site-packages\binance\client.py", line 308, in _request
self.response = getattr(self.session, method)(uri, **kwargs)
File "C:\Users\Evgeni\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 555, in get
return self.request('GET', url, **kwargs)
File "C:\Users\Evgeni\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\Evgeni\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "C:\Users\Evgeni\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 498, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

In such occasions the bot must be manually started again. Perhaps there can be a try/catch or something smarter to handle it :)

Incorrect BNB market buy price

Hi thanks for the bot. I'm running against TESTNET and changed variables to trigger a buy if coins moved more than 1% in 1 min (100USDT max). It just brought BNB since it said it gained 26.24% in the last 1 min which isn't right since that would mean it moved around $170 in the last minute. BNB price for the last hour has been between 650 and 665 so how could it move $170? The JSON said it brought it for $585.
boterr1
Timestamp for the buy: 7:17PM EST. I included a screencap. Thanks for your help!

APIError(code=-1013): Filter failure: MIN_NOTIONAL

image

I've set the vars like this:
image

This could be user error. It appears to mean the buy amount is too small?

I only have a small amount ( $50 AUD ) in binance. Is there any error handling or workarounds? Thanks!

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

I've had the bot running for a few hours, worked around #1 by adding in a sleep, so it has been successfully buying crypto. The bot hadn't had the opportunity to sell until now and it failed to sell saying insufficient balance despite attempting to sell the exact amount it bought earlier:

DOGEUSDT has gained 3.106% in the last 5 minutes, calculating volume in USDT
preparing to buy 35.2 DOGEUSDT

TP or SL reached, selling 35.2 DOGEUSDT...
APIError(code=-2010): Account has insufficient balance for requested action.

May be an issue with python-binance? Can't see a reason binance would reject that though, I'll leave it running a bit longer and see if it triggers again, if it fails again I'll try a manual sell.

APIError Timestamp for this request was 1000ms ahead of the server's time.

TRXUSDT has gained 56.956% in the last 5 minutes, calculating volume in USDT
 preparing to buy 707.9 TRXUSDT
Traceback (most recent call last):
  File "script.py", line 343, in <module>
    orders, last_price, volume = buy()
  File "script.py", line 228, in buy
    test_order = client.create_test_order(symbol=coin, side='BUY', type='MARKET', quantity=volume[coin])
  File "/home/ngetty/Binance-volatility-trading-bot/venv/lib/python3.8/site-packages/binance/client.py", line 1578, in create_test_order
    return self._post('order/test', True, data=params)
  File "/home/ngetty/Binance-volatility-trading-bot/venv/lib/python3.8/site-packages/binance/client.py", line 240, in _post
    return self._request_api('post', path, signed, version, **kwargs)
  File "/home/ngetty/Binance-volatility-trading-bot/venv/lib/python3.8/site-packages/binance/client.py", line 202, in _request_api
    return self._request(method, uri, signed, **kwargs)
  File "/home/ngetty/Binance-volatility-trading-bot/venv/lib/python3.8/site-packages/binance/client.py", line 197, in _request
    return self._handle_response()
  File "/home/ngetty/Binance-volatility-trading-bot/venv/lib/python3.8/site-packages/binance/client.py", line 230, in _handle_response
    raise BinanceAPIException(self.response)
binance.exceptions.BinanceAPIException: APIError(code=-1021): Timestamp for this request was 1000ms ahead of the server's time.

Portfolio file gets overwritten

When the coin sells the portfolio json file appears to get overwritten and there is no record of the sell transaction. I would be good to just keep appending to that file so we see a history of all buy/sells transaction details. Thanks.

close after 5 mins passed

First of all thank you for creating this awesome script, but after the update is no longer working for me.

image

It will basically closed after this this issue is not seen on the previous version. Am I missing anything on the update? thanks again.

Sell orders are not executed

Hello, when it is ready to sell, the amount it tries to sell is always more than the available amount in my account. How can I solve this type of problem? For example, Iin coins_bought.json file the volume is 37.26 and in my account the amount I own is 37.23, something like that.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.