Skip to content

Commit 7742bd9

Browse files
committed
[OrderGroup] try to find matching quantity first
tmp
1 parent 9b1f996 commit 7742bd9

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

octobot_trading/personal_data/orders/groups/balanced_take_profit_and_stop_order_group.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -141,9 +141,12 @@ def _get_balance(self, closed_order, ignored_orders):
141141
self.STOP: _SideBalance()
142142
}
143143
for order in self.get_group_open_orders():
144-
if order is not closed_order \
145-
and (ignored_orders is None or order not in ignored_orders) \
146-
and order not in self.balancing_orders:
144+
if ((not closed_order
145+
or order.order_id is not (closed_order.order_id
146+
if closed_order
147+
else None))
148+
and (ignored_orders is None or order not in ignored_orders)
149+
and order not in self.balancing_orders):
147150
if order_util.is_stop_order(order.order_type):
148151
balance[self.STOP].add_order(order)
149152
else:
@@ -174,16 +177,30 @@ def get_actions_to_balance(self, target_balance):
174177
return actions
175178
to_be_reduced_amount = constants.ZERO
176179
remaining_orders = list(self.orders)
180+
amount_to_reduce = balance - target_balance
181+
182+
# try to find order with the same quantity
183+
matching_quantity_order_index = None
184+
for index, order in enumerate(remaining_orders):
185+
if order.origin_quantity == amount_to_reduce:
186+
matching_quantity_order_index = index
187+
break
188+
177189
while remaining_orders and balance - to_be_reduced_amount > target_balance:
178-
order_quantity = remaining_orders[0].origin_quantity
190+
if matching_quantity_order_index is not None:
191+
order_to_check = matching_quantity_order_index
192+
matching_quantity_order_index = None
193+
else:
194+
order_to_check = 0
195+
order_quantity = remaining_orders[order_to_check].origin_quantity
179196
if balance - to_be_reduced_amount - order_quantity >= target_balance:
180197
# cancel order and keep reducing
181-
actions[BalancedTakeProfitAndStopOrderGroup.CANCEL].append(remaining_orders.pop(0))
198+
actions[BalancedTakeProfitAndStopOrderGroup.CANCEL].append(remaining_orders.pop(order_to_check))
182199
to_be_reduced_amount += order_quantity
183200
else:
184201
# update order and stop reducing
185202
actions[BalancedTakeProfitAndStopOrderGroup.UPDATE].append({
186-
BalancedTakeProfitAndStopOrderGroup.ORDER: remaining_orders.pop(0),
203+
BalancedTakeProfitAndStopOrderGroup.ORDER: remaining_orders.pop(order_to_check),
187204
BalancedTakeProfitAndStopOrderGroup.UPDATED_QUANTITY:
188205
target_balance - (balance - to_be_reduced_amount - order_quantity)
189206
})

0 commit comments

Comments
 (0)