tickrs 0.15.0

Realtime ticker data in your terminal 📈
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
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};

use crossterm::terminal;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, StatefulWidget, Widget};
use serde::Deserialize;

use super::chart::prices_kagi::{self, ReversalOption};
use super::{block, CachableWidget, CacheState};
use crate::common::{ChartType, TimeFrame};
use crate::draw::{add_padding, PaddingDirection};
use crate::theme::style;
use crate::THEME;

#[derive(Default, Debug, Clone)]
pub struct ChartConfigurationState {
    pub input: Input,
    pub selection: Option<KagiSelection>,
    pub error_message: Option<String>,
    pub kagi_options: KagiOptions,
    pub cache_state: CacheState,
}

impl ChartConfigurationState {
    pub fn add_char(&mut self, c: char) {
        let input_field = match self.selection {
            Some(KagiSelection::ReversalValue) => &mut self.input.kagi_reversal_value,
            _ => return,
        };

        // Width of our text input box
        if input_field.len() == 20 {
            return;
        }

        input_field.push(c);
    }

    pub fn del_char(&mut self) {
        let input_field = match self.selection {
            Some(KagiSelection::ReversalValue) => &mut self.input.kagi_reversal_value,
            _ => return,
        };

        input_field.pop();
    }

    fn get_tab_artifacts(&mut self) -> Option<(&mut usize, usize)> {
        let tab_field = match self.selection {
            Some(KagiSelection::ReversalType) => &mut self.input.kagi_reversal_type,
            Some(KagiSelection::PriceType) => &mut self.input.kagi_price_type,
            _ => return None,
        };

        let mod_value = match self.selection {
            Some(KagiSelection::ReversalType) => 2,
            Some(KagiSelection::PriceType) => 2,
            _ => 1,
        };
        Some((tab_field, mod_value))
    }

    pub fn tab(&mut self) {
        if let Some((tab_field, mod_value)) = self.get_tab_artifacts() {
            *tab_field = (*tab_field + 1) % mod_value;
        }
    }

    pub fn back_tab(&mut self) {
        if let Some((tab_field, mod_value)) = self.get_tab_artifacts() {
            *tab_field = (*tab_field + mod_value - 1) % mod_value;
        }
    }

    pub fn enter(&mut self, time_frame: TimeFrame) {
        self.error_message.take();

        // Validate Kagi reversal option
        let new_kagi_reversal_option = {
            let input_value = &self.input.kagi_reversal_value;

            let value = match input_value.parse::<f64>() {
                Ok(value) => value,
                Err(_) => {
                    self.error_message = Some("Reversal Value must be a valid number".to_string());
                    return;
                }
            };

            match self.input.kagi_reversal_type {
                0 => ReversalOption::Pct(value),
                1 => ReversalOption::Amount(value),
                _ => unreachable!(),
            }
        };

        let new_kagi_price_option = Some(match self.input.kagi_price_type {
            0 => prices_kagi::PriceOption::Close,
            1 => prices_kagi::PriceOption::HighLow,
            _ => unreachable!(),
        });

        // Everything validated, save the form values to our state
        match &mut self.kagi_options.reversal_option {
            reversal_options @ None => {
                let mut options_by_timeframe = BTreeMap::new();
                for iter_time_frame in TimeFrame::ALL.iter() {
                    let default_reversal_amount = match iter_time_frame {
                        TimeFrame::Day1 => 0.01,
                        _ => 0.04,
                    };

                    // If this is the time frame we are submitting for, store that value,
                    // otherwise use the default still
                    if *iter_time_frame == time_frame {
                        options_by_timeframe.insert(*iter_time_frame, new_kagi_reversal_option);
                    } else {
                        options_by_timeframe.insert(
                            *iter_time_frame,
                            ReversalOption::Pct(default_reversal_amount),
                        );
                    }
                }

                *reversal_options = Some(KagiReversalOption::ByTimeFrame(options_by_timeframe));
            }
            reversal_options @ Some(KagiReversalOption::Single(_)) => {
                // Always succeeds since we already pattern matched it
                if let KagiReversalOption::Single(config_option) = reversal_options.clone().unwrap()
                {
                    let mut options_by_timeframe = BTreeMap::new();
                    for iter_time_frame in TimeFrame::ALL.iter() {
                        // If this is the time frame we are submitting for, store that value,
                        // otherwise use the single value defined from the config
                        if *iter_time_frame == time_frame {
                            options_by_timeframe.insert(*iter_time_frame, new_kagi_reversal_option);
                        } else {
                            options_by_timeframe.insert(*iter_time_frame, config_option);
                        }
                    }

                    *reversal_options = Some(KagiReversalOption::ByTimeFrame(options_by_timeframe));
                }
            }
            Some(KagiReversalOption::ByTimeFrame(options_by_timeframe)) => {
                options_by_timeframe.insert(time_frame, new_kagi_reversal_option);
            }
        }

        self.kagi_options.price_option = new_kagi_price_option;
    }

    pub fn selection_up(&mut self) {
        let new_selection = match self.selection {
            None => KagiSelection::ReversalValue,
            Some(KagiSelection::ReversalValue) => KagiSelection::ReversalType,
            Some(KagiSelection::ReversalType) => KagiSelection::PriceType,
            Some(KagiSelection::PriceType) => KagiSelection::ReversalValue,
        };

        self.selection = Some(new_selection);
    }

    pub fn selection_down(&mut self) {
        let new_selection = match self.selection {
            None => KagiSelection::PriceType,
            Some(KagiSelection::PriceType) => KagiSelection::ReversalType,
            Some(KagiSelection::ReversalType) => KagiSelection::ReversalValue,
            Some(KagiSelection::ReversalValue) => KagiSelection::PriceType,
        };

        self.selection = Some(new_selection);
    }

    pub fn reset_form(&mut self, time_frame: TimeFrame) {
        self.input = Default::default();
        self.error_message.take();

        let default_reversal_amount = match time_frame {
            TimeFrame::Day1 => 0.01,
            _ => 0.04,
        };

        let (reversal_type, reversal_amount) = self
            .kagi_options
            .reversal_option
            .as_ref()
            .map(|o| {
                let option = match o {
                    KagiReversalOption::Single(option) => *option,
                    KagiReversalOption::ByTimeFrame(options_by_timeframe) => options_by_timeframe
                        .get(&time_frame)
                        .copied()
                        .unwrap_or(ReversalOption::Pct(default_reversal_amount)),
                };

                match option {
                    ReversalOption::Pct(amount) => (0, amount),
                    ReversalOption::Amount(amount) => (1, amount),
                }
            })
            .unwrap_or((0, default_reversal_amount));

        let price_type = self
            .kagi_options
            .price_option
            .map(|p| match p {
                prices_kagi::PriceOption::Close => 0,
                prices_kagi::PriceOption::HighLow => 1,
            })
            .unwrap_or(0);

        self.selection = Some(KagiSelection::PriceType);
        self.input.kagi_reversal_value = format!("{:.2}", reversal_amount);
        self.input.kagi_reversal_type = reversal_type;
        self.input.kagi_price_type = price_type;
    }
}

impl Hash for ChartConfigurationState {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.input.hash(state);
        self.selection.hash(state);
        self.error_message.hash(state);
        self.kagi_options.hash(state);
    }
}

#[derive(Debug, Default, Clone, Hash)]
pub struct Input {
    pub kagi_reversal_type: usize,
    pub kagi_reversal_value: String,
    pub kagi_price_type: usize,
}

#[derive(Default, Debug, Clone, Deserialize, Hash)]
pub struct KagiOptions {
    #[serde(rename = "reversal")]
    pub reversal_option: Option<KagiReversalOption>,
    #[serde(rename = "price")]
    pub price_option: Option<prices_kagi::PriceOption>,
}

#[derive(Debug, Clone, Deserialize, Hash)]
#[serde(untagged)]
pub enum KagiReversalOption {
    Single(prices_kagi::ReversalOption),
    ByTimeFrame(BTreeMap<TimeFrame, prices_kagi::ReversalOption>),
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum KagiSelection {
    PriceType,
    ReversalType,
    ReversalValue,
}

pub struct ChartConfigurationWidget {
    pub chart_type: ChartType,
}

impl StatefulWidget for ChartConfigurationWidget {
    type State = ChartConfigurationState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
        self.render_cached(area, buf, state);
    }
}

impl CachableWidget<ChartConfigurationState> for ChartConfigurationWidget {
    fn cache_state_mut(state: &mut ChartConfigurationState) -> &mut CacheState {
        &mut state.cache_state
    }

    fn render(self, mut area: Rect, buf: &mut Buffer, state: &mut ChartConfigurationState) {
        block::new(" Configuration ").render(area, buf);
        area = add_padding(area, 1, PaddingDirection::All);
        area = add_padding(area, 1, PaddingDirection::Left);
        area = add_padding(area, 1, PaddingDirection::Right);

        // layout[0] - Info / Error message
        // layout[1] - Kagi options
        let mut layout = Layout::default()
            .constraints([Constraint::Length(6), Constraint::Min(0)])
            .split(area)
            .to_vec();

        let mut padded = layout[0];
        padded = add_padding(padded, 1, PaddingDirection::Top);
        padded = add_padding(padded, 1, PaddingDirection::Bottom);
        layout[0] = padded;

        let info_error = if let Some(msg) = state.error_message.as_ref() {
            vec![Line::from(Span::styled(msg, style().fg(THEME.loss())))]
        } else {
            vec![
                Line::from(Span::styled(
                    "  <Up / Down>: move up / down",
                    style().fg(THEME.text_normal()),
                )),
                Line::from(Span::styled(
                    "  <Tab / Shift+Tab>: move up / down",
                    style().fg(THEME.text_normal()),
                )),
                Line::from(Span::styled(
                    "  <Left / Right>: toggle option",
                    style().fg(THEME.text_normal()),
                )),
                Line::from(Span::styled(
                    "  <Enter>: submit changes",
                    style().fg(THEME.text_normal()),
                )),
            ]
        };

        Paragraph::new(info_error)
            .style(style().fg(THEME.text_normal()))
            .render(layout[0], buf);

        match self.chart_type {
            ChartType::Line => {}
            ChartType::Candlestick => {}
            ChartType::Kagi => render_kagi_options(layout[1], buf, state),
        }
    }
}

fn render_kagi_options(mut area: Rect, buf: &mut Buffer, state: &ChartConfigurationState) {
    Block::default()
        .style(style())
        .title(vec![Span::styled(
            "Kagi Options ",
            style().fg(THEME.text_normal()),
        )])
        .borders(Borders::TOP)
        .border_style(style().fg(THEME.border_secondary()))
        .render(area, buf);

    area = add_padding(area, 1, PaddingDirection::Top);

    // layout[0] - Left column
    // layout[1] - Divider
    // layout[2] - Right Column
    let layout = Layout::default()
        .direction(ratatui::layout::Direction::Horizontal)
        .constraints([
            Constraint::Length(16),
            Constraint::Length(3),
            Constraint::Min(0),
        ])
        .split(area)
        .to_vec();

    let left_column = vec![
        Line::default(),
        Line::from(vec![
            Span::styled(
                if state.selection == Some(KagiSelection::PriceType) {
                    "> "
                } else {
                    "  "
                },
                style().fg(THEME.text_primary()),
            ),
            Span::styled("Price Type", style().fg(THEME.text_normal())),
        ]),
        Line::default(),
        Line::from(vec![
            Span::styled(
                if state.selection == Some(KagiSelection::ReversalType) {
                    "> "
                } else {
                    "  "
                },
                style().fg(THEME.text_primary()),
            ),
            Span::styled("Reversal Type", style().fg(THEME.text_normal())),
        ]),
        Line::default(),
        Line::from(vec![
            Span::styled(
                if state.selection == Some(KagiSelection::ReversalValue) {
                    "> "
                } else {
                    "  "
                },
                style().fg(THEME.text_primary()),
            ),
            Span::styled("Reversal Value", style().fg(THEME.text_normal())),
        ]),
    ];

    let right_column = vec![
        Line::default(),
        Line::from(vec![
            Span::styled(
                "Close",
                style().fg(THEME.text_normal()).bg(
                    match (state.selection, state.input.kagi_price_type) {
                        (Some(KagiSelection::PriceType), 0) => THEME.highlight_focused(),
                        (_, 0) => THEME.highlight_unfocused(),
                        (_, _) => THEME.background(),
                    },
                ),
            ),
            Span::styled(" | ", style().fg(THEME.text_normal())),
            Span::styled(
                "High / Low",
                style().fg(THEME.text_normal()).bg(
                    match (state.selection, state.input.kagi_price_type) {
                        (Some(KagiSelection::PriceType), 1) => THEME.highlight_focused(),
                        (_, 1) => THEME.highlight_unfocused(),
                        (_, _) => THEME.background(),
                    },
                ),
            ),
        ]),
        Line::default(),
        Line::from(vec![
            Span::styled(
                "Pct",
                style().fg(THEME.text_normal()).bg(
                    match (state.selection, state.input.kagi_reversal_type) {
                        (Some(KagiSelection::ReversalType), 0) => THEME.highlight_focused(),
                        (_, 0) => THEME.highlight_unfocused(),
                        (_, _) => THEME.background(),
                    },
                ),
            ),
            Span::styled(" | ", style().fg(THEME.text_normal())),
            Span::styled(
                "Amount",
                style().fg(THEME.text_normal()).bg(
                    match (state.selection, state.input.kagi_reversal_type) {
                        (Some(KagiSelection::ReversalType), 1) => THEME.highlight_focused(),
                        (_, 1) => THEME.highlight_unfocused(),
                        (_, _) => THEME.background(),
                    },
                ),
            ),
        ]),
        Line::default(),
        Line::from(vec![Span::styled(
            format!("{: <22}", &state.input.kagi_reversal_value),
            style()
                .fg(if state.selection == Some(KagiSelection::ReversalValue) {
                    THEME.text_secondary()
                } else {
                    THEME.text_normal()
                })
                .bg(if state.selection == Some(KagiSelection::ReversalValue) {
                    THEME.highlight_unfocused()
                } else {
                    THEME.background()
                }),
        )]),
    ];

    Paragraph::new(left_column)
        .style(style().fg(THEME.text_normal()))
        .render(layout[0], buf);

    Paragraph::new(right_column)
        .style(style().fg(THEME.text_normal()))
        .render(layout[2], buf);

    // Set "cursor" color
    if matches!(state.selection, Some(KagiSelection::ReversalValue)) {
        let size = terminal::size().unwrap_or((0, 0));

        let x = layout[2].left() as usize + state.input.kagi_reversal_value.len().min(20);
        let y = layout[2].top() as usize + 5;
        let idx = y * size.0 as usize + x;

        if let Some(cell) = buf.content.get_mut(idx) {
            cell.bg = THEME.text_secondary();
        }
    }
}