Skip to content

Enterprise C# trading bot framework with backtesting engine, strategy patterns, risk management, and real-time market data

License

Notifications You must be signed in to change notification settings

AndyBodnar/TradeForge

Repository files navigation

TradeForge

A production-grade algorithmic trading framework for .NET 8, designed for building, backtesting, and deploying trading strategies.

Build Status NuGet License: MIT

Features

  • Strategy Engine - Plugin architecture for custom trading strategies
  • Backtesting Engine - Historical simulation with detailed performance metrics
  • Paper Trading - Risk-free strategy validation in real-time
  • Risk Management - Position sizing, stop-loss, and portfolio protection
  • Technical Indicators - SMA, EMA, RSI, MACD, Bollinger Bands, ATR, and more
  • REST API - Full API for strategy management and monitoring
  • CLI Tool - Command-line interface for backtesting and operations
  • Performance Analytics - Sharpe ratio, drawdown analysis, trade statistics

Architecture

TradeForge/
├── src/
│   ├── TradeForge.Core/         # Domain models, interfaces, events
│   ├── TradeForge.Engine/       # Trading engine, order execution, risk
│   ├── TradeForge.Backtesting/  # Historical backtesting engine
│   ├── TradeForge.Strategies/   # Built-in strategies and indicators
│   ├── TradeForge.Api/          # REST API (ASP.NET Core)
│   └── TradeForge.CLI/          # Command-line interface
├── tests/
│   └── TradeForge.Tests/        # Unit and integration tests
└── samples/                     # Example strategies and configurations

Quick Start

Installation

# Clone the repository
git clone https://github.com/tradeforge/tradeforge.git
cd tradeforge

# Build the solution
dotnet build

# Run tests
dotnet test

Using the CLI

# Install the CLI tool
dotnet tool install --global TradeForge.CLI

# List available strategies
tradeforge strategies

# Run a backtest
tradeforge backtest --strategy ma-crossover --symbol AAPL --capital 100000

# Show system info
tradeforge info

Using the API

# Start the API server
cd src/TradeForge.Api
dotnet run

# The API will be available at http://localhost:5000
# Swagger documentation at http://localhost:5000/swagger

API Endpoints

Endpoint Method Description
/api/engine/status GET Get engine status
/api/engine/start POST Start the trading engine
/api/engine/stop POST Stop the trading engine
/api/portfolio GET Get portfolio summary
/api/portfolio/positions GET Get open positions
/api/portfolio/trades GET Get trade history
/api/strategies GET List registered strategies
/api/strategies POST Register a new strategy
/api/backtest/run POST Run a backtest

Creating a Custom Strategy

using TradeForge.Core.Enums;
using TradeForge.Core.Models;
using TradeForge.Strategies.Base;
using TradeForge.Strategies.Indicators;

public class MyStrategy : StrategyBase
{
    private SimpleMovingAverage _sma;

    public override string Id => "my-strategy";
    public override string Name => "My Custom Strategy";

    protected override void OnInitialize()
    {
        _sma = new SimpleMovingAverage(20);
        RegisterParameter("Period", 20);
    }

    protected override Signal? OnBar(Symbol symbol, Bar bar)
    {
        _sma.Update(bar);

        if (!_sma.IsReady)
            return null;

        // Buy when price crosses above SMA
        if (bar.Close > _sma.Value && !HasPosition(symbol))
        {
            return Signal.EnterLong(symbol, bar.Close, Id,
                stopLoss: bar.Close * 0.98m);
        }

        // Sell when price crosses below SMA
        if (bar.Close < _sma.Value && HasPosition(symbol))
        {
            return Signal.ExitLong(symbol, bar.Close, Id);
        }

        return null;
    }
}

Running a Backtest

using TradeForge.Backtesting.Engine;
using TradeForge.Engine.Services;

// Configure the backtest
var config = new BacktestConfiguration
{
    StartDate = DateTime.Parse("2023-01-01"),
    EndDate = DateTime.Parse("2024-01-01"),
    TimeFrame = TimeFrame.Daily,
    WarmupPeriod = 100
};

// Create the backtest engine
var backtestEngine = new BacktestEngine(
    logger,
    tradingEngine,
    marketData,
    performanceAnalyzer,
    config);

// Run the backtest
var result = await backtestEngine.RunAsync(symbols, historicalData);

// View results
Console.WriteLine(result.Report);
Console.WriteLine($"Total Return: {result.TotalReturnPercent:F2}%");
Console.WriteLine($"Sharpe Ratio: {result.Metrics.SharpeRatio:F2}");
Console.WriteLine($"Max Drawdown: {result.Metrics.MaxDrawdown:F2}%");

Built-in Strategies

Strategy Description
ma-crossover Moving Average Crossover (Fast/Slow MA)
rsi RSI Mean Reversion (Oversold/Overbought)
macd MACD Signal Line Crossover
bollinger-bands Bollinger Bands Mean Reversion

Built-in Indicators

  • Trend: SMA, EMA
  • Momentum: RSI, MACD
  • Volatility: Bollinger Bands, ATR

Configuration

Trading Configuration

{
  "Trading": {
    "Mode": "Paper",
    "InitialCapital": 100000,
    "BaseCurrency": "USD",
    "DefaultCommission": 1,
    "Risk": {
      "MaxPositionSizePercent": 10,
      "MaxTotalExposurePercent": 100,
      "MaxPositions": 10,
      "RiskPerTradePercent": 1,
      "MaxDailyLossPercent": 3,
      "MaxDrawdownPercent": 20,
      "DefaultStopLossPercent": 2,
      "RequireStopLoss": true
    }
  }
}

Docker

# Build the image
docker build -t tradeforge-api -f src/TradeForge.Api/Dockerfile .

# Run the container
docker run -d -p 5000:8080 tradeforge-api

Performance Metrics

TradeForge calculates comprehensive performance metrics:

  • Returns: Total, Annualized, CAGR
  • Risk: Volatility, Max Drawdown, Downside Deviation
  • Risk-Adjusted: Sharpe Ratio, Sortino Ratio, Calmar Ratio
  • Trading: Win Rate, Profit Factor, Expectancy
  • Analysis: Average Win/Loss, Consecutive Wins/Losses

Contributing

Contributions are welcome! Please read our Contributing Guide for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Disclaimer

This software is for educational purposes only. Do not use this for live trading without understanding the risks. The authors are not responsible for any financial losses incurred through the use of this software.

Support

About

Enterprise C# trading bot framework with backtesting engine, strategy patterns, risk management, and real-time market data

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published