GamesPs.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. const axios = require('axios');
  2. const Logs = require('../libs/logs');
  3. const Setting = require('./Setting');
  4. const calcTotalProfit = require('../triangle/totalProfitCalc');
  5. const childOptions = process.env.NODE_ENV == 'development' ? {
  6. execArgv: ['--inspect=9228']
  7. } : {};
  8. const { fork } = require('child_process');
  9. const events_child = fork('./triangle/eventsMatch.js', [], childOptions);
  10. const PS_IOR_KEYS = [
  11. ['0', 'ior_mh', 'ior_mn', 'ior_mc'],
  12. // ['0', 'ior_rh_05', 'ior_mn', 'ior_rc_05'],
  13. ['-1', 'ior_rh_15', 'ior_wmh_1', 'ior_rac_05'],
  14. ['-2', 'ior_rh_25', 'ior_wmh_2', 'ior_rac_15'],
  15. ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  16. ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  17. ];
  18. const BASE_URL = 'https://api.isthe.me/api/p';
  19. const IS_DEV = process.env.NODE_ENV == 'development';
  20. const GAMES = {
  21. Leagues: {},
  22. List: {},
  23. Baselist: {},
  24. Relations: {},
  25. Solutions: {},
  26. };
  27. const Request = {
  28. callbacks: {},
  29. count: 0,
  30. }
  31. /**
  32. * 精确浮点数字
  33. * @param {number} number
  34. * @param {number} x
  35. * @returns {number}
  36. */
  37. const fixFloat = (number, x=2) => {
  38. return parseFloat(number.toFixed(x));
  39. }
  40. /**
  41. * 获取市场类型
  42. */
  43. const getMarketType = (mk) => {
  44. return mk == 0 ? 'early' : 'today';
  45. }
  46. /**
  47. * 同步联赛列表
  48. */
  49. const syncLeaguesList = ({ mk, leagues }) => {
  50. if (IS_DEV) {
  51. return Logs.out('syncLeaguesList', { mk, leagues });
  52. }
  53. axios.post(`${BASE_URL}/syncLeague`, { mk, leagues })
  54. .then(res => {
  55. Logs.out('syncLeaguesList', res.data);
  56. })
  57. .catch(err => {
  58. Logs.out('syncLeaguesList', err.message);
  59. });
  60. }
  61. /**
  62. * 更新联赛列表
  63. */
  64. const updateLeaguesList = ({ mk, leagues }) => {
  65. const leaguesList = GAMES.Leagues;
  66. if (JSON.stringify(leaguesList[mk]) != JSON.stringify(leagues)) {
  67. leaguesList[mk] = leagues;
  68. syncLeaguesList({ mk, leagues });
  69. return leagues.length;
  70. }
  71. return 0;
  72. }
  73. /**
  74. * 获取筛选过的联赛
  75. */
  76. const getFilteredLeagues = async (mk) => {
  77. return axios.get(`${BASE_URL}/getLeagueTast?mk=${mk}`)
  78. .then(res => {
  79. if (res.data.code == 0) {
  80. return res.data.data;
  81. }
  82. return Promise.reject(new Error(res.data.message));
  83. });
  84. }
  85. /**
  86. * 同步比赛列表到服务器
  87. */
  88. const syncGamesList = ({ platform, mk, games }) => {
  89. if (IS_DEV) {
  90. return Logs.out('syncGamesList', { platform, mk, games });
  91. }
  92. axios.post(`${BASE_URL}/syncGames`, { platform, mk, games })
  93. .then(res => {
  94. Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  95. })
  96. .catch(err => {
  97. Logs.out('syncGamesList', { platform, mk }, err.message);
  98. });
  99. }
  100. /**
  101. * 同步基准比赛列表
  102. */
  103. const syncBaseList = ({ marketType, games }) => {
  104. const baseList = GAMES.Baselist;
  105. if (!baseList[marketType]) {
  106. baseList[marketType] = games;
  107. }
  108. const newMap = new Map(games.map(item => [item.eventId, item]));
  109. // 删除不存在的项
  110. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  111. if (!newMap.has(baseList[marketType][i].eventId)) {
  112. baseList[marketType].splice(i, 1);
  113. }
  114. }
  115. // 添加或更新
  116. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  117. games.forEach(game => {
  118. if (!oldIds.has(game.eventId)) {
  119. // 添加新项
  120. baseList[marketType].push(game);
  121. }
  122. });
  123. }
  124. /**
  125. * 更新比赛列表
  126. */
  127. const updateGamesList = (({ platform, mk, games } = {}) => {
  128. return new Promise((resolve, reject) => {
  129. if (!platform || !games) {
  130. return reject(new Error('PLATFORM_GAMES_INVALID'));
  131. }
  132. const marketType = getMarketType(mk);
  133. syncGamesList({ platform, mk, games });
  134. if (platform == 'ps') {
  135. syncBaseList({ marketType, games });
  136. }
  137. resolve();
  138. });
  139. });
  140. /**
  141. * 提交盘口数据
  142. */
  143. const submitOdds = ({ platform, mk, games }) => {
  144. if (IS_DEV) {
  145. return Logs.out('syncOdds', { platform, mk, games });
  146. }
  147. axios.post(`${BASE_URL}/syncOdds`, { platform, mk, games})
  148. .then(res => {
  149. Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  150. })
  151. .catch(err => {
  152. Logs.out('syncOdds', { platform, mk }, err.message);
  153. });
  154. }
  155. /**
  156. * 同步基准盘口
  157. */
  158. const syncBaseEvents = ({ mk, games, outrights }) => {
  159. const marketType = getMarketType(mk);
  160. const baseList = GAMES.Baselist;
  161. if (!baseList[marketType]) {
  162. return;
  163. }
  164. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  165. games?.forEach(game => {
  166. const { eventId, evtime, events } = game;
  167. const baseGame = baseMap.get(eventId);
  168. if (baseGame) {
  169. baseGame.evtime = evtime;
  170. baseGame.events = events;
  171. }
  172. });
  173. outrights?.forEach(outright => {
  174. const { parentId, sptime, special } = outright;
  175. const baseGame = baseMap.get(parentId);
  176. if (baseGame) {
  177. baseGame.sptime = sptime;
  178. baseGame.special = special;
  179. }
  180. });
  181. if (games?.length) {
  182. const gamesList = baseList[marketType]?.map(game => {
  183. const { evtime, events, sptime, special, ...gameInfo } = game;
  184. const expireTime = Date.now() - 15000;
  185. let odds = {};
  186. if (evtime > expireTime) {
  187. odds = { ...odds, ...events };
  188. }
  189. if (sptime > expireTime) {
  190. odds = { ...odds, ...special };
  191. }
  192. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  193. const match = keys.map(key => ({
  194. key,
  195. value: odds[key] ?? 0
  196. }));
  197. return {
  198. label,
  199. match
  200. };
  201. }).filter(item => item.match.every(entry => entry.value !== 0));
  202. return { ...gameInfo, matches, uptime: Math.min(evtime ?? 0, sptime ?? 0) };
  203. });
  204. if (gamesList.filter(item => item.uptime > 0).length) {
  205. submitOdds({ platform: 'ps', mk, games: gamesList });
  206. }
  207. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  208. if (!relatedGames.length) {
  209. return 0;
  210. }
  211. let update = 0;
  212. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  213. gamesList?.forEach(game => {
  214. const { eventId, matches, uptime } = game;
  215. const relatedGame = relatedMap.get(eventId);
  216. if (relatedGame) {
  217. const events = {};
  218. matches.forEach(({ label, match }) => {
  219. match.forEach(({ key, value }) => {
  220. events[key] = value;
  221. });
  222. });
  223. relatedGame.evtime = uptime;
  224. relatedGame.events = events;
  225. update ++;
  226. }
  227. });
  228. return update;
  229. }
  230. }
  231. const updateGamesEvents = ({ platform, mk, games, outrights }) => {
  232. return new Promise((resolve, reject) => {
  233. if (!platform || (!games && !outrights)) {
  234. return reject(new Error('PLATFORM_GAMES_INVALID'));
  235. }
  236. if (platform == 'ps') {
  237. const update = syncBaseEvents({ mk, games, outrights });
  238. return resolve({ update });
  239. }
  240. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.[platform] ?? {});
  241. if (!relatedGames.length) {
  242. return resolve({ update: 0 });
  243. }
  244. const updateCount = {
  245. update: 0
  246. };
  247. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  248. games?.forEach(game => {
  249. const { eventId, evtime, events } = game;
  250. const relatedGame = relatedMap.get(eventId);
  251. if (relatedGame) {
  252. relatedGame.evtime = evtime;
  253. relatedGame.events = events;
  254. updateCount.update ++;
  255. }
  256. });
  257. outrights?.forEach(outright => {
  258. const { parentId, sptime, special } = outright;
  259. const relatedGame = relatedMap.get(parentId);
  260. if (relatedGame) {
  261. relatedGame.sptime = sptime;
  262. relatedGame.special = special;
  263. updateCount.update ++;
  264. }
  265. });
  266. resolve(updateCount);
  267. });
  268. }
  269. /**
  270. * 获取比赛盘口
  271. */
  272. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  273. if (!relIds.length) {
  274. return null;
  275. }
  276. const idSet = new Set(relIds);
  277. const relations = { ...GAMES.Relations };
  278. Object.keys(relations).forEach(id => {
  279. if (idSet.size && !idSet.has(+id)) {
  280. delete relations[id];
  281. }
  282. });
  283. if (platform) {
  284. return Object.values(relations).map(rel => rel[platform] ?? {});
  285. }
  286. const gamesEvents = {};
  287. Object.values(relations).forEach(({ rel }) => {
  288. Object.keys(rel).forEach(platform => {
  289. const game = rel[platform] ?? {};
  290. const { eventId, events, special } = game;
  291. if (!gamesEvents[platform]) {
  292. gamesEvents[platform] = {};
  293. }
  294. gamesEvents[platform][eventId] = { ...events, ...special };
  295. });
  296. });
  297. return gamesEvents;
  298. }
  299. /**
  300. * 获取关联比赛
  301. */
  302. const fetchGamesRelation = async (mk='') => {
  303. return axios.get(`${BASE_URL}/getGameTast?mk=${mk}`)
  304. .then(res => {
  305. if (res.data.code == 0) {
  306. const now = Date.now();
  307. const gamesRelation = res.data.data?.filter(item => {
  308. const timestamp = new Date(item.timestamp).getTime();
  309. item.timestamp = timestamp;
  310. return timestamp > now;
  311. }).map(item => {
  312. const {
  313. id, mk, league_name,
  314. event_id: ps_event_id,
  315. league_id: ps_league_id,
  316. team_home_name: ps_team_home_name,
  317. team_away_name: ps_team_away_name,
  318. ob_event_id, ob_league_id,
  319. ob_team_home_name,
  320. ob_team_away_name,
  321. hg_event_id, hg_league_id,
  322. hg_team_home_name,
  323. hg_team_away_name,
  324. timestamp,
  325. } = item;
  326. const rel = {
  327. ps: {
  328. eventId: +ps_event_id,
  329. leagueId: +ps_league_id,
  330. leagueName: league_name,
  331. teamHomeName: ps_team_home_name,
  332. teamAwayName: ps_team_away_name,
  333. timestamp
  334. },
  335. ob: ob_event_id ? {
  336. eventId: +ob_event_id,
  337. leagueId: +ob_league_id,
  338. leagueName: league_name,
  339. teamHomeName: ob_team_home_name,
  340. teamAwayName: ob_team_away_name,
  341. timestamp
  342. } : null,
  343. hg: hg_event_id ? {
  344. eventId: +hg_event_id,
  345. leagueId: +hg_league_id,
  346. leagueName: league_name,
  347. teamHomeName: hg_team_home_name,
  348. teamAwayName: hg_team_away_name,
  349. timestamp
  350. } : null
  351. };
  352. return { id: ps_event_id, mk, rel };
  353. }) ?? [];
  354. return gamesRelation;
  355. }
  356. return Promise.reject(new Error(res.data.message));
  357. });
  358. }
  359. const getGamesRelation = ({ mk, listEvents } = {}) => {
  360. const relations = Object.values(GAMES.Relations).filter(item => {
  361. if (typeof(mk) == 'undefined') {
  362. return true;
  363. }
  364. return item.mk == mk;
  365. });
  366. if (listEvents) {
  367. return relations;
  368. }
  369. const gamesRelation = relations.map(item => {
  370. const { rel, ...relationInfo } = item;
  371. const tempRel = { ...rel };
  372. Object.keys(tempRel).forEach(platform => {
  373. const { events, evtime, sptime, special, ...gameInfo } = tempRel[platform];
  374. tempRel[platform] = gameInfo;
  375. });
  376. return { ...relationInfo, rel: tempRel };
  377. });
  378. return gamesRelation;
  379. }
  380. /**
  381. * 定时更新关联比赛列表
  382. */
  383. const updateGamesRelation = () => {
  384. fetchGamesRelation()
  385. .then(res => {
  386. const gamesRelation = res.flat();
  387. const updateCount = {
  388. add: 0,
  389. delete: 0
  390. };
  391. gamesRelation.forEach(item => {
  392. const { id } = item;
  393. if (!GAMES.Relations[id]) {
  394. GAMES.Relations[id] = item;
  395. updateCount.add ++;
  396. }
  397. });
  398. const relations = new Set(gamesRelation.map(item => +item.id));
  399. Object.keys(GAMES.Relations).forEach(id => {
  400. if (!relations.has(+id)) {
  401. delete GAMES.Relations[id];
  402. updateCount.delete ++;
  403. }
  404. });
  405. Logs.out('updateGamesRelation', updateCount);
  406. })
  407. .catch(err => {
  408. Logs.out('updateGamesRelation', err.message);
  409. })
  410. .finally(() => {
  411. setTimeout(updateGamesRelation, 60000);
  412. });
  413. }
  414. updateGamesRelation();
  415. /**
  416. * 同步比赛结果
  417. */
  418. const syncGamesResult = async (result) => {
  419. if (IS_DEV) {
  420. return Logs.out('updateGamesResult', result);
  421. }
  422. axios.post(`${BASE_URL}/syncMatchResult`, result)
  423. .then(res => {
  424. Logs.out('syncMatchResult', res.data);
  425. })
  426. .catch(err => {
  427. Logs.out('syncMatchResult', err.message);
  428. });
  429. }
  430. /**
  431. * 更新比赛结果
  432. */
  433. const updateGamesResult = (result) => {
  434. syncGamesResult(result);
  435. return Promise.resolve();
  436. }
  437. /**
  438. * 同步中单方案
  439. */
  440. const syncSolutions = (solutions) => {
  441. if (IS_DEV) {
  442. return Logs.out('syncSolutions', solutions);
  443. }
  444. axios.post(`${BASE_URL}/syncDsOpportunity`, solutions)
  445. .then(res => {
  446. Logs.out('syncSolutions', res.data);
  447. })
  448. .catch(err => {
  449. Logs.out('syncSolutions', err.message);
  450. });
  451. }
  452. /**
  453. * 更新中单方案
  454. */
  455. const getCprKey = (cpr) => {
  456. const { k, p, v } = cpr;
  457. return `${k}_${p}_${v}`;
  458. }
  459. const compareCpr = (cpr1, cpr2) => {
  460. const key1 = getCprKey(cpr1);
  461. const key2 = getCprKey(cpr2);
  462. return key1 === key2;
  463. }
  464. const updateSolutions = (solutions) => {
  465. if (solutions?.length) {
  466. const solutionsHistory = GAMES.Solutions;
  467. const updateIds = { add: [], update: [] }
  468. solutions.forEach(item => {
  469. const { sid, cpr, sol: { win_average } } = item;
  470. if (!solutionsHistory[sid]) {
  471. solutionsHistory[sid] = item;
  472. updateIds.add.push(sid);
  473. return;
  474. }
  475. const historySolution = solutionsHistory[sid];
  476. if (historySolution.sol.win_average !== win_average || !compareCpr(historySolution.cpr, cpr)) {
  477. solutionsHistory[sid] = item;
  478. updateIds.update.push(sid);
  479. return;
  480. }
  481. const { timestamp } = item;
  482. solutionsHistory[sid].timestamp = timestamp;
  483. });
  484. if (updateIds.add.length || updateIds.update.length) {
  485. const solutionUpdate = {};
  486. Object.keys(updateIds).forEach(key => {
  487. solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  488. });
  489. syncSolutions(solutionUpdate);
  490. // Logs.outDev('solutions history update', solutionUpdate);
  491. }
  492. }
  493. }
  494. /**
  495. * 获取中单方案
  496. */
  497. const getSolutions = async () => {
  498. const solutionsList = Object.values(GAMES.Solutions);
  499. const relIds = solutionsList.map(item => item.info.id);
  500. const gamesEvents = getGamesEvents({ relIds });
  501. const gamesRelation = getGamesRelation();
  502. const relationsMap = new Map(gamesRelation.map(item => [item.id, item.rel]));
  503. const solutions = solutionsList.sort((a, b) => b.sol.win_average - a.sol.win_average).map(item => {
  504. const { info: { id } } = item;
  505. const relation = relationsMap.get(id);
  506. return {
  507. ...item,
  508. info: { id, ...relation }
  509. }
  510. });
  511. return { solutions, gamesEvents };
  512. }
  513. /**
  514. * 清理中单方案
  515. */
  516. const solutionsCleanup = () => {
  517. const solutionsHistory = GAMES.Solutions;
  518. const updateIds = { remove: [] }
  519. Object.keys(solutionsHistory).forEach(sid => {
  520. const { timestamp } = solutionsHistory[sid];
  521. const nowTime = Date.now();
  522. if (nowTime - timestamp > 1000*60) {
  523. delete solutionsHistory[sid];
  524. updateIds.remove.push(sid);
  525. return;
  526. }
  527. const solution = solutionsHistory[sid];
  528. const eventTime = solution.info.timestamp;
  529. if (nowTime > eventTime) {
  530. delete solutionsHistory[sid];
  531. updateIds.remove.push(sid);
  532. }
  533. });
  534. if (updateIds.remove.length) {
  535. syncSolutions(updateIds);
  536. }
  537. }
  538. /**
  539. * 定时清理中单方案
  540. */
  541. setInterval(() => {
  542. solutionsCleanup();
  543. }, 1000*30);
  544. /**
  545. * 获取综合利润
  546. */
  547. const getTotalProfit = async (sid1, sid2, gold_side_inner) => {
  548. const preSolution = GAMES.Solutions[sid1];
  549. const subSolution = GAMES.Solutions[sid2];
  550. const sol1 = preSolution?.sol;
  551. const sol2 = subSolution?.sol;
  552. if (!sol1 || !sol2) {
  553. return Promise.reject(new Error('SOLUTION_ID_INVALID'));
  554. }
  555. if (!gold_side_inner) {
  556. return Promise.reject(new Error('GOLD_SIDE_INNER_INVALID'));
  557. }
  558. const { innerRebateRatio: rebate_side_inner } = await getSetting();
  559. const profit = calcTotalProfit(sol1, sol2, gold_side_inner, rebate_side_inner);
  560. return { profit, solutions: [preSolution, subSolution] };
  561. }
  562. /**
  563. * 获取后台设置
  564. */
  565. const getSetting = async () => {
  566. return Setting.get();
  567. }
  568. /**
  569. * 从子进程获取数据
  570. */
  571. const getDataFromChild = (type, callback) => {
  572. const id = ++Request.count;
  573. Request.callbacks[id] = callback;
  574. events_child.send({ method: 'get', id, type });
  575. }
  576. /**
  577. * 处理子进程消息
  578. */
  579. events_child.on('message', async (message) => {
  580. const { callbacks } = Request;
  581. const { method, id, type, data } = message;
  582. if (method == 'get' && id) {
  583. let responseData = null;
  584. if (type == 'getGamesRelation') {
  585. responseData = getGamesRelation({ listEvents: true });
  586. }
  587. else if (type == 'getSetting') {
  588. responseData = await getSetting();
  589. }
  590. // else if (type == 'getSolutionHistory') {
  591. // responseData = getSolutionHistory();
  592. // }
  593. events_child.send({ type: 'response', id, data: responseData });
  594. }
  595. else if (method == 'post') {
  596. if (type == 'updateSolutions') {
  597. updateSolutions(data);
  598. }
  599. }
  600. else if (method == 'response' && id && callbacks[id]) {
  601. callbacks[id](data);
  602. delete callbacks[id];
  603. }
  604. });
  605. module.exports = {
  606. updateLeaguesList, getFilteredLeagues,
  607. updateGamesList, updateGamesEvents,
  608. getGamesRelation,
  609. updateGamesResult,
  610. getSolutions,
  611. getTotalProfit,
  612. }