├── .buildkite └── pipeline.yaml ├── .envrc ├── .github └── pull_request_template.md ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── benches └── candle_aggregation.rs ├── data ├── Bitmex_XBTUSD_1M.csv └── Bitstamp_BTCEUR_1M.csv ├── examples ├── aggregate_all_ohlc.rs ├── streaming_aggregate_ohlc.rs └── user_trade_type.rs ├── flake.lock ├── flake.nix ├── img └── relative_price_candles_plot.png ├── mprocs.yaml ├── readme_img ├── agplv3.png ├── monero_donations_qrcode.png └── time_candles_plot.png ├── rustfmt.toml ├── src ├── aggregation_rules │ ├── aggregation_rule_trait.rs │ ├── aligned_time_rule.rs │ ├── mod.rs │ ├── relative_price_rule.rs │ ├── tick_rule.rs │ ├── time_rule.rs │ └── volume_rule.rs ├── aggregator.rs ├── candle_components │ ├── average_price.rs │ ├── candle_component_trait.rs │ ├── close.rs │ ├── close_timestamp.rs │ ├── directional_trade_ratio.rs │ ├── directional_volume_ratio.rs │ ├── entropy.rs │ ├── high.rs │ ├── low.rs │ ├── median_price.rs │ ├── mod.rs │ ├── num_trades.rs │ ├── open.rs │ ├── open_datetime.rs │ ├── open_timestamp.rs │ ├── std_dev_prices.rs │ ├── std_dev_sizes.rs │ ├── time_velocity.rs │ ├── trades.rs │ ├── volume.rs │ ├── volume_buys.rs │ ├── volume_sells.rs │ ├── vpin.rs │ └── weighted_price.rs ├── constants.rs ├── errors.rs ├── lib.rs ├── modular_candle_trait.rs ├── plot.rs ├── types.rs ├── utils.rs └── welford_online.rs └── trade_aggregation_derive ├── Cargo.toml ├── LICENSE ├── README.md └── src └── lib.rs /.buildkite/pipeline.yaml: -------------------------------------------------------------------------------- 1 | steps: 2 | - label: ":nixos: :rust: check" 3 | command: RUSTFLAGS="-D warnings" nix develop --command bash -c "cargo check" 4 | agents: 5 | queue: nixos 6 | 7 | - label: ":nixos: :rust: clippy" 8 | command: RUSTFLAGS="-D warnings" nix develop --command bash -c "cargo clippy" 9 | agents: 10 | queue: nixos 11 | 12 | - label: ":nixos: :rust: test" 13 | command: RUSTFLAGS="-D warnings" nix develop --command bash -c "cargo test" 14 | agents: 15 | queue: nixos 16 | 17 | - label: ":nixos: :rust: fmt" 18 | command: RUSTFLAGS="-D warnings" nix develop --command bash -c "cargo fmt --check" 19 | agents: 20 | queue: nixos 21 | 22 | - label: ":nixos: :rust: doc" 23 | command: nix develop --command bash -c "cargo doc --no-deps --workspace" 24 | agents: 25 | queue: nixos 26 | 27 | - label: ":nixos: :rust: taplo" 28 | command: nix develop --command bash -c "taplo fmt --check" 29 | agents: 30 | queue: nixos 31 | 32 | - label: ":nixos: :rust: semver-checks" 33 | command: nix develop --command bash -c "cargo semver-checks" 34 | agents: 35 | queue: nixos 36 | 37 | - label: ":nixos: :rust: bench" 38 | command: nix develop --command bash -c "cargo bench" 39 | agents: 40 | queue: nixos 41 | -------------------------------------------------------------------------------- /.envrc: -------------------------------------------------------------------------------- 1 | use flake 2 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ## Changes: 2 | 3 | 6 | 7 | * 🩹 Bug Fix 8 | * 🦚 Feature 9 | * 📙 Documentation 10 | * 🪣 Misc 11 | 12 | ## References: 13 | 14 | 17 | 18 | ## Changes proposed by this PR: 19 | 20 | 23 | 24 | ## Notes to reviewer: 25 | 26 | 32 | 33 | ## 📜 Checklist 34 | 35 | * [ ] The PR scope is bounded 36 | * [ ] Relevant issues and discussions are referenced 37 | * [ ] Test coverage is excellent and passes 38 | * [ ] Tests test the desired behavior 39 | * [ ] Documentation is thorough 40 | 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /vendor 3 | /.idea 4 | /trade_aggregation_derive/target 5 | /img 6 | /.direnv 7 | Cargo.lock 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "trade_aggregation" 3 | version = "12.0.3" 4 | authors = ["MathisWellmann "] 5 | edition = "2021" 6 | license-file = "LICENSE" 7 | description = "Aggregate trades into user defined candles using information driven rules" 8 | repository = "https://github.com/MathisWellmann/trade_aggregation-rs" 9 | readme = "README.md" 10 | keywords = ["trading", "candles"] 11 | categories = ["algorithms"] 12 | exclude = ["/img", "/.idea"] 13 | 14 | [workspace.lints.rust] 15 | unused_imports = "deny" 16 | missing_docs = "deny" 17 | dead_code = "deny" 18 | 19 | [workspace.lints.clippy] 20 | all = "deny" 21 | 22 | [dependencies] 23 | csv = "1" 24 | thiserror = "1" 25 | 26 | trade_aggregation_derive = { path = "./trade_aggregation_derive", version = "0.4.1" } 27 | 28 | # Optionals 29 | serde = { version = "1", features = ["derive"], optional = true } 30 | chrono = { version = "0.4", features = ["serde"], optional = true } 31 | 32 | [dev-dependencies] 33 | round = "0.1" 34 | criterion = "0.5" 35 | plotters = "0.3" 36 | 37 | [[bench]] 38 | name = "candle_aggregation" 39 | harness = false 40 | 41 | [features] 42 | serde = ["dep:serde"] 43 | chrono = ["dep:chrono"] 44 | 45 | [workspace.metadata.spellcheck] 46 | config = "./.spellcheck/spellcheck.toml" 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Trade Aggregation 2 | A high performance, modular and flexible trade aggregation crate, producing Candle data, 3 | suitable for low-latency applications and incremental updates. 4 | It allows the user to choose the rule dictating how a new candle is created 5 | through the [AggregationRule](src/aggregation_rules/aggregation_rule_trait.rs) trait, 6 | e.g: Time, Volume based or some other information driven rule. 7 | It also allows the user to choose which type of candle will be created from the aggregation process 8 | through the [ModularCandle](src/modular_candle_trait.rs) trait. Combined with the [Candle](trade_aggregation_derive/src/lib.rs) macro, 9 | it enables the user to flexibly create any type of Candle as long as each component implements 10 | the [CandleComponent](src/candle_components/candle_component_trait.rs) trait. 11 | The aggregation process is also generic over the type of input trade data 12 | as long as it implements the [TakerTrade](src/types.rs) trait, 13 | allowing for greater flexibility for downstream projects. 14 | 15 | See [MathisWellmann/go_trade_aggregation](https://github.com/MathisWellmann/go_trade_aggregation) for a go implementation with less features and performance. 16 | 17 | Here is a sample trade series of `Bitmex_XBTUSD` aggregated into 15 minute candles: 18 | ![time_candles](readme_img/time_candles_plot.png) 19 | 20 | ## Features: 21 | ### `AggregationRule`: 22 | The pre-existing rules in this crate include: 23 | 'AggregationRule' | Description 24 | --------------------|------------- 25 | `TimeRule` | Create candles every n seconds 26 | `AlignedTimeRule` | Same as TimeRule but candles are aligned to the start of a period 27 | `VolumeRule` | Create candles every n units traded 28 | `TickRule` | Create candles every n ticks 29 | `RelativePriceRule` | Create candles with every n basis points price movement (Renko) 30 | 31 | If these don't satisfy your desires, just create your own by implementing the [`AggregationRule`](src/aggregation_rules/aggregation_rule_trait.rs) trait, 32 | and you can plug and play it into the [`GenericAggregator`](src/aggregator.rs). 33 | 34 | ### `CandleComponent`: 35 | These pre-existing 'CandleComponents' exist out of the box: 36 | 'CandleComponent' | Description 37 | --------------------| --- 38 | `Open` | Price at the beginning of a candle 39 | `High` | Maximum price during the candle 40 | `Low` | Minimum price during the candle 41 | `Close` | Price at the end of a candle 42 | `Volume` | The cumulative trading volume 43 | `NumTrades` | The number of trades during the candle 44 | `AveragePrice` | The equally weighted average price 45 | `WeightedPrice` | The volume weighted price 46 | `StdDevPrices` | Keeps track of the standard deviation of prices 47 | `StdDevSizes` | Keeps track of the standard deviation of sizes 48 | `TimeVelocity` | Essentially how fast the candle was created time wise 49 | `Entropy` | Binary Shannon entropy using the trade side as inputs 50 | `Trades` | Just returns the observed trades during that candle 51 | 52 | And again, if these don't satisfy your needs, just bring your own by implementing the 53 | [CandleComponent](src/candle_components/candle_component_trait.rs) trait and you can plug them into your own candle struct. 54 | 55 | ## How to use: 56 | To use this crate in your project, add the following to your Cargo.toml: 57 | 58 | ```toml 59 | [dependencies] 60 | trade_aggregation = "12" 61 | ``` 62 | 63 | Lets aggregate all trades into time based 1 minute candles, consisting of open, high, low and close information. 64 | Notice how easy it is to specify the 'AggregationRule' and 'ModularCandle' being used in the process. 65 | One can easily plug in their own implementation of those trait for full customization. 66 | This examples uses an online style approach to update with each tick: 67 | 68 | ```rust 69 | use trade_aggregation::{ 70 | candle_components::{Close, High, Low, Open}, 71 | *, 72 | }; 73 | 74 | #[derive(Debug, Default, Clone, Candle)] 75 | struct MyCandle { 76 | open: Open, 77 | high: High, 78 | low: Low, 79 | close: Close, 80 | } 81 | 82 | fn main() { 83 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv") 84 | .expect("Could not load trades from file!"); 85 | 86 | // specify the aggregation rule to be time based and the resolution each trade timestamp has 87 | let time_rule = TimeRule::new(M1, TimestampResolution::Millisecond); 88 | // Notice how the aggregator is generic over the output candle type, 89 | // the aggregation rule as well as the input trade data 90 | let mut aggregator = GenericAggregator::::new(time_rule, false); 91 | 92 | for t in &trades { 93 | if let Some(candle) = aggregator.update(t) { 94 | println!( 95 | "candle created with open: {}, high: {}, low: {}, close: {}", 96 | candle.open(), 97 | candle.high(), 98 | candle.low(), 99 | candle.close() 100 | ); 101 | } 102 | } 103 | } 104 | ``` 105 | 106 | Notice how the code is calling the 'open()', 'high()', 'low()' and 'close()' 107 | methods on the 'MyCandle' struct. 108 | These are getters automatically generated by the [Candle](trade_aggregation_derive/src/lib.rs) macro, 109 | that have the same name as the field. 110 | In this case the 'Candle' derive macro for 'MyCandle' expands into this: 111 | ```rust 112 | use trade_aggregation::{ 113 | candle_components::{Close, High, Low, Open}, 114 | *, 115 | }; 116 | 117 | #[derive(Debug, Default, Clone)] 118 | struct MyCandle { 119 | open: Open, 120 | high: High, 121 | low: Low, 122 | close: Close, 123 | } 124 | 125 | impl MyCandle { 126 | fn open(&self) -> f64 { 127 | self.open.value() 128 | } 129 | fn high(&self) -> f64 { 130 | self.high.value() 131 | } 132 | fn low(&self) -> f64 { 133 | self.low.value() 134 | } 135 | fn close(&self) -> f64 { 136 | self.close.value() 137 | } 138 | } 139 | 140 | impl ModularCandle for MyCandle { 141 | fn update(&mut self, trade: &Trade) { 142 | self.open.update(trade); 143 | self.high.update(trade); 144 | self.low.update(trade); 145 | self.close.update(trade); 146 | } 147 | fn reset(&mut self) { 148 | self.open.reset(); 149 | self.high.reset(); 150 | self.low.reset(); 151 | self.close.reset(); 152 | } 153 | } 154 | ``` 155 | 156 | See examples folder for more. 157 | Run examples using 158 | ```ignore 159 | cargo run --release --example aggregate_all_ohlc 160 | cargo run --release --example streaming_aggregate_ohlc 161 | ``` 162 | 163 | ## Performance: 164 | To run the benchmarks, written using criterion, run: 165 | 166 | ```ignore 167 | cargo bench 168 | ``` 169 | 170 | Here are some results running on a 12th gen Intel Core i7-12800H, aggregating 1 million trades into 1 minute candles: 171 | 172 | Candle | Time 173 | -------|----------- 174 | Open | 1 ms 175 | OHLC | 2.5 ms 176 | All | 8 ms 177 | 178 | The more 'CandleComponent's you use, the longer it takes obviously. 179 | 180 | ### Features 181 | The serde feature exists which, when enabled, derives Serialize and Deserialize 182 | 183 | 184 | ### TODOs: 185 | - Make generic over the data type storing the price (`f64`, `f32`, `i64`, `Decimal`, etc...) 186 | 187 | ### Donations :moneybag: :money_with_wings: 188 | I you would like to support the development of this crate, feel free to send over a donation: 189 | 190 | Monero (XMR) address: 191 | ```plain 192 | 47xMvxNKsCKMt2owkDuN1Bci2KMiqGrAFCQFSLijWLs49ua67222Wu3LZryyopDVPYgYmAnYkSZSz9ZW2buaDwdyKTWGwwb 193 | ``` 194 | 195 | ![monero](readme_img/monero_donations_qrcode.png) 196 | 197 | 198 | ### License 199 | Copyright (C) 2020 200 | 201 | This program is free software: you can redistribute it and/or modify 202 | it under the terms of the GNU Affero General Public License as published by 203 | the Free Software Foundation, either version 3 of the License, or 204 | (at your option) any later version. 205 | 206 | This program is distributed in the hope that it will be useful, 207 | but WITHOUT ANY WARRANTY; without even the implied warranty of 208 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 209 | GNU Affero General Public License for more details. 210 | 211 | You should have received a copy of the GNU Affero General Public License 212 | along with this program. If not, see . 213 | 214 | ![GNU AGPLv3](readme_img/agplv3.png) 215 | 216 | ### Commercial License 217 | If you'd like to use this crate legally without the restrictions of the GNU AGPLv3 license, 218 | please contact me so we can quickly arrange a custom license. 219 | -------------------------------------------------------------------------------- /benches/candle_aggregation.rs: -------------------------------------------------------------------------------- 1 | use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput}; 2 | use trade_aggregation::{ 3 | aggregate_all_trades, candle_components::*, load_trades_from_csv, CandleComponent, 4 | GenericAggregator, ModularCandle, TimeRule, TimestampResolution, Trade, M1, 5 | }; 6 | use trade_aggregation_derive::Candle; 7 | 8 | #[derive(Debug, Clone, Default, Candle)] 9 | struct CandleOpen { 10 | open: Open, 11 | } 12 | 13 | #[derive(Debug, Clone, Default, Candle)] 14 | struct CandleOHLC { 15 | open: Open, 16 | high: High, 17 | low: Low, 18 | close: Close, 19 | } 20 | 21 | #[derive(Debug, Clone, Default, Candle)] 22 | struct CandleAll { 23 | open: Open, 24 | high: High, 25 | low: Low, 26 | close: Close, 27 | volume: Volume, 28 | num_trades: NumTrades, 29 | directional_trade_ratio: DirectionalTradeRatio, 30 | directional_volume_ratio: DirectionalVolumeRatio, 31 | std_dev_prices: StdDevPrices, 32 | std_dev_sizes: StdDevSizes, 33 | weighted_price: WeightedPrice, 34 | average_price: AveragePrice, 35 | time_velocity: TimeVelocity, 36 | } 37 | 38 | fn time_aggregation_open(trades: &[Trade]) { 39 | let time_rule = TimeRule::new(M1, TimestampResolution::Millisecond); 40 | let mut aggregator = GenericAggregator::::new(time_rule, false); 41 | let _candles = aggregate_all_trades(trades, &mut aggregator); 42 | } 43 | 44 | fn time_aggregation_ohlc(trades: &[Trade]) { 45 | let time_rule = TimeRule::new(M1, TimestampResolution::Millisecond); 46 | let mut aggregator = GenericAggregator::::new(time_rule, false); 47 | let _candles = aggregate_all_trades(trades, &mut aggregator); 48 | } 49 | 50 | fn time_aggregation_all(trades: &[Trade]) { 51 | let time_rule = TimeRule::new(M1, TimestampResolution::Millisecond); 52 | let mut aggregator = GenericAggregator::::new(time_rule, false); 53 | let _candles = aggregate_all_trades(trades, &mut aggregator); 54 | } 55 | 56 | fn criterion_benchmark(c: &mut Criterion) { 57 | let trades = 58 | load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv").expect("Could not open trade data file!"); 59 | let mut group = c.benchmark_group("time_aggregation"); 60 | group.throughput(Throughput::Elements(1_000_000)); 61 | group.bench_function("time_aggregation_open", |b| { 62 | b.iter(|| time_aggregation_open(black_box(&trades))) 63 | }); 64 | group.bench_function("time_aggregation_ohlc", |b| { 65 | b.iter(|| time_aggregation_ohlc(black_box(&trades))) 66 | }); 67 | group.bench_function("time_aggregation_all", |b| { 68 | b.iter(|| time_aggregation_all(black_box(&trades))) 69 | }); 70 | } 71 | 72 | criterion_group!(benches, criterion_benchmark); 73 | criterion_main!(benches); 74 | -------------------------------------------------------------------------------- /data/Bitstamp_BTCEUR_1M.csv: -------------------------------------------------------------------------------- 1 | timestamp,price,size 2 | 1612137602564000,27334.25,0.00289 3 | 1612137605659000,27308.91,0.01344 4 | 1612137610980000,27334.08,0.00297938 5 | 1612137613201000,27329.54,0.00289654 6 | 1612137622744000,27304.72,0.02326593 7 | 1612137622980000,27304.72,0.20373407 8 | 1612137645215000,27304.31,0.006 9 | 1612137645316000,27304.31,0.00025762 10 | 1612137647182000,27308.32,0.01766778 11 | 1612137659521000,27288.07,0.00145 12 | 1612137664747000,27298.5,0.00909044 13 | -------------------------------------------------------------------------------- /examples/aggregate_all_ohlc.rs: -------------------------------------------------------------------------------- 1 | //! This example shows how to aggregate all trades into time based 2 | //! 1 minute candles all at once. The candle will contain the open, high, low and close price 3 | //! 4 | //! When deriving the 'Candle' macro, make sure the following things are in scope: 5 | //! - Trade 6 | //! - ModularCandle 7 | //! - CandleComponent 8 | 9 | use trade_aggregation::{ 10 | candle_components::{Close, High, Low, Open}, 11 | *, 12 | }; 13 | 14 | #[derive(Debug, Default, Clone, Candle)] 15 | pub struct MyCandle { 16 | open: Open, 17 | high: High, 18 | low: Low, 19 | close: Close, 20 | } 21 | 22 | fn main() { 23 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv") 24 | .expect("Could not load trades from file!"); 25 | 26 | // specify the aggregation rule to be time based 27 | let time_rule = TimeRule::new(M1, TimestampResolution::Millisecond); 28 | let mut aggregator = GenericAggregator::::new(time_rule, false); 29 | 30 | let candles = aggregate_all_trades(&trades, &mut aggregator); 31 | println!("got {} candles", candles.len()); 32 | } 33 | -------------------------------------------------------------------------------- /examples/streaming_aggregate_ohlc.rs: -------------------------------------------------------------------------------- 1 | //! This example shows how to perform tick-by-tick streaming trade aggregation 2 | //! 3 | 4 | use trade_aggregation::{ 5 | candle_components::{Close, High, Low, Open}, 6 | *, 7 | }; 8 | 9 | #[derive(Debug, Default, Clone, Candle)] 10 | struct MyCandle { 11 | open: Open, 12 | high: High, 13 | low: Low, 14 | close: Close, 15 | } 16 | 17 | fn main() { 18 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv") 19 | .expect("Could not load trades from file!"); 20 | 21 | // specify the aggregation rule to be time based 22 | let time_rule = TimeRule::new(M1, TimestampResolution::Millisecond); 23 | let mut aggregator = GenericAggregator::::new(time_rule, false); 24 | 25 | for t in &trades { 26 | if let Some(candle) = aggregator.update(t) { 27 | println!( 28 | "candle created with open: {}, high: {}, low: {}, close: {}", 29 | candle.open(), 30 | candle.high(), 31 | candle.low(), 32 | candle.close() 33 | ); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /examples/user_trade_type.rs: -------------------------------------------------------------------------------- 1 | //! This example shows how to implement the TakerTrade trait for your own 2 | //! input type. It builds on the `aggregate_all_ohlc.rs` example. However, instead 3 | //! of using the default `Trade` type we define a custom type called `Tick`, 4 | //! which is very similar to `Trade`. Take note of the `input` field on 5 | //! `MyCandle` and the use of `PhantomData`, the `Candle` derive macro parses 6 | //! the `MyCandle` struct definition for this attribute and uses it to define the generic 7 | //! trait `ModularCandle`. 8 | 9 | //! When deriving the 'Candle' macro, make sure the following things are in scope: 10 | //! - Trade 11 | //! - ModularCandle 12 | //! - CandleComponent 13 | 14 | use std::marker::PhantomData; 15 | 16 | use trade_aggregation::{ 17 | candle_components::{Close, High, Low, Open}, 18 | *, 19 | }; 20 | 21 | pub enum Side { 22 | Bid, 23 | Ask, 24 | } 25 | 26 | pub struct Tick { 27 | /// Timestamp, assumed to be in milliseconds 28 | pub date_stamp: i64, 29 | 30 | /// Price of the asset 31 | pub trade_price: f64, 32 | 33 | /// Size of the trade 34 | pub size: usize, 35 | /// whether the trade was executed on the bid or the ask 36 | pub side: Side, 37 | } 38 | 39 | impl TakerTrade for Tick { 40 | #[inline(always)] 41 | fn timestamp(&self) -> i64 { 42 | self.date_stamp 43 | } 44 | 45 | #[inline(always)] 46 | fn price(&self) -> f64 { 47 | self.trade_price 48 | } 49 | 50 | #[inline(always)] 51 | fn size(&self) -> f64 { 52 | match self.side { 53 | Side::Bid => self.size as f64 * -1.0, 54 | Side::Ask => self.size as f64, 55 | } 56 | } 57 | } 58 | 59 | impl From for Tick { 60 | fn from(trade: Trade) -> Self { 61 | let side = if trade.size > 0.0 { 62 | Side::Ask 63 | } else { 64 | Side::Bid 65 | }; 66 | Tick { 67 | date_stamp: trade.timestamp, 68 | trade_price: trade.price, 69 | size: trade.size.abs() as usize, 70 | side, 71 | } 72 | } 73 | } 74 | 75 | #[derive(Debug, Default, Clone, Candle)] 76 | struct MyCandle { 77 | open: Open, 78 | high: High, 79 | low: Low, 80 | close: Close, 81 | input: PhantomData, 82 | } 83 | 84 | fn main() { 85 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv") 86 | .expect("Could not load trades from file!"); 87 | let ticks: Vec = trades.into_iter().map(|x| x.into()).collect(); 88 | 89 | // specify the aggregation rule to be time based 90 | let time_rule = TimeRule::new(M1, TimestampResolution::Millisecond); 91 | let mut aggregator = GenericAggregator::::new(time_rule, false); 92 | 93 | let candles = aggregate_all_trades(&ticks, &mut aggregator); 94 | println!("got {} candles", candles.len()); 95 | } 96 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "flake-utils": { 4 | "inputs": { 5 | "systems": "systems" 6 | }, 7 | "locked": { 8 | "lastModified": 1710146030, 9 | "narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=", 10 | "owner": "numtide", 11 | "repo": "flake-utils", 12 | "rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a", 13 | "type": "github" 14 | }, 15 | "original": { 16 | "owner": "numtide", 17 | "repo": "flake-utils", 18 | "type": "github" 19 | } 20 | }, 21 | "nixpkgs": { 22 | "locked": { 23 | "lastModified": 0, 24 | "narHash": "sha256-hMyG9/WlUi0Ho9VkRrrez7SeNlDzLxalm9FwY7n/Noo=", 25 | "path": "/nix/store/920a6ivyd50598z8djw9x3mr33gys0j5-source", 26 | "type": "path" 27 | }, 28 | "original": { 29 | "id": "nixpkgs", 30 | "type": "indirect" 31 | } 32 | }, 33 | "nixpkgs_2": { 34 | "locked": { 35 | "lastModified": 1728538411, 36 | "narHash": "sha256-f0SBJz1eZ2yOuKUr5CA9BHULGXVSn6miBuUWdTyhUhU=", 37 | "owner": "NixOS", 38 | "repo": "nixpkgs", 39 | "rev": "b69de56fac8c2b6f8fd27f2eca01dcda8e0a4221", 40 | "type": "github" 41 | }, 42 | "original": { 43 | "owner": "NixOS", 44 | "ref": "nixpkgs-unstable", 45 | "repo": "nixpkgs", 46 | "type": "github" 47 | } 48 | }, 49 | "nixpks": { 50 | "locked": { 51 | "lastModified": 1711703276, 52 | "narHash": "sha256-iMUFArF0WCatKK6RzfUJknjem0H9m4KgorO/p3Dopkk=", 53 | "owner": "NixOS", 54 | "repo": "nixpkgs", 55 | "rev": "d8fe5e6c92d0d190646fb9f1056741a229980089", 56 | "type": "github" 57 | }, 58 | "original": { 59 | "owner": "NixOS", 60 | "ref": "nixos-unstable", 61 | "repo": "nixpkgs", 62 | "type": "github" 63 | } 64 | }, 65 | "root": { 66 | "inputs": { 67 | "flake-utils": "flake-utils", 68 | "nixpkgs": "nixpkgs", 69 | "nixpks": "nixpks", 70 | "rust-overlay": "rust-overlay" 71 | } 72 | }, 73 | "rust-overlay": { 74 | "inputs": { 75 | "nixpkgs": "nixpkgs_2" 76 | }, 77 | "locked": { 78 | "lastModified": 1730169013, 79 | "narHash": "sha256-rvgF03ODu1uEYbdEsloN4fQrJ+k1NOv/7MJvCpHHnBk=", 80 | "owner": "oxalica", 81 | "repo": "rust-overlay", 82 | "rev": "92eb1268cc19609f2fe24311b871f37bf3dc5afd", 83 | "type": "github" 84 | }, 85 | "original": { 86 | "owner": "oxalica", 87 | "repo": "rust-overlay", 88 | "type": "github" 89 | } 90 | }, 91 | "systems": { 92 | "locked": { 93 | "lastModified": 1681028828, 94 | "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", 95 | "owner": "nix-systems", 96 | "repo": "default", 97 | "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", 98 | "type": "github" 99 | }, 100 | "original": { 101 | "owner": "nix-systems", 102 | "repo": "default", 103 | "type": "github" 104 | } 105 | } 106 | }, 107 | "root": "root", 108 | "version": 7 109 | } 110 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "Flake for trade_aggregation-rs"; 3 | 4 | inputs = { 5 | nixpks.url = "github:NixOS/nixpkgs/nixos-unstable"; 6 | rust-overlay.url = "github:oxalica/rust-overlay"; 7 | flake-utils.url = "github:numtide/flake-utils"; 8 | }; 9 | 10 | outputs = { 11 | nixpkgs, 12 | rust-overlay, 13 | flake-utils, 14 | ... 15 | }: 16 | flake-utils.lib.eachDefaultSystem ( 17 | system: let 18 | overlays = [(import rust-overlay)]; 19 | pkgs = import nixpkgs { 20 | inherit system overlays; 21 | }; 22 | rust = ( 23 | pkgs.rust-bin.stable."1.82.0".default.override { 24 | extensions = [ 25 | "rust-src" 26 | "rust-analyzer" 27 | ]; 28 | targets = ["x86_64-unknown-linux-gnu"]; 29 | } 30 | ); 31 | in 32 | with pkgs; { 33 | devShells.default = mkShell { 34 | buildInputs = [ 35 | openssl 36 | protobuf 37 | clang 38 | pkg-config 39 | fontconfig 40 | cmake 41 | # We use some `rustfmt` rules that are only available on the nightly channel. 42 | (lib.hiPrio rust-bin.nightly."2024-10-01".rustfmt) 43 | rust 44 | taplo 45 | cargo-semver-checks 46 | ]; 47 | }; 48 | } 49 | ); 50 | } 51 | -------------------------------------------------------------------------------- /img/relative_price_candles_plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MathisWellmann/trade_aggregation-rs/c3d933d804bc4733d931e40baf4988740ce9ec0b/img/relative_price_candles_plot.png -------------------------------------------------------------------------------- /mprocs.yaml: -------------------------------------------------------------------------------- 1 | procs: 2 | cargo-check: 3 | shell: "cargo check" 4 | cargo-test: 5 | shell: "cargo test" 6 | cargo-bench: 7 | shell: "cargo bench" 8 | cargo-fmt: 9 | shell: "cargo fmt" 10 | cargo-clippy: 11 | shell: "cargo clippy" 12 | cargo-doc: 13 | shell: "cargo doc" 14 | taplo: 15 | shell: "taplo fmt" 16 | semver-checks: 17 | shell: "cargo semver-checks" 18 | -------------------------------------------------------------------------------- /readme_img/agplv3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MathisWellmann/trade_aggregation-rs/c3d933d804bc4733d931e40baf4988740ce9ec0b/readme_img/agplv3.png -------------------------------------------------------------------------------- /readme_img/monero_donations_qrcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MathisWellmann/trade_aggregation-rs/c3d933d804bc4733d931e40baf4988740ce9ec0b/readme_img/monero_donations_qrcode.png -------------------------------------------------------------------------------- /readme_img/time_candles_plot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MathisWellmann/trade_aggregation-rs/c3d933d804bc4733d931e40baf4988740ce9ec0b/readme_img/time_candles_plot.png -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | imports_granularity = "Crate" 2 | group_imports = "StdExternalCrate" 3 | -------------------------------------------------------------------------------- /src/aggregation_rules/aggregation_rule_trait.rs: -------------------------------------------------------------------------------- 1 | use crate::TakerTrade; 2 | 3 | /// Defines under what conditions one aggregation period is finished 4 | /// Is generic over the type of candle being produced C, 5 | /// as well as the type of input trade T 6 | pub trait AggregationRule { 7 | /// The main method defining when the aggregation is done 8 | /// 9 | /// # Arguments: 10 | /// trade: The most recent taker trade (tick) information 11 | /// candle: Some generic Candle, allowing for information driven decision making 12 | /// 13 | /// # Returns: 14 | /// if true, the aggregation period is finished and a Candle can be emitted 15 | /// else the aggregation needs to continue 16 | fn should_trigger(&mut self, trade: &T, candle: &C) -> bool; 17 | } 18 | -------------------------------------------------------------------------------- /src/aggregation_rules/aligned_time_rule.rs: -------------------------------------------------------------------------------- 1 | use crate::{aggregation_rules::TimestampResolution, AggregationRule, ModularCandle, TakerTrade}; 2 | 3 | /// The classic time based aggregation rule, 4 | /// creating a new candle every n seconds. The time trigger is aligned such that 5 | /// the trigger points are starting from a time equals zero. For example, if the first 6 | /// tick comes in a 1:32:00 on a 5 minute candle, that first candle will only contain 7 | /// 3 minutes of trades, representing a 1:30 start. 8 | #[derive(Debug, Clone)] 9 | pub struct AlignedTimeRule { 10 | // The timestamp this rule uses as a reference 11 | reference_timestamp: i64, 12 | 13 | // The period for the candle in seconds 14 | // constants can be used nicely here from constants.rs 15 | // e.g.: M1 -> 1 minute candles 16 | period_s: i64, 17 | } 18 | 19 | impl AlignedTimeRule { 20 | /// Create a new instance of the aligned time rule, 21 | /// with a given candle period in seconds 22 | /// 23 | /// # Arguments: 24 | /// period_s: How many seconds a candle will contain 25 | /// ts_res: The resolution each Trade timestamp will have 26 | /// 27 | pub fn new(period_s: i64, ts_res: TimestampResolution) -> Self { 28 | let ts_multiplier = match ts_res { 29 | TimestampResolution::Second => 1, 30 | TimestampResolution::Millisecond => 1_000, 31 | TimestampResolution::Microsecond => 1_000_000, 32 | TimestampResolution::Nanosecond => 1_000_000_000, 33 | }; 34 | 35 | Self { 36 | reference_timestamp: 0, 37 | period_s: period_s * ts_multiplier, 38 | } 39 | } 40 | 41 | /// Calculates the "aligned" timestamp, which the rule will use when receiving 42 | /// for determining the trigger. This is done at the initialization of 43 | /// each period. 44 | #[must_use] 45 | pub fn aligned_timestamp(&self, timestamp: i64) -> i64 { 46 | timestamp - (timestamp % self.period_s) 47 | } 48 | } 49 | 50 | impl AggregationRule for AlignedTimeRule 51 | where 52 | C: ModularCandle, 53 | T: TakerTrade, 54 | { 55 | fn should_trigger(&mut self, trade: &T, _candle: &C) -> bool { 56 | if self.reference_timestamp == 0 { 57 | self.reference_timestamp = self.aligned_timestamp(trade.timestamp()); 58 | return false; 59 | } 60 | 61 | let should_trigger = trade.timestamp() - self.reference_timestamp >= self.period_s; 62 | if should_trigger { 63 | self.reference_timestamp = self.aligned_timestamp(trade.timestamp()); 64 | } 65 | 66 | should_trigger 67 | } 68 | } 69 | 70 | #[cfg(test)] 71 | mod tests { 72 | use trade_aggregation_derive::Candle; 73 | 74 | use super::*; 75 | use crate::{ 76 | aggregate_all_trades, 77 | candle_components::{ 78 | CandleComponent, CandleComponentUpdate, Close, NumTrades, Open, Volume, 79 | }, 80 | load_trades_from_csv, 81 | plot::OhlcCandle, 82 | GenericAggregator, ModularCandle, TimestampResolution, Trade, M1, M15, 83 | }; 84 | 85 | #[derive(Default, Debug, Clone, Candle)] 86 | struct MyCandle { 87 | open: Open, 88 | close: Close, 89 | num_trades: NumTrades, 90 | volume: Volume, 91 | } 92 | 93 | #[test] 94 | fn aligned_time_rule() { 95 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv").unwrap(); 96 | 97 | let mut aggregator = GenericAggregator::::new( 98 | AlignedTimeRule::new(M15, TimestampResolution::Millisecond), 99 | false, 100 | ); 101 | let candles = aggregate_all_trades(&trades, &mut aggregator); 102 | assert_eq!(candles.len(), 396); 103 | 104 | // make sure that the aggregator starts a new candle with the "trigger tick", 105 | // and includes that information of the trade that triggered the new candle as well 106 | let c = &candles[0]; 107 | assert_eq!(c.open(), 13873.0); 108 | assert_eq!(c.close(), 13769.0); 109 | let c = &candles[1]; 110 | assert_eq!(c.open(), 13768.5); 111 | assert_eq!(c.close(), 13721.5); 112 | } 113 | 114 | #[test] 115 | fn aligned_time_rule_volume() { 116 | let trades = load_trades_from_csv("data/Bitstamp_BTCEUR_1M.csv").unwrap(); 117 | 118 | let mut aggregator = GenericAggregator::::new( 119 | AlignedTimeRule::new(M1, TimestampResolution::Microsecond), 120 | false, 121 | ); 122 | let candles = aggregate_all_trades(&trades, &mut aggregator); 123 | 124 | let c = &candles[0]; 125 | assert_eq!(c.num_trades(), 10); 126 | assert_eq!(c.volume(), 0.27458132); 127 | } 128 | 129 | #[test] 130 | fn aligned_time_rule_trigger_on_0() { 131 | let trades: [Trade; 5] = [ 132 | Trade { 133 | timestamp: 1712656800000, 134 | price: 100.0, 135 | size: 10.0, 136 | }, 137 | Trade { 138 | timestamp: 1712656815000, 139 | price: 101.0, 140 | size: -10.0, 141 | }, 142 | Trade { 143 | timestamp: 1712656860000, 144 | price: 100.5, 145 | size: -10.0, 146 | }, 147 | Trade { 148 | timestamp: 1712656860001, 149 | price: 102.0, 150 | size: -10.0, 151 | }, 152 | Trade { 153 | timestamp: 1712656935000, 154 | price: 105.0, 155 | size: -10.0, 156 | }, 157 | ]; 158 | 159 | let mut aggregator = GenericAggregator::::new( 160 | AlignedTimeRule::new(M1, TimestampResolution::Millisecond), 161 | false, 162 | ); 163 | let candles = aggregate_all_trades(&trades, &mut aggregator); 164 | assert_eq!(candles.len(), 2); 165 | assert_eq!(candles[0].open(), 100.00); 166 | assert_eq!(candles[0].close(), 101.00); 167 | assert_eq!(candles[1].open(), 100.5); 168 | assert_eq!(candles[1].close(), 102.00); 169 | } 170 | 171 | #[test] 172 | fn aligned_time_rule_candle_with_one_trade() { 173 | let trades: [Trade; 4] = [ 174 | Trade { 175 | timestamp: 1712656800000, 176 | price: 100.0, 177 | size: 10.0, 178 | }, 179 | Trade { 180 | timestamp: 1712656815000, 181 | price: 101.0, 182 | size: -10.0, 183 | }, 184 | Trade { 185 | timestamp: 1712656861000, 186 | price: 100.5, 187 | size: -10.0, 188 | }, 189 | Trade { 190 | timestamp: 1712657930000, 191 | price: 102.0, 192 | size: -10.0, 193 | }, 194 | ]; 195 | 196 | let mut aggregator = GenericAggregator::::new( 197 | AlignedTimeRule::new(M1, TimestampResolution::Millisecond), 198 | false, 199 | ); 200 | let candles = aggregate_all_trades(&trades, &mut aggregator); 201 | assert_eq!(candles.len(), 2); 202 | assert_eq!(candles[0].open(), 100.0); 203 | assert_eq!(candles[0].close(), 101.0); 204 | assert_eq!(candles[1].open(), 100.5); 205 | assert_eq!(candles[1].close(), 100.5); 206 | } 207 | } 208 | -------------------------------------------------------------------------------- /src/aggregation_rules/mod.rs: -------------------------------------------------------------------------------- 1 | mod aggregation_rule_trait; 2 | mod aligned_time_rule; 3 | mod relative_price_rule; 4 | mod tick_rule; 5 | mod time_rule; 6 | mod volume_rule; 7 | 8 | pub use aggregation_rule_trait::AggregationRule; 9 | pub use aligned_time_rule::*; 10 | pub use relative_price_rule::RelativePriceRule; 11 | pub use tick_rule::TickRule; 12 | pub use time_rule::*; 13 | pub use volume_rule::VolumeRule; 14 | -------------------------------------------------------------------------------- /src/aggregation_rules/relative_price_rule.rs: -------------------------------------------------------------------------------- 1 | use crate::{AggregationRule, Error, ModularCandle, Result, TakerTrade}; 2 | 3 | /// Creates Candles once the price changed by a give relative absolute price delta 4 | #[derive(Debug, Clone)] 5 | pub struct RelativePriceRule { 6 | init: bool, 7 | init_price: f64, 8 | threshold_fraction: f64, 9 | } 10 | 11 | impl RelativePriceRule { 12 | /// Create a new instance. 13 | /// 14 | /// # Arguments: 15 | /// `threshold_fraction`: The relative distance ((`p_t` - `p_i`) / `p_i`) the price needs to move before a new candle creation is triggered. 16 | /// 17 | pub fn new(threshold_fraction: f64) -> Result { 18 | if threshold_fraction <= 0.0 { 19 | return Err(Error::InvalidParam); 20 | } 21 | Ok(Self { 22 | init: true, 23 | init_price: 0.0, 24 | threshold_fraction, 25 | }) 26 | } 27 | } 28 | 29 | impl AggregationRule for RelativePriceRule 30 | where 31 | C: ModularCandle, 32 | T: TakerTrade, 33 | { 34 | fn should_trigger(&mut self, trade: &T, _candle: &C) -> bool { 35 | if self.init { 36 | self.init = false; 37 | self.init_price = trade.price(); 38 | return false; 39 | } 40 | 41 | let price_delta = (trade.price() - self.init_price).abs() / self.init_price; 42 | 43 | if price_delta >= self.threshold_fraction { 44 | self.init_price = trade.price(); 45 | return true; 46 | } 47 | false 48 | } 49 | } 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use super::*; 54 | use crate::{ 55 | aggregate_all_trades, load_trades_from_csv, 56 | plot::{plot_ohlc_candles, OhlcCandle}, 57 | GenericAggregator, Trade, 58 | }; 59 | 60 | #[test] 61 | fn relative_price_rule() { 62 | let mut rule = RelativePriceRule::new(0.01).unwrap(); 63 | 64 | assert_eq!( 65 | rule.should_trigger( 66 | &Trade { 67 | timestamp: 0, 68 | price: 100.0, 69 | size: 10.0 70 | }, 71 | &OhlcCandle::default() 72 | ), 73 | false 74 | ); 75 | assert_eq!( 76 | rule.should_trigger( 77 | &Trade { 78 | timestamp: 0, 79 | price: 100.5, 80 | size: 10.0 81 | }, 82 | &OhlcCandle::default() 83 | ), 84 | false 85 | ); 86 | assert_eq!( 87 | rule.should_trigger( 88 | &Trade { 89 | timestamp: 0, 90 | price: 101.0, 91 | size: 10.0 92 | }, 93 | &OhlcCandle::default() 94 | ), 95 | true 96 | ); 97 | assert_eq!( 98 | rule.should_trigger( 99 | &Trade { 100 | timestamp: 0, 101 | price: 100.5, 102 | size: 10.0 103 | }, 104 | &OhlcCandle::default() 105 | ), 106 | false 107 | ); 108 | assert_eq!( 109 | rule.should_trigger( 110 | &Trade { 111 | timestamp: 0, 112 | price: 99.0, 113 | size: 10.0 114 | }, 115 | &OhlcCandle::default() 116 | ), 117 | true 118 | ); 119 | } 120 | 121 | #[test] 122 | fn relative_price_rule_real_data() { 123 | let trades = load_trades_from_csv("./data/Bitmex_XBTUSD_1M.csv").expect("Unable to load trades at this path, are you sure you're in the root directory of the project?"); 124 | 125 | // 0.5% candles 126 | const THRESHOLD: f64 = 0.005; 127 | let rule = RelativePriceRule::new(0.01).unwrap(); 128 | let mut aggregator = GenericAggregator::::new(rule, false); 129 | let candles = aggregate_all_trades(&trades, &mut aggregator); 130 | assert!(!candles.is_empty()); 131 | 132 | for c in candles { 133 | assert!((c.high() - c.low()) / c.low() >= THRESHOLD); 134 | assert!((c.close() - c.open()).abs() / c.open() >= THRESHOLD); 135 | } 136 | } 137 | 138 | #[test] 139 | fn relative_price_candles_plot() { 140 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv").unwrap(); 141 | 142 | const THRESHOLD: f64 = 0.005; 143 | let rule = RelativePriceRule::new(THRESHOLD).unwrap(); 144 | let mut aggregator = GenericAggregator::::new(rule, false); 145 | let candles = aggregate_all_trades(&trades, &mut aggregator); 146 | println!("got {} candles", candles.len()); 147 | 148 | plot_ohlc_candles( 149 | &candles, 150 | "img/relative_price_candles_plot.png", 151 | (3840, 2160), 152 | ) 153 | .unwrap(); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/aggregation_rules/tick_rule.rs: -------------------------------------------------------------------------------- 1 | use crate::{AggregationRule, ModularCandle, TakerTrade}; 2 | 3 | /// Creates candles every n ticks 4 | #[derive(Debug, Clone)] 5 | pub struct TickRule { 6 | init: bool, 7 | tick_counter: usize, 8 | n_ticks: usize, 9 | } 10 | 11 | impl TickRule { 12 | /// Create a new instance of the `TickRule` 13 | /// 14 | /// # Arguments: 15 | /// `n_ticks`: create a candle every n ticks 16 | /// 17 | pub fn new(n_ticks: usize) -> Self { 18 | Self { 19 | init: true, 20 | tick_counter: 0, 21 | n_ticks, 22 | } 23 | } 24 | } 25 | 26 | impl AggregationRule for TickRule 27 | where 28 | C: ModularCandle, 29 | T: TakerTrade, 30 | { 31 | fn should_trigger(&mut self, _trade: &T, _candle: &C) -> bool { 32 | if self.init { 33 | self.tick_counter = 0; 34 | self.init = false; 35 | } 36 | 37 | self.tick_counter += 1; 38 | 39 | if self.tick_counter >= self.n_ticks { 40 | self.init = true; 41 | return true; 42 | } 43 | false 44 | } 45 | } 46 | 47 | #[cfg(test)] 48 | mod tests { 49 | use super::*; 50 | use crate::{ 51 | aggregate_all_trades, load_trades_from_csv, plot::OhlcCandle, GenericAggregator, Trade, 52 | }; 53 | 54 | #[test] 55 | fn tick_rule() { 56 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv").unwrap(); 57 | 58 | let mut aggregator = 59 | GenericAggregator::::new(TickRule::new(1000), false); 60 | let candles = aggregate_all_trades(&trades, &mut aggregator); 61 | // As there are 1 million trades in the test data, this will create 1000 candles 62 | assert_eq!(candles.len(), 1000); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/aggregation_rules/time_rule.rs: -------------------------------------------------------------------------------- 1 | use crate::{AggregationRule, ModularCandle, TakerTrade}; 2 | 3 | /// The resolution of the "TakerTrade" timestamps 4 | #[derive(Debug, Clone, Copy)] 5 | pub enum TimestampResolution { 6 | /// The timestamp of the TakerTrade is measured in seconds 7 | Second, 8 | 9 | /// The timestamp of the TakerTrade is measured in milliseconds 10 | Millisecond, 11 | 12 | /// The timestamp of the TakerTrade is measured in microseconds 13 | Microsecond, 14 | 15 | /// The timestamp of the TakerTrade is measured in nanoseconds 16 | Nanosecond, 17 | } 18 | 19 | /// The classic time based aggregation rule, 20 | /// creating a new candle every n seconds 21 | #[derive(Debug, Clone)] 22 | pub struct TimeRule { 23 | /// If true, the reference timestamp needs to be reset 24 | init: bool, 25 | 26 | // The timestamp this rule uses as a reference 27 | reference_timestamp: i64, 28 | 29 | // The period for the candle in seconds 30 | // constants can be used nicely here from constants.rs 31 | // e.g.: M1 -> 1 minute candles 32 | period_s: i64, 33 | } 34 | 35 | impl TimeRule { 36 | /// Create a new instance of the time rule, 37 | /// with a given candle period in seconds 38 | /// 39 | /// # Arguments: 40 | /// period_s: How many seconds a candle will contain 41 | /// ts_res: The resolution each Trade timestamp will have 42 | /// 43 | pub fn new(period_s: i64, ts_res: TimestampResolution) -> Self { 44 | let ts_multiplier = match ts_res { 45 | TimestampResolution::Second => 1, 46 | TimestampResolution::Millisecond => 1_000, 47 | TimestampResolution::Microsecond => 1_000_000, 48 | TimestampResolution::Nanosecond => 1_000_000_000, 49 | }; 50 | 51 | Self { 52 | init: true, 53 | reference_timestamp: 0, 54 | period_s: period_s * ts_multiplier, 55 | } 56 | } 57 | } 58 | 59 | impl AggregationRule for TimeRule 60 | where 61 | C: ModularCandle, 62 | T: TakerTrade, 63 | { 64 | fn should_trigger(&mut self, trade: &T, _candle: &C) -> bool { 65 | if self.init { 66 | self.reference_timestamp = trade.timestamp(); 67 | self.init = false; 68 | } 69 | let should_trigger = trade.timestamp() - self.reference_timestamp > self.period_s; 70 | if should_trigger { 71 | self.init = true; 72 | } 73 | 74 | should_trigger 75 | } 76 | } 77 | 78 | #[cfg(test)] 79 | mod tests { 80 | use super::*; 81 | use crate::{ 82 | aggregate_all_trades, load_trades_from_csv, 83 | plot::{plot_ohlc_candles, OhlcCandle}, 84 | GenericAggregator, Trade, H1, M15, M5, 85 | }; 86 | 87 | #[test] 88 | fn time_candles_plot() { 89 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv").unwrap(); 90 | 91 | let mut aggregator = GenericAggregator::::new( 92 | TimeRule::new(M15, TimestampResolution::Millisecond), 93 | false, 94 | ); 95 | let candles = aggregate_all_trades(&trades, &mut aggregator); 96 | println!("got {} candles", candles.len()); 97 | 98 | plot_ohlc_candles(&candles, "img/time_candles_plot.png", (2560, 1440)).unwrap(); 99 | } 100 | 101 | #[test] 102 | fn time_rule_differing_periods() { 103 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv").unwrap(); 104 | 105 | let mut aggregator = GenericAggregator::::new( 106 | TimeRule::new(M15, TimestampResolution::Millisecond), 107 | false, 108 | ); 109 | let candles = aggregate_all_trades(&trades, &mut aggregator); 110 | assert_eq!(candles.len(), 395); 111 | 112 | let mut aggregator = GenericAggregator::::new( 113 | TimeRule::new(M5, TimestampResolution::Millisecond), 114 | false, 115 | ); 116 | let candles = aggregate_all_trades(&trades, &mut aggregator); 117 | assert_eq!(candles.len(), 1180); 118 | 119 | let mut aggregator = GenericAggregator::::new( 120 | TimeRule::new(H1, TimestampResolution::Millisecond), 121 | false, 122 | ); 123 | let candles = aggregate_all_trades(&trades, &mut aggregator); 124 | assert_eq!(candles.len(), 99); 125 | } 126 | 127 | #[test] 128 | fn time_rule_differing_timestamp_resolutions() { 129 | // We know the XBTUSD series from Bitmex has millisecond timestamp resolution 130 | let trades_ms = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv").unwrap(); 131 | 132 | // we can therefore transform them into seconds, microseconds and nanoseconds respectively 133 | let trades_s: Vec = trades_ms 134 | .iter() 135 | .map(|v| Trade { 136 | timestamp: v.timestamp / 1000, 137 | price: v.price, 138 | size: v.size, 139 | }) 140 | .collect(); 141 | let trades_micros: Vec = trades_ms 142 | .iter() 143 | .map(|v| Trade { 144 | timestamp: v.timestamp * 1000, 145 | price: v.price, 146 | size: v.size, 147 | }) 148 | .collect(); 149 | let trades_ns: Vec = trades_ms 150 | .iter() 151 | .map(|v| Trade { 152 | timestamp: v.timestamp * 1_000_000, 153 | price: v.price, 154 | size: v.size, 155 | }) 156 | .collect(); 157 | 158 | // And make sure they produce the same number of candles regardless of timestamp resolution 159 | let mut aggregator = GenericAggregator::::new( 160 | TimeRule::new(M15, TimestampResolution::Second), 161 | false, 162 | ); 163 | let candles = aggregate_all_trades(&trades_s, &mut aggregator); 164 | assert_eq!(candles.len(), 395); 165 | 166 | let mut aggregator = GenericAggregator::::new( 167 | TimeRule::new(M15, TimestampResolution::Millisecond), 168 | false, 169 | ); 170 | let candles = aggregate_all_trades(&trades_ms, &mut aggregator); 171 | assert_eq!(candles.len(), 395); 172 | 173 | let mut aggregator = GenericAggregator::::new( 174 | TimeRule::new(M15, TimestampResolution::Microsecond), 175 | false, 176 | ); 177 | let candles = aggregate_all_trades(&trades_micros, &mut aggregator); 178 | assert_eq!(candles.len(), 395); 179 | 180 | let mut aggregator = GenericAggregator::::new( 181 | TimeRule::new(M15, TimestampResolution::Nanosecond), 182 | false, 183 | ); 184 | let candles = aggregate_all_trades(&trades_ns, &mut aggregator); 185 | assert_eq!(candles.len(), 395); 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /src/aggregation_rules/volume_rule.rs: -------------------------------------------------------------------------------- 1 | use crate::{AggregationRule, By, Error, ModularCandle, Result, TakerTrade}; 2 | 3 | /// Creates candles every n units of volume traded. 4 | /// If the last trade needed to complete a bucket is for a size greater than required, 5 | /// the excess size is given to the next bucket 6 | #[derive(Debug, Clone)] 7 | pub struct VolumeRule { 8 | /// See docs on By enum for details 9 | by: By, 10 | 11 | /// cumulative volume 12 | cum_vol: f64, 13 | 14 | /// The theshold volume the candle needs to have before finishing it 15 | threshold_vol: f64, 16 | } 17 | 18 | impl VolumeRule { 19 | /// Create a new instance with the given volume threshold 20 | pub fn new(threshold_vol: f64, by: By) -> Result { 21 | if threshold_vol <= 0.0 { 22 | return Err(Error::InvalidParam); 23 | } 24 | Ok(Self { 25 | by, 26 | cum_vol: 0.0, 27 | threshold_vol, 28 | }) 29 | } 30 | } 31 | 32 | impl AggregationRule for VolumeRule 33 | where 34 | C: ModularCandle, 35 | T: TakerTrade, 36 | { 37 | fn should_trigger(&mut self, trade: &T, _candle: &C) -> bool { 38 | if self.cum_vol >= self.threshold_vol { 39 | // If the last trade needed to complete a bucket is for a size greater than required, 40 | // the excess size is given to the next bucket 41 | self.cum_vol = self.cum_vol - self.threshold_vol; 42 | debug_assert!(self.cum_vol >= 0.0); 43 | } 44 | self.cum_vol += match self.by { 45 | By::Quote => trade.size().abs(), 46 | By::Base => trade.size().abs() / trade.price(), 47 | }; 48 | 49 | self.cum_vol >= self.threshold_vol 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/aggregator.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use crate::{AggregationRule, ModularCandle, TakerTrade}; 4 | 5 | /// Defines the needed methods for any online `Aggregator` 6 | pub trait Aggregator { 7 | /// Updates the aggregation state with a new trade 8 | /// 9 | /// # Arguments: 10 | /// trade: the trade information to add to the aggregation process 11 | /// 12 | /// # Returns: 13 | /// Some output only when a new candle has been created, 14 | /// otherwise it returns None 15 | fn update(&mut self, trade: &T) -> Option; 16 | 17 | /// Get a reference to an unfinished `Candle`. 18 | /// Accessing a `Candle` using this method does not guarantee that the `AggregationRule` is respected. 19 | /// It is generally advised to call `update` instead and use the resulting `Candle` if its `Some`. 20 | fn unfinished_candle(&self) -> &Candle; 21 | } 22 | 23 | /// An `Aggregator` that is generic over 24 | /// the type of Candle being produced, 25 | /// as well as by which rule the candle is created 26 | #[derive(Debug, Clone)] 27 | pub struct GenericAggregator { 28 | candle: C, 29 | aggregation_rule: R, 30 | // During some aggregations, the desired behaviour is that the trade that crosses the trigger boundary 31 | // is included in both the current and next candle. 32 | // Examples uses include ensuring the close and open price of the current and next candle are equal. 33 | // If that's desired, set the field to true during construction of `Self`. 34 | include_trade_that_triggered_rule: bool, 35 | _trade_type: PhantomData, 36 | } 37 | 38 | impl GenericAggregator 39 | where 40 | C: ModularCandle, 41 | R: AggregationRule, 42 | T: TakerTrade, 43 | { 44 | /// Create a new instance with a concrete aggregation rule 45 | /// and an empty candle. 46 | /// 47 | /// # Arguments: 48 | /// `aggregation_rule`: The rule that dictates when to trigger the creation of a new candle. 49 | /// `include_trade_that_triggered_rule`: If true, the trade that triggered a rule is included in the current candle 50 | /// as well as the next one. 51 | /// During some aggregations, the desired behaviour is that the trade that crosses the trigger boundary 52 | /// is included in both the current and next candle. 53 | /// Examples uses include ensuring the close and open price of the current and next candle are equal. 54 | /// If that's desired, set the field to true during construction of `Self`. 55 | /// E.g on Tradingview the time aggregation would have this set to `false`, which may create gaps between close and open of subsequent candles. 56 | pub fn new(aggregation_rule: R, include_trade_that_triggered_rule: bool) -> Self { 57 | Self { 58 | candle: Default::default(), 59 | aggregation_rule, 60 | include_trade_that_triggered_rule, 61 | _trade_type: PhantomData, 62 | } 63 | } 64 | } 65 | 66 | impl Aggregator for GenericAggregator 67 | where 68 | C: ModularCandle, 69 | R: AggregationRule, 70 | T: TakerTrade, 71 | { 72 | fn update(&mut self, trade: &T) -> Option { 73 | if self.aggregation_rule.should_trigger(trade, &self.candle) { 74 | // During some aggregations, the desired behaviour is that the trade that crosses the trigger boundary 75 | // is included in both the current and next candle. 76 | // Examples uses include ensuring the close and open price of the current and next candle are equal. 77 | // If that's desired, set the field to true during construction of `Self`. 78 | if self.include_trade_that_triggered_rule { 79 | self.candle.update(trade); 80 | } 81 | let candle = self.candle.clone(); 82 | 83 | // Create a new candle. 84 | self.candle.reset(); 85 | self.candle.update(trade); 86 | 87 | return Some(candle); 88 | } 89 | 90 | self.candle.update(trade); 91 | 92 | None 93 | } 94 | 95 | fn unfinished_candle(&self) -> &C { 96 | &self.candle 97 | } 98 | } 99 | 100 | #[cfg(test)] 101 | mod tests { 102 | use trade_aggregation_derive::Candle; 103 | 104 | use super::*; 105 | use crate::{ 106 | candle_components::{CandleComponent, CandleComponentUpdate, Close, NumTrades, Open}, 107 | load_trades_from_csv, ModularCandle, TimeRule, TimestampResolution, Trade, M1, 108 | }; 109 | 110 | #[derive(Default, Debug, Clone, Candle)] 111 | struct MyCandle { 112 | open: Open, 113 | close: Close, 114 | num_trades: NumTrades, 115 | } 116 | 117 | #[test] 118 | fn generic_aggregator() { 119 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv") 120 | .expect("Could not load trades from file!"); 121 | 122 | let rule = TimeRule::new(M1, TimestampResolution::Millisecond); 123 | let mut a = GenericAggregator::::new(rule, false); 124 | 125 | let mut candle_counter: usize = 0; 126 | for t in trades.iter() { 127 | if let Some(_candle) = a.update(t) { 128 | // println!( 129 | // "got candle: {:?} at {:?}, {:?}", 130 | // candle, t.timestamp, t.price 131 | // ); 132 | 133 | candle_counter += 1; 134 | } 135 | } 136 | assert_eq!(candle_counter, 5704); 137 | } 138 | 139 | #[test] 140 | fn candle_macro() { 141 | let my_candle = MyCandle::default(); 142 | println!("my_candle: {:?}", my_candle); 143 | 144 | // make sure the 'open' and 'close' getters have been generated 145 | println!("open: {}", my_candle.open()); 146 | println!("close: {}", my_candle.close()); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/candle_components/average_price.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the arithmetic mean price 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct AveragePrice { 7 | num_trades: f64, 8 | price_sum: f64, 9 | } 10 | 11 | impl CandleComponent for AveragePrice { 12 | #[inline(always)] 13 | fn value(&self) -> f64 { 14 | self.price_sum / self.num_trades 15 | } 16 | 17 | #[inline(always)] 18 | fn reset(&mut self) { 19 | self.num_trades = 0.0; 20 | self.price_sum = 0.0; 21 | } 22 | } 23 | 24 | impl CandleComponentUpdate for AveragePrice { 25 | #[inline(always)] 26 | fn update(&mut self, trade: &T) { 27 | self.num_trades += 1.0; 28 | self.price_sum += trade.price(); 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn average_price() { 38 | let mut m = AveragePrice::default(); 39 | for t in &crate::candle_components::tests::TRADES { 40 | m.update(t); 41 | } 42 | assert_eq!(m.value(), 102.0); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/candle_components/candle_component_trait.rs: -------------------------------------------------------------------------------- 1 | use crate::TakerTrade; 2 | 3 | /// Each component of a Candle must fullfill this trait 4 | pub trait CandleComponent { 5 | /// An associated type which is the output type of the value() method 6 | /// The current value of the component 7 | fn value(&self) -> T; 8 | 9 | /// Resets the component state to its default 10 | fn reset(&mut self); 11 | } 12 | 13 | /// Each component of a Candle must fullfill this trait 14 | pub trait CandleComponentUpdate { 15 | /// Updates the state with newest trade information 16 | fn update(&mut self, trade: &T); 17 | } 18 | -------------------------------------------------------------------------------- /src/candle_components/close.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the close price 4 | #[derive(Default, Debug, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct Close { 7 | value: f64, 8 | } 9 | 10 | impl CandleComponent for Close { 11 | #[inline(always)] 12 | fn value(&self) -> f64 { 13 | self.value 14 | } 15 | 16 | #[inline(always)] 17 | fn reset(&mut self) {} 18 | } 19 | 20 | impl CandleComponentUpdate for Close { 21 | #[inline(always)] 22 | fn update(&mut self, trade: &T) { 23 | self.value = trade.price() 24 | } 25 | } 26 | 27 | #[cfg(test)] 28 | mod tests { 29 | use super::*; 30 | 31 | #[test] 32 | fn close() { 33 | let mut m = Close::default(); 34 | for t in &crate::candle_components::tests::TRADES { 35 | m.update(t); 36 | assert_eq!(m.value(), t.price); 37 | } 38 | assert_eq!(m.value(), crate::candle_components::tests::TRADES[9].price); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/candle_components/close_timestamp.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the closing timestamp of a Candle, using the 4 | /// same unit resolution as the underlying input of [`TakerTrade.timestamp()`]. 5 | #[derive(Debug, Clone)] 6 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 7 | pub struct CloseTimeStamp { 8 | value: T, 9 | } 10 | 11 | impl Default for CloseTimeStamp { 12 | fn default() -> Self { 13 | Self { 14 | value: Default::default(), 15 | } 16 | } 17 | } 18 | 19 | impl CandleComponent for CloseTimeStamp { 20 | #[inline(always)] 21 | fn value(&self) -> i64 { 22 | self.value 23 | } 24 | 25 | #[inline(always)] 26 | fn reset(&mut self) {} 27 | } 28 | 29 | impl CandleComponentUpdate for CloseTimeStamp { 30 | #[inline(always)] 31 | fn update(&mut self, trade: &T) { 32 | self.value = trade.timestamp(); 33 | } 34 | } 35 | 36 | #[cfg(test)] 37 | mod tests { 38 | use super::*; 39 | 40 | #[test] 41 | fn close_timestamp() { 42 | let mut m = CloseTimeStamp::default(); 43 | for t in &crate::candle_components::tests::TRADES { 44 | m.update(t); 45 | } 46 | assert_eq!(m.value(), 1684677290_000); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/candle_components/directional_trade_ratio.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the ratio of buys vs total trades 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct DirectionalTradeRatio { 7 | num_buys: usize, 8 | num_trades: usize, 9 | } 10 | 11 | impl CandleComponent for DirectionalTradeRatio { 12 | #[inline(always)] 13 | fn value(&self) -> f64 { 14 | self.num_buys as f64 / self.num_trades as f64 15 | } 16 | 17 | #[inline(always)] 18 | fn reset(&mut self) { 19 | self.num_buys = 0; 20 | self.num_trades = 0; 21 | } 22 | } 23 | 24 | impl CandleComponentUpdate for DirectionalTradeRatio { 25 | #[inline(always)] 26 | fn update(&mut self, trade: &T) { 27 | self.num_trades += 1; 28 | if trade.size() > 0.0 { 29 | self.num_buys += 1; 30 | } 31 | } 32 | } 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use super::*; 37 | 38 | #[test] 39 | fn trade_direction_ratio() { 40 | let mut m = DirectionalTradeRatio::default(); 41 | for t in &crate::candle_components::tests::TRADES { 42 | m.update(t); 43 | } 44 | assert_eq!(m.value(), 0.7); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/candle_components/directional_volume_ratio.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the ratio of buy volume vs total volume 4 | #[derive(Clone, Debug, Default)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct DirectionalVolumeRatio { 7 | volume: f64, 8 | buy_volume: f64, 9 | } 10 | 11 | impl CandleComponent for DirectionalVolumeRatio { 12 | #[inline(always)] 13 | fn value(&self) -> f64 { 14 | self.buy_volume / self.volume 15 | } 16 | 17 | #[inline(always)] 18 | fn reset(&mut self) { 19 | self.volume = 0.0; 20 | self.buy_volume = 0.0; 21 | } 22 | } 23 | 24 | impl CandleComponentUpdate for DirectionalVolumeRatio { 25 | #[inline(always)] 26 | fn update(&mut self, trade: &T) { 27 | self.volume += trade.size().abs(); 28 | if trade.size() > 0.0 { 29 | self.buy_volume += trade.size(); 30 | } 31 | } 32 | } 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use round::round; 37 | 38 | use super::*; 39 | 40 | #[test] 41 | fn volume_direction_ratio() { 42 | let mut m = DirectionalVolumeRatio::default(); 43 | for t in &crate::candle_components::tests::TRADES { 44 | m.update(t); 45 | } 46 | assert_eq!(round(m.value(), 4), 0.7143); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/candle_components/entropy.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// A `CandleComponent` that computes the binary entropy of whether a trade is a buy or a sell. 4 | #[derive(Default, Debug, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct Entropy { 7 | buys: usize, 8 | total_observed_trades: usize, 9 | } 10 | 11 | impl CandleComponent for Entropy { 12 | fn value(&self) -> f64 { 13 | let pt = self.buys as f64 / self.total_observed_trades as f64; 14 | let pn = 1_f64 - pt; 15 | 16 | let mut h = pt * pt.log2() + pn * pn.log2(); 17 | if h.is_nan() { 18 | h = 0.0; 19 | } 20 | 21 | -h 22 | } 23 | 24 | fn reset(&mut self) { 25 | self.buys = 0; 26 | self.total_observed_trades = 0; 27 | } 28 | } 29 | 30 | impl CandleComponentUpdate for Entropy { 31 | fn update(&mut self, trade: &T) { 32 | if trade.size() > 0.0 { 33 | self.buys += 1 34 | } 35 | self.total_observed_trades += 1; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/candle_components/high.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the high price 4 | #[derive(Default, Debug, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct High { 7 | high: f64, 8 | } 9 | 10 | impl CandleComponent for High { 11 | #[inline(always)] 12 | fn value(&self) -> f64 { 13 | self.high 14 | } 15 | 16 | #[inline(always)] 17 | fn reset(&mut self) { 18 | self.high = std::f64::MIN; 19 | } 20 | } 21 | 22 | impl CandleComponentUpdate for High { 23 | #[inline(always)] 24 | fn update(&mut self, trade: &T) { 25 | if trade.price() > self.high { 26 | self.high = trade.price(); 27 | } 28 | } 29 | } 30 | 31 | #[cfg(test)] 32 | mod tests { 33 | use super::*; 34 | 35 | #[test] 36 | fn high() { 37 | let mut m = High::default(); 38 | for t in &crate::candle_components::tests::TRADES { 39 | m.update(t); 40 | } 41 | assert_eq!(m.value(), 105.0); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/candle_components/low.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the low price 4 | #[derive(Debug, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct Low { 7 | low: f64, 8 | } 9 | 10 | impl Default for Low { 11 | fn default() -> Self { 12 | // ensure the initial value is maximal, 13 | // so any subsequent calls to 'update' will set the proper low value 14 | Self { low: f64::MAX } 15 | } 16 | } 17 | 18 | impl CandleComponent for Low { 19 | #[inline(always)] 20 | fn value(&self) -> f64 { 21 | self.low 22 | } 23 | 24 | #[inline(always)] 25 | fn reset(&mut self) { 26 | self.low = f64::MAX; 27 | } 28 | } 29 | 30 | impl CandleComponentUpdate for Low { 31 | #[inline(always)] 32 | fn update(&mut self, trade: &T) { 33 | if trade.price() < self.low { 34 | self.low = trade.price(); 35 | } 36 | } 37 | } 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | use super::*; 42 | 43 | #[test] 44 | fn low() { 45 | let mut m = Low::default(); 46 | for t in &crate::candle_components::tests::TRADES { 47 | m.update(t); 48 | } 49 | assert_eq!(m.value(), 100.0); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/candle_components/median_price.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// Computes the median price from a sorted list of trade prices 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct MedianPrice { 7 | prices: Vec, 8 | } 9 | 10 | impl CandleComponent for MedianPrice { 11 | #[inline(always)] 12 | fn value(&self) -> f64 { 13 | let mut prices = self.prices.clone(); 14 | prices.sort_by(|a, b| a.partial_cmp(b).unwrap()); 15 | 16 | prices[prices.len() / 2] 17 | } 18 | 19 | #[inline(always)] 20 | fn reset(&mut self) { 21 | self.prices.clear(); 22 | } 23 | } 24 | 25 | impl CandleComponentUpdate for MedianPrice { 26 | #[inline(always)] 27 | fn update(&mut self, trade: &T) { 28 | self.prices.push(trade.price()); 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use super::*; 35 | 36 | #[test] 37 | fn median_price() { 38 | let mut m = MedianPrice::default(); 39 | for t in &crate::candle_components::tests::TRADES { 40 | m.update(t); 41 | } 42 | assert_eq!(m.value(), 102.0); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/candle_components/mod.rs: -------------------------------------------------------------------------------- 1 | //! This module contains a bunch of ready to use 'CandleComponents' 2 | //! that can easily be combined to create a 'ModularCandle' using the 'Candle' macro. 3 | 4 | mod average_price; 5 | mod candle_component_trait; 6 | mod close; 7 | mod close_timestamp; 8 | mod directional_trade_ratio; 9 | mod directional_volume_ratio; 10 | mod entropy; 11 | mod high; 12 | mod low; 13 | mod median_price; 14 | mod num_trades; 15 | mod open; 16 | #[cfg(feature = "chrono")] 17 | mod open_datetime; 18 | mod open_timestamp; 19 | mod std_dev_prices; 20 | mod std_dev_sizes; 21 | mod time_velocity; 22 | mod trades; 23 | mod volume; 24 | mod volume_buys; 25 | mod volume_sells; 26 | mod vpin; 27 | mod weighted_price; 28 | 29 | pub use average_price::AveragePrice; 30 | pub use candle_component_trait::{CandleComponent, CandleComponentUpdate}; 31 | pub use close::Close; 32 | pub use close_timestamp::CloseTimeStamp; 33 | pub use directional_trade_ratio::DirectionalTradeRatio; 34 | pub use directional_volume_ratio::DirectionalVolumeRatio; 35 | pub use entropy::Entropy; 36 | pub use high::High; 37 | pub use low::Low; 38 | pub use median_price::MedianPrice; 39 | pub use num_trades::NumTrades; 40 | pub use open::Open; 41 | #[cfg(feature = "chrono")] 42 | pub use open_datetime::OpenDateTime; 43 | pub use open_timestamp::OpenTimeStamp; 44 | pub use std_dev_prices::StdDevPrices; 45 | pub use std_dev_sizes::StdDevSizes; 46 | pub use time_velocity::TimeVelocity; 47 | pub use trades::Trades; 48 | pub use volume::Volume; 49 | pub use volume_buys::VolumeBuys; 50 | pub use volume_sells::VolumeSells; 51 | pub use vpin::Vpin; 52 | pub use weighted_price::WeightedPrice; 53 | 54 | #[cfg(test)] 55 | mod tests { 56 | use crate::Trade; 57 | 58 | pub const TRADES: [Trade; 10] = [ 59 | Trade { 60 | timestamp: 1684677200_000, 61 | price: 100.0, 62 | size: 10.0, 63 | }, 64 | Trade { 65 | timestamp: 1684677210_000, 66 | price: 101.0, 67 | size: -10.0, 68 | }, 69 | Trade { 70 | timestamp: 1684677220_000, 71 | price: 100.0, 72 | size: 20.0, 73 | }, 74 | Trade { 75 | timestamp: 1684677230_000, 76 | price: 102.0, 77 | size: 10.0, 78 | }, 79 | Trade { 80 | timestamp: 1684677240_000, 81 | price: 103.0, 82 | size: 10.0, 83 | }, 84 | Trade { 85 | timestamp: 1684677250_000, 86 | price: 104.0, 87 | size: -20.0, 88 | }, 89 | Trade { 90 | timestamp: 1684677260_000, 91 | price: 102.0, 92 | size: -10.0, 93 | }, 94 | Trade { 95 | timestamp: 1684677270_000, 96 | price: 101.0, 97 | size: 10.0, 98 | }, 99 | Trade { 100 | timestamp: 1684677280_000, 101 | price: 102.0, 102 | size: 30.0, 103 | }, 104 | Trade { 105 | timestamp: 1684677290_000, 106 | price: 105.0, 107 | size: 10.0, 108 | }, 109 | ]; 110 | } 111 | -------------------------------------------------------------------------------- /src/candle_components/num_trades.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the number of trades 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct NumTrades { 7 | value: T, 8 | } 9 | 10 | impl CandleComponent for NumTrades { 11 | #[inline(always)] 12 | fn value(&self) -> u32 { 13 | self.value 14 | } 15 | 16 | #[inline(always)] 17 | fn reset(&mut self) { 18 | self.value = 0; 19 | } 20 | } 21 | impl CandleComponentUpdate for NumTrades { 22 | #[inline(always)] 23 | fn update(&mut self, _: &T) { 24 | self.value += 1; 25 | } 26 | } 27 | 28 | #[cfg(test)] 29 | mod tests { 30 | use super::*; 31 | 32 | #[test] 33 | fn num_trades() { 34 | let mut m = NumTrades::default(); 35 | for t in &crate::candle_components::tests::TRADES { 36 | m.update(t); 37 | } 38 | assert_eq!(m.value(), 10); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/candle_components/open.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the opening price of a Candle 4 | #[derive(Debug, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct Open { 7 | init: bool, 8 | value: f64, 9 | } 10 | 11 | impl Default for Open { 12 | fn default() -> Self { 13 | Self { 14 | init: true, 15 | value: 0.0, 16 | } 17 | } 18 | } 19 | 20 | impl CandleComponent for Open { 21 | /// Returns the open price of the candle 22 | #[inline(always)] 23 | fn value(&self) -> f64 { 24 | self.value 25 | } 26 | /// This makes sure the next time "update" is called, the new open value is set 27 | #[inline(always)] 28 | fn reset(&mut self) { 29 | self.init = true; 30 | } 31 | } 32 | 33 | impl CandleComponentUpdate for Open { 34 | /// Only update the open price if this module is in init mode 35 | #[inline(always)] 36 | fn update(&mut self, trade: &T) { 37 | if self.init { 38 | self.value = trade.price(); 39 | self.init = false; 40 | } 41 | } 42 | } 43 | 44 | #[cfg(test)] 45 | mod tests { 46 | use super::*; 47 | 48 | #[test] 49 | fn open() { 50 | let mut m = Open::default(); 51 | let first_trade = &crate::candle_components::tests::TRADES[0]; 52 | for t in &crate::candle_components::tests::TRADES { 53 | m.update(t); 54 | assert_eq!(m.value(), first_trade.price()); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/candle_components/open_datetime.rs: -------------------------------------------------------------------------------- 1 | use chrono::{DateTime, TimeZone, Utc}; 2 | 3 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade, TimestampResolution}; 4 | 5 | /// This 'CandleComponent' keeps track of the opening [`DateTime`] of a Candle. 6 | #[derive(Debug, Clone)] 7 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 8 | pub struct OpenDateTime { 9 | init: bool, 10 | value: DateTime, 11 | } 12 | 13 | impl Default for OpenDateTime { 14 | fn default() -> Self { 15 | Self { 16 | init: true, 17 | value: Default::default(), 18 | } 19 | } 20 | } 21 | 22 | impl CandleComponent> for OpenDateTime { 23 | /// Returns the open price of the candle 24 | #[inline(always)] 25 | fn value(&self) -> DateTime { 26 | self.value 27 | } 28 | /// This makes sure the next time "update" is called, the new open value is set 29 | #[inline(always)] 30 | fn reset(&mut self) { 31 | self.init = true; 32 | } 33 | } 34 | 35 | impl CandleComponentUpdate for OpenDateTime { 36 | /// Only update the open price if this module is in init mode 37 | #[inline(always)] 38 | fn update(&mut self, trade: &T) { 39 | if self.init { 40 | let stamp = trade.timestamp(); 41 | self.value = match trade.timestamp_resolution() { 42 | TimestampResolution::Second => Utc.timestamp(stamp, 0), 43 | TimestampResolution::Millisecond => Utc.timestamp_millis(trade.timestamp()), 44 | TimestampResolution::Microsecond => Utc.timestamp_nanos(stamp * 1000), 45 | TimestampResolution::Nanosecond => Utc.timestamp_nanos(stamp), 46 | }; 47 | self.init = false; 48 | } 49 | } 50 | } 51 | 52 | #[cfg(test)] 53 | mod tests { 54 | use super::*; 55 | 56 | #[test] 57 | fn open_datetime() { 58 | let mut m = OpenDateTime::default(); 59 | for t in &crate::candle_components::tests::TRADES { 60 | m.update(t); 61 | } 62 | assert_eq!(m.value(), Utc.ymd(1985, 11, 5).and_hms(0, 53, 20)); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/candle_components/open_timestamp.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the opening timestamp of a Candle, using the 4 | /// same unit resolution as the underlying input of [`TakerTrade.timestamp()`]. 5 | #[derive(Debug, Clone)] 6 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 7 | pub struct OpenTimeStamp { 8 | init: bool, 9 | value: T, 10 | } 11 | 12 | impl Default for OpenTimeStamp { 13 | fn default() -> Self { 14 | Self { 15 | init: true, 16 | value: Default::default(), 17 | } 18 | } 19 | } 20 | 21 | impl CandleComponent for OpenTimeStamp { 22 | #[inline(always)] 23 | fn value(&self) -> i64 { 24 | self.value 25 | } 26 | 27 | #[inline(always)] 28 | fn reset(&mut self) { 29 | self.init = true; 30 | } 31 | } 32 | 33 | impl CandleComponentUpdate for OpenTimeStamp { 34 | #[inline(always)] 35 | fn update(&mut self, trade: &T) { 36 | if self.init { 37 | self.value = trade.timestamp(); 38 | self.init = false; 39 | } 40 | } 41 | } 42 | 43 | #[cfg(test)] 44 | mod tests { 45 | use super::*; 46 | 47 | #[test] 48 | fn open_timestamp() { 49 | let mut m = OpenTimeStamp::default(); 50 | for t in &crate::candle_components::tests::TRADES { 51 | m.update(t); 52 | } 53 | assert_eq!(m.value(), 1684677200000); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/candle_components/std_dev_prices.rs: -------------------------------------------------------------------------------- 1 | use crate::{welford_online::WelfordOnline, CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the standard deviation in trade prices 4 | #[derive(Debug, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct StdDevPrices { 7 | welford: WelfordOnline, 8 | } 9 | 10 | impl Default for StdDevPrices { 11 | fn default() -> Self { 12 | Self { 13 | welford: WelfordOnline::new(), 14 | } 15 | } 16 | } 17 | 18 | impl CandleComponent for StdDevPrices { 19 | #[inline(always)] 20 | fn value(&self) -> f64 { 21 | self.welford.std_dev() 22 | } 23 | 24 | #[inline(always)] 25 | fn reset(&mut self) { 26 | self.welford.reset(); 27 | } 28 | } 29 | 30 | impl CandleComponentUpdate for StdDevPrices { 31 | #[inline(always)] 32 | fn update(&mut self, trade: &T) { 33 | self.welford.add(trade.price()); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/candle_components/std_dev_sizes.rs: -------------------------------------------------------------------------------- 1 | use crate::{welford_online::WelfordOnline, CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the standard deviation in the trade sizes 4 | #[derive(Debug, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct StdDevSizes { 7 | welford: WelfordOnline, 8 | } 9 | 10 | impl Default for StdDevSizes { 11 | fn default() -> Self { 12 | Self { 13 | welford: WelfordOnline::new(), 14 | } 15 | } 16 | } 17 | impl CandleComponent for StdDevSizes { 18 | #[inline(always)] 19 | fn value(&self) -> f64 { 20 | self.welford.std_dev() 21 | } 22 | 23 | #[inline(always)] 24 | fn reset(&mut self) { 25 | self.welford.reset(); 26 | } 27 | } 28 | 29 | impl CandleComponentUpdate for StdDevSizes { 30 | #[inline(always)] 31 | fn update(&mut self, trade: &T) { 32 | self.welford.add(trade.size()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/candle_components/time_velocity.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade, TimestampResolution}; 2 | 3 | /// Measures the velocity of candle creation based on the formula: 4 | /// 1.0 / t , where t is measured in seconds 5 | /// The higher the velocity the faster the candle has been created 6 | #[derive(Debug, Clone)] 7 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 8 | pub struct TimeVelocity { 9 | init: bool, 10 | // unix time (in seconds) 11 | init_time: i64, 12 | last_time: i64, 13 | } 14 | 15 | impl Default for TimeVelocity { 16 | fn default() -> Self { 17 | Self { 18 | init: true, 19 | init_time: 0, 20 | last_time: 0, 21 | } 22 | } 23 | } 24 | 25 | impl CandleComponent for TimeVelocity { 26 | #[inline(always)] 27 | fn value(&self) -> f64 { 28 | let mut elapsed_s: f64 = (self.last_time - self.init_time) as f64; 29 | if elapsed_s < 1.0 { 30 | // cap elapsed_s to avoid time_velocity being infinite 31 | elapsed_s = 1.0; 32 | } 33 | 1.0 / elapsed_s 34 | } 35 | 36 | #[inline(always)] 37 | fn reset(&mut self) { 38 | self.init = true 39 | } 40 | } 41 | 42 | impl CandleComponentUpdate for TimeVelocity { 43 | #[inline(always)] 44 | fn update(&mut self, trade: &T) { 45 | let div = match trade.timestamp_resolution() { 46 | TimestampResolution::Second => 1, 47 | TimestampResolution::Millisecond => 1_000, 48 | TimestampResolution::Microsecond => 1_000_000, 49 | TimestampResolution::Nanosecond => 1_000_000_000, 50 | }; 51 | if self.init { 52 | self.init_time = trade.timestamp() / div; 53 | self.init = false; 54 | } 55 | self.last_time = trade.timestamp() / div; 56 | } 57 | } 58 | 59 | #[cfg(test)] 60 | mod tests { 61 | use super::*; 62 | use crate::candle_components::tests::TRADES; 63 | 64 | #[test] 65 | fn time_velocity() { 66 | let mut comp = TimeVelocity::default(); 67 | for t in TRADES.iter() { 68 | comp.update(t); 69 | } 70 | assert_eq!(round::round(comp.value(), 3), 0.011); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/candle_components/trades.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// A `CandleComponent` that gathers all observed trades and returns them. 4 | /// Be careful, the `value` method clones the inner vector, 5 | /// due to the trait definition and lifetime restrictions. 6 | /// So call sparingly. 7 | #[derive(Debug, Clone, Default)] 8 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 9 | pub struct Trades 10 | where 11 | T: TakerTrade, 12 | { 13 | trades: Vec, 14 | } 15 | 16 | impl CandleComponent> for Trades 17 | where 18 | T: TakerTrade + Clone, 19 | { 20 | #[inline(always)] 21 | fn value(&self) -> Vec { 22 | // NOTE: due to the trait definition and borrowing lifetimes, 23 | // the return type cannot be a reference, 24 | // Would be better if we borrow here. 25 | self.trades.clone() 26 | } 27 | 28 | #[inline(always)] 29 | fn reset(&mut self) { 30 | self.trades.clear(); 31 | } 32 | } 33 | 34 | impl CandleComponentUpdate for Trades 35 | where 36 | T: TakerTrade + Clone, 37 | { 38 | #[inline(always)] 39 | fn update(&mut self, trade: &T) { 40 | self.trades.push(trade.clone()); 41 | } 42 | } 43 | 44 | #[cfg(test)] 45 | mod test { 46 | use super::*; 47 | 48 | #[test] 49 | fn trades() { 50 | let mut comp = Trades::default(); 51 | for t in &crate::candle_components::tests::TRADES { 52 | comp.update(t); 53 | } 54 | assert_eq!(comp.value(), crate::candle_components::tests::TRADES); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/candle_components/volume.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the cumulative volume of trades. 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct Volume { 7 | volume: f64, 8 | } 9 | 10 | impl CandleComponent for Volume { 11 | #[inline(always)] 12 | fn value(&self) -> f64 { 13 | self.volume 14 | } 15 | 16 | #[inline(always)] 17 | fn reset(&mut self) { 18 | self.volume = 0.0; 19 | } 20 | } 21 | 22 | impl CandleComponentUpdate for Volume { 23 | #[inline(always)] 24 | fn update(&mut self, trade: &T) { 25 | self.volume += trade.size().abs() 26 | } 27 | } 28 | 29 | #[cfg(test)] 30 | mod tests { 31 | use super::*; 32 | 33 | #[test] 34 | fn volume() { 35 | let mut m = Volume::default(); 36 | let mut sum: f64 = 0.0; 37 | for t in &crate::candle_components::tests::TRADES { 38 | sum += t.size.abs(); 39 | m.update(t); 40 | assert_eq!(m.value(), sum); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/candle_components/volume_buys.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the cumulative buy volume of trades. 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct VolumeBuys { 7 | buy_volume: f64, 8 | } 9 | 10 | impl CandleComponent for VolumeBuys { 11 | #[inline(always)] 12 | fn value(&self) -> f64 { 13 | self.buy_volume 14 | } 15 | 16 | #[inline(always)] 17 | fn reset(&mut self) { 18 | self.buy_volume = 0.0; 19 | } 20 | } 21 | 22 | impl CandleComponentUpdate for VolumeBuys { 23 | #[inline(always)] 24 | fn update(&mut self, trade: &T) { 25 | if trade.size().is_sign_positive() { 26 | self.buy_volume += trade.size().abs() 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/candle_components/volume_sells.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the cumulative volume of trades. 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct VolumeSells { 7 | sell_volume: f64, 8 | } 9 | 10 | impl CandleComponent for VolumeSells { 11 | #[inline(always)] 12 | fn value(&self) -> f64 { 13 | self.sell_volume 14 | } 15 | 16 | #[inline(always)] 17 | fn reset(&mut self) { 18 | self.sell_volume = 0.0; 19 | } 20 | } 21 | 22 | impl CandleComponentUpdate for VolumeSells { 23 | #[inline(always)] 24 | fn update(&mut self, trade: &T) { 25 | if trade.size().is_sign_negative() { 26 | self.sell_volume += trade.size().abs() 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/candle_components/vpin.rs: -------------------------------------------------------------------------------- 1 | use super::{CandleComponent, CandleComponentUpdate}; 2 | use crate::TakerTrade; 3 | 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct Vpin {} 7 | 8 | impl CandleComponent for Vpin { 9 | fn value(&self) -> f64 { 10 | todo!() 11 | } 12 | 13 | fn reset(&mut self) { 14 | todo!() 15 | } 16 | } 17 | 18 | impl CandleComponentUpdate for Vpin { 19 | #[inline(always)] 20 | fn update(&mut self, _: &T) { 21 | todo!() 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/candle_components/weighted_price.rs: -------------------------------------------------------------------------------- 1 | use crate::{CandleComponent, CandleComponentUpdate, TakerTrade}; 2 | 3 | /// This 'CandleComponent' keeps track of the volume weighted price 4 | #[derive(Debug, Default, Clone)] 5 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 6 | pub struct WeightedPrice { 7 | total_weights: f64, 8 | weighted_sum: f64, 9 | } 10 | 11 | impl CandleComponent for WeightedPrice { 12 | #[inline(always)] 13 | fn value(&self) -> f64 { 14 | self.weighted_sum / self.total_weights 15 | } 16 | 17 | #[inline(always)] 18 | fn reset(&mut self) { 19 | self.total_weights = 0.0; 20 | self.weighted_sum = 0.0; 21 | } 22 | } 23 | impl CandleComponentUpdate for WeightedPrice { 24 | #[inline(always)] 25 | fn update(&mut self, trade: &T) { 26 | self.total_weights += trade.size().abs(); 27 | self.weighted_sum += trade.price() * trade.size().abs(); 28 | } 29 | } 30 | 31 | #[cfg(test)] 32 | mod tests { 33 | use super::*; 34 | 35 | #[test] 36 | fn weighted_price() { 37 | let mut m = WeightedPrice::default(); 38 | for t in &crate::candle_components::tests::TRADES { 39 | m.update(t); 40 | } 41 | assert_eq!(m.value(), 102.0); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/constants.rs: -------------------------------------------------------------------------------- 1 | /// 1 Minute candle period 2 | pub const M1: i64 = 60; 3 | 4 | /// 5 Minute candle period 5 | pub const M5: i64 = 300; 6 | 7 | /// 15 Minute candle period 8 | pub const M15: i64 = 900; 9 | 10 | /// 30 Minute candle period 11 | pub const M30: i64 = 1800; 12 | 13 | /// 1 Hour candle period 14 | pub const H1: i64 = 3600; 15 | 16 | /// 2 Hour candle period 17 | pub const H2: i64 = 7200; 18 | 19 | /// 4 Hour candle period 20 | pub const H4: i64 = 14400; 21 | 22 | /// 8 Hour candle period 23 | pub const H8: i64 = 28800; 24 | 25 | /// 12 Hour candle period 26 | pub const H12: i64 = 43200; 27 | 28 | /// 1 Day candle period 29 | pub const D1: i64 = 86400; 30 | -------------------------------------------------------------------------------- /src/errors.rs: -------------------------------------------------------------------------------- 1 | /// Enumerate the possible errors in this crate 2 | #[derive(thiserror::Error, Debug)] 3 | #[allow(missing_docs)] 4 | pub enum Error { 5 | #[error(transparent)] 6 | Io(#[from] std::io::Error), 7 | 8 | #[error(transparent)] 9 | Csv(#[from] csv::Error), 10 | 11 | #[error(transparent)] 12 | ParseInt(#[from] std::num::ParseIntError), 13 | 14 | #[error(transparent)] 15 | ParseFloat(#[from] std::num::ParseFloatError), 16 | 17 | #[error("An invalid parameter was provided")] 18 | InvalidParam, 19 | } 20 | 21 | /// Convenient wrapper for this crates custom Error 22 | pub type Result = std::result::Result; 23 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | 3 | //! This crate is used for aggregating raw trade data into candles using various methods 4 | 5 | #[cfg(test)] 6 | mod plot; 7 | 8 | mod aggregation_rules; 9 | mod aggregator; 10 | pub mod candle_components; 11 | mod constants; 12 | mod errors; 13 | mod modular_candle_trait; 14 | mod types; 15 | mod utils; 16 | mod welford_online; 17 | 18 | pub use aggregation_rules::*; 19 | pub use aggregator::*; 20 | pub use candle_components::{CandleComponent, CandleComponentUpdate}; 21 | pub use constants::*; 22 | pub use errors::*; 23 | pub use modular_candle_trait::ModularCandle; 24 | pub use trade_aggregation_derive::Candle; 25 | pub use types::*; 26 | pub use utils::*; 27 | -------------------------------------------------------------------------------- /src/modular_candle_trait.rs: -------------------------------------------------------------------------------- 1 | use crate::TakerTrade; 2 | 3 | /// A modular candle that can be composed of multiple components 4 | /// Is generic over the type of trade it accepts during the update step, 5 | /// as long as it implements the `TakerTrade` trait 6 | pub trait ModularCandle: Clone + Default { 7 | /// Updates the candle information with trade information 8 | fn update(&mut self, trade: &T); 9 | 10 | /// Resets the state of the candle 11 | fn reset(&mut self); 12 | } 13 | -------------------------------------------------------------------------------- /src/plot.rs: -------------------------------------------------------------------------------- 1 | use plotters::prelude::*; 2 | use trade_aggregation_derive::Candle; 3 | 4 | use crate::{ 5 | candle_components::{CandleComponent, CandleComponentUpdate, Close, High, Low, Open}, 6 | ModularCandle, Trade, 7 | }; 8 | 9 | #[derive(Debug, Default, Clone, Candle)] 10 | pub(crate) struct OhlcCandle { 11 | open: Open, 12 | high: High, 13 | low: Low, 14 | close: Close, 15 | } 16 | 17 | /// Creates a plot of `OHLC` candles 18 | pub(crate) fn plot_ohlc_candles( 19 | candles: &[OhlcCandle], 20 | filename: &str, 21 | dims: (u32, u32), 22 | ) -> Result<(), Box> { 23 | let n = candles.len(); 24 | 25 | let mut candlesticks: Vec> = Vec::with_capacity(n); 26 | let mut price_min = f64::MAX; 27 | let mut price_max = f64::MIN; 28 | let candle_width = (dims.0 / n as u32) - 1; 29 | for (i, c) in candles.iter().enumerate() { 30 | candlesticks.push(CandleStick::new( 31 | i as f64, 32 | c.open(), 33 | c.high(), 34 | c.low(), 35 | c.close(), 36 | &GREEN, 37 | &RED, 38 | candle_width, 39 | )); 40 | 41 | if c.low() < price_min { 42 | price_min = c.low(); 43 | } 44 | if c.high() > price_max { 45 | price_max = c.high(); 46 | } 47 | } 48 | 49 | let root_area = BitMapBackend::new(filename, dims).into_drawing_area(); 50 | 51 | root_area.fill(&WHITE)?; 52 | let root_area = root_area.titled(filename, ("sans-serif", 20).into_font())?; 53 | 54 | let mut cc0 = ChartBuilder::on(&root_area) 55 | .margin(20) 56 | .set_all_label_area_size(20) 57 | .caption("Candles", ("sans-serif", 20).into_font()) 58 | .build_cartesian_2d(0_f64..candles.len() as f64, price_min..price_max)?; 59 | 60 | cc0.configure_mesh().x_labels(20).y_labels(20).draw()?; 61 | 62 | cc0.draw_series(candlesticks)?; 63 | 64 | Ok(()) 65 | } 66 | -------------------------------------------------------------------------------- /src/types.rs: -------------------------------------------------------------------------------- 1 | use crate::TimestampResolution; 2 | 3 | #[derive(Default, Debug, Clone, Copy, PartialEq)] 4 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 5 | /// Defines a taker trade 6 | pub struct Trade { 7 | /// Timestamp, assumed to be in milliseconds 8 | pub timestamp: i64, 9 | 10 | /// Price of the asset 11 | pub price: f64, 12 | 13 | /// Size of the trade 14 | /// negative values indicate a taker Sell order 15 | pub size: f64, 16 | } 17 | 18 | impl TakerTrade for Trade { 19 | #[inline(always)] 20 | fn timestamp(&self) -> i64 { 21 | self.timestamp 22 | } 23 | 24 | #[inline(always)] 25 | fn price(&self) -> f64 { 26 | self.price 27 | } 28 | 29 | #[inline(always)] 30 | fn size(&self) -> f64 { 31 | self.size 32 | } 33 | } 34 | 35 | /// Defines how to aggregate trade size 36 | /// either by Base currency or Quote Currency 37 | /// assumes trades sizes are denoted in Quote 38 | /// e.g.: buy 10 contracts of BTC would be trade size of 10 39 | #[derive(Debug, Clone, Copy)] 40 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 41 | pub enum By { 42 | /// when aggregating by Base, divide size by price for volume sum 43 | Base, 44 | /// when aggregating by Quote, take the raw trade size for volume sum 45 | /// as the assumption is that Trade size is denoted in Quote 46 | Quote, 47 | } 48 | 49 | /// Trait to enable third party types to be passed into aggregators. 50 | pub trait TakerTrade { 51 | /// The timestamp of a trade, 52 | fn timestamp(&self) -> i64; 53 | 54 | /// units for the timestamp integer returned by [`TakerTrade.timestamp()`] method 55 | /// A default implementation is included and assumes milliseconds 56 | fn timestamp_resolution(&self) -> TimestampResolution { 57 | TimestampResolution::Millisecond 58 | } 59 | 60 | /// Fill price of the transaction 61 | fn price(&self) -> f64; 62 | 63 | /// Number of shares or contracts in this trade. 64 | /// A negative value indicates 65 | /// that the trade was a sell order, taking liquidity from the bid. 66 | fn size(&self) -> f64; 67 | } 68 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | 3 | use crate::{errors::Result, Aggregator, ModularCandle, TakerTrade, Trade}; 4 | 5 | /// Determine the candle volume which produces the same number of candles 6 | /// as the given time aggregation equivalent 7 | /// 8 | /// # Parameters: 9 | /// `total_volume` - sum of traded volume over entire time period 10 | /// `total_time_days` - total number of days 11 | /// `target_time_minutes` - time aggregated candle period which to target 12 | /// 13 | /// # Returns: 14 | /// target candle volume for which volume aggregation produces 15 | /// the same number of candles as the time aggregation did 16 | /// e.g.: 17 | /// 10 days of 1 hour candles -> 240 candles 18 | /// assuming 9840 volume traded over 10 days 19 | /// -> each candle should have 41 volume to produce 240 candles using volume aggregation 20 | pub fn candle_volume_from_time_period( 21 | total_volume: f64, 22 | total_time_days: f64, 23 | target_time_minutes: f64, 24 | ) -> f64 { 25 | let num_candles = total_time_days * 24.0 * (60.0 / target_time_minutes); 26 | total_volume / num_candles 27 | } 28 | 29 | /// Apply an aggregator for all trades at once 30 | /// 31 | /// # Arguments: 32 | /// trades: The input trade data to aggregate 33 | /// aggregator: Something that can aggregate 34 | /// 35 | /// # Returns: 36 | /// A vector of aggregated candle data 37 | pub fn aggregate_all_trades(trades: &[T], aggregator: &mut A) -> Vec 38 | where 39 | A: Aggregator, 40 | C: ModularCandle, 41 | T: TakerTrade, 42 | { 43 | let mut out: Vec = vec![]; 44 | 45 | for t in trades { 46 | if let Some(candle) = aggregator.update(t) { 47 | out.push(candle) 48 | } 49 | } 50 | 51 | out 52 | } 53 | 54 | /// Load trades from csv file 55 | /// 56 | /// # Arguments: 57 | /// filename: The path to the csv file 58 | /// 59 | /// # Returns 60 | /// If Ok, A vector of the trades inside the file 61 | pub fn load_trades_from_csv(filename: &str) -> Result> { 62 | let f = File::open(filename)?; 63 | 64 | let mut r = csv::Reader::from_reader(f); 65 | 66 | let mut out: Vec = vec![]; 67 | for record in r.records() { 68 | let row = record?; 69 | 70 | let ts = row[0].parse::()?; 71 | let price = row[1].parse::()?; 72 | let size = row[2].parse::()?; 73 | 74 | // convert to Trade 75 | let trade = Trade { 76 | timestamp: ts, 77 | price, 78 | size, 79 | }; 80 | out.push(trade); 81 | } 82 | 83 | Ok(out) 84 | } 85 | 86 | #[cfg(test)] 87 | mod tests { 88 | use round::round; 89 | 90 | use super::*; 91 | 92 | // TODO: re-enable this test 93 | /* 94 | #[test] 95 | fn test_aggregate_all_trades() { 96 | let trades = load_trades_from_csv("data/Bitmex_XBTUSD_1M.csv").unwrap(); 97 | let mut aggregator = GenericAggregator::new(100.0, By::Quote); 98 | let candles = aggregate_all_trades(&trades, &mut aggregator); 99 | assert!(candles.len() > 0); 100 | } 101 | */ 102 | 103 | #[test] 104 | fn test_candle_volume_from_time_period() { 105 | let total_volume = 100.0; 106 | let time_days = 10.0; 107 | let target_time_minutes = 5.0; 108 | let vol_threshold = 109 | candle_volume_from_time_period(total_volume, time_days, target_time_minutes); 110 | assert_eq!(round(vol_threshold, 3), 0.035); 111 | 112 | let total_volume = 100.0; 113 | let time_days = 10.0; 114 | let target_time_minutes = 10.0; 115 | let vol_threshold = 116 | candle_volume_from_time_period(total_volume, time_days, target_time_minutes); 117 | assert_eq!(round(vol_threshold, 3), 0.069); 118 | 119 | let total_volume = 200.0; 120 | let time_days = 10.0; 121 | let target_time_minutes = 10.0; 122 | let vol_threshold = 123 | candle_volume_from_time_period(total_volume, time_days, target_time_minutes); 124 | assert_eq!(round(vol_threshold, 3), 0.139); 125 | 126 | let total_volume = 50.0; 127 | let time_days = 10.0; 128 | let target_time_minutes = 10.0; 129 | let vol_threshold = 130 | candle_volume_from_time_period(total_volume, time_days, target_time_minutes); 131 | assert_eq!(round(vol_threshold, 3), 0.035); 132 | 133 | let total_volume = 100.0; 134 | let time_days = 5.0; 135 | let target_time_minutes = 5.0; 136 | let vol_threshold = 137 | candle_volume_from_time_period(total_volume, time_days, target_time_minutes); 138 | assert_eq!(round(vol_threshold, 3), 0.069); 139 | 140 | let total_volume = 100.0; 141 | let time_days = 5.0; 142 | let target_time_minutes = 10.0; 143 | let vol_threshold = 144 | candle_volume_from_time_period(total_volume, time_days, target_time_minutes); 145 | assert_eq!(round(vol_threshold, 3), 0.139); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/welford_online.rs: -------------------------------------------------------------------------------- 1 | /// Algorithm for online estimation of standard deviation 2 | #[derive(Debug, Clone)] 3 | #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 4 | pub struct WelfordOnline { 5 | count: u32, 6 | mean: f64, 7 | s: f64, 8 | } 9 | 10 | impl WelfordOnline { 11 | pub fn new() -> Self { 12 | WelfordOnline { 13 | count: 0, 14 | mean: 0.0, 15 | s: 0.0, 16 | } 17 | } 18 | 19 | // variance returns the variance 20 | pub fn variance(&self) -> f64 { 21 | if self.count > 1 { 22 | return self.s / (self.count as f64 - 1.0); 23 | } 24 | 25 | 0.0 26 | } 27 | 28 | // std_dev returns the standard deviation 29 | pub fn std_dev(&self) -> f64 { 30 | self.variance().sqrt() 31 | } 32 | 33 | // reset to defaults 34 | pub fn reset(&mut self) { 35 | self.count = 0; 36 | self.mean = 0.0; 37 | self.s = 0.0; 38 | } 39 | 40 | // add updates the statistics 41 | pub fn add(&mut self, val: f64) { 42 | self.count += 1; 43 | let old_mean = self.mean; 44 | self.mean += (val - old_mean) / self.count as f64; 45 | self.s += (val - old_mean) * (val - self.mean); 46 | } 47 | } 48 | 49 | #[cfg(test)] 50 | mod tests { 51 | use round::round; 52 | 53 | use super::*; 54 | 55 | const VALS: [f64; 4] = [1.0, 2.0, 1.0, 2.0]; 56 | 57 | #[test] 58 | fn welford_online() { 59 | let mut welford = WelfordOnline::new(); 60 | 61 | for v in &VALS { 62 | welford.add(*v); 63 | } 64 | assert_eq!(round(welford.std_dev(), 4), 0.5774); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /trade_aggregation_derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "trade_aggregation_derive" 3 | version = "0.4.1" 4 | edition = "2021" 5 | authors = ["MathisWellmann "] 6 | license-file = "LICENSE" 7 | description = "The macros for trade_aggregation crate" 8 | repository = "https://github.com/MathisWellmann/trade_aggregation-rs" 9 | readme = "README.md" 10 | keywords = ["trading", "candles", "macro"] 11 | categories = ["algorithms"] 12 | ignore = ["target"] 13 | 14 | [lib] 15 | proc-macro = true 16 | 17 | [dependencies] 18 | syn = { version = "2", features = ["extra-traits"] } 19 | quote = "1" 20 | -------------------------------------------------------------------------------- /trade_aggregation_derive/LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /trade_aggregation_derive/README.md: -------------------------------------------------------------------------------- 1 | # trade_aggregation_derive 2 | This is a helper crate for [trade_aggregation-rs](https://github.com/MathisWellmann/trade_aggregation-rs) 3 | which supplies the 'Candle' derive macro. 4 | -------------------------------------------------------------------------------- /trade_aggregation_derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate exposes the 'Candle' macro, 2 | //! It combines multiple types that implement 'CandleComponent' 3 | //! into a single 'ModularCandle' struct 4 | //! which can then be used as the output type of some aggregation process. 5 | //! It also exposes getter methods for each 'CandleComponent' for convenience. 6 | //! The name of the getter method is equivalent to the field name. 7 | //! e.g.: 8 | //! struct MyCandle { 9 | //! open: Open, 10 | //! } 11 | //! with the derive macro will create a "fn open(&self)" method which gets the inner value 12 | //! 13 | //! When deriving the 'Candle' macro, make sure the following things are in scope: 14 | //! - Trade 15 | //! - ModularCandle 16 | //! - CandleComponent 17 | 18 | #![deny(missing_docs)] 19 | 20 | use proc_macro::TokenStream; 21 | use quote::{__private::Span, quote}; 22 | use syn::{ 23 | self, AngleBracketedGenericArguments, Data, DataStruct, Fields, GenericArgument, Ident, Type, 24 | TypePath, 25 | }; 26 | 27 | /// The 'Candle' macro takes a named struct, 28 | /// that has multiple fields of type 'CandleComponent' 29 | /// to automatically generate a struct that implements 30 | /// the 'ModularCandle' trait, which means it can then be used 31 | /// in the aggregation process. 32 | /// It also exposes getter functions for each 'CandleComponent' for convenience. 33 | #[proc_macro_derive(Candle)] 34 | pub fn candle_macro_derive(input: TokenStream) -> TokenStream { 35 | // Construct a representation of Rust code as a syntax tree 36 | // that we can manipulate 37 | let ast = syn::parse(input).unwrap(); 38 | 39 | // Build the trait implementation 40 | impl_candle_macro(&ast) 41 | } 42 | 43 | fn phantom_path_to_type(path: &syn::Path) -> Option { 44 | if path.leading_colon.is_some() { 45 | return None; 46 | } 47 | let mut it = path.segments.iter(); 48 | let segment = it.next()?; 49 | match &segment.arguments { 50 | syn::PathArguments::AngleBracketed(AngleBracketedGenericArguments { args: x, .. }) => { 51 | match x.first() { 52 | Some(GenericArgument::Type(Type::Path(TypePath { 53 | path: syn::Path { segments: segs, .. }, 54 | .. 55 | }))) => segs.first().and_then(|x| Some(x.ident.clone())), 56 | _ => None, 57 | } 58 | } 59 | _ => None, 60 | } 61 | } 62 | 63 | fn impl_candle_macro(ast: &syn::DeriveInput) -> TokenStream { 64 | let name = &ast.ident; 65 | let components = match &ast.data { 66 | Data::Struct(DataStruct { 67 | fields: Fields::Named(fields), 68 | .. 69 | }) => &fields.named, 70 | _ => panic!("Use a named struct"), 71 | }; 72 | 73 | let default_output_type = Ident::new("f64", Span::call_site()); 74 | let mut input_type = Some(Ident::new("Trade", Span::call_site())); 75 | let mut value_idents = vec![]; 76 | let mut value_types = vec![]; 77 | 78 | for c in components { 79 | if let syn::Field { 80 | ty: syn::Type::Path(syn::TypePath { path: p, .. }), 81 | ident, 82 | .. 83 | } = c 84 | { 85 | if ident.clone().unwrap().to_string().as_str() == "input" { 86 | input_type = phantom_path_to_type(&p); 87 | } else { 88 | if let Some(type_) = phantom_path_to_type(&p) { 89 | value_idents.push(ident); 90 | value_types.push(type_); 91 | } else { 92 | value_idents.push(ident); 93 | value_types.push(default_output_type.clone()); 94 | } 95 | } 96 | } 97 | } 98 | 99 | let fn_names0 = value_idents.clone(); 100 | let fn_names1 = fn_names0.clone(); 101 | let fn_names2 = fn_names1.clone(); 102 | let input_name = input_type.expect("No PhantomData for input attribute type!"); 103 | 104 | let gen = quote! { 105 | impl #name { 106 | #( 107 | /// Get the value of this candle component. 108 | pub fn #fn_names0(&self) -> #value_types { 109 | self.#fn_names0.value() 110 | } 111 | )* 112 | } 113 | 114 | impl ModularCandle<#input_name> for #name { 115 | fn update(&mut self, trade: &#input_name) { 116 | #( 117 | self.#fn_names1.update(trade); 118 | )* 119 | } 120 | 121 | fn reset(&mut self) { 122 | #( 123 | self.#fn_names2.reset(); 124 | )* 125 | } 126 | } 127 | }; 128 | 129 | gen.into() 130 | } 131 | --------------------------------------------------------------------------------