GamesPs.js 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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, extractOdds } = 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, listOdds=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. if (listOdds) {
  736. const { odds, evExpire, spExpire } = extractOdds({ platform, evtime, events, sptime, special });
  737. tempRel[platform] = { ...gameInfo, odds, evExpire, spExpire };
  738. }
  739. else {
  740. tempRel[platform] = gameInfo;
  741. }
  742. });
  743. }
  744. return { ...relationInfo, rel: tempRel };
  745. });
  746. }
  747. /**
  748. * 定时更新关联比赛列表
  749. */
  750. const updateGamesRelation = () => {
  751. fetchGamesRelation()
  752. .then(gamesRelation => {
  753. const baseList = {};
  754. gamesRelation.map(item => {
  755. const baseGame = item.rel?.['ps'] ?? {};
  756. return { ...baseGame, mk: item.mk };
  757. }).forEach(item => {
  758. const marketType = getMarketType(item.mk);
  759. if (!baseList[marketType]) {
  760. baseList[marketType] = [];
  761. }
  762. baseList[marketType].push(item);
  763. });
  764. Object.keys(baseList).forEach(marketType => {
  765. syncBaseList({ marketType, games: baseList[marketType] });
  766. });
  767. const updateCount = {
  768. add: 0,
  769. update: 0,
  770. delete: 0
  771. };
  772. gamesRelation.forEach(item => {
  773. const { id, mk, updated } = item;
  774. const oldItem = GAMES.Relations[id];
  775. if (!oldItem) {
  776. GAMES.Relations[id] = item;
  777. updateCount.add ++;
  778. }
  779. else if (oldItem.mk != mk) {
  780. GAMES.Relations[id] = item;
  781. updateCount.update ++;
  782. }
  783. else if ((oldItem.updated ?? -1) < updated) {
  784. GAMES.Relations[id] = item;
  785. updateCount.update ++;
  786. }
  787. });
  788. const relations = new Set(gamesRelation.map(item => +item.id));
  789. Object.keys(GAMES.Relations).forEach(id => {
  790. if (!relations.has(+id)) {
  791. delete GAMES.Relations[id];
  792. updateCount.delete ++;
  793. }
  794. });
  795. if (updateCount.add || updateCount.update || updateCount.delete) {
  796. Logs.out('updateGamesRelation', updateCount);
  797. }
  798. else {
  799. Logs.outDev('updateGamesRelation', updateCount);
  800. }
  801. })
  802. .catch(err => {
  803. Logs.out('updateGamesRelation', err.message);
  804. })
  805. .finally(() => {
  806. setTimeout(updateGamesRelation, 60000);
  807. });
  808. }
  809. updateGamesRelation();
  810. const gamesRelationCleanup = () => {
  811. const relations = Object.values(GAMES.Relations);
  812. const expireTime = Date.now() - 1000*60;
  813. relations.forEach(item => {
  814. const { rel } = item;
  815. Object.keys(rel).forEach(platform => {
  816. const { evtime=0, sptime=0 } = rel[platform] ?? {};
  817. if (evtime && evtime < expireTime) {
  818. delete rel[platform].events;
  819. delete rel[platform].evtime;
  820. }
  821. if (sptime && sptime < expireTime) {
  822. delete rel[platform].special;
  823. delete rel[platform].sptime;
  824. }
  825. });
  826. });
  827. }
  828. /**
  829. * 同步比赛结果
  830. */
  831. const syncGamesResult = async (result) => {
  832. if (IS_DEV) {
  833. return Logs.out('updateGamesResult', result);
  834. }
  835. // axios.post(`${BASE_API_URL}/p/syncMatchResult`, result, { proxy: false })
  836. // .then(res => {
  837. // // Logs.out('syncMatchResult', res.data);
  838. // })
  839. // .catch(err => {
  840. // Logs.out('syncMatchResult', err.message);
  841. // });
  842. }
  843. /**
  844. * 更新比赛结果
  845. */
  846. const updateGamesResult = (result) => {
  847. syncGamesResult(result);
  848. return Promise.resolve();
  849. }
  850. /**
  851. * 同步中单方案
  852. */
  853. // const syncSolutions = (solutions) => {
  854. // if (IS_DEV) {
  855. // return Logs.out('syncSolutions', solutions);
  856. // }
  857. // axios.post(`${BASE_API_URL}/p/syncDsOpportunity`, solutions, { proxy: false })
  858. // .then(res => {
  859. // // Logs.out('syncSolutions', res.data);
  860. // })
  861. // .catch(err => {
  862. // Logs.out('syncSolutions', err.message);
  863. // });
  864. // }
  865. /**
  866. * 更新中单方案
  867. */
  868. const getCprKey = (cpr) => {
  869. const { k, p, v, q } = cpr;
  870. return `${k}_${p}_${v}_${q}`;
  871. }
  872. const compareCpr = (cpr1, cpr2) => {
  873. const key1 = getCprKey(cpr1);
  874. const key2 = getCprKey(cpr2);
  875. return key1 === key2;
  876. }
  877. const updateSolutions = (solutions, eventsLogsMap) => {
  878. if (solutions?.length) {
  879. const solutionsHistory = GAMES.Solutions;
  880. const updateIds = { add: [], update: [], retain: [], remove: [] }
  881. solutions.forEach(item => {
  882. const { sid, cpr, sol: { win_average, win_profit_rate } } = item;
  883. if (!solutionsHistory[sid]) {
  884. solutionsHistory[sid] = item;
  885. updateIds.add.push(sid);
  886. return;
  887. }
  888. const historySolution = solutionsHistory[sid];
  889. if (historySolution.sol.win_average !== win_average ||
  890. historySolution.sol.win_profit_rate !== win_profit_rate ||
  891. !compareCpr(historySolution.cpr, cpr)) {
  892. solutionsHistory[sid] = item;
  893. updateIds.update.push(sid);
  894. return;
  895. }
  896. const { timestamp } = item;
  897. historySolution.timestamp = timestamp;
  898. updateIds.retain.push(sid);
  899. });
  900. const solutionsMap = new Map(solutions.map(item => [item.sid, item]));
  901. Object.keys(solutionsHistory).forEach(sid => {
  902. if (!solutionsMap.has(sid)) {
  903. delete solutionsHistory[sid];
  904. updateIds.remove.push(sid);
  905. }
  906. });
  907. // const solutionUpdate = {};
  908. // Object.keys(updateIds).forEach(key => {
  909. // if (key == 'retain' || key == 'remove') {
  910. // solutionUpdate[key] = updateIds[key];
  911. // }
  912. // else {
  913. // solutionUpdate[key] = updateIds[key].map(sid => solutionsHistory[sid]);
  914. // }
  915. // });
  916. // syncSolutions(solutionUpdate);
  917. if (updateIds.add.length / solutions.length > 0.2 ||
  918. updateIds.remove.length / solutions.length > 0.2
  919. ) {
  920. const { expireEvents, removeEvents } = eventsLogsMap;
  921. const expireEvemtsMap = {};
  922. expireEvents.forEach(item => {
  923. const { mk, platform, info, evExpire, spExpire, evtime, sptime } = item;
  924. if (!expireEvemtsMap[mk]) {
  925. expireEvemtsMap[mk] = {};
  926. }
  927. if (!expireEvemtsMap[mk][platform]) {
  928. expireEvemtsMap[mk][platform] = {};
  929. }
  930. if (!expireEvemtsMap[mk][platform].list) {
  931. expireEvemtsMap[mk][platform].list = [];
  932. }
  933. if (!expireEvemtsMap[mk][platform].evtime) {
  934. expireEvemtsMap[mk][platform].evtime = evtime;
  935. }
  936. if (!expireEvemtsMap[mk][platform].sptime) {
  937. expireEvemtsMap[mk][platform].sptime = sptime;
  938. }
  939. expireEvemtsMap[mk][platform].list.push({ info, evExpire, spExpire, evtime, sptime });
  940. });
  941. Object.keys(expireEvemtsMap).forEach(mk => {
  942. Object.keys(expireEvemtsMap[mk]).forEach(platform => {
  943. Logs.out('invalid events, mk %d, platform %s, expire %d, evtime %d, sptime %d',
  944. mk, platform,
  945. expireEvemtsMap[mk][platform].list.length,
  946. expireEvemtsMap[mk][platform].evtime,
  947. expireEvemtsMap[mk][platform].sptime,
  948. )
  949. });
  950. });
  951. Logs.out('solutions add %d, update %d, retain %d, remove %d',
  952. updateIds.add.length, updateIds.update.length, updateIds.retain.length, updateIds.remove.length);
  953. }
  954. else {
  955. Logs.outDev('solutions update complete', updateIds);
  956. }
  957. }
  958. }
  959. /**
  960. * 获取中单方案
  961. */
  962. const getSolutions = async ({ win_min, with_events, show_lower=false, mk=-1 }) => {
  963. // Logs.out('getSolutions', win_min);
  964. const filterMarketType = +mk;
  965. const { minShowAmount } = getSetting();
  966. const solutionsList = Object.values(GAMES.Solutions);
  967. const gamesRelation = getGamesRelation();
  968. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  969. const mkCount = {
  970. all: 0,
  971. rollball: 0,
  972. today: 0,
  973. early: 0,
  974. }
  975. let solutions = solutionsList.filter(item => {
  976. const { sol: { win_average }, lower } = item;
  977. if (!show_lower && lower) {
  978. return false;
  979. }
  980. return win_average >= (win_min ?? minShowAmount);
  981. })
  982. .map(item => {
  983. const { info: { id } } = item;
  984. const { mk, rel } = relationsMap.get(id);
  985. const marketType = getMarketType(mk);
  986. mkCount.all ++;
  987. mkCount[marketType] ++;
  988. return {
  989. ...item,
  990. info: { id, mk, ...rel }
  991. }
  992. });
  993. if (mk >= 0) {
  994. solutions = solutions.filter(item => {
  995. const { info: { mk } } = item;
  996. return mk == filterMarketType;
  997. });
  998. }
  999. solutions = solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  1000. const relIds = solutions.map(item => item.info.id);
  1001. let gamesEvents;
  1002. if (with_events) {
  1003. gamesEvents = getGamesEvents({ relIds });
  1004. }
  1005. return { solutions, gamesEvents, mkCount };
  1006. }
  1007. /**
  1008. * 获取中单方案并按照比赛分组
  1009. */
  1010. const getGamePeriod = (id) => {
  1011. if (id > 0) {
  1012. return 0;
  1013. }
  1014. else if (id < 0) {
  1015. return 1;
  1016. }
  1017. return -1;
  1018. }
  1019. const getGamesSolutions = async ({ win_min, with_events, show_lower=false, mk=-1, gp=-1, tp=0, sk }) => {
  1020. const filterMarketType = +mk;
  1021. const filterGamePeriod = +gp;
  1022. const filterDataType = +tp;
  1023. const { minShowAmount } = getSetting();
  1024. const solutionsList = Object.values(GAMES.Solutions);
  1025. const gamesRelation = getGamesRelation({ listEvents: with_events });
  1026. const relationsMap = new Map(gamesRelation.map(item => [item.id, item]));
  1027. const mkCount = {
  1028. all: 0,
  1029. rollball: 0,
  1030. today: 0,
  1031. early: 0,
  1032. }
  1033. const solutionsMap = {};
  1034. solutionsList.forEach(item => {
  1035. const { info: { id }, ...solution } = item;
  1036. const { rule, sol: { win_average }, lower } = solution;
  1037. const ruleType = getRuleType(rule);
  1038. if (!show_lower && lower) {
  1039. return false;
  1040. }
  1041. if ((filterDataType == 0 || filterDataType == ruleType) &&
  1042. (!!sk || win_average >= (win_min ?? minShowAmount)) &&
  1043. (filterGamePeriod == -1 || filterGamePeriod == getGamePeriod(id))
  1044. ) {
  1045. const gameRelation = relationsMap.get(id);
  1046. if (!solutionsMap[id]) {
  1047. solutionsMap[id] = { ...gameRelation, solutions: [] };
  1048. }
  1049. solutionsMap[id].solutions.push(solution);
  1050. }
  1051. })
  1052. const gamesSolutions = Object.values(solutionsMap)
  1053. .filter(item => {
  1054. const { mk, rel, solutions } = item;
  1055. const marketType = getMarketType(mk);
  1056. if (!sk || matchGame(rel, sk)) {
  1057. mkCount.all ++;
  1058. mkCount[marketType] ++;
  1059. solutions.sort((a, b) => b.sol.win_average - a.sol.win_average);
  1060. return filterMarketType == -1 || filterMarketType == mk;
  1061. }
  1062. return false;
  1063. })
  1064. .sort((a, b) => b.solutions[0].sol.win_average - a.solutions[0].sol.win_average);
  1065. return { gamesSolutions, mkCount };
  1066. }
  1067. /**
  1068. * 获取单个中单方案
  1069. */
  1070. const getSolution = async (sid) => {
  1071. if (!sid) {
  1072. return Promise.reject(new Error('sid is required'));
  1073. }
  1074. const solution = GAMES.Solutions[sid];
  1075. if (!solution) {
  1076. return Promise.reject(new Error('solution not found'));
  1077. }
  1078. return solution;
  1079. }
  1080. /**
  1081. * 通过比赛 ID 获取中单方案
  1082. */
  1083. const getSolutionsByIds = async (ids) => {
  1084. const baseList = Object.values(GAMES.Baselist).flat();
  1085. const baseMap = new Map(baseList.map(item => [item.eventId, item]));
  1086. const result = {};
  1087. ids.forEach(id => {
  1088. const baseGame = baseMap.get(id);
  1089. if (baseGame) {
  1090. result[id] = {};
  1091. result[id].matches = baseGame.matches ?? [];
  1092. result[id].sols = [];
  1093. }
  1094. const haflId = id * -1;
  1095. const halfGame = baseMap.get(haflId);
  1096. if (halfGame) {
  1097. result[haflId] = {};
  1098. result[haflId].matches = halfGame.matches ?? [];
  1099. result[haflId].sols = [];
  1100. }
  1101. });
  1102. Object.values(GAMES.Solutions).forEach(item => {
  1103. const { info: { id }, lower } = item;
  1104. if (result[id] && !lower) {
  1105. result[id].sols.push(item);
  1106. }
  1107. });
  1108. return result;
  1109. }
  1110. /**
  1111. * 清理中单方案
  1112. */
  1113. const solutionsCleanup = () => {
  1114. const solutionsHistory = GAMES.Solutions;
  1115. const updateIds = { remove: [] }
  1116. Object.keys(solutionsHistory).forEach(sid => {
  1117. const { timestamp } = solutionsHistory[sid];
  1118. const nowTime = Date.now();
  1119. if (nowTime - timestamp > 1000*60) {
  1120. delete solutionsHistory[sid];
  1121. updateIds.remove.push(sid);
  1122. return;
  1123. }
  1124. const solution = solutionsHistory[sid];
  1125. const eventTime = solution.info.timestamp;
  1126. if (nowTime > eventTime) {
  1127. delete solutionsHistory[sid];
  1128. updateIds.remove.push(sid);
  1129. }
  1130. });
  1131. // if (updateIds.remove.length) {
  1132. // syncSolutions(updateIds);
  1133. // }
  1134. }
  1135. /**
  1136. * 清理更新时间戳
  1137. */
  1138. const cleanupUpdateTimestamp = () => {
  1139. const updateTimestamp = GAMES.UpdateTimestamp;
  1140. const nowTime = Date.now();
  1141. const expireTime = nowTime - 1000*60;
  1142. Object.keys(updateTimestamp).forEach(key => {
  1143. if (updateTimestamp[key] < expireTime) {
  1144. delete updateTimestamp[key];
  1145. }
  1146. });
  1147. }
  1148. /**
  1149. * 定时清理中单方案
  1150. * 定时清理盘口信息
  1151. */
  1152. setInterval(() => {
  1153. // cleanupBaseList();
  1154. solutionsCleanup();
  1155. gamesRelationCleanup();
  1156. cleanupUpdateTimestamp();
  1157. }, 1000*30);
  1158. /**
  1159. * 获取综合利润
  1160. */
  1161. const getTotalProfit = async (sol1, sol2, inner_base, inner_rebate) => {
  1162. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1163. inner_base = inner_base ? +inner_base : innerDefaultAmount;
  1164. inner_rebate = inner_rebate ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1165. const profit = calcTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1166. return profit;
  1167. }
  1168. /**
  1169. * 通过 sid 获取综合利润
  1170. */
  1171. const getTotalProfitWithSid = async (sid1, sid2, inner_base, inner_rebate) => {
  1172. const preSolution = GAMES.Solutions[sid1];
  1173. const subSolution = GAMES.Solutions[sid2];
  1174. const sol1 = preSolution?.sol;
  1175. const sol2 = subSolution?.sol;
  1176. if (!sol1) {
  1177. return Promise.reject(new Error('sid1 已失效'));
  1178. }
  1179. if (!sol2) {
  1180. return Promise.reject(new Error('sid2 已失效'));
  1181. }
  1182. const profit = await getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1183. return { profit, solutions: [preSolution, subSolution] };
  1184. }
  1185. /**
  1186. * 通过盘口信息获取综合利润
  1187. */
  1188. const getTotalProfitWithBetInfo = async (betInfo1, betInfo2, fixed=false, inner_base, inner_rebate) => {
  1189. if (!betInfo1?.cross_type) {
  1190. return Promise.reject(new Error('第一个下注信息无效'));
  1191. }
  1192. if (!betInfo2?.cross_type) {
  1193. return Promise.reject(new Error('第二个下注信息无效'));
  1194. }
  1195. const { innerDefaultAmount, innerRebateRatio } = getSetting();
  1196. inner_base = typeof(inner_base) != 'undefined' ? +inner_base : innerDefaultAmount;
  1197. inner_rebate = typeof(inner_rebate) != 'undefined' ? +inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1198. if (fixed) {
  1199. return calcTotalProfitWithFixedFirst(betInfo1, betInfo2, inner_base, inner_rebate);
  1200. }
  1201. const [sol1, sol2] = [betInfo1, betInfo2].map(betinfo => eventSolutions({...betinfo, inner_base, inner_rebate }));
  1202. return getTotalProfit(sol1, sol2, inner_base, inner_rebate);
  1203. }
  1204. /**
  1205. * 计算补单综合利润
  1206. */
  1207. const getTotalReplacement = async (data) => {
  1208. const { event_id, inner_ior, inner_odds, pre_bet_info } = data;
  1209. if (!event_id) {
  1210. Logs.out('getTotalReplacement event_id 无效', data);
  1211. return Promise.reject(new Error('event_id 无效'));
  1212. }
  1213. if (!inner_ior) {
  1214. Logs.out('getTotalReplacement inner_ior 无效', data);
  1215. return Promise.reject(new Error('inner_ior 无效'));
  1216. }
  1217. if (isNaN(+inner_odds)) {
  1218. Logs.out('getTotalReplacement inner_odds 无效', data);
  1219. return Promise.reject(new Error('inner_odds 无效'));
  1220. }
  1221. if (!pre_bet_info || typeof(pre_bet_info) !== 'object') {
  1222. Logs.out('getTotalReplacement pre_bet_info 无效', data);
  1223. return Promise.reject(new Error('pre_bet_info 无效'));
  1224. }
  1225. const { loss_out, inner_ref_value: inner_base, inner_odds: inner_odds_first } = getFirstInfo(pre_bet_info);
  1226. const { innerRebateRatio } = getSetting();
  1227. const inner_rebate = typeof(data.inner_rebate) != 'undefined' ? +data.inner_rebate : fixFloat(innerRebateRatio / 100, 3);
  1228. const inner_odds_value = fixFloat(inner_odds * (inner_odds_first+1), 3);
  1229. const relation = getGamesRelation({ ids: [event_id], listEvents: true, listPC: true }).map(item => {
  1230. const { rel, ...relationInfo } = item;
  1231. const tempRel = { ...rel };
  1232. const events = {};
  1233. const evtime = Date.now();
  1234. events[inner_ior] = { v: inner_odds_value };
  1235. tempRel.ps = { ...rel.ps, events, evtime, special: null, sptime: 0 }
  1236. return { ...relationInfo, rel: tempRel };
  1237. });
  1238. if (!relation?.length) {
  1239. Logs.out('getTotalReplacement 没有找到对应的比赛 data %o, relation %o', data, relation);
  1240. return Promise.reject(new Error('没有找到对应的比赛'));
  1241. }
  1242. const passableEvents = getPassableEvents(relation, null);
  1243. const solutions = eventsCombination(passableEvents, inner_base, inner_rebate);
  1244. if (!solutions?.length) {
  1245. Logs.out('getTotalReplacement 没有可用的解决方案 data %o, relation %o, passableEvents %o, solutions %o', data, relation, passableEvents, solutions);
  1246. return Promise.reject(new Error('没有可用的解决方案'));
  1247. }
  1248. Logs.out('getTotalReplacement, event_id[%d], inner_ior[%s], solutions[%d]', event_id, inner_ior, solutions.length);
  1249. // 过滤 .filter(solution => !solution.lower)
  1250. return solutions.map(solution => {
  1251. const { sid, info, sol, ...solutionInfo } = solution;
  1252. const { win_profit_rate, win_average_rate, ...solInfo } = sol;
  1253. const { cross_type } = solInfo;
  1254. solInfo.win_side_a = typeof(solInfo.win_side_a) !== 'number' ? undefined : fixFloat(solInfo.win_side_a - loss_out);
  1255. solInfo.win_side_b = typeof(solInfo.win_side_b) !== 'number' ? undefined : fixFloat(solInfo.win_side_b - loss_out);
  1256. solInfo.win_side_c = cross_type == 'la_wa_rv' ? 0 : (typeof(solInfo.win_side_c) !== 'number' ? undefined : fixFloat(solInfo.win_side_c - loss_out));
  1257. solInfo.win_average = fixFloat(solInfo.win_average - loss_out);
  1258. return { ...solutionInfo, sol: solInfo };
  1259. });
  1260. }
  1261. /**
  1262. * 同步Qboss平台配置
  1263. */
  1264. const syncQbossConfig = () => {
  1265. const setting = getSetting();
  1266. if (!setting.syncSettingEnabled) {
  1267. // Logs.outDev('syncQbossConfig disabled');
  1268. return setTimeout(syncQbossConfig, 1000*5);
  1269. }
  1270. axios.get(`${BASE_API_URL}/p/QbossSystemConfig`, { proxy: false })
  1271. .then(res => {
  1272. const { data } = res;
  1273. Logs.outDev('syncQbossConfig', data);
  1274. if (!data?.data) {
  1275. throw new Error('syncQbossConfig data is empty');
  1276. }
  1277. const {
  1278. qboss_return_ratio,
  1279. ob_return_ratio, ob_return_type, ob_odds_more_than,
  1280. im_return_ratio, im_return_type, im_odds_more_than,
  1281. hg_return_ratio, hg_return_type, hg_odds_more_than,
  1282. pc_return_ratio, pc_return_type,
  1283. qboss_jq_add_odds, qboss_jq_add_hours,
  1284. qboss_gq_add_dy_odds, qboss_gq_add_jq_odds,
  1285. bc_before_hours,
  1286. qboss_ts_sfdx_odds_add, qboss_ts_pjrq_odds_add, qboss_ts_jqs_odds_add,
  1287. } = data.data;
  1288. const qbossSetting = {
  1289. innerRebateRatio: qboss_return_ratio ? +qboss_return_ratio : 0,
  1290. obRebateRatio: ob_return_ratio ? +ob_return_ratio : 0,
  1291. obRebateType: ob_return_type ? +ob_return_type : 0,
  1292. obMaxDiff: ob_odds_more_than ? +ob_odds_more_than : 0,
  1293. imRebateRatio: im_return_ratio ? +im_return_ratio : 0,
  1294. imRebateType: im_return_type ? +im_return_type : 0,
  1295. imMaxDiff: im_odds_more_than ? +im_odds_more_than : 0,
  1296. hgRebateRatio: hg_return_ratio ? +hg_return_ratio : 0,
  1297. hgRebateType: hg_return_type ? +hg_return_type : 0,
  1298. hgMaxDiff: hg_odds_more_than ? +hg_odds_more_than : 0,
  1299. pcRebateRatio: pc_return_ratio ? +pc_return_ratio : 0,
  1300. pcRebateType: pc_return_type ? +pc_return_type : 0,
  1301. subsidyTime: qboss_jq_add_hours ? +qboss_jq_add_hours : 0,
  1302. subsidyAmount: qboss_jq_add_odds ? +qboss_jq_add_odds : 0,
  1303. subsidyRbWmAmount: qboss_gq_add_dy_odds ? +qboss_gq_add_dy_odds : 0,
  1304. subsidyRbOtAmount: qboss_gq_add_jq_odds ? +qboss_gq_add_jq_odds : 0,
  1305. innerRouSubsidyValue: qboss_ts_sfdx_odds_add ? +qboss_ts_sfdx_odds_add : 0,
  1306. innerWmSubsidyRatio: qboss_ts_pjrq_odds_add ? +qboss_ts_pjrq_odds_add : 0,
  1307. innerOtSubsidyRatio: qboss_ts_jqs_odds_add ? +qboss_ts_jqs_odds_add : 0,
  1308. halfTimeActiveTime: bc_before_hours ? +bc_before_hours : 0,
  1309. };
  1310. Logs.outDev('syncQbossConfig', qbossSetting);
  1311. const settingFields = {};
  1312. let needUpdate = false;
  1313. Object.keys(qbossSetting).forEach(key => {
  1314. if (qbossSetting[key] !== setting[key]) {
  1315. settingFields[key] = qbossSetting[key];
  1316. needUpdate = true;
  1317. }
  1318. });
  1319. if (needUpdate) {
  1320. Setting.update(settingFields);
  1321. // Logs.outDev('syncQbossConfig', settingFields);
  1322. }
  1323. // else {
  1324. // Logs.outDev('syncQbossConfig no change');
  1325. // }
  1326. })
  1327. .catch(err => {
  1328. Logs.out('syncQbossConfig error', err.message);
  1329. })
  1330. .finally(() => {
  1331. setTimeout(syncQbossConfig, 1000*15);
  1332. });
  1333. }
  1334. syncQbossConfig();
  1335. /**
  1336. * 异常通知
  1337. */
  1338. const notifyException = (message) => {
  1339. if (IS_DEV) {
  1340. return Logs.out('notifyException', { message });
  1341. }
  1342. const chat_id = -1003032820471;
  1343. Promise.all([
  1344. axios.get(`${BASE_API_URL}/telegram/jump`, { params: { chat_id, message: `@taoger369 ${message}` } }, { proxy: false }),
  1345. axios.post('https://push.long.bid/bark', {
  1346. title: 'QBoss异常通知',
  1347. content: message,
  1348. topic: 'default',
  1349. icon: 'https://bwh.flyzto.com/icon/ball.png',
  1350. }, { proxy: false }),
  1351. ])
  1352. .then(() => {
  1353. Logs.out('notifyException', '通知成功');
  1354. })
  1355. .catch(err => {
  1356. Logs.out('notifyException', err.message);
  1357. });
  1358. }
  1359. /**
  1360. * 从子进程获取数据
  1361. */
  1362. const getDataFromChild = (type, callback) => {
  1363. const id = ++Request.count;
  1364. Request.callbacks[id] = callback;
  1365. events_child.send({ method: 'get', id, type });
  1366. }
  1367. /**
  1368. * 向子进程发送数据
  1369. */
  1370. const postDataToChild = (type, data) => {
  1371. events_child.send({ method: 'post', type, data });
  1372. }
  1373. /**
  1374. * 处理子进程消息
  1375. */
  1376. events_child.on('message', async (message) => {
  1377. const { callbacks } = Request;
  1378. const { method, id, type, data } = message;
  1379. if (method == 'get' && id) {
  1380. let responseData = null;
  1381. if (type == 'getGamesRelation') {
  1382. responseData = getGamesRelation({ listEvents: true });
  1383. }
  1384. else if (type == 'getSetting') {
  1385. responseData = getSetting();
  1386. }
  1387. // else if (type == 'getSolutionHistory') {
  1388. // responseData = getSolutionHistory();
  1389. // }
  1390. events_child.send({ type: 'response', id, data: responseData });
  1391. }
  1392. else if (method == 'post') {
  1393. if (type == 'updateSolutions') {
  1394. updateSolutions(data.solutions, data.eventsLogsMap);
  1395. }
  1396. }
  1397. else if (type == 'response' && id && callbacks[id]) {
  1398. callbacks[id](data);
  1399. delete callbacks[id];
  1400. }
  1401. });
  1402. events_child.stderr?.on('data', data => {
  1403. Logs.out('events_child stderr', data.toString());
  1404. });
  1405. const settingUpdate = (fields) => {
  1406. updateSetting(fields);
  1407. postDataToChild('updateSetting', fields);
  1408. }
  1409. const syncSetting = async () => {
  1410. const setting = await Setting.get();
  1411. settingUpdate(setting.toObject());
  1412. }
  1413. syncSetting();
  1414. Setting.onUpdate(settingUpdate);
  1415. /**
  1416. * 保存GAMES数据到缓存文件
  1417. */
  1418. const saveGamesToCache = () => {
  1419. Cache.setData(GamesCacheFile, GAMES, err => {
  1420. if (err) {
  1421. Logs.out('Failed to save games cache:', err.message);
  1422. }
  1423. else {
  1424. Logs.out('Games cache saved successfully');
  1425. }
  1426. });
  1427. }
  1428. /**
  1429. * 从缓存文件加载GAMES数据
  1430. */
  1431. const loadGamesFromCache = () => {
  1432. const gamesCacheData = Cache.getData(GamesCacheFile, true) ?? {};
  1433. Object.keys(GAMES).forEach(key => {
  1434. if (key in gamesCacheData) {
  1435. GAMES[key] = gamesCacheData[key];
  1436. }
  1437. });
  1438. Logs.out('Games cache loaded successfully');
  1439. }
  1440. // 在模块加载时尝试从缓存恢复数据
  1441. loadGamesFromCache();
  1442. // 监听进程退出事件,保存GAMES数据
  1443. process.on('exit', saveGamesToCache);
  1444. process.on('SIGINT', () => {
  1445. process.exit(0);
  1446. });
  1447. process.on('SIGTERM', () => {
  1448. process.exit(0);
  1449. });
  1450. process.on('SIGUSR2', () => {
  1451. process.exit(0);
  1452. });
  1453. module.exports = {
  1454. updateLeaguesList, getFilteredLeagues,
  1455. updateGamesList, updateGamesEvents, updateBaseEvents,
  1456. getGamesRelation,
  1457. updateGamesResult,
  1458. updateOriginalData, getOriginalData,
  1459. getSolutions, getGamesSolutions, getSolution, getSolutionsByIds,
  1460. getTotalProfitWithSid, getTotalProfitWithBetInfo, getTotalReplacement,
  1461. notifyException,
  1462. }