1use std::{fmt::Debug, sync::Arc};
19
20use nautilus_core::{Params, UnixNanos};
21use nautilus_model::instruments::{BinaryOption, Instrument, InstrumentAny};
22
23use crate::{
24 http::query::{GetGammaEventsParams, GetGammaMarketsParams, GetSearchParams},
25 websocket::messages::PolymarketNewMarket,
26};
27
28pub trait InstrumentFilter: Debug + Send + Sync {
34 fn market_slugs(&self) -> Option<Vec<String>> {
36 None
37 }
38
39 fn event_slugs(&self) -> Option<Vec<String>> {
42 None
43 }
44
45 fn query_params(&self) -> Option<GetGammaMarketsParams> {
47 None
48 }
49
50 fn event_queries(&self) -> Option<Vec<(String, GetGammaMarketsParams)>> {
57 None
58 }
59
60 fn event_params(&self) -> Option<GetGammaEventsParams> {
62 None
63 }
64
65 fn search_params(&self) -> Option<GetSearchParams> {
67 None
68 }
69
70 fn accept(&self, instrument: &InstrumentAny) -> bool {
73 let _ = instrument;
74 true
75 }
76
77 fn accept_new_market(&self, new_market: &PolymarketNewMarket) -> bool {
82 let _ = new_market;
83 true
84 }
85}
86
87pub struct MarketSlugFilter {
89 slug_fn: Box<dyn Fn() -> Vec<String> + Send + Sync>,
90}
91
92impl MarketSlugFilter {
93 pub fn new<F: Fn() -> Vec<String> + Send + Sync + 'static>(slug_fn: F) -> Self {
98 Self {
99 slug_fn: Box::new(slug_fn),
100 }
101 }
102
103 pub fn from_slugs(slugs: Vec<String>) -> Self {
105 Self {
106 slug_fn: Box::new(move || slugs.clone()),
107 }
108 }
109}
110
111impl Debug for MarketSlugFilter {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 f.debug_struct(stringify!(MarketSlugFilter))
114 .field("slug_fn", &"<closure>")
115 .finish()
116 }
117}
118
119impl InstrumentFilter for MarketSlugFilter {
120 fn market_slugs(&self) -> Option<Vec<String>> {
121 Some((self.slug_fn)())
122 }
123}
124
125pub struct EventSlugFilter {
127 slug_fn: Box<dyn Fn() -> Vec<String> + Send + Sync>,
128}
129
130impl EventSlugFilter {
131 pub fn new<F: Fn() -> Vec<String> + Send + Sync + 'static>(slug_fn: F) -> Self {
136 Self {
137 slug_fn: Box::new(slug_fn),
138 }
139 }
140
141 pub fn from_slugs(slugs: Vec<String>) -> Self {
143 Self {
144 slug_fn: Box::new(move || slugs.clone()),
145 }
146 }
147}
148
149impl Debug for EventSlugFilter {
150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 f.debug_struct(stringify!(EventSlugFilter))
152 .field("slug_fn", &"<closure>")
153 .finish()
154 }
155}
156
157impl InstrumentFilter for EventSlugFilter {
158 fn event_slugs(&self) -> Option<Vec<String>> {
159 Some((self.slug_fn)())
160 }
161}
162
163#[derive(Debug, Clone)]
165pub struct GammaQueryFilter {
166 params: GetGammaMarketsParams,
167}
168
169impl GammaQueryFilter {
170 pub fn new(params: GetGammaMarketsParams) -> Self {
172 Self { params }
173 }
174}
175
176impl InstrumentFilter for GammaQueryFilter {
177 fn query_params(&self) -> Option<GetGammaMarketsParams> {
178 Some(self.params.clone())
179 }
180}
181
182#[derive(Debug, Clone)]
190pub struct EventQueryFilter {
191 queries: Vec<(String, GetGammaMarketsParams)>,
192}
193
194impl EventQueryFilter {
195 pub fn new(event_slug: impl Into<String>, params: GetGammaMarketsParams) -> Self {
197 Self {
198 queries: vec![(event_slug.into(), params)],
199 }
200 }
201
202 pub fn from_queries(queries: Vec<(String, GetGammaMarketsParams)>) -> Self {
204 Self { queries }
205 }
206}
207
208impl InstrumentFilter for EventQueryFilter {
209 fn event_queries(&self) -> Option<Vec<(String, GetGammaMarketsParams)>> {
210 Some(self.queries.clone())
211 }
212}
213
214pub struct PredicateFilter {
219 predicate: Box<dyn Fn(&InstrumentAny) -> bool + Send + Sync>,
220 label: String,
221}
222
223impl PredicateFilter {
224 pub fn new<F: Fn(&InstrumentAny) -> bool + Send + Sync + 'static>(
226 label: impl Into<String>,
227 predicate: F,
228 ) -> Self {
229 Self {
230 predicate: Box::new(predicate),
231 label: label.into(),
232 }
233 }
234
235 pub fn outcome(value: impl Into<String>) -> Self {
239 let value: String = value.into();
240 let label = format!("outcome={value}");
241 Self::new(label, move |instrument| {
242 if let InstrumentAny::BinaryOption(opt) = instrument {
243 opt.outcome.as_deref() == Some(value.as_str())
244 } else {
245 false
246 }
247 })
248 }
249
250 pub fn not_expired(now_ns: UnixNanos) -> Self {
256 Self::new("not_expired", move |instrument| {
257 !is_expired(instrument, now_ns)
258 })
259 }
260}
261
262pub(crate) fn is_expired(instrument: &InstrumentAny, now_ns: UnixNanos) -> bool {
267 Instrument::expiration_ns(instrument)
268 .is_some_and(|expiration_ns| expiration_ns.as_u64() != 0 && expiration_ns <= now_ns)
269}
270
271pub(crate) const MARKET_CLOSED_KEY: &str = "closed";
272
273pub(crate) fn market_closed(instrument: &InstrumentAny) -> Option<bool> {
274 match instrument {
275 InstrumentAny::BinaryOption(binary) => binary_market_closed(binary),
276 _ => None,
277 }
278}
279
280pub(crate) fn binary_market_closed(instrument: &BinaryOption) -> Option<bool> {
281 instrument
282 .info
283 .as_ref()
284 .and_then(|info| info.get_bool(MARKET_CLOSED_KEY))
285}
286
287pub(crate) fn set_market_closed(instrument: &mut BinaryOption, closed: bool) {
288 let mut info = instrument
289 .info
290 .as_ref()
291 .map_or_default(Params::to_shared_map);
292 info.insert(MARKET_CLOSED_KEY.to_string(), Arc::new(closed.into()));
293 instrument.info = Some(Params::from_shared(info));
294}
295
296pub(crate) fn is_expired_and_not_reported_open(
302 instrument: &InstrumentAny,
303 now_ns: UnixNanos,
304) -> bool {
305 is_expired(instrument, now_ns) && market_closed(instrument) != Some(false)
306}
307
308impl Debug for PredicateFilter {
309 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310 f.debug_struct(stringify!(PredicateFilter))
311 .field("label", &self.label)
312 .finish()
313 }
314}
315
316impl InstrumentFilter for PredicateFilter {
317 fn accept(&self, instrument: &InstrumentAny) -> bool {
318 (self.predicate)(instrument)
319 }
320}
321
322#[derive(Debug, Clone)]
324pub struct EventParamsFilter {
325 params: GetGammaEventsParams,
326}
327
328impl EventParamsFilter {
329 pub fn new(params: GetGammaEventsParams) -> Self {
331 Self { params }
332 }
333}
334
335impl InstrumentFilter for EventParamsFilter {
336 fn event_params(&self) -> Option<GetGammaEventsParams> {
337 Some(self.params.clone())
338 }
339}
340
341#[derive(Debug, Clone)]
343pub struct SearchFilter {
344 params: GetSearchParams,
345}
346
347impl SearchFilter {
348 pub fn new(params: GetSearchParams) -> Self {
350 Self { params }
351 }
352
353 pub fn from_query(query: impl Into<String>) -> Self {
355 Self {
356 params: GetSearchParams {
357 q: Some(query.into()),
358 ..Default::default()
359 },
360 }
361 }
362}
363
364impl InstrumentFilter for SearchFilter {
365 fn search_params(&self) -> Option<GetSearchParams> {
366 Some(self.params.clone())
367 }
368}
369
370#[derive(Debug, Clone)]
372pub struct TagFilter {
373 inner: GammaQueryFilter,
374}
375
376impl TagFilter {
377 pub fn from_tag_id(tag_id: u64) -> Self {
379 Self {
380 inner: GammaQueryFilter::new(GetGammaMarketsParams {
381 tag_id: Some(vec![tag_id]),
382 ..Default::default()
383 }),
384 }
385 }
386}
387
388impl InstrumentFilter for TagFilter {
389 fn query_params(&self) -> Option<GetGammaMarketsParams> {
390 self.inner.query_params()
391 }
392}
393
394pub struct NewMarketPredicateFilter {
399 predicate: Box<dyn Fn(&PolymarketNewMarket) -> bool + Send + Sync>,
400 label: String,
401}
402
403impl NewMarketPredicateFilter {
404 pub fn new<F: Fn(&PolymarketNewMarket) -> bool + Send + Sync + 'static>(
405 label: impl Into<String>,
406 predicate: F,
407 ) -> Self {
408 Self {
409 predicate: Box::new(predicate),
410 label: label.into(),
411 }
412 }
413
414 pub fn keyword(keyword: impl Into<String>) -> Self {
417 let kw = keyword.into().to_lowercase();
418 let label = format!("keyword={kw}");
419 Self::new(label, move |nm| {
420 nm.question.to_lowercase().contains(&kw) || nm.description.to_lowercase().contains(&kw)
421 })
422 }
423}
424
425impl Debug for NewMarketPredicateFilter {
426 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
427 f.debug_struct(stringify!(NewMarketPredicateFilter))
428 .field("label", &self.label)
429 .finish()
430 }
431}
432
433impl InstrumentFilter for NewMarketPredicateFilter {
434 fn accept_new_market(&self, new_market: &PolymarketNewMarket) -> bool {
435 (self.predicate)(new_market)
436 }
437}
438
439#[cfg(test)]
440mod tests {
441 use nautilus_core::UnixNanos;
442 use nautilus_model::{
443 enums::AssetClass,
444 identifiers::{InstrumentId, Symbol},
445 instruments::{BinaryOption, InstrumentAny},
446 types::{Currency, Price, Quantity},
447 };
448 use rstest::*;
449 use ustr::Ustr;
450
451 use super::*;
452 use crate::websocket::messages::PolymarketNewMarketEvent;
453
454 fn stub_binary_option_with_expiration(
455 outcome: Option<&str>,
456 expiration: UnixNanos,
457 ) -> InstrumentAny {
458 let raw_symbol = Symbol::new("test-token-id");
459 InstrumentAny::BinaryOption(
460 BinaryOption::builder()
461 .instrument_id(InstrumentId::from("test-token-id.POLYMARKET"))
462 .raw_symbol(raw_symbol)
463 .asset_class(AssetClass::Alternative)
464 .currency(Currency::pUSD())
465 .activation_ns(UnixNanos::default())
466 .expiration_ns(expiration)
467 .price_precision(3)
468 .size_precision(2)
469 .price_increment(Price::from("0.001"))
470 .size_increment(Quantity::from("0.01"))
471 .maybe_outcome(outcome.map(Ustr::from))
472 .ts_event(UnixNanos::default())
473 .ts_init(UnixNanos::default())
474 .build()
475 .unwrap(),
476 )
477 }
478
479 fn stub_binary_option(outcome: Option<&str>) -> InstrumentAny {
480 stub_binary_option_with_expiration(outcome, UnixNanos::from(u64::MAX))
481 }
482
483 #[rstest]
484 fn test_not_expired_accepts_future_expiration() {
485 let now = UnixNanos::from(1_000_000u64);
486 let instrument =
487 stub_binary_option_with_expiration(Some("Yes"), UnixNanos::from(2_000_000u64));
488 let filter = PredicateFilter::not_expired(now);
489 assert!(filter.accept(&instrument));
490 }
491
492 #[rstest]
493 fn test_not_expired_rejects_past_expiration() {
494 let now = UnixNanos::from(2_000_000u64);
495 let instrument =
496 stub_binary_option_with_expiration(Some("Yes"), UnixNanos::from(1_000_000u64));
497 let filter = PredicateFilter::not_expired(now);
498 assert!(!filter.accept(&instrument));
499 }
500
501 #[rstest]
502 fn test_not_expired_rejects_equal_expiration() {
503 let now = UnixNanos::from(1_000_000u64);
504 let instrument =
505 stub_binary_option_with_expiration(Some("Yes"), UnixNanos::from(1_000_000u64));
506 let filter = PredicateFilter::not_expired(now);
507 assert!(!filter.accept(&instrument));
508 }
509
510 #[rstest]
511 fn test_not_expired_works_with_simulated_clock() {
512 let simulated_now = UnixNanos::from(1_000_000_000_000_000_000u64); let expiration = UnixNanos::from(1_100_000_000_000_000_000u64); let instrument = stub_binary_option_with_expiration(Some("Yes"), expiration);
517 let filter = PredicateFilter::not_expired(simulated_now);
518 assert!(filter.accept(&instrument));
519 }
520
521 #[rstest]
522 fn test_not_expired_accepts_zero_sentinel_expiration() {
523 let now = UnixNanos::from(1_000_000u64);
525 let instrument = stub_binary_option_with_expiration(Some("Yes"), UnixNanos::from(0u64));
526 let filter = PredicateFilter::not_expired(now);
527 assert!(filter.accept(&instrument));
528 }
529
530 #[rstest]
531 #[case(2_000_000, Some(false), false)]
532 #[case(2_000_000, Some(true), true)]
533 #[case(2_000_000, None, true)]
534 #[case(500_000, Some(true), false)]
535 fn test_expired_and_not_reported_open_requires_expiration_and_no_open_market_state(
536 #[case] now: u64,
537 #[case] closed: Option<bool>,
538 #[case] expected: bool,
539 ) {
540 let mut instrument =
541 stub_binary_option_with_expiration(Some("Yes"), UnixNanos::from(1_000_000));
542 if let (Some(closed), InstrumentAny::BinaryOption(binary)) = (closed, &mut instrument) {
543 set_market_closed(binary, closed);
544 }
545
546 assert_eq!(
547 is_expired_and_not_reported_open(&instrument, UnixNanos::from(now)),
548 expected
549 );
550 }
551
552 #[fixture]
553 fn yes_instrument() -> InstrumentAny {
554 stub_binary_option(Some("Yes"))
555 }
556
557 #[fixture]
558 fn no_instrument() -> InstrumentAny {
559 stub_binary_option(Some("No"))
560 }
561
562 #[fixture]
563 fn no_outcome_instrument() -> InstrumentAny {
564 stub_binary_option(None)
565 }
566
567 #[rstest]
568 fn test_predicate_filter_accepts_matching(yes_instrument: InstrumentAny) {
569 let filter = PredicateFilter::new("test", |_| true);
570 assert!(filter.accept(&yes_instrument));
571 }
572
573 #[rstest]
574 fn test_predicate_filter_rejects_non_matching(yes_instrument: InstrumentAny) {
575 let filter = PredicateFilter::new("test", |_| false);
576 assert!(!filter.accept(&yes_instrument));
577 }
578
579 #[rstest]
580 fn test_predicate_filter_outcome_constructor(
581 yes_instrument: InstrumentAny,
582 no_instrument: InstrumentAny,
583 no_outcome_instrument: InstrumentAny,
584 ) {
585 let filter = PredicateFilter::outcome("Yes");
586 assert!(filter.accept(&yes_instrument));
587 assert!(!filter.accept(&no_instrument));
588 assert!(!filter.accept(&no_outcome_instrument));
589 }
590
591 #[rstest]
592 fn test_default_accept_returns_true(yes_instrument: InstrumentAny) {
593 let filter = MarketSlugFilter::from_slugs(vec!["test".to_string()]);
594 assert!(filter.accept(&yes_instrument)); }
596
597 fn stub_new_market(
598 slug: &str,
599 tags: Vec<String>,
600 event_slug: Option<&str>,
601 ) -> PolymarketNewMarket {
602 PolymarketNewMarket {
603 id: "1".to_string(),
604 question: "Test?".to_string(),
605 market: Ustr::from("0xabc"),
606 slug: slug.to_string(),
607 description: String::new(),
608 assets_ids: vec![],
609 outcomes: vec!["Yes".to_string(), "No".to_string()],
610 timestamp: "0".to_string(),
611 tags,
612 condition_id: "0xabc".to_string(),
613 active: true,
614 clob_token_ids: vec![],
615 order_price_min_tick_size: None,
616 group_item_title: None,
617 event_message: event_slug.map(|s| PolymarketNewMarketEvent {
618 id: "1".to_string(),
619 ticker: s.to_string(),
620 slug: s.to_string(),
621 title: "Test event".to_string(),
622 description: String::new(),
623 }),
624 sports_market_type: None,
625 line: None,
626 game_start_time: None,
627 taker_base_fee: None,
628 fees_enabled: None,
629 fee_schedule: None,
630 }
631 }
632
633 #[rstest]
634 fn test_default_accept_new_market_returns_true() {
635 let filter = GammaQueryFilter::new(GetGammaMarketsParams::default());
636 let nm = stub_new_market("any-market", vec![], None);
637 assert!(filter.accept_new_market(&nm));
638 }
639
640 #[rstest]
641 fn test_market_slug_filter_default_accept_new_market() {
642 let filter = MarketSlugFilter::from_slugs(vec!["trump-win".to_string()]);
643 let nm = stub_new_market("biden-win", vec![], None);
644 assert!(filter.accept_new_market(&nm)); }
646
647 #[rstest]
648 fn test_event_slug_filter_default_accept_new_market() {
649 let filter = EventSlugFilter::from_slugs(vec!["us-election-2024".to_string()]);
650 let nm = stub_new_market("some-market", vec![], Some("uk-election-2024"));
651 assert!(filter.accept_new_market(&nm)); }
653
654 #[rstest]
655 fn test_tag_filter_default_accept_new_market() {
656 let filter = TagFilter::from_tag_id(123);
657 let nm = stub_new_market("nvda-market", vec!["stocks".to_string()], None);
658 assert!(filter.accept_new_market(&nm)); }
660
661 #[rstest]
662 fn test_new_market_predicate_keyword_matches_question() {
663 let filter = NewMarketPredicateFilter::keyword("BTC");
664 let mut nm = stub_new_market("btc-market", vec![], None);
665 nm.question = "Will BTC reach 100k?".to_string();
666 assert!(filter.accept_new_market(&nm));
667 }
668
669 #[rstest]
670 fn test_new_market_predicate_keyword_matches_description() {
671 let filter = NewMarketPredicateFilter::keyword("bitcoin");
672 let mut nm = stub_new_market("some-market", vec![], None);
673 nm.question = "Some question".to_string();
674 nm.description = "This market is about Bitcoin price".to_string();
675 assert!(filter.accept_new_market(&nm));
676 }
677
678 #[rstest]
679 fn test_new_market_predicate_keyword_rejects_no_match() {
680 let filter = NewMarketPredicateFilter::keyword("BTC");
681 let mut nm = stub_new_market("eth-market", vec![], None);
682 nm.question = "Will ETH reach 10k?".to_string();
683 nm.description = "Ethereum price market".to_string();
684 assert!(!filter.accept_new_market(&nm));
685 }
686}