Ejemplo n.º 1
0
        /// <summary>
        /// OnOrderUpdate->OnExecutionUpdate->OnPositionUpdate
        /// OnPositionUpdate: check new trade, change position for curTrade, no order update;
        /// OnExecutionUpdate: check filled order, update the new entry order and liquidate order;
        /// OnOrderUpdate: deal with working order, rejected/cancelled orders;
        /// </summary>
        /// <param name="order"></param>
        /// <param name="limitPrice"></param>
        /// <param name="stopPrice"></param>
        /// <param name="quantity"></param>
        /// <param name="filled"></param>
        /// <param name="averageFillPrice"></param>
        /// <param name="orderState"></param>
        /// <param name="time"></param>
        /// <param name="error"></param>
        /// <param name="comment"></param>
        protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
                                              int quantity, int filled, double averageFillPrice,
                                              Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
        {
            //if(BarsInProgress !=0) return;
            IndicatorProxy.Log2Disk = true;

            if (PrintOut > 1 && !IsInStrategyAnalyzer)
            {
                IndicatorProxy.PrintLog(true, IsLiveTrading(),
                                        CurrentBars[BarsInProgress] + "[" + BarsInProgress + "]:OnOrderUpdate IsUnmanaged=" + IsUnmanaged);
            }

            //The logic is implemented in the method below
            CurrentTrade.OnCurOrderUpdate(order, limitPrice, stopPrice, quantity, filled, averageFillPrice,
                                          orderState, time, error, comment);
            return;

            //The order execution is implemented in the method below
            if (IsUnmanaged)
            {
                OnOrderUpdateUM(order, limitPrice, stopPrice, quantity, filled,
                                averageFillPrice, orderState, time, error, comment);
            }
            else
            {
                OnOrderUpdateMG(order, limitPrice, stopPrice, quantity, filled,
                                averageFillPrice, orderState, time, error, comment);
            }
        }
Ejemplo n.º 2
0
        protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
                                              int quantity, int filled, double averageFillPrice,
                                              Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
        {
            if (PrintDetails)
            {
                Print(string.Format("{0} | OOU | order | {1} | {2}", Times[1][0], time, order.ToString()));
            }

            AssignOrderToVariable(ref order);

            // if either the profit target or stop loss is cancelled or rejected, then reset for a new entry
            if (!suppressCancelExit && entryOrder != null && order != entryOrder &&
                (!UseProfitTarget || (profitTarget != null &&
                                      (profitTarget.OrderState == OrderState.Cancelled ||
                                       profitTarget.OrderState == OrderState.Rejected))) &&
                (!UseStopLoss || (stopLoss != null &&
                                  (stopLoss.OrderState == OrderState.Cancelled ||
                                   stopLoss.OrderState == OrderState.Rejected)))
                )
            {
                // if either the stop or target is cancelled, wait 1 tick in OBU to check
                // to see if this was because of the Exit on close occurring or if manually cancelled
                ordersCancelled = true;

                if (PrintDetails)
                {
                    Print(string.Format("{0} stop or target cancelled or rejected", Times[1][0]));
                }
            }

            // once the stop loss or profit target (or exit for flat / exit for manual cancel) fills, reset for a new entry
            if ((profitTarget != null && profitTarget.OrderState == OrderState.Filled && (stopLoss == null || stopLoss.OrderState == OrderState.Cancelled)) ||
                (stopLoss != null && stopLoss.OrderState == OrderState.Filled && (profitTarget == null || profitTarget.OrderState == OrderState.Cancelled)) ||
                (exitFlat != null && exitFlat.OrderState == OrderState.Filled && (profitTarget == null || profitTarget.OrderState == OrderState.Cancelled) && (stopLoss == null || stopLoss.OrderState == OrderState.Cancelled)))
            {
                if (PrintDetails)
                {
                    Print(string.Format("{0} | OOU | resetting", Times[1][0]));
                }

                entryOrder         = null;
                profitTarget       = null;
                stopLoss           = null;
                exitFlat           = null;
                suppressCancelExit = false;
            }

            // when the Exit on close fills, wait for the new session to start the next entry
            // (so no orders are submitted between the exit on close and the end of the session)
            if (exitSession != null && exitSession.OrderState == OrderState.Filled)
            {
                if (PrintDetails)
                {
                    Print(string.Format("{0} | OOU | exit on close filled waiting for next session for reset\r\n{1}", Times[1][0], order.ToString()));
                }

                exitOnCloseWait = true;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="order"></param>
        /// <param name="limitPrice"></param>
        /// <param name="stopPrice"></param>
        /// <param name="quantity"></param>
        /// <param name="filled"></param>
        /// <param name="averageFillPrice"></param>
        /// <param name="orderState"></param>
        /// <param name="time"></param>
        /// <param name="error"></param>
        /// <param name="comment"></param>
        public virtual void OnCurOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
                                             int quantity, int filled, double averageFillPrice,
                                             Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
        {
            if (!this.InstStrategy.IsInStrategyAnalyzer && InstStrategy.PrintOut > 1)
            {
                InstStrategy.IndicatorProxy.PrintLog(true, InstStrategy.IsLiveTrading(),
                                                     String.Format("{0}:OnCurOrderUpdate, limitPrice={1}, stopPrice={2}, quantity={3},\t\n filled={4}, averageFillPrice={5}, orderState={6}",
                                                                   InstStrategy.CurrentBar, limitPrice, stopPrice, quantity, filled, averageFillPrice, orderState));
            }
            try {
//			    if (order.Name == "myEntryOrder" && orderState != OrderState.Filled)
//			      entryOrder = order;


//			    if (entryOrder != null && entryOrder == order)
//			    {
//			        Print(order.ToString());
//			        if (order.OrderState == OrderState.Filled)
//			              entryOrder = null;
//			    }
                //GetBracketOrderSubType(order);

                //InstStrategy.IndicatorProxy.TraceMessage(this.Name, 1);
                if (BracketOrder.EntryOrder != null && BracketOrder.EntryOrder == order)
                {
                    if (orderState == OrderState.Cancelled ||
                        //order.OrderState == OrderState.Filled ||
                        orderState == OrderState.Rejected ||
                        orderState == OrderState.Unknown)
                    {
                        barsSinceEnOrd          = 0;
                        BracketOrder.EntryOrder = null;
                    }
                }

                //InstStrategy.IndicatorProxy.TraceMessage(this.Name, 1);
                if (BracketOrder.TrailingSLOrder.EntryOrder != null && BracketOrder.TrailingSLOrder.EntryOrder == order)
                {
                    if (orderState == OrderState.Cancelled ||
                        orderState == OrderState.Rejected ||
                        orderState == OrderState.Unknown)
                    {
                        barsSinceEnOrd = 0;
                        BracketOrder.TrailingSLOrder.EntryOrder = null;
                    }
                }
            } catch (Exception ex) {
                InstStrategy.Print("Exception=" + ex.StackTrace);
            }
        }
Ejemplo n.º 4
0
        protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
                                              int quantity, int filled, double averageFillPrice,
                                              Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
        {
            //Print("The most current order state is: " + order.OrderState);   // OrderState.PartFilled
            //Print("This particular order update state is: " + orderState); // OrderState.Working
            if (filled != null && (order.Name == "ORs 1" || order.Name == "ORs 2"))
            {
                Print(order);
                Print("This particular order update state is: " + filled + "\t" + order.OrderType + "\t" + order.Name);             // OrderState.Working
                setInitialStopShort(pct: StopPct, auto: AutoSetStopFromMarket);
            }

            if (filled != null && (order.Name == "OR 1" || order.Name == "OR 2"))
            {
                Print(order);
                Print("This particular order update state is: " + filled + "\t" + order.OrderType + "\t" + order.Name);             // OrderState.Working
                setInitialStop(pct: StopPct, auto: AutoSetStopFromMarket);
            }
        }
Ejemplo n.º 5
0
        private void GetInitialOrderApq(Cbi.Order order, Cbi.OrderState orderState, double limitPrice)
        {
            if (!order.IsLimit)
            {
                return;
            }

            if (SuperDom.AtmStrategySelectionMode == AtmStrategySelectionMode.DisplaySelectedAtmStrategyOnly)
            {
                if (SuperDom.AtmStrategy != null)
                {
                    AtmStrategy atmStrategy1;
                    lock (order.Account.Strategies)
                        atmStrategy1 = order.Account.Strategies.FirstOrDefault(s => { lock (s.Orders) return(s.Orders.FirstOrDefault(o1 => o1 == order) != null); }) as AtmStrategy;

                    if (SuperDom.AtmStrategy != atmStrategy1)
                    {
                        return;
                    }
                }
            }

            double price = limitPrice;

            if (!Cbi.Order.IsTerminalState(orderState))
            {
                ConcurrentDictionary <Cbi.Order, long> ordersThisPrice;
                // Are there any orders at this price?
                if (priceToOrderApqMap.TryGetValue(price, out ordersThisPrice))
                {
                    long apq;
                    if (!ordersThisPrice.TryGetValue(order, out apq))
                    {
                        if (!order.IsSimulatedStop)
                        {
                            if (order.OrderAction == Cbi.OrderAction.Buy || order.OrderAction == Cbi.OrderAction.BuyToCover)
                            {
                                NinjaTrader.Data.MarketDepthRow lr = null;
                                lock (SuperDom.MarketDepth.Instrument.SyncMarketDepth)
                                    lr = SuperDom.MarketDepth.Bids.FirstOrDefault(b => b.Price == price);
                                if (lr != null)
                                {
                                    apq = lr.Volume + 1;
                                }

                                ordersThisPrice.TryAdd(order, apq);
                            }
                            else
                            {
                                NinjaTrader.Data.MarketDepthRow lr = null;
                                lock (SuperDom.MarketDepth.Instrument.SyncMarketDepth)
                                    lr = SuperDom.MarketDepth.Asks.FirstOrDefault(b => b.Price == price);
                                if (lr != null)
                                {
                                    apq = lr.Volume + 1;
                                }

                                ordersThisPrice.TryAdd(order, apq);
                            }

                            // Remove order from any other prices it might reside in
                            RemoveOrder(order, price);
                            // Update APQ value to be written to screen at this price
                            UpdateApqValuesForScreen();
                        }
                    }
                }
                else
                {
                    long apq = 0;
                    if (!order.IsSimulatedStop)
                    {
                        if (order.OrderAction == Cbi.OrderAction.Buy || order.OrderAction == Cbi.OrderAction.BuyToCover)
                        {
                            NinjaTrader.Data.MarketDepthRow lr = null;
                            lock (SuperDom.MarketDepth.Instrument.SyncMarketDepth)
                                lr = SuperDom.MarketDepth.Bids.FirstOrDefault(b => b.Price == price);
                            if (lr != null)
                            {
                                apq = lr.Volume + 1;
                            }
                        }
                        else
                        {
                            NinjaTrader.Data.MarketDepthRow lr = null;
                            lock (SuperDom.MarketDepth.Instrument.SyncMarketDepth)
                                lr = SuperDom.MarketDepth.Asks.FirstOrDefault(b => b.Price == price);
                            if (lr != null)
                            {
                                apq = lr.Volume + 1;
                            }
                        }

                        ordersThisPrice = new ConcurrentDictionary <Cbi.Order, long>();
                        if (ordersThisPrice.TryAdd(order, apq) && priceToOrderApqMap.TryAdd(price, ordersThisPrice))
                        {
                            // Remove order from any other prices it might reside in
                            RemoveOrder(order, price);
                            // Update APQ value to be written to screen at this price
                            UpdateApqValuesForScreen();
                        }
                    }
                }
            }
            else                // Remove terminal orders
            {
                if (!order.IsMarket)
                {
                    // Remove order from any other prices it might reside in
                    RemoveOrder(order);
                    // Update APQ value to be written to screen at this price
                    UpdateApqValuesForScreen();
                }
            }
        }
Ejemplo n.º 6
0
 protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
                                       int quantity, int filled, double averageFillPrice,
                                       Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
 {
 }
Ejemplo n.º 7
0
        protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice,
                                              int quantity, int filled, double averageFillPrice,
                                              Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
        {
            if (PrintDetails)
            {
                Print(string.Format("{0} | OOU | order | {1} | {2}", Times[1][0], time, order.ToString()));
            }

            AssignOrderToVariable(ref order);

            // the logic below is to simulate OCO when manually cancelling an order.

            // if the stop or target has filled (instead of being cancelled), nt will automatically
            // cancel any remaining orders attached to the entry's signal name.
            // prevent the OCO logic below to prevent overfills (cancelling an already cancelled order)
            if (orderState == OrderState.Filled && ((profitTarget != null && order == profitTarget) ||
                                                    (stopLoss != null && order == stopLoss)))
            {
                if (PrintDetails)
                {
                    Print(string.Format("{0} | OOU | stop or target filled, preventing oco actions until reset", Times[1][0]));
                }

                suppressOco = true;
            }

            // oco strings cannot be used in the managed approach. So simulate OCO here for manually cancelled orders
            // if the profit target is cancelled and the stop loss is still working, cancel the stop loss
            if (!suppressOco && profitTarget != null && order == profitTarget &&
                (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
                stopLoss != null &&
                (stopLoss.OrderState == OrderState.Accepted || stopLoss.OrderState == OrderState.Working))
            {
                if (PrintDetails)
                {
                    Print(string.Format("{0} | OOU | cancelling stop", Times[1][0]));
                }

                CancelOrder(stopLoss);
            }

            // if the stop loss is cancelled and the profit target is still working, cancel the profit target
            else if (!suppressOco && stopLoss != null && order == stopLoss &&
                     (orderState == OrderState.Cancelled || orderState == OrderState.Rejected) &&
                     profitTarget != null &&
                     (profitTarget.OrderState == OrderState.Accepted ||
                      profitTarget.OrderState == OrderState.Working))
            {
                if (PrintDetails)
                {
                    Print(string.Format("{0} | OOU | cancelling target", Times[1][0]));
                }

                CancelOrder(profitTarget);
            }

            // if both the profit target and stop loss are cancelled or rejected,
            // then exit the position and reset for a new entry
            else if (entryOrder != null && order != entryOrder &&
                     (!UseProfitTarget || (profitTarget != null &&
                                           (profitTarget.OrderState == OrderState.Cancelled ||
                                            profitTarget.OrderState == OrderState.Rejected))) &&
                     (!UseStopLoss || (stopLoss != null &&
                                       (stopLoss.OrderState == OrderState.Cancelled ||
                                        stopLoss.OrderState == OrderState.Rejected))))
            {
                // if either the stop or target is cancelled, wait 1 tick in OBU to check
                // to see if this was because of the Exit on close occurring or if manually cancelled
                ordersCancelled = true;

                if (PrintDetails)
                {
                    Print(string.Format("{0} | OOU | stop or target cancelled or rejected", Times[1][0]));
                }
            }

            // end of simulated oco logic for manual cancellations

            // once the stop loss or profit target (or exit for flat / exit for manual cancel) fills, reset for a new entry
            if ((profitTarget != null && profitTarget.OrderState == OrderState.Filled && (stopLoss == null || stopLoss.OrderState == OrderState.Cancelled)) ||
                (stopLoss != null && stopLoss.OrderState == OrderState.Filled && (profitTarget == null || profitTarget.OrderState == OrderState.Cancelled)) ||
                (exitFlat != null && exitFlat.OrderState == OrderState.Filled && (profitTarget == null || profitTarget.OrderState == OrderState.Cancelled) && (stopLoss == null || stopLoss.OrderState == OrderState.Cancelled)))
            {
                if (PrintDetails)
                {
                    Print(string.Format("{0} | OOU | resetting", Times[1][0]));
                }

                entryOrder   = null;
                profitTarget = null;
                stopLoss     = null;
                exitFlat     = null;
            }

            // when the Exit on close fills, wait for the new session to start the next entry
            // (so no orders are submitted between the exit on close and the end of the session)
            if (exitSession != null && exitSession.OrderState == OrderState.Filled)
            {
                if (PrintDetails)
                {
                    Print(string.Format("{0} | OOU | exit on close filled waiting for next session for reset\r\n{1}", Times[1][0], order.ToString()));
                }

                exitOnCloseWait = true;
            }
        }
Ejemplo n.º 8
0
        protected override void OnOrderUpdate(Cbi.Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, Cbi.OrderState orderState, DateTime time, Cbi.ErrorCode error, string comment)
        {
            //Entry Order
            if (order.Name == "StartOrder" && order.OrderState == OrderState.Filled)
            {
                StartOrder = order;
                _status    = "StartOrder";
            }

            //if (order.Name == "Profit target" && order.OrderState == OrderState.Filled)
            //{
            //}
            //if (order.Name == "Stop loss" && order.OrderState == OrderState.Filled)
            //{
            //}
            ////Recover
            //if (order.Name == "Cover1" && order.OrderState == OrderState.Filled)
            //    _status = "Recover";
            //if (order.Name == "CollectionMIT")
            //    CollectionMIT = order;

            //if(order.Name == "CollectionMIT" && order.OrderState == OrderState.Filled)
            //{
            //    SetProfitTarget("CollectionMIT", CalculationMode.Price, High[0] + 10 * TickSize, true);
            //    CollectionMIT = order;
            //}

            //if (order.Name == "Profit target" && order.OrderState == OrderState.Filled && _status.Equals("Collection"))
            //{
            //    ProfitTarget = order;
            //    CollectionMIT = EnterLongLimit(0, true, 1, High[1] - 9 * TickSize, "CollectionMIT");
            //}
            #region help

            //else if (order.Name == "Collection" && order.OrderState == OrderState.Filled)
            //{

            //    LimitCollectionOrder = EnterLongLimit(High[0] - 7 * TickSize, "LimitCollectionOrder");
            //}
            //else if (order.Name == "LimitCollectionOrder" && order.OrderState == OrderState.Working)
            //{
            //    LimitCollectionOrder = order;
            //    _status = "LimitCollectionOrder";

            //}
            //else if (order.Name == "LimitCollectionOrder" && order.OrderState == OrderState.Filled)
            //{
            //    LimitCollectionOrder = order;
            //}
            //else if (order.Name == "LimitCollectionOrder")
            //      Draw.Dot(this, @"MyCustomStrategy" + CurrentBars[0].ToString(), false, 0, Close[0], Brushes.Blue);
            //    Logs.SuperLogs(order.ToString());
            ////StartOrderExit
            //if (order.Name == "StartOrderExit" && order.OrderState == OrderState.Filled)
            //{
            //    _status = "Collect";
            //    EnterLongLimit(1, High[0] - 8 * TickSize, "CollectionOrder");
            //}

            ////Collection Order working
            //if (order.Name == "CollectionOrder")
            //    CollectionOrder = order;
            //if(order.Name == "CollectionOrder" && order.OrderState == OrderState.Filled)
            //{
            //    SetProfitTarget("CollectionOrder", CalculationMode.Pips, 10, true);
            //}
            //Collection Activated

            //if(order.Name == "CollectionOrder" && order.OrderState == OrderState.Filled)
            //{
            //    SetStopLoss("CollectionOrder", CalculationMode.Price, StartOrder.AverageFillPrice + 2 * TickSize, true);
            //    SetProfitTarget("CollectionOrder", CalculationMode.Price, High[0] + 10 * TickSize, true);
            //}
            //if(order.Name == "CollectSignal" && order.OrderState == OrderState.Filled)
            //{

            //}
            //if (order != null && entryOrder == null && order.Name == "EntryOrder" && orderState == OrderState.Filled)
            //{
            //    entryOrder = order;
            //    Logs.SuperLogs(entryOrder.ToString());

            //    _initprice = averageFillPrice;
            //    Print("LOL");
            //}

            //Logs.SuperLogs(string.Format("{0} {1}", entryOrder.ToString(), "DOWN DOWN |||  "));



            //// if entry order exists
            //if (entryOrder != null && entryOrder == order)
            //{
            //    Print(order.ToString());
            //    if (order.OrderState == OrderState.Cancelled)
            //    {
            //        // Do something here
            //        entryOrder = null;
            //    }
            //}
            #endregion
        }