public TestHistoricalData(int timeframe, string filename) { this.timeframe = timeframe; //считать данные из файла string text = ReadStringFromFile(filename); if (text != null) { text = text.Replace("\r", ""); List <string> str = text.Split('\n').ToList(); str.RemoveAt(0); str.RemoveAt(0); int i = 0; foreach (string v in str) { var s = v.Split('/'); //var c = new TestCandle(); try { var c = new TestCandle() { Open = Convert.ToDouble(s[1]), High = Convert.ToDouble(s[2]), Low = Convert.ToDouble(s[3]), Close = Convert.ToDouble(s[4]), TimeUTC = i * timeframe * 60 }; Candles.Add(c); i++; } catch { } } } }
public void AddCandle() { Candle old_cndl = Candles[Candles.Count - 1] as Candle; Candle new_cndl = new Candle() { O = old_cndl.O, H = old_cndl.H, L = old_cndl.L, C = old_cndl.C, V = old_cndl.V, t = old_cndl.t }; Candles.Add(new_cndl); }
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private void MergeCandle(string assetPair, CandleTimeInterval interval, ICandle candle) { if (candle.AssetPairId != assetPair) { throw new InvalidOperationException($"Candle {candle.ToJson()} has invalid AssetPriceId"); } if (candle.TimeInterval != interval) { throw new InvalidOperationException($"Candle {candle.ToJson()} has invalid TimeInterval"); } if (candle.PriceType != PriceType) { throw new InvalidOperationException($"Candle {candle.ToJson()} has invalid PriceType"); } // 1. Check if candle with specified time already exist // 2. If found - merge, else - add to list var tick = GetIntervalTick(candle.Timestamp, interval); // Considering that Candles is ordered by Tick for (var i = 0; i < Candles.Count; ++i) { var currentCandle = Candles[i]; // While currentCandle.Tick < tick - just skipping // That's it, merge to existing candle if (currentCandle.Tick == tick) { currentCandle.InplaceMergeWith(candle); return; } // No candle is found but there are some candles after, so we should insert candle right before them if (currentCandle.Tick > tick) { Candles.Insert(i, candle.ToItem(tick)); return; } } // No candle is found, and no candles after, so just add to the end Candles.Add(candle.ToItem(tick)); }
async void OnUpdateCandlesFromInternetTimerTick(object sender, EventArgs e) { try { HttpResponseMessage response = await httpClient.GetAsync($"https://api.cryptowat.ch/markets/{exchangeNameForRestApi}/{tickerNameForRestApi}/ohlc?after={lastCandleUnixTime}&periods=60"); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); JToken jCandles = JObject.Parse(responseBody)["result"]["60"]; int N = jCandles.Count(); for (int i = 0; i < N; i++) { JToken jCandle = jCandles[i]; long unixTime = (long)(jCandle[0]); if (unixTime < lastCandleUnixTime) { continue; } DateTime t = UnixTimeStampToDateTime(unixTime); ICandle cndl = new Candle() { t = t, O = (double)(jCandle[1]), H = (double)(jCandle[2]), L = (double)(jCandle[3]), C = (double)(jCandle[4]), V = (long)(jCandle[5]) }; if (unixTime == lastCandleUnixTime) { if (!Candles[Candles.Count - 1].IsEqualByValue(cndl)) { Candles[Candles.Count - 1] = cndl; } } else { Candles.Add(cndl); lastCandleUnixTime = unixTime; } } } catch (HttpRequestException ee) { MessageBox.Show(ee.Message); } }
public int ReplaceCandles(IEnumerable<ICandle> candlesToReplace) { var replacedCount = 0; foreach (var candle in candlesToReplace) { var tick = GetIntervalTick(candle.Timestamp, candle.TimeInterval); if (Candles.RemoveAll(c => c.Tick == tick) <= 0) continue; // Can't replace if there was no candle with the requested tick. Candles.Add(candle.ToItem(tick)); replacedCount++; } // Sorting candles for storing in DB in proper order. Candles.Sort((a, b) => a.Tick.CompareTo(b.Tick)); return replacedCount; }
private void ProcessingMinutely() { int i = 0; DateTime testDate = DateTime.Parse("01/01/1980"); while (i < CandlesBasic.Count) { DateTime checkPoint = new DateTime(CandlesBasic[i].Date.Year, CandlesBasic[i].Date.Month, CandlesBasic[i].Date.Day, CandlesBasic[i].Date.Hour, 0, 0).AddMinutes(Interval); //DateTime checkPoint = new DateTime(testDate.Date.Year, testDate.Date.Month, testDate.Date.Day, testDate.Date.Hour, 0, 0).AddMinutes(Interval); while ((new DateTime(CandlesBasic[i].Date.Year, CandlesBasic[i].Date.Month, CandlesBasic[i].Date.Day)) == (new DateTime(checkPoint.Year, checkPoint.Month, checkPoint.Day))) { DateTime date = CandlesBasic[i].Date; double high = CandlesBasic[i].High; double low = CandlesBasic[i].Low; double open = CandlesBasic[i].Open; double volume = CandlesBasic[i].Volume; double close = CandlesBasic[i].Close; int numElements = 0; while (CandlesBasic[i].Date < checkPoint) { low = (CandlesBasic[i].Low < low) ? CandlesBasic[i].Low : low; high = (CandlesBasic[i].High > high) ? CandlesBasic[i].High : high; volume += CandlesBasic[i].Volume; close = CandlesBasic[i].Close; i++; numElements++; if (i < CandlesBasic.Count) { continue; } break; } if (numElements > 0) { Candles.Add(new RegCandle { Date = date, Open = open, High = high, Low = low, Close = close, Volume = volume }); } checkPoint = checkPoint.AddMinutes(Interval); if (i >= CandlesBasic.Count) { break; } } } }
/// <summary> /// Processo de transformação dos dados para periodicidade e intervalo solicitado /// </summary> private void Processing() { int i = 0; while (i < CandlesBasic.Count) { DateTime date = CandlesBasic[i].Date; double high = CandlesBasic[i].High; double low = CandlesBasic[i].Low; double open = CandlesBasic[i].Open; double volume = CandlesBasic[i].Volume; int intervalTemp = Interval; while ((intervalTemp > 0) && (i < CandlesBasic.Count - 1)) { switch (Periodicity) { case Periodicity.Weekly: if (DayOfWeek(CandlesBasic[i + 1].Date.DayOfWeek) < DayOfWeek(CandlesBasic[i].Date.DayOfWeek)) { intervalTemp--; } break; case Periodicity.Month: if (CandlesBasic[i + 1].Date.Month > CandlesBasic[i].Date.Month) { intervalTemp--; } break; case Periodicity.Year: if (CandlesBasic[i + 1].Date.Year > CandlesBasic[i].Date.Year) { intervalTemp--; } break; } if (intervalTemp <= 0) { continue; } low = (CandlesBasic[i].Low < low) ? CandlesBasic[i].Low : low; high = (CandlesBasic[i].High > high) ? CandlesBasic[i].High : high; volume += CandlesBasic[i].Volume; i++; } double close = CandlesBasic[i].Close; volume += CandlesBasic[i].Volume; low = (CandlesBasic[i].Low < low) ? CandlesBasic[i].Low : low; high = (CandlesBasic[i].High > high) ? CandlesBasic[i].High : high; i++; Candles.Add(new RegCandle { Date = date, Open = open, High = high, Low = low, Close = close, Volume = volume }); } }
private void OnCandle(Candle candle) { Candles.Add(candle); }
public decimal Calculate(Candle candle) { if (Candles.Count == 0) Candles.Add(candle); if (candle.OpenTime != Candles[Candles.Count - 1].OpenTime) Candles.Add(candle); else Candles[Candles.Count - 1] = candle; _prevValue = _ind.GetCurrentValue(); if (Candles.Count < 3) return _prevValue; if (Candles.Count == 3) { _longPosition = Candles[Candles.Count - 1].HighPrice > Candles[Candles.Count - 2].HighPrice; var max = Candles.Max(t => t.HighPrice); var min = Candles.Min(t => t.LowPrice); _xp = _longPosition ? max : min; _af = _ind.Acceleration; return _xp + (_longPosition ? -1 : 1) * (max - min) * _af; } if (_afIncreased && _prevBar != Candles.Count) _afIncreased = false; var value = _prevValue; if (_reverseBar != Candles.Count) { _todaySar = TodaySar(_prevValue + _af * (_xp - _prevValue)); for (var x = 1; x <= 2; x++) { if (_longPosition) { if (_todaySar > Candles[Candles.Count - 1 - x].LowPrice) _todaySar = Candles[Candles.Count - 1 - x].LowPrice; } else { if (_todaySar < Candles[Candles.Count - 1 - x].HighPrice) _todaySar = Candles[Candles.Count - 1 - x].HighPrice; } } if ((_longPosition && (Candles[Candles.Count - 1].LowPrice < _todaySar || Candles[Candles.Count - 2].LowPrice < _todaySar)) || (!_longPosition && (Candles[Candles.Count - 1].HighPrice > _todaySar || Candles[Candles.Count - 2].HighPrice > _todaySar))) { return Reverse(); } if (_longPosition) { if (_prevBar != Candles.Count || Candles[Candles.Count - 1].LowPrice < _prevSar) { value = _todaySar; _prevSar = _todaySar; } else value = _prevSar; if (Candles[Candles.Count - 1].HighPrice > _xp) { _xp = Candles[Candles.Count - 1].HighPrice; AfIncrease(); } } else if (!_longPosition) { if (_prevBar != Candles.Count || Candles[Candles.Count - 1].HighPrice > _prevSar) { value = _todaySar; _prevSar = _todaySar; } else value = _prevSar; if (Candles[Candles.Count - 1].LowPrice < _xp) { _xp = Candles[Candles.Count - 1].LowPrice; AfIncrease(); } } } else { if (_longPosition && Candles[Candles.Count - 1].HighPrice > _xp) _xp = Candles[Candles.Count - 1].HighPrice; else if (!_longPosition && Candles[Candles.Count - 1].LowPrice < _xp) _xp = Candles[Candles.Count - 1].LowPrice; value = _prevSar; _todaySar = TodaySar(_longPosition ? Math.Min(_reverseValue, Candles[Candles.Count - 1].LowPrice) : Math.Max(_reverseValue, Candles[Candles.Count - 1].HighPrice)); } _prevBar = Candles.Count; return value; }
public static bool GetNewCandle(string resolution, string pair, string symbol) { if (!Candles.ContainsKey(pair)) { Candles.Add(pair, new List <Candle>()); } string requestStr = requestUrl; if (Candles[pair].Count <= 0) { requestStr = requesthistory; } requestStr = string.Format(requestStr, resolution, pair); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestStr); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string raw = new StreamReader(response.GetResponseStream()).ReadToEnd(); string[] sep = { "," }; string[] dataArray = raw.Replace("[", "").Replace("]", "").Split(sep, StringSplitOptions.RemoveEmptyEntries); if (Candles[pair].Count <= 0) { Console.WriteLine(string.Format("No history available for {0} with resolution {1}", pair, resolution)); Console.WriteLine("Getting last 100 candles..."); for (int i = 6; i < dataArray.Length; i += 6) { long mtsTemp = Convert.ToInt64(dataArray[i]); DateTime time = new DateTime(1970, 1, 1).AddMilliseconds(mtsTemp).AddMinutes(60); float open = Convert.ToSingle(dataArray[i + 1].Replace(".", ",")); float close = Convert.ToSingle(dataArray[i + 2].Replace(".", ",")); float high = Convert.ToSingle(dataArray[i + 3].Replace(".", ",")); float low = Convert.ToSingle(dataArray[i + 4].Replace(".", ",")); Candle c = new Candle(symbol, pair, resolution, mtsTemp, time, open, high, low, close, true); } Console.WriteLine("Successfully retrieved history"); Console.WriteLine("Searching for new candles..."); return(true); } long[] converted = new long[5]; for (int i = 0; i < converted.Length; i++) { converted[i] = (long)Convert.ToSingle(dataArray[i + 6].Replace(".", ",")); } long mts = Convert.ToInt64(dataArray[6]); if (mts > Candles[pair][Candles[pair].Count - 1].mts) { DateTime time = new DateTime(1970, 1, 1).AddMilliseconds(mts).AddMinutes(60); Candle c = new Candle(symbol, pair, resolution, mts, time, converted[1], converted[3], converted[4], converted[2]); return(true); } return(false); } catch (WebException e) { Console.WriteLine(e.Message); Thread.Sleep(2000); return(GetNewCandle(resolution, pair, symbol)); } }
/// <summary> /// Receive Raw Data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BData_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { //Data caching and moving to Azure Data Table logic goes here switch (e.Action) { case System.Collections.Specialized.NotifyCollectionChangedAction.Add: var Candle = (BinanceStreamKlineData)e.NewItems[0]; //Remove Extra var sourcedata = new Trady.Core.Candle(Candle.Data.CloseTime, Candle.Data.Open, Candle.Data.High, Candle.Data.Low, Candle.Data.Close, Candle.Data.Volume); BinanceCandle Standardize = new BinanceCandle(sourcedata); Standardize.Last = Candle.Data.Final; Standardize.Name = Candle.Symbol; Standardize.Candle = sourcedata; Type myType = Candle.Data.GetType(); //Extract all exchanger candle properties IList <PropertyInfo> props = new List <PropertyInfo>(myType.GetProperties()); foreach (PropertyInfo prop in props) { object propValue = prop.GetValue(Candle.Data, null); Standardize.Properties.Add(prop.Name, propValue); } Standardize.Update(); try { Candles.Add(Standardize); } catch (Exception ex) { Console.WriteLine("Exception during core candle add (computed) : {0} ", ex.Message); } //Until fix try { if (UseSender) { this.Sender.Send(Standardize.Jscontainer); } DataOrganizer.SourceData.Add(Standardize); //if (Moon.Global.shared.table != null) //{ // TableOperation insertOperation = TableOperation.Insert(Standardize); // // Execute the insert operation. // Moon.Global.shared.table.Execute(insertOperation); //} } catch (Exception ex) { } break; case System.Collections.Specialized.NotifyCollectionChangedAction.Move: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Remove: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Replace: break; case System.Collections.Specialized.NotifyCollectionChangedAction.Reset: break; } }
private void OnCandle(Candle candle) { Candles.Add(candle); OnPropertyChanged(nameof(FilteredCandles)); }
private void TicksToCandles(string data) { var ticks = ((List <Tick>) new XmlSerializer(typeof(List <Tick>), new XmlRootAttribute("ticks")).Deserialize( new StringReader(data))).Where(item => item.Board == _board && item.Seccode == _seccode) .ToList(); if (_ticks == null) { _ticks = ticks; } else { _ticks.AddRange(ticks); } var interval = new TimeSpan(0, _timeframe, 0); var temp = (from t in _ticks group t by DateTime.Parse(t.Tradetime).Ticks / interval.Ticks into g select new Candle { High = (from t2 in g select t2.Price).Max(), Low = (from t2 in g select t2.Price).Min(), Open = g.First().Price, Close = g.Last().Price, Volume = g.Count(), Time = g.First().Tradetime }).ToList(); foreach (var candle in temp) { if (candle.Open < candle.Close) { candle.StickColor = System.Windows.Media.Brushes.Green; } else { candle.StickColor = System.Windows.Media.Brushes.Red; } } if (Candles.Count == _historyCount) { var realtime = Candles.ToList(); realtime.AddRange(temp); Candles = new ObservableCollection <Candle>(realtime); return; } //todo : create value if u use some math or other operatin which dublicated var qqqqq = temp.Count + _historyCount; if (qqqqq == Candles.Count) { _dispatcher.Invoke(() => Candles[Candles.Count - 1] = temp.Last()); } else if (qqqqq == Candles.Count + 1) { _dispatcher.Invoke(() => Candles.Add(temp.Last())); } else { Candles = new ObservableCollection <Candle>(temp); } }