Files
ai/gateway/knowledge/strategies/strategy-development.md

5.0 KiB

Strategy Development Guide

Trading strategies in Dexorder define entry/exit rules and position management logic.

Strategy Structure

class Strategy:
    def __init__(self, **params):
        """Initialize strategy with parameters"""
        self.params = params

    def generate_signals(self, df):
        """
        Generate trading signals

        Args:
            df: DataFrame with OHLCV + indicator columns

        Returns:
            DataFrame with 'signal' column:
                1 = long entry
               -1 = short entry
                0 = no action
        """
        pass

    def calculate_position_size(self, capital, price, risk_pct):
        """Calculate position size based on risk"""
        pass

    def get_stop_loss(self, entry_price, direction):
        """Calculate stop loss level"""
        pass

    def get_take_profit(self, entry_price, direction):
        """Calculate take profit level"""
        pass

Example: Simple Moving Average Crossover

class SMACrossoverStrategy:
    def __init__(self, fast_period=20, slow_period=50, risk_pct=0.02):
        self.fast_period = fast_period
        self.slow_period = slow_period
        self.risk_pct = risk_pct

    def generate_signals(self, df):
        # Calculate moving averages
        df['sma_fast'] = df['close'].rolling(self.fast_period).mean()
        df['sma_slow'] = df['close'].rolling(self.slow_period).mean()

        # Generate signals
        df['signal'] = 0

        # Long when fast crosses above slow
        df.loc[
            (df['sma_fast'] > df['sma_slow']) &
            (df['sma_fast'].shift(1) <= df['sma_slow'].shift(1)),
            'signal'
        ] = 1

        # Short when fast crosses below slow
        df.loc[
            (df['sma_fast'] < df['sma_slow']) &
            (df['sma_fast'].shift(1) >= df['sma_slow'].shift(1)),
            'signal'
        ] = -1

        return df

    def calculate_position_size(self, capital, price, atr):
        # Risk-based position sizing
        risk_amount = capital * self.risk_pct
        stop_distance = 2 * atr
        position_size = risk_amount / stop_distance
        return position_size

    def get_stop_loss(self, entry_price, direction, atr):
        if direction == 1:  # Long
            return entry_price - (2 * atr)
        else:  # Short
            return entry_price + (2 * atr)

    def get_take_profit(self, entry_price, direction, atr):
        if direction == 1:  # Long
            return entry_price + (4 * atr)  # 2:1 risk/reward
        else:  # Short
            return entry_price - (4 * atr)

Strategy Components

Signal Generation

Entry conditions based on:

  • Indicator crossovers
  • Price patterns
  • Volume confirmation
  • Multiple timeframe confluence

Risk Management

Essential elements:

  • Position Sizing: Based on account risk percentage
  • Stop Losses: ATR-based or support/resistance
  • Take Profits: Multiple targets or trailing stops
  • Max Positions: Limit concurrent trades

Filters

Reduce false signals:

  • Trend Filter: Only trade with the trend
  • Volatility Filter: Avoid low volatility periods
  • Time Filter: Specific trading hours
  • Volume Filter: Minimum volume requirements

Exit Rules

Multiple exit types:

  • Stop Loss: Protect capital
  • Take Profit: Lock in gains
  • Trailing Stop: Follow profitable moves
  • Time Exit: Close at end of period
  • Signal Exit: Opposite signal

Backtesting Considerations

Data Quality

  • Use clean, validated data
  • Handle missing data appropriately
  • Account for survivorship bias
  • Include realistic spreads and slippage

Performance Metrics

Track key metrics:

  • Total Return: Cumulative profit/loss
  • Sharpe Ratio: Risk-adjusted returns
  • Max Drawdown: Largest peak-to-trough decline
  • Win Rate: Percentage of profitable trades
  • Profit Factor: Gross profit / gross loss
  • Expectancy: Average $ per trade

Validation

Prevent overfitting:

  • Train/Test Split: 70/30 or 60/40
  • Walk-Forward: Rolling windows
  • Out-of-Sample: Test on recent unseen data
  • Monte Carlo: Randomize trade order
  • Paper Trading: Live validation

Common Strategy Types

Trend Following

Follow sustained price movements:

  • Moving average crossovers
  • Breakout strategies
  • Trend channels
  • Works best in trending markets

Mean Reversion

Profit from price returning to average:

  • Bollinger Band reversals
  • RSI extremes
  • Statistical arbitrage
  • Works best in ranging markets

Momentum

Trade in direction of strong moves:

  • Relative strength
  • Price acceleration
  • Volume surges
  • Breakout confirmation

Arbitrage

Exploit price discrepancies:

  • Cross-exchange spreads
  • Funding rate arbitrage
  • Statistical pairs trading
  • Requires low latency

Integration with Platform

Store strategies in your git repository under strategies/ directory.

Test using the backtesting tools provided by the platform.

Deploy live strategies through the execution engine with proper risk controls.

Monitor performance and adjust parameters as market conditions change.