Overall Statistics
Total Trades
6891
Average Win
0.05%
Average Loss
-0.40%
Compounding Annual Return
19.589%
Drawdown
4.500%
Expectancy
0.012
Net Profit
26.859%
Sharpe Ratio
1.789
Loss Rate
10%
Win Rate
90%
Profit-Loss Ratio
0.12
Alpha
0.127
Beta
-0.04
Annual Standard Deviation
0.07
Annual Variance
0.005
Information Ratio
1.057
Tracking Error
0.095
Treynor Ratio
-3.179
Total Fees
$13784.36
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
    }
}
/*
 * 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;
using QuantConnect.Util;

namespace QuantConnect.Algorithm.CSharp
{
    public class TrendVolatilityForex : QCAlgorithm, IRequiredOrderMethods
    {
        public string[] Symbols = { "EURUSD", "GBPUSD", "NZDUSD", "AUDUSD" };
        public decimal RiskPerTrade = 400;
        public decimal TargetProfitLossRatio = 0.1m;
        public decimal MaximumTradeSize = 100000;
        private Resolution _dataResolution = Resolution.Minute;
        private Dictionary<Symbol, TradingAsset> _tradingAssets;
        private RelativeStrengthIndex _rsi;
        
        public override void Initialize()
        {
            SetStartDate(2013, 1, 1);
            SetEndDate(DateTime.Now);
            SetCash(100000);
            //SetBrokerageModel(Brokerages.BrokerageName.OandaBrokerage,AccountType.Margin);
            _tradingAssets = new Dictionary<Symbol, TradingAsset>();
            SetBenchmark(SecurityType.Forex, "EURUSD");
            
            foreach (var symbol in Symbols)
            {
                AddSecurity(SecurityType.Forex, symbol, _dataResolution, Market.Oanda, true, 50m, false);
                //Securities[symbol].FeeModel = new ConstantFeeModel(0.04m);
                _rsi = RSI(symbol, 60, MovingAverageType.Exponential, _dataResolution);
                var tradeBarHistory = History(symbol, TimeSpan.FromDays(2), _dataResolution);
                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 OneShotTrigger(new RsiSignal(_rsi, Portfolio[symbol])),
                        new ProfitTargetSignalExit(null, TargetProfitLossRatio),
                        RiskPerTrade,
                        MaximumTradeSize,
                        this
                    ));
            }
        }

        public void OnData(TradeBars data)
        {
            foreach (var symbol in Symbols)
            {
                //Create a trading asset package for each symbol 
                var curSymb = new Symbol(SecurityIdentifier.GenerateForex(symbol,"Oanda"),symbol);
                if (data.Count < Symbols.Length) return;
                if (data.ContainsKey(symbol))
                    _tradingAssets[curSymb].Scan(data[curSymb]);
            }
        }

        public override void OnEndOfDay()
        {
            foreach (var symbol in Symbols)
            {
                Plot("Charts", "Holdings", Portfolio[symbol].Quantity);
                Plot("Charts", "RSI", _rsi);
            }
        }

    }

    /// <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 = "");
    }
}
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.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.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.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);
                //Check if the value for the maximum trade quantity is less than zero to avoid placing 0 value trade
                if (quantity > _maximumTradeQuantity)
                {
                    return _maximumTradeQuantity < 1000 ? 1000 : _maximumTradeQuantity;
                }

                return (int)quantity < 1000 ? 1000 : (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);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Securities;
//using QuantConnect.Logging;

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)
                {
                    //var stopLoss = Math.Round(profile.OpenTicket.AverageFillPrice - (int)EnterSignal.Signal * profile.DeltaStopLoss,5);
                    profile.OpenTicket = _orderMethods.MarketOrder(_symbol, (int)EnterSignal.Signal * profile.Quantity);
                    profile.StopTicket = _orderMethods.StopMarketOrder(_symbol, -(int)EnterSignal.Signal * profile.Quantity,
                        Math.Round(profile.OpenTicket.AverageFillPrice - (int)EnterSignal.Signal * profile.DeltaStopLoss, 5));
                    //Log.Trace(data.Time + " ENTER "+_symbol+" "+ (int)EnterSignal.Signal * profile.Quantity+" @"+data.Close+ " "+_security.Holdings.Profit);
                    //Log.Trace(data.Time + " STOP " + _symbol + " @" + (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();
                        //Log.Trace(data.Time + " EXIT " +  _symbol+ " "+ -(int)tradeProfile.OpenTicket.QuantityFilled + " @" + data.Close + " " + _security.Holdings.Profit);
                        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 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 * 2.5m; }
        }

        /// <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)
        {

        }

    }
}