GamesPs.js 45 KB

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