Esempio n. 1
0
        void CreateAutoSpreader(object sender, InstrumentLookupSubscriptionEventArgs e)
        {
            if (e.Instrument != null && e.Error == null)
            {
                // Instrument was found
                Console.WriteLine("Found: {0}", e.Instrument.Name);

                InstrumentDictionary.Add(e.Instrument.Key, e.Instrument);

                // Update the dictionary to indicate that the instrument was found.
                InstrumentLookupSubscription instrLookupSub = sender as InstrumentLookupSubscription;

                if (SpreadLegKeys.ContainsKey((int)instrLookupSub.Tag))
                {
                    SpreadLegKeys[(int)instrLookupSub.Tag] = e.Instrument;
                }
            }
            else if (e.IsFinal)
            {
                // Instrument was not found and TT API has given up looking for it
                Console.WriteLine("Cannot find instrument: {0}", e.Error.Message);
                Subs.Dispose();
            }

            // If we have found all of the leg instruments, proceed with the creation of the spread.
            if (HaveWeFoundAllLegs())
            {
                Console.WriteLine("All leg instruments have been found.  Creating the spread...");

                // SpreadDetails related properties
                SpreadDetails spreadDetails = new SpreadDetails();
                spreadDetails.Name = AutoSpreaderName;

                for (int i = 0; i < DbTickerList.Count; i++)
                {
                    Instrument instrument = SpreadLegKeys[i + 1];

                    var ValidOrderFeeds = instrument.GetValidOrderFeeds();

                    while (ValidOrderFeeds.Count == 0)
                    {
                        ValidOrderFeeds = instrument.GetValidOrderFeeds();
                        Console.WriteLine("Attempting to get valid forder feed for: " + DbTickerList[i]);
                    }

                    SpreadLegDetails spreadlegDetails = new SpreadLegDetails(instrument, ValidOrderFeeds[0].ConnectionKey);
                    spreadlegDetails.SpreadRatio     = (int)RatioAndMultiplier["Ratio"][i];
                    spreadlegDetails.PriceMultiplier = RatioAndMultiplier["Multiplier"][i];
                    spreadlegDetails.CustomerName    = "<DEFAULT>";
                    spreadlegDetails.PayupTicks      = PayUpTicks;
                    spreadDetails.Legs.Append(spreadlegDetails);
                }

                // Create an AutospreaderInstrument corresponding to the synthetic spread
                Air            = new CreateAutospreaderInstrumentRequest(m_apiInstance.Session, Dispatcher.Current, spreadDetails);
                Air.Completed += new EventHandler <CreateAutospreaderInstrumentRequestEventArgs>(m_casReq_Completed);
                Air.Submit();
            }
        }
Esempio n. 2
0
        public static string SendLimitOrder(TradingTechnologies.TTAPI.Instrument instrument,
                                            TradingTechnologies.TTAPI.Price price, int qty, Subscription ttapisubs, string orderTag = "")

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

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

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

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

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

            AccountType AccType = AccountType.P2;

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

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

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

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

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


            op.LimitPrice = price;

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

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

            return(op.SiteOrderKey);
        }
Esempio n. 3
0
        public static void SendLimitOrder(TradingTechnologies.TTAPI.Instrument instrument,
            TradingTechnologies.TTAPI.Price price, int qty, Subscription ttapisubs, string orderTag="")

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

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

            string tickerDB = TA.TickerConverters.ConvertFromTTAPIFields2DB(instrument.Product.ToString(), instrument.Name.ToString());
            string[] TickerList = tickerDB.Split('-');

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

            AccountType AccType = AccountType.P2;

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

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

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

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


            op.LimitPrice = price;

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

            if (!TS.SendOrder(op))
            {
                Console.WriteLine("Send new order failed.  {0}", op.RoutingStatus.Message);
                ttapisubs.Dispose();
            }
            else
            {
                Console.WriteLine("Send new order succeeded.");
            }
        }
Esempio n. 4
0
 public void Dispose()
 {
     TTAPISubs.Dispose();
 }
Esempio n. 5
0
 /// <summary>
 /// Shuts down the TT API
 /// </summary>
 public void Dispose()
 {
     ttapiSubs.Dispose();
 }
Esempio n. 6
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();
                }
            }
        }