Esempio n. 1
0
 public TradeSignalUpdate(int serviceId, string ticker, BarSettings timeframe, DateTime timeUpdated)
 {
     ServiceId = serviceId;
     Ticker = ticker;
     Timeframe = timeframe;
     TimeUpdated = timeUpdated;
 }
Esempio n. 2
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 DiversByTimeframe(DiversByTimeframe div)
 {
     timeframe = new BarSettings(div.timeframe);
     foreach (var ind in div.IndexList)
     {
         var cpy = new IndexDivergencyInfo(ind);
         indexList.Add(cpy);
     }
 }
        public string GetBarSettingsFriendlyName(BarSettings sets)
        {
            if (sets == null)
            {
                return(string.Empty);
            }
            var exists = barSettingsSeries.FirstOrDefault(bs => bs == sets);

            return(exists == null?sets.ToString() : exists.Title);
        }
        public void ReadSeriesFromXml()
        {
            var pathFile = string.Format("{0}\\{1}", ExecutablePath.ExecPath, BarSettingsFileName);
            var doc      = new XmlDocument();

            try
            {
                if (!File.Exists(pathFile))
                {
                    return;
                }
                doc.Load(pathFile);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("Ошибка загрузки данных BarSettings \"{0}\": {1}", pathFile, ex);
            }
            try
            {
                // разбираем xml
                var node = doc.SelectSingleNode("BarSettingsList");
                if (node != null)
                {
                    var nodes = node.SelectNodes("BarSettings");

                    if (nodes != null)
                    {
                        foreach (XmlElement item in nodes)
                        {
                            var bars = new BarSettings {
                                Title = item.Attributes["Title"].Value, IsUserDefined = true
                            };
                            try
                            {
                                bars.ReadFromTagString(item.InnerText, ";#");
                            }
                            catch
                            {
                                continue;
                            }

                            if (!barSettingsSeries.Any(s => s.Title == bars.Title))
                            {
                                barSettingsSeries.Add(bars);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("BarSettings.ReadSeriesFromXml error", ex);
            }
        }
Esempio n. 6
0
 public BarSettings(BarSettings settings)
 {
     Title = settings.Title;
     intervals = new List<int>();
     StartMinute = settings.StartMinute;
     foreach (var span in settings.Intervals)
     {
         intervals.Add(span);
     }
     IsUserDefined = false;
 }
Esempio n. 7
0
 public BarSettings(BarSettings settings)
 {
     Title       = settings.Title;
     intervals   = new List <int>();
     StartMinute = settings.StartMinute;
     foreach (var span in settings.Intervals)
     {
         intervals.Add(span);
     }
     IsUserDefined = false;
 }
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            es = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
            if (es == null) return value;

            bot = BarSettingsStorage.Instance.GetBarSettingsByName((string) value);
            // открыть модальный диалог выбора пары / ТФ
            var dlg = new TimeframeSettingsForm(bot);
            return dlg.ShowDialog() != DialogResult.OK ? value
                : BarSettingsStorage.Instance.GetBarSettingsFriendlyName(dlg.Timeframe);
        }
        public string GetBarSettingsFriendlyName(string timeframeString)
        {
            var sets = BarSettings.TryParseString(timeframeString);

            if (ReferenceEquals(sets, null))
            {
                return(timeframeString);
            }
            var exists = barSettingsSeries.FirstOrDefault(bs => bs.Equals(sets));

            return(!ReferenceEquals(exists, null) ? exists.Title : sets.ToString());
        }
Esempio n. 10
0
        /// <param name="isBuy">Side > 0 ? "BUY" : "SELL"</param>
        public Bitmap GetGraphSchematic(BarSettings timeframe, string symbol, DateTime dealDate)
        {
            var candlesCount = 15;
            var candles      = GetCandles(timeframe, symbol, dealDate, candlesCount);

            if (candles.Count == 0)
            {
                return(null);
            }

            return(DrawSchematic(candles, candlesCount));
        }
 private void BtnOkClick(object sender, EventArgs e)
 {
     var sets = BarSettingsStorage.Instance.GetBarSettingsByName(cbTimeframe.Text);
     if (sets == null)
     {
         MessageBox.Show(string.Format(Localizer.GetString("MessageUnableParseTimeframeStringFmt"),
                                       cbTimeframe.Text), Localizer.GetString("TitleError"),
                                       MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     Timeframe = sets;
     DialogResult = DialogResult.OK;
     Close();
 }
Esempio n. 12
0
        /// <param name="isBuy">Side > 0 ? "BUY" : "SELL"</param>
        public string SaveGraphToFile(string folderName, BarSettings timeframe, string symbol, bool isBuy, int candlesCount)
        {
            var tempFileName = Path.Combine(folderName, $"{symbol}.png");
            var candles      = GetCandles(timeframe, symbol, DateTime.Now, candlesCount);

            if (candles.Count == 0)
            {
                return(string.Empty);
            }

            using (var btm = GetGraphDefault(candles, isBuy, candlesCount))
                btm.Save(tempFileName, ImageFormat.Png);

            return(tempFileName);
        }
Esempio n. 13
0
        public MemoryStream GetGraphStream(BarSettings timeframe, string symbol, bool isBuy, int candlesCount)
        {
            var candles = GetCandles(timeframe, symbol, DateTime.Now, candlesCount);

            if (candles.Count == 0)
            {
                return(null);
            }

            var          bitmap       = GetGraphDefault(candles, isBuy, candlesCount);
            MemoryStream memoryStream = new MemoryStream();

            bitmap.Save(memoryStream, ImageFormat.Bmp);
            return(memoryStream);
        }
Esempio n. 14
0
 public bool Equals(BarSettings tf)
 {
     if (tf == null)
     {
         return(false);
     }
     if (StartMinute != tf.StartMinute)
     {
         return(false);
     }
     if (intervals.Count != tf.intervals.Count)
     {
         return(false);
     }
     for (var i = 0; i < intervals.Count; i++)
     {
         if (intervals[i] != tf.intervals[i])
         {
             return(false);
         }
     }
     return(true);
 }
        public void BuildSeries(ChartControl chart)
        {
            if (chart.Timeframe == previousTimeframe && !needRebuildLevels) return;
            previousTimeframe = chart.Timeframe;

            var candles = chart.StockSeries.Data.Candles;
            if (candles.Count == 0) return;

            // добавить данные об объемах
            BuildSeries();
            needRebuildLevels = false;
        }
Esempio n. 16
0
        private void SetupGrid()
        {
            var fontBold = new Font(Font, FontStyle.Bold);
            var blankAccountEventSettings = new AccountEventSettings();
            gridEvents.Columns.Add(new FastColumn(blankAccountEventSettings.Property(p => p.CodeName), Localizer.GetString("TitleEvent"))
                {
                    ColumnMinWidth = 60
                });
            gridEvents.Columns.Add(new FastColumn(blankAccountEventSettings.Property(p => p.ActionName), Localizer.GetString("TitleAction"))
                {
                    ColumnMinWidth = 60,
                    IsHyperlinkStyleColumn = true,
                    HyperlinkFontActive = fontBold,
                    HyperlinkActiveCursor = Cursors.Hand
                });

            foreach (var action in Enum.GetValues(typeof(AccountEventAction)).Cast<AccountEventAction>())
            {
                var item = contextMenuAction.Items.Add(EnumFriendlyName<AccountEventAction>.GetString(action));
                item.Tag = action;
                item.Click += ActionMenuItemClicked;
            }

            var blankBarSettings = new BarSettings();
            gridCandles.Columns.Add(new FastColumn(blankBarSettings.Property(p => p.Title), Localizer.GetString("TitleName")));
            gridCandles.Columns.Add(new FastColumn(blankBarSettings.Property(p => p.TimeDescription), Localizer.GetString("TitleIntervals")));

            var blankGridImageRecord = new GridImageRecord(string.Empty, null, null);
            gridTradeSettings.Columns.Add(new FastColumn(blankGridImageRecord.Property(p => p.Name), Localizer.GetString("TitleParameter"))
                {
                    SortOrder = FastColumnSort.Ascending,
                    ColumnMinWidth = 100
                });
            gridTradeSettings.Columns.Add(new FastColumn(blankGridImageRecord.Property(p => p.Name), "?")
            {
                ColumnWidth = 20,
                formatter = v => "?",
                IsHyperlinkStyleColumn = true,
                HyperlinkActiveCursor = Cursors.Hand,
                HyperlinkFontActive = fontBold,
                ColorHyperlinkTextActive = Color.Blue
            });
            gridTradeSettings.Columns.Add(new FastColumn(blankGridImageRecord.Property(p => p.ImageIndex), "*")
            {
                ColumnWidth = 23,
                IsHyperlinkStyleColumn = true,
                HyperlinkActiveCursor = Cursors.Hand,
                ImageList = imageListSetsGrid
            });
            gridTradeSettings.UserHitCell += GridTradeSettingsOnUserHitCell;
            // заполнить таблицу настроек
            var sets = new List<GridImageRecord>
                {
                    new GridImageRecord(Localizer.GetString("MessageQuotesConfirmOrder"),
                        val => { UserSettings.Instance.PromptTradeFromQuoteWindow = (bool) val; },
                        () => UserSettings.Instance.PromptTradeFromQuoteWindow)
                        {
                            BooleanValue = UserSettings.Instance.PromptTradeFromQuoteWindow
                        },
                    new GridImageRecord(Localizer.GetString("MessageQuotesConfirmOrder"),
                        val => { UserSettings.Instance.PromptFastButtonTrade = (bool) val; },
                        () => UserSettings.Instance.PromptFastButtonTrade)
                        {
                            BooleanValue = UserSettings.Instance.PromptFastButtonTrade
                        },
                    new GridImageRecord(Localizer.GetString("MessageInstantOrderPriceCheck"),
                        val => { UserSettings.Instance.CheckInstTradePrice = (bool) val; },
                        () => UserSettings.Instance.CheckInstTradePrice)
                        {
                            BooleanValue = UserSettings.Instance.CheckInstTradePrice
                        }
                };
            gridTradeSettings.CalcSetTableMinWidth();
            gridTradeSettings.DataBind(sets);
            gridTradeSettings.CheckSize();
        }
 private string GetCommentForChart(string ticker, BarSettings timeframe, List<BaseRobot> robots)
 {
     var robotStates = robots.Where(r => r.Graphics.Any(g => g.a == ticker && g.b == timeframe)).Select(s =>
         "Робот \"" + s.GetUniqueName() + "\"\n" + s.ReportState());
     return string.Join("\n\n", robotStates);
 }
Esempio n. 18
0
 public bool Equals(BarSettings tf)
 {
     if (tf == null) return false;
     if (StartMinute != tf.StartMinute) return false;
     if (intervals.Count != tf.intervals.Count) return false;
     for (var i = 0; i < intervals.Count; i++)
         if (intervals[i] != tf.intervals[i]) return false;
     return true;
 }
Esempio n. 19
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();
        }
Esempio n. 20
0
 public static void MakeOrderComments(MarketOrder order, BarSettings timeframe,
     decimal priceA, decimal priceB, int sequence = 1)
 {
     order.ExpertComment = RobotNamePreffix;
     order.Comment = string.Join(";",
                                 BarSettingsStorage.Instance.GetBarSettingsFriendlyName(timeframe),
                                 priceA.ToStringUniformPriceFormat(),
                                 priceB.ToStringUniformPriceFormat(),
                                 sequence);
 }
Esempio n. 21
0
        public static bool PutForecast(int categoryId, string ticker, BarSettings timeframe, string xmlForecast)
        {
            var wc = new WebClient();
            if (!string.IsNullOrEmpty(username))
                wc.Credentials = new NetworkCredential(username, pass);

            var requestParams = new NameValueCollection
                                    {
                                        { TradeSignalXml.ReqPtrForecastCategory, categoryId.ToString() },
                                        { TradeSignalXml.ReqPtrForecastTicker, ticker },
                                        { TradeSignalXml.ReqPtrForecastTimeframe, timeframe.ToString(TradeSignalXml.TimeframeSeparator) }
                                    };
            wc.QueryString = requestParams;
            try
            {
                var responseBytes = wc.UploadData(url, "PUT", TradeSignalXml.DefaultEncoding.GetBytes(xmlForecast));
                var respString = TradeSignalXml.DefaultEncoding.GetString(responseBytes);
                return respString == "OK";
            }
            catch (Exception ex)
            {
                Logger.Error("Ошибка в PutForecast()", ex);
                return false;
            }
        }
Esempio n. 22
0
 public ForecastQueueItem(string forecastXml, int categoryId, string ticker, BarSettings timeframe)
 {
     this.forecastXml = forecastXml;
     this.categoryId = categoryId;
     this.ticker = ticker;
     this.timeframe = timeframe;
 }
Esempio n. 23
0
 public CandlePacker(BarSettings barSettings)
 {
     BarSettings = barSettings;
 }
Esempio n. 24
0
 public static List<FiboRobotPosition> GetRobotPositions(string ticker,
     IEnumerable<MarketOrder> orders, BarSettings timeframe,
     decimal? priceAFilter, decimal? priceBFilter)
 {
     var maxDeltaPriceAbs = DalSpot.Instance.GetAbsValue(ticker, 1.5M);
     var deals = orders.Select(MakeFiboPosition)
               .Where(o => o != null)
               .Where(d =>
                   d.timeframe == timeframe &&
                   (!priceAFilter.HasValue || d.PriceA.RoughCompares(priceAFilter.Value, maxDeltaPriceAbs)) &&
                   (!priceBFilter.HasValue || d.PriceB.RoughCompares(priceBFilter.Value, maxDeltaPriceAbs)))
               .ToList();
     return deals;
 }
Esempio n. 25
0
        private void InitCandlePackers()
        {
            var barSetsM1 = new BarSettings {Intervals = new List<int> {1}};
            barSettingsCodeM1 = BarSettingsStorage.Instance.GetBarSettingsFriendlyName(barSetsM1);
            packers.Add(barSettingsCodeM1, tickersToStore.ToDictionary(t => t, t => new CandlePacker(barSetsM1)));
            candles.Add(barSettingsCodeM1, tickersToStore.ToDictionary(t => t, t => new List<CandleData>()));
            candlesM1 = tickersToStore.ToDictionary(t => t, t => new List<CandleData>());

            // прочитать из настроек, какие свечи нужны
            var barSetsStr = AppConfig.GetStringParam("Candles", "H1 H4 D1");
            var parts = barSetsStr.Split(new[] {' ', ',', '.'}, StringSplitOptions.RemoveEmptyEntries);
            foreach (var part in parts)
            {
                if (part == barSettingsCodeM1) continue;
                var sets = BarSettingsStorage.Instance.GetBarSettingsByName(part);
                if (ReferenceEquals(sets, null))
                {
                    Logger.ErrorFormat("InitCandlePackers - таймфрейм {0} не распознан", part);
                    continue;
                }
                var nameFriendly = BarSettingsStorage.Instance.GetBarSettingsFriendlyName(sets);
                packers.Add(nameFriendly, tickersToStore.ToDictionary(t => t, t => new CandlePacker(sets)));
                candles.Add(nameFriendly, tickersToStore.ToDictionary(t => t, t => new List<CandleData>()));
            }

            // по каждому пакеру слепить свечи из минуток
            Logger.InfoFormat("Формировать свечи для {0} тикеров, {1} таймфреймов",
                tickersToStore.Count, packers.Count);
            foreach (var ticker in tickersToStore)
            {
                var atomCandles = AtomCandleStorage.Instance.GetAllMinuteCandles(ticker) ?? new List<CandleData>();

                foreach (var cm1 in atomCandles)
                foreach (var packTimeframe in packers)
                {
                    var packer = packTimeframe.Value[ticker];
                    if (ReferenceEquals(packer, null))
                    {
                        Logger.ErrorFormat("packer({0}, {1}) = null", ticker, packTimeframe.Key);
                        continue;
                    }
                    if (!candles.ContainsKey(packTimeframe.Key))
                    {
                        Logger.ErrorFormat("!candles.ContainsKey({0})", packTimeframe.Key);
                        continue;
                    }
                    if (!candles[packTimeframe.Key].ContainsKey(ticker))
                    {
                        Logger.ErrorFormat("!candles[{0}].ContainsKey({1})",
                            packTimeframe.Key, ticker);
                        continue;
                    }

                    // добавить минутную свечу как есть
                    if (packer.BarSettings.IsAtomic)
                    {
                        candles[packTimeframe.Key][ticker].Add(cm1);
                        continue;
                    }

                    var candle = packer.UpdateCandle(cm1);
                    if (candle == null) continue;
                    candles[packTimeframe.Key][ticker].Add(candle);
                }
            }
        }
Esempio n. 26
0
 public RobotMarkClear(string symbol, BarSettings timeframe, string code)
 {
     Symbol = symbol;
     HintCode = code;
     Timeframe = BarSettingsStorage.Instance.GetBarSettingsFriendlyName(timeframe);
 }
Esempio n. 27
0
 public ChartControl()
 {
     InitializeComponent();
     visualSettings = new ChartVisualSettings(this);
     SetStyle((ControlStyles)0x22012, true);
     _chartFrame = new ChartFrame();
     _panes = new PaneCollection(this);
     _interactivityTools = new InteractivityToolCollection(this);
     CreateStockSeries();
     _window = new Window(this);
     candleRange = new CandleRange(StockSeries);
     Timeframe = new BarSettings();
     Timeframe.Intervals.Add(60);
     //DoubleBuffered = true;
 }
Esempio n. 28
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);
        }
Esempio n. 29
0
        /// <summary>
        /// обновить торговые рекомендации (список объектов в формате XML)
        /// </summary>
        /// <param name="signalCatId">категория сигнала</param>
        /// <param name="ticker">тикер (USDCHF...)</param>
        /// <param name="timeframe">таймфрейм прогноза</param>
        /// <param name="signalXml">XML (well-formed) в виде строки</param>
        public void UpdateSignal(int signalCatId, string ticker, BarSettings timeframe, string signalXml)
        {
            // проверить параметры
            if (string.IsNullOrEmpty(signalXml))
            {
                Logger.ErrorFormat("UpdateSignal (cat={0}) error: signalXml is empty", signalCatId);
                return;
            }
            if (!DalSpot.Instance.GetTickerNames().Contains(ticker))
            {
                Logger.ErrorFormat("UpdateSignal (cat={0}) error: ticker \"{1}\" is not found", signalCatId, ticker);
                return;
            }

            // проверить XML
            if (!TradeSignalXml.XmlIsValid(ref signalXml, true))
            {
                Logger.ErrorFormat("UpdateSignal (cat={0}) error: ", signalCatId, ticker);
                return;
            }

            // записать файл
            var key = new SignalStorageKey {categoryId = signalCatId, ticker = ticker, timeframe = timeframe};
            if (!WriteFile(key, signalXml)) return;

            // обновить словарь dicUpdateLocker
            try
            {
                dicUpdateLocker.AcquireWriterLock(LockTimeout);
            }
            catch (ApplicationException)
            {
                Logger.Error("SignalStorage - updateTimes write lock timeout");
                return;
            }

            try
            {
                if (updateTimes.ContainsKey(key)) updateTimes[key] = DateTime.Now;
                else updateTimes.Add(key, DateTime.Now);
            }
            catch (Exception ex)
            {
                Logger.Error("SignalStorage - updateTimes update error", ex);
                return;
            }
            finally
            {
                dicUpdateLocker.ReleaseWriterLock();
            }
        }
Esempio n. 30
0
        private static void ProcessPutRequest(Dictionary<string, string> queryParams, HttpListenerContext context, StringBuilder resp)
        {
            string catIdString;
            queryParams.TryGetValue(TradeSignalXml.ReqPtrForecastCategory, out catIdString);
            if (string.IsNullOrEmpty(catIdString))
            {
                Logger.Error("SignalWebServer, PUT request - param \"" + TradeSignalXml.ReqPtrForecastCategory + "\" is not set");
                resp.Append("error");
                return;
            }

            string ticker;
            queryParams.TryGetValue(TradeSignalXml.ReqPtrForecastTicker, out ticker);
            if (string.IsNullOrEmpty(ticker))
            {
                Logger.Error("SignalWebServer, PUT request - param \"" + TradeSignalXml.ReqPtrForecastTicker + "\" is not set");
                resp.Append("error");
                return;
            }

            string timeframe;
            queryParams.TryGetValue(TradeSignalXml.ReqPtrForecastTimeframe, out timeframe);
            if (string.IsNullOrEmpty(timeframe))
            {
                Logger.Error("SignalWebServer, PUT request - param \"" + TradeSignalXml.ReqPtrForecastTimeframe + "\" is not set");
                resp.Append("error");
                return;
            }

            var catId = catIdString.ToIntSafe();
            if (!catId.HasValue)
            {
                Logger.ErrorFormat("SignalWebServer, PUT request - param \"" + TradeSignalXml.ReqPtrForecastCategory +
                    "\" is terribly wrong (\"{0}\")",
                    catIdString);
                resp.Append("error");
                return;
            }

            BarSettings timeframeSets;
            try
            {
                timeframeSets = new BarSettings(timeframe, TradeSignalXml.TimeframeSeparator);
            }
            catch
            {
                Logger.ErrorFormat("SignalWebServer, PUT request - param \"" + TradeSignalXml.ReqPtrForecastTimeframe +
                    "\" is terribly wrong (\"{0}\")", timeframe);
                resp.Append("error");
                return;
            }

            // получить данные запроса
            var body = context.Request.InputStream;
            var encoding = TradeSignalXml.DefaultEncoding; // context.Request.ContentEncoding;
            var len = context.Request.ContentLength64;
            if (len == 0)
            {
                Logger.Error("SignalWebServer, PUT request - zero data length");
                resp.Append("error");
                return;
            }
            var data = new byte[len];
            using (var reader = new BinaryReader(body, encoding))
            {
                for (var i = 0; i < len; i++)
                    data[i] = reader.ReadByte();
            }
            var forecastXml = encoding.GetString(data);

            // отправить запрос - положить "сигнал" в хранилище
            ThreadPool.QueueUserWorkItem(PutForecastInStorage, new ForecastQueueItem(forecastXml,
                                                                                     catId.Value, ticker, timeframeSets));
            resp.Append("OK");
        }
Esempio n. 31
0
 public string GetTradeSignalXml(int signalCatId, string ticker, BarSettings timeframe)
 {
     return GetTradeSignalXml(new SignalStorageKey
         { categoryId = signalCatId, ticker = ticker, timeframe = timeframe });
 }
Esempio n. 32
0
 private static void MakeForecastResponseString(Dictionary<string, string> queryParams, StringBuilder response)
 {
     if (!queryParams.ContainsKey(TradeSignalXml.ReqPtrForecastCategory) ||
         string.IsNullOrEmpty(queryParams[TradeSignalXml.ReqPtrForecastCategory]))
     {
         response.Append("error:param \"" + TradeSignalXml.ReqPtrForecastCategory + "\" is missed");
         return;
     }
     if (!queryParams.ContainsKey(TradeSignalXml.ReqPtrForecastTicker) ||
         string.IsNullOrEmpty(queryParams[TradeSignalXml.ReqPtrForecastTicker]))
     {
         response.Append("error:param \"" + TradeSignalXml.ReqPtrForecastTicker + "\" is missed");
         return;
     }
     if (!queryParams.ContainsKey(TradeSignalXml.ReqPtrForecastTimeframe) ||
         string.IsNullOrEmpty(queryParams[TradeSignalXml.ReqPtrForecastTimeframe]))
     {
         response.Append("error:param \"" + TradeSignalXml.ReqPtrForecastTimeframe + "\" is missed");
         return;
     }
     var catId = queryParams[TradeSignalXml.ReqPtrForecastCategory].ToIntSafe();
     if (!catId.HasValue)
     {
         response.Append("error:param \"" + TradeSignalXml.ReqPtrForecastCategory + "\" should be a number");
         return;
     }
     var ticker = queryParams[TradeSignalXml.ReqPtrForecastTicker];
     if (!DalSpot.Instance.GetTickerNames().Contains(ticker))
     {
         response.Append("error:param \"" + TradeSignalXml.ReqPtrForecastTicker + "\" refers to a wrong symbol");
         return;
     }
     BarSettings timeframeSets;
     try
     {
         timeframeSets = new BarSettings(queryParams[TradeSignalXml.ReqPtrForecastTimeframe], TradeSignalXml.TimeframeSeparator);
     }
     catch
     {
         response.Append("error:param \"" + TradeSignalXml.ReqPtrForecastTimeframe + "\" was not recognized");
         return;
     }
     var respXml = SignalStorage.Instance.GetTradeSignalXml(catId.Value, ticker, timeframeSets);
     if (string.IsNullOrEmpty(respXml))
     {
         response.Append("error:not found");
         return;
     }
     response.Append(respXml);
 }
Esempio n. 33
0
 public CandlePacker(BarSettings barSettings)
 {
     BarSettings = barSettings;
 }
Esempio n. 34
0
 private static SignalStorageKey GetKeyFromFilePath(int catId, string filePath)
 {
     var fileName = Path.GetFileNameWithoutExtension(filePath);
     var nameParts = fileName.Split('_');
     if (nameParts.Length != 2)
         return default(SignalStorageKey);
     if (string.IsNullOrEmpty(nameParts[0]) || string.IsNullOrEmpty(nameParts[1]))
         return default(SignalStorageKey);
     if (!DalSpot.Instance.GetTickerNames().Contains(nameParts[0]))
         return default(SignalStorageKey);
     var ticker = nameParts[0];
     try
     {
         var timeframe = new BarSettings(nameParts[1]);
         return new SignalStorageKey {categoryId = catId, ticker = ticker, timeframe = timeframe};
     }
     catch
     {
         return default(SignalStorageKey);
     }
 }
        private void BuildSeries()
        {
            if (DrawPane != null && DrawPane != owner.StockPane)
                DrawPane.Title = UniqueName;
            if (volumeData.Count == 0) return;
            if (owner.StockSeries.Data.Count == 0) return;
            previousTimeframe = owner.Timeframe;

            seriesBuy.Data.Clear();
            seriesSell.Data.Clear();

            var lstVolm = new List<Cortege3<int, long, long>>();

            foreach (var volData in volumeData)
            {
                var index = owner.StockSeries.GetIndexByCandleOpen(volData.a);
                if (index <= 0) continue;

                lstVolm.Add(new Cortege3<int, long, long>(index, volData.b, volData.c));
            }

            // интерполировать
            if (lstVolm.Count > 0)
            {
                var lastIndex = 0;
                foreach (var ptVol in lstVolm)
                {
                    if (ptVol.a >= owner.StockSeries.Data.Count) break;
                    for (var i = lastIndex; i <= ptVol.a; i++)
                    {
                        seriesBuy.Data.Add(ptVol.b);
                        seriesSell.Data.Add(ptVol.c);
                    }
                    lastIndex = ptVol.a + 1;
                }
            }
        }
Esempio n. 36
0
 public string GetBarSettingsFriendlyName(BarSettings sets)
 {
     var exists = barSettingsSeries.FirstOrDefault(bs => bs == sets);
     return !ReferenceEquals(exists, null) ? exists.Title : sets.ToString();
 }
Esempio n. 37
0
        public void ReadSeriesFromXml()
        {
            var pathFile = string.Format("{0}\\{1}", ExecutablePath.ExecPath, BarSettingsFileName);
            var doc = new XmlDocument();
            try
            {
                if (!File.Exists(pathFile))
                    return;
                doc.Load(pathFile);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("Ошибка загрузки данных BarSettings \"{0}\": {1}", pathFile, ex);
            }
            try
            {
                // разбираем xml
                var node = doc.SelectSingleNode("BarSettingsList");
                if (node != null)
                {
                    var nodes = node.SelectNodes("BarSettings");

                    if (nodes != null)
                        foreach (XmlElement item in nodes)
                        {
                            var bars = new BarSettings {Title = item.Attributes["Title"].Value, IsUserDefined = true};
                            try
                            {
                                bars.ReadFromTagString(item.InnerText, ";#");
                            }
                            catch
                            {
                                continue;
                            }

                            if (!barSettingsSeries.Any(s => s.Title == bars.Title))
                                barSettingsSeries.Add(bars);
                        }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("BarSettings.ReadSeriesFromXml error", ex);
            }
        }
Esempio n. 38
0
        private void BtnOkClick(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cbTicker.Text))
            {
                MessageBox.Show(Localizer.GetString("MessageTickerNotChosen"));
                return;
            }

            if (!DalSpot.Instance.GetTickerNames().Contains(cbTicker.Text))
            {
                MessageBox.Show(string.Format(Localizer.GetString("MessageTickerNotFoundFmt"),
                    cbTicker.Text));
                return;
            }

            Timeframe = BarSettingsStorage.Instance.GetBarSettingsByName(cbTimeframe.Text);
            Ticker = cbTicker.Text;
            intervalModeIsOn = panelTimeBounds.Visible;

            //Если выбран какой нибудь шаблон
            if (cbTemplates.SelectedIndex > -1) TemplateName = cbTemplates.Text;

            DialogResult = DialogResult.OK;
        }
 public TimeframeSettingsForm(BarSettings timeframe)
 {
     InitializeComponent();
     Timeframe = timeframe;
 }
Esempio n. 40
0
        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();
        }
Esempio n. 41
0
        public string GetBarSettingsFriendlyName(BarSettings sets)
        {
            var exists = barSettingsSeries.FirstOrDefault(bs => bs == sets);

            return(!ReferenceEquals(exists, null) ? exists.Title : sets.ToString());
        }