Overall Statistics
Total Trades
5366
Average Win
0.09%
Average Loss
-0.15%
Compounding Annual Return
14.419%
Drawdown
12.300%
Expectancy
0.017
Net Profit
6.552%
Sharpe Ratio
0.624
Probabilistic Sharpe Ratio
37.105%
Loss Rate
36%
Win Rate
64%
Profit-Loss Ratio
0.60
Alpha
0.051
Beta
-0.246
Annual Standard Deviation
0.189
Annual Variance
0.036
Information Ratio
1.221
Tracking Error
0.318
Treynor Ratio
-0.478
Total Fees
$6425.71
Estimated Strategy Capacity
$29000000.00
Lowest Capacity Asset
BIL TT1EBZ21QWKL
 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.Drawing;
 using System.Globalization;
 using System.Linq;
 using QuantConnect;
 using QuantConnect.Parameters;
 using QuantConnect.Benchmarks;
 using QuantConnect.Brokerages;
 using QuantConnect.Util;
 using QuantConnect.Interfaces;
 using QuantConnect.Indicators;
 using QuantConnect.Algorithm;
 using QuantConnect.Algorithm.Framework;
 using QuantConnect.Algorithm.Framework.Selection;
 using QuantConnect.Algorithm.Framework.Alphas;
 using QuantConnect.Algorithm.Framework.Portfolio;
 using QuantConnect.Algorithm.Framework.Execution;
 using QuantConnect.Algorithm.Framework.Risk;
 using QuantConnect.Data;
 using QuantConnect.Data.Consolidators;
 using QuantConnect.Data.Custom;
 using QuantConnect.Data.Fundamental;
 using QuantConnect.Data.Market;
 using QuantConnect.Data.UniverseSelection;
 using QuantConnect.Notifications;
 using QuantConnect.Orders;
 using QuantConnect.Orders.Fees;
 using QuantConnect.Orders.Fills;
 using QuantConnect.Orders.Slippage;
 using QuantConnect.Scheduling;
 using QuantConnect.Securities;
 using QuantConnect.Securities.Equity;
 using QuantConnect.Securities.Forex;
 using QuantConnect.Securities.Interfaces;
 using QuantConnect.Python;
 using QuantConnect.Storage;
 using Ind = SharpMacaco.Indicator;
 using SharpMacaco.Indicator;
 using SharpMacaco.Alpha.Model;
 using SharpMacaco.Alpha.Decorator.Strategy.Volatility;
 // using SharpMacaco.Alpha.Model.Trap;
 using SharpMacaco.Alpha.Decorator.Strategy.ToccataEFuga;
 using SharpMacaco.Alpha.Decorator.Strategy.ShadowLine;
 // using SharpMacaco.Alpha.Model.OscillatorCross;
 using SharpMacaco.Alpha.Decorator;
 using SharpMacaco.DataManagement;
 using SharpMacaco.RiskManagement.Model;
 using SharpMacaco.RiskManagement.Decorator;
 using IAlpha = SharpMacaco.Alpha.Model.IAlphaModel;
 using IRisk = SharpMacaco.RiskManagement.Model.IRiskManagementModel;

namespace QuantConnect.Algorithm.CSharp
{
    public class OneAlphaExampleAlgorithm : QCAlgorithm
    {
        private DataManager dataManager; // the place where we store and manage all shared data. We give this as a parametert to each and every alpha base

        public override void Initialize()
        {

            SetStartDate(2022, 1, 1);
            // SetEndDate(2018, 6, 1); // if commented goes until today

            // Initialize data manager
            dataManager = new DataManager(algorithm: this);  

            // Define benchmark to use
            Symbol benchmarkSymbol = AddEquity("SPY").Symbol; 

            // DEFINE INDICATOR GENERATORS


            (string id, TimeSpan resolution, Func<SingleIndicatorData<Ind.KeltnerChannels, IBaseDataBar>> generator) keltnerIndicatorInfo
            = ("keltnerIndicatorInfo", TimeSpan.FromMinutes(15), () => new SingleIndicatorData<Ind.KeltnerChannels, IBaseDataBar>(
                    new Ind.KeltnerChannels(period: 10, k: 1M)
                )
            );

            // crisis
            (string id, TimeSpan resolution, Func<MovingAverageGroupIndicatorData> generator) crisisIndicatorInfo
            = (
                id: "crisisIndicator", 
                resolution: TimeSpan.FromDays(1), 
                generator: () => new MovingAverageGroupIndicatorData(
                new()
                {
                    { "hullSlow", new MovingAverageIndicatorData(new Ind.HullMovingAverage(80)) },
                    { "hullFast", new MovingAverageIndicatorData(new Ind.HullMovingAverage(25)) }
                }
            ));
            

            // DEFINE UNIVERSES

            var universe1 = Universe.DollarVolume.Top(20);
            universe1.UniverseSettings.Resolution = Resolution.Minute;
            // var universe1 = new ManualUniverseSelectionModel(new[]{AddEquity("VOO").Symbol}).CreateUniverses(this).First();
          
            // DEFINE ALPHAS

            // this is the base of the pizza
            var base1 = new AlphaModelBase(
                resolution: TimeSpan.FromMinutes(15), // candle size is one day
                universes: new() { universe1 }, // list of universes to run this alpha on. If empty, uses all universes of the algorithm.
                symbolsToSkip: new() { benchmarkSymbol }, // list of assets we do not want to trade
                dataManager: dataManager // we use data manager to store data 
            );

            // let's add the tomato sauce, the first topping
            // first topping is always the strategy!
            AlphaDecoratorBase alpha1=new KeltnerEntryAlphaModel(
                alphaModelBase:base1,
                options:new(
                    keltnerIndicatorInfo:keltnerIndicatorInfo
                )
            );


            alpha1=new TrailingHighLowExitAlphaDecorator(
                alphaModel:alpha1, 
                options:new(
                    nrCandlesAgo:2,
                    nrBarsBeforeActivation:1
                )
            );


            // alpha1=new FullProfitableCandleExitAlphaDecorator(
            //     alphaModel:alpha1, 
            //     options:new(
            //         nrBarsBeforeActivation:1
            //     )
            // );
            
             alpha1 = new DistanceFromEntryStopLossAlphaDecorator(
                 alphaModel:alpha1,
                 options: new(
                     function: DistanceFromEntryStopLossAlphaDecorator.Fixed(
                         distancePercent: 2m / 100
                     )
                     ,nrBarsBeforeActivation: 6
                 )
            );


            // (string id, TimeSpan resolution, Func<MovingAverageIndicatorData> generator) sma5Daily
            // = ("sma5Daily", TimeSpan.FromDays(1), () => new MovingAverageIndicatorData(new Ind.SimpleMovingAverage(5)));

            // (string id, TimeSpan resolution, Func<MovingAverageIndicatorData> generator) ema3Daily
            // = ("ema3Daily", TimeSpan.FromDays(1), () => new MovingAverageIndicatorData(new Ind.ExponentialMovingAverage(3)));

            

            // alpha1 = new GeneralEntryExitRulesAlphaDecorator(
            //     alphaModel: alpha1,
            //     options: new(
            //         exitEndOfDay: false,
            //         exitEndOfDayOnlyIfPofitable: false,
            //         strategyExitOnlyIfProfitable: false,
            //         allowLong: true,
            //         allowShort: true,
            //         lastMinutes: TimeSpan.FromMinutes(5),
            //         allowEntryOnLastMinutes: false,
            //         allowExitOnLastMinutes: true,
            //         allowExitOnSameBar: true
            //     )
            // );
            
            // alpha1 = new MovingAverageStopLossAlphaDecorator(
            //     alphaModel: alpha1,
            //     options: new(
            //         stopLossIndicatorInfo: sma5Daily,
            //         exitTrendIndicatorInfo: ema3Daily,
            //         activateOnlyIfProfitable: false,
            //         activateOnlyIfItFollowsExitTrend: true,
            //         forceAfterGapSizePercent: 5m / 100, // TODO: discuss about this parameter
            //         distancePercent: 3m / 100
            //     )
            // );

            // alpha1 = new CrisisRulesAlphaDecorator(
            //     alphaModel: alpha1,
            //     options: new(
            //         crisisIndicatorInfo: crisisIndicatorInfo
            //     )
            // );
            

            // DEFINE PORTFOLIO

            Dictionary<string, SharpMacaco.Portfolio.AlphaDiversificationOptions> alphaDiversificationOptions
            = new(){
                // {rsiAlpha.Name, new(
                //     maxNrEntries: 5,
                //     maxValue: 50_000,
                //     period: TimeSpan.FromDays(1)
                // )},
            };

            var portfolioModel = new SharpMacaco.Portfolio.PortfolioConstructionModel(
                alphaDiversificationOptions: alphaDiversificationOptions,
                startHoursToEnterPositions: 10,
                endHoursToEnterPositions: 15.5,
                minimumHoursBetweenTrades: 0,
                oneTradePerPeriod: false,
                lowestOrderLimit: 10000,
                feeBudget: 1000,
                highestOrderLimitPercent: 20m / 100
            );


            // DEFINE risk management

            // // this is the base of the pizza
            // var riskBase1 = new RiskManagementModelBase(
            //     dataManager: dataManager,
            //     universes: new() {} // list of universes. If empty it means it manages risk for all universes
            // );

            // // empty topping (Noop = No-Operation)
            // IRisk riskManagementModel1 = new NoopRiskManagementDecorator(riskBase1);

            // riskManagementModel1 = new CrisisRiskManagementDecorator(
            //     riskManagementModel1,
            //     new(
            //         indicatorInfo: crisisIndicatorInfo,
            //         symbols: new() { benchmarkSymbol },
            //         allowLongDuringBearishMarket: false,
            //         allowLongDuringSidewaysMarket: true,
            //         allowShortDuringSidewaysMarket: true,
            //         allowShortDuringBullishMarket: false
            // ));


            // DEFINE execution model

            var executionModel = new SharpMacaco.Execution.ExecutionModel();


            // ALGORITHM is always made of the following modules
            // - universes
            // - alphas
            // - portfolio management
            // - risk management [OPTIONAL]
            // - execution management

            SharpMacaco.Analysis.Charts.AddAllPlots(new(showInDashboard: false, saveInObjectStore: true));
            SharpMacaco.Analysis.Charts.PlotDailyPerformance(this);
            SharpMacaco.Analysis.Charts.SetUpChartingObjectStoreWrites(this);
            

            // here we SERVE the pizza
            AddUniverse(universe1);
            AddAlpha(alpha1);
            SetPortfolioConstruction(portfolioModel);
        //    AddRiskManagement(riskManagementModel1); // facultative
            SetExecution(executionModel);  

        }

        public override void OnEndOfAlgorithm() {
            SharpMacaco.Analysis.Charts.WriteChartsCacheToObjectStore(this);
        }

    }

}