Пример #1
0
        /// <summary>
        /// Creates a deep-copy clone of this order
        /// </summary>
        /// <returns>A copy of this order</returns>
        public override Order Clone()
        {
            var order = new MarketOnCloseOrder();

            CopyTo(order);
            return(order);
        }
Пример #2
0
        /// <summary>
        /// Creates an order of the correct type
        /// </summary>
        private static Order CreateOrder(OrderType orderType, JObject jObject)
        {
            Order order;

            switch (orderType)
            {
            case OrderType.Market:
                order = new MarketOrder();
                break;

            case OrderType.Limit:
                order = new LimitOrder {
                    LimitPrice = jObject["LimitPrice"] == null ? default(decimal) : jObject["LimitPrice"].Value <decimal>()
                };
                break;

            case OrderType.StopMarket:
                order = new StopMarketOrder
                {
                    StopPrice = jObject["StopPrice"] == null ? default(decimal) : jObject["StopPrice"].Value <decimal>()
                };
                break;

            case OrderType.StopLimit:
                order = new StopLimitOrder
                {
                    LimitPrice = jObject["LimitPrice"] == null ? default(decimal) : jObject["LimitPrice"].Value <decimal>(),
                    StopPrice  = jObject["StopPrice"] == null ? default(decimal) : jObject["StopPrice"].Value <decimal>()
                };
                break;

            case OrderType.LimitIfTouched:
                order = new LimitIfTouchedOrder
                {
                    LimitPrice   = jObject["LimitPrice"] == null ? default(decimal) : jObject["LimitPrice"].Value <decimal>(),
                    TriggerPrice = jObject["TriggerPrice"] == null ? default(decimal) : jObject["TriggerPrice"].Value <decimal>()
                };
                break;

            case OrderType.MarketOnOpen:
                order = new MarketOnOpenOrder();
                break;

            case OrderType.MarketOnClose:
                order = new MarketOnCloseOrder();
                break;

            case OrderType.OptionExercise:
                order = new OptionExerciseOrder();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            return(order);
        }
Пример #3
0
        private static Order CreateOrder(int orderId, OrderType type, Symbol symbol, decimal quantity, DateTime time,
                                         string tag, IOrderProperties properties, decimal limitPrice, decimal stopPrice, decimal triggerPrice)
        {
            Order order;

            switch (type)
            {
            case OrderType.Market:
                order = new MarketOrder(symbol, quantity, time, tag, properties);
                break;

            case OrderType.Limit:
                order = new LimitOrder(symbol, quantity, limitPrice, time, tag, properties);
                break;

            case OrderType.StopMarket:
                order = new StopMarketOrder(symbol, quantity, stopPrice, time, tag, properties);
                break;

            case OrderType.StopLimit:
                order = new StopLimitOrder(symbol, quantity, stopPrice, limitPrice, time, tag, properties);
                break;

            case OrderType.LimitIfTouched:
                order = new LimitIfTouchedOrder(symbol, quantity, triggerPrice, limitPrice, time, tag, properties);
                break;

            case OrderType.MarketOnOpen:
                order = new MarketOnOpenOrder(symbol, quantity, time, tag, properties);
                break;

            case OrderType.MarketOnClose:
                order = new MarketOnCloseOrder(symbol, quantity, time, tag, properties);
                break;

            case OrderType.OptionExercise:
                order = new OptionExerciseOrder(symbol, quantity, time, tag, properties);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            order.Status = OrderStatus.New;
            order.Id     = orderId;
            return(order);
        }
Пример #4
0
        /// <summary>
        /// Creates an <see cref="Order"/> to match the specified <paramref name="request"/>
        /// </summary>
        /// <param name="request">The <see cref="SubmitOrderRequest"/> to create an order for</param>
        /// <returns>The <see cref="Order"/> that matches the request</returns>
        public static Order CreateOrder(SubmitOrderRequest request)
        {
            Order order;

            switch (request.OrderType)
            {
            case OrderType.Market:
                order = new MarketOrder(request.Symbol, request.Quantity, request.Time, request.Tag, request.OrderProperties);
                break;

            case OrderType.Limit:
                order = new LimitOrder(request.Symbol, request.Quantity, request.LimitPrice, request.Time, request.Tag, request.OrderProperties);
                break;

            case OrderType.StopMarket:
                order = new StopMarketOrder(request.Symbol, request.Quantity, request.StopPrice, request.Time, request.Tag, request.OrderProperties);
                break;

            case OrderType.StopLimit:
                order = new StopLimitOrder(request.Symbol, request.Quantity, request.StopPrice, request.LimitPrice, request.Time, request.Tag, request.OrderProperties);
                break;

            case OrderType.MarketOnOpen:
                order = new MarketOnOpenOrder(request.Symbol, request.Quantity, request.Time, request.Tag, request.OrderProperties);
                break;

            case OrderType.MarketOnClose:
                order = new MarketOnCloseOrder(request.Symbol, request.Quantity, request.Time, request.Tag, request.OrderProperties);
                break;

            case OrderType.OptionExercise:
                order = new OptionExerciseOrder(request.Symbol, request.Quantity, request.Time, request.Tag, request.OrderProperties);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            order.Status = OrderStatus.New;
            order.Id     = request.OrderId;
            if (request.Tag != null)
            {
                order.Tag = request.Tag;
            }
            return(order);
        }
Пример #5
0
        private Order ConvertOrder(IB.Order ibOrder, IB.Contract contract)
        {
            // this function is called by GetOpenOrders which is mainly used by the setup handler to
            // initialize algorithm state.  So the only time we'll be executing this code is when the account
            // has orders sitting and waiting from before algo initialization...
            // because of this we can't get the time accurately

            Order order;
            var mappedSymbol = MapSymbol(contract);
            var orderType = ConvertOrderType(ibOrder);
            switch (orderType)
            {
                case OrderType.Market:
                    order = new MarketOrder(mappedSymbol,
                        ibOrder.TotalQuantity,
                        new DateTime() // not sure how to get this data
                        );
                    break;

                case OrderType.MarketOnOpen:
                    order = new MarketOnOpenOrder(mappedSymbol, 
                        ibOrder.TotalQuantity,
                        new DateTime());
                    break;

                case OrderType.MarketOnClose:
                    order = new MarketOnCloseOrder(mappedSymbol,
                        ibOrder.TotalQuantity,
                        new DateTime()
                        );
                    break;

                case OrderType.Limit:
                    order = new LimitOrder(mappedSymbol,
                        ibOrder.TotalQuantity,
                        ibOrder.LimitPrice,
                        new DateTime()
                        );
                    break;

                case OrderType.StopMarket:
                    order = new StopMarketOrder(mappedSymbol,
                        ibOrder.TotalQuantity,
                        ibOrder.AuxPrice,
                        new DateTime()
                        );
                    break;

                case OrderType.StopLimit:
                    order = new StopLimitOrder(mappedSymbol,
                        ibOrder.TotalQuantity,
                        ibOrder.AuxPrice,
                        ibOrder.LimitPrice,
                        new DateTime()
                        );
                    break;

                default:
                    throw new InvalidEnumArgumentException("orderType", (int) orderType, typeof (OrderType));
            }

            order.BrokerId.Add(ibOrder.OrderId.ToString());

            return order;
        }
Пример #6
0
 /// <summary>
 /// Creates an <see cref="Order"/> to match the specified <paramref name="request"/>
 /// </summary>
 /// <param name="request">The <see cref="SubmitOrderRequest"/> to create an order for</param>
 /// <returns>The <see cref="Order"/> that matches the request</returns>
 public static Order CreateOrder(SubmitOrderRequest request)
 {
     Order order;
     switch (request.OrderType)
     {
         case OrderType.Market:
             order =  new MarketOrder(request.Symbol, request.Quantity, request.Time, request.Tag, request.SecurityType);
             break;
         case OrderType.Limit:
             order =  new LimitOrder(request.Symbol, request.Quantity, request.LimitPrice, request.Time, request.Tag, request.SecurityType);
             break;
         case OrderType.StopMarket:
             order =  new StopMarketOrder(request.Symbol, request.Quantity, request.StopPrice, request.Time, request.Tag, request.SecurityType);
             break;
         case OrderType.StopLimit:
             order =  new StopLimitOrder(request.Symbol, request.Quantity, request.StopPrice, request.LimitPrice, request.Time, request.Tag, request.SecurityType);
             break;
         case OrderType.MarketOnOpen:
             order =  new MarketOnOpenOrder(request.Symbol, request.SecurityType, request.Quantity, request.Time, request.Tag);
             break;
         case OrderType.MarketOnClose:
             order =  new MarketOnCloseOrder(request.Symbol, request.SecurityType, request.Quantity, request.Time, request.Tag);
             break;
         default:
             throw new ArgumentOutOfRangeException();
     }
     order.Status = OrderStatus.New;
     order.Id = request.OrderId;
     if (request.Tag != null)
     {
         order.Tag = request.Tag;
     }
     return order;
 }
Пример #7
0
        /// <summary>
        /// Creates an order of the correct type
        /// </summary>
        private static Order CreateOrder(OrderType orderType, JObject jObject)
        {
            Order order;
            switch (orderType)
            {
                case OrderType.Market:
                    order = new MarketOrder();
                    break;

                case OrderType.Limit:
                    order = new LimitOrder {LimitPrice = jObject["LimitPrice"].Value<decimal>()};
                    break;

                case OrderType.StopMarket:
                    order = new StopMarketOrder
                    {
                        StopPrice = jObject["StopPrice"].Value<decimal>()
                    };
                    break;

                case OrderType.StopLimit:
                    order = new StopLimitOrder
                    {
                        LimitPrice = jObject["LimitPrice"].Value<decimal>(),
                        StopPrice = jObject["StopPrice"].Value<decimal>()
                    };
                    break;

                case OrderType.MarketOnOpen:
                    order = new MarketOnOpenOrder();
                    break;

                case OrderType.MarketOnClose:
                    order = new MarketOnCloseOrder();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
            }
            return order;
        }
        public void PerformsMarketOnCloseUsingClosingPrice()
        {
            var reference = new DateTime(2015, 06, 05, 15, 0, 0); // before market close
            var model = new SecurityTransactionModel();
            var order = new MarketOnCloseOrder(Symbol, SecurityType.Equity, 100, reference);
            var config = CreateTradeBarConfig(Symbol);
            var security = new Security(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, 1)
            {
                Exchange = new EquityExchange(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours())
            };
            var time = reference;
            security.SetMarketPrice(time, new TradeBar(time, Symbol, 1m, 2m, 0.5m, 1.33m, 100));

            var fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(0, fill.FillQuantity);

            // market closes after 60min, so this is just before market Close
            time = reference.AddMinutes(59);
            security.SetMarketPrice(time, new TradeBar(time, Symbol, 1.33m, 2.75m, 1.15m, 1.45m, 100));

            fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(0, fill.FillQuantity);

            // market closes
            time = reference.AddMinutes(60);
            security.SetMarketPrice(time, new TradeBar(time, Symbol, 1.45m, 2.0m, 1.1m, 1.40m, 100));

            while (security.Exchange.ExchangeOpen)
            {
                time += TimeSpan.FromTicks(1);
                security.SetMarketPrice(time, null);
            }
            Console.WriteLine("Time: " + time);

            fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(order.Quantity, fill.FillQuantity);
            Assert.AreEqual(security.Close, fill.FillPrice);
        }
Пример #9
0
 /// <summary>
 /// Creates a deep-copy clone of this order
 /// </summary>
 /// <returns>A copy of this order</returns>
 public override Order Clone()
 {
     var order = new MarketOnCloseOrder();
     CopyTo(order);
     return order;
 }
        public void PerformsMarketOnCloseUsingClosingPrice()
        {
            var reference = new DateTime(2015, 06, 05, 15, 0, 0); // before market close
            var model = new SecurityTransactionModel();
            var order = new MarketOnCloseOrder(Symbols.SPY, 100, reference);
            var config = CreateTradeBarConfig(Symbols.SPY);
            var security = new Security(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));
            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            var time = reference;
            TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork));
            security.SetMarketPrice(new TradeBar(time, Symbols.SPY, 1m, 2m, 0.5m, 1.33m, 100));

            var fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(0, fill.FillQuantity);

            // market closes after 60min, so this is just before market Close
            time = reference.AddMinutes(59);
            TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork));
            security.SetMarketPrice(new TradeBar(time, Symbols.SPY, 1.33m, 2.75m, 1.15m, 1.45m, 100));

            fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(0, fill.FillQuantity);

            // market closes
            time = reference.AddMinutes(60);
            TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork));
            security.SetMarketPrice(new TradeBar(time, Symbols.SPY, 1.45m, 2.0m, 1.1m, 1.40m, 100));

            fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(order.Quantity, fill.FillQuantity);
            Assert.AreEqual(security.Close, fill.FillPrice);
        }
Пример #11
0
        public void PerformsMarketOnCloseUsingClosingPrice()
        {
            var reference = new DateTime(2015, 06, 05, 15, 0, 0); // before market close
            var model = new SecurityTransactionModel();
            var order = new MarketOnCloseOrder(Symbol, SecurityType.Equity, 100, reference, 1m);
            var config = new SubscriptionDataConfig(typeof(TradeBar), SecurityType.Equity, Symbol, Resolution.Minute, true, true, true, true, false, 0);
            var security = new Security(config, 1) { Exchange = new EquityExchange() };
            var time = reference;
            security.SetMarketPrice(time, new TradeBar(time, Symbol, 1m, 2m, 0.5m, 1.33m, 100));

            var fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(0, fill.FillQuantity);

            // market closes after 60min, so this is just before market Close
            time = reference.AddMinutes(59);
            security.SetMarketPrice(time, new TradeBar(time, Symbol, 1.33m, 2.75m, 1.15m, 1.45m, 100));

            fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(0, fill.FillQuantity);

            // market closes
            time = reference.AddMinutes(60);
            security.SetMarketPrice(time, new TradeBar(time, Symbol, 1.45m, 2.0m, 1.1m, 1.40m, 100));

            fill = model.MarketOnCloseFill(security, order);
            Assert.AreEqual(order.Quantity, fill.FillQuantity);
            Assert.AreEqual(security.Close, fill.FillPrice);
        }
        /// <summary>
        /// Market on Close Fill Model. Return an order event with the fill details
        /// </summary>
        /// <param name="asset">Asset we're trading with this order</param>
        /// <param name="order">Order to be filled</param>
        /// <returns>Order fill information detailing the average price and quantity filled.</returns>
        public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order)
        {
            var utcTime = asset.LocalTime.ConvertToUtc(asset.Exchange.TimeZone);
            var orderFee = GetOrderFee(asset, order);
            var fill = new OrderEvent(order, utcTime, orderFee);

            if (order.Status == OrderStatus.Canceled) return fill;

            try
            {
                var localOrderTime = order.Time.ConvertFromUtc(asset.Exchange.TimeZone);
                var nextMarketClose = asset.Exchange.Hours.GetNextMarketClose(localOrderTime, false);
                
                // wait until market closes after the order time 
                if (asset.LocalTime < nextMarketClose)
                {
                    return fill;
                }

                fill.FillPrice = asset.Close;
                fill.Status = OrderStatus.Filled;

                //Calculate the model slippage: e.g. 0.01c
                var slip = GetSlippageApproximation(asset, order);

                //Apply slippage
                switch (order.Direction)
                {
                    case OrderDirection.Buy:
                        fill.FillPrice += slip;
                        break;
                    case OrderDirection.Sell:
                        fill.FillPrice -= slip;
                        break;
                }

                // assume the order completely filled
                if (fill.Status == OrderStatus.Filled) fill.FillQuantity = order.Quantity;
            }
            catch (Exception err)
            {
                Log.Error(err);
            }

            return fill;
        }
Пример #13
0
        /// <summary>
        /// Market on close order implementation: Send a market order when the exchange closes
        /// </summary>
        /// <param name="symbol">The symbol to be ordered</param>
        /// <param name="quantity">The number of shares to required</param>
        /// <param name="tag">Place a custom order property or tag (e.g. indicator data).</param>
        /// <returns>The order ID</returns>
        public int MarketOnCloseOrder(string symbol, int quantity, string tag = "")
        {
            var error = PreOrderChecks(symbol, quantity, OrderType.MarketOnClose);
            if (error < 0)
            {
                return error;
            }

            var security = Securities[symbol];
            var order = new MarketOnCloseOrder(symbol, security.Type, quantity, Time, security.Price, tag);

            return Transactions.AddOrder(order);
        }
Пример #14
0
        /// <summary>
        /// Market on Close Fill Model. Return an order event with the fill details
        /// </summary>
        /// <param name="asset">Asset we're trading with this order</param>
        /// <param name="order">Order to be filled</param>
        /// <returns>Order fill informaton detailing the average price and quantity filled.</returns>
        public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order)
        {
            var fill = new OrderEvent(order);

            if (order.Status == OrderStatus.Canceled) return fill;

            try
            {
                // wait until market closes
                if (asset.Exchange.ExchangeOpen)
                {
                    return fill;
                }

                order.Price = asset.Close;
                order.Status = OrderStatus.Filled;

                //Calculate the model slippage: e.g. 0.01c
                var slip = GetSlippageApproximation(asset, order);

                //Apply slippage
                switch (order.Direction)
                {
                    case OrderDirection.Buy:
                        order.Price += slip;
                        break;
                    case OrderDirection.Sell:
                        order.Price -= slip;
                        break;
                }

                //For backtesting, we assuming the order is 100% filled on first attempt.
                fill.FillPrice = order.Price;
                fill.FillQuantity = order.Quantity;
                fill.Status = order.Status;
            }
            catch (Exception err)
            {
                Log.Error(err);
            }

            return fill;
        }
Пример #15
0
 /// <summary>
 /// Market on Close Fill Model. Return an order event with the fill details
 /// </summary>
 /// <param name="asset">Asset we're trading with this order</param>
 /// <param name="order">Order to be filled</param>
 /// <returns>Order fill information detailing the average price and quantity filled.</returns>
 public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order)
 {
     return _fillModel.MarketOnCloseFill(asset, order);
 }
Пример #16
0
        /// <summary>
        /// Market on Close Fill Model. Return an order event with the fill details
        /// </summary>
        /// <param name="asset">Asset we're trading with this order</param>
        /// <param name="order">Order to be filled</param>
        /// <returns>Order fill informaton detailing the average price and quantity filled.</returns>
        public OrderEvent MarketOnCloseFill(Security asset, MarketOnCloseOrder order)
        {
            var fill = new OrderEvent(order);

            if (order.Status == OrderStatus.Canceled) return fill;

            try
            {
                var localOrderTime = order.Time.ConvertTo(TimeZones.Utc, asset.Exchange.TimeZone);
                var nextMarketClose = asset.Exchange.Hours.GetNextMarketClose(localOrderTime, false);

                // wait until market closes after the order time
                if (asset.LocalTime < nextMarketClose)
                {
                    return fill;
                }

                order.Price = asset.Close;
                order.Status = OrderStatus.Filled;

                //Calculate the model slippage: e.g. 0.01c
                var slip = GetSlippageApproximation(asset, order);

                //Apply slippage
                switch (order.Direction)
                {
                    case OrderDirection.Buy:
                        order.Price += slip;
                        break;
                    case OrderDirection.Sell:
                        order.Price -= slip;
                        break;
                }

                //For backtesting, we assuming the order is 100% filled on first attempt.
                fill.FillPrice = order.Price;
                fill.FillQuantity = order.Quantity;
                fill.Status = order.Status;
            }
            catch (Exception err)
            {
                Log.Error(err);
            }

            return fill;
        }