DEV Community

Cover image for Trading bot risk management: SL, TP, and trailing stops
Lucas Gragg
Lucas Gragg

Posted on

Trading bot risk management: SL, TP, and trailing stops

Trading bot risk management is a critical aspect of automated trading, and one that can make or break the success of a strategy. I've spent countless hours refining my own approach to managing risk, and have come to rely on a combination of stop-loss (SL), take-profit (TP), and trailing stops to protect my positions. The 3:1 risk-reward ratio is a good starting point, but it's just that - a starting point. In practice, I've found that a more nuanced approach is needed, one that takes into account the specific characteristics of the market and the strategy being used.

Stop-Loss and Take-Profit

The most basic form of risk management is the stop-loss, which closes a position when it reaches a certain price threshold. This can be a fixed price, or a percentage of the entry price. Take-profit is similar, but closes the position when it reaches a certain profit threshold. These two orders are the foundation of risk management, and are used in conjunction with each other to limit losses and lock in gains. For example, if I enter a long position at $100, I might set a stop-loss at $95 and a take-profit at $110. If the price falls to $95, the stop-loss will be triggered and the position will be closed, limiting my loss to $5. If the price rises to $110, the take-profit will be triggered and the position will be closed, locking in a gain of $10.

Trailing Stops

Trailing stops are a more advanced form of risk management, which involve adjusting the stop-loss price as the position moves in the desired direction. For example, if I enter a long position at $100 and set a trailing stop of 5%, the stop-loss price will be adjusted to $105 if the price rises to $110. This allows me to lock in some of the gains while still giving the position room to move. I've found that trailing stops are particularly useful in volatile markets, where the price can move quickly and unpredictably.

import ccxt

def set_trailing_stop(exchange, symbol, side, amount, price, trailing_percent):
    # Set initial stop-loss price
    stop_loss_price = price * (1 - trailing_percent) if side == 'buy' else price * (1 + trailing_percent)

    # Set trailing stop
    def update_stop_loss(ticker):
        if side == 'buy':
            new_stop_loss_price = ticker['close'] * (1 - trailing_percent)
        else:
            new_stop_loss_price = ticker['close'] * (1 + trailing_percent)

        # Update stop-loss order
        exchange.cancel_order(stop_loss_order['id'])
        stop_loss_order = exchange.create_order(symbol, 'stop_loss_limit', side, amount, new_stop_loss_price)

    # Get ticker and update stop-loss
    ticker = exchange.fetch_ticker(symbol)
    update_stop_loss(ticker)

    # Set interval to update stop-loss
    import schedule
    import time

    def update_stop_loss_interval():
        ticker = exchange.fetch_ticker(symbol)
        update_stop_loss(ticker)

    schedule.every(1).minutes.do(update_stop_loss_interval)  # Update every 1 minute

    while True:
        schedule.run_pending()
        time.sleep(1)

# Example usage:
exchange = ccxt.binance({
    'apiKey': 'YOUR_API_KEY',
    'apiSecret': 'YOUR_API_SECRET',
})
set_trailing_stop(exchange, 'BTC/USDT', 'buy', 0.1, 50000, 0.05)
Enter fullscreen mode Exit fullscreen mode

Implementing Risk Management

Implementing risk management in a trading bot can be complex, especially when dealing with multiple positions and exchanges. I've spent countless hours writing and refining my own code, and have come to realize that a modular approach is key. By breaking down the risk management logic into smaller, reusable functions, I can easily adapt my code to different strategies and markets. I actually packaged this into a tool called crypto exchange trading bot if you want the full working version, which supports multiple exchanges and strategies.

One of the biggest gotchas I've encountered is the issue of order execution speed. When a stop-loss or take-profit is triggered, it's critical that the order is executed quickly and reliably. I've found that using a high-quality exchange API can make all the difference, as it allows for fast and efficient order execution. For example, the Binance API has a average order execution time of around 10-20 milliseconds, which is extremely fast. However, even with a fast API, there are still risks associated with order execution, such as network latency and exchange downtime. To mitigate these risks, I've implemented a system of redundant orders and fail-safes, which ensures that my positions are always protected.

Now, I'm trying to optimize the trailing stop logic to account for sudden price movements, maybe by using a combination of moving averages and volatility indicators...

Also available on Payhip with instant PayPal checkout.


If you need a server to run your bots 24/7, I use DigitalOcean — $200 free credit for new accounts.

Top comments (0)