AgentSkillsCN

python-trading-bot

为 NQ 期货自营交易公司(Apex Trader Funding)打造、重构并维护 Python 实时交易机器人。支持 Databento API 获取市场数据,集成 TradersPost 进行交易执行,覆盖评估/PA 模式、自定义策略,以及全面的生产级功能。触发条件:“实时交易机器人”、“Python 机器人”、“NQ 机器人”、“期货机器人”、“创建机器人”、“重构机器人”、“/bot:new”、“/bot:refactor”、“/bot:custom”。

SKILL.md
--- frontmatter
name: python-trading-bot
description: Generate, refactor, and maintain Python live trading bots for NQ futures prop firm trading (Apex Trader Funding). Supports Databento API for market data, TradersPost for execution, eval/PA modes, custom strategies, and comprehensive production features. Triggers: "live trading bot", "Python bot", "NQ bot", "futures bot", "create bot", "refactor bot", "/bot:new", "/bot:refactor", "/bot:custom".
allowed-tools: Read, Write, Edit, Grep, Glob, Bash(pip:*, python3:*)

Python Trading Bot Skill

Generate, refactor, and maintain production-ready Python trading bots for NQ futures prop firm trading with:

  • Databento API for real-time and historical market data
  • TradersPost webhooks for order execution (Apex Trader Funding compatible)
  • Eval and PA modes with trailing drawdown, profit targets, dynamic sizing
  • 5 backtested signals + support for custom strategies
  • Production features (state persistence, news filtering, alerting, comprehensive testing)

Commands

Bot Generation

CommandDescription
/bot:newStart interactive bot builder (with eval/PA mode selection)
/bot:new <signal>Start with signal pre-selected
/bot:customBuild bot with custom strategy/indicators
/bot:keltnerGenerate Keltner Channel bot (PF 10.04)
/bot:emaGenerate EMA Cross bot (PF 6.23)
/bot:vwapGenerate Rolling VWAP bot (PF 5.20)
/bot:supertrendGenerate SuperTrend bot (PF 4.41)
/bot:alligatorGenerate Alligator bot (PF 4.16)
/bot:listShow signals with backtest metrics

Bot Refactoring

CommandDescription
/bot:refactor <bot_name>Start interactive refactoring session
/bot:add-feature <bot_name> <feature>Add feature (news filter, indicator, etc.)
/bot:remove-feature <bot_name> <feature>Remove feature cleanly
/bot:migrate-pa <bot_name>Convert eval bot to PA mode
/bot:analyze <bot_name>Analyze code quality and suggest improvements

Top 5 Entry Signals

SignalProfit FactorWin RateKey Parameters
keltner10.0487.8%EMA=20, ATR_MULT=2.75
ema_cross6.2382.7%Fast=3, Slow=8, Sep=0.35
vwap5.2085.3%Window=720, Mult=1.0
supertrend4.4182.5%Period=10, Mult=3.0
alligator4.1683.5%Jaw=13, Teeth=8, Lips=5

Metrics from 219-day NQ futures backtest (May 2025 - Jan 2026) with ADX di_rising, threshold 35.


When to Use This Skill

Use this skill when:

  • Creating a new live trading bot for NQ futures
  • Refactoring or modifying existing trading bots
  • Converting eval bots to PA mode (or vice versa)
  • Adding features to bots (news filter, alerts, new indicators)
  • Building custom strategies beyond the 5 pre-built signals
  • Setting up Apex Trader Funding eval or PA accounts
  • Implementing prop firm risk management (trailing DD, dynamic sizing)
  • Testing strategies with CSV backtest before going live

Do NOT use for:

  • Offline backtesting only (use Python/backtest.py instead)
  • Creating platform indicators (use indicator-generator skill for TradingView/NinjaTrader/Tradovate)
  • Multi-account management (run separate bot instances)
  • Non-futures markets (skill optimized for NQ futures)

Generated Bot Structure

Each generated bot includes these files:

code
Python/bots/<signal>/
├── bot_<signal>.py              # Main entry point (asyncio)
├── config.py                    # Configuration from .env
├── databento_client.py          # Market data (Databento API)
├── traderspost_client.py        # Order execution (TradersPost webhook)
├── risk_manager.py              # Apex account tracking (eval/PA modes)
├── indicators.py                # Self-contained indicator calculations
├── news_calendar.py             # Economic calendar filtering (optional)
├── alerting.py                  # Email/SMS alerts (optional)
├── bot_state.db                 # SQLite persistence (created at runtime)
├── requirements.txt             # Python dependencies
├── .env.example                 # Credential template
├── .gitignore                   # Exclude .env, logs, *.db
└── README.md                    # Bot documentation

Bot Architecture

code
┌─────────────────────────────────────────────────────────────┐
│                    DATABENTO API                             │
│  https://databento.com (real-time & historical 2-min bars)  │
│  + CSV files for backtesting                                 │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                      PYTHON BOT                              │
│  • Indicator calculation (EMA, ATR, ADX, signal-specific)   │
│  • Signal detection (edge-triggered crossovers)              │
│  • Apex account tracking (eval/PA modes, trailing DD)       │
│  • Position management (SL/TP/trailing stops)               │
│  • Re-entry logic (3 bars wait, ADX > 40)                   │
│  • News calendar filtering (blackout periods)               │
│  • State persistence (SQLite - survive restarts)            │
│  • Alerting (email/SMS on critical events)                  │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                   TRADERSPOST WEBHOOK                        │
│  POST https://webhooks.traderspost.io/trading/webhook/...   │
│  {ticker, action, quantity, stopLoss, takeProfit}           │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│          BROKER (Tradovate / Apex Trader Funding)           │
│  Order execution, position management, OCO brackets          │
└─────────────────────────────────────────────────────────────┘

Key Features

FeatureImplementation
Market DataDatabento API (real-time + historical) + CSV files
Account ModesEval (profit target, trailing DD) or PA (risk %, static DD)
Position SizingFixed contracts (eval) or risk-based % (PA mode)
Indicator calculationsSelf-contained (EMA, ATR, ADX, VWAP, signal-specific)
Signal detectionEdge-triggered crossovers (5 pre-built + custom)
Position managementEntry price, SL, TP, HWM/LWM, trailing stops
Re-entry logic3 bars wait, ADX > 40, max 10 per direction
News calendarEconomic event blackouts (FOMC, NFP, CPI)
AlertingEmail + SMS on daily loss limit, DD breach, connection loss
State persistenceSQLite database (survive mid-day restarts)
Session filteringConfigurable allowed hours (ET timezone)
Volume filterVolume > EMA(volume, 20)
Graceful shutdownSIGINT/SIGTERM handlers, exit positions on shutdown
LoggingFile + console with timestamps
TestingCSV backtest mode, unit tests, integration tests

Quick Start

1. Interactive Mode

code
User: Create a live trading bot
Assistant: [Runs /bot:new workflow]
  - Step 1: Select signal (keltner, ema_cross, vwap, supertrend, alligator)
  - Step 2: Configure signal parameters
  - Step 3: Set risk parameters (contracts, daily max loss)
  - Step 4: Configure exits (SL, TP, trailing)
  - Step 5: API credentials guidance
  - Step 6: Generate bot files

2. Direct Signal

code
User: /bot:keltner
Assistant: [Generates Keltner bot with optimal settings]

3. Quick Mode

code
User: /bot:new keltner --quick
Assistant: [Uses all defaults, generates immediately]

ADX Filter Modes

All 5 modes from backtest.py supported:

ModeLogicRecommended
traditionalADX > threshold
di_aligned+ DIs aligned with direction
di_rising+ Dominant DI rising
adx_rising+ ADX itself rising
combinedAll conditions

Exit Priority Order

  1. Trailing Stop (if active AND hit)
  2. Stop Loss (hard protective stop)
  3. Take Profit (profit target)

Skill References

Core Documentation

ResourceDescription
Interactive WorkflowInteractive bot generation workflow (includes account_mode)
Refactoring GuideBot refactoring and modification workflows
Configuration IndexConfiguration index with links to topics
Signals OverviewSignal overview and selection guide
Apex RulesComprehensive Apex Trader Funding rules
Apex ComplianceApex compliance guidelines for automated trading

Configuration Topics

ResourceDescription
Apex AccountsAccount modes, presets, position sizing
Signal ParametersAll 5 signal parameters
ADX ModesADX filter modes with examples
Exits & Re-entryStop loss, take profit, trailing, re-entry
Risk & FiltersRisk mgmt, filters, alerts, persistence

Guides

ResourceDescription
Eval vs PA ComparisonEval vs PA mode comparison
Eval Mode GuideEval account detailed guide
PA Mode GuidePA account detailed guide
Data Provider GuideData provider overview
Custom Provider TutorialCustom provider implementation
Provider ReferenceBar format, testing, best practices
ArchitectureArchitecture overview
Architecture ComponentsComponent details
Data FlowBar processing, entry/exit flows
Deployment GuideDeployment overview
VPS SetupServer setup and installation
Systemd ServiceService configuration
Production OperationsMonitoring, security, backup
Economic CalendarNews calendar integration
Testing GuideUnit, integration, CSV backtest testing
Setup GuideBot setup and deployment

Signal Details

ResourceDescription
Top 5 SignalsDetailed top 5 with all parameters
Keltner ChannelKeltner Channel details
EMA CrossoverEMA Crossover details
Rolling VWAPRolling VWAP details
SuperTrendSuperTrend details
Williams AlligatorWilliams Alligator details

Templates

ResourceDescription
Base BotMain bot template (with persistence, news, alerts)
ConfigConfig file template
IndicatorsIndicators class overview
Core IndicatorsEMA, SMA, SMMA, ATR, ADX
Signal IndicatorsVWAP, Keltner, SuperTrend, Alligator
Apex IntegrationApex account integration template
Risk ManagerRisk manager with eval/PA support
PersistenceSQLite state persistence
News FilterEconomic calendar filtering
AlertingEmail/SMS alerting system
Data ProviderData provider adapter interface
Test SuiteTest suite template
TradersPost ClientTradersPost webhook client
Tradovate ClientTradovate WebSocket client

Workflows

ResourceDescription
Add FeatureAdd feature to existing bot
Remove FeatureRemove feature from bot
Change IndicatorSwap or modify indicators
Migrate to PAConvert eval bot to PA mode
Custom StrategyBuild custom strategy bot

Examples

ResourceDescription
Keltner Bot ExampleFull working Keltner Channel bot example
Custom Data ProviderExample custom data provider adapter
Alert ConfigAlerting configuration example
Indicator TestsUnit test examples
Environment Template.env file template with all required credentials

Related Files

FilePurpose
Python/backtest.pyReference implementation (indicator calculations, signal logic)
Python/docs/TRADOVATE_API_GUIDE.mdTradersPost payload format, Tradovate WebSocket
Python/STRATEGY.mdStrategy specification