1use std::collections::{BTreeMap, HashSet, VecDeque};
7use std::sync::atomic::{AtomicBool, 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 stage: AccountStage,
650 pub fail_note: Option<String>,
652 pub effective_classes: Vec<String>,
657 pub connected: bool,
660 pub login: LoginState,
664 pub status_note: Option<String>,
667 pub login_brief: Option<String>,
674 pub chain_note: Option<String>,
682}
683
684impl AccountRow {
685 pub fn derive(form: &CtpForm) -> Result<Self, String> {
690 let broker = form.broker_id.trim();
691 let account = form.td_user.trim();
692 let gateway = ek_ctp::derived_gateway_name(broker, account).ok_or_else(|| {
693 "账户: broker/账号 不能为空且只能含字母数字(且派生名 ≤32)".to_string()
694 })?;
695 Ok(Self {
696 gateway,
697 alias: String::new(),
698 broker_id: broker.to_string(),
699 account: account.to_string(),
700 md_source: false,
701 form: form.clone(),
702 stage: AccountStage::NotAssembled,
703 fail_note: None,
704 effective_classes: Vec::new(),
705 connected: false,
706 login: LoginState::Unknown,
707 status_note: None,
708 login_brief: None,
709 chain_note: None,
710 })
711 }
712
713 #[must_use]
719 pub fn status_label(&self) -> String {
720 if self.stage == AccountStage::Assembled {
721 match self.login {
722 LoginState::Unknown => "已装配·登录态未知".to_string(),
723 other => format!("已装配·{}", other.label()),
724 }
725 } else {
726 self.stage.label().to_string()
727 }
728 }
729
730 pub fn apply_status(
743 &mut self,
744 st: &ek_ctp::plugin::GatewayStatus,
745 now_ms: i64,
746 reject_limit: u32,
747 stale_secs: i64,
748 ) {
749 let td_side = !self.form.td_addr.trim().is_empty();
750 let (login, note) = if td_side {
751 if st.td_login_failed && !st.td_logged_in {
752 (
753 LoginState::LoginFailed,
754 st.td_last_error
755 .clone()
756 .or_else(|| Some("登录失败(网关未回带原因)".to_string())),
757 )
758 } else if st.td_logged_in {
759 if st.td_query_reject_streak >= reject_limit {
760 (
761 LoginState::QueryStarved,
762 Some(format!("查询连续被拒 {} 次", st.td_query_reject_streak)),
763 )
764 } else if let Some(last) = st.td_last_account_ms {
765 let idle_ms = now_ms.saturating_sub(last);
766 if idle_ms > stale_secs.saturating_mul(1_000) {
767 (
768 LoginState::QueryStarved,
769 Some(format!("资金回报已 {}s 未更新", idle_ms / 1_000)),
770 )
771 } else {
772 (LoginState::Online, count_note("掉线", st.td_disconnects))
773 }
774 } else {
775 let since_login_ms = st.td_last_login_ok_ms.map(|ok| now_ms.saturating_sub(ok));
782 match since_login_ms {
783 Some(ms) if ms > stale_secs.saturating_mul(1_000) => (
784 LoginState::QueryStarved,
785 Some(format!("资金回报从未到手(登录已 {}s)", ms / 1_000)),
786 ),
787 _ => (LoginState::Online, Some("资金回报尚未到手".to_string())),
788 }
789 }
790 } else if self.login == LoginState::Stopped {
791 let extra = if st.td_disconnects > 0 {
792 format!("(此前掉线 {} 次)", st.td_disconnects)
793 } else {
794 String::new()
795 };
796 (
797 LoginState::Stopped,
798 Some(format!("会话已停{extra};『连接』可恢复")),
799 )
800 } else if st.td_disconnects > 0 {
801 (
802 LoginState::FrontDown,
803 Some(format!("掉线 {} 次", st.td_disconnects)),
804 )
805 } else {
806 (LoginState::Unknown, st.td_last_error.clone())
807 }
808 } else if st.md_logged_in {
809 (
810 LoginState::Online,
811 count_note("掉线", st.md_disconnects)
812 .or_else(|| Some("纯行情账户(无 TD 会话)".to_string())),
813 )
814 } else if self.login == LoginState::Stopped {
815 (
816 LoginState::Stopped,
817 Some("会话已停;『连接』可恢复".to_string()),
818 )
819 } else if st.md_disconnects > 0 {
820 (
821 LoginState::FrontDown,
822 Some(format!("掉线 {} 次", st.md_disconnects)),
823 )
824 } else {
825 (LoginState::Unknown, st.md_last_error.clone())
826 };
827 let note = if td_side && st.td_instrument_rejects > 0 {
832 let add = format!("合约查询被拒 {} 次", st.td_instrument_rejects);
833 match note {
834 Some(base) if base.contains("合约查询被拒") => Some(base),
836 Some(base) => Some(format!("{base};{add}")),
837 None => Some(add),
838 }
839 } else {
840 note
841 };
842 self.login = login;
843 self.status_note = note;
844 self.login_brief = if login.is_alarm() {
847 st.td_last_error
848 .as_deref()
849 .or(st.md_last_error.as_deref())
850 .and_then(brief_counter_reason)
851 } else {
852 None
853 };
854 }
855
856 #[must_use]
858 pub fn display_name(&self) -> String {
859 let a = self.alias.trim();
860 if a.is_empty() {
861 self.account.clone()
862 } else {
863 a.to_string()
864 }
865 }
866}
867
868#[derive(Debug, Clone, PartialEq, Default)]
871pub struct TradeSnap {
872 pub orders: Vec<ek_data::order::OrderData>,
873 pub trades: Vec<ek_data::trade::TradeData>,
874 pub positions: Vec<ek_data::position::PositionData>,
875 pub accounts: Vec<ek_data::account::AccountData>,
877}
878
879pub fn parse_reload_csv(form: &ReloadForm) -> Result<(i64, String, Vec<BarData>), String> {
882 let interval: i64 = form
883 .interval
884 .trim()
885 .parse()
886 .map_err(|_| format!("回灌 解析: interval 非整数:{:?}", form.interval))?;
887 let symbol = form.symbol.trim().to_string();
888 if symbol.is_empty() {
889 return Err("回灌解析: symbol 空".to_string());
890 }
891 if form.csv.trim().is_empty() {
892 return Err("回灌解析: csv 空".to_string());
893 }
894 let mut bars = Vec::new();
895 for (i, raw) in form.csv.lines().enumerate() {
896 let line = raw.trim();
897 if line.is_empty() || line.starts_with('#') {
898 continue;
899 }
900 let parts: Vec<&str> = line.split(',').map(str::trim).collect();
901 if parts.len() != 6 {
902 return Err(format!("回灌解析: 第 {} 列数 ≠ 6", i + 1));
903 }
904 let num = |s: &str| -> Result<f64, String> {
905 s.parse::<f64>()
906 .map_err(|_| format!("回灌解析: 第 {} 列数值坏:{:?}", i + 1, s))
907 };
908 let dt_s: i64 = parts[0]
909 .parse()
910 .map_err(|_| format!("回灌解析: 第 {} 列 dt 坏:{:?}", i + 1, parts[0]))?;
911 bars.push(BarData {
912 symbol: symbol.clone(),
913 datetime: dt_s * 1_000_000_000,
914 interval: Some(
915 ek_dm::wire::interval_of_seconds(interval)
916 .unwrap_or(ek_data::constant::Interval::MINUTE),
917 ),
918 open_price: num(parts[1])?,
919 high_price: num(parts[2])?,
920 low_price: num(parts[3])?,
921 close_price: num(parts[4])?,
922 volume: num(parts[5])?,
923 ..BarData::default()
924 });
925 }
926 if bars.is_empty() {
927 return Err("回灌解析: 无有效行".to_string());
928 }
929 Ok((interval, symbol, bars))
930}
931
932#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
937pub enum TopLeftTab {
938 #[default]
939 Orders,
940 Active,
941}
942
943impl TopLeftTab {
944 pub fn label(self) -> &'static str {
945 match self {
946 Self::Orders => "委托",
947 Self::Active => "未成交",
948 }
949 }
950}
951
952#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
954pub enum BottomRightTab {
955 #[default]
956 Account,
957 Logs,
958}
959
960impl BottomRightTab {
961 pub fn label(self) -> &'static str {
962 match self {
963 Self::Account => "资金",
964 Self::Logs => "日志",
965 }
966 }
967}
968
969#[derive(Debug, Clone, Copy, PartialEq)]
972pub struct DataSplit {
973 pub col: f32,
975 pub row: f32,
977}
978
979impl Default for DataSplit {
980 fn default() -> Self {
981 Self {
982 col: crate::splitters::DATA_SPLIT_DEFAULT,
983 row: crate::splitters::DATA_SPLIT_DEFAULT,
984 }
985 }
986}
987
988pub const MARKET_ORDER: [ek_data::constant::Exchange; 6] = [
991 ek_data::constant::Exchange::SHFE,
992 ek_data::constant::Exchange::DCE,
993 ek_data::constant::Exchange::CZCE,
994 ek_data::constant::Exchange::CFFEX,
995 ek_data::constant::Exchange::INE,
996 ek_data::constant::Exchange::GFEX,
997];
998
999#[derive(Debug, Default)]
1009pub struct TickStore {
1010 ticks: BTreeMap<String, ek_data::tick::TickData>,
1011}
1012
1013impl TickStore {
1014 pub fn put(&mut self, t: &ek_data::tick::TickData) {
1017 self.ticks
1018 .insert(format!("{}.{}", t.exchange.as_str(), t.symbol), t.clone());
1019 }
1020
1021 pub fn rows(&self) -> Vec<ek_data::tick::TickData> {
1023 let mut v: Vec<ek_data::tick::TickData> = self.ticks.values().cloned().collect();
1024 v.sort_by(|a, b| {
1025 (a.exchange.as_str().to_string(), a.symbol.clone())
1026 .cmp(&(b.exchange.as_str().to_string(), b.symbol.clone()))
1027 });
1028 v
1029 }
1030
1031 pub fn groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
1033 let mut out: Vec<(String, Vec<ek_data::tick::TickData>)> = Vec::new();
1034 for t in self.rows() {
1035 let ex = t.exchange.as_str().to_string();
1036 match out.last_mut() {
1037 Some((e, v)) if *e == ex => v.push(t),
1038 _ => out.push((ex, vec![t])),
1039 }
1040 }
1041 out
1042 }
1043
1044 pub fn len(&self) -> usize {
1045 self.ticks.len()
1046 }
1047
1048 pub fn is_empty(&self) -> bool {
1049 self.ticks.is_empty()
1050 }
1051}
1052
1053#[derive(Debug, Clone, PartialEq)]
1055pub struct OrderForm {
1056 pub exchange: String,
1058 pub symbol: String,
1060 pub direction: ek_data::constant::Direction,
1061 pub offset: ek_data::constant::Offset,
1062 pub order_type: ek_data::constant::OrderType,
1063 pub price: String,
1065 pub volume: String,
1066 pub gateway: String,
1068 pub follow_price: bool,
1070 pub auto_split: bool,
1073}
1074
1075impl Default for OrderForm {
1076 fn default() -> Self {
1077 Self {
1078 exchange: "SHFE".to_string(),
1079 symbol: String::new(),
1080 direction: ek_data::constant::Direction::LONG,
1081 offset: ek_data::constant::Offset::OPEN,
1082 order_type: ek_data::constant::OrderType::LIMIT,
1083 price: String::new(),
1084 volume: "1".to_string(),
1085 gateway: String::new(),
1086 follow_price: true,
1087 auto_split: true,
1088 }
1089 }
1090}
1091
1092impl OrderForm {
1093 pub fn to_request(&self) -> Result<ek_data::order_request::OrderRequest, String> {
1095 use std::str::FromStr;
1096 let symbol = self.symbol.trim();
1097 if symbol.is_empty() {
1098 return Err("下单: 代码为空".to_string());
1099 }
1100 if symbol.contains('.') {
1101 return Err("下单: 代码不带交易所前缀(交易所走下拉)".to_string());
1102 }
1103 let exchange = ek_data::constant::Exchange::from_str(self.exchange.trim())
1104 .map_err(|e| format!("下单: {e}"))?;
1105 let price: f64 = self
1106 .price
1107 .trim()
1108 .parse()
1109 .map_err(|_| format!("下单: 价格无效 {:?}", self.price))?;
1110 let volume: f64 = self
1111 .volume
1112 .trim()
1113 .parse()
1114 .map_err(|_| format!("下单: 数量无效 {:?}", self.volume))?;
1115 if self.order_type != ek_data::constant::OrderType::MARKET && price <= 0.0 {
1116 return Err("下单: 限价单价格须为正".to_string());
1117 }
1118 if volume <= 0.0 {
1119 return Err("下单: 数量须为正".to_string());
1120 }
1121 Ok(ek_data::order_request::OrderRequest {
1122 symbol: symbol.to_string(),
1123 exchange,
1124 direction: self.direction,
1125 order_type: self.order_type,
1126 volume,
1127 price,
1128 offset: self.offset,
1129 ..ek_data::order_request::OrderRequest::default()
1130 })
1131 }
1132}
1133
1134#[derive(Debug, Default)]
1140pub struct ContractStore {
1141 contracts: BTreeMap<String, ek_data::contract::ContractData>,
1142}
1143
1144impl ContractStore {
1145 pub fn put(&mut self, c: &ek_data::contract::ContractData) {
1146 self.contracts
1147 .insert(format!("{}.{}", c.exchange.as_str(), c.symbol), c.clone());
1148 }
1149
1150 pub fn query(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
1152 let p = pattern.trim();
1153 self.contracts
1154 .values()
1155 .filter(|c| {
1156 p.is_empty()
1157 || c.symbol.contains(p)
1158 || c.exchange.as_str().eq_ignore_ascii_case(p)
1159 || c.name.contains(p)
1160 })
1161 .cloned()
1162 .collect()
1163 }
1164
1165 pub fn len(&self) -> usize {
1166 self.contracts.len()
1167 }
1168
1169 pub fn is_empty(&self) -> bool {
1170 self.contracts.is_empty()
1171 }
1172}
1173
1174#[derive(Debug, Default)]
1176pub struct UiShared {
1177 logs: Mutex<LogRing>,
1178 snap: Mutex<Arc<BusSnap>>,
1179 market: MarketStore,
1180 ctp_form: Mutex<CtpForm>,
1181 trade_orders: Mutex<BTreeMap<String, (u64, ek_data::order::OrderData)>>,
1184 trade_trades: Mutex<VecDeque<(u64, ek_data::trade::TradeData)>>,
1185 trade_ids: Mutex<HashSet<String>>,
1193 trade_positions: Mutex<BTreeMap<String, (u64, ek_data::position::PositionData)>>,
1194 trade_funds: Mutex<BTreeMap<String, (u64, ek_data::account::AccountData)>>,
1195 trade_seq: AtomicU64,
1197 trade_dropped: AtomicU64,
1199 trade_dirty: AtomicBool,
1201 trade_snap: Mutex<Arc<TradeSnap>>,
1203 tick_store: Mutex<TickStore>,
1204 order_form: Mutex<OrderForm>,
1205 data_split: Mutex<DataSplit>,
1208 selected_exchange: Mutex<String>,
1210 topleft_tab: Mutex<TopLeftTab>,
1212 bottomright_tab: Mutex<BottomRightTab>,
1214 ops_window: AtomicBool,
1215 accounts_window: AtomicBool,
1218 contracts_window: AtomicBool,
1219 contract_store: Mutex<ContractStore>,
1220 contract_query: Mutex<String>,
1221 contract_selected: Mutex<Vec<String>>,
1222 kline_windows: Mutex<Vec<String>>,
1223 rev: AtomicU64,
1224 stop: AtomicBool,
1226 cmds: Mutex<VecDeque<UiCmd>>,
1228 pending_confirm: Mutex<Option<String>>,
1230 accounts: Mutex<Vec<AccountRow>>,
1232 account_edit_window: AtomicBool,
1234 editing_account: Mutex<Option<String>>,
1236 edit_alias: Mutex<String>,
1238 edit_error: Mutex<Option<String>>,
1240 md_source: Mutex<String>,
1242 subscriptions: Mutex<Vec<String>>,
1244 row_sel: Mutex<BTreeMap<String, String>>,
1247 table_sorts: Mutex<BTreeMap<String, Option<(usize, bool)>>>,
1251 status_cursor: AtomicUsize,
1257 status_seed: Mutex<Vec<String>>,
1260 list_tick: AtomicU32,
1262 list_due: AtomicBool,
1266 seed_due: AtomicBool,
1270 pipeline_due: AtomicBool,
1272 cfg_due: AtomicBool,
1274 cfg_briefs: Mutex<Option<Vec<ek_cfg::wire::NsBrief>>>,
1277 cfg_delete_arm: Mutex<Option<String>>,
1279 bad_payload: Mutex<BTreeMap<String, u64>>,
1281 pipeline_lines: Mutex<Vec<String>>,
1284 status_thresholds: Mutex<Option<(u32, i64)>>,
1287 pending_alerts: Mutex<Vec<(crate::toast::AlertLevel, String)>>,
1289 toasts: crate::toast::ToastsCell,
1292 alerted: Mutex<std::collections::BTreeSet<String>>,
1294 exit_confirm_open: AtomicBool,
1296 exit_confirmed: AtomicBool,
1298}
1299
1300impl UiShared {
1301 pub fn new() -> Self {
1303 Self::default()
1304 }
1305
1306 pub fn update_tick(&self, t: &ek_data::tick::TickData) {
1310 self.tick_store.lock().unwrap().put(t);
1311 self.bump();
1312 }
1313
1314 pub fn tick_rows(&self) -> Vec<ek_data::tick::TickData> {
1316 self.tick_store.lock().unwrap().rows()
1317 }
1318
1319 pub fn tick_groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
1321 self.tick_store.lock().unwrap().groups()
1322 }
1323
1324 pub fn tick_count(&self) -> usize {
1326 self.tick_store.lock().unwrap().len()
1327 }
1328
1329 pub fn order_form(&self) -> OrderForm {
1331 self.order_form.lock().unwrap().clone()
1332 }
1333
1334 pub fn set_order_form(&self, f: OrderForm) {
1336 *self.order_form.lock().unwrap() = f;
1337 self.bump();
1338 }
1339
1340 pub fn selected_exchange(&self) -> String {
1344 let s = self.selected_exchange.lock().unwrap().clone();
1345 if MARKET_ORDER.iter().any(|e| e.as_str() == s) {
1346 s
1347 } else {
1348 MARKET_ORDER[0].as_str().to_string()
1349 }
1350 }
1351
1352 pub fn set_selected_exchange(&self, s: impl Into<String>) {
1354 *self.selected_exchange.lock().unwrap() = s.into();
1355 self.bump();
1356 }
1357
1358 pub fn topleft_tab(&self) -> TopLeftTab {
1360 *self.topleft_tab.lock().unwrap()
1361 }
1362
1363 pub fn set_topleft_tab(&self, t: TopLeftTab) {
1365 *self.topleft_tab.lock().unwrap() = t;
1366 self.bump();
1367 }
1368
1369 pub fn bottomright_tab(&self) -> BottomRightTab {
1371 *self.bottomright_tab.lock().unwrap()
1372 }
1373
1374 pub fn set_bottomright_tab(&self, t: BottomRightTab) {
1376 *self.bottomright_tab.lock().unwrap() = t;
1377 self.bump();
1378 }
1379
1380 pub fn data_split(&self) -> DataSplit {
1382 *self.data_split.lock().unwrap()
1383 }
1384
1385 pub fn set_data_split(&self, s: DataSplit) {
1388 let s = DataSplit {
1389 col: crate::splitters::clamp_frac(s.col),
1390 row: crate::splitters::clamp_frac(s.row),
1391 };
1392 let mut g = self.data_split.lock().unwrap();
1393 if g.col != s.col || g.row != s.row {
1394 *g = s;
1395 self.bump();
1396 }
1397 }
1398
1399 pub fn reset_layout(&self) {
1403 *self.data_split.lock().unwrap() = DataSplit::default();
1404 *self.selected_exchange.lock().unwrap() = String::new();
1405 *self.topleft_tab.lock().unwrap() = TopLeftTab::default();
1406 *self.bottomright_tab.lock().unwrap() = BottomRightTab::default();
1407 self.bump();
1408 }
1409
1410 pub fn ops_window_open(&self) -> bool {
1414 self.ops_window.load(Ordering::Acquire)
1415 }
1416
1417 pub fn table_sort(&self, table: &str) -> Option<(usize, bool)> {
1420 self.table_sorts
1421 .lock()
1422 .unwrap()
1423 .get(table)
1424 .copied()
1425 .flatten()
1426 }
1427
1428 pub fn toggle_table_sort(&self, table: &str, col: usize) {
1430 let mut m = self.table_sorts.lock().unwrap();
1431 let asc = match m.get(table).copied().flatten() {
1432 Some((c, a)) if c == col => !a,
1433 _ => true,
1434 };
1435 m.insert(table.to_string(), Some((col, asc)));
1436 }
1437
1438 pub fn set_ops_window_open(&self, v: bool) {
1439 self.ops_window.store(v, Ordering::Release);
1440 self.bump();
1441 }
1442
1443 pub fn accounts_window_open(&self) -> bool {
1447 self.accounts_window.load(Ordering::Acquire)
1448 }
1449
1450 pub fn set_accounts_window_open(&self, v: bool) {
1452 self.accounts_window.store(v, Ordering::Release);
1453 self.bump();
1454 }
1455
1456 pub fn account_edit_open(&self) -> bool {
1458 self.account_edit_window.load(Ordering::Acquire)
1459 }
1460
1461 pub fn editing_account(&self) -> Option<String> {
1463 self.editing_account.lock().unwrap().clone()
1464 }
1465
1466 pub fn begin_account_edit(&self, gateway: Option<&str>) -> bool {
1470 match gateway {
1471 Some(gw) => {
1472 let Some(row) = self.account(gw) else {
1473 return false;
1474 };
1475 *self.editing_account.lock().unwrap() = Some(gw.to_string());
1476 *self.edit_alias.lock().unwrap() = row.alias.clone();
1477 self.set_ctp_form(row.form.clone());
1478 }
1479 None => {
1480 *self.editing_account.lock().unwrap() = None;
1481 *self.edit_alias.lock().unwrap() = String::new();
1482 let draft = self.draft_from_existing();
1483 self.set_ctp_form(draft);
1484 }
1485 }
1486 *self.edit_error.lock().unwrap() = None;
1487 self.account_edit_window.store(true, Ordering::Release);
1488 self.bump();
1489 true
1490 }
1491
1492 pub fn end_account_edit(&self) {
1494 *self.editing_account.lock().unwrap() = None;
1495 *self.edit_alias.lock().unwrap() = String::new();
1496 *self.edit_error.lock().unwrap() = None;
1497 self.account_edit_window.store(false, Ordering::Release);
1498 let draft = self.draft_from_existing();
1499 self.set_ctp_form(draft);
1500 self.bump();
1501 }
1502
1503 pub fn end_account_edit_if_editing(&self, gateway: &str) {
1509 if self.editing_account().as_deref() == Some(gateway) {
1510 self.end_account_edit();
1511 }
1512 }
1513
1514 pub fn edit_alias(&self) -> String {
1516 self.edit_alias.lock().unwrap().clone()
1517 }
1518
1519 pub fn set_edit_alias(&self, v: impl Into<String>) {
1521 *self.edit_alias.lock().unwrap() = v.into();
1522 self.bump();
1523 }
1524
1525 pub fn edit_error(&self) -> Option<String> {
1527 self.edit_error.lock().unwrap().clone()
1528 }
1529
1530 pub fn set_edit_error(&self, e: Option<String>) {
1532 *self.edit_error.lock().unwrap() = e;
1533 self.bump();
1534 }
1535
1536 pub fn account_edit_dirty(&self) -> bool {
1538 let editing = self.editing_account();
1539 let draft = self.ctp_form();
1540 match editing {
1541 Some(gw) => self.account(&gw).map(|a| a.form != draft).unwrap_or(false),
1542 None => draft != CtpForm::default() && !draft.td_user.trim().is_empty(),
1543 }
1544 }
1545
1546 pub fn accounts(&self) -> Vec<AccountRow> {
1548 self.accounts.lock().unwrap().clone()
1549 }
1550
1551 pub fn account(&self, gateway: &str) -> Option<AccountRow> {
1553 self.accounts
1554 .lock()
1555 .unwrap()
1556 .iter()
1557 .find(|a| a.gateway == gateway)
1558 .cloned()
1559 }
1560
1561 pub fn add_account(&self, row: AccountRow) -> Result<(), String> {
1567 let mut acc = self.accounts.lock().unwrap();
1568 if acc.iter().any(|a| a.gateway == row.gateway) {
1569 return Err(format!("账户 {} 已存在(同 broker + 账号)", row.gateway));
1570 }
1571 let alias = row.alias.trim();
1572 if !alias.is_empty()
1573 && acc
1574 .iter()
1575 .any(|a| a.alias.trim().eq_ignore_ascii_case(alias))
1576 {
1577 return Err(format!("别名 {alias:?} 已被其他账户占用(别名须唯一)"));
1578 }
1579 if acc.len() >= MAX_ACCOUNTS {
1580 return Err(format!(
1581 "账户已达软上限 {MAX_ACCOUNTS} 个(先移除一个再添加)"
1582 ));
1583 }
1584 acc.push(row);
1585 drop(acc);
1586 self.bump();
1587 Ok(())
1588 }
1589
1590 #[must_use]
1592 pub fn can_add_account(&self) -> bool {
1593 self.accounts.lock().unwrap().len() < MAX_ACCOUNTS
1594 }
1595
1596 pub fn set_account_alias(&self, gateway: &str, alias: &str) -> bool {
1602 let alias = alias.trim().to_string();
1603 let mut acc = self.accounts.lock().unwrap();
1604 if !alias.is_empty()
1605 && acc
1606 .iter()
1607 .any(|a| a.gateway != gateway && a.alias.eq_ignore_ascii_case(&alias))
1608 {
1609 return false;
1610 }
1611 match acc.iter_mut().find(|a| a.gateway == gateway) {
1612 Some(a) => {
1613 a.alias = alias;
1614 drop(acc);
1615 self.bump();
1616 true
1617 }
1618 None => false,
1619 }
1620 }
1621
1622 pub fn note_connect_sent(&self, gateway: &str) {
1627 let mut acc = self.accounts.lock().unwrap();
1628 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1629 a.stage = AccountStage::Assembling;
1630 a.fail_note = None;
1631 a.login = LoginState::Unknown;
1632 a.status_note = None;
1633 a.login_brief = None;
1634 a.chain_note = None;
1636 drop(acc);
1637 self.bump();
1638 }
1639 }
1640
1641 pub fn note_connect_result(&self, gateway: &str, result: Result<(), String>) {
1645 let mut acc = self.accounts.lock().unwrap();
1646 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1647 match result {
1648 Ok(()) => {
1649 a.stage = AccountStage::Assembled;
1650 a.fail_note = None;
1651 }
1652 Err(e) => {
1653 a.stage = AccountStage::AssembleFailed;
1654 a.fail_note = Some(e);
1655 }
1656 }
1657 drop(acc);
1658 self.bump();
1659 }
1660 }
1661
1662 pub fn note_effective_product_classes(&self, gateway: &str, classes: &[String]) {
1666 let mut acc = self.accounts.lock().unwrap();
1667 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1668 a.effective_classes = classes.to_vec();
1669 drop(acc);
1670 self.bump();
1671 }
1672 }
1673
1674 pub fn note_chain(&self, gateway: &str, note: &str) {
1679 let mut acc = self.accounts.lock().unwrap();
1680 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1681 if a.chain_note.as_deref() == Some(note) {
1682 return; }
1684 a.chain_note = Some(note.to_string());
1685 drop(acc);
1686 self.bump();
1687 }
1688 }
1689
1690 #[must_use]
1694 pub fn status_thresholds(&self) -> (u32, i64) {
1695 self.status_thresholds
1696 .lock()
1697 .unwrap()
1698 .unwrap_or((QUERY_REJECT_STREAK_LIMIT, ACCOUNT_STALE_SECS))
1699 }
1700
1701 pub fn set_status_thresholds(&self, reject_limit: u32, stale_secs: i64) {
1703 *self.status_thresholds.lock().unwrap() = Some((reject_limit, stale_secs));
1704 self.bump();
1705 }
1706
1707 pub fn list_poll_due(&self) -> bool {
1712 let n = self.list_tick.fetch_add(1, Ordering::Relaxed) + 1;
1713 self.list_due.swap(false, Ordering::AcqRel) || n == 1 || n.is_multiple_of(LIST_POLL_TICKS)
1714 }
1715
1716 pub fn request_list_refresh(&self) {
1718 self.list_due.store(true, Ordering::Release);
1719 }
1720
1721 pub fn request_trade_reseed(&self) {
1723 self.seed_due.store(true, Ordering::Release);
1724 }
1725
1726 pub fn take_trade_reseed(&self) -> bool {
1728 self.seed_due.swap(false, Ordering::AcqRel)
1729 }
1730
1731 pub fn status_batch(&self, present: &[String]) -> Vec<String> {
1736 let mut uniq: Vec<String> = Vec::with_capacity(present.len());
1740 for gw in present {
1741 if !uniq.iter().any(|u| u == gw) {
1742 uniq.push(gw.clone());
1743 }
1744 }
1745 let n = uniq.len();
1746 if n == 0 {
1747 return Vec::new();
1748 }
1749 let start = self.status_cursor.fetch_add(1, Ordering::Relaxed) % n;
1750 let take = STATUS_ASKS_PER_TICK.min(n);
1751 let mut out = Vec::with_capacity(take);
1752 for i in 0..take {
1753 out.push(uniq[(start + i) % n].clone());
1754 }
1755 out
1756 }
1757
1758 pub fn request_status_seed(&self, gateway: &str) {
1760 let mut q = self.status_seed.lock().unwrap();
1761 if !q.iter().any(|g| g == gateway) {
1762 q.push(gateway.to_string());
1763 }
1764 }
1765
1766 pub fn take_status_seeds(&self) -> Vec<String> {
1768 let mut q = self.status_seed.lock().unwrap();
1769 std::mem::take(&mut *q)
1770 }
1771
1772 pub fn note_status_event(&self, ev: &ek_ctp::GatewayStatusEvent) {
1782 let gw = ev.gateway.as_str();
1783 let text = ev.describe();
1784 self.log_line(format!("[INFO][{gw}] {text}"));
1785 let note = text
1786 .strip_prefix(CHAIN_STATE_PREFIX)
1787 .map(|s| s.trim().to_string())
1788 .unwrap_or_else(|| text.clone());
1789 self.note_chain(gw, ¬e);
1790 self.note_gateway_status(gw, &ev.status);
1791 let alarm_kind = matches!(
1792 ev.change,
1793 ek_ctp::GatewayChange::TdDisconnected
1794 | ek_ctp::GatewayChange::TdAuthFailed
1795 | ek_ctp::GatewayChange::TdLoginFailed
1796 | ek_ctp::GatewayChange::ContractQueryStopped
1797 | ek_ctp::GatewayChange::QueryRejected
1798 | ek_ctp::GatewayChange::MdDisconnected
1799 | ek_ctp::GatewayChange::MdLoginFailed
1800 | ek_ctp::GatewayChange::SubscribeRejected
1801 );
1802 if alarm_kind {
1803 let session = if ev.change.kind().starts_with("md-") {
1805 ev.status.md_disconnects
1806 } else {
1807 ev.status.td_disconnects
1808 };
1809 let key = format!("estatus:{gw}:{}:{session}", ev.change.kind());
1810 if self.alert_once(key) {
1811 self.push_alert(
1812 crate::toast::AlertLevel::Warning,
1813 format!("账户 {gw}:{}", note.trim()),
1814 );
1815 }
1816 }
1817 }
1818
1819 pub fn request_pipeline_refresh(&self) {
1821 self.pipeline_due.store(true, Ordering::Release);
1822 }
1823 pub fn take_pipeline_due(&self) -> bool {
1825 self.pipeline_due.swap(false, Ordering::AcqRel)
1826 }
1827
1828 pub fn request_cfg_refresh(&self) {
1830 self.cfg_due.store(true, Ordering::Release);
1831 }
1832 pub fn take_cfg_due(&self) -> bool {
1834 self.cfg_due.swap(false, Ordering::AcqRel)
1835 }
1836 pub fn set_cfg_briefs(&self, b: Vec<ek_cfg::wire::NsBrief>) {
1838 *self.cfg_briefs.lock().unwrap() = Some(b);
1839 self.bump();
1840 }
1841 pub fn cfg_briefs(&self) -> Option<Vec<ek_cfg::wire::NsBrief>> {
1843 self.cfg_briefs.lock().unwrap().clone()
1844 }
1845
1846 pub fn cfg_delete_armed(&self) -> Option<String> {
1848 self.cfg_delete_arm.lock().unwrap().clone()
1849 }
1850 pub fn arm_cfg_delete(&self, ns: Option<String>) {
1851 *self.cfg_delete_arm.lock().unwrap() = ns;
1852 self.bump();
1853 }
1854
1855 pub fn set_pipeline_lines(&self, lines: Vec<String>) {
1857 *self.pipeline_lines.lock().unwrap() = lines;
1858 self.bump();
1859 }
1860
1861 pub fn pipeline_lines(&self) -> Vec<String> {
1863 self.pipeline_lines.lock().unwrap().clone()
1864 }
1865
1866 pub fn note_bad_payload(&self, line: &str) {
1872 let mut book = self.bad_payload.lock().unwrap();
1873 let n = book.entry(line.to_string()).or_insert(0);
1874 *n += 1;
1875 if *n == 1 {
1876 self.log_line(format!(
1877 "[ui] {line} 载荷类型异常(第一次):这一路的行进不了账本"
1878 ));
1879 }
1880 }
1881
1882 #[must_use]
1884 pub fn bad_payload_count(&self, line: &str) -> u64 {
1885 self.bad_payload
1886 .lock()
1887 .unwrap()
1888 .get(line)
1889 .copied()
1890 .unwrap_or(0)
1891 }
1892
1893 pub fn note_plugin_spill(&self, rows: &[ek_station::wire::PlugRow]) {
1907 for r in rows {
1908 let (warn, crit) = pending_thresholds(r.soft_cap);
1909 if r.pending >= warn && self.alert_once(format!("pend-warn:{}", r.name)) {
1910 self.push_alert(
1911 crate::toast::AlertLevel::Warning,
1912 format!(
1913 "插件 {}:邮箱积压 {} 帧(峰值 {};该插件软顶 {})——它的 worker 消化不过来,刷新会变慢",
1914 r.name, r.pending, r.peak, r.soft_cap
1915 ),
1916 );
1917 }
1918 if r.pending >= crit && self.alert_once(format!("pend-crit:{}", r.name)) {
1919 self.push_alert(
1920 crate::toast::AlertLevel::Error,
1921 format!(
1922 "插件 {}:邮箱积压 {} 帧,越过软顶 {} 的四分之一——再涨就开始丢新到的事件",
1923 r.name, r.pending, r.soft_cap
1924 ),
1925 );
1926 }
1927 if r.spilled > 0 && self.alert_once(format!("spill:{}", r.name)) {
1928 self.push_alert(
1929 crate::toast::AlertLevel::Error,
1930 format!(
1931 "插件 {}:已触软顶 {} 并丢弃新到事件累计 {} 条(峰值 {})——它的消化速度跟不上生产速度",
1932 r.name, r.soft_cap, r.spilled, r.peak
1933 ),
1934 );
1935 }
1936 }
1937 }
1938
1939 pub fn note_gateway_status(&self, gateway: &str, st: &ek_ctp::plugin::GatewayStatus) {
1947 let (limit, stale) = self.status_thresholds();
1948 let now = ek_ctp::map::now_epoch_ms();
1949 let mut alarm: Option<(LoginState, String)> = None;
1952 let mut found = false;
1953 {
1954 let mut acc = self.accounts.lock().unwrap();
1955 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1956 found = true;
1957 a.apply_status(st, now, limit, stale);
1958 if a.login.is_alarm() || a.login == LoginState::QueryStarved {
1959 alarm = Some((
1960 a.login,
1961 a.status_note
1962 .clone()
1963 .unwrap_or_else(|| a.login.label().to_string()),
1964 ));
1965 }
1966 }
1967 }
1968 if found {
1969 self.bump();
1970 }
1971 if let Some((login, note)) = alarm
1972 && self.alert_once(format!("{gateway}|{}", login.label()))
1973 {
1974 self.push_alert(
1975 crate::toast::AlertLevel::Error,
1976 format!("账户 {gateway}:{note}"),
1977 );
1978 }
1979 }
1980
1981 pub fn note_status_unreachable(&self, gateway: &str, why: &str) {
1985 let mut acc = self.accounts.lock().unwrap();
1986 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1987 a.login = LoginState::Unknown;
1988 a.status_note = Some(format!("状态口问不到:{why}"));
1989 a.login_brief = None;
1990 drop(acc);
1991 self.bump();
1992 }
1993 }
1994
1995 pub fn mark_account_stopped(&self, gateway: &str) {
1997 let mut acc = self.accounts.lock().unwrap();
1998 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1999 a.login = LoginState::Stopped;
2000 a.status_note = Some("会话已停;『连接』可恢复".to_string());
2001 a.login_brief = None;
2002 drop(acc);
2003 self.bump();
2004 }
2005 }
2006
2007 pub fn prepare_connect_form(&self, gateway: &str, form: CtpForm) -> CtpForm {
2010 let source = self.md_source();
2011 let mut f = form;
2012 if source.as_str() != gateway {
2013 f.md_addr.clear();
2014 f.md_user.clear();
2015 f.md_password.clear();
2016 }
2017 self.update_account_form(gateway, f.clone());
2018 f
2019 }
2020
2021 #[must_use]
2025 pub fn draft_from_existing(&self) -> CtpForm {
2026 let acc = self.accounts.lock().unwrap();
2027 let mut draft = CtpForm::default();
2028 if let Some(a) = acc.last() {
2029 draft.broker_id = a.form.broker_id.clone();
2030 draft.td_auth_code = a.form.td_auth_code.clone();
2031 draft.td_app_id = a.form.td_app_id.clone();
2032 draft.accept_futures = a.form.accept_futures;
2033 draft.accept_options = a.form.accept_options;
2034 }
2035 draft
2036 }
2037
2038 pub fn update_account_form(&self, gateway: &str, form: CtpForm) -> bool {
2040 let mut acc = self.accounts.lock().unwrap();
2041 match acc.iter_mut().find(|a| a.gateway == gateway) {
2042 Some(a) => {
2043 a.form = form;
2044 drop(acc);
2045 self.bump();
2046 true
2047 }
2048 None => false,
2049 }
2050 }
2051
2052 pub fn remove_account(&self, gateway: &str) -> bool {
2054 let mut acc = self.accounts.lock().unwrap();
2055 let before = acc.len();
2056 acc.retain(|a| a.gateway != gateway);
2057 let removed = acc.len() != before;
2058 if removed {
2059 let mut md = self.md_source.lock().unwrap();
2061 if md.as_str() == gateway {
2062 md.clear();
2063 }
2064 drop(acc);
2065 self.bump();
2066 }
2067 removed
2068 }
2069
2070 pub fn sync_accounts_connected(&self, rows: &[PlugRow]) -> Vec<String> {
2079 let mut newly = Vec::new();
2080 {
2081 let mut acc = self.accounts.lock().unwrap();
2082 for a in acc.iter_mut() {
2083 let up = rows.iter().any(|r| r.name == a.gateway);
2084 if up && !a.connected {
2085 newly.push(a.gateway.clone());
2086 }
2087 a.connected = up;
2088 if up {
2089 a.stage = AccountStage::Assembled;
2090 a.fail_note = None;
2091 } else {
2092 a.chain_note = None;
2095 if a.stage == AccountStage::Assembled {
2096 a.stage = AccountStage::NotAssembled;
2097 a.login = LoginState::Unknown;
2098 a.status_note = None;
2099 a.login_brief = None;
2100 }
2101 }
2102 }
2103 }
2104 if !newly.is_empty() {
2105 self.bump();
2106 }
2107 newly
2108 }
2109
2110 pub fn md_source(&self) -> String {
2112 self.md_source.lock().unwrap().clone()
2113 }
2114
2115 pub fn accounts_locked(&self) -> bool {
2117 self.accounts.lock().unwrap().iter().any(|a| a.connected)
2118 }
2119
2120 pub fn set_md_source(&self, gateway: &str) -> Result<(), String> {
2122 {
2123 let acc = self.accounts.lock().unwrap();
2124 if acc.iter().any(|a| a.connected) {
2125 return Err("元账号已锁定:有账户在线,切换行情源需先断开该账户".to_string());
2126 }
2127 if !acc.iter().any(|a| a.gateway == gateway) {
2128 return Err(format!("账户 {gateway} 不在清册"));
2129 }
2130 }
2131 let mut acc = self.accounts.lock().unwrap();
2132 for a in acc.iter_mut() {
2133 a.md_source = a.gateway == gateway;
2134 }
2135 drop(acc);
2136 let mut md = self.md_source.lock().unwrap();
2137 *md = gateway.to_string();
2138 self.bump();
2139 Ok(())
2140 }
2141
2142 pub fn subscriptions(&self) -> Vec<String> {
2144 self.subscriptions.lock().unwrap().clone()
2145 }
2146
2147 pub fn note_subscriptions(&self, symbols: &[String]) {
2149 {
2150 let mut subs = self.subscriptions.lock().unwrap();
2151 for s in symbols {
2152 let s = s.trim();
2153 if !s.is_empty() && !subs.iter().any(|x| x == s) {
2154 subs.push(s.to_string());
2155 }
2156 }
2157 }
2158 self.bump();
2159 }
2160
2161 pub fn default_gateway(&self) -> Option<String> {
2168 let chosen = {
2169 let f = self.order_form.lock().unwrap();
2170 f.gateway.trim().to_string()
2171 };
2172 if !chosen.is_empty() && self.account(&chosen).is_some_and(|a| a.connected) {
2173 return Some(chosen);
2174 }
2175 let acc = self.accounts.lock().unwrap();
2176 acc.iter().find(|a| a.connected).map(|a| a.gateway.clone())
2177 }
2178
2179 pub fn kline_symbols(&self) -> Vec<String> {
2181 self.kline_windows.lock().unwrap().clone()
2182 }
2183
2184 pub fn open_kline(&self, symbol: impl Into<String>) {
2186 let s = symbol.into();
2187 let mut v = self.kline_windows.lock().unwrap();
2188 if !v.contains(&s) {
2189 v.push(s.clone());
2190 }
2191 drop(v);
2192 self.log_line(format!("[kline] 打开 K线窗 {s}"));
2193 }
2194
2195 pub fn close_kline(&self, symbol: &str) {
2197 self.kline_windows.lock().unwrap().retain(|s| s != symbol);
2198 self.bump();
2199 }
2200
2201 pub fn contracts_window_open(&self) -> bool {
2205 self.contracts_window.load(Ordering::Acquire)
2206 }
2207
2208 pub fn set_contracts_window_open(&self, v: bool) {
2210 self.contracts_window.store(v, Ordering::Release);
2211 self.bump();
2212 }
2213
2214 pub fn update_contract(&self, c: &ek_data::contract::ContractData) {
2221 self.contract_store.lock().unwrap().put(c);
2222 if !c.name.is_empty() {
2223 self.backfill_names(&c.symbol, &c.name);
2224 }
2225 self.bump();
2226 }
2227
2228 fn backfill_names(&self, symbol: &str, name: &str) {
2233 let mut touched = false;
2234 {
2235 let mut rows = self.trade_orders.lock().unwrap();
2236 for (_, (_, o)) in rows.iter_mut() {
2237 if o.symbol == symbol && o.name.is_empty() {
2238 o.name = name.to_string();
2239 touched = true;
2240 }
2241 }
2242 }
2243 {
2244 let mut rows = self.trade_trades.lock().unwrap();
2245 for (_, t) in rows.iter_mut() {
2246 if t.symbol == symbol && t.name.is_empty() {
2247 t.name = name.to_string();
2248 touched = true;
2249 }
2250 }
2251 }
2252 {
2253 let mut rows = self.trade_positions.lock().unwrap();
2254 for (_, (_, p)) in rows.iter_mut() {
2255 if p.symbol == symbol && p.name.is_empty() {
2256 p.name = name.to_string();
2257 touched = true;
2258 }
2259 }
2260 }
2261 if touched {
2262 self.trade_dirty.store(true, Ordering::Release);
2264 }
2265 }
2266
2267 pub fn contracts(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
2269 self.contract_store.lock().unwrap().query(pattern)
2270 }
2271
2272 pub fn contract_count(&self) -> usize {
2274 self.contract_store.lock().unwrap().len()
2275 }
2276
2277 fn contract_name_of(&self, symbol: &str) -> Option<String> {
2279 self.contract_store
2280 .lock()
2281 .unwrap()
2282 .query(symbol)
2283 .into_iter()
2284 .find(|c| c.symbol == symbol && !c.name.is_empty())
2285 .map(|c| c.name)
2286 }
2287
2288 pub fn contract_query(&self) -> String {
2290 self.contract_query.lock().unwrap().clone()
2291 }
2292
2293 pub fn set_contract_query(&self, q: impl Into<String>) {
2295 *self.contract_query.lock().unwrap() = q.into();
2296 self.bump();
2297 }
2298
2299 pub fn toggle_contract_selection(&self, en_symbol: &str) {
2301 let mut v = self.contract_selected.lock().unwrap();
2302 match v.iter().position(|s| s == en_symbol) {
2303 Some(i) => {
2304 v.remove(i);
2305 }
2306 None => v.push(en_symbol.to_string()),
2307 }
2308 self.bump();
2309 }
2310
2311 pub fn selected_contracts(&self) -> Vec<String> {
2313 self.contract_selected.lock().unwrap().clone()
2314 }
2315
2316 #[must_use]
2322 pub fn cancel_reject_note(msg: &str) -> String {
2323 let head = msg.split(' ').next().unwrap_or(msg);
2324 let note = if head.starts_with("unknown:order") {
2325 "这台网关的账本里没有这笔委托(登录前的旧单,或不属于这个账户)"
2326 } else if head.starts_with("mismatch:gateway") {
2327 "该委托不属于这个账户(归属守卫挡住,不会撤到别人头上)"
2328 } else if head.starts_with("terminal:status") {
2329 "这笔委托已经到终态(已成交/已撤/已拒),撤不了了"
2330 } else if head.starts_with("limit:cancel-guard") {
2331 "撤单尝试次数已到上限(每单有上限,防连点打爆柜台)"
2332 } else {
2333 ""
2334 };
2335 if note.is_empty() {
2336 format!("撤单被拒:{msg}")
2338 } else {
2339 format!("撤单被拒:{note}(机器码:{msg})")
2340 }
2341 }
2342
2343 pub fn log_line(&self, line: impl Into<String>) {
2345 self.logs.lock().unwrap().push(line);
2346 self.bump();
2347 }
2348
2349 pub fn clear_logs(&self) {
2351 self.logs.lock().unwrap().clear();
2352 self.bump();
2353 }
2354
2355 pub fn logs_snapshot(&self) -> (Vec<String>, u64) {
2357 let r = self.logs.lock().unwrap();
2358 (r.snapshot(), r.spilled())
2359 }
2360
2361 pub fn logs_entries(&self) -> (Vec<LogEntry>, u64) {
2363 let r = self.logs.lock().unwrap();
2364 (r.entries(), r.spilled())
2365 }
2366
2367 pub fn logs_len(&self) -> usize {
2369 self.logs.lock().unwrap().len()
2370 }
2371
2372 pub fn set_snapshot(&self, snap: BusSnap) {
2374 *self.snap.lock().unwrap() = Arc::new(snap);
2375 self.bump();
2376 }
2377
2378 pub fn snapshot(&self) -> Arc<BusSnap> {
2380 Arc::clone(&self.snap.lock().unwrap())
2381 }
2382
2383 pub fn rev(&self) -> u64 {
2385 self.rev.load(Ordering::Acquire)
2386 }
2387
2388 pub fn bump(&self) {
2390 self.rev.fetch_add(1, Ordering::AcqRel);
2391 }
2392
2393 pub fn request_stop(&self) {
2395 self.stop.store(true, Ordering::Release);
2396 }
2397
2398 pub fn push_alert(&self, level: crate::toast::AlertLevel, text: impl Into<String>) {
2401 self.pending_alerts
2402 .lock()
2403 .unwrap_or_else(std::sync::PoisonError::into_inner)
2404 .push((level, text.into()));
2405 }
2406
2407 pub(crate) fn take_alerts(&self) -> Vec<(crate::toast::AlertLevel, String)> {
2409 let mut q = self
2410 .pending_alerts
2411 .lock()
2412 .unwrap_or_else(std::sync::PoisonError::into_inner);
2413 std::mem::take(&mut *q)
2414 }
2415
2416 pub(crate) fn toasts(&self) -> std::sync::MutexGuard<'_, Option<egui_notify::Toasts>> {
2418 self.toasts.lock()
2419 }
2420
2421 pub fn alert_once(&self, key: impl Into<String>) -> bool {
2423 let key = key.into();
2424 self.alerted
2425 .lock()
2426 .unwrap_or_else(std::sync::PoisonError::into_inner)
2427 .insert(key)
2428 }
2429
2430 #[must_use]
2432 pub fn pending_alert_count(&self) -> usize {
2433 self.pending_alerts
2434 .lock()
2435 .unwrap_or_else(std::sync::PoisonError::into_inner)
2436 .len()
2437 }
2438
2439 #[must_use]
2441 pub fn alerted_count(&self) -> usize {
2442 self.alerted
2443 .lock()
2444 .unwrap_or_else(std::sync::PoisonError::into_inner)
2445 .len()
2446 }
2447
2448 pub fn exit_confirm_open(&self) -> bool {
2450 self.exit_confirm_open
2451 .load(std::sync::atomic::Ordering::Relaxed)
2452 }
2453
2454 pub fn open_exit_confirm(&self) {
2455 self.exit_confirm_open
2456 .store(true, std::sync::atomic::Ordering::Relaxed);
2457 }
2458
2459 pub fn close_exit_confirm(&self) {
2460 self.exit_confirm_open
2461 .store(false, std::sync::atomic::Ordering::Relaxed);
2462 }
2463
2464 pub fn exit_confirmed(&self) -> bool {
2465 self.exit_confirmed
2466 .load(std::sync::atomic::Ordering::Relaxed)
2467 }
2468
2469 pub fn confirm_exit(&self) {
2470 self.exit_confirmed
2471 .store(true, std::sync::atomic::Ordering::Relaxed);
2472 }
2473
2474 pub fn is_stop(&self) -> bool {
2475 self.stop.load(Ordering::Acquire)
2476 }
2477
2478 pub fn push_cmd(&self, cmd: UiCmd) {
2482 self.cmds.lock().unwrap().push_back(cmd);
2483 self.bump();
2484 }
2485
2486 pub fn drain_cmds(&self) -> Vec<UiCmd> {
2488 self.cmds.lock().unwrap().drain(..).collect()
2489 }
2490
2491 #[must_use]
2493 pub fn cmd_pending(&self) -> bool {
2494 !self.cmds.lock().unwrap().is_empty()
2495 }
2496
2497 pub fn pending_confirm(&self) -> Option<String> {
2499 self.pending_confirm.lock().unwrap().clone()
2500 }
2501
2502 pub fn confirm_step(&self, name: &str) -> ConfirmStep {
2504 let mut g = self.pending_confirm.lock().unwrap();
2505 match g.take() {
2506 Some(p) if p == name => ConfirmStep::Fired,
2507 Some(_) => {
2508 *g = Some(name.to_string());
2509 ConfirmStep::Switched
2510 }
2511 None => {
2512 *g = Some(name.to_string());
2513 ConfirmStep::Armed
2514 }
2515 }
2516 }
2517
2518 pub fn confirm_cancel(&self) {
2520 *self.pending_confirm.lock().unwrap() = None;
2521 self.bump();
2522 }
2523
2524 pub fn market(&self) -> &MarketStore {
2528 &self.market
2529 }
2530
2531 pub fn seed_trade_snap(&self, ts: TradeSnap) {
2540 let named = |symbol: &str, name: String| -> String {
2543 if name.is_empty() {
2544 self.contract_name_of(symbol).unwrap_or(name)
2545 } else {
2546 name
2547 }
2548 };
2549 {
2550 let mut book = self.trade_orders.lock().unwrap();
2551 book.clear();
2552 for mut o in ts.orders.into_iter().rev() {
2553 o.name = named(&o.symbol, o.name);
2554 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2555 book.insert(o.en_orderid(), (seq, o));
2556 }
2557 }
2558 {
2559 let mut book = self.trade_trades.lock().unwrap();
2560 book.clear();
2561 let mut ids = self.trade_ids.lock().unwrap();
2562 ids.clear();
2563 for mut t in ts.trades.into_iter().rev() {
2564 t.name = named(&t.symbol, t.name);
2565 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2566 ids.insert(t.en_tradeid());
2567 book.push_front((seq, t));
2568 }
2569 }
2570 {
2571 let mut book = self.trade_positions.lock().unwrap();
2572 book.clear();
2573 for mut p in ts.positions.into_iter().rev() {
2574 p.name = named(&p.symbol, p.name);
2575 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2576 book.insert(p.en_positionid(), (seq, p));
2577 }
2578 }
2579 {
2580 let mut book = self.trade_funds.lock().unwrap();
2581 book.clear();
2582 for a in ts.accounts.into_iter().rev() {
2583 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2584 book.insert(a.en_accountid(), (seq, a));
2585 }
2586 }
2587 self.trade_dirty.store(true, Ordering::Release);
2588 self.bump();
2589 }
2590
2591 pub fn note_order(&self, o: &ek_data::order::OrderData) {
2599 let key = o.en_orderid();
2600 {
2601 let mut book = self.trade_orders.lock().unwrap();
2602 match book.get_mut(&key) {
2603 Some((_, cur)) => {
2604 cur.name.clone_from(&o.name);
2605 cur.traded = o.traded;
2606 cur.traded_price = o.traded_price;
2607 cur.status = o.status;
2608 cur.status_msg.clone_from(&o.status_msg);
2609 cur.datetime = o.datetime;
2610 }
2611 None => {
2612 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2613 book.insert(key, (seq, o.clone()));
2614 }
2615 }
2616 }
2617 self.trade_dirty.store(true, Ordering::Release);
2618 self.bump();
2619 }
2620
2621 pub fn note_trade(&self, t: &ek_data::trade::TradeData) {
2629 let id = t.en_tradeid();
2630 if self.trade_ids.lock().unwrap().contains(&id) {
2631 return;
2632 }
2633 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2634 let dropped = {
2635 let mut book = self.trade_trades.lock().unwrap();
2636 book.push_front((seq, t.clone()));
2637 self.trade_ids.lock().unwrap().insert(id);
2638 let over = book.len().saturating_sub(TRADE_CAP);
2639 for _ in 0..over {
2640 if let Some((_, old)) = book.pop_back() {
2642 self.trade_ids.lock().unwrap().remove(&old.en_tradeid());
2643 }
2644 }
2645 over
2646 };
2647 if dropped > 0 {
2648 let total = self
2649 .trade_dropped
2650 .fetch_add(dropped as u64, Ordering::AcqRel)
2651 + dropped as u64;
2652 if total == dropped as u64 {
2654 self.push_alert(
2655 crate::toast::AlertLevel::Warning,
2656 format!("成交表已达 {TRADE_CAP} 行上限:更早的成交不再显示"),
2657 );
2658 }
2659 }
2660 self.trade_dirty.store(true, Ordering::Release);
2661 self.bump();
2662 }
2663
2664 pub fn note_position(&self, p: &ek_data::position::PositionData) {
2669 let key = p.en_positionid();
2670 {
2671 let mut book = self.trade_positions.lock().unwrap();
2672 match book.get_mut(&key) {
2673 Some((_, cur)) => {
2674 cur.volume = p.volume;
2675 cur.yd_volume = p.yd_volume;
2676 cur.can_use_volume = p.can_use_volume;
2677 cur.frozen = p.frozen;
2678 cur.on_road_volume = p.on_road_volume;
2679 cur.market_value = p.market_value;
2680 cur.avg_price = p.avg_price;
2681 cur.price = p.price;
2682 cur.last_price = p.last_price;
2683 cur.pnl = p.pnl;
2684 cur.profit_rate = p.profit_rate;
2685 cur.name.clone_from(&p.name);
2686 }
2687 None => {
2688 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2689 book.insert(key, (seq, p.clone()));
2690 }
2691 }
2692 }
2693 self.trade_dirty.store(true, Ordering::Release);
2694 self.bump();
2695 }
2696
2697 pub fn note_funds(&self, a: &ek_data::account::AccountData) {
2699 let key = a.en_accountid();
2700 {
2701 let mut book = self.trade_funds.lock().unwrap();
2702 match book.get_mut(&key) {
2703 Some((_, cur)) => {
2704 cur.balance = a.balance;
2705 cur.frozen = a.frozen;
2706 }
2707 None => {
2708 let seq = self.trade_seq.fetch_add(1, Ordering::Relaxed) + 1;
2709 book.insert(key, (seq, a.clone()));
2710 }
2711 }
2712 }
2713 self.trade_dirty.store(true, Ordering::Release);
2714 self.bump();
2715 }
2716
2717 pub fn clear_gateway_rows(&self, gateway: &str) -> usize {
2719 let mut removed = 0usize;
2720 {
2721 let mut book = self.trade_orders.lock().unwrap();
2722 let before = book.len();
2723 book.retain(|_, (_, o)| o.gateway_name != gateway);
2724 removed += before - book.len();
2725 }
2726 {
2727 let mut book = self.trade_trades.lock().unwrap();
2728 let before = book.len();
2729 book.retain(|(_, t)| t.gateway_name != gateway);
2730 removed += before - book.len();
2731 let prefix = format!("{gateway}.");
2734 self.trade_ids
2735 .lock()
2736 .unwrap()
2737 .retain(|id| !id.starts_with(&prefix));
2738 }
2739 {
2740 let mut book = self.trade_positions.lock().unwrap();
2741 let before = book.len();
2742 book.retain(|_, (_, p)| p.gateway_name != gateway);
2743 removed += before - book.len();
2744 }
2745 {
2746 let mut book = self.trade_funds.lock().unwrap();
2747 let before = book.len();
2748 book.retain(|_, (_, a)| a.gateway_name != gateway);
2749 removed += before - book.len();
2750 }
2751 if removed > 0 {
2752 self.trade_dirty.store(true, Ordering::Release);
2753 self.bump();
2754 }
2755 removed
2756 }
2757
2758 #[must_use]
2760 pub fn trade_dropped(&self) -> u64 {
2761 self.trade_dropped.load(Ordering::Acquire)
2762 }
2763
2764 pub fn trade_snap(&self) -> Arc<TradeSnap> {
2769 let mut cache = self.trade_snap.lock().unwrap();
2770 if self.trade_dirty.swap(false, Ordering::AcqRel) {
2771 *cache = Arc::new(self.build_trade_snap());
2772 }
2773 Arc::clone(&cache)
2774 }
2775
2776 fn build_trade_snap(&self) -> TradeSnap {
2779 fn by_seq<T>(rows: &BTreeMap<String, (u64, T)>) -> Vec<T>
2780 where
2781 T: Clone,
2782 {
2783 let mut v: Vec<(u64, &String, &T)> =
2784 rows.iter().map(|(k, (s, v))| (*s, k, v)).collect();
2785 v.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
2786 v.into_iter().map(|(_, _, v)| v.clone()).collect()
2787 }
2788 TradeSnap {
2789 orders: by_seq(&self.trade_orders.lock().unwrap()),
2790 trades: self
2791 .trade_trades
2792 .lock()
2793 .unwrap()
2794 .iter()
2795 .map(|(_, t)| t.clone())
2796 .collect(),
2797 positions: by_seq(&self.trade_positions.lock().unwrap()),
2798 accounts: by_seq(&self.trade_funds.lock().unwrap()),
2799 }
2800 }
2801
2802 pub fn ctp_form(&self) -> CtpForm {
2806 self.ctp_form.lock().unwrap().clone()
2807 }
2808
2809 pub fn set_ctp_form(&self, f: CtpForm) {
2811 *self.ctp_form.lock().unwrap() = f;
2812 self.bump();
2813 }
2814
2815 pub fn row_selected(&self, table: &str, key: &str) -> bool {
2819 self.row_sel
2820 .lock()
2821 .unwrap()
2822 .get(table)
2823 .is_some_and(|k| k == key)
2824 }
2825
2826 pub fn select_row(&self, table: &str, key: &str) {
2828 self.row_sel
2829 .lock()
2830 .unwrap()
2831 .insert(table.to_string(), key.to_string());
2832 }
2833}