Trigger on time (seconds)

The "Trigger on Time" feature allows a market-making bot to execute trades at specified intervals, ensuring that the bot remains active and responsive to market conditions. This can be particularly useful for strategies that require periodic adjustments, such as updating orders or recalibrating spreads based on market volatility.

▎How It Works

  1. Time Interval: Define a time interval (in seconds) at which the bot will trigger its trading logic.

  2. Execution Logic: At each interval, the bot fetch current market prices, evaluate its trading strategy, and place or adjust orders accordingly.

  3. Continuous Loop: The bot runs in a continuous loop, checking the time and executing trades when the specified interval has elapsed.

▎Example Code

Below is an example implementation that incorporates the "Trigger on Time" feature into a market-making bot using Python and the ccxt library.

▎Sample Code

import ccxt import time

class TimeBasedMarketMakingBot: def init(self, exchanges, trading_pairs, spread=0.01, interval=10): self.exchanges = {name: ccxt.getattribute(name)() for name in exchanges} self.trading_pairs = trading_pairs self.spread = spread self.interval = interval self.last_trigger_time = time.time()

def fetch_prices(self):
    prices = {}
    for name, exchange in self.exchanges.items():
        prices[name] = {}
        for pair in self.trading_pairs:
            try:
                ticker = exchange.fetch_ticker(pair)
                prices[name][pair] = ticker['last']
            except Exception as e:
                print(f"Error fetching price from {name} for {pair}: {e}")
    return prices

def place_orders(self, prices):
    for name, pairs in prices.items():
        exchange = self.exchanges[name]
        for pair, price in pairs.items():
            try:
                # Calculate buy and sell prices based on the spread
                buy_price = price * (1 - self.spread)
                sell_price = price * (1 + self.spread)

                # Place buy and sell orders
                exchange.create_limit_buy_order(pair, 1, buy_price)
                exchange.create_limit_sell_order(pair, 1, sell_price)
                print(f"Placed orders on {name} for {pair}: Buy at {buy_price}, Sell at {sell_price}")

            except Exception as e:
                print(f"Error placing orders on {name} for {pair}: {e}")

def run(self):
    while True:
        current_time = time.time()
        if current_time - self.last_trigger_time >= self.interval:
            prices = self.fetch_prices()
            if prices:
                self.place_orders(prices)
            self.last_trigger_time = current_time  # Update last trigger time
        time.sleep(1)  # Sleep briefly to avoid busy waiting

if name == "main": exchanges = ['binance', 'kraken'] # List of exchanges to support trading_pairs = ['BTC/USDT', 'ETH/USDT', 'LTC/USDT'] # List of trading pairs bot = TimeBasedMarketMakingBot(exchanges, trading_pairs) bot.run()

▎Explanation of the Code

  1. Initialization:

    • The bot initializes with a list of exchanges and trading pairs.

    • It defines a spread and a time interval (in seconds) for triggering trades.

    • last_trigger_time is initialized to the current time.

  2. Fetching Prices:

    • The fetch_prices method retrieves the latest prices for all specified trading pairs from each exchange.

  3. Placing Orders:

    • The place_orders method calculates buy and sell prices based on the fetched prices for each pair and places limit orders accordingly.

  4. Running the Bot:

    • The run method continuously checks the elapsed time since the last trigger.

    • If the elapsed time is greater than or equal to the specified interval, it fetches prices and places orders.

      • The bot sleeps briefly (1 second) to avoid busy waiting.

    ▎Considerations

    • Adjustable Interval: You may want to allow dynamic adjustment of the interval based on market conditions or user input.

    • Error Handling: Implement robust error handling to manage issues like API rate limits and connection problems.

    • Performance Monitoring: Include logging features to monitor the performance of trades over time.

Last updated