its task is that it should not close the grid orders until the close request is not sent.
now this is the way I want the grids to work.
- the entry price should also be counted inn the grid
- if the Entry order is ‘buy’, whenever it touches a high level grid price, it should sell (as the levels are already given in the signal. same for the buy if it touches the lower level. the high levels will be called favor levels and lower levels will be called against level
- if the entry order is ‘sell’, it should be opposite of the buy. whenever it touches a high level grid price, it should sell (as the levels are already given in the signal. same for the buy if it touches the lower level. the high levels will be called against levels and lower levels will be called favor level.
- if one grid level is touched, it should open a opposite order on the previous level. including the entry level.
- 1 level should only have 1 order placed until any other level is breached.
this is my current code which has alot of issues. fix that for me
Issues:
It doesn’t open any order on the previous level when a grid level is breached
if i add to open the order, it executes multiple orders at the same level
It has some unique features than the normmal grid
- when the entry order is ‘buy/long’ it will name the high level as ‘favor_levels’ and lower grid levels to ‘against_level’. It same but opposite for the ‘sell/short’ entry order
def monitor_grid_orders(symbol, side, qty, entry_price, favor_levels, against_levels, favor_qty_percentage,
against_qty_percentage):
levels = [entry_price] + favor_levels + against_levels
levels.sort()
last_breached_index = -1 # Track the index of the last breached level
last_price = None
while True: # Infinite loop to continuously monitor
try:
current_price = bybit.fetch_ticker(symbol)['last']
print(f"Current price: {current_price}")
if current_price != last_price:
for i in range(len(levels)):
level = levels[i]
if (side.lower() == 'buy' and level <= current_price) or (
side.lower() == 'sell' and level >= current_price):
if i > last_breached_index:
print(f"Level breached: {level}")
last_breached_index = i
quantity = qty * (favor_qty_percentage / 100) if side.lower() == 'buy' else qty * (
against_qty_percentage / 100)
if side.lower() == 'buy':
if i == 0:
# Open sell order at entry price
bybit.create_order(symbol, 'limit', 'sell', quantity, entry_price)
else:
# Open buy order at the breached level and sell at previous level
bybit.create_order(symbol, 'limit', 'buy', quantity, levels[i])
bybit.create_order(symbol, 'limit', 'sell', quantity, levels[i - 1])
else: # side.lower() == 'sell'
if i == 0:
# Open buy order at entry price
bybit.create_order(symbol, 'limit', 'buy', quantity, entry_price)
else:
# Open sell order at the breached level and buy at previous level
bybit.create_order(symbol, 'limit', 'sell', quantity, levels[i])
bybit.create_order(symbol, 'limit', 'buy', quantity, levels[i - 1])
print('Orders placed.')
break # Exit loop after placing one order per price level
last_price = current_price
time.sleep(1.5)
except Exception as e:
print(f"Error: {str(e)}")
time.sleep(1)
@api_view(['POST'])
def open_grid_orders(request):
if request.method == 'POST':
data = request.data
secret = data.get('secret')
if secret != config.secret:
return Response({'error': 'Invalid secret'}, status=status.HTTP_400_BAD_REQUEST)
try:
order = extract_grid_data(data)
symbol = order['symbol']
order_type = order['orderType']
side = order['side']
qty = float(order['qty'])
price = float(order['price'])
favor_levels = [float(level) for level in order.get('favor_levels', [])]
against_levels = [float(level) for level in order.get('against_levels', [])]
percentage_difference_favor = order['percentage_difference_favor']
percentage_difference_against = order['percentage_difference_against']
# Open initial order
bybit.create_order(symbol, order_type, side, qty, price)
# Open grid orders
for level in favor_levels:
level_price = float(level)
qty_percent = qty * (percentage_difference_favor / 100)
# Place sell orders at favor levels
bybit.create_order(symbol, 'limit', 'sell', qty_percent, level_price)
for level in against_levels:
level_price = float(level)
qty_percent = qty * (percentage_difference_against / 100)
# Place buy orders at against levels
bybit.create_order(symbol, 'limit', 'buy', qty_percent, level_price)
# Start monitoring orders in a separate thread
monitoring_thread = threading.Thread(target=monitor_grid_orders, args=(
symbol, side, qty, price, favor_levels, against_levels, percentage_difference_favor,
percentage_difference_against))
monitoring_thread.start()
save_order_to_db(order)
return Response({'success': 'Grid orders created and monitoring started successfully'},
status=status.HTTP_201_CREATED)
except Exception as e:
return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
I am expecting that it satisfies the above conditions. I tried from chat-gpt which was a mistake obviously and tried myself few changes but none of them works