From 048650e1f26ccc9a773aa76f94ff82ef4920fae4 Mon Sep 17 00:00:00 2001 From: JohanLarsson Date: Sun, 11 Jul 2021 09:44:16 +0200 Subject: [PATCH] Merge when zero volume. #75 --- Sideways.Tests/Model/CandleTests.cs | 31 +++++++++++++++++++++++++++++ Sideways/Chart/Candles.cs | 8 ++++---- Sideways/Model/Candle.cs | 21 +++++++++++++++---- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/Sideways.Tests/Model/CandleTests.cs b/Sideways.Tests/Model/CandleTests.cs index 8804f8e..d2a672d 100644 --- a/Sideways.Tests/Model/CandleTests.cs +++ b/Sideways.Tests/Model/CandleTests.cs @@ -37,6 +37,37 @@ public static void Merge() Assert.AreEqual(expected, c2.Merge(c1)); } + [Test] + public static void MergeWhenZeroVolume() + { + var c1 = new Candle( + new DateTimeOffset(2021, 05, 22, 09, 30, 00, 0, TimeSpan.Zero), + open: 0f, + high: 0f, + low: 0f, + close: 0f, + volume: 0); + + var c2 = new Candle( + new DateTimeOffset(2021, 05, 22, 09, 31, 00, 0, TimeSpan.Zero), + open: 1.3f, + high: 1.4f, + low: 1.1f, + close: 1.2f, + volume: 1); + + var expected = new Candle( + new DateTimeOffset(2021, 05, 22, 09, 31, 00, 0, TimeSpan.Zero), + open: 1.3f, + high: 1.4f, + low: 1.1f, + close: 1.2f, + volume: 1); + + Assert.AreEqual(expected, c1.Merge(c2)); + Assert.AreEqual(expected, c2.Merge(c1)); + } + [Test] public static void Adjust() { diff --git a/Sideways/Chart/Candles.cs b/Sideways/Chart/Candles.cs index 46a46a7..0639f0c 100644 --- a/Sideways/Chart/Candles.cs +++ b/Sideways/Chart/Candles.cs @@ -25,15 +25,15 @@ public Candles(SortedCandles days, SortedCandles minutes) public IEnumerable DescendingDays(DateTimeOffset end) { if (TradingDay.IsRegularHours(end) && - this.DayRegularMinutes(end, this.minuteIndex) is { Length: > 0 } minutes) + this.DayRegularMinutes(end, this.minuteIndex) is { Length: > 0 } dayMinutes) { - if (minutes.Length == 1) + if (dayMinutes.Length == 1) { - yield return minutes[0]; + yield return dayMinutes[0]; } else { - yield return Candle.Merge(minutes); + yield return Candle.Merge(dayMinutes); } end = end.AddDays(-1); diff --git a/Sideways/Model/Candle.cs b/Sideways/Model/Candle.cs index daf688e..dbe119d 100644 --- a/Sideways/Model/Candle.cs +++ b/Sideways/Model/Candle.cs @@ -81,15 +81,28 @@ public static bool ShouldMergeFiveMinutes(DateTimeOffset x, DateTimeOffset y) => public Candle Merge(Candle other) { - return other.Time <= this.Time - ? new( + if (other.Time <= this.Time) + { + if (this.Volume == 0) + { + return other.WithTime(this.Time); + } + + if (other.Volume == 0) + { + return this; + } + + return new( time: this.Time, open: other.Open, high: Math.Max(this.High, other.High), low: Math.Min(this.Low, other.Low), close: this.Close, - volume: this.Volume + other.Volume) - : other.Merge(this); + volume: this.Volume + other.Volume); + } + + return other.Merge(this); } public bool Equals(Candle other)