@icgio/icg-utils 1.9.74 → 1.9.75
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.
- package/README.md +18 -177
- package/index.js +0 -3
- package/lib/influxdb.js +54 -76
- package/lib/logger.js +1 -19
- package/lib/market-history-buffer.js +2 -8
- package/lib/observable.js +0 -18
- package/lib/ohlcv.js +0 -7
- package/lib/ordered-dict.js +4 -31
- package/lib/rate-limiter.js +4 -16
- package/lib/rates.js +66 -197
- package/lib/utils.js +58 -604
- package/package.json +1 -4
- package/lib/ip.js +0 -19
- package/test/combine-orderbooks.test.js +0 -226
- package/test/merge-trades.test.js +0 -327
- package/test/ordered-dict.test.js +0 -343
- package/test/rate-limiter.test.js +0 -60
- package/test/sorted-book.test.js +0 -257
package/README.md
CHANGED
|
@@ -1,189 +1,30 @@
|
|
|
1
1
|
# ICG Utils
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## Features
|
|
6
|
-
|
|
7
|
-
- **Crypto Rate Fetching**: Get cryptocurrency prices from CoinMarketCap and CoinGecko
|
|
8
|
-
- **Forex Rates**: Fetch foreign exchange rates
|
|
9
|
-
- **InfluxDB Integration**: Write and query time-series data
|
|
10
|
-
- **Orderbook Utilities**: Advanced orderbook processing and combination
|
|
11
|
-
- **Rate Limiting**: Control request frequency to avoid API throttling
|
|
12
|
-
- **Observable Pattern**: Reactive data streams implementation
|
|
13
|
-
- **OHLCV Processing**: Candlestick data aggregation and manipulation
|
|
14
|
-
- **Logging**: Structured logging with Winston
|
|
15
|
-
|
|
16
|
-
## Installation
|
|
3
|
+
Shared helpers for the ICG trading services: exchange rates, InfluxDB access, orderbook math, rate limiting and logging.
|
|
17
4
|
|
|
18
5
|
```bash
|
|
19
6
|
npm install @icgio/icg-utils
|
|
20
7
|
```
|
|
21
8
|
|
|
22
|
-
##
|
|
23
|
-
|
|
24
|
-
### Crypto Rates
|
|
25
|
-
|
|
26
|
-
```javascript
|
|
27
|
-
const { coinmarketcap, coingecko } = require('@icgio/icg-utils')
|
|
28
|
-
|
|
29
|
-
// Get crypto prices
|
|
30
|
-
const btc_price = await coinmarketcap.get_price('BTC')
|
|
31
|
-
const eth_price = await coingecko.get_price('ETH')
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
### InfluxDB
|
|
35
|
-
|
|
36
|
-
```javascript
|
|
37
|
-
const { influx } = require('@icgio/icg-utils')
|
|
38
|
-
|
|
39
|
-
// Write data points
|
|
40
|
-
await influx.write_point(measurement, tags, fields)
|
|
41
|
-
|
|
42
|
-
// Query data
|
|
43
|
-
const results = await influx.query(query)
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
### Rate Limiter
|
|
47
|
-
|
|
48
|
-
```javascript
|
|
49
|
-
const { rate_limiter: RateLimiter } = require('@icgio/icg-utils')
|
|
50
|
-
|
|
51
|
-
const limiter = new RateLimiter({
|
|
52
|
-
max_concurrent: 5,
|
|
53
|
-
interval_concurrent: 1000,
|
|
54
|
-
abandon_tx: false,
|
|
55
|
-
only_same_args: false,
|
|
56
|
-
})
|
|
57
|
-
|
|
58
|
-
// Process function with rate limiting
|
|
59
|
-
await limiter.process(async_function, arg1, arg2)
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
### Orderbook Utilities
|
|
63
|
-
|
|
64
|
-
```javascript
|
|
65
|
-
const { utils } = require('@icgio/icg-utils')
|
|
66
|
-
|
|
67
|
-
// Get position by volume
|
|
68
|
-
const position = utils.vol_position(orderbook, target_volume)
|
|
69
|
-
|
|
70
|
-
// Get position by sum (quote currency)
|
|
71
|
-
const position = utils.sum_position(orderbook, target_sum)
|
|
72
|
-
|
|
73
|
-
// Combine orderbooks from multiple exchanges
|
|
74
|
-
const combined = utils.combine_orderbooks(orderbooks_dict, depth)
|
|
75
|
-
|
|
76
|
-
// Find arbitrage opportunities
|
|
77
|
-
const opportunities = utils.arb_opportunities_from_combined_orderbook(combined_orderbook, profit_percentage, amount_cap)
|
|
78
|
-
|
|
79
|
-
// Parse trading pair
|
|
80
|
-
const [base, quote] = utils.parse_pair('BTCUSDT') // ['BTC', 'USDT']
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
### Observable
|
|
84
|
-
|
|
85
|
-
```javascript
|
|
86
|
-
const { observable } = require('@icgio/icg-utils')
|
|
87
|
-
|
|
88
|
-
// Create observable
|
|
89
|
-
const obs = observable.create()
|
|
90
|
-
|
|
91
|
-
// Subscribe to changes
|
|
92
|
-
obs.subscribe((value) => {
|
|
93
|
-
console.log('Value changed:', value)
|
|
94
|
-
})
|
|
95
|
-
|
|
96
|
-
// Update value
|
|
97
|
-
obs.next(new_value)
|
|
98
|
-
```
|
|
99
|
-
|
|
100
|
-
### OHLCV
|
|
101
|
-
|
|
102
|
-
```javascript
|
|
103
|
-
const { ohlcv } = require('@icgio/icg-utils')
|
|
104
|
-
|
|
105
|
-
// Process OHLCV data
|
|
106
|
-
const processed = ohlcv.aggregate(candles, interval)
|
|
107
|
-
```
|
|
108
|
-
|
|
109
|
-
### Logger
|
|
110
|
-
|
|
111
|
-
```javascript
|
|
112
|
-
const { logger } = require('@icgio/icg-utils')
|
|
113
|
-
|
|
114
|
-
logger.info('Info message')
|
|
115
|
-
logger.error('Error message')
|
|
116
|
-
logger.warn('Warning message')
|
|
117
|
-
```
|
|
118
|
-
|
|
119
|
-
### Constants
|
|
120
|
-
|
|
121
|
-
```javascript
|
|
122
|
-
const { constants } = require('@icgio/icg-utils')
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
## Project Structure
|
|
126
|
-
|
|
127
|
-
```
|
|
128
|
-
icg-utils/
|
|
129
|
-
├── index.js # Main entry point
|
|
130
|
-
├── lib/
|
|
131
|
-
│ ├── crypto-rates.js # CoinMarketCap/CoinGecko integration
|
|
132
|
-
│ ├── dex-rate.js # DEX rate fetching
|
|
133
|
-
│ ├── forex-rate.js # Forex rate fetching
|
|
134
|
-
│ ├── influxdb.js # InfluxDB client
|
|
135
|
-
│ ├── ip.js # IP utilities
|
|
136
|
-
│ ├── logger.js # Winston logger
|
|
137
|
-
│ ├── observable.js # Observable pattern
|
|
138
|
-
│ ├── ohlcv.js # OHLCV processing
|
|
139
|
-
│ ├── rate-limiter.js # Rate limiting
|
|
140
|
-
│ └── utils.js # General utilities
|
|
141
|
-
├── constants/
|
|
142
|
-
│ ├── coins-map-coingecko.js # CoinGecko mappings
|
|
143
|
-
│ └── coins-map-coinmarketcap.js # CMC mappings
|
|
144
|
-
└── package.json
|
|
145
|
-
```
|
|
146
|
-
|
|
147
|
-
## Key Utility Functions
|
|
148
|
-
|
|
149
|
-
### Orderbook Processing
|
|
150
|
-
|
|
151
|
-
| Function | Description |
|
|
152
|
-
| ------------------------------------------- | ---------------------------------------- |
|
|
153
|
-
| `vol_position` | Find position in orderbook by volume |
|
|
154
|
-
| `sum_position` | Find position in orderbook by quote sum |
|
|
155
|
-
| `price_position` | Find position in orderbook by price |
|
|
156
|
-
| `level_position` | Find position by orderbook level |
|
|
157
|
-
| `combine_orderbooks` | Merge orderbooks from multiple exchanges |
|
|
158
|
-
| `arb_opportunities_from_combined_orderbook` | Find arbitrage opportunities |
|
|
159
|
-
|
|
160
|
-
### General Utilities
|
|
161
|
-
|
|
162
|
-
| Function | Description |
|
|
163
|
-
| -------------------- | ------------------------------------ |
|
|
164
|
-
| `parse_pair` | Parse trading pair into base/quote |
|
|
165
|
-
| `reverse_pair` | Reverse a trading pair |
|
|
166
|
-
| `round` | Round number to precision |
|
|
167
|
-
| `ordered_dict` | Sorted dictionary for orderbooks |
|
|
168
|
-
| `number_with_commas` | Format numbers with comma separators |
|
|
169
|
-
|
|
170
|
-
## Dependencies
|
|
9
|
+
## Exports
|
|
171
10
|
|
|
172
|
-
|
|
|
173
|
-
|
|
|
174
|
-
|
|
|
175
|
-
|
|
|
176
|
-
| `
|
|
177
|
-
| `
|
|
178
|
-
| `
|
|
179
|
-
| `
|
|
11
|
+
| Export | What it is |
|
|
12
|
+
| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
13
|
+
| `crypto_rates(cb, curs, type)` | `'curs'`: Coinpaprika USD prices for a list of symbols. `'curs_dict'`: mid of `<cur>/USDT` on the exchange named per currency, e.g. `{ B3TR: 'mexc' }`. Calls back with `{ CUR: { USD, USDT } }`, leaving out currencies it could not price. |
|
|
14
|
+
| `forex_rate.get_forex_rate_usd(curs, cb)` | USD value of one unit of each fiat currency. |
|
|
15
|
+
| `influx` | `new Influx({ url, token, org, org_id, bucket, schema, transportOptions })` with `query(flux, cb)` and `write_points_with_check(points, cb)`. Writes drop points or fields that `schema` does not know and values that are missing or not finite, and create the bucket on first use. |
|
|
16
|
+
| `rate_limiter` | `new RateLimiter({ max_concurrent, interval_concurrent, abandon_tx, only_same_args })`, then `limiter.process(fn, ...args)`. Setting `limiter.priority` before `process` queues that call ahead of higher numbers. |
|
|
17
|
+
| `sorted_book`, `utils.ordered_dict` | Price-level books keyed by price: a red-black tree for large books, a binary-searched array for small ones. |
|
|
18
|
+
| `market_history_buffer` | Record, prune and read the per-pair trade buffers in `market.market_history_dict`. |
|
|
19
|
+
| `observable` | Minimal `subscribe` / `notify` class. |
|
|
20
|
+
| `ohlcv(pair, interval, cb)` | Binance klines. |
|
|
21
|
+
| `logger` | Winston console logger. |
|
|
22
|
+
| `utils` | Orderbook math (`level_position`, `price_position`, `orderbook_mid`, `orderbook_spread`, `depth_within_pct`, `max_level_gap`, `combine_orderbooks`), `merge_trades_with_same_id`, pairs and exchange keys (`parse_pair`, `exchange_base_from_key`, `is_exchange_account_key`, `exchange_cur_quote_cur_converter`), formatting (`round`, `number_with_commas`, `format_amount`, `sort_keys`) and `convert_deposit_withdrawal_chain`. |
|
|
180
23
|
|
|
181
|
-
|
|
24
|
+
Loading the package also adds `Number.prototype.toStringNoExponents`, `Date.prototype.addHours`, `floorHours`, `addMinutes` and `addSeconds`, and `String.prototype.replaceAt` (used by `message_prefix` in each MM server's `config/settings.js`, which is not in git).
|
|
182
25
|
|
|
183
|
-
|
|
184
|
-
- Variable naming: `snake_case`
|
|
185
|
-
- Extends native prototypes for convenience (Number, Date, String)
|
|
26
|
+
Exchange accounts are keyed `<base>_<index>`, e.g. `mexc_1`; `exchange_cur_quote_cur_converter` picks one primary account per base from `exchange_roles` and treats the rest as its affiliates.
|
|
186
27
|
|
|
187
|
-
##
|
|
28
|
+
## Development
|
|
188
29
|
|
|
189
|
-
|
|
30
|
+
CommonJS, `snake_case`, Prettier (`.prettierrc.json`).
|
package/index.js
CHANGED
|
@@ -3,15 +3,12 @@ const rates = require('./lib/rates.js')
|
|
|
3
3
|
module.exports = {
|
|
4
4
|
crypto_rates: rates.get_crypto_rates,
|
|
5
5
|
forex_rate: { get_forex_rate_usd: rates.get_forex_rate_usd },
|
|
6
|
-
rates,
|
|
7
6
|
influx: require('./lib/influxdb.js'),
|
|
8
|
-
ip: require('./lib/ip.js'),
|
|
9
7
|
logger: require('./lib/logger.js'),
|
|
10
8
|
observable: require('./lib/observable.js'),
|
|
11
9
|
ohlcv: require('./lib/ohlcv'),
|
|
12
10
|
market_history_buffer: require('./lib/market-history-buffer.js'),
|
|
13
11
|
rate_limiter: require('./lib/rate-limiter.js'),
|
|
14
|
-
ordered_dict: require('./lib/ordered-dict.js').ordered_dict,
|
|
15
12
|
sorted_book: require('./lib/sorted-book.js'),
|
|
16
13
|
utils: require('./lib/utils.js'),
|
|
17
14
|
}
|
package/lib/influxdb.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const _ = require('lodash')
|
|
2
2
|
|
|
3
|
-
const { parse } = require('csv-parse')
|
|
3
|
+
const { parse } = require('csv-parse/sync')
|
|
4
4
|
|
|
5
5
|
const { InfluxDB, Point } = require('@influxdata/influxdb-client')
|
|
6
6
|
const { BucketsAPI } = require('@influxdata/influxdb-client-apis')
|
|
@@ -14,16 +14,17 @@ function report_schema_gap(key, ...message) {
|
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
// Missing and non-finite values fail the point; Point.floatField/intField would throw on them
|
|
17
18
|
function fields_check(fields) {
|
|
18
|
-
|
|
19
|
-
for (let key in fields) {
|
|
20
|
-
if (_.isNaN(fields[key]) || _.isNull(fields[key]) || _.isUndefined(fields[key])) {
|
|
21
|
-
result = false
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
return result
|
|
19
|
+
return Object.values(fields || {}).every((v) => v != null && (typeof v !== 'number' || Number.isFinite(v)))
|
|
25
20
|
}
|
|
26
21
|
|
|
22
|
+
const FIELD_SETTERS = new Map([
|
|
23
|
+
['float', 'floatField'],
|
|
24
|
+
['integer', 'intField'],
|
|
25
|
+
['string', 'stringField'],
|
|
26
|
+
])
|
|
27
|
+
|
|
27
28
|
class Influx {
|
|
28
29
|
constructor(config) {
|
|
29
30
|
const { url, token, org, org_id, bucket, schema, transportOptions } = config
|
|
@@ -36,95 +37,72 @@ class Influx {
|
|
|
36
37
|
this.schema = schema
|
|
37
38
|
}
|
|
38
39
|
async query(query_string, cb) {
|
|
39
|
-
const query_api = this.influx_db.getQueryApi(this.org)
|
|
40
|
-
const parse_table = (csv) =>
|
|
41
|
-
new Promise((resolve, reject) => {
|
|
42
|
-
parse(csv, { columns: true, comment: '#', skip_empty_lines: true, relax_column_count: true }, (err, res) => {
|
|
43
|
-
if (err) reject(err)
|
|
44
|
-
else resolve(res)
|
|
45
|
-
})
|
|
46
|
-
})
|
|
47
40
|
try {
|
|
48
|
-
|
|
41
|
+
const csv = await this.influx_db.getQueryApi(this.org).queryRaw(query_string)
|
|
49
42
|
// Split by empty lines into table blocks — each InfluxDB table may have
|
|
50
43
|
// different columns (different tag sets), so parse each with its own headers
|
|
51
|
-
const tables =
|
|
52
|
-
|
|
53
|
-
cb({ success: true, body: results.flat() })
|
|
44
|
+
const tables = csv.split(/\r?\n\s*\r?\n/).filter((b) => b.trim())
|
|
45
|
+
cb({ success: true, body: tables.flatMap((t) => parse(t, { columns: true, comment: '#', skip_empty_lines: true, relax_column_count: true })) })
|
|
54
46
|
} catch (err) {
|
|
55
47
|
cb({ success: false, body: err })
|
|
56
48
|
}
|
|
57
49
|
}
|
|
58
50
|
async write_points_with_check(points, cb) {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
51
|
+
try {
|
|
52
|
+
if (!this.bucket_exist) {
|
|
53
|
+
// A name lookup 404s when the bucket is missing; an unfiltered list only returns the first 20
|
|
54
|
+
const found = await this.buckets_api.getBuckets({ org: this.org, name: this.bucket }).catch((err) => {
|
|
55
|
+
if (err.statusCode !== 404) throw err
|
|
56
|
+
})
|
|
57
|
+
if (!found?.buckets?.length) {
|
|
58
|
+
// 422: a concurrent write created it first
|
|
59
|
+
const created = await this.buckets_api.postBuckets({ body: { orgID: this.org_id, name: this.bucket } }).catch((err) => {
|
|
60
|
+
if (err.statusCode !== 422) throw err
|
|
61
|
+
})
|
|
62
|
+
if (created) console.log('successfully create bucket:', this.bucket)
|
|
63
|
+
}
|
|
67
64
|
this.bucket_exist = true
|
|
68
65
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (typeof point.timestamp === 'number' || typeof point.timestamp === 'string') {
|
|
75
|
-
const timestamp = new Date(point.timestamp)
|
|
76
|
-
if (!_.isNaN(timestamp.getTime())) {
|
|
77
|
-
return { ...point, timestamp }
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return point
|
|
81
|
-
})
|
|
82
|
-
.filter((point) => {
|
|
83
|
-
if (!_.get(this.schema, [point.measurement, 'fields'])) {
|
|
66
|
+
let dropped_points = 0
|
|
67
|
+
let dropped_fields = 0
|
|
68
|
+
const influx_points = points.flatMap((point) => {
|
|
69
|
+
const field_types = _.get(this.schema, [point.measurement, 'fields'])
|
|
70
|
+
if (!field_types) {
|
|
84
71
|
report_schema_gap(point.measurement, 'influx unknown measurement, points dropped:', point.measurement)
|
|
85
72
|
dropped_points++
|
|
86
|
-
return
|
|
73
|
+
return []
|
|
74
|
+
}
|
|
75
|
+
let { timestamp } = point
|
|
76
|
+
if (typeof timestamp === 'number' || typeof timestamp === 'string') {
|
|
77
|
+
const date = new Date(timestamp)
|
|
78
|
+
if (!_.isNaN(date.getTime())) timestamp = date
|
|
87
79
|
}
|
|
88
|
-
if (fields_check(point.fields)
|
|
89
|
-
return true
|
|
90
|
-
} else {
|
|
80
|
+
if (!fields_check(point.fields) || (timestamp && !(timestamp instanceof Date))) {
|
|
91
81
|
console.error('influx check_points', point)
|
|
92
82
|
dropped_points++
|
|
93
|
-
return
|
|
83
|
+
return []
|
|
94
84
|
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
for (let field in p.fields) {
|
|
102
|
-
let field_type = this.schema[p.measurement].fields[field]
|
|
103
|
-
if (field_type === 'float') {
|
|
104
|
-
p_temp = p_temp.floatField(field, p.fields[field])
|
|
105
|
-
} else if (field_type === 'integer') {
|
|
106
|
-
p_temp = p_temp.intField(field, p.fields[field])
|
|
107
|
-
} else if (field_type === 'string') {
|
|
108
|
-
p_temp = p_temp.stringField(field, p.fields[field])
|
|
85
|
+
const p = new Point(point.measurement)
|
|
86
|
+
for (const tag in point.tags) p.tag(tag, point.tags[tag])
|
|
87
|
+
for (const field in point.fields) {
|
|
88
|
+
const setter = FIELD_SETTERS.get(field_types[field])
|
|
89
|
+
if (setter) {
|
|
90
|
+
p[setter](field, point.fields[field])
|
|
109
91
|
} else {
|
|
110
|
-
report_schema_gap(
|
|
92
|
+
report_schema_gap(point.measurement + '.' + field, 'influx unknown field, dropped:', point.measurement, field)
|
|
111
93
|
dropped_fields++
|
|
112
94
|
}
|
|
113
95
|
}
|
|
114
|
-
if (p.timestamp)
|
|
115
|
-
|
|
116
|
-
}
|
|
117
|
-
return p_temp
|
|
118
|
-
})
|
|
119
|
-
write_api.writePoints(points)
|
|
120
|
-
write_api
|
|
121
|
-
.close()
|
|
122
|
-
.then(() => {
|
|
123
|
-
cb({ success: true, body: points.length, dropped_points, dropped_fields })
|
|
124
|
-
})
|
|
125
|
-
.catch((err) => {
|
|
126
|
-
cb({ success: false, body: err })
|
|
96
|
+
if (timestamp) p.timestamp(timestamp)
|
|
97
|
+
return [p]
|
|
127
98
|
})
|
|
99
|
+
const write_api = this.influx_db.getWriteApi(this.org, this.bucket)
|
|
100
|
+
write_api.writePoints(influx_points)
|
|
101
|
+
await write_api.close()
|
|
102
|
+
cb({ success: true, body: influx_points.length, dropped_points, dropped_fields })
|
|
103
|
+
} catch (err) {
|
|
104
|
+
cb({ success: false, body: err })
|
|
105
|
+
}
|
|
128
106
|
}
|
|
129
107
|
}
|
|
130
108
|
|
package/lib/logger.js
CHANGED
|
@@ -1,15 +1,7 @@
|
|
|
1
1
|
const winston = require('winston')
|
|
2
|
-
// const Papertrail = require('winston-papertrail').Papertrail
|
|
3
2
|
|
|
3
|
+
// winston's default (npm) levels; verbose and silly print grey
|
|
4
4
|
let logger = new winston.Logger({
|
|
5
|
-
levels: {
|
|
6
|
-
error: 0,
|
|
7
|
-
warn: 1,
|
|
8
|
-
info: 2,
|
|
9
|
-
verbose: 3,
|
|
10
|
-
debug: 4,
|
|
11
|
-
silly: 5,
|
|
12
|
-
},
|
|
13
5
|
colors: {
|
|
14
6
|
silly: 'grey',
|
|
15
7
|
verbose: 'grey',
|
|
@@ -19,22 +11,12 @@ let logger = new winston.Logger({
|
|
|
19
11
|
error: 'red',
|
|
20
12
|
},
|
|
21
13
|
transports: [
|
|
22
|
-
// new(Papertrail)({
|
|
23
|
-
// host: 'logs5.papertrailapp.com',
|
|
24
|
-
// port: 53204,
|
|
25
|
-
// colorize: true,
|
|
26
|
-
// level: 'debug'
|
|
27
|
-
// }),
|
|
28
14
|
new winston.transports.Console({
|
|
29
15
|
prettyPrint: true,
|
|
30
16
|
colorize: true,
|
|
31
17
|
timestamp: true,
|
|
32
18
|
level: 'debug',
|
|
33
19
|
}),
|
|
34
|
-
// new (winston.transports.File)({
|
|
35
|
-
// filename: 'out.log',
|
|
36
|
-
// level: 'debug'
|
|
37
|
-
// })
|
|
38
20
|
],
|
|
39
21
|
})
|
|
40
22
|
|
|
@@ -44,7 +44,7 @@ function maybe_prune(market, pair, arr) {
|
|
|
44
44
|
market._last_history_prune_at[pair] = now
|
|
45
45
|
const cutoff = now - market.market_history_store_time
|
|
46
46
|
let i = 0
|
|
47
|
-
while (i < arr.length &&
|
|
47
|
+
while (i < arr.length && arr[i].close_time <= cutoff) i++
|
|
48
48
|
if (i > 0) arr.splice(0, i)
|
|
49
49
|
}
|
|
50
50
|
|
|
@@ -57,16 +57,10 @@ function read_market_history_since(market, pair, timeframe_in_ms) {
|
|
|
57
57
|
// pair, so close_time is near-monotonic and we can break early once we
|
|
58
58
|
// cross the cutoff. Drops a read from O(N=full_buffer) to O(K=window).
|
|
59
59
|
for (let i = arr.length - 1; i >= 0; i--) {
|
|
60
|
-
if (
|
|
60
|
+
if (arr[i].close_time <= cutoff) break
|
|
61
61
|
result.push(arr[i])
|
|
62
62
|
}
|
|
63
63
|
return result
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
function to_ms(value) {
|
|
67
|
-
if (typeof value === 'number') return value
|
|
68
|
-
if (value && typeof value.valueOf === 'function') return value.valueOf()
|
|
69
|
-
return Number(value)
|
|
70
|
-
}
|
|
71
|
-
|
|
72
66
|
module.exports = { record_market_history_trade, record_market_history_trades, read_market_history_since }
|
package/lib/observable.js
CHANGED
|
@@ -34,21 +34,3 @@ class Observable {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
module.exports = Observable
|
|
37
|
-
|
|
38
|
-
// // Example Usage
|
|
39
|
-
// const observable = new Observable()
|
|
40
|
-
|
|
41
|
-
// // Subscribe to updates
|
|
42
|
-
// const unsubscribe = observable.subscribe((update) => {
|
|
43
|
-
// console.log('Received update:', update)
|
|
44
|
-
// })
|
|
45
|
-
|
|
46
|
-
// // Emit updates
|
|
47
|
-
// observable.notify({ message: 'Hello, world!' }) // Logs: Received update: { message: 'Hello, world!' }
|
|
48
|
-
// observable.notify({ message: 'Another update!' }) // Logs: Received update: { message: 'Another update!' }
|
|
49
|
-
|
|
50
|
-
// // Unsubscribe from updates
|
|
51
|
-
// unsubscribe()
|
|
52
|
-
|
|
53
|
-
// // No logs after unsubscribe
|
|
54
|
-
// observable.notify({ message: 'No one will see this' })
|
package/lib/ohlcv.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
const _ = require('lodash')
|
|
2
|
-
|
|
3
1
|
const needle = require('needle')
|
|
4
2
|
|
|
5
3
|
function get_ohlcv(pair, interval, cb) {
|
|
@@ -25,8 +23,3 @@ function get_ohlcv(pair, interval, cb) {
|
|
|
25
23
|
}
|
|
26
24
|
|
|
27
25
|
module.exports = get_ohlcv
|
|
28
|
-
|
|
29
|
-
// get_ohlcv('BTCUSDT', '1h', (res) => {
|
|
30
|
-
// res = _.initial(res)
|
|
31
|
-
// console.log(_.last(res).total / _.minBy(res, 'total').total)
|
|
32
|
-
// })
|
package/lib/ordered-dict.js
CHANGED
|
@@ -46,7 +46,7 @@ function ordered_dict(is_ask) {
|
|
|
46
46
|
// Append without sort — only safe if caller guarantees order.
|
|
47
47
|
// Prefer insert() for correctness.
|
|
48
48
|
k = parseFloat(k)
|
|
49
|
-
if (!vals
|
|
49
|
+
if (!(k in vals)) {
|
|
50
50
|
keys.push(k)
|
|
51
51
|
}
|
|
52
52
|
vals[k] = v
|
|
@@ -54,14 +54,8 @@ function ordered_dict(is_ask) {
|
|
|
54
54
|
insert: function (k, v) {
|
|
55
55
|
if (v != 0) {
|
|
56
56
|
k = parseFloat(k)
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
if (!vals[k]) {
|
|
60
|
-
keys.splice(pos, 0, k)
|
|
61
|
-
vals[k] = v
|
|
62
|
-
} else {
|
|
63
|
-
vals[k] = v
|
|
64
|
-
}
|
|
57
|
+
if (!(k in vals)) keys.splice(binary_find(k, is_ask, keys).index, 0, k)
|
|
58
|
+
vals[k] = v
|
|
65
59
|
}
|
|
66
60
|
},
|
|
67
61
|
del: function (k) {
|
|
@@ -72,24 +66,6 @@ function ordered_dict(is_ask) {
|
|
|
72
66
|
delete vals[k]
|
|
73
67
|
}
|
|
74
68
|
},
|
|
75
|
-
// Remove all entries before k in sort order (exclusive — k itself is kept if present)
|
|
76
|
-
del_before: function (k) {
|
|
77
|
-
k = parseFloat(k)
|
|
78
|
-
let search = binary_find(k, is_ask, keys)
|
|
79
|
-
let cut = search.found ? search.index : search.index
|
|
80
|
-
if (cut <= 0) return
|
|
81
|
-
let removed = keys.splice(0, cut)
|
|
82
|
-
for (let r of removed) delete vals[r]
|
|
83
|
-
},
|
|
84
|
-
// Remove all entries after k in sort order (exclusive — k itself is kept if present)
|
|
85
|
-
del_after: function (k) {
|
|
86
|
-
k = parseFloat(k)
|
|
87
|
-
let search = binary_find(k, is_ask, keys)
|
|
88
|
-
let keep = search.found ? search.index + 1 : search.index
|
|
89
|
-
if (keep >= keys.length) return
|
|
90
|
-
let removed = keys.splice(keep)
|
|
91
|
-
for (let r of removed) delete vals[r]
|
|
92
|
-
},
|
|
93
69
|
val: function (k) {
|
|
94
70
|
return vals[k]
|
|
95
71
|
},
|
|
@@ -99,13 +75,10 @@ function ordered_dict(is_ask) {
|
|
|
99
75
|
keys: function () {
|
|
100
76
|
return keys
|
|
101
77
|
},
|
|
102
|
-
values: function () {
|
|
103
|
-
return vals
|
|
104
|
-
},
|
|
105
78
|
entries: function () {
|
|
106
79
|
return keys.map((key) => [key, vals[key]])
|
|
107
80
|
},
|
|
108
81
|
}
|
|
109
82
|
}
|
|
110
83
|
|
|
111
|
-
module.exports = { ordered_dict
|
|
84
|
+
module.exports = { ordered_dict }
|
package/lib/rate-limiter.js
CHANGED
|
@@ -24,16 +24,10 @@ class RateLimiter {
|
|
|
24
24
|
const key = this._serializeArgs(args)
|
|
25
25
|
let state = this.keyToState.get(key)
|
|
26
26
|
if (!state) {
|
|
27
|
-
state = { count: 0
|
|
27
|
+
state = { count: 0 }
|
|
28
28
|
this.keyToState.set(key, state)
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
state.timerId = setTimeout(() => {
|
|
32
|
-
state.count = 0
|
|
33
|
-
state.timerId = null
|
|
34
|
-
// cleanup to avoid unbounded growth
|
|
35
|
-
this.keyToState.delete(key)
|
|
36
|
-
}, this.interval_concurrent)
|
|
29
|
+
// a key's window ends after one interval; dropping it also bounds the map
|
|
30
|
+
setTimeout(() => this.keyToState.delete(key), this.interval_concurrent)
|
|
37
31
|
}
|
|
38
32
|
if (state.count < this.max_concurrent) {
|
|
39
33
|
state.count++
|
|
@@ -50,13 +44,7 @@ class RateLimiter {
|
|
|
50
44
|
func(...args)
|
|
51
45
|
} else if (!this.abandon_tx) {
|
|
52
46
|
this._enqueue({ func, args, priority })
|
|
53
|
-
|
|
54
|
-
if (this.count === 0) {
|
|
55
|
-
this._drainQueue()
|
|
56
|
-
} else {
|
|
57
|
-
this._scheduleResetTimer()
|
|
58
|
-
}
|
|
59
|
-
}
|
|
47
|
+
this._scheduleResetTimer()
|
|
60
48
|
}
|
|
61
49
|
}
|
|
62
50
|
}
|