private void SendOrderEventsToFile() { string filepath = AssemblyLocator.ExecutingDirectory() + "orderEvents.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } var liststring = CsvSerializer.Serialize <OrderEvent>(",", _orderEvents, true); using (StreamWriter fs = new StreamWriter(filepath, true)) { foreach (var s in liststring) { fs.WriteLine(s); } fs.Flush(); fs.Close(); } }
private void SendTradesToFile() { string filepath = AssemblyLocator.ExecutingDirectory() + "trades.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } var liststring = CsvSerializer.Serialize <MatchedTrade>(",", _orderTransactionProcessor.Trades, true); using (StreamWriter fs = new StreamWriter(filepath, true)) { foreach (var s in liststring) { fs.WriteLine(s); } fs.Flush(); fs.Close(); } }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { #region logging var algoname = this.GetType().Name; mylog.Debug(algoname); mylog.Debug(ondataheader); dailylog.Debug(algoname); dailylog.Debug(dailyheader); _transactions = new List <OrderTransaction>(); string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } #endregion //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(_portfolioAmount); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); // Indicators Price = new RollingWindow <IndicatorDataPoint>(14); // The price history // ITrend trend = new InstantaneousTrend(7); trendHistory = new RollingWindow <IndicatorDataPoint>(14); // The ITrendStrategy iTrendStrategy = new InstantTrendStrategyOriginal(symbol, 14, this); iTrendStrategy.ShouldSellOutAtEod = shouldSellOutAtEod; #region lists #endregion var security = Securities[symbol]; security.TransactionModel = new ConstantFeeTransactionModel(1.0m); }
public override void OnEndOfAlgorithm() { Debug(string.Format("\nAlgorithm Name: {0}\n Ending Portfolio Value: {1} ", this.GetType().Name, Portfolio.TotalPortfolioValue)); #region Logging stuff - Saving the logs int i = 0; //foreach (string symbol in Symbols) //{ // string filename = string.Format("ITrendDebug_{0}.csv", symbol); // string filePath = @"C:\Users\JJ\Desktop\MA y señales\ITrend Debug\" + filename; // // JJ do not delete this line it locates my engine\bin\debug folder // // I just uncomment it when I run on my local machine // filePath = AssemblyLocator.ExecutingDirectory() + filename; // if (File.Exists(filePath)) File.Delete(filePath); // File.AppendAllText(filePath, stockLogging[i].ToString()); // Debug(string.Format("\nSymbol Name: {0}, Ending Portfolio Value: {1} ", symbol, Portfolio[symbol].Profit)); //} string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } var liststring = CsvSerializer.Serialize <OrderTransaction>(",", _transactions, true); using (StreamWriter fs = new StreamWriter(filepath)) { foreach (var s in liststring) { fs.WriteLine(s); } fs.Flush(); fs.Close(); } #endregion Logging stuff - Saving the logs }
public override void OnEndOfAlgorithm() { #region Logging stuff - Saving the logs int i = 0; foreach (string symbol in Symbols) { string filename = string.Format("ITrendDebug_{0}.csv", symbol); string filePath = @"C:\Users\JJ\Desktop\MA y señales\ITrend Debug\" + filename; // JJ do not delete this line it locates my engine\bin\debug folder // I just uncomment it when I run on my local machine filePath = AssemblyLocator.ExecutingDirectory() + filename; if (File.Exists(filePath)) { File.Delete(filePath); } File.AppendAllText(filePath, stockLogging[i].ToString()); Debug(string.Format("\nSymbol Name: {0}, Ending Value: {1} ", symbol, Portfolio[symbol].Profit)); } StringBuilder sb = new StringBuilder(); //sb.Append(" Symbols: "); foreach (var s in Symbols) { sb.Append(s.ToString()); sb.Append(","); } string symbolsstring = sb.ToString(); symbolsstring = symbolsstring.Substring(0, symbolsstring.LastIndexOf(",", System.StringComparison.Ordinal)); string debugstring = string.Format( "\nAlgorithm Name: {0}\n Symbol: {1}\n Ending Portfolio Value: {2} \n lossThreshhold = {3}\n Start Time: {4}\n End Time: {5}", this.GetType().Name, symbolsstring, Portfolio.TotalPortfolioValue, lossThreshhold, startTime, DateTime.Now); Log(debugstring); #endregion Logging stuff - Saving the logs }
public override void Initialize() { SetStartDate(_startDate); //Set Start Date SetEndDate(_endDate); //Set End Date SetCash(_portfolioAmount); //Set Strategy Cash #region Nick logging var algoname = this.GetType().Name; mylog.Debug(algoname); mylog.Debug(ondataheader); dailylog.Debug(algoname); dailylog.Debug(dailyheader); _proformatransactions = new List <OrderTransaction>(); string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } #endregion #region Logging stuff - Initializing Portfolio Logging portfolioLogging.AppendLine("Counter, Time, Portfolio Value"); int i = 0; // Only used for logging. #endregion Logging stuff - Initializing Portfolio Logging #region "Read Symbols from File" /********************************************** * THIS SECTION IS FOR READING SYMBOLS FROM A FILE ************************************************/ //string symbols; var filename = AssemblyLocator.ExecutingDirectory() + "symbols.txt"; using (StreamReader sr = new StreamReader(filename)) { string[] symbols = { }; var readLine = sr.ReadLine(); if (readLine != null) { symbols = readLine.Split(','); } foreach (string t in symbols) { Symbols.Add(new Symbol(t)); } sr.Close(); } // Make sure the list contains the static symbol //if (!Symbols.Contains(symbol)) //{ // Symbols.Add(symbol); //} #endregion foreach (string symbol in Symbols) { AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); var priceIdentity = Identity(symbol, selector: Field.Close); Strategy.Add(symbol, new ITrendStrategy(priceIdentity, ITrendPeriod, Tolerance, RevertPCT)); // Equally weighted portfolio. //ShareSize.Add(symbol, (maxLeverage * (1 - leverageBuffer)) / Symbols.Count()); ShareSize.Add(symbol, .58m); #region Logging stuff - Initializing Stock Logging stockLogging.Add(new StringBuilder()); stockLogging[i].AppendLine("Counter, Time, Close, ITrend, Trigger," + "Momentum, EntryPrice, Signal," + "TriggerCrossOverITrend, TriggerCrossUnderITrend, ExitFromLong, ExitFromShort," + "StateFromStrategy, StateFromPorfolio, Portfolio Value"); i++; #endregion Logging stuff - Initializing Stock Logging } }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { #region logging var algoname = this.GetType().Name + " UseSig=" + LiveSignalIndex; mylog.Debug(algoname); mylog.Debug(ondataheader); dailylog.Debug(algoname); dailylog.Debug(dailyheader); _transactions = new List <OrderTransaction>(); _proformatransactions = new List <OrderTransaction>(); string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } #endregion //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(_portfolioAmount); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); // Indicators Price = new RollingWindow <IndicatorDataPoint>(14); // The price history // ITrend trend = new InstantaneousTrend(7); trendHistory = new RollingWindow <IndicatorDataPoint>(14); //_ticketsQueue = new ConcurrentQueue<OrderTicket>(); _ticketsQueue = new List <OrderTicket>(); //sim = new BrokerSimulator(this); #region lists signalInfos.Add(new SignalInfo { Id = 0, Name = "Minutes_015", IsActive = true, SignalJson = string.Empty, Value = OrderSignal.doNothing, InternalState = string.Empty, SignalType = typeof(Sig9) }); signalInfos.Add(new SignalInfo { Id = 1, Name = "Minutes_001", IsActive = true, SignalJson = string.Empty, Value = OrderSignal.doNothing, InternalState = string.Empty, SignalType = typeof(Sig9) }); //foreach (SignalInfo s in signalInfos) //{ // s.IsActive = false; // if (s.Id == LiveSignalIndex) // { // s.IsActive = true; // } //} #endregion // define our 15 minute consolidator //var fifteenMinuteConsolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(15)); // if we want to make decisions every 15 minutes as well, we can add an event handler // to the DataConsolidated event fifteenMinuteConsolidator.DataConsolidated += OnFiftenMinuteAAPL; trend15Min = new InstantaneousTrend(3); RegisterIndicator(symbol, trend15Min, fifteenMinuteConsolidator, Field.Close); //int fast = 15; //int slow = 30; //// define our EMA, we'll manually register this, so we aren't using the helper function 'EMA(...)' //var fastEmaOnFifteenMinuteBars = new ExponentialMovingAverage("AAPL_EMA15", fast); //var slowEmaOnFifteenMinuteBars = new ExponentialMovingAverage("AAPL_EMA30", slow); //// register our indicator and consolidator together. this will wire the consolidator up to receive //// data for the specified symbol, and also set up the indicator to receive its data from the consolidator //RegisterIndicator("AAPL", fastEmaOnFifteenMinuteBars, fifteenMinuteConsolidator, Field.Close); //RegisterIndicator("AAPL", slowEmaOnFifteenMinuteBars, fifteenMinuteConsolidator, Field.Close); // for use with Tradier. Default is IB. var security = Securities[symbol]; security.TransactionModel = new ConstantFeeTransactionModel(7.0m); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { symbol = new Symbol("NFLX"); #region "Read Symbols from File" /********************************************** * THIS SECTION IS FOR READING SYMBOLS FROM A FILE ************************************************/ //string symbols; Symbols = new List <Symbol>(); var filename = AssemblyLocator.ExecutingDirectory() + "symbols.txt"; using (StreamReader sr = new StreamReader(filename)) { string[] symbols = { }; var readLine = sr.ReadLine(); if (readLine != null) { symbols = readLine.Split(','); } foreach (string t in symbols) { Symbols.Add(new Symbol(t)); } sr.Close(); } // Make sure the list contains the static symbol //if (!Symbols.Contains(symbol)) //{ // Symbols.Add(symbol); //} #endregion #region logging var algoname = this.GetType().Name; mylog.Debug(algoname); StringBuilder sb = new StringBuilder(); foreach (var s in Symbols) { sb.Append(s.Value + ","); } mylog.Debug(ondataheader); dailylog.Debug(algoname + " " + sb.ToString()); dailylog.Debug(dailyheader); string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } #endregion //Initialize dates sd = Config.Get("start-date"); ed = Config.Get("end-date"); _startDate = new DateTime(Convert.ToInt32(sd.Substring(0, 4)), Convert.ToInt32(sd.Substring(4, 2)), Convert.ToInt32(sd.Substring(6, 2))); _endDate = new DateTime(Convert.ToInt32(ed.Substring(0, 4)), Convert.ToInt32(ed.Substring(4, 2)), Convert.ToInt32(ed.Substring(6, 2))); SetStartDate(_startDate); SetEndDate(_endDate); SetCash(_portfolioAmount); SetBenchmark(symbol); foreach (string sym in Symbols) { AddSecurity(SecurityType.Equity, sym); } }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { #region logging var algoname = this.GetType().Name; mylog.Debug(algoname); ondataheader += _scig5C.GetNames(); mylog.Debug(ondataheader); dailylog.Debug(algoname); dailylog.Debug(dailyheader); _transactions = new List <OrderTransaction>(); _proformatransactions = new List <OrderTransaction>(); string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } #endregion //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(_portfolioAmount); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Daily); // Indicators Price = new RollingWindow <IndicatorDataPoint>(14); // The price history // ITrend trend = new InstantaneousTrend(7); trendHistory = new RollingWindow <IndicatorDataPoint>(14); _ticketsQueue = new List <OrderTicket>(); #region lists sigDictionary = new Dictionary <int, ISigSerializable>(); signalInfos.Add(new SignalInfo { Id = 0, Name = "Minutes_001", IsActive = true, SignalJson = string.Empty, Value = OrderSignal.doNothing, InternalState = string.Empty, SignalType = typeof(Sig9) }); //foreach (SignalInfo s in signalInfos) //{ // s.IsActive = false; // if (s.Id == LiveSignalIndex) // { // s.IsActive = true; // } //} #endregion // for use with Tradier. Default is IB. //var security = Securities[symbol]; //security.TransactionModel = new ConstantFeeTransactionModel(1.0m); }
//private string sig7comment; //private TradeBarConsolidator fifteenMinuteConsolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(15)); //private InstantaneousTrend trend15Min; //private bool CanMakeTrade = true; //private bool MinuteDataActivated = false; #endregion /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { #region logging var algoname = this.GetType().Name + " UseSig=" + LiveSignalIndex; mylog.Debug(algoname); mylog.Debug(ondataheader); dailylog.Debug(algoname); dailylog.Debug(dailyheader); _proformatransactions = new List <OrderTransaction>(); string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv"; if (File.Exists(filepath)) { File.Delete(filepath); } #endregion //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(_portfolioAmount); symbol = new Symbol("AAPL"); #region "Read Symbols from File" /********************************************** * THIS SECTION IS FOR READING SYMBOLS FROM A FILE ************************************************/ string symbols; var filename = AssemblyLocator.ExecutingDirectory() + "symbols.txt"; using (StreamReader sr = new StreamReader(filename)) { symbols = sr.ReadLine(); sr.Close(); } //symbol = new Symbol(symbols); #endregion minuteReturns.AppendFormat("{0},{1}", symbol, _startDate.ToShortDateString()); minuteHeader.AppendFormat("Symbol,Date"); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); // Indicators Price = new RollingWindow <IndicatorDataPoint>(14); // The price history // ITrend trend = new InstantaneousTrend("Main", 7, .24m); _orderTransactionProcessor = new OrderTransactionProcessor(); _transactions = new List <OrderTransaction>(); _ticketsQueue = new List <OrderTicket>(); #region ITrend iTrendSignal = new ITrendSignal(7); LastOrderSent.Add(symbol, OrderSignal.doNothing); #endregion #region lists signalInfos.Add(new SignalInfo { Id = 0, Name = "Minutes_001", IsActive = true, SignalJson = string.Empty, Value = OrderSignal.doNothing, InternalState = string.Empty, SignalType = typeof(Sig9) }); //signalInfos.Add(new SignalInfo //{ // Id = 1, // Name = "ITrend", // IsActive = true, // SignalJson = string.Empty, // Value = OrderSignal.doNothing, // InternalState = string.Empty, // SignalType = typeof(ITrendSignal) //}); //foreach (SignalInfo s in signalInfos) //{ // s.IsActive = false; // if (s.Id == LiveSignalIndex) // { // s.IsActive = true; // } //} #endregion #region "15 Minute" // define our 15 minute consolidator //var fifteenMinuteConsolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(15)); // if we want to make decisions every 15 minutes as well, we can add an event handler // to the DataConsolidated event //fifteenMinuteConsolidator.DataConsolidated += OnFiftenMinuteAAPL; //trend15Min = new InstantaneousTrend(3); //RegisterIndicator(symbol, trend15Min, fifteenMinuteConsolidator, Field.Close); //int fast = 15; //int slow = 30; //// define our EMA, we'll manually register this, so we aren't using the helper function 'EMA(...)' //var fastEmaOnFifteenMinuteBars = new ExponentialMovingAverage("AAPL_EMA15", fast); //var slowEmaOnFifteenMinuteBars = new ExponentialMovingAverage("AAPL_EMA30", slow); //// register our indicator and consolidator together. this will wire the consolidator up to receive //// data for the specified symbol, and also set up the indicator to receive its data from the consolidator //RegisterIndicator("AAPL", fastEmaOnFifteenMinuteBars, fifteenMinuteConsolidator, Field.Close); //RegisterIndicator("AAPL", slowEmaOnFifteenMinuteBars, fifteenMinuteConsolidator, Field.Close); #endregion // for use with Tradier. Default is IB. //var security = Securities[symbol]; //security.TransactionModel = new ConstantFeeTransactionModel(1.0m); }