Number of grids within the price range and their width

Viewed 80

So I'm trying to create a Binance trading grid-like structure:

My attempt:

grid_start = 2.5
grid_gap = 5

total_grids = 10

grids = 0

buy_grid_start = grid_start

buy_grids = []

# CALCULATE GRID
while True:
    if grids == total_grids:
        break
    else:
        grids += 1
        buy_grid_start += (buy_grid_start * grid_gap / 100)
        buy_grids.append(f"{buy_grid_start:0.3f}")

print(buy_grids)
print(f"Total grids: {grids}")

This just gives me 10 grids, each grid 5% above the previous grid (price).

My question is how do I get a grid structure like where you can enter Lower Price and Upper Price, and the number of grids - which will show you the percentage between each grid?

See example: enter image description here

ATTEMPT 2: 

import math

grid_start = 1.1
grid_end = 2.2

total_grids = 10
grids = 0

buy_grid_start = grid_start
buy_grid_end = grid_end

ratio = math.pow(buy_grid_start / buy_grid_end, 1 / total_grids) * 100

buy_grids = []


# CALCULATE GRID
while True:
    if grids == total_grids:
        break
    else:
        grids += 1

        buy_grid_end == buy_grid_start * math.pow(ratio, grids)

        buy_grids.append(f"{buy_grid_start:0.3f}")

print(buy_grids)
print(f"Total grids: {grids}")

Output:

['1.100', '1.100', '1.100', '1.100', '1.100', '1.100', '1.100', '1.100', '1.100', '1.100']
Total grids: 10
1 Answers

Math.


FOR LINEAR SPACING BETWEEN GRIDS

Desired equality:

grid_end == grid_start + (total_grids * grid_gap)

Solution:

grid_gap = (grid_end - grid_start) / total_grids

Depending on how you use it, might need to replace total_grids with (total_grids - 1) in the above.


FOR EXPONENTIAL ("RATIO") SPACING BETWEEN GRIDS

That is, each grid's price is multiplied by a RATIO to the previous grid's price. Or to say it another way, starting with lower_price, multiply by ratio repeatedly.

Desired equality:

upper_price == lower_price * math.pow(ratio, total_grids)

Solution:

ratio = math.pow(upper_price / lower_price, 1 / total_grids)

Expect ratio to be slightly greater than 1. E.g. 1.05 represents an increase by 5% each time.

For ratio as a percent:

ratio * 100   // %

To remove "1" from ratio, to show increase, as a percent:

grid_gap = (ratio - 1) * 100   // %

Round as desired.

NOTE: As in the Linear case, you might need (total_grids - 1) in formula.

Related