private void PeriodicCall(object source, ElapsedEventArgs e) { ButterfliesStopSheet = CalculateStrategyPnls(StrategyTableInput: ButterfliesStopSheet); DataRow[] Ready2CloseRows = ButterfliesStopSheet.Select("PnlMid>0"); if (Ready2CloseRows.Count() == 0) { if (DateTime.UtcNow > LogTime1.AddMinutes(5)) { ButterflyLogger.Log("No trades to close"); LogTime1 = DateTime.UtcNow; } } for (int i = 0; i < Ready2CloseRows.Count(); i++) { string Alias = Ready2CloseRows[i].Field <string>("Alias"); if (Ready2CloseRows[i].Field <int>("ButterflyQuantity") + Ready2CloseRows[i].Field <int>("WorkingButterflyOrders") != 0) { Ready2CloseRows[i]["WorkingButterflyOrders"] = -Ready2CloseRows[i].Field <int>("ButterflyQuantity"); ButterflyLogger.Log(Ready2CloseRows[i].Field <string>("Alias") + " will be closed"); ButterflyLogger.Log("Intraday pnl: " + Ready2CloseRows[i].Field <double>("PnlMid")); ButterflyLogger.Log("Number of Butterflies: " + Ready2CloseRows[i].Field <int>("ButterflyQuantity")); ButterflyLogger.Log("Number of Extra Spreads: " + Ready2CloseRows[i].Field <int>("SpreadQuantity")); Console.Write("Do you agree? (Y/N): "); string Decision = Console.ReadLine(); Decision = Decision.ToUpper(); if (Decision == "Y") { string AutoSpreaderName = Alias2AutoSpreaderDictionary[Alias]; ttapiUtils.AutoSpreader AutoSpreader = AutoSpreaderDictionary[AutoSpreaderName]; string OrderTag = TagDictionary[AutoSpreaderName]; string emre = "merve"; ttapiUtils.Trade.SendAutospreaderOrder(instrument: AutoSpreader.AutoSpreaderInstrument, instrumentDetails: AutoSpreader.AutoSpreaderInstrument.InstrumentDetails, autoSpreader: AutoSpreader, qty: Ready2CloseRows[i].Field <int>("WorkingButterflyOrders"), price: (decimal)Ready2CloseRows[i].Field <double>("ButterflyMidPrice"), orderTag: OrderTag, logger: ButterflyLogger); } else if (Decision == "N") { ButterflyLogger.Log("You have chosen to keep " + Ready2CloseRows[i].Field <string>("Alias")); } } } }
public static string SendAutospreaderOrder(ttapiUtils.AutoSpreader autoSpreader, int qty, decimal price, string orderTag, Logger logger, int reloadQuantity = 0) { Instrument instrument = autoSpreader.AutoSpreaderInstrument; InstrumentDetails instrumentDetails = instrument.InstrumentDetails; AutospreaderSyntheticOrderProfile op = new AutospreaderSyntheticOrderProfile(((AutospreaderInstrument)instrument).GetValidGateways()[autoSpreader.GateWay], (AutospreaderInstrument)instrument); BuySell Direction = BuySell.Buy; Rounding Rounding = Rounding.Down; if (qty < 0) { Direction = BuySell.Sell; qty = -qty; Rounding = Rounding.Up; } string OrderKey = op.SiteOrderKey; if (reloadQuantity != 0) { op.SlicerType = SlicerType.Reload; op.DisclosedQuantity = Quantity.FromInt(instrument, reloadQuantity); } op.BuySell = Direction; op.OrderQuantity = Quantity.FromInt(instrument, qty); op.OrderType = OrderType.Limit; op.OrderTag = orderTag; op.LimitPrice = Price.FromDouble(instrumentDetails, Convert.ToDouble(price), Rounding); if (!autoSpreader.ts.SendOrder(op)) { logger.Log("Send new order failed: " + op.RoutingStatus.Message); } else { logger.Log("Send new order succeeded."); } return(OrderKey); }
public static bool CancelAutospreaderOrder(string orderKey, ttapiUtils.AutoSpreader autoSpreader, Logger logger) { ASInstrumentTradeSubscription Ts = autoSpreader.ts; bool Status = false; if (Ts.Orders.ContainsKey(orderKey)) { AutospreaderSyntheticOrderProfile Op = Ts.Orders[orderKey].GetOrderProfile() as AutospreaderSyntheticOrderProfile; Op.Action = OrderAction.Delete; if (!Ts.SendOrder(Op)) { logger.Log("Cancal order failed. {0}" + Op.RoutingStatus.Message); } else { logger.Log("Cancel order succeeded."); Status = true; } } return(Status); }
public static bool ChangeAutospreaderOrder(string orderKey, decimal price, ttapiUtils.AutoSpreader autoSpreader, TradingTechnologies.TTAPI.Instrument instrument, Logger logger) { ASInstrumentTradeSubscription Ts = autoSpreader.ts; bool Status = false; if (Ts.Orders.ContainsKey(orderKey)) { AutospreaderSyntheticOrderProfile Op = Ts.Orders[orderKey].GetOrderProfile() as AutospreaderSyntheticOrderProfile; Rounding Rounding = Rounding.Down; if (Op.BuySell == BuySell.Sell) { Rounding = Rounding.Up; } Price LimitPrice = Price.FromDouble(instrument.InstrumentDetails, Convert.ToDouble(price), Rounding); if (Op.LimitPrice != LimitPrice) { Op.LimitPrice = LimitPrice; Op.Action = OrderAction.Change; if (!Ts.SendOrder(Op)) { logger.Log("Send change order failed. {0}" + Op.RoutingStatus.Message); } else { logger.Log("Send change order succeeded."); Status = true; } } } return(Status); }
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; }
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>(); AliasDictionary = new Dictionary<string, string>(); TagDictionary = new Dictionary<string, string>(); 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 DirectoryExtension = TA.DirectoryNames.GetDirectoryExtension(directoryDate: ReportDate); DataSet FollowupOutput = IOUtilities.ExcelDataReader.LoadFile(DirectoryName + "/" + DirectoryExtension + "/followup.xlsx"); DataTable ButterfliesFollowupSheet = FollowupOutput.Tables["butterflies"]; PriceTable = new DataTable(); PriceTable.Columns.Add("Ticker", typeof(string)); PriceTable.Columns.Add("TickerHead", typeof(string)); PriceTable.Columns.Add("IsAutoSpreaderQ", typeof(bool)); PriceTable.Columns.Add("BidPrice", typeof(double)); PriceTable.Columns.Add("AskPrice", typeof(double)); 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)); 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.Add(Alias, StrategyPosition); SpreadList.AddRange(TickerList); if (PositionManagerOut.CorrectPositionQ) { bool wuhu = TickerList[0].Contains("-"); string[] TickerListAux = TickerList[0].Split('-'); ttapiUtils.AutoSpreader As = new ttapiUtils.AutoSpreader(dbTickerList: TickerList, payUpTicks: 2); AutoSpreaderList.Add(As); AutoSpreaderDictionary.Add(As.AutoSpreaderName, As); AliasDictionary.Add(As.AutoSpreaderName, Alias); TagDictionary.Add(As.AutoSpreaderName, "fut_but_fol" + i); 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; }
private void PeriodicCall(object source, ElapsedEventArgs e) { DateTime TimeStamp = DateTime.Now; DateTime TimeStampFull = new DateTime(TodayDate.Year, TodayDate.Month, TodayDate.Day, TimeStamp.Hour, TimeStamp.Minute, 0); int RowIndx = 0; OpportunityZone OpZone; PositionZone PosZone; int Qty = 1; DataRow SelectedRow = SummaryTable.Rows[RowIndx]; ttapiUtils.AutoSpreader SelectedAutospreader = AutoSpreaderDictionary[SelectedRow.Field <string>("Ticker")]; Instrument SelectedInstrument = SelectedAutospreader.AutoSpreaderInstrument; if (SelectedRow.Field <bool>("ValidPrice")) { TimeSeriesObj.updateValues(newPrice: SelectedRow.Field <double>("MidConverted"), newDateTime: TimeStampFull, instrument: SelectedRow.Field <string>("Ticker")); double IndicatorValue = TechnicalSignals.MovingAverage.CalculateTimeSeriesMovingAverage(timeSeries: TimeSeriesObj.Data, columnName: SelectedRow.Field <string>("Ticker"), dateTimePoint: TimeStampFull, numObs: 40); double Spread = SelectedRow.Field <double>("MidConverted") - IndicatorValue; if (Spread > SelectedRow.Field <double>("UpperLimit")) { OpZone = OpportunityZone.Zone1; } else if ((Spread <= SelectedRow.Field <double>("UpperLimit")) && (Spread > 0)) { OpZone = OpportunityZone.Zone2; } else if ((Spread <= 0) && (Spread > SelectedRow.Field <double>("LowerLimit"))) { OpZone = OpportunityZone.Zone3; } else if (Spread < SelectedRow.Field <double>("LowerLimit")) { OpZone = OpportunityZone.Zone4; } else { OpZone = OpportunityZone.Zone0; } if ((SelectedRow.Field <int>("Position") == 0) && (SelectedRow.Field <int>("WorkingOrders") == 0)) { PosZone = PositionZone.None; } else if ((SelectedRow.Field <int>("Position") > 0) && (SelectedRow.Field <int>("WorkingOrders") == 0)) { PosZone = PositionZone.Long; } else if ((SelectedRow.Field <int>("Position") < 0) && (SelectedRow.Field <int>("WorkingOrders") == 0)) { PosZone = PositionZone.Short; } else if ((SelectedRow.Field <int>("Position") == 0) && (SelectedRow.Field <int>("WorkingOrders") > 0)) { PosZone = PositionZone.WorkingEntryLong; } else if ((SelectedRow.Field <int>("Position") == 0) && (SelectedRow.Field <int>("WorkingOrders") < 0)) { PosZone = PositionZone.WorkingEntryShort; } else if ((SelectedRow.Field <int>("Position") > 0) && (SelectedRow.Field <int>("WorkingOrders") < 0)) { PosZone = PositionZone.WorkingExitLong; } else if ((SelectedRow.Field <int>("Position") < 0) && (SelectedRow.Field <int>("WorkingOrders") > 0)) { PosZone = PositionZone.WorkingEntryShort; } else { PosZone = PositionZone.Undefined; } //New Short Position if ((OpZone == OpportunityZone.Zone1) && (PosZone == PositionZone.None)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " entering a short position for " + SelectedRow.Field <double>("Mid")); SelectedRow["WorkingOrders"] = -Qty; SelectedRow["WorkingOrderKey"] = ttapiUtils.Trade.SendAutospreaderOrder(instrument: SelectedInstrument, instrumentDetails: SelectedInstrument.InstrumentDetails, autoSpreader: SelectedAutospreader, qty: -Qty, price: (decimal)SelectedRow.Field <double>("Mid"), orderTag: SelectedRow.Field <string>("Tag"), logger: IFSLogger); } //New Long Position else if ((OpZone == OpportunityZone.Zone4) && (PosZone == PositionZone.None)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " entering a long position for " + SelectedRow.Field <double>("Mid")); SelectedRow["WorkingOrders"] = Qty; SelectedRow["WorkingOrderKey"] = ttapiUtils.Trade.SendAutospreaderOrder(instrument: SelectedInstrument, instrumentDetails: SelectedInstrument.InstrumentDetails, autoSpreader: SelectedAutospreader, qty: Qty, price: (decimal)SelectedRow.Field <double>("Mid"), orderTag: SelectedRow.Field <string>("Tag"), logger: IFSLogger); } //Adjusting Short Open Position else if ((OpZone == OpportunityZone.Zone1) && (PosZone == PositionZone.WorkingEntryShort)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " adjusting short open order price to " + SelectedRow.Field <double>("Mid")); ttapiUtils.Trade.ChangeAutospreaderOrder(orderKey: SelectedRow.Field <string>("WorkingOrderKey"), price: (decimal)SelectedRow.Field <double>("Mid"), autoSpreader: SelectedAutospreader, instrument: SelectedInstrument, logger: IFSLogger); } //Adjusting Long Open Position else if ((OpZone == OpportunityZone.Zone4) && (PosZone == PositionZone.WorkingEntryLong)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " adjusting long open order price to " + SelectedRow.Field <double>("Mid")); ttapiUtils.Trade.ChangeAutospreaderOrder(orderKey: SelectedRow.Field <string>("WorkingOrderKey"), price: (decimal)SelectedRow.Field <double>("Mid"), autoSpreader: SelectedAutospreader, instrument: SelectedInstrument, logger: IFSLogger); } //Closing Short Position else if (((OpZone == OpportunityZone.Zone3) | (OpZone == OpportunityZone.Zone4)) && (PosZone == PositionZone.Short)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " has normalized. Closing position for " + SelectedRow.Field <double>("Mid")); SelectedRow["WorkingOrders"] = -SelectedRow.Field <int>("Position"); SelectedRow["WorkingOrderKey"] = ttapiUtils.Trade.SendAutospreaderOrder(instrument: SelectedInstrument, instrumentDetails: SelectedInstrument.InstrumentDetails, autoSpreader: SelectedAutospreader, qty: -SelectedRow.Field <int>("Position"), price: (decimal)SelectedRow.Field <double>("Mid"), orderTag: SelectedRow.Field <string>("Tag"), logger: IFSLogger); } //Closing Long Position else if (((OpZone == OpportunityZone.Zone1) | (OpZone == OpportunityZone.Zone2)) && (PosZone == PositionZone.Long)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " has normalized. Closing position for " + SelectedRow.Field <double>("Mid")); SelectedRow["WorkingOrders"] = -SelectedRow.Field <int>("Position"); SelectedRow["WorkingOrderKey"] = ttapiUtils.Trade.SendAutospreaderOrder(instrument: SelectedInstrument, instrumentDetails: SelectedInstrument.InstrumentDetails, autoSpreader: SelectedAutospreader, qty: -SelectedRow.Field <int>("Position"), price: (decimal)SelectedRow.Field <double>("Mid"), orderTag: SelectedRow.Field <string>("Tag"), logger: IFSLogger); } // Adjusting Short Close Position else if (((OpZone == OpportunityZone.Zone3) | (OpZone == OpportunityZone.Zone4)) && (PosZone == PositionZone.WorkingExitShort)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " adjusting short close order price to " + SelectedRow.Field <double>("Mid")); ttapiUtils.Trade.ChangeAutospreaderOrder(orderKey: SelectedRow.Field <string>("WorkingOrderKey"), price: (decimal)SelectedRow.Field <double>("Mid"), autoSpreader: SelectedAutospreader, instrument: SelectedInstrument, logger: IFSLogger); } // Adjusting Long Close Position else if (((OpZone == OpportunityZone.Zone1) | (OpZone == OpportunityZone.Zone2)) && (PosZone == PositionZone.WorkingExitLong)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " adjusting long close order price to " + SelectedRow.Field <double>("Mid")); ttapiUtils.Trade.ChangeAutospreaderOrder(orderKey: SelectedRow.Field <string>("WorkingOrderKey"), price: (decimal)SelectedRow.Field <double>("Mid"), autoSpreader: SelectedAutospreader, instrument: SelectedInstrument, logger: IFSLogger); } //Canceling Short Entry Order else if ((OpZone != OpportunityZone.Zone1) && (PosZone == PositionZone.WorkingEntryShort)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " has normalized canceling working order"); bool cancelSuccess = ttapiUtils.Trade.CancelAutospreaderOrder(orderKey: SelectedRow.Field <string>("WorkingOrderKey"), autoSpreader: SelectedAutospreader, logger: IFSLogger); if (cancelSuccess) { SelectedRow["WorkingOrders"] = 0; } } //Canceling Long Entry Order else if ((OpZone != OpportunityZone.Zone4) && (PosZone == PositionZone.WorkingEntryLong)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " has normalized canceling working order"); bool cancelSuccess = ttapiUtils.Trade.CancelAutospreaderOrder(orderKey: SelectedRow.Field <string>("WorkingOrderKey"), autoSpreader: SelectedAutospreader, logger: IFSLogger); if (cancelSuccess) { SelectedRow["WorkingOrders"] = 0; } } //Canceling Short Exit Order else if ((OpZone != OpportunityZone.Zone3) && (OpZone != OpportunityZone.Zone4) && (PosZone == PositionZone.WorkingExitShort)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " has de-normalized canceling working order"); bool cancelSuccess = ttapiUtils.Trade.CancelAutospreaderOrder(orderKey: SelectedRow.Field <string>("WorkingOrderKey"), autoSpreader: SelectedAutospreader, logger: IFSLogger); if (cancelSuccess) { SelectedRow["WorkingOrders"] = 0; } } //Canceling Long Exit Order else if ((OpZone != OpportunityZone.Zone1) && (OpZone != OpportunityZone.Zone2) && (PosZone == PositionZone.WorkingExitLong)) { IFSLogger.Log(SelectedRow.Field <string>("Alias") + " has de-normalized canceling working order"); bool cancelSuccess = ttapiUtils.Trade.CancelAutospreaderOrder(orderKey: SelectedRow.Field <string>("WorkingOrderKey"), autoSpreader: SelectedAutospreader, logger: IFSLogger); if (cancelSuccess) { SelectedRow["WorkingOrders"] = 0; } } Console.WriteLine(DateTime.Now + " Recorded Price: " + SummaryTable.Rows[RowIndx].Field <double>("MidConverted")); Console.WriteLine(DateTime.Now + " Spread: " + (SummaryTable.Rows[RowIndx].Field <double>("MidConverted") - IndicatorValue)); } }