Skip to main content

Interval

Enum Interval 

Source
pub enum Interval {
    Undefined(String),
    Min1,
    Min5,
    Min15,
    Min30,
    Hour1,
    Hour2,
    Hour4,
    Day1,
    Week1,
    Month1,
}

Variants§

§

Undefined(String)

§

Min1

§

Min5

§

Min15

§

Min30

§

Hour1

§

Hour2

§

Hour4

§

Day1

§

Week1

§

Month1

Implementations§

Source§

impl Interval

Source

pub fn undefined(s: &str) -> Interval

Create an undefined interval.

Source

pub fn parse(s: &str) -> Result<Interval>

Parses an interval from a string.

Source

pub fn parse_undefined(s: &str) -> Interval

Parses an interval from a string, or return the undefined interval if it fails.

Examples found in repository?
examples/tradingview_get.rs (line 154)
87async fn main() -> Result<()> {
88    let opts = Opts::parse();
89    match opts.subcmd {
90        SubCommand::Search(args) => {
91            // Parse arguments
92            let screener = args.screener;
93            let exchanges = args.exchanges;
94            let types = args.types;
95            let name_filter = args.name;
96            // Prepare extra fields if specified
97            let extra_fields: Vec<FieldWithInterval> = args
98                .fields
99                .into_iter()
100                .map(|x| FieldWithInterval::parse_undefined(&x))
101                .collect();
102
103            // Initialize TradingView client and search symbols with given parameters
104            let tv = TradingView::new(&screener, "");
105            let values = tv
106                .search_symbols(&exchanges, &types, name_filter, &extra_fields)
107                .await
108                .context("search symbols error")?;
109
110            // Prepare fields to be printed
111            let fields = [
112                Field::Exchange,
113                Field::Name,
114                Field::Type,
115                Field::Description,
116            ]
117            .into_iter()
118            .map(|x| x.with_interval(&Interval::default()))
119            .chain(extra_fields.into_iter())
120            .collect::<Vec<_>>();
121
122            // Assemble data rows for output
123            let mut table: Vec<Vec<String>> = vec![];
124            for vals in values {
125                let mut row = vec![];
126                for field in fields.iter() {
127                    let val = vals
128                        .values()
129                        .get(&field)
130                        .map_or("".into(), |x| x.to_string());
131                    row.push(val);
132                }
133                table.push(row);
134            }
135
136            // Print csv header
137            println!(
138                "{}",
139                fields
140                    .iter()
141                    .map(|x| x.to_string())
142                    .collect::<Vec<_>>()
143                    .join(",")
144            );
145            // Print csv data rows
146            for vals in table {
147                println!("{}", vals.join(","));
148            }
149        }
150        SubCommand::Scan(args) => {
151            // Parse arguments
152            let screener = args.screener;
153            let exchange = args.exchange;
154            let interval = Interval::parse_undefined(&args.default_interval);
155            let symbols = args.symbols;
156            // Prepare fields with default intervals if not specified
157            let fields = args
158                .fields
159                .iter()
160                .map(|x| FieldWithInterval::parse_undefined_with_default_interval(x, &interval))
161                .collect::<Vec<_>>();
162
163            // Initialize TradingView client and retrieve data for specified symbols and fields
164            let tv = TradingView::new(&screener, exchange);
165            let symbols = tv
166                .scan_symbols(&symbols, &fields)
167                .await
168                .context("scan symbols error")?;
169
170            // Assemble data rows for output
171            let mut table: Vec<Vec<String>> = vec![];
172            for vals in symbols {
173                let mut row = vec![format!("\"{}\"", vals.symbol())];
174                for field in fields.iter() {
175                    let val = vals
176                        .values()
177                        .get(&field)
178                        .map_or("".into(), |x| x.to_string());
179                    row.push(val);
180                }
181                table.push(row);
182            }
183
184            // Print csv header
185            println!(
186                "symbol,{}",
187                fields
188                    .iter()
189                    .map(|x| x.to_string())
190                    .collect::<Vec<_>>()
191                    .join(",")
192            );
193            // Print csv data rows
194            for vals in table {
195                println!("{}", vals.join(","));
196            }
197        }
198        SubCommand::Get(args) => {
199            // Parse arguments
200            let screener = args.screener;
201            let exchange = args.exchange;
202            let interval = Interval::parse_undefined(&args.interval);
203            let symbol = args.symbol;
204            // Prepare fields with default intervals if not specified
205            let fields = args
206                .fields
207                .iter()
208                .map(|x| FieldWithInterval::parse_undefined_with_default_interval(x, &interval))
209                .collect::<Vec<_>>();
210
211            // Initialize TradingView client and retrieve data for specified symbol and fields
212            let tv = TradingView::new(&screener, exchange);
213            let symbol = tv
214                .get_symbol_fields_with_interval(&symbol, &fields)
215                .await
216                .context("Failed to retrieve symbol fields")?;
217
218            // Collect key-value pairs for output, including screener, symbol, interval, and field data
219            let mut values: Vec<(String, Value)> = Vec::new();
220            values.extend(vec![
221                ("screener".to_string(), json!(screener.to_string())),
222                ("symbol".to_string(), json!(symbol.symbol().to_string())),
223                ("interval".to_string(), json!(interval.to_string())),
224            ]);
225            for field in &fields {
226                if let Some(val) = symbol.values().get(field) {
227                    values.push((field.to_string(), val.clone()));
228                }
229            }
230
231            // Output data, formatted as JSON if specified, else as plain key-value pairs
232            if args.json {
233                println!(
234                    "{}",
235                    serde_json::to_string_pretty(&values.into_iter().collect::<HashMap<_, _>>())?
236                );
237            } else {
238                for (k, v) in values {
239                    println!("{:>13} : {}", k, v.to_string());
240                }
241            }
242        }
243        SubCommand::ListScreeners => {
244            for screener in Screener::all_screeners() {
245                println!("{:?}", screener);
246            }
247        }
248        SubCommand::ListIntervals => {
249            for interval in Interval::all_intervals() {
250                println!("{}", interval);
251            }
252        }
253    };
254    Ok(())
255}
Source

pub fn as_field_suffix(&self) -> String

Get the string representation of the interval as a suffix for a field.

Source

pub fn all_intervals() -> &'static [Interval]

Examples found in repository?
examples/tradingview_get.rs (line 249)
87async fn main() -> Result<()> {
88    let opts = Opts::parse();
89    match opts.subcmd {
90        SubCommand::Search(args) => {
91            // Parse arguments
92            let screener = args.screener;
93            let exchanges = args.exchanges;
94            let types = args.types;
95            let name_filter = args.name;
96            // Prepare extra fields if specified
97            let extra_fields: Vec<FieldWithInterval> = args
98                .fields
99                .into_iter()
100                .map(|x| FieldWithInterval::parse_undefined(&x))
101                .collect();
102
103            // Initialize TradingView client and search symbols with given parameters
104            let tv = TradingView::new(&screener, "");
105            let values = tv
106                .search_symbols(&exchanges, &types, name_filter, &extra_fields)
107                .await
108                .context("search symbols error")?;
109
110            // Prepare fields to be printed
111            let fields = [
112                Field::Exchange,
113                Field::Name,
114                Field::Type,
115                Field::Description,
116            ]
117            .into_iter()
118            .map(|x| x.with_interval(&Interval::default()))
119            .chain(extra_fields.into_iter())
120            .collect::<Vec<_>>();
121
122            // Assemble data rows for output
123            let mut table: Vec<Vec<String>> = vec![];
124            for vals in values {
125                let mut row = vec![];
126                for field in fields.iter() {
127                    let val = vals
128                        .values()
129                        .get(&field)
130                        .map_or("".into(), |x| x.to_string());
131                    row.push(val);
132                }
133                table.push(row);
134            }
135
136            // Print csv header
137            println!(
138                "{}",
139                fields
140                    .iter()
141                    .map(|x| x.to_string())
142                    .collect::<Vec<_>>()
143                    .join(",")
144            );
145            // Print csv data rows
146            for vals in table {
147                println!("{}", vals.join(","));
148            }
149        }
150        SubCommand::Scan(args) => {
151            // Parse arguments
152            let screener = args.screener;
153            let exchange = args.exchange;
154            let interval = Interval::parse_undefined(&args.default_interval);
155            let symbols = args.symbols;
156            // Prepare fields with default intervals if not specified
157            let fields = args
158                .fields
159                .iter()
160                .map(|x| FieldWithInterval::parse_undefined_with_default_interval(x, &interval))
161                .collect::<Vec<_>>();
162
163            // Initialize TradingView client and retrieve data for specified symbols and fields
164            let tv = TradingView::new(&screener, exchange);
165            let symbols = tv
166                .scan_symbols(&symbols, &fields)
167                .await
168                .context("scan symbols error")?;
169
170            // Assemble data rows for output
171            let mut table: Vec<Vec<String>> = vec![];
172            for vals in symbols {
173                let mut row = vec![format!("\"{}\"", vals.symbol())];
174                for field in fields.iter() {
175                    let val = vals
176                        .values()
177                        .get(&field)
178                        .map_or("".into(), |x| x.to_string());
179                    row.push(val);
180                }
181                table.push(row);
182            }
183
184            // Print csv header
185            println!(
186                "symbol,{}",
187                fields
188                    .iter()
189                    .map(|x| x.to_string())
190                    .collect::<Vec<_>>()
191                    .join(",")
192            );
193            // Print csv data rows
194            for vals in table {
195                println!("{}", vals.join(","));
196            }
197        }
198        SubCommand::Get(args) => {
199            // Parse arguments
200            let screener = args.screener;
201            let exchange = args.exchange;
202            let interval = Interval::parse_undefined(&args.interval);
203            let symbol = args.symbol;
204            // Prepare fields with default intervals if not specified
205            let fields = args
206                .fields
207                .iter()
208                .map(|x| FieldWithInterval::parse_undefined_with_default_interval(x, &interval))
209                .collect::<Vec<_>>();
210
211            // Initialize TradingView client and retrieve data for specified symbol and fields
212            let tv = TradingView::new(&screener, exchange);
213            let symbol = tv
214                .get_symbol_fields_with_interval(&symbol, &fields)
215                .await
216                .context("Failed to retrieve symbol fields")?;
217
218            // Collect key-value pairs for output, including screener, symbol, interval, and field data
219            let mut values: Vec<(String, Value)> = Vec::new();
220            values.extend(vec![
221                ("screener".to_string(), json!(screener.to_string())),
222                ("symbol".to_string(), json!(symbol.symbol().to_string())),
223                ("interval".to_string(), json!(interval.to_string())),
224            ]);
225            for field in &fields {
226                if let Some(val) = symbol.values().get(field) {
227                    values.push((field.to_string(), val.clone()));
228                }
229            }
230
231            // Output data, formatted as JSON if specified, else as plain key-value pairs
232            if args.json {
233                println!(
234                    "{}",
235                    serde_json::to_string_pretty(&values.into_iter().collect::<HashMap<_, _>>())?
236                );
237            } else {
238                for (k, v) in values {
239                    println!("{:>13} : {}", k, v.to_string());
240                }
241            }
242        }
243        SubCommand::ListScreeners => {
244            for screener in Screener::all_screeners() {
245                println!("{:?}", screener);
246            }
247        }
248        SubCommand::ListIntervals => {
249            for interval in Interval::all_intervals() {
250                println!("{}", interval);
251            }
252        }
253    };
254    Ok(())
255}

Trait Implementations§

Source§

impl AsRef<str> for Interval

Source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for Interval

Source§

fn clone(&self) -> Interval

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Interval

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Interval

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Interval

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Interval

Source§

impl Hash for Interval

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Interval

Source§

fn eq(&self, other: &Interval) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Interval

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more