warframe-nexus-query 2.1.1 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Statistics calculator for order data
3
+ * Replaces v1's pre-calculated statistics with client-side calculation
4
+ */
5
+
6
+ /**
7
+ * Calculate statistics from order list
8
+ * @param {Array<Order>} orders - Array of orders
9
+ * @param {Object} options - Calculation options
10
+ * @param {string} [options.type='sell'] - Order type ('buy' or 'sell')
11
+ * @param {boolean} [options.onlineOnly=true] - Only include online users
12
+ * @param {boolean} [options.includeOutliers=true] - Include price outliers
13
+ * @returns {Object} Statistics object
14
+ */
15
+ export function calculateStatistics(orders, options = {}) {
16
+ const { type = 'sell', onlineOnly = true, includeOutliers = true } = options;
17
+
18
+ // Filter orders
19
+ let filtered = orders.filter((o) => o.type === type);
20
+
21
+ // Filter online users only
22
+ if (onlineOnly) {
23
+ filtered = filtered.filter((o) => o.isUserOnline());
24
+ }
25
+
26
+ // Extract prices
27
+ let prices = filtered.map((o) => o.platinum).sort((a, b) => a - b);
28
+
29
+ // Remove outliers if requested (using IQR method)
30
+ if (!includeOutliers && prices.length > 4) {
31
+ prices = removeOutliers(prices);
32
+ }
33
+
34
+ // If no prices, return empty stats
35
+ if (prices.length === 0) {
36
+ return {
37
+ volume: 0,
38
+ orderCount: 0,
39
+ median: 0,
40
+ min: 0,
41
+ max: 0,
42
+ avg: 0,
43
+ q1: 0,
44
+ q3: 0,
45
+ };
46
+ }
47
+
48
+ // Calculate volume
49
+ const volume = filtered.reduce((sum, o) => sum + o.quantity, 0);
50
+
51
+ // Calculate statistics
52
+ const median = calculateMedian(prices);
53
+ const min = prices[0];
54
+ const max = prices[prices.length - 1];
55
+ const avg = prices.reduce((a, b) => a + b, 0) / prices.length;
56
+ const q1 = calculatePercentile(prices, 25);
57
+ const q3 = calculatePercentile(prices, 75);
58
+
59
+ return {
60
+ volume,
61
+ orderCount: filtered.length,
62
+ median: Math.round(median),
63
+ min,
64
+ max,
65
+ avg: Math.round(avg),
66
+ q1: Math.round(q1),
67
+ q3: Math.round(q3),
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Calculate median of sorted array
73
+ * @param {number[]} sortedPrices - Sorted price array
74
+ * @returns {number}
75
+ */
76
+ function calculateMedian(sortedPrices) {
77
+ const len = sortedPrices.length;
78
+ if (len === 0) return 0;
79
+ if (len === 1) return sortedPrices[0];
80
+
81
+ const mid = Math.floor(len / 2);
82
+ if (len % 2 === 0) {
83
+ return (sortedPrices[mid - 1] + sortedPrices[mid]) / 2;
84
+ }
85
+ return sortedPrices[mid];
86
+ }
87
+
88
+ /**
89
+ * Calculate percentile of sorted array
90
+ * @param {number[]} sortedPrices - Sorted price array
91
+ * @param {number} percentile - Percentile (0-100)
92
+ * @returns {number}
93
+ */
94
+ function calculatePercentile(sortedPrices, percentile) {
95
+ if (sortedPrices.length === 0) return 0;
96
+ if (sortedPrices.length === 1) return sortedPrices[0];
97
+
98
+ const index = (percentile / 100) * (sortedPrices.length - 1);
99
+ const lower = Math.floor(index);
100
+ const upper = Math.ceil(index);
101
+ const weight = index - lower;
102
+
103
+ return sortedPrices[lower] * (1 - weight) + sortedPrices[upper] * weight;
104
+ }
105
+
106
+ /**
107
+ * Remove outliers using IQR method
108
+ * @param {number[]} sortedPrices - Sorted price array
109
+ * @returns {number[]}
110
+ */
111
+ function removeOutliers(sortedPrices) {
112
+ const q1 = calculatePercentile(sortedPrices, 25);
113
+ const q3 = calculatePercentile(sortedPrices, 75);
114
+ const iqr = q3 - q1;
115
+ const lowerBound = q1 - 1.5 * iqr;
116
+ const upperBound = q3 + 1.5 * iqr;
117
+
118
+ return sortedPrices.filter((price) => price >= lowerBound && price <= upperBound);
119
+ }
120
+
121
+ /**
122
+ * Get best orders (lowest sell / highest buy)
123
+ * @param {Array<Order>} orders - Array of orders
124
+ * @param {Object} options - Options
125
+ * @param {number} [options.limit=5] - Number of orders to return
126
+ * @param {boolean} [options.onlineOnly=true] - Only online users
127
+ * @returns {Object} { buy: Order[], sell: Order[] }
128
+ */
129
+ export function getBestOrders(orders, options = {}) {
130
+ const { limit = 5, onlineOnly = true } = options;
131
+
132
+ // Filter online if requested
133
+ let filtered = orders;
134
+ if (onlineOnly) {
135
+ filtered = orders.filter((o) => o.isUserOnline());
136
+ }
137
+
138
+ // Separate buy and sell orders
139
+ const buyOrders = filtered.filter((o) => o.isBuyOrder()).sort((a, b) => b.platinum - a.platinum);
140
+
141
+ const sellOrders = filtered.filter((o) => o.isSellOrder()).sort((a, b) => a.platinum - b.platinum);
142
+
143
+ return {
144
+ buy: buyOrders.slice(0, limit),
145
+ sell: sellOrders.slice(0, limit),
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Format price range string
151
+ * @param {Object} stats - Statistics object
152
+ * @returns {string}
153
+ */
154
+ export function formatPriceRange(stats) {
155
+ if (stats.orderCount === 0) {
156
+ return 'No orders found';
157
+ }
158
+
159
+ if (stats.min === stats.max) {
160
+ return `${stats.min}p`;
161
+ }
162
+
163
+ return `${stats.min}p - ${stats.max}p (median: ${stats.median}p)`;
164
+ }
165
+
166
+ /**
167
+ * Format statistics for display
168
+ * @param {Object} stats - Statistics object
169
+ * @param {string} type - Order type ('buy' or 'sell')
170
+ * @returns {string}
171
+ */
172
+ export function formatStatistics(stats, type = 'sell') {
173
+ const action = type === 'sell' ? 'Sellers' : 'Buyers';
174
+
175
+ if (stats.orderCount === 0) {
176
+ return `No ${action.toLowerCase()} found`;
177
+ }
178
+
179
+ return [
180
+ `**${action}:** ${stats.orderCount} orders (${stats.volume} items)`,
181
+ `**Median:** ${stats.median}p`,
182
+ `**Range:** ${stats.min}p - ${stats.max}p`,
183
+ `**Average:** ${stats.avg}p`,
184
+ ].join('\n');
185
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "warframe-nexus-query",
3
- "version": "2.1.1",
3
+ "version": "2.2.1",
4
4
  "description": "Query prices form nexus-stats.com and warframe.market.",
5
5
  "keywords": [
6
6
  "warframe",
@@ -12,7 +12,10 @@
12
12
  "bugs": {
13
13
  "url": "https://github.com/WFCD/warframe-nexus-query/issues"
14
14
  },
15
- "repository": "https://github.com/WFCD/warframe-nexus-query",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/WFCD/warframe-nexus-query.git"
18
+ },
16
19
  "license": "Apache-2.0",
17
20
  "author": "tobitenno",
18
21
  "type": "module",
@@ -33,80 +36,8 @@
33
36
  "prepare": "husky && npx install-peerdeps @wfcd/eslint-config@latest -S",
34
37
  "test": "c8 mocha"
35
38
  },
36
- "commitlint": {
37
- "extends": [
38
- "@commitlint/config-conventional"
39
- ],
40
- "rules": {
41
- "body-max-line-length": [
42
- 0
43
- ]
44
- }
45
- },
46
- "lint-staged": {
47
- "*.js": [
48
- "eslint --cache --fix"
49
- ],
50
- "package*.json": [
51
- "prettier --write",
52
- "npm dedupe",
53
- "npx sort-package-json"
54
- ],
55
- "*.{json,yaml,yml},!package*.json": [
56
- "prettier --write"
57
- ]
58
- },
59
- "babel": {
60
- "plugins": [
61
- "@babel/plugin-transform-class-properties",
62
- "@babel/plugin-transform-private-methods"
63
- ],
64
- "presets": [
65
- "@babel/preset-env"
66
- ]
67
- },
68
- "prettier": "@wfcd/eslint-config/prettier",
69
- "eslintConfig": {
70
- "extends": "@wfcd/eslint-config/esm",
71
- "rules": {
72
- "no-underscore-dangle": [
73
- "error",
74
- {
75
- "allow": [
76
- "__basedir"
77
- ]
78
- }
79
- ]
80
- }
81
- },
82
- "eslintIgnore": [
83
- ".github/**",
84
- "docs/**",
85
- "resources/**",
86
- "types/**"
87
- ],
88
- "release": {
89
- "branch": "master"
90
- },
91
- "mocha": {
92
- "bail": true,
93
- "exit": true,
94
- "slow": 10000,
95
- "spec": "test/test.js",
96
- "timeout": 30000
97
- },
98
- "c8": {
99
- "exclude": [
100
- "test/*",
101
- "lib/nexus/*"
102
- ],
103
- "reporter": [
104
- "lcov",
105
- "text"
106
- ],
107
- "skip-full": true
108
- },
109
39
  "dependencies": {
40
+ "flat-cache": "^6.1.19",
110
41
  "get-image-colors": "^4.0.1",
111
42
  "image-downloader": "^4.0.2",
112
43
  "json-fetch-cache": "^1.2.6",
@@ -1,148 +0,0 @@
1
- import fs from 'node:fs/promises';
2
-
3
- import getColors from 'get-image-colors';
4
- import imageDownloader from 'image-downloader';
5
- import jsonQuery from 'json-query';
6
- import JSONCache from 'json-fetch-cache';
7
-
8
- import baseDir from '../../../basedir.js';
9
-
10
- import MarketSummary from './summary.js';
11
-
12
- /**
13
- * @typedef {Object} MappedPrice
14
- * @property {string} volume
15
- * @property {string} median
16
- * @property {string} max_price
17
- * @property {string} min_price
18
- * @property {string} datetime ts formatted date string
19
- */
20
-
21
- export default class MarketFetcher {
22
- constructor({ logger = console, settings, marketCache }) {
23
- /**
24
- * The json cache stored data from warframe.market
25
- * @type {JSONCache}
26
- */
27
- this.marketCache = marketCache || new JSONCache(settings.urls.market, settings.maxCacheLength, { logger });
28
-
29
- this.settings = settings;
30
- this.urls = {
31
- market: process.env.MARKET_URL_OVERRIDE || 'https://api.warframe.market',
32
- marketAssets: process.env.MARKET_ASSETS_URL_OVERRIDE || 'https://warframe.market/static/assets/',
33
- marketBasePath: '/v1/items/',
34
- };
35
-
36
- this.logger = logger;
37
-
38
- this.logger.info('finished setting up market fetcher');
39
- }
40
-
41
- async averagesForItem(urlName, platform = 'pc') {
42
- const reqOpts = {
43
- headers: {
44
- platform: platform.toLowerCase(),
45
- },
46
- };
47
- const data = await fetch(`${this.urls.market}${this.urls.marketBasePath}${urlName}/statistics`, reqOpts).then((d) =>
48
- d.json()
49
- );
50
- /**
51
- * @type {MappedPrice[]}
52
- */
53
- const stats = data.payload.statistics_live['48hours'];
54
-
55
- // Descending sort
56
- stats.sort((a, b) => {
57
- const tsA = new Date(a.datetime).getTime();
58
- const tsB = new Date(b.datetime).getTime();
59
- if (tsA === tsB) return 0;
60
- if (tsA < tsB) return -1;
61
- if (tsA > tsB) return 1;
62
- /* istanbul ignore next */
63
- return 0;
64
- });
65
-
66
- const deepData = stats[0];
67
- return {
68
- soldCount: deepData ? Number.parseInt(deepData.volume, 10) : undefined,
69
- soldPrice: deepData ? Number.parseInt(deepData.median, 10) : undefined,
70
- maximum: deepData ? Number.parseInt(deepData.max_price, 10) : undefined,
71
- minimum: deepData ? Number.parseInt(deepData.min_price, 10) : undefined,
72
- };
73
- }
74
-
75
- async resultForItem(urlName, platform = 'pc') {
76
- const reqOpts = {
77
- headers: {
78
- platform: platform.toLowerCase(),
79
- },
80
- };
81
- const res = await fetch(`${this.urls.market}${this.urls.marketBasePath}${urlName}`, reqOpts).then((d) => d.json());
82
- return res.payload ? Promise.all(res.payload.item.items_in_set.map((item) => this.summaryForItem(item))) : {};
83
- }
84
-
85
- /**
86
- * Construct a summary for the market item
87
- * @param {Object} item Warframe.market Item
88
- * @returns {Object} Market summary for item
89
- */
90
- async summaryForItem(item) {
91
- try {
92
- // set up temp folder
93
- await fs.mkdir(`${baseDir}/tmp`);
94
- } catch (e) {
95
- // this.logger.error(e);
96
- }
97
- const summary = new MarketSummary(item);
98
-
99
- summary.prices = await this.averagesForItem(item.url_name);
100
- const options = {
101
- url: summary.thumbnail,
102
- dest: `${baseDir}/tmp/${summary.name}.png`,
103
- };
104
- try {
105
- const { image } = await imageDownloader.image(options);
106
- if (image) {
107
- const colors = await getColors(image, 'image/png');
108
- summary.color = typeof colors !== 'undefined' ? colors[0].hex().replace('#', '0x') : 0xff0000;
109
- }
110
- } catch (e) {
111
- /* istanbul ignore next */
112
- this.logger.error(e);
113
- } finally {
114
- await fs.unlink(`${baseDir}/tmp/${summary.name}.png`);
115
- }
116
- return summary;
117
- }
118
-
119
- async queryMarket(query, { successfulQuery, platform = 'pc' }) {
120
- this.logger.info(`querying market for ${query} on ${platform}`);
121
- const attachments = [];
122
- try {
123
- // get market data
124
- const marketData = await this.marketCache.getDataJson();
125
- if (!marketData) {
126
- this.logger.info('No market data!');
127
- return [];
128
- }
129
- const marketResults = jsonQuery(`items[*item_name~/^${successfulQuery || query}.*/i]`, {
130
- data: marketData.payload || {},
131
- allowRegexp: true,
132
- }).value;
133
- if (!marketResults || marketResults.length < 1) {
134
- this.logger.info('No market results!');
135
- return [];
136
- }
137
-
138
- const marketComponents = await this.resultForItem(marketResults[0].url_name, platform);
139
- if (marketComponents.length > 0) {
140
- attachments.push(...marketComponents);
141
- }
142
- } catch (err) {
143
- /* istanbul ignore next */
144
- this.logger.error(err);
145
- }
146
- return attachments;
147
- }
148
- }
@@ -1,65 +0,0 @@
1
- const urls = {
2
- market: process.env.MARKET_URL_OVERRIDE || 'https://api.warframe.market/v1/items',
3
- marketAssets: process.env.MARKET_ASSETS_URL_OVERRIDE || 'https://warframe.market/static/assets/',
4
- };
5
-
6
- /**
7
- * Represents an individual component object of an item.
8
- */
9
- export default class Summary {
10
- /**
11
- * Represents an individual item.
12
- * @param {json} itemData the component data to parse into a summary
13
- * @constructor
14
- */
15
- constructor(itemData) {
16
- this.name = itemData.en.item_name.trim();
17
- this.thumbnail = `${urls.marketAssets}${itemData.thumb}`;
18
- this.partThumb = `${urls.marketAssets}${itemData.sub_icon}`;
19
- this.tradingTax = itemData.trading_tax || 0;
20
- this.ducats = itemData.ducats || 0;
21
- this.masteryLevel = itemData.mastery_level;
22
- this.tradable = itemData.tradable;
23
- this.wikiUrl = itemData.en.wiki_link;
24
- this.codex = itemData.en.codex;
25
- this.description = itemData.en.description.replace(/<\/?p>/gi, '');
26
- this.drops = itemData.en.drop;
27
- this.url = `http://warframe.market/items/${itemData.url_name}`;
28
-
29
- this.type = 'market-v1';
30
- }
31
-
32
- /**
33
- * The components' string representation
34
- * @param {string} opt Option, either 'codex', 'item', 'location', 'all'
35
- * @returns {string}
36
- */
37
- toString(opt = 'item') {
38
- let value = this.name;
39
- if (opt === 'codex' || opt === 'all') {
40
- value += `\`\`\`\nCodex: ${this.codex}\n`;
41
- }
42
- if (opt === 'item' || opt === 'all') {
43
- value +=
44
- `${this.pad(`Requires: ${this.masteryLevel}`, 15)}| Tax: ${this.pad(`${this.tradingTax}cr`)}\n` +
45
- `Item is ${this.tradable ? '' : ' not '} tradable\n` +
46
- `${this.pad(`Sold ${this.prices.soldCount} for ${this.prices.soldPrice}`, 15)}|` +
47
- `Minimum ${this.prices.minimum} | Maximum ${this.prices.maximum}\n`;
48
- }
49
- if (opt === 'location' || opt === 'all') {
50
- value += `${this.pad(`Drops: ${this.drops.map((drop) => drop.name).join(', ')}`, 15)}\n`;
51
- }
52
- value += `\`\`\`\n${this.wikiUrl}`;
53
- return `\u221F${value}`;
54
- }
55
-
56
- pad(str, length = 10, character = ' ') {
57
- let stringRet;
58
- if (str.length < length) {
59
- stringRet = this.pad(`${str}${character}`);
60
- } else {
61
- stringRet = str;
62
- }
63
- return stringRet;
64
- }
65
- }