public FuturesButterflyTTAPI(string u, string p)
        {
            m_username = u;
            m_password = p;

            mysql connection = new mysql();

            conn = connection.conn;

            string       OutputFolder = TA.DirectoryNames.GetDirectoryName("daily");
            StreamWriter LogFile      = new StreamWriter(OutputFolder + "/FuturesButterfly.txt", true);

            ButterflyLogger = new Logger(LogFile);

            AutoSpreaderList             = new List <ttapiUtils.AutoSpreader>();
            AutoSpreaderDictionary       = new Dictionary <string, ttapiUtils.AutoSpreader>();
            Alias2AutoSpreaderDictionary = new Dictionary <string, string>();
            TagDictionary = new Dictionary <string, string>();
            LogTime1      = DateTime.MinValue;

            PriceTableSymbolsReceived  = new List <string>();
            StrategyPositionDictionary = new Dictionary <string, DataTable>();

            TTAPISubs  = new ttapiUtils.Subscription(m_username, m_password);
            SpreadList = new List <string>();

            DateTime ReportDate = CalendarUtilities.BusinessDays.GetBusinessDayShifted(shiftInDays: -1);
            DateTime TodayDate  = DateTime.Now.Date;



            ButterflyLogger.SW.WriteLine();
            ButterflyLogger.Log("NOTES FOR " + TodayDate.ToString("MM/dd/yyyy"));
            ButterflyLogger.Log(new String('-', 20));

            string DirectoryName = TA.DirectoryNames.GetDirectoryName(ext: "ta");
            string ButterflyOutputDirectoryName = TA.DirectoryNames.GetDirectoryName(ext: "futuresButterflyOutput");
            string DirectoryExtension           = TA.DirectoryNames.GetDirectoryExtension(directoryDate: ReportDate);

            DataSet   FollowupOutput           = IOUtilities.ExcelDataReader.LoadFile(DirectoryName + "/" + DirectoryExtension + "/followup.xlsx");
            DataTable ButterfliesFollowupSheet = FollowupOutput.Tables["butterflies"];

            DataSet   ButterfliesOutput = IOUtilities.ExcelDataReader.LoadFile(ButterflyOutputDirectoryName + "/" + DirectoryExtension + "/butterflies.xlsx");
            DataTable ButterfliesSheet  = ButterfliesOutput.Tables["good"];

            PeriodicTimer          = new System.Timers.Timer();
            PeriodicTimer.Elapsed += new ElapsedEventHandler(PeriodicCall);
            PeriodicTimer.Interval = 30000;
            // And start it
            PeriodicTimer.Enabled = true;



            DataColumn SizeColumn = new DataColumn("Size", typeof(double));

            SizeColumn.DefaultValue = 0;
            ButterfliesSheet.Columns.Add(SizeColumn);

            ButterfliesSheet.Columns.Add("Theme", typeof(string));

            DataColumn ExistingThemePositionColumn = new DataColumn("ExistingThemePosition", typeof(double));

            ExistingThemePositionColumn.DefaultValue = 0;
            ButterfliesSheet.Columns.Add(ExistingThemePositionColumn);

            ButterfliesSheet.Columns.Add("SlackFromTheme", typeof(double));



            for (int i = 0; i < ButterfliesFollowupSheet.Rows.Count; i++)
            {
                StrategyUtilities.PositionManagerOutput PositionManagerOut = PositionManager.GetFuturesButterflyPosition(alias: ButterfliesFollowupSheet.Rows[i].Field <string>("Alias"),
                                                                                                                         asOfDate: TodayDate, conn: conn);
                if (PositionManagerOut.CorrectPositionQ)
                {
                    StrategyPositionDictionary.Add(ButterfliesFollowupSheet.Rows[i].Field <string>("Alias"), PositionManagerOut.SortedPosition);
                }
            }


            DataTable ButterfliesFollowupSheetAdjusted = RiskManager.CalculateAdjustedDownside(dataTableInput: ButterfliesFollowupSheet, newTradesTable: ButterfliesSheet,
                                                                                               strategyPositionDictionary: StrategyPositionDictionary);

            DataTable RiskAcrossTickerhead = RiskManager.AggregateRiskAcrossTickerHead(dataTableInput: ButterfliesFollowupSheetAdjusted);

            Dictionary <string, double> RiskAcrossTheme = RiskManager.GetRiskAcrossTheme(dataTableInput: ButterfliesFollowupSheetAdjusted,
                                                                                         strategyPositionDictionary: StrategyPositionDictionary);



            ButterfliesSheetFiltered = Filtering.GetFilteredNewTrades(butterfliesSheet: ButterfliesSheet, riskAcrossTickerhead: RiskAcrossTickerhead, riskAcrossTheme: RiskAcrossTheme);

            DataColumn ButterflyQuantityColumn = new DataColumn("ButterflyQuantity", typeof(int));

            ButterflyQuantityColumn.DefaultValue = 0;
            ButterfliesSheetFiltered.Columns.Add(ButterflyQuantityColumn);

            DataColumn Spread1QuantityColumn = new DataColumn("Spread1Quantity", typeof(int));

            Spread1QuantityColumn.DefaultValue = 0;
            ButterfliesSheetFiltered.Columns.Add(Spread1QuantityColumn);

            DataColumn Spread2QuantityColumn = new DataColumn("Spread2Quantity", typeof(int));

            Spread2QuantityColumn.DefaultValue = 0;
            ButterfliesSheetFiltered.Columns.Add(Spread2QuantityColumn);

            ButterfliesSheetFiltered.Columns.Add("Alias", typeof(string));

            PriceTable = new DataTable();
            PriceTable.Columns.Add("Ticker", typeof(string));
            PriceTable.Columns.Add("TickerHead", typeof(string));
            PriceTable.Columns.Add("IsAutoSpreaderQ", typeof(bool));

            DataColumn BidPriceColumn = new DataColumn("BidPrice", typeof(double));

            BidPriceColumn.DefaultValue = Double.NaN;
            PriceTable.Columns.Add(BidPriceColumn);

            DataColumn AskPriceColumn = new DataColumn("AskPrice", typeof(double));

            AskPriceColumn.DefaultValue = Double.NaN;
            PriceTable.Columns.Add(AskPriceColumn);

            PriceTable.Columns.Add("BidQ", typeof(int));
            PriceTable.Columns.Add("AskQ", typeof(int));



            DataColumn ValidPriceColumn = new DataColumn("ValidPriceQ", typeof(bool));

            ValidPriceColumn.DefaultValue = false;
            PriceTable.Columns.Add(ValidPriceColumn);

            for (int i = 0; i < ButterfliesSheetFiltered.Rows.Count; i++)
            {
                DataRow SelectedRow = ButterfliesSheetFiltered.Rows[i];
                string  Alias       = "";
                string  Ticker1     = SelectedRow.Field <string>("ticker1");
                string  Ticker2     = SelectedRow.Field <string>("ticker2");
                string  Ticker3     = SelectedRow.Field <string>("ticker3");


                if (SelectedRow.Field <double>("z1") < 0)
                {
                    double FirstSpreadQuantity  = Math.Round(SelectedRow.Field <double>("Size") / Math.Abs(SelectedRow.Field <double>("Downside")));
                    double SecondSpreadQuantity = Math.Round(FirstSpreadQuantity * SelectedRow.Field <double>("second_spread_weight_1"));

                    if (FirstSpreadQuantity < SecondSpreadQuantity)
                    {
                        SelectedRow["ButterflyQuantity"] = (int)FirstSpreadQuantity;
                        SelectedRow["Spread2Quantity"]   = -(int)(SecondSpreadQuantity - FirstSpreadQuantity);
                    }
                    else if (FirstSpreadQuantity > SecondSpreadQuantity)
                    {
                        SelectedRow["ButterflyQuantity"] = (int)SecondSpreadQuantity;
                        SelectedRow["Spread1Quantity"]   = (int)(FirstSpreadQuantity - SecondSpreadQuantity);
                    }

                    else
                    {
                        ButterfliesSheetFiltered.Rows[i]["ButterflyQuantity"] = (int)FirstSpreadQuantity;
                    }

                    Alias = SelectedRow.Field <string>("tickerHead") + Ticker1.Substring(Ticker1.Count() - 5, 5) + Ticker2.Substring(Ticker2.Count() - 5, 5) +
                            Ticker2.Substring(Ticker2.Count() - 5, 5) + Ticker3.Substring(Ticker3.Count() - 5, 5);
                }
                else if (ButterfliesSheetFiltered.Rows[i].Field <double>("z1") > 0)
                {
                    double FirstSpreadQuantity  = Math.Round(ButterfliesSheetFiltered.Rows[i].Field <double>("Size") / Math.Abs(ButterfliesSheetFiltered.Rows[i].Field <double>("Upside")));
                    double SecondSpreadQuantity = Math.Round(FirstSpreadQuantity * ButterfliesSheetFiltered.Rows[i].Field <double>("second_spread_weight_1"));

                    if (FirstSpreadQuantity < SecondSpreadQuantity)
                    {
                        SelectedRow["ButterflyQuantity"] = -(int)FirstSpreadQuantity;
                        SelectedRow["Spread2Quantity"]   = (int)(SecondSpreadQuantity - FirstSpreadQuantity);
                    }
                    else if (FirstSpreadQuantity > SecondSpreadQuantity)
                    {
                        SelectedRow["ButterflyQuantity"] = -(int)SecondSpreadQuantity;
                        SelectedRow["Spread1Quantity"]   = -(int)(FirstSpreadQuantity - SecondSpreadQuantity);
                    }

                    else
                    {
                        SelectedRow["ButterflyQuantity"] = (int)FirstSpreadQuantity;
                    }

                    Alias = SelectedRow.Field <string>("tickerHead") + Ticker2.Substring(Ticker2.Count() - 5, 5) + Ticker3.Substring(Ticker3.Count() - 5, 5) +
                            Ticker1.Substring(Ticker1.Count() - 5, 5) + Ticker2.Substring(Ticker2.Count() - 5, 5);
                }

                SelectedRow["Alias"] = Alias;

                List <string> TickerList = new List <string> {
                    Ticker1 + "-" + Ticker2,
                    Ticker2 + "-" + Ticker3
                };

                ttapiUtils.AutoSpreader As = new ttapiUtils.AutoSpreader(dbTickerList: TickerList, payUpTicks: 2);

                SpreadList.AddRange(TickerList);
                AutoSpreaderList.Add(As);
                AutoSpreaderDictionary.Add(As.AutoSpreaderName, As);
                Alias2AutoSpreaderDictionary.Add(Alias, As.AutoSpreaderName);
                TagDictionary.Add(As.AutoSpreaderName, "fut_but_fol_" + i);

                DataRow PriceRow = PriceTable.NewRow();
                PriceRow["Ticker"]          = As.AutoSpreaderName;
                PriceRow["TickerHead"]      = SelectedRow.Field <string>("tickerHead");
                PriceRow["IsAutoSpreaderQ"] = true;
                PriceTable.Rows.Add(PriceRow);
            }



            HistoricPriceTable = GetPrice.GetFuturesPrice.getFuturesPrice4Ticker(tickerHeadList: ContractUtilities.ContractMetaInfo.FuturesButterflyTickerheadList,
                                                                                 dateTimeFrom: ReportDate, dateTimeTo: ReportDate, conn: conn);

            DataRow [] StopList = ButterfliesFollowupSheet.Select("Recommendation='STOP'");

            if (StopList.Length > 0)
            {
                ButterfliesStopSheet = StopList.CopyToDataTable();
                ButterfliesStopSheet.Columns.Add("PnlMid", typeof(double));
                ButterfliesStopSheet.Columns.Add("PnlWorst", typeof(double));
                ButterfliesStopSheet.Columns.Add("ButterflyMidPrice", typeof(double));
                ButterfliesStopSheet.Columns.Add("ButterflyWorstPrice", typeof(double));
                ButterfliesStopSheet.Columns.Add("ButterflyQuantity", typeof(int));
                ButterfliesStopSheet.Columns.Add("SpreadMidPrice", typeof(double));
                ButterfliesStopSheet.Columns.Add("SpreadWorstPrice", typeof(double));
                ButterfliesStopSheet.Columns.Add("SpreadQuantity", typeof(int));

                DataColumn WorkingButterflyOrdersColumn = new DataColumn("WorkingButterflyOrders", typeof(int));
                WorkingButterflyOrdersColumn.DefaultValue = 0;
                ButterfliesStopSheet.Columns.Add(WorkingButterflyOrdersColumn);

                DataColumn WorkingSpreadOrdersColumn = new DataColumn("WorkingSpreadOrders", typeof(int));
                WorkingSpreadOrdersColumn.DefaultValue = 0;
                ButterfliesStopSheet.Columns.Add(WorkingSpreadOrdersColumn);

                for (int i = 0; i < StopList.Length; i++)
                {
                    string Alias = StopList[i].Field <string>("Alias");
                    StrategyUtilities.PositionManagerOutput PositionManagerOut = PositionManager.GetFuturesButterflyPosition(alias: Alias, asOfDate: TodayDate, conn: conn);
                    DataTable StrategyPosition = PositionManagerOut.SortedPosition;

                    StrategyPosition.Columns.Add("ClosePrice", typeof(double));

                    for (int j = 0; j < StrategyPosition.Rows.Count; j++)
                    {
                        DataRow SelectedHistRow = HistoricPriceTable.Select("ticker='" + StrategyPosition.Rows[j].Field <string>("Ticker") + "'")[0];
                        StrategyPosition.Rows[j]["ClosePrice"] = SelectedHistRow.Field <decimal>("close_price");
                    }


                    List <string> TickerList = new List <string> {
                        StrategyPosition.Rows[0].Field <string>("Ticker") + "-" + StrategyPosition.Rows[1].Field <string>("Ticker"),
                        StrategyPosition.Rows[1].Field <string>("Ticker") + "-" + StrategyPosition.Rows[2].Field <string>("Ticker")
                    };
                    StrategyPositionDictionary[Alias] = StrategyPosition;

                    SpreadList.AddRange(TickerList);

                    if (PositionManagerOut.CorrectPositionQ)
                    {
                        ttapiUtils.AutoSpreader As = new ttapiUtils.AutoSpreader(dbTickerList: TickerList, payUpTicks: 2);

                        AutoSpreaderList.Add(As);
                        AutoSpreaderDictionary.Add(As.AutoSpreaderName, As);
                        Alias2AutoSpreaderDictionary.Add(Alias, As.AutoSpreaderName);
                        TagDictionary.Add(As.AutoSpreaderName, "fut_but_fol_" + (i + ButterfliesSheetFiltered.Rows.Count));


                        DataRow PriceRow = PriceTable.NewRow();
                        PriceRow["Ticker"]          = As.AutoSpreaderName;
                        PriceRow["TickerHead"]      = StrategyPosition.Rows[0].Field <string>("TickerHead");
                        PriceRow["IsAutoSpreaderQ"] = true;
                        PriceTable.Rows.Add(PriceRow);
                    }
                    else
                    {
                        ButterflyLogger.Log("Check " + Alias + " ! Position may be incorrect.");
                    }
                }


                SpreadList = SpreadList.Distinct().ToList();

                SpreadTable = new DataTable();
                SpreadTable.Columns.Add("Ticker", typeof(string));
                SpreadTable.Columns.Add("IsSpreadQ", typeof(bool));

                for (int i = 0; i < SpreadList.Count; i++)
                {
                    DataRow SpreadRow = SpreadTable.NewRow();
                    SpreadRow["Ticker"]    = SpreadList[i];
                    SpreadRow["IsSpreadQ"] = true;
                    SpreadTable.Rows.Add(SpreadRow);

                    DataRow PriceRow = PriceTable.NewRow();
                    PriceRow["Ticker"] = SpreadList[i];
                    string[] SpreadAsArray = SpreadList[i].Split(new char[] { '-' });
                    PriceRow["TickerHead"]      = ContractUtilities.ContractMetaInfo.GetContractSpecs(SpreadAsArray[0]).tickerHead;
                    PriceRow["IsAutoSpreaderQ"] = false;
                    PriceTable.Rows.Add(PriceRow);
                }
            }



            PriceTableSymbols = DataAnalysis.DataTableFunctions.GetColumnAsList <string>(dataTableInput: PriceTable, columnName: "Ticker");


            TTAPISubs.TickerTable      = SpreadTable;
            TTAPISubs.AutoSpreaderList = AutoSpreaderList;
            TTAPISubs.AsuUpdateList    = new List <EventHandler <AuthenticationStatusUpdateEventArgs> > {
                TTAPISubs.StartASESubscriptions, TTAPISubs.startInstrumentLookupSubscriptionsFromDataTable
            };
            //TTAPISubs.AsuUpdateList = new List<EventHandler<AuthenticationStatusUpdateEventArgs>> {TTAPISubs.startInstrumentLookupSubscriptionsFromDataTable };
            TTAPISubs.ilsUpdateList = new List <EventHandler <InstrumentLookupSubscriptionEventArgs> > {
                TTAPISubs.startPriceSubscriptions, TTAPISubs.startTradeSubscriptions
            };
            //TTAPISubs.ilsUpdateList = new List<EventHandler<InstrumentLookupSubscriptionEventArgs>> { TTAPISubs.startPriceSubscriptions};
            TTAPISubs.priceUpdatedEventHandler = m_ps_FieldsUpdated;
            TTAPISubs.orderFilledEventHandler  = m_ts_OrderFilled;
        }
Exemplo n.º 2
0
        public static DataTable GetFilteredNewTrades(DataTable butterfliesSheet, DataTable riskAcrossTickerhead, Dictionary <string, double> riskAcrossTheme)
        {
            DataTable     ButterfliesSheet  = butterfliesSheet.Select("trDte1>=" + MinTrDte).CopyToDataTable();
            List <string> TickerHeadNewList = DataAnalysis.DataTableFunctions.GetColumnAsList <string>(dataTableInput: ButterfliesSheet, columnName: "tickerHead", uniqueQ: true);

            DataTable ButterfliesSheetFiltered = new DataTable();

            ButterfliesSheetFiltered = ButterfliesSheet.Clone();

            DateTime CurrentDate = DateTime.Now.Date;

            ContIndx1YearOut = 100 * (CurrentDate.Year + 1) + CurrentDate.Month;

            for (int i = 0; i < ButterfliesSheet.Rows.Count; i++)
            {
                DataRow SelectedRow = ButterfliesSheet.Rows[i];

                List <string> TickerList = new List <string> {
                    SelectedRow.Field <string>("Ticker1"), SelectedRow.Field <string>("Ticker2"), SelectedRow.Field <string>("Ticker3")
                };
                double Direction;

                if (SelectedRow.Field <double>("z1") < 0)
                {
                    Direction = 1;
                }
                else
                {
                    Direction = -1;
                }

                List <string> ThemeList = RiskManager.GetThemeList4Position(tickerList: TickerList, direction: Direction);

                if (ThemeList.Count > 0)
                {
                    List <double> RelatedThemeDownsideList = new List <double>();
                    for (int j = 0; j < ThemeList.Count; j++)
                    {
                        RelatedThemeDownsideList.Add(ButterflyFinalBetSize * RiskManager.ThemeMultipliers[ThemeList[j]] - Math.Abs(riskAcrossTheme[ThemeList[j]]));
                        SelectedRow["SlackFromTheme"] = RelatedThemeDownsideList.Min();
                    }
                }
                else
                {
                    SelectedRow["SlackFromTheme"] = ButterflyFinalBetSize;
                }
            }

            for (int i = 0; i < TickerHeadNewList.Count; i++)
            {
                DataTable Selected4TickerHeadTable = ButterfliesSheet.Select("tickerHead='" + TickerHeadNewList[i] + "'").CopyToDataTable();

                DataRow[] Long4TickerHead  = Selected4TickerHeadTable.Select("z1<0");
                DataRow[] Short4TickerHead = Selected4TickerHeadTable.Select("z1>0");

                if (Long4TickerHead.Count() > 0)
                {
                    DataRow[] ExistingLongRows = riskAcrossTickerhead.Select("TickerHead='" + TickerHeadNewList[i] + "' and Direction=1");

                    if (ExistingLongRows.Count() == 0)
                    {
                        for (int j = 0; j < Long4TickerHead.Count(); j++)
                        {
                            if (Math.Min(ButterflyFinalBetSize, Long4TickerHead[j].Field <double>("SlackFromTheme")) > MinNewPosition)
                            {
                                Long4TickerHead[j]["Size"] = Math.Min(ButterflyFinalBetSize, Long4TickerHead[j].Field <double>("SlackFromTheme"));
                                ButterfliesSheetFiltered.ImportRow(Long4TickerHead[j]);
                            }
                        }
                    }

                    else if ((ButterflyFinalBetSize - Math.Abs(ExistingLongRows[0].Field <double>("DownSide")) > MinNewPosition))
                    {
                        for (int j = 0; j < Long4TickerHead.Count(); j++)
                        {
                            if (Math.Min(ButterflyFinalBetSize, Long4TickerHead[j].Field <double>("SlackFromTheme")) > MinNewPosition)
                            {
                                Long4TickerHead[j]["Size"] = Math.Min(ButterflyFinalBetSize - Math.Abs(ExistingLongRows[0].Field <double>("DownSide")),
                                                                      Math.Min(ButterflyFinalBetSize, Long4TickerHead[j].Field <double>("SlackFromTheme")));
                                ButterfliesSheetFiltered.ImportRow(Long4TickerHead[j]);
                            }
                        }
                    }
                }

                if (Short4TickerHead.Count() > 0)
                {
                    DataRow[] ExistingShortRows = riskAcrossTickerhead.Select("TickerHead='" + TickerHeadNewList[i] + "' and Direction=-1");


                    if (ExistingShortRows.Count() == 0)
                    {
                        for (int j = 0; j < Short4TickerHead.Count(); j++)
                        {
                            if (Short4TickerHead[j].Field <double>("z1") >= 1.2)
                            {
                                if (Math.Min(ButterflyFinalBetSize, Short4TickerHead[j].Field <double>("SlackFromTheme")) > MinNewPosition)
                                {
                                    Short4TickerHead[j]["Size"] = Math.Min(ButterflyFinalBetSize, Short4TickerHead[j].Field <double>("SlackFromTheme"));
                                }
                            }
                            else if (Short4TickerHead[j].Field <double>("z1") >= 0.6)
                            {
                                if (Math.Min(ButterflyFirstBetSize, Short4TickerHead[j].Field <double>("SlackFromTheme")) > MinNewPosition)
                                {
                                    Short4TickerHead[j]["Size"] = Math.Min(ButterflyFirstBetSize, Short4TickerHead[j].Field <double>("SlackFromTheme"));
                                }
                            }

                            if (Short4TickerHead[j].Field <double>("Size") > 0)
                            {
                                ButterfliesSheetFiltered.ImportRow(Short4TickerHead[j]);
                            }
                        }
                    }

                    else
                    {
                        for (int j = 0; j < Short4TickerHead.Count(); j++)
                        {
                            if ((Short4TickerHead[j].Field <double>("z1") >= 1.2) &&
                                (ButterflyFinalBetSize - Math.Abs(ExistingShortRows[0].Field <double>("DownSide")) > MinNewPosition) &&
                                (Math.Min(ButterflyFinalBetSize, Short4TickerHead[j].Field <double>("SlackFromTheme")) > MinNewPosition)
                                )
                            {
                                Short4TickerHead[j]["Size"] = Math.Min(ButterflyFinalBetSize - Math.Abs(ExistingShortRows[0].Field <double>("DownSide")),
                                                                       Math.Min(ButterflyFinalBetSize, Short4TickerHead[j].Field <double>("SlackFromTheme")));
                            }
                            else if ((Short4TickerHead[j].Field <double>("z1") >= 0.6) &&
                                     (ButterflyFirstBetSize - Math.Abs(ExistingShortRows[0].Field <double>("DownSide")) > MinNewPosition) &&
                                     (Math.Min(ButterflyFirstBetSize, Short4TickerHead[j].Field <double>("SlackFromTheme")) > MinNewPosition))
                            {
                                Short4TickerHead[j]["Size"] = Math.Min(ButterflyFirstBetSize - Math.Abs(ExistingShortRows[0].Field <double>("DownSide")),
                                                                       Math.Min(ButterflyFirstBetSize, Short4TickerHead[j].Field <double>("SlackFromTheme")));
                            }

                            if (Short4TickerHead[j].Field <double>("Size") > 0)
                            {
                                ButterfliesSheetFiltered.ImportRow(Short4TickerHead[j]);
                            }
                        }
                    }
                }
            }
            return(ButterfliesSheetFiltered);
        }