Repository Public
1//2// VQuant iOS3// File: Core/Networking/VQuantAPI.swift4// Description: The backend endpoints the app uses, one function per route. Nothing here exists that the server does not serve.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112struct VQuantAPI: Sendable {13 let client: APIClient1415 // MARK: account, devices1617 func me() async throws -> Account { try await client.decode(.get("/api/me")) }18 func health() async throws -> Bool {19 struct H: Decodable { var status: String }20 return try await client.decode(H.self, .get("/api/health", timeout: 10)).status == "ok"21 }22 func session() async throws -> NativeSession { try await client.decode(.get("/api/native/session", timeout: 15)) }23 func devices() async throws -> DeviceList { try await client.decode(.get("/api/native/devices")) }24 /// Both revocations need a passkey verification made in the last five minutes (403 `reauth_required` otherwise).25 func revokeDevice(_ id: String) async throws { _ = try await client.data(APIRequest(method: "DELETE", path: "/api/native/devices/\(id)")) }26 func revokePasskey(ref: String) async throws { _ = try await client.data(APIRequest(method: "DELETE", path: "/api/native/passkeys/\(ref)")) }27 func logout() async throws { _ = try await client.data(.send("POST", "/api/native/logout")) }2829 // MARK: quantitative computations (server engines)3031 func quantTools() async throws -> QuantToolList { try await client.decode(.get("/api/quant/tools")) }32 func quantJobs() async throws -> QuantJobList { try await client.decode(.get("/api/quant/jobs")) }33 func quantJob(_ id: String) async throws -> QuantJob {34 struct Envelope: Decodable { var job: QuantJob }35 return try await client.decode(Envelope.self, .get("/api/quant/jobs/\(id)", timeout: 60)).job36 }37 /// Starts a computation on the server (202). It runs there whether or not this app stays open.38 func startQuantJob(tool: String, params: [String: JSONValue]) async throws -> QuantJob {39 struct Body: Encodable { var tool: String; var params: [String: JSONValue] }40 struct Envelope: Decodable { var job: QuantJob }41 return try await client.decode(Envelope.self, try .json("POST", "/api/quant/jobs", Body(tool: tool, params: params))).job42 }43 func deleteQuantJob(_ id: String) async throws { _ = try await client.data(APIRequest(method: "DELETE", path: "/api/quant/jobs/\(id)")) }4445 // MARK: market data4647 func indices() async throws -> [Quote] { try await client.decode(.get("/api/fmp/indices")) }48 func quote(_ symbol: String) async throws -> Quote {49 let list: [Quote] = try await client.decode(.get("/api/fmp/quote/\(symbol)"))50 guard let q = list.first else { throw APIError(kind: .notFound, message: "Aucune cotation pour \(symbol).") }51 return q52 }53 func movers(_ kind: MoverKind) async throws -> [Quote] { try await client.decode(.get("/api/fmp/\(kind.rawValue)")) }54 func marketHours() async throws -> [ExchangeHours] { try await client.decode(.get("/api/fmp/market-hours")) }55 func profile(_ symbol: String) async throws -> CompanyProfile? {56 let list: [CompanyProfile] = try await client.decode(.get("/api/fmp/company-profile/\(symbol)"))57 return list.first58 }59 func news(_ symbol: String) async throws -> [NewsItem] { try await client.decode(.get("/api/fmp/financial-news/\(symbol)")) }60 func search(_ text: String, limit: Int = 12) async throws -> [SymbolMatch] {61 try await client.decode(.get("/api/fmp/search", query: ["q": text, "limit": String(limit)]))62 }63 func fundamentals(_ table: FundamentalTable, symbol: String) async throws -> [FundamentalRecord] {64 let v: JSONValue = try await client.decode(.get("\(table.path)/\(symbol)"))65 if let a = v.arrayValue { return a.compactMap(\.objectValue) }66 if let o = v.objectValue { return [o] }67 return []68 }6970 /// Bars for a chart, oldest first. End-of-day ranges come from `/chart/full`, intraday ranges from71 /// `/chart/intraday` at the resolution of the range: the server aggregates, the device draws what it receives.72 func bars(_ symbol: String, range: ChartRange, interval: IntradayInterval? = nil, now: Date = Date()) async throws -> [Bar] {73 let from = MarketDate.day(now.addingTimeInterval(-Double(range.lookbackDays) * 86_400))74 let to = MarketDate.day(now)75 let raw: [Bar]76 if let iv = interval ?? range.interval {77 raw = try await client.decode(.get("/api/fmp/chart/intraday/\(symbol)", query: ["interval": iv.rawValue, "from": from, "to": to], timeout: 45))78 } else {79 raw = try await client.decode(.get("/api/fmp/chart/full/\(symbol)", query: ["from": from, "to": to], timeout: 45))80 }81 var sorted = raw.sorted { $0.date < $1.date }82 if range == .day, let last = sorted.last { // one session only: the most recent trading day83 let day = MarketDate.day(last.date)84 sorted = sorted.filter { MarketDate.day($0.date) == day }85 }86 return sorted87 }8889 // MARK: analyses9091 func generations() async throws -> GenerationList { try await client.decode(.get("/api/generations", timeout: 15)) }92 func cancelGeneration(_ id: String) async throws { _ = try await client.data(.send("POST", "/api/generations/\(id)/cancel")) }93 func streamGeneration(_ id: String, from index: Int) -> AsyncThrowingStream<StreamItem, Error> {94 client.stream(.get("/api/generations/\(id)/stream", query: ["from": String(max(0, index))]))95 }96 /// Starts an analysis. The response is the event stream of the new server job; closing it does not stop the job.97 func startAnalysis(_ request: ChatRequest) -> AsyncThrowingStream<StreamItem, Error> {98 do { return client.stream(try .json("POST", "/api/chat", request)) } catch { return AsyncThrowingStream { $0.finish(throwing: error) } }99 }100101 // MARK: conversations and reports102103 func conversations(search: String? = nil) async throws -> [ConversationSummary] {104 try await client.decode(.get("/api/sessions", query: (search?.isEmpty == false) ? ["q": search!] : [:]))105 }106 func conversation(_ id: String) async throws -> Conversation { try await client.decode(.get("/api/sessions/\(id)", timeout: 60)) }107 func conversationData(_ id: String) async throws -> Data { try await client.data(.get("/api/sessions/\(id)", timeout: 60)) }108 func renameConversation(_ id: String, title: String) async throws {109 _ = try await client.data(try .json("PATCH", "/api/sessions/\(id)", ["title": title]))110 }111 func pinConversation(_ id: String, pinned: Bool) async throws {112 _ = try await client.data(try .json("PATCH", "/api/sessions/\(id)", ["pinned": pinned]))113 }114 func deleteConversation(_ id: String) async throws { _ = try await client.data(APIRequest(method: "DELETE", path: "/api/sessions/\(id)")) }115 func sharedReports() async throws -> [SharedReportSummary] { try await client.decode(.get("/api/shared-reports", timeout: 60)) }116 func sharedReport(_ shareId: String) async throws -> SharedReport { try await client.decode(.get("/api/share/\(shareId)", timeout: 60)) }117 /// The report as a PDF typeset by the server (same document as the web app's export).118 func pdf(question: String, answer: String) async throws -> Data {119 try await client.data(try .json("POST", "/api/generate-pdf", ["question": question, "answer": answer], timeout: 120))120 }121 /// A file the server produced (`/figures/…`, `/plots/…`, `/api/download/…`).122 func file(_ path: String) async throws -> Data {123 guard path.hasPrefix("/figures/") || path.hasPrefix("/plots/") || path.hasPrefix("/api/download/") else { throw APIError(kind: .badRequest, message: "Fichier hors du serveur VQuant.") }124 var r = APIRequest.get(path, timeout: 60); r.accept = "*/*"125 return try await client.data(r)126 }127128 // MARK: workspace129130 func workspace() async throws -> Workspace { try await client.decode(.get("/api/workspace")) }131 func addMemory(content: String, category: String) async throws -> Memory {132 try await client.decode(try .json("POST", "/api/workspace/memories", ["content": content, "category": category]))133 }134 func deleteMemory(_ id: String) async throws { _ = try await client.data(APIRequest(method: "DELETE", path: "/api/workspace/memories/\(id)")) }135 func upsertPosition(symbol: String, quantity: Double, costBasis: Double?, note: String?) async throws -> Position {136 struct Body: Encodable { var quantity: Double; var costBasis: Double?; var note: String? }137 let request = try APIRequest.json("PUT", "/api/workspace/portfolio/\(symbol)", Body(quantity: quantity, costBasis: costBasis, note: note))138 return try await client.decode(Position.self, request)139 }140 func removePosition(_ symbol: String) async throws { _ = try await client.data(APIRequest(method: "DELETE", path: "/api/workspace/portfolio/\(symbol)")) }141142 struct WatchDraft: Encodable, Sendable {143 var title: String; var prompt: String; var time: String; var days: String; var deep: Bool; var model: String?144 }145 func createWatch(_ draft: WatchDraft) async throws -> Watch { try await client.decode(try .json("POST", "/api/workspace/watches", draft)) }146 struct WatchPatch: Encodable, Sendable {147 var enabled: Bool?; var title: String?; var prompt: String?; var time: String?; var days: String?; var deep: Bool?148 }149 func updateWatch(_ id: String, _ patch: WatchPatch) async throws -> Watch { try await client.decode(try .json("PATCH", "/api/workspace/watches/\(id)", patch)) }150 func deleteWatch(_ id: String) async throws { _ = try await client.data(APIRequest(method: "DELETE", path: "/api/workspace/watches/\(id)")) }151 func runWatch(_ id: String) async throws { _ = try await client.data(.send("POST", "/api/workspace/watches/\(id)/run")) }152}153154enum MoverKind: String, CaseIterable, Sendable, Identifiable {155 case gainers, losers, actives156 var id: String { rawValue }157}158