Beispiel #1
0
        private List <CandleData> GetCandles(BarSettings timeframe, string symbol, DateTime date, int candlesCount)
        {
            var startTime     = timeframe.GetDistanceTime(candlesCount, -1, date);
            var minuteCandles = AtomCandleStorage.Instance.GetAllMinuteCandles(symbol, startTime, date) ?? new List <CandleData>();

            var packer  = new CandlePacker(timeframe);
            var candles = new List <CandleData>();

            foreach (var minuteCandle in minuteCandles)
            {
                var candle = packer.UpdateCandle(minuteCandle);
                if (candle != null)
                {
                    candles.Add(candle);
                }
            }

            var tail = minuteCandles.Where(x => x.timeOpen > candles.Last().timeClose).ToArray();

            if (tail.Length > 0)
            {
                float open  = tail.First().open;
                float close = tail.Last().close;
                float high  = tail.Max(x => x.high);
                float low   = tail.Min(x => x.low);

                DateTime timeOpen  = tail.First().timeOpen;
                DateTime timeClose = tail.Last().timeClose;

                var currentCandel = new CandleData(open, high, low, close, timeOpen, timeClose);
                candles.Add(currentCandel);
            }

            return(candles);
        }
 public CandlePackerBidAsk()
 {
     packerBid = new CandlePacker(minuteTimeframe);
     packerAsk = new CandlePacker(minuteTimeframe);
 }
        public override void Initialize(BacktestServerProxy.RobotContext grobotContext)
        {
            base.Initialize(grobotContext);
            // проверка настроек графиков
            if (Graphics.Count == 0)
            {
                Logger.DebugFormat("OscillatorBasedRobot: настройки графиков не заданы");
                return;
            }
            if (Graphics.Count > 1)
            {
                Logger.DebugFormat("OscillatorBasedRobot: настройки графиков должны описывать один тикер / один ТФ");
                return;
            }
            ticker = Graphics[0].a;

            try
            {
                formulaResolver = new ExpressionResolver(indexFormula);
                formulaVariableNames = formulaResolver.GetVariableNames();
                lastBids = new Dictionary<string, float>();
                lastIndicies = new RestrictedQueue<float>(CandlesInIndexHistory);
                candles = new RestrictedQueue<CandleData>(CandlesInIndexHistory);
                packer = new CandlePacker(Graphics[0].b);
                indexPeaks = new List<Cortege3<float, int, float>>();
                tickerNames = DalSpot.Instance.GetTickerNames();
                randomGener = new Random(DateTime.Now.Millisecond);
                lastBidLists = new Dictionary<string, RestrictedQueue<float>>();
                // по каждой валютной паре найти макс. количество отсчетов (из формулы индекса)
                InitLastBidLists();
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("OscillatorBasedRobot: ошибка парсинга выражения \"{0}\": {1}",
                                   indexFormula, ex);
                formulaResolver = null;
            }
        }
        public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext)
        {
            base.Initialize(grobotContext, protectedContext);
            // проверка настроек графиков
            if (Graphics.Count == 0)
            {
                Logger.DebugFormat("Atracotes MTS: настройки графиков не заданы");
                return;
            }
            if (Graphics.Count > 1)
            {
                Logger.DebugFormat("Atracotes MTS: настройки графиков должны описывать один тикер / один ТФ");
                return;
            }
            ticker = Graphics[0].a;

            lastBids = new Dictionary<string, double>();

            foreach (var ind in IndexList)
            {
                ind.Initialize();
                ind.lastIndicies = new List<double>();
                ind.indexPeaks = new List<Cortege3<decimal, int, decimal>>();
            }

            candles = new List<CandleData>();
            packer = new CandlePacker(Graphics[0].b);

            var levels = FiboLevels.ToFloatArrayUniform();
            fiboLevels.Clear();
            foreach (var level in levels)
            {
                try
                {
                    fiboLevels.Add(level);
                }
                catch (FormatException)
                {

                }
            }

            tickerNames = DalSpot.Instance.GetTickerNames();
            randomGener = new Random(DateTime.Now.Millisecond);
            lastBidLists = new Dictionary<string, List<double>>();
            // по каждой валютной паре найти макс. количество отсчетов (из формулы индекса)
            InitLastBidLists();
            //RobotTradeState = TradeState.НетПозиций;
            stopsOnPositions = StopPositionsState.Незащищены;
            TerminalLog.Instance.SaveRobotLog("Atracotes MTS: RobotTradeState = " + RobotTradeState);
        }
        /// <summary>
        /// упаковать котировки в свечки
        /// </summary>
        public void UpdateCandles(List<CandleData> minuteCandles)
        {
            chart.StockSeries.Data.Clear();
            // родной интервал равен m1 - не производить никаких действий
            if (Timeframe.IsAtomic)
            {
                foreach (var candle in minuteCandles)
                    chart.StockSeries.Data.Candles.Add(new CandleData(candle));
                return;
            }

            // упаковать m1 в свечи нужного ТФ
            candlePacker = new CandlePacker(chart.Timeframe);
            foreach (var minuteCandle in minuteCandles)
            {
                var candle = candlePacker.UpdateCandle(minuteCandle);
                if (candle != null) chart.StockSeries.Data.Candles.Add(candle);
            }
            // добавить незавершенную свечу
            var shouldAdd = true;
            if (chart.StockSeries.Data.Candles.Count > 0)
                if (chart.StockSeries.Data.Candles[chart.StockSeries.Data.Candles.Count - 1].timeOpen ==
                    candlePacker.CurrentCandle.timeOpen) shouldAdd = false;
            if (shouldAdd && candlePacker.CurrentCandle != null)
                chart.StockSeries.Data.Candles.Add(candlePacker.CurrentCandle);
        }
Beispiel #6
0
 public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext)
 {
     base.Initialize(grobotContext, protectedContext);
     // проверка настроек графиков
     if (Graphics.Count == 0)
     {
         Logger.DebugFormat("StopRobot: настройки графиков не заданы");
         return;
     }
     if (Graphics.Count > 1)
     {
         Logger.DebugFormat("StopRobot: настройки графиков должны описывать один тикер / один ТФ");
         return;
     }
     ticker = Graphics[0].a;
     packer = new CandlePacker(Graphics[0].b);
 }
Beispiel #7
0
        public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContextx)
        {
            base.Initialize(grobotContext, protectedContextx);
            if (Graphics.Count == 0)
            {
                Logger.DebugFormat("RobotMA: настройки графиков не заданы");
                return;
            }
            if (Graphics.Count > 1)
            {
                Logger.DebugFormat("RobotMA: настройки графиков должны описывать один тикер / один ТФ");
                return;
            }
            packer = new CandlePacker(Graphics[0].b);
            ticker = Graphics[0].a;
            maDifSign = 0;
            queueSlow = new RestrictedQueue<float>(RangeSlowMA);
            queueFast = new RestrictedQueue<float>(RangeFastMA);

            virtualDeal = null;
            prevSign = 0;
            virtualResults = new RestrictedQueue<float>(PeriodVirtualResults);
        }
 public void Setup()
 {
     var barSettings = new BarSettings { Intervals = new List<int> { 60 }, Title = "H1" };
     packer = new CandlePacker(barSettings);
 }
Beispiel #9
0
        private List<CandleData> MakeCandlesFromM1(BarSettings timeframe, string ticker, DateTime timeStart)
        {
            var result = new List<CandleData>();
            var minutes = candles[barSettingsCodeM1][ticker];
            var packer = new CandlePacker(timeframe);

            foreach (var canM1 in minutes)
            {
                var candle = packer.UpdateCandle(canM1);
                if (candle != null)
                    result.Add(candle);
            }

            return result.Where(c => c.timeOpen >= timeStart).ToList();
        }
Beispiel #10
0
        public override void Initialize(BacktestServerProxy.RobotContext grobotContext, Contract.Util.BL.CurrentProtectedContext protectedContextx)
        {
            base.Initialize(grobotContext, protectedContextx);
            if (Graphics.Count == 0)
            {
                Logger.DebugFormat("RobotMA: настройки графиков не заданы");
                return;
            }
            if (Graphics.Count > 1)
            {
                Logger.DebugFormat("RobotMA: настройки графиков должны описывать один тикер / один ТФ");
                return;
            }
            packer = new CandlePacker(Graphics[0].b);
            ticker = Graphics[0].a;
            stopLoss = null;
            takeProfit = null;

            extremumRangeQueue = new RestrictedQueue<CandleData>(ExtremumRange * 2 + 1);
            extremumQueue = new RestrictedQueue<Cortege3<float, bool, DateTime>>(4);
        }
Beispiel #11
0
        public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext)
        {
            base.Initialize(grobotContext, protectedContext);
            // проверка настроек графиков
            if (Graphics.Count == 0)
            {
                Logger.DebugFormat("FiboLevelRobot: настройки графиков не заданы");
                return;
            }
            if (Graphics.Count > 1)
            {
                Logger.DebugFormat("FiboLevelRobot: настройки графиков должны описывать один тикер / один ТФ");
                return;
            }
            ticker = Graphics[0].a;
            timeframe = Graphics[0].b;
            packer = new CandlePacker(timeframe);
            // расчет вспомогательных переменных
            side = PriceB > PriceA ? 1 : PriceB < PriceA ? -1 : 0;

            minuteCandlesCount = 0;
            minuteCandlesBodiesSum = 0;
            lastBid = 0;
            timeOfLastCandle = new DateTime(1972, 1, 1);

            // получить категории торговых сигналов
            if (ShouldMakePresignals)
            {
                currentPresignalPrimeTimes = presignalMinutesToClose.ToList();
                var signals = grobotContext is BacktestServerProxy.RobotContextLive
                                  ? ((BacktestServerProxy.RobotContextLive)grobotContext).GetAuthoredTradeSignals()
                                  : new List<PaidService>();

                if (signals.Count > 0)
                {
                    var signal = signals[0];
                    if (signal != null)
                    {
                        authoredTradeSignalCategory = signal.Id;
                        Logger.InfoFormat("Робот {0} - отправляет сигналы {1} ({2})",
                            GetUniqueName(), authoredTradeSignalCategory, signal.Comment);
                    }
                }
            }

            // поставить на графике точечки
            AddRobotHintOnPriceUpdated("A", 0, priceA, TimeOfA);
            AddRobotHintOnPriceUpdated("B", 0, priceB, TimeOfB);
        }
Beispiel #12
0
 public CandlePackerBidAsk()
 {
     packerBid = new CandlePacker(minuteTimeframe);
     packerAsk = new CandlePacker(minuteTimeframe);
 }
Beispiel #13
0
        public void TestGetLastCandleClose()
        {
            packer = new CandlePacker(new BarSettings() { Intervals = new EditableList<int> { 5 } });

            DateTime candleOpenTime;
            int nextCandlePeriod;
            var time = new DateTime(2014, 6, 18, 9, 5, 0);
            var timeClose = packer.GetLastCandleClose(time, out candleOpenTime, out nextCandlePeriod);
            Assert.AreEqual(time, candleOpenTime, "GetLastCandleClose() - время начала свечи должно быть равно текущему");
            Assert.AreEqual(time.AddMinutes(5), timeClose, "GetLastCandleClose() - время закрытия свечи должно быть равно текущему + 5 минут");

            var timeShifted = new DateTime(2014, 6, 18, 9, 5, 0, 10, DateTimeKind.Unspecified);
            timeClose = packer.GetLastCandleClose(timeShifted, out candleOpenTime, out nextCandlePeriod);
            Assert.AreEqual(time, candleOpenTime, "GetLastCandleClose(+10ms) - время начала свечи должно быть равно текущему");
            Assert.AreEqual(time.AddMinutes(5), timeClose, "GetLastCandleClose(+10ms) - время закрытия свечи должно быть равно текущему + 5 минут");
        }
        public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext)
        {
            base.Initialize(grobotContext, protectedContext);
            // проверка настроек графиков
            if (Graphics.Count == 0)
            {
                Logger.DebugFormat("MultiIndexRobot: настройки графиков не заданы");
                return;
            }
            if (Graphics.Count > 1)
            {
                Logger.DebugFormat("MultiIndexRobot: настройки графиков должны описывать один тикер / один ТФ");
                return;
            }
            ticker = Graphics[0].a;

            lastBids = new Dictionary<string, double>();

            foreach (var ind in DiversToEnter)
            {
                ind.Initialize();
                ind.lastIndicies = new List<double>();
                ind.indexPeaks = new List<Cortege3<decimal, int, decimal>>();
            }

            foreach (var protectSets in DiversToProtect)
                foreach (var ind in protectSets.IndexList)
            {
                ind.Initialize();
                ind.lastIndicies = new List<double>();
                ind.indexPeaks = new List<Cortege3<decimal, int, decimal>>();
            }

            foreach (var filter in filters)
                filter.Initialize();

            candles = new List<CandleData>();//CandlesInIndexHistory);
            packer = new CandlePacker(Graphics[0].b);
            packerDiverProtect = diversToProtect.Count == 0
                                     ? null
                                     : diversToProtect.ToDictionary(d => d, d => new CandlePacker(d.timeframe));
            candles4Protect = diversToProtect.Count == 0
                                     ? null
                                     : diversToProtect.ToDictionary(d => d, d => new List<CandleData>());

            tickerNames = DalSpot.Instance.GetTickerNames();
            randomGener = new Random(DateTime.Now.Millisecond);
            lastBidLists = new Dictionary<string, List<double>>();
            // по каждой валютной паре найти макс. количество отсчетов (из формулы индекса)
            InitLastBidLists();

            if (CalcDealChainStat)
            {
                dealChainStat = new List<int>();
            }
        }
Beispiel #15
0
        private List<float> GetTargetCandlesLengths(int candleLength)
        {
            var candlesM1 = AtomCandleStorage.Instance.GetAllMinuteCandles(chart.Symbol);
            if (candlesM1.Count < candleLength * 50) return null;

            var packer = new CandlePacker(new BarSettings { Intervals = new List<int> { candleLength } });
            var lengths = new List<float>();
            foreach (var cm1 in candlesM1)
            {
                var candle = packer.UpdateCandle(cm1);
                if (candle != null)
                    lengths.Add((float)Math.Log(candle.close / candle.open));
            }

            return lengths;
        }
        public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext xprotectedContext)
        {
            base.Initialize(grobotContext, xprotectedContext);
            // проверка настроек графиков
            if (Graphics.Count == 0)
            {
                Logger.DebugFormat("MultiIndexRobot: настройки графиков не заданы");
                return;
            }
            if (Graphics.Count > 1)
            {
                Logger.DebugFormat("MultiIndexRobot: настройки графиков должны описывать один тикер / один ТФ");
                return;
            }
            ticker = Graphics[0].a;
            timeframe = Graphics[0].b;

            lastBids = new Dictionary<string, double>();

            foreach (var ind in IndexList)
            {
                ind.Initialize();
                ind.lastIndicies = new List<double>();
                ind.indexPeaks = new List<Cortege3<decimal, int, decimal>>();
            }

            candles = new List<CandleData>();
            packer = new CandlePacker(Graphics[0].b);
            tickerNames = DalSpot.Instance.GetTickerNames();
            randomGener = new Random(DateTime.Now.Millisecond);
            lastBidLists = new Dictionary<string, List<double>>();
            // по каждой валютной паре найти макс. количество отсчетов (из формулы индекса)
            InitLastBidLists();
        }
Beispiel #17
0
 public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext)
 {
     base.Initialize(grobotContext, protectedContext);
     // проверка настроек графиков
     if (Graphics.Count == 0)
     {
         Logger.DebugFormat("FibonacciRobot: настройки графиков не заданы");
         return;
     }
     if (Graphics.Count > 1)
     {
         Logger.DebugFormat("FibonacciRobot: настройки графиков должны описывать один тикер / один ТФ");
         return;
     }
     ticker = Graphics[0].a;
     packer = new CandlePacker(Graphics[0].b);
     candles = new List<CandleData>();
     pointPrice = 1M/DalSpot.Instance.GetPrecision10(ticker);
     //fiboDistanceAbs = FiboReachDistancePoint*pointPrice;
     markedZigZagPivots = new List<int>();
 }