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 self.login = login;
694 self.status_note = note;
695 }
696
697 #[must_use]
699 pub fn display_name(&self) -> String {
700 let a = self.alias.trim();
701 if a.is_empty() {
702 self.account.clone()
703 } else {
704 a.to_string()
705 }
706 }
707}
708
709#[derive(Debug, Clone, PartialEq, Default)]
711pub struct TradeSnap {
712 pub orders: Vec<ek_data::order::OrderData>,
713 pub trades: Vec<ek_data::trade::TradeData>,
714 pub positions: Vec<ek_data::position::PositionData>,
715 pub accounts: Vec<ek_data::account::AccountData>,
717}
718
719pub fn parse_reload_csv(form: &ReloadForm) -> Result<(i64, String, Vec<BarData>), String> {
722 let interval: i64 = form
723 .interval
724 .trim()
725 .parse()
726 .map_err(|_| format!("回灌 解析: interval 非整数:{:?}", form.interval))?;
727 let symbol = form.symbol.trim().to_string();
728 if symbol.is_empty() {
729 return Err("回灌解析: symbol 空".to_string());
730 }
731 if form.csv.trim().is_empty() {
732 return Err("回灌解析: csv 空".to_string());
733 }
734 let mut bars = Vec::new();
735 for (i, raw) in form.csv.lines().enumerate() {
736 let line = raw.trim();
737 if line.is_empty() || line.starts_with('#') {
738 continue;
739 }
740 let parts: Vec<&str> = line.split(',').map(str::trim).collect();
741 if parts.len() != 6 {
742 return Err(format!("回灌解析: 第 {} 列数 ≠ 6", i + 1));
743 }
744 let num = |s: &str| -> Result<f64, String> {
745 s.parse::<f64>()
746 .map_err(|_| format!("回灌解析: 第 {} 列数值坏:{:?}", i + 1, s))
747 };
748 let dt_s: i64 = parts[0]
749 .parse()
750 .map_err(|_| format!("回灌解析: 第 {} 列 dt 坏:{:?}", i + 1, parts[0]))?;
751 bars.push(BarData {
752 symbol: symbol.clone(),
753 datetime: dt_s * 1_000_000_000,
754 interval: Some(
755 ek_dm::wire::interval_of_seconds(interval)
756 .unwrap_or(ek_data::constant::Interval::MINUTE),
757 ),
758 open_price: num(parts[1])?,
759 high_price: num(parts[2])?,
760 low_price: num(parts[3])?,
761 close_price: num(parts[4])?,
762 volume: num(parts[5])?,
763 ..BarData::default()
764 });
765 }
766 if bars.is_empty() {
767 return Err("回灌解析: 无有效行".to_string());
768 }
769 Ok((interval, symbol, bars))
770}
771
772#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
777pub enum TopLeftTab {
778 #[default]
779 Orders,
780 Active,
781}
782
783impl TopLeftTab {
784 pub fn label(self) -> &'static str {
785 match self {
786 Self::Orders => "委托",
787 Self::Active => "未成交",
788 }
789 }
790}
791
792#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
794pub enum BottomRightTab {
795 #[default]
796 Account,
797 Logs,
798}
799
800impl BottomRightTab {
801 pub fn label(self) -> &'static str {
802 match self {
803 Self::Account => "资金",
804 Self::Logs => "日志",
805 }
806 }
807}
808
809#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
813pub enum Theme {
814 #[default]
816 FinanceDark,
817 EguiDark,
819 EguiLight,
821 QtClassic,
823}
824
825impl Theme {
826 pub fn label(self) -> &'static str {
827 match self {
828 Self::FinanceDark => "金融深色",
829 Self::EguiDark => "egui深色",
830 Self::EguiLight => "egui浅色",
831 Self::QtClassic => "Qt灰白",
832 }
833 }
834
835 pub fn next(self) -> Self {
837 match self {
838 Self::FinanceDark => Self::EguiDark,
839 Self::EguiDark => Self::EguiLight,
840 Self::EguiLight => Self::QtClassic,
841 Self::QtClassic => Self::FinanceDark,
842 }
843 }
844}
845
846#[derive(Debug, Default)]
849pub struct TickStore {
850 ticks: BTreeMap<String, ek_data::tick::TickData>,
851}
852
853impl TickStore {
854 pub fn put(&mut self, t: &ek_data::tick::TickData) {
857 self.ticks
858 .insert(format!("{}.{}", t.exchange.as_str(), t.symbol), t.clone());
859 }
860
861 pub fn rows(&self) -> Vec<ek_data::tick::TickData> {
863 let mut v: Vec<ek_data::tick::TickData> = self.ticks.values().cloned().collect();
864 v.sort_by(|a, b| {
865 (a.exchange.as_str().to_string(), a.symbol.clone())
866 .cmp(&(b.exchange.as_str().to_string(), b.symbol.clone()))
867 });
868 v
869 }
870
871 pub fn groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
873 let mut out: Vec<(String, Vec<ek_data::tick::TickData>)> = Vec::new();
874 for t in self.rows() {
875 let ex = t.exchange.as_str().to_string();
876 match out.last_mut() {
877 Some((e, v)) if *e == ex => v.push(t),
878 _ => out.push((ex, vec![t])),
879 }
880 }
881 out
882 }
883
884 pub fn len(&self) -> usize {
885 self.ticks.len()
886 }
887
888 pub fn is_empty(&self) -> bool {
889 self.ticks.is_empty()
890 }
891}
892
893#[derive(Debug, Clone, PartialEq)]
895pub struct OrderForm {
896 pub exchange: String,
898 pub symbol: String,
900 pub direction: ek_data::constant::Direction,
901 pub offset: ek_data::constant::Offset,
902 pub order_type: ek_data::constant::OrderType,
903 pub price: String,
905 pub volume: String,
906 pub gateway: String,
908 pub follow_price: bool,
910 pub auto_split: bool,
913}
914
915impl Default for OrderForm {
916 fn default() -> Self {
917 Self {
918 exchange: "SHFE".to_string(),
919 symbol: String::new(),
920 direction: ek_data::constant::Direction::LONG,
921 offset: ek_data::constant::Offset::OPEN,
922 order_type: ek_data::constant::OrderType::LIMIT,
923 price: String::new(),
924 volume: "1".to_string(),
925 gateway: String::new(),
926 follow_price: true,
927 auto_split: true,
928 }
929 }
930}
931
932impl OrderForm {
933 pub fn to_request(&self) -> Result<ek_data::order_request::OrderRequest, String> {
935 use std::str::FromStr;
936 let symbol = self.symbol.trim();
937 if symbol.is_empty() {
938 return Err("下单: 代码为空".to_string());
939 }
940 if symbol.contains('.') {
941 return Err("下单: 代码不带交易所前缀(交易所走下拉)".to_string());
942 }
943 let exchange = ek_data::constant::Exchange::from_str(self.exchange.trim())
944 .map_err(|e| format!("下单: {e}"))?;
945 let price: f64 = self
946 .price
947 .trim()
948 .parse()
949 .map_err(|_| format!("下单: 价格无效 {:?}", self.price))?;
950 let volume: f64 = self
951 .volume
952 .trim()
953 .parse()
954 .map_err(|_| format!("下单: 数量无效 {:?}", self.volume))?;
955 if self.order_type != ek_data::constant::OrderType::MARKET && price <= 0.0 {
956 return Err("下单: 限价单价格须为正".to_string());
957 }
958 if volume <= 0.0 {
959 return Err("下单: 数量须为正".to_string());
960 }
961 Ok(ek_data::order_request::OrderRequest {
962 symbol: symbol.to_string(),
963 exchange,
964 direction: self.direction,
965 order_type: self.order_type,
966 volume,
967 price,
968 offset: self.offset,
969 ..ek_data::order_request::OrderRequest::default()
970 })
971 }
972}
973
974#[derive(Debug, Default)]
980pub struct ContractStore {
981 contracts: BTreeMap<String, ek_data::contract::ContractData>,
982}
983
984impl ContractStore {
985 pub fn put(&mut self, c: &ek_data::contract::ContractData) {
986 self.contracts
987 .insert(format!("{}.{}", c.exchange.as_str(), c.symbol), c.clone());
988 }
989
990 pub fn query(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
992 let p = pattern.trim();
993 self.contracts
994 .values()
995 .filter(|c| {
996 p.is_empty()
997 || c.symbol.contains(p)
998 || c.exchange.as_str().eq_ignore_ascii_case(p)
999 || c.name.contains(p)
1000 })
1001 .cloned()
1002 .collect()
1003 }
1004
1005 pub fn len(&self) -> usize {
1006 self.contracts.len()
1007 }
1008
1009 pub fn is_empty(&self) -> bool {
1010 self.contracts.is_empty()
1011 }
1012}
1013
1014#[derive(Debug, Default)]
1016pub struct UiShared {
1017 logs: Mutex<LogRing>,
1018 snap: Mutex<Arc<BusSnap>>,
1019 market: MarketStore,
1020 ctp_form: Mutex<CtpForm>,
1021 trade_snap: Mutex<Arc<TradeSnap>>,
1022 tick_store: Mutex<TickStore>,
1023 order_form: Mutex<OrderForm>,
1024 selected_exchange: Mutex<String>,
1025 topleft_tab: Mutex<TopLeftTab>,
1026 bottomright_tab: Mutex<BottomRightTab>,
1027 ops_window: AtomicBool,
1028 accounts_window: AtomicBool,
1031 contracts_window: AtomicBool,
1032 theme: AtomicU8,
1034 contract_store: Mutex<ContractStore>,
1035 contract_query: Mutex<String>,
1036 contract_selected: Mutex<Vec<String>>,
1037 kline_windows: Mutex<Vec<String>>,
1038 rev: AtomicU64,
1039 stop: AtomicBool,
1041 cmds: Mutex<VecDeque<UiCmd>>,
1043 pending_confirm: Mutex<Option<String>>,
1045 accounts: Mutex<Vec<AccountRow>>,
1047 account_edit_window: AtomicBool,
1049 editing_account: Mutex<Option<String>>,
1051 edit_alias: Mutex<String>,
1053 edit_error: Mutex<Option<String>>,
1055 md_source: Mutex<String>,
1057 subscriptions: Mutex<Vec<String>>,
1059 row_sel: Mutex<BTreeMap<String, String>>,
1062 status_tick: AtomicU32,
1064 status_thresholds: Mutex<Option<(u32, i64)>>,
1067}
1068
1069impl UiShared {
1070 pub fn new() -> Self {
1072 Self::default()
1073 }
1074
1075 pub fn update_tick(&self, t: &ek_data::tick::TickData) {
1079 self.tick_store.lock().unwrap().put(t);
1080 self.bump();
1081 }
1082
1083 pub fn tick_rows(&self) -> Vec<ek_data::tick::TickData> {
1085 self.tick_store.lock().unwrap().rows()
1086 }
1087
1088 pub fn tick_groups(&self) -> Vec<(String, Vec<ek_data::tick::TickData>)> {
1090 self.tick_store.lock().unwrap().groups()
1091 }
1092
1093 pub fn tick_count(&self) -> usize {
1095 self.tick_store.lock().unwrap().len()
1096 }
1097
1098 pub fn order_form(&self) -> OrderForm {
1100 self.order_form.lock().unwrap().clone()
1101 }
1102
1103 pub fn set_order_form(&self, f: OrderForm) {
1105 *self.order_form.lock().unwrap() = f;
1106 self.bump();
1107 }
1108
1109 pub fn selected_exchange(&self) -> String {
1111 self.selected_exchange.lock().unwrap().clone()
1112 }
1113
1114 pub fn set_selected_exchange(&self, s: impl Into<String>) {
1116 *self.selected_exchange.lock().unwrap() = s.into();
1117 self.bump();
1118 }
1119
1120 pub fn topleft_tab(&self) -> TopLeftTab {
1122 *self.topleft_tab.lock().unwrap()
1123 }
1124
1125 pub fn set_topleft_tab(&self, t: TopLeftTab) {
1127 *self.topleft_tab.lock().unwrap() = t;
1128 self.bump();
1129 }
1130
1131 pub fn bottomright_tab(&self) -> BottomRightTab {
1133 *self.bottomright_tab.lock().unwrap()
1134 }
1135
1136 pub fn set_bottomright_tab(&self, t: BottomRightTab) {
1138 *self.bottomright_tab.lock().unwrap() = t;
1139 self.bump();
1140 }
1141
1142 pub fn theme(&self) -> Theme {
1146 match self.theme.load(Ordering::Acquire) {
1147 1 => Theme::EguiDark,
1148 2 => Theme::EguiLight,
1149 3 => Theme::QtClassic,
1150 _ => Theme::FinanceDark,
1151 }
1152 }
1153
1154 pub fn set_theme(&self, t: Theme) {
1156 self.theme.store(t as u8, Ordering::Release);
1157 self.bump();
1158 }
1159
1160 pub fn cycle_theme(&self) -> Theme {
1162 let t = self.theme().next();
1163 self.set_theme(t);
1164 t
1165 }
1166
1167 pub fn ops_window_open(&self) -> bool {
1169 self.ops_window.load(Ordering::Acquire)
1170 }
1171
1172 pub fn set_ops_window_open(&self, v: bool) {
1174 self.ops_window.store(v, Ordering::Release);
1175 self.bump();
1176 }
1177
1178 pub fn accounts_window_open(&self) -> bool {
1182 self.accounts_window.load(Ordering::Acquire)
1183 }
1184
1185 pub fn set_accounts_window_open(&self, v: bool) {
1187 self.accounts_window.store(v, Ordering::Release);
1188 self.bump();
1189 }
1190
1191 pub fn account_edit_open(&self) -> bool {
1193 self.account_edit_window.load(Ordering::Acquire)
1194 }
1195
1196 pub fn editing_account(&self) -> Option<String> {
1198 self.editing_account.lock().unwrap().clone()
1199 }
1200
1201 pub fn begin_account_edit(&self, gateway: Option<&str>) -> bool {
1205 match gateway {
1206 Some(gw) => {
1207 let Some(row) = self.account(gw) else {
1208 return false;
1209 };
1210 *self.editing_account.lock().unwrap() = Some(gw.to_string());
1211 *self.edit_alias.lock().unwrap() = row.alias.clone();
1212 self.set_ctp_form(row.form.clone());
1213 }
1214 None => {
1215 *self.editing_account.lock().unwrap() = None;
1216 *self.edit_alias.lock().unwrap() = String::new();
1217 let draft = self.draft_from_existing();
1218 self.set_ctp_form(draft);
1219 }
1220 }
1221 *self.edit_error.lock().unwrap() = None;
1222 self.account_edit_window.store(true, Ordering::Release);
1223 self.bump();
1224 true
1225 }
1226
1227 pub fn end_account_edit(&self) {
1229 *self.editing_account.lock().unwrap() = None;
1230 *self.edit_alias.lock().unwrap() = String::new();
1231 *self.edit_error.lock().unwrap() = None;
1232 self.account_edit_window.store(false, Ordering::Release);
1233 let draft = self.draft_from_existing();
1234 self.set_ctp_form(draft);
1235 self.bump();
1236 }
1237
1238 pub fn end_account_edit_if_editing(&self, gateway: &str) {
1244 if self.editing_account().as_deref() == Some(gateway) {
1245 self.end_account_edit();
1246 }
1247 }
1248
1249 pub fn edit_alias(&self) -> String {
1251 self.edit_alias.lock().unwrap().clone()
1252 }
1253
1254 pub fn set_edit_alias(&self, v: impl Into<String>) {
1256 *self.edit_alias.lock().unwrap() = v.into();
1257 self.bump();
1258 }
1259
1260 pub fn edit_error(&self) -> Option<String> {
1262 self.edit_error.lock().unwrap().clone()
1263 }
1264
1265 pub fn set_edit_error(&self, e: Option<String>) {
1267 *self.edit_error.lock().unwrap() = e;
1268 self.bump();
1269 }
1270
1271 pub fn account_edit_dirty(&self) -> bool {
1273 let editing = self.editing_account();
1274 let draft = self.ctp_form();
1275 match editing {
1276 Some(gw) => self.account(&gw).map(|a| a.form != draft).unwrap_or(false),
1277 None => draft != CtpForm::default() && !draft.td_user.trim().is_empty(),
1278 }
1279 }
1280
1281 pub fn accounts(&self) -> Vec<AccountRow> {
1283 self.accounts.lock().unwrap().clone()
1284 }
1285
1286 pub fn account(&self, gateway: &str) -> Option<AccountRow> {
1288 self.accounts
1289 .lock()
1290 .unwrap()
1291 .iter()
1292 .find(|a| a.gateway == gateway)
1293 .cloned()
1294 }
1295
1296 pub fn add_account(&self, row: AccountRow) -> Result<(), String> {
1302 let mut acc = self.accounts.lock().unwrap();
1303 if acc.iter().any(|a| a.gateway == row.gateway) {
1304 return Err(format!("账户 {} 已存在(同 broker + 账号)", row.gateway));
1305 }
1306 let alias = row.alias.trim();
1307 if !alias.is_empty()
1308 && acc
1309 .iter()
1310 .any(|a| a.alias.trim().eq_ignore_ascii_case(alias))
1311 {
1312 return Err(format!("别名 {alias:?} 已被其他账户占用(别名须唯一)"));
1313 }
1314 if acc.len() >= MAX_ACCOUNTS {
1315 return Err(format!(
1316 "账户已达软上限 {MAX_ACCOUNTS} 个(先移除一个再添加)"
1317 ));
1318 }
1319 acc.push(row);
1320 drop(acc);
1321 self.bump();
1322 Ok(())
1323 }
1324
1325 #[must_use]
1327 pub fn can_add_account(&self) -> bool {
1328 self.accounts.lock().unwrap().len() < MAX_ACCOUNTS
1329 }
1330
1331 pub fn set_account_alias(&self, gateway: &str, alias: &str) -> bool {
1337 let alias = alias.trim().to_string();
1338 let mut acc = self.accounts.lock().unwrap();
1339 if !alias.is_empty()
1340 && acc
1341 .iter()
1342 .any(|a| a.gateway != gateway && a.alias.eq_ignore_ascii_case(&alias))
1343 {
1344 return false;
1345 }
1346 match acc.iter_mut().find(|a| a.gateway == gateway) {
1347 Some(a) => {
1348 a.alias = alias;
1349 drop(acc);
1350 self.bump();
1351 true
1352 }
1353 None => false,
1354 }
1355 }
1356
1357 pub fn note_connect_sent(&self, gateway: &str) {
1362 let mut acc = self.accounts.lock().unwrap();
1363 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1364 a.stage = AccountStage::Assembling;
1365 a.fail_note = None;
1366 a.login = LoginState::Unknown;
1367 a.status_note = None;
1368 drop(acc);
1369 self.bump();
1370 }
1371 }
1372
1373 pub fn note_connect_result(&self, gateway: &str, result: Result<(), String>) {
1377 let mut acc = self.accounts.lock().unwrap();
1378 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1379 match result {
1380 Ok(()) => {
1381 a.stage = AccountStage::Assembled;
1382 a.fail_note = None;
1383 }
1384 Err(e) => {
1385 a.stage = AccountStage::AssembleFailed;
1386 a.fail_note = Some(e);
1387 }
1388 }
1389 drop(acc);
1390 self.bump();
1391 }
1392 }
1393
1394 pub fn note_effective_product_classes(&self, gateway: &str, classes: &[String]) {
1398 let mut acc = self.accounts.lock().unwrap();
1399 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1400 a.effective_classes = classes.to_vec();
1401 drop(acc);
1402 self.bump();
1403 }
1404 }
1405
1406 #[must_use]
1410 pub fn status_thresholds(&self) -> (u32, i64) {
1411 self.status_thresholds
1412 .lock()
1413 .unwrap()
1414 .unwrap_or((QUERY_REJECT_STREAK_LIMIT, ACCOUNT_STALE_SECS))
1415 }
1416
1417 pub fn set_status_thresholds(&self, reject_limit: u32, stale_secs: i64) {
1419 *self.status_thresholds.lock().unwrap() = Some((reject_limit, stale_secs));
1420 self.bump();
1421 }
1422
1423 pub fn status_poll_due(&self) -> bool {
1425 let n = self.status_tick.fetch_add(1, Ordering::Relaxed) + 1;
1426 n % STATUS_POLL_TICKS == 0
1427 }
1428
1429 pub fn note_gateway_status(&self, gateway: &str, st: &ek_ctp::plugin::GatewayStatus) {
1431 let (limit, stale) = self.status_thresholds();
1432 let now = ek_ctp::map::now_epoch_ms();
1433 let mut acc = self.accounts.lock().unwrap();
1434 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1435 a.apply_status(st, now, limit, stale);
1436 drop(acc);
1437 self.bump();
1438 }
1439 }
1440
1441 pub fn note_status_unreachable(&self, gateway: &str, why: &str) {
1445 let mut acc = self.accounts.lock().unwrap();
1446 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1447 a.login = LoginState::Unknown;
1448 a.status_note = Some(format!("状态口问不到:{why}"));
1449 drop(acc);
1450 self.bump();
1451 }
1452 }
1453
1454 pub fn mark_account_stopped(&self, gateway: &str) {
1456 let mut acc = self.accounts.lock().unwrap();
1457 if let Some(a) = acc.iter_mut().find(|a| a.gateway == gateway) {
1458 a.login = LoginState::Stopped;
1459 a.status_note = Some("会话已停;『连接』可恢复".to_string());
1460 drop(acc);
1461 self.bump();
1462 }
1463 }
1464
1465 pub fn prepare_connect_form(&self, gateway: &str, form: CtpForm) -> CtpForm {
1468 let source = self.md_source();
1469 let mut f = form;
1470 if source.as_str() != gateway {
1471 f.md_addr.clear();
1472 f.md_user.clear();
1473 f.md_password.clear();
1474 }
1475 self.update_account_form(gateway, f.clone());
1476 f
1477 }
1478
1479 #[must_use]
1483 pub fn draft_from_existing(&self) -> CtpForm {
1484 let acc = self.accounts.lock().unwrap();
1485 let mut draft = CtpForm::default();
1486 if let Some(a) = acc.last() {
1487 draft.broker_id = a.form.broker_id.clone();
1488 draft.td_auth_code = a.form.td_auth_code.clone();
1489 draft.td_app_id = a.form.td_app_id.clone();
1490 draft.accept_futures = a.form.accept_futures;
1491 draft.accept_options = a.form.accept_options;
1492 }
1493 draft
1494 }
1495
1496 pub fn update_account_form(&self, gateway: &str, form: CtpForm) -> bool {
1498 let mut acc = self.accounts.lock().unwrap();
1499 match acc.iter_mut().find(|a| a.gateway == gateway) {
1500 Some(a) => {
1501 a.form = form;
1502 drop(acc);
1503 self.bump();
1504 true
1505 }
1506 None => false,
1507 }
1508 }
1509
1510 pub fn remove_account(&self, gateway: &str) -> bool {
1512 let mut acc = self.accounts.lock().unwrap();
1513 let before = acc.len();
1514 acc.retain(|a| a.gateway != gateway);
1515 let removed = acc.len() != before;
1516 if removed {
1517 let mut md = self.md_source.lock().unwrap();
1519 if md.as_str() == gateway {
1520 md.clear();
1521 }
1522 drop(acc);
1523 self.bump();
1524 }
1525 removed
1526 }
1527
1528 pub fn sync_accounts_connected(&self, rows: &[PlugRow]) -> Vec<String> {
1537 let mut newly = Vec::new();
1538 {
1539 let mut acc = self.accounts.lock().unwrap();
1540 for a in acc.iter_mut() {
1541 let up = rows.iter().any(|r| r.name == a.gateway);
1542 if up && !a.connected {
1543 newly.push(a.gateway.clone());
1544 }
1545 a.connected = up;
1546 if up {
1547 a.stage = AccountStage::Assembled;
1548 a.fail_note = None;
1549 } else if a.stage == AccountStage::Assembled {
1550 a.stage = AccountStage::NotAssembled;
1551 a.login = LoginState::Unknown;
1552 a.status_note = None;
1553 }
1554 }
1555 }
1556 if !newly.is_empty() {
1557 self.bump();
1558 }
1559 newly
1560 }
1561
1562 pub fn md_source(&self) -> String {
1564 self.md_source.lock().unwrap().clone()
1565 }
1566
1567 pub fn accounts_locked(&self) -> bool {
1569 self.accounts.lock().unwrap().iter().any(|a| a.connected)
1570 }
1571
1572 pub fn set_md_source(&self, gateway: &str) -> Result<(), String> {
1574 {
1575 let acc = self.accounts.lock().unwrap();
1576 if acc.iter().any(|a| a.connected) {
1577 return Err("元账号已锁定:有账户在线,切换行情源需先断开该账户".to_string());
1578 }
1579 if !acc.iter().any(|a| a.gateway == gateway) {
1580 return Err(format!("账户 {gateway} 不在清册"));
1581 }
1582 }
1583 let mut acc = self.accounts.lock().unwrap();
1584 for a in acc.iter_mut() {
1585 a.md_source = a.gateway == gateway;
1586 }
1587 drop(acc);
1588 let mut md = self.md_source.lock().unwrap();
1589 *md = gateway.to_string();
1590 self.bump();
1591 Ok(())
1592 }
1593
1594 pub fn subscriptions(&self) -> Vec<String> {
1596 self.subscriptions.lock().unwrap().clone()
1597 }
1598
1599 pub fn note_subscriptions(&self, symbols: &[String]) {
1601 {
1602 let mut subs = self.subscriptions.lock().unwrap();
1603 for s in symbols {
1604 let s = s.trim();
1605 if !s.is_empty() && !subs.iter().any(|x| x == s) {
1606 subs.push(s.to_string());
1607 }
1608 }
1609 }
1610 self.bump();
1611 }
1612
1613 pub fn default_gateway(&self) -> Option<String> {
1620 let chosen = {
1621 let f = self.order_form.lock().unwrap();
1622 f.gateway.trim().to_string()
1623 };
1624 if !chosen.is_empty() && self.account(&chosen).is_some_and(|a| a.connected) {
1625 return Some(chosen);
1626 }
1627 let acc = self.accounts.lock().unwrap();
1628 acc.iter().find(|a| a.connected).map(|a| a.gateway.clone())
1629 }
1630
1631 pub fn kline_symbols(&self) -> Vec<String> {
1633 self.kline_windows.lock().unwrap().clone()
1634 }
1635
1636 pub fn open_kline(&self, symbol: impl Into<String>) {
1638 let s = symbol.into();
1639 let mut v = self.kline_windows.lock().unwrap();
1640 if !v.contains(&s) {
1641 v.push(s.clone());
1642 }
1643 drop(v);
1644 self.log_line(format!("[kline] 打开 K线窗 {s}"));
1645 }
1646
1647 pub fn close_kline(&self, symbol: &str) {
1649 self.kline_windows.lock().unwrap().retain(|s| s != symbol);
1650 self.bump();
1651 }
1652
1653 pub fn contracts_window_open(&self) -> bool {
1657 self.contracts_window.load(Ordering::Acquire)
1658 }
1659
1660 pub fn set_contracts_window_open(&self, v: bool) {
1662 self.contracts_window.store(v, Ordering::Release);
1663 self.bump();
1664 }
1665
1666 pub fn update_contract(&self, c: &ek_data::contract::ContractData) {
1668 self.contract_store.lock().unwrap().put(c);
1669 self.bump();
1670 }
1671
1672 pub fn contracts(&self, pattern: &str) -> Vec<ek_data::contract::ContractData> {
1674 self.contract_store.lock().unwrap().query(pattern)
1675 }
1676
1677 pub fn contract_count(&self) -> usize {
1679 self.contract_store.lock().unwrap().len()
1680 }
1681
1682 pub fn contract_query(&self) -> String {
1684 self.contract_query.lock().unwrap().clone()
1685 }
1686
1687 pub fn set_contract_query(&self, q: impl Into<String>) {
1689 *self.contract_query.lock().unwrap() = q.into();
1690 self.bump();
1691 }
1692
1693 pub fn toggle_contract_selection(&self, en_symbol: &str) {
1695 let mut v = self.contract_selected.lock().unwrap();
1696 match v.iter().position(|s| s == en_symbol) {
1697 Some(i) => {
1698 v.remove(i);
1699 }
1700 None => v.push(en_symbol.to_string()),
1701 }
1702 self.bump();
1703 }
1704
1705 pub fn selected_contracts(&self) -> Vec<String> {
1707 self.contract_selected.lock().unwrap().clone()
1708 }
1709
1710 pub fn log_line(&self, line: impl Into<String>) {
1712 self.logs.lock().unwrap().push(line);
1713 self.bump();
1714 }
1715
1716 pub fn clear_logs(&self) {
1718 self.logs.lock().unwrap().clear();
1719 self.bump();
1720 }
1721
1722 pub fn logs_snapshot(&self) -> (Vec<String>, u64) {
1724 let r = self.logs.lock().unwrap();
1725 (r.snapshot(), r.spilled())
1726 }
1727
1728 pub fn logs_len(&self) -> usize {
1730 self.logs.lock().unwrap().len()
1731 }
1732
1733 pub fn set_snapshot(&self, snap: BusSnap) {
1735 *self.snap.lock().unwrap() = Arc::new(snap);
1736 self.bump();
1737 }
1738
1739 pub fn snapshot(&self) -> Arc<BusSnap> {
1741 Arc::clone(&self.snap.lock().unwrap())
1742 }
1743
1744 pub fn rev(&self) -> u64 {
1746 self.rev.load(Ordering::Acquire)
1747 }
1748
1749 pub fn bump(&self) {
1751 self.rev.fetch_add(1, Ordering::AcqRel);
1752 }
1753
1754 pub fn request_stop(&self) {
1756 self.stop.store(true, Ordering::Release);
1757 }
1758
1759 pub fn is_stop(&self) -> bool {
1761 self.stop.load(Ordering::Acquire)
1762 }
1763
1764 pub fn push_cmd(&self, cmd: UiCmd) {
1768 self.cmds.lock().unwrap().push_back(cmd);
1769 self.bump();
1770 }
1771
1772 pub fn drain_cmds(&self) -> Vec<UiCmd> {
1774 self.cmds.lock().unwrap().drain(..).collect()
1775 }
1776
1777 pub fn pending_confirm(&self) -> Option<String> {
1779 self.pending_confirm.lock().unwrap().clone()
1780 }
1781
1782 pub fn confirm_step(&self, name: &str) -> ConfirmStep {
1784 let mut g = self.pending_confirm.lock().unwrap();
1785 match g.take() {
1786 Some(p) if p == name => ConfirmStep::Fired,
1787 Some(_) => {
1788 *g = Some(name.to_string());
1789 ConfirmStep::Switched
1790 }
1791 None => {
1792 *g = Some(name.to_string());
1793 ConfirmStep::Armed
1794 }
1795 }
1796 }
1797
1798 pub fn confirm_cancel(&self) {
1800 *self.pending_confirm.lock().unwrap() = None;
1801 self.bump();
1802 }
1803
1804 pub fn market(&self) -> &MarketStore {
1808 &self.market
1809 }
1810
1811 pub fn set_trade_snap(&self, ts: TradeSnap) {
1815 *self.trade_snap.lock().unwrap() = Arc::new(ts);
1816 self.bump();
1817 }
1818
1819 pub fn trade_snap(&self) -> Arc<TradeSnap> {
1821 self.trade_snap.lock().unwrap().clone()
1822 }
1823
1824 pub fn ctp_form(&self) -> CtpForm {
1828 self.ctp_form.lock().unwrap().clone()
1829 }
1830
1831 pub fn set_ctp_form(&self, f: CtpForm) {
1833 *self.ctp_form.lock().unwrap() = f;
1834 self.bump();
1835 }
1836
1837 pub fn row_selected(&self, table: &str, key: &str) -> bool {
1841 self.row_sel
1842 .lock()
1843 .unwrap()
1844 .get(table)
1845 .is_some_and(|k| k == key)
1846 }
1847
1848 pub fn select_row(&self, table: &str, key: &str) {
1850 self.row_sel
1851 .lock()
1852 .unwrap()
1853 .insert(table.to_string(), key.to_string());
1854 }
1855}