当前位置: 首页>>代码示例>>C#>>正文


C# TradeBars类代码示例

本文整理汇总了C#中TradeBars的典型用法代码示例。如果您正苦于以下问题:C# TradeBars类的具体用法?C# TradeBars怎么用?C# TradeBars使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


TradeBars类属于命名空间,在下文中一共展示了TradeBars类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OnData

 public void OnData(TradeBars data)
 {
     if (!Portfolio.Invested)
     {
         SetHoldings("SPY", 1);
     }
 }
开发者ID:iorixyz,项目名称:Lean,代码行数:7,代码来源:CustomSecurityInitializerAlgorithm.cs

示例2: OnData

        public void OnData(TradeBars slice)
        {
            if (tradedToday.Date != Time.Date)
            {
                // leave a small buffer of cash
                var targetPercentage = 1m/(_todaysResponse.Securities.Count + 1);

                foreach (var target in _todaysResponse.Securities.Where(x => ValidSymbols.Contains(x.Ticker)))
                {
                    // rebalance portfolio to equal weights
                    SetHoldings(target.Ticker, targetPercentage);
                }

                tradedToday = Time.Date;
            }
            else
            {
                foreach (var target in _todaysResponse.Securities.Where(x => ValidSymbols.Contains(x.Ticker)))
                {
                    // set stop loss / profit orders
                    var security = Securities[target.Ticker];
                    if (!security.Invested) continue;

                    if (security.Close < target.StopLoss || security.Close > target.StopGain)
                    {
                        MarketOrder(target.Ticker, -security.Holdings.Quantity, true);
                    }
                }
            }
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:30,代码来源:EquitiesLabAlgorithm.cs

示例3: OnData

        public void OnData(TradeBars data)
        {
            if (rsi.IsReady && mom.IsReady)
            {
                try
                {
                    double signal = engine.DoInference((float)mom.Current.Value, (float)rsi.Current.Value);

                    if (!Portfolio.Invested)
                    {
                        if (signal > 30)
                        {
                            int quantity = Decimal.ToInt32(Portfolio.Cash / data[symbol].Price);
                            Buy(symbol, quantity);
                            Debug("Purchased Stock: " + quantity + " shares");
                        }
                    }
                    else
                    {
                        if (signal < -10)
                        {
                            int quantity = Portfolio[symbol].Quantity;
                            Sell(symbol, quantity);
                            Debug("Sold Stock: " + quantity + " shares");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug("Ex: " + ex.Message);
                    Debug("## rsi: " + rsi + " mom: " + mom);
                }
            }

        }
开发者ID:AlexCatarino,项目名称:Lean,代码行数:35,代码来源:FuzzyInferenceAlgorithm.cs

示例4: OnData

        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">Slice object keyed by symbol containing the stock data</param>
        public void OnData(TradeBars data)
        {
            if (lastAction.Date == Time.Date) return;

            if (!Portfolio.Invested)
            {
                SetHoldings("SPY", 0.5);
                lastAction = Time;
            }
            if (Time.DayOfWeek == DayOfWeek.Tuesday)
            {
                AddSecurity(SecurityType.Equity, "AIG");
                AddSecurity(SecurityType.Equity, "BAC");
                lastAction = Time;
            }
            else if (Time.DayOfWeek == DayOfWeek.Wednesday)
            {
                SetHoldings("AIG", .25);
                SetHoldings("BAC", .25);
                lastAction = Time;
            }
            else if (Time.DayOfWeek == DayOfWeek.Thursday)
            {
                RemoveSecurity("BAC");
                RemoveSecurity("AIG");
                lastAction = Time;
            }
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:32,代码来源:AddRemoveSecurityRegressionAlgorithm.cs

示例5: OnData

        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">TradeBars IDictionary object with your stock data</param>
        public void OnData(TradeBars data)
        {
            // only once per day
            if (previous.Date == data.Time.Date) return;

            if (!macd.IsReady) return;

            var holding = Portfolio[Symbol];

            decimal signalDeltaPercent = (macd - macd.Signal)/macd.Fast;
            var tolerance = 0.0025m;

            // if our macd is greater than our signal, then let's go long
            if (holding.Quantity <= 0 && signalDeltaPercent > tolerance) // 0.01%
            {
                // longterm says buy as well
                SetHoldings(Symbol, 1.0);
            }
            // of our macd is less than our signal, then let's go short
            else if (holding.Quantity >= 0 && signalDeltaPercent < -tolerance)
            {
                Liquidate(Symbol);
            }

            // plot both lines
            Plot("MACD", macd, macd.Signal);
            Plot(Symbol, "Open", data[Symbol].Open);
            Plot(Symbol, macd.Fast, macd.Slow);

            previous = data.Time;
        }
开发者ID:reddream,项目名称:Lean,代码行数:35,代码来源:MACDTrendAlgorithm.cs

示例6: OnData

        public void OnData(TradeBars data)
        {
            //First Order, Set 50% MSFT:
            if (!Portfolio.Invested)
            {
                SetHoldings("MSFT", 0.5); step++;
            }

            if (Time.Date == new DateTime(2013, 7, 1) && step == 1)
            {
                SetHoldings("MSFT", 1); step++;
            }

            if (Time.Date == new DateTime(2013, 8, 1) && step == 2)
            {
                SetHoldings("IBM", 1, true); step++;
            }

            if (Time.Date == new DateTime(2013, 9, 3) && step == 3)
            {
                SetHoldings("IBM", -0.5, true); step++;
            }

            if (Time.Date == new DateTime(2013, 10, 1) && step == 4)
            {
                SetHoldings("SPY", -0.5); step++;
            }

            if (Time.Date == new DateTime(2013, 11, 1) && step == 5)
            {
                SetHoldings("IBM", -0.5, true);  //Succeed.
                SetHoldings("SPY", -0.5); step++;
            }
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:34,代码来源:Test_SetHolding.cs

示例7: OnData

        public void OnData(TradeBars data)
        {
            bool isMarketAboutToClose = !theMarket.DateTimeIsOpen(Time.AddMinutes(10));
            OrderSignal actualOrder = OrderSignal.doNothing;

            int i = 0;
            foreach (string symbol in Symbols)
            {
                // Operate only if the market is open
                if (theMarket.DateTimeIsOpen(Time))
                {
                    // First check if there are some limit orders not filled yet.
                    if (Transactions.LastOrderId > 0)
                    {
                        CheckLimitOrderStatus(symbol);
                    }
                    // Check if the market is about to close and noOvernight is true.
                    if (noOvernight && isMarketAboutToClose)
                    {
                        actualOrder = ClosePositions(symbol);
                    }
                    else
                    {
                        // Now check if there is some signal and execute the strategy.
                        actualOrder = Strategy[symbol].ActualSignal;
                    }
                    ExecuteStrategy(symbol, actualOrder);
                }
            }
        }
开发者ID:bizcad,项目名称:LeanITrend,代码行数:30,代码来源:MultisymbolAlgorithm.cs

示例8: OnData

 /// <summary>
 /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
 /// </summary>
 /// <param name="data">TradeBars IDictionary object with your stock data</param>
 public void OnData(TradeBars data)
 {
     barcount++;
     var time = this.Time;
     hma7.Update(time, data[symbol].Close);
     hma14.Update(time, data[symbol].Close);
     hma28.Update(time, data[symbol].Close);
     Price.Add(idp(time, data[symbol].Close));
     UpdateInstantTrend(time);
     if (hma28.IsReady)
     {
         string logmsg = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10}",
             this.Time,
             barcount,
             data[symbol].Open,
             data[symbol].High,
             data[symbol].Low,
             data[symbol].Close,
             hma7.Current.Value,
             hma14.Current.Value,
             hma28.Current.Value,
             instantTrend[0].Value,
             "");
         mylog.Debug(logmsg);
     }
 }
开发者ID:bizcad,项目名称:LeanITrend,代码行数:30,代码来源:HullMovingAverageAlgorithm.cs

示例9: OnData

        public void OnData(TradeBars data)
        {
            if (Time - lastTradeTradeBars < tradeEvery) return;
            lastTradeTradeBars = Time;

            foreach (var kvp in data)
            {
                var symbol = kvp.Key;
                var bar = kvp.Value;

                if (bar.Time.RoundDown(bar.Period) != bar.Time)
                {
                    // only trade on new data
                    continue;
                }

                var holdings = Portfolio[symbol];
                if (!holdings.Invested)
                {
                    MarketOrder(symbol, 10);
                }
                else
                {
                    MarketOrder(symbol, -holdings.Quantity);
                }
            }
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:27,代码来源:RegressionAlgorithm.cs

示例10: OnData

        // Data Event Handler: New data arrives here. "TradeBars" type is a dictionary of strings so you can access it by symbol.
        public void OnData(TradeBars data)
        {
            if (_vix == 0) return;

            if (Time.Date > _lastRebalance.Date.AddDays(5))
            {
                //Rebalance every 5 days:
                _lastRebalance = Time;

                //Scale VIX fractionally 0-1 for 8-30.
                _deployedCapital = 1 - ((_vix - 8m) / 22m);

                //Don't allow negative scaling:
                if (_deployedCapital < -0.20m) _deployedCapital = -0.20m;

                //Fraction of capital preserved for bonds:
                _safeCapital = 1 - _deployedCapital;

                var tag = "Deployed: " + _deployedCapital.ToString("0.00") + " Safe: " + _safeCapital.ToString("0.00");

                SetHoldings("SPY", _deployedCapital, true, tag);
                SetHoldings("IBM", _safeCapital - 0.01m, false, tag);

                // if (_scale > 0)
                // {

                // }
                // else if (Portfolio.Invested)
                // {
                //     Liquidate();
                // }

            }
        }
开发者ID:kevinalexanderwong,项目名称:QCAlgorithm,代码行数:35,代码来源:8_Algorithm_Test_Mixed_Asset.cs

示例11: OnData

        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">TradeBars IDictionary object with your stock data</param>
        public void OnData(TradeBars data)
        {
            // wait for our entire ribbon to be ready
            if (!_ribbon.All(x => x.IsReady)) return;

            // only once per day
            if (_previous.Date == Time.Date) return;

            Plot(Symbol, "Price", data[Symbol].Price);
            Plot(Symbol, _ribbon);


            // check for a buy signal
            var values = _ribbon.Select(x => x.Current.Value).ToArray();

            var holding = Portfolio[Symbol];
            if (holding.Quantity <= 0 && IsAscending(values))
            {
                SetHoldings(Symbol, 1.0);
            }
            else if (holding.Quantity > 0 && IsDescending(values))
            {
                Liquidate(Symbol);
            }

            _previous = Time;
        }
开发者ID:skyfyl,项目名称:Lean,代码行数:31,代码来源:DisplacedMovingAverageRibbon.cs

示例12: OnData

        /// <summary>
        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
        /// </summary>
        /// <param name="data">TradeBars IDictionary object with your stock data</param>
        public void OnData(TradeBars data)
        {
            foreach (string symbol in symbols)
            {
                Strategy[symbol].Add(data[symbol].Price);
                if (Strategy[symbol].IsReady() && ActualEMA[symbol].IsReady)
                {
                    if (Strategy[symbol].Signal != 0)
                    {
                        decimal prevOscilator = Strategy[symbol].PreviousLaguerre - PreviousEMA[symbol];
                        decimal actualOscilator = Strategy[symbol].ActualLaguerre - ActualEMA[symbol];

                        bool longSignal = prevOscilator - tolerance > 0 && actualOscilator + tolerance < 0;
                        bool shortSignal = prevOscilator + tolerance < 0 && actualOscilator - tolerance > 0;

                        double signal = 0;
                        if (longSignal) signal = 1;
                        if (shortSignal) signal = -1;

                        if (!Portfolio[symbol].HoldStock)
                        {

                            SetHoldings(symbol, signal * 0.25);
                        }
                        else
                        {
                            if (Portfolio[symbol].IsLong && shortSignal) Liquidate(symbol);
                            if (Portfolio[symbol].IsShort && longSignal) Liquidate(symbol);
                        }
                    }
                }
                PreviousEMA[symbol] = ActualEMA[symbol].Current.Price;
            }
        }
开发者ID:bizcad,项目名称:LeanITrend,代码行数:38,代码来源:LaguerreEMA.cs

示例13: OnData

        /// <summary>
        /// On receiving new tradebar data it will be passed into this function. The general pattern is:
        /// "public void OnData( CustomType name ) {...s"
        /// </summary>
        /// <param name="data">TradeBars data type synchronized and pushed into this function. The tradebars are grouped in a dictionary.</param>
        public void OnData(TradeBars data)
        {
            //int x = 0;
            //int y = 10;
            //int z = y / x;

            //if (!Portfolio.Invested)
            //{
            //    SetHoldings("SPY", 1);
            //}

            if (!Portfolio.HoldStock && data.ContainsKey("SPY"))
            {
                Order("SPY", (int)Math.Floor(Portfolio.Cash / data["SPY"].Close));
                Debug("Debug Purchased MSFT: " + Portfolio.Cash);
            }

            if (Time.TimeOfDay.TotalSeconds % 10 == 0)
            {
                int i = Transactions.GetIncrementOrderId();
                var order = new Order("BTC", 10, OrderType.Market, Time, data["BTC"].Price, "Tag: Test");
                order.Status = OrderStatus.Filled;
                Transactions.Orders.AddOrUpdate<int, Order>(i, order);
            }
        }
开发者ID:kevinalexanderwong,项目名称:QCAlgorithm,代码行数:30,代码来源:1_Algorithm_BasicTemplate.cs

示例14: OnData

 /// <summary>
 /// On receiving new tradebar data it will be passed into this function. The general pattern is:
 /// "public void OnData( CustomType name ) {...s"
 /// </summary>
 /// <param name="data">TradeBars data type synchronized and pushed into this function. The tradebars are grouped in a dictionary.</param>
 public void OnData(TradeBars data)
 {
     if (!Portfolio.Invested)
     {
         Order("SPY", (int)(Portfolio.Cash / data["SPY"].Close));
     }
 }
开发者ID:nagyist,项目名称:QuantConnect-QCAlgorithm,代码行数:12,代码来源:1_Algorithm_BasicTemplate.cs

示例15: OnData

 /// <summary>
 /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
 /// </summary>
 /// <param name="data">TradeBars IDictionary object with your stock data</param>
 public void OnData(TradeBars data)
 {
     if (!Portfolio.Invested)
     {
         SetHoldings("SPY", .75); // leave some room lest we experience a margin call!
         Debug("Purchased Stock");
     }
 }
开发者ID:skyfyl,项目名称:Lean,代码行数:12,代码来源:BenchmarkAlgorithm.cs


注:本文中的TradeBars类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。