/// <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() { //mylog.Debug(transheader); mylog.Debug("Mean Reversion Algorithm"); mylog.Debug(ondataheader); dailylog.Debug("Mean Reversion Algorithm"); dailylog.Debug(dailyheader); //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(22000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); Price = new RollingWindow <IndicatorDataPoint>(14); trendHistory = new RollingWindow <IndicatorDataPoint>(14); trend = new InstantaneousTrend(10); ema10 = new ExponentialMovingAverage(10); sma10 = new SimpleMovingAverage(10); madiff = new RollingWindow <IndicatorDataPoint>(390); stddev = new StandardDeviation(390); emaHistory = new RollingWindow <IndicatorDataPoint>(10); smaHistory = new RollingWindow <IndicatorDataPoint>(10); }
/// <summary> /// Prints the report heading /// </summary> public void ReportHeading(string heading) { _logHandler.Debug(heading); StringBuilder sb = new StringBuilder(); sb.Append(columnHeader); foreach (var item in ColumnList) { sb.Append(","); sb.Append(item.Key); } _logHandler.Debug(sb.ToString()); }
/// <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() { //Initialize dates SetStartDate(2015, 6, 15); SetEndDate(2015, 6, 15); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); #region "Init indicators" Price = new RollingWindow <IndicatorDataPoint>(samplesize); ema = new RollingWindow <IndicatorDataPoint>(samplesize); zema = new RollingWindow <IndicatorDataPoint>(samplesize); OptimalValue1 = new RollingWindow <IndicatorDataPoint>(samplesize); OmtimalValue2 = new RollingWindow <IndicatorDataPoint>(samplesize); OptimalTrackingFilter = new RollingWindow <IndicatorDataPoint>(samplesize); lambda = new RollingWindow <IndicatorDataPoint>(samplesize); alpha = new RollingWindow <IndicatorDataPoint>(samplesize); priceOptimalDiff = new RollingWindow <IndicatorDataPoint>(samplesize); priceOptimalSign = new RollingWindow <IndicatorDataPoint>(samplesize); priceOptimalCross = new RollingWindow <IndicatorDataPoint>(samplesize); fudge = new RollingWindow <IndicatorDataPoint>(samplesize); instantTrend = new RollingWindow <IndicatorDataPoint>(samplesize); instantTrendTrigger = new RollingWindow <IndicatorDataPoint>(samplesize); cyberCycle = new RollingWindow <IndicatorDataPoint>(samplesize); centerGravity = new RollingWindow <IndicatorDataPoint>(samplesize); cyberCycleSmooth = new RollingWindow <IndicatorDataPoint>(samplesize); rvi = new RelativeVigorIndex(8); rviHistory = new RollingWindow <IndicatorDataPoint>(samplesize); stochCenterGravityValue1 = new RollingWindow <IndicatorDataPoint>(8); stochCenterGravityValue2 = new RollingWindow <IndicatorDataPoint>(8); stochCyberCycleValue1 = new RollingWindow <IndicatorDataPoint>(8); stochCyberCycleValue2 = new RollingWindow <IndicatorDataPoint>(8); stochCyberCycleInverseFisher = new RollingWindow <IndicatorDataPoint>(8); stochCyberCycleFisher = new RollingWindow <IndicatorDataPoint>(8); stochRviHistoryValue1 = new RollingWindow <IndicatorDataPoint>(8); stochRviHistoryValue2 = new RollingWindow <IndicatorDataPoint>(8); ROC = new RateOfChange(4); maxCyberCycle = new Maximum(8); minCyberCycle = new Minimum(8); #endregion //mylog.Debug(transheader); mylog.Debug(ondataheader); string msg = "Security,Date,Day Profit,Day Fees, Day Net, Total Profit, Total Fees"; mylog.Debug(msg); mylog.Debug(tradeheader); }
/// <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 InstantTrendStrategy(symbol, 14, this); for (int i = 0; i < signals.Length; i++) { signals[i] = OrderSignal.doNothing; } _ticketsQueue = new ConcurrentQueue <OrderTicket>(); #region lists #endregion // for use with Tradier. Default is IB. //var security = Securities[symbol]; //security.TransactionModel = new ConstantFeeTransactionModel(1.0m); }
/// <summary> /// Write debug message to log /// </summary> /// <param name="logHandler"></param> /// <param name="text">Message</param> /// <param name="args">Arguments to format.</param> public static void Debug(this ILogHandler logHandler, string text, params object[] args) { if (logHandler == null) { throw new ArgumentNullException("logHandler", "Log Handler cannot be null"); } logHandler.Debug(string.Format(text, args)); }
public virtual UdpMessage ParseUdpReceiveResult(UdpReceiveResult result) { var message = result.ToUdpMessage(); if (Logger.IsDebugEnabled) { Logger.Debug(string.Format("RECEIVE {0}, PacketType {1}, Size {2}", message.RemoteEndPoint, message.PacketType, message.Message.Count())); } return(message); }
private decimal a = .05m; // used in instantTrend /// <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() { //mylog.Debug(transheader); mylog.Debug(ondataheader); //Initialize dates SetStartDate(2015, 5, 13); SetEndDate(2015, 5, 13); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); Price = new RollingWindow <IndicatorDataPoint>(14); hma7 = new HullMovingAverage("hma7", 7); hma14 = new HullMovingAverage("hma14", 14); hma28 = new HullMovingAverage("hma28", 28); instantTrend = new RollingWindow <IndicatorDataPoint>(7); }
/// <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); }
/// <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() { //mylog.Debug(transheader); mylog.Debug(ondataheader); //Initialize dates SetStartDate(2013, 10, 07); SetEndDate(2013, 10, 07); SetCash(25000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, _symbol, Resolution.Minute); maxHigh = new Maximum("MaxHigh", _period); minLow = new Minimum("MinLow", _period); value1 = new RollingWindow <IndicatorDataPoint>(_period); fish = new RollingWindow <IndicatorDataPoint>(_period); //wma = new LinearWeightedMovingAverage(5); // induces 2 bar lag //wwma = new RollingWindow<IndicatorDataPoint>(_period); //fishHigh = new Maximum("FishHigh", 400); //fishLow = new Minimum("FishLow", 400); fx = new FisherTransform(_symbol, _period); //fx = FT(_symbol, _period, Resolution.Minute); // Add a bars to initialize the RollingWindow value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); value1.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); fish.Add(new IndicatorDataPoint(DateTime.MinValue, 0m)); //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); //wwma.Add(new IndicatorDataPoint(DateTime.MinValue, .0001m)); }
/// <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() { //mylog.Debug(transheader); mylog.Debug(ondataheader); //Initialize dates SetStartDate(_startDate); SetEndDate(_endDate); SetCash(22000); //Add as many securities as you like. All the data will be passed into the event handler: AddSecurity(SecurityType.Equity, symbol, Resolution.Minute); Price = new RollingWindow <IndicatorDataPoint>(14); cycleSignal = new RollingWindow <IndicatorDataPoint>(14); cycle = new CyberCycle(7); Price = new RollingWindow <IndicatorDataPoint>(14); diff = new RollingWindow <IndicatorDataPoint>(20); standardDeviation = new StandardDeviation(30); fish = new InverseFisherTransform(10); fishHistory = new RollingWindow <IndicatorDataPoint>(7); fishDirectionHistory = new RollingWindow <IndicatorDataPoint>(7); }
/// <summary> /// Output to the console /// </summary> /// <param name="text">The message to show</param> /// <param name="level">debug level</param> public static void Debug(string text, int level = 1) { try { if (!_debuggingEnabled || level < _level) { return; } _logHandler.Debug(text); } catch (Exception err) { Console.WriteLine("Log.Debug(): Error writing debug: " + err.Message); } }
private void OnDataForSymbol(KeyValuePair <Symbol, TradeBar> data) { if (data.Key == "VIX") { vix = data.Value; } if (data.Key == new Symbol("SPY")) { wvfh.Update(data.Value); wvfl.Update(data.Value); ifwvfh.Update(wvfh.Current); ifwvfl.Update(wvfl.Current); ichi.Update(data.Value); iTrend.Update(new IndicatorDataPoint(data.Value.EndTime, data.Value.Close)); #region "biglog" if (!headingwritten) { StringBuilder sb = new StringBuilder(); sb.Append("Barcount, Symbol,EndTime,Volume,Open,High,Low,Close"); sb.Append(",EndTime"); sb.Append(",vix"); sb.Append(",iTrend"); sb.Append(",wvfh"); sb.Append(",fwvfh"); sb.Append(",wvfl"); sb.Append(",fwvfl"); sb.Append(",t1"); sb.Append(",k1"); sb.Append(",sa1"); sb.Append(",sb1"); sb.Append(",t5"); sb.Append(",k5"); sb.Append(",sa5"); sb.Append(",sb5"); sb.Append(",t10"); sb.Append(",k10"); sb.Append(",sa10"); sb.Append(",sb10"); mylog.Debug(sb.ToString()); headingwritten = true; } string logmsg = string.Format( "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19}" + ",{20},{21},{22},{23},{24},{25},{26},{27}" //,{28},{29} " //+ ",{30},{31},{32},{33}" , barcount, data.Key, data.Value.EndTime, data.Value.Volume, data.Value.Open, data.Value.High, data.Value.Low, data.Value.Close, data.Value.EndTime.ToShortTimeString(), vix.Close, iTrend.Current.Value, wvfh.Current.Value, ifwvfh.Current.Value * -1, wvfl.Current.Value, ifwvfl.Current.Value * -1, //data.Value.EndTime.ToShortTimeString(), //data.Value.Close, ichi.Tenkan.Current.Value, ichi.Kijun.Current.Value, ichi.SenkouA.Current.Value, ichi.SenkouB.Current.Value, //data.Value.EndTime.ToShortTimeString(), //data.Value.Close, ichi5.Tenkan.Current.Value, ichi5.Kijun.Current.Value, ichi5.SenkouA.Current.Value, ichi5.SenkouB.Current.Value, //data.Value.EndTime.ToShortTimeString(), //data.Value.Close, ichi10.Tenkan.Current.Value, ichi10.Kijun.Current.Value, ichi10.SenkouA.Current.Value, ichi10.SenkouB.Current.Value, "" ); mylog.Debug(logmsg); #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; mylog.Debug(algoname); mylog.Debug(ondataheader); dailylog.Debug(algoname); dailylog.Debug(dailyheader); _transactions = new List <OrderTransaction>(); var days = _endDate.Subtract(_startDate).TotalDays; MaxDailyProfit = new Maximum("MaxDailyProfit", (int)days); MinDailyProfit = new Minimum("MinDailyProfit", (int)days); #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); // Initialize the Symbol indexed dictionaries foreach (string s in Symbols) { AddSecurity(SecurityType.Equity, s, Resolution.Minute); Strategy.Add(symbol, new MultiITStrategy(s, ITrendPeriod, this)); Tickets.Add(s, new List <OrderTicket>()); // Equal portfolio shares for every stock. ShareSize.Add(s, (maxLeverage * (1 - leverageBuffer)) / Symbols.Count()); LastOrderSent.Add(s, OrderSignal.doNothing); #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 } // Indicators Price = new RollingWindow <IndicatorDataPoint>(14); // The price history // ITrend trend = new InstantaneousTrend("Main", 7, .25m); trendHistory = new RollingWindow <IndicatorDataPoint>(14); // The ITrendStrategy iTrendStrategy = new InstantTrendStrategy(symbol, 14, this); iTrendStrategy.ShouldSellOutAtEod = shouldSellOutAtEod; #region lists // Initialize the lists for the strategies trendList = new Dictionary <int, InstantaneousTrend>(); trendHistoryList = new Dictionary <int, RollingWindow <IndicatorDataPoint> >(); strategyList = new Dictionary <int, MultiITStrategy>(); entryPriceList = new Dictionary <int, decimal>(); int listIndex = 0; for (decimal d = .25m; d < .26m; d += .01m) { trendList.Add(listIndex, new InstantaneousTrend("ITrend_" + d, 7, d)); // eg ITrend.25, period 7, alpha .25 trendHistoryList.Add(listIndex, new RollingWindow <IndicatorDataPoint>(4)); strategyList.Add(listIndex, new MultiITStrategy(symbol, 7, this)); entryPriceList.Add(listIndex, 0); listIndex++; } #endregion #region Proforma _brokerSimulator = new BrokerSimulator(this); #endregion }
//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); }
/// <summary> /// Write debug message to log /// </summary> /// <param name="text">The debug text to log</param> public void Debug(string text) { WriteMessage(LogType.Debug, text); _fileLogger.Debug(text); }
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 } }
internal static void Debug(object message) => handler.Debug(message);
/// <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); }
/// <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 + " 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); }