Overall Statistics
Total Trades
976
Average Win
0.02%
Average Loss
-0.02%
Compounding Annual Return
-0.910%
Drawdown
1.100%
Expectancy
-0.097
Net Profit
-0.912%
Sharpe Ratio
-1.059
Loss Rate
56%
Win Rate
44%
Profit-Loss Ratio
1.06
Alpha
-0.006
Beta
-0.005
Annual Standard Deviation
0.006
Annual Variance
0
Information Ratio
-0.071
Tracking Error
0.132
Treynor Ratio
1.18
Total Fees
$0.00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QuantConnect.Data.Market;

namespace QuantConnect.Algorithm.CSharp
{
    class ProfitTargetSignalExit : IExitSignal
    {
        private TradeProfile _tradeProfile;
        private decimal _targetProfitLossRatio;

        public ProfitTargetSignalExit() { }

        public ProfitTargetSignalExit(TradeProfile tradeProfile, decimal targetProfitLossRatio)
        {
            _tradeProfile = tradeProfile;
            _targetProfitLossRatio = targetProfitLossRatio;
        }

        public void Scan(TradeBar data)
        {
            if (_tradeProfile.ProfitLossRatio > _targetProfitLossRatio)
            {
                Signal = SignalType.Exit;
            }
            else
            {
                Signal = SignalType.NoSignal;
            }
        }

        public SignalType Signal { get; private set; }

        public ISignal ExitSignalFactory(TradeProfile tradeProfile)
        {
            return new ProfitTargetSignalExit(tradeProfile, _targetProfitLossRatio);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QuantConnect.Data.Market;
using QuantConnect.Securities;

namespace QuantConnect.Algorithm.CSharp
{
    class OneShotTrigger : ISignal
    {
        private ISignal _signal;
        private SignalType _previousSignalType;
        public OneShotTrigger(ISignal signal)
        {
            _signal = signal;
            Signal = SignalType.NoSignal;
            _previousSignalType = SignalType.NoSignal;
        }

        public void Scan(TradeBar data)
        {
            _signal.Scan(data);

            if (_signal.Signal != _previousSignalType)
            {
                Signal = _signal.Signal;
            }
            else
            {
                Signal = SignalType.NoSignal;
            }
            _previousSignalType = _signal.Signal;
        }

        public SignalType Signal { get; private set; }
    }
}
using System;
using System.Collections.Generic;
using System.Security.Permissions;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using QuantConnect.Securities;

namespace QuantConnect.Algorithm.CSharp
{
    class RsiSignal : ISignal
    {
        private RelativeStrengthIndex _rsi;
        private SecurityHolding _securityHolding;

        public RsiSignal(RelativeStrengthIndex rsi, SecurityHolding securityHolding)
        {
            _rsi = rsi;
            _securityHolding = securityHolding;
        }

        public void Scan(TradeBar data)
        {
            if (_rsi > 70 && !_securityHolding.Invested)
            {
                Signal = SignalType.Short;
            }
            else if (_rsi < 30 && !_securityHolding.Invested)
            {
                Signal = SignalType.Long;
            }
            else
            {
                Signal = SignalType.NoSignal;
            }
        }

        public SignalType Signal { get; private set; }
    }



}
using QuantConnect.Data.Market;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// Base Signal Interface
    /// </summary>
    public interface ISignal
    {
        void Scan(TradeBar data);

        SignalType Signal { get; }
    }

    public interface IExitSignal : ISignal
    {
        ISignal ExitSignalFactory(TradeProfile tradeProfile);
    }



    public enum SignalType
    {
        Long = 1,
        Short = -1,
        Exit = 2,
        NoSignal = 0
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Securities;

namespace QuantConnect.Algorithm.CSharp
{
    class TradingAsset
    {
        public IExitSignal ExitSignal;
        public ISignal EnterSignal;

        private decimal _risk;
        private Symbol _symbol;
        private Security _security;
        private decimal _maximumTradeSize;
        private List<TradeProfile> _tradeProfiles;
        private IRequiredOrderMethods _orderMethods;
        // private decimal _targetProfitLossRatio;

        /// <summary>
        /// Initializes each Trading Asset
        /// </summary>
        /// <param name="security"></param>
        /// <param name="enterSignal"></param>
        /// <param name="exitSignal"></param>
        /// <param name="risk"></param>
        /// <param name="maximumTradeSize"></param>
        /// <param name="orderMethods"></param>
        public TradingAsset(Security security, ISignal enterSignal, IExitSignal exitSignal, decimal risk, decimal maximumTradeSize, IRequiredOrderMethods orderMethods)
        {
            _security = security;
            _symbol = _security.Symbol;
            EnterSignal = enterSignal;
            ExitSignal = exitSignal;
            _risk = risk;
            _maximumTradeSize = maximumTradeSize;
            _orderMethods = orderMethods;
            _tradeProfiles = new List<TradeProfile>();
        }

        /// <summary>
        /// Scan
        /// </summary>
        /// <param name="data"></param>
        public void Scan(TradeBar data)
        {
            foreach (var tradeProfile in _tradeProfiles)
            {
                tradeProfile.CurrentPrice = data.Close;
            }
            MarkStopTicketsFilled();
            EnterTradeSignal(data);
            ExitTradeSignal(data);
            RemoveAllFinishedTrades();
        }

        /// <summary>
        /// Executes all the logic when the Enter Signal is triggered
        /// </summary>
        /// <param name="data"></param>
        public void EnterTradeSignal(TradeBar data)
        {
            EnterSignal.Scan(data);
            if (EnterSignal.Signal == SignalType.Long || EnterSignal.Signal == SignalType.Short)
            {
                //Creates a new trade profile once it enters a trade
                var profile = new TradeProfile(_symbol, _security.VolatilityModel.Volatility, _risk, data.Close, _maximumTradeSize);
               
                profile.ExitSignal = ExitSignal.ExitSignalFactory(profile);

                var profileQuantity = profile.Quantity;
                if (profileQuantity > 0)
                {
                    profile.OpenTicket = _orderMethods.MarketOrder(_symbol, (int)EnterSignal.Signal * profile.Quantity);
                    profile.StopTicket = _orderMethods.StopMarketOrder(_symbol, -(int)EnterSignal.Signal * profile.Quantity,
                        profile.OpenTicket.AverageFillPrice - (int)EnterSignal.Signal * profile.DeltaStopLoss);

                    _tradeProfiles.Add(profile);
                }
            }
        }

        /// <summary>
        /// Executes all the logic when the Exit Signal is triggered
        /// </summary>
        /// <param name="data"></param>
        public void ExitTradeSignal(TradeBar data)
        {
            foreach (var tradeProfile in _tradeProfiles.Where(x => x.IsTradeFinished == false))
            {
                tradeProfile.ExitSignal.Scan(data);

                if (tradeProfile.ExitSignal.Signal == SignalType.Exit)
                {
                    if (tradeProfile.StopTicket.Status != OrderStatus.Filled)
                    {
                        tradeProfile.ExitTicket = _orderMethods.MarketOrder(_symbol, -(int)tradeProfile.OpenTicket.QuantityFilled);
                        tradeProfile.StopTicket.Cancel();

                        tradeProfile.IsTradeFinished = true;
                    }
                }
            }
        }

        /// <summary>
        /// Marks all the trades as finished which are completed due to hitting the stop loss
        /// </summary>
        public void MarkStopTicketsFilled()
        {
            foreach (var tradeProfile in _tradeProfiles)
            {
                if (tradeProfile.StopTicket.Status == OrderStatus.Filled)
                {
                    tradeProfile.IsTradeFinished = true;
                }
            }
        }

        /// <summary>
        /// Removes all the completed trades from the trade profile list
        /// </summary>
        public void RemoveAllFinishedTrades()
        {
            _tradeProfiles = _tradeProfiles.Where(x => !x.IsTradeFinished).ToList();
        }
    }
}
using QuantConnect.Orders;

namespace QuantConnect.Algorithm.CSharp
{
    public class TradeProfile
    {

        //Ticket tracking the open order
        public OrderTicket OpenTicket, StopTicket, ExitTicket;
        //Keeps track of the current price and the direction of the trade
        public decimal CurrentPrice;
        public int TradeDirection;
        public Symbol TradeSymbol;
        private bool isTradeFinished;

        private decimal _risk;
        private int _maximumTradeQuantity;
        protected decimal _volatility;


        // Calclate the quantity based on the target risk in dollars.
        public int Quantity
        {
            get
            {
                if (_volatility == 0) return 0;
                long quantity = (long)(_risk / _volatility);
                if (quantity > _maximumTradeQuantity) return _maximumTradeQuantity;
                return (int)quantity;
            }
        }

        //What is the stoploss move from current price
        public decimal DeltaStopLoss
        {
            get
            {
                if (Quantity == 0) return 0m;
                return _risk / Quantity;
            }
        }

        /// <summary>
        /// Calculates  the Profit:Loss ratio
        /// </summary>
        public decimal ProfitLossRatio
        {
            get
            {
                if(OpenTicket != null)
                {
                      return OpenTicket.Quantity*(CurrentPrice - OpenTicket.AverageFillPrice)  /_risk;
                }
                return 0m;
            }
        }

        /// <summary>
        /// Exit signal for each trade
        /// </summary>
        public ISignal ExitSignal
        {
            get;
            set;
        }

        public bool IsTradeFinished
        {
            get
            {
                return isTradeFinished;
            }

            set
            {
                isTradeFinished = value;
            }
        }


        /// <summary>
        /// Create a new tradeProfile and limit the maximum risk.
        /// </summary>
        /// <param name="symbol"></param>
        /// <param name="volatility"></param>
        /// <param name="risk"></param>
        /// <param name="currentPrice"></param>
        /// <param name="maximumTradeSize"></param>
        /// <param name="exitSignal"></param>
        public TradeProfile(Symbol symbol, decimal volatility, decimal risk, decimal currentPrice, decimal maximumTradeSize)
        {
            TradeSymbol = symbol;
            _volatility = volatility;
            _risk = risk;
            CurrentPrice = currentPrice;
            _maximumTradeQuantity = (int) (maximumTradeSize/CurrentPrice);
        }
    }
}
/*
 * 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.Collections.Generic;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Securities;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// Basic template algorithm simply initializes the date range and cash
    /// </summary>
    public class BasicTemplateAlgorithm : QCAlgorithm, IRequiredOrderMethods
    {
        //Configure which securities you'd like to use:
        public string[] Symbols = { "EURUSD", "GBPUSD" };

        //Risk in dollars per trade ($ or the quote currency of the assets)
        public decimal RiskPerTrade = 10;

        //Sets the profit to loss ratio we want to hit before we exit
        public decimal TargetProfitLossRatio = 0.1m;

        //Cap the investment maximum size ($).
        public decimal MaximumTradeSize = 10000;

        private Resolution _dataResolution = Resolution.Minute;
        private Dictionary<Symbol, TradingAsset> _tradingAssets;

        //List to store the RSI value for each asset
        private RelativeStrengthIndex _rsi;

        public override void Initialize()
        {
            SetStartDate(2015, 1, 1);
            SetEndDate(2016, 1, 1);
            SetCash(25000);
            _tradingAssets = new Dictionary<Symbol, TradingAsset>();

            //Add as many securities as you like. All the data will be passed into the event handler:
            foreach (var symbol in Symbols)
            {
                AddSecurity(SecurityType.Forex, symbol, _dataResolution);
                Securities[symbol].FeeModel = new ConstantFeeModel(0m);
                //SetBrokerageModel(BrokerageName.FxcmBrokerage);

                //Initializes the RSI
                _rsi = RSI(symbol, 60, MovingAverageType.Exponential, _dataResolution);

                var tradeBarHistory = History(symbol, TimeSpan.FromDays(2), _dataResolution);

                //Warms up the RSI
                foreach (var tradeBar in tradeBarHistory)
                {
                    _rsi.Update(tradeBar.EndTime, tradeBar.Close);
                }

                Securities[symbol].VolatilityModel = new ThreeSigmaVolatilityModel(STD(symbol, 390, _dataResolution));
                _tradingAssets.Add(symbol,
                    new TradingAsset(Securities[symbol],
                        new TimeSignal(TimeSpan.FromHours(9.5)),
                        new TimeSignalExit(null, TimeSpan.FromHours(16)), 
                        RiskPerTrade,
                        MaximumTradeSize,
                        this
                    ));
            }
        }

        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        public void OnData(TradeBars data)
        {

            foreach (var symbol in Symbols)
            {
                //Create a trading asset package for each symbol 
                _tradingAssets[symbol].Scan(data[symbol]);
            }
        }
    }

    /// <summary>
    /// Interface for the two types of orders required to make the trade
    /// </summary>
    public interface IRequiredOrderMethods
    {
        OrderTicket StopMarketOrder(Symbol symbol, int quantity, decimal stopPrice, string tag = "");
        OrderTicket MarketOrder(Symbol symbol, int quantity, bool asynchronous = false, string tag = "");
    }
}
/*
 * 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 MathNet.Numerics.Statistics;
using QuantConnect.Data;
using QuantConnect.Indicators;

namespace QuantConnect.Securities
{
    /// <summary>
    /// Provides an implementation of <see cref="IVolatilityModel"/> that computes the
    /// relative standard deviation as the volatility of the security
    /// </summary>
    public class ThreeSigmaVolatilityModel : IVolatilityModel
    {
        private StandardDeviation _standardDeviation;


        /// <summary>
        /// Gets the volatility of the security as a percentage
        /// </summary>
        public decimal Volatility
        {
            get { return _standardDeviation*3m; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="QuantConnect.Securities.RelativeStandardDeviationVolatilityModel"/> class
        /// </summary>
        /// <param name="periodSpan">The time span representing one 'period' length</param>
        /// <param name="periods">The nuber of 'period' lengths to wait until updating the value</param>
        public ThreeSigmaVolatilityModel(StandardDeviation standardDeviation)
        {
            _standardDeviation = standardDeviation;
        }

        /// <summary>
        /// Updates this model using the new price information in
        /// the specified security instance
        /// </summary>
        /// <param name="security">The security to calculate volatility for</param>
        /// <param name="data"></param>
        public void Update(Security security, BaseData data)
        {
           
        }
        
    }
}
using System;
using QuantConnect.Data.Market;
using QuantConnect.Orders;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// This Time Signal Enters the trade at a particular time and exits the trade at a particular time set for the entery and exit
    /// </summary>
    public class TimeSignal : ISignal
    {
        private readonly Random _random = new Random(131);
        private readonly TimeSpan _timeOfDay;

        public TimeSignal(TimeSpan timeOfDay)
        {
            _timeOfDay = timeOfDay;
        }

        /// <summary>
        /// Scans the new data coming in and randomly assigns direction if entry conditions are met
        /// </summary>
        /// <param name="data"></param>
        public void Scan(TradeBar data)
        {
            if (data.Time.TimeOfDay == _timeOfDay)
            {
                Signal = (RandomOrderDirection() == OrderDirection.Buy) ? SignalType.Long : SignalType.Short;
            }
            else
            {
                Signal = SignalType.NoSignal;
            }
        }

        /// <summary>
        /// Signal value for the binary signal
        /// </summary>
        public SignalType Signal { get; private set; }

        /// <summary>
        /// Produces a random direction for the signal to trade
        /// </summary>
        /// <returns></returns>
        private OrderDirection RandomOrderDirection()
        {
            if (_random.NextDouble() > 0.5)
                return OrderDirection.Buy;
            return OrderDirection.Sell;
        }
    }
}
using System;
using QuantConnect.Data.Market;
using QuantConnect.Orders;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// This Time Signal Enters the trade at a particular time and exits the trade at a particular time set for the entery and exit
    /// </summary>
    public class TimeSignalExit : IExitSignal
    {
        private readonly Random _random = new Random(131);
        private readonly TimeSpan _timeOfDay;
        private TradeProfile _tradeProfile;

        public TimeSignalExit(TradeProfile tradeprofile, TimeSpan timeOfDay)
        {
            _timeOfDay = timeOfDay;
            _tradeProfile = tradeprofile;
        }

        /// <summary>
        /// Scans the new data coming in and randomly assigns direction if entry conditions are met
        /// </summary>
        /// <param name="data"></param>
        public void Scan(TradeBar data)
        {
            if (data.Time.TimeOfDay == _timeOfDay)
            {
                Signal = SignalType.Exit;
            }
            else
            {
                Signal = SignalType.NoSignal;
            }
        }

        /// <summary>
        /// Signal value for the binary signal
        /// </summary>
        public SignalType Signal { get; private set; }

        public ISignal ExitSignalFactory(TradeProfile tradeProfile)
        {
            return new TimeSignalExit(tradeProfile, _timeOfDay);
        }

        /// <summary>
        /// Produces a random direction for the signal to trade
        /// </summary>
        /// <returns></returns>
        // private OrderDirection RandomOrderDirection()
        // {
        //     if (_random.NextDouble() > 0.5)
        //         return OrderDirection.Buy;
        //     return OrderDirection.Sell;
        // }
    }
}