Skip to content

Commit

Permalink
update balance and crypto balance after initial crypto purchase - rem…
Browse files Browse the repository at this point in the history
…ove some useless HealthCheck tests
  • Loading branch information
jordantete committed Jan 8, 2025
1 parent f2eb72d commit 617f96b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
12 changes: 0 additions & 12 deletions core/bot_management/health_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,18 +221,6 @@ async def _check_and_alert_resource_usage(self, usage: dict):
)
alerts.append(message)

# Check for memory leaks - adjusted thresholds
if trends.get("bot_memory_trend", 0) > 50:
old_memory = self._metrics_history[0].bot_memory_mb
recent_memory = self._metrics_history[-1].bot_memory_mb
if old_memory > 0:
percent_increase = ((recent_memory - old_memory) / old_memory) * 100
if percent_increase > 20: # Only alert if more than 20% increase
alerts.append(
f"Possible memory leak detected: Bot memory usage increased by "
f"{percent_increase:.1f}% ({trends['bot_memory_trend']:.1f} MB/hour)"
)

# Check for CPU spikes
if trends.get("bot_cpu_trend", 0) > 10: # %/hour
alerts.append(f"High CPU usage trend: Bot CPU usage increasing by "
Expand Down
20 changes: 19 additions & 1 deletion core/order_handling/balance_tracker.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
from config.trading_mode import TradingMode
from .fee_calculator import FeeCalculator
from .order import Order, OrderSide
from .order import Order, OrderSide, OrderStatus
from core.bot_management.event_bus import EventBus, Events
from ..validation.exceptions import InsufficientBalanceError, InsufficientCryptoBalanceError
from core.services.exchange_interface import ExchangeInterface
Expand Down Expand Up @@ -158,6 +158,24 @@ def _update_after_sell_order_filled(
self.balance += sale_proceeds
self.total_fees += fee
self.logger.info(f"Sell order completed: {quantity} crypto sold at {price}.")

def update_after_initial_purchase(self, initial_order: Order):
"""
Updates balances after an initial crypto purchase.
Args:
initial_order: The Order object containing details of the completed purchase.
"""
if initial_order.status != OrderStatus.FILLED:
raise ValueError(f"Order {initial_order.id} is not FILLED. Cannot update balances.")

total_cost = initial_order.filled * initial_order.average
fee = self.fee_calculator.calculate_fee(initial_order.amount * initial_order.average)

self.crypto_balance += initial_order.filled
self.balance -= total_cost + fee
self.total_fees += fee
self.logger.info(f"Updated balances. Crypto balance: {self.crypto_balance}, Fiat balance: {self.balance}, Total fees: {self.total_fees}")

def reserve_funds_for_buy(
self,
Expand Down
6 changes: 5 additions & 1 deletion core/order_handling/order_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,9 @@ async def perform_initial_purchase(

if self.trading_mode == TradingMode.BACKTEST:
await self._simulate_fill(buy_order, buy_order.timestamp)
else:
# Update fiat and crypto balance in LIVE & PAPER_TRADING modes without simulating it
self.balance_tracker.update_after_initial_purchase(initial_order=buy_order)

except OrderExecutionFailedError as e:
self.logger.error(f"Failed while executing initial purchase - {str(e)}", exc_info=True)
Expand Down Expand Up @@ -450,7 +453,8 @@ async def _simulate_fill(
"""
order.filled = order.amount
order.remaining = 0.0
order.status = OrderStatus.CLOSED
order.status = OrderStatus.CLOSED
order.timestamp = timestamp
order.last_trade_timestamp = timestamp
timestamp_in_seconds = timestamp / 1000 if timestamp > 10**10 else timestamp
formatted_timestamp = datetime.fromtimestamp(timestamp_in_seconds).strftime('%Y-%m-%d %H:%M:%S')
Expand Down

0 comments on commit 617f96b

Please sign in to comment.