private void ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                Last = MidPoint;

                double Bid = e.Fields.GetBestBidPriceField().Value.ToTicks();
                double Ask = e.Fields.GetBestAskPriceField().Value.ToTicks();

                MidPoint = ((Ask - Bid) / 2) + Bid;

                if (First == 0 && e.Fields.GetOpenPriceField().HasValidValue)
                {
                    First = e.Fields.GetOpenPriceField().Value.ToTicks();
                }

                if (High == 0)
                {
                    High = MidPoint;
                }
                if (Low == 0)
                {
                    Low = MidPoint;
                }

                if (MidPoint > High)
                {
                    High = MidPoint;
                }
                else if (MidPoint < Low)
                {
                    Low = MidPoint;
                }
            }
        }
        void priceSub_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // Initial price info is sent as a snapshot
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    foreach (FieldId id in e.Fields.GetFieldIds())
                    {
                        Field f = e.Fields[id];
                        // put code to process the field here
                        //Console.WriteLine(f.FieldId.ToString() + " : " + f.FormattedValue);
                    }
                }
                else
                {
                    // only some fields have changed (not snapshot like initial price update)
                    foreach (FieldId id in e.Fields.GetChangedFieldIds())
                    {
                        Field f = e.Fields[id];
                        // put code to process the field here
                        //Console.WriteLine("***" + f.FieldId.ToString() + " : " + f.FormattedValue);
                    }

                    // you can access specified field values directly...
                    Price    bid    = e.Fields.GetDirectBidPriceField().Value;
                    Quantity bidQty = e.Fields.GetBidMarketQuantityField().Value;
                }
            }
        }
Exemple #3
0
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            Price  BidPrice = e.Fields.GetDirectBidPriceField().Value;
            Price  AskPrice = e.Fields.GetDirectAskPriceField().Value;
            double BidPriceDb;
            double AskPriceDb;

            DateTimeNow = DateTime.Now;
            TickerDB    = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString());

            if (!BidPrice.IsTradable)
            {
                return;
            }
            else
            {
                BidPriceDb = BidPrice.ToDouble();
                BidPriceDictionary[TickerDB] = BidPriceDb;
            }

            if (!AskPrice.IsTradable)
            {
                return;
            }
            else
            {
                AskPriceDb = AskPrice.ToDouble();
                AskPriceDictionary[TickerDB] = AskPriceDb;
            }


            candleObj.updateValues((BidPriceDb + AskPriceDb) / 2, DateTimeNow, TickerDB);
        }
        public void priceSub_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot
                    Console.WriteLine("Market Data Snapshot:");

                    foreach (FieldId id in e.Fields.GetFieldIds())
                    {
                        Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id].FormattedValue);
                    }
                }
                else
                {
                    // Only some fields have changed
                    Console.WriteLine("Market Data Update:");

                    foreach (FieldId id in e.Fields.GetChangedFieldIds())
                    {
                        Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id].FormattedValue);
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: " + e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #5
0
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                int RowIndex = ASENameList.IndexOf(e.Fields.Instrument.Name);

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

                double BidPriceDb = BidPrice.ToDouble();
                double AskPriceDb = AskPrice.ToDouble();

                SummaryTable.Rows[RowIndex]["Bid"] = BidPrice.ToDouble();
                SummaryTable.Rows[RowIndex]["Ask"] = AskPrice.ToDouble();

                SummaryTable.Rows[RowIndex]["Mid"] = (SummaryTable.Rows[RowIndex].Field <double>("Bid") + SummaryTable.Rows[RowIndex].Field <double>("Ask")) / 2;

                SummaryTable.Rows[RowIndex]["MidConverted"] = TA.PriceConverters.FromTTAutoSpreader2DB(ttPrice: (decimal)SummaryTable.Rows[RowIndex].Field <double>("Mid"), tickerHead: SummaryTable.Rows[RowIndex].Field <string>("TickerHead"));

                SummaryTable.Rows[RowIndex]["ValidPrice"] = true;
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #6
0
        void UpdatePriceData(string ticker, string tickerHead, FieldsUpdatedEventArgs e)
        {
            int RowIndex = UnderlyingTickerList.IndexOf(ticker);

            if (string.IsNullOrEmpty(e.Fields.GetDirectBidPriceField().FormattedValue))
            {
                return;
            }
            else
            {
                PriceData.Rows[RowIndex]["BidPrice"] = TA.PriceConverters.FromTT2DB(ttPrice: Convert.ToDecimal(e.Fields.GetDirectBidPriceField().FormattedValue), tickerHead: tickerHead);
            }

            if (string.IsNullOrEmpty(e.Fields.GetDirectBidPriceField().FormattedValue))
            {
                return;
            }
            else
            {
                PriceData.Rows[RowIndex]["AskPrice"] = TA.PriceConverters.FromTT2DB(ttPrice: Convert.ToDecimal(e.Fields.GetDirectAskPriceField().FormattedValue), tickerHead: tickerHead);
            }

            PriceData.Rows[RowIndex]["MidPrice"] = (PriceData.Rows[RowIndex].Field <decimal>("AskPrice") +
                                                    PriceData.Rows[RowIndex].Field <decimal>("BidPrice")) / 2;

            PriceData.Rows[RowIndex]["SpreadCost"] = (PriceData.Rows[RowIndex].Field <decimal>("AskPrice") -
                                                      PriceData.Rows[RowIndex].Field <decimal>("BidPrice")) * (decimal)ContractUtilities.ContractMetaInfo.ContractMultiplier[tickerHead];
        }
Exemple #7
0
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));

                    sw.WriteLine("{0},{1},{2},{3},{4},{5}", e.Fields.Instrument.Name,
                                 e.Fields.Instrument.Key.MarketKey.ToString(),
                                 e.Fields.Instrument.Product.Type.ToString(),
                                 e.Fields.Instrument.Product.Name.ToString(),
                                 e.Fields.Instrument.Name.ToString(),
                                 e.Fields[FieldId.TotalTradedQuantity].FormattedValue);
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #8
0
        private void PriceFieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            Price bid   = e.Fields.GetBestBidPriceField().Value;
            Price ask   = e.Fields.GetBestAskPriceField().Value;
            Price close = e.Fields.GetSettlementPriceField().Value; // closeField is contains wrong values

            string instrumentTtCode = e.Fields.Instrument.Key.SeriesKey;

            if (_instrumentToSubscribe[instrumentTtCode].PriceType == "Mid")
            {
                if (e.Error == null && bid.IsTradable && ask.IsTradable)
                {
                    log.Debug($"instru: {instrumentTtCode} mid: {(bid.ToDouble() + ask.ToDouble()) / 2}");
                    PriceUpdateEvent?.Invoke(this, instrumentTtCode, (bid.ToDouble() + ask.ToDouble()) / 2);
                }
            }
            else if (_instrumentToSubscribe[instrumentTtCode].PriceType == "Close")
            {
                if (_instrumentToSubscribe[instrumentTtCode].ClosePrice != close.ToDouble())
                {
                    log.Debug($"instru: {instrumentTtCode} close: {close.ToDouble()}");

                    if (e.Error == null && close.IsValid)
                    {
                        PriceUpdateEvent?.Invoke(this, instrumentTtCode, close.ToDouble());
                        _instrumentToSubscribe[instrumentTtCode].ClosePrice = close.ToDouble();
                    }
                }
            }
        }
        public void priceSub_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot
                    Console.WriteLine("Market Data Snapshot:");

                    foreach (FieldId id in e.Fields.GetFieldIds())
                    {
                        Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id].FormattedValue);
                    }
                }
                else
                {
                    // Only some fields have changed
                    Console.WriteLine("Market Data Update:");

                    foreach (FieldId id in e.Fields.GetChangedFieldIds())
                    {
                        Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id].FormattedValue);
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: " + e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #10
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Event notification for price update. </summary>
        /// <param name="sender">   Source of the event. </param>
        /// <param name="e">        Fields updated event information. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        void m_priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that there is a valid bid
                if (e.Fields.GetBestBidPriceField().Value != null && m_isOrderBookDownloaded)
                {
                    if (m_orderKey == "")
                    {
                        // If there is no order working, submit one .
                        OrderProfile op = new OrderProfile(e.Fields.Instrument);
                        op.BuySell       = BuySell.Buy;
                        op.Account       = m_accounts.ElementAt(0);
                        op.OrderQuantity = Quantity.FromDecimal(e.Fields.Instrument, 10);
                        op.OrderType     = OrderType.Limit;
                        op.LimitPrice    = e.Fields.GetBestBidPriceField().Value - 1;

                        if (!m_instrumentTradeSubscription.SendOrder(op))
                        {
                            Console.WriteLine("Send new order Failed.!!");
                            Dispose();
                        }
                        else
                        {
                            m_orderKey = op.SiteOrderKey;
                            Console.WriteLine("\nSent new order: " + e.Fields.Instrument.Name + " " + op.BuySell + " " + op.OrderQuantity.ToString() + "@" + op.LimitPrice.ToString() + " SOK=" + op.SiteOrderKey);
                        }
                    }
                    else if (m_instrumentTradeSubscription.Orders.ContainsKey(m_orderKey) &&
                             m_instrumentTradeSubscription.Orders[m_orderKey].LimitPrice != (e.Fields.GetBestBidPriceField().Value - 1))
                    {
                        // If there is a working order, reprice it
                        OrderProfile op = m_instrumentTradeSubscription.Orders[m_orderKey].GetOrderProfile();
                        op.LimitPrice = e.Fields.GetBestBidPriceField().Value - 1;
                        op.Action     = OrderAction.Change;

                        Console.WriteLine("Change price from {0} to {1}", m_instrumentTradeSubscription.Orders[m_orderKey].LimitPrice, op.LimitPrice);

                        if (!m_instrumentTradeSubscription.SendOrder(op))
                        {
                            Console.WriteLine("Sent order update: " + e.Fields.Instrument.Name + " " + op.OrderQuantity.ToString() + "@" + op.LimitPrice.ToString() + " SOK=" + op.SiteOrderKey);
                        }
                        else
                        {
                            Console.WriteLine("Send change order succeeded.");
                        }
                    }
                }
            }
            else
            {
                if (e.Error != null)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that there is a valid bid
                if (e.Fields.GetBestBidPriceField().HasValidValue)
                {
                    if (m_orderKey == "")
                    {
                        // If there is no order working, submit one through the first valid order feed.
                        // You should use the order feed that is valid for your purposes.
                        OrderProfile op = new OrderProfile(e.Fields.Instrument.GetValidOrderFeeds()[0], e.Fields.Instrument);
                        op.BuySell       = BuySell.Buy;
                        op.AccountName   = "12345678";
                        op.AccountType   = AccountType.A1;
                        op.OrderQuantity = Quantity.FromInt(e.Fields.Instrument, 10);
                        op.OrderType     = OrderType.Limit;
                        op.LimitPrice    = e.Fields.GetBestBidPriceField().Value;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send new order failed.  {0}", op.RoutingStatus.Message);
                            Dispose();
                        }
                        else
                        {
                            m_orderKey = op.SiteOrderKey;
                            Console.WriteLine("Send new order succeeded.");
                        }
                    }
                    else if (m_ts.Orders.ContainsKey(m_orderKey) &&
                             m_ts.Orders[m_orderKey].LimitPrice != e.Fields.GetBestBidPriceField().Value)
                    {
                        // If there is a working order, reprice it if its price is not the same as the bid
                        OrderProfileBase op = m_ts.Orders[m_orderKey].GetOrderProfile();
                        op.LimitPrice = e.Fields.GetBestBidPriceField().Value;
                        op.Action     = OrderAction.Change;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send change order failed.  {0}", op.RoutingStatus.Message);
                        }
                        else
                        {
                            Console.WriteLine("Send change order succeeded.");
                        }
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #12
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Event notification for price update. </summary>
        /// <param name="sender">   Source of the event. </param>
        /// <param name="e">        Fields updated event information. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        void m_priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            Console.WriteLine("\n================= {0}", m_ps_counter++);
            if (e.Error != null)
            {
                // Error has occured - the subscription is no longer active

                tt_net_sdk.PriceSubscription ps = (tt_net_sdk.PriceSubscription)sender;
                Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                ps.Dispose();
                return;
            }

            if (e.UpdateType == UpdateType.Snapshot)
            {
                // Received a detailed depth data snapshot

                // TODO: initialize your data here.
                //       the snap shot event can come multiple times
                Console.WriteLine("\nSnapshot Update");

                // You can now apply the changed/valid value fields.
            }
            else
            {
                Console.WriteLine("\nIncremental Update");
            }
            Console.WriteLine("\nTop and level 0 field(s):");
            foreach (FieldId f in e.Fields.GetChangedFieldIds())
            {
                Console.WriteLine("    {0} : {1}", f.ToString(), e.Fields[f].FormattedValue);
            }

            Console.WriteLine("\nDepth field(s):");
            int depthLevels = e.Fields.GetMaxDepthLevel();

            for (int i = 0; i < depthLevels; i++)
            {
                if (e.Fields.GetChangedFieldIds(i).Length > 0)
                {
                    Console.WriteLine("Level={0}", i);
                    foreach (FieldId id in e.Fields.GetChangedFieldIds(i))
                    {
                        Console.WriteLine("    {0}: {1}", id.ToString(), e.Fields[id, i].FormattedValue);
                    }

                    int detailedDepthLevels = e.Fields.GetMaxDetailedDepthLevel();
                    for (int j = 0; j < detailedDepthLevels; j++)
                    {
                        foreach (FieldId field in e.Fields.GetChangedFieldIds(i, j))
                        {
                            Console.WriteLine("             DETAILED DEPTH  {0}: {1}", field.ToString(), e.Fields[field, i, j].FormattedValue);
                        }
                    }
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that there is a valid bid
                if (e.Fields.GetBestBidPriceField().HasValidValue)
                {
                    if (m_orderKey == "")
                    {
                        // In this example, the order is submitted to ASE-A.
                        // You should use the order feed that is appropriate for your purposes.
                        AutospreaderSyntheticOrderProfile op = new AutospreaderSyntheticOrderProfile(((AutospreaderInstrument)e.Fields.Instrument).GetValidGateways()[m_ASEGateway],
                                                                                                     (AutospreaderInstrument)e.Fields.Instrument);
                        op.BuySell       = BuySell.Buy;
                        op.OrderQuantity = Quantity.FromInt(e.Fields.Instrument, 10);
                        op.OrderType     = OrderType.Limit;
                        op.LimitPrice    = e.Fields.GetBestBidPriceField().Value;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send new order failed.  {0}", op.RoutingStatus.Message);
                        }
                        else
                        {
                            m_orderKey = op.SiteOrderKey;
                            Console.WriteLine("Send new order succeeded.");
                        }
                    }
                    else if (m_ts.Orders.ContainsKey(m_orderKey) &&
                             m_ts.Orders[m_orderKey].LimitPrice != e.Fields.GetBestBidPriceField().Value)
                    {
                        // If there is a working order, reprice it if its price is not the same as the bid
                        AutospreaderSyntheticOrderProfile op = m_ts.Orders[m_orderKey].GetOrderProfile() as AutospreaderSyntheticOrderProfile;
                        op.LimitPrice = e.Fields.GetBestBidPriceField().Value;
                        op.Action     = OrderAction.Change;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send change order failed.  {0}", op.RoutingStatus.Message);
                        }
                        else
                        {
                            Console.WriteLine("Send change order succeeded.");
                        }
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
 /// <summary>
 /// Event to notify the application there has been a change in the price feed
 /// Here we pull the values and publish them to the GUI
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e">Struct containing data pertaining to the event</param>
 void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
 {
     // Extract the values we want as Typed fields
     this.txtBidPrice.Text  = e.Fields.GetDirectBidPriceField().FormattedValue;
     this.txtBidQty.Text    = e.Fields.GetDirectBidQuantityField().FormattedValue;
     this.txtAskPrice.Text  = e.Fields.GetDirectAskPriceField().FormattedValue;
     this.txtAskQty.Text    = e.Fields.GetDirectAskQuantityField().FormattedValue;
     this.txtLastPrice.Text = e.Fields.GetLastTradedPriceField().FormattedValue;
     this.txtLastQty.Text   = e.Fields.GetLastTradedQuantityField().FormattedValue;
 }
        public void priceSub_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (orderKey == null)
                {
                    // In this example, the order is routed to the first order feed in the list of valid order feeds.
                    // You should use the order feed that is appropriate for your purposes.
                    OrderProfile prof = new OrderProfile(e.Fields.Instrument.GetValidOrderFeeds()[0], e.Fields.Instrument);
                    prof.BuySell = BuySell.Buy;
                    prof.AccountType = AccountType.Agent1;
                    prof.AccountName = "fg006001";
                    prof.OrderQuantity = Quantity.FromInt(e.Fields.Instrument, 1);
                    prof.OrderType = OrderType.Limit;
                    prof.LimitPrice = e.Fields.GetBestBidPriceField().Value;

                    if (!ts.SendOrder(prof))
                    {
                        Console.WriteLine("Send Order failed : {0}", prof.RoutingStatus.Message);
                        Dispose();
                    }
                    else
                    {
                        orderKey = prof.SiteOrderKey;
                        Console.WriteLine("Order sent with price = {0}", prof.LimitPrice);
                    }
                }
                else if (ts.Orders.Keys.Contains(orderKey) &&
                         e.Fields.GetBestBidPriceField().HasValueChanged &&
                         e.Fields.GetBestBidPriceField().HasValidValue)
                {
                    OrderProfileBase prof = ts.Orders[orderKey].GetOrderProfile();
                    prof.LimitPrice = e.Fields.GetBestBidPriceField().Value;
                    prof.Action = OrderAction.Change;

                    if (!ts.SendOrder(prof))
                    {
                        Console.WriteLine("Send Order failed : {0}", prof.RoutingStatus.Message);
                        Dispose();
                    }
                    else
                    {
                        Console.WriteLine("Order Re-priced to {0}", prof.LimitPrice);
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: " + e.Error.Message);
                    Dispose();
                }
            }
        }
 private void PxSub_FieldsUpdated(object sender, FieldsUpdatedEventArgs evt)
 {
     if (evt.Error != null)
     {
         _obsvrRaw?.OnError(evt.Error);
     }
     else
     {
         _obsvrRaw?.OnNext(evt);
     }
 }
Exemple #17
0
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 /// <summary>   Event notification for price update. </summary>
 /// <param name="sender">   Source of the event. </param>
 /// <param name="e">        Fields updated event information. </param>
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 void m_priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
 {
     if (e.Error != null)
     {
         Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
         Dispose();
     }
     else if (e.Fields.GetBestBidPriceField().Value != null)
     {
         m_price = e.Fields.GetBestBidPriceField().Value - 1;
     }
 }
Exemple #18
0
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot

                    Console.WriteLine("Ask Depth Snapshot");
                    int askDepthLevels = e.Fields.GetLargestCurrentDepthLevel(FieldId.BestAskPrice);
                    for (int i = 0; i < askDepthLevels; i++)
                    {
                        Console.WriteLine("    Level={0} Qty={1} Price={2}", i, e.Fields.GetBestAskQuantityField(i).Value.ToInt(),
                                          e.Fields.GetBestAskPriceField(i).Value.ToString());
                    }

                    Console.WriteLine("Bid Depth Snapshot");
                    int bidDepthLevels = e.Fields.GetLargestCurrentDepthLevel(FieldId.BestBidPrice);
                    for (int i = 0; i < bidDepthLevels; i++)
                    {
                        Console.WriteLine("    Level={0} Qty={1} Price={2}", i, e.Fields.GetBestBidQuantityField(i).Value.ToInt(),
                                          e.Fields.GetBestBidPriceField(i).Value.ToString());
                    }
                }
                else
                {
                    // Only some fields have changed

                    Console.WriteLine("Depth Updates");
                    int depthLevels = e.Fields.GetLargestCurrentDepthLevel();
                    for (int i = 0; i < depthLevels; i++)
                    {
                        if (e.Fields.GetChangedFieldIds(i).Length > 0)
                        {
                            Console.WriteLine("Level={0}", i);
                            foreach (FieldId id in e.Fields.GetChangedFieldIds(i))
                            {
                                Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id, i].FormattedValue);
                            }
                        }
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that there is a valid bid
                if (e.Fields.GetBestBidPriceField().HasValidValue)
                {
                    if (m_orderKey == "")
                    {
                        // If there is no order working, submit one through the first valid order feed.
                        // You should use the order feed that is valid for your purposes.
                        OrderProfile op = new OrderProfile(e.Fields.Instrument.GetValidOrderFeeds()[0], e.Fields.Instrument);
                        op.BuySell       = BuySell.Buy;
                        op.AccountName   = "12345678";
                        op.AccountType   = AccountType.A1;
                        op.OrderQuantity = Quantity.FromInt(e.Fields.Instrument, 100);
                        op.OrderType     = OrderType.Limit;
                        op.LimitPrice    = e.Fields.GetBestBidPriceField().Value;

                        op.SlicerType               = SlicerType.TimeSliced;
                        op.DisclosedQuantity        = Quantity.FromInt(e.Fields.Instrument, 10);
                        op.DisclosedQuantityMode    = QuantityMode.Quantity;
                        op.InterSliceDelay          = 10;
                        op.InterSliceDelayTimeUnits = TimeUnits.Sec;
                        op.LeftoverAction           = LeftoverAction.Leave;
                        op.LeftoverActionTime       = LeftoverActionTime.AtEnd;
                        op.PriceMode = PriceMode.Absolute;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send new order failed.  {0}", op.RoutingStatus.Message);
                            Dispose();
                        }
                        else
                        {
                            m_orderKey = op.SiteOrderKey;
                            Console.WriteLine("Send new order succeeded.");
                        }
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {

            if (DateTime.Now > EndTime)
            {
                Dispatcher.Current.BeginInvoke(new Action(Dispose));
                return;
            }

            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot
                    //Console.WriteLine("Market Data Snapshot:");

                    foreach (FieldId id in e.Fields.GetFieldIds())
                    {

                        //e.Fields.Instrument

                        PriceFileDictionary[e.Fields.Instrument.Name.ToString()].AutoFlush = true;
                        PriceFileDictionary[e.Fields.Instrument.Name.ToString()].WriteLine("{0},{1},{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), id.ToString(), e.Fields[id].FormattedValue);
                        
                    }
                }
                else
                {
                    // Only some fields have changed
                    //Console.WriteLine("Market Data Update:");

                    foreach (FieldId id in e.Fields.GetChangedFieldIds())
                    {
                        Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id].FormattedValue);

                        PriceFileDictionary[e.Fields.Instrument.Name.ToString()].WriteLine("{0},{1},{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),id.ToString(), e.Fields[id].FormattedValue);
                        
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #21
0
        public static MosaicPrice ToMosaicPrice(FieldsUpdatedEventArgs qt)
        {
            var data = new MosaicPrice()
            {
                InstrumentKey   = qt.Fields.Instrument.Key.ToString(),
                PriceType       = qt.Fields.Instrument.Product.Type.ToString(),
                Bid_px          = qt.Fields.GetBestBidPriceField().Value.IsValid ? (decimal?)qt.Fields.GetBestBidPriceField().Value.Value: null,
                Bid_qty         = qt.Fields.GetBestBidPriceField().Value.IsValid ? (decimal?)qt.Fields.GetBestBidQuantityField().Value.Value : null,
                Ask_px          = qt.Fields.GetBestAskPriceField().Value.IsValid ? (decimal?)qt.Fields.GetBestAskPriceField().Value.Value : null,
                Ask_qty         = qt.Fields.GetBestAskPriceField().Value.IsValid ? (decimal?)qt.Fields.GetBestAskQuantityField().Value.Value : null,
                SettlePrice     = qt.Fields.GetSettlementPriceField().Value.IsValid ? (decimal?)qt.Fields.GetSettlementPriceField().Value.Value: null,
                IndicativePrice = qt.Fields.GetIndicativePriceField().Value.IsValid ? (decimal?)qt.Fields.GetIndicativePriceField().Value.Value: null
            };

            return(data);
        }
        /// <summary>
        /// Event to notify the application there has been a change in the price feed
        /// Here we pull the values and publish them to the GUI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error != null)
            {
                Console.WriteLine(String.Format("TT API FieldsUpdated Error: {0}", e.Error));
                return;
            }

            // Extract the values we want as Typed fields
            this.txtBidPrice.Text  = e.Fields.GetDirectBidPriceField().FormattedValue;
            this.txtBidQty.Text    = e.Fields.GetDirectBidQuantityField().FormattedValue;
            this.txtAskPrice.Text  = e.Fields.GetDirectAskPriceField().FormattedValue;
            this.txtAskQty.Text    = e.Fields.GetDirectAskQuantityField().FormattedValue;
            this.txtLastPrice.Text = e.Fields.GetLastTradedPriceField().FormattedValue;
            this.txtLastQty.Text   = e.Fields.GetLastTradedQuantityField().FormattedValue;
        }
        public void priceSub_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (orderKey == null)
                {
                    // This is a time-slicer order
                    // In this example, the order is routed to the first order feed in the list of valid order feeds.
                    // You should use the order feed that is appropriate for your purposes.
                    OrderProfile prof = new OrderProfile(e.Fields.Instrument.GetValidOrderFeeds()[0], e.Fields.Instrument);
                    prof.BuySell = BuySell.Buy;
                    prof.AccountType = AccountType.Agent1;
                    prof.AccountName = "123";
                    prof.OrderQuantity = Quantity.FromInt(e.Fields.Instrument, 100);
                    prof.OrderType = OrderType.Limit;
                    prof.LimitPrice = e.Fields.GetBestBidPriceField().Value;

                    prof.SlicerType = SlicerType.TimeSliced;
                    prof.DisclosedQuantity = Quantity.FromInt(e.Fields.Instrument, 10);
                    prof.DisclosedQuantityMode = QuantityMode.Quantity;
                    prof.InterSliceDelay = 10;
                    prof.InterSliceDelayTimeUnits = TimeUnits.Sec;
                    prof.LeftoverAction = LeftoverAction.Leave;
                    prof.LeftoverActionTime = LeftoverActionTime.AtEnd;
                    prof.PriceMode = PriceMode.Absolute;

                    if (!ts.SendOrder(prof))
                    {
                        Console.WriteLine("Send Order failed : " + prof.RoutingStatus.Message);
                        Dispose();
                    }
                    else
                    {
                        orderKey = prof.SiteOrderKey;
                        Console.WriteLine("Order sent with price = " + prof.LimitPrice);
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: " + e.Error.Message);
                    Dispose();
                }
            }
        }
 /// <summary>
 /// PriceSubscription FieldsUpdated event.
 /// </summary>
 void m_priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
 {
     if (e.Error == null)
     {
         if (e.UpdateType == UpdateType.Snapshot)
         {
             updatePrices(e.Fields);
         }
         else if (e.UpdateType == UpdateType.Update)
         {
             updatePrices(e.Fields);
         }
     }
     else
     {
         Console.WriteLine(String.Format("PriceSubscription FieldsUpdated Error: {0}", e.Error.Message));
     }
 }
Exemple #25
0
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            int RowIndex = ASENameList.IndexOf(e.Fields.Instrument.Name);

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

            double BidPriceDb = BidPrice.ToDouble();
            double AskPriceDb = AskPrice.ToDouble();

            SummaryTable.Rows[RowIndex]["Bid"] = BidPrice.ToDouble();
            SummaryTable.Rows[RowIndex]["Ask"] = AskPrice.ToDouble();

            SummaryTable.Rows[RowIndex]["Mid"] = (SummaryTable.Rows[RowIndex].Field <double>("Bid") + SummaryTable.Rows[RowIndex].Field <double>("Ask")) / 2;

            SummaryTable.Rows[RowIndex]["MidConverted"] = TA.PriceConverters.FromTTAutoSpreader2DB(ttPrice: (decimal)SummaryTable.Rows[RowIndex].Field <double>("Mid"), tickerHead: SummaryTable.Rows[RowIndex].Field <string>("TickerHead"));
            SummaryTable.Rows[RowIndex]["ValidPrice"]   = true;
        }
        void WriteVolume2File(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));

                    sw.WriteLine("{0},{1},{2},{3},{4}", e.Fields.Instrument.Name,
                                 e.Fields.Instrument.Key.MarketKey.ToString(),
                                 e.Fields.Instrument.Product.Type.ToString(),
                                 e.Fields.Instrument.Product.Name.ToString(),
                                 e.Fields[FieldId.TotalTradedQuantity].FormattedValue);

                    sw.Flush();

                    bool IlsDictionaryCompleteQ = TTAPISubs.IlsDictionaryCompleteQ;

                    for (int i = 0; i < ilsUpdateList.Count; i++)
                    {
                        IlsDictionary[e.Fields.Instrument.Key].Update -= ilsUpdateList[i];
                    }


                    IlsDictionary[e.Fields.Instrument.Key].Dispose();
                    IlsDictionary[e.Fields.Instrument.Key] = null;
                    IlsDictionary.Remove(e.Fields.Instrument.Key);

                    if ((IlsDictionary.Count == 0) & IlsDictionaryCompleteQ)
                    {
                        Dispatcher.Current.BeginInvoke(new Action(Dispose));
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
        void WriteVolume2File(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                    
                    sw.WriteLine("{0},{1},{2},{3},{4}", e.Fields.Instrument.Name, 
                        e.Fields.Instrument.Key.MarketKey.ToString(),
                        e.Fields.Instrument.Product.Type.ToString(),
                        e.Fields.Instrument.Product.Name.ToString(),
                        e.Fields[FieldId.TotalTradedQuantity].FormattedValue);

                    sw.Flush();

                    bool IlsDictionaryCompleteQ = TTAPISubs.IlsDictionaryCompleteQ;

                    for (int i = 0; i < ilsUpdateList.Count; i++)
                    {
                        IlsDictionary[e.Fields.Instrument.Key].Update -= ilsUpdateList[i];
                    }

                    
                    IlsDictionary[e.Fields.Instrument.Key].Dispose();
                    IlsDictionary[e.Fields.Instrument.Key] = null;
                    IlsDictionary.Remove(e.Fields.Instrument.Key);

                    if ((IlsDictionary.Count == 0)&IlsDictionaryCompleteQ)
                    {
                        Dispatcher.Current.BeginInvoke(new Action(Dispose));
                    }
                }  
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
        /// <summary>
        /// Event to notify the application there has been a change in the price feed
        /// Here we pull the values and publish them to the GUI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            // Clear out any data in the list boxes
            this.lboAskDepth.Items.Clear();
            this.lboBidDepth.Items.Clear();

            // upper bound of the depth array
            int askDepthLevels = e.Fields.GetLargestCurrentDepthLevel(FieldId.BestAskPrice);

            for (int i = 0; i < askDepthLevels; i++)
            {
                // Get the price and quantity of the iteration
                Price    price = m_priceSubscription.Fields.GetDirectAskPriceField(i).Value;
                Quantity qty   = m_priceSubscription.Fields.GetDirectAskQuantityField(i).Value;

                if (!price.IsValid || !price.IsTradable)
                {
                    Console.WriteLine(String.Format("TT API Invalid Ask Price: {0}", price.ToString()));
                    continue;
                }

                this.lboAskDepth.Items.Add("AskPrice: " + price.ToString() + " | AskQty: " + qty.ToString());
            }

            // upper bound of the depth array
            int bidDepthLevels = e.Fields.GetLargestCurrentDepthLevel(FieldId.BestBidPrice);

            for (int i = 0; i < bidDepthLevels; i++)
            {
                // Get the price and quantity of the iteration
                Price    price = m_priceSubscription.Fields.GetDirectBidPriceField(i).Value;
                Quantity qty   = m_priceSubscription.Fields.GetDirectBidQuantityField(i).Value;

                if (!price.IsValid || !price.IsTradable)
                {
                    Console.WriteLine(String.Format("TT API Invalid Bid Price: {0}", price.ToString()));
                    continue;
                }

                this.lboBidDepth.Items.Add("BidPrice: " + price.ToString() + " | BidQty: " + qty.ToString());
            }
        }
Exemple #29
0
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            dateTimeNow = DateTime.Now;

            if (dateTimeNow > endTime)
            {
                candlestickData           = candleObj.data;
                candlestickData.TableName = "candleStick";
                candlestickData.WriteXml(OutputFolder + "/" + TA.FileNames.candlestick_signal_file, XmlWriteMode.WriteSchema);
                Dispatcher.Current.BeginInvoke(new Action(Dispose));
                return;
            }


            if (e.Error == null)
            {
                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;
                tickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString());

                candleObj.updateValues((bidPrice + askPrice) / 2, dateTimeNow, tickerDB);
            }
        }
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            Price BidPrice = e.Fields.GetDirectBidPriceField().Value;
            Price AskPrice = e.Fields.GetDirectAskPriceField().Value;



            if ((!BidPrice.IsValid) || (!AskPrice.IsValid))
            {
                return;
            }

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

            if (e.Fields.Instrument.Product.FormattedName == "Autospreader")
            {
                TickerDB = e.Fields.Instrument.Name;
            }
            else
            {
                TickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString());
            }

            int RowIndex = PriceTableSymbols.IndexOf(TickerDB);

            double BidPriceDb = BidPrice.ToDouble();
            double AskPriceDb = AskPrice.ToDouble();

            PriceTable.Rows[RowIndex]["BidPrice"]    = BidPriceDb;
            PriceTable.Rows[RowIndex]["AskPrice"]    = AskPriceDb;
            PriceTable.Rows[RowIndex]["BidQ"]        = e.Fields.GetDirectBidQuantityField().Value.ToInt();
            PriceTable.Rows[RowIndex]["AskQ"]        = e.Fields.GetDirectAskQuantityField().Value.ToInt();
            PriceTable.Rows[RowIndex]["ValidPriceQ"] = true;

            PriceTableSymbolsReceived.Add(TickerDB);

            List <string> wuhu = PriceTableSymbols.Except(PriceTableSymbolsReceived).ToList();
        }
        /// <summary>
        /// Event to notify the application there has been a change in the price feed
        /// Here we pull the values and publish them to the GUI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error != null)
            {
                Console.WriteLine(String.Format("TT API FieldsUpdated Error: {0}", e.Error));
                return;
            }

            // Extract the values we want as Typed fields
            this.txtBidPrice.Text = e.Fields.GetDirectBidPriceField().FormattedValue;
            this.txtBidQty.Text = e.Fields.GetDirectBidQuantityField().FormattedValue;
            this.txtAskPrice.Text = e.Fields.GetDirectAskPriceField().FormattedValue;
            this.txtAskQty.Text = e.Fields.GetDirectAskQuantityField().FormattedValue;
            this.txtLastPrice.Text = e.Fields.GetLastTradedPriceField().FormattedValue;
            this.txtLastQty.Text = e.Fields.GetLastTradedQuantityField().FormattedValue;  
        }
Exemple #32
0
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {

            if (e.Error == null)
            {
              
                        int RowIndex = ASENameList.IndexOf(e.Fields.Instrument.Name);

                        MarketPriceTable.Rows[RowIndex]["Bid"] = Convert.ToDecimal(e.Fields.GetDirectBidPriceField().FormattedValue);
                        MarketPriceTable.Rows[RowIndex]["Ask"] = Convert.ToDecimal(e.Fields.GetDirectAskPriceField().FormattedValue);

                        MarketPriceTable.Rows[RowIndex]["Mid"] = (MarketPriceTable.Rows[RowIndex].Field<decimal>("Bid") + MarketPriceTable.Rows[RowIndex].Field<decimal>("Ask")) / 2;

                        MarketPriceTable.Rows[RowIndex]["MidConverted"] = TA.PriceConverters.FromTTAutoSpreader2DB(ttPrice: MarketPriceTable.Rows[RowIndex].Field<decimal>("Mid"), tickerHead: MarketPriceTable.Rows[RowIndex].Field<string>("TickerHead"));

                        double MidPriceConverted = (double)MarketPriceTable.Rows[RowIndex].Field<decimal>("MidConverted");
                        double YesterdayMean = MarketPriceTable.Rows[RowIndex].Field<double>("Mean");
                        double YesterdayStd = MarketPriceTable.Rows[RowIndex].Field<double>("Std");

                        ttapiUtils.AutoSpreader As = AutoSpreaderList[RowIndex];


                        if ((MarketPriceTable.Rows[RowIndex].Field<int>("ExistingPosition")<0) && (MidPriceConverted > YesterdayMean + YesterdayStd))
                        {
                            return;
                        }
                        else if (((MarketPriceTable.Rows[RowIndex].Field<int>("ExistingPosition")<0) && (MidPriceConverted < YesterdayMean + YesterdayStd))||
                                ((MarketPriceTable.Rows[RowIndex].Field<int>("ExistingPosition")>0) && (MidPriceConverted > YesterdayMean - YesterdayStd)))

                        {

                            DataRow[] RowList = MarketPriceTable.Select("TickerHead='" + MarketPriceTable.Rows[RowIndex].Field<string>("TickerHead") + "'");

                            foreach (DataRow Row in RowList)
                            {
                                Row["ExistingPositionTickerHead"] = Row.Field<int>("ExistingPositionTickerHead") - MarketPriceTable.Rows[RowIndex].Field<int>("ExistingPosition");
                            }

                            IFSLogger.Log(MarketPriceTable.Rows[RowIndex].Field<string>("Alias") + " has normalized. Closing position...");

                            ttapiUtils.Trade.SendAutospreaderOrder(instrument: e.Fields.Instrument, instrumentDetails: e.Fields.InstrumentDetails, autoSpreader: As, 
                                qty: -MarketPriceTable.Rows[RowIndex].Field<int>("ExistingPosition"),
                               price: MarketPriceTable.Rows[RowIndex].Field<decimal>("Mid"), orderTag: MarketPriceTable.Rows[RowIndex].Field<string>("Tag"), logger: IFSLogger);

                            MarketPriceTable.Rows[RowIndex]["ExistingPosition"] = 0;
                            
                        }

                        else if (MarketPriceTable.Select("WorkingPosition<>0").Count() >= NumBets)
                            return;

                        else if ((MidPriceConverted > YesterdayMean + YesterdayStd) &&
                                 (MarketPriceTable.Rows[RowIndex].Field<int>("WorkingPosition")==0) &&
                                 (MarketPriceTable.Rows[RowIndex].Field<int>("ExistingPositionTickerHead")>=0))

                        {
                            MarketPriceTable.Rows[RowIndex]["SuggestedPosition"] = -1;
                            MarketPriceTable.Rows[RowIndex]["WorkingPosition"] = -1;

                            IFSLogger.Log(MarketPriceTable.Rows[RowIndex].Field<string>("Alias") + " entering a short position...");


                            ttapiUtils.Trade.SendAutospreaderOrder(instrument: e.Fields.Instrument, instrumentDetails: e.Fields.InstrumentDetails, autoSpreader: As, qty: -1,
                                price: MarketPriceTable.Rows[RowIndex].Field<decimal>("Mid"), orderTag: MarketPriceTable.Rows[RowIndex].Field<string>("Tag"), logger: IFSLogger);

                           
                        }
                        else if ((MidPriceConverted<YesterdayMean-YesterdayStd) && 
                            (MarketPriceTable.Rows[RowIndex].Field<int>("WorkingPosition")==0) &&
                            (MarketPriceTable.Rows[RowIndex].Field<int>("ExistingPositionTickerHead")<=0))
                        {
                            MarketPriceTable.Rows[RowIndex]["SuggestedPosition"] = 1;
                            MarketPriceTable.Rows[RowIndex]["WorkingPosition"] = 1;

                            IFSLogger.Log(MarketPriceTable.Rows[RowIndex].Field<string>("Alias") + " entering a long position...");

                            ttapiUtils.Trade.SendAutospreaderOrder(instrument: e.Fields.Instrument, instrumentDetails: e.Fields.InstrumentDetails, autoSpreader: As, qty: 1,
                                price: MarketPriceTable.Rows[RowIndex].Field<decimal>("Mid"), orderTag: MarketPriceTable.Rows[RowIndex].Field<string>("Tag"), logger: IFSLogger);

                        }
                        else
                        {
                            MarketPriceTable.Rows[RowIndex]["SuggestedPosition"] = 0;
                        }

            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #33
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>
 /// PriceSubscription FieldsUpdated event.
 /// </summary>
 void m_priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
 {
     if (e.Error == null)
     {
         if (e.UpdateType == UpdateType.Snapshot)
         {
             updatePrices(e.Fields);
         }
         else if (e.UpdateType == UpdateType.Update)
         {
             updatePrices(e.Fields);
         }
     }
     else
     {
         Console.WriteLine(String.Format("PriceSubscription FieldsUpdated Error: {0}", e.Error.Message));
     }
 }
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that there is a valid bid
                if (e.Fields.GetBestBidPriceField().HasValidValue)
                {
                    if (m_orderKey == "")
                    {
                        // In this example, the order is submitted to ASE-A.
                        // You should use the order feed that is appropriate for your purposes.
                        AutospreaderSyntheticOrderProfile op = new AutospreaderSyntheticOrderProfile(((AutospreaderInstrument)e.Fields.Instrument).GetValidGateways()[m_ASEGateway], 
                            (AutospreaderInstrument)e.Fields.Instrument);
                        op.BuySell = BuySell.Buy;
                        op.OrderQuantity = Quantity.FromInt(e.Fields.Instrument, 10);
                        op.OrderType = OrderType.Limit;
                        op.LimitPrice = e.Fields.GetBestBidPriceField().Value;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send new order failed.  {0}", op.RoutingStatus.Message);
                        }
                        else
                        {
                            m_orderKey = op.SiteOrderKey;
                            Console.WriteLine("Send new order succeeded.");
                        }
                    }
                    else if (m_ts.Orders.ContainsKey(m_orderKey) &&
                        m_ts.Orders[m_orderKey].LimitPrice != e.Fields.GetBestBidPriceField().Value)
                    {
                        // If there is a working order, reprice it if its price is not the same as the bid
                        AutospreaderSyntheticOrderProfile op = m_ts.Orders[m_orderKey].GetOrderProfile() as AutospreaderSyntheticOrderProfile;
                        op.LimitPrice = e.Fields.GetBestBidPriceField().Value;
                        op.Action = OrderAction.Change;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send change order failed.  {0}", op.RoutingStatus.Message);
                        }
                        else
                        {
                            Console.WriteLine("Send change order succeeded.");
                        }
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            string InstrumentName = e.Fields.Instrument.Name.ToString();

            if (e.Fields.Instrument.Product.FormattedName=="Autospreader")
            {
                TickerDB = e.Fields.Instrument.Name;
            }
            else
            {
                TickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString());
            }

            int RowIndex = PriceTableSymbols.IndexOf(TickerDB);
            

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

            double BidPriceDb = BidPrice.ToDouble();
            double AskPriceDb = AskPrice.ToDouble();

            PriceTable.Rows[RowIndex]["BidPrice"] = BidPriceDb;
            PriceTable.Rows[RowIndex]["AskPrice"] = AskPriceDb;

            PriceTableSymbolsReceived.Add(TickerDB);

           if (PriceTableSymbols.Except(PriceTableSymbolsReceived).ToList().Count==0)
           {
               ButterfliesStopSheet = CalculateStrategyPnls(StrategyTableInput: ButterfliesStopSheet);
               DataRow[] Ready2CloseRows = ButterfliesStopSheet.Select("PnlMid>0");

               if (Ready2CloseRows.Count()==0)
               {
                   ButterflyLogger.Log("No trades to close");
               }

               if (e.Fields.Instrument.Product.FormattedName == "Autospreader")
               {
                   string emre = "merve";
               }


              
           }
            
        }
 /// <summary>
 /// Event where the price subscription fields have been updated.  Assign
 /// the updates values to the GUI.
 /// </summary>
 void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
 {
     this.BidPrice = e.Fields.GetDirectBidPriceField().FormattedValue;
     this.AskPrice = e.Fields.GetDirectAskPriceField().FormattedValue;
     this.LastPrice = e.Fields.GetLastTradedPriceField().FormattedValue;
 }
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            dateTimeNow = DateTime.Now;

            if (dateTimeNow>endTime)
            {
                candlestickData = candleObj.data;
                candlestickData.TableName = "candleStick";
                candlestickData.WriteXml(OutputFolder + "/" + TA.FileNames.candlestick_signal_file, XmlWriteMode.WriteSchema);
                Dispatcher.Current.BeginInvoke(new Action(Dispose));
                return;
            }


            if (e.Error == null)
            {

                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;
                tickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(e.Fields.Instrument.Product.ToString(), e.Fields.Instrument.Name.ToString());

                candleObj.updateValues((bidPrice + askPrice) / 2, dateTimeNow, tickerDB);
            }     
        }
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot

                    Console.WriteLine("Ask Depth Snapshot");
                    int askDepthLevels = e.Fields.GetLargestCurrentDepthLevel(FieldId.BestAskPrice);
                    for (int i = 0; i < askDepthLevels; i++)
                    {
                        Console.WriteLine("    Level={0} Qty={1} Price={2}", i, e.Fields.GetBestAskQuantityField(i).Value.ToInt(),
                            e.Fields.GetBestAskPriceField(i).Value.ToString());
                    }

                    Console.WriteLine("Bid Depth Snapshot");
                    int bidDepthLevels = e.Fields.GetLargestCurrentDepthLevel(FieldId.BestBidPrice);
                    for (int i = 0; i < bidDepthLevels; i++)
                    {
                        Console.WriteLine("    Level={0} Qty={1} Price={2}", i, e.Fields.GetBestBidQuantityField(i).Value.ToInt(),
                            e.Fields.GetBestBidPriceField(i).Value.ToString());
                    }
                }
                else
                {
                    // Only some fields have changed

                    Console.WriteLine("Depth Updates");
                    int depthLevels = e.Fields.GetLargestCurrentDepthLevel();
                    for (int i = 0; i < depthLevels; i++)
                    {
                        if (e.Fields.GetChangedFieldIds(i).Length > 0)
                        {
                            Console.WriteLine("Level={0}", i);
                            foreach (FieldId id in e.Fields.GetChangedFieldIds(i))
                            {
                                Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id,i].FormattedValue);
                            }
                        }
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
 /// <summary>
 /// Event to notify the application there has been a change in the price feed
 /// Here we pull the values and publish them to the GUI
 /// </summary>
 void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
 {
     m_bindingModels[e.Fields.Instrument.Key].BidPrice = e.Fields.GetDirectBidPriceField().FormattedValue;
     m_bindingModels[e.Fields.Instrument.Key].AskPrice = e.Fields.GetDirectAskPriceField().FormattedValue;
     m_bindingModels[e.Fields.Instrument.Key].LastPrice = e.Fields.GetLastTradedPriceField().FormattedValue;
 }
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that there is a valid bid
                if (e.Fields.GetBestBidPriceField().HasValidValue)
                {
                    if (m_orderKey == "")
                    {
                        // If there is no order working, submit one through the first valid order feed.
                        // You should use the order feed that is valid for your purposes.
                        OrderProfile op = new OrderProfile(e.Fields.Instrument.GetValidOrderFeeds()[0], e.Fields.Instrument);
                        op.BuySell = BuySell.Buy;
                        op.AccountName = "12345678";
                        op.AccountType = AccountType.A1;
                        op.OrderQuantity = Quantity.FromInt(e.Fields.Instrument, 10);
                        op.OrderType = OrderType.Limit;
                        op.LimitPrice = e.Fields.GetBestBidPriceField().Value;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send new order failed.  {0}", op.RoutingStatus.Message);
                            Dispose();
                        }
                        else
                        {
                            m_orderKey = op.SiteOrderKey;
                            Console.WriteLine("Send new order succeeded.");
                        }
                    }
                    else if(m_ts.Orders.ContainsKey(m_orderKey) && 
                        m_ts.Orders[m_orderKey].LimitPrice != e.Fields.GetBestBidPriceField().Value)
                    {
                        // If there is a working order, reprice it if its price is not the same as the bid
                        OrderProfileBase op = m_ts.Orders[m_orderKey].GetOrderProfile();
                        op.LimitPrice = e.Fields.GetBestBidPriceField().Value;
                        op.Action = OrderAction.Change;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send change order failed.  {0}", op.RoutingStatus.Message);
                        }
                        else
                        {
                            Console.WriteLine("Send change order succeeded.");
                        }
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
 /// <summary>
 /// Event to notify the application there has been a change in the price feed
 /// Here we pull the values and publish them to the GUI
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e">Struct containing data pertaining to the event</param>
 void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
 {
     // Extract the values we want as Typed fields
     this.txtBidPrice.Text = e.Fields.GetDirectBidPriceField().FormattedValue;
     this.txtBidQty.Text = e.Fields.GetDirectBidQuantityField().FormattedValue;
     this.txtAskPrice.Text = e.Fields.GetDirectAskPriceField().FormattedValue;
     this.txtAskQty.Text = e.Fields.GetDirectAskQuantityField().FormattedValue;
     this.txtLastPrice.Text = e.Fields.GetLastTradedPriceField().FormattedValue;
     this.txtLastQty.Text = e.Fields.GetLastTradedQuantityField().FormattedValue;
 }
Exemple #43
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>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot
                    Console.WriteLine("Market Data Snapshot:");

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

                    Console.WriteLine(BidPrice.ToDouble());
                    Console.WriteLine(AskPrice.ToDouble());

                    Price MidPrice = (BidPrice + AskPrice) / 2;
                    MidPrice = MidPrice.Round(Rounding.Down);

                    Console.WriteLine(MidPrice.ToDouble());

                    foreach (FieldId id in e.Fields.GetFieldIds())
                    {
                        Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id].FormattedValue);
                    }
                    //Dispose();
                    Dispatcher.Current.BeginInvoke(new Action(Dispose));
                }
                else
                {
                    // Only some fields have changed
                    Console.WriteLine("Market Data Update:");

                    foreach (FieldId id in e.Fields.GetChangedFieldIds())
                    {
                        Console.WriteLine("    {0} : {1}", id.ToString(), e.Fields[id].FormattedValue);
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
        /// <summary>
        /// Event to notify the application there has been a change in the price feed
        /// Here we pull the values and publish them to the GUI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            // Clear out any data in the list boxes
            this.lboAskDepth.Items.Clear();
            this.lboBidDepth.Items.Clear();
            
            // upper bound of the depth array
            int askDepthLevels = e.Fields.GetLargestCurrentDepthLevel(FieldId.BestAskPrice);
            for (int i = 0; i < askDepthLevels; i++)
            {
                // Get the price and quantity of the iteration
                Price price = m_priceSubscription.Fields.GetDirectAskPriceField(i).Value;
                Quantity qty = m_priceSubscription.Fields.GetDirectAskQuantityField(i).Value;

                if (!price.IsValid || !price.IsTradable)
                {
                    Console.WriteLine(String.Format("TT API Invalid Ask Price: {0}", price.ToString()));
                    continue;
                }

                this.lboAskDepth.Items.Add("AskPrice: " + price.ToString() + " | AskQty: " + qty.ToString());
            }

            // upper bound of the depth array
            int bidDepthLevels = e.Fields.GetLargestCurrentDepthLevel(FieldId.BestBidPrice);
            for (int i = 0; i < bidDepthLevels; i++)
            {
                // Get the price and quantity of the iteration
                Price price = m_priceSubscription.Fields.GetDirectBidPriceField(i).Value;
                Quantity qty = m_priceSubscription.Fields.GetDirectBidQuantityField(i).Value;

                if (!price.IsValid || !price.IsTradable)
                {
                    Console.WriteLine(String.Format("TT API Invalid Bid Price: {0}", price.ToString()));
                    continue;
                }

                this.lboBidDepth.Items.Add("BidPrice: " + price.ToString() + " | BidQty: " + qty.ToString());
            }
        }
Exemple #46
0
        void priceSub_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // A full snapshot update occurs when the TTAPI loses and restores its connection
                // with a TT Gateway or associated Exchange.
                // If you modify the ProductSubscription.Settings property, the TTAPI automatically
                // stops and restarts the subscription with the new settings. The TTAPI does not deliver
                // updates during the restart process.

                /*
                 * if (e.UpdateType == UpdateType.Snapshot)
                 *  ;
                 * else
                 *  e.UpdateType == UpdateType.Update;
                 */

                InstrumentKey key = e.Fields.Instrument.Key;
                TTInstrument  tti = _ttInstruments[key];
                tti.Bid              = e.Fields.GetDirectBidPriceField().Value;
                tti.BidQty           = e.Fields.GetDirectBidQuantityField().Value;
                tti.Ask              = e.Fields.GetDirectAskPriceField().Value;
                tti.AskQty           = e.Fields.GetDirectAskQuantityField().Value;
                tti.Last             = e.Fields.GetLastTradedPriceField().Value;
                tti.LastQty          = e.Fields.GetLastTradedQuantityField().Value;
                tti.Open             = e.Fields.GetOpenPriceField().Value;
                tti.High             = e.Fields.GetHighPriceField().Value;
                tti.Low              = e.Fields.GetLowPriceField().Value;
                tti.Close            = e.Fields.GetClosePriceField().Value;
                tti.NetChange        = e.Fields.GetNetChangeField().Value;
                tti.NetChangePercent = e.Fields.GetNetChangePercentField().Value;
                tti.Volume           = e.Fields.GetTotalTradedQuantityField().Value;

                if (OnInsideMarketUpdate != null)
                {
                    OnInsideMarketUpdate(tti);
                }

                if (SubscribeMarketDepth == true)
                {
                    if (tti.MarketDepth == null)
                    {
                        int maxDepthCount = e.Fields.GetLargestCurrentDepthLevel();

                        tti.MarketDepth = new TTMarketDepth(maxDepthCount);
                    }

                    for (int i = 0; i < tti.MarketDepth.DepthCount; i++)
                    {
                        tti.MarketDepth[i].Bid    = e.Fields.GetDirectBidPriceField(i).Value;
                        tti.MarketDepth[i].BidQty = e.Fields.GetDirectBidQuantityField(i).Value;
                        tti.MarketDepth[i].Ask    = e.Fields.GetDirectAskPriceField(i).Value;
                        tti.MarketDepth[i].AskQty = e.Fields.GetDirectAskQuantityField(i).Value;
                    }

                    if (OnMarketDepthUpdate != null)
                    {
                        OnMarketDepthUpdate(_ttInstruments[key], tti.MarketDepth);
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    if (OnSystemMessage != null)
                    {
                        OnSystemMessage(SystemMessage.UNRECOVERABLE_PRICE_ERROR);
                    }
                }
            }
        }
        /// <summary>
        /// Event notification for price update
        /// </summary>
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that there is a valid bid
                if (e.Fields.GetBestBidPriceField().HasValidValue)
                {
                    if (m_orderKey == "")
                    {
                        // If there is no order working, submit one through the first valid order feed.
                        // You should use the order feed that is valid for your purposes.
                        OrderProfile op = new OrderProfile(e.Fields.Instrument.GetValidOrderFeeds()[0], e.Fields.Instrument);
                        op.BuySell = BuySell.Buy;
                        op.AccountName = "12345678";
                        op.AccountType = AccountType.A1;
                        op.OrderQuantity = Quantity.FromInt(e.Fields.Instrument, 100);
                        op.OrderType = OrderType.Limit;
                        op.LimitPrice = e.Fields.GetBestBidPriceField().Value;

                        op.SlicerType = SlicerType.TimeSliced;
                        op.DisclosedQuantity = Quantity.FromInt(e.Fields.Instrument, 10);
                        op.DisclosedQuantityMode = QuantityMode.Quantity;
                        op.InterSliceDelay = 10;
                        op.InterSliceDelayTimeUnits = TimeUnits.Sec;
                        op.LeftoverAction = LeftoverAction.Leave;
                        op.LeftoverActionTime = LeftoverActionTime.AtEnd;
                        op.PriceMode = PriceMode.Absolute;

                        if (!m_ts.SendOrder(op))
                        {
                            Console.WriteLine("Send new order failed.  {0}", op.RoutingStatus.Message);
                            Dispose();
                        }
                        else
                        {
                            m_orderKey = op.SiteOrderKey;
                            Console.WriteLine("Send new order succeeded.");
                        }
                    }
                }
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
        /// <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 #49
0
 /// <summary>
 /// Event where the price subscription fields have been updated.  Assign
 /// the updates values to the GUI.
 /// </summary>
 void priceSubscription_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
 {
     this.BidPrice  = e.Fields.GetDirectBidPriceField().FormattedValue;
     this.AskPrice  = e.Fields.GetDirectAskPriceField().FormattedValue;
     this.LastPrice = e.Fields.GetLastTradedPriceField().FormattedValue;
 }
Exemple #50
0
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error != null)
            {
                Console.WriteLine(String.Format("TT API FieldsUpdated Error: {0}", e.Error));
                return;
            }

            // Extract the values we want as Typed fields

            bidPrice = Convert.ToDouble(e.Fields.GetDirectBidPriceField().FormattedValue);
            askPrice = Convert.ToDouble(e.Fields.GetDirectAskPriceField().FormattedValue);

            midPrice = (bidPrice + askPrice) / 2;
            tickerHeadDB = TA.TickerheadConverters.ConvertFromTT2DB(e.Fields.Instrument.Product.ToString());

            this.Controls.Find(bidPriceFields[tickerHeadDB], true)[0].Text = 
                e.Fields.GetDirectBidPriceField().FormattedValue;
            this.Controls.Find(askPriceFields[tickerHeadDB], true)[0].Text =
                e.Fields.GetDirectAskPriceField().FormattedValue;
                
            int hourMinute = 100 * DateTime.Now.Hour + DateTime.Now.Minute;

            int timeIndex = Enumerable.Range(0, candleStartTimeList.Length).Where(i => candleStartTimeList[i] > hourMinute).ToList()[0];

            double highPrice = (double)candlestickData.Rows[timeIndex][tickerHeadDB + "_high"];
            double lowPrice = (double)candlestickData.Rows[timeIndex][tickerHeadDB + "_low"];

            
            candlestickData.Rows[timeIndex][tickerHeadDB + "_low"] = midPrice;

            if ((Double.IsNaN(highPrice)) || (midPrice>highPrice))
            {
                candlestickData.Rows[timeIndex][tickerHeadDB + "_high"] = midPrice;
            }

            if ((Double.IsNaN(lowPrice)) || (midPrice < lowPrice))
            {
                candlestickData.Rows[timeIndex][tickerHeadDB + "_low"] = midPrice;
            }

            this.Controls.Find(lowPriceFields[tickerHeadDB], true)[0].Text =
                candlestickData.Rows[timeIndex][tickerHeadDB + "_low"].ToString();
            this.Controls.Find(highPriceFields[tickerHeadDB], true)[0].Text =
                candlestickData.Rows[timeIndex][tickerHeadDB + "_high"].ToString();
  
        }
        void m_ps_FieldsUpdated(object sender, FieldsUpdatedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.UpdateType == UpdateType.Snapshot)
                {
                    // Received a market data snapshot
                    Console.WriteLine(DateTime.Now.ToString("h:mm:ss tt"));
                    
                    sw.WriteLine("{0},{1},{2},{3},{4},{5}", e.Fields.Instrument.Name, 
                        e.Fields.Instrument.Key.MarketKey.ToString(),
                        e.Fields.Instrument.Product.Type.ToString(),
                        e.Fields.Instrument.Product.Name.ToString(),
                        e.Fields.Instrument.Name.ToString(),
                        e.Fields[FieldId.TotalTradedQuantity].FormattedValue);

                
                        

                }  
            }
            else
            {
                if (e.Error.IsRecoverableError == false)
                {
                    Console.WriteLine("Unrecoverable price subscription error: {0}", e.Error.Message);
                    Dispose();
                }
            }
        }
Exemple #52
0
        //
        //
        //
        // ****             PriceSubscription_Updated()                 ****
        //
        private void PriceSubscription_Updated(object sender, FieldsUpdatedEventArgs eventArgs)
        {
            if (m_isDisposing)
            {
                return;
            }
            bool isSnapShot = (eventArgs.UpdateType == UpdateType.Snapshot);

            if (eventArgs.Error == null)
            {
                // Analyze
                FieldId[] changedFieldIds = eventArgs.Fields.GetChangedFieldIds();
                if (changedFieldIds.Length > 0)
                {
                    InstrumentKey            key = eventArgs.Fields.Instrument.Key;
                    MistyProd.InstrumentName instrKey;
                    if (m_KeyToInstruments.TryGetValue(key, out instrKey))
                    {
                        m_NewEvents.Clear();
                        // Bid side
                        if (isSnapShot || changedFieldIds.Contains <FieldId>(FieldId.BestBidPrice) || changedFieldIds.Contains <FieldId>(FieldId.BestBidQuantity))
                        {
                            Price    p = (Price)eventArgs.Fields.GetField(FieldId.BestBidPrice).Value;
                            Quantity q = (Quantity)eventArgs.Fields.GetField(FieldId.BestBidQuantity).Value;
                            if (p.IsValid && q.IsValid)
                            {
                                int qty = q.ToInt();
                                if (qty > 0)
                                {
                                    Misty.Lib.BookHubs.MarketUpdateEventArgs e = new Misty.Lib.BookHubs.MarketUpdateEventArgs();
                                    //e.Instrument = instrument;
                                    e.Name  = instrKey;
                                    e.Price = p.ToDouble();
                                    e.Qty   = q.ToInt();
                                    e.Side  = QTMath.BidSide;
                                    m_NewEvents.Add(e);
                                }
                            }
                        }
                        // Ask side
                        if (isSnapShot || changedFieldIds.Contains <FieldId>(FieldId.BestAskPrice) || changedFieldIds.Contains <FieldId>(FieldId.BestAskQuantity))
                        {
                            Price    p = (Price)eventArgs.Fields.GetField(FieldId.BestAskPrice).Value;
                            Quantity q = (Quantity)eventArgs.Fields.GetField(FieldId.BestAskQuantity).Value;
                            if (p.IsValid && q.IsValid)
                            {
                                int qty = q.ToInt();
                                if (qty > 0)
                                {
                                    Misty.Lib.BookHubs.MarketUpdateEventArgs e = new Misty.Lib.BookHubs.MarketUpdateEventArgs();
                                    //e.Instrument = instrument;
                                    e.Name  = instrKey;
                                    e.Price = p.ToDouble();
                                    e.Qty   = q.ToInt();
                                    e.Side  = QTMath.AskSide;
                                    m_NewEvents.Add(e);
                                }
                            }
                        }
                        // Last
                        if (isSnapShot || changedFieldIds.Contains <FieldId>(FieldId.LastTradedPrice) || changedFieldIds.Contains <FieldId>(FieldId.LastTradedQuantity))
                        {
                            Price    p = (Price)eventArgs.Fields.GetField(FieldId.LastTradedPrice).Value;
                            Quantity q = (Quantity)eventArgs.Fields.GetField(FieldId.LastTradedQuantity).Value;
                            if (p == 0)
                            {
                                //int nn = 0;
                            }
                            if (p.IsValid && q.IsValid)
                            {
                                int qty = q.ToInt();
                                if (qty > 0)
                                {
                                    Misty.Lib.BookHubs.MarketUpdateEventArgs e = new Misty.Lib.BookHubs.MarketUpdateEventArgs();
                                    //e.Instrument = instrument;
                                    e.Name  = instrKey;
                                    e.Price = p.ToDouble();
                                    e.Qty   = q.ToInt();
                                    e.Side  = QTMath.LastSide;
                                    m_NewEvents.Add(e);
                                }
                            }
                        }
                        // Total Volume

                        /*
                         * if (isSnapShot || changedFieldIds.Contains<FieldId>(FieldId.TotalTradedQuantity))
                         * {
                         *  object f = eventArgs.Fields.GetField(FieldId.TotalTradedQuantity).Value;
                         *  Quantity q = (Quantity)eventArgs.Fields.GetField(FieldId.LastTradedQuantity).Value;
                         *  if (q.IsValid)
                         *  {
                         *      Misty.Lib.BookHubs.MarketUpdateEventArgs e = new Misty.Lib.BookHubs.MarketUpdateEventArgs();
                         *      e.Instrument = instrument;
                         *      e.Qty = q.ToInt();
                         *      //e.Side = QTMath.LastSide;
                         *      //m_NewEvents.Add(e);
                         *  }
                         * }
                         * if (isSnapShot || changedFieldIds.Contains<FieldId>(FieldId.HighPrice))
                         * {
                         *  object f = eventArgs.Fields.GetField(FieldId.HighPrice).Value;
                         * }
                         * if (isSnapShot || changedFieldIds.Contains<FieldId>(FieldId.LowPrice))
                         * {
                         *  object f = eventArgs.Fields.GetField(FieldId.LowPrice).Value;
                         * }
                         */
                        /*
                         * if (changedFieldIds.Contains<FieldId>(FieldId.OpenPrice))
                         * {
                         *  object f = eventArgs.Fields.GetField(FieldId.OpenPrice).Value;
                         * }
                         * if (isSnapShot || changedFieldIds.Contains<FieldId>(FieldId.SettlementPrice))
                         * {
                         *  object f = eventArgs.Fields.GetField(FieldId.SettlementPrice).Value;
                         * }
                         */
                        // Series Status
                        if (changedFieldIds.Contains <FieldId>(FieldId.SeriesStatus))
                        {
                            TradingStatus status = (TradingStatus)eventArgs.Fields.GetField(FieldId.SeriesStatus).Value;
                            Log.NewEntry(LogLevel.Minor, "PriceListener: SeriesStatus change {0} is {1}.", instrKey, status.ToString());
                            Misty.Lib.BookHubs.MarketStatusEventArgs e = new Misty.Lib.BookHubs.MarketStatusEventArgs();
                            //e.Instrument = instrument;
                            e.InstrumentName = instrKey;
                            if (status == TradingStatus.Trading)
                            {
                                e.Status = Misty.Lib.BookHubs.MarketStatus.Trading;
                            }
                            else if (status == TradingStatus.Closed || status == TradingStatus.ClosingAuction || status == TradingStatus.Expired ||
                                     status == TradingStatus.NotTradable || status == TradingStatus.PostTrading)
                            {
                                e.Status = Misty.Lib.BookHubs.MarketStatus.NotTrading;
                            }
                            else
                            {
                                e.Status = Misty.Lib.BookHubs.MarketStatus.Special;
                            }
                            m_NewEvents.Add(e);
                        }
                        // Session rollover
                        if (changedFieldIds.Contains <FieldId>(FieldId.SessionRollover))
                        {
                            TradingStatus status = (TradingStatus)eventArgs.Fields.GetField(FieldId.SeriesStatus).Value;
                            Log.NewEntry(LogLevel.Minor, "PriceListener: SessionRollover change {0} is {1}.", instrKey, status.ToString());
                            Misty.Lib.BookHubs.MarketStatusEventArgs e = new Misty.Lib.BookHubs.MarketStatusEventArgs();
                            //e.Instrument = instrument;
                            e.InstrumentName = instrKey;
                            if (status == TradingStatus.Trading)
                            {
                                e.Status = Misty.Lib.BookHubs.MarketStatus.Trading;
                            }
                            else if (status == TradingStatus.Closed || status == TradingStatus.ClosingAuction || status == TradingStatus.Expired ||
                                     status == TradingStatus.NotTradable || status == TradingStatus.PostTrading)
                            {
                                e.Status = Misty.Lib.BookHubs.MarketStatus.NotTrading;
                            }
                            else
                            {
                                e.Status = Misty.Lib.BookHubs.MarketStatus.Special;
                            }
                            m_NewEvents.Add(e);
                        }

                        //
                        // Fire events
                        //
                        ProcessPriceChangeEvents(ref m_NewEvents);
                    }// if instrument not found for ttKey.
                    else
                    {
                        Log.NewEntry(LogLevel.Warning, "{0}: Failed to find instrument for TTKey {1}.", this.Name, key);
                    }
                }
            }
            else
            {
                Log.NewEntry(LogLevel.Warning, "{0}: Error in price subscription {1}.", this.Name, eventArgs.Error.Message);
            }
        }//PriceSubscription()