/// <summary>
        /// Dispose of all the TT API objects and shutdown the TT API
        /// </summary>
        public void shutdownTTAPI()
        {
            if (!m_shutdownInProcess)
            {
                // Dispose of all request objects
                if (m_customerDefaultsSubscription != null)
                {
                    m_customerDefaultsSubscription.CustomerDefaultsChanged -= m_customerDefaultsSubscription_CustomerDefaultsChanged;
                    m_customerDefaultsSubscription.Dispose();
                    m_customerDefaultsSubscription = null;
                }

                if (m_instrumentTradeSubscription != null)
                {
                    m_instrumentTradeSubscription.OrderAdded    -= m_instrumentTradeSubscription_OrderAdded;
                    m_instrumentTradeSubscription.OrderRejected -= m_instrumentTradeSubscription_OrderRejected;
                    m_instrumentTradeSubscription.Dispose();
                    m_instrumentTradeSubscription = null;
                }

                if (m_priceSubscription != null)
                {
                    m_priceSubscription.FieldsUpdated -= m_priceSubscription_FieldsUpdated;
                    m_priceSubscription.Dispose();
                    m_priceSubscription = null;
                }

                TTAPI.ShutdownCompleted += new EventHandler(TTAPI_ShutdownCompleted);
                TTAPI.Shutdown();
            }

            // only run shutdown once
            m_shutdownInProcess = true;
        }
        /// <summary>
        /// Event notification for instrument lookup
        /// </summary>
        void m_req_Update(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.Instrument != null && e.Error == null)
            {
                // Instrument was found
                Console.WriteLine("Found: {0}", e.Instrument.Name);

                // Subscribe for Inside Market Data
                m_ps                = new PriceSubscription(e.Instrument, Dispatcher.Current);
                m_ps.Settings       = new PriceSubscriptionSettings(PriceSubscriptionType.InsideMarket);
                m_ps.FieldsUpdated += new FieldsUpdatedEventHandler(m_ps_FieldsUpdated);
                m_ps.Start();

                // Create a TradeSubscription to listen for order / fill events only for orders submitted through it
                m_ts = new InstrumentTradeSubscription(m_apiInstance.Session, Dispatcher.Current, e.Instrument, true, true, false, false);
                m_ts.OrderUpdated  += new EventHandler <OrderUpdatedEventArgs>(m_ts_OrderUpdated);
                m_ts.OrderAdded    += new EventHandler <OrderAddedEventArgs>(m_ts_OrderAdded);
                m_ts.OrderDeleted  += new EventHandler <OrderDeletedEventArgs>(m_ts_OrderDeleted);
                m_ts.OrderFilled   += new EventHandler <OrderFilledEventArgs>(m_ts_OrderFilled);
                m_ts.OrderRejected += new EventHandler <OrderRejectedEventArgs>(m_ts_OrderRejected);
                m_ts.Start();
            }
            else if (e.IsFinal)
            {
                // Instrument was not found and TT API has given up looking for it
                Console.WriteLine("Cannot find instrument: {0}", e.Error.Message);
                Dispose();
            }
        }
        /// <summary>
        /// Create subscriptions and update the GUI.
        /// </summary>
        /// <param name="instrument">Instrument to create subscriptions with.</param>
        private void instrumentFound(Instrument instrument)
        {
            txtExchange.Text    = instrument.Key.MarketKey.Name;
            txtProduct.Text     = instrument.Key.ProductKey.Name;
            txtProductType.Text = instrument.Key.ProductKey.Type.Name;
            txtContract.Text    = instrument.Name;

            m_priceSubscription = new PriceSubscription(instrument, Dispatcher.Current);
            m_priceSubscription.FieldsUpdated += new FieldsUpdatedEventHandler(m_priceSubscription_FieldsUpdated);
            m_priceSubscription.Start();

            m_instrumentTradeSubscription                = new InstrumentTradeSubscription(m_TTAPI.Session, Dispatcher.Current, instrument);
            m_instrumentTradeSubscription.OrderAdded    += new EventHandler <OrderAddedEventArgs>(m_instrumentTradeSubscription_OrderAdded);
            m_instrumentTradeSubscription.OrderRejected += new EventHandler <OrderRejectedEventArgs>(m_instrumentTradeSubscription_OrderRejected);
            m_instrumentTradeSubscription.Start();

            populateOrderFeedDropDown(instrument);

            // Enable the user interface items.
            txtQuantity.Enabled       = true;
            cboOrderType.Enabled      = true;
            comboBoxOrderFeed.Enabled = true;
            cboCustomer.Enabled       = true;
            btnBuy.Enabled            = true;
            btnSell.Enabled           = true;
        }
Exemple #4
0
        public static bool ChangeLimitOrder(string orderKey, TradingTechnologies.TTAPI.Instrument instrument, Subscription ttapisubs, double price, Logger logger)

        {
            InstrumentTradeSubscription TS = ttapisubs.TsDictionary[instrument.Key];
            bool Status = true;

            OrderProfileBase Op         = TS.Orders[orderKey].GetOrderProfile();
            Price            LimitPrice = Price.FromDouble(instrument.InstrumentDetails, price);

            if (Op.LimitPrice != LimitPrice)
            {
                Op.LimitPrice = LimitPrice;
                Op.Action     = OrderAction.Change;

                if (!TS.SendOrder(Op))
                {
                    logger.Log("Send change order failed.  {0}" + Op.RoutingStatus.Message);
                    Status = false;
                }
                else
                {
                    logger.Log("Send change order succeeded.");
                }
            }

            return(Status);
        }
        public void startTradeSubscriptions(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.Instrument != null && e.Error == null)
            {
                // Create a TradeSubscription to listen for order / fill events only for orders submitted through it
                ts = new InstrumentTradeSubscription(m_apiInstance.Session, Dispatcher.Current, e.Instrument, true, true, false, false);
                ts.OrderUpdated += new EventHandler <OrderUpdatedEventArgs>(m_ts_OrderUpdated);
                ts.OrderAdded   += new EventHandler <OrderAddedEventArgs>(m_ts_OrderAdded);
                ts.OrderDeleted += new EventHandler <OrderDeletedEventArgs>(m_ts_OrderDeleted);

                if (orderFilledEventHandler != null)
                {
                    ts.OrderFilled += new EventHandler <OrderFilledEventArgs>(orderFilledEventHandler);
                }

                ts.OrderRejected += new EventHandler <OrderRejectedEventArgs>(m_ts_OrderRejected);

                TsDictionary.Add(e.Instrument.Key, ts);
                ts.Start();
            }
            else if (e.IsFinal)
            {
                // Instrument was not found and TT API has given up looking for it
                Console.WriteLine("Cannot find instrument: {0}", e.Error.Message);
                Dispose();
            }
        }
Exemple #6
0
        public static string SendLimitOrder(TradingTechnologies.TTAPI.Instrument instrument,
                                            TradingTechnologies.TTAPI.Price price, int qty, Subscription ttapisubs, string orderTag = "")

        {
            BuySell Direction   = BuySell.Buy;
            string  AccountName = "H1KOC";

            if (qty < 0)
            {
                Direction = BuySell.Sell;
                qty       = -qty;
            }

            string tickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(instrument.Product.ToString(), instrument.Name.ToString());

            string[] TickerList = tickerDB.Split('-');

            string TickerHead   = ContractUtilities.ContractMetaInfo.GetContractSpecs(TickerList[0]).tickerHead;
            string ExchangeName = ContractUtilities.ContractMetaInfo.GetExchange4Tickerhead(TickerHead);

            AccountType AccType = AccountType.P2;

            OrderProfile op = new OrderProfile(instrument.GetValidOrderFeeds()[0], instrument);

            op.BuySell     = Direction;
            op.AccountName = AccountName;

            if (ExchangeName == "ICE")
            {
                AccType   = AccountType.G2;
                op.GiveUp = "5283";
            }

            op.AccountType   = AccType;
            op.OrderQuantity = Quantity.FromInt(instrument, qty);
            op.OrderType     = OrderType.Limit;

            if (orderTag.Count() > 0)
            {
                op.OrderTag = orderTag;
            }


            op.LimitPrice = price;

            InstrumentTradeSubscription TS = ttapisubs.TsDictionary[instrument.Key];

            if (!TS.SendOrder(op))
            {
                Console.WriteLine("Send new order failed.  {0}", op.RoutingStatus.Message);
                ttapisubs.Dispose();
            }
            else
            {
                Console.WriteLine("Send new order succeeded.");
            }

            return(op.SiteOrderKey);
        }
        /// <summary>
        /// Event notification for instrument lookup
        /// </summary>
        public void req_Update(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.Instrument != null && e.Error == null)
            {
                cout("Subscribed to Instrument: {0}", e.Instrument.Key);

                _instruments[GetIid(e.Instrument)].FoundInstrument(e.Instrument);

                // Market Depth subscription (or just Inside Market if you change the PriceSubscriptionSettings)
                var prcSub = new PriceSubscription(e.Instrument, Dispatcher.Current);
                //psSub.Settings = new PriceSubscriptionSettings(PriceSubscriptionType.InsideMarket);
                prcSub.Settings       = new PriceSubscriptionSettings(PriceSubscriptionType.MarketDepth);
                prcSub.FieldsUpdated += new FieldsUpdatedEventHandler(m_prc_FieldsUpdated);
                m_lprc.Add(prcSub);
                prcSub.Start();

                // Time & Sales subscription
                var tsSub = new TimeAndSalesSubscription(e.Instrument, Dispatcher.Current);
                tsSub.Update += new EventHandler <TimeAndSalesEventArgs>(tsSub_Update);
                m_lts.Add(tsSub);
                tsSub.Start();

                // Fills subscription
                var filSub = new FillsSubscription(m_TTAPI.Session, Dispatcher.Current);
                filSub.FillAdded        += new EventHandler <FillAddedEventArgs>(m_fil_FillAdded);
                filSub.FillAmended      += new EventHandler <FillAmendedEventArgs>(m_fil_FillAmended);
                filSub.FillBookDownload += new EventHandler <FillBookDownloadEventArgs>(m_fil_FillBookDownload);
                filSub.FillDeleted      += new EventHandler <FillDeletedEventArgs>(m_fil_FillDeleted);
                filSub.FillListEnd      += new EventHandler <FillListEventArgs>(m_fil_FillListEnd);
                filSub.FillListStart    += new EventHandler <FillListEventArgs>(m_fil_FillListStart);
                m_lfil.Add(filSub);
                filSub.Start();

                // Trade Subscription (to listen for order / fill events only for orders submitted through it)
                var trdSub = new InstrumentTradeSubscription(m_TTAPI.Session, Dispatcher.Current, e.Instrument, true, true, false, false);
                trdSub.OrderUpdated     += new EventHandler <OrderUpdatedEventArgs>(m_trd_OrderUpdated);
                trdSub.OrderAdded       += new EventHandler <OrderAddedEventArgs>(m_trd_OrderAdded);
                trdSub.OrderDeleted     += new EventHandler <OrderDeletedEventArgs>(m_trd_OrderDeleted);
                trdSub.OrderFilled      += new EventHandler <OrderFilledEventArgs>(m_trd_OrderFilled);
                trdSub.OrderRejected    += new EventHandler <OrderRejectedEventArgs>(m_trd_OrderRejected);
                m_dtrd[e.Instrument.Key] = trdSub;
                trdSub.Start();
            }
            else if (e.IsFinal)
            {
                // Instrument was not found and TT API has given up looking for it
                cout("Cannot find instrument, and giving up: {0}", e.Error.Message);
                Dispose();
            }
            else
            {
                cout("Cannot find instrument: {0}", e.Error.Message);
            }
        }
Exemple #8
0
        private void CreateInstrumentTradeSubscription(Instrument instrument)
        {
            if (m_instrumentTradeSubscription != null)
            {
                m_instrumentTradeSubscription.Dispose();
                m_instrumentTradeSubscription = null;
            }

            m_instrumentTradeSubscription               = new InstrumentTradeSubscription(m_TTAPI.Session, Dispatcher.Current, instrument);
            m_instrumentTradeSubscription.OrderAdded   += new EventHandler <OrderAddedEventArgs>(instrumentTradeSubscription_OrderAdded);
            m_instrumentTradeSubscription.OrderDeleted += new EventHandler <OrderDeletedEventArgs>(instrumentTradeSubscription_OrderDeleted);
        }
        void req_Update(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            Console.WriteLine("req_Update");
            if (e.Instrument != null && e.Error == null)
            {
                tslblInfo.Text = "SUBSCRIBED: " + e.Instrument.Name;
                Message("SUBSCRIBED: " + e.Instrument.Name);
                // if this instrument is one of our managed hedges, then add it
                // to the managed hedge dictionary
                foreach (InstrumentInfo info in managedHedgeList)
                {
                    if (info.ProductKey == e.Instrument.Product.Key && e.Instrument.Name.Contains(info.Contract)) // && info.Contract.Equals(e.Instrument.Name))
                    {
                        info.Instrument    = e.Instrument;
                        info.InstrumentKey = e.Instrument.Key;
                        managedHedges.Add(e.Instrument.Key, info);
                    }
                }

                // iterate order feeds enabled for each instrument
                foreach (OrderFeed oFeed in e.Instrument.GetValidOrderFeeds())
                {
                    if (oFeed.IsTradingEnabled)
                    {
                        Console.WriteLine("Order feed {0} is enabled for trading", oFeed.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Order feed {0} is NOT enabled for trading", oFeed.ToString());
                    }
                }
                // successfully subscribed to an instrument so request prices

                PriceSubscription priceSub = new PriceSubscription(e.Instrument, Dispatcher.Current);
                priceSub.Settings       = new PriceSubscriptionSettings(PriceSubscriptionType.InsideMarket);
                priceSub.FieldsUpdated += new FieldsUpdatedEventHandler(priceSub_FieldsUpdated);
                priceSub.Start();

                InstrumentTradeSubscription its = new InstrumentTradeSubscription(apiInstance.Session, Dispatcher.Current, e.Instrument);
                its.Start();
            }
            else if (e.IsFinal)
            {
                // Instrument was not found and TTAPI has given up looking for it
                tslblInfo.Text = "ERROR: " + e.Error.Message;
            }
        }
Exemple #10
0
        /// <summary>
        /// Dispose of all the TT API objects and shutdown the TT API
        /// </summary>
        public void shutdownTTAPI()
        {
            if (!m_shutdownInProcess)
            {
                // Dispose of all request objects
                if (m_instrumentTradeSubscription != null)
                {
                    m_instrumentTradeSubscription.ProfitLossChanged -= instrumentTradeSubscription_ProfitLossChanged;
                    m_instrumentTradeSubscription.Dispose();
                    m_instrumentTradeSubscription = null;
                }

                TTAPI.ShutdownCompleted += new EventHandler(TTAPI_ShutdownCompleted);
                TTAPI.Shutdown();
            }

            // only run shutdown once
            m_shutdownInProcess = true;
        }
Exemple #11
0
        /// <summary>
        /// Instrument request completed event.
        /// </summary>
        void instrRequest_Completed(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.IsFinal && e.Instrument != null)
            {
                try
                {
                    UpdateStatusBar("Instrument Found.");
                    Console.WriteLine(String.Format("TT API FindInstrument {0}", e.Instrument.Name));

                    // Grab the contract specifications and output to the user
                    this.txtExchange.Text    = e.Instrument.Product.Market.Name;
                    this.txtProduct.Text     = e.Instrument.Product.Name;
                    this.txtProductType.Text = e.Instrument.Product.Type.ToString();
                    this.txtContract.Text    = e.Instrument.GetFormattedName(InstrumentNameFormat.User);

                    if (m_instrumentTradeSubscription != null)
                    {
                        m_instrumentTradeSubscription.Dispose();
                        m_instrumentTradeSubscription = null;
                    }

                    // The use of the InstrumentTradeSubscription will filter for a specific instrument
                    m_instrumentTradeSubscription                    = new InstrumentTradeSubscription(m_TTAPI.Session, Dispatcher.Current, e.Instrument);
                    m_instrumentTradeSubscription.EnablePNL          = true;
                    m_instrumentTradeSubscription.ProfitLossChanged += new EventHandler <ProfitLossChangedEventArgs>(instrumentTradeSubscription_ProfitLossChanged);
                    m_instrumentTradeSubscription.Start();
                }
                catch (Exception err)
                {
                    Console.WriteLine(String.Format("TT API FindInstrument Exception: {0}", err.Message));
                }
            }
            else if (e.IsFinal)
            {
                Console.WriteLine(String.Format("TT API FindInstrument Instrument Not Found: {0}", e.Error));
            }
            else
            {
                Console.WriteLine(String.Format("TT API FindInstrument Instrument Not Found: (Still Searching) {0}", e.Error));
            }
        }
Exemple #12
0
        public static bool CancelLimitOrder(string orderKey, TradingTechnologies.TTAPI.Instrument instrument, Subscription ttapisubs, Logger logger)
        {
            InstrumentTradeSubscription TS = ttapisubs.TsDictionary[instrument.Key];
            bool Status = true;

            OrderProfileBase Op = TS.Orders[orderKey].GetOrderProfile();

            Op.Action = OrderAction.Delete;

            if (!TS.SendOrder(Op))
            {
                logger.Log("Cancal order failed.  {0}" + Op.RoutingStatus.Message);
                Status = false;
            }
            else
            {
                logger.Log("Cancel order succeeded.");
            }

            return(Status);
        }
        void ils_Update(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            Console.WriteLine("ils_Update");
            if (e.Instrument != null && e.Error == null)
            {
                Message("SUBSCRIBED: " + e.Instrument.Name);

                // iterate order feeds enabled for each instrument
                foreach (OrderFeed oFeed in e.Instrument.GetValidOrderFeeds())
                {
                    if (oFeed.IsTradingEnabled)
                    {
                        Console.WriteLine("Order feed {0} is enabled for trading", oFeed.ToString());
                    }
                    else
                    {
                        Console.WriteLine("Order feed {0} is NOT enabled for trading", oFeed.ToString());
                    }
                }
                // successfully subscribed to an instrument so request prices

                PriceSubscription priceSub = new PriceSubscription(e.Instrument, Dispatcher.Current);
                priceSub.Settings       = new PriceSubscriptionSettings(PriceSubscriptionType.InsideMarket);
                priceSub.FieldsUpdated += new FieldsUpdatedEventHandler(priceSub_FieldsUpdated);
                priceSub.Start();

                InstrumentTradeSubscription its = new InstrumentTradeSubscription(apiInstance.Session, Dispatcher.Current, e.Instrument);
                its.EnablePNL          = true;
                its.ProfitLossChanged += new EventHandler <ProfitLossChangedEventArgs>(its_ProfitLossChanged);
                its.Start();

                instruments[e.Instrument.Key].Instrument        = e.Instrument;
                instruments[e.Instrument.Key].TradeSubscription = its;
            }
            else if (e.IsFinal)
            {
                // Instrument was not found and TTAPI has given up looking for it
                ErrorMessage(e.Error.Message);
            }
        }
Exemple #14
0
        TTInstrument processInstrumentFound(Instrument instrument)
        {
            Dispatcher dispatcher = Dispatcher.Current;
            //Dispatcher dispatcher = _dispatcher;

            PriceSubscription priceSub = new PriceSubscription(instrument, dispatcher);

            if (SubscribeMarketDepth == true)
            {
                priceSub.Settings = new PriceSubscriptionSettings(PriceSubscriptionType.MarketDepth);
            }
            else
            {
                priceSub.Settings = new PriceSubscriptionSettings(PriceSubscriptionType.InsideMarket);
            }
            priceSub.FieldsUpdated += new FieldsUpdatedEventHandler(priceSub_FieldsUpdated);
            priceSub.Start();

            InstrumentTradeSubscription its = new InstrumentTradeSubscription(_apiSession, dispatcher, instrument);

            its.EnablePNL          = true;
            its.ProfitLossChanged += new EventHandler <ProfitLossChangedEventArgs>(its_ProfitLossChanged);
            its.Start();

            if (SubscribeTimeAndSales == true)
            {
                TimeAndSalesSubscription tsSub = new TimeAndSalesSubscription(instrument, dispatcher);
                tsSub.Update += new EventHandler <TimeAndSalesEventArgs>(tsSub_Update);
                tsSub.Start();
            }

            TTInstrument tti = NewTTInstrument(instrument);

            tti.TradeSubscription = its;
            its.Tag = tti;

            tti.OrderRoute = OrderRoute.GetOrderRoute(tti, instrument.Product.Market.Name);

            return(tti);
        }
        /// <summary>
        /// Shuts down the TT API
        /// </summary>
        public void Dispose()
        {
            lock (m_lock)
            {
                if (!m_disposed)
                {
                    // Unattached callbacks and dispose of all subscriptions
                    if (m_req != null)
                    {
                        m_req.Update -= m_req_Update;
                        m_req.Dispose();
                        m_req = null;
                    }
                    if (m_ps != null)
                    {
                        m_ps.FieldsUpdated -= m_ps_FieldsUpdated;
                        m_ps.Dispose();
                        m_ps = null;
                    }
                    if (m_ts != null)
                    {
                        m_ts.OrderAdded    -= m_ts_OrderAdded;
                        m_ts.OrderDeleted  -= m_ts_OrderDeleted;
                        m_ts.OrderFilled   -= m_ts_OrderFilled;
                        m_ts.OrderRejected -= m_ts_OrderRejected;
                        m_ts.OrderUpdated  -= m_ts_OrderUpdated;
                        m_ts.Dispose();
                        m_ts = null;
                    }

                    // Begin shutdown the TT API
                    TTAPI.ShutdownCompleted += new EventHandler(TTAPI_ShutdownCompleted);
                    TTAPI.Shutdown();

                    m_disposed = true;
                }
            }
        }
Exemple #16
0
        public void Dispose()
        {
            lock (m_Lock)
            {
                if (!m_isDisposed)
                {
                    // Unattached callbacks and dispose of all subscriptions
                    if (m_instrLookupRequest != null)
                    {
                        m_instrLookupRequest.OnData -= m_instrLookupRequest_OnData;
                        m_instrLookupRequest.Dispose();
                        m_instrLookupRequest = null;
                    }
                    if (m_priceSubscription != null)
                    {
                        m_priceSubscription.FieldsUpdated -= m_priceSubscription_FieldsUpdated;
                        m_priceSubscription.Dispose();
                        m_priceSubscription = null;
                    }
                    if (m_instrumentTradeSubscription != null)
                    {
                        m_instrumentTradeSubscription.OrderUpdated  -= m_instrumentTradeSubscription_OrderUpdated;
                        m_instrumentTradeSubscription.OrderAdded    -= m_instrumentTradeSubscription_OrderAdded;
                        m_instrumentTradeSubscription.OrderDeleted  -= m_instrumentTradeSubscription_OrderDeleted;
                        m_instrumentTradeSubscription.OrderFilled   -= m_instrumentTradeSubscription_OrderFilled;
                        m_instrumentTradeSubscription.OrderRejected -= m_instrumentTradeSubscription_OrderRejected;
                        m_instrumentTradeSubscription.Dispose();
                        m_instrumentTradeSubscription = null;
                    }

                    m_isDisposed = true;
                }


                TTAPI.Shutdown();
            }
        }
Exemple #17
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Event notification for instrument lookup. </summary>
        /// <param name="sender">   Source of the event. </param>
        /// <param name="e">        Instrument lookup subscription event information. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        void m_instrLookupRequest_OnData(object sender, InstrumentLookupEventArgs e)
        {
            if (e.Event == ProductDataEvent.Found)
            {
                // Instrument was found
                Instrument instrument = e.InstrumentLookup.Instrument;
                Console.WriteLine("Found: {0}", instrument);

                // Subscribe for market Data
                m_priceSubscription                = new PriceSubscription(instrument, tt_net_sdk.Dispatcher.Current);
                m_priceSubscription.Settings       = new PriceSubscriptionSettings(PriceSubscriptionType.MarketDepth);
                m_priceSubscription.FieldsUpdated += m_priceSubscription_FieldsUpdated;
                m_priceSubscription.Start();


                // Create a TradeSubscription to listen for order / fill events only for orders submitted through it
                m_instrumentTradeSubscription = new InstrumentTradeSubscription(tt_net_sdk.Dispatcher.Current, instrument);

                m_instrumentTradeSubscription.OrderUpdated      += new EventHandler <OrderUpdatedEventArgs>(m_instrumentTradeSubscription_OrderUpdated);
                m_instrumentTradeSubscription.OrderAdded        += new EventHandler <OrderAddedEventArgs>(m_instrumentTradeSubscription_OrderAdded);
                m_instrumentTradeSubscription.OrderDeleted      += new EventHandler <OrderDeletedEventArgs>(m_instrumentTradeSubscription_OrderDeleted);
                m_instrumentTradeSubscription.OrderFilled       += new EventHandler <OrderFilledEventArgs>(m_instrumentTradeSubscription_OrderFilled);
                m_instrumentTradeSubscription.OrderRejected     += new EventHandler <OrderRejectedEventArgs>(m_instrumentTradeSubscription_OrderRejected);
                m_instrumentTradeSubscription.OrderBookDownload += new EventHandler <OrderBookDownloadEventArgs>(m_instrumentTradeSubscription_OrderBookDownload);
                m_instrumentTradeSubscription.Start();
            }
            else if (e.Event == ProductDataEvent.NotAllowed)
            {
                Console.WriteLine("Not Allowed : Please check your Token access");
            }
            else
            {
                // Instrument was not found and TT API has given up looking for it
                Console.WriteLine("Cannot find instrument: {0}", e.Message);
                Dispose();
            }
        }
Exemple #18
0
        /// <summary>
        /// Instrument request completed event.
        /// </summary>
        void instrRequest_Completed(object sender, TT.InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.IsFinal && e.Instrument != null)
            {
                try
                {
                    cout("TT API FindInstrument {0}", e.Instrument.Name);

                    TTInstrument ttinstr = _instruments.Values.First(tti => tti.InstrumentKey == e.Instrument.Key);
                    ttinstr.FoundInstrument(e.Instrument);

                    // subscribe for price updates
                    m_priceSubscription                = new TT.PriceSubscription(e.Instrument, TT.Dispatcher.Current);
                    m_priceSubscription.Settings       = new TT.PriceSubscriptionSettings(TT.PriceSubscriptionType.InsideMarket);
                    m_priceSubscription.FieldsUpdated += new TT.FieldsUpdatedEventHandler(priceSubscription_FieldsUpdated);
                    m_priceSubscription.Start();

                    // subscribe for trade updates
                    m_instrumentTradeSubscription                = new InstrumentTradeSubscription(m_TTAPI.Session, TT.Dispatcher.Current, e.Instrument);
                    m_instrumentTradeSubscription.OrderAdded    += new EventHandler <TT.OrderAddedEventArgs>(m_instrumentTradeSubscription_OrderAdded);
                    m_instrumentTradeSubscription.OrderRejected += new EventHandler <TT.OrderRejectedEventArgs>(m_instrumentTradeSubscription_OrderRejected);
                    m_instrumentTradeSubscription.Start();
                }
                catch (Exception err)
                {
                    ErrorMessage("TT API FindInstrument Exception: {0}", err.Message);
                }
            }
            else if (e.IsFinal)
            {
                cout("TT API FindInstrument Instrument Not Found: {0}", e.Error);
            }
            else
            {
                cout("TT API FindInstrument Instrument Not Found: (Still Searching) {0}", e.Error);
            }
        }
        /// <summary>
        /// Dispose of all the TT API objects and shutdown the TT API 
        /// </summary>
        public void shutdownTTAPI()
        {
            if (!m_shutdownInProcess)
            {
                // Dispose of all request objects
                if (m_instrumentTradeSubscription != null)
                {
                    m_instrumentTradeSubscription.ProfitLossChanged -= instrumentTradeSubscription_ProfitLossChanged;
                    m_instrumentTradeSubscription.Dispose();
                    m_instrumentTradeSubscription = null;
                }

                TTAPI.ShutdownCompleted += new EventHandler(TTAPI_ShutdownCompleted);
                TTAPI.Shutdown();
            }

            // only run shutdown once
            m_shutdownInProcess = true;
        }
Exemple #20
0
        void GetBidAsk(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if ((string.IsNullOrEmpty(e.Fields.GetDirectBidPriceField().FormattedValue)) || (string.IsNullOrEmpty(e.Fields.GetDirectAskPriceField().FormattedValue)))
                {
                    return;
                }

                string InstrumentName = e.Fields.Instrument.Name.ToString();

                TickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString());
                string TickerHead = TA.TickerheadConverters.ConvertFromTT2DB(e.Fields.Instrument.Product.ToString());

                UpdatePriceData(ticker: TickerDB, tickerHead: TickerHead, e: e);

                TA.ttapiTicker TTAPITicker = TA.TickerConverters.ConvertFromDbTicker2ttapiTicker(dbTicker: TickerDB, productType: e.Fields.Instrument.Product.Type.ToString());

                InstrumentKey IKey = new InstrumentKey(new ProductKey(e.Fields.Instrument.Product.Market.Key, e.Fields.Instrument.Product.Type, e.Fields.Instrument.Product.Name), TTAPITicker.SeriesKey);
                Ts = TTAPISubs.TsDictionary[e.Fields.Instrument.Key];

                if (IlsDictionary.ContainsKey(IKey))
                {
                    for (int i = 0; i < ilsUpdateList.Count; i++)
                    {
                        IlsDictionary[IKey].Update -= ilsUpdateList[i];
                    }

                    IlsDictionary[IKey].Dispose();
                    IlsDictionary[IKey] = null;
                    IlsDictionary.Remove(IKey);
                    TTAPISubs.IlsDictionary = IlsDictionary;
                }


                if ((IlsDictionary.Count == 0) & (!PricesReceivedQ))
                {
                    PricesReceivedQ = true;

                    HedgeStrategies.HedgeStrategiesAgainstDelta(conn: conn, priceTable: PriceData);

                    DataTable StdMoves   = CalculateStdMoves(priceData: PriceData);
                    DataTable HedgeTable = GenerateHedgeTable(conn: conn);
                    NetHedgeTable = CalculateUrgency(hedgeTable: HedgeTable);
                    //NetHedgeTable = NetHedgeTable.Select("IsSpreadQ=true").CopyToDataTable();

                    List <string> TickerHeads2Report = DataAnalysis.DataTableFunctions.GetColumnAsList <string>(dataTableInput: StdMoves, columnName: "TickerHead", uniqueQ: true);



                    foreach (string TickerHead2Report in TickerHeads2Report)
                    {
                        DeltaLogger.Log(new String('-', 20));
                        DataRow[] SelectedRows = StdMoves.Select("TickerHead='" + TickerHead2Report + "'");

                        foreach (DataRow Row in SelectedRows)
                        {
                            DeltaLogger.Log(Row.Field <string>("Ticker") + " std change: " + Row.Field <double>("StdChange"));
                        }

                        DataRow[] SelectedHedgeRows = NetHedgeTable.Select("TickerHead='" + TickerHead2Report + "'");

                        foreach (DataRow Row in SelectedHedgeRows)
                        {
                            DeltaLogger.Log(Row.Field <int>("Hedge") + "  " + Row.Field <string>("Ticker") + " with urgency " + Row.Field <decimal>("Urgency"));
                        }
                    }

                    Console.Write("Do you agree? (Y/N): ");
                    Decision = Console.ReadLine();
                    Decision = Decision.ToUpper();


                    DataColumn WorkingOrdersColumn = new DataColumn("WorkingOrders", typeof(int));
                    WorkingOrdersColumn.DefaultValue = 0;
                    NetHedgeTable.Columns.Add(WorkingOrdersColumn);
                    NetHedgeTickerList = DataAnalysis.DataTableFunctions.GetColumnAsList <string>(dataTableInput: NetHedgeTable, columnName: "Ticker");
                }

                if ((PricesReceivedQ) && (Decision == "Y"))
                {
                    int RowIndex = NetHedgeTickerList.IndexOf(TickerDB);

                    if ((RowIndex < 0) || (NetHedgeTable.Rows[RowIndex].Field <int>("WorkingOrders") != 0))
                    {
                        return;
                    }

                    Price BidPrice = e.Fields.GetDirectBidPriceField().Value;
                    Price AskPrice = e.Fields.GetDirectAskPriceField().Value;

                    Price MidPrice = (AskPrice + BidPrice) / 2;

                    Price TradePrice;

                    NetHedgeTable.Rows[RowIndex]["WorkingOrders"] = NetHedgeTable.Rows[RowIndex].Field <int>("Hedge");

                    if (NetHedgeTable.Rows[RowIndex].Field <int>("Hedge") > 0)
                    {
                        if (NetHedgeTable.Rows[RowIndex].Field <decimal>("Urgency") > 5)
                        {
                            TradePrice = MidPrice.Round(Rounding.Up);
                        }
                        else
                        {
                            TradePrice = BidPrice;
                        }
                    }
                    else if (NetHedgeTable.Rows[RowIndex].Field <int>("Hedge") < 0)
                    {
                        if (NetHedgeTable.Rows[RowIndex].Field <decimal>("Urgency") > 5)
                        {
                            TradePrice = MidPrice.Round(Rounding.Down);
                        }
                        else
                        {
                            TradePrice = AskPrice;
                        }
                    }
                    else
                    {
                        return;
                    }

                    DeltaLogger.Log(NetHedgeTable.Rows[RowIndex].Field <int>("Hedge") + " " + TickerDB + " for " + TradePrice +
                                    ", Bid: " + e.Fields.GetDirectBidPriceField().FormattedValue +
                                    ", Ask: " + e.Fields.GetDirectAskPriceField().FormattedValue);
                    ttapiUtils.Trade.SendLimitOrder(instrument: e.Fields.Instrument, price: TradePrice,
                                                    qty: NetHedgeTable.Rows[RowIndex].Field <int>("Hedge"), ttapisubs: TTAPISubs, orderTag: "DeltaHedge");
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    //Dispose();
                }
            }
        }
        /// <summary>
        /// Instrument request completed event.
        /// </summary>
        void instrRequest_Completed(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.IsFinal && e.Instrument != null)
            {
                try
                {
                    UpdateStatusBar("Instrument Found.");
                    Console.WriteLine(String.Format("TT API FindInstrument {0}", e.Instrument.Name));

                    // Grab the contract specifications and output to the user
                    this.txtExchange.Text = e.Instrument.Product.Market.Name;
                    this.txtProduct.Text = e.Instrument.Product.Name;
                    this.txtProductType.Text = e.Instrument.Product.Type.ToString();
                    this.txtContract.Text = e.Instrument.GetFormattedName(InstrumentNameFormat.User);

                    if (m_instrumentTradeSubscription != null)
                    {
                        m_instrumentTradeSubscription.Dispose();
                        m_instrumentTradeSubscription = null;
                    }

                    // The use of the InstrumentTradeSubscription will filter for a specific instrument
                    m_instrumentTradeSubscription = new InstrumentTradeSubscription(m_TTAPI.Session, Dispatcher.Current, e.Instrument);
                    m_instrumentTradeSubscription.EnablePNL = true;
                    m_instrumentTradeSubscription.ProfitLossChanged += new EventHandler<ProfitLossChangedEventArgs>(instrumentTradeSubscription_ProfitLossChanged);
                    m_instrumentTradeSubscription.Start();
                }
                catch (Exception err)
                {
                    Console.WriteLine(String.Format("TT API FindInstrument Exception: {0}", err.Message));
                }
            }
            else if (e.IsFinal)
            {
                Console.WriteLine(String.Format("TT API FindInstrument Instrument Not Found: {0}", e.Error));
            }
            else
            {
                Console.WriteLine(String.Format("TT API FindInstrument Instrument Not Found: (Still Searching) {0}", e.Error));
            }
        }
        /// <summary>
        /// Event notification for price update
        /// </summary>

        void BreakoutAlgo(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                dateTimeNow = DateTime.Now;

                if ((dateTimeNow-DateTimePastPnlDisplay).Minutes>10)
                {
                    DisplayPnl();
                    DateTimePastPnlDisplay = dateTimeNow;
                }

                if (string.IsNullOrEmpty(e.Fields.GetDirectBidPriceField().FormattedValue))
                { return; }
                else
                { bidPrice = Convert.ToDouble(e.Fields.GetDirectBidPriceField().FormattedValue); }

                if (string.IsNullOrEmpty(e.Fields.GetDirectAskPriceField().FormattedValue))
                { return; }
                else
                { askPrice = Convert.ToDouble(e.Fields.GetDirectAskPriceField().FormattedValue); }

                midPrice = (bidPrice + askPrice) / 2;
                spreadPrice = askPrice - bidPrice;
                tickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString());

                string TickerHead = ContractUtilities.ContractMetaInfo.GetContractSpecs(tickerDB).tickerHead;
                string ExchangeName = ContractUtilities.ContractMetaInfo.GetExchange4Tickerhead(TickerHead);

                FilledPosition = BreakoutPosition.GetFilledPosition4Ticker(tickerDB);
                WorkingPosition = BreakoutPosition.GetWorkingPosition4Ticker(tickerDB);
                TotalPosition = FilledPosition + WorkingPosition;
                Std4Ticker = StdDict[tickerDB];
                Qty4Ticker = QtyDict[tickerDB];
                TotalOrders = BreakoutPosition.PositionWithAllOrders.Select("Qty<>0").Length;

                int tickerIndex = Enumerable.Range(0, dbTickerList.Count).Where(i => dbTickerList[i] == tickerDB).ToList()[0];
                ts = ttapiSubs.TsDictionary[e.Fields.Instrument.Key];

                if ((midPrice < rangeMinList[tickerIndex]) &&
                    (FilledPosition == 0) && (WorkingPosition==0) &&
                    (dateTimeNow < LastTradeEntryTime))
                {
                    if (Std4Ticker>StdPerBet)
                    {
                        BreakoutLogger.Log(tickerDB + " has std " + Std4Ticker + " too large for current risk limits! ");
                        return;
                    }

                    PortfolioVarChange = Risk.PorfolioRisk.GetChangeInRiskAfterTickerInclusion(BreakoutPosition.PositionWithAllOrders, CovMatrix,
                        tickerDB, -Qty4Ticker);

                    PortfolioStdAfter = Math.Sqrt(Math.Pow(PortfolioStd, 2) + PortfolioVarChange);

                    if (double.IsNaN(PortfolioStdAfter))
                    {
                        BreakoutLogger.Log("After trading " + tickerDB + " portfolio std would be: " + PortfolioStdAfter);
                        BreakoutLogger.Log("PortfolioStd: " + PortfolioStd);
                        BreakoutLogger.Log("PortfolioVarChange: " + PortfolioVarChange);
                        
                        return;
                    }

                    if (PortfolioStdAfter > PortfolioStdLimit)
                    {
                        BreakoutLogger.Log("After trading " + tickerDB + " portfolio std would be: " + PortfolioStdAfter + " too large!");
                        return;
                    }
                    else
                    {
                        BreakoutLogger.Log(tickerDB + " trade satisfies risk limit with target portfolio risk: " + PortfolioStdAfter);
                    }

                    BreakoutLogger.Log("Bearish Breakout in " + tickerDB);
                    BreakoutLogger.Log("Range Min: " + rangeMinList[tickerIndex]);
                    BreakoutLogger.Log("Current Price: " + midPrice);
                    BreakoutLogger.Log("Std 4 Ticker: " + Std4Ticker);
                    
                    if (TotalOrders>=MaxOrdersSent)
                    {
                        BreakoutLogger.Log("Total orders sent : " + TotalOrders + " is not smaller than " +MaxOrdersSent);
                        return;
                    }

                    if (LiveTradingQ)
                    {
                        ttapiUtils.Trade.SendLimitOrder(e.Fields.Instrument, e.Fields.GetBestAskPriceField().Value, -Qty4Ticker, ttapiSubs);
                        BreakoutPosition.OrderSend(tickerDB, -Qty4Ticker); 
                    }
                       
                    else
                    {
                        BreakoutPosition.OrderSend(tickerDB, -Qty4Ticker);
                        BreakoutPosition.OrderFill(tickerDB, -Qty4Ticker);
                    }
                    PortfolioStd = Risk.PorfolioRisk.GetPortfolioRiskFromCovMatrix(BreakoutPosition.PositionWithAllOrders, CovMatrix);
                    BreakoutLogger.Log("Portfolio Std After Fill: " + PortfolioStd);
                }
                else if ((midPrice > rangeMaxList[tickerIndex]) &&
                    (FilledPosition == 0) && (WorkingPosition == 0)&&
                    (dateTimeNow < LastTradeEntryTime))
                {
                    if (Std4Ticker > StdPerBet)
                    {
                        BreakoutLogger.Log(tickerDB + " has std " + Std4Ticker + " too large for current risk limits! ");
                        return;
                    }

                    PortfolioVarChange = Risk.PorfolioRisk.GetChangeInRiskAfterTickerInclusion(BreakoutPosition.PositionWithAllOrders, CovMatrix,
                        tickerDB, Qty4Ticker);

                    PortfolioStdAfter = Math.Sqrt(Math.Pow(PortfolioStd, 2) + PortfolioVarChange);
                 
                    if (double.IsNaN(PortfolioStdAfter))
                    {
                        BreakoutLogger.Log("After trading " + tickerDB + " portfolio std would be: " + PortfolioStdAfter);
                        BreakoutLogger.Log("PortfolioStd: " + PortfolioStd);
                        BreakoutLogger.Log("PortfolioVarChange: " + PortfolioVarChange);

                        return;
                    }

                    if (PortfolioStdAfter > PortfolioStdLimit)
                    {
                        BreakoutLogger.Log("After trading " + tickerDB + " portfolio std would be: " + PortfolioStdAfter + " too large!");
                        return;
                    }
                    else
                    {
                        BreakoutLogger.Log(tickerDB + " trade satisfies risk limit with target portfolio risk: " + PortfolioStdAfter);
                    }

                    BreakoutLogger.Log("Bullish Breakout in " + tickerDB);
                    BreakoutLogger.Log("Range Max: " + rangeMaxList[tickerIndex]);
                    BreakoutLogger.Log("Current Price: " + midPrice);
                    BreakoutLogger.Log("Std 4 Ticker: " + Std4Ticker);

                    if (TotalOrders >= MaxOrdersSent)
                    {
                        BreakoutLogger.Log("Total orders sent : " + TotalOrders + " is not smaller than " + MaxOrdersSent);
                        return;
                    }
                    
                    if (LiveTradingQ)
                    {
                        ttapiUtils.Trade.SendLimitOrder(e.Fields.Instrument, e.Fields.GetBestAskPriceField().Value, Qty4Ticker, ttapiSubs);
                        BreakoutPosition.OrderSend(tickerDB, Qty4Ticker);
                    }
                    else
                    {
                        BreakoutPosition.OrderSend(tickerDB, Qty4Ticker);
                        BreakoutPosition.OrderFill(tickerDB, Qty4Ticker);
                    }
                    PortfolioStd = Risk.PorfolioRisk.GetPortfolioRiskFromCovMatrix(BreakoutPosition.PositionWithAllOrders, CovMatrix);
                    BreakoutLogger.Log("Portfolio Std After Fill: " + PortfolioStd);
                    
                }

                else if ((FilledPosition > 0) && (WorkingPosition == 0) && (midPrice < rangeMinList[tickerIndex]))
                {
                    BreakoutLogger.Log("Pnl in " + tickerDB + ": " + (midPrice - rangeMaxList[tickerIndex]).ToString());

                    if (LiveTradingQ)
                    {
                        ttapiUtils.Trade.SendLimitOrder(e.Fields.Instrument, e.Fields.GetBestAskPriceField().Value, -(int)FilledPosition, ttapiSubs);
                        BreakoutPosition.OrderSend(tickerDB, -FilledPosition);
                    }

                    else
                    {
                        BreakoutPosition.OrderSend(tickerDB, -FilledPosition);
                        BreakoutPosition.OrderFill(tickerDB, -FilledPosition);
                       
                    }
                    PortfolioStd = Risk.PorfolioRisk.GetPortfolioRiskFromCovMatrix(BreakoutPosition.PositionWithAllOrders, CovMatrix);
                    BreakoutLogger.Log("Portfolio Std After Fill: " + PortfolioStd);

                }

                else if ((FilledPosition < 0) && (WorkingPosition == 0) && (midPrice > rangeMaxList[tickerIndex]))
                {
                    BreakoutLogger.Log("Pnl in " + tickerDB + ": " + (rangeMinList[tickerIndex] - midPrice).ToString());

                    if (LiveTradingQ)
                    {
                        ttapiUtils.Trade.SendLimitOrder(e.Fields.Instrument, e.Fields.GetBestAskPriceField().Value, -(int)FilledPosition, ttapiSubs);
                        BreakoutPosition.OrderSend(tickerDB, -FilledPosition);
                       
                    }
                    else
                    {
                        BreakoutPosition.OrderSend(tickerDB, -FilledPosition);
                        BreakoutPosition.OrderFill(tickerDB, -FilledPosition);
                    }
                    PortfolioStd = Risk.PorfolioRisk.GetPortfolioRiskFromCovMatrix(BreakoutPosition.PositionWithAllOrders, CovMatrix);
                    BreakoutLogger.Log("Portfolio Std After Fill: " + PortfolioStd);
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    ttapiSubs.Dispose();
                }
            }
        }
Exemple #23
0
        /// <summary>
        /// Event notification for price update
        /// </summary>

        void BreakoutAlgo(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                dateTimeNow = DateTime.Now;

                if ((dateTimeNow - DateTimePastPnlDisplay).Minutes > 10)
                {
                    DisplayPnl();
                    DateTimePastPnlDisplay = dateTimeNow;
                }

                if (string.IsNullOrEmpty(e.Fields.GetDirectBidPriceField().FormattedValue))
                {
                    return;
                }
                else
                {
                    bidPrice = Convert.ToDouble(e.Fields.GetDirectBidPriceField().FormattedValue);
                }

                if (string.IsNullOrEmpty(e.Fields.GetDirectAskPriceField().FormattedValue))
                {
                    return;
                }
                else
                {
                    askPrice = Convert.ToDouble(e.Fields.GetDirectAskPriceField().FormattedValue);
                }

                midPrice    = (bidPrice + askPrice) / 2;
                spreadPrice = askPrice - bidPrice;
                tickerDB    = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString());

                string TickerHead   = ContractUtilities.ContractMetaInfo.GetContractSpecs(tickerDB).tickerHead;
                string ExchangeName = ContractUtilities.ContractMetaInfo.GetExchange4Tickerhead(TickerHead);

                FilledPosition  = BreakoutPosition.GetFilledPosition4Ticker(tickerDB);
                WorkingPosition = BreakoutPosition.GetWorkingPosition4Ticker(tickerDB);
                TotalPosition   = FilledPosition + WorkingPosition;
                Std4Ticker      = StdDict[tickerDB];
                Qty4Ticker      = QtyDict[tickerDB];
                TotalOrders     = BreakoutPosition.PositionWithAllOrders.Select("Qty<>0").Length;

                int tickerIndex = Enumerable.Range(0, dbTickerList.Count).Where(i => dbTickerList[i] == tickerDB).ToList()[0];
                ts = ttapiSubs.TsDictionary[e.Fields.Instrument.Key];

                if ((midPrice < rangeMinList[tickerIndex]) &&
                    (FilledPosition == 0) && (WorkingPosition == 0) &&
                    (dateTimeNow < LastTradeEntryTime))
                {
                    if (Std4Ticker > StdPerBet)
                    {
                        BreakoutLogger.Log(tickerDB + " has std " + Std4Ticker + " too large for current risk limits! ");
                        return;
                    }

                    PortfolioVarChange = Risk.PorfolioRisk.GetChangeInRiskAfterTickerInclusion(BreakoutPosition.PositionWithAllOrders, CovMatrix,
                                                                                               tickerDB, -Qty4Ticker);

                    PortfolioStdAfter = Math.Sqrt(Math.Pow(PortfolioStd, 2) + PortfolioVarChange);

                    if (double.IsNaN(PortfolioStdAfter))
                    {
                        BreakoutLogger.Log("After trading " + tickerDB + " portfolio std would be: " + PortfolioStdAfter);
                        BreakoutLogger.Log("PortfolioStd: " + PortfolioStd);
                        BreakoutLogger.Log("PortfolioVarChange: " + PortfolioVarChange);

                        return;
                    }

                    if (PortfolioStdAfter > PortfolioStdLimit)
                    {
                        BreakoutLogger.Log("After trading " + tickerDB + " portfolio std would be: " + PortfolioStdAfter + " too large!");
                        return;
                    }
                    else
                    {
                        BreakoutLogger.Log(tickerDB + " trade satisfies risk limit with target portfolio risk: " + PortfolioStdAfter);
                    }

                    BreakoutLogger.Log("Bearish Breakout in " + tickerDB);
                    BreakoutLogger.Log("Range Min: " + rangeMinList[tickerIndex]);
                    BreakoutLogger.Log("Current Price: " + midPrice);
                    BreakoutLogger.Log("Std 4 Ticker: " + Std4Ticker);

                    if (TotalOrders >= MaxOrdersSent)
                    {
                        BreakoutLogger.Log("Total orders sent : " + TotalOrders + " is not smaller than " + MaxOrdersSent);
                        return;
                    }

                    if (LiveTradingQ)
                    {
                        ttapiUtils.Trade.SendLimitOrder(e.Fields.Instrument, e.Fields.GetBestAskPriceField().Value, -Qty4Ticker, ttapiSubs);
                        BreakoutPosition.OrderSend(tickerDB, -Qty4Ticker);
                    }

                    else
                    {
                        BreakoutPosition.OrderSend(tickerDB, -Qty4Ticker);
                        BreakoutPosition.OrderFill(tickerDB, -Qty4Ticker);
                    }
                    PortfolioStd = Risk.PorfolioRisk.GetPortfolioRiskFromCovMatrix(BreakoutPosition.PositionWithAllOrders, CovMatrix);
                    BreakoutLogger.Log("Portfolio Std After Fill: " + PortfolioStd);
                }
                else if ((midPrice > rangeMaxList[tickerIndex]) &&
                         (FilledPosition == 0) && (WorkingPosition == 0) &&
                         (dateTimeNow < LastTradeEntryTime))
                {
                    if (Std4Ticker > StdPerBet)
                    {
                        BreakoutLogger.Log(tickerDB + " has std " + Std4Ticker + " too large for current risk limits! ");
                        return;
                    }

                    PortfolioVarChange = Risk.PorfolioRisk.GetChangeInRiskAfterTickerInclusion(BreakoutPosition.PositionWithAllOrders, CovMatrix,
                                                                                               tickerDB, Qty4Ticker);

                    PortfolioStdAfter = Math.Sqrt(Math.Pow(PortfolioStd, 2) + PortfolioVarChange);

                    if (double.IsNaN(PortfolioStdAfter))
                    {
                        BreakoutLogger.Log("After trading " + tickerDB + " portfolio std would be: " + PortfolioStdAfter);
                        BreakoutLogger.Log("PortfolioStd: " + PortfolioStd);
                        BreakoutLogger.Log("PortfolioVarChange: " + PortfolioVarChange);

                        return;
                    }

                    if (PortfolioStdAfter > PortfolioStdLimit)
                    {
                        BreakoutLogger.Log("After trading " + tickerDB + " portfolio std would be: " + PortfolioStdAfter + " too large!");
                        return;
                    }
                    else
                    {
                        BreakoutLogger.Log(tickerDB + " trade satisfies risk limit with target portfolio risk: " + PortfolioStdAfter);
                    }

                    BreakoutLogger.Log("Bullish Breakout in " + tickerDB);
                    BreakoutLogger.Log("Range Max: " + rangeMaxList[tickerIndex]);
                    BreakoutLogger.Log("Current Price: " + midPrice);
                    BreakoutLogger.Log("Std 4 Ticker: " + Std4Ticker);

                    if (TotalOrders >= MaxOrdersSent)
                    {
                        BreakoutLogger.Log("Total orders sent : " + TotalOrders + " is not smaller than " + MaxOrdersSent);
                        return;
                    }

                    if (LiveTradingQ)
                    {
                        ttapiUtils.Trade.SendLimitOrder(e.Fields.Instrument, e.Fields.GetBestAskPriceField().Value, Qty4Ticker, ttapiSubs);
                        BreakoutPosition.OrderSend(tickerDB, Qty4Ticker);
                    }
                    else
                    {
                        BreakoutPosition.OrderSend(tickerDB, Qty4Ticker);
                        BreakoutPosition.OrderFill(tickerDB, Qty4Ticker);
                    }
                    PortfolioStd = Risk.PorfolioRisk.GetPortfolioRiskFromCovMatrix(BreakoutPosition.PositionWithAllOrders, CovMatrix);
                    BreakoutLogger.Log("Portfolio Std After Fill: " + PortfolioStd);
                }

                else if ((FilledPosition > 0) && (WorkingPosition == 0) && (midPrice < rangeMinList[tickerIndex]))
                {
                    BreakoutLogger.Log("Pnl in " + tickerDB + ": " + (midPrice - rangeMaxList[tickerIndex]).ToString());

                    if (LiveTradingQ)
                    {
                        ttapiUtils.Trade.SendLimitOrder(e.Fields.Instrument, e.Fields.GetBestAskPriceField().Value, -(int)FilledPosition, ttapiSubs);
                        BreakoutPosition.OrderSend(tickerDB, -FilledPosition);
                    }

                    else
                    {
                        BreakoutPosition.OrderSend(tickerDB, -FilledPosition);
                        BreakoutPosition.OrderFill(tickerDB, -FilledPosition);
                    }
                    PortfolioStd = Risk.PorfolioRisk.GetPortfolioRiskFromCovMatrix(BreakoutPosition.PositionWithAllOrders, CovMatrix);
                    BreakoutLogger.Log("Portfolio Std After Fill: " + PortfolioStd);
                }

                else if ((FilledPosition < 0) && (WorkingPosition == 0) && (midPrice > rangeMaxList[tickerIndex]))
                {
                    BreakoutLogger.Log("Pnl in " + tickerDB + ": " + (rangeMinList[tickerIndex] - midPrice).ToString());

                    if (LiveTradingQ)
                    {
                        ttapiUtils.Trade.SendLimitOrder(e.Fields.Instrument, e.Fields.GetBestAskPriceField().Value, -(int)FilledPosition, ttapiSubs);
                        BreakoutPosition.OrderSend(tickerDB, -FilledPosition);
                    }
                    else
                    {
                        BreakoutPosition.OrderSend(tickerDB, -FilledPosition);
                        BreakoutPosition.OrderFill(tickerDB, -FilledPosition);
                    }
                    PortfolioStd = Risk.PorfolioRisk.GetPortfolioRiskFromCovMatrix(BreakoutPosition.PositionWithAllOrders, CovMatrix);
                    BreakoutLogger.Log("Portfolio Std After Fill: " + PortfolioStd);
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    ttapiSubs.Dispose();
                }
            }
        }
        /// <summary>
        /// Dispose of all the TT API objects and shutdown the TT API 
        /// </summary>
        public void shutdownTTAPI()
        {
            if (!m_shutdownInProcess)
            {
                // Dispose of all request objects
                if (m_customerDefaultsSubscription != null)
                {
                    m_customerDefaultsSubscription.CustomerDefaultsChanged -= m_CustomerDefaultsSubscription_CustomerDefaultsChanged;
                    m_customerDefaultsSubscription.Dispose();
                    m_customerDefaultsSubscription = null;
                }

                if (m_instrumentTradeSubscription != null)
                {
                    m_instrumentTradeSubscription.OrderAdded -= instrumentTradeSubscription_OrderAdded;
                    m_instrumentTradeSubscription.OrderDeleted -= instrumentTradeSubscription_OrderDeleted;
                    m_instrumentTradeSubscription.Dispose();
                    m_instrumentTradeSubscription = null;
                }

                TTAPI.ShutdownCompleted += new EventHandler(TTAPI_ShutdownCompleted);
                TTAPI.Shutdown();
            }

            // only run shutdown once
            m_shutdownInProcess = true;
        }
        private void CreateInstrumentTradeSubscription(Instrument instrument)
        {
            if (m_instrumentTradeSubscription != null)
            {
                m_instrumentTradeSubscription.Dispose();
                m_instrumentTradeSubscription = null;
            }

            m_instrumentTradeSubscription = new InstrumentTradeSubscription(m_TTAPI.Session, Dispatcher.Current, instrument);
            m_instrumentTradeSubscription.OrderAdded += new EventHandler<OrderAddedEventArgs>(instrumentTradeSubscription_OrderAdded);
            m_instrumentTradeSubscription.OrderDeleted += new EventHandler<OrderDeletedEventArgs>(instrumentTradeSubscription_OrderDeleted);
        }
        /// <summary>
        /// Instrument request completed event.
        /// </summary>
        void instrRequest_Completed(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.IsFinal && e.Instrument != null)
            {
                try
                {
                    UpdateStatusBar("Instrument Found.");
                    Console.WriteLine(String.Format("TT API FindInstrument {0}", e.Instrument.Name));

                    // Grab the contract specifications and output to the user
                    this.txtExchange.Text = e.Instrument.Product.Market.Name;
                    this.txtProduct.Text = e.Instrument.Product.Name;
                    this.txtProductType.Text = e.Instrument.Product.Type.ToString();
                    this.txtContract.Text = e.Instrument.GetFormattedName(InstrumentNameFormat.User);

                    if (m_InstrumentTradeSubscription != null)
                    {
                        m_InstrumentTradeSubscription.Dispose();
                        m_InstrumentTradeSubscription = null;
                    }

                    // populate the order feed dropdown
                    this.cboOrderFeed.Items.Clear();
                    foreach (OrderFeed orderFeed in e.Instrument.GetValidOrderFeeds())
                        this.cboOrderFeed.Items.Add(orderFeed);

                    this.cboOrderFeed.SelectedIndex = 0;

                    // This sample will monitor new orders and deleting working orders
                    m_InstrumentTradeSubscription = new InstrumentTradeSubscription(m_TTAPI.Session, Dispatcher.Current, e.Instrument);
                    m_InstrumentTradeSubscription.OrderAdded += new EventHandler<OrderAddedEventArgs>(instrumentTradeSubscription_OrderAdded);
                    m_InstrumentTradeSubscription.OrderDeleted += new EventHandler<OrderDeletedEventArgs>(instrumentTradeSubscription_OrderDeleted);
                    m_InstrumentTradeSubscription.Start();
                }
                catch (Exception err)
                {
                    Console.WriteLine(String.Format("TT API FindInstrument Exception: {0}", err.Message));
                }
            }
            else if (e.IsFinal)
            {
                Console.WriteLine(String.Format("TT API FindInstrument Instrument Not Found: {0}", e.Error));
            }
            else
            {
                Console.WriteLine(String.Format("TT API FindInstrument Instrument Not Found: (Still Searching) {0}", e.Error));
            }
        }
        /// <summary>
        /// Create subscriptions and update the GUI.
        /// </summary>
        /// <param name="instrument">Instrument to create subscriptions with.</param>
        private void instrumentFound(Instrument instrument)
        {
            txtExchange.Text = instrument.Key.MarketKey.Name;
            txtProduct.Text = instrument.Key.ProductKey.Name;
            txtProductType.Text = instrument.Key.ProductKey.Type.Name;
            txtContract.Text = instrument.Name;

            m_priceSubscription = new PriceSubscription(instrument, Dispatcher.Current);
            m_priceSubscription.FieldsUpdated += new FieldsUpdatedEventHandler(m_priceSubscription_FieldsUpdated);
            m_priceSubscription.Start();

            m_instrumentTradeSubscription = new InstrumentTradeSubscription(m_TTAPI.Session, Dispatcher.Current, instrument);
            m_instrumentTradeSubscription.OrderAdded += new EventHandler<OrderAddedEventArgs>(m_instrumentTradeSubscription_OrderAdded);
            m_instrumentTradeSubscription.OrderRejected += new EventHandler<OrderRejectedEventArgs>(m_instrumentTradeSubscription_OrderRejected);
            m_instrumentTradeSubscription.Start();

            populateOrderFeedDropDown(instrument);

            // Enable the user interface items.
            txtQuantity.Enabled = true;
            cboOrderType.Enabled = true;
            comboBoxOrderFeed.Enabled = true;
            cboCustomer.Enabled = true;
            btnBuy.Enabled = true;
            btnSell.Enabled = true;
        }
        /// <summary>
        /// Event notification for instrument lookup
        /// </summary>
        void m_req_Update(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.Instrument != null && e.Error == null)
            {
                // Instrument was found
                Console.WriteLine("Found: {0}", e.Instrument.Name);

                // Subscribe for Inside Market Data
                m_ps = new PriceSubscription(e.Instrument, Dispatcher.Current);
                m_ps.Settings = new PriceSubscriptionSettings(PriceSubscriptionType.InsideMarket);
                m_ps.FieldsUpdated += new FieldsUpdatedEventHandler(m_ps_FieldsUpdated);
                m_ps.Start();

                // Create a TradeSubscription to listen for order / fill events only for orders submitted through it
                m_ts = new InstrumentTradeSubscription(m_apiInstance.Session, Dispatcher.Current, e.Instrument, true, true, false, false);
                m_ts.OrderUpdated += new EventHandler<OrderUpdatedEventArgs>(m_ts_OrderUpdated);
                m_ts.OrderAdded += new EventHandler<OrderAddedEventArgs>(m_ts_OrderAdded);
                m_ts.OrderDeleted += new EventHandler<OrderDeletedEventArgs>(m_ts_OrderDeleted);
                m_ts.OrderFilled += new EventHandler<OrderFilledEventArgs>(m_ts_OrderFilled);
                m_ts.OrderRejected += new EventHandler<OrderRejectedEventArgs>(m_ts_OrderRejected);
                m_ts.Start();
            }
            else if (e.IsFinal)
            {
                // Instrument was not found and TT API has given up looking for it
                Console.WriteLine("Cannot find instrument: {0}", e.Error.Message);
                Dispose();
            }
        }
        /// <summary>
        /// Shuts down the TT API
        /// </summary>
        public void Dispose()
        {
            lock(m_lock)
            {
                if (!m_disposed)
                {
                    // Unattached callbacks and dispose of all subscriptions
                    if (m_req != null)
                    {
                        m_req.Update -= m_req_Update;
                        m_req.Dispose();
                        m_req = null;
                    }
                    if (m_ps != null)
                    {
                        m_ps.FieldsUpdated -= m_ps_FieldsUpdated;
                        m_ps.Dispose();
                        m_ps = null;
                    }
                    if (m_ts != null)
                    {
                        m_ts.OrderAdded -= m_ts_OrderAdded;
                        m_ts.OrderDeleted -= m_ts_OrderDeleted;
                        m_ts.OrderFilled -= m_ts_OrderFilled;
                        m_ts.OrderRejected -= m_ts_OrderRejected;
                        m_ts.OrderUpdated -= m_ts_OrderUpdated;
                        m_ts.Dispose();
                        m_ts = null;
                    }

                    // Begin shutdown the TT API
                    TTAPI.ShutdownCompleted += new EventHandler(TTAPI_ShutdownCompleted);
                    TTAPI.Shutdown();

                    m_disposed = true;
                }
            }
        }
        public void startTradeSubscriptions(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.Instrument != null && e.Error == null)
            {
                // Create a TradeSubscription to listen for order / fill events only for orders submitted through it
                ts = new InstrumentTradeSubscription(m_apiInstance.Session, Dispatcher.Current, e.Instrument, true, true, false, false);
                ts.OrderUpdated += new EventHandler<OrderUpdatedEventArgs>(m_ts_OrderUpdated);
                ts.OrderAdded += new EventHandler<OrderAddedEventArgs>(m_ts_OrderAdded);
                ts.OrderDeleted += new EventHandler<OrderDeletedEventArgs>(m_ts_OrderDeleted);

                if (orderFilledEventHandler !=null)
                {
                    ts.OrderFilled += new EventHandler<OrderFilledEventArgs>(orderFilledEventHandler);
                }
               
                ts.OrderRejected += new EventHandler<OrderRejectedEventArgs>(m_ts_OrderRejected);

                TsDictionary.Add(e.Instrument.Key,ts);
                ts.Start();
            }
            else if (e.IsFinal)
            {
                // Instrument was not found and TT API has given up looking for it
                Console.WriteLine("Cannot find instrument: {0}", e.Error.Message);
                Dispose();
            }
        }