AI Trading Engine

This document covers the core AI decision-making components of the Signal trading system, specifically the three-stage AI pipeline that drives all trading decisions. This includes the SignalOutline, CloseOutline, and RiskOutline services with their TTL (Time To Live) systems and decision logic.

For information about the mathematical analysis services that feed data into these AI components, see Mathematical Analysis Services. For details about the agent swarm system used for user consultation, see Agent Swarm System.

The AI Trading Engine employs a sophisticated three-stage pipeline that mimics professional trader thinking. Each stage operates independently with its own specialized AI prompts, TTL intervals, and decision logic.

Mermaid Diagram

The SignalOutline service determines whether to open LONG/SHORT positions or wait based on comprehensive market analysis across multiple timeframes.

The SignalOutline produces structured decisions with the following format:

Field Type Description
action "trade" | "wait" Primary decision
position "long" | "short" | "wait" Position direction
current_price number Market price at decision
stop_loss_price number Risk management level
take_profit_price number Profit target
description string Professional recommendation
reasoning string Detailed technical justification

The SignalOutline employs a dynamic Time-To-Live system that adapts to market conditions:

Mermaid Diagram

The SignalOutline uses sophisticated prompts that emphasize:

  • Intuitive Market Analysis: Detection of hidden opportunities and anomalies
  • Multi-timeframe Coherence: Analysis across 1m/15m/30m/1h intervals
  • Historical P&L Learning: Pattern recognition from previous trades
  • Strategy-Specific Logic: Separate decision trees for FAST_TRADE, SWING_TRADE, and POSITION_TRADE

Key prompt sections include directional bias detection:

БЫСТРАЯ ЛОНГ ТОРГОВЛЯ (15-минутные покупки) подходит когда:
- Видишь высокую волатильность и четкие импульсные движения ВВЕРХ
- RSI и StochRSI дают ясные сигналы на покупку на коротких периодах
- Объемы взрываются на пробоях уровней сопротивления ВВЕРХ

The CloseOutline service specializes in scalping-oriented early position closure based on P&L dynamics and reversal signal detection.

The CloseOutline implements a sophisticated adaptive TTL system that responds to profit/loss momentum:

P&L State TTL Duration Reasoning
PROFIT_RISING_TTL 2.5 minutes Profit growing, price rising - normal monitoring
PROFIT_FALLING_TTL 1.0 minutes Profit declining, fast check for reversal
LOSS_RISING_TTL 5.0 minutes Loss shrinking, slow check for recovery
LOSS_FALLING_TTL 5.0 minutes Loss growing, slow check to avoid panic

The CloseOutline employs professional trader intuition with specific criteria:

HOLD Position when:

  • P&L demonstrates STABLE or ASCENDING growth
  • Volatility remains NORMAL (fluctuations up to 0.2%)
  • Position progresses toward Take Profit naturally
  • INDICATORS SHOW trend continuation across most timeframes

CLOSE Position when:

  • Impulse CONSISTENTLY FALLS for more than 15 minutes
  • Volatility becomes EXCESSIVELY HIGH (more than 0.3% from peak)
  • P&L shows SUSTAINED LOSS (more than 0.3%) without recovery signs
  • INDICATORS SHOW CLEAR trend reversal consistently over 15 minutes

The close.json file demonstrates an actual AI decision where the system chose to close a position:

{
"action": "close",
"description": "ЗАКРЫТЬ ПОЗИЦИЮ — P&L показывает слабый импульс и потерю первоначального прогресса",
"reasoning": "Текущий P&L демонстрирует слабый импульс — достиг пика +0.10% но откатился до +0.05%..."
}

The RiskOutline service performs global safety assessment of trading conditions and recommends optimal trading strategies.

Mermaid Diagram

The RiskOutline incorporates intuitive analysis capabilities:

  • Hidden Opportunity Detection: Identifies potential entry points not reflected in obvious indicator signals
  • Anomaly Recognition: Monitors price movement, volume, and indicator behavior anomalies
  • Market Context Awareness: Considers recent news, large player behavior, and order book liquidity
ИНТУИТИВНЫЙ АНАЛИЗ РЫНКА:
- Используй интуицию для выявления скрытых рыночных возможностей
- Обращай внимание на аномалии в движении цены, объемах или поведении индикаторов
- Учитывай рыночный контекст: недавние новости, поведение крупных игроков

The AI Trading Engine uses a sophisticated configurable prompt system with override capabilities and fallback mechanisms.

Mermaid Diagram

Each prompt service follows a consistent singleshot caching pattern:

export class SignalPromptService {
private getPrompt = singleshot(async (): Promise<PromptModel> => {
const customPath = require.resolve('./config/signal.prompt.cjs');
if (await exists(customPath)) {
return require(customPath); // Custom override
}
return signal_prompt_default; // Default fallback
});
}

This architecture provides:

  • Separation of Concerns: Prompts isolated from business logic
  • Hot-swappable Updates: Zero-downtime prompt modifications
  • Type Safety: TypeScript structure integrity guarantees
  • Performance Optimization: Singleshot caching with lazy loading

The AI Trading Engine integrates with multiple AI providers through the InferenceMetaService for model selection and completion processing.

Mermaid Diagram

Each AI completion goes through structured processing:

  1. Prompt Assembly: System + user prompts with market data
  2. AI Completion: Multi-provider inference with model selection
  3. JSON Parsing: Structured decision extraction
  4. Validation: Business rule compliance checking
  5. TTL Assignment: Dynamic interval calculation for next execution

The system ensures robust error handling and graceful degradation when AI services are unavailable.