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


C# API.Bar类代码示例

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


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

示例1: GetEffectiveAllowedSlippage

        internal double GetEffectiveAllowedSlippage(Bar bar)
        {
            if (Instrument.Type != InstrumentType.Stock)
                return 0;

            if (TargetOrderType == OrderType.Market)
                return 0;

            double timeDifferenceInSessionClose = GetSecondsLeftInSessionEnd(bar);
            double returnValue = EffectiveMaxAllowedSlippage;

            double differencePer30Minutes = (EffectiveMaxAllowedSlippage - EffectiveMinAllowedSlippage) / 12;

            double timeDifferenceInMinutes = timeDifferenceInSessionClose / 60;
            int halfHourPeriodsLeft = Convert.ToInt32(Math.Floor(timeDifferenceInMinutes / 30));

            if (halfHourPeriodsLeft > 12)
                halfHourPeriodsLeft = 12;
            if (halfHourPeriodsLeft < 0)
                halfHourPeriodsLeft = 0;

            returnValue = EffectiveMaxAllowedSlippage - (differencePer30Minutes * halfHourPeriodsLeft);

            LoggingUtility.WriteDebug(LoggingConfig,
                                      string.Format(
                                          "Calculated allowed slippage: {0}. [Min: {1}. Max: {2}. Half Hour Period {3}]",
                                          returnValue,
                                          EffectiveMinAllowedSlippage,
                                          EffectiveMaxAllowedSlippage,
                                          halfHourPeriodsLeft));

            return returnValue;
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:33,代码来源:BaseStrategy.PriceHandling.Methods.cs

示例2: HandleOrderTriggered

        protected override void HandleOrderTriggered(Bar bar, double targetPrice)
        {
            double targetQuantity = 0;

            // While closing sometimes it places duplicate orders which triggers
            // unwanted reverse positions

            RefreshOpenQuantity(true);

            if (GetAbsoluteOpenQuantity() <= 0)
                // This means the order was already processed by other thread
                return;

            targetQuantity = GetTargetQuantity();

            if (targetPrice <= 0 || targetQuantity <= 0)
                throw new ApplicationException(
                    string.Format("Invalid price of quantity calculated. Price {0:c}, Qty {1}", targetPrice,
                                  targetQuantity));

            string orderName = GetAutoPlacedOrderName(TargetOrderType, EffectiveOrderSide, "Auto-Closed",
                                                      Instrument.Symbol, EffectiveOrderRetriesConsumed, IbBrokerAccountNumber);

            base.PlaceTargetOrder(targetQuantity,
                                  targetPrice,
                                  orderName);

            LoggingUtility.LogOrder(LoggingConfig, orderName, EffectiveOrderSide, targetQuantity, targetPrice, EffectiveOrderRetriesConsumed);
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:29,代码来源:BaseClosingStrategy.cs

示例3: OnBarOpen

        public override void OnBarOpen(Bar bar)
        {
            try
            {
                if (!IsItOkToHandleBar(bar))
                {
                    return;
                }

                LoggingUtility.WriteTraceFormat(this, "OnBarOpen. {0}", bar);

                if (bar.Size == PeriodConstants.PERIOD_DAILY)
                {
                    // Since we will like to capture any gaps in the current day
                    // open and corresponding effects of ATR calculations
                    OnBar(bar);
                }
                else if (bar.BeginTime >= CurrentStartOfSessionTime)
                {
                    //EvaluateIndicatorsAtBeginningOfSession();

                    OnBar(bar);

                }

                base.OnBarOpen(bar);

            }
            catch (Exception ex)
            {
                LoggingUtility.WriteError(this, ex, "Error in OnBarOpen");
            }
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:33,代码来源:BaseStrategy.EventProcessing.cs

示例4: LogCurrentBarArrival

 internal static void LogCurrentBarArrival(LoggingConfig config, Bar bar)
 {
     if (config.IsDebugEnabled)
     {
         string message = string.Format("Bar with begin time {0} arrived: {1}", bar.BeginTime, bar);
         WriteDebug(config, message);
     }
 }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:8,代码来源:LoggingUtility.cs

示例5:

		public override double this [Bar bar]
		{
			get
			{
				this.Init();
				return base[bar];
			}
		}
开发者ID:heber,项目名称:FreeOQ,代码行数:8,代码来源:UserIndicator.cs

示例6: LogOkToTriggerOrder

 internal static void LogOkToTriggerOrder(LoggingConfig config, Bar bar)
 {
     if (config.IsInfoEnabled)
     {
         string message = string.Format("It is OK to trigger the trade @ bar: {0}", bar);
         Console.WriteLine();
         WriteInfo(config, message);
     }
 }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:9,代码来源:LoggingUtility.cs

示例7: OnBar

        public override void OnBar(Bar bar)
        {
            DateTime time = Clock.Now;
            int dateTime = time.Hour * 10000 + time.Minute * 100 + time.Second;

            if (dateTime > closeTime)
            {
                ClosePosition("T|尾盘平仓");
                return;
            }

            if (86400 == bar.Size)
            {
                return;
            }

            if (double.IsNaN(UpLine))
                return;

            UpSeries.Add(bar.DateTime, UpLine);
            DownSeries.Add(bar.DateTime, DownLine);
            RangeSeries.Add(bar.DateTime, Range);

            if (Mode == StrategyMode.Simulation)
            {
                // 从模拟切换实盘时用
                //return;
            }

            if (HasPosition)
            {
                if (Position.Amount < 0
                  && bar.Close > UpLine)
                {
                    ClosePosition("T|反手");
                    Buy(Qty, "O|");
                }
                if (Position.Amount > 0
                  && bar.Close < DownLine)
                {
                    ClosePosition("T|反手");
                    Sell(Qty, "O|");
                }
            }
            else
            {
                if (bar.Close > UpLine)
                {
                    Buy(Qty, "O|");
                }
                else if (bar.Close < DownLine)
                {
                    Sell(Qty, "O|");
                }
            }
        }
开发者ID:qianweiqiang,项目名称:OpenQuant,代码行数:56,代码来源:DualThrust_OpenRange_code.cs

示例8: OnBar

        public override void OnBar(Bar bar)
        {
            if (bStopStrategy)
            {
                Console.WriteLine("OnBar");
                StopStrategy();
            }

            Console.WriteLine(bar);
        }
开发者ID:ForTrade,项目名称:OpenQuant,代码行数:10,代码来源:Comfirm_code.cs

示例9: HandleBarOpen

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bar"></param>
        protected override void HandleBarOpen(Bar bar)
        {
            if (IsItTimeToTrigger(bar, false))
            {
                if (stopPrice.HasValue)
                {
                    double lastClosePrice = bar.Close;

                    if (StopPriceManager.IsEntryStopPriceMet(lastClosePrice, stopPrice.Value, OrderSide))
                    {
                        LoggingUtility.LogCurrentBarArrival(LoggingConfig, bar);

                        PriceCalculator priceCalc = new PriceCalculator(LoggingConfig);
                        double targetPrice = priceCalc.CalculateSlippageAdjustedPrice(new PriceCalculatorInput()
                                                                                                {
                                                                                                    AllowedSlippage = AllowedSlippage,
                                                                                                    Atr = GetAtrValue(Instrument, AtrPeriod, triggerTime.Value),
                                                                                                    CurrentBar = bar,
                                                                                                    PreviousBar = GetPreviousBar(Instrument, bar, PeriodConstants.PERIOD_MINUTE),
                                                                                                    OrderSide = OrderSide
                                                                                                });

                        double targetQuantity = new QuantityCalculator(LoggingConfig).Calculate(new QuantityCalculatorInput()
                                                                                 {
                                                                                     MaxPortfolioRisk = MaxPortfolioRisk,
                                                                                     MaxPositionRisk = MaxPositionRisk,
                                                                                     NumberOfPositions = NumberOfPositions,
                                                                                     PortfolioAmt = PortfolioAmount,
                                                                                     PortfolioAllocationPercentage = PortfolioAllocationPercentage,
                                                                                     PositionSizePercentage = PositionSizePercentage,
                                                                                     RoundLots = RoundLots,
                                                                                     StopPercentage = StopPercentage,
                                                                                     TargetPrice = targetPrice
                                                                                 });

                        targetPrice = priceCalc.RoundPrice(targetPrice, Instrument);

                        if (targetPrice <= 0 || targetQuantity <= 0)
                            throw new ApplicationException(string.Format("Invalid price of quantity calculated. Price {0:c}, Qty {1}", targetPrice, targetQuantity));

                        string orderName = GetAutoPlacedOrderName(OrderSide, string.Format("Auto-Open Stop Order @ {0:c}", stopPrice.Value), Instrument.Symbol);

                        strategyOrder = CreateOrder(OrderSide, targetQuantity, orderName, targetPrice);

                        LoggingUtility.LogOrder(LoggingConfig, orderName, OrderSide, targetQuantity, targetPrice, retryCount);

                        if (AutoSubmit)
                            strategyOrder.Send();
                    }
                }

            }
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:57,代码来源:BaseStopOpeningStrategy.cs

示例10: HandleBarOpen

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bar"></param>
        protected virtual void HandleBarOpen(Bar bar)
        {
            if (RetryOrder(bar, HandleStrategyStart))
            {
                LoggingUtility.LogRetryOrder(LoggingConfig, bar, retryCount);
            }

            if (IsItTimeToTrigger(bar, true))
            {
                PriceCalculator priceCalc = new PriceCalculator(LoggingConfig);
                QuantityCalculator qtyCalc = new QuantityCalculator(LoggingConfig);

                double targetPrice = priceCalc.Calculate(new PriceCalculatorInput()
                                                                   {
                                                                       CurrentBar = Bar,
                                                                       PreviousBar = GetPreviousBar(Instrument, bar, PeriodConstants.PERIOD_MINUTE),
                                                                       Atr = GetAtrValue(Instrument, AtrPeriod, triggerTime.Value),
                                                                       AllowedSlippage = AllowedSlippage,
                                                                       FavorableGap = FavorableGap,
                                                                       FavorableGapAllowedSlippage = FavorableGapAllowedSlippage,
                                                                       UnfavorableGap = UnfavorableGap,
                                                                       UnfavorableGapAllowedSlippage = UnfavorableGapAllowedSlippage,
                                                                       OrderSide = OrderSide
                                                                   });

                double targetQuantity = qtyCalc.Calculate(new QuantityCalculatorInput()
                                                                       {
                                                                           NumberOfPositions = NumberOfPositions,
                                                                           PortfolioAmt = PortfolioAmount,
                                                                           PortfolioAllocationPercentage = PortfolioAllocationPercentage,
                                                                           MaxPortfolioRisk = MaxPortfolioRisk,
                                                                           MaxPositionRisk = MaxPositionRisk,
                                                                           RoundLots = RoundLots,
                                                                           TargetPrice = targetPrice,
                                                                           StopPercentage = StopPercentage,
                                                                           PositionSizePercentage = PositionSizePercentage
                                                                       });

                targetPrice = priceCalc.RoundPrice(targetPrice, Instrument);

                if (targetPrice <= 0 || targetQuantity <= 0)
                    throw new ApplicationException(string.Format("Invalid price of quantity calculated. Price {0:c}, Qty {1}", targetPrice, targetQuantity));

                string orderName = GetAutoPlacedOrderName(OrderSide, "Auto-Opened", Instrument.Symbol);

                strategyOrder = CreateOrder(OrderSide, targetQuantity, orderName, targetPrice);

                LoggingUtility.LogOrder(LoggingConfig, orderName, OrderSide, targetQuantity, targetPrice, retryCount);

                if (AutoSubmit)
                    strategyOrder.Send();
            }
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:57,代码来源:BaseOpeningStrategy.cs

示例11: ReloadDailyData

        /*
        protected void ReloadDailyData()
        {
            DateTime start = DateTime.Now;
            DailyBarSeries = GetHistoricalBars("IB", Instrument, DateTime.Now.AddDays(-60), DateTime.Now, PeriodConstants.PERIOD_DAILY);
            DateTime end = DateTime.Now;

            LoggingUtility.WriteDebug(LoggingConfig, string.Format("Took {0}ms to retrieve data from IB for daily data", end.Subtract(start).TotalMilliseconds));

            start = DateTime.Now;
            foreach (Bar currentBar in DailyBarSeries)
            {
                Bars.Add(currentBar);
                if (PersistHistoricalData)
                    DataManager.Add(Instrument, currentBar);
            }
            end = DateTime.Now;

            LoggingUtility.WriteVerbose(LoggingConfig, string.Format("Took {0}ms to load data into memory for daily data", end.Subtract(start).TotalMilliseconds));
        }*/
        protected Bar GetPreviousBar(Bar bar, int period)
        {
            Bar retVal = null;
            BarSeries barsToUse = null;

            bool isSessionOpenBar = bar.IsSessionOpenBar(Instrument.Type);
            bool isDailyPeriod = period == PeriodConstants.PERIOD_DAILY;

            if (isDailyPeriod)
                return GetPreviousDayBar();

            barsToUse = MinutelyBarSeries;

            if (barsToUse.Count > 0)
            {
                int idx = 0;
                bool found = false;

                while (!found && idx <= barsToUse.Count - 1)
                {
                    Bar prevBar = barsToUse.Ago(idx);
                    if ((prevBar.EndTime <= bar.BeginTime) && prevBar.IsWithinRegularTradingHours(Instrument.Type))
                    {
                        if (isSessionOpenBar || isDailyPeriod)
                        {
                            found = DateTime.Today.Subtract(prevBar.BeginTime.Date).TotalDays >= 1;
                            if (!found && DateTime.Now.IsPastRegularTradingHours(Instrument.Type))
                                found = DateTime.Today.Subtract(prevBar.BeginTime.Date).TotalDays >= 0;
                        }
                        else
                        {
                            found = true;
                        }
                    }

                    if (found)
                        retVal = prevBar;
                    else
                        idx++;
                }
            }

            if (retVal == null)
                throw new ApplicationException(string.Format("Count not retreive a period {0} bar to {1}. If it is due to exchange holidays - then set the 'DaysToGoBackForMinutelyData' parameter to fetch more data.", period, bar));

            LoggingUtility.WriteInfo(LoggingConfig, string.Format("Previous closing bar was {0}", retVal));

            return retVal;
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:69,代码来源:BaseStrategy.DataHandling.cs

示例12: ProcessAndPlaceOrder

        private void ProcessAndPlaceOrder(Bar bar)
        {
            double targetPrice = GetTargetPrice(bar);

            EffectiveLastOrderDateTime = DateTime.Now;
            EffectiveLastOrderPrice = targetPrice;

            EffectiveOrderRetriesConsumed++;

            UpdateRetrialStopPrice(bar);

            SetParamsForRetrialOrder();

            HandleOrderTriggered(bar, targetPrice);
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:15,代码来源:BaseStrategy.OrderHandling.cs

示例13: HandleOrderTriggered

        protected override void HandleOrderTriggered(Bar bar, double targetPrice)
        {
            double targetQuantity = GetTargetQuantity(targetPrice);

            if (targetPrice <= 0 || targetQuantity <= 0)
                throw new ApplicationException(string.Format("Invalid price of quantity calculated. Price {0:c}, Qty {1}", targetPrice, targetQuantity));

            string orderName = GetAutoPlacedOrderName(TargetOrderType, EffectiveOrderSide, "Auto-Opened", Instrument.Symbol, EffectiveOrderRetriesConsumed, IbBrokerAccountNumber);

            base.PlaceTargetOrder(targetQuantity,
                                  targetPrice,
                                  orderName);

            LoggingUtility.LogOrder(LoggingConfig, orderName, OrderSide, targetQuantity, targetPrice, EffectiveOrderRetriesConsumed);
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:15,代码来源:BaseOpeningStrategy.cs

示例14: OnBar

        public override void OnBar(Bar bar)
        {
            if (bar.Size == 86400)
                return;

            if (lbd.Count < 1 || dbbu.Count < 1)
                return;

            int lookBackDaysInt = (int)lbd.Last;
            int nEnd = bars86400.Count - 1;
            int nBegin = nEnd - lookBackDays + 1;

            double buyPoint = bars86400.HighestHigh(nBegin, nEnd);
            double sellPoint = bars86400.LowestLow(nBegin, nEnd);
            double longLiqPoint = dbbu.SMA.Last;
            double shortLiqPoint = dbbu.SMA.Last;
            double upBand = dbbu.Last;
            double dnBand = dbbu.BBL.Last;

            upBandSeries.Add(bar.DateTime, upBand);
            dnBandSeries.Add(bar.DateTime, dnBand);
            buyPointSeries.Add(bar.DateTime, buyPoint);
            sellPointSeries.Add(bar.DateTime, sellPoint);

            //  下面代码可能有问题
            if (HasPosition)
            {
                if (Position.Amount > 0 && Bar.Close < longLiqPoint)
                {
                    ClosePosition("T|");
                }
                if (Position.Amount < 0 && Bar.Close > shortLiqPoint)
                {
                    ClosePosition("T|");
                }
            }
            else
            {
                if (Bar.Close > upBand)// && Bar.Close >= buyPoint
                {
                    Buy(Qty, "O|");
                }
                if (Bar.Close < dnBand)// && Bar.Close <= sellPoint
                {
                    Sell(Qty, "O|");
                }
            }
        }
开发者ID:qianweiqiang,项目名称:OpenQuant,代码行数:48,代码来源:DynamicBreakOut2_code.cs

示例15: GetSecondsLeftInSessionEnd

        public double GetSecondsLeftInSessionEnd(Bar bar)
        {
            double timeDifferenceInSessionClose = 0;

            if (bar.BeginTime.IsWithinRegularTradingHours(Instrument.Type)
                && bar.BeginTime >= EffectiveStartOfSessionTime)
            {
                timeDifferenceInSessionClose = Math.Abs((new DateTime(ValidityTriggerDate.Date.Year,
                                                                      ValidityTriggerDate.Date.Month,
                                                                      ValidityTriggerDate.Date.Day)
                                                            .AddSeconds(PstSessionTimeConstants.StockExchangeEndTimeSeconds)
                                                            .Subtract(bar.BeginTime)).TotalSeconds);
            }

            return timeDifferenceInSessionClose;
        }
开发者ID:aggarwalmanuj,项目名称:open-quant,代码行数:16,代码来源:BaseStrategy.Public.Methods.cs


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