Repository: mcardillo55/cbpro-trader Branch: master Commit: fca241478bd8 Files: 61 Total size: 144.7 KB Directory structure: gitextract_9sgs8461/ ├── .gitignore ├── LICENSE ├── README.md ├── cbpro-trader/ │ ├── daemon/ │ │ ├── Dockerfile │ │ ├── cbpro-trader.py │ │ ├── config.yml.sample │ │ ├── engine/ │ │ │ ├── OrderBookCustom.py │ │ │ ├── Product.py │ │ │ ├── TradeAndHeartbeatWebsocket.py │ │ │ ├── TradeEngine.py │ │ │ └── __init__.py │ │ ├── indicators/ │ │ │ ├── IndicatorSubsystem.py │ │ │ └── __init__.py │ │ ├── interface/ │ │ │ ├── __init__.py │ │ │ ├── cursesDisplay.py │ │ │ └── web.py │ │ ├── period/ │ │ │ ├── Candlestick.py │ │ │ ├── MetaPeriod.py │ │ │ ├── Period.py │ │ │ └── __init__.py │ │ ├── requirements.txt │ │ ├── tests/ │ │ │ ├── __init__.py │ │ │ └── test_period.py │ │ └── trade/ │ │ ├── Trade.py │ │ └── __init__.py │ └── web/ │ ├── .gitignore │ ├── Dockerfile │ ├── README.md │ ├── package.json │ ├── public/ │ │ ├── index.html │ │ ├── manifest.json │ │ └── robots.txt │ └── src/ │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── actions/ │ │ └── index.js │ ├── components/ │ │ ├── Balances.jsx │ │ ├── Chart.jsx │ │ ├── CollapseButton.jsx │ │ ├── Config.jsx │ │ ├── Details.jsx │ │ ├── Flags.jsx │ │ ├── Orders.jsx │ │ ├── SelectAvailable.jsx │ │ ├── Sidebar.jsx │ │ └── Tooltip.jsx │ ├── containers/ │ │ ├── BalancesContainer.jsx │ │ ├── ChartContainer.jsx │ │ ├── ChartController.jsx │ │ ├── DetailsContainer.jsx │ │ ├── FlagsContainer.jsx │ │ ├── OrdersContainer.jsx │ │ └── SidebarContainer.jsx │ ├── index.css │ ├── index.js │ ├── reducers/ │ │ ├── chart.js │ │ ├── index.js │ │ └── sidebar.js │ └── serviceWorker.js ├── docker-compose.prod.yml └── docker-compose.yml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store *.pyc config.yml *.log .pytest_cache __pycache__ .vscode cbpro-trader/daemon/config.live cbpro-trader/daemon/config.sandbox ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # cbpro-trader cbpro-trader is a bot to automate trading on the Coinbase Pro cryptocurrency exchange. It is based around the ta-lib and coinbasepro-python libraries, allowing easy trading based on technical analysis indicators. The bot can monitor and trade any ticker supported by Coinbase Pro, and will even trade between cryptocurrencies if the opportunity is better. ## Disclaimer This bot is still in early stages and may have bugs. The strategies also need major reworking. **Do not use with any money you are not 100% willing to lose.** ## Installation ### Docker A docker-compose file is included to try to ease installation. If you are using the `web` frontend, you can simply run `docker-compose up` and then visit the URL provided by the frontend server. If you are using the `curses` or `debug` frontends, you can run `docker-compose build cbpro` `docker run -it cbpro-trader_cbpro -v $ABSOLUTE_PATH_TO_PROJECT/cbpro-trader/cbpro-trader/daemon/:/cbpro-trader/:Z` to build and run the image, making sure to replace the absolute path of the project, then`python3 ./cbpro-trader.py` to start the bot You will need to run `docker-compose up --build` if you change the config after the initial build. ### Manual You can install most requirements with `cd ./cbpro-trader` `pip install -r ./requirements.txt` then run with `python3 ./cbpro-trader.py` Note that it is currently pointing to a custom version of the coinbasepro-python library until I can push my OrderBook changes upstream. Also note that the TA-Lib python library is actually a wrapper for the ta-lib C library, so you will need to install that before. See the "Dependencies" section on https://github.com/mrjbq7/ta-lib for more information on that. ## Configuration Copy config.yml.sample to config.yml and include your `key`, `secret`, and `passphrase` values from your Coinbase Pro API key. | Name | Type | Description | | ------------ | ------- | -------------------------------------------------------------------------------- | | key | string | Coinbase API key | | secret | string | Coinbase API secret | | passphrase | string | Coinbase API passphrase | | sandbox | boolean | Set to 'yes' to use Coinbase sandbox servers (for testing) | | live | boolean | Set to 'yes' to to toggle live trading | | frontend | string | Which frontend to use - 'console', 'web' or 'debug'. See below for more info. | | web_config | boolean | Set to 'yes' to allow setting config from the web API | | logging | boolean | Set to 'yes' to add additional logging to debug.log file | | fiat | string | Which fiat currency to use - e.g. 'USD' or 'EUR' | | max_slippage | float | Max percentage change in limit orders before executing a market order | | periods | list | A YAML list of periods, each including the options listed in the periods section | For each period in the `periods` list, include the following options | Name | Type | Description | | ------- | ------- | ------------------------------------------------------------------------------ | | name | string | The display name of the period | | product | string | The Coinbase product to trade | | length | integer | The period length in minutes | | trade | boolean | Set to 'yes' to trade this period | | meta | boolean | Set to 'yes' if this is a 'meta' product (one that does not exist on Coinbase) | Set `live` to `yes` **only if** you want the bot to execute **actual trades.** The bot will still collect data and calculate indicators when `live` is set to `no`. You may also wish to test functionality with a Coinbase Pro sandbox API key first. In config.yml you can list as many periods as you would like under the periods section. Periods will be used for trading logic only if their `trade:` attribute is set to `yes`, otherwise they are just used for gathering indicator data. There is experimental support for 'meta' periods, which can be used for comparing 2 products that do not currently have a Coinbase Pro trading pair, by setting the `meta:` attribute to `yes` in the period description. The only real use case for this right now is LTC-ETH. Trading on meta periods is not yet supported (work in progress). `frontend` can have the following values * `web` - a web based frontend to be viewed in your web browser (WORK IN PROGRESS) * `curses` - an ncurses display of balances, indicator values, recent candlesticks and trades and current open orders or `debug` which will print the same infromation to the console, line-by-line, as it is available. * `debug` used for debugging (obviously). ## Tweaking indicators and trade logic I'm currently working on making indicators and trade strategies more configurable, but if you're handy with Python, any indicators from TA-Lib can be added, as desired. Trade logic can also obviously be modified as well. ### Design The IndicatorSubsystem class contains several methods to calculate indicators. Simple ones are already included, such as `calculate_macd()` and `calculate_obv()`. These methods write to the dictionary `IndicatorSubsystem.current_indicators` which is eventually used by `TradeEngine.determine_trades()` to determine if the bot should trade. ### Adding indicators To add a new indicator, first create the new method, following the naming convention. For example, if adding Simple Moving Average (SMA), `calculate_sma()` In the new method, you will probably want to use TA-LIB to calculate the indicator. Refer to http://mrjbq7.github.io/ta-lib/ for API documentation. For our example: `sma = talib.SMA(closing_prices, timeperiod=10)` Note that `closing_prices` and `volumes` are already available in the IndicatorSubsystem. Now, just add the most recent of this calculated value to the `current_indicators` dictionary, so that it is available to `TradeEngine`. You will need to add the indicator to the correct key, determined by `period_name` as well. This is to support multiple periods. `self.current_indicators[period_name]['sma'] = sma[-1]` ### Modifying trade logic Trade logic can obviously be modified as desired. Just make your decisions in `TradeEngine.determine_trades()`. `TradeEngine.determine_trades()` has access to the `IndicatorSubsystem.current_indicators` as `indicators`, as was discussed earlier. When issuing a buy order, be sure to set `product.buy_flag = True` and `product.sell_flag = False` before starting the buy order thread. This is to be sure that if there is a sell order pending, it will be cancelled and the sell thread will be closed. The same obviously holds true when issueing a sell order. ================================================ FILE: cbpro-trader/daemon/Dockerfile ================================================ FROM ubuntu:18.04 # Set locale ENV LANG C.UTF-8 # Allow for curses interface ENV TERM xterm # Update Ubuntu & install system dependencies RUN apt-get update RUN apt-get upgrade -y RUN apt-get install -y python3 python3-pip git locales # Build and install ta-lib ADD https://downloads.sourceforge.net/project/ta-lib/ta-lib/0.4.0/ta-lib-0.4.0-src.tar.gz / RUN tar xzvf ta-lib-0.4.0-src.tar.gz WORKDIR /ta-lib/ RUN ./configure --prefix=/usr RUN make RUN make install # Copy bot files RUN mkdir -p /cbpro-trader COPY ./requirements.txt / # Install Python dependencies WORKDIR / RUN pip3 install numpy==1.15.2 RUN pip3 install -r ./requirements.txt WORKDIR /cbpro-trader/ ================================================ FILE: cbpro-trader/daemon/cbpro-trader.py ================================================ # # bitcoin-trade.py # Mike Cardillo # # Main program for interacting with Coinbase Pro websocket and managing trade data import cbpro import period import indicators import engine import yaml import queue import time import interface import logging import datetime import threading from decimal import Decimal from websocket import WebSocketConnectionClosedException class CBProTrader(object): def __init__(self): with open("config.yml", 'r') as ymlfile: self.config = yaml.load(ymlfile, Loader=yaml.Loader) self.logger = logging.getLogger('trader-logger') self.logger.setLevel(logging.DEBUG) if self.config['logging']: self.logger.addHandler(logging.FileHandler("debug.log")) if self.config['frontend'] == 'debug': self.logger.addHandler(logging.StreamHandler()) self.error_logger = logging.getLogger('error-logger') self.error_logger.addHandler(logging.FileHandler("error.log")) self.initializing = False self.web_interface = None self.init_engine_and_indicators() def init_interface(self): if self.web_interface: self.web_interface.indicator_subsys = self.indicator_subsys self.web_interface.trade_engine = self.trade_engine else: if self.config['frontend'] == 'curses': curses_enable = True else: curses_enable = False self.interface = interface.cursesDisplay(enable=curses_enable) if self.config['frontend'] == 'web': self.web_interface = interface.web(self.indicator_subsys, self.trade_engine, self.config, self.init_engine_and_indicators) self.server_thread = threading.Thread(target=self.web_interface.start, daemon=True) self.server_thread.start() def init_engine_and_indicators(self): self.initializing = True try: self.cbpro_websocket.close() except: pass # Periods to update indicators for self.indicator_period_list = [] # Periods to actively trade on (typically 1 per product) self.trade_period_list = {} # List of products that we are actually monitoring self.product_list = set() fiat_currency = self.config['fiat'] if self.config['sandbox']: api_url = "https://api-public.sandbox.pro.coinbase.com" else: api_url = "https://api.pro.coinbase.com" auth_client = cbpro.AuthenticatedClient(self.config['key'], self.config['secret'], self.config['passphrase'], api_url=api_url) for cur_period in self.config['periods']: self.logger.debug("INITIALIZING %s", cur_period['name']) if cur_period.get('meta'): new_period = period.MetaPeriod(period_size=(60 * cur_period['length']), fiat=fiat_currency, product=cur_period['product'], name=cur_period['name'], cbpro_client=auth_client) else: new_period = period.Period(period_size=(60 * cur_period['length']), product=cur_period['product'], name=cur_period['name'], cbpro_client=auth_client) self.indicator_period_list.append(new_period) self.product_list.add(cur_period['product']) if cur_period['trade']: if self.trade_period_list.get(cur_period['product']) is None: self.trade_period_list[cur_period['product']] = [] self.trade_period_list[cur_period['product']].append(new_period) max_slippage = Decimal(str(self.config['max_slippage'])) self.trade_engine = engine.TradeEngine(auth_client, product_list=self.product_list, fiat=fiat_currency, is_live=self.config['live'], max_slippage=max_slippage) self.cbpro_websocket = engine.TradeAndHeartbeatWebsocket(fiat=fiat_currency, sandbox=self.config['sandbox']) self.cbpro_websocket.start() self.indicator_period_list[0].verbose_heartbeat = True self.indicator_subsys = indicators.IndicatorSubsystem(self.indicator_period_list) self.last_indicator_update = time.time() self.init_interface() self.initializing = False def start(self): while(True): if not self.initializing: try: if self.cbpro_websocket.error: raise self.cbpro_websocket.error msg = self.cbpro_websocket.websocket_queue.get(timeout=15) for product in self.trade_engine.products: product.order_book.process_message(msg) if msg.get('type') == "match": for cur_period in self.indicator_period_list: cur_period.process_trade(msg) if time.time() - self.last_indicator_update >= 1.0: for cur_period in self.indicator_period_list: self.indicator_subsys.recalculate_indicators(cur_period) for product_id, period_list in self.trade_period_list.items(): self.trade_engine.determine_trades(product_id, period_list, self.indicator_subsys.current_indicators) self.last_indicator_update = time.time() elif msg.get('type') == "heartbeat": for cur_period in self.indicator_period_list: cur_period.process_heartbeat(msg) for product_id, period_list in self.trade_period_list.items(): if len(self.indicator_subsys.current_indicators[cur_period.name]) > 0: self.trade_engine.determine_trades(product_id, period_list, self.indicator_subsys.current_indicators) self.trade_engine.print_amounts() self.interface.update(self.trade_engine, self.indicator_subsys.current_indicators, self.indicator_period_list, msg) except KeyboardInterrupt: self.trade_engine.close(exit=True) self.cbpro_websocket.close() self.interface.close() break except Exception as e: self.error_logger.exception(datetime.datetime.now()) self.trade_engine.close() self.cbpro_websocket.close() self.cbpro_websocket.error = None # Period data cannot be trusted. Re-initialize for cur_period in self.indicator_period_list: cur_period.initialize() time.sleep(10) self.cbpro_websocket.start() cbprotrader = CBProTrader() cbprotrader.start() ================================================ FILE: cbpro-trader/daemon/config.yml.sample ================================================ key: mykey secret: mysecret passphrase: mypassphrase sandbox: yes live: no frontend: curses web_config: no logging: no fiat: USD max_slippage: 0.10 periods: - name: BTC product: BTC-USD length: 5 trade: yes meta: no - name: ETH product: ETH-USD length: 15 trade: yes meta: no - name: LTC product: LTC-USD length: 30 trade: yes meta: no - name: LTCETH product: LTC-ETH length: 30 trade: no meta: yes ================================================ FILE: cbpro-trader/daemon/engine/OrderBookCustom.py ================================================ import cbpro import time import logging class OrderBookCustom(cbpro.OrderBook): def __init__(self, product_id='BTC-USD', auth_client=None): self.logger = logging.getLogger('trader-logger') self.error_logger = logging.getLogger('error-logger') super(OrderBookCustom, self).__init__(product_id=product_id) if auth_client is not None: self._client = auth_client def is_ready(self): try: super(OrderBookCustom, self).get_ask() except (ValueError, AttributeError): return False return True def get_ask(self): while not self.is_ready(): time.sleep(0.01) return super(OrderBookCustom, self).get_ask() def get_bid(self): while not self.is_ready(): time.sleep(0.01) return super(OrderBookCustom, self).get_bid() ================================================ FILE: cbpro-trader/daemon/engine/Product.py ================================================ import time from .OrderBookCustom import OrderBookCustom class Product(object): def __init__(self, auth_client, product_id='BTC-USD'): self.product_id = product_id self.order_book = OrderBookCustom(product_id=product_id, auth_client=auth_client) self.order_in_progress = False self.buy_flag = False self.sell_flag = False self.open_orders = [] self.order_thread = None self.meta = True self.last_signal_switch = time.time() cbpro_products = auth_client.get_products() while not isinstance(cbpro_products, list): # May be rate limited time.sleep(3) cbpro_products = auth_client.get_products() for cbpro_product in cbpro_products: if product_id == cbpro_product.get('id'): self.meta = False # If product_id is in response, it must be a real product self.quote_increment = cbpro_product.get('quote_increment') self.min_size = cbpro_product.get('base_min_size') ================================================ FILE: cbpro-trader/daemon/engine/TradeAndHeartbeatWebsocket.py ================================================ import datetime import logging import queue import cbpro from websocket import WebSocketConnectionClosedException class TradeAndHeartbeatWebsocket(cbpro.WebsocketClient): def __init__(self, fiat='USD', sandbox=False): self.logger = logging.getLogger('trader-logger') self.error_logger = logging.getLogger('error-logger') self.fiat_currency = fiat self.products = ["BTC-" + self.fiat_currency, "ETH-" + self.fiat_currency] self.channels = ['full', 'heartbeat'] if sandbox: url="wss://ws-feed-public.sandbox.pro.coinbase.com" else: url="wss://ws-feed.pro.coinbase.com" super(TradeAndHeartbeatWebsocket, self).__init__(products=self.products, channels=self.channels, url=url) def on_open(self): self.websocket_queue = queue.Queue() self.stop = False self.logger.debug("-- CBPRO Websocket Opened ---") def on_close(self): self.logger.debug("-- CBPRO Websocket Closed ---") def on_error(self, e): self.error_logger.exception(datetime.datetime.now()) self.error = e self.stop = True raise e def close(self): if not self.stop: self.on_close() self.stop = True self.thread.join() try: if self.ws: self.ws.close() except WebSocketConnectionClosedException: self.error_logger.exception(datetime.datetime.now()) pass def on_message(self, msg): self.websocket_queue.put(msg) ================================================ FILE: cbpro-trader/daemon/engine/TradeEngine.py ================================================ import time import logging import threading import datetime import itertools from decimal import Decimal, ROUND_DOWN from .Product import Product class TradeEngine(): def __init__(self, auth_client, product_list=['BTC-USD', 'ETH-USD', 'LTC-USD'], fiat='USD', is_live=False, max_slippage=Decimal('0.10')): self.logger = logging.getLogger('trader-logger') self.error_logger = logging.getLogger('error-logger') self.auth_client = auth_client self.product_list = product_list self.fiat_currency = fiat self.is_live = is_live self.market_orders = True # TODO: make this a config option self.available_products = [] self.products = [] self.balances = {} self.stop_update_order_thread = False self.last_order_update = time.time() self.all_open_orders = [] self.recent_fills = [] for product in self.product_list: self.products.append(Product(auth_client, product_id=product)) self.last_balance_update = 0 self.update_amounts() self.init_available_products() self.last_balance_update = time.time() self.max_slippage = max_slippage self.update_order_thread = threading.Thread(target=self.update_orders, name='update_orders') self.update_order_thread.start() def close(self, exit=False): if exit: self.stop_update_order_thread = True for product in self.products: # Setting both flags will close any open order threads product.buy_flag = False product.sell_flag = False # Cancel any orders that may still be remaining product.order_in_progress = False try: self.auth_client.cancel_all() except Exception: self.error_logger.exception(datetime.datetime.now()) def get_product_by_product_id(self, product_id='BTC-USD'): for product in self.products: if product.product_id == product_id: return product return None def init_available_products(self): for product in self.auth_client.get_products(): self.available_products.append(product.get('id')) def update_orders(self): while not self.stop_update_order_thread: need_updating = False for product in self.products: if product.order_in_progress: need_updating = True if time.time() - self.last_order_update >= 1.0: self.temp_recent_fills = [] try: for product in self.products: self.temp_recent_fills += list(itertools.islice(self.auth_client.get_fills(product_id=product.product_id), 5)) self.recent_fills = sorted(self.temp_recent_fills, key=lambda x: x['created_at'], reverse=True)[:5] except Exception: self.error_logger.exception(datetime.datetime.now()) if need_updating: try: self.all_open_orders = list(self.auth_client.get_orders()) for product in self.products: product.open_orders = [] for order in self.all_open_orders: self.get_product_by_product_id(order.get('product_id')).open_orders.append(order) except Exception: self.error_logger.exception(datetime.datetime.now()) elif not need_updating: self.all_open_orders = [] self.last_order_update = time.time() time.sleep(0.01) def round_fiat(self, money): return Decimal(money).quantize(Decimal('.01'), rounding=ROUND_DOWN) def round_coin(self, money): return Decimal(money).quantize(Decimal('.00000001'), rounding=ROUND_DOWN) def update_amounts(self): if time.time() - self.last_balance_update > 1.0: try: self.last_balance_update = time.time() ret = self.auth_client.get_accounts() if isinstance(ret, list): for account in ret: self.balances[account['currency']] = self.round_coin(account.get('available')) except Exception: self.error_logger.exception(datetime.datetime.now()) return self.balances['fiat_equivalent'] = Decimal('0.0') for product in self.products: if not product.meta and product.order_book.get_current_ticker() and product.order_book.get_current_ticker().get('price'): self.balances['fiat_equivalent'] += self.get_base_currency_from_product_id(product.product_id, update=False) * Decimal(product.order_book.get_current_ticker().get('price')) self.balances['fiat_equivalent'] += self.balances[self.fiat_currency] def print_amounts(self): self.logger.debug("[BALANCES] %s: %.2f BTC: %.8f" % (self.fiat_currency, self.balances[self.fiat_currency], self.balances['BTC'])) def place_buy(self, product=None, partial='1.0'): amount = self.get_quoted_currency_from_product_id(product.product_id) * Decimal(partial) bid = product.order_book.get_ask() - Decimal(product.quote_increment) amount = self.round_coin(Decimal(amount) / Decimal(bid)) if amount < Decimal(product.min_size): amount = self.get_quoted_currency_from_product_id(product.product_id) bid = product.order_book.get_ask() - Decimal(product.quote_increment) amount = self.round_coin(Decimal(amount) / Decimal(bid)) if amount >= Decimal(product.min_size): self.logger.debug("Placing buy... Price: %.8f Size: %.8f" % (bid, amount)) ret = self.auth_client.place_limit_order(product.product_id, "buy", size=str(amount), price=str(bid), post_only=True) if ret.get('status') == 'pending' or ret.get('status') == 'open': product.open_orders.append(ret) return ret else: ret = {'status': 'done'} return ret def buy(self, product=None, amount=None): product.order_in_progress = True last_order_update = 0 starting_price = product.order_book.get_ask() - Decimal(product.quote_increment) try: ret = self.place_buy(product=product, partial='0.5') bid = ret.get('price') amount = self.get_quoted_currency_from_product_id(product.product_id) while product.buy_flag and (amount >= Decimal(product.min_size) or len(product.open_orders) > 0): if (((product.order_book.get_ask() - Decimal(product.quote_increment)) / starting_price) - Decimal('1.0')) * Decimal('100.0') > self.max_slippage: self.auth_client.cancel_all(product_id=product.product_id) self.auth_client.place_market_order(product.product_id, "buy", funds=str(self.get_quoted_currency_from_product_id(product.product_id))) product.order_in_progress = False return if ret.get('status') == 'rejected' or ret.get('status') == 'done' or ret.get('message') == 'NotFound': ret = self.place_buy(product=product, partial='0.5') bid = ret.get('price') elif not bid or Decimal(bid) < product.order_book.get_ask() - Decimal(product.quote_increment): if len(product.open_orders) > 0: ret = self.place_buy(product=product, partial='1.0') else: ret = self.place_buy(product=product, partial='0.5') for order in product.open_orders: if order.get('id') != ret.get('id'): self.auth_client.cancel_order(order.get('id')) bid = ret.get('price') if ret.get('id') and time.time() - last_order_update >= 1.0: try: ret = self.auth_client.get_order(ret.get('id')) last_order_update = time.time() except ValueError: self.error_logger.exception(datetime.datetime.now()) pass amount = self.get_quoted_currency_from_product_id(product.product_id) time.sleep(0.01) self.auth_client.cancel_all(product_id=product.product_id) amount = self.get_quoted_currency_from_product_id(product.product_id) except Exception: product.order_in_progress = False self.error_logger.exception(datetime.datetime.now()) self.auth_client.cancel_all(product_id=product.product_id) product.order_in_progress = False def place_sell(self, product=None, partial='1.0'): amount = self.round_coin(self.get_base_currency_from_product_id(product.product_id) * Decimal(partial)) if amount < Decimal(product.min_size): amount = self.get_base_currency_from_product_id(product.product_id) ask = product.order_book.get_bid() + Decimal(product.quote_increment) if amount >= Decimal(product.min_size): self.logger.debug("Placing sell... Price: %.2f Size: %.8f" % (ask, amount)) ret = self.auth_client.place_limit_order(product.product_id, "sell", size=str(amount), price=str(ask), post_only=True) if ret.get('status') == 'pending' or ret.get('status') == 'open': product.open_orders.append(ret) return ret else: ret = {'status': 'done'} return ret def sell(self, product=None, amount=None): product.order_in_progress = True last_order_update = 0 starting_price = product.order_book.get_bid() + Decimal(product.quote_increment) try: ret = self.place_sell(product=product, partial='0.5') ask = ret.get('price') amount = self.get_base_currency_from_product_id(product.product_id) while product.sell_flag and (amount >= Decimal(product.min_size) or len(product.open_orders) > 0): if (Decimal('1') - ((product.order_book.get_bid() + Decimal(product.quote_increment)) / starting_price)) * Decimal('100.0') > self.max_slippage: self.auth_client.cancel_all(product_id=product.product_id) self.auth_client.place_market_order(product.product_id, "sell", size=str(self.get_base_currency_from_product_id(product.product_id))) product.order_in_progress = False return if ret.get('status') == 'rejected' or ret.get('status') == 'done' or ret.get('message') == 'NotFound': ret = self.place_sell(product=product, partial='0.5') ask = ret.get('price') elif not ask or Decimal(ask) > product.order_book.get_bid() + Decimal(product.quote_increment): if len(product.open_orders) > 0: ret = self.place_sell(product=product, partial='1.0') else: ret = self.place_sell(product=product, partial='0.5') for order in product.open_orders: if order.get('id') != ret.get('id'): self.auth_client.cancel_order(order.get('id')) ask = ret.get('price') if ret.get('id') and time.time() - last_order_update >= 1.0: try: ret = self.auth_client.get_order(ret.get('id')) except ValueError: self.error_logger.exception(datetime.datetime.now()) pass last_order_update = time.time() amount = self.get_base_currency_from_product_id(product.product_id) time.sleep(0.01) self.auth_client.cancel_all(product_id=product.product_id) amount = self.get_base_currency_from_product_id(product.product_id) except Exception: product.order_in_progress = False self.error_logger.exception(datetime.datetime.now()) self.auth_client.cancel_all(product_id=product.product_id) product.order_in_progress = False def get_base_currency_from_product_id(self, product_id, update=True): if update: self.update_amounts() return self.balances[product_id[:3]] def get_quoted_currency_from_product_id(self, product_id): self.update_amounts() return self.balances[product_id[4:]] def determine_trades(self, product_id, period_list, indicators): self.update_amounts() if self.is_live: product = self.get_product_by_product_id(product_id) new_buy_flag = True new_sell_flag = False for cur_period in period_list: # Moving Average Strategy new_buy_flag = new_buy_flag and Decimal(indicators[cur_period.name]['sma_trend']) > Decimal('0.0') new_sell_flag = new_sell_flag or Decimal(indicators[cur_period.name]['sma_trend']) < Decimal('0.0') if product_id == 'LTC-BTC' or product_id == 'ETH-BTC': ltc_or_eth_fiat_product = self.get_product_by_product_id(product_id[:3] + '-' + self.fiat_currency) btc_fiat_product = self.get_product_by_product_id('BTC-' + self.fiat_currency) new_buy_flag = new_buy_flag and ltc_or_eth_fiat_product.buy_flag new_sell_flag = new_sell_flag and btc_fiat_product.buy_flag if new_buy_flag: if product.sell_flag: product.last_signal_switch = time.time() product.sell_flag = False product.buy_flag = True amount = self.round_fiat(self.get_quoted_currency_from_product_id(product_id)) if amount >= Decimal(product.min_size): if self.market_orders: ret = self.auth_client.place_market_order(product.product_id, "buy", funds=str(amount)) self.logger.debug(ret) self.logger.debug(amount) else: if not product.order_in_progress: bid = product.order_book.get_ask() - Decimal(product.quote_increment) amount = self.round_coin(Decimal(amount) / Decimal(bid)) product.order_thread = threading.Thread(target=self.buy, name='buy_thread', kwargs={'product': product}) product.order_thread.start() elif new_sell_flag: if product.buy_flag: product.last_signal_switch = time.time() product.buy_flag = False product.sell_flag = True amount_of_coin = self.round_coin(self.get_base_currency_from_product_id(product_id)) if amount_of_coin >= Decimal(product.min_size): if self.market_orders: self.auth_client.place_market_order(product.product_id, "sell", size=str(amount_of_coin)) else: if not product.order_in_progress: product.order_thread = threading.Thread(target=self.sell, name='sell_thread', kwargs={'product': product}) product.order_thread.start() else: product.buy_flag = False product.sell_flag = False ================================================ FILE: cbpro-trader/daemon/engine/__init__.py ================================================ from .OrderBookCustom import OrderBookCustom from .Product import Product from .TradeEngine import TradeEngine from .TradeAndHeartbeatWebsocket import TradeAndHeartbeatWebsocket ================================================ FILE: cbpro-trader/daemon/indicators/IndicatorSubsystem.py ================================================ import talib import logging import numpy as np from decimal import Decimal class IndicatorSubsystem: def __init__(self, period_list): self.logger = logging.getLogger('trader-logger') self.current_indicators = {} self.period_list = period_list for period in self.period_list: self.current_indicators[period.name] = {} def recalculate_indicators(self, cur_period): total_periods = len(cur_period.candlesticks) if total_periods > 0: closing_prices = cur_period.get_closing_prices() closing_prices_close = np.append(closing_prices, cur_period.cur_candlestick.close) self.highs = np.append(cur_period.get_highs(), cur_period.cur_candlestick.high) self.lows = np.append(cur_period.get_lows(), cur_period.cur_candlestick.low) volumes = np.append(cur_period.get_volumes(), cur_period.cur_candlestick.volume) self.calculate_sma(cur_period.name, closing_prices_close) self.current_indicators[cur_period.name]['close'] = cur_period.cur_candlestick.close self.current_indicators[cur_period.name]['total_periods'] = total_periods def calculate_sma(self, period_name, closing_prices): sma = talib.SMA(closing_prices, timeperiod=9) self.current_indicators[period_name]['sma'] = sma[-1] self.current_indicators[period_name]['sma_trend'] = sma[-1] - sma[-2] def calculate_adx(self, period_name, close): adx = talib.ADX(self.highs, self.lows, close, timeperiod=14) self.current_indicators[period_name]['adx'] = adx[-1] def calculate_bbands(self, period_name, close): timeperiod = 20 upperband_1, middleband_1, lowerband_1 = talib.BBANDS(close, timeperiod=timeperiod, nbdevup=1, nbdevdn=1, matype=0) self.current_indicators[period_name]['bband_upper_1'] = upperband_1[-1] self.current_indicators[period_name]['bband_lower_1'] = lowerband_1[-1] upperband_2, middleband_2, lowerband_2 = talib.BBANDS(close, timeperiod=timeperiod, nbdevup=2, nbdevdn=2, matype=0) self.current_indicators[period_name]['bband_upper_2'] = upperband_2[-1] self.current_indicators[period_name]['bband_lower_2'] = lowerband_2[-1] def calculate_macd(self, period_name, closing_prices): macd, macd_sig, macd_hist = talib.MACD(closing_prices, fastperiod=12, slowperiod=26, signalperiod=9) self.current_indicators[period_name]['macd'] = macd[-1] self.current_indicators[period_name]['macd_sig'] = macd_sig[-1] self.current_indicators[period_name]['macd_hist'] = macd_hist[-1] self.current_indicators[period_name]['macd_hist_diff'] = Decimal(macd_hist[-1]) - Decimal(macd_hist[-2]) def calculate_vol_macd(self, period_name, volumes): macd, macd_sig, macd_hist = talib.MACD(volumes, fastperiod=50, slowperiod=200, signalperiod=14) self.current_indicators[period_name]['vol_macd'] = macd[-1] self.current_indicators[period_name]['vol_macd_sig'] = macd_sig[-1] self.current_indicators[period_name]['vol_macd_hist'] = macd_hist[-1] def calculate_avg_volume(self, period_name, volumes): avg_vol = talib.SMA(volumes, timeperiod=15) self.current_indicators[period_name]['avg_volume'] = avg_vol[-1] def calculate_obv(self, period_name, closing_prices, volumes): obv = talib.OBV(closing_prices, volumes) obv_ema = talib.EMA(obv, timeperiod=3) self.current_indicators[period_name]['obv_ema'] = obv_ema[-1] self.current_indicators[period_name]['obv'] = obv[-1] def calculate_sar(self, period_name, highs, lows): sar = talib.SAR(highs, lows) self.current_indicators[period_name]['sar'] = sar[-1] def calculate_stochrsi(self, period_name, closing_prices): fastk, fastd = talib.STOCHRSI(closing_prices, timeperiod=14, fastk_period=3, fastd_period=3, fastd_matype=0) self.current_indicators[period_name]['stochrsi_fastk'] = fastk[-1] self.current_indicators[period_name]['stochrsi_fastd'] = fastd[-1] def calculate_stoch(self, period_name, closing_prices): slowk, slowd = talib.STOCH(self.highs, self.lows, closing_prices, fastk_period=14, slowk_period=2, slowk_matype=0, slowd_period=3, slowd_matype=0) self.current_indicators[period_name]['stoch_slowk'] = slowk[-1] self.current_indicators[period_name]['stoch_slowd'] = slowd[-1] def calculate_mfi(self, period_name, highs, lows, closing_prices, volumes): mfi = talib.MFI(highs, lows, closing_prices, volumes) self.current_indicators[period_name]['mfi'] = mfi[-1] ================================================ FILE: cbpro-trader/daemon/indicators/__init__.py ================================================ from .IndicatorSubsystem import IndicatorSubsystem ================================================ FILE: cbpro-trader/daemon/interface/__init__.py ================================================ from .cursesDisplay import cursesDisplay from .web import web ================================================ FILE: cbpro-trader/daemon/interface/cursesDisplay.py ================================================ import curses import time import logging from decimal import Decimal class cursesDisplay: def __init__(self, enable=True): self.enable = enable if not self.enable: return self.logger = logging.getLogger('trader-logger') self.stdscr = curses.initscr() self.pad = curses.newpad(23, 120) self.order_pad = curses.newpad(10, 120) self.timestamp = "" self.last_order_update = 0 curses.start_color() curses.noecho() curses.cbreak() curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN) curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_RED) self.stdscr.keypad(1) self.pad.addstr(1, 0, "Waiting for a trade...") def update_balances(self, trade_engine): self.pad.addstr(0, 0, "%s: %.2f BTC: %.8f" % (trade_engine.fiat_currency, trade_engine.balances[trade_engine.fiat_currency], trade_engine.balances['BTC'])) self.pad.addstr(1, 0, "%s_EQUIV: %.2f" % (trade_engine.fiat_currency, trade_engine.balances['fiat_equivalent'])) def update_candlesticks(self, period_list): starty = self.starty if starty < self.signal_end_y + 1: starty = self.signal_end_y + 1 for cur_period in period_list: cur_stick = cur_period.cur_candlestick if cur_stick.new is False: self.pad.addstr(starty, 0, "%s - %s O: %f H: %f L: %f C: %f V: %f" % (cur_period.name, cur_stick.time, cur_stick.open, cur_stick.high, cur_stick.low, cur_stick.close, cur_stick.volume), self.print_color(cur_stick.close, cur_stick.open)) starty += 1 self.starty = starty def update_heartbeat(self): self.pad.addstr(0, 83, self.timestamp) def update_indicators(self, period_list, indicators): starty = self.starty for cur_period in period_list: stoch_diff = Decimal(indicators[cur_period.name]['stoch_slowk']) - Decimal(indicators[cur_period.name]['stoch_slowd']) obv_diff = Decimal(indicators[cur_period.name]['obv']) - Decimal(indicators[cur_period.name]['obv_ema']) self.pad.addstr(starty, 0, "%s - OBV_DIFF: %f STOCH_DIFF: %f ADX: %f" % (cur_period.name, obv_diff, stoch_diff, indicators[cur_period.name]['adx']), self.print_color(Decimal(obv_diff), Decimal('0.0'))) starty += 1 self.starty = starty + 1 def update_fills(self, trade_engine): self.pad.addstr(9, 0, "Recent Fills") starty = 10 for fill in trade_engine.auth_client.get_fills(limit=5)[0]: self.pad.addstr(starty, 0, "%s Price: %s Size: %s Time: %s" % (fill.get('side').upper(), fill.get('price'), fill.get('size'), fill.get('created_at'))) starty += 1 def update_orders(self, trade_engine): starty = 0 self.order_pad.addstr(starty, 0, "Open Orders") if time.time() - self.last_order_update > 3.0: self.order_pad.erase() self.order_pad.addstr(starty, 0, "Open Orders") order_in_progress = False # First check if trade engine has any open orders for product in trade_engine.products: if product.order_in_progress: order_in_progress = True starty += 1 if not trade_engine.all_open_orders: self.order_pad.addstr(starty, 0, 'None') for order in trade_engine.all_open_orders: self.order_pad.addstr(starty, 0, "%s %s Price: %s Size: %s Status: %s" % (order.get('side').upper(), order.get('product_id'), order.get('price'), order.get('size'), order.get('status'))) starty += 1 self.last_order_update = time.time() height, width = self.stdscr.getmaxyx() if height > (self.padsize + 1): self.order_pad.refresh(0, 0, (self.padsize + 1), 0, (height - 1), (width - 1)) def update_signals(self, trade_engine): starty = 1 for product in trade_engine.products: if product.buy_flag: text = 'BUY' color = curses.color_pair(1) elif product.sell_flag: text = 'SELL' color = curses.color_pair(2) else: text = 'NONE' color = curses.color_pair(0) self.pad.addstr(starty, 93, "%s: %s" % (product.product_id, text), color) starty += 1 self.signal_end_y = starty def update(self, trade_engine, indicators, period_list, msg): if not self.enable: return self.padsize = (len(period_list) * 2) + 3 self.pad.resize(self.padsize, 120) self.starty = 2 if msg.get('type') == "heartbeat": self.timestamp = msg.get('time') self.pad.erase() self.update_balances(trade_engine) self.update_heartbeat() self.update_signals(trade_engine) # Make sure indicator dict is populated if len(indicators[period_list[0].name]) > 0: self.update_indicators(period_list, indicators) self.update_candlesticks(period_list) self.update_orders(trade_engine) height, width = self.stdscr.getmaxyx() self.pad.refresh(0, 0, 0, 0, (height - 1), (width - 1)) def print_color(self, a, b, c=None, d=None): # If a > b, print green, otherwise red if c and d: if Decimal(a) > Decimal(b) and Decimal(c) > Decimal(d): return curses.color_pair(1) else: return curses.color_pair(2) else: if Decimal(a) > Decimal(b): return curses.color_pair(1) else: return curses.color_pair(2) def close(self): if not self.enable: return curses.nocbreak() self.stdscr.keypad(0) curses.echo() curses.endwin() ================================================ FILE: cbpro-trader/daemon/interface/web.py ================================================ import os from flask import Flask, request, jsonify from gevent.pywsgi import WSGIServer class web(object): def __init__(self, indicator_subsys, trade_engine, config, init_engine_and_indicators): self.indicator_subsys = indicator_subsys self.trade_engine = trade_engine self.config = config self.init_engine_and_indicators = init_engine_and_indicators app = Flask(__name__) self.app = app @app.route('/products/') def products(): return jsonify(self.trade_engine.available_products) @app.route('/periods/') @app.route('/periods/') def periods(periodName=None): period_data = [] if periodName is None: for period in self.indicator_subsys.period_list: period_data.append(period.name) return jsonify(period_data) else: for period in self.indicator_subsys.period_list: if period.name == periodName: period_data = period.candlesticks.tolist() + [period.cur_candlestick.to_list()] return jsonify([{ 'time': stick[0].timestamp(), 'low': stick[1], 'high': stick[2], 'open': stick[3], 'close': stick[4] } for stick in period_data]) @app.route('/indicators/') @app.route('/indicators/') def indicators(periodName=None): if periodName is None: return jsonify(self.indicator_subsys.current_indicators) else: return jsonify(self.indicator_subsys.current_indicators.get(periodName)) @app.route('/orders/') @app.route('/orders/') def orders(productId=None): return jsonify({'orders': trade_engine.all_open_orders, 'fills': trade_engine.recent_fills}) @app.route('/balances/') @app.route('/balances/') def balances(currency=None): balances = trade_engine.balances.copy() for key in balances: balances[key] = '{0:.8f}'.format(balances[key]) return jsonify(balances) @app.route('/flags/') def flags(): flags = {} for product in self.trade_engine.products: if product.buy_flag is True: flags[product.product_id] = "buy" else: flags[product.product_id] = "sell" return jsonify(flags) @app.route('/config/', methods=['GET', 'POST']) def config(periodName=None): if self.config.get("web_config"): if request.method == 'POST': self.trade_engine.close() new_config = request.get_json() self.config.update(new_config) init_engine_and_indicators() # Remove key/secret info from the response new_config = self.config.copy() del new_config['key'] del new_config['secret'] del new_config['passphrase'] else: new_config = {'web_config': False} return jsonify(new_config) def start(self): if 'PRODUCTION' in os.environ: http_server = WSGIServer(('', 8080), self.app) http_server.serve_forever() else: self.app.run(host='0.0.0.0') ================================================ FILE: cbpro-trader/daemon/period/Candlestick.py ================================================ import logging import numpy as np class Candlestick: def __init__(self, isotime=None, existing_candlestick=None, prev_close=None): self.logger = logging.getLogger('trader-logger') self.new = True if isotime: self.time = isotime.replace(second=0, microsecond=0) self.volume = 0 if prev_close: self.open = prev_close self.high = prev_close self.low = prev_close self.close = prev_close else: self.time = isotime.replace(second=0, microsecond=0) self.open = None self.high = None self.low = None self.close = None elif existing_candlestick is not None: self.new = False self.time, self.low, self.high, self.open, self.close, self.volume = existing_candlestick def add_trade(self, new_trade): self.new = False if not self.open: self.open = new_trade.price if not self.high: self.high = new_trade.price elif new_trade.price > self.high: self.high = new_trade.price if not self.low: self.low = new_trade.price elif new_trade.price < self.low: self.low = new_trade.price self.close = new_trade.price self.volume = self.volume + new_trade.volume self.logger.debug("[TRADE] Time: %s Price: %f Vol: %f" % (new_trade.time, new_trade.price, new_trade.volume)) def close_candlestick(self, period_name, prev_stick=None): self.logger.debug("Candlestick Closed!") if self.close is None: self.new = False self.open = prev_stick[4] # Closing price self.high = prev_stick[4] self.low = prev_stick[4] self.close = prev_stick[4] self.print_stick(period_name) return np.array([self.time, self.low, self.high, self.open, self.close, self.volume]) def to_list(self): return [self.time, self.low, self.high, self.open, self.close, self.volume] def print_stick(self, period_name): self.logger.debug("[CANDLESTICK %s] Time: %s Open: %s High: %s Low: %s Close: %s Vol: %s" % (period_name, self.time, self.open, self.high, self.low, self.close, self.volume)) ================================================ FILE: cbpro-trader/daemon/period/MetaPeriod.py ================================================ import copy import cbpro import datetime import time import numpy as np import pytz from decimal import Decimal from .Period import Period class MetaPeriod(Period): def __init__(self, period_size=60, name='Period', product='BTC-USD', fiat='USD', initialize=True, cbpro_client=cbpro.PublicClient()): self.base = product[:3] + '-' + fiat self.quoted = product[4:] + '-' + fiat super(MetaPeriod, self).__init__(period_size=period_size, name=name, product=product, initialize=True, cbpro_client=cbpro_client) def process_trade(self, msg): newmsg = copy.deepcopy(msg) if msg.get('product_id') == self.base: newmsg['product_id'] = self.product quoted_last = Decimal(msg.get('price')) / Decimal(self.cur_candlestick.close) total_price = quoted_last + Decimal(msg.get('price')) newmsg['size'] = Decimal(msg.get('size')) * (Decimal(msg.get('price')) / total_price) newmsg['price'] = Decimal(msg.get('price')) / quoted_last elif msg.get('product_id') == self.quoted: newmsg['product_id'] = self.product base_last = Decimal(self.cur_candlestick.close) * Decimal(msg.get('price')) total_price = base_last + Decimal(msg.get('price')) newmsg['size'] = Decimal(msg.get('size')) * (Decimal(msg.get('price')) / total_price) newmsg['price'] = base_last / Decimal(msg.get('price')) super(MetaPeriod, self).process_trade(msg=newmsg) def get_historical_data(self, num_periods=200): end = datetime.datetime.utcnow() end_iso = end.isoformat() start = end - datetime.timedelta(seconds=(self.period_size * num_periods)) start_iso = start.isoformat() ret_base = self.cbpro_client.get_product_historic_rates(self.base, granularity=self.period_size, start=start_iso, end=end_iso) ret_quoted = self.cbpro_client.get_product_historic_rates(self.quoted, granularity=self.period_size, start=start_iso, end=end_iso) # Check if we got rate limited, which will return a JSON message while not isinstance(ret_base, list): time.sleep(3) ret_base = self.cbpro_client.get_product_historic_rates(self.base, granularity=self.period_size, start=start_iso, end=end_iso) while not isinstance(ret_quoted, list): time.sleep(3) ret_quoted = self.cbpro_client.get_product_historic_rates(self.quoted, granularity=self.period_size, start=start_iso, end=end_iso) hist_data_base = np.array(ret_base, dtype='object') hist_data_quoted = np.array(ret_quoted, dtype='object') array_size = min(len(ret_base), len(ret_quoted)) hist_data_base.resize(array_size, 6) hist_data_quoted.resize(array_size, 6) for row in hist_data_base: row[0] = datetime.datetime.fromtimestamp(row[0], pytz.utc) for row in hist_data_quoted: row[0] = datetime.datetime.fromtimestamp(row[0], pytz.utc) hist_data = np.ndarray((len(hist_data_base), 6), dtype='object') hist_data[:, 0] = hist_data_base[:, 0] hist_data[:, [1,2,3,4]] = hist_data_base[:, [1,2,3,4]]/hist_data_quoted[:, [1,2,3,4]] total_price = (hist_data_base[:, 4] + hist_data_quoted[:, 4]) hist_data[:, 5] = ((hist_data_base[:, 4] / total_price) * hist_data_base[:, 5]) + ((hist_data_base[:, 4] / total_price) * hist_data_quoted[:, 5]) hist_data[:, 5] = hist_data[:, 5] * hist_data[:, 4] return np.flipud(hist_data) ================================================ FILE: cbpro-trader/daemon/period/Period.py ================================================ import logging import cbpro import datetime import time import dateutil import pytz import trade import numpy as np from .Candlestick import Candlestick class Period: def __init__(self, period_size=60, name='Period', product='BTC-USD', initialize=True, cbpro_client=cbpro.PublicClient()): self.period_size = period_size self.name = name self.product = product self.first_trade = True self.verbose_heartbeat = False # CBPRO historical data is not up-to-date # We need to update data 10 minutes after closing the first period self.updated_hist_data = False self.time_of_first_candlestick_close = None self.logger = logging.getLogger('trader-logger') self.error_logger = logging.getLogger('error-logger') self.cbpro_client = cbpro_client if initialize: self.initialize() else: self.candlesticks = np.array([]) def initialize(self): self.candlesticks = self.get_historical_data() self.cur_candlestick = Candlestick(existing_candlestick=self.candlesticks[-1]) self.candlesticks = self.candlesticks[:-1] self.cur_candlestick_start = self.cur_candlestick.time def get_historical_data(self, num_periods=200): end = datetime.datetime.utcnow() end_iso = end.isoformat() start = end - datetime.timedelta(seconds=(self.period_size * num_periods)) start_iso = start.isoformat() ret = None # Check if we got rate limited, which will return a JSON message while not isinstance(ret, list): try: time.sleep(3) ret = self.cbpro_client.get_product_historic_rates(self.product, granularity=self.period_size, start=start_iso, end=end_iso) except Exception: self.error_logger.exception(datetime.datetime.now()) hist_data = np.array(ret, dtype='object') for row in hist_data: row[0] = datetime.datetime.fromtimestamp(row[0], pytz.utc) return np.flipud(hist_data) def update_historical_data(self): updated_sticks = self.get_historical_data(num_periods=5) for new_stick in updated_sticks: for idx, old_stick in enumerate(self.candlesticks[-10:]): if new_stick[0] == old_stick[0]: self.candlesticks[-10 + idx] = new_stick self.updated_hist_data = True def process_heartbeat(self, msg): if not self.updated_hist_data and self.time_of_first_candlestick_close \ and datetime.datetime.now() - self.time_of_first_candlestick_close >= datetime.timedelta(minutes=10): self.update_historical_data() isotime = dateutil.parser.parse(msg.get('time')) if isotime: if self.verbose_heartbeat: self.logger.debug("[HEARTBEAT] " + str(isotime) + " " + str(msg.get('last_trade_id'))) if isotime - self.cur_candlestick_start > datetime.timedelta(seconds=self.period_size): self.close_candlestick() self.new_candlestick(self.cur_candlestick.time + datetime.timedelta(seconds=self.period_size)) def process_trade(self, msg): if msg.get('product_id') == self.product: cur_trade = trade.Trade(msg) isotime = dateutil.parser.parse(msg.get('time')).replace(microsecond=0) if isotime < self.cur_candlestick.time: prev_stick = Candlestick(existing_candlestick=self.candlesticks[-1]) self.candlesticks = self.candlesticks[:-1] prev_stick.add_trade(cur_trade) self.add_stick(prev_stick) else: if isotime > self.cur_candlestick.time + datetime.timedelta(seconds=self.period_size): self.close_candlestick() self.new_candlestick(self.cur_candlestick.time + datetime.timedelta(seconds=self.period_size)) self.cur_candlestick.add_trade(cur_trade) self.cur_candlestick.print_stick(self.name) def get_highs(self): return np.array(self.candlesticks[:, 2], dtype='f8') def get_lows(self): return np.array(self.candlesticks[:, 1], dtype='f8') def get_closing_prices(self): return np.array(self.candlesticks[:, 4], dtype='f8') def get_volumes(self): return np.array(self.candlesticks[:, 5], dtype='f8') def new_candlestick(self, isotime): prev_close = self.cur_candlestick.close self.cur_candlestick = Candlestick(isotime=isotime, prev_close=prev_close) self.cur_candlestick_start = isotime.replace(second=0, microsecond=0) def add_stick(self, stick_to_add): self.candlesticks = np.row_stack((self.candlesticks, stick_to_add.close_candlestick(self.name))) def close_candlestick(self): if not self.updated_hist_data: self.time_of_first_candlestick_close = datetime.datetime.now() if len(self.candlesticks) > 0: self.candlesticks = np.row_stack((self.candlesticks, self.cur_candlestick.close_candlestick(period_name=self.name, prev_stick=self.candlesticks[-1]))) else: self.candlesticks = np.array([self.cur_candlestick.close_candlestick(self.name)]) ================================================ FILE: cbpro-trader/daemon/period/__init__.py ================================================ from .Candlestick import Candlestick from .Period import Period from .MetaPeriod import MetaPeriod ================================================ FILE: cbpro-trader/daemon/requirements.txt ================================================ astroid==2.3.3 atomicwrites==1.2.1 attrs==18.2.0 bintrees==2.0.7 -e git+https://github.com/mcardillo55/coinbasepro-python.git@d2b8bed627339723ab214430fe93ade2331d757e#egg=cbpro Click==7.0 Flask==1.1.1 gevent==20.5.0 greenlet==0.4.15 isort==4.3.21 itsdangerous==1.1.0 Jinja2==2.10.3 lazy-object-proxy==1.4.3 MarkupSafe==1.1.1 mccabe==0.6.1 more-itertools==4.3.0 numpy==1.15.2 pluggy==0.8.0 py==1.7.0 pylint==2.4.4 pymongo==3.5.1 pytest==4.0.1 pytest-mock==1.10.0 python-dateutil==2.6.0 pytz==2017.2 PyYAML==5.1 requests==2.20.0 six==1.13.0 sortedcontainers==2.1.0 TA-Lib==0.4.17 websocket-client==0.40.0 Werkzeug==0.16.0 wrapt==1.11.2 ================================================ FILE: cbpro-trader/daemon/tests/__init__.py ================================================ ================================================ FILE: cbpro-trader/daemon/tests/test_period.py ================================================ # # test_period.py # Mike Cardillo # # Pytest tests on the period file import period import trade import datetime import numpy as np class TestCandlestick(object): def setup_class(self): fake_trade_dict = {"sequence": "12345", "trade_id": "123", "time": "2018-11-29T05:21:06Z", "price": "38.50", "size": "105.34"} self.fake_trade = trade.Trade(fake_trade_dict) self.test_datetime = datetime.datetime(2018, 6, 10, 11, 13, 58, 384) self.test_datetime_zero_sec_ms = datetime.datetime(2018, 6, 10, 11, 13, 0, 0) def test_init_with_isotime_and_prev_close(self): prev_close = 58.30 candlestick = period.Candlestick(isotime=self.test_datetime, prev_close=prev_close) assert candlestick.new is True assert candlestick.time == self.test_datetime_zero_sec_ms assert candlestick.open == 58.30 assert candlestick.high == 58.30 assert candlestick.low == 58.30 assert candlestick.close == 58.30 assert candlestick.volume == 0 def test_init_with_isotime_without_prev_close(self): candlestick = period.Candlestick(isotime=self.test_datetime) assert candlestick.new is True assert candlestick.time == self.test_datetime_zero_sec_ms assert candlestick.open is None assert candlestick.high is None assert candlestick.low is None assert candlestick.close is None assert candlestick.volume == 0 def test_init_without_isotime(self): existing_candlestick = [self.test_datetime_zero_sec_ms, 58.00, 59.50, 58.10, 58.50, 15235.235] candlestick = period.Candlestick(existing_candlestick=existing_candlestick) assert candlestick.new is False assert candlestick.time == self.test_datetime_zero_sec_ms assert candlestick.open == 58.10 assert candlestick.high == 59.50 assert candlestick.low == 58.00 assert candlestick.close == 58.50 assert candlestick.volume == 15235.235 def test_add_trade__new_open(self): candlestick = period.Candlestick(isotime=self.test_datetime) candlestick.add_trade(self.fake_trade) assert candlestick.new is False assert candlestick.open == 38.50 assert candlestick.high == 38.50 assert candlestick.low == 38.50 assert candlestick.close == 38.50 assert candlestick.volume == 105.34 def test_add_trade__higher_high(self): existing_candlestick = [self.test_datetime_zero_sec_ms, 25.57, 35.57, 30.25, 31.25, 15235.235] candlestick = period.Candlestick(existing_candlestick=existing_candlestick) candlestick.add_trade(self.fake_trade) assert candlestick.high == 38.50 assert candlestick.close == 38.50 assert candlestick.volume == 15235.235 + 105.34 def test_add_trade__lower_low(self): existing_candlestick = [self.test_datetime_zero_sec_ms, 39.57, 42.45, 40.25, 39.87, 15235.235] candlestick = period.Candlestick(existing_candlestick=existing_candlestick) candlestick.add_trade(self.fake_trade) assert candlestick.low == 38.50 assert candlestick.close == 38.50 assert candlestick.volume == 15235.235 + 105.34 def test_close_candlestick__all_fields_none(self): candlestick = period.Candlestick(isotime=self.test_datetime) prev_stick = [self.test_datetime_zero_sec_ms, 39.57, 42.45, 40.25, 39.87, 15235.235] ret = candlestick.close_candlestick("TEST STICK", prev_stick=prev_stick) assert candlestick.new is False assert isinstance(ret, type(np.array([]))) np.testing.assert_array_equal(ret, [self.test_datetime_zero_sec_ms, 39.87, 39.87, 39.87, 39.87, 0]) def test_close_candlestick__close_not_none(self): existing_candlestick = [self.test_datetime_zero_sec_ms, 58.00, 59.50, 58.10, 58.50, 15235.235] candlestick = period.Candlestick(existing_candlestick=existing_candlestick) ret = candlestick.close_candlestick("TEST STICK") assert isinstance(ret, type(np.array([]))) np.testing.assert_array_equal(ret, existing_candlestick) class TestPeriod(object): def setup_class(self): self.start_time = datetime.datetime.now(datetime.timezone.utc) self.fake_hist_data = [[self.start_time.timestamp(), 123.4, 133.5, 124.6, 132.3, 3485.38], [(self.start_time + datetime.timedelta(minutes=5)).timestamp(), 122.3, 135.4, 123.7, 133.4, 4385.25], [(self.start_time + datetime.timedelta(minutes=10)).timestamp(), 120.2, 130.2, 132.5, 131.2, 3859.42]] def test_init__initalize_false(self): test_period = period.Period(period_size=15, name="BTC15", product="BTC-USD", initialize=False) assert isinstance(test_period, period.Period) assert test_period.period_size == 15 assert test_period.name == "BTC15" assert test_period.product == "BTC-USD" assert test_period.verbose_heartbeat is False assert isinstance(test_period.candlesticks, type(np.array([]))) np.testing.assert_array_equal(test_period.candlesticks, np.array([])) def test_init__initalize_true(self, mocker): mocker.patch("cbpro.PublicClient.get_product_historic_rates", return_value=self.fake_hist_data) test_period = period.Period(period_size=5, name="ETH5", product="ETH-USD", initialize=True) assert isinstance(test_period, period.Period) assert test_period.period_size == 5 assert test_period.name == "ETH5" assert test_period.product == "ETH-USD" assert test_period.verbose_heartbeat is False assert isinstance(test_period.candlesticks, type(np.array([]))) assert len(test_period.candlesticks) == len(self.fake_hist_data) - 1 assert isinstance(test_period.cur_candlestick, period.Candlestick) assert test_period.cur_candlestick_start == self.start_time assert isinstance(test_period.candlesticks[0], type(np.array([]))) ================================================ FILE: cbpro-trader/daemon/trade/Trade.py ================================================ import dateutil.parser import logging class Trade: def __init__(self, msg): self.seq = int(msg.get('sequence')) self.trade_id = int(msg.get('trade_id')) self.time = dateutil.parser.parse(msg.get('time')) self.price = float(msg.get('price')) self.volume = float(msg.get('size')) self.logger = logging.getLogger('trader-logger') def print_trade(self): self.logger.debug("[TRADE] Trade ID: %d Price: %f Volume: %f" % (self.trade_id, self.price, self.volume)) ================================================ FILE: cbpro-trader/daemon/trade/__init__.py ================================================ from .Trade import Trade ================================================ FILE: cbpro-trader/web/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: cbpro-trader/web/Dockerfile ================================================ FROM node:13.6.0 # Install node dependencies WORKDIR /frontend/ RUN npm install ================================================ FILE: cbpro-trader/web/README.md ================================================ This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.
Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.
You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.
It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.
Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting ### Analyzing the Bundle Size This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size ### Making a Progressive Web App This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app ### Advanced Configuration This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration ### Deployment This section has moved here: https://facebook.github.io/create-react-app/docs/deployment ### `npm run build` fails to minify This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify ================================================ FILE: cbpro-trader/web/package.json ================================================ { "name": "web", "version": "0.1.0", "private": true, "dependencies": { "lightweight-charts": "^3.1.5", "react": "^16.9.0", "react-dom": "^16.9.0", "react-redux": "^7.1.3", "react-scripts": "3.1.1", "redux": "^4.0.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "proxy": "http://cbpro:5000" } ================================================ FILE: cbpro-trader/web/public/index.html ================================================ Coinbase Pro Trader
================================================ FILE: cbpro-trader/web/public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: cbpro-trader/web/public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * ================================================ FILE: cbpro-trader/web/src/App.css ================================================ #chart-controller { display: flex; height: 100vh; } #chart { flex: 1; } #collapse-button { display: flex; justify-content: center; align-items: center; color: rgb(19, 23, 34); background-color: rgb(217, 217, 217); width: 15px; } #collapse-button:hover { background-color: #A6A6A6; } #config { padding: 10px; } #period-list { overflow-y: auto; list-style-type: none; padding: 0px; margin: 0px; } #sidebar { display: grid; grid-template-rows: 1fr 2fr; max-height: 100vh; width: 300px; } #primary-selector { display: grid; grid-template-columns: 1fr 1fr 1fr; border-top: 5px solid; border-bottom: 5px solid; } #primary-section { overflow-y: auto; } #secondary-section { overflow-y: auto; } #secondary-details { overflow-x: auto; white-space: nowrap; } #secondary-selector { display: grid; grid-template-columns: 1fr 1fr 1fr; border-top: 5px solid; border-bottom: 5px solid; } #tooltip { display: block; position: absolute; top: 3px; left: 10px; z-index: -1; } #tooltip-title { font-size: 26px; } #tooltip-prices { font-size: 18px; } #details { font-weight: bold; } #last-trade { font-size: 28px; } .active-button{ background-color: rgb(33, 56, 77); } .collapsed { grid-template-columns: 124fr 1fr !important; } #balances { padding-top: 0px; list-style-type: none; overflow-y: auto; } .currency { font-weight: bold; } .indicator-data { font-weight: normal; } .indicator { margin: 8px 0px; } .sidebar-section { padding: 10px; } .sidebar-section h2.first-h2{ margin-top: 0px; } .flag-title { font-weight: bold; } button { color: rgb(120, 123, 134); background: rgb(19, 23, 34); text-decoration: none; border: 1px solid; padding: 10px; outline: none !important; } button:hover { background-color: #2a2e39; } li.period{ display: block; padding: 10px; text-decoration: none; height: 20px; } li:nth-child(odd).period{ background-color: rgb(28, 32, 48); } li.focused.period{ background-color: rgb(33, 56, 77); } body { color: rgb(217, 217, 217); background: rgb(19, 23, 34); } th { border-right: 1px solid; border-bottom: 1px solid; } th:last-child { border-right: 0; } td { border-right: 1px solid; } td:last-child { border-right: 0; } input, select { margin: 5px; } input[type=text], input[type=number]{ width: 100px; } label { display: inline-block; width: 100px; text-align: right; } input[type=submit]{ display: block; margin-left: 25% } ================================================ FILE: cbpro-trader/web/src/App.js ================================================ import React from 'react'; import ChartController from './containers/ChartController' import './App.css'; function App() { return (
); } export default App; ================================================ FILE: cbpro-trader/web/src/App.test.js ================================================ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(, div); ReactDOM.unmountComponentAtNode(div); }); ================================================ FILE: cbpro-trader/web/src/actions/index.js ================================================ export const changeActivePeriod = period_name => ({ type: 'CHANGE_ACTIVE_PERIOD', period_name }) export const changePrimarySection = section_name => ({ type: 'CHANGE_PRIMARY_SECTION', section_name }) export const changeSecondarySection = section_name => ({ type: 'CHANGE_SECONDARY_SECTION', section_name }) export const updateBalances = balances => ({ type: 'UPDATE_BALANCES', balances }) export const updateFlags = flags => ({ type: 'UPDATE_FLAGS', flags }) export const addPeriod = period_name => ({ type: 'ADD_PERIOD', period_name }) export const clearPeriods = () => ({ type: 'CLEAR_PERIODS' }) export const updateCandlesticks = candlesticks => ({ type: 'UPDATE_CANDLESTICKS', candlesticks }) export const updateIndicators = indicators => ({ type: 'UPDATE_INDICATORS', indicators }) export const updateOrders = orders => ({ type: 'UPDATE_ORDERS', orders }) ================================================ FILE: cbpro-trader/web/src/components/Balances.jsx ================================================ import React from 'react'; function Balances(props) { const { balances } = props; return(
    { Object.keys(balances).map((currency, idx) => { return(
  • { currency.toUpperCase() }: { balances[currency] }
  • ) }) }
) } export default Balances; ================================================ FILE: cbpro-trader/web/src/components/Chart.jsx ================================================ import React from 'react'; import * as LightweightCharts from 'lightweight-charts'; import Tooltip from './Tooltip'; function Chart (props) { const ref = React.useRef(null); const [chart, setChart] = React.useState(null); const [initialZoomSet, setInitialZoomSet] = React.useState(false); // Tracks if we have set the initial zoom yet const [tooltipPrices, setTooltipPrices] = React.useState({}); const [hovering, setHovering] = React.useState(false); // True if hovering a data series; const [candlestickSeries, setCandlestickSeries] = React.useState(null); const { active_period, candlesticks } = props; if (ref.current && !chart) { setChart(LightweightCharts.createChart(ref.current, { width: 0, height: 0, layout: { backgroundColor: 'Transparent', textColor: 'rgba(255, 255, 255, 0.9)', }, grid: { vertLines: { color: 'rgba(197, 203, 206, 0.5)', }, horzLines: { color: 'rgba(197, 203, 206, 0.5)', }, }, crosshair: { mode: LightweightCharts.CrosshairMode.Normal, }, rightPriceScale: { borderColor: 'rgba(197, 203, 206, 0.8)', }, timeScale: { timeVisible: true, borderColor: 'rgba(197, 203, 206, 0.8)', }, })); } React.useEffect(() => { if(chart) { let series = chart.addCandlestickSeries({ upColor: '#53b987', downColor: '#eb4d5c', borderDownColor: '#eb4d5c', borderUpColor: '#53b987', wickDownColor: '#eb4d5c', wickUpColor: '#53b987', }); setCandlestickSeries(series); chart.subscribeCrosshairMove(function(param) { if (param.seriesPrices.size) { setHovering(true); setTooltipPrices(param.seriesPrices.get(series)); } else { setHovering(false); } }) }; }, [chart]); React.useEffect(() => { if (candlesticks.length && candlestickSeries) { candlestickSeries.setData(candlesticks); if (!hovering) { setTooltipPrices(candlesticks[candlesticks.length - 1]); } } if (!initialZoomSet && chart && chart.timeScale().getVisibleRange()) { let timeDiff = candlesticks[candlesticks.length -1]['time'] - candlesticks[candlesticks.length -2]['time']; chart.timeScale().setVisibleRange({ from: candlesticks[candlesticks.length -1]['time'] - (timeDiff * 30), // Show 30 candles by default to: candlesticks[candlesticks.length -1]['time'], }) setInitialZoomSet(true); setTooltipPrices(candlesticks[candlesticks.length - 1]) } }, [candlesticks, candlestickSeries, chart, hovering, initialZoomSet]); function resizeChart() { if (chart) { chart.resize(0, 0); chart.resize(ref.current.clientWidth, ref.current.clientHeight); } } window.addEventListener('resize', () => resizeChart()); resizeChart(); return (
) } export default Chart; ================================================ FILE: cbpro-trader/web/src/components/CollapseButton.jsx ================================================ import React from 'react'; function CollapseButton(props) { const buttonDirection = props.collapsed ? "<" : ">" return (
{buttonDirection}
) } export default CollapseButton; ================================================ FILE: cbpro-trader/web/src/components/Config.jsx ================================================ import React, { Component } from 'react' import { connect } from 'react-redux' import { addPeriod, changeActivePeriod, clearPeriods } from '../actions' import SelectAvailable from './SelectAvailable' class Config extends Component { constructor(){ super(); this.SERVER = process.env.REACT_APP_SERVER || ''; this.state = {"config": {"periods": []}} this.handleConfigChange = this.handleConfigChange.bind(this) this.handlePeriodChange = this.handlePeriodChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } componentDidMount() { fetch(this.SERVER + '/config/') .then(response => response.json()) .then(myJson => this.setState({"config": myJson})) } handleConfigChange(event) { this.setState({ config: {...this.state.config, [event.target.name]: this.parseEventData(event) } }) } handlePeriodChange(event) { let idx = event.target.name.split("+")[0] let name = event.target.name.split("+")[1] let periods = [...this.state.config.periods] let period = {...periods[idx], [name]: this.parseEventData(event)} periods[idx] = period this.setState({ config: {...this.state.config, periods: periods } }) } handleSubmit(event){ event.preventDefault() fetch(this.SERVER + '/config/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(this.state.config) }) .then(() => { this.props.clearPeriods() fetch(this.SERVER + "/periods/") .then(response => { return response.json() }) .then(myJson => { myJson.map((period_name, idx) => { (idx === 0) && this.props.changeActivePeriod(period_name); return this.props.addPeriod(period_name); }) }) }) } parseEventData(event) { switch (event.target.type) { case "select-one": switch (event.target.name.split("+")[1]) { case "length": return parseFloat(event.target.value) default: return event.target.value } case "text": return event.target.value case "number": return parseFloat(event.target.value) case "checkbox": return event.target.checked default: return event.target.value } } parseType(data) { switch (typeof(data)) { case "text": return "text" case "number": return "number" case "boolean": return "checkbox" default: return "text" } } createInput(label, value, period) { let type = this.parseType(value) let checked = type === "checkbox" && value ? "checked" : "" let parsedLabel; if (period) { parsedLabel = label.split("+")[1] } else { parsedLabel = label } switch (parsedLabel) { case "product": return case "length": return default: return } } prettifyLabel(label) { return label.charAt(0).toUpperCase() + label.replace('_', ' ').slice(1) } render() { if (this.state.config['web_config']) { let periods_list = this.state.config["periods"].map((period, idx) => { return( Object.keys(period).map((period_value, idx2) => { return(
{this.createInput(idx + "+" + period_value, period[period_value], true)}
) }) ) }); let config_list = Object.keys(this.state.config).map((config, idx) => { if (config === "periods") { return(
Periods: {periods_list}
) } else { return (
{this.createInput(config, this.state.config[config], false)}
) } }); return (
{config_list}
); } else { return (

Web config disabled

) } } } const mapDispatchToProps = dispatch => ({ addPeriod: period_name => dispatch(addPeriod(period_name)), changeActivePeriod: period_name => dispatch(changeActivePeriod(period_name)), clearPeriods: () => dispatch(clearPeriods()) }) export default connect(null, mapDispatchToProps)(Config); ================================================ FILE: cbpro-trader/web/src/components/Details.jsx ================================================ import React from 'react'; function Details(props) { const { indicators } = props; return(
Last Trade
{indicators.close && indicators.close.toFixed(2)}
{ Object.keys(indicators).map((indicator, idx) => { return(
{indicator.toUpperCase()}
{indicators[indicator]}
) }) }
) } export default Details; ================================================ FILE: cbpro-trader/web/src/components/Flags.jsx ================================================ import React from 'react'; function Flags(props) { const { flags } = props; return(

Flags

{ Object.keys(flags).map((flag, idx) => { return(
{ flag.toUpperCase() }: { flags[flag].toUpperCase() }
) }) }
) } export default Flags; ================================================ FILE: cbpro-trader/web/src/components/Orders.jsx ================================================ import React from 'react'; function Orders(props) { const { orders } = props; return(

Orders

{ orders['orders'].map((order, idx) => { return( ) }) }
Product Side Size Price Filled Fee
{order.product_id} {order.side.toUpperCase()} {order.size} {parseFloat(order.price).toFixed(2)} {order.filled_size} {parseFloat(order.fill_fees).toFixed(8)}

Fills

{ orders['fills'].map((fill, idx) => { return( ) }) }
Product Side Size Price Fee
{fill.product_id} {fill.side.toUpperCase()} {fill.size} {parseFloat(fill.price).toFixed(2)} {parseFloat(fill.fee).toFixed(8)}
) } export default Orders; ================================================ FILE: cbpro-trader/web/src/components/SelectAvailable.jsx ================================================ import React, { Component } from 'react' class SelectAvailable extends Component { constructor(props){ super(props) this.SERVER = process.env.REACT_APP_SERVER || '' this.state = {options: []} } componentDidMount() { if (this.props.url) { fetch(this.SERVER + this.props.url) .then(response => response.json()) .then(myJson => this.setState({options: myJson})) } else if (this.props.options) { this.setState({options: this.props.options}) } } render() { let options = this.state.options.map((option, idx) => { return }) return ( ) } } export default SelectAvailable; ================================================ FILE: cbpro-trader/web/src/components/Sidebar.jsx ================================================ import React from 'react'; import DetailsContainer from '../containers/DetailsContainer' import FlagsContainer from '../containers/FlagsContainer' import OrdersContainer from '../containers/OrdersContainer' import BalancesContainer from '../containers/BalancesContainer'; import Config from '../components/Config'; function Sidebar(props) { const { active_period, period_list, primary_section, secondary_section, changePrimarySection, changeSecondarySection, changeActivePeriod } = props; let period_list_map = period_list.map((period_name, idx) => { return(
  • {changeActivePeriod(period_name)}}>{period_name}
  • ) }) return ( ) } export default Sidebar; ================================================ FILE: cbpro-trader/web/src/components/Tooltip.jsx ================================================ import React from 'react'; function Tooltip (props) { return (
    {props.title}
    O: {props.prices.open} H: {props.prices.high} L: {props.prices.low} C: {props.prices.close}
    ) } export default Tooltip; ================================================ FILE: cbpro-trader/web/src/containers/BalancesContainer.jsx ================================================ import { connect } from 'react-redux' import Balances from '../components/Balances' const mapStateToProps = state => ({ balances: state.sidebar.balances }) export default connect(mapStateToProps)(Balances); ================================================ FILE: cbpro-trader/web/src/containers/ChartContainer.jsx ================================================ import { connect } from 'react-redux' import Chart from '../components/Chart' const mapStateToProps = state => ({ active_period: state.chart.active_period, candlesticks: state.chart.candlesticks }) export default connect(mapStateToProps)(Chart); ================================================ FILE: cbpro-trader/web/src/containers/ChartController.jsx ================================================ import React, { Component } from 'react' import { connect } from 'react-redux' import { addPeriod, changeActivePeriod, updateCandlesticks, updateIndicators, updateFlags, updateOrders, updateBalances } from '../actions' import CollapseButton from '../components/CollapseButton' import SidebarContainer from '../containers/SidebarContainer' import ChartContainer from '../containers/ChartContainer' class ChartController extends Component { constructor() { super(); this.SERVER = process.env.REACT_APP_SERVER || ''; this.state = {sidebarCollapsed: false}; } componentDidMount() { fetch(this.SERVER + "/periods/") .then(response => { return response.json() }) .then(myJson => { myJson.map((period_name, idx) => { (idx === 0) && this.props.changeActivePeriod(period_name); return this.props.addPeriod(period_name); }) }) .then( setInterval(() => this.update(), 1000) ) } update() { if (this.props.active_period) { fetch(this.SERVER + "/periods/" + this.props.active_period) .then(response => { return response.json() }) .then(myJson => { this.props.updateCandlesticks(myJson) }) if (this.props.primary_section === "balances") { fetch(this.SERVER + "/balances/") .then(response => { return response.json() }) .then(myJson => { this.props.updateBalances(myJson) }) } switch(this.props.secondary_section) { case "details": fetch(this.SERVER + "/indicators/" + this.props.active_period) .then(response => { return response.json() }) .then(myJson => { this.props.updateIndicators(myJson) }) break; case "flags": fetch(this.SERVER + "/flags/") .then(response => { return response.json() }) .then(myJson => { this.props.updateFlags(myJson) }) break; case "orders": fetch(this.SERVER + "/orders/") .then(response => { return response.json() }) .then(myJson => { this.props.updateOrders(myJson) }) break; default: break; } } } render() { this.update(); return (
    {this.setState({sidebarCollapsed: !this.state.sidebarCollapsed})}} /> {!this.state.sidebarCollapsed && }
    ) } } const mapStateToProps = state => ({ active_period: state.chart.active_period, primary_section: state.sidebar.primary_section, secondary_section: state.sidebar.secondary_section }) const mapDispatchToProps = dispatch => ({ addPeriod: period_name => dispatch(addPeriod(period_name)), changeActivePeriod: period_name => dispatch(changeActivePeriod(period_name)), updateCandlesticks: candlesticks => dispatch(updateCandlesticks(candlesticks)), updateIndicators: indicators => dispatch(updateIndicators(indicators)), updateFlags: flags => dispatch(updateFlags(flags)), updateOrders: orders => dispatch(updateOrders(orders)), updateBalances: balances => dispatch(updateBalances(balances)) }) export default connect(mapStateToProps, mapDispatchToProps)(ChartController); ================================================ FILE: cbpro-trader/web/src/containers/DetailsContainer.jsx ================================================ import { connect } from 'react-redux' import Details from '../components/Details' const mapStateToProps = state => ({ indicators: state.sidebar.indicators }) export default connect(mapStateToProps)(Details); ================================================ FILE: cbpro-trader/web/src/containers/FlagsContainer.jsx ================================================ import { connect } from 'react-redux' import Flags from '../components/Flags' const mapStateToProps = state => ({ flags: state.sidebar.flags }) export default connect(mapStateToProps)(Flags); ================================================ FILE: cbpro-trader/web/src/containers/OrdersContainer.jsx ================================================ import { connect } from 'react-redux' import Orders from '../components/Orders' const mapStateToProps = state => ({ orders: state.sidebar.orders }) export default connect(mapStateToProps)(Orders); ================================================ FILE: cbpro-trader/web/src/containers/SidebarContainer.jsx ================================================ import { connect } from 'react-redux' import { changeActivePeriod, changePrimarySection, changeSecondarySection } from '../actions' import Sidebar from '../components/Sidebar' const mapStateToProps = state => ({ period_list: state.chart.period_list, active_period: state.chart.active_period, primary_section: state.sidebar.primary_section, secondary_section: state.sidebar.secondary_section }) const mapDispatchToProps = dispatch => ({ changeActivePeriod: period_name => dispatch(changeActivePeriod(period_name)), changePrimarySection: section_name => dispatch(changePrimarySection(section_name)), changeSecondarySection: section_name => dispatch(changeSecondarySection(section_name)) }) export default connect(mapStateToProps, mapDispatchToProps)(Sidebar); ================================================ FILE: cbpro-trader/web/src/index.css ================================================ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace; } ================================================ FILE: cbpro-trader/web/src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import { createStore } from 'redux' import { Provider } from 'react-redux' import rootReducer from './reducers/index' const store = createStore(rootReducer) ReactDOM.render( , document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); ================================================ FILE: cbpro-trader/web/src/reducers/chart.js ================================================ const chart = (state = {period_list: [], candlesticks: [], indicators: []}, action) => { switch (action.type) { case 'CHANGE_ACTIVE_PERIOD': return { ...state, active_period: action.period_name } case 'ADD_PERIOD': return { ...state, period_list: [...state.period_list, action.period_name] } case 'CLEAR_PERIODS': return { ...state, period_list: [] } case 'UPDATE_CANDLESTICKS': return { ...state, candlesticks: action.candlesticks } default: return state } } export default chart; ================================================ FILE: cbpro-trader/web/src/reducers/index.js ================================================ import { combineReducers } from 'redux' import chart from './chart' import sidebar from './sidebar' export default combineReducers({ chart, sidebar }) ================================================ FILE: cbpro-trader/web/src/reducers/sidebar.js ================================================ const sidebar = (state = {indicators: [], flags: {}, balances: {}, orders: {'fills': [], 'orders': []}, primary_section: "periods", secondary_section: "details"}, action) => { switch (action.type) { case 'CHANGE_PRIMARY_SECTION': return { ...state, primary_section: action.section_name } case 'CHANGE_SECONDARY_SECTION': return { ...state, secondary_section: action.section_name } case 'UPDATE_BALANCES': return { ...state, balances: action.balances } case 'UPDATE_INDICATORS': return { ...state, indicators: action.indicators } case 'UPDATE_FLAGS': return { ...state, flags: action.flags } case 'UPDATE_ORDERS': return { ...state, orders: action.orders } default: return state } } export default sidebar; ================================================ FILE: cbpro-trader/web/src/serviceWorker.js ================================================ // This optional code is used to register a service worker. // register() is not called by default. // This lets the app load faster on subsequent visits in production, and gives // it offline capabilities. However, it also means that developers (and users) // will only see deployed updates on subsequent visits to a page, after all the // existing tabs open on the page have been closed, since previously cached // resources are updated in the background. // To learn more about the benefits of this model and instructions on how to // opt-in, read https://bit.ly/CRA-PWA const isLocalhost = Boolean( window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address. window.location.hostname === '[::1]' || // 127.0.0.1/8 is considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); export function register(config) { if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { // The URL constructor is available in all browsers that support SW. const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); if (publicUrl.origin !== window.location.origin) { // Our service worker won't work if PUBLIC_URL is on a different origin // from what our page is served on. This might happen if a CDN is used to // serve assets; see https://github.com/facebook/create-react-app/issues/2374 return; } window.addEventListener('load', () => { const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; if (isLocalhost) { // This is running on localhost. Let's check if a service worker still exists or not. checkValidServiceWorker(swUrl, config); // Add some additional logging to localhost, pointing developers to the // service worker/PWA documentation. navigator.serviceWorker.ready.then(() => { console.log( 'This web app is being served cache-first by a service ' + 'worker. To learn more, visit https://bit.ly/CRA-PWA' ); }); } else { // Is not localhost. Just register service worker registerValidSW(swUrl, config); } }); } } function registerValidSW(swUrl, config) { navigator.serviceWorker .register(swUrl) .then(registration => { registration.onupdatefound = () => { const installingWorker = registration.installing; if (installingWorker == null) { return; } installingWorker.onstatechange = () => { if (installingWorker.state === 'installed') { if (navigator.serviceWorker.controller) { // At this point, the updated precached content has been fetched, // but the previous service worker will still serve the older // content until all client tabs are closed. console.log( 'New content is available and will be used when all ' + 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' ); // Execute callback if (config && config.onUpdate) { config.onUpdate(registration); } } else { // At this point, everything has been precached. // It's the perfect time to display a // "Content is cached for offline use." message. console.log('Content is cached for offline use.'); // Execute callback if (config && config.onSuccess) { config.onSuccess(registration); } } } }; }; }) .catch(error => { console.error('Error during service worker registration:', error); }); } function checkValidServiceWorker(swUrl, config) { // Check if the service worker can be found. If it can't reload the page. fetch(swUrl) .then(response => { // Ensure service worker exists, and that we really are getting a JS file. const contentType = response.headers.get('content-type'); if ( response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1) ) { // No service worker found. Probably a different app. Reload the page. navigator.serviceWorker.ready.then(registration => { registration.unregister().then(() => { window.location.reload(); }); }); } else { // Service worker found. Proceed as normal. registerValidSW(swUrl, config); } }) .catch(() => { console.log( 'No internet connection found. App is running in offline mode.' ); }); } export function unregister() { if ('serviceWorker' in navigator) { navigator.serviceWorker.ready.then(registration => { registration.unregister(); }); } } ================================================ FILE: docker-compose.prod.yml ================================================ version: "3" services: cbpro: ports: - "8080:8080" environment: PRODUCTION: 'true' ================================================ FILE: docker-compose.yml ================================================ version: "3" services: cbpro: build: ./cbpro-trader/daemon command: python3 ./cbpro-trader.py volumes: - ./cbpro-trader/daemon/:/cbpro-trader/:Z web: build: ./cbpro-trader/web command: bash -c "npm install && npm start" volumes: - ./cbpro-trader/web/:/frontend/:Z