Skip to content

Commit

Permalink
Fix bot logs
Browse files Browse the repository at this point in the history
  • Loading branch information
carkod committed Sep 24, 2024
1 parent 08e4be4 commit 9651e56
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 32 deletions.
14 changes: 7 additions & 7 deletions api/deals/margin.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

class MarginDeal(BaseDeal):
def __init__(self, bot, db_collection_name) -> None:
self.active_bot: BotSchema
# Inherit from parent class
super().__init__(bot, db_collection_name=db_collection_name)
self.base_producer = BaseProducer()
Expand Down Expand Up @@ -92,15 +93,15 @@ def cancel_open_orders(self, deal_type):
self.update_deal_logs(
"Old take profit order cancelled", self.active_bot
)
except HTTPError as error:
except HTTPError:
self.update_deal_logs(
"Take profit order not found, no need to cancel", self.active_bot
)
return

except Exception as error:
except BinanceErrors as error:
# Most likely old error out of date orderId
if error.args[1] == -2011:
if error.code == -2011:
return

return
Expand Down Expand Up @@ -317,7 +318,6 @@ def terminate_margin_short(self, buy_back_fiat: bool = True):
try:
# get new balance
self.isolated_balance = self.get_isolated_balance(self.active_bot.pair)
print(f"Transfering leftover isolated assets back to Spot")
if float(self.isolated_balance[0]["quoteAsset"]["free"]) != 0:
# transfer back to SPOT account
self.transfer_isolated_margin_to_spot(
Expand Down Expand Up @@ -563,7 +563,7 @@ def execute_stop_loss(self):
self.active_bot.deal.buy_total_qty = res["origQty"]
self.active_bot.deal.margin_short_buy_back_timestamp = res["transactTime"]

msg = f"Completed Stop loss order"
msg = "Completed Stop loss order"
self.active_bot.errors.append(msg)
self.active_bot.status = Status.completed
self.active_bot = self.save_bot_streaming(self.active_bot)
Expand Down Expand Up @@ -616,10 +616,10 @@ def execute_take_profit(self):
self.active_bot.deal.margin_short_buy_back_price = res["price"]
self.active_bot.deal.margin_short_buy_back_timestamp = res["transactTime"]
self.active_bot.deal.margin_short_buy_back_timestamp = res["transactTime"]
msg = f"Completed Take profit!"
msg = "Completed Take profit!"

else:
msg = f"Re-completed take profit"
msg = "Re-completed take profit"

self.active_bot.errors.append(msg)
self.active_bot.status = Status.completed
Expand Down
79 changes: 55 additions & 24 deletions api/deals/spot.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ def switch_margin_short(self):
2. Calculate take_profit_price and stop_loss_price as usual
3. Create deal
"""
self.update_deal_logs("Resetting bot for margin_short strategy...", self.active_bot)
self.update_deal_logs(
"Resetting bot for margin_short strategy...", self.active_bot
)
self.active_bot.strategy = Strategy.margin_short
self.active_bot = self.create_new_bot_streaming(active_bot=self.active_bot)

Expand Down Expand Up @@ -70,12 +72,14 @@ def execute_stop_loss(self, price):
if not closed_orders:
order = self.verify_deal_close_order()
if order:
self.active_bot.errors.append("Execute stop loss previous order found! Appending...")
self.active_bot.errors.append(
"Execute stop loss previous order found! Appending..."
)
self.active_bot.orders.append(order)
else:
self.update_deal_logs(
f"No quantity in balance, no closed orders. Cannot execute update stop limit.",
self.active_bot
"No quantity in balance, no closed orders. Cannot execute update stop limit.",
self.active_bot,
)
self.active_bot.status = Status.error
self.active_bot = self.save_bot_streaming(self.active_bot)
Expand All @@ -86,7 +90,9 @@ def execute_stop_loss(self, price):
res = self.simulate_order(self.active_bot.pair, price, qty, "SELL")

else:
self.active_bot.errors.append("Dispatching sell order for trailling profit...")
self.active_bot.errors.append(
"Dispatching sell order for trailling profit..."
)
# Dispatch real order
res = self.sell_order(symbol=self.active_bot.pair, qty=qty, price=price)

Expand Down Expand Up @@ -137,12 +143,14 @@ def trailling_profit(self) -> BotSchema | None:
if not closed_orders:
order = self.verify_deal_close_order()
if order:
self.active_bot.errors.append("Execute trailling profit previous order found! Appending...")
self.active_bot.errors.append(
"Execute trailling profit previous order found! Appending..."
)
self.active_bot.orders.append(order)
else:
self.update_deal_logs(
f"No quantity in balance, no closed orders. Cannot execute update trailling profit.",
self.active_bot
"No quantity in balance, no closed orders. Cannot execute update trailling profit.",
self.active_bot,
)
self.active_bot.status = Status.error
self.active_bot = self.save_bot_streaming(self.active_bot)
Expand All @@ -158,7 +166,9 @@ def trailling_profit(self) -> BotSchema | None:
)

else:
self.active_bot.errors.append("Dispatching sell order for trailling profit...")
self.active_bot.errors.append(
"Dispatching sell order for trailling profit..."
)
# Dispatch real order
# No price means market order
res = self.sell_order(
Expand Down Expand Up @@ -212,15 +222,17 @@ def streaming_updates(self, close_price, open_price):
self.base_producer.update_required(self.producer, "EXECUTE_SPOT_STOP_LOSS")
if self.active_bot.margin_short_reversal:
self.switch_margin_short()
self.base_producer.update_required(self.producer, "EXECUTE_SWITCH_MARGIN_SHORT")
self.update_deal_logs("Completed switch to margin short bot", self.active_bot)
self.base_producer.update_required(
self.producer, "EXECUTE_SWITCH_MARGIN_SHORT"
)
self.update_deal_logs(
"Completed switch to margin short bot", self.active_bot
)

return

# Take profit trailling
if (self.active_bot.trailling) and float(
self.active_bot.deal.buy_price
) > 0:
if (self.active_bot.trailling) and float(self.active_bot.deal.buy_price) > 0:
# If current price didn't break take_profit (first time hitting take_profit or trailling_stop_loss lower than base_order buy_price)
if self.active_bot.deal.trailling_stop_loss_price == 0:
trailling_price = float(self.active_bot.deal.buy_price) * (
Expand Down Expand Up @@ -248,13 +260,22 @@ def streaming_updates(self, close_price, open_price):
# trailling_profit_price always be > trailling_stop_loss_price
self.active_bot.deal.trailling_profit_price = new_take_profit

if new_trailling_stop_loss > self.active_bot.deal.buy_price and new_trailling_stop_loss > self.active_bot.deal.trailling_stop_loss_price:
if (
new_trailling_stop_loss > self.active_bot.deal.buy_price
and new_trailling_stop_loss
> self.active_bot.deal.trailling_stop_loss_price
):
# Selling below buy_price will cause a loss
# instead let it drop until it hits safety order or stop loss
# Update trailling_stop_loss
self.active_bot.deal.trailling_stop_loss_price = new_trailling_stop_loss
self.active_bot.deal.trailling_stop_loss_price = (
new_trailling_stop_loss
)

self.update_deal_logs(f"Updated {self.active_bot.pair} trailling_stop_loss_price {self.active_bot.deal.trailling_stop_loss_price}", self.active_bot)
self.update_deal_logs(
f"Updated {self.active_bot.pair} trailling_stop_loss_price {self.active_bot.deal.trailling_stop_loss_price}",
self.active_bot,
)
self.active_bot = self.save_bot_streaming(self.active_bot)

# Direction 2 (downward): breaking the trailling_stop_loss
Expand All @@ -269,10 +290,13 @@ def streaming_updates(self, close_price, open_price):
and (float(open_price) > float(close_price))
):
self.update_deal_logs(
f"Hit trailling_stop_loss_price {self.active_bot.deal.trailling_stop_loss_price}. Selling {self.active_bot.pair}"
f"Hit trailling_stop_loss_price {self.active_bot.deal.trailling_stop_loss_price}. Selling {self.active_bot.pair}",
self.active_bot,
)
self.trailling_profit()
self.base_producer.update_required(self.producer, "EXECUTE_SPOT_TRAILLING_PROFIT")
self.base_producer.update_required(
self.producer, "EXECUTE_SPOT_TRAILLING_PROFIT"
)

# Update unfilled orders
unupdated_order = next(
Expand All @@ -284,7 +308,9 @@ def streaming_updates(self, close_price, open_price):
None,
)
if unupdated_order:
order_response = self.get_all_orders(self.active_bot.pair, unupdated_order.order_id)
order_response = self.get_all_orders(
self.active_bot.pair, unupdated_order.order_id
)
logging.info(f"Unfilled orders response{order_response}")
if order_response[0]["status"] == "FILLED":
for i, order in enumerate(self.active_bot.orders):
Expand All @@ -293,7 +319,7 @@ def streaming_updates(self, close_price, open_price):
self.active_bot.orders[i].qty = order_response["origQty"]
self.active_bot.orders[i].fills = order_response["fills"]
self.active_bot.orders[i].status = order_response["status"]

self.active_bot = self.save_bot_streaming(self.active_bot)

def close_conditions(self, current_price):
Expand All @@ -305,8 +331,13 @@ def close_conditions(self, current_price):
"""
if self.active_bot.close_condition == CloseConditions.market_reversal:
self.render_market_domination_reversal()
if self.market_domination_reversal and current_price < self.active_bot.deal.buy_price:
if (
self.market_domination_reversal
and current_price < self.active_bot.deal.buy_price
):
self.execute_stop_loss()
self.base_producer.update_required(self.producer, "EXECUTE_SPOT_CLOSE_CONDITION_STOP_LOSS")
self.base_producer.update_required(
self.producer, "EXECUTE_SPOT_CLOSE_CONDITION_STOP_LOSS"
)

pass
pass
2 changes: 1 addition & 1 deletion binquant
Submodule binquant updated from e76b75 to f526c3

0 comments on commit 9651e56

Please sign in to comment.