GamesPs.js 45 KB

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