commit 934566879ea9d9cbf0a050fd4e15716aa90b353f Author: rob thijssen Date: Mon Mar 9 10:15:33 2026 +0200 chore: init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..1dbb1fd --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1838 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chrono" +version = "0.4.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.5.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831" + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "pin-utils", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "iri-string" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "js-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.183" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" + +[[package]] +name = "rustls" +version = "0.23.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scout" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "clap", + "reqwest", + "serde", + "serde_json", + "tokio", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27ad5e34374e03cfffefc301becb44e9dc3c17584f414349ebe29ed26661822d" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "iri-string", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uuid" +version = "1.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a68d3c8f01c0cfa54a75291d83601161799e4a89a39e0929f4b0354d88757a37" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" +dependencies = [ + "cfg-if", + "futures-util", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" + +[[package]] +name = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96e13bc581734df6250836c59a5f44f3c57db9f9acb9dc8e3eaabdaf6170254d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3545ea9e86d12ab9bba9fcd99b54c1556fd3199007def5a03c375623d05fac1c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..7b9cd43 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "scout" +version = "0.1.0" +edition = "2021" +description = "Autonomous strategy search agent for swym backtesting platform" + +[dependencies] +anyhow = "1" +chrono = { version = "0.4", features = ["serde"] } +clap = { version = "4", features = ["derive"] } +reqwest = { version = "0.12", features = ["json", "rustls-tls"], default-features = false } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["full"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +uuid = { version = "1", features = ["serde"] } diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..387a5bd --- /dev/null +++ b/readme.md @@ -0,0 +1,93 @@ +# scout + +Autonomous strategy search agent for the [swym](https://swym.rs) backtesting platform. + +Runs a loop: asks Claude to generate trading strategies → submits backtests to swym → +evaluates results → feeds learnings back → repeats. Promising strategies are automatically +validated on out-of-sample data to filter overfitting. + +## Quick start + +```bash +export ANTHROPIC_API_KEY="sk-ant-..." + +cargo run -- \ + --swym-url https://dev.swym.hanzalova.internal/api/v1 \ + --max-iterations 50 \ + --instruments binance_spot:BTCUSDC,binance_spot:ETHUSDC,binance_spot:SOLUSDC \ + --backtest-from 2025-01-01T00:00:00Z \ + --backtest-to 2025-10-01T00:00:00Z \ + --oos-from 2025-10-01T00:00:00Z \ + --oos-to 2026-03-01T00:00:00Z +``` + +## How it works + +1. **Coverage check** — verifies candle data exists for all instruments and finds + common available intervals. + +2. **Strategy generation** — sends the DSL schema + prior results to Claude, which + produces a new strategy JSON each iteration. + +3. **In-sample backtest** — submits the strategy against all instruments for the + training period. Evaluates Sharpe ratio, profit factor, win rate, net PnL. + +4. **Out-of-sample validation** — if any instrument shows Sharpe > threshold with + enough trades, the strategy is re-tested on held-out data. Only strategies that + pass both phases are saved as "validated". + +5. **Learning loop** — all results (including failures) are fed back to Claude so + it can learn from what works and what doesn't. The conversation is trimmed to + avoid context exhaustion while the full results history is passed as structured + text. + +## Configuration + +All options are available as CLI flags and environment variables: + +| Flag | Env | Default | Description | +|------|-----|---------|-------------| +| `--swym-url` | `SWYM_API_URL` | `https://dev.swym.hanzalova.internal/api/v1` | Swym API base URL | +| `--anthropic-key` | `ANTHROPIC_API_KEY` | required | Anthropic API key | +| `--model` | `CLAUDE_MODEL` | `claude-sonnet-4-20250514` | Claude model | +| `--max-iterations` | | `50` | Maximum search iterations | +| `--min-sharpe` | | `1.0` | Minimum Sharpe for "promising" | +| `--min-trades` | | `10` | Minimum trades for significance | +| `--instruments` | | BTC,ETH,SOL vs USDC | Comma-separated exchange:SYMBOL | +| `--backtest-from` | | `2025-01-01` | In-sample start | +| `--backtest-to` | | `2025-10-01` | In-sample end | +| `--oos-from` | | `2025-10-01` | Out-of-sample start | +| `--oos-to` | | `2026-03-01` | Out-of-sample end | +| `--initial-balance` | | `10000` | Starting USDC balance | +| `--fees-percent` | | `0.001` | Fee per trade (0.1%) | +| `--output-dir` | | `./results` | Where to save strategies and reports | + +## Output + +``` +results/ +├── strategy_001.json # Every strategy attempted +├── strategy_002.json +├── ... +├── validated_017.json # Strategies that passed OOS validation +├── validated_031.json # (includes in-sample + OOS metrics) +└── best_strategy.json # Highest avg Sharpe across instruments +``` + +## Tips + +- **Start with Sonnet** (`claude-sonnet-4-20250514`) for cost efficiency during + exploration. Switch to Opus for refinement of promising strategies. + +- **50 iterations** is a reasonable starting point. The agent typically finds + interesting patterns within 20-30 iterations if they exist. + +- **Watch the logs** — the per-iteration summaries show you what the agent is + learning in real time. + +- **Adjust dates** to match your actual candle coverage. The agent checks coverage + at startup and will fail fast if data is missing. + +- **The OOS validation threshold is intentionally relaxed** (70% of in-sample + Sharpe, half the trade count) because out-of-sample degradation is expected. + Strategies that maintain edge through this filter are genuinely interesting. diff --git a/src/agent.rs b/src/agent.rs new file mode 100644 index 0000000..923a36e --- /dev/null +++ b/src/agent.rs @@ -0,0 +1,420 @@ +use std::path::Path; +use std::time::Duration; + +use anyhow::{Context, Result}; +use serde_json::Value; +use tracing::{error, info, warn}; + +use crate::claude::{self, ClaudeClient, Message}; +use crate::config::{Cli, Instrument}; +use crate::prompts; +use crate::swym::{BacktestResult, SwymClient}; + +/// A single iteration's record: strategy + results across instruments. +#[derive(Debug)] +struct IterationRecord { + iteration: u32, + strategy: Value, + results: Vec, +} + +impl IterationRecord { + fn best_sharpe(&self) -> f64 { + self.results + .iter() + .filter_map(|r| r.sharpe_ratio) + .fold(f64::NEG_INFINITY, f64::max) + } + + fn avg_sharpe(&self) -> f64 { + let sharpes: Vec = self.results.iter().filter_map(|r| r.sharpe_ratio).collect(); + if sharpes.is_empty() { + return f64::NEG_INFINITY; + } + sharpes.iter().sum::() / sharpes.len() as f64 + } + + fn summary(&self) -> String { + let mut lines = vec![format!("=== Iteration {} ===", self.iteration)]; + for r in &self.results { + lines.push(r.summary_line()); + } + lines.push(format!( + " avg_sharpe={:.3} best_sharpe={:.3}", + self.avg_sharpe(), + self.best_sharpe() + )); + lines.join("\n") + } +} + +pub async fn run(cli: &Cli) -> Result<()> { + // Parse instruments + let instruments: Vec = cli + .instruments + .iter() + .map(|s| Instrument::parse(s)) + .collect::>()?; + + // Ensure output directory exists + std::fs::create_dir_all(&cli.output_dir)?; + + // Init clients + let swym = SwymClient::new(&cli.swym_url)?; + let claude = ClaudeClient::new(&cli.anthropic_key, &cli.model); + + // Check candle coverage for all instruments + info!( + "checking candle coverage for {} instruments...", + instruments.len() + ); + let mut available_intervals: Vec = Vec::new(); + for inst in &instruments { + match swym.candle_coverage(&inst.exchange, &inst.symbol).await { + Ok(coverage) => { + let intervals: Vec<&str> = coverage.iter().map(|c| c.interval.as_str()).collect(); + info!("{}: intervals {:?}", inst.symbol, intervals); + if available_intervals.is_empty() { + available_intervals = coverage.iter().map(|c| c.interval.clone()).collect(); + } else { + // Intersect — only keep intervals available for ALL instruments + available_intervals.retain(|iv| intervals.contains(&iv.as_str())); + } + } + Err(e) => { + warn!("could not check coverage for {}: {e}", inst.symbol); + } + } + } + if available_intervals.is_empty() { + anyhow::bail!("no common candle intervals available across all instruments"); + } + info!("common intervals: {:?}", available_intervals); + + // Load DSL schema for the system prompt + let schema = include_str!("dsl-schema.json"); + let system = prompts::system_prompt(schema); + + // Agent state + let mut history: Vec = Vec::new(); + let mut conversation: Vec = Vec::new(); + let mut best_strategy: Option<(f64, Value)> = None; // (avg_sharpe, strategy) + let mut consecutive_failures = 0u32; + + let instrument_names: Vec = instruments.iter().map(|i| i.symbol.clone()).collect(); + + for iteration in 1..=cli.max_iterations { + info!("━━━ iteration {}/{} ━━━", iteration, cli.max_iterations); + + // Build the user prompt + let user_msg = if iteration == 1 { + prompts::initial_prompt(&instrument_names, &available_intervals) + } else { + let results_text = history + .iter() + .map(|r| r.summary()) + .collect::>() + .join("\n\n"); + + let best_json = best_strategy + .as_ref() + .map(|(_, v)| serde_json::to_string_pretty(v).unwrap()); + + prompts::iteration_prompt(iteration, &results_text, best_json.as_deref()) + }; + + conversation.push(Message { + role: "user".to_string(), + content: user_msg, + }); + + // Ask Claude for a strategy + info!("requesting strategy from Claude..."); + let (response_text, usage) = match claude.chat(&system, &conversation).await { + Ok(r) => r, + Err(e) => { + error!("Claude API error: {e}"); + consecutive_failures += 1; + if consecutive_failures >= 3 { + error!("3 consecutive failures, aborting"); + break; + } + // Remove the last user message so we can retry + conversation.pop(); + continue; + } + }; + + if let Some(u) = &usage { + info!( + "tokens: in={} out={}", + u.input_tokens.unwrap_or(0), + u.output_tokens.unwrap_or(0) + ); + } + + // Add assistant response to conversation history + conversation.push(Message { + role: "assistant".to_string(), + content: response_text.clone(), + }); + + // Extract strategy JSON + let strategy = match claude::extract_json(&response_text) { + Ok(s) => s, + Err(e) => { + warn!("failed to extract strategy JSON: {e}"); + warn!( + "raw response: {}", + &response_text[..response_text.len().min(500)] + ); + consecutive_failures += 1; + if consecutive_failures >= 3 { + error!("3 consecutive JSON extraction failures, aborting"); + break; + } + continue; + } + }; + + consecutive_failures = 0; + + // Validate basic structure + if strategy.get("type").and_then(|v| v.as_str()) != Some("rule_based") { + warn!("strategy missing type=rule_based, skipping"); + continue; + } + + info!( + "strategy: interval={}, rules={}", + strategy["candle_interval"].as_str().unwrap_or("?"), + strategy["rules"].as_array().map(|r| r.len()).unwrap_or(0) + ); + + // Save the strategy JSON + let strat_path = cli.output_dir.join(format!("strategy_{iteration:03}.json")); + std::fs::write(&strat_path, serde_json::to_string_pretty(&strategy)?)?; + + // Run backtests against all instruments (in-sample) + let mut results: Vec = Vec::new(); + + for inst in &instruments { + info!("backtesting {} on {}...", inst.symbol, cli.backtest_from); + match run_single_backtest( + &swym, + inst, + &strategy, + &cli.backtest_from, + &cli.backtest_to, + &cli.initial_balance, + &cli.fees_percent, + cli.poll_interval_secs, + cli.backtest_timeout_secs, + ) + .await + { + Ok(result) => { + info!(" {}", result.summary_line()); + results.push(result); + } + Err(e) => { + warn!(" backtest failed for {}: {e}", inst.symbol); + results.push(BacktestResult { + run_id: uuid::Uuid::nil(), + instrument: inst.symbol.clone(), + status: "failed".to_string(), + total_positions: None, + winning_positions: None, + losing_positions: None, + win_rate: None, + profit_factor: None, + total_pnl: None, + net_pnl: None, + sharpe_ratio: None, + total_fees: None, + avg_bars_in_trade: None, + error_message: Some(e.to_string()), + condition_audit_summary: None, + }); + } + } + } + + let record = IterationRecord { + iteration, + strategy: strategy.clone(), + results, + }; + + info!("{}", record.summary()); + + // Check if any result is promising → run out-of-sample validation + let promising_instruments: Vec<&BacktestResult> = record + .results + .iter() + .filter(|r| r.is_promising(cli.min_sharpe, cli.min_trades)) + .collect(); + + if !promising_instruments.is_empty() { + info!( + "🎯 promising on {} instrument(s)! running out-of-sample validation...", + promising_instruments.len() + ); + + let mut oos_results: Vec = Vec::new(); + for inst in &instruments { + match run_single_backtest( + &swym, + inst, + &strategy, + &cli.oos_from, + &cli.oos_to, + &cli.initial_balance, + &cli.fees_percent, + cli.poll_interval_secs, + cli.backtest_timeout_secs, + ) + .await + { + Ok(result) => { + info!(" OOS {}", result.summary_line()); + oos_results.push(result); + } + Err(e) => { + warn!(" OOS backtest failed for {}: {e}", inst.symbol); + } + } + } + + // Check if out-of-sample results confirm the edge + let oos_promising: Vec<&BacktestResult> = oos_results + .iter() + .filter(|r| r.is_promising(cli.min_sharpe * 0.7, cli.min_trades / 2)) + .collect(); + + if !oos_promising.is_empty() { + info!( + "✅ OUT-OF-SAMPLE VALIDATED on {} instruments!", + oos_promising.len() + ); + save_validated_strategy( + &cli.output_dir, + iteration, + &strategy, + &record.results, + &oos_results, + )?; + } else { + info!("❌ out-of-sample did not confirm edge (likely overfit)"); + } + } + + // Track best strategy by average Sharpe across instruments + let avg_sharpe = record.avg_sharpe(); + if avg_sharpe + > best_strategy + .as_ref() + .map(|(s, _)| *s) + .unwrap_or(f64::NEG_INFINITY) + { + best_strategy = Some((avg_sharpe, strategy.clone())); + info!("new best avg_sharpe: {avg_sharpe:.3}"); + } + + history.push(record); + + // Trim conversation to avoid context window exhaustion. + // Keep system + last 6 messages (3 exchanges). + if conversation.len() > 10 { + // Summarize old history in the next prompt via results_text instead + conversation.drain(..conversation.len() - 6); + } + } + + // Final summary + info!("━━━ search complete: {} iterations ━━━", history.len()); + if let Some((sharpe, ref strat)) = best_strategy { + info!("best avg_sharpe: {sharpe:.3}"); + let path = cli.output_dir.join("best_strategy.json"); + std::fs::write(&path, serde_json::to_string_pretty(strat)?)?; + info!("saved to {}", path.display()); + } else { + info!("no strategies showed positive Sharpe across instruments"); + } + + Ok(()) +} + +async fn run_single_backtest( + swym: &SwymClient, + inst: &Instrument, + strategy: &Value, + starts_at: &str, + finishes_at: &str, + initial_balance: &str, + fees_percent: &str, + poll_interval_secs: u64, + timeout_secs: u64, +) -> Result { + let resp = swym + .submit_backtest( + &inst.exchange, + &inst.symbol, + &inst.base(), + &inst.quote(), + strategy, + starts_at, + finishes_at, + initial_balance, + fees_percent, + ) + .await + .context("submit")?; + + let run_id = resp.id; + + let final_resp = swym + .poll_until_done( + run_id, + Duration::from_secs(poll_interval_secs), + Duration::from_secs(timeout_secs), + ) + .await + .context("poll")?; + + Ok(BacktestResult::from_response(&final_resp, &inst.symbol)) +} + +fn save_validated_strategy( + output_dir: &Path, + iteration: u32, + strategy: &Value, + in_sample: &[BacktestResult], + out_of_sample: &[BacktestResult], +) -> Result<()> { + let report = serde_json::json!({ + "iteration": iteration, + "strategy": strategy, + "in_sample": in_sample.iter().map(|r| serde_json::json!({ + "instrument": r.instrument, + "sharpe": r.sharpe_ratio, + "net_pnl": r.net_pnl, + "profit_factor": r.profit_factor, + "win_rate": r.win_rate, + "total_trades": r.total_positions, + })).collect::>(), + "out_of_sample": out_of_sample.iter().map(|r| serde_json::json!({ + "instrument": r.instrument, + "sharpe": r.sharpe_ratio, + "net_pnl": r.net_pnl, + "profit_factor": r.profit_factor, + "win_rate": r.win_rate, + "total_trades": r.total_positions, + })).collect::>(), + }); + + let path = output_dir.join(format!("validated_{iteration:03}.json")); + std::fs::write(&path, serde_json::to_string_pretty(&report)?)?; + info!("saved validated strategy to {}", path.display()); + Ok(()) +} diff --git a/src/claude.rs b/src/claude.rs new file mode 100644 index 0000000..eb37414 --- /dev/null +++ b/src/claude.rs @@ -0,0 +1,136 @@ +use anyhow::{Context, Result}; +use reqwest::Client; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub struct ClaudeClient { + client: Client, + api_key: String, + model: String, +} + +#[derive(Serialize)] +struct MessagesRequest { + model: String, + max_tokens: u32, + system: String, + messages: Vec, +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +pub struct Message { + pub role: String, + pub content: String, +} + +#[derive(Deserialize)] +struct MessagesResponse { + content: Vec, + usage: Option, +} + +#[derive(Deserialize)] +struct ContentBlock { + text: Option, +} + +#[derive(Deserialize, Debug)] +pub struct Usage { + pub input_tokens: Option, + pub output_tokens: Option, +} + +impl ClaudeClient { + pub fn new(api_key: &str, model: &str) -> Self { + let client = Client::builder() + .timeout(std::time::Duration::from_secs(120)) + .build() + .expect("build http client"); + Self { + client, + api_key: api_key.to_string(), + model: model.to_string(), + } + } + + /// Send a conversation to Claude and get the text response. + pub async fn chat( + &self, + system: &str, + messages: &[Message], + ) -> Result<(String, Option)> { + let body = MessagesRequest { + model: self.model.clone(), + max_tokens: 4096, + system: system.to_string(), + messages: messages.to_vec(), + }; + + let resp = self + .client + .post("https://api.anthropic.com/v1/messages") + .header("x-api-key", &self.api_key) + .header("anthropic-version", "2023-06-01") + .header("content-type", "application/json") + .json(&body) + .send() + .await + .context("claude API request")?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!("Claude API {status}: {body}"); + } + + let parsed: MessagesResponse = resp.json().await.context("parse claude response")?; + let text = parsed + .content + .into_iter() + .filter_map(|b| b.text) + .collect::>() + .join("\n"); + + Ok((text, parsed.usage)) + } +} + +/// Extract a JSON object from Claude's response text. +/// Looks for the first `{` ... `}` block, handling markdown code fences. +pub fn extract_json(text: &str) -> Result { + // Strip markdown fences if present + let cleaned = text + .replace("```json", "") + .replace("```", ""); + + // Find the outermost JSON object + let mut depth = 0i32; + let mut start = None; + let mut end = None; + + for (i, ch) in cleaned.char_indices() { + match ch { + '{' => { + if depth == 0 { + start = Some(i); + } + depth += 1; + } + '}' => { + depth -= 1; + if depth == 0 { + end = Some(i + 1); + break; + } + } + _ => {} + } + } + + let (s, e) = match (start, end) { + (Some(s), Some(e)) => (s, e), + _ => anyhow::bail!("no JSON object found in Claude response"), + }; + + serde_json::from_str(&cleaned[s..e]).context("parse extracted JSON") +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..d14c854 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,122 @@ +use std::path::PathBuf; + +use clap::Parser; + +/// Autonomous strategy search agent for the swym backtesting platform. +/// +/// Runs a loop: ask Claude to generate/refine strategies → submit backtests to swym → +/// evaluate results → feed learnings back to Claude → repeat. +#[derive(Parser, Debug)] +#[command(name = "scout", version)] +pub struct Cli { + /// Swym API base URL (no trailing slash). + #[arg(long, default_value = "https://dev.swym.hanzalova.internal/api/v1")] + pub swym_url: String, + + /// Anthropic API key. + #[arg(long)] + pub anthropic_key: String, + + /// Claude model to use for strategy generation. + #[arg(long, default_value = "claude-sonnet-4-20250514")] + pub model: String, + + /// Maximum agent iterations (generate → backtest → evaluate cycles). + #[arg(long, default_value_t = 50)] + pub max_iterations: u32, + + /// Minimum Sharpe ratio to consider a strategy "interesting". + #[arg(long, default_value_t = 1.0)] + pub min_sharpe: f64, + + /// Minimum number of trades for a result to be meaningful. + #[arg(long, default_value_t = 10)] + pub min_trades: u32, + + /// Instruments to test against, as "EXCHANGE:SYMBOL" (e.g. "binance_spot:BTCUSDC"). + /// Strategies are tested against all listed instruments. + #[arg(long, value_delimiter = ',', default_values_t = vec![ + "binance_spot:BTCUSDC".to_string(), + "binance_spot:ETHUSDC".to_string(), + "binance_spot:SOLUSDC".to_string(), + ])] + pub instruments: Vec, + + /// Backtest start date (ISO-8601). + #[arg(long, default_value = "2025-01-01T00:00:00Z")] + pub backtest_from: String, + + /// Backtest end date (ISO-8601). + #[arg(long, default_value = "2025-10-01T00:00:00Z")] + pub backtest_to: String, + + /// Out-of-sample start (for validation of promising strategies). + #[arg(long, default_value = "2025-10-01T00:00:00Z")] + pub oos_from: String, + + /// Out-of-sample end. + #[arg(long, default_value = "2026-03-01T00:00:00Z")] + pub oos_to: String, + + /// Initial quote balance for backtests. + #[arg(long, default_value = "10000")] + pub initial_balance: String, + + /// Trading fee as decimal (0.001 = 0.1%). + #[arg(long, default_value = "0.001")] + pub fees_percent: String, + + /// Directory to persist promising strategies and results. + #[arg(long, default_value = "./results")] + pub output_dir: PathBuf, + + /// Poll interval in seconds when waiting for backtest completion. + #[arg(long, default_value_t = 2)] + pub poll_interval_secs: u64, + + /// Maximum seconds to wait for a single backtest to complete. + #[arg(long, default_value_t = 300)] + pub backtest_timeout_secs: u64, +} + +/// Parsed instrument reference. +#[derive(Debug, Clone)] +pub struct Instrument { + pub exchange: String, + pub symbol: String, +} + +impl Instrument { + pub fn parse(s: &str) -> anyhow::Result { + let (exchange, symbol) = s + .split_once(':') + .ok_or_else(|| anyhow::anyhow!("instrument must be 'exchange:SYMBOL', got '{s}'"))?; + Ok(Self { + exchange: exchange.to_string(), + symbol: symbol.to_string(), + }) + } + + /// Base asset, lowercase, derived from symbol convention (e.g. BTCUSDC → btc). + pub fn base(&self) -> String { + // Strip known quote suffixes + let s = &self.symbol; + for quote in ["USDC", "USDT", "BUSD"] { + if let Some(base) = s.strip_suffix(quote) { + return base.to_lowercase(); + } + } + s.to_lowercase() + } + + /// Quote asset, lowercase. + pub fn quote(&self) -> String { + let s = &self.symbol; + for quote in ["USDC", "USDT", "BUSD"] { + if s.ends_with(quote) { + return quote.to_lowercase(); + } + } + "usdc".to_string() + } +} diff --git a/src/dsl-schema.json b/src/dsl-schema.json new file mode 100644 index 0000000..150d379 --- /dev/null +++ b/src/dsl-schema.json @@ -0,0 +1,422 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://swym.internal/strategy/schema.json", + "title": "SwymRuleBasedStrategy", + "description": "Swym rules-based strategy DSL. Submit as the 'strategy' field of a paper run config. All decimal values must be JSON strings.", + "type": "object", + "required": ["type", "candle_interval", "rules"], + "additionalProperties": false, + "properties": { + "type": { + "const": "rule_based" + }, + "candle_interval": { + "type": "string", + "enum": ["1m", "5m", "15m", "1h", "4h", "1d"], + "description": "Primary candle interval driving strategy evaluation cadence." + }, + "rules": { + "type": "array", + "items": { "$ref": "#/definitions/Rule" }, + "minItems": 1, + "description": "All rules whose 'when' is true on a primary candle close fire simultaneously." + } + }, + "definitions": { + "DecimalString": { + "description": "A decimal number encoded as a JSON string, e.g. \"3.14\", \"-0.5\", \"0.001\".", + "type": "string", + "pattern": "^-?[0-9]+(\\.[0-9]+)?$" + }, + "CandleField": { + "type": "string", + "enum": ["open", "high", "low", "close", "volume"] + }, + "TimeframeInterval": { + "type": "string", + "enum": ["1m", "5m", "15m", "1h", "4h", "1d"], + "description": "An additional candle interval to read from. When absent, uses the primary candle_interval. Requires backfilled candle data for the backtest window." + }, + "FuncName": { + "type": "string", + "enum": ["highest", "lowest", "sma", "ema", "wma", "rsi", "std_dev", "sum", "atr", "supertrend", "adx", "bollinger_upper", "bollinger_lower"], + "description": "Rolling-window function. atr/adx/supertrend ignore 'field' and use OHLC internally. bollinger_upper/bollinger_lower use multiplier for num_std_dev (default 2.0)." + }, + "ApplyFuncName": { + "type": "string", + "enum": ["highest", "lowest", "sma", "ema", "wma", "std_dev", "sum", "bollinger_upper", "bollinger_lower"], + "description": "Subset of FuncName valid inside apply_func. atr, supertrend, adx, and rsi are excluded. bollinger_upper/bollinger_lower use fixed num_std_dev=2.0 in apply_func context." + }, + "CmpOp": { + "type": "string", + "enum": [">", "<", ">=", "<=", "=="] + }, + "ArithOp": { + "type": "string", + "enum": ["add", "sub", "mul", "div"] + }, + "UnaryOpKind": { + "type": "string", + "enum": ["abs", "sqrt", "neg", "log"] + }, + "Action": { + "type": "object", + "required": ["side", "quantity"], + "additionalProperties": false, + "properties": { + "side": { "type": "string", "enum": ["buy", "sell"] }, + "quantity": { + "$ref": "#/definitions/DecimalString", + "description": "Per-order size in base asset units, e.g. \"0.001\" for BTC." + } + } + }, + "Rule": { + "type": "object", + "required": ["when", "then"], + "additionalProperties": false, + "properties": { + "comment": { + "type": "string", + "description": "Optional human-readable annotation. Included in the content hash so keep stable." + }, + "when": { "$ref": "#/definitions/Condition" }, + "then": { "$ref": "#/definitions/Action" } + } + }, + "Condition": { + "description": "A boolean condition evaluated at candle close. Returns false (safe no-op) when there is insufficient history.", + "oneOf": [ + { "$ref": "#/definitions/ConditionAllOf" }, + { "$ref": "#/definitions/ConditionAnyOf" }, + { "$ref": "#/definitions/ConditionNot" }, + { "$ref": "#/definitions/ConditionPosition" }, + { "$ref": "#/definitions/ConditionEmaCrossover" }, + { "$ref": "#/definitions/ConditionEmaTrend" }, + { "$ref": "#/definitions/ConditionRsi" }, + { "$ref": "#/definitions/ConditionBollinger" }, + { "$ref": "#/definitions/ConditionPriceLevel" }, + { "$ref": "#/definitions/ConditionCompare" }, + { "$ref": "#/definitions/ConditionCrossOver" }, + { "$ref": "#/definitions/ConditionCrossUnder" }, + { "$ref": "#/definitions/ConditionEventCount" } + ] + }, + "ConditionComment": { + "description": "Optional human-readable annotation on any condition node. Ignored by the evaluator; serde drops unknown fields silently.", + "type": "string" + }, + "ConditionAllOf": { + "type": "object", + "required": ["kind", "conditions"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "all_of" }, + "conditions": { + "type": "array", + "items": { "$ref": "#/definitions/Condition" }, + "minItems": 1 + } + } + }, + "ConditionAnyOf": { + "type": "object", + "required": ["kind", "conditions"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "any_of" }, + "conditions": { + "type": "array", + "items": { "$ref": "#/definitions/Condition" }, + "minItems": 1 + } + } + }, + "ConditionNot": { + "type": "object", + "required": ["kind", "condition"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "not" }, + "condition": { "$ref": "#/definitions/Condition" } + } + }, + "ConditionPosition": { + "type": "object", + "required": ["kind", "state"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "position" }, + "state": { "type": "string", "enum": ["flat", "long", "short"] } + } + }, + "ConditionEmaCrossover": { + "description": "True on the bar where fast EMA crosses above (or below) slow EMA. Fires once per cross event.", + "type": "object", + "required": ["kind", "fast_period", "slow_period", "direction"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "ema_crossover" }, + "fast_period": { "type": "integer", "minimum": 1 }, + "slow_period": { "type": "integer", "minimum": 1 }, + "direction": { "type": "string", "enum": ["above", "below"] }, + "timeframe": { "$ref": "#/definitions/TimeframeInterval" } + } + }, + "ConditionEmaTrend": { + "description": "True while close price is above (or below) the EMA. Persistent condition, not a crossover event.", + "type": "object", + "required": ["kind", "period", "direction"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "ema_trend" }, + "period": { "type": "integer", "minimum": 1 }, + "direction": { "type": "string", "enum": ["above", "below"] }, + "timeframe": { "$ref": "#/definitions/TimeframeInterval" } + } + }, + "ConditionRsi": { + "description": "True while RSI (Wilder's method) is above or below the threshold.", + "type": "object", + "required": ["kind", "threshold", "comparison"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "rsi" }, + "period": { + "type": "integer", + "minimum": 1, + "default": 14, + "description": "RSI period. Defaults to 14." + }, + "threshold": { "$ref": "#/definitions/DecimalString" }, + "comparison": { "type": "string", "enum": ["above", "below"] }, + "timeframe": { "$ref": "#/definitions/TimeframeInterval" } + } + }, + "ConditionBollinger": { + "description": "True when close breaks above the upper or below the lower Bollinger Band.", + "type": "object", + "required": ["kind", "band"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "bollinger" }, + "period": { + "type": "integer", + "minimum": 1, + "default": 20 + }, + "num_std_dev": { + "$ref": "#/definitions/DecimalString", + "description": "Number of standard deviations. Defaults to \"2\"." + }, + "band": { "type": "string", "enum": ["above_upper", "below_lower"] }, + "timeframe": { "$ref": "#/definitions/TimeframeInterval" } + } + }, + "ConditionPriceLevel": { + "description": "True while close is above or below a fixed price level.", + "type": "object", + "required": ["kind", "price", "direction"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "price_level" }, + "price": { "$ref": "#/definitions/DecimalString" }, + "direction": { "type": "string", "enum": ["above", "below"] }, + "timeframe": { "$ref": "#/definitions/TimeframeInterval" } + } + }, + "ConditionCompare": { + "description": "True when left op right holds. Use for any indicator comparison not covered by the legacy shortcuts.", + "type": "object", + "required": ["kind", "left", "op", "right"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "compare" }, + "left": { "$ref": "#/definitions/Expr" }, + "op": { "$ref": "#/definitions/CmpOp" }, + "right": { "$ref": "#/definitions/Expr" } + } + }, + "ConditionCrossOver": { + "description": "True on the single bar where left crosses above right (left was <= right, now > right).", + "type": "object", + "required": ["kind", "left", "right"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "cross_over" }, + "left": { "$ref": "#/definitions/Expr" }, + "right": { "$ref": "#/definitions/Expr" } + } + }, + "ConditionCrossUnder": { + "description": "True on the single bar where left crosses below right (left was >= right, now < right).", + "type": "object", + "required": ["kind", "left", "right"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "cross_under" }, + "left": { "$ref": "#/definitions/Expr" }, + "right": { "$ref": "#/definitions/Expr" } + } + }, + "Expr": { + "description": "A numeric expression evaluating to Option. Returns None (condition → false) when history is insufficient.", + "oneOf": [ + { "$ref": "#/definitions/ExprLiteral" }, + { "$ref": "#/definitions/ExprField" }, + { "$ref": "#/definitions/ExprFunc" }, + { "$ref": "#/definitions/ExprBinOp" }, + { "$ref": "#/definitions/ExprApplyFunc" }, + { "$ref": "#/definitions/ExprUnaryOp" }, + { "$ref": "#/definitions/ExprBarsSince" } + ] + }, + "ExprLiteral": { + "description": "A constant numeric value.", + "type": "object", + "required": ["kind", "value"], + "additionalProperties": false, + "properties": { + "kind": { "const": "literal" }, + "value": { "$ref": "#/definitions/DecimalString" } + } + }, + "ExprField": { + "description": "An OHLCV candle field, optionally from N bars ago and/or from a different timeframe.", + "type": "object", + "required": ["kind", "field"], + "additionalProperties": false, + "properties": { + "kind": { "const": "field" }, + "field": { "$ref": "#/definitions/CandleField" }, + "offset": { + "type": "integer", + "minimum": 0, + "default": 0, + "description": "Bars ago. 0 = current bar, 1 = previous bar." + }, + "timeframe": { "$ref": "#/definitions/TimeframeInterval" } + } + }, + "ExprFunc": { + "description": "A rolling-window function applied to a candle field over the trailing N bars, optionally on a different timeframe.", + "type": "object", + "required": ["kind", "name", "period"], + "additionalProperties": false, + "properties": { + "kind": { "const": "func" }, + "name": { "$ref": "#/definitions/FuncName" }, + "field": { + "$ref": "#/definitions/CandleField", + "description": "Which candle field to use. Defaults to 'close'. Ignored for atr, adx, supertrend." + }, + "period": { + "type": "integer", + "minimum": 1, + "description": "Window size in bars. Minimum bars required: period (most funcs), period+1 (atr/rsi), 2*period+1 (adx), period+2 (supertrend)." + }, + "offset": { + "type": "integer", + "minimum": 0, + "default": 0, + "description": "Shift the window back N bars. 0 = window ending on current bar." + }, + "multiplier": { + "$ref": "#/definitions/DecimalString", + "description": "Numeric multiplier: ATR multiplier for supertrend (e.g. \"3.0\"); num_std_dev for bollinger_upper/bollinger_lower (e.g. \"2.0\", default). Omit for all other functions." + }, + "timeframe": { "$ref": "#/definitions/TimeframeInterval" } + } + }, + "ExprBinOp": { + "description": "Arithmetic combination of two sub-expressions. Division by zero returns None.", + "type": "object", + "required": ["kind", "op", "left", "right"], + "additionalProperties": false, + "properties": { + "kind": { "const": "bin_op" }, + "op": { "$ref": "#/definitions/ArithOp" }, + "left": { "$ref": "#/definitions/Expr" }, + "right": { "$ref": "#/definitions/Expr" } + } + }, + "ExprApplyFunc": { + "description": "Applies a rolling function to an arbitrary sub-expression evaluated at each bar in the window. Use for function composition: EMA-of-EMA, Hull MA, VWAP, etc. NOT valid with atr, adx, supertrend, or rsi.", + "type": "object", + "required": ["kind", "name", "input", "period"], + "additionalProperties": false, + "properties": { + "kind": { "const": "apply_func" }, + "name": { "$ref": "#/definitions/ApplyFuncName" }, + "input": { "$ref": "#/definitions/Expr" }, + "period": { "type": "integer", "minimum": 1 }, + "offset": { + "type": "integer", + "minimum": 0, + "default": 0 + }, + "timeframe": { "$ref": "#/definitions/TimeframeInterval" } + } + }, + "ExprUnaryOp": { + "description": "Unary math operation. sqrt and log return None for invalid inputs (negative / non-positive).", + "type": "object", + "required": ["kind", "op", "operand"], + "additionalProperties": false, + "properties": { + "kind": { "const": "unary_op" }, + "op": { "$ref": "#/definitions/UnaryOpKind" }, + "operand": { "$ref": "#/definitions/Expr" } + } + }, + "ConditionEventCount": { + "description": "Counts how many of the trailing `period` bars (offsets 1..=period, excluding the current bar) the sub-condition was true, then applies op against count. Returns false during warm-up. Only Compare, CrossOver, CrossUnder, AllOf, AnyOf, Not, and nested EventCount sub-conditions are offset-aware; Position/EmaCrossover/EmaTrend/Rsi/Bollinger return false at non-zero offsets.", + "type": "object", + "required": ["kind", "condition", "period", "op", "count"], + "additionalProperties": false, + "properties": { + "comment": { "$ref": "#/definitions/ConditionComment" }, + "kind": { "const": "event_count" }, + "condition": { "$ref": "#/definitions/Condition" }, + "period": { + "type": "integer", + "minimum": 1, + "description": "Number of trailing bars to scan (not including the current bar)." + }, + "op": { "$ref": "#/definitions/CmpOp" }, + "count": { + "type": "integer", + "minimum": 0, + "description": "Integer threshold to compare the fire count against." + } + } + }, + "ExprBarsSince": { + "description": "Scans back up to `period` bars and returns how many bars ago the sub-condition was last true (1 = previous bar). Returns None if the condition never fired within the window. Use inside compare to express recency constraints.", + "type": "object", + "required": ["kind", "condition", "period"], + "additionalProperties": false, + "properties": { + "kind": { "const": "bars_since" }, + "condition": { "$ref": "#/definitions/Condition" }, + "period": { + "type": "integer", + "minimum": 1, + "description": "Maximum bars to look back." + } + } + } + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..065c1f3 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,31 @@ +mod agent; +mod claude; +mod config; +mod prompts; +mod swym; + +use clap::Parser; +use tracing_subscriber::EnvFilter; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + tracing_subscriber::fmt() + .with_env_filter( + EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")), + ) + .with_target(false) + .init(); + + let cli = config::Cli::parse(); + + tracing::info!("scout starting"); + tracing::info!(" swym API: {}", cli.swym_url); + tracing::info!(" model: {}", cli.model); + tracing::info!(" iterations: {}", cli.max_iterations); + tracing::info!(" instruments: {:?}", cli.instruments); + tracing::info!(" in-sample: {} → {}", cli.backtest_from, cli.backtest_to); + tracing::info!(" OOS: {} → {}", cli.oos_from, cli.oos_to); + tracing::info!(" output: {}", cli.output_dir.display()); + + agent::run(&cli).await +} diff --git a/src/prompts.rs b/src/prompts.rs new file mode 100644 index 0000000..f7446ac --- /dev/null +++ b/src/prompts.rs @@ -0,0 +1,180 @@ +/// System prompt for the strategy-generation Claude instance. +/// +/// This is the most important part of the agent — it defines how Claude +/// thinks about strategy design, what it knows about the DSL, and how +/// it should interpret backtest results. +pub fn system_prompt(dsl_schema: &str) -> String { + format!( + r##"You are a quantitative trading strategy researcher. Your task is to design, +evaluate, and iteratively refine trading strategies expressed in the swym JSON DSL. + +## Your goal + +Find strategies with genuine statistical edge — not curve-fitted artifacts. A good +strategy has: +- Sharpe ratio > 1.0 (ideally > 1.5) +- Profit factor > 1.3 +- At least 15+ trades (more is better — sparse strategies are unverifiable) +- Positive net PnL after fees +- Consistent performance across multiple instruments (BTC, ETH, SOL vs USDC) + +## Strategy DSL + +Strategies are JSON objects. Here is the complete JSON Schema: + +```json +{dsl_schema} +``` + +## Key DSL capabilities + +### Indicators (func) +sma, ema, wma, rsi, std_dev, sum, highest, lowest, atr, supertrend, adx, +bollinger_upper, bollinger_lower — applied to any candle field (open/high/low/close/volume) +with configurable period and optional offset. + +### Composed indicators (apply_func) +Apply rolling functions to arbitrary expressions: EMA of EMA, Hull MA (WMA of expression), +VWAP (sum of close*volume / sum of volume), standard deviation of returns, etc. + +### Conditions +compare (>, <, >=, <=, ==), cross_over, cross_under — for event detection. +all_of, any_of, not — boolean combinators. +event_count — count how many times a condition fired in last N bars. +bars_since — how many bars since a condition was last true. + +### Position state (Phase 1 — newly available) +entry_price — average entry price of current position +position_quantity — size of current position +unrealised_pnl — current unrealised P&L +bars_since_entry — complete bars elapsed since position was opened +balance — free balance of a named asset (e.g. "usdt", "usdc") + +### Dynamic quantity +Action quantity can be a fixed string ("0.001") or an Expr for dynamic sizing. +ATR-based sizing, percent-of-balance, etc. + +### Multi-timeframe +Any expression can reference a different timeframe via "timeframe" field. +Use higher timeframes as trend filters, lower timeframes for entry precision. + +## Strategy families to explore + +1. **Trend-following**: Moving average crossovers, breakouts above N-bar highs, + ADX filter for trend strength. Risk: whipsaws in ranging markets. + +2. **Mean reversion**: RSI oversold/overbought, Bollinger band touches, deviation + from moving average. Risk: trending markets run against you. + +3. **Momentum**: Rate of change, volume confirmation, relative strength. + Risk: momentum exhaustion, late entry. + +4. **Volatility breakout**: ATR-based bands, Bollinger squeeze → expansion, + Supertrend flips. Risk: false breakouts. + +5. **Multi-timeframe filtered**: Higher TF trend filter + lower TF entry signal. + E.g. daily EMA trend + 4h RSI entry. Generally more robust than single-TF. + +6. **Composite / hybrid**: Combine families. Trend filter + mean-reversion entry. + Momentum confirmation + volatility sizing. + +## Risk management (always include) + +Every strategy MUST have: +- A stop-loss: use entry_price with a percentage or ATR-based offset +- A time-based exit: use bars_since_entry to avoid holding losers indefinitely +- Reasonable position sizing: prefer ATR-based or percent-of-balance over fixed quantity + +## How to respond + +You must respond with ONLY a valid JSON object — the strategy config. +No prose, no markdown explanation, no commentary. +Just the raw JSON starting with {{ and ending with }}. + +The JSON must be a valid strategy with "type": "rule_based". +Use "usdc" (not "usdt") as the quote asset for balance expressions. + +## Interpreting backtest results + +When I share results from previous iterations, use them to guide your next strategy: + +- **Zero trades**: The entry conditions are too restrictive or never co-occur. + Relax thresholds, simplify conditions, or check if the indicator periods make + sense for the candle interval. + +- **Many trades but negative PnL**: The entry signal has no edge, or the exit + logic is poor. Try different indicator combinations, add trend filters, or + improve stop-loss placement. + +- **Few trades, slightly positive**: Promising direction but not statistically + significant. Try to make the signal fire more often (lower thresholds, shorter + periods) while preserving the edge. + +- **Good Sharpe but low profit factor**: Wins are small relative to losses. + Tighten stop-losses or add a profit target. + +- **Good profit factor but negative Sharpe**: High variance. Add position sizing + or volatility filters to reduce exposure during chaotic periods. + +- **Condition audit shows one condition always true/false**: That condition is + redundant or broken. Remove it or adjust its parameters. + +## Anti-patterns to avoid + +- Don't use the same indicator for both entry and exit (circular logic) +- Don't set RSI thresholds at extreme values (< 10 or > 90) — too rare to fire +- Don't use very short periods (< 5) on high timeframes — noisy +- Don't use very long periods (> 100) on low timeframes — too slow to react +- Don't create strategies with more than 5-6 conditions — overfitting risk +- Don't ignore fees — a strategy needs to overcome 0.1% per round trip +- Always gate buy rules with position state "flat" and sell rules with "long" +"## + ) +} + +/// Build the user message for the first iteration (no prior results). +pub fn initial_prompt(instruments: &[String], candle_intervals: &[String]) -> String { + format!( + r#"Design a trading strategy for crypto spot markets. + +Available instruments: {} +Available candle intervals: {} + +Start with a multi-timeframe trend-following approach with proper risk management +(stop-loss, time exit, and ATR-based position sizing). Use "usdc" as the quote asset. + +Respond with ONLY the strategy JSON."#, + instruments.join(", "), + candle_intervals.join(", "), + ) +} + +/// Build the user message for subsequent iterations, including prior results. +pub fn iteration_prompt( + iteration: u32, + results_history: &str, + best_so_far: Option<&str>, +) -> String { + let best_section = match best_so_far { + Some(strat) => format!( + "\n\nBest strategy so far:\n```json\n{strat}\n```\n\n\ + You may refine this strategy or try something completely different." + ), + None => String::from( + "\n\nNo promising strategies found yet. Try a different approach — \ + different indicator family, different timeframe, different entry logic." + ), + }; + + format!( + r#"Iteration {iteration}. Here are the results from all previous backtests: + +{results_history} +{best_section} + +Based on these results, design the next strategy to test. Learn from what worked +and what didn't. If a strategy family consistently fails, try a different one. + +Respond with ONLY the strategy JSON."#, + ) +} diff --git a/src/swym.rs b/src/swym.rs new file mode 100644 index 0000000..a639c8a --- /dev/null +++ b/src/swym.rs @@ -0,0 +1,249 @@ +use anyhow::{Context, Result}; +use reqwest::Client; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use uuid::Uuid; + +/// Client for the swym backtesting API. +pub struct SwymClient { + client: Client, + base_url: String, +} + +#[derive(Debug, Deserialize)] +pub struct PaperRunResponse { + pub id: Uuid, + pub status: String, + pub result_summary: Option, + pub error_message: Option, +} + +#[derive(Debug, Deserialize)] +pub struct PositionsResponse { + pub total: u32, + pub positions: Vec, +} + +#[derive(Debug, Deserialize)] +pub struct CandleCoverage { + pub interval: String, + pub first_open: String, + pub last_close: String, + pub count: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct BacktestResult { + pub run_id: Uuid, + pub instrument: String, + pub status: String, + pub total_positions: Option, + pub winning_positions: Option, + pub losing_positions: Option, + pub win_rate: Option, + pub profit_factor: Option, + pub total_pnl: Option, + pub net_pnl: Option, + pub sharpe_ratio: Option, + pub total_fees: Option, + pub avg_bars_in_trade: Option, + pub error_message: Option, + pub condition_audit_summary: Option, +} + +impl BacktestResult { + pub fn from_response(resp: &PaperRunResponse, instrument: &str) -> Self { + let summary = resp.result_summary.as_ref(); + Self { + run_id: resp.id, + instrument: instrument.to_string(), + status: resp.status.clone(), + total_positions: summary.and_then(|s| s["total_positions"].as_u64().map(|v| v as u32)), + winning_positions: summary.and_then(|s| s["winning_positions"].as_u64().map(|v| v as u32)), + losing_positions: summary.and_then(|s| s["losing_positions"].as_u64().map(|v| v as u32)), + win_rate: summary.and_then(|s| s["win_rate"].as_f64()), + profit_factor: summary.and_then(|s| s["profit_factor"].as_f64()), + total_pnl: summary.and_then(|s| s["total_pnl"].as_f64()), + net_pnl: summary.and_then(|s| s["net_pnl"].as_f64()), + sharpe_ratio: summary.and_then(|s| s["sharpe_ratio"].as_f64()), + total_fees: summary.and_then(|s| s["total_fees"].as_f64()), + avg_bars_in_trade: summary.and_then(|s| s["avg_bars_in_trade"].as_f64()), + error_message: resp.error_message.clone(), + condition_audit_summary: summary.and_then(|s| s.get("condition_audit_summary").cloned()), + } + } + + /// One-line summary for logging and feeding back to Claude. + pub fn summary_line(&self) -> String { + if self.status == "failed" { + return format!( + "[{}] FAILED: {}", + self.instrument, + self.error_message.as_deref().unwrap_or("unknown error") + ); + } + format!( + "[{}] trades={} win_rate={:.1}% pf={:.2} net_pnl={:.2} sharpe={:.2} avg_bars={:.1}", + self.instrument, + self.total_positions.unwrap_or(0), + self.win_rate.unwrap_or(0.0) * 100.0, + self.profit_factor.unwrap_or(0.0), + self.net_pnl.unwrap_or(0.0), + self.sharpe_ratio.unwrap_or(0.0), + self.avg_bars_in_trade.unwrap_or(0.0), + ) + } + + /// Is this result promising enough to warrant out-of-sample validation? + pub fn is_promising(&self, min_sharpe: f64, min_trades: u32) -> bool { + self.status == "complete" + && self.sharpe_ratio.unwrap_or(0.0) > min_sharpe + && self.total_positions.unwrap_or(0) >= min_trades + && self.net_pnl.unwrap_or(0.0) > 0.0 + } +} + +impl SwymClient { + pub fn new(base_url: &str) -> Result { + let client = Client::builder() + .danger_accept_invalid_certs(true) // internal TLS with self-signed certs + .timeout(std::time::Duration::from_secs(30)) + .build()?; + Ok(Self { + client, + base_url: base_url.trim_end_matches('/').to_string(), + }) + } + + /// Check candle coverage for an instrument. + pub async fn candle_coverage( + &self, + exchange: &str, + symbol: &str, + ) -> Result> { + let url = format!( + "{}/market-candles/coverage/{}/{}", + self.base_url, exchange, symbol + ); + let resp = self + .client + .get(&url) + .send() + .await + .context("candle coverage request")?; + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!("candle coverage {status}: {body}"); + } + resp.json().await.context("parse candle coverage") + } + + /// Submit a backtest run. + pub async fn submit_backtest( + &self, + instrument_exchange: &str, + instrument_symbol: &str, + base_asset: &str, + quote_asset: &str, + strategy: &Value, + starts_at: &str, + finishes_at: &str, + initial_balance: &str, + fees_percent: &str, + ) -> Result { + let body = serde_json::json!({ + "mode": "backtest", + "starts_at": starts_at, + "finishes_at": finishes_at, + "risk_free_return": "0.05", + "config": { + "instrument": { + "exchange": instrument_exchange, + "name_exchange": instrument_symbol, + "underlying": { "base": base_asset, "quote": quote_asset }, + "quote": "underlying_quote", + "kind": "spot" + }, + "execution": { + "mocked_exchange": instrument_exchange, + "latency_ms": 100, + "fees_percent": fees_percent, + "initial_state": { + "exchange": instrument_exchange, + "balances": [{ + "asset": quote_asset, + "balance": { "total": initial_balance, "free": initial_balance }, + "time_exchange": starts_at + }], + "instrument": { + "instrument_name": instrument_symbol, + "orders": [] + } + } + }, + "strategy": strategy, + "audit_conditions": true + } + }); + + let url = format!("{}/paper-runs", self.base_url); + let resp = self + .client + .post(&url) + .json(&body) + .send() + .await + .context("submit backtest")?; + + if !resp.status().is_success() { + let status = resp.status(); + let body_text = resp.text().await.unwrap_or_default(); + anyhow::bail!("submit backtest {status}: {body_text}"); + } + resp.json().await.context("parse backtest response") + } + + /// Poll a run until it reaches a terminal state. + pub async fn poll_until_done( + &self, + run_id: Uuid, + poll_interval: std::time::Duration, + timeout: std::time::Duration, + ) -> Result { + let url = format!("{}/paper-runs/{}", self.base_url, run_id); + let deadline = tokio::time::Instant::now() + timeout; + + loop { + let resp: PaperRunResponse = self + .client + .get(&url) + .send() + .await + .context("poll backtest")? + .json() + .await + .context("parse poll response")?; + + match resp.status.as_str() { + "complete" | "failed" | "cancelled" => return Ok(resp), + _ => { + if tokio::time::Instant::now() > deadline { + anyhow::bail!("backtest {run_id} timed out after {}s", timeout.as_secs()); + } + tokio::time::sleep(poll_interval).await; + } + } + } + } + + /// Fetch condition audit summary for a completed run. + pub async fn condition_audit(&self, run_id: Uuid) -> Result { + let url = format!("{}/paper-runs/{}/condition-audit", self.base_url, run_id); + let resp = self.client.get(&url).send().await?; + if !resp.status().is_success() { + anyhow::bail!("condition audit {}: {}", resp.status(), resp.text().await?); + } + resp.json().await.context("parse condition audit") + } +}