This repository was archived by the owner on Mar 26, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathCandlestickChartView.swift
More file actions
265 lines (239 loc) · 9.74 KB
/
CandlestickChartView.swift
File metadata and controls
265 lines (239 loc) · 9.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Copyright (c). Gem Wallet. All rights reserved.
import SwiftUI
import Charts
import Style
import Primitives
import PrimitivesComponents
import Formatters
private struct ChartKey {
static let date = "Date"
static let low = "Low"
static let high = "High"
static let open = "Open"
static let close = "Close"
static let price = "Price"
}
struct CandlestickChartView: View {
private let data: [ChartCandleStick]
private let period: ChartPeriod
private let basePrice: Double?
private let lineModels: [ChartLineViewModel]
private let formatter: CurrencyFormatter
@State private var selectedCandle: ChartPriceViewModel? {
didSet {
if let selectedCandle, selectedCandle.date != oldValue?.date {
vibrate()
}
}
}
init(
data: [ChartCandleStick],
period: ChartPeriod = .day,
basePrice: Double? = nil,
lineModels: [ChartLineViewModel] = [],
formatter: CurrencyFormatter = CurrencyFormatter(type: .currency, currencyCode: Currency.usd.rawValue)
) {
self.data = data
self.period = period
self.basePrice = basePrice ?? data.first?.close
self.lineModels = lineModels
self.formatter = formatter
}
var body: some View {
VStack {
priceHeader
chartView(bounds: ChartBounds(candles: data, lines: lineModels))
}
}
private var priceHeader: some View {
VStack {
if let selectedCandle {
ChartPriceView(model: selectedCandle)
} else if let currentPrice = currentPriceModel {
ChartPriceView(model: currentPrice)
}
}
.padding(.top, Spacing.small)
.padding(.bottom, Spacing.tiny)
}
private func chartView(bounds: ChartBounds) -> some View {
let dateRange = (data.first?.date ?? Date())...(data.last?.date ?? Date())
return Chart {
candlestickMarks
linesMarks(bounds)
selectionMarks
}
.chartOverlay { proxy in
GeometryReader { geometry in
Rectangle()
.fill(.clear)
.contentShape(Rectangle())
.gesture(
DragGesture(minimumDistance: 0)
.onChanged { value in
if let candle = findCandle(location: value.location, proxy: proxy, geometry: geometry) {
selectedCandle = createPriceModel(for: candle)
}
}
.onEnded { _ in
selectedCandle = nil
}
)
}
}
.chartXAxis {
AxisMarks(position: .bottom, values: .automatic(desiredCount: 6)) { _ in
AxisGridLine(stroke: ChartGridStyle.strokeStyle)
.foregroundStyle(ChartGridStyle.color)
}
}
.chartYAxis {
AxisMarks(position: .trailing, values: .automatic(desiredCount: ChartBounds.desiredTickCount)) { value in
AxisGridLine(stroke: ChartGridStyle.strokeStyle)
.foregroundStyle(ChartGridStyle.color)
AxisTick(stroke: StrokeStyle(lineWidth: ChartGridStyle.lineWidth))
.foregroundStyle(ChartGridStyle.color)
AxisValueLabel {
if let price = value.as(Double.self) {
Text(price, format: bounds.axisFormat)
.font(.caption2)
.foregroundStyle(Colors.gray)
.padding(.horizontal, .extraSmall)
}
}
}
if let currentPrice = data.last?.close {
AxisMarks(position: .trailing, values: [currentPrice]) { value in
AxisValueLabel {
if let price = value.as(Double.self) {
Text(price, format: bounds.axisFormat)
.font(.caption2)
.foregroundStyle(Colors.whiteSolid)
.padding(.horizontal, .extraSmall)
.padding(.vertical, 1)
.background(currentPriceColor)
.clipShape(RoundedRectangle(cornerRadius: Spacing.tiny))
}
}
}
}
}
.chartXScale(domain: dateRange)
.chartYScale(domain: bounds.minPrice...bounds.maxPrice)
}
private var currentPriceColor: Color {
guard let lastCandle = data.last else { return Colors.gray }
return lastCandle.close >= lastCandle.open ? Colors.green : Colors.red
}
@ChartContentBuilder
private var candlestickMarks: some ChartContent {
ForEach(data, id: \.date) { candle in
RuleMark(
x: .value(ChartKey.date, candle.date),
yStart: .value(ChartKey.low, candle.low),
yEnd: .value(ChartKey.high, candle.high)
)
.lineStyle(StrokeStyle(lineWidth: 1))
.foregroundStyle(candle.close >= candle.open ? Colors.green : Colors.red)
RectangleMark(
x: .value(ChartKey.date, candle.date),
yStart: .value(ChartKey.open, candle.open),
yEnd: .value(ChartKey.close, candle.close),
width: .fixed(4)
)
.foregroundStyle(candle.close >= candle.open ? Colors.green : Colors.red)
}
}
@ChartContentBuilder
private func linesMarks(_ bounds: ChartBounds) -> some ChartContent {
ForEach(bounds.visibleLines) { line in
RuleMark(y: .value(ChartKey.price, line.price))
.foregroundStyle(line.color.opacity(0.6))
.lineStyle(line.lineStyle)
}
ForEach(Array(bounds.visibleLines.enumerated()), id: \.element.id) { index, line in
RuleMark(y: .value(ChartKey.price, line.price))
.foregroundStyle(.clear)
.annotation(position: .overlay, alignment: .leading, spacing: 0) {
Text(line.label)
.font(.system(size: .space10, weight: .semibold))
.foregroundStyle(Colors.whiteSolid)
.padding(.tiny)
.background(line.color)
.clipShape(RoundedRectangle(cornerRadius: .tiny))
.offset(x: labelXOffset(for: index, in: bounds))
}
}
}
private func labelXOffset(for index: Int, in bounds: ChartBounds) -> CGFloat {
guard index > 0 else { return 0 }
let threshold = (bounds.maxPrice - bounds.minPrice) * 0.06
let lines = bounds.visibleLines
let space = 115.0
return (1...index).reduce(0.0) { offset, idx in
abs(lines[idx].price - lines[idx - 1].price) < threshold ? offset + space : offset
}
}
@ChartContentBuilder
private var selectionMarks: some ChartContent {
if let selectedCandle,
let selectedDate = selectedCandle.date,
let selectedCandleData = data.first(where: { abs($0.date.timeIntervalSince(selectedDate)) < 1 }) {
PointMark(
x: .value(ChartKey.date, selectedDate),
y: .value(ChartKey.price, selectedCandleData.close)
)
.symbol {
Circle()
.strokeBorder(Colors.blue, lineWidth: 2)
.background(Circle().foregroundColor(Colors.white))
.frame(width: 12)
}
RuleMark(x: .value(ChartKey.date, selectedDate))
.foregroundStyle(Colors.blue)
.lineStyle(StrokeStyle(lineWidth: 1, dash: [5]))
}
}
private var currentPriceModel: ChartPriceViewModel? {
guard let lastCandle = data.last,
let base = basePrice else { return nil }
return ChartPriceViewModel(
period: period,
date: nil,
price: lastCandle.close,
priceChangePercentage: ChartPriceViewModel.priceChangePercentage(close: lastCandle.close, base: base),
formatter: formatter
)
}
private func createPriceModel(for candle: ChartCandleStick) -> ChartPriceViewModel {
let base = basePrice ?? data.first?.close ?? candle.close
return ChartPriceViewModel(
period: period,
date: candle.date,
price: candle.close,
priceChangePercentage: ChartPriceViewModel.priceChangePercentage(close: candle.close, base: base),
formatter: formatter
)
}
private func findCandle(location: CGPoint, proxy: ChartProxy, geometry: GeometryProxy) -> ChartCandleStick? {
guard let plotFrame = proxy.plotFrame else { return nil }
let relativeXPosition = location.x - geometry[plotFrame].origin.x
if let date = proxy.value(atX: relativeXPosition) as Date? {
// Find the closest candle
var minDistance: TimeInterval = .infinity
var closestCandle: ChartCandleStick?
for candle in data {
let distance = abs(candle.date.timeIntervalSince(date))
if distance < minDistance {
minDistance = distance
closestCandle = candle
}
}
return closestCandle
}
return nil
}
private func vibrate() {
UIImpactFeedbackGenerator(style: .light).impactOccurred()
}
}