[
  {
    "path": ".gitignore",
    "content": ".DS_Store\n*.pyc\nconfig.yml\n*.log\n.pytest_cache\n__pycache__\n.vscode\ncbpro-trader/daemon/config.live\ncbpro-trader/daemon/config.sandbox\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# cbpro-trader\n\ncbpro-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.\n\nThe bot can monitor and trade any ticker supported by Coinbase Pro, and will even trade between cryptocurrencies if the opportunity is better.\n\n## Disclaimer\n\nThis 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.**\n\n## Installation\n### Docker\n\nA docker-compose file is included to try to ease installation.\n\nIf you are using the `web` frontend, you can simply run `docker-compose up` and then visit the URL provided by the frontend server.\n\nIf you are using the `curses` or `debug` frontends, you can run\n\n`docker-compose build cbpro`\n`docker run -it cbpro-trader_cbpro -v $ABSOLUTE_PATH_TO_PROJECT/cbpro-trader/cbpro-trader/daemon/:/cbpro-trader/:Z`\n\nto build and run the image, making sure to replace the absolute path of the project, then`python3 ./cbpro-trader.py` to start the bot\n\nYou will need to run `docker-compose up --build` if you change the config after the initial build.\n\n### Manual\n\nYou can install most requirements with\n\n`cd ./cbpro-trader`\n`pip install -r ./requirements.txt`\n\nthen run with\n\n`python3 ./cbpro-trader.py`\n\nNote that it is currently pointing to a custom version of the coinbasepro-python library until I can push my OrderBook changes upstream.\n\nAlso 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.\n\n## Configuration\n\nCopy config.yml.sample to config.yml and include your `key`, `secret`, and `passphrase` values from your Coinbase Pro API key.\n\n| Name         | Type    | Description                                                                      |\n| ------------ | ------- | -------------------------------------------------------------------------------- |\n| key          | string  | Coinbase API key                                                                 |\n| secret       | string  | Coinbase API secret                                                              |\n| passphrase   | string  | Coinbase API passphrase                                                          |\n| sandbox      | boolean | Set to 'yes' to use Coinbase sandbox servers (for testing)                       |\n| live         | boolean | Set to 'yes' to to toggle live trading                                           |\n| frontend     | string  | Which frontend to use - 'console', 'web' or 'debug'. See below for more info.    |\n| web_config   | boolean | Set to 'yes' to allow setting config from the web API                            |\n| logging      | boolean | Set to 'yes' to add additional logging to debug.log file                         |\n| fiat         | string  | Which fiat currency to use - e.g. 'USD' or 'EUR'                                 |\n| max_slippage | float   | Max percentage change in limit orders before executing a market order            |\n| periods      | list    | A YAML list of periods, each including the options listed in the periods section |\n\nFor each period in the `periods` list, include the following options\n\n| Name    | Type    | Description                                                                    |\n| ------- | ------- | ------------------------------------------------------------------------------ |\n| name    | string  | The display name of the period                                                 |\n| product | string  | The Coinbase product to trade                                                  |\n| length  | integer | The period length in minutes                                                   |\n| trade   | boolean | Set to 'yes' to trade this period                                              |\n| meta    | boolean | Set to 'yes' if this is a 'meta' product (one that does not exist on Coinbase) |\n\nSet `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.\n\nIn 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.\n\nThere 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).\n\n`frontend` can have the following values\n* `web` - a web based frontend to be viewed in your web browser (WORK IN PROGRESS)\n* `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.\n* `debug` used for debugging (obviously).\n\n## Tweaking indicators and trade logic\n\nI'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.\n\n### Design\n\nThe IndicatorSubsystem class contains several methods to calculate indicators. Simple ones are already included, such as `calculate_macd()` and `calculate_obv()`.\n\nThese methods write to the dictionary `IndicatorSubsystem.current_indicators` which is eventually used by `TradeEngine.determine_trades()` to determine if the bot should trade.\n\n### Adding indicators\n\nTo add a new indicator, first create the new method, following the naming convention. For example, if adding Simple Moving Average (SMA), `calculate_sma()`\n\nIn 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:\n\n`sma = talib.SMA(closing_prices, timeperiod=10)`\n\nNote that `closing_prices` and  `volumes` are already available in the IndicatorSubsystem.\n\nNow, 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.\n\n`self.current_indicators[period_name]['sma'] = sma[-1]`\n\n### Modifying trade logic\n\nTrade logic can obviously be modified as desired. Just make your decisions in `TradeEngine.determine_trades()`.\n\n`TradeEngine.determine_trades()` has access to the `IndicatorSubsystem.current_indicators` as `indicators`, as was discussed earlier.\n\nWhen 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.\n"
  },
  {
    "path": "cbpro-trader/daemon/Dockerfile",
    "content": "FROM ubuntu:18.04\n\n# Set locale\nENV LANG C.UTF-8\n# Allow for curses interface\nENV TERM xterm\n\n# Update Ubuntu & install system dependencies\nRUN apt-get update\nRUN apt-get upgrade -y\nRUN apt-get install -y python3 python3-pip git locales\n\n# Build and install ta-lib\nADD https://downloads.sourceforge.net/project/ta-lib/ta-lib/0.4.0/ta-lib-0.4.0-src.tar.gz /\nRUN tar xzvf ta-lib-0.4.0-src.tar.gz\nWORKDIR /ta-lib/\nRUN ./configure --prefix=/usr\nRUN make\nRUN make install\n\n# Copy bot files\nRUN mkdir -p /cbpro-trader\nCOPY ./requirements.txt /\n\n# Install Python dependencies\nWORKDIR /\nRUN pip3 install numpy==1.15.2\nRUN pip3 install -r ./requirements.txt\nWORKDIR /cbpro-trader/"
  },
  {
    "path": "cbpro-trader/daemon/cbpro-trader.py",
    "content": "#\n# bitcoin-trade.py\n# Mike Cardillo\n#\n# Main program for interacting with Coinbase Pro websocket and managing trade data\n\nimport cbpro\nimport period\nimport indicators\nimport engine\nimport yaml\nimport queue\nimport time\nimport interface\nimport logging\nimport datetime\nimport threading\nfrom decimal import Decimal\nfrom websocket import WebSocketConnectionClosedException\n\nclass CBProTrader(object):\n    def __init__(self):\n        with open(\"config.yml\", 'r') as ymlfile:\n            self.config = yaml.load(ymlfile, Loader=yaml.Loader)\n\n        self.logger = logging.getLogger('trader-logger')\n        self.logger.setLevel(logging.DEBUG)\n        if self.config['logging']:\n            self.logger.addHandler(logging.FileHandler(\"debug.log\"))\n        if self.config['frontend'] == 'debug':\n            self.logger.addHandler(logging.StreamHandler())\n        self.error_logger = logging.getLogger('error-logger')\n        self.error_logger.addHandler(logging.FileHandler(\"error.log\"))\n\n        self.initializing = False\n        self.web_interface = None\n        self.init_engine_and_indicators()\n\n    def init_interface(self):\n        if self.web_interface:\n            self.web_interface.indicator_subsys = self.indicator_subsys\n            self.web_interface.trade_engine = self.trade_engine\n        else:\n            if self.config['frontend'] == 'curses':\n                curses_enable = True\n            else:\n                curses_enable = False\n            self.interface = interface.cursesDisplay(enable=curses_enable)\n\n            if self.config['frontend'] == 'web':\n                self.web_interface = interface.web(self.indicator_subsys, self.trade_engine, self.config, self.init_engine_and_indicators)\n                self.server_thread = threading.Thread(target=self.web_interface.start, daemon=True)\n                self.server_thread.start()\n\n    def init_engine_and_indicators(self):\n        self.initializing = True\n        try:\n            self.cbpro_websocket.close()\n        except:\n            pass\n        # Periods to update indicators for\n        self.indicator_period_list = []\n        # Periods to actively trade on (typically 1 per product)\n        self.trade_period_list = {}\n        # List of products that we are actually monitoring\n        self.product_list = set()\n        fiat_currency = self.config['fiat']\n        if self.config['sandbox']:\n            api_url = \"https://api-public.sandbox.pro.coinbase.com\"\n        else:\n            api_url = \"https://api.pro.coinbase.com\"\n        auth_client = cbpro.AuthenticatedClient(self.config['key'], self.config['secret'], self.config['passphrase'], api_url=api_url)\n\n        for cur_period in self.config['periods']:\n            self.logger.debug(\"INITIALIZING %s\", cur_period['name'])\n            if cur_period.get('meta'):\n                new_period = period.MetaPeriod(period_size=(60 * cur_period['length']), fiat=fiat_currency,\n                                            product=cur_period['product'], name=cur_period['name'], cbpro_client=auth_client)\n            else:\n                new_period = period.Period(period_size=(60 * cur_period['length']),\n                                        product=cur_period['product'], name=cur_period['name'], cbpro_client=auth_client)\n            self.indicator_period_list.append(new_period)\n            self.product_list.add(cur_period['product'])\n            if cur_period['trade']:\n                if self.trade_period_list.get(cur_period['product']) is None:\n                    self.trade_period_list[cur_period['product']] = []\n                self.trade_period_list[cur_period['product']].append(new_period)\n        max_slippage = Decimal(str(self.config['max_slippage']))\n        self.trade_engine = engine.TradeEngine(auth_client, product_list=self.product_list, fiat=fiat_currency, is_live=self.config['live'], max_slippage=max_slippage)\n        self.cbpro_websocket = engine.TradeAndHeartbeatWebsocket(fiat=fiat_currency, sandbox=self.config['sandbox'])\n        self.cbpro_websocket.start()\n        self.indicator_period_list[0].verbose_heartbeat = True\n        self.indicator_subsys = indicators.IndicatorSubsystem(self.indicator_period_list)\n        self.last_indicator_update = time.time()\n\n        self.init_interface()\n        self.initializing = False\n\n    def start(self):\n        while(True):\n            if not self.initializing:\n                try:\n                    if self.cbpro_websocket.error:\n                        raise self.cbpro_websocket.error\n                    msg = self.cbpro_websocket.websocket_queue.get(timeout=15)\n                    for product in self.trade_engine.products:\n                        product.order_book.process_message(msg)\n                    if msg.get('type') == \"match\":\n                        for cur_period in self.indicator_period_list:\n                            cur_period.process_trade(msg)\n                        if time.time() - self.last_indicator_update >= 1.0:\n                            for cur_period in self.indicator_period_list:\n                                self.indicator_subsys.recalculate_indicators(cur_period)\n                            for product_id, period_list in self.trade_period_list.items():\n                                self.trade_engine.determine_trades(product_id, period_list, self.indicator_subsys.current_indicators)\n                            self.last_indicator_update = time.time()\n                    elif msg.get('type') == \"heartbeat\":\n                        for cur_period in self.indicator_period_list:\n                            cur_period.process_heartbeat(msg)\n                        for product_id, period_list in self.trade_period_list.items():\n                            if len(self.indicator_subsys.current_indicators[cur_period.name]) > 0:\n                                self.trade_engine.determine_trades(product_id, period_list, self.indicator_subsys.current_indicators)\n                        self.trade_engine.print_amounts()\n                    self.interface.update(self.trade_engine, self.indicator_subsys.current_indicators,\n                                    self.indicator_period_list, msg)\n                except KeyboardInterrupt:\n                    self.trade_engine.close(exit=True)\n                    self.cbpro_websocket.close()\n                    self.interface.close()\n                    break\n                except Exception as e:\n                    self.error_logger.exception(datetime.datetime.now())\n                    self.trade_engine.close()\n                    self.cbpro_websocket.close()\n                    self.cbpro_websocket.error = None\n                    # Period data cannot be trusted. Re-initialize\n                    for cur_period in self.indicator_period_list:\n                        cur_period.initialize()\n                    time.sleep(10)\n                    self.cbpro_websocket.start()\n\ncbprotrader = CBProTrader()\ncbprotrader.start()"
  },
  {
    "path": "cbpro-trader/daemon/config.yml.sample",
    "content": "key: mykey\nsecret: mysecret\npassphrase: mypassphrase\nsandbox: yes\nlive: no\nfrontend: curses\nweb_config: no\nlogging: no\nfiat: USD\nmax_slippage: 0.10\nperiods:\n  - name: BTC\n    product: BTC-USD\n    length: 5\n    trade: yes\n    meta: no\n  - name: ETH\n    product: ETH-USD\n    length: 15\n    trade: yes\n    meta: no\n  - name: LTC\n    product: LTC-USD\n    length: 30\n    trade: yes\n    meta: no\n  - name: LTCETH\n    product: LTC-ETH\n    length: 30\n    trade: no\n    meta: yes"
  },
  {
    "path": "cbpro-trader/daemon/engine/OrderBookCustom.py",
    "content": "import cbpro\nimport time\nimport logging\n\nclass OrderBookCustom(cbpro.OrderBook):\n    def __init__(self, product_id='BTC-USD', auth_client=None):\n        self.logger = logging.getLogger('trader-logger')\n        self.error_logger = logging.getLogger('error-logger')\n        super(OrderBookCustom, self).__init__(product_id=product_id)\n        if auth_client is not None:\n            self._client = auth_client\n\n    def is_ready(self):\n        try:\n            super(OrderBookCustom, self).get_ask()\n        except (ValueError, AttributeError):\n            return False\n        return True\n\n    def get_ask(self):\n        while not self.is_ready():\n            time.sleep(0.01)\n        return super(OrderBookCustom, self).get_ask()\n\n    def get_bid(self):\n        while not self.is_ready():\n            time.sleep(0.01)\n        return super(OrderBookCustom, self).get_bid()"
  },
  {
    "path": "cbpro-trader/daemon/engine/Product.py",
    "content": "import time\nfrom .OrderBookCustom import OrderBookCustom\n\nclass Product(object):\n    def __init__(self, auth_client, product_id='BTC-USD'):\n        self.product_id = product_id\n        self.order_book = OrderBookCustom(product_id=product_id, auth_client=auth_client)\n        self.order_in_progress = False\n        self.buy_flag = False\n        self.sell_flag = False\n        self.open_orders = []\n        self.order_thread = None\n        self.meta = True\n        self.last_signal_switch = time.time()\n\n        cbpro_products = auth_client.get_products()\n        while not isinstance(cbpro_products, list):\n            # May be rate limited\n            time.sleep(3)\n            cbpro_products = auth_client.get_products()\n\n        for cbpro_product in cbpro_products:\n            if product_id == cbpro_product.get('id'):\n                self.meta = False # If product_id is in response, it must be a real product\n                self.quote_increment = cbpro_product.get('quote_increment')\n                self.min_size = cbpro_product.get('base_min_size')"
  },
  {
    "path": "cbpro-trader/daemon/engine/TradeAndHeartbeatWebsocket.py",
    "content": "import datetime\nimport logging\nimport queue\nimport cbpro\nfrom websocket import WebSocketConnectionClosedException\n\nclass TradeAndHeartbeatWebsocket(cbpro.WebsocketClient):\n    def __init__(self, fiat='USD', sandbox=False):\n        self.logger = logging.getLogger('trader-logger')\n        self.error_logger = logging.getLogger('error-logger')\n        self.fiat_currency = fiat\n        self.products = [\"BTC-\" + self.fiat_currency, \"ETH-\" + self.fiat_currency]\n        self.channels = ['full', 'heartbeat']\n        if sandbox:\n            url=\"wss://ws-feed-public.sandbox.pro.coinbase.com\"\n        else:\n            url=\"wss://ws-feed.pro.coinbase.com\"\n        super(TradeAndHeartbeatWebsocket, self).__init__(products=self.products, channels=self.channels, url=url)\n\n\n    def on_open(self):\n        self.websocket_queue = queue.Queue()\n        self.stop = False\n        self.logger.debug(\"-- CBPRO Websocket Opened ---\")\n\n    def on_close(self):\n        self.logger.debug(\"-- CBPRO Websocket Closed ---\")\n\n    def on_error(self, e):\n        self.error_logger.exception(datetime.datetime.now())\n        self.error = e\n        self.stop = True\n        raise e\n\n    def close(self):\n        if not self.stop:\n            self.on_close()\n            self.stop = True\n            self.thread.join()\n            try:\n                if self.ws:\n                    self.ws.close()\n            except WebSocketConnectionClosedException:\n                self.error_logger.exception(datetime.datetime.now())\n                pass\n\n    def on_message(self, msg):\n        self.websocket_queue.put(msg)"
  },
  {
    "path": "cbpro-trader/daemon/engine/TradeEngine.py",
    "content": "import time\nimport logging\nimport threading\nimport datetime\nimport itertools\nfrom decimal import Decimal, ROUND_DOWN\nfrom .Product import Product\n\nclass TradeEngine():\n    def __init__(self, auth_client, product_list=['BTC-USD', 'ETH-USD', 'LTC-USD'], fiat='USD', is_live=False, max_slippage=Decimal('0.10')):\n        self.logger = logging.getLogger('trader-logger')\n        self.error_logger = logging.getLogger('error-logger')\n        self.auth_client = auth_client\n        self.product_list = product_list\n        self.fiat_currency = fiat\n        self.is_live = is_live\n        self.market_orders = True # TODO: make this a config option\n        self.available_products = []\n        self.products = []\n        self.balances = {}\n        self.stop_update_order_thread = False\n        self.last_order_update = time.time()\n        self.all_open_orders = []\n        self.recent_fills = []\n        for product in self.product_list:\n            self.products.append(Product(auth_client, product_id=product))\n        self.last_balance_update = 0\n        self.update_amounts()\n        self.init_available_products()\n        self.last_balance_update = time.time()\n        self.max_slippage = max_slippage\n        self.update_order_thread = threading.Thread(target=self.update_orders, name='update_orders')\n        self.update_order_thread.start()\n\n    def close(self, exit=False):\n        if exit:\n            self.stop_update_order_thread = True\n        for product in self.products:\n            # Setting both flags will close any open order threads\n            product.buy_flag = False\n            product.sell_flag = False\n            # Cancel any orders that may still be remaining\n            product.order_in_progress = False\n        try:\n            self.auth_client.cancel_all()\n        except Exception:\n            self.error_logger.exception(datetime.datetime.now())\n\n    def get_product_by_product_id(self, product_id='BTC-USD'):\n        for product in self.products:\n            if product.product_id == product_id:\n                return product\n        return None\n\n    def init_available_products(self):\n        for product in self.auth_client.get_products():\n            self.available_products.append(product.get('id'))\n\n    def update_orders(self):\n        while not self.stop_update_order_thread:\n            need_updating = False\n            for product in self.products:\n                if product.order_in_progress:\n                    need_updating = True\n\n            if time.time() - self.last_order_update >= 1.0:\n                self.temp_recent_fills = []\n                try:\n                    for product in self.products:\n                        self.temp_recent_fills += list(itertools.islice(self.auth_client.get_fills(product_id=product.product_id), 5))\n                        self.recent_fills = sorted(self.temp_recent_fills, key=lambda x: x['created_at'], reverse=True)[:5]\n                except Exception:\n                    self.error_logger.exception(datetime.datetime.now())\n                if need_updating:\n                    try:\n                        self.all_open_orders = list(self.auth_client.get_orders())\n                        for product in self.products:\n                            product.open_orders = []\n                        for order in self.all_open_orders:\n                            self.get_product_by_product_id(order.get('product_id')).open_orders.append(order)\n                    except Exception:\n                        self.error_logger.exception(datetime.datetime.now())\n                elif not need_updating:\n                    self.all_open_orders = []\n                self.last_order_update = time.time()\n            time.sleep(0.01)\n\n    def round_fiat(self, money):\n        return Decimal(money).quantize(Decimal('.01'), rounding=ROUND_DOWN)\n\n    def round_coin(self, money):\n        return Decimal(money).quantize(Decimal('.00000001'), rounding=ROUND_DOWN)\n\n    def update_amounts(self):\n        if time.time() - self.last_balance_update > 1.0:\n            try:\n                self.last_balance_update = time.time()\n                ret = self.auth_client.get_accounts()\n                if isinstance(ret, list):\n                    for account in ret:\n                        self.balances[account['currency']] = self.round_coin(account.get('available'))\n            except Exception:\n                self.error_logger.exception(datetime.datetime.now())\n                return\n            self.balances['fiat_equivalent'] = Decimal('0.0')\n            for product in self.products:\n                if not product.meta and product.order_book.get_current_ticker() and product.order_book.get_current_ticker().get('price'):\n                    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'))\n            self.balances['fiat_equivalent'] += self.balances[self.fiat_currency]\n\n    def print_amounts(self):\n        self.logger.debug(\"[BALANCES] %s: %.2f BTC: %.8f\" % (self.fiat_currency, self.balances[self.fiat_currency], self.balances['BTC']))\n\n    def place_buy(self, product=None, partial='1.0'):\n        amount = self.get_quoted_currency_from_product_id(product.product_id) * Decimal(partial)\n        bid = product.order_book.get_ask() - Decimal(product.quote_increment)\n        amount = self.round_coin(Decimal(amount) / Decimal(bid))\n\n        if amount < Decimal(product.min_size):\n            amount = self.get_quoted_currency_from_product_id(product.product_id)\n            bid = product.order_book.get_ask() - Decimal(product.quote_increment)\n            amount = self.round_coin(Decimal(amount) / Decimal(bid))\n\n        if amount >= Decimal(product.min_size):\n            self.logger.debug(\"Placing buy... Price: %.8f Size: %.8f\" % (bid, amount))\n            ret = self.auth_client.place_limit_order(product.product_id, \"buy\", size=str(amount),\n                                                     price=str(bid), post_only=True)\n            if ret.get('status') == 'pending' or ret.get('status') == 'open':\n                product.open_orders.append(ret)\n            return ret\n        else:\n            ret = {'status': 'done'}\n            return ret\n\n    def buy(self, product=None, amount=None):\n        product.order_in_progress = True\n        last_order_update = 0\n        starting_price = product.order_book.get_ask() - Decimal(product.quote_increment)\n        try:\n            ret = self.place_buy(product=product, partial='0.5')\n            bid = ret.get('price')\n            amount = self.get_quoted_currency_from_product_id(product.product_id)\n            while product.buy_flag and (amount >= Decimal(product.min_size) or len(product.open_orders) > 0):\n                if (((product.order_book.get_ask() - Decimal(product.quote_increment)) / starting_price) - Decimal('1.0')) * Decimal('100.0') > self.max_slippage:\n                    self.auth_client.cancel_all(product_id=product.product_id)\n                    self.auth_client.place_market_order(product.product_id, \"buy\", funds=str(self.get_quoted_currency_from_product_id(product.product_id)))\n                    product.order_in_progress = False\n                    return\n                if ret.get('status') == 'rejected' or ret.get('status') == 'done' or ret.get('message') == 'NotFound':\n                    ret = self.place_buy(product=product, partial='0.5')\n                    bid = ret.get('price')\n                elif not bid or Decimal(bid) < product.order_book.get_ask() - Decimal(product.quote_increment):\n                    if len(product.open_orders) > 0:\n                        ret = self.place_buy(product=product, partial='1.0')\n                    else:\n                        ret = self.place_buy(product=product, partial='0.5')\n                    for order in product.open_orders:\n                        if order.get('id') != ret.get('id'):\n                            self.auth_client.cancel_order(order.get('id'))\n                    bid = ret.get('price')\n                if ret.get('id') and time.time() - last_order_update >= 1.0:\n                    try:\n                        ret = self.auth_client.get_order(ret.get('id'))\n                        last_order_update = time.time()\n                    except ValueError:\n                        self.error_logger.exception(datetime.datetime.now())\n                        pass\n                amount = self.get_quoted_currency_from_product_id(product.product_id)\n                time.sleep(0.01)\n            self.auth_client.cancel_all(product_id=product.product_id)\n            amount = self.get_quoted_currency_from_product_id(product.product_id)\n        except Exception:\n            product.order_in_progress = False\n            self.error_logger.exception(datetime.datetime.now())\n        self.auth_client.cancel_all(product_id=product.product_id)\n        product.order_in_progress = False\n\n    def place_sell(self, product=None, partial='1.0'):\n        amount = self.round_coin(self.get_base_currency_from_product_id(product.product_id) * Decimal(partial))\n        if amount < Decimal(product.min_size):\n            amount = self.get_base_currency_from_product_id(product.product_id)\n        ask = product.order_book.get_bid() + Decimal(product.quote_increment)\n\n        if amount >= Decimal(product.min_size):\n            self.logger.debug(\"Placing sell... Price: %.2f Size: %.8f\" % (ask, amount))\n            ret = self.auth_client.place_limit_order(product.product_id, \"sell\", size=str(amount),\n                                                     price=str(ask), post_only=True)\n            if ret.get('status') == 'pending' or ret.get('status') == 'open':\n                product.open_orders.append(ret)\n            return ret\n        else:\n            ret = {'status': 'done'}\n            return ret\n\n    def sell(self, product=None, amount=None):\n        product.order_in_progress = True\n        last_order_update = 0\n        starting_price = product.order_book.get_bid() + Decimal(product.quote_increment)\n        try:\n            ret = self.place_sell(product=product, partial='0.5')\n            ask = ret.get('price')\n            amount = self.get_base_currency_from_product_id(product.product_id)\n            while product.sell_flag and (amount >= Decimal(product.min_size) or len(product.open_orders) > 0):\n                if (Decimal('1') - ((product.order_book.get_bid() + Decimal(product.quote_increment)) / starting_price)) * Decimal('100.0') > self.max_slippage:\n                    self.auth_client.cancel_all(product_id=product.product_id)\n                    self.auth_client.place_market_order(product.product_id, \"sell\", size=str(self.get_base_currency_from_product_id(product.product_id)))\n                    product.order_in_progress = False\n                    return\n                if ret.get('status') == 'rejected' or ret.get('status') == 'done' or ret.get('message') == 'NotFound':\n                    ret = self.place_sell(product=product, partial='0.5')\n                    ask = ret.get('price')\n                elif not ask or Decimal(ask) > product.order_book.get_bid() + Decimal(product.quote_increment):\n                    if len(product.open_orders) > 0:\n                        ret = self.place_sell(product=product, partial='1.0')\n                    else:\n                        ret = self.place_sell(product=product, partial='0.5')\n                    for order in product.open_orders:\n                        if order.get('id') != ret.get('id'):\n                            self.auth_client.cancel_order(order.get('id'))\n                    ask = ret.get('price')\n                if ret.get('id') and time.time() - last_order_update >= 1.0:\n                    try:\n                        ret = self.auth_client.get_order(ret.get('id'))\n                    except ValueError:\n                        self.error_logger.exception(datetime.datetime.now())\n                        pass\n                    last_order_update = time.time()\n                amount = self.get_base_currency_from_product_id(product.product_id)\n                time.sleep(0.01)\n            self.auth_client.cancel_all(product_id=product.product_id)\n            amount = self.get_base_currency_from_product_id(product.product_id)\n        except Exception:\n            product.order_in_progress = False\n            self.error_logger.exception(datetime.datetime.now())\n        self.auth_client.cancel_all(product_id=product.product_id)\n        product.order_in_progress = False\n\n    def get_base_currency_from_product_id(self, product_id, update=True):\n        if update:\n            self.update_amounts()\n        return self.balances[product_id[:3]]\n\n    def get_quoted_currency_from_product_id(self, product_id):\n        self.update_amounts()\n        return self.balances[product_id[4:]]\n\n    def determine_trades(self, product_id, period_list, indicators):\n        self.update_amounts()\n\n        if self.is_live:\n            product = self.get_product_by_product_id(product_id)\n\n            new_buy_flag = True\n            new_sell_flag = False\n            for cur_period in period_list:\n                # Moving Average Strategy\n                new_buy_flag = new_buy_flag and Decimal(indicators[cur_period.name]['sma_trend']) > Decimal('0.0')\n                new_sell_flag = new_sell_flag or Decimal(indicators[cur_period.name]['sma_trend']) < Decimal('0.0')\n\n            if product_id == 'LTC-BTC' or product_id == 'ETH-BTC':\n                ltc_or_eth_fiat_product = self.get_product_by_product_id(product_id[:3] + '-' + self.fiat_currency)\n                btc_fiat_product = self.get_product_by_product_id('BTC-' + self.fiat_currency)\n                new_buy_flag = new_buy_flag and ltc_or_eth_fiat_product.buy_flag\n                new_sell_flag = new_sell_flag and btc_fiat_product.buy_flag\n\n            if new_buy_flag:\n                if product.sell_flag:\n                    product.last_signal_switch = time.time()\n                product.sell_flag = False\n                product.buy_flag = True\n                amount = self.round_fiat(self.get_quoted_currency_from_product_id(product_id))\n                if amount >= Decimal(product.min_size):\n                    if self.market_orders:\n                        ret = self.auth_client.place_market_order(product.product_id, \"buy\", funds=str(amount))\n                        self.logger.debug(ret)\n                        self.logger.debug(amount)\n                    else:\n                        if not product.order_in_progress:\n                            bid = product.order_book.get_ask() - Decimal(product.quote_increment)\n                            amount = self.round_coin(Decimal(amount) / Decimal(bid))\n                            product.order_thread = threading.Thread(target=self.buy, name='buy_thread', kwargs={'product': product})\n                            product.order_thread.start()\n            elif new_sell_flag:\n                if product.buy_flag:\n                    product.last_signal_switch = time.time()\n                product.buy_flag = False\n                product.sell_flag = True\n                amount_of_coin = self.round_coin(self.get_base_currency_from_product_id(product_id))\n                if amount_of_coin >= Decimal(product.min_size):\n                    if self.market_orders:\n                        self.auth_client.place_market_order(product.product_id, \"sell\", size=str(amount_of_coin))\n                    else:\n                        if not product.order_in_progress:\n                            product.order_thread = threading.Thread(target=self.sell, name='sell_thread', kwargs={'product': product})\n                            product.order_thread.start()\n            else:\n                product.buy_flag = False\n                product.sell_flag = False\n"
  },
  {
    "path": "cbpro-trader/daemon/engine/__init__.py",
    "content": "from .OrderBookCustom import OrderBookCustom\nfrom .Product import Product\nfrom .TradeEngine import TradeEngine\nfrom .TradeAndHeartbeatWebsocket import TradeAndHeartbeatWebsocket"
  },
  {
    "path": "cbpro-trader/daemon/indicators/IndicatorSubsystem.py",
    "content": "import talib\nimport logging\nimport numpy as np\nfrom decimal import Decimal\n\n\nclass IndicatorSubsystem:\n    def __init__(self, period_list):\n        self.logger = logging.getLogger('trader-logger')\n        self.current_indicators = {}\n        self.period_list = period_list\n        for period in self.period_list:\n            self.current_indicators[period.name] = {}\n\n    def recalculate_indicators(self, cur_period):\n        total_periods = len(cur_period.candlesticks)\n        if total_periods > 0:\n            closing_prices = cur_period.get_closing_prices()\n            closing_prices_close = np.append(closing_prices, cur_period.cur_candlestick.close)\n            self.highs = np.append(cur_period.get_highs(), cur_period.cur_candlestick.high)\n            self.lows = np.append(cur_period.get_lows(), cur_period.cur_candlestick.low)\n            volumes = np.append(cur_period.get_volumes(), cur_period.cur_candlestick.volume)\n\n            self.calculate_sma(cur_period.name, closing_prices_close)\n\n            self.current_indicators[cur_period.name]['close'] = cur_period.cur_candlestick.close\n            self.current_indicators[cur_period.name]['total_periods'] = total_periods\n\n    def calculate_sma(self, period_name, closing_prices):\n        sma = talib.SMA(closing_prices, timeperiod=9)\n\n        self.current_indicators[period_name]['sma'] = sma[-1]\n        self.current_indicators[period_name]['sma_trend'] = sma[-1] - sma[-2]\n\n    def calculate_adx(self, period_name, close):\n        adx = talib.ADX(self.highs, self.lows, close, timeperiod=14)\n\n        self.current_indicators[period_name]['adx'] = adx[-1]\n\n    def calculate_bbands(self, period_name, close):\n        timeperiod = 20\n        upperband_1, middleband_1, lowerband_1 = talib.BBANDS(close, timeperiod=timeperiod, nbdevup=1, nbdevdn=1, matype=0)\n\n        self.current_indicators[period_name]['bband_upper_1'] = upperband_1[-1]\n        self.current_indicators[period_name]['bband_lower_1'] = lowerband_1[-1]\n\n        upperband_2, middleband_2, lowerband_2 = talib.BBANDS(close, timeperiod=timeperiod, nbdevup=2, nbdevdn=2, matype=0)\n\n        self.current_indicators[period_name]['bband_upper_2'] = upperband_2[-1]\n        self.current_indicators[period_name]['bband_lower_2'] = lowerband_2[-1]\n\n    def calculate_macd(self, period_name, closing_prices):\n        macd, macd_sig, macd_hist = talib.MACD(closing_prices, fastperiod=12,\n                                               slowperiod=26, signalperiod=9)\n        self.current_indicators[period_name]['macd'] = macd[-1]\n        self.current_indicators[period_name]['macd_sig'] = macd_sig[-1]\n        self.current_indicators[period_name]['macd_hist'] = macd_hist[-1]\n        self.current_indicators[period_name]['macd_hist_diff'] = Decimal(macd_hist[-1]) - Decimal(macd_hist[-2])\n\n    def calculate_vol_macd(self, period_name, volumes):\n        macd, macd_sig, macd_hist = talib.MACD(volumes, fastperiod=50,\n                                               slowperiod=200, signalperiod=14)\n        self.current_indicators[period_name]['vol_macd'] = macd[-1]\n        self.current_indicators[period_name]['vol_macd_sig'] = macd_sig[-1]\n        self.current_indicators[period_name]['vol_macd_hist'] = macd_hist[-1]\n\n    def calculate_avg_volume(self, period_name, volumes):\n        avg_vol = talib.SMA(volumes, timeperiod=15)\n\n        self.current_indicators[period_name]['avg_volume'] = avg_vol[-1]\n\n    def calculate_obv(self, period_name, closing_prices, volumes):\n        obv = talib.OBV(closing_prices, volumes)\n        obv_ema = talib.EMA(obv, timeperiod=3)\n\n        self.current_indicators[period_name]['obv_ema'] = obv_ema[-1]\n        self.current_indicators[period_name]['obv'] = obv[-1]\n\n    def calculate_sar(self, period_name, highs, lows):\n        sar = talib.SAR(highs, lows)\n\n        self.current_indicators[period_name]['sar'] = sar[-1]\n\n    def calculate_stochrsi(self, period_name, closing_prices):\n        fastk, fastd = talib.STOCHRSI(closing_prices, timeperiod=14, fastk_period=3, fastd_period=3, fastd_matype=0)\n        self.current_indicators[period_name]['stochrsi_fastk'] = fastk[-1]\n        self.current_indicators[period_name]['stochrsi_fastd'] = fastd[-1]\n\n    def calculate_stoch(self, period_name, closing_prices):\n        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)\n        self.current_indicators[period_name]['stoch_slowk'] = slowk[-1]\n        self.current_indicators[period_name]['stoch_slowd'] = slowd[-1]\n\n    def calculate_mfi(self, period_name, highs, lows, closing_prices, volumes):\n        mfi = talib.MFI(highs, lows, closing_prices, volumes)\n\n        self.current_indicators[period_name]['mfi'] = mfi[-1]"
  },
  {
    "path": "cbpro-trader/daemon/indicators/__init__.py",
    "content": "from .IndicatorSubsystem import IndicatorSubsystem"
  },
  {
    "path": "cbpro-trader/daemon/interface/__init__.py",
    "content": "from .cursesDisplay import cursesDisplay\nfrom .web import web"
  },
  {
    "path": "cbpro-trader/daemon/interface/cursesDisplay.py",
    "content": "import curses\nimport time\nimport logging\nfrom decimal import Decimal\n\n\nclass cursesDisplay:\n    def __init__(self, enable=True):\n        self.enable = enable\n        if not self.enable:\n            return\n        self.logger = logging.getLogger('trader-logger')\n        self.stdscr = curses.initscr()\n        self.pad = curses.newpad(23, 120)\n        self.order_pad = curses.newpad(10, 120)\n        self.timestamp = \"\"\n        self.last_order_update = 0\n        curses.start_color()\n        curses.noecho()\n        curses.cbreak()\n        curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_GREEN)\n        curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_RED)\n        self.stdscr.keypad(1)\n        self.pad.addstr(1, 0, \"Waiting for a trade...\")\n\n    def update_balances(self, trade_engine):\n        self.pad.addstr(0, 0, \"%s: %.2f BTC: %.8f\" %\n                        (trade_engine.fiat_currency, trade_engine.balances[trade_engine.fiat_currency], trade_engine.balances['BTC']))\n        self.pad.addstr(1, 0, \"%s_EQUIV: %.2f\" %\n                        (trade_engine.fiat_currency, trade_engine.balances['fiat_equivalent']))\n\n    def update_candlesticks(self, period_list):\n        starty = self.starty\n        if starty < self.signal_end_y + 1:\n            starty = self.signal_end_y + 1\n        for cur_period in period_list:\n            cur_stick = cur_period.cur_candlestick\n            if cur_stick.new is False:\n                self.pad.addstr(starty, 0, \"%s - %s O: %f H: %f L: %f C: %f V: %f\" %\n                                (cur_period.name, cur_stick.time, cur_stick.open,\n                                 cur_stick.high, cur_stick.low, cur_stick.close,\n                                 cur_stick.volume),\n                                self.print_color(cur_stick.close, cur_stick.open))\n            starty += 1\n        self.starty = starty\n\n    def update_heartbeat(self):\n        self.pad.addstr(0, 83, self.timestamp)\n\n    def update_indicators(self, period_list, indicators):\n        starty = self.starty\n        for cur_period in period_list:\n            stoch_diff = Decimal(indicators[cur_period.name]['stoch_slowk']) - Decimal(indicators[cur_period.name]['stoch_slowd'])\n            obv_diff = Decimal(indicators[cur_period.name]['obv']) - Decimal(indicators[cur_period.name]['obv_ema'])\n            self.pad.addstr(starty, 0, \"%s - OBV_DIFF: %f STOCH_DIFF: %f ADX: %f\" %\n                            (cur_period.name, obv_diff, stoch_diff, indicators[cur_period.name]['adx']),\n                            self.print_color(Decimal(obv_diff), Decimal('0.0')))\n            starty += 1\n        self.starty = starty + 1\n\n    def update_fills(self, trade_engine):\n        self.pad.addstr(9, 0, \"Recent Fills\")\n        starty = 10\n        for fill in trade_engine.auth_client.get_fills(limit=5)[0]:\n            self.pad.addstr(starty, 0, \"%s Price: %s Size: %s Time: %s\" %\n                            (fill.get('side').upper(), fill.get('price'),\n                             fill.get('size'), fill.get('created_at')))\n            starty += 1\n\n    def update_orders(self, trade_engine):\n        starty = 0\n        self.order_pad.addstr(starty, 0, \"Open Orders\")\n\n        if time.time() - self.last_order_update > 3.0:\n            self.order_pad.erase()\n            self.order_pad.addstr(starty, 0, \"Open Orders\")\n            order_in_progress = False\n            # First check if trade engine has any open orders\n            for product in trade_engine.products:\n                if product.order_in_progress:\n                    order_in_progress = True\n            starty += 1\n            if not trade_engine.all_open_orders:\n                self.order_pad.addstr(starty, 0, 'None')\n            for order in trade_engine.all_open_orders:\n                self.order_pad.addstr(starty, 0, \"%s %s Price: %s Size: %s Status: %s\" %\n                                        (order.get('side').upper(), order.get('product_id'),\n                                        order.get('price'), order.get('size'),\n                                        order.get('status')))\n                starty += 1\n            self.last_order_update = time.time()\n            height, width = self.stdscr.getmaxyx()\n            if height > (self.padsize + 1):\n                self.order_pad.refresh(0, 0, (self.padsize + 1), 0, (height - 1), (width - 1))\n\n    def update_signals(self, trade_engine):\n        starty = 1\n        for product in trade_engine.products:\n            if product.buy_flag:\n                text = 'BUY'\n                color = curses.color_pair(1)\n            elif product.sell_flag:\n                text = 'SELL'\n                color = curses.color_pair(2)\n            else:\n                text = 'NONE'\n                color = curses.color_pair(0)\n            self.pad.addstr(starty, 93, \"%s: %s\" % (product.product_id, text), color)\n            starty += 1\n        self.signal_end_y = starty\n\n    def update(self, trade_engine, indicators, period_list, msg):\n        if not self.enable:\n            return\n        self.padsize = (len(period_list) * 2) + 3\n        self.pad.resize(self.padsize, 120)\n\n        self.starty = 2\n        if msg.get('type') == \"heartbeat\":\n            self.timestamp = msg.get('time')\n        self.pad.erase()\n        self.update_balances(trade_engine)\n        self.update_heartbeat()\n        self.update_signals(trade_engine)\n        # Make sure indicator dict is populated\n        if len(indicators[period_list[0].name]) > 0:\n            self.update_indicators(period_list, indicators)\n        self.update_candlesticks(period_list)\n        self.update_orders(trade_engine)\n\n        height, width = self.stdscr.getmaxyx()\n        self.pad.refresh(0, 0, 0, 0, (height - 1), (width - 1))\n\n    def print_color(self, a, b, c=None, d=None):\n        # If a > b, print green, otherwise red\n        if c and d:\n            if Decimal(a) > Decimal(b) and Decimal(c) > Decimal(d):\n                return curses.color_pair(1)\n            else:\n                return curses.color_pair(2)\n        else:\n            if Decimal(a) > Decimal(b):\n                return curses.color_pair(1)\n            else:\n                return curses.color_pair(2)\n\n    def close(self):\n        if not self.enable:\n            return\n        curses.nocbreak()\n        self.stdscr.keypad(0)\n        curses.echo()\n        curses.endwin()"
  },
  {
    "path": "cbpro-trader/daemon/interface/web.py",
    "content": "import os\nfrom flask import Flask, request, jsonify\nfrom gevent.pywsgi import WSGIServer\n\nclass web(object):\n    def __init__(self, indicator_subsys, trade_engine, config, init_engine_and_indicators):\n        self.indicator_subsys = indicator_subsys\n        self.trade_engine = trade_engine\n        self.config = config\n        self.init_engine_and_indicators = init_engine_and_indicators\n        app = Flask(__name__)\n        self.app = app\n\n        @app.route('/products/')\n        def products():\n            return jsonify(self.trade_engine.available_products)\n    \n        @app.route('/periods/')\n        @app.route('/periods/<periodName>')\n        def periods(periodName=None):\n            period_data = []\n            if periodName is None:\n                for period in self.indicator_subsys.period_list:\n                    period_data.append(period.name)\n                return jsonify(period_data)\n            else:\n                for period in self.indicator_subsys.period_list:\n                    if period.name == periodName:\n                        period_data = period.candlesticks.tolist() + [period.cur_candlestick.to_list()]\n                return jsonify([{\n                                'time': stick[0].timestamp(), \n                                'low': stick[1],\n                                'high': stick[2],\n                                'open': stick[3],\n                                'close': stick[4]\n                                }\n                                for stick in period_data])\n\n        @app.route('/indicators/')\n        @app.route('/indicators/<periodName>')\n        def indicators(periodName=None):\n            if periodName is None:\n                return jsonify(self.indicator_subsys.current_indicators)\n            else:\n                return jsonify(self.indicator_subsys.current_indicators.get(periodName))\n\n        @app.route('/orders/')\n        @app.route('/orders/<productId>')\n        def orders(productId=None):\n            return jsonify({'orders': trade_engine.all_open_orders, 'fills': trade_engine.recent_fills})\n\n        @app.route('/balances/')\n        @app.route('/balances/<currency>')\n        def balances(currency=None):\n            balances = trade_engine.balances.copy()\n            for key in balances:\n                balances[key] = '{0:.8f}'.format(balances[key])\n            return jsonify(balances)\n\n        @app.route('/flags/')\n        def flags():\n            flags = {}\n            for product in self.trade_engine.products:\n                if product.buy_flag is True:\n                    flags[product.product_id] = \"buy\"\n                else:\n                    flags[product.product_id] = \"sell\"\n            return jsonify(flags)\n\n        @app.route('/config/', methods=['GET', 'POST'])\n        def config(periodName=None):\n            if self.config.get(\"web_config\"):\n                if request.method == 'POST':\n                    self.trade_engine.close()\n                    new_config = request.get_json()\n                    self.config.update(new_config)\n                    init_engine_and_indicators()\n\n                # Remove key/secret info from the response\n                new_config = self.config.copy()\n                del new_config['key']\n                del new_config['secret']\n                del new_config['passphrase']\n            else:\n                new_config = {'web_config': False}\n\n            return jsonify(new_config)\n\n    def start(self):\n        if 'PRODUCTION' in os.environ:\n            http_server = WSGIServer(('', 8080), self.app)\n            http_server.serve_forever()\n        else:\n            self.app.run(host='0.0.0.0')"
  },
  {
    "path": "cbpro-trader/daemon/period/Candlestick.py",
    "content": "import logging\nimport numpy as np\n\nclass Candlestick:\n    def __init__(self, isotime=None, existing_candlestick=None, prev_close=None):\n        self.logger = logging.getLogger('trader-logger')\n        self.new = True\n        if isotime:\n            self.time = isotime.replace(second=0, microsecond=0)\n            self.volume = 0\n            if prev_close:\n                self.open = prev_close\n                self.high = prev_close\n                self.low = prev_close\n                self.close = prev_close\n            else:\n                self.time = isotime.replace(second=0, microsecond=0)\n                self.open = None\n                self.high = None\n                self.low = None\n                self.close = None\n\n        elif existing_candlestick is not None:\n            self.new = False\n            self.time, self.low, self.high, self.open, self.close, self.volume = existing_candlestick\n\n    def add_trade(self, new_trade):\n        self.new = False\n        if not self.open:\n            self.open = new_trade.price\n\n        if not self.high:\n            self.high = new_trade.price\n        elif new_trade.price > self.high:\n            self.high = new_trade.price\n\n        if not self.low:\n            self.low = new_trade.price\n        elif new_trade.price < self.low:\n            self.low = new_trade.price\n\n        self.close = new_trade.price\n        self.volume = self.volume + new_trade.volume\n        self.logger.debug(\"[TRADE] Time: %s Price: %f Vol: %f\" %\n                          (new_trade.time, new_trade.price, new_trade.volume))\n\n    def close_candlestick(self, period_name, prev_stick=None):\n        self.logger.debug(\"Candlestick Closed!\")\n        if self.close is None:\n            self.new = False\n            self.open = prev_stick[4]  # Closing price\n            self.high = prev_stick[4]\n            self.low = prev_stick[4]\n            self.close = prev_stick[4]\n        self.print_stick(period_name)\n        return np.array([self.time, self.low, self.high, self.open,\n                        self.close, self.volume])\n\n    def to_list(self):\n        return [self.time, self.low, self.high, self.open,\n                        self.close, self.volume]\n\n    def print_stick(self, period_name):\n        self.logger.debug(\"[CANDLESTICK %s] Time: %s Open: %s High: %s Low: %s Close: %s Vol: %s\" %\n                          (period_name, self.time, self.open, self.high, self.low,\n                           self.close, self.volume))\n"
  },
  {
    "path": "cbpro-trader/daemon/period/MetaPeriod.py",
    "content": "import copy\nimport cbpro\nimport datetime\nimport time\nimport numpy as np\nimport pytz\nfrom decimal import Decimal\nfrom .Period import Period\n\nclass MetaPeriod(Period):\n    def __init__(self, period_size=60, name='Period', product='BTC-USD', fiat='USD', initialize=True, cbpro_client=cbpro.PublicClient()):\n        self.base = product[:3] + '-' + fiat\n        self.quoted = product[4:] + '-' + fiat\n        super(MetaPeriod, self).__init__(period_size=period_size, name=name, product=product, initialize=True, cbpro_client=cbpro_client)\n\n    def process_trade(self, msg):\n        newmsg = copy.deepcopy(msg)\n        if msg.get('product_id') == self.base:\n            newmsg['product_id'] = self.product\n            quoted_last = Decimal(msg.get('price')) / Decimal(self.cur_candlestick.close)\n            total_price = quoted_last + Decimal(msg.get('price'))\n            newmsg['size'] = Decimal(msg.get('size')) * (Decimal(msg.get('price')) / total_price)\n            newmsg['price'] = Decimal(msg.get('price')) / quoted_last\n        elif msg.get('product_id') == self.quoted:\n            newmsg['product_id'] = self.product\n            base_last = Decimal(self.cur_candlestick.close) * Decimal(msg.get('price'))\n            total_price = base_last + Decimal(msg.get('price'))\n            newmsg['size'] = Decimal(msg.get('size')) * (Decimal(msg.get('price')) / total_price)\n            newmsg['price'] = base_last / Decimal(msg.get('price'))\n        super(MetaPeriod, self).process_trade(msg=newmsg)\n\n    def get_historical_data(self, num_periods=200):\n        end = datetime.datetime.utcnow()\n        end_iso = end.isoformat()\n        start = end - datetime.timedelta(seconds=(self.period_size * num_periods))\n        start_iso = start.isoformat()\n\n        ret_base = self.cbpro_client.get_product_historic_rates(self.base, granularity=self.period_size, start=start_iso, end=end_iso)\n        ret_quoted = self.cbpro_client.get_product_historic_rates(self.quoted, granularity=self.period_size, start=start_iso, end=end_iso)\n        # Check if we got rate limited, which will return a JSON message\n        while not isinstance(ret_base, list):\n            time.sleep(3)\n            ret_base = self.cbpro_client.get_product_historic_rates(self.base, granularity=self.period_size, start=start_iso, end=end_iso)\n        while not isinstance(ret_quoted, list):\n            time.sleep(3)\n            ret_quoted = self.cbpro_client.get_product_historic_rates(self.quoted, granularity=self.period_size, start=start_iso, end=end_iso)\n        hist_data_base = np.array(ret_base, dtype='object')\n        hist_data_quoted = np.array(ret_quoted, dtype='object')\n        array_size = min(len(ret_base), len(ret_quoted))\n        hist_data_base.resize(array_size, 6)\n        hist_data_quoted.resize(array_size, 6)\n\n        for row in hist_data_base:\n            row[0] = datetime.datetime.fromtimestamp(row[0], pytz.utc)\n        for row in hist_data_quoted:\n            row[0] = datetime.datetime.fromtimestamp(row[0], pytz.utc)\n\n        hist_data = np.ndarray((len(hist_data_base), 6), dtype='object')\n        hist_data[:, 0] = hist_data_base[:, 0]\n        hist_data[:, [1,2,3,4]] = hist_data_base[:, [1,2,3,4]]/hist_data_quoted[:, [1,2,3,4]]\n        total_price = (hist_data_base[:, 4] + hist_data_quoted[:, 4])\n        hist_data[:, 5] = ((hist_data_base[:, 4] / total_price) * hist_data_base[:, 5]) + ((hist_data_base[:, 4] / total_price)  * hist_data_quoted[:, 5])\n        hist_data[:, 5] = hist_data[:, 5] * hist_data[:, 4]\n        return np.flipud(hist_data)"
  },
  {
    "path": "cbpro-trader/daemon/period/Period.py",
    "content": "import logging\nimport cbpro\nimport datetime\nimport time\nimport dateutil\nimport pytz\nimport trade\nimport numpy as np\nfrom .Candlestick import Candlestick\n\nclass Period:\n    def __init__(self, period_size=60, name='Period', product='BTC-USD', initialize=True, cbpro_client=cbpro.PublicClient()):\n        self.period_size = period_size\n        self.name = name\n        self.product = product\n        self.first_trade = True\n        self.verbose_heartbeat = False\n        # CBPRO historical data is not up-to-date\n        # We need to update data 10 minutes after closing the first period\n        self.updated_hist_data = False\n        self.time_of_first_candlestick_close = None\n        self.logger = logging.getLogger('trader-logger')\n        self.error_logger = logging.getLogger('error-logger')\n        self.cbpro_client = cbpro_client\n        if initialize:\n            self.initialize()\n        else:\n            self.candlesticks = np.array([])\n\n    def initialize(self):\n        self.candlesticks = self.get_historical_data()\n        self.cur_candlestick = Candlestick(existing_candlestick=self.candlesticks[-1])\n        self.candlesticks = self.candlesticks[:-1]\n        self.cur_candlestick_start = self.cur_candlestick.time\n\n    def get_historical_data(self, num_periods=200):\n        end = datetime.datetime.utcnow()\n        end_iso = end.isoformat()\n        start = end - datetime.timedelta(seconds=(self.period_size * num_periods))\n        start_iso = start.isoformat()\n\n        ret = None\n\n        # Check if we got rate limited, which will return a JSON message\n        while not isinstance(ret, list):\n            try:\n                time.sleep(3)\n                ret = self.cbpro_client.get_product_historic_rates(self.product, granularity=self.period_size, start=start_iso, end=end_iso)\n            except Exception:\n                self.error_logger.exception(datetime.datetime.now())\n        hist_data = np.array(ret, dtype='object')\n        for row in hist_data:\n            row[0] = datetime.datetime.fromtimestamp(row[0], pytz.utc)\n        return np.flipud(hist_data)\n\n    def update_historical_data(self):\n        updated_sticks = self.get_historical_data(num_periods=5)\n        for new_stick in updated_sticks:\n            for idx, old_stick in enumerate(self.candlesticks[-10:]):\n                if new_stick[0] == old_stick[0]:\n                    self.candlesticks[-10 + idx] = new_stick\n        self.updated_hist_data = True\n\n    def process_heartbeat(self, msg):\n        if not self.updated_hist_data and self.time_of_first_candlestick_close \\\n           and datetime.datetime.now() - self.time_of_first_candlestick_close >= datetime.timedelta(minutes=10):\n            self.update_historical_data()\n\n        isotime = dateutil.parser.parse(msg.get('time'))\n        if isotime:\n            if self.verbose_heartbeat:\n                self.logger.debug(\"[HEARTBEAT] \" + str(isotime) + \" \" + str(msg.get('last_trade_id')))\n            if isotime - self.cur_candlestick_start > datetime.timedelta(seconds=self.period_size):\n                self.close_candlestick()\n                self.new_candlestick(self.cur_candlestick.time + datetime.timedelta(seconds=self.period_size))\n\n    def process_trade(self, msg):\n        if msg.get('product_id') == self.product:\n            cur_trade = trade.Trade(msg)\n            isotime = dateutil.parser.parse(msg.get('time')).replace(microsecond=0)\n            if isotime < self.cur_candlestick.time:\n                prev_stick = Candlestick(existing_candlestick=self.candlesticks[-1])\n                self.candlesticks = self.candlesticks[:-1]\n                prev_stick.add_trade(cur_trade)\n                self.add_stick(prev_stick)\n            else:\n                if isotime > self.cur_candlestick.time + datetime.timedelta(seconds=self.period_size):\n                    self.close_candlestick()\n                    self.new_candlestick(self.cur_candlestick.time + datetime.timedelta(seconds=self.period_size))\n                self.cur_candlestick.add_trade(cur_trade)\n                self.cur_candlestick.print_stick(self.name)\n\n    def get_highs(self):\n        return np.array(self.candlesticks[:, 2], dtype='f8')\n\n    def get_lows(self):\n        return np.array(self.candlesticks[:, 1], dtype='f8')\n\n    def get_closing_prices(self):\n        return np.array(self.candlesticks[:, 4], dtype='f8')\n\n    def get_volumes(self):\n        return np.array(self.candlesticks[:, 5], dtype='f8')\n\n    def new_candlestick(self, isotime):\n        prev_close = self.cur_candlestick.close\n        self.cur_candlestick = Candlestick(isotime=isotime, prev_close=prev_close)\n        self.cur_candlestick_start = isotime.replace(second=0, microsecond=0)\n\n    def add_stick(self, stick_to_add):\n        self.candlesticks = np.row_stack((self.candlesticks, stick_to_add.close_candlestick(self.name)))\n\n    def close_candlestick(self):\n        if not self.updated_hist_data:\n            self.time_of_first_candlestick_close = datetime.datetime.now()\n        if len(self.candlesticks) > 0:\n            self.candlesticks = np.row_stack((self.candlesticks,\n                                              self.cur_candlestick.close_candlestick(period_name=self.name,\n                                                                                     prev_stick=self.candlesticks[-1])))\n        else:\n            self.candlesticks = np.array([self.cur_candlestick.close_candlestick(self.name)])"
  },
  {
    "path": "cbpro-trader/daemon/period/__init__.py",
    "content": "from .Candlestick import Candlestick\nfrom .Period import Period\nfrom .MetaPeriod import MetaPeriod"
  },
  {
    "path": "cbpro-trader/daemon/requirements.txt",
    "content": "astroid==2.3.3\natomicwrites==1.2.1\nattrs==18.2.0\nbintrees==2.0.7\n-e git+https://github.com/mcardillo55/coinbasepro-python.git@d2b8bed627339723ab214430fe93ade2331d757e#egg=cbpro\nClick==7.0\nFlask==1.1.1\ngevent==20.5.0\ngreenlet==0.4.15\nisort==4.3.21\nitsdangerous==1.1.0\nJinja2==2.10.3\nlazy-object-proxy==1.4.3\nMarkupSafe==1.1.1\nmccabe==0.6.1\nmore-itertools==4.3.0\nnumpy==1.15.2\npluggy==0.8.0\npy==1.7.0\npylint==2.4.4\npymongo==3.5.1\npytest==4.0.1\npytest-mock==1.10.0\npython-dateutil==2.6.0\npytz==2017.2\nPyYAML==5.1\nrequests==2.20.0\nsix==1.13.0\nsortedcontainers==2.1.0\nTA-Lib==0.4.17\nwebsocket-client==0.40.0\nWerkzeug==0.16.0\nwrapt==1.11.2\n"
  },
  {
    "path": "cbpro-trader/daemon/tests/__init__.py",
    "content": ""
  },
  {
    "path": "cbpro-trader/daemon/tests/test_period.py",
    "content": "#\n# test_period.py\n# Mike Cardillo\n#\n# Pytest tests on the period file\n\nimport period\nimport trade\nimport datetime\nimport numpy as np\n\n\nclass TestCandlestick(object):\n    def setup_class(self):\n        fake_trade_dict = {\"sequence\": \"12345\",\n                           \"trade_id\": \"123\",\n                           \"time\": \"2018-11-29T05:21:06Z\",\n                           \"price\": \"38.50\",\n                           \"size\": \"105.34\"}\n        self.fake_trade = trade.Trade(fake_trade_dict)\n        self.test_datetime = datetime.datetime(2018, 6, 10, 11, 13, 58, 384)\n        self.test_datetime_zero_sec_ms = datetime.datetime(2018, 6, 10, 11, 13, 0, 0)\n\n    def test_init_with_isotime_and_prev_close(self):\n        prev_close = 58.30\n        candlestick = period.Candlestick(isotime=self.test_datetime, prev_close=prev_close)\n\n        assert candlestick.new is True\n        assert candlestick.time == self.test_datetime_zero_sec_ms\n        assert candlestick.open == 58.30\n        assert candlestick.high == 58.30\n        assert candlestick.low == 58.30\n        assert candlestick.close == 58.30\n        assert candlestick.volume == 0\n\n    def test_init_with_isotime_without_prev_close(self):\n        candlestick = period.Candlestick(isotime=self.test_datetime)\n\n        assert candlestick.new is True\n        assert candlestick.time == self.test_datetime_zero_sec_ms\n        assert candlestick.open is None\n        assert candlestick.high is None\n        assert candlestick.low is None\n        assert candlestick.close is None\n        assert candlestick.volume == 0\n\n    def test_init_without_isotime(self):\n        existing_candlestick = [self.test_datetime_zero_sec_ms, 58.00, 59.50,\n                                58.10, 58.50, 15235.235]\n        candlestick = period.Candlestick(existing_candlestick=existing_candlestick)\n\n        assert candlestick.new is False\n        assert candlestick.time == self.test_datetime_zero_sec_ms\n        assert candlestick.open == 58.10\n        assert candlestick.high == 59.50\n        assert candlestick.low == 58.00\n        assert candlestick.close == 58.50\n        assert candlestick.volume == 15235.235\n\n    def test_add_trade__new_open(self):\n        candlestick = period.Candlestick(isotime=self.test_datetime)\n        candlestick.add_trade(self.fake_trade)\n\n        assert candlestick.new is False\n        assert candlestick.open == 38.50\n        assert candlestick.high == 38.50\n        assert candlestick.low == 38.50\n        assert candlestick.close == 38.50\n        assert candlestick.volume == 105.34\n\n    def test_add_trade__higher_high(self):\n        existing_candlestick = [self.test_datetime_zero_sec_ms, 25.57, 35.57,\n                                30.25, 31.25, 15235.235]\n        candlestick = period.Candlestick(existing_candlestick=existing_candlestick)\n        candlestick.add_trade(self.fake_trade)\n\n        assert candlestick.high == 38.50\n        assert candlestick.close == 38.50\n        assert candlestick.volume == 15235.235 + 105.34\n\n    def test_add_trade__lower_low(self):\n        existing_candlestick = [self.test_datetime_zero_sec_ms, 39.57, 42.45,\n                                40.25, 39.87, 15235.235]\n        candlestick = period.Candlestick(existing_candlestick=existing_candlestick)\n        candlestick.add_trade(self.fake_trade)\n\n        assert candlestick.low == 38.50\n        assert candlestick.close == 38.50\n        assert candlestick.volume == 15235.235 + 105.34\n\n    def test_close_candlestick__all_fields_none(self):\n\n        candlestick = period.Candlestick(isotime=self.test_datetime)\n        prev_stick = [self.test_datetime_zero_sec_ms, 39.57, 42.45,\n                      40.25, 39.87, 15235.235]\n        ret = candlestick.close_candlestick(\"TEST STICK\", prev_stick=prev_stick)\n\n        assert candlestick.new is False\n        assert isinstance(ret, type(np.array([])))\n        np.testing.assert_array_equal(ret, [self.test_datetime_zero_sec_ms, 39.87, 39.87, 39.87, 39.87, 0])\n\n    def test_close_candlestick__close_not_none(self):\n        existing_candlestick = [self.test_datetime_zero_sec_ms, 58.00, 59.50,\n                                58.10, 58.50, 15235.235]\n        candlestick = period.Candlestick(existing_candlestick=existing_candlestick)\n        ret = candlestick.close_candlestick(\"TEST STICK\")\n\n        assert isinstance(ret, type(np.array([])))\n        np.testing.assert_array_equal(ret, existing_candlestick)\n\n\nclass TestPeriod(object):\n    def setup_class(self):\n        self.start_time = datetime.datetime.now(datetime.timezone.utc)\n        self.fake_hist_data = [[self.start_time.timestamp(), 123.4, 133.5, 124.6, 132.3, 3485.38],\n                               [(self.start_time + datetime.timedelta(minutes=5)).timestamp(), 122.3, 135.4, 123.7, 133.4, 4385.25],\n                               [(self.start_time + datetime.timedelta(minutes=10)).timestamp(), 120.2, 130.2, 132.5, 131.2, 3859.42]]\n\n    def test_init__initalize_false(self):\n        test_period = period.Period(period_size=15, name=\"BTC15\", product=\"BTC-USD\", initialize=False)\n\n        assert isinstance(test_period, period.Period)\n        assert test_period.period_size == 15\n        assert test_period.name == \"BTC15\"\n        assert test_period.product == \"BTC-USD\"\n        assert test_period.verbose_heartbeat is False\n        assert isinstance(test_period.candlesticks, type(np.array([])))\n        np.testing.assert_array_equal(test_period.candlesticks, np.array([]))\n\n    def test_init__initalize_true(self, mocker):\n        mocker.patch(\"cbpro.PublicClient.get_product_historic_rates\", return_value=self.fake_hist_data)\n        test_period = period.Period(period_size=5, name=\"ETH5\", product=\"ETH-USD\", initialize=True)\n\n        assert isinstance(test_period, period.Period)\n        assert test_period.period_size == 5\n        assert test_period.name == \"ETH5\"\n        assert test_period.product == \"ETH-USD\"\n        assert test_period.verbose_heartbeat is False\n\n        assert isinstance(test_period.candlesticks, type(np.array([])))\n        assert len(test_period.candlesticks) == len(self.fake_hist_data) - 1\n        assert isinstance(test_period.cur_candlestick, period.Candlestick)\n        assert test_period.cur_candlestick_start == self.start_time\n        assert isinstance(test_period.candlesticks[0], type(np.array([])))\n"
  },
  {
    "path": "cbpro-trader/daemon/trade/Trade.py",
    "content": "import dateutil.parser\nimport logging\n\n\nclass Trade:\n    def __init__(self, msg):\n        self.seq = int(msg.get('sequence'))\n        self.trade_id = int(msg.get('trade_id'))\n        self.time = dateutil.parser.parse(msg.get('time'))\n        self.price = float(msg.get('price'))\n        self.volume = float(msg.get('size'))\n        self.logger = logging.getLogger('trader-logger')\n\n    def print_trade(self):\n        self.logger.debug(\"[TRADE] Trade ID: %d Price: %f Volume: %f\" %\n                          (self.trade_id, self.price, self.volume))"
  },
  {
    "path": "cbpro-trader/daemon/trade/__init__.py",
    "content": "from .Trade import Trade"
  },
  {
    "path": "cbpro-trader/web/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n"
  },
  {
    "path": "cbpro-trader/web/Dockerfile",
    "content": "FROM node:13.6.0\n\n# Install node dependencies\nWORKDIR /frontend/\nRUN npm install"
  },
  {
    "path": "cbpro-trader/web/README.md",
    "content": "This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).\n\n## Available Scripts\n\nIn the project directory, you can run:\n\n### `npm start`\n\nRuns the app in the development mode.<br>\nOpen [http://localhost:3000](http://localhost:3000) to view it in the browser.\n\nThe page will reload if you make edits.<br>\nYou will also see any lint errors in the console.\n\n### `npm test`\n\nLaunches the test runner in the interactive watch mode.<br>\nSee the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.\n\n### `npm run build`\n\nBuilds the app for production to the `build` folder.<br>\nIt correctly bundles React in production mode and optimizes the build for the best performance.\n\nThe build is minified and the filenames include the hashes.<br>\nYour app is ready to be deployed!\n\nSee the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.\n\n### `npm run eject`\n\n**Note: this is a one-way operation. Once you `eject`, you can’t go back!**\n\nIf 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.\n\nInstead, 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.\n\nYou 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.\n\n## Learn More\n\nYou can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).\n\nTo learn React, check out the [React documentation](https://reactjs.org/).\n\n### Code Splitting\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting\n\n### Analyzing the Bundle Size\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size\n\n### Making a Progressive Web App\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app\n\n### Advanced Configuration\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration\n\n### Deployment\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/deployment\n\n### `npm run build` fails to minify\n\nThis section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify\n"
  },
  {
    "path": "cbpro-trader/web/package.json",
    "content": "{\n  \"name\": \"web\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"lightweight-charts\": \"^3.1.5\",\n    \"react\": \"^16.9.0\",\n    \"react-dom\": \"^16.9.0\",\n    \"react-redux\": \"^7.1.3\",\n    \"react-scripts\": \"3.1.1\",\n    \"redux\": \"^4.0.4\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test\",\n    \"eject\": \"react-scripts eject\"\n  },\n  \"eslintConfig\": {\n    \"extends\": \"react-app\"\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  },\n  \"proxy\": \"http://cbpro:5000\"\n}\n"
  },
  {
    "path": "cbpro-trader/web/public/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>Coinbase Pro Trader</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "cbpro-trader/web/public/manifest.json",
    "content": "{\n  \"short_name\": \"React App\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n      \"sizes\": \"64x64 32x32 24x24 16x16\",\n      \"type\": \"image/x-icon\"\n    },\n    {\n      \"src\": \"logo192.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"192x192\"\n    },\n    {\n      \"src\": \"logo512.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"512x512\"\n    }\t    \n  ],\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "cbpro-trader/web/public/robots.txt",
    "content": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\n"
  },
  {
    "path": "cbpro-trader/web/src/App.css",
    "content": "#chart-controller {\n  display: flex;\n  height: 100vh;\n}\n#chart {\n  flex: 1;\n}\n#collapse-button {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  color: rgb(19, 23, 34);\n  background-color: rgb(217, 217, 217);\n  width: 15px;\n}\n#collapse-button:hover {\n  background-color: #A6A6A6;\n}\n#config {\n  padding: 10px;\n}\n#period-list {\n  overflow-y: auto;\n  list-style-type: none;\n  padding: 0px;\n  margin: 0px;\n}\n#sidebar {\n  display: grid;\n  grid-template-rows: 1fr 2fr;\n  max-height: 100vh;\n  width: 300px;\n}\n#primary-selector {\n  display: grid;\n  grid-template-columns: 1fr 1fr 1fr;\n  border-top: 5px solid;\n  border-bottom: 5px solid;\n}\n#primary-section {\n  overflow-y: auto;\n}\n#secondary-section {\n  overflow-y: auto;\n}\n#secondary-details {\n  overflow-x: auto;\n  white-space: nowrap;\n}\n#secondary-selector {\n  display: grid;\n  grid-template-columns: 1fr 1fr 1fr;\n  border-top: 5px solid;\n  border-bottom: 5px solid;\n}\n#tooltip {\n  display: block;\n  position: absolute;\n  top: 3px;\n  left: 10px;\n  z-index: -1;\n}\n#tooltip-title {\n  font-size: 26px;\n}\n#tooltip-prices {\n  font-size: 18px;\n}\n#details {\n  font-weight: bold;\n}\n#last-trade {\n  font-size: 28px;\n}\n.active-button{\n  background-color: rgb(33, 56, 77);\n}\n.collapsed {\n  grid-template-columns: 124fr 1fr !important;\n}\n#balances {\n  padding-top: 0px;\n  list-style-type: none;\n  overflow-y: auto;\n}\n.currency {\n  font-weight: bold;\n}\n.indicator-data {\n  font-weight: normal;\n}\n.indicator {\n  margin: 8px 0px;\n}\n.sidebar-section {\n  padding: 10px;\n}\n.sidebar-section h2.first-h2{\n  margin-top: 0px;\n}\n.flag-title {\n  font-weight: bold;\n}\n\nbutton {\n  color: rgb(120, 123, 134);\n  background: rgb(19, 23, 34);\n  text-decoration: none;\n  border: 1px solid;\n  padding: 10px;\n  outline: none !important;\n}\n\nbutton:hover {\n  background-color: #2a2e39;\n}\n\nli.period{\n  display: block;\n  padding: 10px;\n  text-decoration: none;\n  height: 20px;\n}\n\nli:nth-child(odd).period{\n  background-color: rgb(28, 32, 48);\n}\n\nli.focused.period{\n  background-color: rgb(33, 56, 77);\n}\n\nbody {\n  color: rgb(217, 217, 217);\n  background: rgb(19, 23, 34);\n}\n\nth {\n  border-right: 1px solid;\n  border-bottom: 1px solid;\n}\nth:last-child {\n  border-right: 0;\n}\ntd {\n  border-right: 1px solid;\n}\ntd:last-child {\n  border-right: 0;\n}\ninput, select {\n  margin: 5px;\n}\ninput[type=text], input[type=number]{\n  width: 100px;\n}\nlabel {\n  display: inline-block;\n  width: 100px;\n  text-align: right;\n}\ninput[type=submit]{\n  display: block;\n  margin-left: 25%\n}"
  },
  {
    "path": "cbpro-trader/web/src/App.js",
    "content": "import React from 'react';\nimport ChartController from './containers/ChartController'\n\nimport './App.css';\n\nfunction App() {\n  return (\n    <div className=\"App\">\n      <ChartController />\n    </div>\n  );\n}\n\nexport default App;\n"
  },
  {
    "path": "cbpro-trader/web/src/App.test.js",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\n\nit('renders without crashing', () => {\n  const div = document.createElement('div');\n  ReactDOM.render(<App />, div);\n  ReactDOM.unmountComponentAtNode(div);\n});\n"
  },
  {
    "path": "cbpro-trader/web/src/actions/index.js",
    "content": "export const changeActivePeriod = period_name => ({\n    type: 'CHANGE_ACTIVE_PERIOD',\n    period_name\n})\n\nexport const changePrimarySection = section_name => ({\n    type: 'CHANGE_PRIMARY_SECTION',\n    section_name\n})\n\nexport const changeSecondarySection = section_name => ({\n    type: 'CHANGE_SECONDARY_SECTION',\n    section_name\n})\n\nexport const updateBalances = balances => ({\n    type: 'UPDATE_BALANCES',\n    balances\n})\n\nexport const updateFlags = flags => ({\n    type: 'UPDATE_FLAGS',\n    flags\n})\n\nexport const addPeriod = period_name => ({\n    type: 'ADD_PERIOD',\n    period_name\n})\n\nexport const clearPeriods = () => ({\n    type: 'CLEAR_PERIODS'\n})\n\nexport const updateCandlesticks = candlesticks => ({\n    type: 'UPDATE_CANDLESTICKS',\n    candlesticks\n})\n\nexport const updateIndicators = indicators => ({\n    type: 'UPDATE_INDICATORS',\n    indicators\n})\n\nexport const updateOrders = orders => ({\n    type: 'UPDATE_ORDERS',\n    orders\n})"
  },
  {
    "path": "cbpro-trader/web/src/components/Balances.jsx",
    "content": "import React from 'react';\n\nfunction Balances(props) {\n    const { balances } = props;\n    return(\n        <ul id=\"balances\" className=\"sidebar-section\">\n            {\n                Object.keys(balances).map((currency, idx) => {\n                    return(\n                        <li key={idx} className=\"currency\"><span className=\"currency\">{ currency.toUpperCase() }</span>: { balances[currency] }</li>\n                    )\n                })\n            }\n        </ul>\n    )\n}\n\nexport default Balances;"
  },
  {
    "path": "cbpro-trader/web/src/components/Chart.jsx",
    "content": "import React from 'react';\nimport * as LightweightCharts from 'lightweight-charts';\nimport Tooltip from './Tooltip';\n\nfunction Chart (props) {\n    const ref = React.useRef(null);\n    const [chart, setChart] = React.useState(null);\n    const [initialZoomSet, setInitialZoomSet] = React.useState(false); // Tracks if we have set the initial zoom yet\n    const [tooltipPrices, setTooltipPrices] = React.useState({});\n    const [hovering, setHovering] = React.useState(false); // True if hovering a data series;\n    const [candlestickSeries, setCandlestickSeries] = React.useState(null);\n    const { active_period, candlesticks } = props;\n\n    if (ref.current && !chart) {\n        setChart(LightweightCharts.createChart(ref.current, {\n        width: 0,\n        height: 0,\n            layout: {\n                backgroundColor: 'Transparent',\n                textColor: 'rgba(255, 255, 255, 0.9)',\n            },\n            grid: {\n                vertLines: {\n                    color: 'rgba(197, 203, 206, 0.5)',\n                },\n                horzLines: {\n                    color: 'rgba(197, 203, 206, 0.5)',\n                },\n            },\n            crosshair: {\n                mode: LightweightCharts.CrosshairMode.Normal,\n            },\n            rightPriceScale: {\n                borderColor: 'rgba(197, 203, 206, 0.8)',\n            },\n            timeScale: {\n                timeVisible: true,\n                borderColor: 'rgba(197, 203, 206, 0.8)',\n            },\n        }));\n    }\n\n    React.useEffect(() => {\n        if(chart) {\n            let series = chart.addCandlestickSeries({\n                upColor: '#53b987',\n                downColor: '#eb4d5c',\n                borderDownColor: '#eb4d5c',\n                borderUpColor: '#53b987',\n                wickDownColor: '#eb4d5c',\n                wickUpColor: '#53b987',\n            });\n            setCandlestickSeries(series);\n\n            chart.subscribeCrosshairMove(function(param) {\n                if (param.seriesPrices.size) {\n                    setHovering(true);\n                    setTooltipPrices(param.seriesPrices.get(series));\n                } else {\n                    setHovering(false);\n                }\n            })\n        };\n    }, [chart]);\n\n    React.useEffect(() => {\n        if (candlesticks.length && candlestickSeries) {\n            candlestickSeries.setData(candlesticks);\n            if (!hovering) {\n                setTooltipPrices(candlesticks[candlesticks.length - 1]);\n            }\n        }\n\n        if (!initialZoomSet && chart && chart.timeScale().getVisibleRange()) {\n            let timeDiff = candlesticks[candlesticks.length -1]['time'] - candlesticks[candlesticks.length -2]['time'];\n            chart.timeScale().setVisibleRange({\n                from: candlesticks[candlesticks.length -1]['time'] - (timeDiff * 30), // Show 30 candles by default\n                to: candlesticks[candlesticks.length -1]['time'],\n            })\n            setInitialZoomSet(true);\n            setTooltipPrices(candlesticks[candlesticks.length - 1])\n        }\n    }, [candlesticks, candlestickSeries, chart, hovering, initialZoomSet]);\n\n    function resizeChart() {\n        if (chart) {\n            chart.resize(0, 0);\n            chart.resize(ref.current.clientWidth, ref.current.clientHeight);\n        }\n    }\n\n    window.addEventListener('resize', () => resizeChart());\n\n    resizeChart();\n\n    return (\n        <div id=\"chart\" ref={ref}>\n            <Tooltip title={active_period} prices={tooltipPrices} />\n        </div>\n    )\n}\n\nexport default Chart;"
  },
  {
    "path": "cbpro-trader/web/src/components/CollapseButton.jsx",
    "content": "import React from 'react';\n\nfunction CollapseButton(props) {\n    const buttonDirection = props.collapsed ? \"<\" : \">\"\n    return (\n        <div id=\"collapse-button\" onClick={props.onClick}>\n            {buttonDirection}\n        </div>\n    )\n}\n\nexport default CollapseButton;"
  },
  {
    "path": "cbpro-trader/web/src/components/Config.jsx",
    "content": "import React, { Component } from 'react'\nimport { connect } from 'react-redux'\nimport { addPeriod, changeActivePeriod, clearPeriods } from '../actions'\nimport SelectAvailable from './SelectAvailable'\n\nclass Config extends Component {\n    constructor(){\n        super();\n        this.SERVER = process.env.REACT_APP_SERVER || '';\n        this.state = {\"config\": {\"periods\": []}}\n        this.handleConfigChange = this.handleConfigChange.bind(this)\n        this.handlePeriodChange = this.handlePeriodChange.bind(this)\n        this.handleSubmit = this.handleSubmit.bind(this)\n    }\n    \n    componentDidMount() {\n        fetch(this.SERVER + '/config/')\n        .then(response => response.json())\n        .then(myJson => this.setState({\"config\": myJson}))\n    }\n\n    handleConfigChange(event) {\n        this.setState({\n                        config: {...this.state.config,\n                                [event.target.name]: this.parseEventData(event)\n                                }\n                        })\n    }\n\n    handlePeriodChange(event) {\n        let idx = event.target.name.split(\"+\")[0]\n        let name = event.target.name.split(\"+\")[1]\n        let periods = [...this.state.config.periods]\n        let period = {...periods[idx],\n                      [name]: this.parseEventData(event)}\n        periods[idx] = period\n        this.setState({\n                        config: {...this.state.config,\n                                periods: periods\n                                }\n                        })\n    }\n\n    handleSubmit(event){\n        event.preventDefault()\n        fetch(this.SERVER + '/config/', {\n            method: 'POST',\n            headers: {\n              'Content-Type': 'application/json',\n            },\n            body: JSON.stringify(this.state.config)\n        })\n        .then(() => {\n            this.props.clearPeriods()\n            fetch(this.SERVER + \"/periods/\")\n            .then(response => {\n                return response.json()\n            })\n            .then(myJson => {\n                myJson.map((period_name, idx) => {\n                    (idx === 0) && this.props.changeActivePeriod(period_name);\n                    return this.props.addPeriod(period_name);\n                })\n            })\n        })\n    }\n\n    parseEventData(event) {\n        switch (event.target.type) {\n            case \"select-one\":\n                switch (event.target.name.split(\"+\")[1]) {\n                    case \"length\":\n                        return parseFloat(event.target.value)\n                    default:\n                        return event.target.value\n                }\n            case \"text\":\n                return event.target.value\n            case \"number\":\n                return parseFloat(event.target.value)\n            case \"checkbox\":\n                return event.target.checked\n            default:\n                return event.target.value\n        } \n    }\n\n    parseType(data) {\n        switch (typeof(data)) {\n            case \"text\":\n                return \"text\"\n            case \"number\":\n                return \"number\"\n            case \"boolean\":\n                return \"checkbox\"\n            default:\n                return \"text\"\n        } \n    }\n    createInput(label, value, period) {\n        let type = this.parseType(value)\n        let checked = type === \"checkbox\" && value ? \"checked\" : \"\"\n        let parsedLabel;\n        if (period) {\n            parsedLabel = label.split(\"+\")[1]\n        } else {\n            parsedLabel = label\n        }\n            \n        switch (parsedLabel) \n        {\n            case \"product\":\n                return <SelectAvailable selected={value}\n                                        name={label}\n                                        url=\"/products/\"\n                                        onChange={this.handlePeriodChange} />\n            case \"length\":\n                return <SelectAvailable selected={value}\n                                        name={label}\n                                        options={[1, 5, 15, 60, 360, 1440]}\n                                        onChange={this.handlePeriodChange} />\n            default:\n                return <input type={type} \n                                checked={checked}\n                                value={value} \n                                name={label} \n                                onChange={period ? this.handlePeriodChange : this.handleConfigChange}/>\n        }\n    }\n\n    prettifyLabel(label) {\n        return label.charAt(0).toUpperCase() + label.replace('_', ' ').slice(1)\n    }\n\n    render() {\n        if (this.state.config['web_config']) {\n            let periods_list = \n                this.state.config[\"periods\"].map((period, idx) => {\n                    return(\n                        Object.keys(period).map((period_value, idx2) => {\n                            return(\n                                <div key={idx + ',' + idx2}>\n                                    <label>\n                                        {this.prettifyLabel(period_value)}:\n                                    </label>\n                                    {this.createInput(idx + \"+\" + period_value, period[period_value], true)}\n                                </div>\n                            )\n                        })\n                    )\n                });\n            let config_list = \n                Object.keys(this.state.config).map((config, idx) => {\n                    if (config === \"periods\") {\n                        return(\n                            <div key={idx}>\n                                Periods:\n                                    {periods_list}\n                            </div>\n                        )\n                    } else {\n                        return (\n                            <div key={idx}>\n                                <label>\n                                    {this.prettifyLabel(config)}:\n                                </label>\n                                {this.createInput(config, this.state.config[config], false)}\n                            </div>\n                        )  \n                    }\n                });\n            return (\n                <form id=\"config\">\n                    {config_list}\n                    <input type=\"submit\" value=\"Save and Restart\" onClick={this.handleSubmit}/>\n                </form>\n            );\n        }\n        else {\n            return (\n                <div id=\"config\">\n                    <h3>Web config disabled</h3>\n                </div>\n            )\n        }\n    }\n}\n\nconst mapDispatchToProps = dispatch => ({\n    addPeriod: period_name => dispatch(addPeriod(period_name)),\n    changeActivePeriod: period_name => dispatch(changeActivePeriod(period_name)),\n    clearPeriods: () => dispatch(clearPeriods())\n})\n\nexport default connect(null, mapDispatchToProps)(Config);"
  },
  {
    "path": "cbpro-trader/web/src/components/Details.jsx",
    "content": "import React from 'react';\n\nfunction Details(props) {\n    const { indicators } = props;\n    return(\n        <div id=\"details\" className=\"sidebar-section\">\n            <div id=\"last-trade-label\">Last Trade</div>\n            <div id=\"last-trade\">{indicators.close && indicators.close.toFixed(2)}</div>\n            <div id=\"indicators\">\n                {\n                    Object.keys(indicators).map((indicator, idx) => {\n                        return(\n                            <div key={idx} className=\"indicator\">\n                                <div className=\"indicator-title\">{indicator.toUpperCase()}</div>\n                                <div className=\"indicator-data\">{indicators[indicator]}</div>\n                            </div>\n                        )\n                    })\n                }\n            </div>\n        </div>\n    )\n}\n\nexport default Details;"
  },
  {
    "path": "cbpro-trader/web/src/components/Flags.jsx",
    "content": "import React from 'react';\n\nfunction Flags(props) {\n    const { flags } = props;\n    return(\n        <div id=\"flags\" className=\"sidebar-section\">\n            <h2 className=\"first-h2\">Flags</h2>\n            {\n                Object.keys(flags).map((flag, idx) => {\n                    return(      \n                        <div key={idx} className=\"flag\">\n                            <span className=\"flag-title\">{ flag.toUpperCase() }:</span> { flags[flag].toUpperCase() }\n                        </div>\n                    )\n                })\n            }\n        </div>\n    )\n}\n\nexport default Flags;"
  },
  {
    "path": "cbpro-trader/web/src/components/Orders.jsx",
    "content": "import React from 'react';\n\nfunction Orders(props) {\n    const { orders } = props;\n    return(\n        <div id=\"orders\" className=\"sidebar-section\">\n            <h2 className=\"first-h2\">Orders</h2>\n            <table>\n                <thead>\n                    <tr>\n                        <th>Product</th>\n                        <th>Side</th>\n                        <th>Size</th>\n                        <th>Price</th>\n                        <th>Filled</th>\n                        <th>Fee</th>\n                    </tr>\n                </thead>\n                <tbody>\n            {\n                orders['orders'].map((order, idx) => {\n                    return(\n                        <tr key={idx}>\n                            <td>{order.product_id}</td>\n                            <td>{order.side.toUpperCase()}</td>\n                            <td>{order.size}</td>\n                            <td>{parseFloat(order.price).toFixed(2)}</td>\n                            <td>{order.filled_size}</td>\n                            <td>{parseFloat(order.fill_fees).toFixed(8)}</td>\n                        </tr>\n                    )\n                })\n            }\n                </tbody>\n            </table>\n            <h2>Fills</h2>\n            <table>\n                <thead>\n                    <tr>\n                        <th>Product</th>\n                        <th>Side</th>\n                        <th>Size</th>\n                        <th>Price</th>\n                        <th>Fee</th>\n\n                    </tr>\n                </thead>\n                <tbody>\n            {\n                orders['fills'].map((fill, idx) => {\n                    return(\n                        <tr key={idx}>\n                            <td>{fill.product_id}</td>\n                            <td>{fill.side.toUpperCase()}</td>\n                            <td>{fill.size}</td>\n                            <td>{parseFloat(fill.price).toFixed(2)}</td>\n                            <td>{parseFloat(fill.fee).toFixed(8)}</td>\n                        </tr>\n                    )\n                })\n            }\n                </tbody>\n            </table>\n        </div>\n    )\n}\n\nexport default Orders;"
  },
  {
    "path": "cbpro-trader/web/src/components/SelectAvailable.jsx",
    "content": "import React, { Component } from 'react'\n\nclass SelectAvailable extends Component {\n    constructor(props){\n        super(props)\n        this.SERVER = process.env.REACT_APP_SERVER || ''\n        this.state = {options: []}\n    }\n    componentDidMount() {\n        if (this.props.url) {\n            fetch(this.SERVER + this.props.url)\n            .then(response => response.json())\n            .then(myJson => this.setState({options: myJson}))\n        } else if (this.props.options) {\n            this.setState({options: this.props.options})\n        }\n    }\n    render() {\n        let options = this.state.options.map((option, idx) => {\n            return <option key={idx} value={option} onChange={this.handleChange}>{option}</option>\n        })\n        return (\n            <select name={this.props.name} onChange={this.props.onChange} value={this.props.selected}>\n                {options}\n            </select>\n        )\n    }\n}\n\nexport default SelectAvailable;"
  },
  {
    "path": "cbpro-trader/web/src/components/Sidebar.jsx",
    "content": "import React from 'react';\nimport DetailsContainer from '../containers/DetailsContainer'\nimport FlagsContainer from '../containers/FlagsContainer'\nimport OrdersContainer from '../containers/OrdersContainer'\nimport BalancesContainer from '../containers/BalancesContainer';\nimport Config from '../components/Config';\n\nfunction Sidebar(props) {\n    const { active_period, period_list, primary_section, secondary_section, changePrimarySection, changeSecondarySection, changeActivePeriod } = props;\n    \n    let period_list_map = period_list.map((period_name, idx) => {\n                                return(\n                                    <li key={idx} className={active_period === period_name ? \"focused period\" : \"period\"} \n                                        onClick={() => {changeActivePeriod(period_name)}}>{period_name}</li>\n                                )\n                            })\n\n    return (\n        <div id=\"sidebar\">\n            <div id=\"primary-section\">\n                <div id=\"primary-selector\">\n                    <button className={primary_section === \"periods\" ? \"active-button\" : \"\"} onClick={() => {changePrimarySection(\"periods\")}}>Periods</button>\n                    <button className={primary_section === \"balances\" ? \"active-button\" : \"\"} onClick={() => {changePrimarySection(\"balances\")}}>Balances</button>\n                    <button className={primary_section === \"config\" ? \"active-button\" : \"\"} onClick={() => {changePrimarySection(\"config\")}}>Config</button>\n                </div>\n                <div id=\"primary-details\">\n                    { primary_section === \"periods\" &&  period_list_map }\n                    { primary_section === \"balances\" && <BalancesContainer /> }\n                    { primary_section === \"config\" && <Config /> }\n                </div>\n            </div>\n            <div id=\"secondary-section\">\n                <div id=\"secondary-selector\">\n                    <button className={secondary_section === \"details\" ? \"active-button\" : \"\"} onClick={() => {changeSecondarySection(\"details\")}}>Details</button>\n                    <button className={secondary_section === \"flags\" ? \"active-button\" : \"\"} onClick={() => {changeSecondarySection(\"flags\")}}>Flags</button>\n                    <button className={secondary_section === \"orders\" ? \"active-button\" : \"\"} onClick={() => {changeSecondarySection(\"orders\")}}>Orders</button>\n                </div>\n                <div id=\"secondary-details\">\n                    {secondary_section === \"details\" && <DetailsContainer />}\n                    {secondary_section === \"flags\" && <FlagsContainer />}\n                    {secondary_section === \"orders\" && <OrdersContainer />}\n                </div>\n            </div>\n        </div>\n    )\n}\n\nexport default Sidebar;"
  },
  {
    "path": "cbpro-trader/web/src/components/Tooltip.jsx",
    "content": "import React from 'react';\n\nfunction Tooltip (props) {\n    return (\n        <div id=\"tooltip\">\n            <div id=\"tooltip-title\">{props.title}</div>\n            <div id=\"tooltip-prices\">O: {props.prices.open} H: {props.prices.high} L: {props.prices.low} C: {props.prices.close}</div>\n        </div>\n    )\n}\n\nexport default Tooltip;"
  },
  {
    "path": "cbpro-trader/web/src/containers/BalancesContainer.jsx",
    "content": "import { connect } from 'react-redux'\nimport Balances from '../components/Balances'\n\nconst mapStateToProps = state => ({\n    balances: state.sidebar.balances\n})\n\nexport default connect(mapStateToProps)(Balances);"
  },
  {
    "path": "cbpro-trader/web/src/containers/ChartContainer.jsx",
    "content": "import { connect } from 'react-redux'\nimport Chart from '../components/Chart'\n\nconst mapStateToProps = state => ({\n    active_period: state.chart.active_period,\n    candlesticks: state.chart.candlesticks\n})\n\nexport default connect(mapStateToProps)(Chart);"
  },
  {
    "path": "cbpro-trader/web/src/containers/ChartController.jsx",
    "content": "import React, { Component } from 'react'\nimport { connect } from 'react-redux'\nimport { addPeriod, changeActivePeriod, updateCandlesticks, updateIndicators, updateFlags, updateOrders, updateBalances } from '../actions'\nimport CollapseButton from '../components/CollapseButton'\nimport SidebarContainer from '../containers/SidebarContainer'\nimport ChartContainer from '../containers/ChartContainer'\n\nclass ChartController extends Component {\n    constructor() {\n        super();\n        this.SERVER = process.env.REACT_APP_SERVER || ''; \n\n        this.state = {sidebarCollapsed: false};\n    }\n    \n    componentDidMount() {\n        fetch(this.SERVER + \"/periods/\")\n            .then(response => {\n                return response.json()\n            })\n            .then(myJson => {\n                myJson.map((period_name, idx) => {\n                    (idx === 0) && this.props.changeActivePeriod(period_name);\n                    return this.props.addPeriod(period_name);\n                })\n                \n            })\n            .then(\n                setInterval(() => this.update(), 1000)\n            )\n    }\n\n    update() {\n        if (this.props.active_period) {\n            fetch(this.SERVER + \"/periods/\" + this.props.active_period)\n                .then(response => {\n                    return response.json()\n                })\n                .then(myJson => {\n                    this.props.updateCandlesticks(myJson)\n                })\n            if (this.props.primary_section === \"balances\") {\n                fetch(this.SERVER + \"/balances/\")\n                    .then(response => {\n                        return response.json()\n                    })\n                    .then(myJson => {\n                        this.props.updateBalances(myJson)\n                    })\n            } \n            switch(this.props.secondary_section) {\n                case \"details\":\n                    fetch(this.SERVER + \"/indicators/\" + this.props.active_period)\n                        .then(response => {\n                            return response.json()\n                        })\n                        .then(myJson => {\n                            this.props.updateIndicators(myJson)\n                        })\n                    break;\n                case \"flags\":\n                    fetch(this.SERVER + \"/flags/\")\n                        .then(response => {\n                            return response.json()\n                        })\n                        .then(myJson => {\n                            this.props.updateFlags(myJson)\n                        })\n                    break;\n                case \"orders\":\n                    fetch(this.SERVER + \"/orders/\")\n                        .then(response => {\n                            return response.json()\n                        })\n                        .then(myJson => {\n                            this.props.updateOrders(myJson)\n                        })\n                    break;\n                default:\n                    break;\n            }\n        }\n    }\n\n    render() {\n        this.update();\n        return (\n            <div className={this.state.sidebarCollapsed ? \"collapsed\" : \"\"} id=\"chart-controller\">\n                <ChartContainer />\n                <CollapseButton collapsed={this.state.sidebarCollapsed} onClick={()=>{this.setState({sidebarCollapsed: !this.state.sidebarCollapsed})}} />\n                {!this.state.sidebarCollapsed && <SidebarContainer />}\n            </div>\n        )\n    }\n}\n\nconst mapStateToProps = state => ({\n    active_period: state.chart.active_period,\n    primary_section: state.sidebar.primary_section,\n    secondary_section: state.sidebar.secondary_section\n  })\n  \nconst mapDispatchToProps = dispatch => ({\n    addPeriod: period_name => dispatch(addPeriod(period_name)),\n    changeActivePeriod: period_name => dispatch(changeActivePeriod(period_name)),\n    updateCandlesticks: candlesticks => dispatch(updateCandlesticks(candlesticks)),\n    updateIndicators: indicators => dispatch(updateIndicators(indicators)),\n    updateFlags: flags => dispatch(updateFlags(flags)),\n    updateOrders: orders => dispatch(updateOrders(orders)),\n    updateBalances: balances => dispatch(updateBalances(balances))\n})\n\nexport default connect(mapStateToProps, mapDispatchToProps)(ChartController);"
  },
  {
    "path": "cbpro-trader/web/src/containers/DetailsContainer.jsx",
    "content": "import { connect } from 'react-redux'\nimport Details from '../components/Details'\n\nconst mapStateToProps = state => ({\n    indicators: state.sidebar.indicators\n})\n\nexport default connect(mapStateToProps)(Details);"
  },
  {
    "path": "cbpro-trader/web/src/containers/FlagsContainer.jsx",
    "content": "import { connect } from 'react-redux'\nimport Flags from '../components/Flags'\n\nconst mapStateToProps = state => ({\n    flags: state.sidebar.flags\n})\n\nexport default connect(mapStateToProps)(Flags);"
  },
  {
    "path": "cbpro-trader/web/src/containers/OrdersContainer.jsx",
    "content": "import { connect } from 'react-redux'\nimport Orders from '../components/Orders'\n\nconst mapStateToProps = state => ({\n    orders: state.sidebar.orders\n})\n\nexport default connect(mapStateToProps)(Orders);"
  },
  {
    "path": "cbpro-trader/web/src/containers/SidebarContainer.jsx",
    "content": "import { connect } from 'react-redux'\nimport { changeActivePeriod, changePrimarySection, changeSecondarySection } from '../actions'\nimport Sidebar from '../components/Sidebar'\n\nconst mapStateToProps = state => ({\n    period_list: state.chart.period_list,\n    active_period: state.chart.active_period,\n    primary_section: state.sidebar.primary_section,\n    secondary_section: state.sidebar.secondary_section\n})\n\nconst mapDispatchToProps = dispatch => ({\n    changeActivePeriod: period_name => dispatch(changeActivePeriod(period_name)),\n    changePrimarySection: section_name => dispatch(changePrimarySection(section_name)),\n    changeSecondarySection: section_name => dispatch(changeSecondarySection(section_name))\n})\n\nexport default connect(mapStateToProps, mapDispatchToProps)(Sidebar);"
  },
  {
    "path": "cbpro-trader/web/src/index.css",
    "content": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n    \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\",\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, \"Courier New\",\n    monospace;\n}\n"
  },
  {
    "path": "cbpro-trader/web/src/index.js",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\nimport { createStore } from 'redux'\nimport { Provider } from 'react-redux'\nimport rootReducer from './reducers/index'\n\nconst store = createStore(rootReducer)\n\nReactDOM.render(<Provider store={store}>\n                    <App />\n                </Provider>, document.getElementById('root'));\n\n// If you want your app to work offline and load faster, you can change\n// unregister() to register() below. Note this comes with some pitfalls.\n// Learn more about service workers: https://bit.ly/CRA-PWA\nserviceWorker.unregister();\n"
  },
  {
    "path": "cbpro-trader/web/src/reducers/chart.js",
    "content": "const chart = (state = {period_list: [], candlesticks: [], indicators: []}, action) => {\n    switch (action.type) {\n        case 'CHANGE_ACTIVE_PERIOD':\n            return {\n                ...state,\n                active_period: action.period_name\n            }\n        case 'ADD_PERIOD':\n            return {\n                ...state,\n                period_list: [...state.period_list, action.period_name]\n            }\n        case 'CLEAR_PERIODS':\n            return {\n                ...state,\n                period_list: []\n            }\n        case 'UPDATE_CANDLESTICKS':\n            return {\n                ...state,\n                candlesticks: action.candlesticks\n            }\n        default:\n            return state\n    }\n}\n\nexport default chart;"
  },
  {
    "path": "cbpro-trader/web/src/reducers/index.js",
    "content": "import { combineReducers } from 'redux'\nimport chart from './chart'\nimport sidebar from './sidebar'\n\nexport default combineReducers({\n    chart,\n    sidebar\n})"
  },
  {
    "path": "cbpro-trader/web/src/reducers/sidebar.js",
    "content": "const sidebar = (state = {indicators: [], flags: {}, balances: {}, orders: {'fills': [], 'orders': []},\n                          primary_section: \"periods\", secondary_section: \"details\"}, action) => {\n    switch (action.type) {\n        case 'CHANGE_PRIMARY_SECTION':\n            return {\n                ...state,\n                primary_section: action.section_name\n            }\n        case 'CHANGE_SECONDARY_SECTION':\n            return {\n                ...state,\n                secondary_section: action.section_name\n            }\n        case 'UPDATE_BALANCES':\n            return {\n                ...state,\n                balances: action.balances\n            }\n        case 'UPDATE_INDICATORS':\n            return {\n                ...state,\n                indicators: action.indicators\n            }\n        case 'UPDATE_FLAGS':\n            return {\n                ...state,\n                flags: action.flags\n            }\n        case 'UPDATE_ORDERS':\n            return {\n                ...state,\n                orders: action.orders\n            }\n        default:\n            return state\n    }\n}\n\nexport default sidebar;"
  },
  {
    "path": "cbpro-trader/web/src/serviceWorker.js",
    "content": "// This optional code is used to register a service worker.\n// register() is not called by default.\n\n// This lets the app load faster on subsequent visits in production, and gives\n// it offline capabilities. However, it also means that developers (and users)\n// will only see deployed updates on subsequent visits to a page, after all the\n// existing tabs open on the page have been closed, since previously cached\n// resources are updated in the background.\n\n// To learn more about the benefits of this model and instructions on how to\n// opt-in, read https://bit.ly/CRA-PWA\n\nconst isLocalhost = Boolean(\n  window.location.hostname === 'localhost' ||\n    // [::1] is the IPv6 localhost address.\n    window.location.hostname === '[::1]' ||\n    // 127.0.0.1/8 is considered localhost for IPv4.\n    window.location.hostname.match(\n      /^127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/\n    )\n);\n\nexport function register(config) {\n  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {\n    // The URL constructor is available in all browsers that support SW.\n    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);\n    if (publicUrl.origin !== window.location.origin) {\n      // Our service worker won't work if PUBLIC_URL is on a different origin\n      // from what our page is served on. This might happen if a CDN is used to\n      // serve assets; see https://github.com/facebook/create-react-app/issues/2374\n      return;\n    }\n\n    window.addEventListener('load', () => {\n      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;\n\n      if (isLocalhost) {\n        // This is running on localhost. Let's check if a service worker still exists or not.\n        checkValidServiceWorker(swUrl, config);\n\n        // Add some additional logging to localhost, pointing developers to the\n        // service worker/PWA documentation.\n        navigator.serviceWorker.ready.then(() => {\n          console.log(\n            'This web app is being served cache-first by a service ' +\n              'worker. To learn more, visit https://bit.ly/CRA-PWA'\n          );\n        });\n      } else {\n        // Is not localhost. Just register service worker\n        registerValidSW(swUrl, config);\n      }\n    });\n  }\n}\n\nfunction registerValidSW(swUrl, config) {\n  navigator.serviceWorker\n    .register(swUrl)\n    .then(registration => {\n      registration.onupdatefound = () => {\n        const installingWorker = registration.installing;\n        if (installingWorker == null) {\n          return;\n        }\n        installingWorker.onstatechange = () => {\n          if (installingWorker.state === 'installed') {\n            if (navigator.serviceWorker.controller) {\n              // At this point, the updated precached content has been fetched,\n              // but the previous service worker will still serve the older\n              // content until all client tabs are closed.\n              console.log(\n                'New content is available and will be used when all ' +\n                  'tabs for this page are closed. See https://bit.ly/CRA-PWA.'\n              );\n\n              // Execute callback\n              if (config && config.onUpdate) {\n                config.onUpdate(registration);\n              }\n            } else {\n              // At this point, everything has been precached.\n              // It's the perfect time to display a\n              // \"Content is cached for offline use.\" message.\n              console.log('Content is cached for offline use.');\n\n              // Execute callback\n              if (config && config.onSuccess) {\n                config.onSuccess(registration);\n              }\n            }\n          }\n        };\n      };\n    })\n    .catch(error => {\n      console.error('Error during service worker registration:', error);\n    });\n}\n\nfunction checkValidServiceWorker(swUrl, config) {\n  // Check if the service worker can be found. If it can't reload the page.\n  fetch(swUrl)\n    .then(response => {\n      // Ensure service worker exists, and that we really are getting a JS file.\n      const contentType = response.headers.get('content-type');\n      if (\n        response.status === 404 ||\n        (contentType != null && contentType.indexOf('javascript') === -1)\n      ) {\n        // No service worker found. Probably a different app. Reload the page.\n        navigator.serviceWorker.ready.then(registration => {\n          registration.unregister().then(() => {\n            window.location.reload();\n          });\n        });\n      } else {\n        // Service worker found. Proceed as normal.\n        registerValidSW(swUrl, config);\n      }\n    })\n    .catch(() => {\n      console.log(\n        'No internet connection found. App is running in offline mode.'\n      );\n    });\n}\n\nexport function unregister() {\n  if ('serviceWorker' in navigator) {\n    navigator.serviceWorker.ready.then(registration => {\n      registration.unregister();\n    });\n  }\n}\n"
  },
  {
    "path": "docker-compose.prod.yml",
    "content": "version: \"3\"\nservices:\n  cbpro:\n    ports:\n      - \"8080:8080\"\n    environment:\n      PRODUCTION: 'true'"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: \"3\"\nservices:\n  cbpro:\n    build: ./cbpro-trader/daemon\n    command: python3 ./cbpro-trader.py\n    volumes:\n      - ./cbpro-trader/daemon/:/cbpro-trader/:Z\n  web:\n    build: ./cbpro-trader/web\n    command: bash -c \"npm install && npm start\"\n    volumes:\n      - ./cbpro-trader/web/:/frontend/:Z"
  }
]