Skip to main content

nautilus_polymarket/
filters.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Instrument filters for the Polymarket adapter.
17
18use 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
28/// Declarative filter for controlling which instruments are loaded.
29///
30/// All three methods default to `None`. At least one must return `Some` for
31/// the filter to be useful. Methods are called on each `load_all()` cycle,
32/// enabling dynamic re-evaluation (e.g., time-based slug generation).
33pub trait InstrumentFilter: Debug + Send + Sync {
34    /// Market slugs for concurrent per-slug fetching via `GET /markets?slug=`.
35    fn market_slugs(&self) -> Option<Vec<String>> {
36        None
37    }
38
39    /// Event slugs for fetching event containers via `GET /events?slug=`.
40    /// Each event returns multiple markets.
41    fn event_slugs(&self) -> Option<Vec<String>> {
42        None
43    }
44
45    /// Gamma API query params for bulk filtered fetching.
46    fn query_params(&self) -> Option<GetGammaMarketsParams> {
47        None
48    }
49
50    /// Event queries with client-side sorting and limiting of embedded markets.
51    ///
52    /// Only `order`, `ascending`, and `max_markets` are supported. Other parameters
53    /// and unsupported order fields cause an error when loading. See
54    /// [`PolymarketGammaHttpClient::request_instruments_by_event_query`](
55    /// crate::http::gamma::PolymarketGammaHttpClient::request_instruments_by_event_query).
56    fn event_queries(&self) -> Option<Vec<(String, GetGammaMarketsParams)>> {
57        None
58    }
59
60    /// Gamma events API query params for fetching events with full filtering.
61    fn event_params(&self) -> Option<GetGammaEventsParams> {
62        None
63    }
64
65    /// Public search API params for text-based instrument discovery.
66    fn search_params(&self) -> Option<GetSearchParams> {
67        None
68    }
69
70    /// Post-fetch predicate: only instruments where this returns `true` are kept.
71    /// Default accepts all instruments. Override to refine results after fetching.
72    fn accept(&self, instrument: &InstrumentAny) -> bool {
73        let _ = instrument;
74        true
75    }
76
77    /// Pre-fetch gate for new market WS events: returns `true` if the market
78    /// should proceed to Gamma HTTP fetch. Used when this filter is set as
79    /// the dedicated `new_market_filter` in the data client config.
80    /// Default accepts all new markets.
81    fn accept_new_market(&self, new_market: &PolymarketNewMarket) -> bool {
82        let _ = new_market;
83        true
84    }
85}
86
87/// Filter that provides market slugs, optionally via a dynamic closure.
88pub struct MarketSlugFilter {
89    slug_fn: Box<dyn Fn() -> Vec<String> + Send + Sync>,
90}
91
92impl MarketSlugFilter {
93    /// Creates a new [`MarketSlugFilter`] from a closure that generates slugs.
94    ///
95    /// The closure is re-evaluated on each `load_all()` call, enabling
96    /// time-based or stateful slug generation.
97    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    /// Creates a new [`MarketSlugFilter`] from a static list of market slugs.
104    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
125/// Filter that provides event slugs, optionally via a dynamic closure.
126pub struct EventSlugFilter {
127    slug_fn: Box<dyn Fn() -> Vec<String> + Send + Sync>,
128}
129
130impl EventSlugFilter {
131    /// Creates a new [`EventSlugFilter`] from a closure that generates slugs.
132    ///
133    /// The closure is re-evaluated on each `load_all()` call, enabling
134    /// time-based or stateful slug generation.
135    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    /// Creates a new [`EventSlugFilter`] from a static list of event slugs.
142    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/// Filter that provides Gamma API query parameters for bulk filtered fetching.
164#[derive(Debug, Clone)]
165pub struct GammaQueryFilter {
166    params: GetGammaMarketsParams,
167}
168
169impl GammaQueryFilter {
170    /// Creates a new [`GammaQueryFilter`] from query parameters.
171    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/// Event filter that sorts and limits an event's embedded markets client-side.
183///
184/// Only `order`, `ascending`, and `max_markets` are supported. Other parameters
185/// and unsupported order fields cause an error when loading. See
186/// [`PolymarketGammaHttpClient::request_instruments_by_event_query`](
187/// crate::http::gamma::PolymarketGammaHttpClient::request_instruments_by_event_query)
188/// for supported order fields. [`EventSlugFilter`] returns all markets from the event.
189#[derive(Debug, Clone)]
190pub struct EventQueryFilter {
191    queries: Vec<(String, GetGammaMarketsParams)>,
192}
193
194impl EventQueryFilter {
195    /// Creates a new [`EventQueryFilter`] for a single event slug with query params.
196    pub fn new(event_slug: impl Into<String>, params: GetGammaMarketsParams) -> Self {
197        Self {
198            queries: vec![(event_slug.into(), params)],
199        }
200    }
201
202    /// Creates a new [`EventQueryFilter`] from multiple event slug + params pairs.
203    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
214/// Pure post-fetch filter that accepts/rejects instruments via a closure.
215///
216/// Does not provide any slugs or query params: combine with source filters
217/// via the provider's `with_filters()` or `add_filter()` methods.
218pub struct PredicateFilter {
219    predicate: Box<dyn Fn(&InstrumentAny) -> bool + Send + Sync>,
220    label: String,
221}
222
223impl PredicateFilter {
224    /// Creates a new [`PredicateFilter`] with a label and closure predicate.
225    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    /// Convenience: keep only instruments with a matching outcome value.
236    ///
237    /// Only [`InstrumentAny::BinaryOption`] instruments are checked; all other variants are rejected.
238    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    /// Convenience: reject instruments past expiration.
251    ///
252    /// The caller provides the current time as [`UnixNanos`] so the filter
253    /// works correctly with both real-time and simulated (backtest) clocks.
254    /// Only [`InstrumentAny::BinaryOption`] instruments are checked; non-binary variants are accepted.
255    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
262/// Returns `true` if `instrument` has a real expiration timestamp at or before `now_ns`.
263///
264/// An `expiration_ns` of `0` is treated as a "no expiration" sentinel, the same as a missing
265/// timestamp, so both report as not expired.
266pub(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
296/// Returns whether `instrument` is past its expiration without Gamma reporting it still open.
297///
298/// Gamma `endDate` is a scheduled end, not proof that trading stopped, so an expired instrument is
299/// retained while Gamma reports `closed=false`. A missing `closed` key means the instrument did not
300/// come from the live Gamma path, which keeps the time-only retirement behavior.
301pub(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/// Filter that queries the Gamma events endpoint with full params.
323#[derive(Debug, Clone)]
324pub struct EventParamsFilter {
325    params: GetGammaEventsParams,
326}
327
328impl EventParamsFilter {
329    /// Creates a new [`EventParamsFilter`] from event query parameters.
330    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/// Filter that uses the Gamma public search endpoint.
342#[derive(Debug, Clone)]
343pub struct SearchFilter {
344    params: GetSearchParams,
345}
346
347impl SearchFilter {
348    /// Creates a new [`SearchFilter`] from search parameters.
349    pub fn new(params: GetSearchParams) -> Self {
350        Self { params }
351    }
352
353    /// Convenience: search by free-text query string.
354    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/// Filter that queries markets by tag ID.
371#[derive(Debug, Clone)]
372pub struct TagFilter {
373    inner: GammaQueryFilter,
374}
375
376impl TagFilter {
377    /// Creates a new [`TagFilter`] from a known tag ID.
378    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
394/// Pre-fetch gate filter for new market WS events via closure.
395///
396/// Intended for use as `new_market_filter` in the data client config.
397/// Does not affect initial instrument loading.
398pub 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    /// Accept new markets where `question` or `description` contains the keyword
415    /// (case-insensitive).
416    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        // Simulates a backtest scenario: clock is set to a historical time,
513        // instrument expires in the "future" relative to the simulated clock
514        let simulated_now = UnixNanos::from(1_000_000_000_000_000_000u64); // ~2001
515        let expiration = UnixNanos::from(1_100_000_000_000_000_000u64); // ~2004
516        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        // A zero expiration is the "no expiration" sentinel, so it must be treated as not expired
524        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)); // default impl returns true
595    }
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)); // default: accept all
645    }
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)); // default: accept all
652    }
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)); // default: accept all
659    }
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}