1use std::collections::{BTreeMap, VecDeque};
7use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, 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
17#[derive(Debug)]
19pub struct LogRing {
20 lines: VecDeque<String>,
21 cap: usize,
22 spilled: u64,
23}
24
25impl Default for LogRing {
26 fn default() -> Self {
27 Self::new(RING_CAP)
28 }
29}
30
31impl LogRing {
32 pub fn new(cap: usize) -> Self {
34 Self {
35 lines: VecDeque::with_capacity(cap),
36 cap,
37 spilled: 0,
38 }
39 }
40
41 pub fn push(&mut self, line: impl Into<String>) {
43 if self.cap == 0 {
44 self.spilled += 1;
45 return;
46 }
47 if self.lines.len() == self.cap {
48 self.lines.pop_front();
49 self.spilled += 1;
50 }
51 self.lines.push_back(line.into());
52 }
53
54 pub fn len(&self) -> usize {
56 self.lines.len()
57 }
58
59 pub fn is_empty(&self) -> bool {
61 self.lines.is_empty()
62 }
63
64 pub fn spilled(&self) -> u64 {
66 self.spilled
67 }
68
69 pub fn snapshot(&self) -> Vec<String> {
71 self.lines.iter().cloned().collect()
72 }
73
74 pub fn clear(&mut self) {
76 self.lines.clear();
77 }
78}
79
80#[derive(Debug, Clone, Default)]
82pub struct BusSnap {
83 pub rows: Vec<PlugRow>,
85 pub services: Vec<(String, Vec<String>)>,
87}
88
89#[derive(Debug, Clone, PartialEq)]
91pub enum UiCmd {
92 Start { factory: String, name: String },
95 Remove { name: String },
97 Reload {
99 interval: i64,
100 symbol: String,
101 bars: Vec<BarData>,
102 },
103 SendOrder {
109 req: ek_data::order_request::OrderRequest,
110 gateway: String,
111 mode: ek_oms::LockMode,
112 },
113 CancelOrder { orderid: String, gateway: String },
117 CtpConfigure { gateway: String, form: CtpForm },
121 Connect { gateway: String, form: CtpForm },
126 CtpSubscribe {
129 gateway: String,
130 symbols: Vec<String>,
131 },
132 Disconnect { gateway: String },
136}
137
138pub const KLINE_CELL_CAP: usize = 4096;
140
141pub const MAX_ACCOUNTS: usize = 8;
144
145pub const QUERY_REJECT_STREAK_LIMIT: u32 = 3;
150
151pub const ACCOUNT_STALE_SECS: i64 = 30;
156
157pub const STATUS_POLL_TICKS: u32 = 2;
162
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub enum ConfirmStep {
166 Armed,
167 Fired,
168 Switched,
169}
170
171#[must_use]
174pub fn is_quarantined(state: &str) -> bool {
175 state.contains("Quarantin")
176}
177
178#[derive(Debug, Default)]
182pub struct MarketStore {
183 cells: Mutex<BTreeMap<(String, i64), Vec<BarData>>>,
184 frames: AtomicU64,
186 updates: AtomicU64,
188 reloads: AtomicU64,
190}
191
192#[derive(Debug, Clone, PartialEq)]
194pub struct CellView {
195 pub symbol: String,
196 pub interval: i64,
197 pub bars: Vec<BarData>,
198}
199
200impl MarketStore {
201 pub fn on_frame(&self, frame: &BarsFrame) {
203 let mut cells = self.cells.lock().unwrap();
204 for b in &frame.bars {
205 let key = (b.symbol.clone(), frame.interval);
206 let cell = cells.entry(key).or_default();
207 match cell.last() {
208 Some(last) if b.datetime < last.datetime => continue,
209 Some(last) if b.datetime == last.datetime => {
210 let slot = cell.last_mut().expect("len>1");
211 *slot = b.clone();
212 }
213 _ => {
214 cell.push(b.clone());
215 if cell.len() > KLINE_CELL_CAP {
216 cell.remove(0);
217 }
218 }
219 }
220 }
221 self.frames.fetch_add(1, Ordering::AcqRel);
222 }
223
224 pub fn on_update(&self, b: &BarData) {
226 let mut cells = self.cells.lock().unwrap();
227 let iv = b
228 .interval
229 .unwrap_or(ek_data::constant::Interval::MINUTE)
230 .seconds();
231 let key = (b.symbol.clone(), iv);
232 let cell = cells.entry(key).or_default();
233 match cell.last() {
234 Some(last) if b.datetime == last.datetime => {
235 let slot = cell.last_mut().expect("len>1");
236 *slot = b.clone();
237 }
238 Some(last) if b.datetime < last.datetime => {}
239 _ => {
240 cell.push(b.clone());
241 if cell.len() > KLINE_CELL_CAP {
242 cell.remove(0);
243 }
244 }
245 }
246 self.updates.fetch_add(1, Ordering::AcqRel);
247 }
248
249 pub fn note_reload(&self) {
251 self.reloads.fetch_add(1, Ordering::AcqRel);
252 }
253
254 pub fn cells(&self) -> Vec<CellView> {
256 self.cells
257 .lock()
258 .unwrap()
259 .iter()
260 .map(|((sym, iv), bars)| CellView {
261 symbol: sym.clone(),
262 interval: *iv,
263 bars: bars.clone(),
264 })
265 .collect()
266 }
267
268 pub fn counts(&self) -> (u64, u64, u64) {
270 (
271 self.frames.load(Ordering::Acquire),
272 self.updates.load(Ordering::Acquire),
273 self.reloads.load(Ordering::Acquire),
274 )
275 }
276}
277
278#[derive(Debug, Default, Clone, PartialEq)]
281pub struct ReloadForm {
282 pub interval: String,
283 pub symbol: String,
284 pub csv: String,
285}
286
287pub fn parse_gateway(raw: &str, fallback: Option<&str>) -> Result<String, String> {
294 let g = raw.trim();
295 if !g.is_empty() {
296 if g.chars().any(|c| c.is_whitespace()) {
297 return Err(format!("网关解析: 含空白:{raw:?}"));
298 }
299 return Ok(g.to_string());
300 }
301 match fallback.map(|f| f.trim()).filter(|f| !f.is_empty()) {
302 Some(f) => Ok(f.to_string()),
303 None => Err("网关解析: 未选择账户(先在账户面板添加账户)".to_string()),
304 }
305}
306
307#[derive(Debug, Clone, PartialEq)]
310pub struct CtpForm {
311 pub broker_id: String,
312 pub td_addr: String,
313 pub td_user: String,
314 pub td_password: String,
315 pub td_auth_code: String,
316 pub td_app_id: String,
317 pub md_addr: String,
318 pub md_user: String,
319 pub md_password: String,
320 pub symbols: String,
322 pub accept_futures: bool,
325 pub accept_options: bool,
326}
327
328impl Default for CtpForm {
331 fn default() -> Self {
332 Self {
333 broker_id: String::new(),
334 td_addr: String::new(),
335 td_user: String::new(),
336 td_password: String::new(),
337 td_auth_code: String::new(),
338 td_app_id: String::new(),
339 md_addr: String::new(),
340 md_user: String::new(),
341 md_password: String::new(),
342 symbols: String::new(),
343 accept_futures: true,
344 accept_options: false,
345 }
346 }
347}
348
349impl CtpForm {
350 #[must_use]
354 pub fn product_classes(&self) -> Vec<String> {
355 let mut codes = Vec::new();
356 if self.accept_futures {
357 codes.push("1".to_string());
358 }
359 if self.accept_options {
360 codes.push("2".to_string());
361 }
362 codes
363 }
364
365 pub fn to_configure_req(&self) -> ek_ctp::plugin::ConfigureReq {
367 ek_ctp::plugin::ConfigureReq {
368 broker_id: self.broker_id.trim().to_string(),
369 td_addr: self.td_addr.trim().to_string(),
370 td_user: self.td_user.trim().to_string(),
371 td_password: self.td_password.clone(),
372 td_auth_code: self.td_auth_code.trim().to_string(),
373 td_app_id: self.td_app_id.trim().to_string(),
374 md_addr: self.md_addr.trim().to_string(),
375 md_user: self.md_user.trim().to_string(),
376 md_password: self.md_password.clone(),
377 product_classes: self.product_classes(),
378 }
379 }
380
381 pub fn parse_symbols(&self) -> Result<Vec<String>, String> {
383 let list: Vec<String> = self
384 .symbols
385 .split([',', ',', ' '])
386 .map(|s| s.trim().to_string())
387 .filter(|s| !s.is_empty())
388 .collect();
389 if list.is_empty() {
390 return Err("订阅解析: 标的位空".to_string());
391 }
392 Ok(list)
393 }
394
395 pub fn validate(&self) -> Result<(), String> {
404 fn front(name: &str, v: &str) -> Result<(), String> {
405 let v = v.trim();
406 let Some(rest) = v.strip_prefix("tcp://") else {
407 return Err(format!("{name} 形制应为 tcp://host:port(当前 {:?})", v));
408 };
409 let Some((host, port)) = rest.rsplit_once(':') else {
410 return Err(format!("{name} 缺端口:{name} {:?}", v));
411 };
412 if host.trim().is_empty() {
413 return Err(format!("{name} 主机位空:{}", v));
414 }
415 let port: u32 = port
416 .parse()
417 .map_err(|_| format!("{name} 端口不是数字:{}", v))?;
418 if port == 0 || port > 65535 {
419 return Err(format!("{name} 端口越界(1..=65535):{}", v));
420 }
421 Ok(())
422 }
423 if self.broker_id.trim().is_empty() {
424 return Err("broker 位空".to_string());
425 }
426 if self.td_user.trim().is_empty() {
427 return Err("交易账号位空".to_string());
428 }
429 front("td 前置", &self.td_addr)?;
430 if !self.md_addr.trim().is_empty() {
431 front("md 前置", &self.md_addr)?;
432 }
433 if self.td_app_id.trim().is_empty() {
434 return Err("AppID 位空(CTP 登录必需)".to_string());
435 }
436 if self.td_auth_code.trim().is_empty() {
437 return Err("AuthCode 位空(CTP 登录必需)".to_string());
438 }
439 Ok(())
440 }
441}
442
443#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
450pub enum AccountStage {
451 #[default]
453 NotAssembled,
454 Assembling,
456 Assembled,
458 AssembleFailed,
460}
461
462impl AccountStage {
463 #[must_use]
465 pub fn label(self) -> &'static str {
466 match self {
467 AccountStage::NotAssembled => "未装配",
468 AccountStage::Assembling => "装配中…",
469 AccountStage::Assembled => "已装配·登录态未知",
472 AccountStage::AssembleFailed => "装配失败",
473 }
474 }
475}
476
477#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
482pub enum LoginState {
483 #[default]
488 Unknown,
489 Online,
491 LoginFailed,
493 FrontDown,
495 QueryStarved,
497 Stopped,
499}
500
501impl LoginState {
502 #[must_use]
504 pub fn label(self) -> &'static str {
505 match self {
506 LoginState::Unknown => "登录态未知",
507 LoginState::Online => "在线",
508 LoginState::LoginFailed => "登录失败",
509 LoginState::FrontDown => "掉线",
510 LoginState::QueryStarved => "查询断供",
511 LoginState::Stopped => "已断开",
512 }
513 }
514
515 #[must_use]
517 pub fn is_alarm(self) -> bool {
518 matches!(self, LoginState::LoginFailed | LoginState::FrontDown)
519 }
520}
521
522fn count_note(label: &str, n: u32) -> Option<String> {
524 (n > 0).then(|| format!("{label} {n} 次"))
525}
526
527#[derive(Debug, Clone, PartialEq, Default)]
533pub struct AccountRow {
534 pub gateway: String,
536 pub alias: String,
538 pub broker_id: String,
539 pub account: String,
540 pub md_source: bool,
542 pub form: CtpForm,
544 pub stage: AccountStage,
546 pub fail_note: Option<String>,
548 pub effective_classes: Vec<String>,
553 pub connected: bool,
556 pub login: LoginState,
560 pub status_note: Option<String>,
563}
564
565impl AccountRow {
566 pub fn derive(form: &CtpForm) -> Result<Self, String> {
571 let broker = form.broker_id.trim();
572 let account = form.td_user.trim();
573 let gateway = ek_ctp::derived_gateway_name(broker, account).ok_or_else(|| {
574 "账户: broker/账号 不能为空且只能含字母数字(且派生名 ≤32)".to_string()
575 })?;
576 Ok(Self {
577 gateway,
578 alias: String::new(),
579 broker_id: broker.to_string(),
580 account: account.to_string(),
581 md_source: false,
582 form: form.clone(),
583 stage: AccountStage::NotAssembled,
584 fail_note: None,
585 effective_classes: Vec::new(),
586 connected: false,
587 login: LoginState::Unknown,
588 status_note: None,
589 })
590 }
591
592 #[must_use]
598 pub fn status_label(&self) -> String {
599 if self.stage == AccountStage::Assembled {
600 match self.login {
601 LoginState::Unknown => "已装配·登录态未知".to_string(),
602 other => format!("已装配·{}", other.label()),
603 }
604 } else {
605 self.stage.label().to_string()
606 }
607 }
608
609 pub fn apply_status(
620 &mut self,
621 st: &ek_ctp::plugin::GatewayStatus,
622 now_ms: i64,
623 reject_limit: u32,
624 stale_secs: i64,
625 ) {
626 let td_side = !self.form.td_addr.trim().is_empty();
627 let (login, note) = if td_side {
628 if st.td_login_failed && !st.td_logged_in {
629 (
630 LoginState::LoginFailed,
631 st.td_last_error
632 .clone()
633 .or_else(|| Some("登录失败(网关未回带原因)".to_string())),
634 )
635 } else if st.td_logged_in {
636 if st.td_query_reject_streak >= reject_limit {
637 (
638 LoginState::QueryStarved,
639 Some(format!("查询连续被拒 {} 次", st.td_query_reject_streak)),
640 )
641 } else if let Some(last) = st.td_last_account_ms {
642 let idle_ms = now_ms.saturating_sub(last);
643 if idle_ms > stale_secs.saturating_mul(1_000) {
644 (
645 LoginState::QueryStarved,
646 Some(format!("资金回报已 {}s 未更新", idle_ms / 1_000)),
647 )
648 } else {
649 (LoginState::Online, count_note("掉线", st.td_disconnects))
650 }
651 } else {
652 (LoginState::Online, Some("资金回报尚未到手".to_string()))
655 }
656 } else if self.login == LoginState::Stopped {
657 let extra = if st.td_disconnects > 0 {
658 format!("(此前掉线 {} 次)", st.td_disconnects)
659 } else {
660 String::new()
661 };
662 (
663 LoginState::Stopped,
664 Some(format!("会话已停{extra};『连接』可恢复")),
665 )
666 } else if st.td_disconnects > 0 {
667 (
668 LoginState::FrontDown,
669 Some(format!("掉线 {} 次", st.td_disconnects)),
670 )
671 } else {
672 (LoginState::Unknown, st.td_last_error.clone())
673 }
674 } else if st.md_logged_in {
675 (
676 LoginState::Online,
677 count_note("掉线", st.md_disconnects)
678 .or_else(|| Some("纯行情账户(无 TD 会话)".to_string())),
679 )
680 } else if self.login == LoginState::Stopped {
681 (
682 LoginState::Stopped,
683 Some("会话已停;『连接』可恢复".to_string()),
684 )
685 } else if st.md_disconnects > 0 {
686 (
687 LoginState::FrontDown,
688 Some(format!("掉线 {} 次", st.md_disconnects)),
689 )
690 } else {
691 (LoginState::Unknown, st.md_last_error.clone())
692 };
693 let note = if td_side && st.td_instrument_rejects > 0 {
698 let add = format!("合约查询被拒 {} 次", st.td_instrument_rejects);
699 match note {
700 Some(base) if base.contains("合约查询被拒") => Some(base),
702 Some(base) => Some(format!("{base};{add}")),
703 None => Some(add),
704 }
705 } else {
706 note
707 };
708 self.login = login;
709 self.status_note = note;
710 }
711
712 #[must_use]
714 pub fn display_name(&self) -> String {
715 let a = self.alias.trim();
716 if a.is_empty() {
717 self.account.clone()
718 } else {
719 a.to_string()
720 }
721 }
722}
723
724#[derive(Debug, Clone, PartialEq, Default)]
726pub struct TradeSnap {
727 pub orders: Vec<ek_data::order::OrderData>,
728 pub trades: Vec<ek_data::trade::TradeData>,
729 pub positions: Vec<ek_data::position::PositionData>,
730 pub accounts: Vec<ek_data::account::AccountData>,
732}
733
734pub fn parse_reload_csv(form: &ReloadForm) -> Result<(i64, String, Vec<BarData>), String> {
737 let interval: i64 = form
738 .interval
739 .trim()
740 .parse()
741 .map_err(|_| format!("回灌 解析: interval 非整数:{:?}", form.interval))?;
742 let symbol = form.symbol.trim().to_string();
743 if symbol.is_empty() {
744 return Err("回灌解析: symbol 空".to_string());
745 }
746 if form.csv.trim().is_empty() {
747 return Err("回灌解析: csv 空".to_string());
748 }
749 let mut bars = Vec::new();
750 for (i, raw) in form.csv.lines().enumerate() {
751 let line = raw.trim();
752 if line.is_empty() || line.starts_with('#') {
753 continue;
754 }
755 let parts: Vec<&str> = line.split(',').map(str::trim).collect();
756 if parts.len() != 6 {
757 return Err(format!("回灌解析: 第 {} 列数 ≠ 6", i + 1));
758 }
759 let num = |s: &str| -> Result<f64, String> {
760 s.parse::<f64>()
761 .map_err(|_| format!("回灌解析: 第 {} 列数值坏:{:?}", i + 1, s))
762 };
763 let dt_s: i64 = parts[0]
764 .parse()
765 .map_err(|_| format!("回灌解析: 第 {} 列 dt 坏:{:?}", i + 1, parts[0]))?;
766 bars.push(BarData {
767 symbol: symbol.clone(),
768 datetime: dt_s * 1_000_000_000,
769 interval: Some(
770 ek_dm::wire::interval_of_seconds(interval)
771 .unwrap_or(ek_data::constant::Interval::MINUTE),
772 ),
773 open_price: num(parts[1])?,
774 high_price: num(parts[2])?,
775 low_price: num(parts[3])?,
776 close_price: num(parts[4])?,
777 volume: num(parts[5])?,
778 ..BarData::default()
779 });
780 }
781 if bars.is_empty() {
782 return Err("回灌解析: 无有效行".to_string());
783 }
784 Ok((interval, symbol, bars))
785}
786
787#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
792pub enum TopLeftTab {
793 #[default]
794 Orders,
795 Active,
796}
797
798impl TopLeftTab {
799 pub fn label(self) -> &'static str {
800 match self {
801 Self::Orders => "委托",
802 Self::Active => "未成交",
803 }
804 }
805}
806
807#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
809pub enum BottomRightTab {
810 #[default]
811 Account,
812 Logs,
813}
814
815impl BottomRightTab {
816 pub fn label(self) -> &'static str {
817 match self {
818 Self::Account => "资金",
819 Self::Logs => "日志",
820 }
821 }
822}
823
824#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
828pub enum Theme {
829 #[default]
831 FinanceDark,
832 EguiDark,
834 EguiLight,
836 QtClassic,
838}
839
840impl Theme {
841 pub fn label(self) -> &'static str {
842 match self {
843 Self::FinanceDark => "金融深色",
844 Self::EguiDark => "egui深色",
845 Self::EguiLight => "egui浅色",
846 Self::QtClassic => "Qt灰白",
847 }
848 }
849
850 pub fn next(self) -> Self {
852 match self {
853 Self::FinanceDark => Self::EguiDark,
854 Self::EguiDark => Self::EguiLight,
855 Self::EguiLight => Self::QtClassic,
856 Self::QtClassic => Self::FinanceDark,
857 }
858 }
859}
860
861#[derive(Debug, Default)]
864pub struct TickStore {
865 ticks: BTreeMap<String, ek_data::tick::TickData>,
866}
867
868impl TickStore {
869 pub fn put(&mut self, t: &ek_data::tick::TickData) {
872 self.ticks
873 .insert(format!("{}.{}", t.exchange.as_str(), t.symbol), t.clone());
874 }
875
876 pub fn rows(&self) -> Vec<ek_data::tick::TickData> {
878 let mut v: Vec<ek_data::tick::TickData> = self.ticks.values().cloned().collect();
879 v.sort_by(|a, b| {
880 (a.exchange.as_str().to_string(), a.symbol.clone())
881 .cmp(&(b.exchange.as_str().to_string(), b.symbol.clone()))
882 });
883 v
884 }
885
886 pub fn groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
888 let mut out: Vec<(String, Vec<ek_data::tick::TickData>)> = Vec::new();
889 for t in self.rows() {
890 let ex = t.exchange.as_str().to_string();
891 match out.last_mut() {
892 Some((e, v)) if *e == ex => v.push(t),
893 _ => out.push((ex, vec![t])),
894 }
895 }
896 out
897 }
898
899 pub fn len(&self) -> usize {
900 self.ticks.len()
901 }
902
903 pub fn is_empty(&self) -> bool {
904 self.ticks.is_empty()
905 }
906}
907
908#[derive(Debug, Clone, PartialEq)]
910pub struct OrderForm {
911 pub exchange: String,
913 pub symbol: String,
915 pub direction: ek_data::constant::Direction,
916 pub offset: ek_data::constant::Offset,
917 pub order_type: ek_data::constant::OrderType,
918 pub price: String,
920 pub volume: String,
921 pub gateway: String,
923 pub follow_price: bool,
925 pub auto_split: bool,
928}
929
930impl Default for OrderForm {
931 fn default() -> Self {
932 Self {
933 exchange: "SHFE".to_string(),
934 symbol: String::new(),
935 direction: ek_data::constant::Direction::LONG,
936 offset: ek_data::constant::Offset::OPEN,
937 order_type: ek_data::constant::OrderType::LIMIT,
938 price: String::new(),
939 volume: "1".to_string(),
940 gateway: String::new(),
941 follow_price: true,
942 auto_split: true,
943 }
944 }
945}
946
947impl OrderForm {
948 pub fn to_request(&self) -> Result<ek_data::order_request::OrderRequest, String> {
950 use std::str::FromStr;
951 let symbol = self.symbol.trim();
952 if symbol.is_empty() {
953 return Err("下单: 代码为空".to_string());
954 }
955 if symbol.contains('.') {
956 return Err("下单: 代码不带交易所前缀(交易所走下拉)".to_string());
957 }
958 let exchange = ek_data::constant::Exchange::from_str(self.exchange.trim())
959 .map_err(|e| format!("下单: {e}"))?;
960 let price: f64 = self
961 .price
962 .trim()
963 .parse()
964 .map_err(|_| format!("下单: 价格无效 {:?}", self.price))?;
965 let volume: f64 = self
966 .volume
967 .trim()
968 .parse()
969 .map_err(|_| format!("下单: 数量无效 {:?}", self.volume))?;
970 if self.order_type != ek_data::constant::OrderType::MARKET && price <= 0.0 {
971 return Err("下单: 限价单价格须为正".to_string());
972 }
973 if volume <= 0.0 {
974 return Err("下单: 数量须为正".to_string());
975 }
976 Ok(ek_data::order_request::OrderRequest {
977 symbol: symbol.to_string(),
978 exchange,
979 direction: self.direction,
980 order_type: self.order_type,
981 volume,
982 price,
983 offset: self.offset,
984 ..ek_data::order_request::OrderRequest::default()
985 })
986 }
987}
988
989#[derive(Debug, Default)]
995pub struct ContractStore {
996 contracts: BTreeMap<String, ek_data::contract::ContractData>,
997}
998
999impl ContractStore {
1000 pub fn put(&mut self, c: &ek_data::contract::ContractData) {
1001 self.contracts
1002 .insert(format!("{}.{}", c.exchange.as_str(), c.symbol), c.clone());
1003 }
1004
1005 pub fn query(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
1007 let p = pattern.trim();
1008 self.contracts
1009 .values()
1010 .filter(|c| {
1011 p.is_empty()
1012 || c.symbol.contains(p)
1013 || c.exchange.as_str().eq_ignore_ascii_case(p)
1014 || c.name.contains(p)
1015 })
1016 .cloned()
1017 .collect()
1018 }
1019
1020 pub fn len(&self) -> usize {
1021 self.contracts.len()
1022 }
1023
1024 pub fn is_empty(&self) -> bool {
1025 self.contracts.is_empty()
1026 }
1027}
1028
1029#[derive(Debug, Default)]
1031pub struct UiShared {
1032 logs: Mutex<LogRing>,
1033 snap: Mutex<Arc<BusSnap>>,
1034 market: MarketStore,
1035 ctp_form: Mutex<CtpForm>,
1036 trade_snap: Mutex<Arc<TradeSnap>>,
1037 tick_store: Mutex<TickStore>,
1038 order_form: Mutex<OrderForm>,
1039 selected_exchange: Mutex<String>,
1040 topleft_tab: Mutex<TopLeftTab>,
1041 bottomright_tab: Mutex<BottomRightTab>,
1042 ops_window: AtomicBool,
1043 accounts_window: AtomicBool,
1046 contracts_window: AtomicBool,
1047 theme: AtomicU8,
1049 contract_store: Mutex<ContractStore>,
1050 contract_query: Mutex<String>,
1051 contract_selected: Mutex<Vec<String>>,
1052 kline_windows: Mutex<Vec<String>>,
1053 rev: AtomicU64,
1054 stop: AtomicBool,
1056 cmds: Mutex<VecDeque<UiCmd>>,
1058 pending_confirm: Mutex<Option<String>>,
1060 accounts: Mutex<Vec<AccountRow>>,
1062 account_edit_window: AtomicBool,
1064 editing_account: Mutex<Option<String>>,
1066 edit_alias: Mutex<String>,
1068 edit_error: Mutex<Option<String>>,
1070 md_source: Mutex<String>,
1072 subscriptions: Mutex<Vec<String>>,
1074 row_sel: Mutex<BTreeMap<String, String>>,
1077 status_tick: AtomicU32,
1079 status_thresholds: Mutex<Option<(u32, i64)>>,
1082}
1083
1084impl UiShared {
1085 pub fn new() -> Self {
1087 Self::default()
1088 }
1089
1090 pub fn update_tick(&self, t: &ek_data::tick::TickData) {
1094 self.tick_store.lock().unwrap().put(t);
1095 self.bump();
1096 }
1097
1098 pub fn tick_rows(&self) -> Vec<ek_data::tick::TickData> {
1100 self.tick_store.lock().unwrap().rows()
1101 }
1102
1103 pub fn tick_groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
1105 self.tick_store.lock().unwrap().groups()
1106 }
1107
1108 pub fn tick_count(&self) -> usize {
1110 self.tick_store.lock().unwrap().len()
1111 }
1112
1113 pub fn order_form(&self) -> OrderForm {
1115 self.order_form.lock().unwrap().clone()
1116 }
1117
1118 pub fn set_order_form(&self, f: OrderForm) {
1120 *self.order_form.lock().unwrap() = f;
1121 self.bump();
1122 }
1123
1124 pub fn selected_exchange(&self) -> String {
1126 self.selected_exchange.lock().unwrap().clone()
1127 }
1128
1129 pub fn set_selected_exchange(&self, s: impl Into<String>) {
1131 *self.selected_exchange.lock().unwrap() = s.into();
1132 self.bump();
1133 }
1134
1135 pub fn topleft_tab(&self) -> TopLeftTab {
1137 *self.topleft_tab.lock().unwrap()
1138 }
1139
1140 pub fn set_topleft_tab(&self, t: TopLeftTab) {
1142 *self.topleft_tab.lock().unwrap() = t;
1143 self.bump();
1144 }
1145
1146 pub fn bottomright_tab(&self) -> BottomRightTab {
1148 *self.bottomright_tab.lock().unwrap()
1149 }
1150
1151 pub fn set_bottomright_tab(&self, t: BottomRightTab) {
1153 *self.bottomright_tab.lock().unwrap() = t;
1154 self.bump();
1155 }
1156
1157 pub fn theme(&self) -> Theme {
1161 match self.theme.load(Ordering::Acquire) {
1162 1 => Theme::EguiDark,
1163 2 => Theme::EguiLight,
1164 3 => Theme::QtClassic,
1165 _ => Theme::FinanceDark,
1166 }
1167 }
1168
1169 pub fn set_theme(&self, t: Theme) {
1171 self.theme.store(t as u8, Ordering::Release);
1172 self.bump();
1173 }
1174
1175 pub fn cycle_theme(&self) -> Theme {
1177 let t = self.theme().next();
1178 self.set_theme(t);
1179 t
1180 }
1181
1182 pub fn ops_window_open(&self) -> bool {
1184 self.ops_window.load(Ordering::Acquire)
1185 }
1186
1187 pub fn set_ops_window_open(&self, v: bool) {
1189 self.ops_window.store(v, Ordering::Release);
1190 self.bump();
1191 }
1192
1193 pub fn accounts_window_open(&self) -> bool {
1197 self.accounts_window.load(Ordering::Acquire)
1198 }
1199
1200 pub fn set_accounts_window_open(&self, v: bool) {
1202 self.accounts_window.store(v, Ordering::Release);
1203 self.bump();
1204 }
1205
1206 pub fn account_edit_open(&self) -> bool {
1208 self.account_edit_window.load(Ordering::Acquire)
1209 }
1210
1211 pub fn editing_account(&self) -> Option<String> {
1213 self.editing_account.lock().unwrap().clone()
1214 }
1215
1216 pub fn begin_account_edit(&self, gateway: Option<&str>) -> bool {
1220 match gateway {
1221 Some(gw) => {
1222 let Some(row) = self.account(gw) else {
1223 return false;
1224 };
1225 *self.editing_account.lock().unwrap() = Some(gw.to_string());
1226 *self.edit_alias.lock().unwrap() = row.alias.clone();
1227 self.set_ctp_form(row.form.clone());
1228 }
1229 None => {
1230 *self.editing_account.lock().unwrap() = None;
1231 *self.edit_alias.lock().unwrap() = String::new();
1232 let draft = self.draft_from_existing();
1233 self.set_ctp_form(draft);
1234 }
1235 }
1236 *self.edit_error.lock().unwrap() = None;
1237 self.account_edit_window.store(true, Ordering::Release);
1238 self.bump();
1239 true
1240 }
1241
1242 pub fn end_account_edit(&self) {
1244 *self.editing_account.lock().unwrap() = None;
1245 *self.edit_alias.lock().unwrap() = String::new();
1246 *self.edit_error.lock().unwrap() = None;
1247 self.account_edit_window.store(false, Ordering::Release);
1248 let draft = self.draft_from_existing();
1249 self.set_ctp_form(draft);
1250 self.bump();
1251 }
1252
1253 pub fn end_account_edit_if_editing(&self, gateway: &str) {
1259 if self.editing_account().as_deref() == Some(gateway) {
1260 self.end_account_edit();
1261 }
1262 }
1263
1264 pub fn edit_alias(&self) -> String {
1266 self.edit_alias.lock().unwrap().clone()
1267 }
1268
1269 pub fn set_edit_alias(&self, v: impl Into<String>) {
1271 *self.edit_alias.lock().unwrap() = v.into();
1272 self.bump();
1273 }
1274
1275 pub fn edit_error(&self) -> Option<String> {
1277 self.edit_error.lock().unwrap().clone()
1278 }
1279
1280 pub fn set_edit_error(&self, e: Option<String>) {
1282 *self.edit_error.lock().unwrap() = e;
1283 self.bump();
1284 }
1285
1286 pub fn account_edit_dirty(&self) -> bool {
1288 let editing = self.editing_account();
1289 let draft = self.ctp_form();
1290 match editing {
1291 Some(gw) => self.account(&gw).map(|a| a.form != draft).unwrap_or(false),
1292 None => draft != CtpForm::default() && !draft.td_user.trim().is_empty(),
1293 }
1294 }
1295
1296 pub fn accounts(&self) -> Vec<AccountRow> {
1298 self.accounts.lock().unwrap().clone()
1299 }
1300
1301 pub fn account(&self, gateway: &str) -> Option<AccountRow> {
1303 self.accounts
1304 .lock()
1305 .unwrap()
1306 .iter()
1307 .find(|a| a.gateway == gateway)
1308 .cloned()
1309 }
1310
1311 pub fn add_account(&self, row: AccountRow) -> Result<(), String> {
1317 let mut acc = self.accounts.lock().unwrap();
1318 if acc.iter().any(|a| a.gateway == row.gateway) {
1319 return Err(format!("账户 {} 已存在(同 broker + 账号)", row.gateway));
1320 }
1321 let alias = row.alias.trim();
1322 if !alias.is_empty()
1323 && acc
1324 .iter()
1325 .any(|a| a.alias.trim().eq_ignore_ascii_case(alias))
1326 {
1327 return Err(format!("别名 {alias:?} 已被其他账户占用(别名须唯一)"));
1328 }
1329 if acc.len() >= MAX_ACCOUNTS {
1330 return Err(format!(
1331 "账户已达软上限 {MAX_ACCOUNTS} 个(先移除一个再添加)"
1332 ));
1333 }
1334 acc.push(row);
1335 drop(acc);
1336 self.bump();
1337 Ok(())
1338 }
1339
1340 #[must_use]
1342 pub fn can_add_account(&self) -> bool {
1343 self.accounts.lock().unwrap().len() < MAX_ACCOUNTS
1344 }
1345
1346 pub fn set_account_alias(&self, gateway: &str, alias: &str) -> bool {
1352 let alias = alias.trim().to_string();
1353 let mut acc = self.accounts.lock().unwrap();
1354 if !alias.is_empty()
1355 && acc
1356 .iter()
1357 .any(|a| a.gateway != gateway && a.alias.eq_ignore_ascii_case(&alias))
1358 {
1359 return false;
1360 }
1361 match acc.iter_mut().find(|a| a.gateway == gateway) {
1362 Some(a) => {
1363 a.alias = alias;
1364 drop(acc);
1365 self.bump();
1366 true
1367 }
1368 None => false,
1369 }
1370 }
1371
1372 pub fn note_connect_sent(&self, gateway: &str) {
1377 let mut acc = self.accounts.lock().unwrap();
1378 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1379 a.stage = AccountStage::Assembling;
1380 a.fail_note = None;
1381 a.login = LoginState::Unknown;
1382 a.status_note = None;
1383 drop(acc);
1384 self.bump();
1385 }
1386 }
1387
1388 pub fn note_connect_result(&self, gateway: &str, result: Result<(), String>) {
1392 let mut acc = self.accounts.lock().unwrap();
1393 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1394 match result {
1395 Ok(()) => {
1396 a.stage = AccountStage::Assembled;
1397 a.fail_note = None;
1398 }
1399 Err(e) => {
1400 a.stage = AccountStage::AssembleFailed;
1401 a.fail_note = Some(e);
1402 }
1403 }
1404 drop(acc);
1405 self.bump();
1406 }
1407 }
1408
1409 pub fn note_effective_product_classes(&self, gateway: &str, classes: &[String]) {
1413 let mut acc = self.accounts.lock().unwrap();
1414 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1415 a.effective_classes = classes.to_vec();
1416 drop(acc);
1417 self.bump();
1418 }
1419 }
1420
1421 #[must_use]
1425 pub fn status_thresholds(&self) -> (u32, i64) {
1426 self.status_thresholds
1427 .lock()
1428 .unwrap()
1429 .unwrap_or((QUERY_REJECT_STREAK_LIMIT, ACCOUNT_STALE_SECS))
1430 }
1431
1432 pub fn set_status_thresholds(&self, reject_limit: u32, stale_secs: i64) {
1434 *self.status_thresholds.lock().unwrap() = Some((reject_limit, stale_secs));
1435 self.bump();
1436 }
1437
1438 pub fn status_poll_due(&self) -> bool {
1440 let n = self.status_tick.fetch_add(1, Ordering::Relaxed) + 1;
1441 n % STATUS_POLL_TICKS == 0
1442 }
1443
1444 pub fn note_gateway_status(&self, gateway: &str, st: &ek_ctp::plugin::GatewayStatus) {
1446 let (limit, stale) = self.status_thresholds();
1447 let now = ek_ctp::map::now_epoch_ms();
1448 let mut acc = self.accounts.lock().unwrap();
1449 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1450 a.apply_status(st, now, limit, stale);
1451 drop(acc);
1452 self.bump();
1453 }
1454 }
1455
1456 pub fn note_status_unreachable(&self, gateway: &str, why: &str) {
1460 let mut acc = self.accounts.lock().unwrap();
1461 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1462 a.login = LoginState::Unknown;
1463 a.status_note = Some(format!("状态口问不到:{why}"));
1464 drop(acc);
1465 self.bump();
1466 }
1467 }
1468
1469 pub fn mark_account_stopped(&self, gateway: &str) {
1471 let mut acc = self.accounts.lock().unwrap();
1472 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1473 a.login = LoginState::Stopped;
1474 a.status_note = Some("会话已停;『连接』可恢复".to_string());
1475 drop(acc);
1476 self.bump();
1477 }
1478 }
1479
1480 pub fn prepare_connect_form(&self, gateway: &str, form: CtpForm) -> CtpForm {
1483 let source = self.md_source();
1484 let mut f = form;
1485 if source.as_str() != gateway {
1486 f.md_addr.clear();
1487 f.md_user.clear();
1488 f.md_password.clear();
1489 }
1490 self.update_account_form(gateway, f.clone());
1491 f
1492 }
1493
1494 #[must_use]
1498 pub fn draft_from_existing(&self) -> CtpForm {
1499 let acc = self.accounts.lock().unwrap();
1500 let mut draft = CtpForm::default();
1501 if let Some(a) = acc.last() {
1502 draft.broker_id = a.form.broker_id.clone();
1503 draft.td_auth_code = a.form.td_auth_code.clone();
1504 draft.td_app_id = a.form.td_app_id.clone();
1505 draft.accept_futures = a.form.accept_futures;
1506 draft.accept_options = a.form.accept_options;
1507 }
1508 draft
1509 }
1510
1511 pub fn update_account_form(&self, gateway: &str, form: CtpForm) -> bool {
1513 let mut acc = self.accounts.lock().unwrap();
1514 match acc.iter_mut().find(|a| a.gateway == gateway) {
1515 Some(a) => {
1516 a.form = form;
1517 drop(acc);
1518 self.bump();
1519 true
1520 }
1521 None => false,
1522 }
1523 }
1524
1525 pub fn remove_account(&self, gateway: &str) -> bool {
1527 let mut acc = self.accounts.lock().unwrap();
1528 let before = acc.len();
1529 acc.retain(|a| a.gateway != gateway);
1530 let removed = acc.len() != before;
1531 if removed {
1532 let mut md = self.md_source.lock().unwrap();
1534 if md.as_str() == gateway {
1535 md.clear();
1536 }
1537 drop(acc);
1538 self.bump();
1539 }
1540 removed
1541 }
1542
1543 pub fn sync_accounts_connected(&self, rows: &[PlugRow]) -> Vec<String> {
1552 let mut newly = Vec::new();
1553 {
1554 let mut acc = self.accounts.lock().unwrap();
1555 for a in acc.iter_mut() {
1556 let up = rows.iter().any(|r| r.name == a.gateway);
1557 if up && !a.connected {
1558 newly.push(a.gateway.clone());
1559 }
1560 a.connected = up;
1561 if up {
1562 a.stage = AccountStage::Assembled;
1563 a.fail_note = None;
1564 } else if a.stage == AccountStage::Assembled {
1565 a.stage = AccountStage::NotAssembled;
1566 a.login = LoginState::Unknown;
1567 a.status_note = None;
1568 }
1569 }
1570 }
1571 if !newly.is_empty() {
1572 self.bump();
1573 }
1574 newly
1575 }
1576
1577 pub fn md_source(&self) -> String {
1579 self.md_source.lock().unwrap().clone()
1580 }
1581
1582 pub fn accounts_locked(&self) -> bool {
1584 self.accounts.lock().unwrap().iter().any(|a| a.connected)
1585 }
1586
1587 pub fn set_md_source(&self, gateway: &str) -> Result<(), String> {
1589 {
1590 let acc = self.accounts.lock().unwrap();
1591 if acc.iter().any(|a| a.connected) {
1592 return Err("元账号已锁定:有账户在线,切换行情源需先断开该账户".to_string());
1593 }
1594 if !acc.iter().any(|a| a.gateway == gateway) {
1595 return Err(format!("账户 {gateway} 不在清册"));
1596 }
1597 }
1598 let mut acc = self.accounts.lock().unwrap();
1599 for a in acc.iter_mut() {
1600 a.md_source = a.gateway == gateway;
1601 }
1602 drop(acc);
1603 let mut md = self.md_source.lock().unwrap();
1604 *md = gateway.to_string();
1605 self.bump();
1606 Ok(())
1607 }
1608
1609 pub fn subscriptions(&self) -> Vec<String> {
1611 self.subscriptions.lock().unwrap().clone()
1612 }
1613
1614 pub fn note_subscriptions(&self, symbols: &[String]) {
1616 {
1617 let mut subs = self.subscriptions.lock().unwrap();
1618 for s in symbols {
1619 let s = s.trim();
1620 if !s.is_empty() && !subs.iter().any(|x| x == s) {
1621 subs.push(s.to_string());
1622 }
1623 }
1624 }
1625 self.bump();
1626 }
1627
1628 pub fn default_gateway(&self) -> Option<String> {
1635 let chosen = {
1636 let f = self.order_form.lock().unwrap();
1637 f.gateway.trim().to_string()
1638 };
1639 if !chosen.is_empty() && self.account(&chosen).is_some_and(|a| a.connected) {
1640 return Some(chosen);
1641 }
1642 let acc = self.accounts.lock().unwrap();
1643 acc.iter().find(|a| a.connected).map(|a| a.gateway.clone())
1644 }
1645
1646 pub fn kline_symbols(&self) -> Vec<String> {
1648 self.kline_windows.lock().unwrap().clone()
1649 }
1650
1651 pub fn open_kline(&self, symbol: impl Into<String>) {
1653 let s = symbol.into();
1654 let mut v = self.kline_windows.lock().unwrap();
1655 if !v.contains(&s) {
1656 v.push(s.clone());
1657 }
1658 drop(v);
1659 self.log_line(format!("[kline] 打开 K线窗 {s}"));
1660 }
1661
1662 pub fn close_kline(&self, symbol: &str) {
1664 self.kline_windows.lock().unwrap().retain(|s| s != symbol);
1665 self.bump();
1666 }
1667
1668 pub fn contracts_window_open(&self) -> bool {
1672 self.contracts_window.load(Ordering::Acquire)
1673 }
1674
1675 pub fn set_contracts_window_open(&self, v: bool) {
1677 self.contracts_window.store(v, Ordering::Release);
1678 self.bump();
1679 }
1680
1681 pub fn update_contract(&self, c: &ek_data::contract::ContractData) {
1683 self.contract_store.lock().unwrap().put(c);
1684 self.bump();
1685 }
1686
1687 pub fn contracts(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
1689 self.contract_store.lock().unwrap().query(pattern)
1690 }
1691
1692 pub fn contract_count(&self) -> usize {
1694 self.contract_store.lock().unwrap().len()
1695 }
1696
1697 pub fn contract_query(&self) -> String {
1699 self.contract_query.lock().unwrap().clone()
1700 }
1701
1702 pub fn set_contract_query(&self, q: impl Into<String>) {
1704 *self.contract_query.lock().unwrap() = q.into();
1705 self.bump();
1706 }
1707
1708 pub fn toggle_contract_selection(&self, en_symbol: &str) {
1710 let mut v = self.contract_selected.lock().unwrap();
1711 match v.iter().position(|s| s == en_symbol) {
1712 Some(i) => {
1713 v.remove(i);
1714 }
1715 None => v.push(en_symbol.to_string()),
1716 }
1717 self.bump();
1718 }
1719
1720 pub fn selected_contracts(&self) -> Vec<String> {
1722 self.contract_selected.lock().unwrap().clone()
1723 }
1724
1725 pub fn log_line(&self, line: impl Into<String>) {
1727 self.logs.lock().unwrap().push(line);
1728 self.bump();
1729 }
1730
1731 pub fn clear_logs(&self) {
1733 self.logs.lock().unwrap().clear();
1734 self.bump();
1735 }
1736
1737 pub fn logs_snapshot(&self) -> (Vec<String>, u64) {
1739 let r = self.logs.lock().unwrap();
1740 (r.snapshot(), r.spilled())
1741 }
1742
1743 pub fn logs_len(&self) -> usize {
1745 self.logs.lock().unwrap().len()
1746 }
1747
1748 pub fn set_snapshot(&self, snap: BusSnap) {
1750 *self.snap.lock().unwrap() = Arc::new(snap);
1751 self.bump();
1752 }
1753
1754 pub fn snapshot(&self) -> Arc<BusSnap> {
1756 Arc::clone(&self.snap.lock().unwrap())
1757 }
1758
1759 pub fn rev(&self) -> u64 {
1761 self.rev.load(Ordering::Acquire)
1762 }
1763
1764 pub fn bump(&self) {
1766 self.rev.fetch_add(1, Ordering::AcqRel);
1767 }
1768
1769 pub fn request_stop(&self) {
1771 self.stop.store(true, Ordering::Release);
1772 }
1773
1774 pub fn is_stop(&self) -> bool {
1776 self.stop.load(Ordering::Acquire)
1777 }
1778
1779 pub fn push_cmd(&self, cmd: UiCmd) {
1783 self.cmds.lock().unwrap().push_back(cmd);
1784 self.bump();
1785 }
1786
1787 pub fn drain_cmds(&self) -> Vec<UiCmd> {
1789 self.cmds.lock().unwrap().drain(..).collect()
1790 }
1791
1792 pub fn pending_confirm(&self) -> Option<String> {
1794 self.pending_confirm.lock().unwrap().clone()
1795 }
1796
1797 pub fn confirm_step(&self, name: &str) -> ConfirmStep {
1799 let mut g = self.pending_confirm.lock().unwrap();
1800 match g.take() {
1801 Some(p) if p == name => ConfirmStep::Fired,
1802 Some(_) => {
1803 *g = Some(name.to_string());
1804 ConfirmStep::Switched
1805 }
1806 None => {
1807 *g = Some(name.to_string());
1808 ConfirmStep::Armed
1809 }
1810 }
1811 }
1812
1813 pub fn confirm_cancel(&self) {
1815 *self.pending_confirm.lock().unwrap() = None;
1816 self.bump();
1817 }
1818
1819 pub fn market(&self) -> &MarketStore {
1823 &self.market
1824 }
1825
1826 pub fn set_trade_snap(&self, ts: TradeSnap) {
1830 *self.trade_snap.lock().unwrap() = Arc::new(ts);
1831 self.bump();
1832 }
1833
1834 pub fn trade_snap(&self) -> Arc<TradeSnap> {
1836 self.trade_snap.lock().unwrap().clone()
1837 }
1838
1839 pub fn ctp_form(&self) -> CtpForm {
1843 self.ctp_form.lock().unwrap().clone()
1844 }
1845
1846 pub fn set_ctp_form(&self, f: CtpForm) {
1848 *self.ctp_form.lock().unwrap() = f;
1849 self.bump();
1850 }
1851
1852 pub fn row_selected(&self, table: &str, key: &str) -> bool {
1856 self.row_sel
1857 .lock()
1858 .unwrap()
1859 .get(table)
1860 .is_some_and(|k| k == key)
1861 }
1862
1863 pub fn select_row(&self, table: &str, key: &str) {
1865 self.row_sel
1866 .lock()
1867 .unwrap()
1868 .insert(table.to_string(), key.to_string());
1869 }
1870}