/// <summary>
 /// Calculates the bet size for this turn
 /// </summary>
 /// <param name="symbol">Symbol - the symbol to size the bet for</param>
 /// <param name="currentPrice">The current price of the security</param>
 /// <param name="transactionSize">The transaction size from the algorithm</param>
 /// <param name="signalInfo"></param>
 /// <param name="proformaProcessor"></param>
 /// <returns></returns>
 public decimal BetSize(Symbol symbol, decimal currentPrice, decimal transactionSize, SignalInfo signalInfo, OrderTransactionProcessor proformaProcessor)
 {
     decimal betsize = _algorithm.Portfolio[symbol].Invested ? Math.Abs(_algorithm.Portfolio[symbol].Quantity) : Math.Abs(transactionSize / currentPrice);
     if (betsize <= 10)
         betsize = 100;
     return betsize;
 }
 public void CanOpenPosition()
 {
     OrderTransaction trans = new OrderTransaction();
     trans.Symbol = "AAPL";
     trans.Direction = OrderDirection.Buy;
     OrderTransactionProcessor processor = new OrderTransactionProcessor();
     IPositionInventory openPosition = processor.OpenPosition(trans, PositionInventoryMethod.Fifo);
     processor.OpenPositions.Add(openPosition);
     Assert.IsTrue(processor.OpenPositions.Count > 0);
 }
Exemple #3
0
        /// <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(_startDate);
            SetEndDate(_endDate);
            SetCash(_portfolioAmount);

            symbol = new Symbol("AAPL");
            #region "Symbols"
            Symbols = new List <Symbol>();

            // Make sure the list contains the static symbol
            if (!Symbols.Contains(symbol))
            {
                Symbols.Add(symbol);
            }
            #endregion
            #region logging
            //mylog = Composer.Instance.GetExportedValueByTypeName<ILogHandler>("CustomFileLogHandler");
            //var algoname = this.GetType().Name;
            //mylog.Debug(algoname);
            //mylog.Debug(ondataheader);
            #endregion

            //Add as many securities as you like. All the data will be passed into the event handler:
            int id = 0;
            foreach (Symbol s in Symbols)
            {
                symbol = s;
                AddSecurity(SecurityType.Equity, symbol);
                signalInfos.Add(new SignalInfo()
                {
                    Id            = id++,
                    Name          = s.Permtick,
                    Symbol        = s,
                    SignalType    = typeof(Sig9),
                    Value         = OrderSignal.doNothing,
                    IsActive      = true,
                    Status        = OrderStatus.None,
                    SignalJson    = string.Empty,
                    InternalState = string.Empty,
                    Comment       = string.Empty,
                    nTrig         = 0,
                    Price         = new RollingWindow <IndicatorDataPoint>(14),
                    trend         = new InstantaneousTrend(s.Permtick, 7, .24m)
                });
            }

            _orderTransactionProcessor = new OrderTransactionProcessor();
            _transactions = new List <OrderTransaction>();

            // for use with Tradier. Default is IB.
            //var security = Securities[symbol];
            //security.TransactionModel = new ConstantFeeTransactionModel(1.0m);
        }
        public void MatchedAndUnmatchedTransactions()
        {
            string path = @"C:\Users\Nick\Documents\Visual Studio 2013\Projects\LeanITrend\Engine\bin\Debug\";
            string pathname = path + "transactions.csv";
            // This part of the test is just to look at the JsonConvert
            //string txt;
            //using (StreamReader sr = new StreamReader(pathname))
            //{
            //    txt = sr.ReadToEnd();
            //    sr.Close();
            //}
            //int index = txt.IndexOf("\r\n", System.StringComparison.Ordinal);
            //string titlesremoved = txt.Substring(index + 2);

            int counter = 0;
            List<OrderTransaction> list = new List<OrderTransaction>();

            OrderTransactionProcessor processor = new OrderTransactionProcessor();

            using (StreamReader sr = new StreamReader(pathname))
            {
                string line = sr.ReadLine();    // read the header but do not count it.

                while (!sr.EndOfStream)
                {
                    line = sr.ReadLine();
                    if (line != null && line.Contains("Symbol")) continue;
                    Assert.IsNotNull(line);
                    counter++;
                    OrderTransaction t = new OrderTransaction();
                    CsvSerializer.Deserialize(",",line,ref t,false);
                    list.Add(t);
                    processor.ProcessTransaction(t);
                }
                sr.Close();
            }
            var csv = CsvSerializer.Serialize(",", processor.Trades, true);
            using (StreamWriter sw = new StreamWriter(path + "Trades.csv"))
            {
                foreach (var s in csv)
                {
                    sw.WriteLine(s);
                }
                sw.Flush();
                sw.Close();
            }
            var x = JsonConvert.SerializeObject(list);
            Assert.IsTrue(counter == list.Count);
            Assert.IsTrue(processor.TotalProfit == 52.75m);
            Assert.IsTrue(processor.TotalCommission == -26m);
        }
        //private string sd;
        //private string ed;

        #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()
        {
            //string symbolstring = "WYNN";
            Symbols = new List<string>();
            #region "Read symbols from config"
            /**********************************************
             * This section reads a symbol list from Config.json
             *********************************************/
            string configsymbols = Config.Get("symbols");
            Symbols.Add(configsymbols);
            #endregion
            #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(t);
            //    }

            //    sr.Close();
            //}
            #endregion

            #region logging
            var algoname = this.GetType().Name;
            mylog.Debug(algoname);
            StringBuilder sb = new StringBuilder();
            foreach (var s in Symbols)
                sb.Append(s + ",");
            mylog.Debug(ondataheader);
            dailylog.Debug(algoname + " " + sb.ToString());
            //dailylog.Debug(dailyheader);
            _proformatransactions = new List<OrderTransaction>();
            string filepath = AssemblyLocator.ExecutingDirectory() + "transactions.csv";
            if (File.Exists(filepath)) File.Delete(filepath);
            #endregion


            //Initialize dates
            var sd = Config.Get("start-date");
            var 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);



            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:
            int id = 0;
            foreach (string symbolstring in Symbols)
                AddSecurity(SecurityType.Equity, symbolstring);
            var keys = Securities.Keys;

            foreach (Symbol s in Securities.Keys)
            {
                signalInfos.Add(new SignalInfo()
                {
                    Id = id++,
                    Name = s.Value,
                    Symbol = s,
                    SignalType = typeof(Sig9),
                    Value = OrderSignal.doNothing,
                    IsActive = true,
                    Status = OrderStatus.None,
                    SignalJson = string.Empty,
                    InternalState = string.Empty,
                    Comment = string.Empty,
                    nTrig = 0,
                    Price = new RollingWindow<IndicatorDataPoint>(14),
                    trend = new InstantaneousTrend(s.Value, 7, .24m),
                    mmi = new MarketMeanessIndex("MMI", 22)
                    
                });
            }

            _orderTransactionProcessor = new OrderTransactionProcessor();
            _transactions = new List<OrderTransaction>();


            #region ITrend
            //LastOrderSent.Add(symbol, OrderSignal.doNothing);
            #endregion

            //SetBenchmark(symbol);
            // for use with Tradier. Default is IB.
            //var security = Securities[symbol];
            //security.TransactionModel = new ConstantFeeTransactionModel(1.0m);

        }
Exemple #6
0
        /// <summary>
        /// Calculates the bet size for this turn
        /// </summary>
        /// <param name="symbol">Symbol - the symbol to size the bet for</param>
        /// <param name="currentPrice">The current price of the security</param>
        /// <param name="transactionSize">The transaction size from the algorithm</param>
        /// <param name="signalInfo"></param>
        /// <param name="proformaProcessor"></param>
        /// <returns></returns>
        public decimal BetSize(Symbol symbol, decimal currentPrice, decimal transactionSize, SignalInfo signalInfo, OrderTransactionProcessor proformaProcessor)
        {
            decimal betsize = _algorithm.Portfolio[symbol].Invested ? Math.Abs(_algorithm.Portfolio[symbol].Quantity) : Math.Abs(transactionSize / currentPrice);

            if (betsize <= 10)
            {
                betsize = 100;
            }
            return(betsize);
        }
 public void Setup()
 {
     p = new OrderTransactionProcessor();
 }
        /// <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);
        }
        //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);
        }
        public override void Initialize()
        {
            var mbs = Config.Get("size");
            minBarSize = Convert.ToDecimal(mbs);
            var tolerance = Config.Get("tolerance");
            barDifferenceTolerance = Convert.ToDecimal(tolerance);

            //Initialize dates
            var sd = Config.Get("start-date");
            var 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)));

            _symbolarray = Config.Get("symbols").Split(',');

            SetStartDate(_startDate);       // Set Start Date
            SetEndDate(_endDate);           // Set End Date
            SetCash(PortfolioAmount);       // Set Strategy Cash

            foreach (string t in _symbolarray)
            {
                _symbols.Add(t);
            }

            foreach (string symbol in _symbols)
            {
                AddSecurity(SecurityType.Equity, symbol, Resolution.Minute);
            }
            foreach (Symbol symbol in Portfolio.Keys)
            {
                Consolidator15Minute.DataConsolidated += On15Minute;
                SubscriptionManager.AddConsolidator(symbol, Consolidator15Minute);
                Strategies.Add(new TwoBarReversalStrategy(symbol, this, barDifferenceTolerance, minBarSize));
            }

            #region logging
            var algoname = GetType().Name;
            mylog.Debug(algoname);
            mylog.Debug(ondataheader);
            _orderTransactionProcessor = new OrderTransactionProcessor();
            _transactions = new List<OrderTransaction>();

            #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()
        {
            //Initialize dates
            SetStartDate(_startDate);
            SetEndDate(_endDate);
            SetCash(_portfolioAmount);

            symbol = new Symbol("AAPL");
            #region "Symbols"
            Symbols = new List<Symbol>();

            // Make sure the list contains the static symbol
            if (!Symbols.Contains(symbol))
            {
                Symbols.Add(symbol);
            }
            #endregion
            #region logging
            //mylog = Composer.Instance.GetExportedValueByTypeName<ILogHandler>("CustomFileLogHandler");
            //var algoname = this.GetType().Name;
            //mylog.Debug(algoname);
            //mylog.Debug(ondataheader);
            #endregion

            //Add as many securities as you like. All the data will be passed into the event handler:
            int id = 0;
            foreach (Symbol s in Symbols)
            {
                symbol = s;
                AddSecurity(SecurityType.Equity, symbol);
                signalInfos.Add(new SignalInfo()
                {
                    Id = id++,
                    Name = s.Permtick,
                    Symbol = s,
                    SignalType = typeof(Sig9),
                    Value = OrderSignal.doNothing,
                    IsActive = true,
                    Status = OrderStatus.None,
                    SignalJson = string.Empty,
                    InternalState = string.Empty,
                    Comment = string.Empty,
                    nTrig = 0,
                    Price = new RollingWindow<IndicatorDataPoint>(14),
                    trend = new InstantaneousTrend(s.Permtick, 7, .24m)
                });
            }

            _orderTransactionProcessor = new OrderTransactionProcessor();
            _transactions = new List<OrderTransaction>();

            // for use with Tradier. Default is IB.
            //var security = Securities[symbol];
            //security.TransactionModel = new ConstantFeeTransactionModel(1.0m);
        }