1use std::collections::{BTreeMap, HashSet, VecDeque};
7use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, AtomicUsize, Ordering};
8use std::sync::{Arc, Mutex};
9
10use ek_data::bar::BarData;
11use ek_dm::wire::BarsFrame;
12use ek_station::wire::PlugRow;
13
14pub const RING_CAP: usize = 512;
16
17pub(crate) fn beijing_tz() -> chrono::FixedOffset {
22 chrono::FixedOffset::east_opt(8 * 3600).expect("+08 offset is always valid")
23}
24
25#[derive(Debug, Clone)]
29pub struct LogEntry {
30 pub at: String,
32 pub text: String,
34}
35
36#[derive(Debug)]
38pub struct LogRing {
39 lines: VecDeque<LogEntry>,
40 cap: usize,
41 spilled: u64,
42}
43
44impl Default for LogRing {
45 fn default() -> Self {
46 Self::new(RING_CAP)
47 }
48}
49
50impl LogRing {
51 pub fn new(cap: usize) -> Self {
53 Self {
54 lines: VecDeque::with_capacity(cap),
55 cap,
56 spilled: 0,
57 }
58 }
59
60 pub fn push(&mut self, line: impl Into<String>) {
62 if self.cap == 0 {
63 self.spilled += 1;
64 return;
65 }
66 if self.lines.len() == self.cap {
67 self.lines.pop_front();
68 self.spilled += 1;
69 }
70 let at = chrono::Utc::now()
71 .with_timezone(&beijing_tz())
72 .format("%H:%M:%S")
73 .to_string();
74 self.lines.push_back(LogEntry {
75 at,
76 text: line.into(),
77 });
78 }
79
80 pub fn len(&self) -> usize {
82 self.lines.len()
83 }
84
85 pub fn is_empty(&self) -> bool {
87 self.lines.is_empty()
88 }
89
90 pub fn spilled(&self) -> u64 {
92 self.spilled
93 }
94
95 pub fn snapshot(&self) -> Vec<String> {
97 self.lines.iter().map(|e| e.text.clone()).collect()
98 }
99
100 pub fn entries(&self) -> Vec<LogEntry> {
102 self.lines.iter().cloned().collect()
103 }
104
105 pub fn clear(&mut self) {
107 self.lines.clear();
108 }
109}
110
111#[derive(Debug, Clone, Default)]
113pub struct BusSnap {
114 pub rows: Vec<PlugRow>,
116 pub services: Vec<(String, Vec<String>)>,
118}
119
120#[derive(Debug, Clone, PartialEq)]
122pub enum UiCmd {
123 Start { factory: String, name: String },
126 Remove { name: String },
128 Reload {
130 interval: i64,
131 symbol: String,
132 bars: Vec<BarData>,
133 },
134 SendOrder {
140 req: ek_data::order_request::OrderRequest,
141 gateway: String,
142 mode: ek_oms::LockMode,
143 },
144 CancelOrder { orderid: String, gateway: String },
148 CtpConfigure { gateway: String, form: CtpForm },
152 Connect { gateway: String, form: CtpForm },
157 CtpSubscribe {
160 gateway: String,
161 symbols: Vec<String>,
162 },
163 Disconnect { gateway: String },
167 CfgList,
169 CfgDelete { ns: String },
171 CfgResave { ns: String },
174}
175
176pub const KLINE_CELL_CAP: usize = 4096;
178
179pub const MAX_ACCOUNTS: usize = 8;
182
183pub const QUERY_REJECT_STREAK_LIMIT: u32 = 3;
188
189pub const ACCOUNT_STALE_SECS: i64 = 30;
195
196pub use ek_ctp::driver::CHAIN_STATE_PREFIX;
202
203pub const LIST_POLL_TICKS: u32 = 4;
209
210pub const STATUS_ASKS_PER_TICK: usize = 2;
215
216pub const TRADE_CAP: usize = 5000;
221
222pub const PENDING_WARN_FLOOR: u64 = 4_096;
224pub const PENDING_CRIT_FLOOR: u64 = 32_768;
226
227#[must_use]
235pub fn pending_thresholds(soft_cap: u64) -> (u64, u64) {
236 let warn = (soft_cap / 16).max(PENDING_WARN_FLOOR);
237 let crit = (soft_cap / 4).max(PENDING_CRIT_FLOOR);
238 (warn.min(soft_cap.max(1)), crit.min(soft_cap.max(1)))
239}
240
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub enum ConfirmStep {
244 Armed,
245 Fired,
246 Switched,
247}
248
249#[must_use]
252pub fn is_quarantined(state: &str) -> bool {
253 state.contains("Quarantin")
254}
255
256#[derive(Debug, Default)]
260pub struct MarketStore {
261 cells: Mutex<BTreeMap<(String, i64), Vec<BarData>>>,
262 frames: AtomicU64,
264 updates: AtomicU64,
266 reloads: AtomicU64,
268}
269
270#[derive(Debug, Clone, PartialEq)]
272pub struct CellView {
273 pub symbol: String,
274 pub interval: i64,
275 pub bars: Vec<BarData>,
276}
277
278impl MarketStore {
279 pub fn on_frame(&self, frame: &BarsFrame) {
281 let mut cells = self.cells.lock().unwrap();
282 for b in &frame.bars {
283 let key = (b.symbol.clone(), frame.interval);
284 let cell = cells.entry(key).or_default();
285 match cell.last() {
286 Some(last) if b.datetime < last.datetime => continue,
287 Some(last) if b.datetime == last.datetime => {
288 let slot = cell.last_mut().expect("len>1");
289 *slot = b.clone();
290 }
291 _ => {
292 cell.push(b.clone());
293 if cell.len() > KLINE_CELL_CAP {
294 cell.remove(0);
295 }
296 }
297 }
298 }
299 self.frames.fetch_add(1, Ordering::AcqRel);
300 }
301
302 pub fn on_update(&self, b: &BarData) {
304 let mut cells = self.cells.lock().unwrap();
305 let iv = b
306 .interval
307 .unwrap_or(ek_data::constant::Interval::MINUTE)
308 .seconds();
309 let key = (b.symbol.clone(), iv);
310 let cell = cells.entry(key).or_default();
311 match cell.last() {
312 Some(last) if b.datetime == last.datetime => {
313 let slot = cell.last_mut().expect("len>1");
314 *slot = b.clone();
315 }
316 Some(last) if b.datetime < last.datetime => {}
317 _ => {
318 cell.push(b.clone());
319 if cell.len() > KLINE_CELL_CAP {
320 cell.remove(0);
321 }
322 }
323 }
324 self.updates.fetch_add(1, Ordering::AcqRel);
325 }
326
327 pub fn note_reload(&self) {
329 self.reloads.fetch_add(1, Ordering::AcqRel);
330 }
331
332 pub fn cells(&self) -> Vec<CellView> {
334 self.cells
335 .lock()
336 .unwrap()
337 .iter()
338 .map(|((sym, iv), bars)| CellView {
339 symbol: sym.clone(),
340 interval: *iv,
341 bars: bars.clone(),
342 })
343 .collect()
344 }
345
346 pub fn counts(&self) -> (u64, u64, u64) {
348 (
349 self.frames.load(Ordering::Acquire),
350 self.updates.load(Ordering::Acquire),
351 self.reloads.load(Ordering::Acquire),
352 )
353 }
354}
355
356#[derive(Debug, Default, Clone, PartialEq)]
359pub struct ReloadForm {
360 pub interval: String,
361 pub symbol: String,
362 pub csv: String,
363}
364
365pub fn parse_gateway(raw: &str, fallback: Option<&str>) -> Result<String, String> {
372 let g = raw.trim();
373 if !g.is_empty() {
374 if g.chars().any(|c| c.is_whitespace()) {
375 return Err(format!("网关解析: 含空白:{raw:?}"));
376 }
377 return Ok(g.to_string());
378 }
379 match fallback.map(|f| f.trim()).filter(|f| !f.is_empty()) {
380 Some(f) => Ok(f.to_string()),
381 None => Err("网关解析: 未选择账户(先在账户面板添加账户)".to_string()),
382 }
383}
384
385#[derive(Debug, Clone, PartialEq)]
388pub struct CtpForm {
389 pub broker_id: String,
390 pub td_addr: String,
391 pub td_user: String,
392 pub td_password: String,
393 pub td_auth_code: String,
394 pub td_app_id: String,
395 pub md_addr: String,
396 pub md_user: String,
397 pub md_password: String,
398 pub symbols: String,
400 pub accept_futures: bool,
403 pub accept_options: bool,
404}
405
406impl Default for CtpForm {
409 fn default() -> Self {
410 Self {
411 broker_id: String::new(),
412 td_addr: String::new(),
413 td_user: String::new(),
414 td_password: String::new(),
415 td_auth_code: String::new(),
416 td_app_id: String::new(),
417 md_addr: String::new(),
418 md_user: String::new(),
419 md_password: String::new(),
420 symbols: String::new(),
421 accept_futures: true,
422 accept_options: false,
423 }
424 }
425}
426
427impl CtpForm {
428 #[must_use]
432 pub fn product_classes(&self) -> Vec<String> {
433 let mut codes = Vec::new();
434 if self.accept_futures {
435 codes.push("1".to_string());
436 }
437 if self.accept_options {
438 codes.push("2".to_string());
439 }
440 codes
441 }
442
443 pub fn to_configure_req(&self) -> ek_ctp::plugin::ConfigureReq {
445 ek_ctp::plugin::ConfigureReq {
446 broker_id: self.broker_id.trim().to_string(),
447 td_addr: self.td_addr.trim().to_string(),
448 td_user: self.td_user.trim().to_string(),
449 td_password: self.td_password.clone(),
450 td_auth_code: self.td_auth_code.trim().to_string(),
451 td_app_id: self.td_app_id.trim().to_string(),
452 md_addr: self.md_addr.trim().to_string(),
453 md_user: self.md_user.trim().to_string(),
454 md_password: self.md_password.clone(),
455 product_classes: self.product_classes(),
456 }
457 }
458
459 pub fn parse_symbols(&self) -> Result<Vec<String>, String> {
461 let list: Vec<String> = self
462 .symbols
463 .split([',', ',', ' '])
464 .map(|s| s.trim().to_string())
465 .filter(|s| !s.is_empty())
466 .collect();
467 if list.is_empty() {
468 return Err("订阅解析: 标的位空".to_string());
469 }
470 Ok(list)
471 }
472
473 pub fn validate(&self) -> Result<(), String> {
482 fn front(name: &str, v: &str) -> Result<(), String> {
483 let v = v.trim();
484 let Some(rest) = v.strip_prefix("tcp://") else {
485 return Err(format!("{name} 形制应为 tcp://host:port(当前 {:?})", v));
486 };
487 let Some((host, port)) = rest.rsplit_once(':') else {
488 return Err(format!("{name} 缺端口:{name} {:?}", v));
489 };
490 if host.trim().is_empty() {
491 return Err(format!("{name} 主机位空:{}", v));
492 }
493 let port: u32 = port
494 .parse()
495 .map_err(|_| format!("{name} 端口不是数字:{}", v))?;
496 if port == 0 || port > 65535 {
497 return Err(format!("{name} 端口越界(1..=65535):{}", v));
498 }
499 Ok(())
500 }
501 if self.broker_id.trim().is_empty() {
502 return Err("broker 位空".to_string());
503 }
504 if self.td_user.trim().is_empty() {
505 return Err("交易账号位空".to_string());
506 }
507 front("td 前置", &self.td_addr)?;
508 if !self.md_addr.trim().is_empty() {
509 front("md 前置", &self.md_addr)?;
510 }
511 if self.td_app_id.trim().is_empty() {
512 return Err("AppID 位空(CTP 登录必需)".to_string());
513 }
514 if self.td_auth_code.trim().is_empty() {
515 return Err("AuthCode 位空(CTP 登录必需)".to_string());
516 }
517 Ok(())
518 }
519}
520
521#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
528pub enum AccountStage {
529 #[default]
531 NotAssembled,
532 Assembling,
534 Assembled,
536 AssembleFailed,
538}
539
540impl AccountStage {
541 #[must_use]
543 pub fn label(self) -> &'static str {
544 match self {
545 AccountStage::NotAssembled => "未装配",
546 AccountStage::Assembling => "装配中…",
547 AccountStage::Assembled => "已装配·登录态未知",
550 AccountStage::AssembleFailed => "装配失败",
551 }
552 }
553}
554
555#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
560pub enum LoginState {
561 #[default]
566 Unknown,
567 Online,
569 LoginFailed,
571 FrontDown,
573 QueryStarved,
575 Stopped,
577}
578
579impl LoginState {
580 #[must_use]
582 pub fn label(self) -> &'static str {
583 match self {
584 LoginState::Unknown => "登录态未知",
585 LoginState::Online => "在线",
586 LoginState::LoginFailed => "登录失败",
587 LoginState::FrontDown => "掉线",
588 LoginState::QueryStarved => "查询断供",
589 LoginState::Stopped => "已断开",
590 }
591 }
592
593 #[must_use]
595 pub fn is_alarm(self) -> bool {
596 matches!(self, LoginState::LoginFailed | LoginState::FrontDown)
597 }
598}
599
600fn count_note(label: &str, n: u32) -> Option<String> {
602 (n > 0).then(|| format!("{label} {n} 次"))
603}
604
605fn brief_counter_reason(full: &str) -> Option<String> {
612 let tail = full.rfind("信息:").map(|i| &full[i + "信息:".len()..])?;
613 let body = tail.trim().trim_start_matches("CTP:").trim();
614 if body.is_empty() {
615 return None;
616 }
617 let code = full
618 .rfind("代码:")
619 .map(|i| {
620 let rest = &full[i + "代码:".len()..];
621 let end = rest.find(',').unwrap_or(rest.len());
622 rest[..end].trim().to_string()
623 })
624 .filter(|c| !c.is_empty() && c.parse::<i64>().is_ok());
625 Some(match code {
626 Some(c) => format!("{body}({c})"),
627 None => body.to_string(),
628 })
629}
630
631#[derive(Debug, Clone, PartialEq, Default)]
637pub struct AccountRow {
638 pub gateway: String,
640 pub alias: String,
642 pub broker_id: String,
643 pub account: String,
644 pub md_source: bool,
646 pub form: CtpForm,
648 pub restored: bool,
654 pub auto_connect: bool,
659 pub password_ref: bool,
664 pub stage: AccountStage,
666 pub fail_note: Option<String>,
668 pub effective_classes: Vec<String>,
673 pub connected: bool,
676 pub login: LoginState,
680 pub status_note: Option<String>,
683 pub login_brief: Option<String>,
690 pub chain_note: Option<String>,
698}
699
700impl AccountRow {
701 pub fn derive(form: &CtpForm) -> Result<Self, String> {
706 let broker = form.broker_id.trim();
707 let account = form.td_user.trim();
708 let gateway = ek_ctp::derived_gateway_name(broker, account).ok_or_else(|| {
709 "账户: broker/账号 不能为空且只能含字母数字(且派生名 ≤32)".to_string()
710 })?;
711 Ok(Self {
712 gateway,
713 alias: String::new(),
714 broker_id: broker.to_string(),
715 account: account.to_string(),
716 md_source: false,
717 form: form.clone(),
718 stage: AccountStage::NotAssembled,
719 fail_note: None,
720 effective_classes: Vec::new(),
721 connected: false,
722 login: LoginState::Unknown,
723 status_note: None,
724 login_brief: None,
725 chain_note: None,
726 restored: false,
729 auto_connect: false,
730 password_ref: false,
731 })
732 }
733
734 #[must_use]
740 pub fn status_label(&self) -> String {
741 if self.stage == AccountStage::Assembled {
742 match self.login {
743 LoginState::Unknown => "已装配·登录态未知".to_string(),
744 other => format!("已装配·{}", other.label()),
745 }
746 } else {
747 self.stage.label().to_string()
748 }
749 }
750
751 pub fn apply_status(
764 &mut self,
765 st: &ek_ctp::plugin::GatewayStatus,
766 now_ms: i64,
767 reject_limit: u32,
768 stale_secs: i64,
769 ) {
770 let td_side = !self.form.td_addr.trim().is_empty();
771 let (login, note) = if td_side {
772 if st.td_login_failed && !st.td_logged_in {
773 (
774 LoginState::LoginFailed,
775 st.td_last_error
776 .clone()
777 .or_else(|| Some("登录失败(网关未回带原因)".to_string())),
778 )
779 } else if st.td_logged_in {
780 if st.td_query_reject_streak >= reject_limit {
781 (
782 LoginState::QueryStarved,
783 Some(format!("查询连续被拒 {} 次", st.td_query_reject_streak)),
784 )
785 } else if let Some(last) = st.td_last_account_ms {
786 let idle_ms = now_ms.saturating_sub(last);
787 if idle_ms > stale_secs.saturating_mul(1_000) {
788 (
789 LoginState::QueryStarved,
790 Some(format!("资金回报已 {}s 未更新", idle_ms / 1_000)),
791 )
792 } else {
793 (LoginState::Online, count_note("掉线", st.td_disconnects))
794 }
795 } else {
796 let since_login_ms = st.td_last_login_ok_ms.map(|ok| now_ms.saturating_sub(ok));
803 match since_login_ms {
804 Some(ms) if ms > stale_secs.saturating_mul(1_000) => (
805 LoginState::QueryStarved,
806 Some(format!("资金回报从未到手(登录已 {}s)", ms / 1_000)),
807 ),
808 _ => (LoginState::Online, Some("资金回报尚未到手".to_string())),
809 }
810 }
811 } else if self.login == LoginState::Stopped {
812 let extra = if st.td_disconnects > 0 {
813 format!("(此前掉线 {} 次)", st.td_disconnects)
814 } else {
815 String::new()
816 };
817 (
818 LoginState::Stopped,
819 Some(format!("会话已停{extra};『连接』可恢复")),
820 )
821 } else if st.td_disconnects > 0 {
822 (
823 LoginState::FrontDown,
824 Some(format!("掉线 {} 次", st.td_disconnects)),
825 )
826 } else {
827 (LoginState::Unknown, st.td_last_error.clone())
828 }
829 } else if st.md_logged_in {
830 (
831 LoginState::Online,
832 count_note("掉线", st.md_disconnects)
833 .or_else(|| Some("纯行情账户(无 TD 会话)".to_string())),
834 )
835 } else if self.login == LoginState::Stopped {
836 (
837 LoginState::Stopped,
838 Some("会话已停;『连接』可恢复".to_string()),
839 )
840 } else if st.md_disconnects > 0 {
841 (
842 LoginState::FrontDown,
843 Some(format!("掉线 {} 次", st.md_disconnects)),
844 )
845 } else {
846 (LoginState::Unknown, st.md_last_error.clone())
847 };
848 let note = if td_side && st.td_instrument_rejects > 0 {
853 let add = format!("合约查询被拒 {} 次", st.td_instrument_rejects);
854 match note {
855 Some(base) if base.contains("合约查询被拒") => Some(base),
857 Some(base) => Some(format!("{base};{add}")),
858 None => Some(add),
859 }
860 } else {
861 note
862 };
863 self.login = login;
864 self.status_note = note;
865 self.login_brief = if login.is_alarm() {
868 st.td_last_error
869 .as_deref()
870 .or(st.md_last_error.as_deref())
871 .and_then(brief_counter_reason)
872 } else {
873 None
874 };
875 }
876
877 #[must_use]
879 pub fn display_name(&self) -> String {
880 let a = self.alias.trim();
881 if a.is_empty() {
882 self.account.clone()
883 } else {
884 a.to_string()
885 }
886 }
887}
888
889#[derive(Debug, Clone, PartialEq, Default)]
892pub struct TradeSnap {
893 pub orders: Vec<ek_data::order::OrderData>,
894 pub trades: Vec<ek_data::trade::TradeData>,
895 pub positions: Vec<ek_data::position::PositionData>,
896 pub accounts: Vec<ek_data::account::AccountData>,
898}
899
900pub fn parse_reload_csv(form: &ReloadForm) -> Result<(i64, String, Vec<BarData>), String> {
903 let interval: i64 = form
904 .interval
905 .trim()
906 .parse()
907 .map_err(|_| format!("回灌 解析: interval 非整数:{:?}", form.interval))?;
908 let symbol = form.symbol.trim().to_string();
909 if symbol.is_empty() {
910 return Err("回灌解析: symbol 空".to_string());
911 }
912 if form.csv.trim().is_empty() {
913 return Err("回灌解析: csv 空".to_string());
914 }
915 let mut bars = Vec::new();
916 for (i, raw) in form.csv.lines().enumerate() {
917 let line = raw.trim();
918 if line.is_empty() || line.starts_with('#') {
919 continue;
920 }
921 let parts: Vec<&str> = line.split(',').map(str::trim).collect();
922 if parts.len() != 6 {
923 return Err(format!("回灌解析: 第 {} 列数 ≠ 6", i + 1));
924 }
925 let num = |s: &str| -> Result<f64, String> {
926 s.parse::<f64>()
927 .map_err(|_| format!("回灌解析: 第 {} 列数值坏:{:?}", i + 1, s))
928 };
929 let dt_s: i64 = parts[0]
930 .parse()
931 .map_err(|_| format!("回灌解析: 第 {} 列 dt 坏:{:?}", i + 1, parts[0]))?;
932 bars.push(BarData {
933 symbol: symbol.clone(),
934 datetime: dt_s * 1_000_000_000,
935 interval: Some(
936 ek_dm::wire::interval_of_seconds(interval)
937 .unwrap_or(ek_data::constant::Interval::MINUTE),
938 ),
939 open_price: num(parts[1])?,
940 high_price: num(parts[2])?,
941 low_price: num(parts[3])?,
942 close_price: num(parts[4])?,
943 volume: num(parts[5])?,
944 ..BarData::default()
945 });
946 }
947 if bars.is_empty() {
948 return Err("回灌解析: 无有效行".to_string());
949 }
950 Ok((interval, symbol, bars))
951}
952
953#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
958pub enum TopLeftTab {
959 #[default]
960 Orders,
961 Active,
962}
963
964impl TopLeftTab {
965 pub fn label(self) -> &'static str {
966 match self {
967 Self::Orders => "委托",
968 Self::Active => "未成交",
969 }
970 }
971}
972
973#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
975pub enum BottomRightTab {
976 #[default]
977 Account,
978 Logs,
979}
980
981impl BottomRightTab {
982 pub fn label(self) -> &'static str {
983 match self {
984 Self::Account => "资金",
985 Self::Logs => "日志",
986 }
987 }
988}
989
990#[derive(Debug, Clone, Copy, PartialEq)]
993pub struct DataSplit {
994 pub col: f32,
996 pub row: f32,
998}
999
1000impl Default for DataSplit {
1001 fn default() -> Self {
1002 Self {
1003 col: crate::splitters::DATA_SPLIT_DEFAULT,
1004 row: crate::splitters::DATA_SPLIT_DEFAULT,
1005 }
1006 }
1007}
1008
1009pub const MARKET_ORDER: [ek_data::constant::Exchange; 6] = [
1012 ek_data::constant::Exchange::SHFE,
1013 ek_data::constant::Exchange::DCE,
1014 ek_data::constant::Exchange::CZCE,
1015 ek_data::constant::Exchange::CFFEX,
1016 ek_data::constant::Exchange::INE,
1017 ek_data::constant::Exchange::GFEX,
1018];
1019
1020#[derive(Debug, Default)]
1030pub struct TickStore {
1031 ticks: BTreeMap<String, ek_data::tick::TickData>,
1032}
1033
1034impl TickStore {
1035 pub fn put(&mut self, t: &ek_data::tick::TickData) {
1038 self.ticks
1039 .insert(format!("{}.{}", t.exchange.as_str(), t.symbol), t.clone());
1040 }
1041
1042 pub fn rows(&self) -> Vec<ek_data::tick::TickData> {
1044 let mut v: Vec<ek_data::tick::TickData> = self.ticks.values().cloned().collect();
1045 v.sort_by(|a, b| {
1046 (a.exchange.as_str().to_string(), a.symbol.clone())
1047 .cmp(&(b.exchange.as_str().to_string(), b.symbol.clone()))
1048 });
1049 v
1050 }
1051
1052 pub fn groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
1054 let mut out: Vec<(String, Vec<ek_data::tick::TickData>)> = Vec::new();
1055 for t in self.rows() {
1056 let ex = t.exchange.as_str().to_string();
1057 match out.last_mut() {
1058 Some((e, v)) if *e == ex => v.push(t),
1059 _ => out.push((ex, vec![t])),
1060 }
1061 }
1062 out
1063 }
1064
1065 pub fn len(&self) -> usize {
1066 self.ticks.len()
1067 }
1068
1069 pub fn is_empty(&self) -> bool {
1070 self.ticks.is_empty()
1071 }
1072}
1073
1074#[derive(Debug, Clone, PartialEq)]
1076pub struct OrderForm {
1077 pub exchange: String,
1079 pub symbol: String,
1081 pub direction: ek_data::constant::Direction,
1082 pub offset: ek_data::constant::Offset,
1083 pub order_type: ek_data::constant::OrderType,
1084 pub price: String,
1086 pub volume: String,
1087 pub gateway: String,
1089 pub follow_price: bool,
1091 pub auto_split: bool,
1094}
1095
1096impl Default for OrderForm {
1097 fn default() -> Self {
1098 Self {
1099 exchange: "SHFE".to_string(),
1100 symbol: String::new(),
1101 direction: ek_data::constant::Direction::LONG,
1102 offset: ek_data::constant::Offset::OPEN,
1103 order_type: ek_data::constant::OrderType::LIMIT,
1104 price: String::new(),
1105 volume: "1".to_string(),
1106 gateway: String::new(),
1107 follow_price: true,
1108 auto_split: true,
1109 }
1110 }
1111}
1112
1113impl OrderForm {
1114 pub fn to_request(&self) -> Result<ek_data::order_request::OrderRequest, String> {
1116 use std::str::FromStr;
1117 let symbol = self.symbol.trim();
1118 if symbol.is_empty() {
1119 return Err("下单: 代码为空".to_string());
1120 }
1121 if symbol.contains('.') {
1122 return Err("下单: 代码不带交易所前缀(交易所走下拉)".to_string());
1123 }
1124 let exchange = ek_data::constant::Exchange::from_str(self.exchange.trim())
1125 .map_err(|e| format!("下单: {e}"))?;
1126 let price: f64 = self
1127 .price
1128 .trim()
1129 .parse()
1130 .map_err(|_| format!("下单: 价格无效 {:?}", self.price))?;
1131 let volume: f64 = self
1132 .volume
1133 .trim()
1134 .parse()
1135 .map_err(|_| format!("下单: 数量无效 {:?}", self.volume))?;
1136 if self.order_type != ek_data::constant::OrderType::MARKET && price <= 0.0 {
1137 return Err("下单: 限价单价格须为正".to_string());
1138 }
1139 if volume <= 0.0 {
1140 return Err("下单: 数量须为正".to_string());
1141 }
1142 Ok(ek_data::order_request::OrderRequest {
1143 symbol: symbol.to_string(),
1144 exchange,
1145 direction: self.direction,
1146 order_type: self.order_type,
1147 volume,
1148 price,
1149 offset: self.offset,
1150 ..ek_data::order_request::OrderRequest::default()
1151 })
1152 }
1153}
1154
1155#[derive(Debug, Default)]
1161pub struct ContractStore {
1162 contracts: BTreeMap<String, ek_data::contract::ContractData>,
1163}
1164
1165impl ContractStore {
1166 pub fn put(&mut self, c: &ek_data::contract::ContractData) {
1167 self.contracts
1168 .insert(format!("{}.{}", c.exchange.as_str(), c.symbol), c.clone());
1169 }
1170
1171 pub fn query(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
1173 let p = pattern.trim();
1174 self.contracts
1175 .values()
1176 .filter(|c| {
1177 p.is_empty()
1178 || c.symbol.contains(p)
1179 || c.exchange.as_str().eq_ignore_ascii_case(p)
1180 || c.name.contains(p)
1181 })
1182 .cloned()
1183 .collect()
1184 }
1185
1186 pub fn len(&self) -> usize {
1187 self.contracts.len()
1188 }
1189
1190 pub fn is_empty(&self) -> bool {
1191 self.contracts.is_empty()
1192 }
1193}
1194
1195#[derive(Debug, Default)]
1197pub struct UiShared {
1198 logs: Mutex<LogRing>,
1199 snap: Mutex<Arc<BusSnap>>,
1200 market: MarketStore,
1201 ctp_form: Mutex<CtpForm>,
1202 trade_orders: Mutex<BTreeMap<String, (u64, ek_data::order::OrderData)>>,
1205 trade_trades: Mutex<VecDeque<(u64, ek_data::trade::TradeData)>>,
1206 trade_ids: Mutex<HashSet<String>>,
1214 trade_positions: Mutex<BTreeMap<String, (u64, ek_data::position::PositionData)>>,
1215 trade_funds: Mutex<BTreeMap<String, (u64, ek_data::account::AccountData)>>,
1216 trade_seq: AtomicU64,
1218 trade_dropped: AtomicU64,
1220 trade_dirty: AtomicBool,
1222 trade_snap: Mutex<Arc<TradeSnap>>,
1224 tick_store: Mutex<TickStore>,
1225 order_form: Mutex<OrderForm>,
1226 data_split: Mutex<DataSplit>,
1229 selected_exchange: Mutex<String>,
1231 topleft_tab: Mutex<TopLeftTab>,
1233 bottomright_tab: Mutex<BottomRightTab>,
1235 ops_window: AtomicBool,
1236 accounts_window: AtomicBool,
1239 contracts_window: AtomicBool,
1240 contract_store: Mutex<ContractStore>,
1241 contract_query: Mutex<String>,
1242 contract_selected: Mutex<Vec<String>>,
1243 kline_windows: Mutex<Vec<String>>,
1244 rev: AtomicU64,
1245 stop: AtomicBool,
1247 cmds: Mutex<VecDeque<UiCmd>>,
1249 pending_confirm: Mutex<Option<String>>,
1251 accounts: Mutex<Vec<AccountRow>>,
1253 account_edit_window: AtomicBool,
1255 editing_account: Mutex<Option<String>>,
1257 edit_alias: Mutex<String>,
1259 edit_error: Mutex<Option<String>>,
1261 md_source: Mutex<String>,
1263 subscriptions: Mutex<Vec<String>>,
1265 row_sel: Mutex<BTreeMap<String, String>>,
1268 table_sorts: Mutex<BTreeMap<String, Option<(usize, bool)>>>,
1272 status_cursor: AtomicUsize,
1278 status_seed: Mutex<Vec<String>>,
1281 list_tick: AtomicU32,
1283 list_due: AtomicBool,
1287 seed_due: AtomicBool,
1291 pipeline_due: AtomicBool,
1293 cfg_due: AtomicBool,
1295 cfg_briefs: Mutex<Option<Vec<ek_cfg::wire::NsBrief>>>,
1298 cfg_delete_arm: Mutex<Option<String>>,
1300 theme: AtomicU8,
1304 theme_persist_due: AtomicBool,
1307 auto_connect_persist_due: AtomicBool,
1311 bad_payload: Mutex<BTreeMap<String, u64>>,
1313 pipeline_lines: Mutex<Vec<String>>,
1316 status_thresholds: Mutex<Option<(u32, i64)>>,
1319 pending_alerts: Mutex<Vec<(crate::toast::AlertLevel, String)>>,
1321 toasts: crate::toast::ToastsCell,
1324 alerted: Mutex<std::collections::BTreeSet<String>>,
1326 exit_confirm_open: AtomicBool,
1328 exit_confirmed: AtomicBool,
1330}
1331
1332impl UiShared {
1333 pub fn new() -> Self {
1335 Self::default()
1336 }
1337
1338 pub fn update_tick(&self, t: &ek_data::tick::TickData) {
1342 self.tick_store.lock().unwrap().put(t);
1343 self.bump();
1344 }
1345
1346 pub fn tick_rows(&self) -> Vec<ek_data::tick::TickData> {
1348 self.tick_store.lock().unwrap().rows()
1349 }
1350
1351 pub fn tick_groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
1353 self.tick_store.lock().unwrap().groups()
1354 }
1355
1356 pub fn tick_count(&self) -> usize {
1358 self.tick_store.lock().unwrap().len()
1359 }
1360
1361 pub fn order_form(&self) -> OrderForm {
1363 self.order_form.lock().unwrap().clone()
1364 }
1365
1366 pub fn set_order_form(&self, f: OrderForm) {
1368 *self.order_form.lock().unwrap() = f;
1369 self.bump();
1370 }
1371
1372 pub fn selected_exchange(&self) -> String {
1376 let s = self.selected_exchange.lock().unwrap().clone();
1377 if MARKET_ORDER.iter().any(|e| e.as_str() == s) {
1378 s
1379 } else {
1380 MARKET_ORDER[0].as_str().to_string()
1381 }
1382 }
1383
1384 pub fn set_selected_exchange(&self, s: impl Into<String>) {
1386 *self.selected_exchange.lock().unwrap() = s.into();
1387 self.bump();
1388 }
1389
1390 pub fn topleft_tab(&self) -> TopLeftTab {
1392 *self.topleft_tab.lock().unwrap()
1393 }
1394
1395 pub fn set_topleft_tab(&self, t: TopLeftTab) {
1397 *self.topleft_tab.lock().unwrap() = t;
1398 self.bump();
1399 }
1400
1401 pub fn bottomright_tab(&self) -> BottomRightTab {
1403 *self.bottomright_tab.lock().unwrap()
1404 }
1405
1406 pub fn set_bottomright_tab(&self, t: BottomRightTab) {
1408 *self.bottomright_tab.lock().unwrap() = t;
1409 self.bump();
1410 }
1411
1412 pub fn data_split(&self) -> DataSplit {
1414 *self.data_split.lock().unwrap()
1415 }
1416
1417 pub fn set_data_split(&self, s: DataSplit) {
1420 let s = DataSplit {
1421 col: crate::splitters::clamp_frac(s.col),
1422 row: crate::splitters::clamp_frac(s.row),
1423 };
1424 let mut g = self.data_split.lock().unwrap();
1425 if g.col != s.col || g.row != s.row {
1426 *g = s;
1427 self.bump();
1428 }
1429 }
1430
1431 pub fn reset_layout(&self) {
1435 *self.data_split.lock().unwrap() = DataSplit::default();
1436 *self.selected_exchange.lock().unwrap() = String::new();
1437 *self.topleft_tab.lock().unwrap() = TopLeftTab::default();
1438 *self.bottomright_tab.lock().unwrap() = BottomRightTab::default();
1439 self.bump();
1440 }
1441
1442 pub fn ops_window_open(&self) -> bool {
1446 self.ops_window.load(Ordering::Acquire)
1447 }
1448
1449 pub fn table_sort(&self, table: &str) -> Option<(usize, bool)> {
1452 self.table_sorts
1453 .lock()
1454 .unwrap()
1455 .get(table)
1456 .copied()
1457 .flatten()
1458 }
1459
1460 pub fn toggle_table_sort(&self, table: &str, col: usize) {
1462 let mut m = self.table_sorts.lock().unwrap();
1463 let asc = match m.get(table).copied().flatten() {
1464 Some((c, a)) if c == col => !a,
1465 _ => true,
1466 };
1467 m.insert(table.to_string(), Some((col, asc)));
1468 }
1469
1470 pub fn set_ops_window_open(&self, v: bool) {
1471 self.ops_window.store(v, Ordering::Release);
1472 self.bump();
1473 }
1474
1475 pub fn accounts_window_open(&self) -> bool {
1479 self.accounts_window.load(Ordering::Acquire)
1480 }
1481
1482 pub fn set_accounts_window_open(&self, v: bool) {
1484 self.accounts_window.store(v, Ordering::Release);
1485 self.bump();
1486 }
1487
1488 pub fn account_edit_open(&self) -> bool {
1490 self.account_edit_window.load(Ordering::Acquire)
1491 }
1492
1493 pub fn editing_account(&self) -> Option<String> {
1495 self.editing_account.lock().unwrap().clone()
1496 }
1497
1498 pub fn begin_account_edit(&self, gateway: Option<&str>) -> bool {
1502 match gateway {
1503 Some(gw) => {
1504 let Some(row) = self.account(gw) else {
1505 return false;
1506 };
1507 *self.editing_account.lock().unwrap() = Some(gw.to_string());
1508 *self.edit_alias.lock().unwrap() = row.alias.clone();
1509 self.set_ctp_form(row.form.clone());
1510 }
1511 None => {
1512 *self.editing_account.lock().unwrap() = None;
1513 *self.edit_alias.lock().unwrap() = String::new();
1514 let draft = self.draft_from_existing();
1515 self.set_ctp_form(draft);
1516 }
1517 }
1518 *self.edit_error.lock().unwrap() = None;
1519 self.account_edit_window.store(true, Ordering::Release);
1520 self.bump();
1521 true
1522 }
1523
1524 pub fn end_account_edit(&self) {
1526 *self.editing_account.lock().unwrap() = None;
1527 *self.edit_alias.lock().unwrap() = String::new();
1528 *self.edit_error.lock().unwrap() = None;
1529 self.account_edit_window.store(false, Ordering::Release);
1530 let draft = self.draft_from_existing();
1531 self.set_ctp_form(draft);
1532 self.bump();
1533 }
1534
1535 pub fn end_account_edit_if_editing(&self, gateway: &str) {
1541 if self.editing_account().as_deref() == Some(gateway) {
1542 self.end_account_edit();
1543 }
1544 }
1545
1546 pub fn edit_alias(&self) -> String {
1548 self.edit_alias.lock().unwrap().clone()
1549 }
1550
1551 pub fn set_edit_alias(&self, v: impl Into<String>) {
1553 *self.edit_alias.lock().unwrap() = v.into();
1554 self.bump();
1555 }
1556
1557 pub fn edit_error(&self) -> Option<String> {
1559 self.edit_error.lock().unwrap().clone()
1560 }
1561
1562 pub fn set_edit_error(&self, e: Option<String>) {
1564 *self.edit_error.lock().unwrap() = e;
1565 self.bump();
1566 }
1567
1568 pub fn account_edit_dirty(&self) -> bool {
1570 let editing = self.editing_account();
1571 let draft = self.ctp_form();
1572 match editing {
1573 Some(gw) => self.account(&gw).map(|a| a.form != draft).unwrap_or(false),
1574 None => draft != CtpForm::default() && !draft.td_user.trim().is_empty(),
1575 }
1576 }
1577
1578 pub fn accounts(&self) -> Vec<AccountRow> {
1580 self.accounts.lock().unwrap().clone()
1581 }
1582
1583 pub fn account(&self, gateway: &str) -> Option<AccountRow> {
1585 self.accounts
1586 .lock()
1587 .unwrap()
1588 .iter()
1589 .find(|a| a.gateway == gateway)
1590 .cloned()
1591 }
1592
1593 pub fn add_account(&self, row: AccountRow) -> Result<(), String> {
1599 let mut acc = self.accounts.lock().unwrap();
1600 if acc.iter().any(|a| a.gateway == row.gateway) {
1601 return Err(format!("账户 {} 已存在(同 broker + 账号)", row.gateway));
1602 }
1603 let alias = row.alias.trim();
1604 if !alias.is_empty()
1605 && acc
1606 .iter()
1607 .any(|a| a.alias.trim().eq_ignore_ascii_case(alias))
1608 {
1609 return Err(format!("别名 {alias:?} 已被其他账户占用(别名须唯一)"));
1610 }
1611 if acc.len() >= MAX_ACCOUNTS {
1612 return Err(format!(
1613 "账户已达软上限 {MAX_ACCOUNTS} 个(先移除一个再添加)"
1614 ));
1615 }
1616 acc.push(row);
1617 drop(acc);
1618 self.bump();
1619 Ok(())
1620 }
1621
1622 #[must_use]
1624 pub fn can_add_account(&self) -> bool {
1625 self.accounts.lock().unwrap().len() < MAX_ACCOUNTS
1626 }
1627
1628 pub fn set_account_alias(&self, gateway: &str, alias: &str) -> bool {
1634 let alias = alias.trim().to_string();
1635 let mut acc = self.accounts.lock().unwrap();
1636 if !alias.is_empty()
1637 && acc
1638 .iter()
1639 .any(|a| a.gateway != gateway && a.alias.eq_ignore_ascii_case(&alias))
1640 {
1641 return false;
1642 }
1643 match acc.iter_mut().find(|a| a.gateway == gateway) {
1644 Some(a) => {
1645 a.alias = alias;
1646 drop(acc);
1647 self.bump();
1648 true
1649 }
1650 None => false,
1651 }
1652 }
1653
1654 pub fn note_connect_sent(&self, gateway: &str) {
1659 let mut acc = self.accounts.lock().unwrap();
1660 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1661 a.stage = AccountStage::Assembling;
1662 a.fail_note = None;
1663 a.login = LoginState::Unknown;
1664 a.status_note = None;
1665 a.login_brief = None;
1666 a.chain_note = None;
1668 drop(acc);
1669 self.bump();
1670 }
1671 }
1672
1673 pub fn note_connect_result(&self, gateway: &str, result: Result<(), String>) {
1677 let mut acc = self.accounts.lock().unwrap();
1678 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1679 match result {
1680 Ok(()) => {
1681 a.stage = AccountStage::Assembled;
1682 a.fail_note = None;
1683 }
1684 Err(e) => {
1685 a.stage = AccountStage::AssembleFailed;
1686 a.fail_note = Some(e);
1687 }
1688 }
1689 drop(acc);
1690 self.bump();
1691 }
1692 }
1693
1694 pub fn note_effective_product_classes(&self, gateway: &str, classes: &[String]) {
1698 let mut acc = self.accounts.lock().unwrap();
1699 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1700 a.effective_classes = classes.to_vec();
1701 drop(acc);
1702 self.bump();
1703 }
1704 }
1705
1706 pub fn note_chain(&self, gateway: &str, note: &str) {
1711 let mut acc = self.accounts.lock().unwrap();
1712 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1713 if a.chain_note.as_deref() == Some(note) {
1714 return; }
1716 a.chain_note = Some(note.to_string());
1717 drop(acc);
1718 self.bump();
1719 }
1720 }
1721
1722 #[must_use]
1726 pub fn status_thresholds(&self) -> (u32, i64) {
1727 self.status_thresholds
1728 .lock()
1729 .unwrap()
1730 .unwrap_or((QUERY_REJECT_STREAK_LIMIT, ACCOUNT_STALE_SECS))
1731 }
1732
1733 pub fn set_status_thresholds(&self, reject_limit: u32, stale_secs: i64) {
1735 *self.status_thresholds.lock().unwrap() = Some((reject_limit, stale_secs));
1736 self.bump();
1737 }
1738
1739 pub fn list_poll_due(&self) -> bool {
1744 let n = self.list_tick.fetch_add(1, Ordering::Relaxed) + 1;
1745 self.list_due.swap(false, Ordering::AcqRel) || n == 1 || n.is_multiple_of(LIST_POLL_TICKS)
1746 }
1747
1748 pub fn request_list_refresh(&self) {
1750 self.list_due.store(true, Ordering::Release);
1751 }
1752
1753 pub fn request_trade_reseed(&self) {
1755 self.seed_due.store(true, Ordering::Release);
1756 }
1757
1758 pub fn take_trade_reseed(&self) -> bool {
1760 self.seed_due.swap(false, Ordering::AcqRel)
1761 }
1762
1763 pub fn status_batch(&self, present: &[String]) -> Vec<String> {
1768 let mut uniq: Vec<String> = Vec::with_capacity(present.len());
1772 for gw in present {
1773 if !uniq.iter().any(|u| u == gw) {
1774 uniq.push(gw.clone());
1775 }
1776 }
1777 let n = uniq.len();
1778 if n == 0 {
1779 return Vec::new();
1780 }
1781 let start = self.status_cursor.fetch_add(1, Ordering::Relaxed) % n;
1782 let take = STATUS_ASKS_PER_TICK.min(n);
1783 let mut out = Vec::with_capacity(take);
1784 for i in 0..take {
1785 out.push(uniq[(start + i) % n].clone());
1786 }
1787 out
1788 }
1789
1790 pub fn request_status_seed(&self, gateway: &str) {
1792 let mut q = self.status_seed.lock().unwrap();
1793 if !q.iter().any(|g| g == gateway) {
1794 q.push(gateway.to_string());
1795 }
1796 }
1797
1798 pub fn take_status_seeds(&self) -> Vec<String> {
1800 let mut q = self.status_seed.lock().unwrap();
1801 std::mem::take(&mut *q)
1802 }
1803
1804 pub fn note_status_event(&self, ev: &ek_ctp::GatewayStatusEvent) {
1814 let gw = ev.gateway.as_str();
1815 let text = ev.describe();
1816 self.log_line(format!("[INFO][{gw}] {text}"));
1817 let note = text
1818 .strip_prefix(CHAIN_STATE_PREFIX)
1819 .map(|s| s.trim().to_string())
1820 .unwrap_or_else(|| text.clone());
1821 self.note_chain(gw, ¬e);
1822 self.note_gateway_status(gw, &ev.status);
1823 let alarm_kind = matches!(
1824 ev.change,
1825 ek_ctp::GatewayChange::TdDisconnected
1826 | ek_ctp::GatewayChange::TdAuthFailed
1827 | ek_ctp::GatewayChange::TdLoginFailed
1828 | ek_ctp::GatewayChange::ContractQueryStopped
1829 | ek_ctp::GatewayChange::QueryRejected
1830 | ek_ctp::GatewayChange::MdDisconnected
1831 | ek_ctp::GatewayChange::MdLoginFailed
1832 | ek_ctp::GatewayChange::SubscribeRejected
1833 );
1834 if alarm_kind {
1835 let session = if ev.change.kind().starts_with("md-") {
1837 ev.status.md_disconnects
1838 } else {
1839 ev.status.td_disconnects
1840 };
1841 let key = format!("estatus:{gw}:{}:{session}", ev.change.kind());
1842 if self.alert_once(key) {
1843 self.push_alert(
1844 crate::toast::AlertLevel::Warning,
1845 format!("账户 {gw}:{}", note.trim()),
1846 );
1847 }
1848 }
1849 }
1850
1851 pub fn request_pipeline_refresh(&self) {
1853 self.pipeline_due.store(true, Ordering::Release);
1854 }
1855 pub fn take_pipeline_due(&self) -> bool {
1857 self.pipeline_due.swap(false, Ordering::AcqRel)
1858 }
1859
1860 pub fn request_cfg_refresh(&self) {
1862 self.cfg_due.store(true, Ordering::Release);
1863 }
1864
1865 pub fn take_cfg_due(&self) -> bool {
1867 self.cfg_due.swap(false, Ordering::AcqRel)
1868 }
1869
1870 pub fn theme(&self) -> crate::tokens::Theme {
1872 crate::tokens::Theme::from_u8(self.theme.load(Ordering::Acquire))
1873 }
1874
1875 pub fn set_theme(&self, theme: crate::tokens::Theme) {
1878 self.theme.store(theme.as_u8(), Ordering::Release);
1879 self.bump();
1880 }
1881
1882 pub fn toggle_theme(&self) -> crate::tokens::Theme {
1884 let next = self.theme().flipped();
1885 self.theme.store(next.as_u8(), Ordering::Release);
1886 self.theme_persist_due.store(true, Ordering::Release);
1887 self.bump();
1888 next
1889 }
1890
1891 pub fn take_theme_persist_due(&self) -> bool {
1893 self.theme_persist_due.swap(false, Ordering::AcqRel)
1894 }
1895
1896 pub fn set_auto_connect(&self, gateway: &str, on: bool) -> Result<(), String> {
1900 {
1901 let mut acc = self.accounts.lock().unwrap();
1902 match acc.iter_mut().find(|a| a.gateway == gateway) {
1903 Some(a) => {
1904 if a.auto_connect != on {
1905 a.auto_connect = on;
1906 self.auto_connect_persist_due.store(true, Ordering::Release);
1907 self.bump();
1908 }
1909 }
1910 None => return Err(format!("账户 {gateway} 不在清册")),
1911 }
1912 }
1913 Ok(())
1914 }
1915
1916 pub fn take_auto_connect_persist_due(&self) -> bool {
1918 self.auto_connect_persist_due.swap(false, Ordering::AcqRel)
1919 }
1920
1921 pub fn restore_saved_accounts_from(&self, store: &ek_cfg::Store) -> Vec<String> {
1936 let mut flags: std::collections::BTreeMap<String, bool> = Default::default();
1938 match store.load(crate::plugin::THEME_NS) {
1939 Ok(ek_cfg::LoadOutcome::Loaded { map, .. }) => {
1940 for (k, _f) in map.iter() {
1941 if let Some(gw) = k.strip_prefix("auto_connect.") {
1942 flags.insert(gw.to_string(), map.get_plain(k) == Some("1"));
1943 }
1944 }
1945 }
1946 Ok(_) => {} Err(_) => {} }
1949 let mut restored: Vec<String> = Vec::new();
1950 let ns_list = match store.list_namespaces() {
1951 Ok(v) => v,
1952 Err(_) => {
1953 let msg = "[ui] 档案清点失败:存储根不可读(具体见运行日志)".to_string();
1954 self.log_line(msg.clone());
1955 return restored;
1956 }
1957 };
1958 for ns in ns_list {
1959 let Some(gw) = ns.strip_prefix("ctp.") else {
1960 continue;
1961 };
1962 if self.account(gw).is_some() {
1963 self.log_line(format!(
1964 "[ui] 档案 {ns} 与在册同名行撞名,清点不覆盖(清册行为唯一事实源)"
1965 ));
1966 continue;
1967 }
1968 let map = match store.load(&ns) {
1969 Ok(ek_cfg::LoadOutcome::Loaded { map, .. }) => map,
1970 Ok(_) => {
1971 self.log_line(format!("[ui] 档案 {ns} 一段也读不出(跳过)"));
1972 continue;
1973 }
1974 Err(e) => {
1975 self.log_line(format!("[ui] 档案 {ns} 读不了:{e:?}(跳过)"));
1976 continue;
1977 }
1978 };
1979 let password_ref = map
1981 .get_secret_key("td_password")
1982 .is_some_and(|k| !k.is_empty());
1983 let mut form = CtpForm {
1984 broker_id: map.get_plain("broker_id").unwrap_or_default().to_owned(),
1985 td_addr: map.get_plain("td_addr").unwrap_or_default().to_owned(),
1986 td_user: map.get_plain("td_user").unwrap_or_default().to_owned(),
1987 td_password: String::new(),
1988 td_auth_code: map.get_plain("td_auth_code").unwrap_or_default().to_owned(),
1989 td_app_id: map.get_plain("td_app_id").unwrap_or_default().to_owned(),
1990 md_addr: map.get_plain("md_addr").unwrap_or_default().to_owned(),
1991 md_user: String::new(),
1992 md_password: String::new(),
1993 symbols: String::new(),
1994 accept_futures: false,
1995 accept_options: false,
1996 };
1997 for c in map
2000 .get_plain("product_classes")
2001 .unwrap_or_default()
2002 .split(',')
2003 {
2004 if c.trim() == "1" {
2005 form.accept_futures = true;
2006 }
2007 }
2008 let Ok(mut row) = AccountRow::derive(&form) else {
2009 self.log_line(format!(
2010 "[ui] 档案 {ns} 无法派生(账号/前置非法别名冲突?),跳过 —— 界面手输重配更省心"
2011 ));
2012 continue;
2013 };
2014 row.restored = true;
2015 row.auto_connect = flags.get(gw).copied().unwrap_or(false);
2016 row.password_ref = password_ref;
2017 restored.push(row.gateway.clone());
2018 self.add_account(row).ok();
2019 }
2020 if !restored.is_empty() {
2021 self.log_line(format!(
2022 "[ui] 账户档案清点复原 {} 行(手点「连接」直连存档;自动连接按行上勾选)",
2023 restored.len()
2024 ));
2025 self.bump();
2026 }
2027 restored
2028 }
2029
2030 pub fn restore_saved_accounts(&self) -> Vec<String> {
2032 match ek_cfg::Store::eco() {
2033 Ok(store) => self.restore_saved_accounts_from(&store),
2034 Err(_) => {
2035 self.log_line(
2036 "[ui] 档案清点跳过:config_dir() 不可用(BD-CFG-20;配置根异常该显形)".to_string(),
2037 );
2038 Vec::new()
2039 }
2040 }
2041 }
2042
2043 pub fn set_cfg_briefs(&self, b: Vec<ek_cfg::wire::NsBrief>) {
2045 *self.cfg_briefs.lock().unwrap() = Some(b);
2046 self.bump();
2047 }
2048 pub fn cfg_briefs(&self) -> Option<Vec<ek_cfg::wire::NsBrief>> {
2050 self.cfg_briefs.lock().unwrap().clone()
2051 }
2052
2053 pub fn cfg_delete_armed(&self) -> Option<String> {
2055 self.cfg_delete_arm.lock().unwrap().clone()
2056 }
2057 pub fn arm_cfg_delete(&self, ns: Option<String>) {
2058 *self.cfg_delete_arm.lock().unwrap() = ns;
2059 self.bump();
2060 }
2061
2062 pub fn set_pipeline_lines(&self, lines: Vec<String>) {
2064 *self.pipeline_lines.lock().unwrap() = lines;
2065 self.bump();
2066 }
2067
2068 pub fn pipeline_lines(&self) -> Vec<String> {
2070 self.pipeline_lines.lock().unwrap().clone()
2071 }
2072
2073 pub fn note_bad_payload(&self, line: &str) {
2079 let mut book = self.bad_payload.lock().unwrap();
2080 let n = book.entry(line.to_string()).or_insert(0);
2081 *n += 1;
2082 if *n == 1 {
2083 self.log_line(format!(
2084 "[ui] {line} 载荷类型异常(第一次):这一路的行进不了账本"
2085 ));
2086 }
2087 }
2088
2089 #[must_use]
2091 pub fn bad_payload_count(&self, line: &str) -> u64 {
2092 self.bad_payload
2093 .lock()
2094 .unwrap()
2095 .get(line)
2096 .copied()
2097 .unwrap_or(0)
2098 }
2099
2100 pub fn note_plugin_spill(&self, rows: &[ek_station::wire::PlugRow]) {
2114 for r in rows {
2115 let (warn, crit) = pending_thresholds(r.soft_cap);
2116 if r.pending >= warn && self.alert_once(format!("pend-warn:{}", r.name)) {
2117 self.push_alert(
2118 crate::toast::AlertLevel::Warning,
2119 format!(
2120 "插件 {}:邮箱积压 {} 帧(峰值 {};该插件软顶 {})——它的 worker 消化不过来,刷新会变慢",
2121 r.name, r.pending, r.peak, r.soft_cap
2122 ),
2123 );
2124 }
2125 if r.pending >= crit && self.alert_once(format!("pend-crit:{}", r.name)) {
2126 self.push_alert(
2127 crate::toast::AlertLevel::Error,
2128 format!(
2129 "插件 {}:邮箱积压 {} 帧,越过软顶 {} 的四分之一——再涨就开始丢新到的事件",
2130 r.name, r.pending, r.soft_cap
2131 ),
2132 );
2133 }
2134 if r.spilled > 0 && self.alert_once(format!("spill:{}", r.name)) {
2135 self.push_alert(
2136 crate::toast::AlertLevel::Error,
2137 format!(
2138 "插件 {}:已触软顶 {} 并丢弃新到事件累计 {} 条(峰值 {})——它的消化速度跟不上生产速度",
2139 r.name, r.soft_cap, r.spilled, r.peak
2140 ),
2141 );
2142 }
2143 }
2144 }
2145
2146 pub fn note_gateway_status(&self, gateway: &str, st: &ek_ctp::plugin::GatewayStatus) {
2154 let (limit, stale) = self.status_thresholds();
2155 let now = ek_ctp::map::now_epoch_ms();
2156 let mut alarm: Option<(LoginState, String)> = None;
2159 let mut found = false;
2160 {
2161 let mut acc = self.accounts.lock().unwrap();
2162 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
2163 found = true;
2164 a.apply_status(st, now, limit, stale);
2165 if a.login.is_alarm() || a.login == LoginState::QueryStarved {
2166 alarm = Some((
2167 a.login,
2168 a.status_note
2169 .clone()
2170 .unwrap_or_else(|| a.login.label().to_string()),
2171 ));
2172 }
2173 }
2174 }
2175 if found {
2176 self.bump();
2177 }
2178 if let Some((login, note)) = alarm
2179 && self.alert_once(format!("{gateway}|{}", login.label()))
2180 {
2181 self.push_alert(
2182 crate::toast::AlertLevel::Error,
2183 format!("账户 {gateway}:{note}"),
2184 );
2185 }
2186 }
2187
2188 pub fn note_status_unreachable(&self, gateway: &str, why: &str) {
2192 let mut acc = self.accounts.lock().unwrap();
2193 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
2194 a.login = LoginState::Unknown;
2195 a.status_note = Some(format!("状态口问不到:{why}"));
2196 a.login_brief = None;
2197 drop(acc);
2198 self.bump();
2199 }
2200 }
2201
2202 pub fn mark_account_stopped(&self, gateway: &str) {
2204 let mut acc = self.accounts.lock().unwrap();
2205 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
2206 a.login = LoginState::Stopped;
2207 a.status_note = Some("会话已停;『连接』可恢复".to_string());
2208 a.login_brief = None;
2209 drop(acc);
2210 self.bump();
2211 }
2212 }
2213
2214 pub fn prepare_connect_form(&self, gateway: &str, form: CtpForm) -> CtpForm {
2217 let source = self.md_source();
2218 let mut f = form;
2219 if source.as_str() != gateway {
2220 f.md_addr.clear();
2221 f.md_user.clear();
2222 f.md_password.clear();
2223 }
2224 self.update_account_form(gateway, f.clone());
2225 f
2226 }
2227
2228 #[must_use]
2232 pub fn draft_from_existing(&self) -> CtpForm {
2233 let acc = self.accounts.lock().unwrap();
2234 let mut draft = CtpForm::default();
2235 if let Some(a) = acc.last() {
2236 draft.broker_id = a.form.broker_id.clone();
2237 draft.td_auth_code = a.form.td_auth_code.clone();
2238 draft.td_app_id = a.form.td_app_id.clone();
2239 draft.accept_futures = a.form.accept_futures;
2240 draft.accept_options = a.form.accept_options;
2241 }
2242 draft
2243 }
2244
2245 pub fn update_account_form(&self, gateway: &str, form: CtpForm) -> bool {
2247 let mut acc = self.accounts.lock().unwrap();
2248 match acc.iter_mut().find(|a| a.gateway == gateway) {
2249 Some(a) => {
2250 a.form = form;
2251 drop(acc);
2252 self.bump();
2253 true
2254 }
2255 None => false,
2256 }
2257 }
2258
2259 pub fn remove_account(&self, gateway: &str) -> bool {
2261 let mut acc = self.accounts.lock().unwrap();
2262 let before = acc.len();
2263 acc.retain(|a| a.gateway != gateway);
2264 let removed = acc.len() != before;
2265 if removed {
2266 let mut md = self.md_source.lock().unwrap();
2268 if md.as_str() == gateway {
2269 md.clear();
2270 }
2271 drop(acc);
2272 self.bump();
2273 }
2274 removed
2275 }
2276
2277 pub fn sync_accounts_connected(&self, rows: &[PlugRow]) -> Vec<String> {
2286 let mut newly = Vec::new();
2287 {
2288 let mut acc = self.accounts.lock().unwrap();
2289 for a in acc.iter_mut() {
2290 let up = rows.iter().any(|r| r.name == a.gateway);
2291 if up && !a.connected {
2292 newly.push(a.gateway.clone());
2293 }
2294 a.connected = up;
2295 if up {
2296 a.stage = AccountStage::Assembled;
2297 a.fail_note = None;
2298 } else {
2299 a.chain_note = None;
2302 if a.stage == AccountStage::Assembled {
2303 a.stage = AccountStage::NotAssembled;
2304 a.login = LoginState::Unknown;
2305 a.status_note = None;
2306 a.login_brief = None;
2307 }
2308 }
2309 }
2310 }
2311 if !newly.is_empty() {
2312 self.bump();
2313 }
2314 newly
2315 }
2316
2317 pub fn md_source(&self) -> String {
2319 self.md_source.lock().unwrap().clone()
2320 }
2321
2322 pub fn accounts_locked(&self) -> bool {
2324 self.accounts.lock().unwrap().iter().any(|a| a.connected)
2325 }
2326
2327 pub fn set_md_source(&self, gateway: &str) -> Result<(), String> {
2329 {
2330 let acc = self.accounts.lock().unwrap();
2331 if acc.iter().any(|a| a.connected) {
2332 return Err("元账号已锁定:有账户在线,切换行情源需先断开该账户".to_string());
2333 }
2334 if !acc.iter().any(|a| a.gateway == gateway) {
2335 return Err(format!("账户 {gateway} 不在清册"));
2336 }
2337 }
2338 let mut acc = self.accounts.lock().unwrap();
2339 for a in acc.iter_mut() {
2340 a.md_source = a.gateway == gateway;
2341 }
2342 drop(acc);
2343 let mut md = self.md_source.lock().unwrap();
2344 *md = gateway.to_string();
2345 self.bump();
2346 Ok(())
2347 }
2348
2349 pub fn subscriptions(&self) -> Vec<String> {
2351 self.subscriptions.lock().unwrap().clone()
2352 }
2353
2354 pub fn note_subscriptions(&self, symbols: &[String]) {
2356 {
2357 let mut subs = self.subscriptions.lock().unwrap();
2358 for s in symbols {
2359 let s = s.trim();
2360 if !s.is_empty() && !subs.iter().any(|x| x == s) {
2361 subs.push(s.to_string());
2362 }
2363 }
2364 }
2365 self.bump();
2366 }
2367
2368 pub fn default_gateway(&self) -> Option<String> {
2375 let chosen = {
2376 let f = self.order_form.lock().unwrap();
2377 f.gateway.trim().to_string()
2378 };
2379 if !chosen.is_empty() && self.account(&chosen).is_some_and(|a| a.connected) {
2380 return Some(chosen);
2381 }
2382 let acc = self.accounts.lock().unwrap();
2383 acc.iter().find(|a| a.connected).map(|a| a.gateway.clone())
2384 }
2385
2386 pub fn kline_symbols(&self) -> Vec<String> {
2388 self.kline_windows.lock().unwrap().clone()
2389 }
2390
2391 pub fn open_kline(&self, symbol: impl Into<String>) {
2393 let s = symbol.into();
2394 let mut v = self.kline_windows.lock().unwrap();
2395 if !v.contains(&s) {
2396 v.push(s.clone());
2397 }
2398 drop(v);
2399 self.log_line(format!("[kline] 打开 K线窗 {s}"));
2400 }
2401
2402 pub fn close_kline(&self, symbol: &str) {
2404 self.kline_windows.lock().unwrap().retain(|s| s != symbol);
2405 self.bump();
2406 }
2407
2408 pub fn contracts_window_open(&self) -> bool {
2412 self.contracts_window.load(Ordering::Acquire)
2413 }
2414
2415 pub fn set_contracts_window_open(&self, v: bool) {
2417 self.contracts_window.store(v, Ordering::Release);
2418 self.bump();
2419 }
2420
2421 pub fn update_contract(&self, c: &ek_data::contract::ContractData) {
2428 self.contract_store.lock().unwrap().put(c);
2429 if !c.name.is_empty() {
2430 self.backfill_names(&c.symbol, &c.name);
2431 }
2432 self.bump();
2433 }
2434
2435 fn backfill_names(&self, symbol: &str, name: &str) {
2440 let mut touched = false;
2441 {
2442 let mut rows = self.trade_orders.lock().unwrap();
2443 for (_, (_, o)) in rows.iter_mut() {
2444 if o.symbol == symbol && o.name.is_empty() {
2445 o.name = name.to_string();
2446 touched = true;
2447 }
2448 }
2449 }
2450 {
2451 let mut rows = self.trade_trades.lock().unwrap();
2452 for (_, t) in rows.iter_mut() {
2453 if t.symbol == symbol && t.name.is_empty() {
2454 t.name = name.to_string();
2455 touched = true;
2456 }
2457 }
2458 }
2459 {
2460 let mut rows = self.trade_positions.lock().unwrap();
2461 for (_, (_, p)) in rows.iter_mut() {
2462 if p.symbol == symbol && p.name.is_empty() {
2463 p.name = name.to_string();
2464 touched = true;
2465 }
2466 }
2467 }
2468 if touched {
2469 self.trade_dirty.store(true, Ordering::Release);
2471 }
2472 }
2473
2474 pub fn contracts(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
2476 self.contract_store.lock().unwrap().query(pattern)
2477 }
2478
2479 pub fn contract_count(&self) -> usize {
2481 self.contract_store.lock().unwrap().len()
2482 }
2483
2484 fn contract_name_of(&self, symbol: &str) -> Option<String> {
2486 self.contract_store
2487 .lock()
2488 .unwrap()
2489 .query(symbol)
2490 .into_iter()
2491 .find(|c| c.symbol == symbol && !c.name.is_empty())
2492 .map(|c| c.name)
2493 }
2494
2495 pub fn contract_query(&self) -> String {
2497 self.contract_query.lock().unwrap().clone()
2498 }
2499
2500 pub fn set_contract_query(&self, q: impl Into<String>) {
2502 *self.contract_query.lock().unwrap() = q.into();
2503 self.bump();
2504 }
2505
2506 pub fn toggle_contract_selection(&self, en_symbol: &str) {
2508 let mut v = self.contract_selected.lock().unwrap();
2509 match v.iter().position(|s| s == en_symbol) {
2510 Some(i) => {
2511 v.remove(i);
2512 }
2513 None => v.push(en_symbol.to_string()),
2514 }
2515 self.bump();
2516 }
2517
2518 pub fn selected_contracts(&self) -> Vec<String> {
2520 self.contract_selected.lock().unwrap().clone()
2521 }
2522
2523 #[must_use]
2529 pub fn cancel_reject_note(msg: &str) -> String {
2530 let head = msg.split(' ').next().unwrap_or(msg);
2531 let note = if head.starts_with("unknown:order") {
2532 "这台网关的账本里没有这笔委托(登录前的旧单,或不属于这个账户)"
2533 } else if head.starts_with("mismatch:gateway") {
2534 "该委托不属于这个账户(归属守卫挡住,不会撤到别人头上)"
2535 } else if head.starts_with("terminal:status") {
2536 "这笔委托已经到终态(已成交/已撤/已拒),撤不了了"
2537 } else if head.starts_with("limit:cancel-guard") {
2538 "撤单尝试次数已到上限(每单有上限,防连点打爆柜台)"
2539 } else {
2540 ""
2541 };
2542 if note.is_empty() {
2543 format!("撤单被拒:{msg}")
2545 } else {
2546 format!("撤单被拒:{note}(机器码:{msg})")
2547 }
2548 }
2549
2550 pub fn log_line(&self, line: impl Into<String>) {
2552 self.logs.lock().unwrap().push(line);
2553 self.bump();
2554 }
2555
2556 pub fn clear_logs(&self) {
2558 self.logs.lock().unwrap().clear();
2559 self.bump();
2560 }
2561
2562 pub fn logs_snapshot(&self) -> (Vec<String>, u64) {
2564 let r = self.logs.lock().unwrap();
2565 (r.snapshot(), r.spilled())
2566 }
2567
2568 pub fn logs_entries(&self) -> (Vec<LogEntry>, u64) {
2570 let r = self.logs.lock().unwrap();
2571 (r.entries(), r.spilled())
2572 }
2573
2574 pub fn logs_len(&self) -> usize {
2576 self.logs.lock().unwrap().len()
2577 }
2578
2579 pub fn set_snapshot(&self, snap: BusSnap) {
2581 *self.snap.lock().unwrap() = Arc::new(snap);
2582 self.bump();
2583 }
2584
2585 pub fn snapshot(&self) -> Arc<BusSnap> {
2587 Arc::clone(&self.snap.lock().unwrap())
2588 }
2589
2590 pub fn rev(&self) -> u64 {
2592 self.rev.load(Ordering::Acquire)
2593 }
2594
2595 pub fn bump(&self) {
2597 self.rev.fetch_add(1, Ordering::AcqRel);
2598 }
2599
2600 pub fn request_stop(&self) {
2602 self.stop.store(true, Ordering::Release);
2603 }
2604
2605 pub fn push_alert(&self, level: crate::toast::AlertLevel, text: impl Into<String>) {
2608 self.pending_alerts
2609 .lock()
2610 .unwrap_or_else(std::sync::PoisonError::into_inner)
2611 .push((level, text.into()));
2612 }
2613
2614 pub(crate) fn take_alerts(&self) -> Vec<(crate::toast::AlertLevel, String)> {
2616 let mut q = self
2617 .pending_alerts
2618 .lock()
2619 .unwrap_or_else(std::sync::PoisonError::into_inner);
2620 std::mem::take(&mut *q)
2621 }
2622
2623 pub(crate) fn toasts(&self) -> std::sync::MutexGuard<'_, Option<egui_notify::Toasts>> {
2625 self.toasts.lock()
2626 }
2627
2628 pub fn alert_once(&self, key: impl Into<String>) -> bool {
2630 let key = key.into();
2631 self.alerted
2632 .lock()
2633 .unwrap_or_else(std::sync::PoisonError::into_inner)
2634 .insert(key)
2635 }
2636
2637 #[must_use]
2639 pub fn pending_alert_count(&self) -> usize {
2640 self.pending_alerts
2641 .lock()
2642 .unwrap_or_else(std::sync::PoisonError::into_inner)
2643 .len()
2644 }
2645
2646 #[must_use]
2648 pub fn alerted_count(&self) -> usize {
2649 self.alerted
2650 .lock()
2651 .unwrap_or_else(std::sync::PoisonError::into_inner)
2652 .len()
2653 }
2654
2655 pub fn exit_confirm_open(&self) -> bool {
2657 self.exit_confirm_open
2658 .load(std::sync::atomic::Ordering::Relaxed)
2659 }
2660
2661 pub fn open_exit_confirm(&self) {
2662 self.exit_confirm_open
2663 .store(true, std::sync::atomic::Ordering::Relaxed);
2664 }
2665
2666 pub fn close_exit_confirm(&self) {
2667 self.exit_confirm_open
2668 .store(false, std::sync::atomic::Ordering::Relaxed);
2669 }
2670
2671 pub fn exit_confirmed(&self) -> bool {
2672 self.exit_confirmed
2673 .load(std::sync::atomic::Ordering::Relaxed)
2674 }
2675
2676 pub fn confirm_exit(&self) {
2677 self.exit_confirmed
2678 .store(true, std::sync::atomic::Ordering::Relaxed);
2679 }
2680
2681 pub fn is_stop(&self) -> bool {
2682 self.stop.load(Ordering::Acquire)
2683 }
2684
2685 pub fn push_cmd(&self, cmd: UiCmd) {
2689 self.cmds.lock().unwrap().push_back(cmd);
2690 self.bump();
2691 }
2692
2693 pub fn drain_cmds(&self) -> Vec<UiCmd> {
2695 self.cmds.lock().unwrap().drain(..).collect()
2696 }
2697
2698 #[must_use]
2700 pub fn cmd_pending(&self) -> bool {
2701 !self.cmds.lock().unwrap().is_empty()
2702 }
2703
2704 pub fn pending_confirm(&self) -> Option<String> {
2706 self.pending_confirm.lock().unwrap().clone()
2707 }
2708
2709 pub fn confirm_step(&self, name: &str) -> ConfirmStep {
2711 let mut g = self.pending_confirm.lock().unwrap();
2712 match g.take() {
2713 Some(p) if p == name => ConfirmStep::Fired,
2714 Some(_) => {
2715 *g = Some(name.to_string());
2716 ConfirmStep::Switched
2717 }
2718 None => {
2719 *g = Some(name.to_string());
2720 ConfirmStep::Armed
2721 }
2722 }
2723 }
2724
2725 pub fn confirm_cancel(&self) {
2727 *self.pending_confirm.lock().unwrap() = None;
2728 self.bump();
2729 }
2730
2731 pub fn market(&self) -> &MarketStore {
2735 &self.market
2736 }
2737
2738 pub fn seed_trade_snap(&self, ts: TradeSnap) {
2747 let named = |symbol: &str, name: String| -> String {
2750 if name.is_empty() {
2751 self.contract_name_of(symbol).unwrap_or(name)
2752 } else {
2753 name
2754 }
2755 };
2756 {
2757 let mut book = self.trade_orders.lock().unwrap();
2758 book.clear();
2759 for mut o in ts.orders.into_iter().rev() {
2760 o.name = named(&o.symbol, o.name);
2761 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2762 book.insert(o.en_orderid(), (seq, o));
2763 }
2764 }
2765 {
2766 let mut book = self.trade_trades.lock().unwrap();
2767 book.clear();
2768 let mut ids = self.trade_ids.lock().unwrap();
2769 ids.clear();
2770 for mut t in ts.trades.into_iter().rev() {
2771 t.name = named(&t.symbol, t.name);
2772 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2773 ids.insert(t.en_tradeid());
2774 book.push_front((seq, t));
2775 }
2776 }
2777 {
2778 let mut book = self.trade_positions.lock().unwrap();
2779 book.clear();
2780 for mut p in ts.positions.into_iter().rev() {
2781 p.name = named(&p.symbol, p.name);
2782 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2783 book.insert(p.en_positionid(), (seq, p));
2784 }
2785 }
2786 {
2787 let mut book = self.trade_funds.lock().unwrap();
2788 book.clear();
2789 for a in ts.accounts.into_iter().rev() {
2790 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2791 book.insert(a.en_accountid(), (seq, a));
2792 }
2793 }
2794 self.trade_dirty.store(true, Ordering::Release);
2795 self.bump();
2796 }
2797
2798 pub fn note_order(&self, o: &ek_data::order::OrderData) {
2806 let key = o.en_orderid();
2807 {
2808 let mut book = self.trade_orders.lock().unwrap();
2809 match book.get_mut(&key) {
2810 Some((_, cur)) => {
2811 cur.name.clone_from(&o.name);
2812 cur.traded = o.traded;
2813 cur.traded_price = o.traded_price;
2814 cur.status = o.status;
2815 cur.status_msg.clone_from(&o.status_msg);
2816 cur.datetime = o.datetime;
2817 }
2818 None => {
2819 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2820 book.insert(key, (seq, o.clone()));
2821 }
2822 }
2823 }
2824 self.trade_dirty.store(true, Ordering::Release);
2825 self.bump();
2826 }
2827
2828 pub fn note_trade(&self, t: &ek_data::trade::TradeData) {
2836 let id = t.en_tradeid();
2837 if self.trade_ids.lock().unwrap().contains(&id) {
2838 return;
2839 }
2840 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2841 let dropped = {
2842 let mut book = self.trade_trades.lock().unwrap();
2843 book.push_front((seq, t.clone()));
2844 self.trade_ids.lock().unwrap().insert(id);
2845 let over = book.len().saturating_sub(TRADE_CAP);
2846 for _ in 0..over {
2847 if let Some((_, old)) = book.pop_back() {
2849 self.trade_ids.lock().unwrap().remove(&old.en_tradeid());
2850 }
2851 }
2852 over
2853 };
2854 if dropped > 0 {
2855 let total = self
2856 .trade_dropped
2857 .fetch_add(dropped as u64, Ordering::AcqRel)
2858 + dropped as u64;
2859 if total == dropped as u64 {
2861 self.push_alert(
2862 crate::toast::AlertLevel::Warning,
2863 format!("成交表已达 {TRADE_CAP} 行上限:更早的成交不再显示"),
2864 );
2865 }
2866 }
2867 self.trade_dirty.store(true, Ordering::Release);
2868 self.bump();
2869 }
2870
2871 pub fn note_position(&self, p: &ek_data::position::PositionData) {
2876 let key = p.en_positionid();
2877 {
2878 let mut book = self.trade_positions.lock().unwrap();
2879 match book.get_mut(&key) {
2880 Some((_, cur)) => {
2881 cur.volume = p.volume;
2882 cur.yd_volume = p.yd_volume;
2883 cur.can_use_volume = p.can_use_volume;
2884 cur.frozen = p.frozen;
2885 cur.on_road_volume = p.on_road_volume;
2886 cur.market_value = p.market_value;
2887 cur.avg_price = p.avg_price;
2888 cur.price = p.price;
2889 cur.last_price = p.last_price;
2890 cur.pnl = p.pnl;
2891 cur.profit_rate = p.profit_rate;
2892 cur.name.clone_from(&p.name);
2893 }
2894 None => {
2895 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2896 book.insert(key, (seq, p.clone()));
2897 }
2898 }
2899 }
2900 self.trade_dirty.store(true, Ordering::Release);
2901 self.bump();
2902 }
2903
2904 pub fn note_funds(&self, a: &ek_data::account::AccountData) {
2906 let key = a.en_accountid();
2907 {
2908 let mut book = self.trade_funds.lock().unwrap();
2909 match book.get_mut(&key) {
2910 Some((_, cur)) => {
2911 cur.balance = a.balance;
2912 cur.frozen = a.frozen;
2913 }
2914 None => {
2915 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2916 book.insert(key, (seq, a.clone()));
2917 }
2918 }
2919 }
2920 self.trade_dirty.store(true, Ordering::Release);
2921 self.bump();
2922 }
2923
2924 pub fn clear_gateway_rows(&self, gateway: &str) -> usize {
2926 let mut removed = 0usize;
2927 {
2928 let mut book = self.trade_orders.lock().unwrap();
2929 let before = book.len();
2930 book.retain(|_, (_, o)| o.gateway_name != gateway);
2931 removed += before - book.len();
2932 }
2933 {
2934 let mut book = self.trade_trades.lock().unwrap();
2935 let before = book.len();
2936 book.retain(|(_, t)| t.gateway_name != gateway);
2937 removed += before - book.len();
2938 let prefix = format!("{gateway}.");
2941 self.trade_ids
2942 .lock()
2943 .unwrap()
2944 .retain(|id| !id.starts_with(&prefix));
2945 }
2946 {
2947 let mut book = self.trade_positions.lock().unwrap();
2948 let before = book.len();
2949 book.retain(|_, (_, p)| p.gateway_name != gateway);
2950 removed += before - book.len();
2951 }
2952 {
2953 let mut book = self.trade_funds.lock().unwrap();
2954 let before = book.len();
2955 book.retain(|_, (_, a)| a.gateway_name != gateway);
2956 removed += before - book.len();
2957 }
2958 if removed > 0 {
2959 self.trade_dirty.store(true, Ordering::Release);
2960 self.bump();
2961 }
2962 removed
2963 }
2964
2965 #[must_use]
2967 pub fn trade_dropped(&self) -> u64 {
2968 self.trade_dropped.load(Ordering::Acquire)
2969 }
2970
2971 pub fn trade_snap(&self) -> Arc<TradeSnap> {
2976 let mut cache = self.trade_snap.lock().unwrap();
2977 if self.trade_dirty.swap(false, Ordering::AcqRel) {
2978 *cache = Arc::new(self.build_trade_snap());
2979 }
2980 Arc::clone(&cache)
2981 }
2982
2983 fn build_trade_snap(&self) -> TradeSnap {
2986 fn by_seq<T>(rows: &BTreeMap<String, (u64, T)>) -> Vec<T>
2987 where
2988 T: Clone,
2989 {
2990 let mut v: Vec<(u64, &String, &T)> =
2991 rows.iter().map(|(k, (s, v))| (*s, k, v)).collect();
2992 v.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
2993 v.into_iter().map(|(_, _, v)| v.clone()).collect()
2994 }
2995 TradeSnap {
2996 orders: by_seq(&self.trade_orders.lock().unwrap()),
2997 trades: self
2998 .trade_trades
2999 .lock()
3000 .unwrap()
3001 .iter()
3002 .map(|(_, t)| t.clone())
3003 .collect(),
3004 positions: by_seq(&self.trade_positions.lock().unwrap()),
3005 accounts: by_seq(&self.trade_funds.lock().unwrap()),
3006 }
3007 }
3008
3009 pub fn ctp_form(&self) -> CtpForm {
3013 self.ctp_form.lock().unwrap().clone()
3014 }
3015
3016 pub fn set_ctp_form(&self, f: CtpForm) {
3018 *self.ctp_form.lock().unwrap() = f;
3019 self.bump();
3020 }
3021
3022 pub fn row_selected(&self, table: &str, key: &str) -> bool {
3026 self.row_sel
3027 .lock()
3028 .unwrap()
3029 .get(table)
3030 .is_some_and(|k| k == key)
3031 }
3032
3033 pub fn select_row(&self, table: &str, key: &str) {
3035 self.row_sel
3036 .lock()
3037 .unwrap()
3038 .insert(table.to_string(), key.to_string());
3039 }
3040}