Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1937 lines (1662 loc) · 76.9 KB
/
Copy pathscript.js
File metadata and controls
1937 lines (1662 loc) · 76.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
document.addEventListener('DOMContentLoaded', () => {
console.log("DOM fully loaded and parsed");
// --- Configuration ---
let API_BASE_URL = ''; // 将根据用户配置的IP和端口动态设置
const API_ENDPOINTS = {
// --- GET Endpoints ---
getConfig: `/api/config`,
getStatus: `/api/status`,
getHoldings: `/api/holdings`,
getLogs: `/api/logs`,
getPositionsAll: `/api/positions-all`, // 获取所有持仓数据
getTradeRecords: `/api/trade-records`, // 获取交易记录
getStockPool: `/api/stock_pool/list`,
// --- POST Endpoints ---
saveConfig: `/api/config/save`,
checkConnection: '/api/connection/status',
startMonitor: `/api/monitor/start`,
stopMonitor: `/api/monitor/stop`,
clearLogs: `/api/logs/clear`,
clearCurrentData: `/api/data/clear_current`,
clearBuySellData: `/api/data/clear_buysell`,
importSavedData: `/api/data/import`,
initHoldings: `/api/holdings/init`,
executeBuy: `/api/actions/execute_buy`,
updateHoldingParams: `/api/holdings/update`
};
// 轮询设置
let POLLING_INTERVAL = 5000; // 默认5秒
const ACTIVE_POLLING_INTERVAL = 3000; // 活跃状态:3秒
const INACTIVE_POLLING_INTERVAL = 10000; // 非活跃状态:10秒
let pollingIntervalId = null;
let isMonitoring = false; // 前端监控状态,仅控制UI数据刷新
let isAutoTradingEnabled = false; // 自动交易状态,由全局监控总开关控制
let isSimulationMode = false; // 模拟交易模式
let isPageActive = true; // 页面活跃状态
let userMonitoringIntent = null; // 用户监控意图(点击按钮后)
let isApiConnected = true; // API连接状态,初始假设已连接
// 为不同类型的数据设置不同的刷新频率
const DATA_REFRESH_INTERVALS = {
status: 5000, // 状态信息每5秒刷新一次
holdings: 3000, // 持仓列表每3秒刷新一次
logs: 5000 // 日志每5秒刷新一次
};
// SSE连接
let sseConnection = null;
// 数据版本号跟踪
let currentDataVersions = {
holdings: 0,
logs: 0,
status: 0
};
// 请求锁定状态 - 防止重复请求
let requestLocks = {
status: false,
holdings: false,
logs: false
};
// 最近一次显示刷新状态的时间戳
let lastRefreshStatusShown = 0;
// æœ
10BC8
€近数据更新时间戳
let lastDataUpdateTimestamps = {
status: 0,
holdings: 0,
logs: 0
};
// 参数范围
let paramRanges = {};
// --- DOM Element References ---
const elements = {
messageArea: document.getElementById('messageArea'),
simulationModeWarning: document.getElementById('simulationModeWarning'),
// 配置表单元素
singleBuyAmount: document.getElementById('singleBuyAmount'),
firstProfitSell: document.getElementById('firstProfitSell'),
firstProfitSellEnabled: document.getElementById('firstProfitSellEnabled'),
stockGainSellPencent: document.getElementById('stockGainSellPencent'),
firstProfitSellPencent: document.getElementById('firstProfitSellPencent'),
allowBuy: document.getElementById('allowBuy'),
allowSell: document.getElementById('allowSell'),
stopLossBuy: document.getElementById('stopLossBuy'),
stopLossBuyEnabled: document.getElementById('stopLossBuyEnabled'),
stockStopLoss: document.getElementById('stockStopLoss'),
StopLossEnabled: document.getElementById('StopLossEnabled'),
singleStockMaxPosition: document.getElementById('singleStockMaxPosition'),
totalMaxPosition: document.getElementById('totalMaxPosition'),
connectPort: document.getElementById('connectPort'),
totalAccounts: document.getElementById('totalAccounts'),
globalAllowBuySell: document.getElementById('globalAllowBuySell'),
simulationMode: document.getElementById('simulationMode'),
// 错误提示元素
singleBuyAmountError: document.getElementById('singleBuyAmountError'),
firstProfitSellError: document.getElementById('firstProfitSellError'),
stockGainSellPencentError: document.getElementById('stockGainSellPencentError'),
stopLossBuyError: document.getElementById('stopLossBuyError'),
stockStopLossError: document.getElementById('stockStopLossError'),
singleStockMaxPositionError: document.getElementById('singleStockMaxPositionError'),
totalMaxPositionError: document.getElementById('totalMaxPositionError'),
connectPortError: document.getElementById('connectPortError'),
// 账户信息和状态
accountId: document.getElementById('accountId'),
availableBalance: document.getElementById('availableBalance'),
maxHoldingValue: document.getElementById('maxHoldingValue'),
totalAssets: document.getElementById('totalAssets'),
lastUpdateTimestamp: document.getElementById('last-update-timestamp'),
statusIndicator: document.getElementById('statusIndicator'),
// 按钮
toggleMonitorBtn: document.getElementById('toggleMonitorBtn'),
saveConfigBtn: document.getElementById('saveConfigBtn'),
clearLogBtn: document.getElementById('clearLogBtn'),
clearCurrentDataBtn: document.getElementById('clearCurrentDataBtn'),
clearBuySellDataBtn: document.getElementById('clearBuySellDataBtn'),
importDataBtn: document.getElementById('importDataBtn'),
initHoldingsBtn: document.getElementById('initHoldingsBtn'),
executeBuyBtn: document.getElementById('executeBuyBtn'),
// 买入设置
buyStrategy: document.getElementById('buyStrategy'),
buyQuantity: document.getElementById('buyQuantity'),
// 持仓表格
holdingsTableBody: document.getElementById('holdingsTableBody'),
selectAllHoldings: document.getElementById('selectAllHoldings'),
holdingsLoading: document.getElementById('holdingsLoading'),
holdingsError: document.getElementById('holdingsError'),
// 订单日志
orderLog: document.getElementById('orderLog'),
logLoading: document.getElementById('logLoading'),
logError: document.getElementById('logError'),
// 连接状态
connectionStatus: document.getElementById('connectionStatus')
};
// --- 监听页面可见性变化 ---
document.addEventListener('visibilitychange', () => {
isPageActive = !document.hidden;
// 如果轮询已启动,重新调整轮询间隔
if (pollingIntervalId && isMonitoring) {
stopPolling();
startPolling();
}
});
// --- 添加参数验证函数 ---
function validateParameter(inputElement, errorElement, min, max, fieldName) {
const value = parseFloat(inputElement.value);
let errorMessage = "";
if (isNaN(value)) {
errorMessage = `${fieldName || '参数'}必须是数字`;
} else if (min !== undefined && value < min) {
errorMessage = `${fieldName || '参数'}不能小于${min}`;
} else if (max !== undefined && value > max) {
errorMessage = `${fieldName || '参数'}不能大于${max}`;
}
if (errorMessage) {
errorElement.textContent = errorMessage;
errorElement.classList.remove('hidden');
inputElement.classList.add('border-red-500');
return false;
} else {
errorElement.classList.add('hidden');
inputElement.classList.remove('border-red-500');
return true;
}
}
// --- 添加表单验证函数 ---
function validateForm() {
let isValid = true;
// 验证单次买入金额
isValid = validateParameter(
elements.singleBuyAmount,
elements.singleBuyAmountError,
paramRanges.singleBuyAmount?.min,
paramRanges.singleBuyAmount?.max,
"单次买入金额"
) && isValid;
// 验证首次止盈比例
isValid = validateParameter(
elements.firstProfitSell,
elements.firstProfitSellError,
paramRanges.firstProfitSell?.min,
paramRanges.firstProfitSell?.max,
"首次止盈比例"
) && isValid;
// 验证首次盈利平仓卖出
isValid = validateParameter(
elements.stockGainSellPencent,
elements.stockGainSellPencentError,
paramRanges.stockGainSellPencent?.min,
paramRanges.stockGainSellPencent?.max,
"首次盈利平仓卖出比例"
) && isValid;
// 验证补仓跌幅
isValid = validateParameter(
elements.stopLossBuy,
elements.stopLossBuyError,
paramRanges.stopLossBuy?.min,
paramRanges.stopLossBuy?.max,
"补仓跌幅"
) && isValid;
// 验证止损比例
isValid = validateParameter(
elements.stockStopLoss,
elements.stockStopLossError,
paramRanges.stockStopLoss?.min,
paramRanges.stockStopLoss?.max,
"止损比例"
) && isValid;
// 验证单只股票最大持仓
isValid = validateParameter(
elements.singleStockMaxPosition,
elements.singleStockMaxPositionError,
paramRanges.singleStockMaxPosition?.min,
paramRanges.singleStockMaxPosition?.max,
"单只股票最大持仓"
) && isValid;
// 验证最大总持仓
isValid = validateParameter(
elements.totalMaxPosition,
elements.totalMaxPositionError,
paramRanges.totalMaxPosition?.min,
paramRanges.totalMaxPosition?.max,
"最大总持仓"
) && isValid;
// 验证端口号
isValid = validateParameter(
elements.connectPort,
elements.connectPortError,
paramRanges.connectPort?.min,
paramRanges.connectPort?.max,
"端口号"
) && isValid;
return isValid;
}
// --- 添加参数监听器 ---
function addParameterValidationListeners() {
// 为每个需要验证的输入框添加监听器
elements.singleBuyAmount.addEventListener('change', () => {
if (validateParameter(
elements.singleBuyAmount,
elements.singleBuyAmountError,
paramRanges.singleBuyAmount?.min,
paramRanges.singleBuyAmount?.max,
"单次买入金额"
)) {
throttledSyncParameter('singleBuyAmount', parseFloat(elements.singleBuyAmount.value));
}
});
elements.firstProfitSell.addEventListener('change', () => {
if (validateParameter(
elements.firstProfitSell,
elements.firstProfitSellError,
paramRanges.firstProfitSell?.min,
paramRanges.firstProfitSell?.max,
"首次止盈比例"
)) {
throttledSyncParameter('firstProfitSell', parseFloat(elements.firstProfitSell.value));
}
});
elements.stockGainSellPencent.addEventListener('change', () => {
if (validateParameter(
elements.stockGainSellPencent,
elements.stockGainSellPencentError,
paramRanges.stockGainSellPencent?.min,
paramRanges.stockGainSellPencent?.max,
"首次盈利平仓卖出比例"
)) {
throttledSyncParameter('stockGainSellPencent', parseFloat(elements.stockGainSellPencent.value));
}
});
elements.stopLossBuy.addEventListener('change', () => {
if (validateParameter(
elements.stopLossBuy,
elements.stopLossBuyError,
paramRanges.stopLossBuy?.min,
paramRanges.stopLossBuy?.max,
"补仓跌幅"
)) {
throttledSyncParameter('stopLossBuy', parseFloat(elements.stopLossBuy.value));
}
});
elements.stockStopLoss.addEventListener('change', () => {
if (validateParameter(
elements.stockStopLoss,
elements.stockStopLossError,
paramRanges.stockStopLoss?.min,
paramRanges.stockStopLoss?.max,
"止损比例"
)) {
throttledSyncParameter('stockStopLoss', parseFloat(elements.stockStopLoss.value));
}
});
elements.singleStockMaxPosition.addEventListener('change', () => {
if (validateParameter(
elements.singleStockMaxPosition,
elements.singleStockMaxPositionError,
paramRanges.singleStockMaxPosition?.min,
8
10BC8
paramRanges.singleStockMaxPosition?.max,
"单只股票最大持仓"
)) {
throttledSyncParameter('singleStockMaxPosition', parseFloat(elements.singleStockMaxPosition.value));
}
});
elements.totalMaxPosition.addEventListener('change', () => {
if (validateParameter(
elements.totalMaxPosition,
elements.totalMaxPositionError,
paramRanges.totalMaxPosition?.min,
paramRanges.totalMaxPosition?.max,
"最大总持仓"
)) {
throttledSyncParameter('totalMaxPosition', parseFloat(elements.totalMaxPosition.value));
}
});
elements.connectPort.addEventListener('change', () => {
if (validateParameter(
elements.connectPort,
elements.connectPortError,
paramRanges.connectPort?.min,
paramRanges.connectPort?.max,
"端口号"
)) {
throttledSyncParameter('connectPort', parseInt(elements.connectPort.value));
// 端口更改后更新API基础URL
updateApiBaseUrl();
}
});
// 开关类参数的实时同步
elements.allowBuy.addEventListener('change', (event) => {
throttledSyncParameter('allowBuy', event.target.checked);
});
elements.allowSell.addEventListener('change', (event) => {
throttledSyncParameter('allowSell', event.target.checked);
});
// 模拟交易模式切换监听
elements.simulationMode.addEventListener('change', (event) => {
isSimulationMode = event.target.checked;
updateSimulationModeUI();
throttledSyncParameter('simulationMode', event.target.checked);
});
// 全局监控总开关 - 自动交易控制
elements.globalAllowBuySell.addEventListener('change', (event) => {
// 明确:这里只影响自动交易状态,不影响监控UI状态
const autoTradingEnabled = event.target.checked;
isAutoTradingEnabled = autoTradingEnabled; // 更新本地状态
apiRequest(API_ENDPOINTS.saveConfig, {
method: 'POST',
body: JSON.stringify({ globalAllowBuySell: autoTradingEnabled })
})
.then(response => {
console.log("自动交易状态已更新:", autoTradingEnabled);
})
.catch(error => {
console.error("更新自动交易状态失败:", error);
// 可选:回滚UI状态
event.target.checked = !autoTradingEnabled;
isAutoTradingEnabled = !autoTradingEnabled;
});
});
// 其他开关类参数实时同步
elements.firstProfitSellEnabled.addEventListener('change', (event) => {
throttledSyncParameter('firstProfitSellEnabled', event.target.checked);
});
elements.firstProfitSellPencent.addEventListener('change', (event) => {
throttledSyncParameter('firstProfitSellPencent', event.target.checked);
});
elements.stopLossBuyEnabled.addEventListener('change', (event) => {
throttledSyncParameter('stopLossBuyEnabled', event.target.checked);
});
elements.StopLossEnabled.addEventListener('change', (event) => {
throttledSyncParameter('StopLossEnabled', event.target.checked);
});
// 监听IP地址变更
elements.totalAccounts.addEventListener('change', (event) => {
throttledSyncParameter('totalAccounts', event.target.value);
// IP变更后更新API基础URL
updateApiBaseUrl();
});
}
// 更新模拟交易模式UI
function updateSimulationModeUI() {
if (isSimulationMode) {
elements.simulationModeWarning.classList.remove('hidden');
elements.executeBuyBtn.classList.add('bg-orange-600', 'hover:bg-orange-700');
elements.executeBuyBtn.classList.remove('bg-cyan-600', 'hover:bg-cyan-700');
} else {
elements.simulationModeWarning.classList.add('hidden');
elements.executeBuyBtn.classList.remove('bg-orange-600', 'hover:bg-orange-700');
elements.executeBuyBtn.classList.add('bg-cyan-600', 'hover:bg-cyan-700');
}
}
// --- 节流函数 ---
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function() {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
}
}
// 判断两个数据是否基本相同(避免不必要的UI更新)
function areDataEqual(oldData, newData, ignoreFields = []) {
if (!oldData || !newData) return false;
// 对于简单对象,比较关键字段
for (const key in newData) {
if (ignoreFields.includes(key)) continue;
if (typeof newData[key] === 'number' && typeof oldData[key] === 'number') {
// 对于数值,考虑舍入误差
if (Math.abs(newData[key] - oldData[key]) > 0.001) return false;
} else if (newData[key] !== oldData[key]) {
return false;
}
}
return true;
}
// --- 工具函数 ---
function showMessage(text, type = 'info', duration = 5000) {
elements.messageArea.innerHTML = '';
const messageDiv = document.createElement('div');
messageDiv.textContent = text;
messageDiv.className = `status-message ${type}`;
elements.messageArea.appendChild(messageDiv);
if (duration > 0) {
setTimeout(() => {
if (messageDiv.parentNode === elements.messageArea) {
elements.messageArea.removeChild(messageDiv);
}
}, duration);
}
// 消息滚动到可见
messageDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
// 显示刷新状态 - 添加节流
function showRefreshStatus() {
// 限制刷新状态显示频率 - 最少间隔3秒
const now = Date.now();
if (now - lastRefreshStatusShown < 3000) {
return;
}
lastRefreshStatusShown = now;
// 如果已经存在刷新状态元素,则移除它
const existingStatus = document.getElementById('refreshStatus');
if (existingStatus) {
existingStatus.remove();
}
// 创建新的刷新状态元素
const statusElement = document.createElement('div');
statusElement.id = 'refreshStatus';
statusElement.className = 'fixed bottom-2 right-2 bg-blue-100 text-blue-800 px-2 py-1 rounded text-xs';
statusElement.innerHTML = '数据刷新中...';
document.body.appendChild(statusElement);
// 0.5秒后淡出
setTimeout(() => {
statusElement.style.animation = 'fadeOut 0.5s ease-in-out';
setTimeout(() => {
if (statusElement.parentNode) {
statusElement.parentNode.removeChild(statusElement);
}
}, 500);
}, 500);
}
// 显示更新指示器
function showUpdatedIndicator() {
// 检查最近是否已经显示过更新指示器
const now = Date.now();
if (now - lastRefreshStatusShown < 2000) {
return; // 如果2秒内已显示过刷新状态,则不显示更新指示器
}
const indicator = document.createElement('div');
indicator.className = 'fixed top-2 left-2 bg-green-100 text-green-800 px-2 py-1 rounded text-xs z-50';
indicator.textContent = '数据已更新';
document.body.appendChild(indicator);
setTimeout(() => {
indicator.style.opacity = '0';
indicator.style.transition = 'opacity 0.5s';
setTimeout(() => {
if (indicator.parentNode) {
indicator.parentNode.removeChild(indicator);
}
}, 500);
}, 1000);
}
// 更新API基础URL
function updateApiBaseUrl() {
const ip = elements.totalAccounts.value || '127.0.0.1';
const port = elements.connectPort.value || '5000';
API_BASE_URL = `http://${ip}:${port}`;
// 更新所有API端点
for (let key in API_ENDPOINTS) {
API_ENDPOINTS[key] = `${API_BASE_URL}${API_ENDPOINTS[key]}`;
}
console.log("API Base URL updated:", API_BASE_URL);
}
// API请求函数 - 添加节流
async function apiRequest(url, options = {}) {
// 提取URL中的关键部分用于日志
const urlParts = url.split('/');
const endpoint = urlParts[urlParts.length - 1].split('?')[0]; // 获取API路径的最后一部分
console.log(`API Request: ${options.method || 'GET'} ${endpoint}`, options.body ? JSON.parse(options.body) : '');
try {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
...options.headers,
},
...options,
});
if (!response.ok) {
let errorMsg = `HTTP error! Status: ${response.status}`;
try {
const errData = await response.json();
errorMsg += ` - ${errData.message || JSON.stringify(errData)}`;
// 处理参数验证错误
if (errData.errors && Array.isArray(errData.errors)) {
errorMsg += `\n参数错误: ${errData.errors.join(', ')}`;
}
} catch (e) { /* 忽略非JSON响应错误 */ }
throw new Error(errorMsg);
}
const data = await response.json();
console.log(`API Response: ${options.method || 'GET'} ${endpoint}`, data.status || 'success');
// 更新API连接状态为已连接
updateConnectionStatus(true);
return data;
} catch (error) {
console.error(`API Error: ${options.method || 'GET'} ${endpoint}`, error);
showMessage(`请求失败: ${error.message}`, 'error');
// 可能是API连接问题,标记为未连接
if (endpoint !== 'connection/status') {
updateConnectionStatus(false);
}
throw error;
}
}
// --- UI更新函数 ---
function updateConfigForm(config) {
console.log("Updating config form:", config);
if (!config) return;
elements.singleBuyAmount.value = config.singleBuyAmount ?? '35000';
elements.firstProfitSell.value = config.firstProfitSell ?? '5.00';
elements.firstProfitSellEnabled.checked = config.firstProfitSellEnabled ?? true;
elements.stockGainSellPencent.value = config.stockGainSellPencent ?? '60.00';
elements.firstProfitSellPencent.checked = config.firstProfitSellPencent ?? true;
elements.allowBuy.checked = config.allowBuy ?? true;
elements.allowSell.checked = config.allowSell ?? true;
elements.stopLossBuy.value = config.stopLossBuy ?? '5.00';
elements.stopLossBuyEnabled.checked = config.stopLossBuyEnabled ?? true;
elements.stockStopLoss.value = config.stockStopLoss ?? '7.00';
elements.StopLossEnabled.checked = config.StopLossEnabled ?? true;
elements.singleStockMaxPosition.value = config.singleStockMaxPosition ?? '70000';
elements.totalMaxPosition.value = config.totalMaxPosition ?? '400000';
elements.connectPort.value = config.connectPort ?? '5000';
elements.totalAccounts.value = config.totalAccounts ?? '127.0.0.1';
elements.globalAllowBuySell.checked = config.globalAllowBuySell ?? true;
elements.simulationMode.checked = config.simulationMode ?? false;
// 更新模拟交易模式状态
isSimulationMode = config.simulationMode ?? false;
updateSimulationModeUI();
}
// 修改后的updateStatusDisplay函数 - 关键修改在这里
function updateStatusDisplay(statusData) {
// 检查数据是否实际变化
const lastStatusData = window._lastStatusData || {};
const isDataChanged = !areDataEqual(lastStatusData, statusData, ['timestamp']);
if (!isDataChanged && window._lastStatusData) {
console.log("Status data unchanged, skipping update");
return;
}
window._lastStatusData = {...statusData};
console.log("Updating status display - data changed");
if (!statusData) return;
// 账户信息更新
elements.accountId.textContent = statusData.account?.id ?? '--';
elements.availableBalance.textContent = statusData.account?.availableBalance?.toFixed(2) ?? '--';
elements.maxHoldingValue.textContent = statusData.account?.maxHoldingValue?.toFixed(2) ?? '--';
elements.totalAssets.textContent = statusData.account?.totalAssets?.toFixed(2) ?? '--';
elements.lastUpdateTimestamp.textContent = statusData.account?.timestamp ?? new Date().toLocaleString('zh-CN');
// 获取后端状态,但不自动更新前端状态
const backendMonitoring = statusData.isMonitoring ?? false;
const backendAutoTrading = statusData.settings?.enableAutoTrading ?? false;
// 更新自动交易状态 - 只更新全局监控总开关,不影响监控状态
isAutoTradingEnabled = backendAutoTrading;
elements.globalAllowBuySell.checked = isAutoTradingEnabled;
// 核心修改:用户明确的监控意图优先,用户操作后不再让后端状态覆盖前端状态
if (userMonitoringIntent !== null) {
// 用户通过按钮明确表达了监控意图
console.log(`使用用户意图设置监控状态: ${userMonitoringIntent}`);
isMonitoring = userMonitoringIntent;
// 检查状态是否一致并同步到后端,但不让后端状态影响前端
if (isMonitoring !== backendMonitoring) {
console.warn(`监控状态不一致: 前端=${isMonitoring}, 后端=${backendMonitoring}, 尝试同步`);
// 发送额外同步请求,单向同步前端状态到后端
const endpoint = isMonitoring ? API_ENDPOINTS.startMonitor : API_ENDPOINTS.stopMonitor;
apiRequest(endpoint, {
method: 'POST',
body: JSON.stringify({ isMonitoring: isMonitoring })
}).catch(err => console.error("同步监控状态失败:", err));
}
// 已使用用户意图,重置它
userMonitoringIntent = null;
}
// 重要修改:不再自动使用后端状态覆盖前端监控状态
// 只在初始加载时使用后端状态
else if (!window._initialMonitoringLoaded) {
isMonitoring = backendMonitoring;
window._initialMonitoringLoaded = true;
console.log(`初始化监控状态: ${isMonitoring}`);
}
// 根据最终确定的监控状态更新UI
updateMonitoringUI();
// 更新系统设置
if (statusData.settings) {
// 同步模拟交易模式状态
isSimulationMode = statusData.settings.simulationMode || false;
elements.simulationMode.checked = isSimulationMode;
// 同步允许买卖设置
elements.allowBuy.checked = statusData.settings.allowBuy || false;
elements.allowSell.checked = statusData.settings.allowSell || false;
// 更新模拟交易模式UI
updateSimulationModeUI();
}
}
// 新增:监控状态UI更新函数,与自动交易状态分离
function updateMonitoringUI() {
if (isMonitoring) {
elements.statusIndicator.textContent = '运行中';
elements.statusIndicator.className = 'text-lg font-bold text-green-600';
elements.toggleMonitorBtn.textContent = '停止执行监控';
elements.toggleMonitorBtn.classList.remove('bg-blue-600', 'hover:bg-blue-700');
elements.toggleMonitorBtn.classList.add('bg-red-600', 'hover:bg-red-700');
// 只有在非轮询状态下才开始轮询
if (!pollingIntervalId) {
startPolling();
}
} else {
elements.statusIndicator.textContent = '未运行';
elements.statusIndicator.className = 'text-lg font-bold text-red-600';
elements.toggleMonitorBtn.textContent = '开始执行监控';
elements.toggleMonitorBtn.classList.remove('bg-red-600', 'hover:bg-red-700');
elements.toggleMonitorBtn.classList.add('bg-blue-600', 'hover:bg-blue-700');
// 只有在轮询状态下才停止轮询
if (pollingIntervalId) {
stopPolling();
}
}
}
// 轻量级账户信息更新,用于SSE
function updateQuickAccountInfo(accountInfo) {
if (accountInfo.available !== undefined) {
elements.availableBalance.textContent = parseFloat(accountInfo.available).toFixed(2);
// 添加闪烁效果
elements.availableBalance.classList.add('highlight-update');
setTimeout(() => {
elements.availableBalance.classList.remove('highlight-update');
}, 1000);
}
if (accountInfo.market_value !== undefined) {
elements.maxHoldingValue.textContent = parseFloat(accountInfo.market_value).toFixed(2);
elements.maxHoldingValue.classList.add('highlight-update');
setTimeout(() => {
elements.maxHoldingValue.classList.remove('highlight-update');
}, 1000);
}
if (accountInfo.total_asset !== undefined) {
elements.totalAssets.textContent = parseFloat(accountInfo.total_asset).toFixed(2);
elements.totalAssets.classList.add('highlight-update');
setTimeout(() => {
elements.totalAssets.classList.remove('highlight-update');
}, 1000);
}
}
// 更新监控状态UI,用于SSE - 修改后的版本,不再让监控状态和自动交易状态相互干扰
function updateMonitoringInfo(monitoringInfo) {
if (!monitoringInfo) return;
// 只更新全局监控总开关状态,不影响监控开关状态
if (monitoringInfo.autoTradingEnabled !== undefined) {
const wasAutoTrading = isAutoTradingEnabled;
isAutoTradingEnabled = monitoringInfo.autoTradingEnabled;
// 只有状态有变化时才更新UI
if (wasAutoTrading !== isAutoTradingEnabled) {
elements.globalAllowBuySell.checked = isAutoTradingEnabled;
}
}
// 更新允许买入/卖出状态
if (monitoringInfo.allowBuy !== undefined) {
elements.allowBuy.checked = monitoringInfo.allowBuy;
}
if (monitoringInfo.allowSell !== undefined) {
elements.allowSell.checked = monitoringInfo.allowSell;
}
// 更新模拟交易模式
if (monitoringInfo.simulationMode !== undefined) {
const wasSimulationMode = isSimulationMode;
isSimulationMode = monitoringInfo.simulationMode;
elements.simulationMode.checked = isSimulationMode;
// 只有状态有变化时才更新UI
if (wasSimulationMode !== isSimulationMode) {
updateSimulationModeUI();
}
}
}
// 显示股票选择对话框
function showStockSelectDialog(title, content, confirmCallback) {
const dialog = document.getElementById('stockSelectDialog');
const dialogTitle = document.getElementById('dialogTitle');
const dialogContent = document.getElementById('dialogContent');
const dialogConfirmBtn = document.getElementById('dialogConfirmBtn');
const dialogCancelBtn = document.getElementById('dialogCancelBtn');
// 设置对话框标题和内容
dialogTitle.textContent = title;
dialogContent.innerHTML = content;
// 设置确认按钮事件
dialogConfirmBtn. => {
confirmCallback();
dialog.classList.add('hidden');
};
// 设置取消按钮事件
dialogCancelBtn. => {
dialog.classList.add('hidden');
};
// 显示对话框
dialog.classList.remove('hidden');
}
// 处理从备选池随机买入(修改为可编
D908
辑版本)
async function handleRandomPoolBuy(quantity) {
try {
// 从后端获取备选池股票列表
const response = await apiRequest(API_ENDPOINTS.getStockPool);
if (response.status === 'success' && Array.isArray(response.data)) {
const stocks = response.data;
// 构建对话框内容 - 使用可编辑的文本框而非只读显示
const content = `
<p class="mb-2">以下股票将被用于随机买入(可编辑):</p>
<textarea id="randomPoolStockInput" class="w-full border rounded p-2 h-40">${stocks.join('\n')}</textarea>
`;
// 显示对话框
showStockSelectDialog(
'确认随机买入股票',
content,
() => {
// 获取用户可能编辑过的股票代码
const input = document.getElementById('randomPoolStockInput').value;
const editedStocks = input.split('\n')
.map(s => s.trim())
.filter(s => s.length > 0);
if (editedStocks.length === 0) {
showMessage('请输入有效的股票代码', 'warning');
return;
}
// 确认后执行买入,使用编辑后的股票列表
executeBuyAction('random_pool', quantity, editedStocks);
}
);
} else {
throw new Error(response.message || '获取备选池股票失败');
}
} catch (error) {
showMessage(`获取备选池股票失败: ${error.message}`, 'error');
}
}
// 处理自定义股票买入
function handleCustomStockBuy(quantity) {
// 构建对话框内容
const content = `
<p class="mb-2">请输入要买入的股票代码(一行一个):</p>
<textarea id="customStockInput" class="w-full border rounded p-2 h-40"></textarea>
`;
// 显示对话框
showStockSelectDialog(
'自定义股票买入',
content,
() => {
// 获取用户输入的股票代码
const input = document.getElementById('customStockInput').value;
const stocks = input.split('\n')
.map(s => s.trim())
.filter(s => s.length > 0);
if (stocks.length === 0) {
showMessage('请输入有效的股票代码', 'warning');
return;
}
// 执行买入
executeBuyAction('custom_stock', quantity, stocks);
}
);
}
// 执行买入动作
async function executeBuyAction(strategy, quantity, stocks) {
elements.executeBuyBtn.disabled = true;
showMessage(`执行买入 (${strategy}, ${quantity}只)...`, 'loading', 0);
try {
const buyData = {
strategy: strategy,
quantity: quantity,
stocks: stocks,
...getConfigData() // 包含所有配置参数
};
const data = await apiRequest(API_ENDPOINTS.executeBuy, {
method: 'POST',
body: JSON.stringify(buyData),
});
if (data.status === 'success') {
showMessage(data.message || "买入指令已发送", 'success');
// 重置请求锁定状态
requestLocks.holdings = false;
requestLocks.logs = false;
currentHoldingsVersion = 0; // 重置版本号,强制刷新
// 刷新相关数据
await fetchHoldings();
await fetchLogs();
await fetchStatus(); // 更新余额等
} else {
showMessage(data.message || "买入指令发送失败", 'error');
}
} catch (error) {
// 错误已由apiRequest处理
} finally {
elements.executeBuyBtn.disabled = false;
// 3秒后清除消息
setTimeout(() => {
elements.messageArea.innerHTML = '';
}, 3000);
}
}
// 判断持仓数据是否需要更新
function shouldUpdateRow(oldData, newData) {
// 检查关键字段是否有变化
const keysToCheck = ['current_price', 'market_value', 'profit_ratio', 'available', 'volume', 'change_percentage'];
return keysToCheck.some(key => {
// 对于数值,考虑舍入误差
if (typeof oldData[key] === 'number' && typeof newData[key] === 'number') {
return Math.abs(oldData[key] - newData[key]) > 0.001;
}
return oldData[key] !== newData[key];
});
}
// 更新现有持仓行
function updateExistingRow(row, stock) {
// 更新各个单元格的值
const cells = row.querySelectorAll('td');
// 确保保留复选框
// 更新基本信息
cells[1].textContent = stock.stock_code || '--';
cells[2].textContent = stock.stock_name || stock.name || '--';
// 更新涨跌幅,包括类名
const changePercentage = parseFloat(stock.change_percentage || 0);
cells[3].textContent = `${changePercentage.toFixed(2)}%`;
cells[3].className = `border p-2 ${changePercentage >= 0 ? 'text-red-600' : 'text-green-600'}`;
// 更新价格、成本和盈亏
cells[4].textContent = parseFloat(stock.current_price || 0).toFixed(2);
cells[5].textContent = parseFloat(stock.cost_price || 0).toFixed(2);
const profitRatio = parseFloat(stock.profit_ratio || 0);
cells[6].textContent = `${profitRatio.toFixed(2)}%`;
cells[6].className = `border p-2 ${profitRatio >= 0 ? 'text-red-600' : 'text-green-600'}`;
// 更新持仓信息
cells[7].textContent = parseFloat(stock.market_value || 0).toFixed(0);
cells[8].textContent = parseFloat(stock.available || 0).toFixed(0);
cells[9].textContent = parseFloat(stock.volume || 0).toFixed(0);
// 更新止盈标志
cells[10].innerHTML = `<input type="checkbox" ${stock.profit_triggered ? 'checked' : ''} disabled>`;
// 更新其他数据
cells[11].textContent = parseFloat(stock.highest_price || 0).toFixed(2);