DEV Community

Cover image for How to Add Pre-Trade Risk Checks to Your Algo Trading Bot in 5 Minutes
flop95
flop95

Posted on

How to Add Pre-Trade Risk Checks to Your Algo Trading Bot in 5 Minutes

How to Add Pre-Trade Risk Checks to Your Algo Trading Bot in 5 Minutes

You built a trading bot. It watches the market, generates signals, and places orders. It works — until it doesn't.

Maybe you changed a position sizing parameter last Tuesday and didn't realize it broke your stop-loss logic. Maybe your bot bought the same ticker three times in ten minutes because your duplicate detection had a bug. Maybe you hit your daily loss limit at 10am and kept trading anyway because nothing was checking.

The frustrating part isn't that these things happen. It's that you have no record of why they happened. Your bot either placed the trade or it didn't. There's no audit trail showing which risk checks passed, which failed, and what the parameters were at the time.

This post walks through adding a pre-trade risk gate to any Python trading bot using Titan Fortress — a hosted platform that evaluates your signals against a configurable pipeline of 20+ risk checks and records a complete trace for every decision. It takes about 5 minutes to set up.

What you'll get

By the end of this walkthrough, every signal your bot generates will:

  • Pass through duplicate detection, position exposure limits, daily loss checks, price drift validation, volatility bounds, and position sizing — before any order is placed
  • Produce a permanent, structured trace record showing exactly which gates passed, which failed, and why
  • Return a clear allow/deny verdict your bot can act on

You keep full control of execution. Titan Fortress never sees your broker credentials and never places orders. It just tells your bot whether the trade should happen.

Step 1: Sign up and create an agent key

Go to titan-bot-afa6.onrender.com and create a free account. Paper trading mode is on by default — nothing goes live until you explicitly configure it.

Once you're in, click Agents in the sidebar, then fill in a name for your bot (something like my-python-bot) and click Create Agent Key. You'll see a key that starts with tak_. Copy it now — it's shown exactly once and never stored in plaintext.

Step 2: Add the risk gate to your bot

Here's the minimal integration. Your bot calls Titan Fortress before placing any order:

import requests

TITAN_URL = "https://titan-bot-afa6.onrender.com"
AGENT_KEY = "tak_your_key_here"

def should_trade(symbol, side, price):
    """Ask Titan Fortress whether this trade should happen."""
    resp = requests.post(
        f"{TITAN_URL}/v1/pretrade/eval",
        headers={"X-Titan-Agent-Key": AGENT_KEY},
        json={
            "symbol": symbol,
            "action": side,
            "price": price,
        },
        timeout=5,
    )
    data = resp.json()

    if data.get("allow"):
        print(f"{symbol} {side} at {price} — ALLOWED")
        print(f"  Trace: {data.get('trace_viewer_url')}")
        return True
    else:
        print(f"{symbol} {side} at {price} — DENIED")
        print(f"  Reason: {data.get('reason')}")
        print(f"  Trace: {data.get('trace_viewer_url')}")
        return False
Enter fullscreen mode Exit fullscreen mode

Now wrap your existing order logic:

def on_signal(symbol, side, price):
    """Your existing signal handler, now with a risk gate."""
    if not should_trade(symbol, side, price):
        return  # Titan Fortress said no — skip this trade

    # Your existing order placement code goes here
    place_order(symbol, side, price)
Enter fullscreen mode Exit fullscreen mode

That's it. Every signal now passes through Titan Fortress's full gate pipeline before your bot acts on it.

Step 3: See your first trace

Run your bot and let it generate a signal. Or just call the function directly to test:

should_trade("AAPL", "buy", 182.50)
Enter fullscreen mode Exit fullscreen mode

You'll see output like:

✓ AAPL buy at 182.50 — ALLOWED
  Trace: https://titan-bot-afa6.onrender.com/trace/AAPL_1_1711234567_EXT
Enter fullscreen mode Exit fullscreen mode

Click the trace URL. You'll see the complete gate evaluation — every risk check that ran, whether it passed or failed, the exact parameters used, and the order intent that was computed. If the signal was denied, the trace shows exactly which gate rejected it and why.

You can also see all your traces in the dashboard at /traces, filter by symbol, status, or time range, and drill into any individual decision.

What the gate pipeline actually checks

When your signal hits Titan Fortress, it passes through a sequential pipeline of risk gates. The first gate that fails stops evaluation and records the rejection. Here's what gets checked:

Duplicate detection — Has this exact signal already been processed? Prevents double-orders from webhook retries or bot bugs.

Symbol allowlist — Is this ticker approved for trading? Catches signals for symbols you didn't intend to trade.

Cooldown windows — Did you just buy this symbol? Prevents rapid-fire re-entries.

Daily loss limit — Has the account lost more than your configured maximum today? A circuit breaker that halts trading before losses compound.

Market hours — Is the market open? Optionally blocks signals during off-hours.

Position exposure — Are you already at your maximum number of open positions? Prevents over-allocation.

Already held — Do you already have a position in this symbol? Prevents duplicate positions.

Price drift — Does the signal's quoted price diverge from the live market price? Catches stale signals.

ATR / volatility bounds — Is market volatility within expected bounds? Prevents trading during abnormal conditions.

Position sizing — Computes position size using a triple clamp: risk-based (from your risk percentage and stop distance), cap-based (max percentage of portfolio per order), and buying-power-based. The smallest of the three wins.

Bracket validation — Are the stop-loss and take-profit parameters valid and correctly placed relative to entry?

Every gate result — pass or fail — is recorded in the trace. Nothing is silently swallowed.

Going further: the deploy gate

Once you've been running for a while and have some trace history, Titan Fortress lets you do something no other retail-tier tool offers: regression test your configuration changes before deploying them.

Say you want to tighten your cooldown window from 30 minutes to 12 minutes. Before changing it in production, you can:

  1. Pin your recent live signals as a baseline
  2. Replay them through the candidate config (12-minute cooldown)
  3. Get a PASS, WARN, or FAIL verdict showing exactly how many decisions would change

The deploy gate compares not just whether signals pass or fail, but the actual order parameters — position size, stop distance, bracket prices. If the verdicts match but the position sizes changed by 25%, it flags that. If signals that the baseline accepted turn out to have been losers, it shows the P&L impact. It even tells you which specific gate caused each mismatch and whether that's likely a real behavioral change or just timing noise.

It's essentially CI/CD for your trading parameters. You'd never deploy code without running tests. Why would you change risk parameters without testing them against your own live history?

What Titan Fortress doesn't do

It's worth being explicit about this:

  • No signal generation. Titan Fortress doesn't tell you what to trade. It evaluates signals your bot already produces.
  • No fund custody. It never holds your money.
  • No broker credentials. Your API keys stay on your machine. Titan Fortress actively rejects any payload that looks like a credential. If you want Titan Fortress verdicts to trigger actual orders, a lightweight forwarder script on your machine reads the verdict and places the order locally.
  • No financial advice. It's infrastructure, not an advisor.

Try it

Sign up free at titan-bot-afa6.onrender.com. Paper trading is on by default. You can hit the Send Test Signal button on the dashboard to see a complete trace before connecting your bot.

The pretrade eval API works with any language — Python, JavaScript, Go, Rust, curl. If it can send an HTTP POST, it works with Titan Fortress.


Titan Fortress is built by Titan Diagnostic Systems. It's a hosted observability platform for algorithmic trading — every signal traced, every rejection explained.

Top comments (0)