Overall Statistics
Total Trades
390
Average Win
0%
Average Loss
-0.01%
Compounding Annual Return
-99.903%
Drawdown
3.100%
Expectancy
-1
Net Profit
-3.120%
Sharpe Ratio
-11.225
Loss Rate
100%
Win Rate
0%
Profit-Loss Ratio
0
Alpha
0
Beta
-1.217
Annual Standard Deviation
0.35
Annual Variance
0.123
Information Ratio
-11.225
Tracking Error
0.638
Treynor Ratio
3.229
Total Fees
$780.00
namespace QuantConnect
{
    public partial class TestingTrailingOrders : QCAlgorithm
    {
        #region Wrapper methods
        /// <summary>
        /// Instantiate a stop trailing order with stop price estiamted as a price fixed percentage 
        /// </summary>
        /// <param name="symbol">Symbol asset we're seeking to trade.</param>
        /// <param name="quantity">Quantity of the asset we're seeking to trade.</param>
        /// <param name="price">The actual symbol's price.</param>
        /// <param name="pricePercentage">The price fixed percentage used to estiamte the stop price.</param>
        /// <param name="time">Time the order was placed.</param>
        /// <returns>A trailing stop order</returns>
        public TrailingStopOrder FixedTrailingStopOrder(string symbol, int quantity, decimal price, decimal pricePercentage, DateTime time)
        {
            var order = new TrailingStopOrder(this, symbol, quantity, price, pricePercentage, time);
            var returnCode = Transactions.AddOrder(order.StopOrder);
            
            if(returnCode < 1)
            {
                Console.WriteLine("Error [{0}] submitting {1}", returnCode, order.StopOrder);
            }
            return order;
        }

        /// <summary>
        /// Instantiate a stop trailing order with stop price estiamted as price +/- a standar deviation.
        /// </summary>
        /// <param name="symbol">Symbol asset we're seeking to trade</param>
        /// <param name="quantity">Quantity of the asset we're seeking to trade.</param>
        /// <param name="series">Historical prices used to estimate the standar deviation</param>
        /// <param name="lookBackWindow">The look back window used to estimate the standar deviation.</param>
        /// <param name="time">Time the order was placed.</param>
        /// <returns></returns>
        public TrailingStopOrder SDTrailingStopOrder(string symbol, int quantity, List<decimal> series, int lookBackWindow, DateTime time)
        {
            var order = new TrailingStopOrder(this, symbol, quantity, series, lookBackWindow, time);
            Transactions.AddOrder(order.StopOrder);
            return order;
        }
        #endregion
    }
}
namespace QuantConnect
{
    /// <summary>
    /// Method used to trailing the stop loss price.
    /// </summary>
    public enum TrailingMethod
    {
        FixedPercentage,
        StandardDeviationStop, // not fully implemented yet
        // WIP
    }

    /// <summary>
    /// Stop Market Order Type Definition
    /// </summary>
    public class TrailingStopOrder // : QCAlgorithm, IDisposable
    {
        #region Fields and properties
		
		/// Algorithm reference for updating orders and logging
        /// </summary>
        private readonly QCAlgorithm _algorithm;
		
        /// <summary>
        /// The symbol which this order will track.
        /// </summary>
        private string _symbol;

        /// <summary>
        /// The fixed percentage to determine the trailing stop price.
        /// </summary>
        private decimal _stopPricePercentage;

        /// <summary>
        /// The window look-back to estimate the standard deviations stop prices.
        /// </summary>
        private int _windowLookback;

        /// <summary>
        /// The series history used to estimate the standard deviations stop prices.
        /// </summary>
        private RollingWindow<decimal> _seriesHistory;

        /// <summary>
        /// The StopMarketOrder object to be used.
        /// </summary>
        public StopMarketOrder StopOrder;

        /// <summary>
        /// Stop price for this stop market order.
        /// </summary>
        public decimal StopPrice;

        /// <summary>
        /// Is the stop price allowed to move backwards?
        /// </summary>
        public bool AllowStopPriceRetreat; // not implemented yet

        /// <summary>
        /// The trailing method used to determine the stop price.
        /// </summary>
        public TrailingMethod trailingMethod;

        /// <summary>
        /// Maximum value of the order at is the stop limit price
        /// </summary>
        public decimal Value
        {
            get { return StopOrder.Quantity * StopOrder.StopPrice; }
        }
        #endregion

        #region Constructor and destructor
        /// <summary>
        /// Initializes a new instance of the <see cref="TrailingStopOrder"/> class.
        /// </summary>
        /// <param name="stopOrder">The stop order.</param>
        public TrailingStopOrder(QCAlgorithm algorithm, string symbol, int quantity, decimal price, decimal pricePercentage, DateTime time)
        {
			_algorithm = algorithm;
            _symbol = symbol;
            _stopPricePercentage = CheckPercentage(quantity, pricePercentage);
            trailingMethod = TrailingMethod.FixedPercentage;
            StopPrice = price * _stopPricePercentage;
            StopOrder = new StopMarketOrder(symbol, quantity, StopPrice, time);
            RegisterTrailingOrder(_symbol);
            _algorithm.Log(String.Format("Trailing Stop Order ID " + StopOrder.Id + " set for " + _symbol + " at stop price " + StopOrder.StopPrice));
        }

        public TrailingStopOrder(QCAlgorithm algorithm, string symbol, int quantity, List<decimal> series, int lookBackWindow, DateTime time)
        {
			_algorithm = algorithm;
            _symbol = symbol;
            _windowLookback = lookBackWindow;
			trailingMethod = TrailingMethod.StandardDeviationStop;
            _seriesHistory = new RollingWindow<decimal>(_windowLookback);
            foreach (decimal seriesValue in series)
            {
                _seriesHistory.Add(seriesValue);
            }

            decimal SDBand = EstimateSDBand(_seriesHistory);
            StopPrice = (quantity > 0) ? series[series.Count] - SDBand : series[series.Count] + SDBand;
            StopOrder = new StopMarketOrder(symbol, quantity, StopPrice, time);
            RegisterTrailingOrder(_symbol);
        }
        #endregion

        #region Methods
        /// <summary>
        /// Registers the trailing order to receive automatic prices updates.
        /// </summary>
        /// <param name="symbol">Symbol asset prices to be updated.</param>
        private void RegisterTrailingOrder(string symbol)
        {
            var consolidator = new IdentityDataConsolidator<TradeBar>();
            _algorithm.SubscriptionManager.AddConsolidator(symbol, consolidator);
            consolidator.DataConsolidated += (sender, consolidated) =>
            {
                this.ActualizeStopPrice(consolidated.Price);	// Big mistake!!
            };
        }

        /// <summary>
        /// Check the order status and dispose the object if is filled.
        /// If not, estimates the new stop price and update the order if needed.
        /// </summary>
        /// <param name="lastPrice">The last price observation.</param>
        public void ActualizeStopPrice(decimal lastPrice)
        {
            decimal newStopPrice;
            bool stopPriceChanged = false;

            // If the order is filled, dispose the instance.
            if (StopOrder.Status == OrderStatus.Filled)
            {
                
                //return;
            }

            switch (trailingMethod)
            {
                case TrailingMethod.FixedPercentage:
                    newStopPrice = lastPrice * _stopPricePercentage;
                    if ((StopOrder.Direction == OrderDirection.Buy && newStopPrice > StopPrice) ||
                        (StopOrder.Direction == OrderDirection.Sell && newStopPrice < StopPrice))
                    {
                        StopPrice = newStopPrice;
                        stopPriceChanged = true;
                    }
                    break;

                case TrailingMethod.StandardDeviationStop:
                    _seriesHistory.Add(lastPrice);
                    decimal SDBand = EstimateSDBand(_seriesHistory);
                    decimal direction = (StopOrder.Direction == OrderDirection.Buy) ? new decimal(-1) : new decimal(1);
                    StopPrice = lastPrice + SDBand * direction;
                    stopPriceChanged = true;
                    break;
            }
            if (stopPriceChanged) ActualizeOrder(StopPrice);
        }

        /// <summary>
        /// Actualizes the order.
        /// </summary>
        /// <param name="StopPrice">The updated stop price.</param>
        private void ActualizeOrder(decimal StopPrice)
        {
            
            StopOrder.StopPrice = StopPrice;
			
			_algorithm.Log(String.Format("Updating {0}", StopOrder));
			// update the order by sending to transaction manager
            var errorCode = _algorithm.Transactions.UpdateOrder(StopOrder);
            
            if(errorCode < 1)
            {
                _algorithm.Log(String.Format("Error [{0}] updating order {1}", errorCode, StopOrder));
            }
            
            //Console.WriteLine("Trailing Stop Order ID " + StopOrder.Id + " for " + _symbol + " update stop price to " + StopOrder.StopPrice);
		}

        /// <summary>
        /// Gets or sets the stop price percentage, adjusting the value if needed.
        /// </summary>
        /// <value>
        /// The stop price percentage.
        /// </value>
        private decimal CheckPercentage(int quantity, decimal pricePercentage)
        {
            if (quantity > 0 && pricePercentage > 1m) return pricePercentage - 1m;
            else if (quantity < 0 && pricePercentage < 1m) return pricePercentage + 1m;
            else return pricePercentage;
        }

        /// <summary>
        /// Estimates the standard deviation of the historical prices.
        /// </summary>
        /// <param name="seriesHistory">The price series history.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        private decimal EstimateSDBand(RollingWindow<decimal> seriesHistory)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}
namespace QuantConnect
{
    public partial class TestingTrailingOrders : QCAlgorithm
    {
        string symbol = "IBM";
        TrailingStopOrder trailingOrder;
        
        public override void Initialize()
        {
            SetStartDate(2013, 1, 1);
            SetEndDate(2013, 1, 2);

            SetCash(25000);

            AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
        }

        public void OnData(TradeBars data)
        {
            if (!Portfolio.HoldStock)
            {
                int quantity = (int)Math.Floor(Portfolio.Cash / data[symbol].Close);
                Order(symbol, -quantity);

                trailingOrder = FixedTrailingStopOrder(symbol, quantity, data[symbol].Price, 0.80m, Time);
                
                Log(String.Format("Submitting {0}", trailingOrder.StopOrder));
            }
            // trailingOrder.ActualizeStopPrice(data[symbol].Price);
        }

        public override void OnOrderEvent(OrderEvent fill)
        {
            var order = Transactions.GetOrderById(fill.OrderId);
            Log(String.Format(Time + " - " + order.Type + " - " + fill.Status + ":: " + fill));
        }        
    }
}