diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ed2ff6c..21191b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,7 +9,7 @@ jobs: - name: Install build and isolated-test dependencies run: | apt-get update - DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ pkg-config libpq-dev libcurl4-openssl-dev libssl-dev libxml2-dev nlohmann-json3-dev libcpp-httplib-dev python3 postgresql openssl nodejs + DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ pkg-config libpq-dev libcurl4-openssl-dev libssl-dev libxml2-dev nlohmann-json3-dev libcpp-httplib-dev python3 postgresql openssl nodejs libgtk-3-dev xvfb xauth - name: Build and numerical checks run: | cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release diff --git a/CMakeLists.txt b/CMakeLists.txt index c99b692..8d400de 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,3 +28,23 @@ add_test(NAME core COMMAND core_tests) add_executable(release_tests tests/release_tests.cpp) target_link_libraries(release_tests PRIVATE nlohmann_json::nlohmann_json OpenSSL::Crypto LibXml2::LibXml2 CURL::libcurl) add_test(NAME release COMMAND release_tests) +option(REACH_BUILD_DESKTOP "Build the native GTK desktop frontend" ON) +if(REACH_BUILD_DESKTOP) + set(REACH_PREV_PKG_SYSROOT "$ENV{PKG_CONFIG_SYSROOT_DIR}") + set(REACH_PREV_PKG_PATH "$ENV{PKG_CONFIG_PATH}") + set(ENV{PKG_CONFIG_SYSROOT_DIR} "") + set(ENV{PKG_CONFIG_PATH} "") + pkg_check_modules(GTK3 QUIET IMPORTED_TARGET gtk+-3.0>=3.24) + set(ENV{PKG_CONFIG_SYSROOT_DIR} "${REACH_PREV_PKG_SYSROOT}") + set(ENV{PKG_CONFIG_PATH} "${REACH_PREV_PKG_PATH}") + if(GTK3_FOUND) + add_executable(reachterminal-desktop desktop/main.cpp desktop/pages.cpp) + target_link_libraries(reachterminal-desktop PRIVATE PkgConfig::GTK3 CURL::libcurl nlohmann_json::nlohmann_json Threads::Threads) + target_compile_options(reachterminal-desktop PRIVATE -Wall -Wextra) + add_executable(native_tests desktop/unit_tests.cpp) + target_link_libraries(native_tests PRIVATE PkgConfig::GTK3 CURL::libcurl nlohmann_json::nlohmann_json Threads::Threads) + add_test(NAME native-adapters COMMAND native_tests) + else() + message(STATUS "GTK 3.24 development files unavailable; install libgtk-3-dev for native frontend") + endif() +endif() diff --git a/README.md b/README.md index b7978a8..bfdbab8 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # ReachTerminal +默认使用 **C++ / GTK 原生桌面前端**,不需要浏览器或 WebView。编译后运行 `./scripts/desktop.sh`;参见 [原生桌面说明](docs/native-desktop.md)。IBKR 官方网关登录与双重验证仍使用其官方外部登录流程。 + An open-source, self-hosted investment research terminal. Browser frontend, C++20 backend, PostgreSQL database. No broker order submission code. diff --git a/desktop/api.hpp b/desktop/api.hpp new file mode 100644 index 0000000..58e54ef --- /dev/null +++ b/desktop/api.hpp @@ -0,0 +1,123 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using json = nlohmann::json; +class LocalApi { + std::string base, token, expected; + std::atomic &stopping; + std::chrono::steady_clock::time_point last{}; + json transport(const std::string &path, const std::string &body, bool post, + const std::string &type) { + if (!path.starts_with("/api/") || path.find('\r') != std::string::npos || + path.find('\n') != std::string::npos) + throw std::runtime_error("Invalid local API path"); + auto now = std::chrono::steady_clock::now(); + if (now - last < std::chrono::milliseconds(300)) + std::this_thread::sleep_for(std::chrono::milliseconds(300) - (now - last)); + last = std::chrono::steady_clock::now(); + auto c = curl_easy_init(); + if (!c) + throw std::runtime_error("Cannot initialize local connection"); + std::string data, url = base + path; + auto headers = curl_slist_append(nullptr, ("X-Reach-Token: " + token).c_str()); + headers = curl_slist_append(headers, ("Content-Type: " + type).c_str()); + curl_easy_setopt(c, CURLOPT_URL, url.c_str()); + curl_easy_setopt(c, CURLOPT_PROXY, ""); + curl_easy_setopt(c, CURLOPT_FOLLOWLOCATION, 0L); + curl_easy_setopt(c, CURLOPT_PROTOCOLS_STR, "http"); + curl_easy_setopt(c, CURLOPT_CONNECTTIMEOUT, 2L); + curl_easy_setopt(c, CURLOPT_TIMEOUT, 60L); + curl_easy_setopt(c, CURLOPT_NOSIGNAL, 1L); + curl_easy_setopt(c, CURLOPT_HTTPHEADER, headers); + if (post) { + curl_easy_setopt(c, CURLOPT_POST, 1L); + curl_easy_setopt(c, CURLOPT_POSTFIELDS, body.data()); + curl_easy_setopt(c, CURLOPT_POSTFIELDSIZE_LARGE, static_cast(body.size())); + } + curl_easy_setopt( + c, CURLOPT_WRITEFUNCTION, +[](char *p, size_t a, size_t b, void *u) -> size_t { + auto &s = *static_cast(u); + if (b && a > (32 * 1024 * 1024 - s.size()) / b) + return 0; + s.append(p, a * b); + return a * b; + }); + curl_easy_setopt(c, CURLOPT_WRITEDATA, &data); + curl_easy_setopt(c, CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt( + c, CURLOPT_XFERINFOFUNCTION, + +[](void *p, curl_off_t, curl_off_t, curl_off_t, curl_off_t) -> int { + return static_cast *>(p)->load() ? 1 : 0; + }); + curl_easy_setopt(c, CURLOPT_XFERINFODATA, &stopping); + auto code = curl_easy_perform(c); + long status = 0; + curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &status); + curl_slist_free_all(headers); + curl_easy_cleanup(c); + if (code != CURLE_OK) + throw std::runtime_error("本地后端连接失败:" + std::string(curl_easy_strerror(code)) + + "。请检查终端后端是否正在运行。"); + json v; + try { + v = json::parse(data); + } catch (...) { + throw std::runtime_error("本地后端返回无效数据"); + } + if (status < 200 || status >= 300) + throw std::runtime_error( + v.value("error", std::string("本地请求失败 HTTP ") + std::to_string(status))); + return v; + } + + public: + LocalApi(int port, const std::string &mode, std::atomic &stop) + : base("http://127.0.0.1:" + std::to_string(port)), expected(mode), stopping(stop) { + if (port < 1 || port > 65535) + throw std::runtime_error("Invalid local port"); + } + void connect() { + auto s = transport("/api/session", "", false, "application/json"); + if (s.value("environment", std::string()) != expected) + throw std::runtime_error("工作区环境不匹配,已拒绝连接以保护用户数据"); + token = s.at("token"); + } + json get(const std::string &p) { + if (token.empty()) + connect(); + return transport(p, "", false, "application/json"); + } + json post(const std::string &p, const json &v = json::object()) { + if (token.empty()) + connect(); + return transport(p, v.dump(), true, "application/json"); + } + json raw(const std::string &p, const std::string &v, const std::string &type) { + if (token.empty()) + connect(); + return transport(p, v, true, type); + } + static std::string encode(const std::string &s) { + std::string out; + const char *h = "0123456789ABCDEF"; + for (unsigned char c : s) { + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '-' || c == '_' || c == '.') + out += static_cast(c); + else { + out += '%'; + out += h[c >> 4]; + out += h[c & 15]; + } + } + return out; + } +}; diff --git a/desktop/main.cpp b/desktop/main.cpp new file mode 100644 index 0000000..0a9db6c --- /dev/null +++ b/desktop/main.cpp @@ -0,0 +1,78 @@ +#include "window.hpp" +#include +void Terminal::preview() { + if (snapshot.empty()) + return; + gtk_container_check_resize(GTK_CONTAINER(window)); + GtkAllocation allocation; + gtk_widget_get_allocation(window, &allocation); + gtk_widget_size_allocate(window, &allocation); + while (gtk_events_pending()) + gtk_main_iteration(); + int width = gtk_widget_get_allocated_width(window), + height = gtk_widget_get_allocated_height(window); + auto surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); + auto cr = cairo_create(surface); + gtk_widget_draw(window, cr); + cairo_destroy(cr); + auto result = cairo_surface_write_to_png(surface, snapshot.c_str()); + cairo_surface_destroy(surface); + if (result != CAIRO_STATUS_SUCCESS) { + testFailed = true; + std::cerr << "Cannot render native preview\n"; + } +} +int main(int argc, char **argv) { + bool test = false; + std::string image; + int port = 8788; + try { + if (auto p = std::getenv("REACH_DESKTOP_PORT")) + port = std::stoi(p); + for (int i = 1; i < argc; ++i) { + std::string a = argv[i]; + if (a == "--self-test") + test = true; + else if (a == "--snapshot" && i + 1 < argc) + image = argv[++i]; + else + throw std::runtime_error( + "Usage: reachterminal-desktop [--self-test] [--snapshot FILE]"); + } + if (port < 1 || port > 65535) + throw std::runtime_error("Invalid local port"); + curl_global_init(CURL_GLOBAL_DEFAULT); + int gtkArgc = 1; + if (!gtk_init_check(>kArgc, &argv)) + throw std::runtime_error("无法连接图形桌面;请在本机桌面会话运行原生终端。"); + auto css = gtk_css_provider_new(); + gtk_css_provider_load_from_data(css, R"CSS( + * { font-family: "Noto Sans", "DejaVu Sans", sans-serif; font-size: 13px; } + window, viewport {background:#0b121a;color:#d6e2eb;} box {color:#d6e2eb;} .rail {background:#111b27;border-right:1px solid #283746;} + .brand {color:#50ccba;font-size:24px;font-weight:bold;} .eyebrow {color:#53c6b7;font-size:11px;letter-spacing:1px;} .page-title {font-size:27px;font-weight:bold;} + .section-title {font-size:15px;font-weight:bold;color:#e4edf4;} .muted {color:#94a6b8;font-size:12px;} .metric {font-size:23px;font-weight:bold;color:#e4edf4;} + frame {border:1px solid #2a3948;border-radius:7px;background:#131e2a;} frame border {border:none;} label {padding:2px 0;} + button {background:#192836;color:#dbe7ef;border:1px solid #314453;border-radius:5px;padding:9px 13px;box-shadow:none;text-shadow:none;} + button:hover,button.selected {background:#1b4945;color:#77e3d3;border-color:#388d81;} button:disabled {color:#526675;background:#15202a;} + entry,spinbutton,combobox button,textview text {background:#0c1721;color:#dce7ef;border-color:#304252;} entry {padding:7px;} spinbutton entry {padding:7px;} + treeview {background:#111d28;color:#dbe7ef;} treeview:selected {background:#24564f;color:#ecfffa;} treeview header button {background:#182b3c;color:#a7c0d0;} + scrolledwindow {border:none;} .connection {color:#56cdbb;border-left:3px solid #56cdbb;padding:12px;} scrollbar slider {background:#3b5367;min-width:7px;min-height:24px;border-radius:5px;} +)CSS", + -1, nullptr); + gtk_style_context_add_provider_for_screen(gdk_screen_get_default(), GTK_STYLE_PROVIDER(css), + GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + g_object_unref(css); + Terminal terminal(port, test, image); + terminal.run(); + if (test) { + if (terminal.failed()) + return 1; + std::cout << "Native desktop: all 9 workspaces and hedge scenario verified in isolated " + "test environment\n"; + } + return 0; + } catch (const std::exception &e) { + std::cerr << "ReachTerminal Desktop: " << e.what() << '\n'; + return 1; + } +} diff --git a/desktop/pages.cpp b/desktop/pages.cpp new file mode 100644 index 0000000..92e3ff0 --- /dev/null +++ b/desktop/pages.cpp @@ -0,0 +1,880 @@ +#include "window.hpp" +void Terminal::overview() { + title("PORTFOLIO / USD BASE", "组合总览", + "现金股票 FIFO · 策略归属 · 历史汇率 · 日末资金流近似收益"); + get("/api/portfolio?" + query(), [this](const json &p) { + stats(content, {{"净资产 · USD", p.value("nav", json(nullptr))}, + {"经济盈亏 · USD", p.value("economic_pnl", json(nullptr))}, + {"股票市值", p.value("market_value", json(nullptr))}, + {"现金余额", p.value("cash_value", json(nullptr))}}); + auto b = panel(content, "组合表现"); + chart(b, p.value("curve", json::array()), "return_index", "RETURN INDEX · BASE 100"); + b = panel(content, "策略持仓"); + std::vector> rows; + for (auto &r : p["positions"]) + rows.push_back({field(r, "symbol"), field(r, "strategy"), field(r, "quantity"), + field(r, "cost_local"), field(r, "market_value_base"), + field(r, "realized_base"), field(r, "unrealized_base")}); + table(b, {"标的", "策略", "数量", "本币成本", "市值 · USD", "已实现盈亏", "未实现盈亏"}, + rows); + auto note = panel(content, "核算质量"); + add(note, + label(p.value("complete", false) ? "必要估值数据齐全;历史是否完整仍需经纪商对账。" + : "估值数据不完整;缺失金额不以零替代。", + "muted")); + for (auto &w : p.value("warnings", json::array())) + add(note, label(text(w))); + b = panel(content, "现金"); + rows.clear(); + for (auto &r : p["cash"]) + rows.push_back({field(r, "account"), field(r, "currency"), field(r, "amount"), + field(r, "base_value")}); + table(b, {"账户", "币种", "余额", "折算 · USD"}, rows, 150); + }); +} +void Terminal::research() { + title("FUNDAMENTALS / POINT IN TIME", "公司研究", + "按披露日期查看财报和估值指标;双击财务事实可在下方查看来源。"); + if (selected.empty()) { + add(content, label("先在数据中心导入或注册研究标的。")); + return; + } + get(researchPath(), [this](const json &r) { + auto b = panel(content, field(r["instrument_info"], "name")); + keyValues(b, r["metrics"]); + b = panel(content, "原始日线 · 未复权"); + auto bars = r.value("bars", json::array()); + std::sort(bars.begin(), bars.end(), [](auto &a, auto &b) { + return a.value("date", std::string()) < b.value("date", std::string()); + }); + chart(b, bars, "close", "DAILY CLOSE · " + field(r["instrument_info"], "currency")); + b = panel(content, "当前分析日期可用的财务事实"); + auto facts = r.value("selected", json::array()); + std::vector> rows; + for (auto &f : facts) + rows.push_back({field(f, "concept"), field(f, "value"), field(f, "unit"), + field(f, "period_end"), field(f, "filed"), field(f, "source")}); + auto view = table(b, {"项目", "值", "单位", "报告期", "披露日期", "来源"}, rows, 320); + auto detail = label("选择一项事实查看原始来源。", "muted"); + gtk_label_set_selectable(GTK_LABEL(detail), true); + add(b, detail); + activateRow(view, [facts, detail](int i) { + if (i >= 0 && static_cast(i) < facts.size()) + gtk_label_set_text( + GTK_LABEL(detail), + (field(facts[i], "source_url") + "\nAccession: " + field(facts[i], "accession")) + .c_str()); + }); + b = panel(content, "财务披露历史 · 包含季度与重述"); + rows.clear(); + for (auto &f : r.value("history", json::array())) + rows.push_back({field(f, "concept"), field(f, "value"), field(f, "unit"), + field(f, "period_kind"), field(f, "period_end"), field(f, "filed"), + field(f, "source")}); + table(b, {"项目", "值", "单位", "期间类型", "报告期", "披露日期", "来源"}, rows, 240); + }); + auto peerPanel = panel(content, "同业比较 · 同一分析日期"); + get("/api/peers?" + query(), [peerPanel](const json &rows) { + std::vector> cells; + for (auto &p : rows) { + auto i = p["instrument"], m = p["metrics"]; + cells.push_back({field(i, "symbol"), field(i, "currency"), field(m, "pe"), + field(m, "pb"), field(m, "fcf_yield"), field(m, "net_margin")}); + } + table(peerPanel, {"标的", "币种", "市盈率", "市净率", "现金流收益率", "净利率"}, cells, + 170); + }); +} +void Terminal::valuation() { + title("VALUATION / ASSUMPTIONS", "估值工作台", + "自由现金流假设由你填写;默认示例不来自公司财报。金融企业不适用此模型。"); + if (selected.empty()) { + add(content, label("请先选择研究标的。")); + return; + } + auto b = panel(content, "现金流折现 · FCFF"); + auto fcff = number(1e8, .01), growth = number(5, -94, 100), wacc = number(10, .001, 100), + terminal = number(2, -49, 99), debt = number(0), shares = number(1e8, .01), + years = number(5, 1, 20, 1), ccy = entry("USD"), name = entry("基准估值"); + for (auto &i : instruments) + if (i["id"] == selected) + gtk_entry_set_text(GTK_ENTRY(ccy), field(i, "currency").c_str()); + gtk_editable_set_editable(GTK_EDITABLE(ccy), false); + form(b, {{"基期 FCFF · 本币", fcff}, + {"预测增长率 %", growth}, + {"资本成本 %", wacc}, + {"永续增长率 %", terminal}, + {"净债务 · 本币", debt}, + {"普通股股数", shares}, + {"预测年数", years}, + {"模型币种", ccy}, + {"版本名称", name}}); + auto result = panel(content, "估值结果"); + auto assumptions = [=, this] { + std::string sector; + for (auto &i : instruments) + if (i["id"] == selected) + sector = i.value("sector", std::string()); + return json{{"fcff", numeric(fcff)}, + {"growth", numeric(growth) / 100}, + {"wacc", numeric(wacc) / 100}, + {"terminal_growth", numeric(terminal) / 100}, + {"net_debt", numeric(debt)}, + {"shares", numeric(shares)}, + {"years", static_cast(numeric(years))}, + {"currency", value(ccy)}, + {"sector", sector}}; + }; + auto calculate = [=, this] { + auto a = assumptions(); + request( + [a](LocalApi &api) { + json out = {{"base", api.post("/api/dcf", a)}, {"rows", json::array()}}; + double w = a["wacc"], g = a["terminal_growth"]; + for (double dw : {-0.01, 0.0, 0.01}) { + json row = json::array({(w + dw) * 100}); + for (double dg : {-0.005, 0.0, 0.005}) { + if (w + dw <= 0 || w + dw <= g + dg) { + row.push_back(nullptr); + continue; + } + auto v = a; + v["wacc"] = w + dw; + v["terminal_growth"] = g + dg; + row.push_back(api.post("/api/dcf", v)["per_share"]); + } + out["rows"].push_back(row); + } + out["growth"] = g * 100; + return out; + }, + [=, this](const json &out) { + auto r = out["base"]; + clear(result); + stats(result, {{"每股价值 · " + field(r, "currency"), r["per_share"]}, + {"企业价值", r["enterprise_value"]}, + {"股权价值", r["equity_value"]}, + {"终值占比", r["terminal_share"]}}); + add(result, label("敏感性 · 每股价值(无效假设显示为空)", "section-title")); + double g = out["growth"]; + std::vector> rows; + for (auto &row : out["rows"]) + rows.push_back({text(row[0]) + "%", text(row[1]), text(row[2]), text(row[3])}); + table(result, + {"WACC / 永续增长", text(g - .5) + "%", text(g) + "%", text(g + .5) + "%"}, + rows, 150); + }); + }; + add(b, button("计算估值与敏感性", calculate)); + if (testMode) + calculate(); + add(b, button("保存估值版本", [=, this] { + post("/api/valuations", + {{"instrument", selected}, + {"date", value(dateBox)}, + {"title", value(name)}, + {"assumptions", assumptions()}}, + [this](const json &) { footer("估值版本已保存"); }); + })); + get(researchPath(), [this](const json &r) { + auto b = panel(content, "历史估值版本"); + std::vector> rows; + for (auto &v : r.value("valuations", json::array())) + rows.push_back({field(v, "date"), field(v, "title"), field(v["result"], "per_share"), + field(v["result"], "currency")}); + table(b, {"日期", "方案", "每股价值", "币种"}, rows, 160); + }); +} +void Terminal::risk() { + title("RISK / STRATEGY", "风险与策略", + "现金股票与外汇联合冲击;衍生品和保证金使用各自工作区。"); + auto b = panel(content, "组合压力情景"); + auto equity = number(-10, -100, 100), fx = number(-5, -100, 100); + form(b, {{"股票价格冲击 %", equity}, {"非美元兑美元冲击 %", fx}}); + auto result = box(); + add(b, result); + add(b, button("重新估值", [=, this] { + post("/api/stress", + {{"as_of", value(dateBox)}, + {"equity_shock", numeric(equity) / 100}, + {"fx_shock", numeric(fx) / 100}}, + [this, result](const json &r) { + clear(result); + stats(result, + {{"情景损益 · USD", r["pnl"]}, {"冲击后净资产", r["nav_after"]}}); + }); + })); + get("/api/portfolio?" + query(), [this](const json &p) { + for (auto pair : std::vector>{ + {"行业敞口", "sector_exposure"}, {"币种敞口", "currency_exposure"}}) { + auto b = panel(content, pair.first); + auto values = p.value(pair.second, json::object()); + std::vector> rows; + if (values.is_object()) + for (auto &[k, v] : values.items()) + rows.push_back({k, text(v)}); + table(b, {"类别", "股票市值 · USD"}, rows, 150); + } + auto b = panel(content, "策略核算"); + auto strategies = p.value("strategies", json::array()); + if (strategies.is_object()) + keyValues(b, strategies); + else if (strategies.is_array()) { + std::vector> rows; + for (auto &r : strategies) + rows.push_back({field(r, "name"), field(r, "realized_base"), + field(r, "unrealized_base"), field(r, "market_value_base")}); + table(b, {"策略", "已实现盈亏", "未实现盈亏", "市值"}, rows); + } + add(b, label("近似收益指数最大回撤:" + field(p, "max_drawdown"))); + }); +} +void Terminal::news() { + title("INTELLIGENCE / RESEARCH JOURNAL", "新闻与研究", + "官方新闻摘要、来源与公司投资论点;原文链接为可选外部阅读。"); + auto actions = box(true); + add(content, actions); + add(actions, button("获取美联储官方新闻", [this] { + post("/api/news/fetch", json::object(), [this](const json &) { render(4); }); + })); + auto items = panel(content, "新闻与公告"); + get("/api/news?" + query(), [this, items](const json &rows) { + if (rows.empty()) + add(items, label("当前分析日期没有已导入的新闻。")); + for (auto &n : rows) { + auto item = panel(items, field(n, "title")); + add(item, label(field(n, "date") + " · " + field(n, "source"), "eyebrow")); + add(item, label(n.value("summary", std::string()))); + auto url = n.value("source_url", std::string()); + add(item, button("查看原文来源(外部)", [this, url] { + try { + uri(url); + } catch (const std::exception &e) { + footer(e.what()); + } + })); + } + }); + if (!selected.empty()) { + auto b = panel(content, "投资论点"); + auto name = entry(""), body = gtk_text_view_new(); + gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(body), GTK_WRAP_WORD_CHAR); + gtk_widget_set_size_request(body, -1, 140); + form(b, {{"标题", name}}); + add(b, body); + add(b, button("保存研究笔记", [=, this] { + auto buf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(body)); + GtkTextIter a, z; + gtk_text_buffer_get_bounds(buf, &a, &z); + auto p = gtk_text_buffer_get_text(buf, &a, &z, false); + std::string note = p; + g_free(p); + post("/api/notes", + {{"instrument", selected}, + {"date", value(dateBox)}, + {"title", value(name)}, + {"body", note}}, + [this](const json &) { render(4); }); + })); + get(researchPath(), [b](const json &r) { + for (auto &n : r.value("notes", json::array())) { + add(b, label(field(n, "date") + " · " + field(n, "title"), "section-title")); + add(b, label(field(n, "body"))); + } + }); + } +} +void Terminal::gatewayCheck(GtkWidget *line, GtkWidget *prepare, GtkWidget *) { + if (brokerBusy) + return; + brokerBusy = true; + request([](LocalApi &a) { return a.post("/api/ibkr/connection"); }, + [=, this](const json &r) { + brokerBusy = false; + bool ready = r.value("market_ready", r.value("authenticated", false)); + std::string msg; + if (r.value("competing", false)) + msg = "检测到竞争行情会话,请核对其他设备或 TWS。"; + else if (r.value("initializing", false)) + msg = "账户已登录,行情正在初始化并检查账户握手;请等待就绪。"; + else if (ready) { + msg = "登录成功:行情会话已认证,可以搜索标的并准备行情。"; + stopMonitor(); + } else if (r.contains("sso_valid") && r["sso_valid"] == true) + msg = "账户登录成功;行情未认证。可点击“连接行情会话(不抢占)”。"; + else if (r.contains("sso_valid") && r["sso_valid"] == false) + msg = "账户登录尚未确认,请完成官方授权和双重验证。"; + else + msg = "状态未知:" + r.value("sso_error", std::string("账户验证暂未返回结果")); + msg += "\n检测时间:" + epochText(r.value("checked_at_ms", json(nullptr))) + + ";账户验证时间:" + epochText(r.value("sso_checked_at_ms", json(nullptr))) + + "(最多每60秒验证)"; + gtk_label_set_text(GTK_LABEL(line), msg.c_str()); + gtk_widget_set_sensitive(prepare, ready); + }, + [=, this](const std::string &e) { + brokerBusy = false; + gtk_label_set_text(GTK_LABEL(line), ("检测失败:" + e).c_str()); + gtk_widget_set_sensitive(prepare, false); + }); +} +void Terminal::data() { + title("DATA / DEVICE-LOCAL CONNECTIVITY", "数据中心", + "本机网关独立配置 · 导入导出 · SEC 财报 · 真实市场数据"); + auto b = panel(content, "IBKR 网关连接"); + auto line = label("正在检测本机连接…", "connection"); + auto actions = box(true); + auto results = box(); + auto prepare = button("准备行情", [=, this] { + post("/api/ibkr/prepare", json::object(), [line](const json &) { + gtk_label_set_text(GTK_LABEL(line), "行情准备完成;首次快照可能仍需要预热。"); + }); + }); + gtk_widget_set_sensitive(prepare, false); + auto watch = [=, this] { + stopMonitor(); + deadline = g_get_monotonic_time() + 180000000; + struct Monitor { + Terminal *t; + GtkWidget *line, *prepare, *results; + }; + auto context = new Monitor{this, line, prepare, results}; + monitor = g_timeout_add_seconds_full( + G_PRIORITY_DEFAULT, 5, + +[](gpointer p) -> gboolean { + auto m = static_cast(p); + auto t = m->t; + if (t->pageIndex != 5 || t->stopping) + return G_SOURCE_REMOVE; + if (g_get_monotonic_time() >= t->deadline) { + gtk_label_set_text(GTK_LABEL(m->line), + "等待确认超时,不能据此判断登录失败。请手动重新检测。"); + t->monitor = 0; + t->deadline = 0; + return G_SOURCE_REMOVE; + } + t->gatewayCheck(m->line, m->prepare, m->results); + return G_SOURCE_CONTINUE; + }, + context, +[](gpointer p) { delete static_cast(p); }); + }; + get("/api/ibkr/settings", [=, this](const json &s) { + auto port = number(s.value("port", 5000), 1024, 65535, 1), ca = gtk_text_view_new(); + gtk_widget_set_size_request(ca, -1, 90); + gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(ca), GTK_WRAP_WORD_CHAR); + add(b, label("设备:" + field(s, "device") + " · " + field(s, "scope") + + "。配置、网关和登录状态不可迁移。", + "muted")); + form(b, {{"本机网关端口", port}}); + add(b, label("公开 CA 证书 " + "PEM(只填写公开证书,不填写密码或私钥;留空重新保存会清除现有自定义证书)", + "muted")); + add(b, ca); + add(b, button("保存本机连接设置", [=, this] { + stopMonitor(); + revision++; + brokerBusy = false; + contract.clear(); + clear(results); + auto buf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ca)); + GtkTextIter a, z; + gtk_text_buffer_get_bounds(buf, &a, &z); + auto raw = gtk_text_buffer_get_text(buf, &a, &z, false); + std::string pem = raw; + g_free(raw); + post("/api/ibkr/settings", + {{"port", static_cast(numeric(port))}, {"ca_pem", pem}}, + [=, this](const json &) { + gtk_label_set_text(GTK_LABEL(line), + "连接设置已保存,请重新检测登录状态。"); + gtk_widget_set_sensitive(prepare, false); + }); + })); + if (s.contains("login_url") && s["login_url"].is_string()) { + auto url = s["login_url"].get(); + add(actions, button("IBKR 官方授权(外部)", [=, this] { + try { + uri(url); + watch(); + gatewayCheck(line, prepare, results); + } catch (const std::exception &e) { + footer(e.what()); + } + })); + } else + add(actions, label("隔离环境:禁止打开真实授权页面")); + add(b, actions); + add(actions, button("检测状态", [=, this] { gatewayCheck(line, prepare, results); })); + add(actions, button("连接行情(不抢占)", [=, this] { + request([](LocalApi &a) { return a.post("/api/ibkr/connect-market"); }, + [=, this](const json &) { + watch(); + gatewayCheck(line, prepare, results); + }, + [line](const std::string &e) { + gtk_label_set_text(GTK_LABEL(line), e.c_str()); + }); + })); + add(actions, prepare); + add(actions, button("登出", [=, this] { + stopMonitor(); + revision++; + brokerBusy = false; + contract.clear(); + brokerAccounts = json::array(); + clear(results); + gtk_widget_set_sensitive(prepare, false); + request( + [](LocalApi &a) { return a.post("/api/ibkr/logout"); }, + [line](const json &) { + gtk_label_set_text(GTK_LABEL(line), "网关已确认退出;本地查询状态已清除。"); + }, + [line](const std::string &e) { + gtk_label_set_text(GTK_LABEL(line), + ("本地查询已清除,但远端退出尚未确认:" + e).c_str()); + }, + false, true); + })); + add(b, line); + gatewayCheck(line, prepare, results); + }); + auto searchPanel = panel(content, "全球标的搜索 · 只读预览"); + auto term = entry("IBM"), by = combo({{"symbol", "证券代码"}, {"name", "公司名称"}}); + form(searchPanel, {{"搜索内容", term}, {"搜索方式", by}}); + add(searchPanel, button("搜索 IBKR 标的", [=, this] { + post("/api/ibkr/search", {{"query", value(term)}, {"by_name", chosen(by) == "name"}}, + [=, this](const json &rows) { + clear(results); + std::vector> cells; + for (auto &r : rows) + cells.push_back({field(r, "conid"), field(r, "symbol"), + field(r, "companyName"), field(r, "companyHeader")}); + auto view = table(results, {"合约 ID", "代码", "名称", "市场"}, cells); + add(results, + label("双击合约行获取详情。此查询不会写入持仓或价格账本。", "muted")); + activateRow(view, [=, this](int i) { + if (i < 0 || static_cast(i) >= rows.size()) + return; + contract = rows[i]["conid"].get(); + auto selectedConid = contract; + post("/api/ibkr/detail", {{"conid", selectedConid}}, + [=, this](const json &r) { + auto detail = panel(results, "已选合约"); + keyValues(detail, r); + auto dataBox = box(); + add(detail, dataBox); + add(detail, button("获取快照", [=, this] { + post("/api/ibkr/snapshot", {{"conid", selectedConid}}, + [=](const json &s) { + clear(dataBox); + add(dataBox, label("行情可用性:" + + field(s, "availability"))); + std::vector> rows; + for (auto &v : s["fields"]) + rows.push_back( + {field(v, "label"), field(v, "value")}); + table(dataBox, {"指标", "原始值"}, rows); + }); + })); + add(detail, button("获取近月日线", [=, this] { + post("/api/ibkr/history", {{"conid", selectedConid}}, + [=](const json &s) { + clear(dataBox); + auto bars = s.value("bars", json::array()); + chart(dataBox, bars, "c", "IBKR DAILY PREVIEW"); + std::vector> rows; + for (auto &v : bars) + rows.push_back({field(v, "timestamp"), + field(v, "o"), field(v, "h"), + field(v, "l"), field(v, "c"), + field(v, "v")}); + table(dataBox, + {"时间戳", "开盘", "最高", "最低", "收盘", + "成交量"}, + rows); + }); + })); + }); + }); + }); + })); + add(searchPanel, results); + auto registration = panel(content, "注册现金股票研究标的"); + auto identifier = entry(""), symbol = entry(""), company = entry(""), exchange = entry("XNYS"), + country = entry("USA"), sector = entry("Technology"), currency = entry("USD"), + sec = entry(""); + form(registration, {{"内部标识(唯一)", identifier}, + {"证券代码", symbol}, + {"公司名称", company}, + {"交易所", exchange}, + {"国家/地区", country}, + {"行业", sector}, + {"币种", currency}, + {"SEC CIK(可选)", sec}}); + add(registration, button("注册研究标的", [=, this] { + json i = {{"id", value(identifier)}, {"symbol", value(symbol)}, + {"name", value(company)}, {"exchange", value(exchange)}, + {"country", value(country)}, {"sector", value(sector)}, + {"currency", value(currency)}, {"asset_class", "STK"}}; + if (!value(sec).empty()) + i["sec_cik"] = value(sec); + post("/api/import", {{"instruments", json::array({i})}}, + [this](const json &) { reloadInstruments(); }); + })); + add(registration, button("刷新研究标的列表", [this] { reloadInstruments(); })); + auto io = panel(content, "导入与导出"); + auto format = combo( + {{"normalized", "标准 JSON"}, {"flex", "IBKR Flex XML"}, {"sec", "SEC CompanyFacts JSON"}}); + form(io, {{"文件格式", format}}); + add(io, button("选择文件并导入", [=, this] { + auto path = chooseFile(false, "导入本地研究数据"); + if (path.empty()) + return; + auto kind = chosen(format), instrument = selected; + request( + [path, kind, instrument](LocalApi &a) { + std::ifstream f(path, std::ios::binary); + if (!f) + throw std::runtime_error("无法打开导入文件"); + std::string body((std::istreambuf_iterator(f)), {}); + if (body.size() > 32 * 1024 * 1024) + throw std::runtime_error("导入文件超过32MB"); + auto endpoint = kind == "flex" ? "/api/import/flex" + : kind == "sec" ? "/api/import/sec?instrument=" + + LocalApi::encode(instrument) + : "/api/import"; + return a.raw(endpoint, body, + kind == "flex" ? "application/xml" : "application/json"); + }, + [this](const json &r) { + footer("导入完成:新增 " + field(r, "inserted") + ",重复 " + + field(r, "duplicates") + "。研究标的列表已刷新。"); + reloadInstruments(); + }, + {}, true, true); + })); + add(io, button("导出完整工作区", [this] { + auto path = chooseFile(true, "保存本地工作区备份"); + if (path.empty()) + return; + request( + [path](LocalApi &a) { + auto r = a.get("/api/export"); + std::ofstream f(path); + if (!f) + throw std::runtime_error("无法写入导出文件"); + if (chmod(path.c_str(), 0600) != 0) + throw std::runtime_error("无法保护备份文件权限"); + f << r.dump(2); + f.flush(); + if (!f) + throw std::runtime_error("导出写入失败"); + return json::object(); + }, + [this](const json &) { footer("本地工作区备份已保存"); }, {}, true, true); + })); + auto sources = panel(content, "免费财报与日线"); + auto cik = entry(""); + for (auto &i : instruments) + if (i["id"] == selected) + gtk_entry_set_text(GTK_ENTRY(cik), i.value("sec_cik", std::string()).c_str()); + form(sources, {{"当前标的 SEC CIK", cik}}); + add(sources, button("抓取 SEC 财报", [=, this] { + post("/api/sec/fetch", {{"instrument", selected}, {"cik", value(cik)}}, + [this](const json &r) { footer("SEC 财报已导入:" + field(r, "inserted")); }); + })); + add(sources, button("获取公开日线", [this] { + post("/api/market/daily", {{"instrument", selected}}, + [this](const json &r) { footer("日线已导入:" + field(r, "inserted")); }); + })); + add(sources, label("服务端管理真实联系邮箱和个人数据密钥;IBM " + "支持公开试用。桌面程序不复制密钥或其他设备状态。", + "muted")); +} +json Terminal::hedgeInputs(GtkWidget *ccy, GtkWidget *shock, GtkWidget *vol, GtkWidget *days) { + json positions = json::array(); + GtkTreeIter it; + bool valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(hedgeStore), &it); + while (valid) { + std::vector cells; + for (int i = 0; i < 12; ++i) { + gchar *p = nullptr; + gtk_tree_model_get(GTK_TREE_MODEL(hedgeStore), &it, i, &p, -1); + cells.emplace_back(p ? p : ""); + g_free(p); + } + auto num = [&](int i) { + size_t used = 0; + double n = std::stod(cells[i], &used); + if (used != cells[i].size() || !std::isfinite(n)) + throw std::runtime_error("假设持仓数值无效,请使用小数点:" + cells[i]); + return n; + }; + json p = {{"id", cells[0]}, {"type", cells[1]}, {"underlying", cells[2]}, + {"spot", num(3)}, {"quantity", num(4)}, {"multiplier", num(5)}}; + if (cells[1] == "OPT") { + p["right"] = cells[6]; + p["strike"] = num(7); + p["years"] = num(8); + p["volatility"] = num(9) / 100; + p["rate"] = num(10) / 100; + p["yield"] = num(11) / 100; + p["style"] = "European"; + } + positions.push_back(p); + valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(hedgeStore), &it); + } + return {{"currency", value(ccy)}, + {"positions", positions}, + {"scenario", + {{"spot", numeric(shock) / 100}, + {"volatility", numeric(vol) / 100}, + {"days", numeric(days)}}}}; +} +void Terminal::hedgeResult(GtkWidget *result, const json &r) { + if (testMode && (std::abs(r["market_value"].get() - 10602.79) > .02 || + std::abs(r["scenario_pnl"].get() + 353.39) > .02)) + throw std::runtime_error("Native hedge input mapping failed reference values"); + lastHedge = r; + clear(result); + add(result, label("模型结果 · " + field(r, "currency"), "section-title")); + stats(result, {{"模型市值", r["market_value"]}, + {"情景损益", r["scenario_pnl"]}, + {"Vega / +1百分点", r["vega_1pp"]}, + {"Theta / 日", r["theta_day"]}}); + std::vector> rows; + for (auto &[u, g] : r["underlyings"].items()) + rows.push_back({u, field(g, "delta_units"), field(g, "delta_notional"), + field(g, "gamma_half_notional"), field(g, "delta_neutral_stock_units")}); + table(result, {"标的", "Delta 单位", "Delta 名义敞口", "Gamma × S² / 2", "理论股票对冲数量"}, + rows, 130); + add(result, label("对冲数量仅中和当前模型 " + "Delta。情景采用全量重估;不计算券商保证金、期货基差或美式提前行权。", + "muted")); +} +void Terminal::hedge() { + title("DERIVATIVES / SCENARIO LAB", "衍生品对冲", + "独立单币种假设组合 · 原生可编辑持仓表 · 欧式期权与线性期货"); + auto b = panel(content, "组合假设"); + auto name = entry("保护性看跌示例"), ccy = entry("USD"), shock = number(-10, -99, 200), + vol = number(5, -490, 490), days = number(7, 0, 3650, 1); + form(b, {{"方案名称", name}, + {"币种", ccy}, + {"价格冲击 %", shock}, + {"波动率变化 · 百分点", vol}, + {"时间流逝 · 天", days}}); + add(b, label("以下为假设案例,不是账户持仓。双击表格单元格编辑;数值使用小数点。STK " + "股数、OPT/FUT 合约张数;真实合约乘数须自行核对。", + "muted")); + std::vector types(12, G_TYPE_STRING); + hedgeStore = gtk_list_store_newv(12, types.data()); + auto view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(hedgeStore)); + g_object_unref(hedgeStore); + const std::vector headers = {"编号", "STK/OPT/FUT", "标的标识", "现价", + "数量", "乘数", "call/put", "行权价", + "期限/年", "波动率%", "利率%", "收益率%"}; + for (int i = 0; i < 12; ++i) { + auto renderer = gtk_cell_renderer_text_new(); + g_object_set(renderer, "editable", TRUE, nullptr); + struct Edit { + GtkListStore *store; + int col; + }; + auto edit = new Edit{hedgeStore, i}; + g_signal_connect_data( + renderer, "edited", + G_CALLBACK((+[](GtkCellRendererText *, gchar *path, gchar *value, gpointer p) { + auto e = static_cast(p); + GtkTreeIter it; + if (gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(e->store), &it, path)) + gtk_list_store_set(e->store, &it, e->col, value, -1); + })), + edit, +[](gpointer p, GClosure *) { delete static_cast(p); }, + G_CONNECT_DEFAULT); + auto col = gtk_tree_view_column_new_with_attributes(headers[i].c_str(), renderer, "text", i, + nullptr); + gtk_tree_view_column_set_resizable(col, true); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); + } + auto append = [this](const std::vector &row) { + GtkTreeIter it; + gtk_list_store_append(hedgeStore, &it); + for (int i = 0; i < 12; ++i) + gtk_list_store_set(hedgeStore, &it, i, row[i].c_str(), -1); + }; + append({"stock", "STK", "MODEL", "100", "100", "1", "call", "100", "0.5", "25", "4", "0"}); + append({"put", "OPT", "MODEL", "100", "1", "100", "put", "100", "0.5", "25", "4", "0"}); + auto scroll = gtk_scrolled_window_new(nullptr, nullptr); + gtk_widget_set_size_request(scroll, -1, 170); + gtk_container_add(GTK_CONTAINER(scroll), view); + add(b, scroll); + auto actions = box(true); + add(b, actions); + add(actions, button("增加持仓", [append] { + append({"position-" + std::to_string(g_get_real_time()), "STK", "MODEL", "100", "100", + "1", "call", "100", "0.5", "25", "4", "0"}); + })); + add(actions, button("删除选中持仓", [this, view] { + GtkTreeIter it; + auto sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); + if (gtk_tree_selection_get_selected(sel, nullptr, &it)) + gtk_list_store_remove(hedgeStore, &it); + })); + auto result = panel(content, "对冲与情景结果"); + auto analyze = [=, this] { + try { + auto assumptions = hedgeInputs(ccy, shock, vol, days); + post("/api/hedge/analyze", assumptions, + [=, this](const json &r) { hedgeResult(result, r); }); + } catch (const std::exception &e) { + footer(e.what()); + if (testMode) + testFailed = true; + } + }; + add(actions, button("计算对冲与情景", analyze)); + add(actions, button("保存方案版本", [=, this] { + try { + post("/api/hedge/models", + {{"title", value(name)}, + {"date", value(dateBox)}, + {"assumptions", hedgeInputs(ccy, shock, vol, days)}}, + [this](const json &) { footer("方案版本已保存,刷新后可以加载"); }); + } catch (const std::exception &e) { + footer(e.what()); + } + })); + auto saved = panel(content, "历史方案 · 双击加载"); + get("/api/hedge/models?" + query(), [=, this](const json &models) { + std::vector> rows; + for (auto &m : models) + rows.push_back({field(m, "date"), field(m, "title"), field(m["result"], "scenario_pnl"), + field(m["result"], "currency")}); + auto list = table(saved, {"日期", "方案", "情景损益", "币种"}, rows, 140); + activateRow(list, [=, this](int i) { + if (i < 0 || static_cast(i) >= models.size()) + return; + auto m = models[i], a = m["assumptions"]; + gtk_entry_set_text(GTK_ENTRY(name), field(m, "title").c_str()); + gtk_entry_set_text(GTK_ENTRY(ccy), field(a, "currency").c_str()); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(shock), + a["scenario"]["spot"].get() * 100); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(vol), + a["scenario"]["volatility"].get() * 100); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(days), a["scenario"]["days"].get()); + gtk_list_store_clear(hedgeStore); + for (auto &p : a["positions"]) + append({field(p, "id"), field(p, "type"), field(p, "underlying"), field(p, "spot"), + field(p, "quantity"), field(p, "multiplier"), + p.value("right", std::string("call")), field(p, "strike"), + field(p, "years"), text(p.value("volatility", .25) * 100), + text(p.value("rate", .04) * 100), text(p.value("yield", 0.) * 100)}); + hedgeResult(result, m["result"]); + }); + }); + if (testMode) + analyze(); +} +void Terminal::margin() { + title("BROKER / MARGIN MONITOR", "保证金监控", + "券商报告汇总 · 本设备会话 · 账户及金额只在当前窗口预览"); + auto b = panel(content, "账户连接"); + auto accounts = gtk_combo_box_text_new(); + form(b, {{"本机账户", accounts}}); + auto result = panel(content, "保证金报告"); + add(b, button("读取本机账户列表", [=, this] { + post("/api/ibkr/accounts", json::object(), [=, this](const json &rows) { + brokerAccounts = rows; + gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(accounts)); + for (auto &r : rows) + gtk_combo_box_text_append( + GTK_COMBO_BOX_TEXT(accounts), r["id"].get().c_str(), + (field(r, "id") + " · " + field(r, "currency")).c_str()); + if (!rows.empty()) + gtk_combo_box_set_active(GTK_COMBO_BOX(accounts), 0); + }); + })); + add(b, button("读取保证金", [=, this] { + post("/api/ibkr/margin", {{"account", chosen(accounts)}}, [=](const json &r) { + clear(result); + std::string state = r.value("status", std::string()); + add(result, label(state == "critical" ? "剩余流动性不足" + : state == "low-buffer" ? "流动性缓冲偏低" + : state == "reported" ? "券商已报告" + : "数据不足或过期,状态未知", + "section-title")); + add(result, label("剩余流动性 / 净清算值:" + field(r, "liquidity_ratio"))); + std::vector> rows; + for (auto &v : r["fields"]) + rows.push_back({field(v, "label"), field(v, "value"), field(v, "currency"), + epochText(v.value("broker_timestamp", json(nullptr))), + v.value("stale", true) ? "过期 / 未知" : "近期"}); + table(result, {"券商字段", "值", "币种", "券商更新时间 · UTC", "时效"}, rows, 300); + }); + })); + add(b, label("最短刷新间隔10秒;超过120秒的券商时间戳标记为过期。10%" + "仅是本地提醒阈值,不推断强平价格;不叠加证券与商品分项。", + "muted")); +} +void Terminal::macro() { + title("GLOBAL / MACRO OBSERVATORY", "宏观数据", + "世界银行年度 GDP、实际增长和 CPI 通胀 · 保存抓取版本"); + auto b = panel(content, "官方数据"); + auto country = combo({{"USA", "美国"}, + {"CHN", "中国"}, + {"DEU", "德国"}, + {"JPN", "日本"}, + {"GBR", "英国"}, + {"HKG", "中国香港"}, + {"FRA", "法国"}, + {"IND", "印度"}, + {"BRA", "巴西"}, + {"AUS", "澳大利亚"}}), + indicator = combo( + {{"gdp", "名义 GDP"}, {"growth", "实际 GDP 增速"}, {"inflation", "居民消费价格通胀"}}); + form(b, {{"国家 / 地区", country}, {"指标", indicator}}); + add(b, button("抓取年度数据", [=, this] { + post("/api/macro/fetch", + {{"country", chosen(country)}, {"indicator", chosen(indicator)}}, + [this](const json &) { render(8); }); + })); + add(b, label("报告期不等于发布日期。历史发布日期未知,从实际抓取日期起允许历史分析使用;缺失值" + "保持为空。", + "muted")); + get("/api/macro?" + query(), [this](const json &r) { + auto b = panel(content, "年度观测"); + auto rows = r["observations"]; + std::vector> cells; + std::vector> series; + std::set keys; + for (auto &o : rows) { + cells.push_back({field(o, "country"), field(o, "indicator"), field(o, "period_end"), + field(o, "value"), field(o, "unit"), field(o, "date")}); + auto key = field(o, "country") + "/" + field(o, "indicator"); + if (keys.insert(key).second) + series.push_back({key, key}); + } + table(b, {"国家", "指标", "报告期", "值", "单位", "抓取日期"}, cells, 300); + auto selection = combo(series); + form(b, {{"图表序列", selection}}); + auto plot = box(); + add(b, plot); + auto draw = [=] { + clear(plot); + auto key = chosen(selection); + json data = json::array(); + for (auto &o : rows) + if (field(o, "country") + "/" + field(o, "indicator") == key) + data.push_back(o); + std::sort(data.begin(), data.end(), [](auto &a, auto &b) { + return a["period_end"].template get() < + b["period_end"].template get(); + }); + chart(plot, data, "value", key + " · GDP: trillion USD; growth/inflation: %", + key.ends_with("/gdp") ? 1e12 : 1); + gtk_widget_show_all(plot); + }; + on(selection, "changed", draw); + draw(); + }); +} diff --git a/desktop/unit_tests.cpp b/desktop/unit_tests.cpp new file mode 100644 index 0000000..4b2651c --- /dev/null +++ b/desktop/unit_tests.cpp @@ -0,0 +1,28 @@ +#include "api.hpp" +#include "widgets.hpp" +#include +int main() { + int count = 0; + auto check = [&](bool v) { + if (!v) + throw std::runtime_error("Native adapter assertion failed"); + ++count; + }; + check(std::abs(plotNumber("123.456") - 123.456) < 1e-10); + check(plotNumber(0) == 0); + check(std::isnan(plotNumber(nullptr))); + check(std::isnan(plotNumber("12bad"))); + check(std::isnan(plotNumber("nan"))); + check(std::isnan(plotNumber("inf"))); + check(LocalApi::encode("Apple & AAPL") == "Apple%20%26%20AAPL"); + check(LocalApi::encode("../orders?x=1") == "..%2Forders%3Fx%3D1"); + std::atomic stop = false; + bool rejected = false; + try { + LocalApi invalid(0, "user", stop); + } catch (...) { + rejected = true; + } + check(rejected); + std::cout << count << " native data-adapter assertions passed\n"; +} diff --git a/desktop/widgets.hpp b/desktop/widgets.hpp new file mode 100644 index 0000000..c9db75f --- /dev/null +++ b/desktop/widgets.hpp @@ -0,0 +1,283 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +using json = nlohmann::json; +inline std::string text(const json &v) { + if (v.is_null()) + return "—"; + if (v.is_string()) + return v.get(); + if (v.is_number()) { + std::ostringstream s; + s << std::fixed << std::setprecision(2) << v.get(); + return s.str(); + } + return v.dump(); +} +inline std::string field(const json &v, const char *k) { + return v.contains(k) ? text(v[k]) : "—"; +} +inline std::string epochText(const json &v) { + if (!v.is_number_integer() || v.get() <= 0) + return "—"; + auto t = g_date_time_new_from_unix_utc(v.get() / 1000); + if (!t) + return "—"; + auto p = g_date_time_format(t, "%Y-%m-%d %H:%M:%S UTC"); + std::string out = p ? p : "—"; + g_free(p); + g_date_time_unref(t); + return out; +} +inline GtkWidget *box(bool horizontal = false, int spacing = 12) { + return gtk_box_new(horizontal ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL, spacing); +} +inline void add(GtkWidget *b, GtkWidget *w, bool expand = false) { + gtk_box_pack_start(GTK_BOX(b), w, expand, expand, 0); +} +inline GtkWidget *label(const std::string &s, const char *klass = "") { + auto w = gtk_label_new(s.c_str()); + gtk_label_set_xalign(GTK_LABEL(w), 0); + gtk_label_set_line_wrap(GTK_LABEL(w), true); + gtk_label_set_line_wrap_mode(GTK_LABEL(w), PANGO_WRAP_WORD_CHAR); + gtk_label_set_max_width_chars(GTK_LABEL(w), 120); + if (*klass) + gtk_style_context_add_class(gtk_widget_get_style_context(w), klass); + return w; +} +inline GtkWidget *entry(const std::string &s) { + auto w = gtk_entry_new(); + gtk_entry_set_text(GTK_ENTRY(w), s.c_str()); + return w; +} +inline std::string value(GtkWidget *w) { + return gtk_entry_get_text(GTK_ENTRY(w)); +} +inline GtkWidget *number(double v, double low = -1e18, double high = 1e18, double step = .1) { + auto w = gtk_spin_button_new_with_range(low, high, step); + gtk_spin_button_set_digits(GTK_SPIN_BUTTON(w), 4); + gtk_spin_button_set_value(GTK_SPIN_BUTTON(w), v); + return w; +} +inline double numeric(GtkWidget *w) { + gtk_spin_button_update(GTK_SPIN_BUTTON(w)); + return gtk_spin_button_get_value(GTK_SPIN_BUTTON(w)); +} +inline GtkWidget *combo(const std::vector> &options) { + auto w = gtk_combo_box_text_new(); + for (auto &[id, title] : options) + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(w), id.c_str(), title.c_str()); + if (!options.empty()) + gtk_combo_box_set_active(GTK_COMBO_BOX(w), 0); + return w; +} +inline std::string chosen(GtkWidget *w) { + auto id = gtk_combo_box_get_active_id(GTK_COMBO_BOX(w)); + return id ? id : ""; +} +inline void on(GtkWidget *w, const char *signal, std::function f) { + auto p = new std::function(std::move(f)); + g_signal_connect_data( + w, signal, G_CALLBACK((+[](GtkWidget *, gpointer p) { + auto f = *static_cast *>(p); + f(); + })), + p, +[](gpointer p, GClosure *) { delete static_cast *>(p); }, + G_CONNECT_DEFAULT); +} +inline GtkWidget *button(const std::string &s, std::function f) { + auto w = gtk_button_new_with_label(s.c_str()); + on(w, "clicked", std::move(f)); + return w; +} +inline void clear(GtkWidget *w) { + auto list = gtk_container_get_children(GTK_CONTAINER(w)); + for (auto *p = list; p; p = p->next) + gtk_widget_destroy(GTK_WIDGET(p->data)); + g_list_free(list); +} +inline GtkWidget *panel(GtkWidget *parent, const std::string &title) { + auto frame = gtk_frame_new(nullptr); + auto content = box(); + gtk_container_set_border_width(GTK_CONTAINER(content), 18); + add(content, label(title, "section-title")); + gtk_container_add(GTK_CONTAINER(frame), content); + add(parent, frame); + return content; +} +inline GtkWidget *form(GtkWidget *parent, + const std::vector> &fields) { + auto grid = gtk_grid_new(); + gtk_grid_set_column_spacing(GTK_GRID(grid), 16); + gtk_grid_set_row_spacing(GTK_GRID(grid), 10); + int i = 0; + for (auto &[name, w] : fields) { + int row = i / 2, col = (i % 2) * 2; + gtk_grid_attach(GTK_GRID(grid), label(name), col, row, 1, 1); + gtk_widget_set_hexpand(w, true); + gtk_grid_attach(GTK_GRID(grid), w, col + 1, row, 1, 1); + ++i; + } + add(parent, grid); + return grid; +} +inline GtkWidget *table(GtkWidget *parent, const std::vector &headers, + const std::vector> &rows, int height = 240) { + std::vector types(headers.size(), G_TYPE_STRING); + auto store = gtk_list_store_newv(static_cast(types.size()), types.data()); + for (auto &r : rows) { + GtkTreeIter it; + gtk_list_store_append(store, &it); + for (size_t i = 0; i < headers.size(); ++i) + gtk_list_store_set(store, &it, static_cast(i), i < r.size() ? r[i].c_str() : "", + -1); + } + auto view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + g_object_unref(store); + for (size_t i = 0; i < headers.size(); ++i) { + auto cell = gtk_cell_renderer_text_new(); + auto col = gtk_tree_view_column_new_with_attributes(headers[i].c_str(), cell, "text", + static_cast(i), nullptr); + gtk_tree_view_column_set_resizable(col, true); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); + } + auto scroll = gtk_scrolled_window_new(nullptr, nullptr); + gtk_widget_set_size_request(scroll, -1, height); + gtk_container_add(GTK_CONTAINER(scroll), view); + add(parent, scroll); + return view; +} +inline void activateRow(GtkWidget *view, std::function f) { + auto p = new std::function(std::move(f)); + g_signal_connect_data( + view, "row-activated", + G_CALLBACK((+[](GtkTreeView *, GtkTreePath *path, GtkTreeViewColumn *, gpointer p) { + auto index = gtk_tree_path_get_indices(path); + if (index) + (*static_cast *>(p))(index[0]); + })), + p, +[](gpointer p, GClosure *) { delete static_cast *>(p); }, + G_CONNECT_DEFAULT); +} +inline void keyValues(GtkWidget *parent, const json &v) { + std::vector> rows; + if (v.is_object()) + for (auto &[k, n] : v.items()) + if (!n.is_structured()) + rows.push_back({k, text(n)}); + table(parent, {"指标", "值"}, rows, 200); +} +inline double plotNumber(const json &v) { + if (v.is_number()) { + auto n = v.get(); + return std::isfinite(n) ? n : NAN; + } + if (v.is_string()) + try { + auto str = v.get(); + size_t used = 0; + auto n = std::stod(str, &used); + if (used == str.size() && std::isfinite(n)) + return n; + } catch (const std::exception &) { + } + return NAN; +} +struct Plot { + std::vector dates; + std::vector values; + std::string title; +}; +inline GtkWidget *chart(GtkWidget *parent, const json &rows, const std::string &key, + const std::string &title, double divisor = 1) { + auto model = new Plot; + model->title = title; + for (auto &r : rows) { + model->dates.push_back(r.value("date", r.value("period_end", std::string()))); + if (model->dates.back().empty() && r.contains("timestamp")) + model->dates.back() = epochText(r["timestamp"]).substr(0, 10); + model->values.push_back(r.contains(key) ? plotNumber(r[key]) / divisor : NAN); + } + auto area = gtk_drawing_area_new(); + gtk_widget_set_size_request(area, -1, 270); + g_object_set_data_full( + G_OBJECT(area), "plot", model, +[](gpointer p) { delete static_cast(p); }); + g_signal_connect( + area, "draw", G_CALLBACK((+[](GtkWidget *w, cairo_t *c, gpointer) -> gboolean { + auto m = static_cast(g_object_get_data(G_OBJECT(w), "plot")); + double width = gtk_widget_get_allocated_width(w), + height = gtk_widget_get_allocated_height(w), lo = INFINITY, hi = -INFINITY; + for (double v : m->values) + if (std::isfinite(v)) { + lo = std::min(lo, v); + hi = std::max(hi, v); + } + cairo_set_source_rgb(c, .05, .075, .10); + cairo_paint(c); + cairo_select_font_face(c, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); + cairo_set_font_size(c, 11); + cairo_set_source_rgb(c, .55, .65, .70); + cairo_move_to(c, 16, 22); + cairo_show_text(c, m->title.c_str()); + if (!std::isfinite(lo)) { + cairo_move_to(c, 20, height / 2); + cairo_show_text(c, "No observations available"); + return FALSE; + } + if (lo == hi) { + lo -= 1; + hi += 1; + } + double pad = (hi - lo) * .12; + lo -= pad; + hi += pad; + auto x = [&](size_t n) { + return 18. + static_cast(n) / + static_cast(std::max(1, m->values.size() - 1)) * + (width - 115); + }; + auto y = [&](double v) { return 40 + (hi - v) / (hi - lo) * (height - 75); }; + for (int i = 0; i < 5; ++i) { + double v = lo + (hi - lo) * i / 4, py = y(v); + cairo_set_source_rgb(c, .14, .19, .23); + cairo_move_to(c, 16, py); + cairo_line_to(c, width - 90, py); + cairo_stroke(c); + cairo_set_source_rgb(c, .55, .65, .7); + cairo_move_to(c, width - 85, py + 3); + cairo_show_text(c, text(v).c_str()); + } + cairo_set_source_rgb(c, .28, .80, .72); + cairo_set_line_width(c, 2); + bool opened = false; + for (size_t i = 0; i < m->values.size(); ++i) { + if (!std::isfinite(m->values[i])) { + opened = false; + continue; + } + if (opened) + cairo_line_to(c, x(i), y(m->values[i])); + else + cairo_move_to(c, x(i), y(m->values[i])); + opened = true; + } + cairo_stroke(c); + cairo_set_source_rgb(c, .55, .65, .7); + if (!m->dates.empty()) { + cairo_move_to(c, 18, height - 12); + cairo_show_text(c, m->dates.front().c_str()); + cairo_move_to(c, width - 170, height - 12); + cairo_show_text(c, m->dates.back().c_str()); + } + return FALSE; + })), + nullptr); + add(parent, area); + return area; +} diff --git a/desktop/window.hpp b/desktop/window.hpp new file mode 100644 index 0000000..9dce984 --- /dev/null +++ b/desktop/window.hpp @@ -0,0 +1,426 @@ +#pragma once +#include "api.hpp" +#include "widgets.hpp" +#include +#include +#include +#include +#include +class Terminal { + struct Job { + int revision; + bool global; + bool durable; + std::function work; + std::function done; + std::function failed; + }; + struct Completion { + Terminal *owner; + std::shared_ptr> life; + Job job; + json data; + std::string error; + }; + std::atomic stopping{false}; + std::shared_ptr> life = std::make_shared>(true); + LocalApi api; + std::mutex mutex; + std::condition_variable cv; + std::queue queue; + std::thread worker; + std::atomic revision{0}, pending{0}; + GtkWidget *window, *content, *status, *instrumentBox, *dateBox, *nav; + std::vector navButtons; + json instruments = json::array(), brokerAccounts = json::array(); + std::string selected, contract; + int pageIndex = 0; + guint monitor = 0; + int64_t deadline = 0; + bool brokerBusy = false, testMode = false, connected = false; + int testPage = -1; + std::string snapshot; + bool testFailed = false; + json lastHedge; + GtkListStore *hedgeStore = nullptr; + static std::string today() { + std::time_t now = std::time(nullptr); + std::tm t{}; + gmtime_r(&now, &t); + char b[32]; + std::strftime(b, sizeof b, "%Y-%m-%d", &t); + return b; + } + std::string query() const { + return "as_of=" + LocalApi::encode(value(dateBox)); + } + std::string researchPath() const { + return "/api/research?instrument=" + LocalApi::encode(selected) + "&" + query(); + } + void footer(const std::string &s) { + gtk_label_set_text(GTK_LABEL(status), s.c_str()); + } + void request(std::function work, std::function done, + std::function failed = {}, bool global = false, + bool durable = false) { + footer("正在连接本地 C++ 服务…"); + pending++; + { + std::lock_guard lock(mutex); + queue.push({revision.load(), global, durable, std::move(work), std::move(done), + std::move(failed)}); + } + cv.notify_one(); + } + void get(const std::string &path, std::function done) { + request([path](LocalApi &a) { return a.get(path); }, std::move(done)); + } + void post(const std::string &path, const json &body, std::function done) { + bool durable = path == "/api/import" || path == "/api/notes" || path == "/api/valuations" || + path == "/api/hedge/models" || path == "/api/sec/fetch" || + path == "/api/market/daily" || path == "/api/news/fetch" || + path == "/api/macro/fetch" || path == "/api/ibkr/settings" || + path == "/api/ibkr/prepare"; + request([path, body](LocalApi &a) { return a.post(path, body); }, std::move(done), {}, + false, durable); + } + void show() { + gtk_widget_show_all(content); + } + void title(const std::string &eyebrow, const std::string &name, const std::string &sub) { + add(content, label(eyebrow, "eyebrow")); + add(content, label(name, "page-title")); + add(content, label(sub, "muted")); + } + void stopMonitor() { + if (monitor) { + g_source_remove(monitor); + monitor = 0; + } + deadline = 0; + } + std::string chooseFile(bool save, const std::string &title) { + auto dialog = gtk_file_chooser_dialog_new( + title.c_str(), GTK_WINDOW(window), + save ? GTK_FILE_CHOOSER_ACTION_SAVE : GTK_FILE_CHOOSER_ACTION_OPEN, "取消", + GTK_RESPONSE_CANCEL, save ? "保存" : "打开", GTK_RESPONSE_ACCEPT, nullptr); + if (save) + gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), true); + std::string path; + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + auto p = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + if (p) { + path = p; + g_free(p); + } + } + gtk_widget_destroy(dialog); + return path; + } + void uri(const std::string &u) { + if (!(u.starts_with("https://") || u.starts_with("http://"))) + throw std::runtime_error("仅允许 HTTP/HTTPS 来源链接"); + GError *error = nullptr; + if (!gtk_show_uri_on_window(GTK_WINDOW(window), u.c_str(), GDK_CURRENT_TIME, &error)) { + std::string m = error ? error->message : "无法打开授权页面"; + g_clear_error(&error); + throw std::runtime_error(m); + } + } + void stats(GtkWidget *parent, const std::vector> &items) { + auto grid = gtk_grid_new(); + gtk_grid_set_column_homogeneous(GTK_GRID(grid), true); + gtk_grid_set_column_spacing(GTK_GRID(grid), 12); + int n = 0; + for (auto &[name, v] : items) { + auto frame = gtk_frame_new(nullptr); + auto b = box(); + gtk_container_set_border_width(GTK_CONTAINER(b), 18); + add(b, label(name, "muted")); + add(b, label(text(v), "metric")); + gtk_container_add(GTK_CONTAINER(frame), b); + int index = n++; + gtk_grid_attach(GTK_GRID(grid), frame, index % 4, index / 4, 1, 1); + } + add(parent, grid); + } + void reloadInstruments() { + request([](LocalApi &a) { return a.get("/api/instruments"); }, + [this](const json &rows) { + auto keep = selected; + instruments = rows; + gtk_combo_box_text_remove_all(GTK_COMBO_BOX_TEXT(instrumentBox)); + for (auto &i : rows) + gtk_combo_box_text_append( + GTK_COMBO_BOX_TEXT(instrumentBox), i["id"].get().c_str(), + (field(i, "symbol") + " · " + field(i, "name")).c_str()); + if (!gtk_combo_box_set_active_id(GTK_COMBO_BOX(instrumentBox), keep.c_str()) && + !rows.empty()) + gtk_combo_box_set_active(GTK_COMBO_BOX(instrumentBox), 0); + footer("研究标的列表已更新"); + }, + {}, true); + } + void overview(); + void research(); + void valuation(); + void risk(); + void news(); + void data(); + void hedge(); + void margin(); + void macro(); + void gatewayCheck(GtkWidget *line, GtkWidget *prepare, GtkWidget *results); + json hedgeInputs(GtkWidget *ccy, GtkWidget *spotShock, GtkWidget *volShock, GtkWidget *days); + void hedgeResult(GtkWidget *result, const json &r); + void preview(); + void render(int page) { + stopMonitor(); + revision++; + brokerBusy = false; + contract.clear(); + brokerAccounts = json::array(); + pageIndex = page; + clear(content); + for (size_t i = 0; i < navButtons.size(); ++i) { + auto ctx = gtk_widget_get_style_context(navButtons[i]); + if (static_cast(i) == page) + gtk_style_context_add_class(ctx, "selected"); + else + gtk_style_context_remove_class(ctx, "selected"); + } + switch (page) { + case 0: + overview(); + break; + case 1: + research(); + break; + case 2: + valuation(); + break; + case 3: + risk(); + break; + case 4: + news(); + break; + case 5: + data(); + break; + case 6: + hedge(); + break; + case 7: + margin(); + break; + case 8: + macro(); + break; + } + show(); + } + + public: + Terminal(int port, bool selftest, const std::string &image) + : api(port, selftest ? "test" : "user", stopping), testMode(selftest), snapshot(image) { + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(window), "ReachTerminal · 原生桌面终端"); + gtk_window_set_default_size(GTK_WINDOW(window), 1440, 940); + gtk_widget_set_size_request(window, 1050, 650); + auto shell = box(true, 0); + gtk_container_add(GTK_CONTAINER(window), shell); + auto rail = box(false, 16); + gtk_widget_set_size_request(rail, 210, -1); + gtk_style_context_add_class(gtk_widget_get_style_context(rail), "rail"); + gtk_container_set_border_width(GTK_CONTAINER(rail), 18); + add(shell, rail); + add(rail, label("R ↗ REACH", "brand")); + add(rail, label("TERMINAL / NATIVE C++", "eyebrow")); + add(rail, label("投资研究工作区", "muted")); + const std::vector names = {"◫ 组合总览", "⌕ 公司研究", "ƒ 估值工作台", + "◇ 风险与策略", "≋ 新闻与研究", "▤ 数据中心", + "Δ 衍生品对冲", "◴ 保证金监控", "◎ 宏观数据"}; + for (size_t i = 0; i < names.size(); ++i) { + auto b = button(names[i], [this, i] { + if (connected) + render(static_cast(i)); + }); + navButtons.push_back(b); + add(rail, b); + } + auto space = box(); + add(rail, space, true); + add(rail, label("LOCAL · DEVICE ISOLATED", "eyebrow")); + add(rail, label("C++ / GTK / PostgreSQL\nv0.1.0 · 只读券商接入", "muted")); + auto main = box(false, 0); + add(shell, main, true); + auto top = box(true); + gtk_container_set_border_width(GTK_CONTAINER(top), 16); + add(main, top); + add(top, label(selftest ? "TEST / SYNTHETIC" : "LOCAL / PRIVATE", "eyebrow")); + instrumentBox = gtk_combo_box_text_new(); + gtk_widget_set_hexpand(instrumentBox, true); + add(top, instrumentBox, true); + dateBox = entry(today()); + gtk_widget_set_size_request(dateBox, 135, -1); + add(top, label("分析日期")); + add(top, dateBox); + add(top, button("刷新", [this] { + if (connected) + render(pageIndex); + })); + auto scroll = gtk_scrolled_window_new(nullptr, nullptr); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll), GTK_POLICY_AUTOMATIC, + GTK_POLICY_AUTOMATIC); + content = box(false, 18); + gtk_container_set_border_width(GTK_CONTAINER(content), 24); + gtk_container_add(GTK_CONTAINER(scroll), content); + add(main, scroll, true); + status = label("正在连接本地服务…", "muted"); + gtk_widget_set_margin_start(status, 20); + gtk_widget_set_margin_bottom(status, 10); + add(main, status); + on(instrumentBox, "changed", [this] { + selected = chosen(instrumentBox); + if (connected && (pageIndex == 1 || pageIndex == 2 || pageIndex == 4)) + render(pageIndex); + }); + on(window, "destroy", [this] { + *life = false; + stopping = true; + stopMonitor(); + cv.notify_all(); + gtk_main_quit(); + }); + worker = std::thread([this] { + while (!stopping) { + Job j; + { + std::unique_lock lock(mutex); + cv.wait(lock, [this] { return stopping || !queue.empty(); }); + if (stopping) + break; + j = std::move(queue.front()); + queue.pop(); + } + if (!j.global && !j.durable && j.revision != revision.load()) { + pending--; + continue; + } + auto result = new Completion{this, life, std::move(j), {}, {}}; + try { + result->data = result->job.work(api); + } catch (const std::exception &e) { + result->error = e.what(); + } + g_idle_add_full( + G_PRIORITY_DEFAULT, + +[](gpointer p) -> gboolean { + std::unique_ptr r(static_cast(p)); + if (!*r->life) + return G_SOURCE_REMOVE; + auto t = r->owner; + t->pending--; + if (!r->job.global && r->job.revision != t->revision.load()) + return G_SOURCE_REMOVE; + try { + if (!r->error.empty()) { + t->footer(r->error); + if (r->job.failed) + r->job.failed(r->error); + if (t->testMode) + t->testFailed = true; + } else { + t->footer("本地工作区 · 数据来源和分析日期可追溯"); + r->job.done(r->data); + t->show(); + } + } catch (const std::exception &e) { + t->footer(e.what()); + if (t->testMode) + t->testFailed = true; + } + return G_SOURCE_REMOVE; + }, + result, nullptr); + } + }); + request( + [](LocalApi &a) { + a.connect(); + return a.get("/api/instruments"); + }, + [this](const json &rows) { + instruments = rows; + for (auto &i : rows) + gtk_combo_box_text_append( + GTK_COMBO_BOX_TEXT(instrumentBox), i["id"].get().c_str(), + (field(i, "symbol") + " · " + field(i, "name")).c_str()); + if (!rows.empty()) + gtk_combo_box_set_active(GTK_COMBO_BOX(instrumentBox), 0); + connected = true; + render(0); + }, + [this](const std::string &e) { + clear(content); + title("LOCAL CONNECTION", "后端连接失败", e); + add(content, label("请通过 scripts/desktop.sh 启动。桌面界面仅连接本机 " + "127.0.0.1,不连接其他设备的网关。")); + add(content, button("重试连接", [this] { + request( + [](LocalApi &a) { + a.connect(); + return a.get("/api/instruments"); + }, + [this](const json &v) { + instruments = v; + reloadInstruments(); + connected = true; + render(0); + }, + {}, true); + })); + show(); + }, + true); + if (testMode) + g_timeout_add( + 100, + +[](gpointer p) -> gboolean { + auto t = static_cast(p); + if (t->testFailed) { + gtk_widget_destroy(t->window); + return G_SOURCE_REMOVE; + } + if (!t->connected || t->pending.load() != 0) + return G_SOURCE_CONTINUE; + if (++t->testPage < 9) { + t->render(t->testPage); + return G_SOURCE_CONTINUE; + } + if (t->testPage == 9) { + t->render(6); + return G_SOURCE_CONTINUE; + } + t->preview(); + gtk_widget_destroy(t->window); + return G_SOURCE_REMOVE; + }, + this); + } + ~Terminal() { + *life = false; + stopping = true; + cv.notify_all(); + if (worker.joinable()) + worker.join(); + } + void run() { + gtk_widget_show_all(window); + gtk_main(); + } + bool failed() const { + return testFailed; + } +}; diff --git a/docs/native-desktop.md b/docs/native-desktop.md new file mode 100644 index 0000000..38f9d1f --- /dev/null +++ b/docs/native-desktop.md @@ -0,0 +1,21 @@ +# 原生桌面终端 + +ReachTerminal 提供 C++20 / GTK 3 原生桌面前端,使用 Cairo 绘制图表,不包含 WebView,不需要浏览器或 Node.js 运行前端。当前支持 Linux 图形桌面。 + +桌面进程通过仅限 127.0.0.1 的 HTTP 接口连接 C++ 服务,数据库仍由 C++ 服务管理。耗时请求在独立工作线程执行;离开页面会丢弃过期读请求,但已经提交的保存、导入和导出继续完成。 + +## 启动 + +安装 GTK 3 开发库(Debian/Ubuntu:`libgtk-3-dev`),按主 README 编译,然后运行 `./scripts/desktop.sh`。脚本复用已经运行的用户服务;否则启动本机正式数据库服务,关闭窗口时只停止由该脚本启动的服务。脚本不会打开网页。 + +九个工作区包括组合核算、基本面研究、DCF 估值、风险与策略、新闻与笔记、数据中心、衍生品对冲、保证金和宏观数据。表格、文件选择、设置、表单和图表均为原生控件。衍生品使用模型估值,不能代替交易所报价;本终端没有下单接口。 + +IBKR 的个人 Client Portal Gateway 仍要求在官方外部登录页完成登录和双重验证;桌面数据中心中的登录入口只在点击时打开该官方页面。终端本身不依赖浏览器。登录后桌面监控认证和行情会话,并提供明确状态、手动连接及登出入口。网关地址、证书和会话始终绑定本机,不能跨设备迁移。 + +## 打包 + +运行 `python3 scripts/package-native.py --output /tmp/reachterminal-native-release`,生成带校验值的 Linux 动态链接程序包。包含原生前端、C++ 服务和启动脚本,不包含网关、设备配置、数据库、用户导出、账户或密钥。目标设备必须安装兼容 GTK 3、libpq、libcurl、OpenSSL、libxml2、cpp-httplib 等系统库,并准备自己的 PostgreSQL 数据库;这不是跨发行版静态包。程序包启动需要设置 `REACH_DATABASE_URL`,可用 `REACH_ROOT` 指定独立用户工作区。 + +## 验证与隔离 + +`ctest --test-dir build --output-on-failure` 验证原生数值适配与现有模型。`python3 scripts/test-isolated.py` 使用临时测试数据库、合成账户和模拟网关;原生自测遍历九个工作区并核验对冲结果,产生仅含合成数据的原生窗口预览。无图形桌面的 CI 使用 Xvfb。正式前端拒绝连接测试环境,自测前端拒绝连接用户环境。 diff --git a/scripts/desktop.sh b/scripts/desktop.sh new file mode 100755 index 0000000..b08830f --- /dev/null +++ b/scripts/desktop.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +set -euo pipefail +repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +export LD_LIBRARY_PATH="$repo_dir/.local/deps/usr/lib/x86_64-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +export REACH_PORT="${REACH_PORT:-8788}" +export REACH_DESKTOP_PORT="$REACH_PORT" +export REACH_ENV=user +if [[ ! -x "$repo_dir/build/reachterminal-desktop" ]]; then + echo "请先编译 reachterminal-desktop(需要 GTK 3 开发库)。" >&2 + exit 1 +fi +health() { + python3 - "$REACH_PORT" <<'PYHEALTH' +import json,sys,urllib.request +try: + opener=urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open('http://127.0.0.1:'+str(int(sys.argv[1]))+'/api/health',timeout=2) as f: + data=json.load(f) + sys.exit(0 if data.get('environment')=='user' else 2) +except Exception: sys.exit(1) +PYHEALTH +} +backend_pid="" +cleanup() { if [[ -n "$backend_pid" ]]; then kill "$backend_pid" 2>/dev/null || true; wait "$backend_pid" 2>/dev/null || true; fi; } +trap cleanup EXIT INT TERM +if health; then :; else + status=$? + if [[ "$status" == 2 ]]; then echo "该端口属于测试环境,拒绝连接。" >&2; exit 1; fi + mkdir -p "$repo_dir/.local" + (umask 077; exec "$repo_dir/scripts/live.sh") >"$repo_dir/.local/desktop-backend.log" 2>&1 & + backend_pid=$! + ready=false + for ((i=0;i<120;i++)); do + if health; then ready=true; break; fi + if ! kill -0 "$backend_pid" 2>/dev/null; then break; fi + sleep 1 + done + if [[ "$ready" != true ]]; then echo "本地服务未就绪,请查看 .local/desktop-backend.log。" >&2; exit 1; fi +fi +"$repo_dir/build/reachterminal-desktop" diff --git a/scripts/package-native.py b/scripts/package-native.py new file mode 100644 index 0000000..c6ff120 --- /dev/null +++ b/scripts/package-native.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Package native executables only; never include device or user runtime state.""" +import argparse, hashlib, platform, shutil, tarfile +from pathlib import Path +root=Path(__file__).resolve().parents[1] +p=argparse.ArgumentParser(); p.add_argument('--output', required=True); args=p.parse_args() +out=Path(args.output).resolve(); out.mkdir(parents=True, exist_ok=True) +name='ReachTerminal-0.1.0-native-linux-'+platform.machine(); folder=out/name +folder.mkdir(exist_ok=True) +files=['reachterminal-desktop','reachterminal','LICENSE','start.sh','README.txt'] +for binary in files[:2]: shutil.copy2(root/'build'/binary,folder/binary) +shutil.copy2(root/'LICENSE',folder/'LICENSE') +(folder/'start.sh').write_text('''#!/usr/bin/env bash +set -euo pipefail +base="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +: "${REACH_DATABASE_URL:?请设置本机用户 PostgreSQL 连接 REACH_DATABASE_URL}" +export REACH_ENV=user +export REACH_ROOT="${REACH_ROOT:-$base/workspace}" +export REACH_PORT="${REACH_PORT:-8788}" +export REACH_DESKTOP_PORT="$REACH_PORT" +mkdir -p "$REACH_ROOT" +"$base/reachterminal" serve & +backend_pid=$! +cleanup() { kill "$backend_pid" 2>/dev/null || true; wait "$backend_pid" 2>/dev/null || true; } +trap cleanup EXIT INT TERM +sleep 1 +if ! kill -0 "$backend_pid" 2>/dev/null; then echo "本地服务启动失败(端口可能占用)" >&2; exit 1; fi +"$base/reachterminal-desktop" +''') +(folder/'start.sh').chmod(0o755) +(folder/'README.txt').write_text((root/'docs/native-desktop.md').read_text()) +archive=out/(name+'.tar.gz') +with tarfile.open(archive,'w:gz') as target: + for file in files: target.add(folder/file,arcname=name+'/'+file,recursive=False) +(out/(archive.name+'.sha256')).write_text(hashlib.sha256(archive.read_bytes()).hexdigest()+' '+archive.name+'\n') +print(archive) diff --git a/scripts/package-release.py b/scripts/package-release.py index d4469a5..fd47db4 100644 --- a/scripts/package-release.py +++ b/scripts/package-release.py @@ -6,7 +6,7 @@ p=argparse.ArgumentParser();p.add_argument('--output',required=True);a=p.parse_args();out=Path(a.output).resolve();out.mkdir(parents=True,exist_ok=True) version=re.search(r'project\(ReachTerminal VERSION ([0-9.]+)',(root/'CMakeLists.txt').read_text())[1] name=f'ReachTerminal-{version}';target=out/(name+'.tar.gz') -allowed={'backend':{'.hpp','.cpp'},'frontend':{'.html','.js','.css'},'db':{'.sql'},'scripts':{'.py','.sh'},'tests':{'.cpp','.py','.mjs'},'docs':{'.md','.json','.png'},'examples':{'.json','.csv','.xml'},'.github':{'.yml','.yaml'}} +allowed={'backend':{'.hpp','.cpp'},'desktop':{'.hpp','.cpp'},'frontend':{'.html','.js','.css'},'db':{'.sql'},'scripts':{'.py','.sh'},'tests':{'.cpp','.py','.mjs'},'docs':{'.md','.json','.png'},'examples':{'.json','.csv','.xml'},'.github':{'.yml','.yaml'}} files=[root/f for f in ['CMakeLists.txt','README.md','LICENSE','.gitignore','.clang-format']] for directory,extensions in allowed.items(): for f in (root/directory).rglob('*'): diff --git a/scripts/test-isolated.py b/scripts/test-isolated.py old mode 100755 new mode 100644 index 3353695..679ab80 --- a/scripts/test-isolated.py +++ b/scripts/test-isolated.py @@ -42,6 +42,17 @@ def free_port(): command([sys.executable,root/'tests/ibkr_gateway_test.py','--url',url,'--fixture-dir',run]) command([sys.executable,root/'tests/integration.py','--url',url,'--root',root,'--report',run/'integration-report.json']) command([sys.executable,root/'tests/release_integration.py','--url',url]) + native=root/'build/reachterminal-desktop' + if native.exists(): + env['REACH_DESKTOP_PORT']=str(http_port) + env['G_DEBUG']='fatal-criticals' + native_args=[native,'--self-test','--snapshot',run/'native-desktop.png'] + if env.get('DISPLAY') or env.get('WAYLAND_DISPLAY'):command(native_args,timeout=90) + else: + import shutil + xvfb=shutil.which('xvfb-run') + if xvfb:env['GDK_BACKEND']='x11';command([xvfb,'-a',*native_args],timeout=90) + else:raise RuntimeError('Native desktop built but no graphical test display; install xvfb') print('ISOLATED_TEST_REPORTS='+str(run)) except BaseException: print('ISOLATED_TEST_LOGS='+str(run),file=sys.stderr,flush=True)