/// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public override void OnData(Slice data)
        {
            if (!Portfolio.Invested)
            {
                _ticket = LimitOrder(_spy, 10, 100);
                Debug("Purchased Stock");

                // Here we will show how to correctly change an order, we will then verify at End of Algorithm!
                // First get the order as it is now, should be a copy, so it wont be updated!
                _originalOrder = Transactions.GetOrderById(_ticket.OrderId);

                // Create an UpdateOrderRequest and send it to the ticket
                var updateFields = new UpdateOrderFields {
                    Quantity = 20, Tag = "Pepe", LimitPrice = data[_spy].Low
                };
                var response = _ticket.Update(updateFields);

                // Test order time
                if (_originalOrder.Time != UtcTime)
                {
                    Error("Order Time should be UtcTime!");
                    throw new Exception("Order Time should be UtcTime!");
                }
            }
        }
Example #2
0
        /// <summary>
        /// All order events get pushed through this function
        /// </summary>
        /// <param name="orderEvent">OrderEvent object that contains all the information about the event</param>
        public override void OnOrderEvent(OrderEvent orderEvent)
        {
            // Get the order twice, since they are clones they should NOT be the same
            var orderV1 = Transactions.GetOrderById(orderEvent.OrderId);
            var orderV2 = Transactions.GetOrderById(orderEvent.OrderId);

            if (orderV1 == orderV2)
            {
                Error("Orders should be clones, hence not equal!");
                throw new Exception("Orders should be clones, hence not equal!");
            }

            //Try and manipulate the orderV1 using UpdateOrderRequest
            //NOTICE: Orders should only be updated through their tickets!
            var updateFields = new UpdateOrderFields {
                Quantity = 99, Tag = "Pepe"
            };
            var updateRequest = new UpdateOrderRequest(DateTime.Now, orderEvent.OrderId, updateFields);

            orderV1.ApplyUpdateOrderRequest(updateRequest);

            //Get another copy of the order and compare
            var orderV3 = Transactions.GetOrderById(orderEvent.OrderId);

            if (orderV1.Quantity == orderV3.Quantity)
            {
                Error("Quantities should not be changed!");
                throw new Exception("Quantities should not be changed!");
            }

            if (orderV1.Tag == orderV3.Tag)
            {
                Error("Tag should not be changed!");
                throw new Exception("Tag should not be changed!");
            }

            //Try and manipulate orderV2 using the only external accessor BrokerID
            orderV2.BrokerId.Add("FAKE BROKER ID");

            //Get another copy of the order and compare
            var orderV4 = Transactions.GetOrderById(orderEvent.OrderId);

            if (orderV2.BrokerId == orderV4.BrokerId)
            {
                Error("BrokerIDs should not be the same!");
                throw new Exception("BrokerIDs should not be the same!");
            }
        }
        public void TestInvalidUpdateOrderId()
        {
            var updateFields = new UpdateOrderFields {
                Quantity = 99, Tag = "Pepe", StopPrice = 77, LimitPrice = 55
            };
            var updateRequest = new UpdateOrderRequest(DateTime.Now, 11, updateFields);
            var ticket        = OrderTicket.InvalidUpdateOrderId(null, updateRequest);

            Assert.AreEqual(ticket.OrderId, 11);
            Assert.AreEqual(ticket.Quantity, 0);
            Assert.AreEqual(ticket.Tag, "Pepe");
            Assert.AreEqual(ticket.Status, OrderStatus.Invalid);
            Assert.AreEqual(ticket.UpdateRequests.Count, 1);
            Assert.AreEqual(ticket.UpdateRequests[0].Status, OrderRequestStatus.Error);
            Assert.AreEqual(ticket.UpdateRequests[0].Response.ErrorCode, OrderResponseErrorCode.UnableToFindOrder);
            Assert.AreEqual(ticket.UpdateRequests[0].OrderId, 11);
            Assert.AreEqual(ticket.UpdateRequests[0].Quantity, 99);
            Assert.AreEqual(ticket.UpdateRequests[0].Tag, "Pepe");
            Assert.AreEqual(ticket.UpdateRequests[0].StopPrice, 77);
            Assert.AreEqual(ticket.UpdateRequests[0].LimitPrice, 55);
        }
Example #4
0
        public override void OnData(Slice data)
        {
            if (!_initialize)
            {
                HandleOrder(LimitOrder(_spy, -1001, 10000m)); // Should be canceled, exceeds the max shortable quantity
                HandleOrder(LimitOrder(_spy, -1000, 10000m)); // Allowed, orders at or below 1000 should be accepted
                HandleOrder(LimitOrder(_spy, -10, 0.01m));    // Should be canceled, the total quantity we would be short would exceed the max shortable quantity.
                _initialize = true;
                return;
            }

            if (!_invalidatedAllowedOrder)
            {
                if (_ordersAllowed.Count != 1)
                {
                    throw new Exception($"Expected 1 successful order, found: {_ordersAllowed.Count}");
                }
                if (_ordersDenied.Count != 2)
                {
                    throw new Exception($"Expected 2 failed orders, found: {_ordersDenied.Count}");
                }

                var allowedOrder = _ordersAllowed[0];
                var orderUpdate  = new UpdateOrderFields()
                {
                    LimitPrice = 0.01m,
                    Quantity   = -1001,
                    Tag        = "Testing updating and exceeding maximum quantity"
                };

                var response = allowedOrder.Update(orderUpdate);
                if (response.ErrorCode != OrderResponseErrorCode.ExceedsShortableQuantity)
                {
                    throw new Exception($"Expected order to fail due to exceeded shortable quantity, found: {response.ErrorCode.ToString()}");
                }

                var cancelResponse = allowedOrder.Cancel();
                if (cancelResponse.IsError)
                {
                    throw new Exception("Expected to be able to cancel open order after bad qty update");
                }

                _invalidatedAllowedOrder = true;
                _ordersDenied.Clear();
                _ordersAllowed.Clear();
                return;
            }

            if (!_invalidatedNewOrderWithPortfolioHoldings)
            {
                HandleOrder(MarketOrder(_spy, -1000)); // Should succeed, no holdings and no open orders to stop this
                var spyShares = Portfolio[_spy].Quantity;
                if (spyShares != -1000m)
                {
                    throw new Exception($"Expected -1000 shares in portfolio, found: {spyShares}");
                }

                HandleOrder(LimitOrder(_spy, -1, 0.01m)); // Should fail, portfolio holdings are at the max shortable quantity.
                if (_ordersDenied.Count != 1)
                {
                    throw new Exception($"Expected limit order to fail due to existing holdings, but found {_ordersDenied.Count} failures");
                }

                _ordersAllowed.Clear();
                _ordersDenied.Clear();

                HandleOrder(MarketOrder(_aig, -1001));
                if (_ordersAllowed.Count != 1)
                {
                    throw new Exception($"Expected market order of -1001 BAC to not fail");
                }

                _invalidatedNewOrderWithPortfolioHoldings = true;
            }
        }
Example #5
0
        /// <summary>
        /// This API lets you update the fields, comment, shippingProvider, and/or shippingTracking for a given order. All three fields can be updated simultaneously or independently.
        /// </summary>
        /// <param name="orderId">Requested order ID, specifies the order to update.</param>
        /// <param name="siteId">	Unique identifier for the site</param>
        ///  /// <param name="fields">update fields value</param>
        /// <returns>The <see cref="Order"/>.</returns>
        public virtual async Task <OrderModel> UpdateOrder(string siteId, string orderId, UpdateOrderFields fields)
        {
            var         req     = PrepareRequest($"sites/{siteId}/order/{orderId}/");
            HttpContent content = null;

            if (fields != null)
            {
                var body = fields.ToDictionary();
                content = new JsonContent(body);
            }

            return(await ExecuteRequestAsync <OrderModel>(req, HttpMethod.Patch, content));
        }