ohlcv-indicators 3.5.79 → 3.5.82

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.
@@ -10,27 +10,27 @@ export const lag = (main, index, colKeys, lookback) => {
10
10
  {
11
11
  const lagColumns = new Map()
12
12
 
13
- for (const targetKey of colKeys) {
14
- if (!verticalOhlcv.hasOwnProperty(targetKey)) {
13
+ for (const target of colKeys) {
14
+ if (!verticalOhlcv.hasOwnProperty(target)) {
15
15
  throw new Error(
16
- `Lag processing invoked by col "${targetKey}" was not found in "verticalOhlcv".`
16
+ `Lag processing invoked by col "${target}" was not found in "verticalOhlcv".`
17
17
  )
18
18
  }
19
19
 
20
- const addToPriceBased = priceBased.has(targetKey)
21
- const type = Array.isArray(verticalOhlcv[targetKey]) ? 'Array' : 'Float64Array'
20
+ const addToPriceBased = priceBased.has(target)
21
+ const type = Array.isArray(verticalOhlcv[target]) ? 'Array' : 'Float64Array'
22
22
  const columns = []
23
23
  const keyNames = []
24
24
 
25
25
  for (let step = 1; step <= lookback; step++) {
26
- const key = `${targetKey}_lag_${step}`
26
+ const key = `${target}_lag_${step}`
27
27
 
28
28
  columns.push({ key, type, priceBased: addToPriceBased, includeInLag: false })
29
29
  keyNames.push(key)
30
30
  }
31
31
 
32
32
  initializeColumns(main, columns)
33
- lagColumns.set(targetKey, keyNames)
33
+ lagColumns.set(target, keyNames)
34
34
  }
35
35
 
36
36
  // colKeys belongs to the runtime queue; keep cached names out of exported params.
@@ -40,15 +40,14 @@ export const lag = (main, index, colKeys, lookback) => {
40
40
 
41
41
  const lagColumns = instances[lagColumnsKey]?.get(colKeys)
42
42
 
43
- for (const targetKey of colKeys) {
44
- const keyNames = lagColumns?.get(targetKey)
45
- const currentColumn = verticalOhlcv[targetKey]
43
+ for (const target of colKeys) {
44
+ const keyNames = lagColumns?.get(target)
45
+ const currentColumn = verticalOhlcv[target]
46
46
  const missingValue = Array.isArray(currentColumn) ? null : NaN
47
47
 
48
48
  // Populate the lagged values each tick:
49
49
  for (let step = 1; step <= lookback; step++) {
50
- // Runtime callbacks may change the target list or lookback after initialization.
51
- const key = keyNames?.[step - 1] ?? `${targetKey}_lag_${step}`
50
+ const key = keyNames?.[step - 1] ?? `${target}_lag_${step}`
52
51
  const laggedIndex = index - step
53
52
  const value =
54
53
  laggedIndex < 0 || currentColumn[laggedIndex] == null
@@ -47,7 +47,7 @@ export const assignTypes = main => {
47
47
  }
48
48
  else if (colName === 'volume') {
49
49
  inputTypes[colName] = classifyNum(cellValue, true)
50
- arrayTypes[colName] = 'Int32Array'
50
+ arrayTypes[colName] = 'Float64Array'
51
51
  }
52
52
  else if (initialPriceBased.has(colName)) {
53
53
  inputTypes[colName] = classifyNum(cellValue, true, precision)
@@ -1,15 +1,11 @@
1
- import { defaultMapColsCallback } from '../studies/mapCols.js';
2
-
3
1
  export const CONFIG_VERSION = 1;
4
- const mapCallbacks = new Map([['default', defaultMapColsCallback]]);
5
2
 
6
3
  // Copy configuration without JSON's silent conversion of functions/NaN to null.
7
- export const copyConfig = (value, allowFunctions = false, ancestors = new Set()) => {
4
+ export const copyConfig = (value, ancestors = new Set()) => {
8
5
  if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
9
6
  if (typeof value === 'number' && Number.isFinite(value)) return value;
10
- if (typeof value === 'function' && allowFunctions) return value;
11
7
  if (typeof value !== 'object' || value === null) {
12
- throw new TypeError('Configuration values must be JSON-safe: no undefined, non-finite numbers, or unregistered functions.');
8
+ throw new TypeError('Configuration values must be JSON-safe: no undefined, non-finite numbers, or functions.');
13
9
  }
14
10
  if (ancestors.has(value)) throw new TypeError('Configuration must not contain circular references.');
15
11
  const prototype = Object.getPrototypeOf(value);
@@ -20,8 +16,8 @@ export const copyConfig = (value, allowFunctions = false, ancestors = new Set())
20
16
 
21
17
  ancestors.add(value);
22
18
  const result = Array.isArray(value)
23
- ? Array.from(value, item => copyConfig(item, allowFunctions, ancestors))
24
- : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyConfig(item, allowFunctions, ancestors)]));
19
+ ? Array.from(value, item => copyConfig(item, ancestors))
20
+ : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyConfig(item, ancestors)]));
25
21
  ancestors.delete(value);
26
22
  return result;
27
23
  };
@@ -33,32 +29,3 @@ export const freezeConfig = value => {
33
29
  }
34
30
  return value;
35
31
  };
36
-
37
- export const registerMapCallback = (name, callback) => {
38
- if (typeof name !== 'string' || !name || typeof callback !== 'function') {
39
- throw new TypeError('registerMapCallback requires a nonempty name and a function.');
40
- }
41
- if (mapCallbacks.has(name) && mapCallbacks.get(name) !== callback) {
42
- throw new Error(`mapCols callback "${name}" is already registered. Use a new versioned name.`);
43
- }
44
- mapCallbacks.set(name, callback);
45
- };
46
-
47
- export const resolveMapCallback = callback => {
48
- if (typeof callback === 'function') return callback;
49
- if (typeof callback === 'string' && mapCallbacks.has(callback)) return mapCallbacks.get(callback);
50
- throw new Error(`Unknown mapCols callback "${callback}". Register it before loading the configuration.`);
51
- };
52
-
53
- export const exportInputParams = inputParams => {
54
- const result = copyConfig(inputParams, true);
55
- for (const job of result) {
56
- if (job.key !== 'mapCols' || typeof job.params[1] !== 'function') continue;
57
- const entry = [...mapCallbacks].find(([, callback]) => callback === job.params[1]);
58
- if (!entry) {
59
- throw new Error('Cannot export an unregistered mapCols callback. Register it with OHLCV_INDICATORS.registerMapCallback(name, callback).');
60
- }
61
- job.params[1] = entry[0];
62
- }
63
- return copyConfig(result);
64
- };
@@ -5,13 +5,13 @@ export const isPositiveInteger = n => Number.isInteger(n) && n >= 0;
5
5
  export const inputNumberFormatter = {
6
6
  number: n => n,
7
7
  numberCleanString: n => Number(n),
8
- precisionNumberCleanString: (strNum, multiplier) => addPrecisionAsNumber(strNum, multiplier)
8
+ precisionNumberCleanString: (strNum, multiplier, cachedDecimals) => addPrecisionAsNumber(strNum, multiplier, cachedDecimals)
9
9
  }
10
10
 
11
11
  export const outputNumberFormatter = {
12
12
  number: n => n,
13
13
  numberCleanString: n => n,
14
- precisionNumberCleanString: (strNum, multiplier) => revertPrecisionAsNumber(strNum, multiplier)
14
+ precisionNumberCleanString: (strNum, multiplier, cachedDecimals) => revertPrecisionAsNumber(strNum, multiplier, cachedDecimals)
15
15
  }
16
16
 
17
17
  export const classifyNum = (num, throwError = false, precision = false) => {
@@ -34,4 +34,4 @@ export const classifyNum = (num, throwError = false, precision = false) => {
34
34
 
35
35
  if(throwError) throw new TypeError('Invalid input: expected a number or numeric string')
36
36
  return typeof num
37
- }
37
+ }
@@ -51,8 +51,14 @@ export const calcPrecisionMultiplier = main => {
51
51
  }
52
52
 
53
53
 
54
+ // Keep the existing decimal-width rule, including scientific-notation multipliers.
55
+ export const getPrecisionDecimals = multiplier => {
56
+ const mulStr = String(multiplier)
57
+ return multiplier === 1 ? 0 : mulStr.length - 1
58
+ }
59
+
54
60
  //this function converts the strNum into a integer * multiplier
55
- export const addPrecisionAsNumber = (strNum, multiplier) => {
61
+ export const addPrecisionAsNumber = (strNum, multiplier, cachedDecimals) => {
56
62
  if (typeof strNum !== 'string') throw new Error('addPrecisionExact expects a string when precision=true')
57
63
 
58
64
  const negative = strNum.charAt(0) === '-'
@@ -60,8 +66,7 @@ export const addPrecisionAsNumber = (strNum, multiplier) => {
60
66
  const [intPart, decPart = ''] = s.split('.')
61
67
 
62
68
  // Compute decimals from multiplier (multiplier expected as 10^decimals)
63
- const mulStr = String(multiplier);
64
- const decimals = (multiplier === 1) ? 0 : (mulStr.length - 1)
69
+ const decimals = cachedDecimals === undefined ? getPrecisionDecimals(multiplier) : cachedDecimals
65
70
 
66
71
  const decPadded = decPart.padEnd(decimals, '0').slice(0, decimals); // pad or trim
67
72
  const integerString = intPart + decPadded // e.g. "12" + "3400" => "123400"
@@ -75,7 +80,7 @@ export const addPrecisionAsNumber = (strNum, multiplier) => {
75
80
 
76
81
 
77
82
  //this function converts the outputs the number generated in addPrecisionAsNumber / multiplier
78
- export const revertPrecisionAsNumber = (num, multiplier) => {
83
+ export const revertPrecisionAsNumber = (num, multiplier, cachedDecimals) => {
79
84
  if (typeof num !== 'number' || !Number.isFinite(num)) {
80
85
  throw new Error('revertPrecisionAsNumber expects a finite number')
81
86
  }
@@ -86,7 +91,7 @@ export const revertPrecisionAsNumber = (num, multiplier) => {
86
91
  // Make sure we're working with an integer, mirroring addPrecisionAsNumber
87
92
  abs = Math.trunc(abs)
88
93
 
89
- const decimals = (multiplier === 1) ? 0 : (String(multiplier).length - 1)
94
+ const decimals = cachedDecimals === undefined ? getPrecisionDecimals(multiplier) : cachedDecimals
90
95
 
91
96
  if (decimals === 0) {
92
97
  // No fractional part; just restore sign
@@ -106,4 +111,4 @@ export const revertPrecisionAsNumber = (num, multiplier) => {
106
111
  : `${intPart}.${fracStr}`
107
112
 
108
113
  return Number(negative ? `-${resultStr}` : resultStr)
109
- }
114
+ }
@@ -141,7 +141,7 @@ export const validateInputValues = (
141
141
  const value = verticalOhlcv[key]?.[index];
142
142
 
143
143
  const isValid = key === "volume"
144
- ? Number.isInteger(value) && value >= 0
144
+ ? Number.isFinite(value) && value >= 0
145
145
  : Number.isFinite(value) && value > 0;
146
146
 
147
147
  if (!isValid) invalidParams.push(key);
@@ -1,5 +1,6 @@
1
1
  import { dateOutputFormaters } from "./dateUtilities.js"
2
2
  import { outputNumberFormatter } from "./numberUtilities.js"
3
+ import { getPrecisionDecimals } from "./precisionMultiplier.js"
3
4
 
4
5
  export const verticalToHorizontal = ({main, skipNull = false, startIndex = 0, dateFormat}) => {
5
6
 
@@ -8,6 +9,10 @@ export const verticalToHorizontal = ({main, skipNull = false, startIndex = 0, da
8
9
 
9
10
 
10
11
  if (verticalOhlcvKeyNames.length === 0) return []
12
+
13
+ const precisionDecimals = precision && typeof precisionMultiplier === 'number'
14
+ ? getPrecisionDecimals(precisionMultiplier)
15
+ : undefined
11
16
 
12
17
  const skipNullIndex = skipNull && invalidValueIndex >= 0 ? invalidValueIndex + 1 : 0
13
18
  const maxStartIndex = Math.max(skipNullIndex, startIndex)
@@ -33,7 +38,7 @@ export const verticalToHorizontal = ({main, skipNull = false, startIndex = 0, da
33
38
  const value = arr[i]
34
39
  result[i - maxStartIndex][key] = value == null || Number.isNaN(value)
35
40
  ? value
36
- : formatter(value, precisionMultiplier)
41
+ : formatter(value, precisionMultiplier, precisionDecimals)
37
42
  }
38
43
  }
39
44
  else
@@ -16,7 +16,7 @@ export const atr = (main, index, size, {lag, retLogs}) => {
16
16
 
17
17
  instances[baseKeyName] = new FasterATR(size, FasterWSMA)
18
18
 
19
- initializeColumns(main, [{ key: baseKeyName, priceBased: true }], { lag })
19
+ initializeColumns(main, [{ key: baseKeyName, priceBased: !retLogs }], { lag })
20
20
  }
21
21
 
22
22
  // Retrieve the current price value.
package/webpack.config.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { resolve, dirname } from 'path';
2
2
  import { fileURLToPath } from 'url';
3
- //import TerserPlugin from 'terser-webpack-plugin';
4
3
 
5
4
  const __dirname = dirname(fileURLToPath(import.meta.url));
6
5
 
@@ -8,51 +7,12 @@ const entry = './index.js';
8
7
  const output = {
9
8
  filename: 'ohlcv-indicators.min.js',
10
9
  path: resolve(__dirname, './dist'),
11
- library: 'OHLCV_INDICATORS'
10
+ library: {name: 'OHLCV_INDICATORS', type: 'var', export: 'default'}
12
11
  };
13
12
 
14
13
  export default {
15
14
  entry,
16
15
  output,
17
16
  mode: 'production',
18
- target: 'web',
19
- /* optimization: { //TerserPlugin start
20
- minimize: true,
21
- minimizer: [
22
- new TerserPlugin({
23
- terserOptions: {
24
- output: {
25
- beautify: true, // Beautify the output
26
- comments: true, // Preserve comments
27
- },
28
- },
29
- }),
30
- ],
31
- }, // TerserPlugin end */
32
- module: {
33
- rules: [
34
- {
35
- test: /\.js$/,
36
- exclude: /node_modules/,
37
- use: {
38
- loader: 'babel-loader',
39
- options: {
40
- presets: ['@babel/preset-env'],
41
- plugins: ['@babel/plugin-proposal-class-properties']
42
- }
43
- }
44
- },
45
- {
46
- test: /\.js$/,
47
- include: /node_modules\/trading-signals/,
48
- use: {
49
- loader: 'babel-loader',
50
- options: {
51
- presets: ['@babel/preset-env'],
52
- plugins: ['@babel/plugin-proposal-class-properties']
53
- }
54
- }
55
- }
56
- ]
57
- }
17
+ target: 'web'
58
18
  };
@@ -1,23 +0,0 @@
1
- /*!
2
- * Portions adapted from trading-signals 5.0.4.
3
- * MIT License
4
- * Copyright (c) 2020 Benny Neugebauer
5
- *
6
- * Permission is hereby granted, free of charge, to any person obtaining a copy
7
- * of this software and associated documentation files (the "Software"), to deal
8
- * in the Software without restriction, including without limitation the rights
9
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- * copies of the Software, and to permit persons to whom the Software is
11
- * furnished to do so, subject to the following conditions:
12
- *
13
- * The above copyright notice and this permission notice shall be included in all
14
- * copies or substantial portions of the Software.
15
- *
16
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- * SOFTWARE.
23
- */
@@ -1,45 +0,0 @@
1
- import { validateInputValues } from '../utilities/validators.js'
2
- import { initializeColumns } from '../core-functions/initializeColumns.js'
3
-
4
- export const mapCols = (main, index, newCols, callback, {lag, isPriceBased, callbackParams = {}}) => {
5
-
6
- const {verticalOhlcv, precision} = main
7
-
8
- if(index === 0)
9
- {
10
- if (callback === defaultMapColsCallback) {
11
- validateInputValues({ open: true, close: true }, verticalOhlcv, index, 'mapCols')
12
- }
13
-
14
- for(const key of newCols)
15
- {
16
- if(verticalOhlcv.hasOwnProperty(key)) {
17
- throw new Error(`New property "${key}" already exist in "verticalOhlcv" and can not be modified using mapCols.`)
18
- }
19
- }
20
-
21
- initializeColumns(main, newCols.map(key => ({
22
- key, type: 'Array', priceBased: precision && isPriceBased
23
- })), { lag })
24
- }
25
-
26
- const cols = callback({index, main, params: callbackParams})
27
-
28
- if(cols == null) return;
29
-
30
- for(const [key, value] of Object.entries(cols))
31
- {
32
- main.pushToMain({ index, key, value })
33
- }
34
- }
35
-
36
- export const defaultMapColsCallback = ({main, index}) => {
37
- const {verticalOhlcv} = main
38
-
39
- const close = verticalOhlcv.close[index]
40
- const open = verticalOhlcv.open[index-1]
41
-
42
- return {
43
- change: ((close - open) / open) * 100
44
- }
45
- }