Skip to content
⚠️ Not financial advice. For educational use only.
WikiBots

Bots & Strategies

Bots are the strategies that decide when to enter and exit trades.
In Algo Trading Stack, bots inherit from a common base class (BaseStrategyBot) that provides risk management, sizing, and lifecycle control.

This page explains how bots work, the built-in bots included with the stack, and how to implement your own.


1. Role of Bots

  • Bots encapsulate the strategy logic — when to go long/short or stay flat
  • They rely on the TradingEnvironment to fetch data, indicators, and portfolio state
  • Exits are separate, pluggable modules (ExitStrategy) that the bot delegates stop-loss/take-profit logic to
  • Bots use risk-aware position sizing and respect margin requirements

2. Lifecycle

Each bar, during the OPEN phase:

  1. The TradingEnvironment calls bot.on_bar(env)
  2. The bot:
    • Checks eligibility (session hours, ATR threshold, etc.)
    • If flat → calls decide_side() to choose long/short/none
    • Computes stop-loss and take-profit via its attached ExitStrategy
    • Computes safe position size (% risk, margin limits, slippage/fees)
    • Places an order with the environment
  3. If already in a position → the bot delegates to exit_strategy.update_stop() to adjust protective levels

3. BaseStrategyBot

All bots inherit from BaseStrategyBot, which provides:

  • Risk management: % equity at risk, buffers for slippage & fees
  • Position sizing: contracts sized so risk ≤ configured percentage of equity
  • Eligibility gates: session/holiday filters, ATR thresholds
  • Maintenance flattening: auto-closes before daily margin reset (e.g., 5pm ET)
  • Exit integration: pluggable ExitStrategy for SL/TP logic
  • Online learning hook: if the exit supports ingest_trade_log(env), it is called automatically

4. Built-in Bots

CoinFlipBot

  • Description: Baseline strategy that flips a coin to go long or short
  • Purpose: Provides a neutral baseline for testing risk, exits, and config setups
  • Usage:
    from bots.coin_flip_bot.coin_flip_bot import CoinFlipBot
    bot = CoinFlipBot()
    env.set_bot(bot)

TrendFollowingBot

  • Description: Trades in the direction of EMA trends
  • Logic: Goes long if price is above trend EMA, short if below
  • Usage:
    from bots.trend_following_bot.trend_following_bot import TrendFollowingBot
    bot = TrendFollowingBot()
    env.set_bot(bot)

5. Writing Your Own Bot

To implement your own bot:

  1. Subclass BaseStrategyBot
from bots.base_strategy_bot import BaseStrategyBot
 
class MyBot(BaseStrategyBot):
    def decide_side(self, env, symbol, df, idx_last, idx_prev):
        # Example: EMA crossover
        if df['ema_21'].iloc[idx_prev] > df['ema_50'].iloc[idx_prev]:
            return "buy"
        elif df['ema_21'].iloc[idx_prev] < df['ema_50'].iloc[idx_prev]:
            return "sell"
        return None
  1. Attach an exit strategy (e.g. TrailingATRExit, FixedRatioExit, or RL/bandit hybrid)
from bots.exit_strategies import TrailingATRExit
bot = MyBot(exit_strategy=TrailingATRExit(atr_multiple=3.0))
  1. Run the bot in a backtest or live environment
env.set_bot(bot)
engine.start_backtest()

6. Using Exit Strategies with Bots

Exits are independent modules that can be swapped across bots:

  • ATR trailing stop (TrailingATRExit)
  • ATR stop + fixed ratio TP (FixedRatioExit)
  • PPO policy-driven stop (RLTrailingATRExit)
  • LSTM rolling classifier (SequenceRLATRExit)
  • Hybrid exits (RL/LSTM priors + LinUCB bandits)

This makes bots modular: you can keep the same entry logic but experiment with different exits.


7. Summary

  • Bots decide when to enter and exit positions
  • All bots inherit from BaseStrategyBot for sizing, risk, and lifecycle control
  • Exits are pluggable — bots don’t hardcode stop-loss logic
  • Built-in bots (CoinFlip, TrendFollowing) are starting points; users can extend them easily
  • Writing a new bot requires only a few lines of strategy-specific logic

Bots are where trading ideas live, and Algo Trading Stack makes them simple, modular, and interchangeable.