GamesPs.js 45 KB

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