-1

I am trying to automate cryptocurrency orders on Binance for several trading pairs. Each trading pair has a specified step size, generally 1.0, 0.1, 0.01, etc. and any order must conform to this constraint or fail. I attempt to calculate the number of coins to order by dividing the dollar amount by the current price, then adjusting for this constraint. Usually it works fine, but not always. Here's a screenshot of some data containing a list of coins with prices, steps and orders. Note item 8, which has a 1 in the last decimal place.

List of coins with prices, steps and orders

The code to calculate this is:

def calculate_order_sizes():
    for coin_dict in coin_list:
        coin_dict['order'] = coin_dict['step'] * math.floor((100/coin_dict['price'])/coin_dict['step'])

The 100 is the dollar amount I wish to order.

Bibhav
  • 1,579
  • 1
  • 5
  • 18

1 Answers1

0

Working with floats are often a bit difficult, as floats cannot in all cases be represented as you expect. This is because numbers are not base10 but base2 (in base 10 the same problem will occur with when trying to represent 1/3)

As a quick fix you could add something like this:

coin_dict['order'] = float(f'{coin_dict["order"]:.5f}')

It will give you a float with up to 5 decimal places.

You could also work with integers only, and then use the decimal module to give you a decimal number with any number of decimals. decimal module

In general I prefer using Integers only, and then converting these when needed.

greylock
  • 89
  • 4
  • Thanks, I think this has worked. Running my script has downloaded new price data so I'm not sure if some values might cause a problem, but this looks good. – Christina Norwood Nov 04 '21 at 08:01