k-line/test3.html
2024-12-11 09:52:47 +08:00

112 lines
3.2 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<script>
const API_URL = 'https://www.shidaotec.com/api/rank/getTop50StockList'
const stockCache = {
hold: [],
favorites: [],
china: [],
hk: [],
us: []
}
// 从服务器获取股票数据
async function fetchStocks (stockType) {
// 检查缓存
if (stockCache[stockType].length > 0) {
console.log('使用缓存数据:', stockType)
return stockCache[stockType] // 使用缓存
}
const stockTypeMapping = {
hold: { market: 'a', type: 2 },
favorites: { market: 'us', type: 2 },
china: { market: 'a', type: 1 },
hk: { market: 'hk', type: 1 },
us: { market: 'us', type: 1 }
}
const { market, type } = stockTypeMapping[stockType]
console.log(`请求的市场: ${market}, 类型: ${type}`)
try {
const response = await axios.get(API_URL, {
params: {
market: market,
stockPoolCode: 'None',
year: 'today',
type: type
}
})
console.log("响应数据: ", response.data)
if (response.data.code === 200 && response.data.data) {
const stockList = response.data.data
const stocks = stockList.map(stock => {
const price = parseFloat(stock.price)
const change = parseFloat(stock.change)
return {
stockName: stock.stockName,
formattedStockName: formatStockName(stock.stockName),
stockCode: stock.stockCode,
price: price,
change: change,
isPositiveChange: change > 0 // 新增属性判断涨跌幅是否大于0
}
})
stockCache[stockType] = stocks // 缓存结果
return stocks
} else {
throw new Error('Unexpected response format')
}
} catch (error) {
handleAxiosError(error)
throw new Error('无法获取股票数据')
}
}
// 辅助函数:格式化股票名称
function formatStockName (name) {
const maxLength = isFirstCharEnglish(name) ? 8 : 4
return name.length > maxLength
? name.substring(0, maxLength) + '...'
: name.padEnd(maxLength + 1, ' ')
}
// 辅助函数:判断名称的首字母是否为英文字符
function isFirstCharEnglish (name) {
return /^[A-Za-z]/.test(name)
}
// 错误处理函数
function handleAxiosError (error) {
if (axios.isAxiosError(error)) {
console.error('获取股票数据失败: ', error.response ? error.response.data : error.message)
} else if (error instanceof Error) {
console.error('获取股票数据失败: ', error.message)
} else {
console.error('获取股票数据失败: ', '未知错误')
}
}
fetchStocks('hold')
// K线图数据
// [open, close, lowest, highest] (即:[开盘值, 收盘值, 最低值, 最高值]
</script>
</body>
</html>