P
PipsGrowth
Bot completeness reference

Complete Auto Trading Bot Cheat Sheet

Every automated strategy must define the full trade lifecycle before code: analysis, entry, confirmation, execution, in-trade management, exit, and post-exit review. This page is a complete bot specification map for humans and a reference contract for IDE AI agents so they do not build partial bots or partial strategies.

Non-Negotiable Safety Rule

هذا المحتوى تعليمي فقط. التداول الآلي قد يسبب خسائر بسرعة. نتائج الاختبار الخلفي لا تضمن نتائج حية، ويجب اختبار أي روبوت على حساب تجريبي مع سبريد وعمولة وانزلاق وأخبار واقعية قبل أي استخدام حقيقي. هذا ليس نصيحة مالية.

Complete Bot Specification Map

Do not accept a bot that has only indicators, entries, and a backtest equity curve. A complete bot has a market thesis, data contract, decision contract, validation evidence, execution adapter, monitoring, and rollback.

1

Strategy Definition

The idea must be specific enough to reject bad trades, not just describe a favorite indicator.

  • Market thesis, target instruments, timeframe, session, expected regime, and why the edge should exist.
  • Exact allowed and forbidden market states, including when the bot must stay flat.
  • Trade direction rules, portfolio exposure rules, and whether shorts, hedges, or multiple positions are allowed.
2

Data and Feature Contract

The bot must say what data it needs and how that data is transformed before decisions are made.

  • OHLCV, tick, bid/ask, spread, order book, news, calendar, sentiment, fundamentals, funding, and broker account data.
  • Timestamp alignment, timezone, missing-data policy, warmup bars, indicator lookback, feature lagging, and stale-feed detection.
  • Data version, source, storage format, symbol mapping, and replay method used for repeatable tests.
3

Decision and Risk Contract

Signals, confirmations, sizing, and exits should be deterministic and explainable.

  • Setup, entry trigger, confirmation, no-trade filters, risk per trade, max daily loss, and max portfolio heat.
  • Initial stop, target, trailing stop, break-even rule, time stop, emergency stop, and invalidation logic.
  • Position sizing formula, rounding rules, min/max lot handling, margin checks, and correlation limits.
4

Engineering Contract

A production-ready bot is a system, not one script with buy and sell conditions.

  • Separate modules for data, features, signals, risk, execution, state, backtest, validation, monitoring, and reporting.
  • Config files, environment variables, secrets handling, dry-run mode, versioned parameters, and repeatable command-line runs.
  • Unit tests for pure logic, integration tests for adapters, replay tests for scenarios, and live safety checks.

Full Trade Lifecycle

The lifecycle is the main guardrail against partial automation. If one stage is missing, the bot specification is not ready.

1

1. Market Thesis and Analysis

Define why the opportunity should exist before selecting indicators or writing code.

  • Market, symbols, session, timeframe, spread behavior, liquidity profile, and allowed trading hours.
  • Regime definition: trend, range, breakout, volatility expansion, mean reversion, news, or portfolio rotation.
  • Data inputs: OHLCV, bid and ask, tick data, economic calendar, order book, funding, sentiment, correlation, and broker execution logs.
  • Failure conditions: when the thesis is invalid and when the bot must stop looking for trades.
2

2. Setup, Entry, and Confirmation

Separate raw signal, trade trigger, and confirmation so the bot does not enter on vague conditions.

  • Setup rule: the market state that makes a trade possible.
  • Entry trigger: the exact event that creates an order candidate.
  • Confirmation filters: trend, volatility, volume, spread, news, session, correlation, higher timeframe, or ML score.
  • No-trade filters: max spread, abnormal slippage, high-impact news, low liquidity, stale feed, open exposure, and duplicate signal prevention.
3

3. Execution and Order Handling

A strategy is incomplete until order placement, rejection, retries, fills, and broker limits are specified.

  • Order type: market, limit, stop, stop-limit, bracket, OCO, or staged basket.
  • Sizing: fixed fractional, volatility adjusted, portfolio heat, symbol cap, margin cap, and max correlated exposure.
  • Execution checks: min stop distance, freeze level, tick size, lot step, margin available, slippage tolerance, partial fills, requotes, and retry policy.
  • Logging: every signal, rejected signal, order request, response code, fill, modification, cancellation, and exception.
4

4. In-Trade Management

Open trades need rules for protection, adaptation, scaling, and emergency shutdown.

  • Initial stop, take profit, invalidation stop, time stop, break-even rule, trailing method, and partial profit logic.
  • Scaling rules: whether the bot may add, reduce, hedge, pyramid, grid, or average, and the hard maximum for each.
  • Live monitoring: spread widening, connection loss, data staleness, calendar blackout, equity drawdown, and broker execution drift.
  • State machine: pending, active, protected, scaled, reducing, exit requested, closed, and reconciled.
5

5. Exit and After-Exit Review

Exits must be as explicit as entries because most partial bots only define how to get in.

  • Exit triggers: stop loss, target, trailing stop, opposite signal, volatility collapse, regime change, time window, news lockout, or max adverse excursion.
  • Emergency exits: max daily loss, max account drawdown, broker disconnect, repeated order failure, data feed corruption, or manual kill switch.
  • Post-exit review: realized R, slippage, spread paid, rule path, screenshots or chart state, feature values, and reason for exit.
  • Journal output: trade id, setup id, model version, code version, parameter set, data source, and broker account environment.

Backtesting, OOS, and Bias Control

A profitable test is not enough. The process must actively search for false confidence, hidden leakage, and execution assumptions that will fail live.

1

Research Validation Discipline

Backtesting is a research filter, not proof. The test must reject fragile logic before demo or live execution.

  • Use separate in-sample, out-of-sample, walk-forward, and final holdout periods.
  • Model commission, spread, slippage, rollover, latency, fill assumptions, rejected orders, and symbol trading sessions.
  • Block lookahead bias, survivorship bias, data snooping, overfitting, and leakage from future bars, future news, or post-trade labels.
  • Use robustness checks: parameter stability, Monte Carlo sequencing, random spread stress, missed-fill stress, bootstrapping, and market-regime slices.
  • Reject strategies that only work after excessive parameter search, unrealistic fills, tiny sample size, or one exceptional market period.
2

Forward Test and Release Gates

A complete bot has deployment gates, not only a profitable notebook or MT5 tester report.

  • Paper trade or demo with the same broker, symbol naming, leverage, account currency, trading hours, and VPS setup intended for production.
  • Compare expected signals to actual signals and expected fills to actual broker fills.
  • Use minimum sample gates: number of trades, number of sessions, news days, quiet days, high-volatility days, and drawdown events.
  • Require rollback: disable new entries, flatten positions, restore previous version, and preserve logs for audit.

Research Workflow From Idea to Live Bot

The page should guide the user from idea to validated system, not jump from wizard choices to code.

1

1. Hypothesis and Baseline

Write the market behavior hypothesis before optimizing anything.

  • Define the naive baseline: buy and hold, session breakout, random entry with same exit, or simple trend filter.
  • List what would falsify the idea before you see the test result.
  • Choose metrics beyond profit: expectancy, max drawdown, profit factor, win/loss distribution, exposure time, turnover, and capacity.
2

2. Prototype and Event Replay

Start simple, then replay the market exactly as the bot would see it.

  • Vectorized tests are useful for quick scans but can hide execution problems.
  • Event-driven backtest with order queue, fill model, rejected orders, partial fills, and position state is required before live logic.
  • Record every decision path so a losing trade can be traced from data to signal to order to exit.
3

3. Robustness and Release

Only promote a strategy after it survives conditions it was not tuned on.

  • Use out-of-sample, walk-forward, untouched holdout, parameter perturbation, spread stress, slippage stress, and Monte Carlo ordering.
  • Compare variants against a simple baseline to prove complexity is earning its place.
  • Promote to demo only with a release note, parameter lock, expected behavior range, and rollback plan.

Indicators and Logic Families

Indicators are inputs, not strategies. Combine them with regime, risk, execution, and exit rules.

Trend: EMA, SMA, ADX, Supertrend, Ichimoku, moving-average slope, market structure.
Momentum: RSI, MACD, stochastic, rate of change, CCI, oscillator divergence.
Volatility: ATR, Bollinger Band width, Keltner Channels, realized volatility, compression and expansion.
Volume and order flow: tick volume, VWAP, OBV, volume profile, DOM imbalance, bid-ask spread, liquidity sweeps.
Price action: support and resistance, break of structure, retests, candlestick patterns, session highs and lows.
Portfolio context: correlation, beta, exposure by currency, sector, asset class, volatility contribution, and drawdown heat.

Python Libraries and API Integrations

These are implementation options, not endorsements. The correct stack depends on asset class, broker, execution permissions, latency needs, and validation depth.

Python Research and Backtesting

Use Python to make research reproducible before any live connection is allowed.

  • pandas and numpy for data cleaning, feature engineering, vectorized calculations, and repeatable datasets.
  • vectorbt, backtrader, bt, Zipline-style workflows, or custom event-driven engines when fill logic matters.
  • TA-Lib, pandas-ta, statsmodels, scikit-learn, XGBoost, PyTorch, or TensorFlow for indicators, statistics, and model research.
  • Optuna or similar optimizers only with walk-forward discipline and strict holdout validation.
  • MLflow, DVC, parquet, SQLite, DuckDB, or PostgreSQL for experiment tracking, versioned datasets, and reproducible runs.

Execution APIs and Broker Integrations

Choose execution APIs based on asset class, account availability, and broker constraints.

  • MetaTrader5 Python package or MQL5 Expert Advisor for MT5 execution and Strategy Tester workflows.
  • Alpaca, Interactive Brokers, OANDA, Binance, CCXT-compatible crypto exchanges, FIX gateways, or broker REST and WebSocket APIs where permitted.
  • TradingView webhooks, broker webhooks, or message queues only when authentication, idempotency, replay protection, and risk checks are implemented.
  • VPS, Docker, process supervisors, secrets management, heartbeat checks, alerting, and automatic restart policies.

LLM, News, and Calendar Layer

AI and news can support decisions, but they should not bypass deterministic risk controls.

  • Economic calendars for high-impact event filters, pre-news lockouts, post-news cooldowns, and spread stress expectations.
  • News APIs, RSS, broker calendars, central bank calendars, earnings calendars, and sentiment feeds as optional context layers.
  • LLMs may summarize news, classify event risk, generate review notes, explain why a rule fired, or create human-readable reports.
  • LLMs should not place orders directly. Their output must pass deterministic schema validation, confidence thresholds, and human-defined risk rules.

Strategy Families and Required Extra Rules

Trend following, breakout, mean reversion, grid, market making, statistical arbitrage, ML filter, and news-aware bots each need different safeguards. A generic template is not enough.

Trend Following

Needs regime detection and protection from chop.

  • Required extras: trend filter, pullback or continuation trigger, volatility stop, trailing exit, and range-market disable rule.
  • Failure mode: many small losses during sideways markets if the no-trade regime is weak.

Breakout

Needs false-breakout handling and realistic execution assumptions.

  • Required extras: range definition, breakout trigger, retest or momentum confirmation, spread limit, slippage model, and news/session rules.
  • Failure mode: backtests often overstate fills exactly when volatility expands.

Mean Reversion

Needs hard protection from trend continuation.

  • Required extras: fair-value definition, exhaustion trigger, volatility filter, max adverse excursion rule, and trend-regime kill switch.
  • Failure mode: one directional move can erase many small winners.

Grid, Martingale, and Recovery

High-risk systems need explicit exposure ceilings before any entry rule.

  • Required extras: max levels, max basket loss, equity stop, no-martingale default, margin stress test, and forced flattening rule.
  • Failure mode: smooth backtests hide tail risk until one live regime shift destroys the account.

Market Making and Scalping

Execution quality is the strategy.

  • Required extras: bid/ask data, spread capture logic, queue/fill assumptions, latency budget, commission model, and cancellation rules.
  • Failure mode: profitable candle tests can fail after spread, latency, and fill priority.

ML, LLM, and News-Aware Bots

AI should support a deterministic trading system, not replace it.

  • Required extras: feature lagging, train/test split, model registry, confidence threshold, fallback behavior, and deterministic risk override.
  • Failure mode: leakage, label mistakes, prompt drift, hallucinated news summaries, and models that cannot survive regime change.

Data Quality Checklist

Check timestamp timezone, missing bars, duplicate ticks, adjusted prices, bid-ask availability, session gaps, symbol rollovers, broker-specific spreads, and feature calculation windows.

News and Calendar Checklist

Define what counts as high impact, when to stop new entries, whether to close positions, cooldown minutes after release, and whether a strategy is allowed to trade news at all.

Production Safety Checklist

Require heartbeat monitoring, alerting, read-only dry-run mode, position reconciliation, max loss limits, kill switch, exception logging, versioned config, and rollback instructions.

Live Operations and Failure Modes

Live trading is mostly operational control. The system must know how to pause, flatten, retry, alert, and recover when market data, broker execution, or infrastructure fails.

  • Data feed stale, delayed, duplicated, missing bars, wrong timezone, wrong symbol, bad rollover, or mismatched bid/ask stream.
  • Broker rejects orders because of lot step, min stop distance, freeze level, margin, market closed, symbol disabled, or off quotes.
  • Execution drift from spread widening, slippage, partial fill, requote, latency, VPS restart, API limit, or websocket disconnect.
  • Logic drift from changed parameters, unversioned model, changed broker contract, untested market regime, or calendar feed failure.
  • Operational failure from missing alerts, no kill switch, no dry-run mode, unhandled exception, duplicate process, or unsynced local state.

Review Cadence

A complete bot has pre-trade, in-trade, post-trade, daily, weekly, and release review, not only final profit and loss.

Pre-trade review: data freshness, spread, calendar, exposure, margin, duplicate signal, and kill-switch state.
In-trade review: stop state, target state, trailing state, partials, spread drift, connection health, and position reconciliation.
Post-trade review: entry reason, exit reason, rule path, slippage, cost, realized R, model version, and screenshot or feature snapshot.
Daily review: drawdown, error logs, rejected orders, missing data, symbol behavior, broker execution drift, and risk-limit events.
Weekly review: parameter stability, regime fit, trade distribution, correlation exposure, version changes, and whether live behavior matches backtest assumptions.
Release review: changelog, migration plan, config diff, rollback command, demo evidence, and human approval before live deployment.

Dynamic Data, Contract Specs, and Adaptation

A bot that only works for one fixed account, one symbol suffix, one broker timezone, or one lot setting is not robust. Dynamic data should be refreshed, validated, and logged before analysis, sizing, execution, and live monitoring.

If broker time, symbol suffix, contract size, tick value, lot step, margin rule, balance, equity, leverage, or trading session changes, the bot must re-query and re-validate before opening new trades.
Contract specifications must be read from the broker or exchange adapter: min lot, max lot, lot step, tick size, tick value, contract size, stop level, freeze level, margin mode, swap, commission, and trading hours.
Risk sizing must use current balance/equity, stop distance, tick value, contract size, margin requirement, currency conversion, open exposure, and max portfolio heat.
Adaptive market logic must be bounded: regime-adaptive parameters, volatility-adaptive stops, spread-adaptive entry gating, and session/calendar reloads need max/min limits and audit logs.
Reusable modules: market data adapter, contract-spec resolver, broker clock, risk sizing engine, execution adapter, state machine, validation harness, and journal.

Complete Bot Architecture Blocks

Ask the IDE to implement these as separate modules or explicit interfaces. Do not accept one monolithic script where research, execution, risk, and logging are mixed together.

Data ingestion and normalization
Feature and indicator pipeline
Signal engine
Confirmation and no-trade filters
Risk and position sizing
Execution adapter
Trade state machine
Backtest engine
Validation and bias checks
Live monitor and alerting
Journal and analytics
Deployment and rollback controls

IDE Prompt Contract

Paste this into an IDE agent before asking it to build an auto trading bot.

Do not code a trading bot until this checklist is satisfied.

Build the bot as separate modules for data ingestion, feature generation, signal logic, confirmation filters, risk sizing, execution, in-trade management, exits, logging, backtesting, validation, and deployment safety.

The strategy must explicitly define analysis, entry, confirmation, execution, in-trade management, exit, and post-exit review. Include no-trade filters, spread and slippage rules, order rejection handling, kill switches, data-staleness checks, and full trade journaling.

Before any live-trading code is accepted, provide backtests with realistic costs, out-of-sample validation, walk-forward testing, Monte Carlo or stress testing, and checks for lookahead bias, survivorship bias, data snooping, overfitting, and leakage.

LLM, news, and calendar modules may support context and reporting only. They must not bypass deterministic risk controls or place orders directly.

Do not accept a bot that has only indicators, entries, and a backtest equity curve. Require a complete specification, tests, logs, validation report, dry-run mode, live safety controls, and rollback plan.

Use This With the Strategy Builder

The Strategy Builder helps assemble a code-ready plan. This cheat sheet defines the completeness standard. Use both together: first design the strategy in the builder, then check the output against this page before asking an IDE to write code.

Complete Auto Trading Bot Cheat Sheet