Skip to content

Commit

Permalink
Merge pull request #412 from tlff/stock
Browse files Browse the repository at this point in the history
feat: 增加股票收益计算
  • Loading branch information
giscafer authored Jan 31, 2024
2 parents c1f1919 + aba2446 commit e3dfb07
Show file tree
Hide file tree
Showing 11 changed files with 1,637 additions and 666 deletions.
54 changes: 54 additions & 0 deletions .vscode/bookmarks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"files": [
{
"path": "src/registerCommand.ts",
"bookmarks": [
{
"line": 37,
"column": 0,
"label": ""
},
{
"line": 257,
"column": 2,
"label": ""
}
]
},
{
"path": "src/explorer/stockService.ts",
"bookmarks": [
{
"line": 66,
"column": 2,
"label": ""
}
]
},
{
"path": "src/extension.ts",
"bookmarks": [
{
"line": 221,
"column": 1,
"label": ""
},
{
"line": 222,
"column": 2,
"label": ""
}
]
},
{
"path": "src/statusbar/Profit.ts",
"bookmarks": [
{
"line": 77,
"column": 1,
"label": ""
}
]
}
]
}
21 changes: 20 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "leek-fund",
"displayName": "韭菜盒子",
"description": "韭菜盒子,VSCode 里也可以看股票 & 基金实时数据,做最好用的投资插件",
"version": "3.6.1",
"version": "3.6.2",
"author": "giscafer <[email protected]>",
"repository": {
"type": "git",
Expand Down Expand Up @@ -171,6 +171,14 @@
"title": "添加股票",
"icon": "$(add)"
},
{
"command": "leek-fund.setStockPrice",
"title": "设置股票成本价",
"icon": {
"light": "resources/light/amount.svg",
"dark": "resources/dark/amount.svg"
}
},
{
"command": "leek-fund.leekCenterView",
"title": "韭菜中心",
Expand Down Expand Up @@ -339,6 +347,11 @@
"when": "view == leekFundView.stock",
"group": "navigation"
},
{
"command": "leek-fund.setStockPrice",
"when": "view == leekFundView.stock",
"group": "navigation"
},
{
"command": "leek-fund.refreshFollow",
"when": "view == leekFundView.news",
Expand Down Expand Up @@ -506,6 +519,11 @@
],
"description": "配置需要监控的股票代码(建议通过界面新增)"
},
"leek-fund.stockPrice": {
"type": "object",
"default": {},
"description": "股票持仓金额(不建议手填,格式错误影响功能)"
},
"leek-fund.funds": {
"type": "array",
"default": [
Expand Down Expand Up @@ -744,6 +762,7 @@
"@types/ws": "^7.4.0",
"@typescript-eslint/eslint-plugin": "^2.30.0",
"@typescript-eslint/parser": "^2.30.0",
"cross-env": "^7.0.3",
"eslint": "^6.8.0",
"glob": "^7.1.6",
"husky": "^4.3.0",
Expand Down
59 changes: 40 additions & 19 deletions src/explorer/stockService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default class StockService extends LeekService {
const res = await Axios.get('https://xueqiu.com/');
const cookies: string[] = res.headers['set-cookie'];

const param: string = cookies.filter(key => key.includes('xq_a_token'))[0] || '';
const param: string = cookies.filter((key) => key.includes('xq_a_token'))[0] || '';
this.token = param.split(';')[0] || '';

return this.token;
Expand Down Expand Up @@ -59,7 +59,10 @@ export default class StockService extends LeekService {
});

let stockList: Array<LeekTreeItem> = [];
const result = await Promise.allSettled([this.getStockData(stockCodes), this.getHKStockData(hkCodes)]);
const result = await Promise.allSettled([
this.getStockData(stockCodes),
this.getHKStockData(hkCodes),
]);
result.forEach((item) => {
if (item.status === 'fulfilled') {
stockList = stockList.concat(item.value);
Expand All @@ -70,6 +73,7 @@ export default class StockService extends LeekService {
executeStocksRemind(res, this.stockList);
const oldStockList = this.stockList;
this.stockList = res;
events.emit('updateBar:stock-profit-refresh', this);
events.emit('stockListUpdate', this.stockList, oldStockList);
return res;
}
Expand Down Expand Up @@ -104,7 +108,9 @@ export default class StockService extends LeekService {
});
if (/FAILED/.test(resp.data)) {
if (codes.length === 1) {
window.showErrorMessage(`fail: error Stock code in ${codes}, please delete error Stock code.`);
window.showErrorMessage(
`fail: error Stock code in ${codes}, please delete error Stock code.`
);
return [];
}
for (const code of codes) {
Expand Down Expand Up @@ -215,15 +221,15 @@ export default class StockService extends LeekService {
let yestclose = params[8 + 2];
let volume = params[8 + 6]; // 成交量
//股指期货
const stockIndexFuture = /nf_IC/.test(code) // 中证500
|| /nf_IF/.test(code) // 沪深300
|| /nf_IH/.test(code) // 上证50
|| /nf_IM/.test(code) // 中证 1000
|| /nf_TF/.test(code) // 五债
|| /nf_TS/.test(code) // 二债
|| /nf_T\d+/.test(code) // 十债
|| /nf_TL/.test(code) // 三十年国债
;
const stockIndexFuture =
/nf_IC/.test(code) || // 中证500
/nf_IF/.test(code) || // 沪深300
/nf_IH/.test(code) || // 上证50
/nf_IM/.test(code) || // 中证 1000
/nf_TF/.test(code) || // 五债
/nf_TS/.test(code) || // 二债
/nf_T\d+/.test(code) || // 十债
/nf_TL/.test(code); // 三十年国债
if (stockIndexFuture) {
// 0 开盘 1 最高 2 最低 3 收盘
// ['5372.000', '5585.000', '5343.000', '5581.600',
Expand Down Expand Up @@ -390,7 +396,9 @@ export default class StockService extends LeekService {
});
const { data, error_code, error_description } = resp.data;
if (error_code) {
window.showErrorMessage(`fail: a HK Stock request error has occured. (${error_code}, ${error_description})`);
window.showErrorMessage(
`fail: a HK Stock request error has occured. (${error_code}, ${error_description})`
);
return [];
} else {
const stocks = data.items || [];
Expand All @@ -404,7 +412,9 @@ export default class StockService extends LeekService {
let low = quote.low?.toString() || '0';
const fixedNumber = calcFixedPriceNumber(open, yestclose, price, high, low);
const stockItem: any = {
code: quote.symbol.startsWith('HK') ? quote.symbol.replace('HK', 'hk') : 'hk' + quote.symbol,
code: quote.symbol.startsWith('HK')
? quote.symbol.replace('HK', 'hk')
: 'hk' + quote.symbol,
name: quote.name,
open: formatNumber(open, fixedNumber, false),
yestclose: formatNumber(yestclose, fixedNumber, false),
Expand Down Expand Up @@ -437,7 +447,9 @@ export default class StockService extends LeekService {
stockList.push(treeItem);
}
} else {
window.showErrorMessage(`fail: error Stock code in ${codes[index]}, please delete error Stock code.`);
window.showErrorMessage(
`fail: error Stock code in ${codes[index]}, please delete error Stock code.`
);
}
});
}
Expand Down Expand Up @@ -467,11 +479,17 @@ export default class StockService extends LeekService {
const result: QuickPickItem[] = [];

// 期货大写字母开头
const isFuture = /^[A-Z]/.test(searchText[0]) || /nf_/.test(searchText) || /hf_/.test(searchText) || /fx_/.test(searchText);
const isFuture =
/^[A-Z]/.test(searchText[0]) ||
/nf_/.test(searchText) ||
/hf_/.test(searchText) ||
/fx_/.test(searchText);
if (isFuture) {
//期货使用新浪数据源
const type = '85,86,88';
const futureUrl = `http://suggest3.sinajs.cn/suggest/type=${type}&key=${encodeURIComponent(searchText)}`;
const futureUrl = `http://suggest3.sinajs.cn/suggest/type=${type}&key=${encodeURIComponent(
searchText
)}`;
try {
console.log('getFutureSuggestList: getting...');
const futureResponse = await Axios.get(futureUrl, {
Expand Down Expand Up @@ -532,7 +550,9 @@ export default class StockService extends LeekService {
}
} else {
//股票使用雪球数据源
const stockUrl = `https://xueqiu.com/stock/search.json?code=${encodeURIComponent(searchText)}`;
const stockUrl = `https://xueqiu.com/stock/search.json?code=${encodeURIComponent(
searchText
)}`;
try {
console.log('getStockSuggestList: getting...');
const stockResponse = await Axios.get(stockUrl, {
Expand All @@ -558,7 +578,8 @@ export default class StockService extends LeekService {
label: `${_code} | ${name}`,
description: `A股`,
});
} else if (/^0\d{4}$/.test(code) || /^HK[A-Z].*/.test(code)) { // 港股个股 || 港股指数
} else if (/^0\d{4}$/.test(code) || /^HK[A-Z].*/.test(code)) {
// 港股个股 || 港股指数
const _code = code.startsWith('HK') ? code.replace('HK', 'hk') : 'hk' + code;
result.push({
label: `${_code} | ${name}`,
Expand Down
7 changes: 5 additions & 2 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { StatusBar } from './statusbar/statusBar';
import { ProfitStatusBar } from './statusbar/Profit';
import { cacheStocksRemindData } from './webview/leekCenterView';
import { cacheFundAmountData, updateAmount } from './webview/setAmount';
import { cacheStockPriceData, updateStockPrice } from './webview/setStockPrice';
import FlashNewsOutputServer from './output/flash-news/FlashNewsOutputServer';
import { ForexService } from './explorer/forexService';
import { ForexProvider } from './explorer/forexProvider';
Expand All @@ -40,7 +41,6 @@ let flashNewsOutputServer: FlashNewsOutputServer | null = null;
let profitBar: ProfitStatusBar | null = null;

export function activate(context: ExtensionContext) {

globalState.isDevelopment = process.env.NODE_ENV === 'development';
globalState.context = context;

Expand All @@ -57,6 +57,7 @@ export function activate(context: ExtensionContext) {

setGlobalVariable();
updateAmount();
updateStockPrice();

flashNewsOutputServer = new FlashNewsOutputServer();

Expand Down Expand Up @@ -211,13 +212,15 @@ export function activate(context: ExtensionContext) {
);

// register command
registerCommandPaletteEvent(context, statusBar,);
registerCommandPaletteEvent(context, statusBar);

// Telemetry Event
telemetry.sendEvent('activate');
}

function setGlobalVariable() {
const stockPrice = LeekFundConfig.getConfig('leek-fund.stockPrice') || {};
cacheStockPriceData(stockPrice);
globalState.iconType = LeekFundConfig.getConfig('leek-fund.iconType') || 'arrow';

const fundAmount = LeekFundConfig.getConfig('leek-fund.fundAmount') || {};
Expand Down
7 changes: 6 additions & 1 deletion src/globalState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Telemetry } from './shared/telemetry';

const deviceId = Math.random().toString(16).substr(2) + Math.random().toString(32).substr(2);

let context: ExtensionContext = (undefined as unknown) as ExtensionContext;
let context: ExtensionContext = undefined as unknown as ExtensionContext;

let telemetry: Telemetry | any = null;

Expand Down Expand Up @@ -36,6 +36,8 @@ let isDevelopment = false; // 是否开发环境
let fundGroups: Array<string> = [];
let fundLists: Array<Array<string>> = [];

let stockPrice = {}; // 缓存数据
let stockPriceCacheDate = '2020-10-30';
export default {
context,
telemetry,
Expand Down Expand Up @@ -65,4 +67,7 @@ export default {
isDevelopment,
fundGroups,
fundLists,

stockPrice,
stockPriceCacheDate,
};
10 changes: 10 additions & 0 deletions src/registerCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import fundTrend from './webview/fundTrend';
import leekCenterView from './webview/leekCenterView';
import openNews from './webview/news';
import setAmount from './webview/setAmount';
import setStockPrice from './webview/setStockPrice';

import stockTrend from './webview/stockTrend';
import stockTrendPic from './webview/stockTrendPic';
import tucaoForum from './webview/tucaoForum';
Expand Down Expand Up @@ -251,6 +253,14 @@ export function registerViewEvent(
}
setAmount(fundService);
});
// 设置股票成本价
commands.registerCommand('leek-fund.setStockPrice', () => {
if (stockService.stockList.length === 0) {
window.showWarningMessage('数据刷新中,请重试!');
return;
}
setStockPrice(stockService);
});
commands.registerCommand('leek-fund.stockTrendPic', (target) => {
const { code, name, type, symbol } = target.info;
stockTrendPic(code, name, `${type}${symbol}`);
Expand Down
Loading

0 comments on commit e3dfb07

Please sign in to comment.