Monitoring and alerts

Monitoring and alerting are essential features for market-making bots to ensure they operate effectively and respond promptly to market conditions. These features help traders stay informed about the bot's performance, potential issues, and significant market events.

▎Key Components of Monitoring and Alerts

  1. Performance Metrics:

    • Track metrics such as profit/loss, inventory levels, and order status.

    • Monitor execution times and slippage.

  2. Market Conditions:

    • Monitor significant price changes, volatility, and liquidity.

    • Set thresholds for alerts based on predefined criteria (e.g., price drops or spikes).

  3. Alerts:

    • Send notifications via email, SMS, or messaging platforms when certain conditions are met.

    • Alerts can be triggered by performance metrics or market conditions.

  4. Logging:

    • Maintain logs of all trades, orders, and alerts for future analysis and debugging.

▎Example Code for Monitoring and Alerts

Below is an example implementation of monitoring and alerting features within a market-making bot using Python. This example uses a simple console alert system but can be extended to integrate with email or messaging APIs.

import random import time import smtplib from email.mime.text import MIMEText

class MarketMakingBot: def init(self, initial_capital=10000): self.capital = initial_capital self.inventory = 0 self.orders = [] self.alert_thresholds = { "profit_loss": 500, "inventory": 5, "price_drop": 2, "price_spike": 2 } self.last_price = None

def get_current_price(self):
    return random.uniform(95, 105)

def place_order(self, order_type, price, quantity):
    if order_type == "buy" and self.capital >= price * quantity:
        self.orders.append({"type": "buy", "price": price, "quantity": quantity})
        self.capital -= price * quantity
        self.inventory += quantity
        print(f"Placed Buy Order: {quantity} at {price:.2f}")
    elif order_type == "sell" and self.inventory >= quantity:
        self.orders.append({"type": "sell", "price": price, "quantity": quantity})
        self.capital += price * quantity
        self.inventory -= quantity
        print(f"Placed Sell Order: {quantity} at {price:.2f}")

def check_alerts(self):
    current_price = self.get_current_price()
    
    # Check profit/loss threshold
    if (self.capital + self.inventory * current_price) - 10000 >= self.alert_thresholds["profit_loss"]:
        self.send_alert("Profit/Loss Alert", f"Profit/Loss exceeded: {self.capital + self.inventory * current_price - 10000:.2f}")

    # Check inventory threshold
    if self.inventory >= self.alert_thresholds["inventory"]:
        self.send_alert("Inventory Alert", f"Inventory exceeded: {self.inventory} assets held.")

    # Check price drop/spike
    if self.last_price is not None:
        if current_price < (self.last_price - self.alert_thresholds["price_drop"]):
            self.send_alert("Price Drop Alert", f"Price dropped significantly to: {current_price:.2f}")
        elif current_price > (self.last_price + self.alert_thresholds["price_spike"]):
            self.send_alert("Price Spike Alert", f"Price spiked significantly to: {current_price:.2f}")

    self.last_price = current_price

def send_alert(self, subject, message):
    print(f"ALERT: {subject} - {message}")
    # Uncomment below lines to send email alerts
    # msg = MIMEText(message)
    # msg['Subject'] = subject
    # msg['From'] = 'your_email@example.com'
    # msg['To'] = 'recipient@example.com'
    
    # with smtplib.SMTP('smtp.example.com', 587) as server:
    #     server.starttls()
    #     server.login('your_email@example.com', 'your_password')
    #     server.send_message(msg)

def run(self):
        while True:
            current_price = self.get_current_price()
            print(f"\nCurrent Price: {current_price:.2f}, Capital: {self.capital:.2f}, Inventory: {self.inventory}")

            # Example order management logic
            if current_price < 100:
                self.place_order("buy", current_price, 1)
            elif current_price > 102 and self.inventory > 0:
                self.place_order("sell", current_price, 1)

            # Check alerts based on current market conditions
            self.check_alerts()

            time.sleep(5)  # Wait for 5 seconds before the next iteration

# Example usage
if __name__ == "__main__":
    bot = MarketMakingBot(initial_capital=10000)
    bot.run()

▎Explanation of the Code

  1. MarketMakingBot Class: The class now includes alerting features.

  2. check_alerts(): This method checks various conditions to determine whether an alert should be triggered based on profit/loss, inventory levels, and price changes.

  3. send_alert(): This method prints an alert message to the console. The email alert functionality is commented out but can be enabled by providing SMTP server details.

  4. run(): Continuously monitors the market price and checks alerts after each trading decision.

Last updated