Enhance trailing stop with ATR-based sizing

This commit is contained in:
mindesbunister
2025-11-05 15:28:12 +01:00
parent 149294084e
commit a100945864
8 changed files with 183 additions and 35 deletions

View File

@@ -38,7 +38,10 @@ export interface TradingConfig {
// Trailing stop for runner (after TP2)
useTrailingStop: boolean // Enable trailing stop for remaining position
trailingStopPercent: number // Trail by this % below peak
trailingStopPercent: number // Legacy fixed trail percent (used as fallback)
trailingStopAtrMultiplier: number // Multiplier for ATR-based trailing distance
trailingStopMinPercent: number // Minimum trailing distance in percent
trailingStopMaxPercent: number // Maximum trailing distance in percent
trailingStopActivation: number // Activate when runner profits exceed this %
// Position Scaling (add to winning positions)
@@ -115,7 +118,10 @@ export const DEFAULT_TRADING_CONFIG: TradingConfig = {
// Trailing stop for runner (after TP2)
useTrailingStop: true, // Enable trailing stop for remaining position after TP2
trailingStopPercent: 0.3, // Trail by 0.3% below peak price
trailingStopPercent: 0.3, // Legacy fallback (%, used if ATR data unavailable)
trailingStopAtrMultiplier: 1.5, // Trail ~1.5x ATR (converted to % of price)
trailingStopMinPercent: 0.25, // Never trail tighter than 0.25%
trailingStopMaxPercent: 0.9, // Cap trailing distance at 0.9%
trailingStopActivation: 0.5, // Activate trailing when runner is +0.5% in profit
// Position Scaling (conservative defaults)
@@ -248,6 +254,18 @@ export function validateTradingConfig(config: TradingConfig): void {
if (config.slippageTolerance < 0 || config.slippageTolerance > 10) {
throw new Error('Slippage tolerance must be between 0 and 10%')
}
if (config.trailingStopAtrMultiplier <= 0) {
throw new Error('Trailing stop ATR multiplier must be positive')
}
if (config.trailingStopMinPercent < 0 || config.trailingStopMaxPercent < 0) {
throw new Error('Trailing stop bounds must be non-negative')
}
if (config.trailingStopMinPercent > config.trailingStopMaxPercent) {
throw new Error('Trailing stop min percent cannot exceed max percent')
}
}
// Environment-based configuration
@@ -321,6 +339,15 @@ export function getConfigFromEnv(): Partial<TradingConfig> {
trailingStopPercent: process.env.TRAILING_STOP_PERCENT
? parseFloat(process.env.TRAILING_STOP_PERCENT)
: undefined,
trailingStopAtrMultiplier: process.env.TRAILING_STOP_ATR_MULTIPLIER
? parseFloat(process.env.TRAILING_STOP_ATR_MULTIPLIER)
: undefined,
trailingStopMinPercent: process.env.TRAILING_STOP_MIN_PERCENT
? parseFloat(process.env.TRAILING_STOP_MIN_PERCENT)
: undefined,
trailingStopMaxPercent: process.env.TRAILING_STOP_MAX_PERCENT
? parseFloat(process.env.TRAILING_STOP_MAX_PERCENT)
: undefined,
trailingStopActivation: process.env.TRAILING_STOP_ACTIVATION
? parseFloat(process.env.TRAILING_STOP_ACTIVATION)
: undefined,