Algorithm Structure
This document provides the complete schema reference for the TradingAlgorithm configuration object. Understanding this structure is essential for creating and managing trading algorithms programmatically.
Overview
A trading algorithm in x3Algo consists of five main configuration steps, each represented as a nested object within the algorithm structure:
- Basic Information - Strategy type, timeframe, symbols
- Position Sizing - How to calculate position sizes
- Entry Conditions - When to open positions
- Exit Conditions - When to close positions
- Risk Parameters & Execution - Risk limits and execution settings
Top-Level Schema
interface TradingAlgorithm {
// Identification
id: string
userId: string
name: string
description?: string
// Status and Lifecycle
status: 'draft' | 'active' | 'paused' | 'stopped' | 'error' | 'archived'
active: boolean
version: number
// Configuration Steps
basicInfo: BasicInfo
positionSizing: PositionSizing
entryConditions: EntryConditions
exitConditions: ExitConditions
riskParameters: RiskParameters
executionSettings: ExecutionSettings
// Performance Tracking
performance: Performance
// Optimization (Optional)
walkForwardConfig?: WalkForwardConfig
walkForwardResults?: WalkForwardResult[]
monteCarloConfig?: MonteCarloConfig
monteCarloResults?: MonteCarloResults
// Metadata
isTemplate: boolean
isPublic: boolean
clonedFrom?: string
lastExecution?: LastExecution
createdAt: Date
updatedAt: Date
}
Field Descriptions
Identification Fields
id
- Type:
string - Required: Yes (auto-generated)
- Description: Unique identifier for the algorithm
- Example:
"507f1f77bcf86cd799439011"
userId
- Type:
string - Required: Yes
- Description: ID of the user who owns this algorithm
- Example:
"507f191e810c19729de860ea"
name
- Type:
string - Required: Yes
- Description: Human-readable name for the algorithm
- Default:
"Algorithm #X"(auto-generated for drafts) - Example:
"EMA Crossover Strategy"
description
- Type:
string - Required: No
- Description: Optional detailed description of the strategy
- Example:
"15m EMA crossover with RSI confirmation"
Status and Lifecycle Fields
status
- Type:
enum - Required: Yes
- Values:
draft- Algorithm is being configured, not yet completeactive- Algorithm is running and generating signalspaused- Algorithm is temporarily suspendedstopped- Algorithm is complete but not runningerror- Algorithm encountered an errorarchived- Algorithm is archived (soft deleted)
- Default:
draft - Example:
"active"
active
- Type:
boolean - Required: Yes
- Description: Whether the algorithm is currently active
- Default:
false - Example:
true
version
- Type:
number - Required: Yes
- Description: Version number, increments on significant changes
- Default:
1 - Example:
3
Configuration Objects
basicInfo
- Type:
BasicInfo - Required: Yes
- Description: Step 1 configuration - strategy type, timeframe, symbols
- See: Basic Information Configuration
positionSizing
- Type:
PositionSizing - Required: Yes
- Description: Step 2 configuration - position sizing method and parameters
- See: Position Sizing Schema
entryConditions
- Type:
EntryConditions - Required: Yes
- Description: Step 3 configuration - entry signal generation rules
- See: Entry Conditions Schema
exitConditions
- Type:
ExitConditions - Required: Yes
- Description: Step 4 configuration - exit rules and profit/loss management
- See: Exit Conditions Schema
riskParameters
- Type:
RiskParameters - Required: Yes
- Description: Step 5 configuration - risk limits and position constraints
- See: Risk Parameters Schema
executionSettings
- Type:
ExecutionSettings - Required: Yes
- Description: Step 5 configuration - execution mode, broker, exchange settings
- See: Execution Settings Schema
Performance Tracking
performance
- Type:
Performance - Required: Yes (auto-populated)
- Description: Real-time performance metrics
- Structure:
interface Performance {
totalTrades: number
winningTrades: number
losingTrades: number
totalProfit: number
totalLoss: number
winRate: number // Percentage (0-100)
profitFactor: number // totalProfit / totalLoss
sharpeRatio: number // Risk-adjusted return
maxDrawdown: number // Maximum peak-to-trough decline
averageWin: number // Average profit per winning trade
averageLoss: number // Average loss per losing trade
}
Optimization Configuration
walkForwardConfig
- Type:
WalkForwardConfig - Required: No
- Description: Configuration for walk-forward optimization
- See: Walk-Forward Optimization
walkForwardResults
- Type:
WalkForwardResult[] - Required: No
- Description: Results from walk-forward optimization runs
- See: Walk-Forward Optimization
monteCarloConfig
- Type:
MonteCarloConfig - Required: No
- Description: Configuration for Monte Carlo simulation
- See: Monte Carlo Simulation
monteCarloResults
- Type:
MonteCarloResults - Required: No
- Description: Results from Monte Carlo simulation
- See: Monte Carlo Simulation
Metadata Fields
isTemplate
- Type:
boolean - Required: Yes
- Description: Whether this algorithm is a reusable template
- Default:
false - Example:
true
isPublic
- Type:
boolean - Required: Yes
- Description: Whether this template is publicly discoverable
- Default:
false - Example:
false
clonedFrom
- Type:
string - Required: No
- Description: ID of the algorithm this was cloned from
- Example:
"507f1f77bcf86cd799439011"
lastExecution
- Type:
LastExecution - Required: No
- Description: Information about the last execution
- Structure:
interface LastExecution {
timestamp: Date
status: 'success' | 'error'
result?: any
error?: string
}
createdAt
- Type:
Date - Required: Yes (auto-generated)
- Description: Timestamp when the algorithm was created
- Example:
"2024-01-15T10:30:00Z"
updatedAt
- Type:
Date - Required: Yes (auto-updated)
- Description: Timestamp when the algorithm was last modified
- Example:
"2024-01-20T14:45:00Z"
Basic Information Structure
The basicInfo object contains Step 1 configuration:
interface BasicInfo {
strategyType: StrategyType
timeframe: Timeframe
symbols: string[]
}
strategyType
- Type:
enum - Required: Yes
- Values:
scalping- Very short-term trades (seconds to minutes)swing- Medium-term trades (days to weeks)position- Long-term trades (weeks to months)arbitrage- Exploit price differences across marketsmarket_making- Provide liquidity and profit from spreadmomentum- Follow strong price trendsmean_reversion- Trade against temporary price deviations
- Example:
"momentum"
timeframe
- Type:
enum - Required: Yes
- Values:
1m,5m,15m,30m,1h,4h,1d,1w - Description: Candle timeframe for strategy execution
- Example:
"15m"
symbols
- Type:
string[] - Required: Yes
- Description: Array of trading symbols in EXCHANGE:SYMBOL format
- Format:
EXCHANGE:SYMBOL - Examples:
- Equity:
"NSE:RELIANCE","BSE:INFY" - Futures:
"MCX:CRUDEOIL25JANFUT","NSE:NIFTY25JAN24500CE" - Commodity:
"MCX:GOLD","NCDEX:SOYBEAN"
- Equity:
Complete Example
Here's a complete algorithm configuration example:
{
"id": "507f1f77bcf86cd799439011",
"userId": "507f191e810c19729de860ea",
"name": "EMA Crossover with RSI",
"description": "15-minute EMA crossover strategy with RSI confirmation",
"status": "active",
"active": true,
"version": 2,
"basicInfo": {
"strategyType": "momentum",
"timeframe": "15m",
"symbols": ["NSE:RELIANCE", "NSE:TCS"]
},
"positionSizing": {
"method": "risk_based",
"riskPercentage": 1.5,
"pyramiding": {
"enabled": false
}
},
"entryConditions": {
"positionType": "both",
"logicalOperator": "AND",
"confirmationCandles": 1,
"conditions": [
{
"type": "indicator_indicator",
"indicator1": {
"type": "EMA",
"period": 9
},
"operator": "crosses_above",
"indicator2": {
"type": "EMA",
"period": 21
}
},
{
"type": "indicator_value",
"indicator": {
"type": "RSI",
"period": 14
},
"operator": "above",
"value": 50
}
]
},
"exitConditions": {
"stopLoss": {
"type": "percentage",
"percentage": 2.0
},
"takeProfit": {
"type": "risk_reward",
"ratio": 2.0
},
"trailingStop": {
"enabled": true,
"type": "percentage",
"percentage": 1.5,
"activationThreshold": 1.0
}
},
"riskParameters": {
"maxPositionSize": 10.0,
"stopLoss": 2.0,
"takeProfit": 4.0,
"maxDailyLoss": 5000,
"maxOpenPositions": 5,
"riskRewardRatio": 2.0
},
"executionSettings": {
"mode": "paper",
"exchange": "NSE",
"broker": "AngelOne",
"orderType": "market",
"slippage": 0.1
},
"performance": {
"totalTrades": 45,
"winningTrades": 27,
"losingTrades": 18,
"totalProfit": 15000,
"totalLoss": 8000,
"winRate": 60.0,
"profitFactor": 1.875,
"sharpeRatio": 1.45,
"maxDrawdown": 3500,
"averageWin": 555.56,
"averageLoss": 444.44
},
"isTemplate": false,
"isPublic": false,
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-20T14:45:00Z"
}
Validation Rules
Draft Algorithms
- Can be saved with incomplete configuration
- Only
nameanduserIdare required - Other fields can be null or have default values
Complete Algorithms
- All five configuration steps must be fully configured
- All required fields in each step must have valid values
- Must pass validation before transitioning from
drafttostoppedstatus
Active Algorithms
- Must be in
stoppedstatus before starting - All configuration must be valid
- Must have at least one symbol configured
- Entry conditions must have at least one condition
- Risk parameters must be within acceptable ranges
Related Documentation
- Position Sizing Schema - Detailed position sizing configuration
- Entry Conditions Schema - Entry signal configuration
- Exit Conditions Schema - Exit rules configuration
- Risk Parameters Schema - Risk management configuration
- Execution Settings Schema - Execution mode and broker settings
- Algorithm Lifecycle - Understanding algorithm states
- API Reference - Creating algorithms via API