Centralize strategy contracts and share indicator calculations
This commit is contained in:
parent
366d39001b
commit
4207bf2c1c
25 changed files with 1323 additions and 477 deletions
54
apps/stock/engine/src/api/strategy_parameters.rs
Normal file
54
apps/stock/engine/src/api/strategy_parameters.rs
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
use napi::{Error, JsObject, JsUnknown, Result, ValueType};
|
||||
|
||||
/// Native bindings are a trust boundary too: never truncate fractional periods or default bad types.
|
||||
pub fn number(
|
||||
object: &JsObject,
|
||||
key: &str,
|
||||
default: f64,
|
||||
min: f64,
|
||||
max: f64,
|
||||
integer: bool,
|
||||
) -> Result<f64> {
|
||||
if !object.has_named_property(key)? {
|
||||
return Ok(default);
|
||||
}
|
||||
let value: JsUnknown = object.get_named_property(key)?;
|
||||
if value.get_type()? == ValueType::Undefined {
|
||||
return Ok(default);
|
||||
}
|
||||
let invalid = || {
|
||||
Error::from_reason(format!(
|
||||
"{} must be a finite {}number in [{}, {}]",
|
||||
key,
|
||||
if integer { "integer " } else { "" },
|
||||
min,
|
||||
max
|
||||
))
|
||||
};
|
||||
let value = object
|
||||
.get_named_property::<f64>(key)
|
||||
.map_err(|_| invalid())?;
|
||||
if !value.is_finite() || value < min || value > max || (integer && value.fract() != 0.0) {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub fn period(object: &JsObject, key: &str, default: f64, min: f64) -> Result<usize> {
|
||||
Ok(number(object, key, default, min, 10000.0, true)? as usize)
|
||||
}
|
||||
|
||||
pub fn keys(object: &JsObject, allowed: &[&str]) -> Result<()> {
|
||||
let names = object.get_property_names()?;
|
||||
for index in 0..names.get_array_length()? {
|
||||
let raw = names.get_element::<napi::JsString>(index)?.into_utf8()?;
|
||||
let name = raw.as_str()?;
|
||||
if !allowed.contains(&name) {
|
||||
return Err(Error::from_reason(format!(
|
||||
"Unknown strategy parameter: {}",
|
||||
name
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue