Overall Statistics
Total Trades
741
Average Win
1.37%
Average Loss
-0.27%
Compounding Annual Return
46.660%
Drawdown
8.700%
Expectancy
3.681
Net Profit
3383.836%
Sharpe Ratio
2.712
Loss Rate
22%
Win Rate
78%
Profit-Loss Ratio
5.04
Alpha
0.718
Beta
-25.619
Annual Standard Deviation
0.115
Annual Variance
0.013
Information Ratio
2.573
Tracking Error
0.115
Treynor Ratio
-0.012
Total Fees
$1370.85
/*
 * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
 * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

using System;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Indicators;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// EMA cross with SP500 E-mini futures
    /// In this example, we demostrate how to trade futures contracts using an equity to generate the trading signals
    /// It also shows how you can prefilter contracts easily based on expirations.
    /// It also shows how you can inspect the futures chain to pick a specific contract to trade.
    /// </summary>
    /// <meta name="tag" content="using data" />
    /// <meta name="tag" content="futures" />
    /// <meta name="tag" content="indicators" />
    /// <meta name="tag" content="strategy example" />
    public class FuturesMomentumAlgorithm : QCAlgorithm
    {
		private const decimal _tolerance = 0.001m;
        private const int _fastPeriod = 4;
        private const int _slowPeriod = 40;

        private ExponentialMovingAverage _fast;
        private ExponentialMovingAverage _slow;

        public bool IsReady { get { return _fast.IsReady && _slow.IsReady; } }
        public bool IsUpTrend { get { return IsReady && _fast > _slow * (1 + _tolerance); } }
        public bool IsDownTrend { get { return IsReady && _fast < _slow * (1 + _tolerance); } }

        public override void Initialize()
        {
            SetStartDate(2009, 05, 03);
            SetEndDate(2018, 08, 06);
            SetCash(10000);
            SetWarmUp(Math.Max(_fastPeriod, _slowPeriod));
            SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash);


            // Adds SPY to be used in our EMA indicators
            var equity = AddEquity("SPY", Resolution.Minute);
            _fast = EMA(equity.Symbol, _fastPeriod, Resolution.Hour);
            _slow = EMA(equity.Symbol, _slowPeriod, Resolution.Hour);

            // Adds the future that will be traded and
            // set our expiry filter for this futures chain
            var future = AddFuture(Futures.Indices.SP500EMini);
            future.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));

        }

        public override void OnData(Slice slice)
        {
            if (!Portfolio.Invested && IsUpTrend)
            {
                foreach (var chain in slice.FutureChains)
                {
                    // find the front contract expiring no earlier than in 90 days
                    var contract = (
                        from futuresContract in chain.Value.OrderBy(x => x.Expiry)
                        where futuresContract.Expiry > Time.Date.AddDays(90)
                        select futuresContract
                        ).FirstOrDefault();
                        

                    // if found, trade it
                    if (contract != null)
                    {
                        MarketOrder(contract.Symbol, 1);
                    }
                }
            }

            if (Portfolio.Invested && IsDownTrend)
            {
            	Liquidate();
            }
        }

        public override void OnEndOfDay()
        {
            Plot("Indicator Signal", "EOD", IsDownTrend ? -1 : IsUpTrend ? 1 : 0);
        }

        public override void OnOrderEvent(OrderEvent orderEvent)
        {
            Log(orderEvent.ToString());
        }
    }
}