A simple and high-performance algorithmic trading backtesting framework for .NET, designed for portfolio based strategy development using market orders.
- Multi-Asset Support - Trade multiple assets at once
- Multi-Strategy Framework - Run multiple trading strategies simultaneously with independent or coordinated execution
- Composable Nested Sub-Strategies - Build complex hierarchical strategies by nesting and combining simpler strategies
- Nested Backtests - Run backtests within backtests for meta-strategy development and validation
- Online Portfolio Optimization - Real-time portfolio allocation using FixedShare and ExponentiatedGradient algorithms
- Comprehensive Analytics - Built-in performance metrics, drawdown analysis, and Sharpe ratio calculation
- Flexible Scheduling - Event-driven execution with calendar integration
- Realistic Market Simulation - Configurable spreads, commissions, and market impact models
- Risk Management - Position sizing, leverage controls, and portfolio constraints
git clone https://github.com/trenki2/NStrat.git
cd NStrat
dotnet buildusing NStrat.Core;
using NStrat.Core.Securities;
using NStrat.Core.Technical;
namespace NStrat.Strategies.Basic
{
public class RsiLowHigh(SecurityId sid, int period, double low, double high) : Strategy
{
public int Lookback { get; init; } = 42;
protected override void OnInitialize()
{
Benchmark = AddSecurity(sid);
}
protected override void OnUpdate()
{
var close = Benchmark!.GetHistory().Close.TakeLast(Lookback).ToArray();
var rsi = TA.Rsi(close, period)[^1];
if (rsi < low)
OrderTargetPercent(Benchmark, 1);
else if (rsi > high)
OrderTargetPercent(Benchmark, 0);
}
}
}The repository includes several example strategies demonstrating different approaches:
- Example1 - Multi-strategy allocation with Buy-and-Hold and RSI
- Example2 - Tech stock portfolio with dynamic rebalancing
- Example3 - Sector rotation using momentum ranking
Strategy- Base class for all trading strategiesFixedShare- Dynamic portfolio allocation algorithmApplyPortfolio- Executes portfolio allocation decisionsStats- Performance tracking and analytics
TradingCalendar- Market schedule and holiday handlingSpreadModel- Bid-ask spread simulationCommissionModel- Transaction cost modelingBroker- Order execution and portfolio management
- Moving averages, RSI, momentum indicators
- Crossover signals and trend detection
- Custom indicator development framework
SetStartDate(new DateTime(2020, 1, 1));
SetEndDate(DateTime.Today);
SetCash(100000);
Benchmark = AddEquity("SPY");TradingCalendar = new UsaEquityTradingCalendar();
SpreadModel = new RelativeSpread(0.001m); // 0.1% spread
CommissionModel = new PerTradeVolumeCommission(0.001m); // $0.001 per shareNStrat provides comprehensive performance metrics:
- Returns Analysis - Total return, annualized return, volatility
- Risk Metrics - Maximum drawdown, Sharpe ratio, Sortino ratio
- Portfolio Analytics - Leverage, concentration, turnover
- Regime Detection - Market trend and volatility analysis
Build complex hierarchical strategies by composing and nesting simpler components:
var strategy1 = new BuyAndHold("QQQ");
var strategy2 = new RsiLowHigh("QQQ", 2, 25, 75);
var level1 = new FixedShare(strategy1, strategy2);
var strategy3 = new SectorRotation(sectorETFs);
var level2 = new ExponentiatedGradient(level1, strategy3);
AddSubStrategy(new ApplyPortfolio(level2));Real-time adaptive allocation using state-of-the-art algorithms:
// FixedShare: Maintains fixed fraction of wealth in each strategy
var fixedShare = new FixedShare(strategies) {
Eta = 50, // Learning rate
Alpha = 1e-4 // Regularization
};
// ExponentiatedGradient: Multiplicative weight updates
var expGrad = new ExponentiatedGradient(strategies) {
Eta = 0.1
};Control rebalancing frequency and transaction costs:
var monthlyRebalance = new UpdateRate(strategy, 21); // Rebalance every 21 days
var stats = new Stats(monthlyRebalance);Execute strategies on flexible schedules:
Schedule.On(DateRules.MonthStart(TradingCalendar),
TimeRules.At(9, 30, 0, TimeZones.Est),
MonthlyRebalance);- .NET 8.0 or later
- Visual Studio 2022 or VS Code
- Windows
This project is licensed under the GNU Affero General Public License v3.0 - see the LICENSE file for details.
This software is for educational and research purposes only. Past performance does not guarantee future results. Always consult with qualified financial professionals before making investment decisions.