GamesPs.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. const axios = require('axios');
  2. const Logs = require('../libs/logs');
  3. const Cache = require('../libs/cache');
  4. const Setting = require('./Setting');
  5. const { eventSolutions } = require('../triangle/eventSolutions');
  6. const { getPassableEvents, eventsCombination } = require('../triangle/trangleCalc');
  7. const { calcTotalProfit, calcTotalProfitWithFixedFirst, getFirstInfo } = require('../triangle/totalProfitCalc');
  8. const { getSetting, updateSetting } = require('../triangle/settings');
  9. const fs = require('fs');
  10. const path = require('path');
  11. const GamesCacheFile = path.join(__dirname, '../data/games.cache');
  12. const childOptions = process.env.NODE_ENV == 'development' ? {
  13. execArgv: ['--inspect=9230'],
  14. stdio: ['pipe', 'pipe', 'pipe', 'ipc']
  15. } : {};
  16. const { fork } = require('child_process');
  17. const events_child = fork('./triangle/eventsMatch.js', [], childOptions);
  18. const PS_IOR_KEYS = [
  19. ['0', 'ior_mh', 'ior_mn', 'ior_mc'],
  20. ['-1', 'ior_rh_15', 'ior_wmh_1', 'ior_rac_05'],
  21. ['-2', 'ior_rh_25', 'ior_wmh_2', 'ior_rac_15'],
  22. ['-3', 'ior_rh_35', 'ior_wmh_3', 'ior_rac_25'],
  23. // ['-4', 'ior_rh_45', 'ior_wmh_4', 'ior_rac_35'],
  24. // ['-5', 'ior_rh_55', 'ior_wmh_5', 'ior_rac_45'],
  25. ['+1', 'ior_rah_05', 'ior_wmc_1', 'ior_rc_15'],
  26. ['+2', 'ior_rah_15', 'ior_wmc_2', 'ior_rc_25'],
  27. ['+3', 'ior_rah_25', 'ior_wmc_3', 'ior_rc_35'],
  28. // ['+4', 'ior_rah_35', 'ior_wmc_4', 'ior_rc_45'],
  29. // ['+5', 'ior_rah_45', 'ior_wmc_5', 'ior_rc_55'],
  30. ['ou', 'ior_ouc_05', 'ior_ouh_05', 'ior_ouc_15', 'ior_ouh_15', 'ior_ouc_25', 'ior_ouh_25', 'ior_ouc_35', 'ior_ouh_35'],
  31. ['jqs', 'ior_ot_1', 'ior_ot_2', 'ior_ot_3', 'ior_ot_4', 'ior_ot_5', /*'ior_ot_6', 'ior_ot_7'*/],
  32. ];
  33. const IOR_KEYS_TYPE = {
  34. A: 1, L: 1, R: 1,
  35. D: 2, K: 2, P: 2,
  36. }
  37. // 测试环境
  38. // const BASE_API_URL = 'https://dev.api.czxd8.com/api/p';
  39. const IS_DEV = process.env.NODE_ENV == 'development';
  40. const BASE_API_URL = IS_DEV ? 'https://cb.long.bid/qbapi' : 'http://172.17.222.37/api';
  41. const GAMES = {
  42. Leagues: {},
  43. Baselist: {},
  44. Relations: {},
  45. Solutions: {},
  46. ObOriginalData: {},
  47. UpdateTimestamp: {},
  48. };
  49. const Request = {
  50. callbacks: {},
  51. count: 0,
  52. }
  53. /**
  54. * 精确浮点数字
  55. * @param {number} number
  56. * @param {number} x
  57. * @returns {number}
  58. */
  59. const fixFloat = (number, x=2) => {
  60. return parseFloat(number.toFixed(x));
  61. }
  62. /**
  63. * 获取市场类型
  64. */
  65. const getMarketType = (mk) => {
  66. if (mk == 0) {
  67. return 'early';
  68. }
  69. else if (mk == 2) {
  70. return 'rollball';
  71. }
  72. return 'today';
  73. }
  74. /**
  75. * 获取策略类型
  76. */
  77. const getRuleType = (rule) => {
  78. const rulePrefix = rule.split(':')[0];
  79. return IOR_KEYS_TYPE[rulePrefix];
  80. }
  81. /**
  82. * 关键词匹配比赛
  83. */
  84. const matchGame = (relation, sk) => {
  85. const keys = [];
  86. Object.keys(relation).forEach(platform => {
  87. if (!relation[platform]) {
  88. return;
  89. }
  90. const { leagueName, teamHomeName, teamAwayName } = relation[platform];
  91. if (platform == 'ps') {
  92. keys.push(leagueName);
  93. }
  94. keys.push(teamHomeName, teamAwayName);
  95. });
  96. return keys.some(key => key?.includes(sk));
  97. }
  98. /**
  99. * 同步联赛列表
  100. */
  101. const syncLeaguesList = ({ mk, leagues }) => {
  102. if (IS_DEV) {
  103. return Logs.out('syncLeaguesList', { mk, leagues });
  104. }
  105. axios.post(`${BASE_API_URL}/p/syncLeague`, { mk, leagues }, { proxy: false })
  106. .then(res => {
  107. // Logs.out('syncLeaguesList', res.data);
  108. })
  109. .catch(err => {
  110. Logs.out('syncLeaguesList', err.message);
  111. });
  112. }
  113. /**
  114. * 更新联赛列表
  115. */
  116. const updateLeaguesList = ({ mk, leagues, platform='ps' }) => {
  117. const { Leagues } = GAMES;
  118. if (!Leagues[platform]) {
  119. Leagues[platform] = {};
  120. }
  121. const leaguesMap = Leagues[platform];
  122. const nowTime = Date.now();
  123. const expireTime = nowTime - 1000 * 60 * 5;
  124. if (!leaguesMap[mk]) {
  125. leaguesMap[mk] = {
  126. timestamp: 0,
  127. leagues: [],
  128. };
  129. }
  130. if (leaguesMap[mk].timestamp < expireTime ||
  131. JSON.stringify(leaguesMap[mk].leagues) != JSON.stringify(leagues)) {
  132. leaguesMap[mk].leagues = leagues;
  133. leaguesMap[mk].timestamp = nowTime;
  134. if (platform == 'ps') {
  135. syncLeaguesList({ mk, leagues });
  136. }
  137. return leagues.length;
  138. }
  139. return 0;
  140. }
  141. /**
  142. * 获取筛选过的联赛
  143. */
  144. const getFilteredLeagues = async (mk) => {
  145. return axios.get(`${BASE_API_URL}/p/getLeagueTast?mk=${mk ?? ''}`, { proxy: false })
  146. .then(res => {
  147. // Logs.out('getFilteredLeagues', res.data);
  148. if (res.data.code == 0) {
  149. return res.data.data;
  150. }
  151. return Promise.reject(new Error(res.data.message));
  152. });
  153. }
  154. /**
  155. * 更新OB原始数据
  156. */
  157. const updateOriginalData = ({ leagues, matches }) => {
  158. const { ObOriginalData } = GAMES;
  159. ObOriginalData.leagues = leagues;
  160. ObOriginalData.matches = matches;
  161. ObOriginalData.timestamp = Date.now();
  162. }
  163. /**
  164. * 获取OB原始数据
  165. */
  166. const getOriginalData = () => {
  167. const { ObOriginalData } = GAMES;
  168. return ObOriginalData;
  169. }
  170. /**
  171. * 同步比赛列表到服务器
  172. */
  173. const syncGamesList = ({ platform, mk, games }) => {
  174. if (IS_DEV) {
  175. return Logs.out('syncGamesList', { platform, mk, games });
  176. }
  177. axios.post(`${BASE_API_URL}/p/syncGames`, { platform, mk, games })
  178. .then(res => {
  179. // Logs.out('syncGamesList', { platform, mk, count: games.length }, res.data);
  180. })
  181. .catch(err => {
  182. Logs.out('syncGamesList', { platform, mk }, err.message);
  183. });
  184. }
  185. /**
  186. * 同步基准比赛列表
  187. */
  188. const syncBaseList = ({ marketType, games }) => {
  189. const baseList = GAMES.Baselist;
  190. // 直接创建新列表
  191. if (!baseList[marketType]) {
  192. baseList[marketType] = games;
  193. return;
  194. }
  195. const newMap = new Map(games.map(item => [item.eventId, item]));
  196. // 删除不存在的项
  197. for (let i = baseList[marketType].length - 1; i >= 0; i--) {
  198. if (!newMap.has(baseList[marketType][i].eventId)) {
  199. baseList[marketType].splice(i, 1);
  200. }
  201. }
  202. // 添加或更新
  203. const oldIds = new Set(baseList[marketType].map(item => item.eventId));
  204. games.forEach(game => {
  205. if (!oldIds.has(game.eventId)) {
  206. // 添加新项
  207. baseList[marketType].push(game);
  208. }
  209. });
  210. }
  211. /**
  212. * 清理基准比赛列表
  213. */
  214. // const cleanupBaseList = () => {
  215. // const baseList = GAMES.Baselist;
  216. // const nowTime = Date.now();
  217. // const expireTime = nowTime - 1000*60*60*3;
  218. // Object.keys(baseList).forEach(marketType => {
  219. // baseList[marketType] = baseList[marketType].filter(item => item.timestamp < expireTime);
  220. // });
  221. // }
  222. /**
  223. * 更新比赛列表
  224. */
  225. const updateGamesList = (({ platform, mk, games } = {}) => {
  226. return new Promise((resolve, reject) => {
  227. if (!platform || !games) {
  228. return reject(new Error('PLATFORM_GAMES_INVALID'));
  229. }
  230. syncGamesList({ platform, mk, games });
  231. resolve();
  232. });
  233. });
  234. /**
  235. * 提交盘口数据
  236. */
  237. // const submitOdds = ({ platform, mk, games }) => {
  238. // if (IS_DEV) {
  239. // return Logs.out('syncOdds', { platform, mk, games });
  240. // }
  241. // axios.post(`${BASE_API_URL}/p/syncOdds`, { platform, mk, games}, { proxy: false })
  242. // .then(res => {
  243. // // Logs.out('syncOdds', { platform, mk, count: games.length }, res.data);
  244. // })
  245. // .catch(err => {
  246. // Logs.out('syncOdds', { platform, mk }, err.message);
  247. // });
  248. // }
  249. /**
  250. * 同步基准盘口
  251. */
  252. const syncBaseEvents = ({ mk, games, outrights }) => {
  253. const {
  254. expireTimeEvents, expireTimeSpecial,
  255. innerRouSubsidyValue, innerWmSubsidyRatio, innerOtSubsidyRatio,
  256. innerOuMinValue,
  257. } = getSetting();
  258. const nowTime = Date.now();
  259. const marketType = getMarketType(mk);
  260. const baseList = GAMES.Baselist;
  261. if (!baseList[marketType]) {
  262. return 0;
  263. }
  264. const baseMap = new Map(baseList[marketType].map(item => [item.eventId, item]));
  265. games?.forEach(game => {
  266. const { eventId, originId, stage, retime, score, wm, evtime, events } = game;
  267. const baseGame = baseMap.get(eventId);
  268. if (baseGame) {
  269. Object.keys(events).forEach(ior => {
  270. const regRm = /^ior_(r|mh|mc)/;
  271. const regWm = /^ior_(wm|mn)/;
  272. const regOu = /^ior_ou/;
  273. const regOt = /^ior_ot/;
  274. // 胜负/让胜负/大小球调水(数值)
  275. if ((regRm.test(ior) || regOu.test(ior)) && innerRouSubsidyValue) {
  276. const sourceOdds = events[ior].v;
  277. events[ior].v = fixFloat(sourceOdds + innerRouSubsidyValue, 3);
  278. events[ior].s = sourceOdds;
  279. }
  280. // 平局/让平调水(%)
  281. else if (regWm.test(ior) && innerWmSubsidyRatio) {
  282. const sourceOdds = events[ior].v;
  283. events[ior].v = fixFloat(sourceOdds * (1 + innerWmSubsidyRatio / 100), 3);
  284. events[ior].s = sourceOdds;
  285. }
  286. // 进球数调水(%)
  287. else if (regOt.test(ior) && innerOtSubsidyRatio) {
  288. const sourceOdds = events[ior].v;
  289. events[ior].v = fixFloat(sourceOdds * (1 + innerOtSubsidyRatio / 100), 3);
  290. events[ior].s = sourceOdds;
  291. }
  292. // 大小球最低赔率
  293. if (regOu.test(ior) && innerOuMinValue) {
  294. const sourceOdds = events[ior].s ?? events[ior].v ?? 1;
  295. events[ior].q = sourceOdds < innerOuMinValue ? 0 : 1;
  296. }
  297. });
  298. baseGame.originId = originId;
  299. baseGame.stage = stage;
  300. baseGame.retime = retime;
  301. baseGame.score = score;
  302. baseGame.wm = wm;
  303. baseGame.evtime = evtime;
  304. baseGame.events = events;
  305. }
  306. });
  307. // 浏览器采集特殊盘口用的
  308. // outrights?.forEach(outright => {
  309. // const { parentId, sptime, special } = outright;
  310. // const baseGame = baseMap.get(parentId);
  311. // if (baseGame) { // 赛前特殊盘口
  312. // const { timestamp } = baseGame;
  313. // const isSubsidy = timestamp > nowTime && timestamp < nowTime + 1000*60*60*subsidyTime;
  314. // if (isSubsidy) {
  315. // Object.keys(special).forEach(ior => {
  316. // if (ior.startsWith('ior_ot') && subsidyAmount) {
  317. // const sourceOdds = special[ior].v;
  318. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyAmount), 3);
  319. // special[ior].s = sourceOdds
  320. // }
  321. // });
  322. // }
  323. // baseGame.sptime = sptime;
  324. // baseGame.special = special;
  325. // }
  326. // else {
  327. // const originBaseMap = new Map(baseList[marketType].map(item => [item.originId, item]));
  328. // const originBaseGame = originBaseMap.get(parentId);
  329. // if (originBaseGame) { // 滚球特殊盘口
  330. // Object.keys(special).forEach(ior => {
  331. // if (ior.startsWith('ior_wm') && subsidyRbWmAmount) {
  332. // const sourceOdds = special[ior].v;
  333. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbWmAmount), 3);
  334. // special[ior].s = sourceOdds
  335. // }
  336. // else if (ior.startsWith('ior_ot') && subsidyRbOtAmount) {
  337. // const sourceOdds = special[ior].v;
  338. // special[ior].v = fixFloat(sourceOdds * (1 + subsidyRbOtAmount), 3);
  339. // special[ior].s = sourceOdds
  340. // }
  341. // });
  342. // originBaseGame.sptime = sptime;
  343. // originBaseGame.special = special;
  344. // }
  345. // }
  346. // });
  347. if (games?.length) {
  348. const gamesList = baseList[marketType]?.map(game => {
  349. const { evtime, events, sptime, special, ...gameInfo } = game;
  350. const expireTimeEv = nowTime - expireTimeEvents;
  351. const expireTimeSP = nowTime - expireTimeSpecial;
  352. let odds = {};
  353. if (evtime > expireTimeEv) {
  354. odds = { ...odds, ...events };
  355. }
  356. if (sptime > expireTimeSP) {
  357. odds = { ...odds, ...special };
  358. }
  359. const matches = PS_IOR_KEYS.map(([label, ...keys]) => {
  360. let match = keys.map(key => {
  361. let value = odds[key]?.v ?? 0;
  362. return {
  363. key, value,
  364. origin: odds[key]?.r,
  365. source: odds[key]?.s,
  366. qualified: odds[key]?.q ?? 1,
  367. };
  368. });
  369. if (label == 'jqs' || label == 'ou') {
  370. match = match.filter(item => item.value !== 0);
  371. }
  372. return {
  373. label,
  374. match
  375. };
  376. }).filter(item => {
  377. if (item.label == 'jqs' || item.label == 'ou') {
  378. return item.match.length;
  379. }
  380. else {
  381. // return item.match.every(entry => {
  382. // return entry.value !== 0;
  383. // });
  384. const validEntrys = item.match.filter(entry => entry.value !== 0);
  385. return validEntrys.length >= 2;
  386. }
  387. });
  388. game.matches = matches; // matches 也记录下来
  389. let uptime = evtime ?? 0;
  390. return { ...gameInfo, matches, uptime };
  391. });
  392. // if (gamesList.filter(item => item.uptime > 0).length) {
  393. // // if (mk == 2) {
  394. // // Logs.out('syncBaseEvents', JSON.stringify({ mk, gamesList }, null, 2));
  395. // // }
  396. // submitOdds({ platform: 'ps', mk, games: gamesList });
  397. // }
  398. const relatedGames = Object.values(GAMES.Relations).map(item => item.rel?.['ps'] ?? {});
  399. if (!relatedGames.length) {
  400. return 0;
  401. }
  402. let update = 0;
  403. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  404. gamesList?.forEach(game => {
  405. const { eventId, matches, uptime, stage, retime, score, wm } = game;
  406. const relatedGame = relatedMap.get(eventId);
  407. if (relatedGame) {
  408. const events = {};
  409. matches.forEach(({ label, match }) => {
  410. match.forEach(({ key, value, origin, source, qualified }) => {
  411. events[key] = {
  412. v: value,
  413. r: origin,
  414. s: source,
  415. q: qualified,
  416. };
  417. });
  418. });
  419. relatedGame.evtime = uptime;
  420. relatedGame.events = events;
  421. relatedGame.stage = stage;
  422. relatedGame.retime = retime;
  423. relatedGame.score = score;
  424. relatedGame.wm = wm;
  425. update ++;
  426. }
  427. });
  428. return update;
  429. }
  430. }
  431. const updateBaseEvents = ({ games, timestamp, tp='ps_9_9_1' }) => {
  432. return new Promise((resolve, reject) => {
  433. if (!games) {
  434. return reject(new Error('GAMES_INVALID'));
  435. }
  436. if (!timestamp) {
  437. return reject(new Error('TIMESTAMP_INVALID'));
  438. }
  439. let update = 0;
  440. const { UpdateTimestamp } = GAMES;
  441. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  442. UpdateTimestamp[tp] = timestamp;
  443. }
  444. else {
  445. return resolve({ update });
  446. }
  447. Object.keys(games).forEach(mk => {
  448. update += syncBaseEvents({ mk, games: games[mk] ?? [] });
  449. });
  450. resolve({ update });
  451. });
  452. }
  453. /**
  454. * 比较外盘与内盘的赔率
  455. */
  456. const compareOdds = (events, baseEvents, platform) => {
  457. const setting = getSetting();
  458. const maxDiff = setting[`${platform}MaxDiff`] ?? 0;
  459. Object.keys(events).forEach(ior => {
  460. const value = events[ior].v;
  461. const baseValue = baseEvents[ior]?.s ?? baseEvents[ior]?.v ?? 1;
  462. if (value - baseValue >= maxDiff) {
  463. events[ior].q = 1;
  464. }
  465. else {
  466. events[ior].q = 0;
  467. }
  468. });
  469. }
  470. const updateGamesEvents = ({ platform, mk, games, outrights, timestamp, tp }) => {
  471. return new Promise((resolve, reject) => {
  472. if (!platform || (!games && !outrights)) {
  473. return reject(new Error('PLATFORM_GAMES_INVALID'));
  474. }
  475. const { UpdateTimestamp } = GAMES;
  476. if (!UpdateTimestamp[tp] || UpdateTimestamp[tp] < timestamp) {
  477. // Logs.out('updateGamesEvents', { tp, timestamp });
  478. UpdateTimestamp[tp] = timestamp;
  479. }
  480. else {
  481. return resolve({ update: 0 });
  482. }
  483. if (platform == 'ps') {
  484. const update = syncBaseEvents({ mk, games, outrights });
  485. return resolve({ update });
  486. }
  487. const relatedGames = Object.values(GAMES.Relations).map(item => {
  488. // item.rel?.[platform] ?? {}
  489. const { rel } = item ?? {};
  490. if (!rel) {
  491. return {};
  492. }
  493. const game = rel[platform] ?? {};
  494. game.baseId = rel['ps']?.eventId;
  495. return game;
  496. });
  497. if (!relatedGames.length) {
  498. return resolve({ update: 0 });
  499. }
  500. const updateCount = {
  501. update: 0
  502. };
  503. const marketType = getMarketType(mk);
  504. const baseList = GAMES.Baselist[marketType] ?? [];
  505. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  506. const relatedMap = new Map(relatedGames.map(item => [item.eventId, item]));
  507. games?.forEach(game => {
  508. const { eventId, evtime, events, stage, retime, score, wm } = game;
  509. const relatedGame = relatedMap.get(eventId);
  510. if (!relatedGame) {
  511. return;
  512. }
  513. const baseEvents = baseMap.get(relatedGame.baseId)?.events ?? {};
  514. compareOdds(events, baseEvents, platform);
  515. if (relatedGame) {
  516. relatedGame.evtime = evtime;
  517. relatedGame.events = events;
  518. relatedGame.stage = stage;
  519. relatedGame.retime = retime;
  520. relatedGame.score = score;
  521. relatedGame.wm = wm;
  522. updateCount.update ++;
  523. }
  524. });
  525. outrights?.forEach(outright => {
  526. const { parentId, sptime, special } = outright;
  527. const relatedGame = relatedMap.get(parentId);
  528. if (!relatedGame) {
  529. return;
  530. }
  531. const baseEvents = baseMap.get(relatedGame.baseId)?.events ?? {};
  532. compareOdds(special, baseEvents, platform);
  533. if (relatedGame) {
  534. relatedGame.sptime = sptime;
  535. relatedGame.special = special;
  536. updateCount.update ++;
  537. }
  538. });
  539. resolve(updateCount);
  540. });
  541. }
  542. /**
  543. * 获取比赛盘口
  544. */
  545. const getGamesEvents = ({ platform, relIds = [] } = {}) => {
  546. if (!relIds.length) {
  547. return null;
  548. }
  549. const idSet = new Set(relIds);
  550. const relations = { ...GAMES.Relations };
  551. Object.keys(relations).forEach(id => {
  552. if (idSet.size && !idSet.has(+id)) {
  553. delete relations[id];
  554. }
  555. });
  556. if (platform) {
  557. return Object.values(relations).map(rel => rel[platform] ?? {});
  558. }
  559. const gamesEvents = {};
  560. Object.values(relations).forEach(({ rel }) => {
  561. Object.keys(rel).forEach(platform => {
  562. const game = rel[platform] ?? {};
  563. const { eventId, events, special } = game;
  564. if (!gamesEvents[platform]) {
  565. gamesEvents[platform] = {};
  566. }
  567. gamesEvents[platform][eventId] = { ...events, ...special };
  568. });
  569. });
  570. return gamesEvents;
  571. }
  572. /**
  573. * 获取远程关联比赛列表
  574. */
  575. const fetchGamesRelation = async (mk='') => {
  576. return axios.get(`${BASE_API_URL}/p/getGameTast?mk=${mk}`, {
  577. proxy: false
  578. }).then(({ data: resData }) => {
  579. if (resData.code == 0) {
  580. const nowTime = Date.now();
  581. const halfTimeActiveTime = getSetting('halfTimeActiveTime');
  582. const activeHalfTime = nowTime + halfTimeActiveTime * 60 * 60 * 1000;
  583. const inactiveHalfTime = nowTime + 60 * 1000;
  584. const gamesRelation = resData.data?.filter?.((item) => {
  585. const timestamp = new Date(item.timestamp).getTime();
  586. const updated = new Date(item.updated_at).getTime();
  587. if (nowTime > timestamp) {
  588. item.mk = 2;
  589. }
  590. item.timestamp = timestamp;
  591. item.updated = updated;
  592. const expireTime = timestamp + 1000*60*60*3;
  593. return expireTime > nowTime;
  594. }).map(item => {
  595. const {
  596. id, mk, league_name,
  597. event_id: ps_event_id,
  598. league_id: ps_league_id,
  599. team_home_name: ps_team_home_name,
  600. team_away_name: ps_team_away_name,
  601. ob_event_id, ob_league_id,
  602. ob_team_home_name,
  603. ob_team_away_name,
  604. hg_event_id, hg_league_id,
  605. hg_team_home_name,
  606. hg_team_away_name,
  607. im_event_id, im_league_id,
  608. im_team_home_name,
  609. im_team_away_name,
  610. updated,
  611. timestamp,
  612. } = item;
  613. const rel = {
  614. ps: {
  615. eventId: +ps_event_id,
  616. leagueId: +ps_league_id,
  617. leagueName: league_name,
  618. teamHomeName: ps_team_home_name,
  619. teamAwayName: ps_team_away_name,
  620. timestamp
  621. },
  622. ob: ob_event_id ? {
  623. eventId: +ob_event_id,
  624. leagueId: +ob_league_id,
  625. leagueName: league_name,
  626. teamHomeName: ob_team_home_name,
  627. teamAwayName: ob_team_away_name,
  628. timestamp
  629. } : null,
  630. hg: hg_event_id ? {
  631. eventId: +hg_event_id,
  632. leagueId: +hg_league_id,
  633. leagueName: league_name,
  634. teamHomeName: hg_team_home_name,
  635. teamAwayName: hg_team_away_name,
  636. timestamp
  637. } : null,
  638. im: im_event_id ? {
  639. eventId: +im_event_id,
  640. leagueId: +im_league_id,
  641. leagueName: league_name,
  642. teamHomeName: im_team_home_name,
  643. teamAwayName: im_team_away_name,
  644. timestamp
  645. } : null
  646. };
  647. const rels = [];
  648. rels.push({ id: ps_event_id, mk, rel, timestamp, updated });
  649. if (timestamp < activeHalfTime && timestamp > inactiveHalfTime) {
  650. const halfRel = {};
  651. Object.keys(rel).forEach(platform => {
  652. const game = rel[platform];
  653. if (game) {
  654. const { eventId, ...gameInfo } = game;
  655. halfRel[platform] = {
  656. eventId: eventId*-1,
  657. ...gameInfo
  658. };
  659. }
  660. else {
  661. halfRel[platform] = null;
  662. }
  663. });
  664. rels.push({ id: ps_event_id*-1, mk, rel: halfRel, timestamp, updated });
  665. }
  666. return rels;
  667. }).flat() ?? [];
  668. return gamesRelation;
  669. }
  670. return Promise.reject(new Error(resData.message));
  671. });
  672. }
  673. /**
  674. * 获取PC数据
  675. */
  676. const getPCEvents = (events) => {
  677. if (!events) {
  678. return undefined;
  679. }
  680. const pcEvents = {};
  681. Object.keys(events).forEach(ior => {
  682. const { v, s, r } = events[ior];
  683. pcEvents[ior] = {
  684. v: s ?? v,
  685. r: r
  686. }
  687. });
  688. return pcEvents;
  689. }
  690. const getPCData = (id) => {
  691. const baseList = Object.values(GAMES.Baselist).flat();
  692. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  693. const baseGame = baseMap.get(id);
  694. if (!baseGame) {
  695. return null;
  696. }
  697. const { matches, events, special, ...gameInfo } = baseGame;
  698. return {
  699. events: getPCEvents(events),
  700. special: getPCEvents(special),
  701. ...gameInfo
  702. }
  703. }
  704. /**
  705. * 获取关联比赛列表
  706. * @param {object} options
  707. * @property {number} mk
  708. * @property {number[]} ids
  709. * @property {boolean} listEvents
  710. * @property {boolean} listPC
  711. * @returns {object[]}
  712. */
  713. const getGamesRelation = ({ mk=-1, ids, listEvents=false, listPC=false } = {}) => {
  714. let relations;
  715. if (ids?.length) {
  716. relations = ids.map(id => GAMES.Relations[id]);
  717. }
  718. else {
  719. relations = Object.values(GAMES.Relations);
  720. }
  721. relations = relations.filter(item => !!item && (mk == -1 || item.mk == mk)).sort((a, b) => a.timestamp - b.timestamp);
  722. if (listEvents && !listPC) {
  723. return relations;
  724. }
  725. return relations.map(item => {
  726. const { rel, ...relationInfo } = item;
  727. const tempRel = { ...rel };
  728. const { id } = relationInfo;
  729. if (listPC) {
  730. tempRel.pc = getPCData(id);
  731. }
  732. if (!listEvents) {
  733. Object.keys(tempRel).forEach(platform => {
  734. const { events, evtime, special, sptime, ...gameInfo } = tempRel[platform] ?? {};
  735. tempRel[platform] = gameInfo;
  736. });
  737. }
  738. return { ...relationInfo, rel: tempRel };
  739. });
  740. }
  741. /**
  742. * 定时更新关联比赛列表
  743. */
  744. const updateGamesRelation = () => {
  745. fetchGamesRelation()
  746. .then(gamesRelation => {
  747. const baseList = {};
  748. gamesRelation.map(item => {
  749. const baseGame = item.rel?.['ps'] ?? {};
  750. return { ...baseGame, mk: item.mk };
  751. }).forEach(item => {
  752. const marketType = getMarketType(item.mk);
  753. if (!baseList[marketType]) {
  754. baseList[marketType] = [];
  755. }
  756. baseList[marketType].push(item);
  757. });
  758. Object.keys(baseList).forEach(marketType => {
  759. syncBaseList({ marketType, games: baseList[marketType] });
  760. });
  761. const updateCount = {
  762. add: 0,
  763. update: 0,
  764. delete: 0
  765. };
  766. gamesRelation.forEach(item => {
  767. const { id, mk, updated } = item;
  768. const oldItem = GAMES.Relations[id];
  769. if (!oldItem) {
  770. GAMES.Relations[id] = item;
  771. updateCount.add ++;
  772. }
  773. else if (oldItem.mk != mk) {
  774. GAMES.Relations[id] = item;
  775. updateCount.update ++;
  776. }
  777. else if ((oldItem.updated ?? -1) < updated) {
  778. GAMES.Relations[id] = item;
  779. updateCount.update ++;
  780. }
  781. });
  782. const relations = new Set(gamesRelation.map(item => +item.id));
  783. Object.keys(GAMES.Relations).forEach(id => {
  784. if (!relations.has(+id)) {
  785. delete GAMES.Relations[id];
  786. updateCount.delete ++;
  787. }
  788. });
  789. if (updateCount.add || updateCount.update || updateCount.delete) {
  790. Logs.out('updateGamesRelation', updateCount);
  791. }
  792. else {
  793. Logs.outDev('updateGamesRelation', updateCount);
  794. }
  795. })
  796. .catch(err => {
  797. Logs.out('updateGamesRelation', err.message);
  798. })
  799. .finally(() => {
  800. setTimeout(updateGamesRelation, 60000);
  801. });
  802. }
  803. updateGamesRelation();
  804. const gamesRelationCleanup = () => {
  805. const relations = Object.values(GAMES.Relations);
  806. const expireTime = Date.now() - 1000*60;
  807. relations.forEach(item => {
  808. const { rel } = item;
  809. Object.keys(rel).forEach(platform => {
  810. const { evtime=0, sptime=0 } = rel[platform] ?? {};
  811. if (evtime && evtime < expireTime) {
  812. delete rel[platform].events;
  813. delete rel[platform].evtime;
  814. }
  815. if (sptime && sptime < expireTime) {
  816. delete rel[platform].special;
  817. delete rel[platform].sptime;
  818. }
  819. });
  820. });
  821. }
  822. /**
  823. * 同步比赛结果
  824. */
  825. const syncGamesResult = async (result) => {
  826. if (IS_DEV) {
  827. return Logs.out('updateGamesResult', result);
  828. }
  829. // axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  830. // .then(res => {
  831. // // Logs.out('syncMatchResult', res.data);
  832. // })
  833. // .catch(err => {
  834. // Logs.out('syncMatchResult', err.message);
  835. // });
  836. }
  837. /**
  838. * 更新比赛结果
  839. */
  840. const updateGamesResult = (result) => {
  841. syncGamesResult(result);
  842. return Promise.resolve();
  843. }
  844. /**
  845. * 同步中单方案
  846. */
  847. // const syncSolutions = (solutions) => {
  848. // if (IS_DEV) {
  849. // return Logs.out('syncSolutions', solutions);
  850. // }
  851. // axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  852. // .then(res => {
  853. // // Logs.out('syncSolutions', res.data);
  854. // })
  855. // .catch(err => {
  856. // Logs.out('syncSolutions', err.message);
  857. // });
  858. // }
  859. /**
  860. * 更新中单方案
  861. */
  862. const getCprKey = (cpr) => {
  863. const { k, p, v, q } = cpr;
  864. return `${k}_${p}_${v}_${q}`;
  865. }
  866. const compareCpr = (cpr1, cpr2) => {
  867. const key1 = getCprKey(cpr1);
  868. const key2 = getCprKey(cpr2);
  869. return key1 === key2;
  870. }
  871. const updateSolutions = (solutions, eventsLogsMap) => {
  872. if (solutions?.length) {
  873. const solutionsHistory = GAMES.Solutions;
  874. const updateIds = { add: [], update: [], retain: [], remove: [] }
  875. solutions.forEach(item => {
  876. const { sid, cpr, sol: { win_average, win_profit_rate } } = item;
  877. if (!solutionsHistory[sid]) {
  878. solutionsHistory[sid] = item;
  879. updateIds.add.push(sid);
  880. return;
  881. }
  882. const historySolution = solutionsHistory[sid];
  883. if (historySolution.sol.win_average !== win_average ||
  884. historySolution.sol.win_profit_rate !== win_profit_rate ||
  885. !compareCpr(historySolution.cpr, cpr)) {
  886. solutionsHistory[sid] = item;
  887. updateIds.update.push(sid);
  888. return;
  889. }
  890. const { timestamp } = item;
  891. historySolution.timestamp = timestamp;
  892. updateIds.retain.push(sid);
  893. });
  894. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  895. Object.keys(solutionsHistory).forEach(sid => {
  896. if (!solutionsMap.has(sid)) {
  897. delete solutionsHistory[sid];
  898. updateIds.remove.push(sid);
  899. }
  900. });
  901. // const solutionUpdate = {};
  902. // Object.keys(updateIds).forEach(key => {
  903. // if (key == 'retain' || key == 'remove') {
  904. // solutionUpdate[key] = updateIds[key];
  905. // }
  906. // else {
  907. // solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  908. // }
  909. // });
  910. // syncSolutions(solutionUpdate);
  911. if (updateIds.add.length / solutions.length > 0.2 ||
  912. updateIds.remove.length / solutions.length > 0.2
  913. ) {
  914. const { expireEvents, removeEvents } = eventsLogsMap;
  915. const expireEvemtsMap = {};
  916. expireEvents.forEach(item => {
  917. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  918. if (!expireEvemtsMap[mk]) {
  919. expireEvemtsMap[mk] = {};
  920. }
  921. if (!expireEvemtsMap[mk][platform]) {
  922. expireEvemtsMap[mk][platform] = {};
  923. }
  924. if (!expireEvemtsMap[mk][platform].list) {
  925. expireEvemtsMap[mk][platform].list = [];
  926. }
  927. if (!expireEvemtsMap[mk][platform].evtime) {
  928. expireEvemtsMap[mk][platform].evtime = evtime;
  929. }
  930. if (!expireEvemtsMap[mk][platform].sptime) {
  931. expireEvemtsMap[mk][platform].sptime = sptime;
  932. }
  933. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  934. });
  935. Object.keys(expireEvemtsMap).forEach(mk => {
  936. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  937. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  938. mk, platform,
  939. expireEvemtsMap[mk][platform].list.length,
  940. expireEvemtsMap[mk][platform].evtime,
  941. expireEvemtsMap[mk][platform].sptime,
  942. )
  943. });
  944. });
  945. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  946. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  947. }
  948. else {
  949. Logs.outDev('solutions update complete', updateIds);
  950. }
  951. }
  952. }
  953. /**
  954. * 获取中单方案
  955. */
  956. const getSolutions = async ({ win_min, with_events, show_lower=false, mk=-1 }) => {
  957. // Logs.out('getSolutions', win_min);
  958. const filterMarketType = +mk;
  959. const { minShowAmount } = getSetting();
  960. const solutionsList = Object.values(GAMES.Solutions);
  961. const gamesRelation = getGamesRelation();
  962. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  963. const mkCount = {
  964. all: 0,
  965. rollball: 0,
  966. today: 0,
  967. early: 0,
  968. }
  969. let solutions = solutionsList.filter(item => {
  970. const { sol: { win_average }, lower } = item;
  971. if (!show_lower && lower) {
  972. return false;
  973. }
  974. return win_average >= (win_min ?? minShowAmount);
  975. })
  976. .map(item => {
  977. const { info: { id } } = item;
  978. const { mk, rel } = relationsMap.get(id);
  979. const marketType = getMarketType(mk);
  980. mkCount.all ++;
  981. mkCount[marketType] ++;
  982. return {
  983. ...item,
  984. info: { id, mk, ...rel }
  985. }
  986. });
  987. if (mk >= 0) {
  988. solutions = solutions.filter(item => {
  989. const { info: { mk } } = item;
  990. return mk == filterMarketType;
  991. });
  992. }
  993. solutions = solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  994. const relIds = solutions.map(item => item.info.id);
  995. let gamesEvents;
  996. if (with_events) {
  997. gamesEvents = getGamesEvents({ relIds });
  998. }
  999. return { solutions, gamesEvents, mkCount };
  1000. }
  1001. /**
  1002. * 获取中单方案并按照比赛分组
  1003. */
  1004. const getGamePeriod = (id) => {
  1005. if (id > 0) {
  1006. return 0;
  1007. }
  1008. else if (id < 0) {
  1009. return 1;
  1010. }
  1011. return -1;
  1012. }
  1013. const getGamesSolutions = async ({ win_min, with_events, show_lower=false, mk=-1, gp=-1, tp=0, sk }) => {
  1014. const filterMarketType = +mk;
  1015. const filterGamePeriod = +gp;
  1016. const filterDataType = +tp;
  1017. const { minShowAmount } = getSetting();
  1018. const solutionsList = Object.values(GAMES.Solutions);
  1019. const gamesRelation = getGamesRelation({ listEvents: with_events });
  1020. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  1021. const mkCount = {
  1022. all: 0,
  1023. rollball: 0,
  1024. today: 0,
  1025. early: 0,
  1026. }
  1027. const solutionsMap = {};
  1028. solutionsList.forEach(item => {
  1029. const { info: { id }, ...solution } = item;
  1030. const { rule, sol: { win_average }, lower } = solution;
  1031. const ruleType = getRuleType(rule);
  1032. if (!show_lower && lower) {
  1033. return false;
  1034. }
  1035. if ((filterDataType == 0 || filterDataType == ruleType) &&
  1036. (!!sk || win_average >= (win_min ?? minShowAmount)) &&
  1037. (filterGamePeriod == -1 || filterGamePeriod == getGamePeriod(id))
  1038. ) {
  1039. const gameRelation = relationsMap.get(id);
  1040. if (!solutionsMap[id]) {
  1041. solutionsMap[id] = { ...gameRelation, solutions: [] };
  1042. }
  1043. solutionsMap[id].solutions.push(solution);
  1044. }
  1045. })
  1046. const gamesSolutions = Object.values(solutionsMap)
  1047. .filter(item => {
  1048. const { mk, rel, solutions } = item;
  1049. const marketType = getMarketType(mk);
  1050. if (!sk || matchGame(rel, sk)) {
  1051. mkCount.all ++;
  1052. mkCount[marketType] ++;
  1053. solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  1054. return filterMarketType == -1 || filterMarketType == mk;
  1055. }
  1056. return false;
  1057. })
  1058. .sort((a, b) => b.solutions[0].sol.win_average - a.solutions[0].sol.win_average);
  1059. return { gamesSolutions, mkCount };
  1060. }
  1061. /**
  1062. * 获取单个中单方案
  1063. */
  1064. const getSolution = async (sid) => {
  1065. if (!sid) {
  1066. return Promise.reject(new Error('sid is required'));
  1067. }
  1068. const solution = GAMES.Solutions[sid];
  1069. if (!solution) {
  1070. return Promise.reject(new Error('solution not found'));
  1071. }
  1072. return solution;
  1073. }
  1074. /**
  1075. * 通过比赛 ID 获取中单方案
  1076. */
  1077. const getSolutionsByIds = async (ids) => {
  1078. const baseList = Object.values(GAMES.Baselist).flat();
  1079. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  1080. const result = {};
  1081. ids.forEach(id => {
  1082. const baseGame = baseMap.get(id);
  1083. if (baseGame) {
  1084. result[id] = {};
  1085. result[id].matches = baseGame.matches ?? [];
  1086. result[id].sols = [];
  1087. }
  1088. const haflId = id * -1;
  1089. const halfGame = baseMap.get(haflId);
  1090. if (halfGame) {
  1091. result[haflId] = {};
  1092. result[haflId].matches = halfGame.matches ?? [];
  1093. result[haflId].sols = [];
  1094. }
  1095. });
  1096. Object.values(GAMES.Solutions).forEach(item => {
  1097. const { info: { id }, lower } = item;
  1098. if (result[id] && !lower) {
  1099. result[id].sols.push(item);
  1100. }
  1101. });
  1102. return result;
  1103. }
  1104. /**
  1105. * 清理中单方案
  1106. */
  1107. const solutionsCleanup = () => {
  1108. const solutionsHistory = GAMES.Solutions;
  1109. const updateIds = { remove: [] }
  1110. Object.keys(solutionsHistory).forEach(sid => {
  1111. const { timestamp } = solutionsHistory[sid];
  1112. const nowTime = Date.now();
  1113. if (nowTime - timestamp > 1000*60) {
  1114. delete solutionsHistory[sid];
  1115. updateIds.remove.push(sid);
  1116. return;
  1117. }
  1118. const solution = solutionsHistory[sid];
  1119. const eventTime = solution.info.timestamp;
  1120. if (nowTime > eventTime) {
  1121. delete solutionsHistory[sid];
  1122. updateIds.remove.push(sid);
  1123. }
  1124. });
  1125. // if (updateIds.remove.length) {
  1126. // syncSolutions(updateIds);
  1127. // }
  1128. }
  1129. /**
  1130. * 清理更新时间戳
  1131. */
  1132. const cleanupUpdateTimestamp = () => {
  1133. const updateTimestamp = GAMES.UpdateTimestamp;
  1134. const nowTime = Date.now();
  1135. const expireTime = nowTime - 1000*60;
  1136. Object.keys(updateTimestamp).forEach(key => {
  1137. if (updateTimestamp[key] < expireTime) {
  1138. delete updateTimestamp[key];
  1139. }
  1140. });
  1141. }
  1142. /**
  1143. * 定时清理中单方案
  1144. * 定时清理盘口信息
  1145. */
  1146. setInterval(() => {
  1147. // cleanupBaseList();
  1148. solutionsCleanup();
  1149. gamesRelationCleanup();
  1150. cleanupUpdateTimestamp();
  1151. }, 1000*30);
  1152. /**
  1153. * 获取综合利润
  1154. */
  1155. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  1156. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1157. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  1158. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1159. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1160. return profit;
  1161. }
  1162. /**
  1163. * 通过 sid 获取综合利润
  1164. */
  1165. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  1166. const preSolution = GAMES.Solutions[sid1];
  1167. const subSolution = GAMES.Solutions[sid2];
  1168. const sol1 = preSolution?.sol;
  1169. const sol2 = subSolution?.sol;
  1170. if (!sol1) {
  1171. return Promise.reject(new Error('sid1 已失效'));
  1172. }
  1173. if (!sol2) {
  1174. return Promise.reject(new Error('sid2 已失效'));
  1175. }
  1176. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1177. return { profit, solutions: [preSolution, subSolution] };
  1178. }
  1179. /**
  1180. * 通过盘口信息获取综合利润
  1181. */
  1182. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  1183. if (!betInfo1?.cross_type) {
  1184. return Promise.reject(new Error('第一个下注信息无效'));
  1185. }
  1186. if (!betInfo2?.cross_type) {
  1187. return Promise.reject(new Error('第二个下注信息无效'));
  1188. }
  1189. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1190. inner_base = typeof(inner_base) != 'undefined' ? +inner_base : innerDefaultAmount;
  1191. inner_rebate = typeof(inner_rebate) != 'undefined' ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1192. if (fixed) {
  1193. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  1194. }
  1195. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  1196. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1197. }
  1198. /**
  1199. * 计算补单综合利润
  1200. */
  1201. const getTotalReplacement = async (data) => {
  1202. const { event_id, inner_ior, inner_odds, pre_bet_info } = data;
  1203. if (!event_id) {
  1204. Logs.out('getTotalReplacement event_id 无效', data);
  1205. return Promise.reject(new Error('event_id 无效'));
  1206. }
  1207. if (!inner_ior) {
  1208. Logs.out('getTotalReplacement inner_ior 无效', data);
  1209. return Promise.reject(new Error('inner_ior 无效'));
  1210. }
  1211. if (isNaN(+inner_odds)) {
  1212. Logs.out('getTotalReplacement inner_odds 无效', data);
  1213. return Promise.reject(new Error('inner_odds 无效'));
  1214. }
  1215. if (!pre_bet_info || typeof(pre_bet_info) !== 'object') {
  1216. Logs.out('getTotalReplacement pre_bet_info 无效', data);
  1217. return Promise.reject(new Error('pre_bet_info 无效'));
  1218. }
  1219. const { loss_out, inner_ref_value: inner_base, inner_odds: inner_odds_first } = getFirstInfo(pre_bet_info);
  1220. const { innerRebateRatio } = getSetting();
  1221. const inner_rebate = typeof(data.inner_rebate) != 'undefined' ? +data.inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1222. const inner_odds_value = fixFloat(inner_odds * (inner_odds_first+1), 3);
  1223. const relation = getGamesRelation({ ids: [event_id], listEvents: true, listPC: true }).map(item => {
  1224. const { rel, ...relationInfo } = item;
  1225. const tempRel = { ...rel };
  1226. const events = {};
  1227. const evtime = Date.now();
  1228. events[inner_ior] = { v: inner_odds_value };
  1229. tempRel.ps = { ...rel.ps, events, evtime, special: null, sptime: 0 }
  1230. return { ...relationInfo, rel: tempRel };
  1231. });
  1232. if (!relation?.length) {
  1233. Logs.out('getTotalReplacement 没有找到对应的比赛 data %o, relation %o', data, relation);
  1234. return Promise.reject(new Error('没有找到对应的比赛'));
  1235. }
  1236. const passableEvents = getPassableEvents(relation, null);
  1237. const solutions = eventsCombination(passableEvents, inner_base, inner_rebate);
  1238. if (!solutions?.length) {
  1239. Logs.out('getTotalReplacement 没有可用的解决方案 data %o, relation %o, passableEvents %o, solutions %o', data, relation, passableEvents, solutions);
  1240. return Promise.reject(new Error('没有可用的解决方案'));
  1241. }
  1242. Logs.out('getTotalReplacement, event_id[%d], inner_ior[%s], solutions[%d]', event_id, inner_ior, solutions.length);
  1243. // 过滤 .filter(solution => !solution.lower)
  1244. return solutions.map(solution => {
  1245. const { sid, info, sol, ...solutionInfo } = solution;
  1246. const { win_profit_rate, win_average_rate, ...solInfo } = sol;
  1247. const { cross_type } = solInfo;
  1248. solInfo.win_side_a = typeof(solInfo.win_side_a) !== 'number' ? undefined : fixFloat(solInfo.win_side_a - loss_out);
  1249. solInfo.win_side_b = typeof(solInfo.win_side_b) !== 'number' ? undefined : fixFloat(solInfo.win_side_b - loss_out);
  1250. solInfo.win_side_c = cross_type == 'la_wa_rv' ? 0 : (typeof(solInfo.win_side_c) !== 'number' ? undefined : fixFloat(solInfo.win_side_c - loss_out));
  1251. solInfo.win_average = fixFloat(solInfo.win_average - loss_out);
  1252. return { ...solutionInfo, sol: solInfo };
  1253. });
  1254. }
  1255. /**
  1256. * 同步Qboss平台配置
  1257. */
  1258. const syncQbossConfig = () => {
  1259. const setting = getSetting();
  1260. if (!setting.syncSettingEnabled) {
  1261. // Logs.outDev('syncQbossConfig disabled');
  1262. return setTimeout(syncQbossConfig, 1000*5);
  1263. }
  1264. axios.get(`${BASE_API_URL}/p/QbossSystemConfig`, { proxy: false })
  1265. .then(res => {
  1266. const { data } = res;
  1267. Logs.outDev('syncQbossConfig', data);
  1268. if (!data?.data) {
  1269. throw new Error('syncQbossConfig data is empty');
  1270. }
  1271. const {
  1272. qboss_return_ratio,
  1273. ob_return_ratio, ob_return_type, ob_odds_more_than,
  1274. im_return_ratio, im_return_type, im_odds_more_than,
  1275. hg_return_ratio, hg_return_type, hg_odds_more_than,
  1276. pc_return_ratio, pc_return_type,
  1277. qboss_jq_add_odds, qboss_jq_add_hours,
  1278. qboss_gq_add_dy_odds, qboss_gq_add_jq_odds,
  1279. bc_before_hours,
  1280. qboss_ts_sfdx_odds_add, qboss_ts_pjrq_odds_add, qboss_ts_jqs_odds_add,
  1281. } = data.data;
  1282. const qbossSetting = {
  1283. innerRebateRatio: qboss_return_ratio ? +qboss_return_ratio : 0,
  1284. obRebateRatio: ob_return_ratio ? +ob_return_ratio : 0,
  1285. obRebateType: ob_return_type ? +ob_return_type : 0,
  1286. obMaxDiff: ob_odds_more_than ? +ob_odds_more_than : 0,
  1287. imRebateRatio: im_return_ratio ? +im_return_ratio : 0,
  1288. imRebateType: im_return_type ? +im_return_type : 0,
  1289. imMaxDiff: im_odds_more_than ? +im_odds_more_than : 0,
  1290. hgRebateRatio: hg_return_ratio ? +hg_return_ratio : 0,
  1291. hgRebateType: hg_return_type ? +hg_return_type : 0,
  1292. hgMaxDiff: hg_odds_more_than ? +hg_odds_more_than : 0,
  1293. pcRebateRatio: pc_return_ratio ? +pc_return_ratio : 0,
  1294. pcRebateType: pc_return_type ? +pc_return_type : 0,
  1295. subsidyTime: qboss_jq_add_hours ? +qboss_jq_add_hours : 0,
  1296. subsidyAmount: qboss_jq_add_odds ? +qboss_jq_add_odds : 0,
  1297. subsidyRbWmAmount: qboss_gq_add_dy_odds ? +qboss_gq_add_dy_odds : 0,
  1298. subsidyRbOtAmount: qboss_gq_add_jq_odds ? +qboss_gq_add_jq_odds : 0,
  1299. innerRouSubsidyValue: qboss_ts_sfdx_odds_add ? +qboss_ts_sfdx_odds_add : 0,
  1300. innerWmSubsidyRatio: qboss_ts_pjrq_odds_add ? +qboss_ts_pjrq_odds_add : 0,
  1301. innerOtSubsidyRatio: qboss_ts_jqs_odds_add ? +qboss_ts_jqs_odds_add : 0,
  1302. halfTimeActiveTime: bc_before_hours ? +bc_before_hours : 0,
  1303. };
  1304. Logs.outDev('syncQbossConfig', qbossSetting);
  1305. const settingFields = {};
  1306. let needUpdate = false;
  1307. Object.keys(qbossSetting).forEach(key => {
  1308. if (qbossSetting[key] !== setting[key]) {
  1309. settingFields[key] = qbossSetting[key];
  1310. needUpdate = true;
  1311. }
  1312. });
  1313. if (needUpdate) {
  1314. Setting.update(settingFields);
  1315. // Logs.outDev('syncQbossConfig', settingFields);
  1316. }
  1317. // else {
  1318. // Logs.outDev('syncQbossConfig no change');
  1319. // }
  1320. })
  1321. .catch(err => {
  1322. Logs.out('syncQbossConfig error', err.message);
  1323. })
  1324. .finally(() => {
  1325. setTimeout(syncQbossConfig, 1000*15);
  1326. });
  1327. }
  1328. syncQbossConfig();
  1329. /**
  1330. * 异常通知
  1331. */
  1332. const notifyException = (message) => {
  1333. if (IS_DEV) {
  1334. return Logs.out('notifyException', { message });
  1335. }
  1336. const chat_id = -1003032820471;
  1337. Promise.all([
  1338. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message: `@taoger369 ${message}` } }, { proxy: false }),
  1339. axios.post('https://push.long.bid/bark', {
  1340. title: 'QBoss异常通知',
  1341. content: message,
  1342. topic: 'default',
  1343. icon: 'https://bwh.flyzto.com/icon/ball.png',
  1344. }, { proxy: false }),
  1345. ])
  1346. .then(() => {
  1347. Logs.out('notifyException', '通知成功');
  1348. })
  1349. .catch(err => {
  1350. Logs.out('notifyException', err.message);
  1351. });
  1352. }
  1353. /**
  1354. * 从子进程获取数据
  1355. */
  1356. const getDataFromChild = (type, callback) => {
  1357. const id = ++Request.count;
  1358. Request.callbacks[id] = callback;
  1359. events_child.send({ method: 'get', id, type });
  1360. }
  1361. /**
  1362. * 向子进程发送数据
  1363. */
  1364. const postDataToChild = (type, data) => {
  1365. events_child.send({ method: 'post', type, data });
  1366. }
  1367. /**
  1368. * 处理子进程消息
  1369. */
  1370. events_child.on('message', async (message) => {
  1371. const { callbacks } = Request;
  1372. const { method, id, type, data } = message;
  1373. if (method == 'get' && id) {
  1374. let responseData = null;
  1375. if (type == 'getGamesRelation') {
  1376. responseData = getGamesRelation({ listEvents: true });
  1377. }
  1378. else if (type == 'getSetting') {
  1379. responseData = getSetting();
  1380. }
  1381. // else if (type == 'getSolutionHistory') {
  1382. // responseData = getSolutionHistory();
  1383. // }
  1384. events_child.send({ type: 'response', id, data: responseData });
  1385. }
  1386. else if (method == 'post') {
  1387. if (type == 'updateSolutions') {
  1388. updateSolutions(data.solutions, data.eventsLogsMap);
  1389. }
  1390. }
  1391. else if (type == 'response' && id && callbacks[id]) {
  1392. callbacks[id](data);
  1393. delete callbacks[id];
  1394. }
  1395. });
  1396. events_child.stderr?.on('data', data => {
  1397. Logs.out('events_child stderr', data.toString());
  1398. });
  1399. const settingUpdate = (fields) => {
  1400. updateSetting(fields);
  1401. postDataToChild('updateSetting', fields);
  1402. }
  1403. const syncSetting = async () => {
  1404. const setting = await Setting.get();
  1405. settingUpdate(setting.toObject());
  1406. }
  1407. syncSetting();
  1408. Setting.onUpdate(settingUpdate);
  1409. /**
  1410. * 保存GAMES数据到缓存文件
  1411. */
  1412. const saveGamesToCache = () => {
  1413. Cache.setData(GamesCacheFile, GAMES, err => {
  1414. if (err) {
  1415. Logs.out('Failed to save games cache:', err.message);
  1416. }
  1417. else {
  1418. Logs.out('Games cache saved successfully');
  1419. }
  1420. });
  1421. }
  1422. /**
  1423. * 从缓存文件加载GAMES数据
  1424. */
  1425. const loadGamesFromCache = () => {
  1426. const gamesCacheData = Cache.getData(GamesCacheFile, true) ?? {};
  1427. Object.keys(GAMES).forEach(key => {
  1428. if (key in gamesCacheData) {
  1429. GAMES[key] = gamesCacheData[key];
  1430. }
  1431. });
  1432. Logs.out('Games cache loaded successfully');
  1433. }
  1434. // 在模块加载时尝试从缓存恢复数据
  1435. loadGamesFromCache();
  1436. // 监听进程退出事件,保存GAMES数据
  1437. process.on('exit', saveGamesToCache);
  1438. process.on('SIGINT', () => {
  1439. process.exit(0);
  1440. });
  1441. process.on('SIGTERM', () => {
  1442. process.exit(0);
  1443. });
  1444. process.on('SIGUSR2', () => {
  1445. process.exit(0);
  1446. });
  1447. module.exports = {
  1448. updateLeaguesList, getFilteredLeagues,
  1449. updateGamesList, updateGamesEvents, updateBaseEvents,
  1450. getGamesRelation,
  1451. updateGamesResult,
  1452. updateOriginalData, getOriginalData,
  1453. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1454. getTotalProfitWithSid, getTotalProfitWithBetInfo, getTotalReplacement,
  1455. notifyException,
  1456. }