GamesPs.js 49 KB

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