GamesPs.js 45 KB

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