You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2653 lines
78 KiB

4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
4 weeks ago
  1. <!-- @format -->
  2. <template>
  3. <!-- 容器 -->
  4. <view class="container">
  5. <!-- 标题 -->
  6. <view class="title-container">
  7. <view class="title">
  8. <image class="back-homepage-btn" src="/static/marketSituation-image/back.png" mode="返回按钮" @click="backToHomepage()"> </image>
  9. <view class="mid-title">
  10. <view class="arrow-left"> </view>
  11. <view class="stock-id">
  12. <view class="stock-name"> {{ stockInformation.stockName }} </view>
  13. <view class="stock-code"> {{ stockInformation.stockCode }} </view>
  14. </view>
  15. <view class="arrow-right"> </view>
  16. </view>
  17. <image class="search" src="/static/marketSituation-image/search.png" mode="搜索" @click="search()"> </image>
  18. <view class="more" @click="getMore()">···</view>
  19. </view>
  20. </view>
  21. <view class="body">
  22. <!-- 股票信息栏 -->
  23. <view class="stock-information" @click="openStockDetail()">
  24. <view v-if="isStockDetail" class="stock-detail-container" @click.stop @click="closeStockDetail()">
  25. <view class="stock-detail" @click.stop>
  26. <view class="first-column">
  27. <view class="first-column-data" v-for="item in firstColumData" :key="item">
  28. <view class="stock-detail-title">
  29. {{ item.title }}
  30. </view>
  31. <view class="stock-detail-value">
  32. {{ item.value }}
  33. </view>
  34. </view>
  35. </view>
  36. <view class="second-column">
  37. <view class="second-column-data" v-for="item in secondColumnData" :key="item">
  38. <view class="stock-detail-title">
  39. {{ item.title }}
  40. </view>
  41. <view class="stock-detail-value">
  42. {{ item.value }}
  43. </view>
  44. </view>
  45. </view>
  46. </view>
  47. </view>
  48. <view class="stock-current-data">
  49. <view class="stock-current-price" :class="confirmStockColor(stockInformation.currentPrice, stockInformation.lastDayStockClosePrice)">
  50. {{ Number(stockInformation.currentPrice).toFixed(2) }}
  51. </view>
  52. <view class="stock-current-other">
  53. <view class="stock-current-value" :class="confirmStockColor(stockInformation.currentValue)">
  54. {{ Number(stockInformation.currentValue).toFixed(2) }}
  55. </view>
  56. <view class="stock-current-ratio" :class="confirmStockColor(stockInformation.currentRatio)"> {{ Number(stockInformation.currentRatio).toFixed(2) }}% </view>
  57. </view>
  58. </view>
  59. <view class="stock-other-data">
  60. <view class="first-line">
  61. <view class="high-price">
  62. <view class="value" :class="confirmStockColor(stockInformation.highPrice, stockInformation.lastDayStockClosePrice)">
  63. {{ Number(stockInformation.highPrice).toFixed(2) }}
  64. </view>
  65. </view>
  66. <view class="volume">
  67. <view class="value">
  68. {{ utils.formatStockNumber(stockInformation.volume, 2) }}
  69. </view>
  70. </view>
  71. <view class="volume-ratio">
  72. 量比
  73. <view class="value">
  74. {{ Number(stockInformation.volumeRatio).toFixed(2) }}
  75. </view>
  76. </view>
  77. </view>
  78. <view class="second-line">
  79. <view class="low-price">
  80. <view class="value" :class="confirmStockColor(stockInformation.lowPrice, stockInformation.lastDayStockClosePrice)">
  81. {{ Number(stockInformation.lowPrice).toFixed(2) }}
  82. </view>
  83. </view>
  84. <view class="amount">
  85. <view class="value">
  86. {{ utils.formatStockNumber(stockInformation.amount, 2) }}
  87. </view>
  88. </view>
  89. <view class="market-earn">
  90. 市盈
  91. <view class="value">
  92. {{ Number(stockInformation.marketEarn).toFixed(2) }}
  93. </view>
  94. </view>
  95. </view>
  96. <view class="third-line">
  97. <view class="open-price">
  98. <view class="value" :class="confirmStockColor(stockInformation.openPrice, stockInformation.lastDayStockClosePrice)">
  99. {{ Number(stockInformation.openPrice).toFixed(2) }}
  100. </view>
  101. </view>
  102. <view class="turnover-ratio">
  103. <view class="value"> {{ Number(stockInformation.turnoverRatio).toFixed(2) }}% </view>
  104. </view>
  105. <view class="market-value">
  106. 市值
  107. <view class="value">
  108. {{ utils.formatStockNumber(stockInformation.marketValue, 2) }}
  109. </view>
  110. </view>
  111. </view>
  112. </view>
  113. </view>
  114. <!-- 股票图表 -->
  115. <view class="stock-chart">
  116. <view class="stock-kline-tab">
  117. <!-- 1:分时 2:日K 3:周K 4:月K -->
  118. <view class="tab-time" :class="{ 'tab-selected': klineTab == 1 }" @click="selectKlineTab(1)"> 分时 </view>
  119. <view class="tab-day" :class="{ 'tab-selected': klineTab == 2 }" @click="selectKlineTab(2)"> 日K </view>
  120. <view class="tab-week" :class="{ 'tab-selected': klineTab == 3 }" @click="selectKlineTab(3)"> 周K </view>
  121. <view class="tab-month" :class="{ 'tab-selected': klineTab == 4 }" @click="selectKlineTab(4)"> 月K </view>
  122. <view class="tab-more" :class="{ 'tab-selected': klineTab != 1 && klineTab != 2 && klineTab != 3 && klineTab != 4 }" @click="isMoreTabs ? closeMoreTabs() : openMoreTabs()">
  123. <view class="more-no-choose" v-if="klineTab == 1 || klineTab == 2 || klineTab == 3 || klineTab == 4"> 更多 </view>
  124. <view class="more-choose" v-else>
  125. {{ chooseTabName(klineTab) }}
  126. </view>
  127. <view :class="[isMoreTabs ? 'arrow-down' : 'arrow-up']"> </view>
  128. </view>
  129. <view class="tab-setting">
  130. <image class="tab-setting-img" src="/static/marketSituation-image/marketCondition-image/setting2.png" mode="设置"></image>
  131. </view>
  132. </view>
  133. <view v-if="isMoreTabs" class="moreTabsContainer">
  134. <view v-for="item in moreTabsData" :key="item" class="moreTabItem" :class="{ 'tab-selected': klineTab == item.value }" @click="selectMoreTab(item.value)">
  135. {{ item.title }}
  136. </view>
  137. </view>
  138. <view class="stock-kline">
  139. <view v-if="klineTab === 1 || klineTab === 2 || klineTab === 3 || klineTab === 4 || klineTab === 5 || klineTab === 6 || klineTab === 7 || klineTab === 8 || klineTab === 9" class="time-chart-container" style="position: relative">
  140. <!-- 主图Canvas -->
  141. <canvas
  142. canvas-id="stockChart"
  143. class="stock-chart"
  144. :width="canvasWidth"
  145. :height="canvasHeight"
  146. :style="{
  147. width: canvasWidth + 'px',
  148. height: canvasHeight + 'px',
  149. pointerEvents: 'none',
  150. }"
  151. will-read-frequently="true"
  152. ></canvas>
  153. <!-- 动态数据Canvas层 -->
  154. <canvas
  155. canvas-id="dynamicCanvas"
  156. id="dynamicCanvas"
  157. :width="canvasWidth"
  158. :height="canvasHeight"
  159. :style="{
  160. width: canvasWidth + 'px',
  161. height: canvasHeight + 'px',
  162. pointerEvents: 'none',
  163. position: 'absolute',
  164. top: '0',
  165. left: '0',
  166. }"
  167. will-read-frequently="true"
  168. ></canvas>
  169. <!-- 十字准心Canvas层 -->
  170. <canvas
  171. canvas-id="crosshairCanvas"
  172. id="crosshairCanvas"
  173. :width="canvasWidth"
  174. :height="canvasHeight"
  175. :style="{
  176. width: canvasWidth + 'px',
  177. height: canvasHeight + 'px',
  178. position: 'absolute',
  179. top: '0',
  180. left: '0',
  181. }"
  182. will-read-frequently="true"
  183. @touchstart="touchStart"
  184. @touchmove="touchMove"
  185. @touchend="touchEnd"
  186. ></canvas>
  187. </view>
  188. <!-- K线图区域 -->
  189. <view class="test" v-else-if="klineTab === 10">
  190. <button @click="startTcp()">接收消息</button>
  191. <button @click="sendStopTimeData()">停止消息</button>
  192. <button @click="sendTcpMessage('real_time')">实时行情推送</button>
  193. <button @click="sendTcpMessage('init_real_time')">初始化获取行情历史数据</button>
  194. <button @click="sendTcpMessage('stop_real_time')">停止实时推送</button>
  195. </view>
  196. <view v-else class="kline-chart-container">
  197. <text>K线图开发中...</text>
  198. </view>
  199. </view>
  200. </view>
  201. </view>
  202. <view class="bottomTool">
  203. <view class="index">
  204. <image class="icon" src="/static/marketSituation-image/marketCondition-image/index.png" mode="指标仓库图标"> </image>
  205. 指标仓库
  206. </view>
  207. <view class="function">
  208. <image class="icon" src="/static/marketSituation-image/marketCondition-image/function.png" mode="功能图标"> </image>
  209. 功能
  210. </view>
  211. <view class="favorites">
  212. <image class="icon" src="/static/marketSituation-image/marketCondition-image/favorites.png" mode="加自选图标"></image>
  213. 加自选
  214. </view>
  215. </view>
  216. </view>
  217. </template>
  218. <script setup>
  219. import { ref, reactive, computed, onMounted, watch, nextTick, onUnmounted, getCurrentInstance } from "vue";
  220. import { onLoad } from "@dcloudio/uni-app";
  221. const instance = getCurrentInstance();
  222. import { prevClosePrice, timeData as testTimeData, klineData as testKlineData } from "@/common/stockTimeInformation.js";
  223. import { throttle } from "@/common/util.js";
  224. import { HCharts } from "@/common/canvasMethod.js";
  225. import tcpConnection, { TCPConnection, TCP_CONFIG } from "@/api/tcpConnection.js";
  226. // TCP相关响应式变量
  227. const tcpConnected = ref(false);
  228. const connectionListener = ref(null);
  229. const messageListener = ref(null);
  230. // 股票信息栏变量
  231. const stockInformation = ref({
  232. stockName: "----", //股票名称
  233. stockCode: "------", //股票代码
  234. lastDayStockClosePrice: 0.0, //前一日收盘价
  235. currentPrice: 0.0, //当前股价
  236. currentValue: 0.0, //涨跌额度
  237. currentRatio: 0.0, //涨跌幅度
  238. highPrice: 0.0, //最高价
  239. lowPrice: 0.0, //最低价
  240. openPrice: 0.0, //开盘价
  241. closePrice: 0.0, //收盘价
  242. volume: 0.0, //成交量
  243. volumeRatio: 0.0, //成交量比
  244. amount: 0.0, //成交额
  245. marketEarn: 0.0, //市盈
  246. turnoverRatio: 0.0, //换手率
  247. marketValue: 0.0, //市值
  248. });
  249. // 是否展开股票信息细节栏的判断变量
  250. const isStockDetail = ref(false);
  251. // 股票信息细节内容变量
  252. const firstColumData = [
  253. {
  254. title: "振幅",
  255. value: 0,
  256. },
  257. {
  258. title: "现手",
  259. value: 0,
  260. },
  261. {
  262. title: "内盘",
  263. value: 0,
  264. },
  265. {
  266. title: "外盘",
  267. value: 0,
  268. },
  269. {
  270. title: "流通股",
  271. value: 0,
  272. },
  273. {
  274. title: "每股净资产",
  275. value: 0,
  276. },
  277. {
  278. title: "净资产收益率",
  279. value: 0,
  280. },
  281. {
  282. title: "总股本",
  283. value: 0,
  284. },
  285. {
  286. title: "总资本",
  287. value: 0,
  288. },
  289. {
  290. title: "总市值",
  291. value: 0,
  292. },
  293. {
  294. title: "一个月最高",
  295. value: 0,
  296. },
  297. {
  298. title: "一个月最低",
  299. value: 0,
  300. },
  301. ];
  302. const secondColumnData = [
  303. {
  304. title: "均价",
  305. value: 0,
  306. },
  307. {
  308. title: "昨收",
  309. value: 0,
  310. },
  311. {
  312. title: "委比",
  313. value: 0,
  314. },
  315. {
  316. title: "委买",
  317. value: 0,
  318. },
  319. {
  320. title: "委卖",
  321. value: 0,
  322. },
  323. {
  324. title: "市盈利(静)",
  325. value: 0,
  326. },
  327. {
  328. title: "市盈利(动)",
  329. value: 0,
  330. },
  331. {
  332. title: "市净率",
  333. value: 0,
  334. },
  335. {
  336. title: "涨停价",
  337. value: 0,
  338. },
  339. {
  340. title: "跌停价",
  341. value: 0,
  342. },
  343. {
  344. title: "一年最高",
  345. value: 0,
  346. },
  347. {
  348. title: "一年最低",
  349. value: 0,
  350. },
  351. ];
  352. // 是否展开更多Tab的判断变量
  353. const isMoreTabs = ref(false);
  354. const moreTabsData = ref([
  355. {
  356. title: "1分",
  357. value: 5,
  358. },
  359. {
  360. title: "5分",
  361. value: 6,
  362. },
  363. {
  364. title: "15分",
  365. value: 7,
  366. },
  367. {
  368. title: "30分",
  369. value: 8,
  370. },
  371. {
  372. title: "60分",
  373. value: 9,
  374. },
  375. {
  376. title: "季K",
  377. value: 10,
  378. },
  379. {
  380. title: "年K",
  381. value: 11,
  382. },
  383. ]);
  384. // 股票当前选中的K线类型Tab
  385. // 1:分时 2:日K 3:周K 4:月K
  386. const klineTab = ref(1);
  387. const startTcp = () => {
  388. try {
  389. removeTcpListeners();
  390. disconnectTcp();
  391. initTcpListeners();
  392. connectTcp();
  393. } catch (error) {
  394. console.error("建立连接并设置监听:", error);
  395. uni.showToast({
  396. title: "建立连接并设置监听",
  397. icon: "none",
  398. duration: 1500,
  399. });
  400. }
  401. };
  402. const sendStopTimeData = () => {
  403. disconnectTcp();
  404. removeTcpListeners();
  405. };
  406. // 确定股票数据的颜色方法
  407. const confirmStockColor = (price, lastDayStockClosePrice) => {
  408. if (typeof lastDayStockClosePrice === "undefined") {
  409. if (price == 0) {
  410. return "price-none";
  411. } else if (price > 0) {
  412. return "price-up";
  413. } else {
  414. return "price-down";
  415. }
  416. } else {
  417. if (price == lastDayStockClosePrice) {
  418. return "price-none";
  419. } else if (price > lastDayStockClosePrice) {
  420. return "price-up";
  421. } else {
  422. return "price-down";
  423. }
  424. }
  425. };
  426. // 股票K线类型方法
  427. const selectKlineTab = (tabId) => {
  428. klineTab.value = tabId;
  429. if (klineTab.value) {
  430. sendTcpMessage("stop_real_time");
  431. }
  432. switch (klineTab.value) {
  433. case 1:
  434. sendTcpMessage("init_real_time");
  435. break;
  436. case 2:
  437. sendTcpMessage("daily_data");
  438. break;
  439. case 3:
  440. sendTcpMessage("weekly_data");
  441. break;
  442. case 4:
  443. sendTcpMessage("monthly_data");
  444. break;
  445. case 5:
  446. sendTcpMessage("daily_one_minutes_data");
  447. break;
  448. case 6:
  449. sendTcpMessage("daily_five_minutes_data");
  450. break;
  451. case 7:
  452. sendTcpMessage("daily_fifteen_minutes_data");
  453. break;
  454. case 8:
  455. sendTcpMessage("daily_thirty_minutes_data");
  456. break;
  457. case 9:
  458. sendTcpMessage("daily_sixty_minutes_data");
  459. break;
  460. case 10:
  461. uni.showToast({
  462. title: "暂无季K数据",
  463. icon: "none",
  464. duration: 2000,
  465. });
  466. break;
  467. case 11:
  468. uni.showToast({
  469. title: "暂无年K数据",
  470. icon: "none",
  471. duration: 2000,
  472. });
  473. break;
  474. default:
  475. break;
  476. }
  477. initCanvas();
  478. // startAddDataTimer();
  479. };
  480. // 返回按钮
  481. const backToHomepage = () => {
  482. const pages = getCurrentPages();
  483. if (pages.length > 1) {
  484. uni.navigateBack();
  485. } else {
  486. // 如果没有上一页,跳转到首页
  487. uni.reLaunch({
  488. url: "/pages/home/home",
  489. });
  490. }
  491. };
  492. const openStockDetail = () => {
  493. isStockDetail.value = true;
  494. };
  495. const closeStockDetail = () => {
  496. isStockDetail.value = false;
  497. };
  498. const openMoreTabs = () => {
  499. isMoreTabs.value = true;
  500. };
  501. const closeMoreTabs = () => {
  502. isMoreTabs.value = false;
  503. };
  504. const selectMoreTab = (value) => {
  505. selectKlineTab(value);
  506. };
  507. const chooseTabName = () => {
  508. if (klineTab.value === 5) {
  509. return "1分";
  510. } else if (klineTab.value === 6) {
  511. return "5分";
  512. } else if (klineTab.value === 7) {
  513. return "15分";
  514. } else if (klineTab.value === 8) {
  515. return "30分";
  516. } else if (klineTab.value === 9) {
  517. return "60分";
  518. } else if (klineTab.value === 10) {
  519. return "季K";
  520. } else if (klineTab.value === 11) {
  521. return "年K";
  522. }
  523. };
  524. // 画布对象
  525. const canvasWidth = ref(100);
  526. const canvasHeight = ref(100);
  527. const CANVAS_BACKGROUND_COLOR = "#fff";
  528. const TEXT_COLOR1 = "#000";
  529. const TEXT_COLOR2 = "red";
  530. const LINE_COLOR = "#e5e5e5";
  531. const timeChartObject = ref({
  532. min: 0,
  533. max: 0,
  534. });
  535. const klineChartObject = ref({
  536. min: 0,
  537. max: 0,
  538. });
  539. const chartRange = ref();
  540. // 开盘时间
  541. const openTime = "09:30";
  542. // 收盘时间
  543. const closeTime = "15:00";
  544. const ctx = ref(null);
  545. const dynamicCtx = ref(null); // 动态Canvas上下文
  546. const crosshairCtx = ref(null); // 十字准心Canvas上下文
  547. const pixelRatio = ref(1);
  548. // 触屏对象
  549. const touchState = reactive({
  550. startX: 0,
  551. startY: 0,
  552. isMoving: false,
  553. moveDistance: 0,
  554. moveThreshold: 10, //移动阈值(用于判断是否在点击)
  555. scale: 1, // 当前缩放比例
  556. minScale: 0.3, // 最小缩放比例
  557. maxScale: 5, // 最大缩放比例
  558. baseVisibleCount: 40, // 基准可见K线数量
  559. offset: 0, // 数据偏移量
  560. isZooming: false, // 是否正在缩放
  561. initialDistance: 0, // 初始两指距离
  562. initialScale: 1, // 初始缩放比例
  563. });
  564. // 计算当前可见的K线数量
  565. const visibleCount = computed(() => {
  566. return Math.floor(touchState.baseVisibleCount / touchState.scale);
  567. });
  568. // 计算当前显示的数据范围
  569. const visibleDataRange = computed(() => {
  570. const start = Math.max(0, klineData.value.length - visibleCount.value - touchState.offset);
  571. const end = Math.min(klineData.value.length, start + visibleCount.value);
  572. return {
  573. start,
  574. end,
  575. };
  576. });
  577. // 获取当前可见的数据
  578. const visibleKlineData = computed(() => {
  579. const { start, end } = visibleDataRange.value;
  580. return klineData.value.slice(start, end);
  581. });
  582. // 计算两点之间的距离
  583. const getDistance = (touch1, touch2) => {
  584. const dx = touch1.x - touch2.x;
  585. const dy = touch1.y - touch2.y;
  586. return Math.sqrt(dx * dx + dy * dy);
  587. };
  588. // 十字准线相关状态
  589. const crosshair = reactive({
  590. show: false,
  591. x: 0,
  592. y: 0,
  593. currentData: null,
  594. snapToData: true,
  595. });
  596. // 绘制网格和坐标轴
  597. const grid = [
  598. {
  599. top: 20,
  600. bottom: canvasHeight.value * 0.5,
  601. left: 5,
  602. right: 5,
  603. lineColor: LINE_COLOR,
  604. lineWidth: 1,
  605. horizontalLineNum: 5,
  606. verticalLineNum: 5,
  607. },
  608. {
  609. top: canvasHeight.value * 0.5 + 20,
  610. bottom: 20,
  611. left: 5,
  612. right: 5,
  613. lineColor: LINE_COLOR,
  614. lineWidth: 1,
  615. horizontalLineNum: 3,
  616. verticalLineNum: 5,
  617. },
  618. ];
  619. // 绘制网格和坐标轴
  620. const dayGrid = [
  621. {
  622. top: 20,
  623. bottom: canvasHeight.value * 0.5,
  624. left: 5,
  625. right: 5,
  626. lineColor: LINE_COLOR,
  627. lineWidth: 1,
  628. horizontalLineNum: 5,
  629. verticalLineNum: 2,
  630. },
  631. {
  632. top: canvasHeight.value * 0.5 + 20,
  633. bottom: 20,
  634. left: 5,
  635. right: 5,
  636. lineColor: LINE_COLOR,
  637. lineWidth: 1,
  638. horizontalLineNum: 3,
  639. verticalLineNum: 2,
  640. },
  641. {
  642. top: canvasHeight.value * 0.5 + 20,
  643. bottom: 20,
  644. left: 5,
  645. right: 5,
  646. lineColor: LINE_COLOR,
  647. lineWidth: 1,
  648. horizontalLineNum: 3,
  649. verticalLineNum: 2,
  650. },
  651. ];
  652. // 工具函数
  653. const utils = {
  654. // 格式化价格
  655. formatPrice(price) {
  656. return price.toFixed(2);
  657. },
  658. // 计算数据范围
  659. calculateDataRange(data, key) {
  660. if (!data || data.length === 0) {
  661. return {
  662. min: 0,
  663. max: 0,
  664. };
  665. }
  666. const values = data.map((item) => item[key]);
  667. return {
  668. min: Math.min(...values),
  669. max: Math.max(...values),
  670. };
  671. },
  672. // 计算标签
  673. calculateLabel(data, type = 2, preClosePrice = 0, key, num) {
  674. let label = [];
  675. if (key === "price") {
  676. // 分时价格区间
  677. if (type == 1) {
  678. const priceRange = utils.calculateDataRange(data, "price");
  679. const theMost = Math.max(priceRange.max - preClosePrice, preClosePrice - priceRange.min);
  680. const mid = (num - 1) / 2;
  681. // 计算分时价格标签
  682. label[mid] = {
  683. value: utils.formatPrice(preClosePrice),
  684. ratio: utils.formatPrice(0) + "%",
  685. };
  686. for (let i = 0; i < mid; i++) {
  687. label[i] = {
  688. value: utils.formatPrice(preClosePrice + (theMost * (mid - i)) / mid),
  689. ratio: utils.formatPrice((100 * (theMost * (mid - i))) / mid / preClosePrice) + "%",
  690. };
  691. label[num - 1 - i] = {
  692. value: utils.formatPrice(preClosePrice - (theMost * (mid - i)) / mid),
  693. ratio: utils.formatPrice((-1 * 100 * (theMost * (mid - i))) / mid / preClosePrice) + "%",
  694. };
  695. }
  696. chartRange.value.push({
  697. max: preClosePrice + theMost,
  698. min: preClosePrice - theMost,
  699. });
  700. // timeChartObject.value.max = preClosePrice + theMost;
  701. // timeChartObject.value.min = preClosePrice - theMost;
  702. return label;
  703. } else {
  704. const highPriceRange = utils.calculateDataRange(data, "high");
  705. const lowPriceRange = utils.calculateDataRange(data, "low");
  706. const priceRange = {
  707. max: highPriceRange.max * 1.01,
  708. min: lowPriceRange.min * 0.99,
  709. };
  710. const priceDiff = priceRange.max - priceRange.min;
  711. for (let i = 0; i < num; ++i) {
  712. label[i] = {
  713. value: utils.formatPrice(priceRange.max - (i * priceDiff) / (num - 1)),
  714. };
  715. }
  716. chartRange.value.push(priceRange);
  717. // klineChartObject.value.max = highPriceRange.max * 1.01;
  718. // klineChartObject.value.min = lowPriceRange.min * 0.99;
  719. return label;
  720. }
  721. } else if (key === "volume") {
  722. const volumeRange = utils.calculateDataRange(data, "volume");
  723. chartRange.value.push({
  724. max: volumeRange.max,
  725. min: 0,
  726. });
  727. label[0] = {
  728. value: utils.formatPrice(volumeRange.max),
  729. };
  730. label[1] = {
  731. value: utils.formatPrice(0),
  732. };
  733. return label;
  734. }
  735. return null;
  736. },
  737. // 线性插值
  738. lerp(start, end, factor) {
  739. return start + (end - start) * factor;
  740. },
  741. // 根据X坐标找到最近的数据点
  742. findNearestDataPoint(x, pointLen, data, grid, offset) {
  743. if (!data.length) return null;
  744. const width = canvasWidth.value;
  745. const height = canvasHeight.value;
  746. // 计算每个数据点的X坐标间隔
  747. // 倒推 const x=5+(index*(width-10)/pointLen) 已知x求index
  748. const xStep = width - grid[0].left - grid[0].right;
  749. // 计算触摸点对应的数据索引
  750. const touchX = (x - grid[0].left - offset) * pointLen;
  751. let nearestIndex = Math.round(touchX / xStep);
  752. let dataX;
  753. // 确保索引在有效范围内
  754. if (nearestIndex >= 0 && nearestIndex <= data.length - 1) {
  755. dataX = offset + grid[0].left + (nearestIndex * (width - grid[0].left - grid[0].right)) / pointLen;
  756. } else {
  757. dataX = x;
  758. }
  759. nearestIndex = Math.max(0, Math.min(nearestIndex, data.length - 1));
  760. return {
  761. ...data[nearestIndex],
  762. index: nearestIndex,
  763. x: dataX,
  764. };
  765. },
  766. // 根据Y坐标计算价格
  767. calculatePriceFromY(y, data, grid) {
  768. if (!data.length) return 0;
  769. const width = canvasWidth.value;
  770. const height = canvasHeight.value;
  771. // 上下边距1
  772. const topPadding1 = 20;
  773. const bottomPadding1 = height * 0.4;
  774. // 上下边距2
  775. const topPadding2 = height - bottomPadding1 + 40;
  776. const bottomPadding2 = 5;
  777. // 左右边距
  778. const verticalPadding = 5;
  779. let chartY;
  780. let price;
  781. for (let i = 0; i < grid.length; i++) {
  782. if (y >= grid[i].top && y <= height - grid[i].bottom) {
  783. const chartDiff = chartRange.value[i].max - chartRange.value[i].min;
  784. chartY = y - grid[i].top;
  785. price = chartRange.value[i].max - (chartY / (height - grid[i].bottom - grid[i].top)) * chartDiff;
  786. break;
  787. }
  788. }
  789. // if (y >= topPadding1 && y <= height - bottomPadding1) {
  790. // const priceDiff = priceRange.max - priceRange.min;
  791. // chartY = y - topPadding1;
  792. // price = priceRange.max - (chartY / (height - topPadding1 - bottomPadding1)) * priceDiff;
  793. // } else if (y >= topPadding2 && y <= height - bottomPadding2) {
  794. // const volumeRange = utils.calculateDataRange(data, "volume");
  795. // const volumeDiff = volumeRange.max - 0;
  796. // chartY = y - topPadding2;
  797. // price = volumeRange.max - (chartY / (height - topPadding2 - bottomPadding2)) * volumeDiff;
  798. // }
  799. return price;
  800. },
  801. // 股市数值格式化方法
  802. formatStockNumber(value, decimalPlaces = 2) {
  803. const num = Number(value);
  804. if (isNaN(num)) return "0";
  805. const absNum = Math.abs(num);
  806. const sign = num < 0 ? "-" : "";
  807. if (absNum >= 1000000000000) {
  808. // 万亿级别
  809. return sign + (absNum / 1000000000000).toFixed(decimalPlaces) + "万亿";
  810. } else if (absNum >= 100000000) {
  811. // 亿级别
  812. return sign + (absNum / 100000000).toFixed(decimalPlaces) + "亿";
  813. } else if (absNum >= 10000) {
  814. // 万级别
  815. return sign + (absNum / 10000).toFixed(decimalPlaces) + "万";
  816. } else {
  817. // 小于万的直接显示
  818. return sign + absNum.toFixed(decimalPlaces);
  819. }
  820. },
  821. };
  822. let text = [
  823. [
  824. {
  825. name: "领先",
  826. value: "暂无数据",
  827. color: "red",
  828. },
  829. {
  830. name: "价",
  831. value: utils.formatPrice(stockInformation.value.currentPrice),
  832. color: "black",
  833. },
  834. ],
  835. [
  836. {
  837. name: "量",
  838. value: utils.formatStockNumber(stockInformation.value.volume),
  839. color: "green",
  840. },
  841. {
  842. name: "额",
  843. value: "暂无数据",
  844. color: "black",
  845. },
  846. ],
  847. ];
  848. // 示例数据
  849. const timeData = ref([]);
  850. const klineData = ref([]);
  851. const initCanvas = async () => {
  852. try {
  853. crosshair.show = false;
  854. grid[0].bottom = canvasHeight.value * 0.4;
  855. grid[1].top = canvasHeight.value * 0.6 + 30;
  856. dayGrid[0].top = 20;
  857. dayGrid[0].bottom = canvasHeight.value * 0.6;
  858. dayGrid[1].top = canvasHeight.value * 0.4 + 30;
  859. dayGrid[1].bottom = canvasHeight.value * 0.3;
  860. dayGrid[2].top = canvasHeight.value * 0.7 + 20;
  861. dayGrid[2].bottom = 20;
  862. // 等待DOM更新
  863. await nextTick();
  864. ctx.value = uni.createCanvasContext("stockChart", instance.proxy);
  865. // 初始化动态数据Canvas上下文
  866. dynamicCtx.value = uni.createCanvasContext("dynamicCanvas", instance.proxy);
  867. // 初始化十字准心Canvas上下文
  868. crosshairCtx.value = uni.createCanvasContext("crosshairCanvas", instance.proxy);
  869. if (ctx.value) {
  870. // 设置Canvas的内部绘图区域尺寸
  871. ctx.value.canvas = {
  872. width: canvasWidth.value,
  873. height: canvasHeight.value,
  874. };
  875. } else {
  876. console.warn("Canvas上下文未初始化,跳过绘制");
  877. }
  878. // 确保Canvas上下文知道正确的尺寸
  879. if (dynamicCtx.value) {
  880. // 设置Canvas的内部绘图区域尺寸
  881. dynamicCtx.value.canvas = {
  882. width: canvasWidth.value,
  883. height: canvasHeight.value,
  884. };
  885. } else {
  886. console.warn("动态Canvas上下文未初始化,跳过绘制");
  887. }
  888. if (crosshairCtx.value) {
  889. // 设置Canvas的内部绘图区域尺寸
  890. crosshairCtx.value.canvas = {
  891. width: canvasWidth.value,
  892. height: canvasHeight.value,
  893. };
  894. } else {
  895. console.warn("十字准心Canvas上下文未初始化,跳过绘制");
  896. }
  897. // 等待DOM更新
  898. await nextTick();
  899. console.log("ctx", ctx.value);
  900. drawChart();
  901. } catch (error) {
  902. console.error("初始化Canvas失败:", error);
  903. }
  904. };
  905. // 绘制图表主函数-设置基础数据
  906. const drawChart = () => {
  907. if (!ctx.value || !dynamicCtx.value || !crosshairCtx.value) {
  908. console.warn("Canvas上下文未初始化,跳过绘制");
  909. return;
  910. }
  911. const data = klineTab.value == 1 ? timeData.value : klineData.value;
  912. console.log("data", data);
  913. chartRange.value = [];
  914. // 清除画布
  915. // HCharts.setCanvasColor(ctx.value, width, height, CANVAS_BACKGROUND_COLOR);
  916. // HCharts.setCanvasColor(dynamicCtx.value, width, height, CANVAS_BACKGROUND_COLOR);
  917. // HCharts.setCanvasColor(crosshairCtx.value, width, height, CANVAS_BACKGROUND_COLOR);
  918. // 根据当前标签绘制对应图表
  919. if (klineTab.value == 1) {
  920. console.log("stockInfomaton.lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  921. // 设置标签样式
  922. const label = [
  923. {
  924. text: utils.calculateLabel(data, 1, stockInformation.value.lastDayStockClosePrice, "price", grid[0].horizontalLineNum),
  925. color: [TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR2],
  926. fontSize: 12,
  927. lineStyle: ["solid", "solid", "solid", "solid", "solid"],
  928. onlyTwo: false,
  929. },
  930. {
  931. text: utils.calculateLabel(data, 2, stockInformation.value.lastDayStockClosePrice, "volume", grid[1].horizontalLineNum),
  932. color: [TEXT_COLOR1, TEXT_COLOR1],
  933. lineStyle: ["solid", "solid", "solid"],
  934. fontSize: 12,
  935. onlyTwo: true,
  936. },
  937. ];
  938. // 把label加进grid中
  939. grid[0].label = label[0];
  940. grid[1].label = label[1];
  941. drawTimeChart();
  942. } else {
  943. // 设置标签样式
  944. const label = [
  945. {
  946. text: utils.calculateLabel(data, 2, stockInformation.value.lastDayStockClosePrice, "price", grid[0].horizontalLineNum),
  947. color: [TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR1, TEXT_COLOR2],
  948. lineStyle: ["solid", "dash", "dash", "dash", "solid"],
  949. fontSize: 12,
  950. onlyTwo: false,
  951. },
  952. {
  953. text: utils.calculateLabel(data, 2, stockInformation.value.lastDayStockClosePrice, "volume", grid[1].horizontalLineNum),
  954. color: [TEXT_COLOR1, TEXT_COLOR1],
  955. lineStyle: ["solid", "dash", "solid"],
  956. fontSize: 12,
  957. onlyTwo: true,
  958. },
  959. {
  960. text: utils.calculateLabel(data, 2, stockInformation.value.lastDayStockClosePrice, "volume", grid[1].horizontalLineNum),
  961. color: [TEXT_COLOR1, TEXT_COLOR1],
  962. lineStyle: ["solid", "dash", "solid"],
  963. fontSize: 12,
  964. onlyTwo: true,
  965. },
  966. ];
  967. // 把label加进grid中
  968. dayGrid[0].label = label[0];
  969. dayGrid[1].label = label[1];
  970. dayGrid[2].label = label[2];
  971. // HCharts.drawGrid(ctx.value, canvasWidth.value, canvasHeight.value, dayGrid, data[0].date, data[data.length - 1].date);
  972. drawKLineChart();
  973. }
  974. // crosshairCtx.value.draw();
  975. };
  976. const throttledDrawChart = throttle(drawChart, 50);
  977. // // 绘制分时图
  978. const drawTimeChart = () => {
  979. drawCtxChart(grid);
  980. drawDynamicCtxChart();
  981. };
  982. // // 绘制K线图
  983. const drawKLineChart = () => {
  984. drawCtxChart(dayGrid);
  985. drawDynamicCtxChart();
  986. };
  987. const drawCtxChart = (paramGrid) => {
  988. // 检查Canvas上下文是否已初始化
  989. if (!ctx.value) {
  990. console.warn("Canvas上下文未初始化,跳过绘制");
  991. return;
  992. }
  993. // 绘制网格
  994. HCharts.drawGrid(ctx.value, canvasWidth.value, canvasHeight.value, paramGrid, openTime, closeTime);
  995. //执行绘制
  996. ctx.value.draw();
  997. };
  998. const drawDynamicCtxChart = () => {
  999. if (klineTab.value == 1) {
  1000. //绘制价格曲线
  1001. HCharts.drawPriceLine(dynamicCtx.value, canvasWidth.value, canvasHeight.value, timeData.value, grid, chartRange.value[0]);
  1002. //绘制成交量
  1003. HCharts.drawVolume(
  1004. dynamicCtx.value,
  1005. canvasWidth.value,
  1006. canvasHeight.value,
  1007. timeData.value,
  1008. 2,
  1009. 240,
  1010. grid,
  1011. {
  1012. max: utils.calculateDataRange(timeData.value, "volume").max,
  1013. min: 0,
  1014. },
  1015. 0
  1016. );
  1017. HCharts.drawAxisLabels(dynamicCtx.value, canvasWidth.value, canvasHeight.value, grid);
  1018. HCharts.drawTopPriceDisplay(crosshairCtx.value, grid, text);
  1019. } else {
  1020. drawKLine(dynamicCtx.value);
  1021. //绘制成交量
  1022. HCharts.drawVolume(
  1023. dynamicCtx.value,
  1024. canvasWidth.value,
  1025. canvasHeight.value,
  1026. klineData.value,
  1027. 2,
  1028. klineData.value.length,
  1029. dayGrid,
  1030. {
  1031. max: utils.calculateDataRange(klineData.value, "volume").max,
  1032. min: 0,
  1033. },
  1034. touchState.offset
  1035. );
  1036. //绘制成交量
  1037. HCharts.drawVolume(
  1038. dynamicCtx.value,
  1039. canvasWidth.value,
  1040. canvasHeight.value,
  1041. klineData.value,
  1042. 3,
  1043. klineData.value.length,
  1044. dayGrid,
  1045. {
  1046. max: utils.calculateDataRange(klineData.value, "volume").max,
  1047. min: 0,
  1048. },
  1049. touchState.offset
  1050. );
  1051. HCharts.drawAxisLabels(dynamicCtx.value, canvasWidth.value, canvasHeight.value, dayGrid);
  1052. // drawMovingAverage();
  1053. HCharts.drawTopPriceDisplay(crosshairCtx.value, dayGrid, []);
  1054. }
  1055. //执行绘制
  1056. dynamicCtx.value.draw(false);
  1057. crosshairCtx.value.draw();
  1058. };
  1059. const throttledDrawDynamicCtxChart = throttle(drawDynamicCtxChart, 50);
  1060. // const throttledDrawKLineChart = throttle(drawKLineChart, 10);
  1061. // 绘制K线
  1062. const drawKLine = (ctx) => {
  1063. const data = klineData.value;
  1064. if (!data.length) return;
  1065. const width = canvasWidth.value;
  1066. const height = canvasHeight.value;
  1067. // 计算价格范围
  1068. const priceRange = chartRange.value[0];
  1069. const priceDiff = priceRange.max - priceRange.min;
  1070. const areaWidth = (width - dayGrid[0].left - dayGrid[0].right) / data.length;
  1071. const candleWidth = areaWidth * 0.6;
  1072. data.forEach((item, index) => {
  1073. const x = touchState.offset + dayGrid[0].left + (index * (width - dayGrid[0].left - dayGrid[0].right)) / data.length;
  1074. // 计算坐标
  1075. const highY = dayGrid[0].top + (height - dayGrid[0].top - dayGrid[0].bottom) * (1 - (item.high - priceRange.min) / priceDiff);
  1076. const lowY = dayGrid[0].top + (height - dayGrid[0].top - dayGrid[0].bottom) * (1 - (item.low - priceRange.min) / priceDiff);
  1077. const openY = dayGrid[0].top + (height - dayGrid[0].top - dayGrid[0].bottom) * (1 - (item.open - priceRange.min) / priceDiff);
  1078. const closeY = dayGrid[0].top + (height - dayGrid[0].top - dayGrid[0].bottom) * (1 - (item.close - priceRange.min) / priceDiff);
  1079. // 判断涨跌
  1080. const isRise = item.close >= item.open;
  1081. const color = isRise ? "green" : "red";
  1082. // 绘制上下影线
  1083. ctx.setStrokeStyle(color);
  1084. ctx.setLineWidth(1);
  1085. ctx.beginPath();
  1086. ctx.moveTo(x, highY);
  1087. ctx.lineTo(x, lowY);
  1088. ctx.stroke();
  1089. // 绘制K线实体
  1090. const entityTop = isRise ? closeY : openY;
  1091. const entityBottom = isRise ? openY : closeY;
  1092. const entityHeight = Math.max(Math.abs(entityBottom - entityTop), 1);
  1093. ctx.setFillStyle(color);
  1094. ctx.fillRect(x - candleWidth / 2, entityTop, candleWidth, entityHeight);
  1095. });
  1096. };
  1097. // 绘制移动平均线
  1098. const drawMovingAverage = () => {
  1099. const data = klineData.value;
  1100. if (!data.length) return;
  1101. const ma5 = calculateMA(data, 5);
  1102. const ma10 = calculateMA(data, 10);
  1103. drawMALine(ma5, "#fadb14", "MA5"); // 黄色
  1104. drawMALine(ma10, "#eb2f96", "MA10"); // 粉色
  1105. };
  1106. // 计算移动平均线
  1107. const calculateMA = (data, period) => {
  1108. const result = [];
  1109. for (let i = period - 1; i < data.length; i++) {
  1110. let sum = 0;
  1111. for (let j = 0; j < period; j++) {
  1112. sum += data[i - j].close;
  1113. }
  1114. result.push({
  1115. index: i,
  1116. value: sum / period,
  1117. });
  1118. }
  1119. return result;
  1120. };
  1121. // 绘制均线
  1122. const drawMALine = (maData, color, label) => {
  1123. if (!maData.length) return;
  1124. const width = canvasWidth.value;
  1125. const height = canvasHeight.value;
  1126. const data = klineData.value;
  1127. // 计算价格范围
  1128. const highs = data.map((item) => item.high);
  1129. const lows = data.map((item) => item.low);
  1130. const priceRange = chartRange.value[0];
  1131. const priceDiff = priceRange.max - priceRange.min;
  1132. ctx.value.setStrokeStyle(color);
  1133. ctx.value.setLineWidth(1.5);
  1134. ctx.value.beginPath();
  1135. maData.forEach((point, idx) => {
  1136. const x = 40 + (point.index * (width - 60)) / (data.length - 1);
  1137. const y = 20 + (height - 60) * (1 - (point.value - priceRange.min) / priceDiff);
  1138. if (idx === 0) {
  1139. ctx.value.moveTo(x, y);
  1140. } else {
  1141. ctx.value.lineTo(x, y);
  1142. }
  1143. });
  1144. ctx.value.stroke();
  1145. // 绘制图例
  1146. if (maData.length > 0) {
  1147. const lastPoint = maData[maData.length - 1];
  1148. const x = 40 + (lastPoint.index * (width - 60)) / (data.length - 1);
  1149. const y = 20 + (height - 60) * (1 - (lastPoint.value - priceRange.min) / priceDiff);
  1150. HCharts.drawText(ctx.value`${label}: ${utils.formatPrice(lastPoint.value)}`, x + 10, y - 5, 12, color);
  1151. }
  1152. };
  1153. // 触摸事件处理
  1154. const touchStart = (e) => {
  1155. e.preventDefault(); // 阻止页面滚动等默认行为
  1156. if (typeof e.touches[1] === "undefined") {
  1157. touchState.startX = e.touches[0].x;
  1158. touchState.startY = e.touches[0].y;
  1159. touchState.isMoving = false;
  1160. } else if (typeof e.touches[1] !== "undefined" && !crosshair.show) {
  1161. // touchState.startX1 = e.touches[0].x;
  1162. // touchState.startY1 = e.touches[0].y;
  1163. // touchState.startX2 = e.touches[1].x;
  1164. // touchState.startY2 = e.touches[1].y;
  1165. // touchState.isMoving = false;
  1166. }
  1167. };
  1168. const touchMove = (e) => {
  1169. touchState.isMoving = true;
  1170. // 计算移动距离
  1171. const currentX = e.touches[0].x;
  1172. const currentY = e.touches[0].y;
  1173. const deltaX = currentX - touchState.startX;
  1174. const deltaY = currentY - touchState.startY;
  1175. touchState.moveDistance = Math.max(touchState.moveDistance, Math.sqrt(deltaX * deltaX + deltaY * deltaY));
  1176. if (crosshair.show) {
  1177. if (isInChartArea(currentX, currentY, klineTab.value === 1 ? grid : dayGrid)) {
  1178. throttledUpdateCrosshair(currentX, currentY);
  1179. } else {
  1180. // 如果移出图表区域,隐藏十字准线
  1181. // crosshair.show = false;
  1182. if (klineTab.value === 1) {
  1183. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, grid, crosshair, text);
  1184. } else {
  1185. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, dayGrid, crosshair, []);
  1186. }
  1187. }
  1188. } else {
  1189. return;
  1190. if (klineTab.value === 2) {
  1191. // if(currentY)
  1192. if (currentX < touchState.startX) {
  1193. touchState.offset += currentX - touchState.startX;
  1194. throttledDrawDynamicCtxChart();
  1195. touchState.startX = currentX;
  1196. } else {
  1197. touchState.offset += currentX - touchState.startX;
  1198. throttledDrawDynamicCtxChart();
  1199. touchState.startX = currentX;
  1200. }
  1201. if (canvasWidth.value + touchState.offset < 30) {
  1202. touchState.offset = 0;
  1203. }
  1204. }
  1205. }
  1206. };
  1207. const touchEnd = (e) => {
  1208. // 触摸结束,隐藏十字准线
  1209. if (touchState.moveDistance < touchState.moveThreshold) {
  1210. // 移动距离小于阈值,认为是点击事件
  1211. crosshair.show = !crosshair.show;
  1212. }
  1213. if (crosshair.show) {
  1214. const currentX = e.changedTouches[0].x;
  1215. const currentY = e.changedTouches[0].y;
  1216. if (isInChartArea(currentX, currentY, klineTab.value === 1 ? grid : dayGrid)) {
  1217. throttledUpdateCrosshair(currentX, currentY);
  1218. }
  1219. }
  1220. if (klineTab.value === 1) {
  1221. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, grid, crosshair, text);
  1222. } else {
  1223. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, dayGrid, crosshair, []);
  1224. }
  1225. // 重置移动距离
  1226. touchState.moveDistance = 0;
  1227. };
  1228. // 检查坐标是否在图表区域内
  1229. const isInChartArea = (x, y, grid) => {
  1230. const width = canvasWidth.value;
  1231. const height = canvasHeight.value;
  1232. if (x < grid[0].left || x > width - grid[0].right) return false;
  1233. for (let i = 0; i < grid.length; i++) {
  1234. if (y >= grid[i].top && y <= height - grid[i].bottom) return true;
  1235. }
  1236. return false;
  1237. };
  1238. // 更新十字准线位置和数据
  1239. const updateCrosshair = (x, y) => {
  1240. if (!crosshair.show) return;
  1241. // 更新Y坐标以匹配实际价格
  1242. const data = klineTab.value === 1 ? timeData.value : klineData.value;
  1243. const width = canvasWidth.value;
  1244. const height = canvasHeight.value;
  1245. crosshair.x = x;
  1246. crosshair.y = y;
  1247. const nearestData = utils.findNearestDataPoint(x, klineTab.value === 1 ? 240 : data.length, data, klineTab.value === 1 ? grid : dayGrid, klineTab.value === 1 ? 0 : touchState.offset);
  1248. crosshair.x = nearestData.x;
  1249. stockInformation.value.currentPrice = nearestData.price || nearestData.close;
  1250. stockInformation.value.volume = nearestData.volume;
  1251. // 涨跌额度
  1252. if (klineTab.value == 1) {
  1253. stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
  1254. stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
  1255. } else {
  1256. stockInformation.value.openPrice = nearestData.open;
  1257. stockInformation.value.highPrice = nearestData.high;
  1258. stockInformation.value.lowPrice = nearestData.low;
  1259. if (nearestData.index != 0) {
  1260. stockInformation.value.lastDayStockClosePrice = data[nearestData.index - 1].close;
  1261. stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
  1262. stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
  1263. }
  1264. }
  1265. if (klineTab.value === 1 && crosshair.snapToData) {
  1266. // 吸附到最近的数据点
  1267. if (nearestData) {
  1268. crosshair.currentData = nearestData;
  1269. const priceDiff = chartRange.value[0].max - chartRange.value[0].min;
  1270. crosshair.y = grid[0].top + (height - grid[0].bottom - grid[0].top) * (1 - (nearestData.price - chartRange.value[0].min) / priceDiff);
  1271. }
  1272. } else {
  1273. // 自由移动模式
  1274. const currentPrice = utils.calculatePriceFromY(y, data, klineTab.value === 1 ? grid : dayGrid);
  1275. crosshair.currentData = {
  1276. ...nearestData,
  1277. price: currentPrice,
  1278. };
  1279. }
  1280. if (crosshair?.currentData?.volume) {
  1281. text[0][1].value = crosshair.currentData.price;
  1282. text[1][0].value = crosshair.currentData.volume;
  1283. }
  1284. // 只重绘十字准心,不重绘整个图表
  1285. if (klineTab.value === 1) {
  1286. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, grid, crosshair, text);
  1287. } else {
  1288. HCharts.drawCrosshair(crosshairCtx.value, canvasWidth.value, canvasHeight.value, dayGrid, crosshair, []);
  1289. }
  1290. };
  1291. const throttledUpdateCrosshair = throttle(updateCrosshair, 10);
  1292. // 缩放控制函数
  1293. const zoomIn = () => {
  1294. touchState.scale = Math.min(touchState.maxScale, touchState.scale * 1.2);
  1295. drawChart();
  1296. };
  1297. const zoomOut = () => {
  1298. touchState.scale = Math.max(touchState.minScale, touchState.scale / 1.2);
  1299. drawChart();
  1300. };
  1301. // 监听数据变化
  1302. // watch([timeData, klineData], () => {
  1303. // console.log("数据变化");
  1304. // drawChart();
  1305. // });
  1306. watch(klineTab, () => {
  1307. console.log("标签页变化");
  1308. drawChart();
  1309. });
  1310. // 初始化TCP监听器
  1311. const initTcpListeners = () => {
  1312. // 创建连接状态监听器并保存引用
  1313. connectionListener.value = (status, result) => {
  1314. tcpConnected.value = status === "connected";
  1315. console.log("TCP连接状态变化:", status, tcpConnected.value);
  1316. // 显示连接状态提示
  1317. uni.showToast({
  1318. title: status === "connected" ? "TCP连接成功" : "TCP连接断开",
  1319. icon: status === "connected" ? "success" : "none",
  1320. duration: 2000,
  1321. });
  1322. if (status === "connected") {
  1323. if (klineTab.value == 1) {
  1324. sendTcpMessage("init_real_time");
  1325. }
  1326. }
  1327. };
  1328. // 创建消息监听器并保存引用
  1329. messageListener.value = (type, message, parsedArray) => {
  1330. const messageObj = {
  1331. type: type,
  1332. content: message,
  1333. parsedArray: parsedArray,
  1334. timestamp: new Date().toLocaleTimeString(),
  1335. direction: "received",
  1336. };
  1337. // 解析股票数据
  1338. parseStockData(message);
  1339. };
  1340. // 注册监听器
  1341. tcpConnection.onConnectionChange(connectionListener.value);
  1342. tcpConnection.onMessage(messageListener.value);
  1343. };
  1344. // 连接TCP服务器
  1345. const connectTcp = () => {
  1346. console.log("开始连接TCP服务器...");
  1347. tcpConnection.connect();
  1348. };
  1349. // 断开TCP连接
  1350. const disconnectTcp = () => {
  1351. console.log("断开TCP连接...");
  1352. tcpConnection.disconnect();
  1353. tcpConnected.value = false;
  1354. };
  1355. // 发送TCP消息
  1356. const sendTcpMessage = (command) => {
  1357. let messageData;
  1358. switch (command) {
  1359. // 实时行情推送
  1360. case "real_time":
  1361. messageData = {
  1362. command: "real_time",
  1363. stock_code: "SH.000001",
  1364. };
  1365. break;
  1366. // 初始化获取行情历史数据
  1367. case "init_real_time":
  1368. messageData = {
  1369. command: "init_real_time",
  1370. stock_code: "SH.000001",
  1371. };
  1372. break;
  1373. case "stop_real_time":
  1374. messageData = {
  1375. command: "stop_real_time",
  1376. };
  1377. break;
  1378. // 股票列表
  1379. case "stock_list":
  1380. messageData = {
  1381. command: "stock_list",
  1382. };
  1383. break;
  1384. // 日线数据
  1385. case "daily_data":
  1386. messageData = {
  1387. command: "daily_data",
  1388. stock_code: "GBPAUD.FXCM",
  1389. start_date: "20250801",
  1390. end_date: "20251029",
  1391. };
  1392. break;
  1393. // 周线数据
  1394. case "weekly_data":
  1395. messageData = {
  1396. command: "weekly_data",
  1397. stock_code: "000001.SZ",
  1398. start_date: "2024912",
  1399. end_date: "20251029",
  1400. };
  1401. break;
  1402. // 周线数据
  1403. case "monthly_data":
  1404. messageData = {
  1405. command: "monthly_data",
  1406. stock_code: "000001.SZ",
  1407. start_date: "20201130",
  1408. end_date: "20251029",
  1409. };
  1410. break;
  1411. // 1分钟线数据
  1412. case "daily_one_minutes_data":
  1413. messageData = {
  1414. command: "daily_one_minutes_data",
  1415. stock_code: "000001.SZ",
  1416. };
  1417. break;
  1418. // 5分钟线数据
  1419. case "daily_five_minutes_data":
  1420. messageData = {
  1421. command: "daily_five_minutes_data",
  1422. stock_code: "000001.SZ",
  1423. };
  1424. break;
  1425. // 15分钟线数据
  1426. case "daily_fifteen_minutes_data":
  1427. messageData = {
  1428. command: "daily_fifteen_minutes_data",
  1429. stock_code: "000001.SZ",
  1430. };
  1431. break;
  1432. // 30分钟线数据
  1433. case "daily_thirty_minutes_data":
  1434. messageData = {
  1435. command: "daily_thirty_minutes_data",
  1436. stock_code: "000001.SZ",
  1437. };
  1438. break;
  1439. // 60分钟线数据
  1440. case "daily_sixty_minutes_data":
  1441. messageData = {
  1442. command: "daily_sixty_minutes_data",
  1443. stock_code: "000001.SZ",
  1444. };
  1445. break;
  1446. case "batch_real_time":
  1447. messageData = {
  1448. command: "batch_real_time",
  1449. stock_codes: ["SH.000001", "SH.000002", "SH.000003", "SH.000004", "SH.000005"],
  1450. };
  1451. break;
  1452. case "help":
  1453. messageData = {
  1454. command: "help",
  1455. };
  1456. break;
  1457. }
  1458. if (!messageData) {
  1459. uni.showToast({
  1460. title: "命令不存在",
  1461. icon: "none",
  1462. duration: 1000,
  1463. });
  1464. return;
  1465. } else {
  1466. try {
  1467. // 发送消息
  1468. const success = tcpConnection.send(messageData);
  1469. if (success) {
  1470. console.log("home发送TCP消息:", messageData);
  1471. uni.showToast({
  1472. title: "消息发送成功",
  1473. icon: "success",
  1474. duration: 1000,
  1475. });
  1476. }
  1477. } catch (error) {
  1478. console.error("发送TCP消息时出错:", error);
  1479. uni.showToast({
  1480. title: "消息发送失败",
  1481. icon: "none",
  1482. duration: 1000,
  1483. });
  1484. }
  1485. }
  1486. };
  1487. // 获取TCP连接状态
  1488. const getTcpStatus = () => {
  1489. const status = tcpConnection.getConnectionStatus();
  1490. uni.showModal({
  1491. title: "TCP连接状态",
  1492. content: `当前状态: ${status ? "已连接" : "未连接"}`,
  1493. showCancel: false,
  1494. });
  1495. };
  1496. let isMorePacket = {
  1497. init_real_time: false,
  1498. daily_data: false,
  1499. weekly_data: false,
  1500. monthly_data: false,
  1501. daily_one_minutes_data: false,
  1502. daily_five_minutes_data: false,
  1503. daily_fifteen_minutes_data: false,
  1504. daily_thirty_minutes_data: false,
  1505. daily_sixty_minutes_data: false,
  1506. };
  1507. let receivedMessage;
  1508. const findJsonPacket = (message, command) => {
  1509. let jsonStartIndex = 0;
  1510. let jsonEndIndex = message.indexOf(command);
  1511. let jsonStartCount = 0;
  1512. let jsonEndCount = 0;
  1513. for (let i = 0; i < message.length - 1; ++i) {
  1514. if (message[i] == "{") {
  1515. jsonStartCount++;
  1516. if (jsonStartCount == 2) {
  1517. jsonStartIndex = i;
  1518. break;
  1519. }
  1520. }
  1521. }
  1522. for (let i = message.indexOf(command); i >= 0; --i) {
  1523. if (message[i] == "}" || i == jsonStartIndex) {
  1524. jsonEndCount++;
  1525. if (jsonEndCount == 1) {
  1526. jsonEndIndex = i;
  1527. break;
  1528. }
  1529. }
  1530. }
  1531. // 检查JSON字符串是否有效
  1532. if (jsonStartIndex >= jsonEndIndex) {
  1533. return { error: true };
  1534. }
  1535. return { json: JSON.parse(message.substring(jsonStartIndex, jsonEndIndex + 1)) };
  1536. };
  1537. // 根据timeData中最后一个时间生成下一个时间
  1538. const generateNextTime = () => {
  1539. if (timeData.value.length === 0) {
  1540. return "09:30"; // 如果没有数据,返回开盘时间
  1541. }
  1542. const lastTime = timeData.value[timeData.value.length - 1].time;
  1543. if (!lastTime) {
  1544. return "09:30";
  1545. }
  1546. // 解析时间字符串,格式为 "HH:MM"
  1547. const [hours, minutes] = lastTime.split(":").map(Number);
  1548. // 计算下一分钟
  1549. let nextMinutes = minutes + 1;
  1550. let nextHours = hours;
  1551. // 处理分钟进位
  1552. if (nextMinutes >= 60) {
  1553. nextMinutes = 0;
  1554. nextHours += 1;
  1555. }
  1556. // 处理小时进位(24小时制)
  1557. if (nextHours >= 24) {
  1558. nextHours = 0;
  1559. }
  1560. // 格式化为 "HH:MM" 格式
  1561. const formattedHours = nextHours.toString().padStart(2, "0");
  1562. const formattedMinutes = nextMinutes.toString().padStart(2, "0");
  1563. return `${formattedHours}:${formattedMinutes}`;
  1564. };
  1565. // 解析TCP股票数据
  1566. const parseStockData = (message) => {
  1567. try {
  1568. console.log("进入parseStockData, message类型:", typeof message);
  1569. let parsedMessage;
  1570. // 如果isMorePacket是true,说明正在接受分包数据,无条件接收
  1571. // 如果message是字符串且以{开头,说明是JSON字符串,需要解析
  1572. // 如果不属于以上两种情况,说明是普通字符串,不预解析
  1573. if (message.includes("欢迎连接到股票数据服务器")) {
  1574. console.log("服务器命令列表,不予处理");
  1575. return;
  1576. }
  1577. if (message.includes("real_time")) {
  1578. let startIndex = 0;
  1579. let endIndex = message.length;
  1580. for (let i = 0; i < message.length - 1; ++i) {
  1581. if (message[i] == "{") {
  1582. startIndex = i;
  1583. break;
  1584. }
  1585. }
  1586. for (let i = message.length - 1; i >= 0; --i) {
  1587. if (message[i] == "}") {
  1588. endIndex = i;
  1589. break;
  1590. }
  1591. }
  1592. parsedMessage = JSON.parse(message.substring(startIndex, endIndex + 1));
  1593. console.log("实时数据解析", parsedMessage);
  1594. // 处理实时数据
  1595. timeData.value.push({
  1596. time: generateNextTime(),
  1597. price: parsedMessage.current_price,
  1598. volume: parsedMessage.volume,
  1599. amount: parsedMessage.amount,
  1600. });
  1601. // 实时更新股票信息
  1602. stockInformation.value.currentPrice = parsedMessage.current_price;
  1603. stockInformation.value.openPrice = parsedMessage.open_price;
  1604. stockInformation.value.closePrice = parsedMessage.close_price;
  1605. stockInformation.value.highPrice = parsedMessage.high_price;
  1606. stockInformation.value.lowPrice = parsedMessage.low_price;
  1607. stockInformation.value.volume = parsedMessage.volume;
  1608. stockInformation.value.amount = parsedMessage.amount;
  1609. stockInformation.value.turnoverRatio = parsedMessage.turnover_ratio;
  1610. stockInformation.value.marketValue = parsedMessage.total_market_value;
  1611. stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
  1612. stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
  1613. console.log("重绘画面");
  1614. drawChart();
  1615. if (timeData.value.length >= 240) {
  1616. sendTcpMessage("stop_real_time");
  1617. }
  1618. return;
  1619. } else if ((typeof message === "string" && message.includes("init_real_data_start")) || isMorePacket.init_real_time) {
  1620. if (typeof message === "string" && message.includes("init_real_data_start")) {
  1621. console.log("开始接受分包数据");
  1622. receivedMessage = "";
  1623. } else {
  1624. console.log("接收分包数据过程中");
  1625. }
  1626. isMorePacket.init_real_time = true;
  1627. receivedMessage += message;
  1628. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1629. if (receivedMessage.includes("init_real_data_complete")) {
  1630. console.log("接受分包数据结束");
  1631. isMorePacket.init_real_time = false;
  1632. console.log("展示数据", receivedMessage);
  1633. const result = findJsonPacket(receivedMessage, "init_real_data_complete");
  1634. if (result.error) {
  1635. throw new Error("解析JSON字符串失败");
  1636. } else {
  1637. parsedMessage = result.json;
  1638. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1639. if (parsedMessage.type === "daily_data") {
  1640. timeData.value = parsedMessage.data;
  1641. stockInformation.value.lastDayStockClosePrice = parsedMessage.pre_close;
  1642. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1643. drawChart();
  1644. sendTcpMessage("stop_real_time");
  1645. sendTcpMessage("real_time");
  1646. }
  1647. }
  1648. }
  1649. } else if ((typeof message === "string" && message.includes("daily_data_start")) || isMorePacket.daily_data) {
  1650. if (typeof message === "string" && message.includes("daily_data_start")) {
  1651. console.log("开始接受分包数据");
  1652. receivedMessage = "";
  1653. } else {
  1654. console.log("接收分包数据过程中");
  1655. }
  1656. isMorePacket.daily_data = true;
  1657. receivedMessage += message;
  1658. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1659. if (receivedMessage.includes("daily_data_complete")) {
  1660. console.log("接受分包数据结束");
  1661. isMorePacket.daily_data = false;
  1662. console.log("展示数据", receivedMessage);
  1663. const result = findJsonPacket(receivedMessage, "daily_data_complete");
  1664. if (result.error) {
  1665. throw new Error("解析JSON字符串失败");
  1666. } else {
  1667. parsedMessage = result.json;
  1668. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1669. if (parsedMessage.type === "daily_data") {
  1670. klineData.value = parsedMessage.data.map((item) => ({
  1671. open: item.ask_open,
  1672. close: item.ask_close,
  1673. high: item.ask_high,
  1674. low: item.ask_low,
  1675. volume: item.tick_qty,
  1676. date: item.trade_date ? `${item.trade_date.slice(0, 4)}-${item.trade_date.slice(4, 6)}-${item.trade_date.slice(6, 8)}` : item.trade_date,
  1677. }));
  1678. stockInformation.value.lastDayStockClosePrice = klineData.value[klineData.value.length - 2].close;
  1679. touchState.offset = canvasWidth.value / klineData.value.length / 2;
  1680. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1681. drawChart();
  1682. }
  1683. }
  1684. }
  1685. } else if ((typeof message === "string" && message.includes("weekly_data_start")) || isMorePacket.weekly_data) {
  1686. if (typeof message === "string" && message.includes("weekly_data_start")) {
  1687. console.log("开始接受分包数据");
  1688. receivedMessage = "";
  1689. } else {
  1690. console.log("接收分包数据过程中");
  1691. }
  1692. isMorePacket.weekly_data = true;
  1693. receivedMessage += message;
  1694. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1695. if (receivedMessage.includes("weekly_data_complete")) {
  1696. console.log("接受分包数据结束");
  1697. isMorePacket.weekly_data = false;
  1698. console.log("展示数据", receivedMessage);
  1699. const result = findJsonPacket(receivedMessage, "weekly_data_complete");
  1700. if (result.error) {
  1701. throw new Error("解析JSON字符串失败");
  1702. } else {
  1703. parsedMessage = result.json;
  1704. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1705. if (parsedMessage.type === "weekly_data") {
  1706. klineData.value = parsedMessage.data.map((item) => ({
  1707. open: item.bid_open,
  1708. close: item.bid_close,
  1709. high: item.bid_high,
  1710. low: item.bid_low,
  1711. volume: item.vol,
  1712. amount: item.amount,
  1713. date: item.trade_date ? `${item.trade_date.slice(0, 4)}-${item.trade_date.slice(4, 6)}-${item.trade_date.slice(6, 8)}` : item.trade_date,
  1714. }));
  1715. stockInformation.value.lastDayStockClosePrice = klineData.value[klineData.value.length - 2].close;
  1716. touchState.offset = canvasWidth.value / klineData.value.length / 2;
  1717. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1718. drawChart();
  1719. }
  1720. }
  1721. }
  1722. } else if ((typeof message === "string" && message.includes("monthly_data_start")) || isMorePacket.monthly_data) {
  1723. if (typeof message === "string" && message.includes("monthly_data_start")) {
  1724. console.log("开始接受分包数据");
  1725. receivedMessage = "";
  1726. } else {
  1727. console.log("接收分包数据过程中");
  1728. }
  1729. isMorePacket.monthly_data = true;
  1730. receivedMessage += message;
  1731. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1732. if (receivedMessage.includes("monthly_data_complete")) {
  1733. console.log("接受分包数据结束");
  1734. isMorePacket.monthly_data = false;
  1735. console.log("展示数据", receivedMessage);
  1736. const result = findJsonPacket(receivedMessage, "monthly_data_complete");
  1737. if (result.error) {
  1738. throw new Error("解析JSON字符串失败");
  1739. } else {
  1740. parsedMessage = result.json;
  1741. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1742. if (parsedMessage.type === "monthly_data") {
  1743. klineData.value = parsedMessage.data.map((item) => ({
  1744. open: item.bid_open,
  1745. close: item.bid_close,
  1746. high: item.bid_high,
  1747. low: item.bid_low,
  1748. volume: item.vol,
  1749. amount: item.amount,
  1750. date: item.trade_date ? `${item.trade_date.slice(0, 4)}-${item.trade_date.slice(4, 6)}-${item.trade_date.slice(6, 8)}` : item.trade_date,
  1751. }));
  1752. stockInformation.value.lastDayStockClosePrice = klineData.value[klineData.value.length - 2].close;
  1753. touchState.offset = canvasWidth.value / klineData.value.length / 2;
  1754. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1755. drawChart();
  1756. }
  1757. }
  1758. }
  1759. } else if ((typeof message === "string" && message.includes("daily_one_minutes_data_start")) || isMorePacket.daily_one_minutes_data) {
  1760. if (typeof message === "string" && message.includes("daily_one_minutes_data_start")) {
  1761. console.log("开始接受分包数据");
  1762. receivedMessage = "";
  1763. } else {
  1764. console.log("接收分包数据过程中");
  1765. }
  1766. isMorePacket.daily_one_minutes_data = true;
  1767. receivedMessage += message;
  1768. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1769. if (receivedMessage.includes("daily_one_minutes_data_complete")) {
  1770. console.log("接受分包数据结束");
  1771. isMorePacket.daily_one_minutes_data = false;
  1772. console.log("展示数据", receivedMessage);
  1773. const result = findJsonPacket(receivedMessage, "daily_one_minutes_data_complete");
  1774. if (result.error) {
  1775. throw new Error("解析JSON字符串失败");
  1776. } else {
  1777. parsedMessage = result.json;
  1778. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1779. if (parsedMessage.type === "daily_one_minutes_data") {
  1780. klineData.value = parsedMessage.data.map((item) => ({
  1781. open: item.open,
  1782. close: item.close,
  1783. high: Math.max(item.low, item.high),
  1784. low: Math.min(item.low, item.high),
  1785. volume: item.volume,
  1786. amount: item.amount,
  1787. date: item.timestamp,
  1788. }));
  1789. stockInformation.value.lastDayStockClosePrice = klineData.value[klineData.value.length - 2].close;
  1790. touchState.offset = canvasWidth.value / klineData.value.length / 2;
  1791. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1792. drawChart();
  1793. }
  1794. }
  1795. }
  1796. } else if ((typeof message === "string" && message.includes("daily_five_minutes_data_start")) || isMorePacket.daily_five_minutes_data) {
  1797. if (typeof message === "string" && message.includes("daily_five_minutes_data_start")) {
  1798. console.log("开始接受分包数据");
  1799. receivedMessage = "";
  1800. } else {
  1801. console.log("接收分包数据过程中");
  1802. }
  1803. isMorePacket.daily_five_minutes_data = true;
  1804. receivedMessage += message;
  1805. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1806. if (receivedMessage.includes("daily_five_minutes_data_complete")) {
  1807. console.log("接受分包数据结束");
  1808. isMorePacket.daily_five_minutes_data = false;
  1809. console.log("展示数据", receivedMessage);
  1810. const result = findJsonPacket(receivedMessage, "daily_five_minutes_data_complete");
  1811. if (result.error) {
  1812. throw new Error("解析JSON字符串失败");
  1813. } else {
  1814. parsedMessage = result.json;
  1815. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1816. if (parsedMessage.type === "daily_five_minutes_data") {
  1817. klineData.value = parsedMessage.data.map((item) => ({
  1818. open: item.open,
  1819. close: item.close,
  1820. high: Math.max(item.low, item.high),
  1821. low: Math.min(item.low, item.high),
  1822. volume: item.volume,
  1823. amount: item.amount,
  1824. date: item.timestamp,
  1825. }));
  1826. stockInformation.value.lastDayStockClosePrice = klineData.value[klineData.value.length - 2].close;
  1827. touchState.offset = canvasWidth.value / klineData.value.length / 2;
  1828. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1829. drawChart();
  1830. }
  1831. }
  1832. }
  1833. } else if ((typeof message === "string" && message.includes("daily_fifteen_minutes_data_start")) || isMorePacket.daily_fifteen_minutes_data) {
  1834. if (typeof message === "string" && message.includes("daily_fifteen_minutes_data_start")) {
  1835. console.log("开始接受分包数据");
  1836. receivedMessage = "";
  1837. } else {
  1838. console.log("接收分包数据过程中");
  1839. }
  1840. isMorePacket.daily_fifteen_minutes_data = true;
  1841. receivedMessage += message;
  1842. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1843. if (receivedMessage.includes("daily_fifteen_minutes_data_complete")) {
  1844. console.log("接受分包数据结束");
  1845. isMorePacket.daily_fifteen_minutes_data = false;
  1846. console.log("展示数据", receivedMessage);
  1847. const result = findJsonPacket(receivedMessage, "daily_fifteen_minutes_data_complete");
  1848. if (result.error) {
  1849. throw new Error("解析JSON字符串失败");
  1850. } else {
  1851. parsedMessage = result.json;
  1852. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1853. if (parsedMessage.type === "daily_fifteen_minutes_data") {
  1854. klineData.value = parsedMessage.data.map((item) => ({
  1855. open: item.open,
  1856. close: item.close,
  1857. high: Math.max(item.low, item.high),
  1858. low: Math.min(item.low, item.high),
  1859. volume: item.volume,
  1860. amount: item.amount,
  1861. date: item.timestamp,
  1862. }));
  1863. stockInformation.value.lastDayStockClosePrice = klineData.value[klineData.value.length - 2].close;
  1864. touchState.offset = canvasWidth.value / klineData.value.length / 2;
  1865. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1866. drawChart();
  1867. }
  1868. }
  1869. }
  1870. } else if ((typeof message === "string" && message.includes("daily_thirty_minutes_data_start")) || isMorePacket.daily_thirty_minutes_data) {
  1871. if (typeof message === "string" && message.includes("daily_thirty_minutes_data_start")) {
  1872. console.log("开始接受分包数据");
  1873. receivedMessage = "";
  1874. } else {
  1875. console.log("接收分包数据过程中");
  1876. }
  1877. isMorePacket.daily_thirty_minutes_data = true;
  1878. receivedMessage += message;
  1879. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1880. if (receivedMessage.includes("daily_thirty_minutes_data_complete")) {
  1881. console.log("接受分包数据结束");
  1882. isMorePacket.daily_thirty_minutes_data = false;
  1883. console.log("展示数据", receivedMessage);
  1884. const result = findJsonPacket(receivedMessage, "daily_thirty_minutes_data_complete");
  1885. if (result.error) {
  1886. throw new Error("解析JSON字符串失败");
  1887. } else {
  1888. parsedMessage = result.json;
  1889. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1890. if (parsedMessage.type === "daily_thirty_minutes_data") {
  1891. klineData.value = parsedMessage.data.map((item) => ({
  1892. open: item.open,
  1893. close: item.close,
  1894. high: Math.max(item.low, item.high),
  1895. low: Math.min(item.low, item.high),
  1896. volume: item.volume,
  1897. amount: item.amount,
  1898. date: item.timestamp,
  1899. }));
  1900. stockInformation.value.lastDayStockClosePrice = klineData.value[klineData.value.length - 2].close;
  1901. touchState.offset = canvasWidth.value / klineData.value.length / 2;
  1902. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1903. drawChart();
  1904. }
  1905. }
  1906. }
  1907. } else if ((typeof message === "string" && message.includes("daily_sixty_minutes_data_start")) || isMorePacket.daily_sixty_minutes_data) {
  1908. if (typeof message === "string" && message.includes("daily_sixty_minutes_data_start")) {
  1909. console.log("开始接受分包数据");
  1910. receivedMessage = "";
  1911. } else {
  1912. console.log("接收分包数据过程中");
  1913. }
  1914. isMorePacket.daily_sixty_minutes_data = true;
  1915. receivedMessage += message;
  1916. // 如果当前消息包含},说明收到JSON字符串结尾,结束接收,开始解析
  1917. if (receivedMessage.includes("daily_sixty_minutes_data_complete")) {
  1918. console.log("接受分包数据结束");
  1919. isMorePacket.daily_sixty_minutes_data = false;
  1920. console.log("展示数据", receivedMessage);
  1921. const result = findJsonPacket(receivedMessage, "daily_sixty_minutes_data_complete");
  1922. if (result.error) {
  1923. throw new Error("解析JSON字符串失败");
  1924. } else {
  1925. parsedMessage = result.json;
  1926. console.log("JSON解析成功,解析后类型:", typeof parsedMessage, parsedMessage);
  1927. if (parsedMessage.type === "daily_sixty_minutes_data") {
  1928. klineData.value = parsedMessage.data.map((item) => ({
  1929. open: item.open,
  1930. close: item.close,
  1931. high: Math.max(item.low, item.high),
  1932. low: Math.min(item.low, item.high),
  1933. volume: item.volume,
  1934. amount: item.amount,
  1935. date: item.timestamp,
  1936. }));
  1937. stockInformation.value.lastDayStockClosePrice = klineData.value[klineData.value.length - 2].close;
  1938. touchState.offset = canvasWidth.value / klineData.value.length / 2;
  1939. console.log("lastDayStockClosePrice", stockInformation.value.lastDayStockClosePrice);
  1940. drawChart();
  1941. }
  1942. }
  1943. }
  1944. } else {
  1945. // 没有通过JSON解析判断,说明不是需要的数据
  1946. console.log("不是需要的数据,不做处理");
  1947. }
  1948. } catch (error) {
  1949. console.error("解析TCP股票数据失败:", error.message);
  1950. console.error("错误详情:", error);
  1951. }
  1952. };
  1953. // 移除TCP监听器
  1954. const removeTcpListeners = () => {
  1955. if (connectionListener.value) {
  1956. tcpConnection.removeConnectionListener(connectionListener.value);
  1957. connectionListener.value = null;
  1958. console.log("已移除TCP连接状态监听器");
  1959. }
  1960. if (messageListener.value) {
  1961. tcpConnection.removeMessageListener(messageListener.value);
  1962. messageListener.value = null;
  1963. console.log("已移除TCP消息监听器");
  1964. }
  1965. };
  1966. // 定时器标识(用于清除定时器)
  1967. let timer = null;
  1968. let index = 0;
  1969. // 定时添加数据的函数
  1970. const startAddDataTimer = () => {
  1971. if (timer) {
  1972. console.log("存在旧定时器,卸载旧定时器");
  1973. clearInterval(timer);
  1974. }
  1975. console.log("开始定时任务");
  1976. // 每隔5秒执行一次
  1977. timer = setInterval(() => {
  1978. if (index < testTimeData.length) {
  1979. timeData.value.push(testTimeData[index]);
  1980. console.log("新增数据:", testTimeData[index]);
  1981. // 触发图表重新绘制
  1982. drawChart();
  1983. index++;
  1984. } else {
  1985. clearInterval(timer);
  1986. }
  1987. }, 2000); // 5000毫秒 = 5秒
  1988. };
  1989. onLoad((options) => {
  1990. console.log("页面接收到的参数:", options);
  1991. // 处理通过data参数传递的复杂对象
  1992. if (options.data) {
  1993. try {
  1994. const stockData = JSON.parse(decodeURIComponent(options.data));
  1995. console.log("解析的股票数据:", stockData);
  1996. // 更新stockInformation
  1997. if (stockData) {
  1998. stockInformation.value.stockName = stockData.stockName;
  1999. stockInformation.value.stockCode = stockData.stockCode;
  2000. }
  2001. } catch (error) {
  2002. console.error("解析股票数据失败:", error);
  2003. }
  2004. }
  2005. // 处理通过stockInformation参数传递的数据(兼容globalIndex.vue的传参方式)
  2006. if (options.stockInformation) {
  2007. try {
  2008. const stockData = JSON.parse(decodeURIComponent(options.stockInformation));
  2009. console.log("解析的股票信息:", stockData);
  2010. // 更新stockInformation
  2011. if (stockData) {
  2012. stockInformation.value = {
  2013. ...stockInformation.value,
  2014. ...stockData,
  2015. };
  2016. }
  2017. } catch (error) {
  2018. console.error("解析股票信息失败:", error);
  2019. }
  2020. }
  2021. // 处理简单参数
  2022. if (options.stockCode) {
  2023. stockInformation.value.stockCode = options.stockCode;
  2024. }
  2025. if (options.stockName) {
  2026. stockInformation.value.stockName = decodeURIComponent(options.stockName);
  2027. }
  2028. });
  2029. // 保存定时器,用于页面卸载时清理
  2030. onUnmounted(() => {
  2031. removeTcpListeners();
  2032. disconnect();
  2033. if (timer) {
  2034. console.log("卸载定时器");
  2035. clearInterval(timer);
  2036. }
  2037. });
  2038. onMounted(async () => {
  2039. try {
  2040. console.log("步骤1: 初始化系统信息");
  2041. const systemInfo = uni.getSystemInfoSync();
  2042. pixelRatio.value = systemInfo.pixelRatio;
  2043. // 设置Canvas实际像素(考虑pixelRatio以获得高清效果)
  2044. // 1rpx = 设备屏幕宽度 / 750
  2045. const rpxToPx = systemInfo.windowWidth / 750;
  2046. const offsetHeight = (150 + 200 + 80 + 150 + 30) * rpxToPx; // 350rpx转换为px
  2047. const calculatedHeight = systemInfo.windowHeight - offsetHeight;
  2048. canvasWidth.value = systemInfo.windowWidth;
  2049. canvasHeight.value = Math.max(calculatedHeight, canvasHeight.value);
  2050. initTcpListeners();
  2051. await nextTick();
  2052. // 开始连接
  2053. startTcp();
  2054. if (timeData.value && timeData.value.length > 0) {
  2055. // 当前股价
  2056. stockInformation.value.currentPrice = timeData.value[timeData.value.length - 1].price;
  2057. // 涨跌额度
  2058. stockInformation.value.currentValue = stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice;
  2059. // 涨跌幅度
  2060. stockInformation.value.currentRatio = ((stockInformation.value.currentPrice - stockInformation.value.lastDayStockClosePrice) / stockInformation.value.lastDayStockClosePrice) * 100;
  2061. // 成交量
  2062. stockInformation.value.volume = timeData.value[timeData.value.length - 1].volume;
  2063. text[0][1].value = utils.formatPrice(stockInformation.value.currentPrice);
  2064. text[1][0].value = utils.formatStockNumber(stockInformation.value.volume);
  2065. } else {
  2066. console.warn("没有时间数据,跳过股票信息计算");
  2067. }
  2068. await nextTick();
  2069. setTimeout(() => {
  2070. initCanvas();
  2071. }, 100);
  2072. console.log("所有初始化步骤完成");
  2073. } catch (error) {
  2074. console.error("初始化过程中出现错误:", error);
  2075. }
  2076. });
  2077. </script>
  2078. <style>
  2079. .container {
  2080. width: 100%;
  2081. min-height: 100vh;
  2082. background-color: #f6f6f6;
  2083. }
  2084. .title-container {
  2085. width: 100%;
  2086. height: 150rpx;
  2087. background-color: white;
  2088. display: flex;
  2089. flex-direction: column;
  2090. justify-content: flex-end;
  2091. }
  2092. .title {
  2093. /* border: 1px solid #ff0000; */
  2094. position: relative;
  2095. /* 关键:作为绝对定位的父容器 */
  2096. width: 100%;
  2097. height: 80rpx;
  2098. display: flex;
  2099. justify-content: center;
  2100. align-items: center;
  2101. }
  2102. .back-homepage-btn {
  2103. margin-left: 40rpx;
  2104. margin-right: auto;
  2105. height: 30rpx;
  2106. width: 20rpx;
  2107. z-index: 1;
  2108. }
  2109. .mid-title {
  2110. position: absolute;
  2111. left: 0;
  2112. right: 0;
  2113. display: flex;
  2114. justify-content: center;
  2115. align-items: center;
  2116. }
  2117. .left-page {
  2118. height: 40rpx;
  2119. width: 40rpx;
  2120. }
  2121. .right-page {
  2122. height: 40rpx;
  2123. width: 40rpx;
  2124. }
  2125. .stock-id {
  2126. margin: 0rpx 40rpx;
  2127. display: flex;
  2128. flex-direction: column;
  2129. text-align: center;
  2130. }
  2131. .stock-name {
  2132. font-weight: bold;
  2133. }
  2134. .stock-code {
  2135. font-size: 0.8rem;
  2136. font-weight: bold;
  2137. color: #a1a1a1;
  2138. }
  2139. .search {
  2140. height: 40rpx;
  2141. width: 40rpx;
  2142. }
  2143. .more {
  2144. height: 100%;
  2145. display: flex;
  2146. justify-content: center;
  2147. align-items: center;
  2148. margin-right: 40rpx;
  2149. margin-left: 20rpx;
  2150. }
  2151. .body {
  2152. overflow: auto;
  2153. height: calc(100vh - 305rpx);
  2154. /* border: 1px solid red; */
  2155. }
  2156. .stock-information {
  2157. background-color: white;
  2158. width: 100%;
  2159. height: 200rpx;
  2160. margin: 10rpx 0rpx;
  2161. display: flex;
  2162. align-items: center;
  2163. position: relative;
  2164. /* 为伪元素定位做准备 */
  2165. }
  2166. /* 右下角黑色三角形 */
  2167. .stock-information::after {
  2168. content: "";
  2169. position: absolute;
  2170. bottom: 0;
  2171. right: 0;
  2172. width: 0;
  2173. height: 0;
  2174. border-left: 20rpx solid transparent;
  2175. border-bottom: 20rpx solid #6a6a6a;
  2176. }
  2177. .stock-detail-container {
  2178. position: absolute;
  2179. top: 100%;
  2180. /* 在父容器下方 */
  2181. left: 0;
  2182. /* 从左边开始 */
  2183. right: 0;
  2184. /* 到右边结束 */
  2185. width: 100%;
  2186. /* height: 300rpx; 使用固定高度替代calc,避免计算问题 */
  2187. height: calc(100vh - 515rpx);
  2188. display: flex;
  2189. flex-direction: column;
  2190. background-color: rgba(0, 0, 0, 0.6);
  2191. z-index: 100;
  2192. box-sizing: border-box;
  2193. pointer-events: auto;
  2194. }
  2195. .stock-detail {
  2196. border: 1px solid #cacaca;
  2197. width: 100%;
  2198. display: flex;
  2199. background-color: white;
  2200. padding: 10rpx 0;
  2201. }
  2202. .first-column,
  2203. .second-column {
  2204. width: 50%;
  2205. height: 100%;
  2206. display: flex;
  2207. flex-direction: column;
  2208. color: #6a6a6a;
  2209. font-size: 0.8rem;
  2210. }
  2211. .first-column-data,
  2212. .second-column-data {
  2213. display: flex;
  2214. justify-content: space-between;
  2215. align-items: center;
  2216. padding: 10rpx 40rpx;
  2217. }
  2218. .stock-detail-title {
  2219. color: #6a6a6a;
  2220. }
  2221. .stock-detail-value {
  2222. color: black;
  2223. }
  2224. .price-up {
  2225. color: #10b981;
  2226. }
  2227. .price-down {
  2228. color: #ef4444;
  2229. }
  2230. .price-none {
  2231. color: black;
  2232. }
  2233. .stock-current-data {
  2234. width: 30%;
  2235. height: 70%;
  2236. display: flex;
  2237. flex-direction: column;
  2238. }
  2239. .stock-current-price {
  2240. font-weight: bold;
  2241. font-size: 1.2rem;
  2242. width: 100%;
  2243. height: 50%;
  2244. display: flex;
  2245. justify-content: center;
  2246. align-items: center;
  2247. }
  2248. .stock-current-other {
  2249. width: 100%;
  2250. height: 50%;
  2251. display: flex;
  2252. font-weight: bold;
  2253. font-size: 0.6rem;
  2254. }
  2255. .stock-current-value {
  2256. width: 50%;
  2257. height: 100%;
  2258. display: flex;
  2259. justify-content: center;
  2260. align-items: center;
  2261. }
  2262. .stock-current-ratio {
  2263. width: 50%;
  2264. height: 100%;
  2265. display: flex;
  2266. justify-content: center;
  2267. align-items: center;
  2268. }
  2269. .stock-other-data {
  2270. height: 100%;
  2271. width: 70%;
  2272. display: flex;
  2273. flex-direction: column;
  2274. }
  2275. .first-line,
  2276. .second-line,
  2277. .third-line {
  2278. display: flex;
  2279. align-items: center;
  2280. width: 100%;
  2281. height: 33%;
  2282. /* font-weight: bold; */
  2283. font-size: 0.8rem;
  2284. }
  2285. .value {
  2286. margin-left: auto;
  2287. margin-right: 20rpx;
  2288. }
  2289. .high-price,
  2290. .volume,
  2291. .volume-ratio,
  2292. .low-price,
  2293. .amount,
  2294. .market-earn,
  2295. .open-price,
  2296. .turnover-ratio,
  2297. .market-value {
  2298. display: flex;
  2299. flex: 1;
  2300. }
  2301. .stock-chart {
  2302. width: 100%;
  2303. }
  2304. .stock-kline-tab {
  2305. display: flex;
  2306. width: 100%;
  2307. height: 80rpx;
  2308. /* border: 1px solid black; */
  2309. }
  2310. .tab-day,
  2311. .tab-month,
  2312. .tab-time,
  2313. .tab-week,
  2314. .tab-more,
  2315. .tab-setting {
  2316. display: flex;
  2317. justify-content: center;
  2318. align-items: center;
  2319. flex: 1;
  2320. font-size: 0.8rem;
  2321. color: #6a6a6a;
  2322. position: relative;
  2323. }
  2324. /* 向下小三角样式 */
  2325. .arrow-down {
  2326. width: 0;
  2327. height: 0;
  2328. border-left: 10rpx solid transparent;
  2329. border-right: 10rpx solid transparent;
  2330. border-bottom: 12rpx solid currentColor;
  2331. margin-left: 8rpx;
  2332. display: inline-block;
  2333. }
  2334. .arrow-up {
  2335. width: 0;
  2336. height: 0;
  2337. border-left: 10rpx solid transparent;
  2338. border-right: 10rpx solid transparent;
  2339. border-top: 12rpx solid currentColor;
  2340. margin-left: 8rpx;
  2341. display: inline-block;
  2342. }
  2343. .arrow-left {
  2344. width: 0;
  2345. height: 0;
  2346. border-top: 10rpx solid transparent;
  2347. border-bottom: 10rpx solid transparent;
  2348. border-right: 12rpx solid currentColor;
  2349. margin-left: 8rpx;
  2350. display: inline-block;
  2351. }
  2352. .arrow-right {
  2353. width: 0;
  2354. height: 0;
  2355. border-top: 10rpx solid transparent;
  2356. border-bottom: 10rpx solid transparent;
  2357. border-left: 12rpx solid currentColor;
  2358. margin-left: 8rpx;
  2359. display: inline-block;
  2360. }
  2361. .moreTabsContainer {
  2362. width: 100%;
  2363. display: flex;
  2364. gap: 5rpx;
  2365. margin-bottom: 5rpx;
  2366. }
  2367. .moreTabItem {
  2368. flex: 1;
  2369. padding: 10rpx 20rpx;
  2370. border-radius: 10rpx;
  2371. background-color: white;
  2372. font-size: 0.85rem;
  2373. color: #6a6a6a;
  2374. text-align: center;
  2375. }
  2376. .tab-selected {
  2377. color: #db1f1d;
  2378. }
  2379. .tab-selected::after {
  2380. content: "";
  2381. position: absolute;
  2382. bottom: 10rpx;
  2383. left: 50%;
  2384. transform: translateX(-50%);
  2385. width: 40rpx;
  2386. height: 5rpx;
  2387. background-color: #db1f1d;
  2388. }
  2389. .tab-setting-img {
  2390. width: 30rpx;
  2391. height: 30rpx;
  2392. }
  2393. .time-chart-container {
  2394. width: 100%;
  2395. min-height: 400rpx;
  2396. background-color: #ffffff;
  2397. box-sizing: border-box;
  2398. }
  2399. .stock-chart {
  2400. display: flex;
  2401. flex-direction: column;
  2402. align-items: center;
  2403. }
  2404. .kline-chart-container {
  2405. width: 100%;
  2406. height: 400rpx;
  2407. background-color: #ffffff;
  2408. padding: 20rpx;
  2409. box-sizing: border-box;
  2410. display: flex;
  2411. justify-content: center;
  2412. align-items: center;
  2413. }
  2414. .bottomTool {
  2415. width: 100%;
  2416. height: 150rpx;
  2417. position: fixed;
  2418. bottom: 0;
  2419. background-color: white;
  2420. display: flex;
  2421. box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
  2422. }
  2423. .index,
  2424. .function,
  2425. .favorites {
  2426. flex: 1;
  2427. display: flex;
  2428. justify-content: center;
  2429. align-items: center;
  2430. flex-direction: column;
  2431. font-size: 12px;
  2432. transition: all 0.2s ease;
  2433. }
  2434. .index:active,
  2435. .function:active,
  2436. .favorites:active {
  2437. background-color: rgba(99, 99, 99, 0.5);
  2438. transform: scale(0.95);
  2439. transition: all 0.1s ease;
  2440. }
  2441. .icon {
  2442. width: 40rpx;
  2443. height: 40rpx;
  2444. }
  2445. </style>