@@ -141,9 +141,12 @@ def _get_balance(self, closed_order, ignored_orders):
141
141
self .STOP : _SideBalance ()
142
142
}
143
143
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 ):
147
150
if order_util .is_stop_order (order .order_type ):
148
151
balance [self .STOP ].add_order (order )
149
152
else :
@@ -174,16 +177,30 @@ def get_actions_to_balance(self, target_balance):
174
177
return actions
175
178
to_be_reduced_amount = constants .ZERO
176
179
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
+
177
189
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
179
196
if balance - to_be_reduced_amount - order_quantity >= target_balance :
180
197
# 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 ))
182
199
to_be_reduced_amount += order_quantity
183
200
else :
184
201
# update order and stop reducing
185
202
actions [BalancedTakeProfitAndStopOrderGroup .UPDATE ].append ({
186
- BalancedTakeProfitAndStopOrderGroup .ORDER : remaining_orders .pop (0 ),
203
+ BalancedTakeProfitAndStopOrderGroup .ORDER : remaining_orders .pop (order_to_check ),
187
204
BalancedTakeProfitAndStopOrderGroup .UPDATED_QUANTITY :
188
205
target_balance - (balance - to_be_reduced_amount - order_quantity )
189
206
})
0 commit comments