示例#1
0
        private void createFifteenMinutesSourceFrom(ISecurity original)
        {
            ISecurity fifteenMinutesSource = original.CompressTo(
                new TSLab.DataSource.Interval(15, DataIntervals.MINUTE)
                );

            IDictionary <string, Bar> newSourceBars =
                new Dictionary <string, Bar>(fifteenMinutesSource.Bars.Count);

            // convert to source bars
            foreach (Bar bar in fifteenMinutesSource.Bars)
            {
                var key = period.keyFromTime(bar.Date);

                if (!newSourceBars.ContainsKey(key))
                {
                    newSourceBars.Add(key, bar);
                }
            }

            this.compressedSource = newSourceBars;
            this.first            = original.Bars[0].Date;
            this.last             = original.Bars[original.Bars.Count - 1].Date;
            this.compressed       = fifteenMinutesSource;
        }
示例#2
0
        private void createDailySourceFrom(ISecurity original)
        {
            ISecurity daySource = original.CompressTo(
                new TSLab.DataSource.Interval(1, DataIntervals.DAYS)
                );

            IDictionary <string, Bar> newSourceBars =
                new Dictionary <string, Bar>(daySource.Bars.Count);

            // convert to source bars
            int day = original.Bars[0].Date.Day;

            int dayBarsIndex = 0;

            for (int i = 0; i < original.Bars.Count; i++)
            {
                if (day != original.Bars[i].Date.Day)
                {
                    ++dayBarsIndex;
                    day = original.Bars[i].Date.Day;
                }

                string key = period.keyFromTime(daySource.Bars[dayBarsIndex].Date);

                if (!newSourceBars.ContainsKey(key))
                {
                    newSourceBars.Add(key, daySource.Bars[dayBarsIndex]);
                }
            }

            this.compressedSource = newSourceBars;
            this.first            = original.Bars[0].Date;
            this.last             = original.Bars[original.Bars.Count - 1].Date;
        }
示例#3
0
        private void createHourlySourceFrom(ISecurity original)
        {
            ISecurity hourSource = original.CompressTo(
                new TSLab.DataSource.Interval(60, DataIntervals.MINUTE)
                );

            IDictionary <string, Bar> newSourceBars =
                new Dictionary <string, Bar>(hourSource.Bars.Count);

            // convert to source bars
            int hour = original.Bars[0].Date.Hour;

            int hourBarsIndex = 0;

            for (int i = 0; i < original.Bars.Count; i++)
            {
                if (hour != original.Bars[i].Date.Hour)
                {
                    ++hourBarsIndex;
                    hour = original.Bars[i].Date.Hour;
                }

                string key = period.keyFromTime(hourSource.Bars[hourBarsIndex].Date);

                if (!newSourceBars.ContainsKey(key))
                {
                    newSourceBars.Add(key, hourSource.Bars[hourBarsIndex]);
                }
            }

            this.compressedSource = newSourceBars;
            this.first            = original.Bars[0].Date;
            this.last             = original.Bars[original.Bars.Count - 1].Date;
        }
示例#4
0
        public override IList <double> Execute(ISecurity source)
        {
            var sec2 = source.CompressTo(new Interval(Interval, source.IntervalBase));

            return(Context.GetData("ATRM", new[] { Period.ToString(), Interval.ToString(), PositiveSide.ToString() },
                                   () => sec2.Decompress(CalcATRM(Context, sec2.Bars, Period, new Interval(1, DataIntervals.DAYS),
                                                                  PositiveSide))));
        }
示例#5
0
        public virtual IList <double> Execute(ISecurity sec)
        {
            var sec2 = sec.CompressTo(Interval);
            var atrs = Context.GetData("ATR", new[] { Period.ToString(), Interval.ToString() },
                                       () => Series.AverageTrueRange(sec2.Bars, Period, Context));

            return(Context.GetData("NRTR",
                                   new[] { Period.ToString(), Coefficient.ToString(CultureInfo.InvariantCulture), Interval.ToString() },
                                   () => sec2.Decompress(NRTR(Context, sec2, atrs, Coefficient))));
        }
示例#6
0
        public ISecurity Execute(ISecurity source)
        {
            var interval = new Interval(Interval, source.IntervalBase);

            switch (interval.Base)
            {
            case DataIntervals.VOLUME:
                return(source.CompressToVolume(interval));

            case DataIntervals.PRICERANGE:
                return(source.CompressToPriceRange(interval));

            default:
                return(source.CompressTo(interval, Shift));
            }
        }
示例#7
0
        public static IList <double> CalcTrend(IContext ctx, ISecurity sec, int btInterval, int btPeriod,
                                               out IList <double> dcHigh, out IList <double> dcLow)
        {
            var btSec = sec.CompressTo(new Interval(btInterval, sec.IntervalBase));

            var btParameters = new[] { sec.CacheName, btInterval.ToString(), btPeriod.ToString() };
            var btHigh       = ctx.GetData("$btHigh", btParameters, () => Series.Highest(btSec.HighPrices, btPeriod));
            var btLow        = ctx.GetData("$btLow", btParameters, () => Series.Lowest(btSec.LowPrices, btPeriod));
            var btMiddle     = ctx.GetData("$btMiddle", btParameters,
                                           () => btHigh.Zip(btLow, (h, l) => (h + l) / 2).ToArray());

            var btTrend = (IReadOnlyList <double>)ctx.GetData("$btTrend", btParameters, () => btMiddle.Difference(ctx));

            IList <double> DcTrendMaker() =>
            Extensions.Decompress(sec.Bars, sec.IntervalInstance, (IReadOnlyList <double>)btMiddle, btTrend,
                                  btSec.IntervalInstance, btSec.Bars, ctx);

            var dcTrend = ctx.GetData("$dcTrend", btParameters, DcTrendMaker);

            dcHigh = ctx.GetData("$dcHigh", btParameters, () => btSec.Decompress(btHigh));
            dcLow  = ctx.GetData("$dcLow", btParameters, () => btSec.Decompress(btLow));
            return(dcTrend);
        }
示例#8
0
        public void Execute(IContext ctx, ISecurity sec)
        {
            // таймер для определения времени выполнения скрипта
            var sw = Stopwatch.StartNew();

            // проверка таймфрейма, используемого для торговли
            if (sec.IntervalInstance != new Interval(30, DataIntervals.MINUTE))
            {
                throw new InvalidOperationException($"Выбран не корректный интервал для торговли{sec.IntervalInstance}. Работать только на таймфрейме 30 минут!");
            }

            #region расчет индикаторов
            // канал Дончиана для основного таймфрема
            IList <double> upChannel = ctx.GetData("UpChannel",
                                                   new string[] { PeriodChannel.ToString() },
                                                   () => Series.Highest(sec.HighPrices, PeriodChannel));
            IList <double> downChannel = ctx.GetData("DownChannel",
                                                     new string[] { PeriodChannel.ToString() },
                                                     () => Series.Lowest(sec.LowPrices, PeriodChannel));

            // свечи дневного таймфрейма
            var daySec = sec.CompressTo(new Interval(1, DataIntervals.DAYS));

            // канал Дончиана для дневного таймфрейма
            IList <double> upChannelDay = ctx.GetData("UpChannelDay",
                                                      new string[] { PeriodChannelDay.ToString() },
                                                      () =>
            {
                var res = Series.Highest(daySec.HighPrices, PeriodChannelDay);
                return(daySec.Decompress(res));
            });

            IList <double> downChannelDay = ctx.GetData("DownChannelDay",
                                                        new string[] { PeriodChannelDay.ToString() },
                                                        () =>
            {
                var res = Series.Lowest(daySec.LowPrices, PeriodChannelDay);
                return(daySec.Decompress(res));
            });
            #endregion

            #region первый и последний бар для расчетов
            // первый бар, используемый для расчетов
            int startBar = Math.Max(PeriodChannel + 1, ctx.TradeFromBar);

            // значение счетчика баров, используемое для расчетов
            int barsCount = ctx.BarsCount;
            if (!ctx.IsLastBarClosed)
            {
                barsCount--;
            }
            #endregion

            // цены закрытия, используемые для торговли
            var closePrices = sec.ClosePrices;

            // вначале трейл-стоп отключен, он будет включен при открытии добавочной позиции LED
            var onTrailStop    = false;
            var trailEnable    = false;
            var lastTrailPrice = 0.0;

            #region Торговый цикл
            for (int i = startBar; i < barsCount; i++)
            {
                // базовая позиция LEB
                var lebPosition = sec.Positions.GetLastActiveForSignal("LEB", i);

                // добавочная позиция LEA, открывается при получении заданного уровня профита по базовой позиции
                var leaPosition = sec.Positions.GetLastActiveForSignal("LEA", i);

                // суммарно базовая и добавочная позиции - позиции, начинающиеся на "LA"
                var lePositions = sec.Positions.GetActiveForBar(i).Where(p => p.EntrySignalName.StartsWith("LE")).ToList();

                // добавочная позиция LED при выходе цены за дневной канал
                var ledPosition = sec.Positions.GetLastActiveForSignal("LED", i);

                // если нет базовой позиции, то выставляем условную заявку на её открытие
                if (lebPosition == null)
                {
                    sec.Positions.BuyIfGreater(i + 1, 1, upChannel[i], Slippage * sec.Tick, "LEB");
                    onTrailStop      = false;
                    trailEnable      = false;
                    lastTrailPrice   = 0.0;
                    OnStopLoss.Value = true;
                }
                else
                {
                    // если есть базовая позиция LEB, нет добавочной позиции LEA и нет добавочной позиции LED
                    // то выставляем условную заявку на открытие добавочной позиции LEA
                    if (leaPosition == null && ledPosition == null)
                    {
                        // цена входа в добавочную позицию
                        double entryPrice = lebPosition.EntryPrice * (1 + AddPositionLevel / 100.0);
                        sec.Positions.BuyIfGreater(i + 1, 1, entryPrice, Slippage, "LEA");
                    }

                    // если нет добавочной позиции LED и цена пробила дневной канал, то открываем добавочную позицию LED
                    if (ledPosition == null && (closePrices[i - 1] <= upChannelDay[i - 1]) && (closePrices[i] > upChannelDay[i]))
                    {
                        sec.Positions.BuyAtMarket(i + 1, 2, "LED");
                        OnStopLoss.Value = false;
                        onTrailStop      = true;
                    }

                    // выставляем стоп-лосс и тейк-профит для всех открытых позиций по средней цене входа,
                    // вычисляем среднюю цену входа в позицию
                    var avrEntryPrice = lePositions.GetAvgEntryPrice();

                    // стоп-лосc
                    foreach (var pos in lePositions)
                    {
                        if (OnStopLoss || OnBreakevenStop || onTrailStop)
                        {
                            // цена стоп-лосса
                            double stopPrice = (OnStopLoss)
                                ? (avrEntryPrice * (1 - StopLossPct / 100.0))
                                : 0;

                            // цена инструмента для перевода позиции в безубыток
                            double movePosBreakevenPrice = avrEntryPrice * (1 + ProfitForBreakevenPct / 100.0);

                            // цена стопа для перевода позиции в безубыток
                            double breakevenStopPrice = (OnBreakevenStop && closePrices[i] > movePosBreakevenPrice)
                                ? avrEntryPrice
                                : 0;

                            // цена трейл-стопа
                            double trailPrice = 0.0;
                            if (onTrailStop)
                            {
                                double onTrailStopPrice = avrEntryPrice * (1 + TrailStopEnablePct / 100.0);
                                if (closePrices[i] > onTrailStopPrice)
                                {
                                    trailEnable = true;
                                }

                                trailPrice = (trailEnable)
                                    ? sec.HighPrices[i] * (1 - TrailStopPct / 100.0)
                                    : avrEntryPrice * (1 - StopLossPct / 100.0);

                                trailPrice = lastTrailPrice = Math.Max(trailPrice, lastTrailPrice);
                            }

                            // берем максимальное значение стопа-лосса
                            stopPrice = Math.Max(stopPrice, breakevenStopPrice);
                            stopPrice = Math.Max(stopPrice, trailPrice);
                            stopPrice = Math.Max(stopPrice, pos.GetStop(i));
                            if (stopPrice != 0)
                            {
                                pos.CloseAtStop(i + 1, stopPrice, Slippage, "LXS");
                            }
                        }
                    }

                    // тейк-профит
                    if (OnTakeProfit)
                    {
                        double profitPrice = avrEntryPrice * (1 + TakeProfitPct / 100.0);
                        lePositions.ForEach(p => p.CloseAtProfit(i + 1, profitPrice, Slippage, "LXP"));
                    }
                }
            }
            #endregion

            #region Прорисовка графиков
            // Если идет процесс оптимизации, то графики рисовать не нужно, это замедляет работу
            if (ctx.IsOptimization)
            {
                return;
            }

            IGraphPane pane = ctx.First ?? ctx.CreateGraphPane("First", "First");

            Color colorCandle = ScriptColors.Black;
            pane.AddList(sec.Symbol,
                         sec,
                         CandleStyles.BAR_CANDLE,
                         colorCandle,
                         PaneSides.RIGHT);

            var lineUpChannel = pane.AddList(string.Format($"UpChannel ({PeriodChannel,0})"),
                                             upChannel,
                                             ListStyles.LINE,
                                             ScriptColors.Blue,
                                             LineStyles.SOLID,
                                             PaneSides.RIGHT);

            var lineDownChannel = pane.AddList(string.Format($"DwChannel ({PeriodChannel,0}"),
                                               downChannel,
                                               ListStyles.LINE,
                                               ScriptColors.Blue,
                                               LineStyles.SOLID,
                                               PaneSides.RIGHT);

            var lineUpChannelDay = pane.AddList(string.Format($"UpChannelDay ({PeriodChannelDay,0}"),
                                                upChannelDay,
                                                ListStyles.LINE,
                                                ScriptColors.Red,
                                                LineStyles.DASH,
                                                PaneSides.RIGHT);
            lineUpChannelDay.Thickness = 2;

            var lineDownChannelDay = pane.AddList(string.Format($"DwChannelDay ({PeriodChannelDay,0}"),
                                                  downChannelDay,
                                                  ListStyles.LINE,
                                                  ScriptColors.Red,
                                                  LineStyles.DASH,
                                                  PaneSides.RIGHT);
            lineDownChannelDay.Thickness = 2;

            #endregion

            #region 'Вывод в лог'
            // Вывод в лог времени выполнения скрипта только в режиме Лаборатория
            if (!ctx.Runtime.IsAgentMode)
            {
                ctx.Log($"Скрипт выполнен за время: {sw.Elapsed}", MessageType.Info, true);
            }
            #endregion
        }
        public IList <bool> Execute(ISecurity source)
        {
            ISecurity      dailySec    = source.CompressTo(Interval.D1, 0, 1440, 600);
            IList <double> highPrices  = dailySec.GetHighPrices(this.Context);
            IList <double> lowPrices   = dailySec.GetLowPrices(this.Context);
            IList <double> closePrices = dailySec.GetClosePrices(this.Context);
            int            count1      = source.Bars.Count;
            int            count2      = dailySec.Bars.Count;
            IList <double> doubleList1 = (IList <double>) new double[count2];
            IList <double> doubleList2 = (IList <double>) new double[count2];
            IList <double> candles1    = (IList <double>) new double[count2];
            IList <double> candles2    = (IList <double>) new double[count2];
            IList <double> candles3    = (IList <double>) new double[count2];
            IList <double> data1       = this.Context.GetData("ATR", new string[1]
            {
                this.ParPeriod.ToString()
            }, (CacheObjectMaker <IList <double> >)(() => Series.AverageTrueRange(dailySec.Bars, this.ParPeriod)));
            IList <double> data2 = this.Context.GetData("EMA", new string[1]
            {
                this.ParPeriod.ToString()
            }, (CacheObjectMaker <IList <double> >)(() => Series.EMA(dailySec.ClosePrices, this.ParPeriod)));
            IList <double> doubleList3 = (IList <double>) new double[count1];
            IList <double> doubleList4 = (IList <double>) new double[count1];
            IList <double> doubleList5 = (IList <double>) new double[count1];
            IList <bool>   boolList1   = (IList <bool>) new bool[count1];
            IList <bool>   boolList2   = (IList <bool>) new bool[count1];
            IList <bool>   boolList3   = (IList <bool>) new bool[count1];

            for (int index = 1; index < count2; ++index)
            {
                candles1[index] = 0.0;
                candles2[index] = 0.0;
                if (highPrices[index] > highPrices[index - 1])
                {
                    candles1[index] = highPrices[index] - highPrices[index - 1];
                }
                if (lowPrices[index] < lowPrices[index - 1])
                {
                    candles2[index] = lowPrices[index - 1] - lowPrices[index];
                }
                if (candles1[index] > candles2[index])
                {
                    candles2[index] = 0.0;
                }
                else if (candles2[index] > candles1[index])
                {
                    candles1[index] = 0.0;
                }
                else if (candles1[index] == candles2[index])
                {
                    candles1[index] = 0.0;
                    candles2[index] = 0.0;
                }
            }
            IList <double> doubleList6 = Series.EMA(candles1, this.ParPeriod);
            IList <double> doubleList7 = Series.EMA(candles2, this.ParPeriod);

            for (int index = 0; index < count2; ++index)
            {
                doubleList6[index] = data1[index] == 0.0 ? 0.0 : doubleList6[index] / data1[index];
                doubleList7[index] = data1[index] == 0.0 ? 0.0 : doubleList7[index] / data1[index];
                candles3[index]    = doubleList6[index] != 0.0 || doubleList7[index] != 0.0 ? Math.Abs(doubleList6[index] - doubleList7[index]) / (doubleList6[index] + doubleList7[index]) * 100.0 : 0.0;
            }
            IList <double> doubleList8 = Series.EMA(candles3, this.ParPeriod);
            int            index1      = 0;

            for (int index2 = 0; index2 < count1; ++index2)
            {
                DateTime date1 = source.Bars[index2].Date;
                DateTime date2 = date1.Date;
                boolList1[index2] = false;
                boolList2[index2] = false;
                while (true)
                {
                    int num;
                    if (index1 < count2)
                    {
                        date1 = dailySec.Bars[index1].Date;
                        num   = date1.Date < date2 ? 1 : 0;
                    }
                    else
                    {
                        num = 0;
                    }
                    if (num != 0)
                    {
                        doubleList3[index2] = doubleList8[index1];
                        doubleList4[index2] = data2[index1];
                        doubleList5[index2] = closePrices[index1];
                        if ((uint)index1 > 0U)
                        {
                            if (doubleList8[index1] > doubleList8[index1 - 1])
                            {
                                boolList1[index2] = true;
                            }
                            else if (doubleList8[index1] < doubleList8[index1 - 1])
                            {
                                boolList2[index2] = true;
                            }
                        }
                        else
                        {
                            boolList1[index2] = false;
                            boolList2[index2] = false;
                        }
                        ++index1;
                    }
                    else
                    {
                        break;
                    }
                }
                int num1;
                if (index2 + 1 < count1)
                {
                    date1 = source.Bars[index2 + 1].Date;
                    if (date1.Date == date2)
                    {
                        num1 = 1;
                        goto label_33;
                    }
                }
                num1 = index1 == count2 ? 1 : 0;
label_33:
                if (num1 != 0)
                {
                    --index1;
                }
                if (index1 <= 0)
                {
                    index1 = 0;
                    doubleList3[index2] = doubleList8[index1];
                    doubleList4[index2] = data2[index1];
                    doubleList5[index2] = closePrices[index1];
                    boolList1[index2]   = false;
                    boolList2[index2]   = false;
                }
            }
            for (int index2 = 0; index2 < count1; ++index2)
            {
                if (this.ParTrendUp && !this.ParFlet && !this.ParTrendDn)
                {
                    bool ResADX = doubleList5[index2] > doubleList4[index2] && doubleList3[index2] > this.KoefADXD1;
                    int  num    = this.ParBolTrendUp ? 0 : (!this.ParMenTrendUp ? 1 : 0);
                    boolList3[index2] = num == 0 ? AdvFazyRynka2.GetResADX(this.ParBolTrendUp, this.ParMenTrendUp, ResADX, boolList1[index2], boolList2[index2]) : ResADX;
                }
                else if (!this.ParTrendUp && this.ParFlet && !this.ParTrendDn)
                {
                    bool ResADX = doubleList3[index2] < this.KoefADXD1;
                    int  num    = this.ParBolFlet ? 0 : (!this.ParMenFlet ? 1 : 0);
                    boolList3[index2] = num == 0 ? AdvFazyRynka2.GetResADX(this.ParBolFlet, this.ParMenFlet, ResADX, boolList1[index2], boolList2[index2]) : ResADX;
                }
                else if (!this.ParTrendUp && !this.ParFlet && this.ParTrendDn)
                {
                    bool ResADX = doubleList5[index2] < doubleList4[index2] && doubleList3[index2] > this.KoefADXD1;
                    int  num    = this.ParBolTrendDn ? 0 : (!this.ParMenTrendDn ? 1 : 0);
                    boolList3[index2] = num == 0 ? AdvFazyRynka2.GetResADX(this.ParBolTrendDn, this.ParMenTrendDn, ResADX, boolList1[index2], boolList2[index2]) : ResADX;
                }
                else if (this.ParTrendUp && this.ParFlet && !this.ParTrendDn)
                {
                    bool ResADX1 = doubleList5[index2] > doubleList4[index2] && doubleList3[index2] > this.KoefADXD1;
                    bool flag1   = this.ParBolTrendUp || this.ParMenTrendUp ? AdvFazyRynka2.GetResADX(this.ParBolTrendUp, this.ParMenTrendUp, ResADX1, boolList1[index2], boolList2[index2]) : ResADX1;
                    bool ResADX2 = doubleList3[index2] < this.KoefADXD1;
                    bool flag2   = this.ParBolFlet || this.ParMenFlet ? AdvFazyRynka2.GetResADX(this.ParBolFlet, this.ParMenFlet, ResADX2, boolList1[index2], boolList2[index2]) : ResADX2;
                    boolList3[index2] = flag1 || flag2;
                }
                else if (this.ParTrendUp && !this.ParFlet && this.ParTrendDn)
                {
                    bool ResADX1 = doubleList5[index2] > doubleList4[index2] && doubleList3[index2] > this.KoefADXD1;
                    bool flag1   = this.ParBolTrendUp || this.ParMenTrendUp ? AdvFazyRynka2.GetResADX(this.ParBolTrendUp, this.ParMenTrendUp, ResADX1, boolList1[index2], boolList2[index2]) : ResADX1;
                    bool ResADX2 = doubleList5[index2] < doubleList4[index2] && doubleList3[index2] > this.KoefADXD1;
                    bool flag2   = this.ParBolTrendDn || this.ParMenTrendDn ? AdvFazyRynka2.GetResADX(this.ParBolTrendDn, this.ParMenTrendDn, ResADX2, boolList1[index2], boolList2[index2]) : ResADX2;
                    boolList3[index2] = flag1 || flag2;
                }
                else if (!this.ParTrendUp && this.ParFlet && this.ParTrendDn)
                {
                    bool ResADX1 = doubleList3[index2] < this.KoefADXD1;
                    bool flag1   = this.ParBolFlet || this.ParMenFlet ? AdvFazyRynka2.GetResADX(this.ParBolFlet, this.ParMenFlet, ResADX1, boolList1[index2], boolList2[index2]) : ResADX1;
                    bool ResADX2 = doubleList5[index2] < doubleList4[index2] && doubleList3[index2] > this.KoefADXD1;
                    bool flag2   = this.ParBolTrendDn || this.ParMenTrendDn ? AdvFazyRynka2.GetResADX(this.ParBolTrendDn, this.ParMenTrendDn, ResADX2, boolList1[index2], boolList2[index2]) : ResADX2;
                    boolList3[index2] = flag1 || flag2;
                }
                else if (this.ParTrendUp && this.ParFlet && this.ParTrendDn)
                {
                    bool ResADX1 = doubleList5[index2] > doubleList4[index2] && doubleList3[index2] > this.KoefADXD1;
                    bool flag1   = this.ParBolTrendUp || this.ParMenTrendUp ? AdvFazyRynka2.GetResADX(this.ParBolTrendUp, this.ParMenTrendUp, ResADX1, boolList1[index2], boolList2[index2]) : ResADX1;
                    bool ResADX2 = doubleList3[index2] < this.KoefADXD1;
                    bool flag2   = this.ParBolFlet || this.ParMenFlet ? AdvFazyRynka2.GetResADX(this.ParBolFlet, this.ParMenFlet, ResADX2, boolList1[index2], boolList2[index2]) : ResADX2;
                    bool ResADX3 = doubleList5[index2] < doubleList4[index2] && doubleList3[index2] > this.KoefADXD1;
                    bool flag3   = this.ParBolTrendDn || this.ParMenTrendDn ? AdvFazyRynka2.GetResADX(this.ParBolTrendDn, this.ParMenTrendDn, ResADX3, boolList1[index2], boolList2[index2]) : ResADX3;
                    boolList3[index2] = flag1 || flag2 || flag3;
                }
                else
                {
                    boolList3[index2] = false;
                }
            }
            return(boolList3);
        }
        public IList <double> Execute(ISecurity source1, ISecurity source2)
        {
            ISecurity      security1    = source1.CompressTo(Interval.D1, 0, 1440, 600);
            ISecurity      security2    = source2.CompressTo(Interval.D1, 0, 1440, 600);
            int            count1       = source1.Bars.Count;
            IList <double> closePrices1 = security1.GetClosePrices(this.Context);
            IList <double> closePrices2 = security2.GetClosePrices(this.Context);
            int            count2       = security1.Bars.Count;
            int            count3       = security2.Bars.Count;
            IList <double> doubleList   = (IList <double>)(this.Context?.GetArray <double>(count1) ?? new double[count1]);
            int            index1       = 0;

            for (int index2 = 0; index2 < count1; ++index2)
            {
                DateTime date1 = source1.Bars[index2].Date;
                DateTime date2 = date1.Date;
                while (true)
                {
                    int num;
                    if (index1 < count2)
                    {
                        date1 = security2.Bars[index1].Date;
                        num   = date1.Date < date2 ? 1 : 0;
                    }
                    else
                    {
                        num = 0;
                    }
                    if (num != 0)
                    {
                        doubleList[index2] = this.ParKoeff * closePrices1[index1] * this.ParLimitPrc * closePrices2[index1] / this.ParBaseGO / this.ParStepMin * (1.0 + closePrices2[index1] / this.ParCalcPrice);
                        ++index1;
                    }
                    else
                    {
                        break;
                    }
                }
                int num1;
                if (index2 + 1 < count1)
                {
                    date1 = source1.Bars[index2 + 1].Date;
                    if (date1.Date == date2)
                    {
                        num1 = 1;
                        goto label_11;
                    }
                }
                num1 = index1 == count2 ? 1 : 0;
label_11:
                if (num1 != 0)
                {
                    --index1;
                }
                if (index1 <= 0)
                {
                    index1             = 0;
                    doubleList[index2] = this.ParKoeff * closePrices1[index1] * this.ParLimitPrc * closePrices2[index1] / this.ParBaseGO / this.ParStepMin * (1.0 + closePrices2[index1] / this.ParCalcPrice);
                }
            }
            return(doubleList);
        }
示例#11
0
        public void Update(int barNumber)
        {
            security.BarNumber = barNumber;
            if (!flagToDebugLog)
            {
                var message = string.Format("ГО на покупку: {0}; ГО на продажу: {1}; Шаг цены: {2}", security.BuyDeposit, security.SellDeposit, security.StepPrice);
                logger.Log(message);
                flagToDebugLog = true;
            }

            var le      = sec.Positions.GetLastActiveForSignal("LE", barNumber);
            var subBars = security.GetBars(barNumber);

            var lastBar = security.LastBar;
            var lows    = pivotPointsIndicator.GetLows(barNumber);

            logger.Log("lows.Count = " + lows.Count.ToString());

            var lowsValues = new List <double>();

            foreach (var low in lows)
            {
                lowsValues.Add(low.Value);
            }

            var compressedSec   = sec.CompressTo(new Interval(30, DataIntervals.MINUTE));
            var filterBarNumber = compressedSecurity.GetBarCompressedNumberFromBarBaseNumber(barNumber);
            var lowsFilter      = pivotPointsIndicatorFilter.GetLows(filterBarNumber - 1);

            var valuesFilterLows = new List <double>();

            foreach (var low in lowsFilter)
            {
                valuesFilterLows.Add(low.Value);
            }

            var highsFilter = pivotPointsIndicatorFilter.GetHighs(filterBarNumber - 1);

            var valuesFilterHighs = new List <double>();

            foreach (var high in highsFilter)
            {
                valuesFilterHighs.Add(high.Value);
            }

            #region Long

            if (le == null)
            {
                if (!IsAboutEndOfSession(lastBar.Date))
                {
                    var message = string.Format("Номер бара = {0}; patternPivotPoints_1g2.Check(lowsValues) = {1}; patternPivotPoints_1g2g3.Check(valuesFilterLows) = {2}; " +
                                                "!patternPivotPoints_1l2.Check(valuesFilterHighs) = {3}", barNumber, patternPivotPoints_1g2.Check(lowsValues), patternPivotPoints_1g2g3.Check(valuesFilterLows),
                                                !patternPivotPoints_1l2.Check(valuesFilterHighs));
                    logger.Log(message);

                    message = string.Format("lowsValues.Count = {0}", lowsValues.Count);
                    logger.Log(message);

                    if (patternPivotPoints_1g2.Check(lowsValues) && patternPivotPoints_1g2g3.Check(valuesFilterLows) && !patternPivotPoints_1l2.Check(valuesFilterHighs))
                    {
                        logger.Log("Номер бара = " + barNumber.ToString() + "; Условие входа выполнено!");
                        if (barNumber == lows.Last().BarNumber + 3)
                        {
                            var lowLast   = lows.Last();
                            var stopPrice = lowLast.Value - 1;
                            var lastPrice = lastBar.Close;
                            if (lastPrice > stopPrice)
                            {
                                var contracts = localMoneyManager.GetQntContracts(lastPrice, stopPrice, PositionSide.Long);
                                //var contracts = 1;
                                sec.Positions.BuyAtMarket(barNumber + 1, contracts, "LE");
                                takeProfitLong = 0;
                            }
                        }
                    }
                }
            }
            else
            {
                if (lows.Count == 0)
                {
                    return;
                }
                var low = lows.Last();
                stopLossLong = low.Value - 1;
                var riskValue = le.EntryPrice - stopLossLong;

                if (takeProfitLong == 0)
                {
                    takeProfitLong = le.EntryPrice + riskValue * 2;
                }

                if (IsAboutEndOfSession(lastBar.Date))
                {
                    le.CloseAtMarket(barNumber + 1, "LXT");
                }

                le.CloseAtStop(barNumber + 1, stopLossLong, 100, "LXS");
                le.CloseAtProfit(barNumber + 1, takeProfitLong, 100, "LXP");
            }

            #endregion

            #region Short

            var se = sec.Positions.GetLastActiveForSignal("SE", barNumber);

            var highs       = pivotPointsIndicator.GetHighs(barNumber);
            var highsValues = new List <double>();
            foreach (var high in highs)
            {
                highsValues.Add(high.Value);
            }

            if (se == null)
            {
                if (!IsAboutEndOfSession(lastBar.Date))
                {
                    if (patternPivotPoints_1l2.Check(highsValues) && patternPivotPoints_1l2l3.Check(valuesFilterHighs) && !patternPivotPoints_1g2.Check(valuesFilterLows))
                    {
                        if (barNumber == highs.Last().BarNumber + 3)
                        {
                            var highLast  = highs.Last();
                            var stopPrice = highLast.Value + 1;
                            var lastPrice = lastBar.Close;
                            if (lastPrice < stopPrice)
                            {
                                var contracts = localMoneyManager.GetQntContracts(lastPrice, stopPrice, PositionSide.Short);
                                //var contracts = 1;
                                sec.Positions.SellAtMarket(barNumber + 1, contracts, "SE");
                                takeProfitShort = 0;
                            }
                        }
                    }
                }
            }
            else
            {
                if (highs.Count == 0)
                {
                    return;
                }

                var high = highs.Last();

                stopLossShort = high.Value + 1;
                var riskValue = stopLossShort - se.EntryPrice;

                if (takeProfitShort == 0)
                {
                    takeProfitShort = se.EntryPrice - riskValue * 2;
                }

                if (IsAboutEndOfSession(lastBar.Date))
                {
                    se.CloseAtMarket(barNumber + 1, "SXT");
                }

                se.CloseAtStop(barNumber + 1, stopLossShort, 100, "SXS");
                se.CloseAtProfit(barNumber + 1, takeProfitShort, 100, "SXP");
            }

            #endregion
        }
示例#12
0
 public ISecurity Execute(ISecurity source)
 {
     return(source.CompressTo(new Interval(Interval, DataIntervals.SECONDS)));
 }