-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPriceService.kt
More file actions
194 lines (170 loc) · 6.86 KB
/
PriceService.kt
File metadata and controls
194 lines (170 loc) · 6.86 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
package to.bitkit.data.widgets
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.statement.HttpResponse
import io.ktor.http.isSuccess
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.first
import to.bitkit.data.WidgetsStore
import to.bitkit.data.dto.price.CandleResponse
import to.bitkit.data.dto.price.Change
import to.bitkit.data.dto.price.GraphPeriod
import to.bitkit.data.dto.price.PriceDTO
import to.bitkit.data.dto.price.PriceResponse
import to.bitkit.data.dto.price.PriceWidgetData
import to.bitkit.data.dto.price.TradingPair
import to.bitkit.env.Env
import to.bitkit.models.WidgetType
import to.bitkit.utils.AppError
import to.bitkit.utils.Logger
import java.text.NumberFormat
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration.Companion.minutes
@Singleton
class PriceService @Inject constructor(
private val client: HttpClient,
private val widgetsStore: WidgetsStore,
) : WidgetService<PriceDTO> {
override val widgetType = WidgetType.PRICE
override val refreshInterval = 1.minutes
override suspend fun fetchData(): Result<PriceDTO> = runCatching {
val period = widgetsStore.data.first().pricePreferences.period ?: GraphPeriod.ONE_DAY
fetchData(period).getOrThrow()
}
suspend fun fetchData(period: GraphPeriod): Result<PriceDTO> = runCatching {
val widgets = TradingPair.entries.mapNotNull { pair ->
runCatching { fetchPairData(pair = pair, period = period) }
.onFailure { Logger.warn(e = it, msg = "Failed to fetch ${pair.ticker}", context = TAG) }
.getOrNull()
}
if (widgets.isEmpty()) throw PriceError.InvalidResponse("No price data available")
PriceDTO(widgets = widgets)
}.onFailure {
Logger.warn(e = it, msg = "Failed to fetch price data", context = TAG)
}
suspend fun fetchAllPeriods(): Result<List<PriceDTO>> = runCatching {
coroutineScope {
GraphPeriod.entries.map { period ->
async {
val widgets = TradingPair.entries.mapNotNull { pair ->
runCatching { fetchPairData(pair = pair, period = period) }.getOrNull()
}
PriceDTO(widgets = widgets)
}
}.awaitAll().filter { it.widgets.isNotEmpty() }
}
}.onFailure {
Logger.warn(e = it, msg = "fetchAllPeriods: Failed to fetch price data", context = TAG)
}
private suspend fun fetchPairData(pair: TradingPair, period: GraphPeriod): PriceWidgetData {
val ticker = pair.ticker
// Fetch historical candles
val candles = fetchCandles(ticker = ticker, period = period)
val sortedCandles = candles.sortedBy { it.timestamp }
val pastValues = sortedCandles.map { it.close }.toMutableList()
// Fetch latest price and replace last candle value
val latestPrice = fetchLatestPrice(ticker)
if (pastValues.isNotEmpty()) {
pastValues[pastValues.size - 1] = latestPrice
} else {
pastValues.add(latestPrice)
}
val change = calculateChange(pastValues)
val formattedPrice = formatPrice(pair, latestPrice)
return PriceWidgetData(
pair = pair,
change = change,
price = formattedPrice,
period = period,
pastValues = pastValues
)
}
private suspend fun fetchLatestPrice(ticker: String): Double {
val response: HttpResponse = client.get("${Env.pricesWidgetBaseUrl}/price/$ticker/latest")
return when (response.status.isSuccess()) {
true -> {
val priceResponse = runCatching { response.body<PriceResponse>() }.getOrElse {
throw PriceError.InvalidResponse("Failed to parse price response: ${it.message}")
}
priceResponse.price
}
else -> throw PriceError.InvalidResponse("Failed to fetch latest price: ${response.status.description}")
}
}
private suspend fun fetchCandles(
ticker: String,
period: GraphPeriod
): List<CandleResponse> {
val response: HttpResponse = client.get(
"${Env.pricesWidgetBaseUrl}/price/$ticker/history/${period.value}"
)
return when (response.status.isSuccess()) {
true -> {
runCatching { response.body<List<CandleResponse>>() }.getOrElse {
throw PriceError.InvalidResponse("Failed to parse candles response: ${it.message}")
}
}
else -> throw PriceError.InvalidResponse("Failed to fetch candles: ${response.status.description}")
}
}
private fun calculateChange(pastValues: List<Double>): Change {
if (pastValues.size < 2) {
return Change(isPositive = true, formatted = "+0%")
}
val firstValue = pastValues.first()
val lastValue = pastValues.last()
val changeRatio = (lastValue / firstValue) - 1
val sign = if (changeRatio >= 0) "+" else ""
val percentage = changeRatio * 100
return Change(
isPositive = changeRatio >= 0,
formatted = "$sign${"%.2f".format(percentage)}%"
)
}
private fun formatPrice(
pair: TradingPair,
price: Double,
locale: Locale = Locale.getDefault(),
): String {
return runCatching {
formatPriceValue(price = price, locale = locale)
}.onFailure {
Logger.warn("Failed to format price for '${pair.displayName}'", it, context = TAG)
}.getOrDefault(String.format(Locale.US, "%.2f", price))
}
companion object {
private const val TAG = "PriceService"
}
}
/**
* Price-specific error types
*/
sealed class PriceError(message: String) : AppError(message) {
class InvalidResponse(override val message: String) : PriceError(message)
class NetworkError(override val message: String) : PriceError(message)
}
private const val GROUPED_PRICE_THRESHOLD = 1_000.0
private const val STANDARD_PRICE_THRESHOLD = 1.0
private const val GROUPED_PRICE_DECIMALS = 0
private const val STANDARD_PRICE_DECIMALS = 2
private const val SMALL_PRICE_DECIMALS = 6
private const val MIN_PRICE_DECIMALS = 0
internal fun formatPriceValue(
price: Double,
locale: Locale = Locale.getDefault(),
): String {
return NumberFormat.getNumberInstance(locale).apply {
maximumFractionDigits = when {
price >= GROUPED_PRICE_THRESHOLD -> GROUPED_PRICE_DECIMALS
price >= STANDARD_PRICE_THRESHOLD -> STANDARD_PRICE_DECIMALS
else -> SMALL_PRICE_DECIMALS
}
minimumFractionDigits = MIN_PRICE_DECIMALS
isGroupingUsed = true
}.format(price)
}