├── .changeset ├── README.md └── config.json ├── .gitignore ├── .vscode └── settings.json ├── LICENSE ├── README.md ├── eslint.config.mjs ├── package.json ├── packages ├── backtest │ ├── CHANGELOG.md │ ├── jest.config.js │ ├── package.json │ ├── rollup.config.js │ ├── src │ │ ├── analyzers │ │ │ ├── BaseAnalyzer.ts │ │ │ ├── DrawDown.ts │ │ │ ├── Positions.ts │ │ │ ├── Returns.ts │ │ │ ├── Trades.ts │ │ │ └── index.ts │ │ ├── core │ │ │ ├── broker.ts │ │ │ └── strategy.ts │ │ ├── index.ts │ │ └── utils.ts │ ├── tsconfig.dts.json │ └── tsconfig.json ├── cli │ ├── CHANGELOG.md │ ├── README.md │ ├── dev │ │ ├── backtests │ │ │ ├── hold-ema.json │ │ │ ├── hold.json │ │ │ ├── ride-momentum-balance.json │ │ │ ├── ride-momentum.json │ │ │ ├── rider-no-filter.json │ │ │ └── test.json │ │ ├── reports │ │ │ └── report.html │ │ └── src │ │ │ ├── js │ │ │ ├── error.js │ │ │ ├── hello-hold.js │ │ │ ├── hello-no-balance.js │ │ │ ├── hello.js │ │ │ ├── hello2.js │ │ │ ├── hold-ema.js │ │ │ ├── hold.js │ │ │ ├── ride-momentum-balance.js │ │ │ ├── ride-momentum.js │ │ │ └── test.js │ │ │ └── zp │ │ │ ├── crossover.zp │ │ │ ├── error.zp │ │ │ ├── hello.zp │ │ │ └── test.zp │ ├── package.json │ ├── rollup.config.js │ ├── src │ │ ├── api │ │ │ ├── cache.ts │ │ │ ├── code.ts │ │ │ ├── data.ts │ │ │ ├── index.ts │ │ │ ├── login.ts │ │ │ └── report.ts │ │ ├── commands │ │ │ ├── backtest.ts │ │ │ ├── create.ts │ │ │ ├── download.ts │ │ │ ├── execute.ts │ │ │ ├── login.ts │ │ │ ├── report.ts │ │ │ └── view.ts │ │ ├── config.ts │ │ ├── index.ts │ │ ├── storage.ts │ │ └── utils.ts │ ├── test.json │ ├── tsconfig.json │ └── zp.config.js ├── core │ ├── CHANGELOG.md │ ├── jest.config.js │ ├── package.json │ ├── rollup.config.js │ ├── src │ │ ├── helpers │ │ │ ├── array.ts │ │ │ ├── assert.ts │ │ │ ├── index.ts │ │ │ ├── number.ts │ │ │ ├── order.ts │ │ │ └── position.ts │ │ ├── index.ts │ │ ├── indicators │ │ │ ├── atr.ts │ │ │ ├── cmr.ts │ │ │ ├── donchian.ts │ │ │ ├── ema.ts │ │ │ ├── highest.ts │ │ │ ├── index.ts │ │ │ ├── lowest.ts │ │ │ ├── momentum.ts │ │ │ ├── rsi.ts │ │ │ ├── sma.ts │ │ │ ├── std.ts │ │ │ └── trueRange.ts │ │ ├── trading │ │ │ ├── assets.ts │ │ │ ├── core.ts │ │ │ ├── env.ts │ │ │ ├── indicators.ts │ │ │ └── trade.ts │ │ └── types.ts │ ├── tsconfig.dts.json │ └── tsconfig.json └── reports │ ├── CHANGELOG.md │ ├── build.js │ ├── jest.config.js │ ├── package.json │ ├── rollup.config.js │ ├── src │ ├── index.ts │ ├── reports │ │ ├── DrawDown.ts │ │ ├── Positions.ts │ │ ├── Report.ts │ │ ├── Returns.ts │ │ └── Trades │ │ │ ├── index.ts │ │ │ └── mapping.ts │ └── utils.ts │ ├── tsconfig.dts.json │ └── tsconfig.json ├── pnpm-lock.yaml └── pnpm-workspace.yaml /.changeset/README.md: -------------------------------------------------------------------------------- 1 | # Changesets 2 | 3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works 4 | with multi-package repos, or single-package repos to help you version and publish your code. You can 5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets) 6 | 7 | We have a quick list of common questions to get you started engaging with this project in 8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) 9 | -------------------------------------------------------------------------------- /.changeset/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://unpkg.com/@changesets/config@2.3.1/schema.json", 3 | "changelog": "@changesets/cli/changelog", 4 | "commit": false, 5 | "fixed": [], 6 | "linked": [], 7 | "access": "public", 8 | "baseBranch": "main", 9 | "updateInternalDependencies": "patch", 10 | "ignore": [] 11 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | node_modules 3 | coverage 4 | 5 | # Keep environment variables out of version control 6 | .env 7 | .env.development 8 | 9 | dist 10 | packages/cli/dev/data/**/* 11 | .DS_Store -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.renderWhitespace": "boundary", 3 | "files.associations": { 4 | "*.zp": "clojure" 5 | }, 6 | "npm.packageManager": "pnpm", 7 | "editor.minimap.enabled": false, 8 | "editor.fontSize": 14 9 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 |
3 | 4 | 5 | 6 |

7 | 8 |

ZapCli

9 |

The quickest way to write trading automations!

10 |

11 | ZapCli is an open-source trading engine. That main focus is to simplify the process of writing trading automations. 12 |

13 | 14 |

15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | GitHub 23 | 24 |
25 |
26 |

27 | 28 | 29 | ## ZapCLI 30 | 31 | - 💡 Intuitive 32 | - 🔌 Extensible 33 | - 🦾 Scalable 34 | - 📦 Extremely easy to use 35 | 36 | ## Documentation 37 | 38 | To learn more about ZapCLI read the documentation [here](https://zapcli.com/) or [watch a video](https://www.youtube.com/watch?v=4-dnBD4YWwU) 39 | 40 | ## Get Started 41 | 42 | ```shell 43 | npm i @zapcli/cli 44 | zapcli create MyProject 45 | zapcli backtest ./src/hello.zp 46 | ``` 47 | 48 | ## Simple example 49 | 50 | Buy one share of AAPL if price over EMA 30 51 | ```javascript 52 | const assets = ["AAPL"] 53 | const window = 30 54 | const settings = {} 55 | 56 | function run() { 57 | const AAPL = this.asset(assets[0]) 58 | const ema = this.ema(AAPL, 30) 59 | 60 | if (AAPL.close > ema) { 61 | this.buy(AAPL, 1) 62 | } 63 | } 64 | 65 | return { assets, settings, window, run } 66 | ``` 67 | 68 | ## Useful links: 69 | 70 | - [Getting Started](https://zapcli.com/getting-started/) full guide. 71 | - [View on Github](https://github.com/ghalex/zapcli) 72 | 73 | ## License 74 | 75 | Copyright (c) 2021 [ZapCLI Contributors](https://github.com/ghalex/zapcli/graphs/contributors) 76 | Licensed under the [GNU General License](https://github.com/ghalex/zapcli/blob/HEAD/LICENSE). 77 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import globals from "globals"; 2 | import jslint from "@eslint/js"; 3 | import tseslint from "typescript-eslint"; 4 | 5 | export default [ 6 | { 7 | languageOptions: { 8 | globals: { ...globals.browser, ...globals.node } 9 | } 10 | }, 11 | jslint.configs.recommended, 12 | ...tseslint.configs.recommended, 13 | // General 14 | { 15 | files: ["packages/**/*.ts"], 16 | rules: { 17 | "@typescript-eslint/no-unused-vars": "warn", 18 | "@typescript-eslint/no-explicit-any": "warn" 19 | } 20 | }, 21 | // CLI 22 | { 23 | files: ["packages/cli/**/*.ts"], 24 | rules: { 25 | } 26 | } 27 | ]; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "root", 3 | "version": "0.0.0", 4 | "description": "ZapCLI monorepo", 5 | "author": "Alexandru Ghiura @ghalex", 6 | "private": true, 7 | "scripts": { 8 | "publish": "pnpm --filter './packages/**' publish", 9 | "cli": "pnpm --filter @zapcli/cli dev" 10 | }, 11 | "devDependencies": { 12 | "@changesets/cli": "^2.27.6" 13 | }, 14 | "dependencies": { 15 | "@eslint/js": "^9.5.0", 16 | "globals": "^15.6.0", 17 | "typescript-eslint": "^7.14.1" 18 | } 19 | } -------------------------------------------------------------------------------- /packages/backtest/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # @zapcli/backtest 2 | 3 | ## 1.0.12 4 | 5 | ### Patch Changes 6 | 7 | - change reports for dd and positions 8 | - Updated dependencies 9 | - @zapcli/core@1.0.12 10 | 11 | ## 1.0.11 12 | 13 | ### Patch Changes 14 | 15 | - Updated dependencies 16 | - @zapcli/core@1.0.11 17 | 18 | ## 1.0.10 19 | 20 | ### Patch Changes 21 | 22 | - Updated dependencies 23 | - @zapcli/core@1.0.10 24 | 25 | ## 1.0.9 26 | 27 | ### Patch Changes 28 | 29 | - add more functions 30 | - Updated dependencies 31 | - @zapcli/core@1.0.9 32 | 33 | ## 1.0.8 34 | 35 | ### Patch Changes 36 | 37 | - fix short position 38 | - Updated dependencies 39 | - @zapcli/core@1.0.8 40 | 41 | ## 1.0.7 42 | 43 | ### Patch Changes 44 | 45 | - Updated dependencies 46 | - @zapcli/core@1.0.7 47 | 48 | ## 1.0.6 49 | 50 | ### Patch Changes 51 | 52 | - Updated dependencies 53 | - @zapcli/core@1.0.6 54 | 55 | ## 1.0.5 56 | 57 | ### Patch Changes 58 | 59 | - Updated dependencies 60 | - @zapcli/core@1.0.5 61 | 62 | ## 1.0.4 63 | 64 | ### Patch Changes 65 | 66 | - Updated dependencies 67 | - @zapcli/core@1.0.4 68 | 69 | ## 1.0.3 70 | 71 | ### Patch Changes 72 | 73 | - add reports command 74 | - Updated dependencies 75 | - @zapcli/core@1.0.3 76 | 77 | ## 1.0.2 78 | 79 | ### Patch Changes 80 | 81 | - update drawdown analyzer 82 | - Updated dependencies 83 | - @zapcli/core@1.0.2 84 | 85 | ## 1.0.1 86 | 87 | ### Patch Changes 88 | 89 | - fix trading bugs 90 | - Updated dependencies 91 | - @zapcli/core@1.0.1 92 | -------------------------------------------------------------------------------- /packages/backtest/jest.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest').JestConfigWithTsJest} */ 2 | 3 | const path = require('path'); 4 | require('dotenv').config({ path: path.resolve(__dirname, '../../.env') }); 5 | 6 | module.exports = { 7 | preset: 'ts-jest', 8 | testEnvironment: 'node', 9 | }; -------------------------------------------------------------------------------- /packages/backtest/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@zapcli/backtest", 3 | "version": "1.0.12", 4 | "description": "", 5 | "main": "dist/zapcli-backtest.cjs.js", 6 | "module": "dist/zapcli-backtest.es.js", 7 | "types": "dist/zapcli-backtest.d.ts", 8 | "files": [ 9 | "dist", 10 | "package.json", 11 | "CHANGELOG.md" 12 | ], 13 | "scripts": { 14 | "start": "rollup -c -w", 15 | "build": "rm -rf ./dist/ && rollup -c --bundleConfigAsCjs", 16 | "lint": "eslint src --ext js,ts", 17 | "test": "jest --verbose", 18 | "prepack": "pnpm build" 19 | }, 20 | "repository": { 21 | "type": "git", 22 | "url": "https://github.com/ghalex/zapcli" 23 | }, 24 | "keywords": [], 25 | "author": "", 26 | "license": "ISC", 27 | "devDependencies": { 28 | "@types/express": "^4.17.21", 29 | "@types/jest": "^29.5.12", 30 | "@types/node": "^20.14.9", 31 | "dotenv-flow": "^4.1.0", 32 | "jest": "^29.7.0", 33 | "module-alias": "^2.2.3", 34 | "rollup": "^4.18.0", 35 | "rollup-plugin-dts": "^6.1.1", 36 | "rollup-plugin-esbuild": "^6.1.1", 37 | "ts-jest": "^29.1.5", 38 | "ts-node": "^10.9.2", 39 | "typescript": "^5.5.2" 40 | }, 41 | "dependencies": { 42 | "@zapcli/core": "workspace:*", 43 | "dayjs": "^1.11.11", 44 | "zplang": "^1.0.56" 45 | } 46 | } -------------------------------------------------------------------------------- /packages/backtest/rollup.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const dts = require('rollup-plugin-dts').default 3 | const esbuild = require('rollup-plugin-esbuild').default 4 | const pkg = require('./package.json') 5 | 6 | const name = 'zapcli-backtest' 7 | // const projectRoot = path.resolve(__dirname, '.') 8 | 9 | module.exports = [ 10 | { 11 | input: 'src/index.ts', 12 | external: [ 13 | 'ramda', 14 | 'dayjs', 15 | 'zplang', 16 | '@zapcli/core' 17 | ], 18 | plugins: [ 19 | esbuild() 20 | ], 21 | output: [ 22 | { 23 | name, 24 | file: path.resolve(__dirname, `dist/${name}.cjs.js`), 25 | format: 'cjs' 26 | }, 27 | { 28 | file: path.resolve(__dirname, `dist/${name}.es.js`), 29 | format: 'es' 30 | } 31 | ] 32 | }, 33 | { 34 | input: 'src/index.ts', 35 | plugins: [dts()], 36 | external: [], 37 | output: { 38 | file: path.resolve(__dirname, `dist/${name}.d.ts`), 39 | format: 'es' 40 | } 41 | } 42 | ] 43 | -------------------------------------------------------------------------------- /packages/backtest/src/analyzers/BaseAnalyzer.ts: -------------------------------------------------------------------------------- 1 | 2 | class BaseAnalyzer { 3 | name = 'base' 4 | data: any = {} 5 | _strategy: any | null = null 6 | 7 | public init(): boolean { 8 | return true 9 | } 10 | 11 | setStrategy(strategy) { 12 | this._strategy = strategy 13 | } 14 | 15 | get strategy() { 16 | if (!this._strategy) throw new Error('Analyzer not added to strategy') 17 | 18 | return this._strategy 19 | } 20 | 21 | public onOrder(order) { } 22 | public onPosition(position) { } 23 | public onCash(oldCash, newCash) { } 24 | 25 | start() { } 26 | end() { } 27 | 28 | prenext() { } 29 | next() { } 30 | 31 | toConsole() { 32 | console.dir(this.data, { depth: null, colors: true }) 33 | } 34 | } 35 | 36 | export default BaseAnalyzer -------------------------------------------------------------------------------- /packages/backtest/src/analyzers/DrawDown.ts: -------------------------------------------------------------------------------- 1 | import dayjs from 'dayjs' 2 | import BaseAnalyzer from './BaseAnalyzer' 3 | import { round } from '../utils' 4 | 5 | class DrawDownAnalyzer extends BaseAnalyzer { 6 | name = 'drawdown' 7 | data = { 8 | maxDrawDown: 0, 9 | maxMoneyDown: 0, 10 | maxDrawDownDuration: 0, 11 | maxDrawDownStart: '', 12 | maxDrawDownEnd: '', 13 | longestDrawDownDuration: 0, 14 | drawDowns: [] as any[] 15 | } 16 | 17 | private value = 0 18 | private maxValue = 0 19 | private len = 0 20 | 21 | public init(): boolean { 22 | return true 23 | } 24 | 25 | next() { 26 | const date = dayjs(this.strategy.currentDate).format('YYYY-MM-DD') 27 | const item: any = { date } 28 | 29 | this.value = this.strategy.broker.getValue() 30 | this.maxValue = Math.max(this.maxValue, this.value) 31 | 32 | item.max = this.maxValue 33 | item.moneyDown = this.maxValue - this.value 34 | item.drawDown = item.moneyDown / this.maxValue 35 | 36 | this.len = item.drawDown > 0 ? this.len + 1 : 0 37 | item.len = this.len 38 | 39 | 40 | this.data.maxMoneyDown = Math.max(this.data.maxMoneyDown, item.moneyDown) 41 | this.data.maxDrawDown = Math.max(this.data.maxDrawDown, item.drawDown) 42 | 43 | this.data.longestDrawDownDuration = Math.max(this.data.longestDrawDownDuration, this.len) 44 | this.data.drawDowns.push(item) 45 | } 46 | 47 | end(): void { 48 | 49 | // calculate start end of max drawdown 50 | const itemIdx = this.data.drawDowns.findIndex(i => i.moneyDown === this.data.maxMoneyDown) 51 | 52 | if (itemIdx > 0) { 53 | let left = itemIdx 54 | let right = itemIdx 55 | 56 | while (left > 0) { 57 | if (this.data.drawDowns[left].len === 0) { 58 | break 59 | } 60 | left-- 61 | } 62 | 63 | while (right < this.data.drawDowns.length - 1) { 64 | if (this.data.drawDowns[right].len === 0) { 65 | break 66 | } 67 | right++ 68 | } 69 | 70 | this.data.maxDrawDownStart = this.data.drawDowns[left]?.date 71 | this.data.maxDrawDownEnd = this.data.drawDowns[right]?.date 72 | this.data.maxDrawDownDuration = right - left 73 | } 74 | 75 | // round to 2 decimal places 76 | this.data.maxDrawDown = round(this.data.maxDrawDown * 100, 2) 77 | } 78 | 79 | toConsole(): void { 80 | const { drawDowns, ...rest } = this.data 81 | console.table({ 82 | ...rest, 83 | maxDrawDown: `${rest.maxDrawDown}%` 84 | }) 85 | } 86 | } 87 | 88 | export default DrawDownAnalyzer -------------------------------------------------------------------------------- /packages/backtest/src/analyzers/Positions.ts: -------------------------------------------------------------------------------- 1 | import dayjs from 'dayjs' 2 | import BaseAnalyzer from './BaseAnalyzer' 3 | import { currencyFormat } from '../utils' 4 | 5 | class PositionsAnalyzer extends BaseAnalyzer { 6 | name = 'positions' 7 | data = [] as any[] 8 | 9 | end() { 10 | this.data = this.strategy.broker.getPositions(). 11 | sort((a, b) => a.closeDate - b.closeDate). 12 | map((p) => { 13 | return { 14 | ...p, 15 | openDate: dayjs(p.openDate).format('YYYY-MM-DD'), 16 | closeDate: p.closeDate ? dayjs(p.closeDate).format('YYYY-MM-DD') : null 17 | } 18 | }).map((p) => { 19 | const { stats, ...rest } = p 20 | return { 21 | ...rest, 22 | pl: parseFloat(stats.pl.toFixed(2)), 23 | value: parseFloat(stats.value.toFixed(2)) 24 | } 25 | }) 26 | 27 | } 28 | 29 | toConsole(): void { 30 | if (this.data.length === 0) { 31 | console.log('No positions generated.') 32 | return 33 | } 34 | 35 | console.table(this.data.map((p) => { 36 | return { 37 | ...p, 38 | pl: currencyFormat(p.pl), 39 | value: currencyFormat(p.value) 40 | } 41 | })) 42 | } 43 | } 44 | 45 | export default PositionsAnalyzer -------------------------------------------------------------------------------- /packages/backtest/src/analyzers/Returns.ts: -------------------------------------------------------------------------------- 1 | import dayjs from 'dayjs' 2 | import BaseAnalyzer from './BaseAnalyzer' 3 | 4 | class RetursAnalyzer extends BaseAnalyzer { 5 | name = 'returns' 6 | data = [] as any[] 7 | 8 | next() { 9 | const date = dayjs(this.strategy.currentDate).format('YYYY-MM-DD') 10 | 11 | const item: any = { date } 12 | item.value = this.strategy.broker.getValue() 13 | item.cash = this.strategy.broker.getCash() 14 | item.pl = this.strategy.broker.getPL() 15 | 16 | this.data.push(item) 17 | } 18 | 19 | toConsole() { 20 | console.table(this.data) 21 | } 22 | 23 | } 24 | 25 | export default RetursAnalyzer -------------------------------------------------------------------------------- /packages/backtest/src/analyzers/Trades.ts: -------------------------------------------------------------------------------- 1 | import { round } from '../utils' 2 | import BaseAnalyzer from './BaseAnalyzer' 3 | 4 | class TreadesAnalyzer extends BaseAnalyzer { 5 | name = 'trades' 6 | data = { 7 | nbOfTrades: 0, 8 | nbOfWinningTrades: 0, 9 | nbOfLosingTrades: 0, 10 | avgWinningTrade: 0, 11 | avgLosingTrade: 0, 12 | winRate: 0, 13 | bestTrade: 0, 14 | worstTrade: 0, 15 | maxTradeDuration: 0, // in seconds 16 | avgTradeDuration: 0, // in seconds 17 | } 18 | 19 | end() { 20 | const positions = this.strategy.broker.getPositions() 21 | let totalWin = 0 22 | let totalLoss = 0 23 | let totalTradesDuration = 0 24 | 25 | for (const position of positions) { 26 | this.data.nbOfTrades += 1 27 | const profit = position.stats.pl 28 | 29 | // Calculate nr of winning and losing trades 30 | if (profit > 0) { 31 | this.data.nbOfWinningTrades++ 32 | totalWin += profit 33 | } else { 34 | this.data.nbOfLosingTrades++ 35 | totalLoss += Math.abs(profit) 36 | } 37 | 38 | // Calculate best and worst trade 39 | if (profit > this.data.bestTrade) { 40 | this.data.bestTrade = profit 41 | } 42 | if (profit < this.data.worstTrade) { 43 | this.data.worstTrade = profit 44 | } 45 | 46 | // Calculate trade duration 47 | const tradeDuration = (position.closeDate - position.openDate) / 1000 // Convert to seconds 48 | totalTradesDuration += tradeDuration 49 | if (tradeDuration > this.data.maxTradeDuration) { 50 | this.data.maxTradeDuration = tradeDuration 51 | } 52 | } 53 | 54 | // Calculate average win and loss 55 | if (totalWin) { 56 | this.data.avgWinningTrade = round(totalWin / this.data.nbOfWinningTrades, 2) 57 | } 58 | if (totalLoss) { 59 | this.data.avgLosingTrade = round(totalLoss / this.data.nbOfLosingTrades, 2) 60 | } 61 | 62 | this.data.winRate = round(this.data.nbOfWinningTrades / this.data.nbOfTrades, 2) 63 | this.data.avgTradeDuration = round(totalTradesDuration / this.data.nbOfTrades, 2) 64 | } 65 | } 66 | 67 | export default TreadesAnalyzer -------------------------------------------------------------------------------- /packages/backtest/src/analyzers/index.ts: -------------------------------------------------------------------------------- 1 | export { default as RetursAnalyzer } from './Returns' 2 | export { default as PositionsAnalyzer } from './Positions' 3 | export { default as TradesAnalyzer } from './Trades' 4 | export { default as DrawDownAnalyzer } from './DrawDown' 5 | export { default as BaseAnalyzer } from './BaseAnalyzer' 6 | -------------------------------------------------------------------------------- /packages/backtest/src/core/broker.ts: -------------------------------------------------------------------------------- 1 | import dayjs from 'dayjs' 2 | import { floor } from '../utils' 3 | import { helpers } from '@zapcli/core' 4 | 5 | class Broker { 6 | cash: number = 10_000 7 | cashStart: number = 10_000 8 | comission: number = 0 9 | orders: any[] = [] 10 | positions: any[] = [] 11 | bars: any = {} 12 | barIndex: number = 0 13 | eventHandler: any = null 14 | 15 | constructor(cash?: number, comission?: number) { 16 | this.cash = this.cashStart = cash ?? 10_000 17 | this.comission = comission ?? 0 18 | } 19 | 20 | setCash(val: number) { 21 | this.cash = this.cashStart = val 22 | } 23 | 24 | changeCash(val: number) { 25 | this.eventHandler?.onCash(this.cash, val) 26 | this.cash = val 27 | } 28 | 29 | setCommision(val: number) { 30 | this.comission = val 31 | } 32 | 33 | setBars(data: any) { 34 | this.bars = data 35 | } 36 | 37 | setBarIndex(index) { 38 | this.barIndex = index 39 | } 40 | 41 | setEventHandler(evtHandler: any) { 42 | this.eventHandler = evtHandler 43 | } 44 | 45 | getCash() { 46 | return floor(this.cash, 2) 47 | } 48 | 49 | getCashStart() { 50 | return floor(this.cashStart, 2) 51 | } 52 | 53 | getValue() { 54 | const positionsValue = this.getOpenPositions().reduce((acc, p) => acc + p.stats.value, 0) 55 | return floor(this.getCash() + positionsValue, 2) 56 | } 57 | 58 | getInvested() { 59 | return floor(this.getOpenPositions().reduce((acc, p) => acc + (p.units * p.openPrice), 0), 2) 60 | } 61 | 62 | getPL() { 63 | return floor(this.getValue() - this.cashStart, 2) 64 | } 65 | 66 | getPositions() { 67 | return this.positions.map(p => { 68 | const today = this.bars[p.symbol]?.[0] 69 | const closePrice = p.closePrice ?? today?.close ?? 0 70 | const pl = floor((closePrice - p.openPrice) * p.units, 2) * (p.side === 'long' ? 1 : -1) 71 | return { 72 | ...p, 73 | stats: { 74 | pl, 75 | value: p.openPrice * p.units + pl, 76 | currentPrice: closePrice, 77 | } 78 | } 79 | }) 80 | } 81 | 82 | getOpenPositions() { 83 | return this.getPositions().filter(p => !p.closeDate) 84 | } 85 | 86 | closeAllPositions() { 87 | for (const position of this.getOpenPositions()) { 88 | const bars = this.bars[position.symbol] 89 | const order = { 90 | symbol: position.symbol, 91 | date: bars[0].date, 92 | price: bars[0].close, 93 | action: position.side === 'long' ? 'sell' : 'buy', 94 | units: position.units, 95 | status: 'created' 96 | } 97 | 98 | this.fillOrder(order, bars) 99 | } 100 | } 101 | 102 | sameSide(position, order) { 103 | return (position.side === 'long' && order.action === 'buy') || (position.side === 'short' && order.action === 'sell') 104 | } 105 | 106 | canFill(order: any, bar: any) { 107 | const fillPrice = order.limitPrice ?? order.price ?? bar.close 108 | const fillCost = fillPrice * order.units 109 | const fillCommision = this.comission * fillCost 110 | const p = this.getOpenPositions().find((p: any) => p.symbol === order.symbol) 111 | 112 | if (!p) { 113 | return this.getCash() >= (fillCost + fillCommision) 114 | } else { 115 | if (this.sameSide(p, order)) { 116 | return this.getCash() >= (fillCost + fillCommision) 117 | } else { 118 | const diffAmmount = (order.units - p.units) * bar.close 119 | 120 | if (diffAmmount > 0) { 121 | return this.getCash() >= diffAmmount + (diffAmmount * this.comission) 122 | } 123 | } 124 | } 125 | 126 | return true 127 | } 128 | 129 | fillOrder(order: any, bars: any) { 130 | const bar = bars[0] 131 | const fillPrice = order.limitPrice ?? order.price ?? bar.close 132 | const fillDate = bar.date 133 | const fillUnits = order.units 134 | const fillCost = fillPrice * fillUnits 135 | const fillCommision = this.comission * fillCost 136 | 137 | let data = { 138 | ...order, 139 | fillPrice, 140 | fillDate, 141 | fillUnits, 142 | fillCost, 143 | fillCommision, 144 | fillBar: this.barIndex, 145 | error: null, 146 | status: 'filled' 147 | } 148 | 149 | if (this.canFill(order, bar)) { 150 | 151 | this.eventHandler?.onOrder(data) 152 | const resultPositions = this.executeOrder(data) 153 | 154 | this.positions = this.positions.filter(p => p.closeDate).concat(resultPositions) 155 | 156 | return data 157 | } else { 158 | data = { 159 | ...order, 160 | error: 'Insufficient funds', 161 | status: 'rejected' 162 | } 163 | 164 | console.warn(`Cannot fill order ${data.symbol} at bar ${this.barIndex}, Required: ${fillCost + fillCommision}, Available: ${this.getCash()}`) 165 | 166 | this.eventHandler?.onOrder(data) 167 | return data 168 | } 169 | } 170 | 171 | fillOrders(orders: any) { 172 | return orders.sort(a => a.isClose ? -1 : 1).map((order: any) => this.fillOrder(order, this.bars[order.symbol])) 173 | } 174 | 175 | executeOrder(order: any) { 176 | const resultPositions = this.getOpenPositions().map(p => ({ ...p })) 177 | const p = resultPositions.find((p: any) => p.symbol === order.symbol) 178 | const today = this.bars[order.symbol][0] 179 | 180 | if (p) { 181 | if (this.sameSide(p, order)) { 182 | p.openPrice = (p.openPrice + order.fillPrice) / 2 183 | p.units += order.fillUnits 184 | 185 | this.changeCash(this.getCash() - (order.fillCost + order.fillCommision)) 186 | } else { 187 | if (floor(p.units, 6) > floor(order.fillUnits, 6)) { 188 | // Close part of the position 189 | p.units -= order.fillUnits 190 | 191 | const closedPart = helpers.position.closePosition(p, order) 192 | resultPositions.push(closedPart) 193 | 194 | this.changeCash(this.getCash() + (helpers.position.value(closedPart, today) - order.fillCommision)) 195 | this.eventHandler?.onPosition(p) 196 | } else { 197 | // Close the position 198 | p.closeDate = order.fillDate 199 | p.closePrice = order.fillPrice 200 | p.closeBar = order.fillBar 201 | 202 | this.changeCash(this.getCash() + (helpers.position.value(p, today) - order.fillCommision)) 203 | 204 | // Open a new position with the remaining units 205 | const diffAmmount = floor((order.fillUnits - p.units) * order.fillPrice, 2) 206 | if (diffAmmount > 2) { 207 | const newPosition = { ...helpers.position.openPosition(order), units: order.fillUnits - p.units } 208 | 209 | resultPositions.push(newPosition) 210 | this.changeCash(this.getCash() - (diffAmmount + (diffAmmount * this.comission))) 211 | this.eventHandler?.onPosition({ ...newPosition, isNew: true }) 212 | } 213 | 214 | } 215 | } 216 | 217 | this.eventHandler?.onPosition(p) 218 | } else { 219 | const newPosition = helpers.position.openPosition(order) 220 | resultPositions.push(newPosition) 221 | 222 | this.changeCash(this.getCash() - (order.fillCost + order.fillCommision)) 223 | this.eventHandler?.onPosition({ ...newPosition, isNew: true }) 224 | } 225 | 226 | return resultPositions 227 | } 228 | } 229 | 230 | export default Broker -------------------------------------------------------------------------------- /packages/backtest/src/core/strategy.ts: -------------------------------------------------------------------------------- 1 | import { Env, evalCode } from 'zplang' 2 | import { createJsEnv } from '@zapcli/core' 3 | import Broker from "./broker" 4 | 5 | 6 | class Strategy { 7 | code: string 8 | lang: string 9 | barIndex: number = 0 10 | broker: Broker 11 | bars: Record = {} 12 | env: any | null = null 13 | analyzers: any[] = [] 14 | startTime: number = 0 15 | endTime: number = 0 16 | verbose: boolean = false 17 | inputs: Record = {} 18 | 19 | constructor({ code, lang, verbose, inputs = {} }) { 20 | this.code = code 21 | this.lang = lang 22 | this.broker = new Broker() 23 | this.verbose = verbose 24 | this.broker.eventHandler = this 25 | this.inputs = inputs ?? {} 26 | } 27 | 28 | get currentBar() { 29 | return this.barIndex 30 | } 31 | 32 | get currentDate() { 33 | return Object.values(this.bars)[0][0].dateFormatted 34 | } 35 | 36 | get duration() { 37 | const inSeconds = (this.endTime - this.startTime) / 1000 38 | return inSeconds 39 | } 40 | 41 | setBars(bars) { 42 | this.bars = bars 43 | } 44 | 45 | setBarIndex(index) { 46 | this.barIndex = index 47 | } 48 | 49 | addAnalyzer(analyzer: any) { 50 | analyzer.setStrategy(this) 51 | 52 | if (analyzer.init(this)) { 53 | this.analyzers.push(analyzer) 54 | } 55 | } 56 | 57 | addAnalyzers(analyzers) { 58 | analyzers.forEach(analyzer => this.addAnalyzer(analyzer)) 59 | } 60 | 61 | getAnalyzer(name: string) { 62 | return this.analyzers.find(a => a.name === name) 63 | } 64 | 65 | start() { 66 | this.broker.setCash(10_000) 67 | this.broker.setCommision(0.00) 68 | 69 | this.analyzers.forEach(analyzer => analyzer.start?.()) 70 | this.startTime = performance.now() 71 | } 72 | 73 | end() { 74 | this.broker.closeAllPositions() 75 | this.analyzers.forEach(analyzer => analyzer.end?.()) 76 | this.endTime = performance.now() 77 | } 78 | 79 | createEnv() { 80 | switch (this.lang) { 81 | case 'js': 82 | this.env = createJsEnv(this.bars) 83 | this.env.barIndex = this.barIndex 84 | this.env.date = this.currentDate 85 | this.env.inputs = this.inputs 86 | 87 | this.env.setCash(this.broker.getCash()) 88 | this.env.setPositions(this.broker.getOpenPositions()) 89 | this.env.setOrders([]) 90 | break 91 | 92 | case 'zp': 93 | this.env = new Env({ bars: this.bars }) 94 | 95 | this.env.bind('inputs', this.inputs) 96 | this.env.bind('barIndex', this.currentBar) 97 | this.env.bind('date', this.currentDate) 98 | 99 | 100 | this.env.call('setCash', this.broker.getCash()) 101 | this.env.call('setPositions', this.broker.getOpenPositions()) 102 | this.env.call('setOrders', []) 103 | break 104 | 105 | default: 106 | throw new Error('Invalid language') 107 | } 108 | 109 | } 110 | 111 | prenext(context) { 112 | const { code, date } = context 113 | 114 | // set data to broker 115 | this.broker.setBarIndex(this.barIndex) 116 | this.broker.setBars(this.bars) 117 | 118 | // set env 119 | this.createEnv() 120 | 121 | // update time 122 | this.endTime = performance.now() 123 | 124 | // prenext analyzers 125 | this.analyzers.forEach(analyzer => analyzer.prenext?.()) 126 | } 127 | 128 | next(context) { 129 | const { code, date } = context 130 | 131 | // run zp code 132 | const { orders, stdout } = this.runCode(code) 133 | 134 | // execute orders 135 | const executedOrders = this.broker.fillOrders(orders) 136 | 137 | if (stdout && stdout.length > 0 && this.verbose) { 138 | console.log(stdout) 139 | } 140 | 141 | this.analyzers.forEach(analyzer => analyzer.next?.({ orders, executedOrders })) 142 | 143 | return executedOrders 144 | } 145 | 146 | private runZpCode(code: string) { 147 | if (!this.env) { 148 | throw new Error('Env is not created') 149 | } 150 | 151 | const start = performance.now() 152 | const result = evalCode(this.env, code) 153 | 154 | const stop = performance.now() 155 | const inSeconds = (stop - start) / 1000 156 | 157 | return { 158 | orders: this.env.call('getOrders'), 159 | result, 160 | stdout: this.env.stdout, 161 | time: inSeconds 162 | } 163 | } 164 | 165 | private runJsCode(code: string) { 166 | if (!this.env) { 167 | throw new Error('Env is not created') 168 | } 169 | 170 | const start = performance.now() 171 | 172 | const execFunc = new Function(code) 173 | const { run } = execFunc() 174 | 175 | // run code here 176 | const result = run.call(this.env) 177 | 178 | const stop = performance.now() 179 | const inSeconds = (stop - start) / 1000 180 | 181 | return { 182 | orders: this.env.getOrders(), 183 | result, 184 | stdout: this.env.stdout.join('\n'), 185 | time: inSeconds 186 | } 187 | } 188 | 189 | private runCode(code: string) { 190 | switch (this.lang) { 191 | case 'js': 192 | return this.runJsCode(code) 193 | 194 | case 'zp': 195 | return this.runZpCode(code) 196 | 197 | default: 198 | throw new Error('Invalid file extension. It should be .js or .zp') 199 | } 200 | } 201 | 202 | public onOrder(order) { 203 | this.analyzers.forEach(analyzer => analyzer.onOrder?.(order)) 204 | } 205 | 206 | public onPosition(position) { 207 | this.analyzers.forEach(analyzer => analyzer.onPosition?.(position)) 208 | } 209 | 210 | public onCash(oldCash, newCash) { 211 | this.analyzers.forEach(analyzer => analyzer.onCash?.(oldCash, newCash)) 212 | } 213 | } 214 | 215 | export default Strategy -------------------------------------------------------------------------------- /packages/backtest/src/index.ts: -------------------------------------------------------------------------------- 1 | export { default as Broker } from './core/broker' 2 | export { default as Strategy } from './core/strategy' 3 | 4 | export * as analyzers from './analyzers' -------------------------------------------------------------------------------- /packages/backtest/src/utils.ts: -------------------------------------------------------------------------------- 1 | 2 | export const floor = function (n: number, d: number) { 3 | const r = Math.pow(10, d) 4 | return Math.floor((n + Number.EPSILON) * r) / r 5 | } 6 | 7 | export const round = function (n: number, d: number) { 8 | const r = Math.pow(10, d) 9 | return Math.round((n + Number.EPSILON) * r) / r 10 | } 11 | 12 | export const currencyFormat = (value: number) => { 13 | const f = new Intl.NumberFormat('en-US', { 14 | style: 'currency', 15 | currency: 'USD', 16 | minimumFractionDigits: 2 17 | }) 18 | 19 | if (isNaN(value)) { 20 | return f.format(0) 21 | } 22 | 23 | return f.format(value) 24 | } -------------------------------------------------------------------------------- /packages/backtest/tsconfig.dts.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "noEmit": false, 5 | "declaration": true, 6 | "declarationDir": "./dist", 7 | "emitDeclarationOnly": true 8 | }, 9 | } -------------------------------------------------------------------------------- /packages/backtest/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Base */ 4 | "target": "esnext", 5 | "module": "commonjs", 6 | "moduleResolution": "node", 7 | "sourceMap": false, 8 | "esModuleInterop": true, 9 | "resolveJsonModule": true, 10 | "allowSyntheticDefaultImports": true, 11 | /* Strictness */ 12 | "strict": true, 13 | "noUnusedLocals": false, 14 | "noUnusedParameters": false, 15 | "noImplicitAny": false, 16 | /* Paths */ 17 | "baseUrl": ".", 18 | "outDir": "dist", 19 | "paths": { 20 | "@/*": [ 21 | "./src/*" 22 | ] 23 | } 24 | }, 25 | "ts-node": { 26 | "files": true 27 | }, 28 | "exclude": [ 29 | "node_modules" 30 | ], 31 | "include": [ 32 | "./src/**/*", 33 | "./tests/**/*" 34 | ] 35 | } -------------------------------------------------------------------------------- /packages/cli/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # @zapcli/cli 2 | 3 | ## 1.0.26 4 | 5 | ### Patch Changes 6 | 7 | - change reports for dd and positions 8 | - Updated dependencies 9 | - @zapcli/backtest@1.0.12 10 | - @zapcli/core@1.0.12 11 | 12 | ## 1.0.25 13 | 14 | ### Patch Changes 15 | 16 | - Updated dependencies 17 | - @zapcli/core@1.0.11 18 | - @zapcli/backtest@1.0.11 19 | 20 | ## 1.0.24 21 | 22 | ### Patch Changes 23 | 24 | - update zplang 25 | 26 | ## 1.0.23 27 | 28 | ### Patch Changes 29 | 30 | - Updated dependencies 31 | - @zapcli/core@1.0.10 32 | - @zapcli/backtest@1.0.10 33 | 34 | ## 1.0.22 35 | 36 | ### Patch Changes 37 | 38 | - add more functions 39 | - Updated dependencies 40 | - @zapcli/backtest@1.0.9 41 | - @zapcli/core@1.0.9 42 | 43 | ## 1.0.21 44 | 45 | ### Patch Changes 46 | 47 | - fix yahoo for stocks 48 | 49 | ## 1.0.20 50 | 51 | ### Patch Changes 52 | 53 | - fix short position 54 | - Updated dependencies 55 | - @zapcli/backtest@1.0.8 56 | - @zapcli/core@1.0.8 57 | 58 | ## 1.0.19 59 | 60 | ### Patch Changes 61 | 62 | - add yahoo and symbols 63 | - Updated dependencies 64 | - @zapcli/core@1.0.7 65 | - @zapcli/backtest@1.0.7 66 | 67 | ## 1.0.18 68 | 69 | ### Patch Changes 70 | 71 | - update dependencies 72 | 73 | ## 1.0.17 74 | 75 | ### Patch Changes 76 | 77 | - Updated dependencies 78 | - @zapcli/core@1.0.6 79 | - @zapcli/backtest@1.0.6 80 | 81 | ## 1.0.16 82 | 83 | ### Patch Changes 84 | 85 | - Updated dependencies 86 | - @zapcli/core@1.0.5 87 | - @zapcli/backtest@1.0.5 88 | 89 | ## 1.0.15 90 | 91 | ### Patch Changes 92 | 93 | - fix execute errors filename 94 | - Updated dependencies 95 | - @zapcli/core@1.0.4 96 | - @zapcli/backtest@1.0.4 97 | 98 | ## 1.0.12 99 | 100 | ### Patch Changes 101 | 102 | - add ability to select template when create a project 103 | 104 | ## 1.0.11 105 | 106 | ### Patch Changes 107 | 108 | - add option to store error in a file 109 | 110 | ## 1.0.10 111 | 112 | ### Patch Changes 113 | 114 | - feth latests data in end is undefined 115 | 116 | ## 1.0.9 117 | 118 | ### Patch Changes 119 | 120 | - ability to login user params 121 | 122 | ## 1.0.7 123 | 124 | ### Patch Changes 125 | 126 | - fix backtest command option 127 | 128 | ## 1.0.6 129 | 130 | ### Patch Changes 131 | 132 | - add ability to download with no prompts 133 | 134 | ## 1.0.5 135 | 136 | ### Patch Changes 137 | 138 | - add ability to select data provider 139 | 140 | ## 1.0.4 141 | 142 | ### Patch Changes 143 | 144 | - add backtest dir 145 | 146 | ## 1.0.3 147 | 148 | ### Patch Changes 149 | 150 | - add reports command 151 | - Updated dependencies 152 | - @zapcli/backtest@1.0.3 153 | - @zapcli/core@1.0.3 154 | 155 | ## 1.0.2 156 | 157 | ### Patch Changes 158 | 159 | - update drawdown analyzer 160 | - Updated dependencies 161 | - @zapcli/backtest@1.0.2 162 | - @zapcli/core@1.0.2 163 | 164 | ## 1.0.1 165 | 166 | ### Patch Changes 167 | 168 | - fix trading bugs 169 | - Updated dependencies 170 | - @zapcli/backtest@1.0.1 171 | - @zapcli/core@1.0.1 172 | -------------------------------------------------------------------------------- /packages/cli/README.md: -------------------------------------------------------------------------------- 1 |

2 |
3 | 4 | 5 | 6 |

7 | 8 |

ZapCli

9 |

The quickest way to write trading automations!

10 |

11 | ZapCli is an open-source trading engine. That main focus is to simplify the process of writing trading automations. 12 |

13 | 14 |

15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | GitHub 23 | 24 |
25 |
26 |

27 | 28 | 29 | ## ZapCLI 30 | 31 | - 💡 Intuitive 32 | - 🔌 Extensible 33 | - 🦾 Scalable 34 | - 📦 Extremely easy to use 35 | 36 | ## Documentation 37 | 38 | To learn more about ZapCLI read the documentation [here](https://zapcli.com/) 39 | 40 | ## Get Started 41 | 42 | ```shell 43 | npm i @zapcli/cli 44 | zapcli create MyProject 45 | zapcli backtest ./src/hello.zp 46 | ``` 47 | 48 | Useful links: 49 | 50 | - [Getting Started](https://zapcli.com/getting-started/) full guide. 51 | 52 | - [View on Github](https://github.com/ghalex/zapcli) 53 | 54 | ## License 55 | 56 | Copyright (c) 2021 [ZapCLI Contributors](https://github.com/ghalex/zapcli/graphs/contributors) 57 | Licensed under the [GNU General License](https://github.com/ghalex/zapcli/blob/HEAD/LICENSE). 58 | -------------------------------------------------------------------------------- /packages/cli/dev/backtests/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "startCash": 10000, 3 | "endCash": 10107.11, 4 | "pl": 107.11, 5 | "analyzers": { 6 | "returns": [ 7 | { 8 | "date": "2024-04-12", 9 | "value": 10000, 10 | "cash": 8234.5, 11 | "pl": 0 12 | }, 13 | { 14 | "date": "2024-04-15", 15 | "value": 10038.61, 16 | "cash": 8234.5, 17 | "pl": 38.61 18 | }, 19 | { 20 | "date": "2024-04-16", 21 | "value": 10071.7, 22 | "cash": 8234.5, 23 | "pl": 71.7 24 | }, 25 | { 26 | "date": "2024-04-17", 27 | "value": 10085.51, 28 | "cash": 8234.5, 29 | "pl": 85.51 30 | }, 31 | { 32 | "date": "2024-04-18", 33 | "value": 10095.11, 34 | "cash": 8234.5, 35 | "pl": 95.11 36 | }, 37 | { 38 | "date": "2024-04-19", 39 | "value": 10115.51, 40 | "cash": 8234.5, 41 | "pl": 115.51 42 | }, 43 | { 44 | "date": "2024-04-22", 45 | "value": 10107.11, 46 | "cash": 8234.5, 47 | "pl": 107.11 48 | } 49 | ], 50 | "drawdown": { 51 | "maxDrawDown": 0.08, 52 | "maxMoneyDown": 8.399999999999636, 53 | "maxDrawDownDuration": 1, 54 | "maxDrawDownStart": "2024-04-19", 55 | "maxDrawDownEnd": "2024-04-22", 56 | "longestDrawDownDuration": 1, 57 | "drawDowns": [ 58 | { 59 | "date": "2024-04-12", 60 | "max": 10000, 61 | "moneyDown": 0, 62 | "drawDown": 0, 63 | "len": 0 64 | }, 65 | { 66 | "date": "2024-04-15", 67 | "max": 10038.61, 68 | "moneyDown": 0, 69 | "drawDown": 0, 70 | "len": 0 71 | }, 72 | { 73 | "date": "2024-04-16", 74 | "max": 10071.7, 75 | "moneyDown": 0, 76 | "drawDown": 0, 77 | "len": 0 78 | }, 79 | { 80 | "date": "2024-04-17", 81 | "max": 10085.51, 82 | "moneyDown": 0, 83 | "drawDown": 0, 84 | "len": 0 85 | }, 86 | { 87 | "date": "2024-04-18", 88 | "max": 10095.11, 89 | "moneyDown": 0, 90 | "drawDown": 0, 91 | "len": 0 92 | }, 93 | { 94 | "date": "2024-04-19", 95 | "max": 10115.51, 96 | "moneyDown": 0, 97 | "drawDown": 0, 98 | "len": 0 99 | }, 100 | { 101 | "date": "2024-04-22", 102 | "max": 10115.51, 103 | "moneyDown": 8.399999999999636, 104 | "drawDown": 0.0008304079576807928, 105 | "len": 1 106 | } 107 | ] 108 | }, 109 | "trades": { 110 | "nbOfTrades": 1, 111 | "nbOfWinningTrades": 1, 112 | "nbOfLosingTrades": 0, 113 | "avgWinningTrade": 107.11, 114 | "avgLosingTrade": 0, 115 | "winRate": 1, 116 | "bestTrade": 107.11, 117 | "worstTrade": 0, 118 | "maxTradeDuration": 864000, 119 | "avgTradeDuration": 864000 120 | }, 121 | "positions": [ 122 | { 123 | "symbol": "AAPL", 124 | "openDate": "2024-04-12T04:00", 125 | "openPrice": 176.55, 126 | "openBar": 1, 127 | "closeDate": "2024-04-22T04:00", 128 | "closePrice": 165.84, 129 | "closeBar": 7, 130 | "units": 10, 131 | "side": "short", 132 | "stats": { 133 | "pl": 107.11, 134 | "value": 1872.61, 135 | "currentPrice": 165.84 136 | } 137 | } 138 | ] 139 | }, 140 | "file": "./dev/src/js/test.js", 141 | "dateGenerated": "2024-07-15T12:46:55.948Z" 142 | } -------------------------------------------------------------------------------- /packages/cli/dev/reports/report.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Report 6 | 7 | 28 | 29 | 30 | 31 |
32 |

Backtest Report

33 | 41 |

Date generated:

42 |

File:

43 |

Start Cash:

44 |

End Cash:

45 |
46 |
47 |
48 | 56 | 95 | 96 | 97 | -------------------------------------------------------------------------------- /packages/cli/dev/src/js/error.js: -------------------------------------------------------------------------------- 1 | const assets = ["ETH/USD"] 2 | const window = 1 3 | const settings = {} 4 | 5 | function run() { 6 | 7 | for (const symbol of assets) { 8 | this.buy(this.asset(symbol), 1) 9 | } 10 | 11 | thi.print(this.getOrders()) 12 | 13 | return { 14 | name: "Test" 15 | } 16 | 17 | } 18 | 19 | return { assets, window, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/hello-hold.js: -------------------------------------------------------------------------------- 1 | const assets = ["BTC/USD", "ETH/USD", "SOL/USD", "LINK/USD"] 2 | const window = 60 3 | const settings = {} 4 | 5 | function run() { 6 | const amount = this.getTotalCapital() / assets.length 7 | // this.print('Amount amount to buy: ', amount) 8 | 9 | // this.print('Bars: ', this.barIndex) 10 | // this.print(this.getPositions()) 11 | 12 | 13 | for (let symbol of assets) { 14 | //const ema30 = this.ema(30, symbol) 15 | // const close = this.asset(symbol).close 16 | 17 | //if (close > ema30) { 18 | // if (!this.hasPosition(symbol)) { 19 | this.buyAmount(this.asset(symbol), amount) 20 | // } 21 | //} 22 | } 23 | 24 | this.balance({ minAmount: 100 }) 25 | 26 | // this.print(this.date, this.getOrders()) 27 | 28 | // close positions if 29 | // under ema30 30 | // const positionsToClose = [] 31 | // for (let position of this.getPositions()) { 32 | // const ema30 = this.ema(30, position.symbol) 33 | // const close = this.asset(position.symbol).close 34 | 35 | // // && this.getOrder(position.symbol) === null 36 | // if (close < ema30) { 37 | // positionsToClose.push(position) 38 | // } 39 | // } 40 | 41 | // if (positionsToClose.length) { 42 | // this.closePositions(positionsToClose) 43 | // } 44 | 45 | // this.print(this.getOrders()) 46 | } 47 | 48 | return { assets, window, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/hello-no-balance.js: -------------------------------------------------------------------------------- 1 | const assets = ["ETH/USD"] 2 | const window = 1 3 | const settings = {} 4 | 5 | function run() { 6 | const amount = this.getCash() / assets.length 7 | // this.print('Amount amount to buy: ', amount) 8 | 9 | // this.print('Bars: ', this.barIndex) 10 | // this.print(this.getPositions()) 11 | 12 | 13 | for (let symbol of assets) { 14 | //const ema30 = this.ema(30, symbol) 15 | // const close = this.asset(symbol).close 16 | 17 | //if (close > ema30) { 18 | if (!this.hasPosition(symbol)) { 19 | this.buyAmount(this.asset(symbol), amount) 20 | } 21 | //} 22 | } 23 | 24 | // this.balance({ minAmount: 100 }) 25 | 26 | // this.print(this.date, this.getOrders()) 27 | 28 | // close positions if 29 | // under ema30 30 | // const positionsToClose = [] 31 | // for (let position of this.getPositions()) { 32 | // const ema30 = this.ema(30, position.symbol) 33 | // const close = this.asset(position.symbol).close 34 | 35 | // // && this.getOrder(position.symbol) === null 36 | // if (close < ema30) { 37 | // positionsToClose.push(position) 38 | // } 39 | // } 40 | 41 | // if (positionsToClose.length) { 42 | // this.closePositions(positionsToClose) 43 | // } 44 | 45 | // this.print(this.getOrders()) 46 | } 47 | 48 | return { assets, window, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/hello.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable @typescript-eslint/no-unused-vars */ 2 | 3 | const symbols = ["BTC/USD", "ETH/USD", "SOL/USD", "LINK/USD"] 4 | const window = 60 5 | const settings = { 6 | market: 'crypto' 7 | } 8 | 9 | function run() { 10 | const amount = this.getTotalCapital() / symbols.length 11 | // this.print('Amount amount to buy: ', amount) 12 | 13 | // this.print('Bars: ', this.barIndex) 14 | // this.print(this.getPositions()) 15 | 16 | 17 | for (let symbol of symbols) { 18 | const ema30 = this.ema(30, symbol) 19 | const close = this.asset(symbol).close 20 | 21 | if (close > ema30) { 22 | // if (!this.hasPosition(symbol)) { 23 | this.buyAmount(this.asset(symbol), amount) 24 | // } 25 | } 26 | } 27 | 28 | this.balance({ minAmount: 100 }) 29 | 30 | // this.print(this.date, this.getOrders()) 31 | 32 | // close positions if 33 | // under ema30 34 | const positionsToClose = [] 35 | for (let position of this.getPositions()) { 36 | const ema30 = this.ema(30, position.symbol) 37 | const close = this.asset(position.symbol).close 38 | 39 | // && this.getOrder(position.symbol) === null 40 | if (close < ema30) { 41 | positionsToClose.push(position) 42 | } 43 | } 44 | 45 | if (positionsToClose.length) { 46 | this.closePositions(positionsToClose) 47 | } 48 | 49 | this.print(this.getOrders()) 50 | } 51 | 52 | return { symbols, window, settings, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/hello2.js: -------------------------------------------------------------------------------- 1 | const symbols = ["ETH/USD", "BTC/USD", "SOL/USD"] 2 | const window = 60 3 | const settings = {} 4 | 5 | function run() { 6 | 7 | for (const symbol of symbols) { 8 | const ema30 = this.ema(30, symbol) 9 | const amount = this.getCash() / symbols.length 10 | 11 | if (!this.hasPosition(symbol) && this.crossover(this.assets(symbol, 2), ema30)) { 12 | //this.buyAmount(this.asset(symbol), amount, { limitPrice: ema30 }) 13 | this.buyAmount(this.asset(symbol), amount, { limitPrice: ema30 }) 14 | } 15 | 16 | const pos = this.getPosition(symbol) 17 | if (pos && this.crossunder(this.assets(symbol, 2), ema30)) { 18 | this.closePositions([pos], [ema30]) 19 | } 20 | } 21 | 22 | this.print(this.getOrders()) 23 | } 24 | 25 | return { symbols, window, settings, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/hold-ema.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @typedef {import('../types').Env} Env 3 | */ 4 | 5 | const symbols = ["AAPL", "MSFT", "AMZN", "GOOGL", "TSLA", "SNOW", "PYPL", "NFLX", "META", "NVDA"] 6 | const window = 100 7 | const settings = {} 8 | 9 | /** 10 | * @this {Env} 11 | */ 12 | function run() { 13 | for (let symbol of symbols) { 14 | const ema30 = this.ema(50, symbol) 15 | const close = this.asset(symbol).close 16 | 17 | if (close > ema30) { 18 | if (!this.hasPosition(symbol)) { 19 | this.buyAmount(this.asset(symbol), 1000) 20 | } 21 | } else { 22 | if (this.hasPosition(symbol)) { 23 | this.closePositions([this.getPosition(symbol)]) 24 | } 25 | } 26 | } 27 | } 28 | 29 | return { symbols, window, settings, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/hold.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @typedef {import('../types').Env} Env 3 | */ 4 | 5 | const symbols = ["AAPL", "MSFT", "AMZN", "GOOGL", "TSLA", "SNOW", "PYPL", "NFLX", "META", "NVDA"] 6 | const window = 100 7 | const settings = {} 8 | 9 | /** 10 | * @this {Env} 11 | */ 12 | function run() { 13 | for (let symbol of symbols) { 14 | //const ema30 = this.ema(30, symbol) 15 | // const close = this.asset(symbol).close 16 | 17 | //if (close > ema30) { 18 | // if (!this.hasPosition(symbol)) { 19 | if (this.barIndex === 1) { 20 | this.buyAmount(this.asset(symbol), 1000) 21 | } 22 | // } 23 | //} 24 | } 25 | } 26 | 27 | return { symbols, window, settings, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/ride-momentum-balance.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @typedef {import('../types').Env} Env 3 | */ 4 | 5 | const symbols = ["AAPL", "MSFT", "AMZN", "GOOGL", "TSLA", "SNOW", "PYPL", "NFLX", "META", "NVDA", "MA"] 6 | const window = 100 7 | const settings = {} 8 | 9 | /** 10 | * @this {Env} 11 | */ 12 | function run() { 13 | const topX = (count = 2) => { 14 | return symbols 15 | .map(s => { 16 | return { 17 | asset: this.asset(s), 18 | mm: this.momentum(50, s), 19 | ema: this.ema(30, s) 20 | } 21 | }) 22 | .filter(x => x.asset.close > x.ema) 23 | .sort((a, b) => b.mm - a.mm) 24 | .slice(0, count) 25 | } 26 | 27 | // Only trade if QQQ is above EMA 28 | const canTrade = () => { 29 | const QQQ = this.asset('QQQ') 30 | const emaQQQ = this.ema(50, 'QQQ') 31 | 32 | return QQQ.close > emaQQQ 33 | // return true 34 | } 35 | 36 | if (canTrade()) { 37 | const topSymbols = topX(2).map(s => s.asset.symbol) 38 | const amount = Math.floor(0.5 * (this.getTotalCapital() - 200)) 39 | 40 | for (let symbol of topSymbols) { 41 | this.buyAmount(this.asset(symbol), amount) 42 | } 43 | 44 | // Balance the portfolio 45 | this.balance({ minAmount: 200 }) 46 | } else { 47 | this.print('QQQ is below EMA, not buying') 48 | this.closePositions() 49 | } 50 | 51 | this.print(this.getOrders()) 52 | } 53 | 54 | return { symbols: [...symbols, "QQQ", "SPY"], window, settings, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/ride-momentum.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @typedef {import('../types').Env} Env 3 | */ 4 | 5 | const symbols = ["AAPL", "MSFT", "AMZN", "GOOGL", "TSLA", "SNOW", "PYPL", "NFLX", "META", "NVDA", "MA"] 6 | const window = 100 7 | const settings = {} 8 | 9 | /** 10 | * @this {Env} 11 | */ 12 | function run() { 13 | 14 | // Get top X momentum assets 15 | const topX = (count = 2) => { 16 | return symbols 17 | .map(s => { 18 | return { 19 | asset: this.asset(s), 20 | mm: this.momentum(50, s), 21 | ema: this.ema(30, s) 22 | } 23 | }) 24 | .filter(x => x.asset.close > x.ema) 25 | .sort((a, b) => b.mm - a.mm) 26 | .slice(0, count) 27 | } 28 | 29 | // Only trade if QQQ is above EMA 30 | const canTrade = () => { 31 | const QQQ = this.asset('QQQ') 32 | const emaQQQ = this.ema(50, 'QQQ') 33 | 34 | return QQQ.close > emaQQQ 35 | // return true 36 | } 37 | 38 | 39 | if (canTrade()) { 40 | const topSymbols = topX(2).map(s => s.asset.symbol) 41 | const newPositions = topSymbols.filter(s => this.getPositions().find(p => p.symbol === s) === undefined) 42 | const positionsToClose = this.getPositions().filter(p => !topSymbols.includes(p.symbol)) 43 | 44 | let freeCash = this.getCash() 45 | 46 | // Close positions 47 | if (positionsToClose.length > 0) { 48 | const value = this.sum(this.closePositions(positionsToClose).map(o => o.value)) 49 | freeCash += value 50 | } 51 | 52 | // Open new positions 53 | newPositions.forEach(symbol => { 54 | const amountPerPosition = Math.floor(freeCash / newPositions.length) 55 | this.buyAmount(this.asset(symbol), amountPerPosition, { round: true }) 56 | }) 57 | 58 | this.print("Top symbols:", topSymbols) 59 | } else { 60 | this.print('QQQ is below EMA, not buying closing all') 61 | this.closePositions() 62 | } 63 | 64 | this.print("Orders:", this.getOrders()) 65 | } 66 | 67 | return { symbols: [...symbols, "QQQ"], window, settings, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/js/test.js: -------------------------------------------------------------------------------- 1 | const symbols = ["AAPL"] 2 | const window = 1 3 | const settings = {} 4 | 5 | function run() { 6 | 7 | const LINK = this.asset("LINK/USD") 8 | const [pos] = this.getPositions() 9 | 10 | this.print(this.today()) 11 | // this.print(LINK) 12 | this.print(pos) 13 | this.print(new Date(pos.openDate)) 14 | this.print(this.getPositionInfo(pos)) 15 | 16 | } 17 | 18 | return { symbols, window, settings, run } -------------------------------------------------------------------------------- /packages/cli/dev/src/zp/crossover.zp: -------------------------------------------------------------------------------- 1 | 2 | (def symbols [ 3 | "ETH/USD" 4 | ]) 5 | 6 | (loop symbol in symbols 7 | (def emaVal (ema 30 symbol)) 8 | (def amount (/ (getCash) (size symbols))) 9 | 10 | (if (and 11 | (crossover {symbol, 2 bars} emaVal) 12 | (not (hasPosition symbol)) 13 | ) 14 | 15 | ;; over ema & no position 16 | (buyAmount {symbol} amount) 17 | ) 18 | 19 | (if (and 20 | (crossunder {symbol, 2 bars} emaVal) 21 | (hasPosition symbol) 22 | ) 23 | 24 | ;; under ema & has position 25 | (closePositions [(getPosition symbol)]) 26 | ) 27 | ) 28 | 29 | -------------------------------------------------------------------------------- /packages/cli/dev/src/zp/error.zp: -------------------------------------------------------------------------------- 1 | ;; Loops a list a symbols and buys 1 share of each 2 | ;; #pragma timeframe 15 3 | 4 | (def symbols [ 5 | "AAPL", 6 | "MSFT" 7 | ]) 8 | 9 | (errrorfn) 10 | (loop symbol in symbols 11 | (buy {symbol} 1) 12 | ) 13 | 14 | ;; (print "barIndex" (barIndex )) 15 | ;; (print "date" (date )) 16 | -------------------------------------------------------------------------------- /packages/cli/dev/src/zp/hello.zp: -------------------------------------------------------------------------------- 1 | #pragma version 0.1.0 2 | #pragma market "stocks" 3 | ;; #pragma timeframe 15 4 | 5 | (def symbols [ 6 | "AAPL", 7 | "MSFT" 8 | ]) 9 | 10 | (sma 5 "AAPL") 11 | 12 | (loop symbol in symbols 13 | (buy {symbol} 1) 14 | ) 15 | 16 | {AAPL, 2 days ago} 17 | 18 | (print "inputs assets" (inputs/assets )) 19 | (print "price AAPL:" (:close {AAPL})) 20 | (print "cash:" (getCash)) 21 | (print "total:" (getTotalCapital)) 22 | (print "positions:" (getPositions)) -------------------------------------------------------------------------------- /packages/cli/dev/src/zp/test.zp: -------------------------------------------------------------------------------- 1 | ;; Loops a list a symbols and buys 1 share of each 2 | ;; #pragma timeframe 15 3 | 4 | (def symbols [ 5 | "AAPL", 6 | "MSFT" 7 | ]) 8 | 9 | 10 | (loop symbol in symbols 11 | (buy {symbol} 1) 12 | ) 13 | 14 | (print "barIndex" (barIndex )) 15 | (print "date" (date )) 16 | -------------------------------------------------------------------------------- /packages/cli/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@zapcli/cli", 3 | "version": "1.0.26", 4 | "description": "A CLI tool for backtesting and trading", 5 | "main": "dist/zapcli.es.mjs", 6 | "module": "dist/zapcli.es.mjs", 7 | "files": [ 8 | "dist", 9 | "package.json", 10 | "CHANGELOG.md" 11 | ], 12 | "bin": { 13 | "zapcli": "dist/zapcli.es.mjs" 14 | }, 15 | "engines": { 16 | "node": ">=20.0.0" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/ghalex/zapcli" 21 | }, 22 | "scripts": { 23 | "dev": "tsx src/index.ts", 24 | "start": "node dist/index.js", 25 | "lint": "tsc", 26 | "build": "rm -rf ./dist/ && rollup -c --bundleConfigAsCjs", 27 | "prepack": "pnpm build" 28 | }, 29 | "keywords": [], 30 | "author": "", 31 | "license": "ISC", 32 | "devDependencies": { 33 | "@rollup/plugin-commonjs": "^26.0.1", 34 | "@rollup/plugin-json": "^6.1.0", 35 | "@rollup/plugin-node-resolve": "^15.2.3", 36 | "@types/cli-color": "^2.0.6", 37 | "@types/cli-spinner": "^0.2.3", 38 | "@types/configstore": "^6.0.2", 39 | "@types/figlet": "^1.5.8", 40 | "@types/listr": "^0.14.9", 41 | "@types/node": "^20.14.9", 42 | "@types/prompts": "^2.4.9", 43 | "@types/pug": "^2.0.10", 44 | "@types/ramda": "^0.30.0", 45 | "@types/shelljs": "^0.8.15", 46 | "@types/signale": "^1.4.7", 47 | "esbuild": "^0.21.5", 48 | "nodemon": "^3.1.4", 49 | "rollup": "^4.18.0", 50 | "rollup-plugin-dts": "^6.1.1", 51 | "rollup-plugin-esbuild": "^6.1.1", 52 | "rollup-plugin-node-externals": "^7.1.2", 53 | "ts-node": "^10.9.2", 54 | "tslib": "^2.6.3", 55 | "tsx": "^4.15.7", 56 | "typescript": "^5.5.2" 57 | }, 58 | "dependencies": { 59 | "@zapant/calendar": "^1.0.1", 60 | "@zapcli/backtest": "workspace:*", 61 | "@zapcli/core": "workspace:*", 62 | "axios": "^1.7.2", 63 | "cli-color": "^2.0.4", 64 | "commander": "^12.1.0", 65 | "configstore": "^6.0.0", 66 | "csvtojson": "^2.0.10", 67 | "dayjs": "^1.11.11", 68 | "figlet": "^1.7.0", 69 | "fs-extra": "^11.2.0", 70 | "ora": "^8.0.1", 71 | "prompts": "^2.4.2", 72 | "pug": "^3.0.3", 73 | "ramda": "^0.30.1", 74 | "shelljs": "^0.8.5", 75 | "voca": "^1.4.1", 76 | "zplang": "^1.0.57" 77 | } 78 | } -------------------------------------------------------------------------------- /packages/cli/rollup.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | const esbuild = require('rollup-plugin-esbuild').default 3 | const json = require('@rollup/plugin-json') 4 | const commonjs = require('@rollup/plugin-commonjs') 5 | 6 | const name = 'zapcli' 7 | 8 | module.exports = [ 9 | { 10 | input: 'src/index.ts', 11 | external: [ 12 | 'figlet', 13 | 'commander', 14 | 'configstore', 15 | 'ora', 16 | 'zlib', 17 | 'prompts', 18 | 'shelljs', 19 | 'ramda', 20 | 'axios', 21 | 'cli-color', 22 | 'node:fs', 23 | 'node:path', 24 | 'node:os', 25 | 'node:zlib', 26 | 'zplang', 27 | '@zapcli/core', 28 | '@zapcli/backtest', 29 | '@zapant/calendar', 30 | 'dayjs', 31 | 'voca', 32 | 'pug', 33 | 'fs-extra' 34 | ], 35 | plugins: [ 36 | esbuild(), 37 | json(), 38 | commonjs() 39 | ], 40 | output: [ 41 | { 42 | file: path.resolve(__dirname, `dist/${name}.es.mjs`), 43 | format: 'es' 44 | } 45 | ] 46 | } 47 | ] -------------------------------------------------------------------------------- /packages/cli/src/api/cache.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'node:fs' 2 | import * as path from 'node:path' 3 | import { gzipSync, gunzipSync } from 'node:zlib' 4 | import clc from 'cli-color' 5 | import dayjs from 'dayjs' 6 | import calendar from '@zapant/calendar' 7 | 8 | export default (config) => { 9 | 10 | /** 11 | * Parse symbol 12 | * @param symbol 13 | * @returns 14 | */ 15 | const parseSymbol = (symbol: string) => { 16 | return symbol.replace(/\//g, '_') 17 | } 18 | 19 | const getAll = (symbol: string, resolution?: number) => { 20 | const dataDir = config.dataDir 21 | const key = `${parseSymbol(symbol)}_${resolution ?? 1440}` 22 | const filePath = path.join(dataDir, key + '.data') 23 | 24 | if (!fs.existsSync(filePath)) { 25 | return [] 26 | } 27 | 28 | try { 29 | const fileContents = fs.readFileSync(filePath) 30 | const buffer = gunzipSync(fileContents) 31 | 32 | 33 | const data = JSON.parse(buffer.toString('utf8')) 34 | return data 35 | } catch (err: any) { 36 | throw new Error(`Error reading compressed data from ${filePath}: ${err.message}`) 37 | } 38 | } 39 | /** 40 | * Get from cache 41 | * @param symbol 42 | * @param window 43 | * @param resolution 44 | * @param end 45 | * @returns 46 | */ 47 | const get = (symbol: string, window: number, resolution: number = 1440, end?: string) => { 48 | const allData = getAll(symbol, resolution) 49 | const date = end ? dayjs(end) : dayjs() 50 | const isStocks = !symbol.includes('/') 51 | const resolutionMap: Record = { 52 | 1440: 'day', 53 | 240: 'hour', 54 | 60: 'hour', 55 | 30: 'minute', 56 | 15: 'minute', 57 | 5: 'minute', 58 | } 59 | 60 | let fromDate = date.endOf(resolutionMap[resolution]) 61 | 62 | // get data from specific date 63 | const index = allData.findIndex(x => x.date <= fromDate.valueOf()) 64 | const data = allData.slice(index) 65 | 66 | if (isStocks) { 67 | fromDate = dayjs(calendar.getDaysUntil(fromDate.toDate(), 1, resolution)?.[0].date) 68 | } 69 | 70 | if (data.length === 0) { 71 | return [] 72 | } 73 | 74 | if (index === 0) { 75 | if (!fromDate.isSame(dayjs(data[0].date), resolutionMap[resolution])) { 76 | return [] 77 | } 78 | } 79 | 80 | if (index < 0) { 81 | return [] 82 | } 83 | 84 | if (data.length < window) { 85 | return []; 86 | } 87 | 88 | return data.slice(0, window) 89 | } 90 | 91 | const canCombine = (oldData: any, newData: any) => { 92 | // Find the date range of oldData 93 | const oldDataDates = oldData.map(item => item.date) 94 | const oldMinDate = Math.min(...oldDataDates) 95 | const oldMaxDate = Math.max(...oldDataDates) 96 | 97 | // Find the date range of newData 98 | const newDataDates = newData.map(item => item.date) 99 | const newMinDate = Math.min(...newDataDates) 100 | const newMaxDate = Math.max(...newDataDates) 101 | 102 | if (oldMaxDate < newMinDate || newMaxDate < oldMinDate) { 103 | return false 104 | } 105 | 106 | return true 107 | } 108 | 109 | const combineData = (oldData: any, newData: any) => { 110 | if (!canCombine(oldData, newData)) return newData 111 | const dataMap = new Map() 112 | 113 | // Add all entries from oldData to the map 114 | oldData.forEach(item => { 115 | dataMap.set(item.date, { ...item }) 116 | }) 117 | 118 | // Add or merge entries from newData to the map 119 | newData.forEach(item => { 120 | if (!dataMap.has(item.date)) { 121 | dataMap.set(item.date, { ...item }) 122 | } 123 | }) 124 | 125 | return Array.from(dataMap.values()).sort((a, b) => b.date - a.date) 126 | } 127 | 128 | /** 129 | * Save to cache 130 | * @param symbol 131 | * @param resolution 132 | * @param end 133 | * @param data 134 | * @returns 135 | */ 136 | const save = async (symbol: string, resolution: number, newData: any) => { 137 | const dataDir = config.dataDir 138 | const oldData = getAll(symbol, resolution) 139 | const data = combineData(oldData, newData) 140 | const key = `${parseSymbol(symbol)}_${resolution ?? 1440}` 141 | 142 | const filePath = path.join(dataDir, key + '.data') 143 | const jsonString = JSON.stringify(data, null, 2) 144 | const buffer = Buffer.from(jsonString, 'utf8') 145 | 146 | if (!fs.existsSync(dataDir)) { 147 | fs.mkdirSync(dataDir, { recursive: true }) 148 | } 149 | 150 | try { 151 | const compressedBuffer = gzipSync(buffer) 152 | fs.writeFileSync(filePath, compressedBuffer) 153 | 154 | const size = compressedBuffer.length; 155 | const kiloBytes = size / 1024; 156 | console.log(`→ Data for ${clc.bold.green(symbol)} symbol was saved successfully ${clc.green(`(${kiloBytes.toFixed(2)} KB)`)}`); 157 | 158 | return filePath; 159 | } catch (err: any) { 160 | console.error(`Error writing compressed data to ${filePath}: ${err.message}`); 161 | throw err; 162 | } 163 | } 164 | 165 | return { get, getAll, save } 166 | } -------------------------------------------------------------------------------- /packages/cli/src/api/code.ts: -------------------------------------------------------------------------------- 1 | import { Env, evalCode } from 'zplang' 2 | import { uniq } from 'ramda' 3 | import * as fs from 'node:fs' 4 | import * as path from 'node:path' 5 | import { createJsEnv } from '@zapcli/core' 6 | 7 | export default () => { 8 | /** 9 | * Run Code 10 | * @param code 11 | * @param bars 12 | * @returns 13 | */ 14 | const runZpCode = (code: string, bars, inputs: any = {}, data = {}) => { 15 | const start = performance.now() 16 | 17 | const zpEnv = new Env({ bars }) 18 | zpEnv.bind('inputs', inputs) 19 | zpEnv.bind('barIndex', 1) 20 | zpEnv.bind('date', new Date(Object.values(bars)?.[0]?.[0].date)) 21 | 22 | zpEnv.call('setCash', inputs.cash ?? inputs.initialCapital ?? 10_000) 23 | zpEnv.call('setPositions', inputs.openPositions ?? []) 24 | 25 | let result = {} 26 | let error = null 27 | 28 | try { 29 | result = evalCode(zpEnv, code) 30 | } catch (err: any) { 31 | error = err.message 32 | } 33 | 34 | const stop = performance.now() 35 | const inSeconds = (stop - start) / 1000 36 | 37 | return { 38 | orders: zpEnv.call('getOrders'), 39 | result, 40 | error, 41 | stdout: zpEnv.stdout, 42 | time: inSeconds 43 | } 44 | } 45 | 46 | const runJsCode = (code: string, bars, inputs: any = {}, data: any = {}) => { 47 | const start = performance.now() 48 | const env: any = createJsEnv(bars) 49 | 50 | env.inputs = inputs 51 | env.barIndex = 1 52 | env.date = new Date(Object.values(bars)?.[0]?.[0].date) 53 | 54 | env.setCash(inputs.cash ?? inputs.initialCapital ?? 10_000) 55 | env.setPositions(inputs.openPositions ?? []) 56 | 57 | const execFunc = new Function(code) 58 | const { run } = execFunc() 59 | 60 | // run code here 61 | const result = run.call(env) 62 | 63 | 64 | const stop = performance.now() 65 | const inSeconds = (stop - start) / 1000 66 | 67 | return { 68 | orders: env.getOrders(), 69 | result: result ?? {}, 70 | stdout: env.stdout.join('\n'), 71 | time: inSeconds 72 | } 73 | } 74 | 75 | const runCode = (code: string, lang: string, bars: any, inputs: any = {}, data: any = {}) => { 76 | switch (lang) { 77 | case 'js': 78 | return runJsCode(code, bars, inputs, data) 79 | 80 | case 'zp': 81 | return runZpCode(code, bars, inputs, data) 82 | 83 | default: 84 | throw new Error('Invalid file extension. It should be .js or .zp') 85 | } 86 | } 87 | 88 | /** 89 | * Get Symbols 90 | * @param code 91 | * @param openPositions 92 | * @returns 93 | */ 94 | const getZpRequirements = (code: string, openPositions: any = [], inputs: any = {}) => { 95 | const metaEnv = new Env({ isMeta: true }) 96 | metaEnv.bind('barIndex', 1) 97 | metaEnv.bind('date', new Date()) 98 | metaEnv.bind('inputs', inputs) 99 | metaEnv.call('setCash', inputs.cash ?? inputs.initialCapital ?? 10_000) 100 | 101 | // Set positions 102 | metaEnv.call('setPositions', [...openPositions]) 103 | 104 | // try { 105 | evalCode(metaEnv, code) 106 | 107 | const settings = metaEnv.getPragma() 108 | const allOpenPositions = [...openPositions, ...(settings.openPositions ?? [])] as any 109 | const assets: Record = metaEnv.getAssets() 110 | const maxAssets = [...Object.values(assets)] 111 | const symbols = uniq([...Object.keys(assets), ...allOpenPositions.map(p => p.symbol)]) 112 | const maxWindow = maxAssets.length > 0 ? Math.max(...maxAssets) : 1 113 | 114 | return { symbols, maxWindow, settings } 115 | // } catch (err: any) { 116 | // throw new Error('Requirements error, cannot eval meta env.') 117 | // } 118 | } 119 | 120 | function getJsRequirements(code: string, openPositions: any = [], inputs: any = {}) { 121 | const execFunc = new Function(code) 122 | const res = execFunc() 123 | const codeSymbols = res.symbols ?? res.assets ?? [] 124 | const inputsSymbols = inputs.symbols ?? inputs.assets ?? [] 125 | 126 | const symbols = uniq([ 127 | ...uniq([...codeSymbols, ...inputsSymbols]), 128 | ...openPositions.map(p => p.symbol), 129 | ...(inputs.openPositions?.map(p => p.symbol) ?? []) 130 | ]) 131 | 132 | return { symbols, maxWindow: res.window ?? 1, settings: res.settings ?? {} } 133 | } 134 | 135 | const getRequirements = (code: string, lang: string, openPositions: any, inputs: any = {}) => { 136 | switch (lang) { 137 | case 'js': 138 | return getJsRequirements(code, openPositions, inputs) 139 | 140 | case 'zp': 141 | return getZpRequirements(code, openPositions, inputs) 142 | 143 | default: 144 | throw new Error('Invalid file extension. It should be .js or .zp') 145 | } 146 | } 147 | 148 | /** 149 | * Read Code 150 | * @param fileName 151 | * @returns 152 | */ 153 | const readCode = (fileName: string) => { 154 | const filePath = path.join(process.cwd(), fileName) 155 | 156 | if (!fs.existsSync(filePath)) { 157 | throw new Error(`File "${fileName}" does not exist`) 158 | } 159 | 160 | return fs.readFileSync(filePath, 'utf8') 161 | } 162 | 163 | return { runCode, getRequirements, readCode } 164 | } -------------------------------------------------------------------------------- /packages/cli/src/api/data.ts: -------------------------------------------------------------------------------- 1 | import clc from 'cli-color' 2 | import Axios, { type AxiosInstance } from 'axios' 3 | import ora from 'ora' 4 | import prompts from 'prompts' 5 | import cache from './cache' 6 | import storage from '../storage' 7 | import dayjs from 'dayjs' 8 | import csv from 'csvtojson' 9 | import calendar from '@zapant/calendar' 10 | 11 | interface DataDownloadOptions { 12 | resolution?: number 13 | end?: string 14 | auto?: boolean 15 | } 16 | 17 | export default (config) => { 18 | const axios: AxiosInstance = Axios.create({ 19 | baseURL: config.apiUrl ?? 'https://zapant.com/api', 20 | timeout: 80000, 21 | headers: { 22 | 'Content-Type': 'application/json' 23 | } 24 | }) 25 | 26 | 27 | const yahooAxios: AxiosInstance = Axios.create({ 28 | baseURL: 'https://query1.finance.yahoo.com/v7/finance/download', 29 | timeout: 80000 30 | }) 31 | 32 | /** 33 | * Download bars uzing zapant provider 34 | * @param symbols 35 | * @param window 36 | * @param resolution 37 | * @param end 38 | * @returns 39 | */ 40 | const downloadZapant = async (symbols: string[], window: number, options: DataDownloadOptions) => { 41 | if (!storage.get('accessToken')) { 42 | throw new Error('You must be logged in to download data. Please run `zapcli login` command.') 43 | } 44 | 45 | const { resolution, end } = options 46 | 47 | try { 48 | const params = { 49 | symbols: symbols.join(','), 50 | window, 51 | resolution: resolution ?? 1440, 52 | end: end && resolution?.toString() === '1440' ? dayjs(end).endOf('D').toISOString() : end 53 | } 54 | 55 | const { data } = await axios.get('/bars', { 56 | params, 57 | headers: { 58 | Authorization: `Bearer ${storage.get('accessToken')}` 59 | } 60 | }) 61 | 62 | // console.log(`${clc.green('✔ Success:')} Data was downloaded successfully`) 63 | return data 64 | 65 | } catch (e: any) { 66 | if (e.response) { 67 | if (e.response.status === 401) { 68 | throw new Error('You must be logged in to download data. Please run `zapcli login` command.') 69 | } 70 | 71 | throw new Error(e.response.data.message) 72 | } else if (e.request) { 73 | throw new Error('Request error') 74 | } else { 75 | throw new Error(e.message) 76 | } 77 | } 78 | } 79 | 80 | /** 81 | * Download bars uzing Yahoo Finance provider 82 | * @param symbols 83 | * @param window 84 | * @param resolution 85 | * @param end 86 | * @returns 87 | */ 88 | const downloadYahoo = async (symbols: string[], window: number, options: DataDownloadOptions) => { 89 | const { resolution, end } = options 90 | const resolutionMap = { 91 | 1440: '1d', 92 | 90: '90m', 93 | 60: '60m', 94 | 30: '30m', 95 | 15: '15m', 96 | 5: '5m', 97 | } 98 | 99 | if (resolution && !resolutionMap[resolution]) { 100 | throw new Error(`${resolution} resolution not supported`) 101 | } 102 | 103 | console.log(symbols, window + 1, resolution) 104 | // console.log(calendar.getDaysUntil(dayjs().toDate(), , resolution)) 105 | 106 | const interval = resolution ? resolutionMap[resolution] : '1d' 107 | const isCrypto = symbols.some(s => s.includes('/')) 108 | const endDate = end ? dayjs(end).add(1, 'days').unix() : dayjs().unix() 109 | const startDate = isCrypto 110 | ? dayjs.unix(endDate).subtract(window, 'days').unix() 111 | : dayjs( 112 | calendar.getDaysUntil(dayjs.unix(endDate).toDate(), window + 1, resolution)?.[0]?.date 113 | ).unix() 114 | 115 | const promises = symbols.map(async (symbol) => { 116 | const formattedSymbol = symbol.replace('/', '-') 117 | const url = `/${formattedSymbol}?period1=${startDate}&period2=${endDate}&interval=${interval}&events=history` 118 | const response = await yahooAxios.get(url) 119 | const json = await csv().fromString(response.data) 120 | return { 121 | symbol, 122 | bars: json.map(bar => ({ 123 | symbol, 124 | open: parseFloat(bar.Open), 125 | high: parseFloat(bar.High), 126 | low: parseFloat(bar.Low), 127 | close: parseFloat(bar.Close), 128 | volume: parseFloat(bar.Volume), 129 | date: dayjs(bar.Date).valueOf(), 130 | dateFormatted: dayjs(bar.Date).toISOString() 131 | })).reverse() 132 | } 133 | }) 134 | 135 | const data = await Promise.all(promises) 136 | const formatted = data.reduce((acc, curr) => { 137 | acc[curr.symbol] = curr.bars 138 | return acc 139 | }, {}) 140 | return formatted 141 | } 142 | 143 | const download = async (provider: string, symbols: string[], window: number | any, options: DataDownloadOptions) => { 144 | switch (provider) { 145 | case 'zapant': 146 | return downloadZapant(symbols, parseInt(window), options) 147 | case 'yahoo': 148 | return downloadYahoo(symbols, parseInt(window), options) 149 | default: 150 | throw new Error('Invalid provider') 151 | } 152 | } 153 | 154 | /** 155 | * Get data from cache or download 156 | * from provider 157 | * @param symbol 158 | * @param window 159 | * @param resolution 160 | * @param end 161 | * @returns 162 | */ 163 | const downloadBars = async (symbols: string[], maxWindow: number, options: DataDownloadOptions) => { 164 | let bars = {} 165 | const dataDir = config.dataDir 166 | const { resolution, end, auto } = options 167 | let missing: string[] = [] 168 | 169 | // if end is undefined always fetch latest price 170 | if (end) { 171 | for (const s of symbols) { 172 | const cachedData = await cache(config).get(s, maxWindow, resolution, end) 173 | 174 | if (cachedData.length === 0) { 175 | missing.push(s) 176 | } else { 177 | bars[s] = cachedData 178 | } 179 | } 180 | } else { 181 | missing = [...symbols] 182 | } 183 | 184 | if (missing.length > 0) { 185 | console.log(`You need to download data (${maxWindow} bars) for the following symbols: [ ${clc.bold.green(missing.join(', '))} ] `) 186 | 187 | const response = auto ? { value: true } : await prompts({ 188 | type: 'toggle', 189 | name: 'value', 190 | message: 'Do you want to download the missing data?', 191 | initial: true, 192 | active: 'yes', 193 | inactive: 'no' 194 | }) 195 | 196 | if (response.value) { 197 | const provider = auto ? { value: config.dataProvider } : await prompts({ 198 | type: 'select', 199 | name: 'value', 200 | message: 'Select data provider', 201 | choices: [ 202 | { title: 'Zapant', value: 'zapant' }, 203 | { title: 'Yahoo', value: 'yahoo' } 204 | ] 205 | }) 206 | 207 | const spinner = ora(`Downloading data for [ ${clc.bold.green(missing.join(', '))} ]`) 208 | spinner.start() 209 | 210 | try { 211 | const data = await download(provider.value, missing, maxWindow, { resolution, end }) 212 | spinner.succeed() 213 | 214 | // Save data to cache 215 | for (const symbol of symbols) { 216 | if (data[symbol] && data[symbol].length > 0) { 217 | await cache(config).save(symbol, resolution ?? 1440, data[symbol]) 218 | } 219 | } 220 | 221 | console.log(`${clc.green('✔ Success:')} All data was saved successfully in ${clc.underline.bold(dataDir)} directory`) 222 | 223 | bars = { ...bars, ...data } 224 | } catch (e: any) { 225 | spinner.fail() 226 | console.error(clc.red(`✖ Error: ${e.message}`)) 227 | } 228 | } else { 229 | console.log(`${clc.green('✔ Success:')} Data was not downloaded`) 230 | throw new Error('Data is missing') 231 | } 232 | 233 | } else { 234 | console.log(`${clc.green('✔ Success:')} All data is already in cache`) 235 | } 236 | 237 | return bars 238 | } 239 | 240 | return { download, downloadBars } 241 | } 242 | -------------------------------------------------------------------------------- /packages/cli/src/api/index.ts: -------------------------------------------------------------------------------- 1 | import cache from './cache' 2 | import code from './code' 3 | import data from './data' 4 | import auth from './login' 5 | import report from './report' 6 | 7 | export { 8 | cache, 9 | code, 10 | data, 11 | auth, 12 | report 13 | } -------------------------------------------------------------------------------- /packages/cli/src/api/login.ts: -------------------------------------------------------------------------------- 1 | import clc from 'cli-color' 2 | import ora from 'ora' 3 | import Axios, { type AxiosInstance } from 'axios' 4 | 5 | export default (config: any) => { 6 | 7 | const axios: AxiosInstance = Axios.create({ 8 | baseURL: config.apiUrl ?? 'https://zapant.com/api', 9 | timeout: 80000, 10 | headers: { 11 | 'Content-Type': 'application/json' 12 | } 13 | }) 14 | 15 | /** 16 | * Login to zapant.com 17 | * @param email 18 | * @param password 19 | * @returns 20 | */ 21 | const login = (email: string, password: string) => { 22 | const spinner = ora('Authenticating with credentials on zapant.com') 23 | 24 | // spinner.prefixText = clc.bgCyan('[info]'); 25 | spinner.spinner = 'circleHalves'; 26 | spinner.color = 'green' 27 | spinner.start() 28 | 29 | return axios.post('/auth/login', { email, password, strategy: 'local' }) 30 | .then(res => res.data) 31 | .then(data => { 32 | spinner.succeed() 33 | // spinner.clearLine(process.stdout) 34 | console.log(`${clc.green('✔ Success: ')} Login was successfull`) 35 | console.log(`${clc.green('✔ User: ')} ${data.user.name} (${data.user.email})`) 36 | 37 | return data 38 | }) 39 | .catch(err => { 40 | spinner.fail() 41 | 42 | if (err.response?.data) { 43 | console.log(`${clc.red('✖ Error: ')} ${err.response.data.message}.`) 44 | console.log(`${clc.red('✖')} Login ${clc.red('failed')}`) 45 | 46 | return null 47 | } 48 | 49 | console.log(`${clc.red('✖ Error: ')} Something went wrong.`) 50 | return null 51 | 52 | }) 53 | } 54 | 55 | return { login } 56 | } -------------------------------------------------------------------------------- /packages/cli/src/api/report.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'node:fs' 2 | import * as path from 'node:path' 3 | import pug from 'pug' 4 | 5 | const template = String.raw` 6 | doctype html 7 | html 8 | head 9 | title Report 10 | script(src="https://cdn.tailwindcss.com") 11 | style. 12 | body { 13 | background-color: #fbfcfe; 14 | } 15 | figure { 16 | margin: 0; 17 | padding: 8px; 18 | display: flex; 19 | flex-direction: column; 20 | align-items: center; 21 | border: 1px solid #e1e1e2; 22 | border-radius: 8px; 23 | } 24 | figure h2 { 25 | font-size: 1.5rem; 26 | text-align: center; 27 | margin-bottom: 4px; 28 | } 29 | body 30 | div.p-8.bg-white.shadow 31 | h1.text-4xl.mb-1 Backtest Report 32 | select#file-select.bg-gray-200.p-1.mb-2 33 | each file in files 34 | option(value=file) #{file} 35 | 36 | p.text-sm 37 | b.mr-1 Date generated: 38 | span#date 39 | p.text-sm 40 | b.mr-1 File: 41 | span#file 42 | p.text-sm 43 | b.mr-1 Start Cash: 44 | span#cash1 45 | p.text-sm 46 | b.mr-1 End Cash: 47 | span#cash2 48 | 49 | hr 50 | div#container.grid.grid-cols-2.p-4.gap-4.container.mx-auto 51 | 52 | script(type="importmap"). 53 | { 54 | "imports": { 55 | "@observablehq/plot": "https://cdn.jsdelivr.net/npm/@observablehq/plot@0.6/+esm", 56 | "@zapcli/reports": "https://cdn.jsdelivr.net/npm/@zapcli/reports/dist/zapcli-reports.es.js" 57 | } 58 | } 59 | script(type="module"). 60 | import * as Plot from "@observablehq/plot" 61 | import renderReport from "@zapcli/reports" 62 | 63 | const dataDir = !{JSON.stringify(dataDir)} 64 | const dataFiles = !{JSON.stringify(files)}; 65 | const container = document.querySelector("#container") 66 | const fileSelect = document.querySelector("#file-select") 67 | 68 | fileSelect.addEventListener("change", () => { 69 | const selectedFile = fileSelect.value 70 | loadFile(selectedFile) 71 | }) 72 | 73 | function loadFile(file) { 74 | fetch(dataDir + '/' + file) 75 | .then(response => response.json()) 76 | .then(data => { 77 | renderFile(data) 78 | }) 79 | .catch(error => console.error(error)) 80 | } 81 | 82 | function renderFile(data) { 83 | container.innerHTML = "" 84 | const plots = Object.keys(data.analyzers).map(name => renderReport(name, data.analyzers[name])).flat() 85 | plots.forEach(plot => { 86 | plot.classList.add(..."shadow bg-white".split(" ")) 87 | container.append(plot) 88 | }) 89 | 90 | document.getElementById('file').textContent = data.file; 91 | document.getElementById('cash1').textContent = data.startCash; 92 | document.getElementById('cash2').textContent = data.endCash; 93 | document.getElementById('date').textContent = data.dateGenerated 94 | } 95 | 96 | loadFile(dataFiles[0]) 97 | ` 98 | 99 | export default (config: any) => { 100 | 101 | const reportsDir = config.reportsDir ?? "reports" 102 | 103 | function getJsonFiles(directory) { 104 | if (!fs.existsSync(directory)) { 105 | return [] 106 | } 107 | 108 | // Read all files in the directory 109 | const files = fs.readdirSync(directory); 110 | 111 | // Filter out the files that are not .json 112 | return files.filter(file => path.extname(file).toLowerCase() === '.json'); 113 | } 114 | 115 | const generateReport = (name: string, files: string[], dir: string) => { 116 | const renderFn = pug.compile(template, { pretty: true }) 117 | const html = renderFn({ files, dataDir: path.relative(reportsDir, dir) }) 118 | 119 | if (!fs.existsSync(reportsDir)) { 120 | fs.mkdirSync(reportsDir, { recursive: true }) 121 | } 122 | 123 | const filePath = path.join(process.cwd(), reportsDir, name) 124 | fs.writeFileSync(filePath, html) 125 | 126 | return filePath 127 | } 128 | 129 | return { generateReport, getJsonFiles } 130 | } -------------------------------------------------------------------------------- /packages/cli/src/commands/backtest.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'node:path' 2 | import * as fs from 'node:fs' 3 | import clc from 'cli-color' 4 | import { Command } from 'commander' 5 | import { map } from 'ramda' 6 | import dayjs from 'dayjs' 7 | import voca from 'voca' 8 | import { Strategy, analyzers } from '@zapcli/backtest' 9 | import loadConfig from '../config' 10 | import * as api from '../api' 11 | import calendar from '@zapant/calendar' 12 | 13 | const program = new Command('backtest') 14 | 15 | // class LoggerAnalyzer { 16 | // name: string = 'logger' 17 | 18 | // next({ strategy, date, barIndex, bars, orders }) { 19 | // console.log(`Date: ${date}, BarIndex: ${barIndex}`) 20 | // console.log(`Cash: ${strategy.broker.getCash()}`) 21 | // console.log(`Bars:`) 22 | // console.dir(bars, { depth: null, colors: true }) 23 | // // console.log(strategy.broker.getOpenPositions()) 24 | // } 25 | // } 26 | 27 | export default () => { 28 | program 29 | .usage(' [options]') 30 | .description('run a backtest using a .zp or .js file and display the result') 31 | .argument('file', 'strategy to backtest') 32 | .option('-d1, --startDate ', 'backtest start date') 33 | .option('-d2, --endDate ', 'backtest end date') 34 | // .option('-m, --market ', 'market to use') 35 | .option('-s, --save ', 'save result to file') 36 | .option('-v, --verbose', 'verbose mode', false) 37 | .option('-a, --analyzers ', 'analyzers to use') 38 | .option('-c, --configDir ', 'config directory') 39 | // .option('-a, --auto', 'don\'t prompt confirmation prompts') 40 | .action(async (file, opts) => { 41 | 42 | try { 43 | const config = await loadConfig(opts.configDir) 44 | const extension = path.extname(file) 45 | const lang = extension === '.js' ? 'js' : 'zp' 46 | const backtestsDir = config.backtestsDir ?? 'backtests' 47 | 48 | console.log(clc.cyanBright(`→ Backtesting using file: `) + clc.underline(file)) 49 | 50 | // add defaults 51 | opts.startDate = opts.startDate ?? config.backtest?.startDate ?? dayjs().endOf('day').subtract(1, 'week').format('YYYY-MM-DD') 52 | opts.endDate = opts.endDate ?? config.backtest?.endDate ?? dayjs().endOf('day').format('YYYY-MM-DD') 53 | opts.save = opts.save ?? path.basename(file, extension) + '.json' 54 | 55 | const code = api.code().readCode(file) 56 | const { symbols, maxWindow, settings } = api.code().getRequirements(code, lang, [], config.backtest?.inputs ?? {}) 57 | 58 | const isStocks = symbols.map(s => s.includes('/')).every(x => !x) 59 | const market = isStocks ? 'stocks' : 'crypto' 60 | 61 | const dates = calendar.getDays({ start: opts.startDate, end: opts.endDate }, market).map(x => x.date) //allDatas[0].map(x => dayjs(x.date).format('YYYY-MM-DD')).slice(0, parseInt(opts.window)).reverse() 62 | const window = dates.length 63 | 64 | // 1. Download bars 65 | const strategy = new Strategy({ code, lang, verbose: opts.verbose, inputs: config.backtest?.inputs ?? {} }) 66 | 67 | //strategy.addAnalyzer(new LoggerAnalyzer()) 68 | const availableAnalyzers: any = Object.values(analyzers).reduce((result: any, AnalyzerClass: any) => { 69 | if (AnalyzerClass.prototype instanceof analyzers.BaseAnalyzer) { 70 | return result 71 | } else { 72 | try { 73 | const analyzer = new AnalyzerClass() 74 | result[analyzer.name] = analyzer 75 | return result 76 | } catch (e) { 77 | return result 78 | } 79 | } 80 | }, {} as any) 81 | 82 | const analyzersList = [...config.backtest?.analyzers ?? [], ...(opts.analyzers ?? []).map(name => { 83 | if (!availableAnalyzers[name]) { 84 | console.warn(clc.yellow(`→ Warning: Analyzer ${clc.underline.bold(name)} not found`)) 85 | } 86 | 87 | return availableAnalyzers[name] 88 | }).filter(x => x)] 89 | 90 | strategy.addAnalyzers(analyzersList) 91 | console.log('') 92 | 93 | const bars: Record = await api.data(config).downloadBars(symbols, maxWindow + window, { resolution: settings.resolution ?? 1440, end: opts.endDate }) 94 | 95 | // 2. Run backtest 96 | const allDatas: any[] = Object.values(bars) 97 | 98 | if (allDatas.length === 0) { 99 | throw new Error('No data in automation for backtest') 100 | } 101 | 102 | strategy.start() 103 | 104 | console.log(clc.cyanBright(`→ Running backtest from ${clc.green(dates[0])} to ${clc.green(dates[dates.length - 1])}. ${clc.underline(dates.length + ' bars\n')}`)) 105 | 106 | for (let index = 0; index < dates.length; index++) { 107 | const date = dates[index]; 108 | const barIndex = index + 1 109 | const currentBars = map(arr => arr.concat().reverse().slice(0, index + maxWindow + 1).reverse(), bars) 110 | const context = { code, date, barIndex } 111 | 112 | strategy.setBarIndex(barIndex) 113 | strategy.setBars(currentBars) 114 | strategy.prenext(context) 115 | strategy.next(context) 116 | 117 | } 118 | 119 | // 3. Finalize backtest 120 | strategy.end() 121 | 122 | console.log('') 123 | console.log(`${clc.green('✔ Success:')} Backtest was executed successfully`) 124 | console.log(`${clc.green('✔ Execution time:')} ${clc.bold(strategy.duration.toFixed(2))} seconds\n`) 125 | 126 | const result: any = { 127 | startCash: strategy.broker.getCashStart(), 128 | endCash: strategy.broker.getCash(), 129 | pl: strategy.broker.getPL(), 130 | } 131 | 132 | console.log(clc.cyanBright(`→ Result: `)) 133 | console.dir(result, { depth: null, colors: true }) 134 | console.log('') 135 | 136 | result.analyzers = {} 137 | 138 | for (const analyzer of strategy.analyzers) { 139 | result.analyzers[analyzer.name] = analyzer.data 140 | console.log(clc.cyanBright(`→ Analyzer: `) + clc.underline(voca.capitalize(analyzer.name))) 141 | // console.dir(analyzer.data, { depth: null, colors: true }) 142 | analyzer.toConsole() 143 | console.log('') 144 | } 145 | 146 | // if (opts.save) { 147 | if (!fs.existsSync(backtestsDir)) { 148 | fs.mkdirSync(backtestsDir, { recursive: true }) 149 | } 150 | 151 | const filePath = path.join(process.cwd(), backtestsDir, opts.save) 152 | console.log(clc.cyanBright(`→ Saving result to file: `) + clc.underline(filePath)) 153 | 154 | result.file = file 155 | result.dateGenerated = new Date().toISOString() 156 | 157 | fs.writeFileSync(filePath, JSON.stringify(result, null, 2)) 158 | console.log(`${clc.green('✔ Success:')} Result saved successfully\n`) 159 | // } 160 | 161 | } catch (e: any) { 162 | console.error(clc.red(`Error: ${e.message}`)) 163 | } 164 | 165 | }) 166 | 167 | return program 168 | } -------------------------------------------------------------------------------- /packages/cli/src/commands/create.ts: -------------------------------------------------------------------------------- 1 | import clc from 'cli-color' 2 | import fse from 'fs-extra' 3 | import { Command } from 'commander' 4 | import prompts from 'prompts' 5 | import ora from 'ora' 6 | import shell from 'shelljs' 7 | import fs from 'node:fs' 8 | import path from 'node:path' 9 | import voca from 'voca' 10 | 11 | const program = new Command('create') 12 | 13 | const createProject = async (name: string, projectDir: string) => { 14 | const spinner = ora(`Creating project ${clc.bold.cyanBright(name)} in ${clc.underline(path.join(process.cwd(), projectDir))}`).start() 15 | const res = shell.exec(`git clone https://github.com/zapant-com/zplang-hello.git ${projectDir}`, { silent: true }) 16 | if (res.code === 0) { 17 | shell.rm('-rf', projectDir + '/.git') 18 | 19 | spinner.succeed() 20 | console.log(`${clc.green('✔ Success: ')} Project ${clc.bold.cyanBright(name)} created successfully`) 21 | 22 | return true 23 | } else { 24 | spinner.fail() 25 | console.log(`${clc.red('✖ Error: ')} Project ${name} could not be created`) 26 | 27 | console.log(res) 28 | return false 29 | } 30 | } 31 | 32 | const createEmptyProject = async (name: string, projectDir: string, filesIndex?: number) => { 33 | const files = [ 34 | { 35 | name: 'package.json', 36 | content: ` 37 | { 38 | "name": "${name}", 39 | "version": "1.0.0", 40 | "description": "zapcli project", 41 | "type": "module", 42 | "scripts": { 43 | "execute": "zapcli execute ./automation.zp", 44 | "backtest": "zapcli backtest ./automation.zp", 45 | "version": "zapcli -v" 46 | }, 47 | "license": "ISC", 48 | "dependencies": {} 49 | } 50 | ` 51 | }, 52 | { 53 | name: 'zp.config.js', 54 | content: ` 55 | const config = { 56 | dataDir: "./data", 57 | reportsDir: "./reports", 58 | backtestsDir: "./backtests", 59 | dataProvider: "zapant", 60 | execute: { 61 | date: undefined, // this is the date execute will run 62 | inputs: { 63 | assets: [], 64 | initialCapital: 10000, 65 | openPositions: [] 66 | }, 67 | }, 68 | backtest: { 69 | startDate: "2024-05-01", 70 | endDate: "2024-05-20" 71 | } 72 | } 73 | 74 | export default config; 75 | ` 76 | }, 77 | { 78 | name: 'automation.zp', 79 | content: ` 80 | (def symbols [ 81 | "AAPL", 82 | "MSFT" 83 | ]) 84 | 85 | (loop symbol in symbols 86 | (buy {symbol} 1) 87 | ) 88 | ` 89 | }, 90 | ] 91 | 92 | const spinner = ora(`Creating project ${clc.bold.cyanBright(name)} in ${clc.underline(path.join(process.cwd(), projectDir))}`).start() 93 | await fse.ensureDir(projectDir) 94 | 95 | files.slice(0, filesIndex).forEach(async (file) => { 96 | const filePath = path.join(projectDir, file.name); 97 | await fse.outputFile(filePath, voca.trim(file.content)); 98 | }) 99 | 100 | spinner.succeed() 101 | console.log(`${clc.green('✔ Success: ')} Project ${clc.bold.cyanBright(name)} created successfully`) 102 | 103 | return true 104 | } 105 | 106 | const installDependencies = async (projectDir:string, pkName: string) => { 107 | shell.cd(projectDir) 108 | const spinner = ora(`Installing dependencies`).start() 109 | const res = shell.exec(`${pkName} install`, { silent: true }) 110 | 111 | if (res.code === 0) { 112 | spinner.succeed() 113 | console.log(`${clc.green('✔ Success: ')} Dependencies installed successfully`) 114 | } else { 115 | spinner.fail() 116 | console.log(`${clc.red('✖ Error: ')} Dependencies could not be installed`) 117 | } 118 | } 119 | 120 | export default () => { 121 | program 122 | .usage(' [options]') 123 | .description('create a new project') 124 | .argument('[name]', 'project name') 125 | .option('-t, --template