qs-strategy 0.4.0

Synchronous reusable configured strategy core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
use std::collections::BTreeMap;
use std::fmt;

use qs_core::OrderType;
use serde::{Deserialize, Deserializer, Serialize};

use crate::{Literal, ScalarType, ValueType, validate_id};

pub const MAX_SOURCES: usize = 32;
pub const MAX_COMPLETED_BARS: usize = 32;
pub const MAX_MATERIALS: usize = 128;
pub const MAX_MATERIAL_INPUTS: usize = 16;
pub const MAX_MATERIAL_ARGS: usize = 32;
pub const MAX_PARAMETERS: usize = 64;
pub const MAX_PARAMETER_OPTIONS: usize = 64;
pub const MAX_MATERIAL_LOOKBACK: usize = 4096;
pub const MAX_MATERIAL_STATE_BYTES: usize = 65_536;
pub const MAX_STATES: usize = 64;
pub const MAX_VARIABLES: usize = 64;
pub const MAX_TRANSITIONS: usize = 64;
pub const MAX_ACTIONS: usize = 16;
pub const MAX_ASSIGNMENTS: usize = 32;
pub const MAX_ENTRY_TARGETS: usize = 16;
pub const MAX_NOTES: usize = 16;
pub const MAX_NAMED_VALUES: usize = 32;
pub const MAX_EXPR_NODES: usize = 512;
pub const MAX_EXPR_DEPTH: usize = 32;
pub const MAX_LEGS: usize = 16;
pub const MAX_OUTPUT_COMMANDS: usize = 16;
pub const MAX_OUTPUT_NOTES: usize = 16;
pub const MAX_COMMAND_CORRELATIONS: usize = 64;
pub const MAX_PENDING_FEEDBACK: usize = 64;

/// Bounded logical completed-bar source identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct SourceId(String);

impl SourceId {
    pub fn new(value: impl Into<String>) -> Result<Self, String> {
        let value = value.into();
        validate_id(&value)?;
        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for SourceId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for SourceId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

/// Strict configured strategy document.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StrategyConfig {
    pub strategy_id: String,
    pub title: String,
    #[serde(default)]
    pub parameters: Vec<ParameterConfig>,
    pub initial_state: String,
    pub sources: Vec<SourceId>,
    pub trade_slots: Vec<String>,
    #[serde(default)]
    pub materials: Vec<MaterialConfig>,
    #[serde(default)]
    pub variables: Vec<VariableConfig>,
    pub states: Vec<StateConfig>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MaterialConfig {
    pub id: String,
    pub key: String,
    #[serde(default)]
    pub inputs: Vec<Expr>,
    #[serde(default)]
    pub params: MaterialArgs,
}

/// One typed material argument or a reference substituted while binding a template.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    content = "value",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum MaterialArg {
    Integer(i64),
    Number(f64),
    Source(SourceId),
    Slot(String),
    BarField(BarField),
    ActionKind(ConfiguredActionKind),
    Param(String),
}

/// Strict named arguments accepted by a material factory.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(transparent)]
pub struct MaterialArgs(pub BTreeMap<String, MaterialArg>);

impl MaterialArgs {
    pub fn new(values: impl IntoIterator<Item = (impl Into<String>, MaterialArg)>) -> Self {
        Self(
            values
                .into_iter()
                .map(|(name, value)| (name.into(), value))
                .collect(),
        )
    }

    pub fn get(&self, name: &str) -> Option<&MaterialArg> {
        self.0.get(name)
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &MaterialArg)> {
        self.0.iter()
    }
}

/// Compatibility builder for Rust callers migrating from the original closed parameter enum.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum MaterialParams {
    #[default]
    None,
    BarField {
        source: SourceId,
        field: BarField,
    },
    Ema {
        period: u16,
    },
    Atr {
        source: SourceId,
        period: u16,
    },
    Position {
        slot: String,
    },
    Feedback {
        slot: String,
        action: ConfiguredActionKind,
    },
}

impl From<MaterialParams> for MaterialArgs {
    fn from(value: MaterialParams) -> Self {
        match value {
            MaterialParams::None => Self::default(),
            MaterialParams::BarField { source, field } => Self::new([
                ("source", MaterialArg::Source(source)),
                ("field", MaterialArg::BarField(field)),
            ]),
            MaterialParams::Ema { period } => {
                Self::new([("period", MaterialArg::Integer(i64::from(period)))])
            }
            MaterialParams::Atr { source, period } => Self::new([
                ("source", MaterialArg::Source(source)),
                ("period", MaterialArg::Integer(i64::from(period))),
            ]),
            MaterialParams::Position { slot } => Self::new([("slot", MaterialArg::Slot(slot))]),
            MaterialParams::Feedback { slot, action } => Self::new([
                ("slot", MaterialArg::Slot(slot)),
                ("action", MaterialArg::ActionKind(action)),
            ]),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum ParameterKind {
    Integer,
    Number,
    Choice { options: Vec<String> },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ParameterConfig {
    pub id: String,
    pub kind: ParameterKind,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(
    tag = "type",
    content = "value",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum ParameterValue {
    Integer(i64),
    Number(f64),
    Choice(String),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(transparent)]
pub struct ParameterBinding(pub BTreeMap<String, ParameterValue>);

impl ParameterBinding {
    pub fn new(values: impl IntoIterator<Item = (impl Into<String>, ParameterValue)>) -> Self {
        Self(
            values
                .into_iter()
                .map(|(name, value)| (name.into(), value))
                .collect(),
        )
    }

    pub fn get(&self, name: &str) -> Option<&ParameterValue> {
        self.0.get(name)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &ParameterValue)> {
        self.0.iter()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BarField {
    Open,
    High,
    Low,
    Close,
    Volume,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PositionField {
    Exists,
    IsPending,
    IsOpen,
    EntryPrice,
    Side,
    RemainingSize,
    Stoploss,
    OpenedAt,
    FavorableExcursion,
    AdverseExcursion,
    InitialRisk,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FeedbackField {
    EntryFilled,
    EntryRejected,
    PositionClosed,
    CancellationApplied,
    CancellationRejected,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConfiguredActionKind {
    Entry,
    Close,
    ClosePartial,
    MoveStoplossToEntry,
    ModifyStoploss,
    CancelPending,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionKind {
    Entry,
    Management,
    Exit,
    Observation,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NoteKind {
    Observation,
    Risk,
    Execution,
    Lifecycle,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct VariableConfig {
    pub id: String,
    pub value_type: ValueType,
    pub initial: Literal,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StateConfig {
    pub id: String,
    #[serde(default)]
    pub transitions: Vec<TransitionConfig>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TransitionConfig {
    pub priority: i32,
    pub target: String,
    pub when: Expr,
    #[serde(default)]
    pub assignments: Vec<AssignmentConfig>,
    pub decision: Option<DecisionTemplate>,
    #[serde(default)]
    pub actions: Vec<ActionTemplate>,
    #[serde(default)]
    pub notes: Vec<NoteTemplate>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AssignmentConfig {
    pub variable: String,
    pub value: Expr,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DecisionTemplate {
    pub kind: DecisionKind,
    pub reason: String,
    pub trade_slot: Option<String>,
    #[serde(default)]
    pub values: Vec<NamedExpr>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NoteTemplate {
    pub kind: NoteKind,
    pub reason: String,
    pub trade_slot: Option<String>,
    #[serde(default)]
    pub values: Vec<NamedExpr>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NamedExpr {
    pub name: String,
    pub value: Expr,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Expr {
    Literal {
        value: Literal,
    },
    Variable {
        id: String,
    },
    Material {
        id: String,
    },
    Param {
        id: String,
    },
    Select {
        param: String,
        cases: BTreeMap<String, Expr>,
    },
    Input {
        field: String,
        value_type: ValueType,
    },
    Bar {
        source: SourceId,
        field: BarField,
    },
    Position {
        slot: String,
        field: PositionField,
    },
    Feedback {
        slot: String,
        action: ConfiguredActionKind,
        field: FeedbackField,
    },
    InputTime,
    Readiness,
    Eq {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Ne {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Lt {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Le {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Gt {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Ge {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    All {
        items: Vec<Expr>,
    },
    Any {
        items: Vec<Expr>,
    },
    Not {
        value: Box<Expr>,
    },
    /// Evaluate comparisons and Boolean operators with strict Missing propagation.
    Strict {
        value: Box<Expr>,
    },
    Add {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Sub {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Mul {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Div {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Min {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Max {
        left: Box<Expr>,
        right: Box<Expr>,
    },
    Abs {
        value: Box<Expr>,
    },
    IsPresent {
        value: Box<Expr>,
    },
    IsMissing {
        value: Box<Expr>,
    },
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum ActionTemplate {
    Entry {
        slot: String,
        side: Expr,
        order_type: OrderType,
        price: Expr,
        risk: Expr,
        stoploss: Expr,
        #[serde(default)]
        targets: Vec<Expr>,
        /// Optional exact class the consuming adapter uses to route the entry to a management profile.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        entry_class: Option<String>,
    },
    Close {
        slot: String,
    },
    ClosePartial {
        slot: String,
        ratio: Expr,
    },
    MoveStoplossToEntry {
        slot: String,
    },
    ModifyStoploss {
        slot: String,
        price: Expr,
    },
    CancelPending {
        slot: String,
    },
}

pub(crate) fn bar_field_type(field: BarField) -> ValueType {
    match field {
        BarField::Volume => ValueType::optional(ScalarType::Number),
        _ => ValueType::optional(ScalarType::Price),
    }
}