Intelligence, Advanced Charting & Trading Platform

1 import Foundation
2 #if canImport(FoundationNetworking)
3 import FoundationNetworking
4 #endif
5
6 enum MarketAPIError: LocalizedError {
7 case invalidSelection, invalidResponse, server(Int)
8 var errorDescription: String? {
9 switch self {
10 case .invalidSelection: return "شناسه نمادهای انتخاب‌شده معتبر نیست."
11 case .invalidResponse: return "پاسخ معتبر از ChartNova دریافت نشد."
12 case .server(let code): return "سرویس بازار در دسترس نیست (HTTP \(code))."
13 }
14 }
15 }
16 struct MarketAPI {
17 static let baseURL = URL(string: "https://app.chartnova.ir")!
18 var session: URLSession = .shared
19
20 func fetchWidget(symbols: [String]) async throws -> WidgetFeed {
21 let clean = MarketSymbol.unique(symbols)
22 guard !clean.isEmpty else { throw MarketAPIError.invalidSelection }
23 var parts = URLComponents(url: Self.baseURL.appendingPathComponent("api/widget"), resolvingAgainstBaseURL: false)!
24 parts.queryItems = [URLQueryItem(name: "symbols", value: clean.joined(separator: ","))]
25 guard let url = parts.url else { throw MarketAPIError.invalidSelection }
26 let req = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 12)
27 let (data, response) = try await session.data(for: req)
28 guard let http = response as? HTTPURLResponse else { throw MarketAPIError.invalidResponse }
29 guard http.statusCode == 200 else { throw MarketAPIError.server(http.statusCode) }
30 let feed = try JSONDecoder().decode(WidgetFeed.self, from: data)
31 guard feed.ok, !feed.items.isEmpty, feed.items.count <= MarketSymbol.maximum,
32 feed.items.allSatisfy({ MarketSymbol.isValid($0.symbol) && $0.price.isFinite && $0.price > 0 }) else { throw MarketAPIError.invalidResponse }
33 return feed
34 }
35
36 func fetchCatalog() async throws -> [CatalogInstrument] {
37 let req = URLRequest(url: Self.baseURL.appendingPathComponent("api/markets"), cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)
38 let (data, response) = try await session.data(for: req)
39 guard let http = response as? HTTPURLResponse else { throw MarketAPIError.invalidResponse }
40 guard http.statusCode == 200 else { throw MarketAPIError.server(http.statusCode) }
41 let catalog = try JSONDecoder().decode(MarketCatalogResponse.self, from: data)
42 guard catalog.ok, !catalog.markets.isEmpty else { throw MarketAPIError.invalidResponse }
43 return catalog.markets.filter { MarketSymbol.isValid($0.symbol) && $0.sellPrice.isFinite && $0.sellPrice > 0 }
44 }
45 }
46 enum WidgetQuoteCache {
47 private static let key = "chartnova.widget.lastValidFeed.v1"
48 static func save(_ feed: WidgetFeed) {
49 guard feed.ok, !feed.items.isEmpty, let data = try? JSONEncoder().encode(feed) else { return }
50 WidgetSettingsStore.defaults.set(data, forKey: key)
51 }
52 static func load() -> WidgetFeed? {
53 guard let data = WidgetSettingsStore.defaults.data(forKey: key),
54 let feed = try? JSONDecoder().decode(WidgetFeed.self, from: data),
55 feed.ok, !feed.items.isEmpty else { return nil }
56 return feed
57 }
58 }