diff --git a/.vscode/configurationCache.log b/.vscode/configurationCache.log
new file mode 100644
index 00000000..bab9054b
--- /dev/null
+++ b/.vscode/configurationCache.log
@@ -0,0 +1 @@
+{"buildTargets":[],"launchTargets":[],"customConfigurationProvider":{"workspaceBrowse":{"browsePath":[],"compilerArgs":[]},"fileIndex":[]}}
\ No newline at end of file
diff --git a/AGPL_LICENSE b/AGPL_LICENSE
new file mode 100644
index 00000000..0ad25db4
--- /dev/null
+++ b/AGPL_LICENSE
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU Affero General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published
+ by the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+.
diff --git a/LICENSE b/MIT_LICENSE
similarity index 100%
rename from LICENSE
rename to MIT_LICENSE
diff --git a/README.md b/README.md
index b1209c6e..337c91e3 100644
--- a/README.md
+++ b/README.md
@@ -1,21 +1,154 @@
-
# lightweight-charts-python
-[](https://pypi.org/project/lightweight-charts/)
-[](https://python.org "Go to Python homepage")
-[](https://github.com/louisnw01/lightweight-charts-python/blob/main/LICENSE)
+## Installation
+
+```bash
+pip install lightweight-charts-esistjosh
+
+
+## Installation
+```
+pip install lightweight-charts-esistjosh
+```
+## Forked to Add Features
+
+
+### PineTS integration (original PineTS source: https://github.com/alaa-eddine/PineTS, edited source: https://github.com/EsIstJosh/PineTS)
+### PineTS related code is licensed seperately using the AGPL3.0 license: [AGPL License](./AGPL_LICENSE)
+ Simple scripting capabilities similar to pinescript,
+ see the [PineTS ReadMe](https://github.com/EsIstJosh/PineTS/blob/bd79b7f2d21d15f7470da118eab4f71638ce07da/README.md)
+ for more information
+
+
+
+
+
+
+
+### Series Types
+ - Area
+ - Bar
+ - Custom Candlestick implementation
+ | | |
+ V V V
+ - Capable of candle data aggregation
+ for displaying multiple timeframes
+ simultaneously
+ - Customizable Line Width
+ - Customizable Line Style
+ - Customizable Bar Spacing
+ - Customizable Shape:
+ - Rectangle
+ - Rounded
+ - Ellipse
+ - Arrow
+ - Polygon
+ - Bar
+ - 3d
+ - Volume Color Opacity
+
+
+### Plugins
+ - Fill Area: Shades the area between two series.
+ - Pitch Fork: Tool for drawing (added to toolbox):
+ - Standard
+ - Schiff
+ - Modified Schiff
+ - Inside
+ - Volume Profile: Displays volume profiles based on the visible range and supports drawing.
+
+ - Trend Trace: A transformable/scalable replica of a section of series between a drawings points. Similar to 'Bars Pattern' in TradingView (instantiated from and linked to existing drawing: box, trendline etc)
+
+
+### Indicators (implemented in typescript, from KLineChart primarily ( https://github.com/klinecharts/KLineChart ))
+
+ Overlay Indicators:
+ - Arnaud Legoux Moving Average
+ - Bollinger Bands
+ - Exponential Moving Average
+ - Highest High
+ - Highest High Lowest Low
+ - Linear Regression Indicator
+ - Lowest Low
+ - Median
+ - Moving Average
+ - Rolling Moving Average
+ - Simple Moving Average
+ - Stop and Reverse
+ - Super Trend
+ - Symmetric Weighted Moving Average
+ - Triple Exponentially Smoothed Average
+ - Volume Weighted Average Price
+ - Volume Weighted Moving Average
+ - Weighted Moving Average
+
+ Oscillator Indicators:
+ - Awesome Oscillator
+ - Average True Range
+ - Bias
+ - BRAR
+ - Bull and Bear Index
+ - Commodity Channel Index
+ - Current Ratio
+ - Difference of Moving Average
+ - Directional Movement Index
+ - Momentum
+ - Moving Average Convergence Divergence
+ - Psychological Line
+ - Rate of Change
+ - Relative Strength Index
+ - Stochastic Oscillator
+ - Variance
+ - Williams %R
+ - Change
+ - Range
+ - Standard Deviation
+
+### Context Menu
+ - Upgraded context menu for better control over chart/series/primitive settings.
+ - Ability to save options for chart, series, and primitives to JSON.
+
+### Legend
+ - Upgraded to allow for collapsible grouping of series.
+ - Tree-style display of groups > series > primitives.
+
+### Series Cloning / Type Conversion
+ - Simple cloning to different series types
+
+
+
+
+## License
+
+Unless otherwise stated, all code in this repository is licensed under the MIT License.
+
+Additional license: See the [AGPL License](./AGPL_LICENSE) for specific components covered under AGPL.
+
+For full details, refer to the [MIT License](./MIT_LICENSE).
+---####################################################################################---
+## Original
+
+
+[](https://pypi.org/project/lightweight-charts/)
+[](https://python.org "Go to Python homepage")
[](https://lightweight-charts-python.readthedocs.io/en/latest/index.html)
-
-lightweight-charts-python aims to provide a simple and pythonic way to access and implement [TradingView's Lightweight Charts](https://www.tradingview.com/lightweight-charts/).
-
+**lightweight-charts-python** aims to provide a simple and Pythonic way to access and implement [TradingView's Lightweight Charts](https://www.tradingview.com/lightweight-charts/).
+
+---
+
+
+## Installation
+
+```bash
+pip install lightweight-charts-esistjosh
## Installation
```
-pip install lightweight-charts
+pip install lightweight-charts-esistjosh
```
___
diff --git a/Screenshot2025-02-07114921.png b/Screenshot2025-02-07114921.png
new file mode 100644
index 00000000..cf03f54f
Binary files /dev/null and b/Screenshot2025-02-07114921.png differ
diff --git a/build.sh b/build.sh
index ea049c03..f7dbbd9c 100755
--- a/build.sh
+++ b/build.sh
@@ -1,34 +1,113 @@
#!/usr/bin/env bash
+set -euo pipefail
+IFS=$'\n\t'
+# ─── Configurable Python binary ─────────────────────────────────────────────
+VENV_PYTHON="${VENV_PYTHON:-/home/linux/lightweight-charts-python/venv/bin/python}"
+
+# ─── Color codes ─────────────────────────────────────────────────────────────
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
-NC='\033[0m'
+NC='\033[0m' # No Color
+# ─── Message prefixes ───────────────────────────────────────────────────────
ERROR="${RED}[ERROR]${NC} "
INFO="${CYAN}[INFO]${NC} "
-WARNING="${WARNING}[WARNING]${NC} "
+WARNING="${YELLOW}[WARNING]${NC} "
+
+# ─── Flags ───────────────────────────────────────────────────────────────────
+BUILD=false
+PACKAGE=false
+UPLOAD=false
-rm -rf dist/bundle.js dist/typings/
+# ─── Parse command-line options ─────────────────────────────────────────────
+while getopts ":bpu" opt; do
+ case "${opt}" in
+ b )
+ BUILD=true
+ ;;
+ p )
+ PACKAGE=true
+ ;;
+ u )
+ UPLOAD=true
+ PACKAGE=true # ensure package runs before upload
+ BUILD=true # ensure build runs before package
+ ;;
+ \? )
+ echo -e "${ERROR}Invalid option: -$OPTARG" >&2
+ exit 1
+ ;;
+ esac
+done
-if [[ $? -eq 0 ]]; then
- echo -e "${INFO}deleted bundle.js and typings.."
-else
- echo -e "${WARNING}could not delete old dist files, continuing.."
+# ─── Default to build if no flags provided ──────────────────────────────────
+if ! $BUILD && ! $PACKAGE && ! $UPLOAD; then
+ BUILD=true
fi
-npx rollup -c rollup.config.js
-if [[ $? -ne 0 ]]; then
+# ─── Build process ──────────────────────────────────────────────────────────
+perform_build() {
+ echo -e "${INFO}Starting build process..."
+ rm -rf dist/bundle.js dist/typings/ || echo -e "${WARNING}No old artifacts to clean"
+ npx rollup -c rollup.config.js || { echo -e "${ERROR}Rollup build failed."; exit 1; }
+ cp dist/bundle.js src/general/styles.css lightweight_charts_esistjosh/js/ \
+ || { echo -e "${ERROR}Failed to copy build outputs."; exit 1; }
+ echo -e "${GREEN}[BUILD SUCCESS]${NC}"
+}
+
+# ─── Package & install ───────────────────────────────────────────────────────
+perform_package() {
+ echo -e "${INFO}Starting packaging & installation..."
+ sudo "$VENV_PYTHON" -m build --sdist --wheel \
+ || { echo -e "${ERROR}Packaging failed."; exit 1; }
+ sudo "$VENV_PYTHON" -m pip install . \
+ || { echo -e "${ERROR}Installation failed."; exit 1; }
+ echo -e "${GREEN}[PACKAGE & INSTALL SUCCESS]${NC}"
+}
+
+# ─── Upload to PyPI ──────────────────────────────────────────────────────────
+perform_upload() {
+ echo -e "${INFO}Starting upload process..."
+ OUTPUT_DIR="./output"
+ rm -rf "$OUTPUT_DIR"
+ mkdir -p "$OUTPUT_DIR"
+
+ shopt -s nullglob
+ files=(dist/*.tar.gz dist/*.whl)
+ shopt -u nullglob
+
+ if [ ${#files[@]} -eq 0 ]; then
+ echo -e "${WARNING}No distribution files found; skipping upload."
+ return
+ fi
+
+ mv "${files[@]}" "$OUTPUT_DIR"/ \
+ || { echo -e "${ERROR}Failed to move artifacts to ${OUTPUT_DIR}."; exit 1; }
+
+ # ensure twine is available
+ "$VENV_PYTHON" -m pip install --upgrade twine >/dev/null
+
+ echo -e "${INFO}Uploading to PyPI…"
+ if ! "$VENV_PYTHON" -m twine upload --verbose "$OUTPUT_DIR"/*; then
+ echo -e "${ERROR}Twine upload failed. Check credentials and network."
exit 1
+ fi
+
+ echo -e "${GREEN}[UPLOAD SUCCESS]${NC}"
+}
+
+# ─── Execution order ─────────────────────────────────────────────────────────
+if $BUILD; then
+ perform_build
fi
-cp dist/bundle.js src/general/styles.css lightweight_charts/js
-if [[ $? -eq 0 ]]; then
- echo -e "${INFO}copied bundle.js, style.css into python package"
-else
- echo -e "${ERROR}could not copy dist into python package ?"
- exit 1
+if $PACKAGE; then
+ perform_package
fi
-echo -e "\n${GREEN}[BUILD SUCCESS]${NC}"
+if $UPLOAD; then
+ perform_upload
+fi
diff --git a/docs/source/examples/.events.md.kate-swp b/docs/source/examples/.events.md.kate-swp
new file mode 100644
index 00000000..718685d8
Binary files /dev/null and b/docs/source/examples/.events.md.kate-swp differ
diff --git a/docs/source/examples/subchart.md b/docs/source/examples/subchart.md
index 91ec8379..a4323bb6 100644
--- a/docs/source/examples/subchart.md
+++ b/docs/source/examples/subchart.md
@@ -4,7 +4,7 @@
```python
import pandas as pd
-from lightweight_charts import Chart
+from lightweight_charts_esistjosh import Chart
if __name__ == '__main__':
chart = Chart(inner_width=0.5, inner_height=0.5)
@@ -32,7 +32,7 @@ ___
```python
import pandas as pd
-from lightweight_charts import Chart
+from lightweight_charts_esistjosh import Chart
if __name__ == '__main__':
chart = Chart(inner_width=1, inner_height=0.8)
@@ -55,7 +55,7 @@ ___
```python
import pandas as pd
-from lightweight_charts import Chart
+from lightweight_charts_esistjosh import Chart
# ascii symbols
FULLSCREEN = '■'
diff --git a/lightweight_charts/abstract.py b/lightweight_charts/abstract.py
deleted file mode 100644
index 0091d3f2..00000000
--- a/lightweight_charts/abstract.py
+++ /dev/null
@@ -1,961 +0,0 @@
-import asyncio
-import json
-import os
-from base64 import b64decode
-from datetime import datetime
-from typing import Callable, Union, Literal, List, Optional
-import pandas as pd
-
-from .table import Table
-from .toolbox import ToolBox
-from .drawings import Box, HorizontalLine, RayLine, TrendLine, TwoPointDrawing, VerticalLine, VerticalSpan
-from .topbar import TopBar
-from .util import (
- BulkRunScript, Pane, Events, IDGen, as_enum, jbool, js_json, TIME, NUM, FLOAT,
- LINE_STYLE, MARKER_POSITION, MARKER_SHAPE, CROSSHAIR_MODE,
- PRICE_SCALE_MODE, marker_position, marker_shape, js_data,
-)
-
-current_dir = os.path.dirname(os.path.abspath(__file__))
-INDEX = os.path.join(current_dir, 'js', 'index.html')
-
-
-class Window:
- _id_gen = IDGen()
- handlers = {}
-
- def __init__(
- self,
- script_func: Optional[Callable] = None,
- js_api_code: Optional[str] = None,
- run_script: Optional[Callable] = None
- ):
- self.loaded = False
- self.script_func = script_func
- self.scripts = []
- self.final_scripts = []
- self.bulk_run = BulkRunScript(script_func)
-
- if run_script:
- self.run_script = run_script
-
- if js_api_code:
- self.run_script(f'window.callbackFunction = {js_api_code}')
-
- def on_js_load(self):
- if self.loaded:
- return
- self.loaded = True
-
- if hasattr(self, '_return_q'):
- while not self.run_script_and_get('document.readyState == "complete"'):
- continue # scary, but works
-
- initial_script = ''
- self.scripts.extend(self.final_scripts)
- for script in self.scripts:
- initial_script += f'\n{script}'
- self.script_func(initial_script)
-
- def run_script(self, script: str, run_last: bool = False):
- """
- For advanced users; evaluates JavaScript within the Webview.
- """
- if self.script_func is None:
- raise AttributeError("script_func has not been set")
- if self.loaded:
- if self.bulk_run.enabled:
- self.bulk_run.add_script(script)
- else:
- self.script_func(script)
- elif run_last:
- self.final_scripts.append(script)
- else:
- self.scripts.append(script)
-
- def run_script_and_get(self, script: str):
- self.run_script(f'_~_~RETURN~_~_{script}')
- return self._return_q.get()
-
- def create_table(
- self,
- width: NUM,
- height: NUM,
- headings: tuple,
- widths: Optional[tuple] = None,
- alignments: Optional[tuple] = None,
- position: FLOAT = 'left',
- draggable: bool = False,
- background_color: str = '#121417',
- border_color: str = 'rgb(70, 70, 70)',
- border_width: int = 1,
- heading_text_colors: Optional[tuple] = None,
- heading_background_colors: Optional[tuple] = None,
- return_clicked_cells: bool = False,
- func: Optional[Callable] = None
- ) -> 'Table':
- return Table(*locals().values())
-
- def create_subchart(
- self,
- position: FLOAT = 'left',
- width: float = 0.5,
- height: float = 0.5,
- sync_id: Optional[str] = None,
- scale_candles_only: bool = False,
- sync_crosshairs_only: bool = False,
- toolbox: bool = False
- ) -> 'AbstractChart':
- subchart = AbstractChart(
- self,
- width,
- height,
- scale_candles_only,
- toolbox,
- position=position
- )
- if not sync_id:
- return subchart
- self.run_script(f'''
- Lib.Handler.syncCharts(
- {subchart.id},
- {sync_id},
- {jbool(sync_crosshairs_only)}
- )
- ''', run_last=True)
- return subchart
-
- def style(
- self,
- background_color: str = '#0c0d0f',
- hover_background_color: str = '#3c434c',
- click_background_color: str = '#50565E',
- active_background_color: str = 'rgba(0, 122, 255, 0.7)',
- muted_background_color: str = 'rgba(0, 122, 255, 0.3)',
- border_color: str = '#3C434C',
- color: str = '#d8d9db',
- active_color: str = '#ececed'
- ):
- self.run_script(f'Lib.Handler.setRootStyles({js_json(locals())});')
-
-
-class SeriesCommon(Pane):
- def __init__(self, chart: 'AbstractChart', name: str = ''):
- super().__init__(chart.win)
- self._chart = chart
- if hasattr(chart, '_interval'):
- self._interval = chart._interval
- else:
- self._interval = 1
- self._last_bar = None
- self.name = name
- self.num_decimals = 2
- self.offset = 0
- self.data = pd.DataFrame()
- self.markers = {}
-
- def _set_interval(self, df: pd.DataFrame):
- if not pd.api.types.is_datetime64_any_dtype(df['time']):
- df['time'] = pd.to_datetime(df['time'])
- common_interval = df['time'].diff().value_counts()
- if common_interval.empty:
- return
- self._interval = common_interval.index[0].total_seconds()
-
- units = [
- pd.Timedelta(microseconds=df['time'].dt.microsecond.value_counts().index[0]),
- pd.Timedelta(seconds=df['time'].dt.second.value_counts().index[0]),
- pd.Timedelta(minutes=df['time'].dt.minute.value_counts().index[0]),
- pd.Timedelta(hours=df['time'].dt.hour.value_counts().index[0]),
- pd.Timedelta(days=df['time'].dt.day.value_counts().index[0]),
- ]
- self.offset = 0
- for value in units:
- value = value.total_seconds()
- if value == 0:
- continue
- elif value >= self._interval:
- break
- self.offset = value
- break
-
- @staticmethod
- def _format_labels(data, labels, index, exclude_lowercase):
- def rename(la, mapper):
- return [mapper[key] if key in mapper else key for key in la]
- if 'date' not in labels and 'time' not in labels:
- labels = labels.str.lower()
- if exclude_lowercase:
- labels = rename(labels, {exclude_lowercase.lower(): exclude_lowercase})
- if 'date' in labels:
- labels = rename(labels, {'date': 'time'})
- elif 'time' not in labels:
- data['time'] = index
- labels = [*labels, 'time']
- return labels
-
- def _df_datetime_format(self, df: pd.DataFrame, exclude_lowercase=None):
- df = df.copy()
- df.columns = self._format_labels(df, df.columns, df.index, exclude_lowercase)
- self._set_interval(df)
- if not pd.api.types.is_datetime64_any_dtype(df['time']):
- df['time'] = pd.to_datetime(df['time'])
- df['time'] = df['time'].astype('int64') // 10 ** 9
- return df
-
- def _series_datetime_format(self, series: pd.Series, exclude_lowercase=None):
- series = series.copy()
- series.index = self._format_labels(series, series.index, series.name, exclude_lowercase)
- series['time'] = self._single_datetime_format(series['time'])
- return series
-
- def _single_datetime_format(self, arg) -> float:
- if isinstance(arg, (str, int, float)) or not pd.api.types.is_datetime64_any_dtype(arg):
- try:
- arg = pd.to_datetime(arg, unit='ms')
- except ValueError:
- arg = pd.to_datetime(arg)
- arg = self._interval * (arg.timestamp() // self._interval)+self.offset
- return arg
-
- def set(self, df: Optional[pd.DataFrame] = None, format_cols: bool = True):
- if df is None or df.empty:
- self.run_script(f'{self.id}.series.setData([])')
- self.data = pd.DataFrame()
- return
- if format_cols:
- df = self._df_datetime_format(df, exclude_lowercase=self.name)
- if self.name:
- if self.name not in df:
- raise NameError(f'No column named "{self.name}".')
- df = df.rename(columns={self.name: 'value'})
- self.data = df.copy()
- self._last_bar = df.iloc[-1]
- self.run_script(f'{self.id}.series.setData({js_data(df)}); ')
-
- def update(self, series: pd.Series):
- series = self._series_datetime_format(series, exclude_lowercase=self.name)
- if self.name in series.index:
- series.rename({self.name: 'value'}, inplace=True)
- if self._last_bar is not None and series['time'] != self._last_bar['time']:
- self.data.loc[self.data.index[-1]] = self._last_bar
- self.data = pd.concat([self.data, series.to_frame().T], ignore_index=True)
- self._last_bar = series
- self.run_script(f'{self.id}.series.update({js_data(series)})')
-
- def _update_markers(self):
- self.run_script(f'{self.id}.series.setMarkers({json.dumps(list(self.markers.values()))})')
-
- def marker_list(self, markers: list):
- """
- Creates multiple markers.\n
- :param markers: The list of markers to set. These should be in the format:\n
- [
- {"time": "2021-01-21", "position": "below", "shape": "circle", "color": "#2196F3", "text": ""},
- {"time": "2021-01-22", "position": "below", "shape": "circle", "color": "#2196F3", "text": ""},
- ...
- ]
- :return: a list of marker ids.
- """
- markers = markers.copy()
- marker_ids = []
- for marker in markers:
- marker_id = self.win._id_gen.generate()
- self.markers[marker_id] = {
- "time": self._single_datetime_format(marker['time']),
- "position": marker_position(marker['position']),
- "color": marker['color'],
- "shape": marker_shape(marker['shape']),
- "text": marker['text'],
- }
- marker_ids.append(marker_id)
- self._update_markers()
- return marker_ids
-
- def marker(self, time: Optional[datetime] = None, position: MARKER_POSITION = 'below',
- shape: MARKER_SHAPE = 'arrow_up', color: str = '#2196F3', text: str = ''
- ) -> str:
- """
- Creates a new marker.\n
- :param time: Time location of the marker. If no time is given, it will be placed at the last bar.
- :param position: The position of the marker.
- :param color: The color of the marker (rgb, rgba or hex).
- :param shape: The shape of the marker.
- :param text: The text to be placed with the marker.
- :return: The id of the marker placed.
- """
- try:
- formatted_time = self._last_bar['time'] if not time else self._single_datetime_format(time)
- except TypeError:
- raise TypeError('Chart marker created before data was set.')
- marker_id = self.win._id_gen.generate()
-
- self.markers[marker_id] = {
- "time": formatted_time,
- "position": marker_position(position),
- "color": color,
- "shape": marker_shape(shape),
- "text": text,
- }
- self._update_markers()
- return marker_id
-
- def remove_marker(self, marker_id: str):
- """
- Removes the marker with the given id.\n
- """
- self.markers.pop(marker_id)
- self._update_markers()
-
- def horizontal_line(self, price: NUM, color: str = 'rgb(122, 146, 202)', width: int = 2,
- style: LINE_STYLE = 'solid', text: str = '', axis_label_visible: bool = True,
- func: Optional[Callable] = None
- ) -> 'HorizontalLine':
- """
- Creates a horizontal line at the given price.
- """
- return HorizontalLine(self, price, color, width, style, text, axis_label_visible, func)
-
- def trend_line(
- self,
- start_time: TIME,
- start_value: NUM,
- end_time: TIME,
- end_value: NUM,
- round: bool = False,
- line_color: str = '#1E80F0',
- width: int = 2,
- style: LINE_STYLE = 'solid',
- ) -> TwoPointDrawing:
- return TrendLine(*locals().values())
-
- def box(
- self,
- start_time: TIME,
- start_value: NUM,
- end_time: TIME,
- end_value: NUM,
- round: bool = False,
- color: str = '#1E80F0',
- fill_color: str = 'rgba(255, 255, 255, 0.2)',
- width: int = 2,
- style: LINE_STYLE = 'solid',
- ) -> TwoPointDrawing:
- return Box(*locals().values())
-
- def ray_line(
- self,
- start_time: TIME,
- value: NUM,
- round: bool = False,
- color: str = '#1E80F0',
- width: int = 2,
- style: LINE_STYLE = 'solid',
- text: str = ''
- ) -> RayLine:
- # TODO
- return RayLine(*locals().values())
-
- def vertical_line(
- self,
- time: TIME,
- color: str = '#1E80F0',
- width: int = 2,
- style: LINE_STYLE ='solid',
- text: str = ''
- ) -> VerticalLine:
- return VerticalLine(*locals().values())
-
- def clear_markers(self):
- """
- Clears the markers displayed on the data.\n
- """
- self.markers.clear()
- self._update_markers()
-
- def price_line(self, label_visible: bool = True, line_visible: bool = True, title: str = ''):
- self.run_script(f'''
- {self.id}.series.applyOptions({{
- lastValueVisible: {jbool(label_visible)},
- priceLineVisible: {jbool(line_visible)},
- title: '{title}',
- }})''')
-
- def precision(self, precision: int):
- """
- Sets the precision and minMove.\n
- :param precision: The number of decimal places.
- """
- min_move = 1 / (10**precision)
- self.run_script(f'''
- {self.id}.series.applyOptions({{
- priceFormat: {{precision: {precision}, minMove: {min_move}}}
- }})''')
- self.num_decimals = precision
-
- def hide_data(self):
- self._toggle_data(False)
-
- def show_data(self):
- self._toggle_data(True)
-
- def _toggle_data(self, arg):
- self.run_script(f'''
- {self.id}.series.applyOptions({{visible: {jbool(arg)}}})
- if ('volumeSeries' in {self.id}) {self.id}.volumeSeries.applyOptions({{visible: {jbool(arg)}}})
- ''')
-
- def vertical_span(
- self,
- start_time: Union[TIME, tuple, list],
- end_time: Optional[TIME] = None,
- color: str = 'rgba(252, 219, 3, 0.2)',
- round: bool = False
- ):
- """
- Creates a vertical line or span across the chart.\n
- Start time and end time can be used together, or end_time can be
- omitted and a single time or a list of times can be passed to start_time.
- """
- if round:
- start_time = self._single_datetime_format(start_time)
- end_time = self._single_datetime_format(end_time) if end_time else None
- return VerticalSpan(self, start_time, end_time, color)
-
-
-class Line(SeriesCommon):
- def __init__(self, chart, name, color, style, width, price_line, price_label, price_scale_id=None, crosshair_marker=True):
-
- super().__init__(chart, name)
- self.color = color
-
- self.run_script(f'''
- {self.id} = {self._chart.id}.createLineSeries(
- "{name}",
- {{
- color: '{color}',
- lineStyle: {as_enum(style, LINE_STYLE)},
- lineWidth: {width},
- lastValueVisible: {jbool(price_label)},
- priceLineVisible: {jbool(price_line)},
- crosshairMarkerVisible: {jbool(crosshair_marker)},
- priceScaleId: {f'"{price_scale_id}"' if price_scale_id else 'undefined'}
- {"""autoscaleInfoProvider: () => ({
- priceRange: {
- minValue: 1_000_000_000,
- maxValue: 0,
- },
- }),
- """ if chart._scale_candles_only else ''}
- }}
- )
- null''')
-
- # def _set_trend(self, start_time, start_value, end_time, end_value, ray=False, round=False):
- # if round:
- # start_time = self._single_datetime_format(start_time)
- # end_time = self._single_datetime_format(end_time)
- # else:
- # start_time, end_time = pd.to_datetime((start_time, end_time)).astype('int64') // 10 ** 9
-
- # self.run_script(f'''
- # {self._chart.id}.chart.timeScale().applyOptions({{shiftVisibleRangeOnNewBar: false}})
- # {self.id}.series.setData(
- # calculateTrendLine({start_time}, {start_value}, {end_time}, {end_value},
- # {self._chart.id}, {jbool(ray)}))
- # {self._chart.id}.chart.timeScale().applyOptions({{shiftVisibleRangeOnNewBar: true}})
- # ''')
-
- def delete(self):
- """
- Irreversibly deletes the line, as well as the object that contains the line.
- """
- self._chart._lines.remove(self) if self in self._chart._lines else None
- self.run_script(f'''
- {self.id}legendItem = {self._chart.id}.legend._lines.find((line) => line.series == {self.id}.series)
- {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter((item) => item != {self.id}legendItem)
-
- if ({self.id}legendItem) {{
- {self._chart.id}.legend.div.removeChild({self.id}legendItem.row)
- }}
-
- {self._chart.id}.chart.removeSeries({self.id}.series)
- delete {self.id}legendItem
- delete {self.id}
- ''')
-
-
-class Histogram(SeriesCommon):
- def __init__(self, chart, name, color, price_line, price_label, scale_margin_top, scale_margin_bottom):
- super().__init__(chart, name)
- self.color = color
- self.run_script(f'''
- {self.id} = {chart.id}.createHistogramSeries(
- "{name}",
- {{
- color: '{color}',
- lastValueVisible: {jbool(price_label)},
- priceLineVisible: {jbool(price_line)},
- priceScaleId: '{self.id}',
- priceFormat: {{type: "volume"}},
- }},
- // precision: 2,
- )
- {self.id}.series.priceScale().applyOptions({{
- scaleMargins: {{top:{scale_margin_top}, bottom: {scale_margin_bottom}}}
- }})''')
-
- def delete(self):
- """
- Irreversibly deletes the histogram.
- """
- self.run_script(f'''
- {self.id}legendItem = {self._chart.id}.legend._lines.find((line) => line.series == {self.id}.series)
- {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter((item) => item != {self.id}legendItem)
-
- if ({self.id}legendItem) {{
- {self._chart.id}.legend.div.removeChild({self.id}legendItem.row)
- }}
-
- {self._chart.id}.chart.removeSeries({self.id}.series)
- delete {self.id}legendItem
- delete {self.id}
- ''')
-
- def scale(self, scale_margin_top: float = 0.0, scale_margin_bottom: float = 0.0):
- self.run_script(f'''
- {self.id}.series.priceScale().applyOptions({{
- scaleMargins: {{top: {scale_margin_top}, bottom: {scale_margin_bottom}}}
- }})''')
-
-
-class Candlestick(SeriesCommon):
- def __init__(self, chart: 'AbstractChart'):
- super().__init__(chart)
- self._volume_up_color = 'rgba(83,141,131,0.8)'
- self._volume_down_color = 'rgba(200,127,130,0.8)'
-
- self.candle_data = pd.DataFrame()
-
- # self.run_script(f'{self.id}.makeCandlestickSeries()')
-
- def set(self, df: Optional[pd.DataFrame] = None, keep_drawings=False):
- """
- Sets the initial data for the chart.\n
- :param df: columns: date/time, open, high, low, close, volume (if volume enabled).
- :param keep_drawings: keeps any drawings made through the toolbox. Otherwise, they will be deleted.
- """
- if df is None or df.empty:
- self.run_script(f'{self.id}.series.setData([])')
- self.run_script(f'{self.id}.volumeSeries.setData([])')
- self.candle_data = pd.DataFrame()
- return
- df = self._df_datetime_format(df)
- self.candle_data = df.copy()
- self._last_bar = df.iloc[-1]
- self.run_script(f'{self.id}.series.setData({js_data(df)})')
-
- if 'volume' not in df:
- return
- volume = df.drop(columns=['open', 'high', 'low', 'close']).rename(columns={'volume': 'value'})
- volume['color'] = self._volume_down_color
- volume.loc[df['close'] > df['open'], 'color'] = self._volume_up_color
- self.run_script(f'{self.id}.volumeSeries.setData({js_data(volume)})')
-
- for line in self._lines:
- if line.name not in df.columns:
- continue
- line.set(df[['time', line.name]], format_cols=False)
- # set autoScale to true in case the user has dragged the price scale
- self.run_script(f'''
- if (!{self.id}.chart.priceScale("right").options.autoScale)
- {self.id}.chart.priceScale("right").applyOptions({{autoScale: true}})
- ''')
- # TODO keep drawings doesn't work consistenly w
- if keep_drawings:
- self.run_script(f'{self._chart.id}.toolBox?._drawingTool.repositionOnTime()')
- else:
- self.run_script(f"{self._chart.id}.toolBox?.clearDrawings()")
-
- def update(self, series: pd.Series, _from_tick=False):
- """
- Updates the data from a bar;
- if series['time'] is the same time as the last bar, the last bar will be overwritten.\n
- :param series: labels: date/time, open, high, low, close, volume (if using volume).
- """
- series = self._series_datetime_format(series) if not _from_tick else series
- if series['time'] != self._last_bar['time']:
- self.candle_data.loc[self.candle_data.index[-1]] = self._last_bar
- self.candle_data = pd.concat([self.candle_data, series.to_frame().T], ignore_index=True)
- self._chart.events.new_bar._emit(self)
-
- self._last_bar = series
- self.run_script(f'{self.id}.series.update({js_data(series)})')
- if 'volume' not in series:
- return
- volume = series.drop(['open', 'high', 'low', 'close']).rename({'volume': 'value'})
- volume['color'] = self._volume_up_color if series['close'] > series['open'] else self._volume_down_color
- self.run_script(f'{self.id}.volumeSeries.update({js_data(volume)})')
-
- def update_from_tick(self, series: pd.Series, cumulative_volume: bool = False):
- """
- Updates the data from a tick.\n
- :param series: labels: date/time, price, volume (if using volume).
- :param cumulative_volume: Adds the given volume onto the latest bar.
- """
- series = self._series_datetime_format(series)
- if series['time'] < self._last_bar['time']:
- raise ValueError(f'Trying to update tick of time "{pd.to_datetime(series["time"])}", which occurs before the last bar time of "{pd.to_datetime(self._last_bar["time"])}".')
- bar = pd.Series(dtype='float64')
- if series['time'] == self._last_bar['time']:
- bar = self._last_bar
- bar['high'] = max(self._last_bar['high'], series['price'])
- bar['low'] = min(self._last_bar['low'], series['price'])
- bar['close'] = series['price']
- if 'volume' in series:
- if cumulative_volume:
- bar['volume'] += series['volume']
- else:
- bar['volume'] = series['volume']
- else:
- for key in ('open', 'high', 'low', 'close'):
- bar[key] = series['price']
- bar['time'] = series['time']
- if 'volume' in series:
- bar['volume'] = series['volume']
- self.update(bar, _from_tick=True)
-
- def price_scale(
- self,
- auto_scale: bool = True,
- mode: PRICE_SCALE_MODE = 'normal',
- invert_scale: bool = False,
- align_labels: bool = True,
- scale_margin_top: float = 0.2,
- scale_margin_bottom: float = 0.2,
- border_visible: bool = False,
- border_color: Optional[str] = None,
- text_color: Optional[str] = None,
- entire_text_only: bool = False,
- visible: bool = True,
- ticks_visible: bool = False,
- minimum_width: int = 0
- ):
- self.run_script(f'''
- {self.id}.series.priceScale().applyOptions({{
- autoScale: {jbool(auto_scale)},
- mode: {as_enum(mode, PRICE_SCALE_MODE)},
- invertScale: {jbool(invert_scale)},
- alignLabels: {jbool(align_labels)},
- scaleMargins: {{top: {scale_margin_top}, bottom: {scale_margin_bottom}}},
- borderVisible: {jbool(border_visible)},
- {f'borderColor: "{border_color}",' if border_color else ''}
- {f'textColor: "{text_color}",' if text_color else ''}
- entireTextOnly: {jbool(entire_text_only)},
- visible: {jbool(visible)},
- ticksVisible: {jbool(ticks_visible)},
- minimumWidth: {minimum_width}
- }})''')
-
- def candle_style(
- self, up_color: str = 'rgba(39, 157, 130, 100)', down_color: str = 'rgba(200, 97, 100, 100)',
- wick_visible: bool = True, border_visible: bool = True, border_up_color: str = '',
- border_down_color: str = '', wick_up_color: str = '', wick_down_color: str = ''):
- """
- Candle styling for each of its parts.\n
- If only `up_color` and `down_color` are passed, they will color all parts of the candle.
- """
- border_up_color = border_up_color if border_up_color else up_color
- border_down_color = border_down_color if border_down_color else down_color
- wick_up_color = wick_up_color if wick_up_color else up_color
- wick_down_color = wick_down_color if wick_down_color else down_color
- self.run_script(f"{self.id}.series.applyOptions({js_json(locals())})")
-
- def volume_config(self, scale_margin_top: float = 0.8, scale_margin_bottom: float = 0.0,
- up_color='rgba(83,141,131,0.8)', down_color='rgba(200,127,130,0.8)'):
- """
- Configure volume settings.\n
- Numbers for scaling must be greater than 0 and less than 1.\n
- Volume colors must be applied prior to setting/updating the bars.\n
- """
- self._volume_up_color = up_color if up_color else self._volume_up_color
- self._volume_down_color = down_color if down_color else self._volume_down_color
- self.run_script(f'''
- {self.id}.volumeSeries.priceScale().applyOptions({{
- scaleMargins: {{
- top: {scale_margin_top},
- bottom: {scale_margin_bottom},
- }}
- }})''')
-
-
-class AbstractChart(Candlestick, Pane):
- def __init__(self, window: Window, width: float = 1.0, height: float = 1.0,
- scale_candles_only: bool = False, toolbox: bool = False,
- autosize: bool = True, position: FLOAT = 'left'):
- Pane.__init__(self, window)
-
- self._lines = []
- self._scale_candles_only = scale_candles_only
- self._width = width
- self._height = height
- self.events: Events = Events(self)
-
- from lightweight_charts.polygon import PolygonAPI
- self.polygon: PolygonAPI = PolygonAPI(self)
-
- self.run_script(
- f'{self.id} = new Lib.Handler("{self.id}", {width}, {height}, "{position}", {jbool(autosize)})')
-
- Candlestick.__init__(self, self)
-
- self.topbar: TopBar = TopBar(self)
- if toolbox:
- self.toolbox: ToolBox = ToolBox(self)
-
- def fit(self):
- """
- Fits the maximum amount of the chart data within the viewport.
- """
- self.run_script(f'{self.id}.chart.timeScale().fitContent()')
-
- def create_line(
- self, name: str = '', color: str = 'rgba(214, 237, 255, 0.6)',
- style: LINE_STYLE = 'solid', width: int = 2,
- price_line: bool = True, price_label: bool = True, price_scale_id: Optional[str] = None
- ) -> Line:
- """
- Creates and returns a Line object.
- """
- self._lines.append(Line(self, name, color, style, width, price_line, price_label, price_scale_id))
- return self._lines[-1]
-
- def create_histogram(
- self, name: str = '', color: str = 'rgba(214, 237, 255, 0.6)',
- price_line: bool = True, price_label: bool = True,
- scale_margin_top: float = 0.0, scale_margin_bottom: float = 0.0
- ) -> Histogram:
- """
- Creates and returns a Histogram object.
- """
- return Histogram(
- self, name, color, price_line, price_label,
- scale_margin_top, scale_margin_bottom)
-
- def lines(self) -> List[Line]:
- """
- Returns all lines for the chart.
- """
- return self._lines.copy()
-
- def set_visible_range(self, start_time: TIME, end_time: TIME):
- self.run_script(f'''
- {self.id}.chart.timeScale().setVisibleRange({{
- from: {pd.to_datetime(start_time).timestamp()},
- to: {pd.to_datetime(end_time).timestamp()}
- }})
- ''')
-
- def resize(self, width: Optional[float] = None, height: Optional[float] = None):
- """
- Resizes the chart within the window.
- Dimensions should be given as a float between 0 and 1.
- """
- self._width = width if width is not None else self._width
- self._height = height if height is not None else self._height
- self.run_script(f'''
- {self.id}.scale.width = {self._width}
- {self.id}.scale.height = {self._height}
- {self.id}.reSize()
- ''')
-
- def time_scale(self, right_offset: int = 0, min_bar_spacing: float = 0.5,
- visible: bool = True, time_visible: bool = True, seconds_visible: bool = False,
- border_visible: bool = True, border_color: Optional[str] = None):
- """
- Options for the timescale of the chart.
- """
- self.run_script(f'''{self.id}.chart.applyOptions({{timeScale: {js_json(locals())}}})''')
-
- def layout(self, background_color: str = '#000000', text_color: Optional[str] = None,
- font_size: Optional[int] = None, font_family: Optional[str] = None):
- """
- Global layout options for the chart.
- """
- self.run_script(f"""
- document.getElementById('container').style.backgroundColor = '{background_color}'
- {self.id}.chart.applyOptions({{
- layout: {{
- background: {{color: "{background_color}"}},
- {f'textColor: "{text_color}",' if text_color else ''}
- {f'fontSize: {font_size},' if font_size else ''}
- {f'fontFamily: "{font_family}",' if font_family else ''}
- }}}})""")
-
- def grid(self, vert_enabled: bool = True, horz_enabled: bool = True,
- color: str = 'rgba(29, 30, 38, 5)', style: LINE_STYLE = 'solid'):
- """
- Grid styling for the chart.
- """
- self.run_script(f"""
- {self.id}.chart.applyOptions({{
- grid: {{
- vertLines: {{
- visible: {jbool(vert_enabled)},
- color: "{color}",
- style: {as_enum(style, LINE_STYLE)},
- }},
- horzLines: {{
- visible: {jbool(horz_enabled)},
- color: "{color}",
- style: {as_enum(style, LINE_STYLE)},
- }},
- }}
- }})""")
-
- def crosshair(
- self,
- mode: CROSSHAIR_MODE = 'normal',
- vert_visible: bool = True,
- vert_width: int = 1,
- vert_color: Optional[str] = None,
- vert_style: LINE_STYLE = 'large_dashed',
- vert_label_background_color: str = 'rgb(46, 46, 46)',
- horz_visible: bool = True,
- horz_width: int = 1,
- horz_color: Optional[str] = None,
- horz_style: LINE_STYLE = 'large_dashed',
- horz_label_background_color: str = 'rgb(55, 55, 55)'
- ):
- """
- Crosshair formatting for its vertical and horizontal axes.
- """
- self.run_script(f'''
- {self.id}.chart.applyOptions({{
- crosshair: {{
- mode: {as_enum(mode, CROSSHAIR_MODE)},
- vertLine: {{
- visible: {jbool(vert_visible)},
- width: {vert_width},
- {f'color: "{vert_color}",' if vert_color else ''}
- style: {as_enum(vert_style, LINE_STYLE)},
- labelBackgroundColor: "{vert_label_background_color}"
- }},
- horzLine: {{
- visible: {jbool(horz_visible)},
- width: {horz_width},
- {f'color: "{horz_color}",' if horz_color else ''}
- style: {as_enum(horz_style, LINE_STYLE)},
- labelBackgroundColor: "{horz_label_background_color}"
- }}
- }}
- }})''')
-
- def watermark(self, text: str, font_size: int = 44, color: str = 'rgba(180, 180, 200, 0.5)'):
- """
- Adds a watermark to the chart.
- """
- self.run_script(f'''
- {self.id}.chart.applyOptions({{
- watermark: {{
- visible: true,
- horzAlign: 'center',
- vertAlign: 'center',
- ...{js_json(locals())}
- }}
- }})''')
-
- def legend(self, visible: bool = False, ohlc: bool = True, percent: bool = True, lines: bool = True,
- color: str = 'rgb(191, 195, 203)', font_size: int = 11, font_family: str = 'Monaco',
- text: str = '', color_based_on_candle: bool = False):
- """
- Configures the legend of the chart.
- """
- l_id = f'{self.id}.legend'
- if not visible:
- self.run_script(f'''
- {l_id}.div.style.display = "none"
- {l_id}.ohlcEnabled = false
- {l_id}.percentEnabled = false
- {l_id}.linesEnabled = false
- ''')
- return
- self.run_script(f'''
- {l_id}.div.style.display = 'flex'
- {l_id}.ohlcEnabled = {jbool(ohlc)}
- {l_id}.percentEnabled = {jbool(percent)}
- {l_id}.linesEnabled = {jbool(lines)}
- {l_id}.colorBasedOnCandle = {jbool(color_based_on_candle)}
- {l_id}.div.style.color = '{color}'
- {l_id}.color = '{color}'
- {l_id}.div.style.fontSize = '{font_size}px'
- {l_id}.div.style.fontFamily = '{font_family}'
- {l_id}.text.innerText = '{text}'
- ''')
-
- def spinner(self, visible):
- self.run_script(f"{self.id}.spinner.style.display = '{'block' if visible else 'none'}'")
-
- def hotkey(self, modifier_key: Literal['ctrl', 'alt', 'shift', 'meta', None],
- keys: Union[str, tuple, int], func: Callable):
- if not isinstance(keys, tuple):
- keys = (keys,)
- for key in keys:
- key = str(key)
- if key.isalnum() and len(key) == 1:
- key_code = f'Digit{key}' if key.isdigit() else f'Key{key.upper()}'
- key_condition = f'event.code === "{key_code}"'
- else:
- key_condition = f'event.key === "{key}"'
- if modifier_key is not None:
- key_condition += f'&& event.{modifier_key}Key'
-
- self.run_script(f'''
- {self.id}.commandFunctions.unshift((event) => {{
- if ({key_condition}) {{
- event.preventDefault()
- window.callbackFunction(`{modifier_key, keys}_~_{key}`)
- return true
- }}
- else return false
- }})''')
- self.win.handlers[f'{modifier_key, keys}'] = func
-
- def create_table(
- self,
- width: NUM,
- height: NUM,
- headings: tuple,
- widths: Optional[tuple] = None,
- alignments: Optional[tuple] = None,
- position: FLOAT = 'left',
- draggable: bool = False,
- background_color: str = '#121417',
- border_color: str = 'rgb(70, 70, 70)',
- border_width: int = 1,
- heading_text_colors: Optional[tuple] = None,
- heading_background_colors: Optional[tuple] = None,
- return_clicked_cells: bool = False,
- func: Optional[Callable] = None
- ) -> Table:
- args = locals()
- del args['self']
- return self.win.create_table(*args.values())
-
- def screenshot(self) -> bytes:
- """
- Takes a screenshot. This method can only be used after the chart window is visible.
- :return: a bytes object containing a screenshot of the chart.
- """
- serial_data = self.win.run_script_and_get(f'{self.id}.chart.takeScreenshot().toDataURL()')
- return b64decode(serial_data.split(',')[1])
-
- def create_subchart(self, position: FLOAT = 'left', width: float = 0.5, height: float = 0.5,
- sync: Optional[Union[str, bool]] = None, scale_candles_only: bool = False,
- sync_crosshairs_only: bool = False,
- toolbox: bool = False) -> 'AbstractChart':
- if sync is True:
- sync = self.id
- args = locals()
- del args['self']
- return self.win.create_subchart(*args.values())
diff --git a/lightweight_charts/js/bundle.js b/lightweight_charts/js/bundle.js
deleted file mode 100644
index bd59e73d..00000000
--- a/lightweight_charts/js/bundle.js
+++ /dev/null
@@ -1 +0,0 @@
-var Lib=function(t,e){"use strict";const i={backgroundColor:"#0c0d0f",hoverBackgroundColor:"#3c434c",clickBackgroundColor:"#50565E",activeBackgroundColor:"rgba(0, 122, 255, 0.7)",mutedBackgroundColor:"rgba(0, 122, 255, 0.3)",borderColor:"#3C434C",color:"#d8d9db",activeColor:"#ececed"};function s(){window.pane={...i},window.containerDiv=document.getElementById("container")||document.createElement("div"),window.setCursor=t=>{t&&(window.cursor=t),document.body.style.cursor=window.cursor},window.cursor="default",window.textBoxFocused=!1}class o{handler;div;seriesContainer;ohlcEnabled=!1;percentEnabled=!1;linesEnabled=!1;colorBasedOnCandle=!1;text;candle;_lines=[];constructor(t){this.legendHandler=this.legendHandler.bind(this),this.handler=t,this.ohlcEnabled=!1,this.percentEnabled=!1,this.linesEnabled=!1,this.colorBasedOnCandle=!1,this.div=document.createElement("div"),this.div.classList.add("legend"),this.div.style.maxWidth=100*t.scale.width-8+"vw",this.div.style.display="none";const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="row",this.seriesContainer=document.createElement("div"),this.seriesContainer.classList.add("series-container"),this.text=document.createElement("span"),this.text.style.lineHeight="1.8",this.candle=document.createElement("div"),e.appendChild(this.seriesContainer),this.div.appendChild(this.text),this.div.appendChild(this.candle),this.div.appendChild(e),t.div.appendChild(this.div),t.chart.subscribeCrosshairMove(this.legendHandler)}toJSON(){const{_lines:t,handler:e,...i}=this;return i}makeSeriesRow(t,e){const i="#FFF";let s=`\n \n \`\n `,o=`\n \n `,n=document.createElement("div");n.style.display="flex",n.style.alignItems="center";let r=document.createElement("div"),a=document.createElement("div");a.classList.add("legend-toggle-switch");let l=document.createElementNS("http://www.w3.org/2000/svg","svg");l.setAttribute("width","22"),l.setAttribute("height","16");let h=document.createElementNS("http://www.w3.org/2000/svg","g");h.innerHTML=s;let d=!0;a.addEventListener("click",(()=>{d?(d=!1,h.innerHTML=o,e.applyOptions({visible:!1})):(d=!0,e.applyOptions({visible:!0}),h.innerHTML=s)})),l.appendChild(h),a.appendChild(l),n.appendChild(r),n.appendChild(a),this.seriesContainer.appendChild(n);const c=e.options().color;this._lines.push({name:t,div:r,row:n,toggle:a,series:e,solid:c.startsWith("rgba")?c.replace(/[^,]+(?=\))/,"1"):c})}legendItemFormat(t,e){return t.toFixed(e).toString().padStart(8," ")}shorthandFormat(t){const e=Math.abs(t);return e>=1e6?(t/1e6).toFixed(1)+"M":e>=1e3?(t/1e3).toFixed(1)+"K":t.toString().padStart(8," ")}legendHandler(t,e=!1){if(!this.ohlcEnabled&&!this.linesEnabled&&!this.percentEnabled)return;const i=this.handler.series.options();if(!t.time)return this.candle.style.color="transparent",void(this.candle.innerHTML=this.candle.innerHTML.replace(i.upColor,"").replace(i.downColor,""));let s,o=null;if(e){const e=this.handler.chart.timeScale();let i=e.timeToCoordinate(t.time);i&&(o=e.coordinateToLogical(i.valueOf())),o&&(s=this.handler.series.dataByIndex(o.valueOf()))}else s=t.seriesData.get(this.handler.series);this.candle.style.color="";let n='';if(s){if(this.ohlcEnabled&&(n+=`O ${this.legendItemFormat(s.open,this.handler.precision)} `,n+=`| H ${this.legendItemFormat(s.high,this.handler.precision)} `,n+=`| L ${this.legendItemFormat(s.low,this.handler.precision)} `,n+=`| C ${this.legendItemFormat(s.close,this.handler.precision)} `),this.percentEnabled){let t=(s.close-s.open)/s.open*100,e=t>0?i.upColor:i.downColor,o=`${t>=0?"+":""}${t.toFixed(2)} %`;this.colorBasedOnCandle?n+=`| ${o}`:n+="| "+o}if(this.handler.volumeSeries){let e;e=o?this.handler.volumeSeries.dataByIndex(o):t.seriesData.get(this.handler.volumeSeries),e&&(n+=this.ohlcEnabled?` V ${this.shorthandFormat(e.value)}`:"")}}this.candle.innerHTML=n+"",this._lines.forEach((i=>{if(!this.linesEnabled)return void(i.row.style.display="none");let s,n;if(i.row.style.display="flex",s=e&&o?i.series.dataByIndex(o):t.seriesData.get(i.series),s?.value){if("Histogram"==i.series.seriesType())n=this.shorthandFormat(s.value);else{const t=i.series.options().priceFormat;n=this.legendItemFormat(s.value,t.precision)}i.div.innerHTML=`▨ ${i.name} : ${n}`}}))}}function n(t){if(void 0===t)throw new Error("Value is undefined");return t}class r{_chart=void 0;_series=void 0;requestUpdate(){this._requestUpdate&&this._requestUpdate()}_requestUpdate;attached({chart:t,series:e,requestUpdate:i}){this._chart=t,this._series=e,this._series.subscribeDataChanged(this._fireDataUpdated),this._requestUpdate=i,this.requestUpdate()}detached(){this._chart=void 0,this._series=void 0,this._requestUpdate=void 0}get chart(){return n(this._chart)}get series(){return n(this._series)}_fireDataUpdated(t){this.dataUpdated&&this.dataUpdated(t)}}const a={lineColor:"#1E80F0",lineStyle:e.LineStyle.Solid,width:4};var l;!function(t){t[t.NONE=0]="NONE",t[t.HOVERING=1]="HOVERING",t[t.DRAGGING=2]="DRAGGING",t[t.DRAGGINGP1=3]="DRAGGINGP1",t[t.DRAGGINGP2=4]="DRAGGINGP2",t[t.DRAGGINGP3=5]="DRAGGINGP3",t[t.DRAGGINGP4=6]="DRAGGINGP4"}(l||(l={}));class h extends r{_paneViews=[];_options;_points=[];_state=l.NONE;_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];constructor(t){super(),this._options={...a,...t}}updateAllViews(){this._paneViews.forEach((t=>t.update()))}paneViews(){return this._paneViews}applyOptions(t){this._options={...this._options,...t},this.requestUpdate()}updatePoints(...t){for(let e=0;ei.name===t&&i.listener===e));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(t){if(this._latestHoverPoint=t.point,h._mouseIsDown)this._handleDragInteraction(t);else if(this._mouseIsOverDrawing(t)){if(this._state!=l.NONE)return;this._moveToState(l.HOVERING),h.hoveredObject=h.lastHoveredObject=this}else{if(this._state==l.NONE)return;this._moveToState(l.NONE),h.hoveredObject===this&&(h.hoveredObject=null)}}static _eventToPoint(t,e){if(!e||!t.point||!t.logical)return null;const i=e.coordinateToPrice(t.point.y);return null==i?null:{time:t.time||null,logical:t.logical,price:i.valueOf()}}static _getDiff(t,e){return{logical:t.logical-e.logical,price:t.price-e.price}}_addDiffToPoint(t,e,i){t&&(t.logical=t.logical+e,t.price=t.price+i,t.time=this.series.dataByIndex(t.logical)?.time||null)}_handleMouseDownInteraction=()=>{h._mouseIsDown=!0,this._onMouseDown()};_handleMouseUpInteraction=()=>{h._mouseIsDown=!1,this._moveToState(l.HOVERING)};_handleDragInteraction(t){if(this._state!=l.DRAGGING&&this._state!=l.DRAGGINGP1&&this._state!=l.DRAGGINGP2&&this._state!=l.DRAGGINGP3&&this._state!=l.DRAGGINGP4)return;const e=h._eventToPoint(t,this.series);if(!e)return;this._startDragPoint=this._startDragPoint||e;const i=h._getDiff(e,this._startDragPoint);this._onDrag(i),this.requestUpdate(),this._startDragPoint=e}}class d{_options;constructor(t){this._options=t}}class c extends d{_p1;_p2;_hovered;constructor(t,e,i,s){super(i),this._p1=t,this._p2=e,this._hovered=s}_getScaledCoordinates(t){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y?null:{x1:Math.round(this._p1.x*t.horizontalPixelRatio),y1:Math.round(this._p1.y*t.verticalPixelRatio),x2:Math.round(this._p2.x*t.horizontalPixelRatio),y2:Math.round(this._p2.y*t.verticalPixelRatio)}}_drawEndCircle(t,e,i){t.context.fillStyle="#000",t.context.beginPath(),t.context.arc(e,i,9,0,2*Math.PI),t.context.stroke(),t.context.fill()}}function p(t,i){const s={[e.LineStyle.Solid]:[],[e.LineStyle.Dotted]:[t.lineWidth,t.lineWidth],[e.LineStyle.Dashed]:[2*t.lineWidth,2*t.lineWidth],[e.LineStyle.LargeDashed]:[6*t.lineWidth,6*t.lineWidth],[e.LineStyle.SparseDotted]:[t.lineWidth,4*t.lineWidth]}[i];t.setLineDash(s)}class u extends d{_point={x:null,y:null};constructor(t,e){super(e),this._point=t}draw(t){t.useBitmapCoordinateSpace((t=>{if(null==this._point.y)return;const e=t.context,i=Math.round(this._point.y*t.verticalPixelRatio),s=this._point.x?this._point.x*t.horizontalPixelRatio:0;e.lineWidth=this._options.width,e.strokeStyle=this._options.lineColor,p(e,this._options.lineStyle),e.beginPath(),e.moveTo(s,i),e.lineTo(t.bitmapSize.width,i),e.stroke()}))}}class _{_source;constructor(t){this._source=t}}class m extends _{_p1={x:null,y:null};_p2={x:null,y:null};_source;constructor(t){super(t),this._source=t}update(){if(!this._source.p1||!this._source.p2)return;const t=this._source.series,e=t.priceToCoordinate(this._source.p1.price),i=t.priceToCoordinate(this._source.p2.price),s=this._getX(this._source.p1),o=this._getX(this._source.p2);this._p1={x:s,y:e},this._p2={x:o,y:i}}_getX(t){return this._source.chart.timeScale().logicalToCoordinate(t.logical)}}class v extends _{_source;_point={x:null,y:null};constructor(t){super(t),this._source=t}update(){const t=this._source._point,e=this._source.chart.timeScale(),i=this._source.series;"RayLine"==this._source._type&&(this._point.x=t.time?e.timeToCoordinate(t.time):e.logicalToCoordinate(t.logical)),this._point.y=i.priceToCoordinate(t.price)}renderer(){return new u(this._point,this._source._options)}}class g{_source;_y=null;_price=null;constructor(t){this._source=t}update(){if(!this._source.series||!this._source._point)return;this._y=this._source.series.priceToCoordinate(this._source._point.price);const t=this._source.series.options().priceFormat.precision;this._price=this._source._point.price.toFixed(t).toString()}visible(){return!0}tickVisible(){return!0}coordinate(){return this._y??0}text(){return this._source._options.text||this._price||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class w extends h{_type="HorizontalLine";_paneViews;_point;_callbackName;_priceAxisViews;_startDragPoint=null;constructor(t,e,i=null){super(e),this._point=t,this._point.time=null,this._paneViews=[new v(this)],this._priceAxisViews=[new g(this)],this._callbackName=i}get points(){return[this._point]}updatePoints(...t){for(const e of t)e&&(this._point.price=e.price);this.requestUpdate()}updateAllViews(){this._paneViews.forEach((t=>t.update())),this._priceAxisViews.forEach((t=>t.update()))}priceAxisViews(){return this._priceAxisViews}_moveToState(t){switch(t){case l.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case l.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case l.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=t}_onDrag(t){this._addDiffToPoint(this._point,0,t.price),this.requestUpdate()}_mouseIsOverDrawing(t,e=4){if(!t.point)return!1;const i=this.series.priceToCoordinate(this._point.price);return!!i&&Math.abs(i-t.point.y){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class y{_chart;_series;_finishDrawingCallback=null;_drawings=[];_activeDrawing=null;_isDrawing=!1;_drawingType=null;constructor(t,e,i=null){this._chart=t,this._series=e,this._finishDrawingCallback=i,this._chart.subscribeClick(this._clickHandler),this._chart.subscribeCrosshairMove(this._moveHandler)}_clickHandler=t=>this._onClick(t);_moveHandler=t=>this._onMouseMove(t);beginDrawing(t){this._drawingType=t,this._isDrawing=!0}stopDrawing(){this._isDrawing=!1,this._activeDrawing=null}get drawings(){return this._drawings}addNewDrawing(t){this._series.attachPrimitive(t),this._drawings.push(t)}delete(t){if(null==t)return;const e=this._drawings.indexOf(t);-1!=e&&(this._drawings.splice(e,1),t.detach())}clearDrawings(){for(const t of this._drawings)t.detach();this._drawings=[]}repositionOnTime(){for(const t of this.drawings){const e=[];for(const i of t.points){if(!i){e.push(i);continue}const t=i.time?this._chart.timeScale().coordinateToLogical(this._chart.timeScale().timeToCoordinate(i.time)||0):i.logical;e.push({time:i.time,logical:t,price:i.price})}t.updatePoints(...e)}}_onClick(t){if(!this._isDrawing)return;const e=h._eventToPoint(t,this._series);if(e)if(null==this._activeDrawing){if(null==this._drawingType)return;this._activeDrawing=new this._drawingType(e,e),this._series.attachPrimitive(this._activeDrawing),this._drawingType==w&&this._onClick(t)}else{if(this._drawings.push(this._activeDrawing),this.stopDrawing(),!this._finishDrawingCallback)return;this._finishDrawingCallback()}}_onMouseMove(t){if(!t)return;for(const e of this._drawings)e._handleHoverInteraction(t);if(!this._isDrawing||!this._activeDrawing)return;const e=h._eventToPoint(t,this._series);e&&this._activeDrawing.updatePoints(null,e)}}class b extends c{constructor(t,e,i,s){super(t,e,i,s)}draw(t){t.useBitmapCoordinateSpace((t=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y)return;const e=t.context,i=this._getScaledCoordinates(t);i&&(e.lineWidth=this._options.width,e.strokeStyle=this._options.lineColor,p(e,this._options.lineStyle),e.beginPath(),e.moveTo(i.x1,i.y1),e.lineTo(i.x2,i.y2),e.stroke(),this._hovered&&(this._drawEndCircle(t,i.x1,i.y1),this._drawEndCircle(t,i.x2,i.y2)))}))}}class x extends m{constructor(t){super(t)}renderer(){return new b(this._p1,this._p2,this._source._options,this._source.hovered)}}class C extends h{_paneViews=[];_hovered=!1;constructor(t,e,i){super(),this.points.push(t),this.points.push(e),this._options={...a,...i}}setFirstPoint(t){this.updatePoints(t)}setSecondPoint(t){this.updatePoints(null,t)}get p1(){return this.points[0]}get p2(){return this.points[1]}get hovered(){return this._hovered}}class f extends C{_type="TrendLine";constructor(t,e,i){super(t,e,i),this._paneViews=[new x(this)]}_moveToState(t){switch(t){case l.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case l.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case l.DRAGGINGP1:case l.DRAGGINGP2:case l.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=t}_onDrag(t){this._state!=l.DRAGGING&&this._state!=l.DRAGGINGP1||this._addDiffToPoint(this.p1,t.logical,t.price),this._state!=l.DRAGGING&&this._state!=l.DRAGGINGP2||this._addDiffToPoint(this.p2,t.logical,t.price)}_onMouseDown(){this._startDragPoint=null;const t=this._latestHoverPoint;if(!t)return;const e=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(e.x&&i.x&&e.y&&i.y))return this._moveToState(l.DRAGGING);Math.abs(t.x-e.x)<10&&Math.abs(t.y-e.y)<10?this._moveToState(l.DRAGGINGP1):Math.abs(t.x-i.x)<10&&Math.abs(t.y-i.y)<10?this._moveToState(l.DRAGGINGP2):this._moveToState(l.DRAGGING)}_mouseIsOverDrawing(t,e=4){if(!t.point)return!1;const i=this._paneViews[0]._p1.x,s=this._paneViews[0]._p1.y,o=this._paneViews[0]._p2.x,n=this._paneViews[0]._p2.y;if(!(i&&o&&s&&n))return!1;const r=t.point.x,a=t.point.y;if(r<=Math.min(i,o)-e||r>=Math.max(i,o)+e)return!1;return Math.abs((n-s)*r-(o-i)*a+o*s-n*i)/Math.sqrt((n-s)**2+(o-i)**2)<=e}}class D extends c{constructor(t,e,i,s){super(t,e,i,s)}draw(t){t.useBitmapCoordinateSpace((t=>{const e=t.context,i=this._getScaledCoordinates(t);if(!i)return;e.lineWidth=this._options.width,e.strokeStyle=this._options.lineColor,p(e,this._options.lineStyle),e.fillStyle=this._options.fillColor;const s=Math.min(i.x1,i.x2),o=Math.min(i.y1,i.y2),n=Math.abs(i.x1-i.x2),r=Math.abs(i.y1-i.y2);e.strokeRect(s,o,n,r),e.fillRect(s,o,n,r),this._hovered&&(this._drawEndCircle(t,s,o),this._drawEndCircle(t,s+n,o),this._drawEndCircle(t,s+n,o+r),this._drawEndCircle(t,s,o+r))}))}}class E extends m{constructor(t){super(t)}renderer(){return new D(this._p1,this._p2,this._source._options,this._source.hovered)}}const k={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.2)",...a};class L extends C{_type="Box";constructor(t,e,i){super(t,e,i),this._options={...k,...i},this._paneViews=[new E(this)]}_moveToState(t){switch(t){case l.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case l.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._unsubscribe("mouseup",this._handleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case l.DRAGGINGP1:case l.DRAGGINGP2:case l.DRAGGINGP3:case l.DRAGGINGP4:case l.DRAGGING:document.body.style.cursor="grabbing",document.body.addEventListener("mouseup",this._handleMouseUpInteraction),this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=t}_onDrag(t){this._state!=l.DRAGGING&&this._state!=l.DRAGGINGP1||this._addDiffToPoint(this.p1,t.logical,t.price),this._state!=l.DRAGGING&&this._state!=l.DRAGGINGP2||this._addDiffToPoint(this.p2,t.logical,t.price),this._state!=l.DRAGGING&&(this._state==l.DRAGGINGP3&&(this._addDiffToPoint(this.p1,t.logical,0),this._addDiffToPoint(this.p2,0,t.price)),this._state==l.DRAGGINGP4&&(this._addDiffToPoint(this.p1,0,t.price),this._addDiffToPoint(this.p2,t.logical,0)))}_onMouseDown(){this._startDragPoint=null;const t=this._latestHoverPoint,e=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(e.x&&i.x&&e.y&&i.y))return this._moveToState(l.DRAGGING);const s=10;Math.abs(t.x-e.x)l-p&&rh-p&&ai.appendChild(this.makeColorBox(t))));let s=document.createElement("div");s.style.backgroundColor=window.pane.borderColor,s.style.height="1px",s.style.width="130px";let o=document.createElement("div");o.style.margin="10px";let n=document.createElement("div");n.style.color="lightgray",n.style.fontSize="12px",n.innerText="Opacity",this._opacityLabel=document.createElement("div"),this._opacityLabel.style.color="lightgray",this._opacityLabel.style.fontSize="12px",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%",this._opacitySlider.oninput=()=>{this._opacityLabel.innerText=this._opacitySlider.value+"%",this.opacity=parseInt(this._opacitySlider.value)/100,this.updateColor()},o.appendChild(n),o.appendChild(this._opacitySlider),o.appendChild(this._opacityLabel),this._div.appendChild(i),this._div.appendChild(s),this._div.appendChild(o),window.containerDiv.appendChild(this._div)}_updateOpacitySlider(){this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%"}makeColorBox(t){const e=document.createElement("div");e.style.width="18px",e.style.height="18px",e.style.borderRadius="3px",e.style.margin="3px",e.style.boxSizing="border-box",e.style.backgroundColor=t,e.addEventListener("mouseover",(()=>e.style.border="2px solid lightgray")),e.addEventListener("mouseout",(()=>e.style.border="none"));const i=S.extractRGBA(t);return e.addEventListener("click",(()=>{this.rgba=i,this.updateColor()})),e}static extractRGBA(t){const e=document.createElement("div");e.style.color=t,document.body.appendChild(e);const i=getComputedStyle(e).color;document.body.removeChild(e);const s=i.match(/\d+/g)?.map(Number);if(!s)return[];let o=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],o]}updateColor(){if(!h.lastHoveredObject||!this.rgba)return;const t=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`;h.lastHoveredObject.applyOptions({[this.colorOption]:t}),this.saveDrawings()}openMenu(t){h.lastHoveredObject&&(this.rgba=S.extractRGBA(h.lastHoveredObject._options[this.colorOption]),this.opacity=this.rgba[3],this._updateOpacitySlider(),this._div.style.top=t.top-30+"px",this._div.style.left=t.right+"px",this._div.style.display="flex",setTimeout((()=>document.addEventListener("mousedown",(t=>{this._div.contains(t.target)||this.closeMenu()}))),10))}closeMenu(){document.body.removeEventListener("click",this.closeMenu),this._div.style.display="none"}}class G{static _styles=[{name:"Solid",var:e.LineStyle.Solid},{name:"Dotted",var:e.LineStyle.Dotted},{name:"Dashed",var:e.LineStyle.Dashed},{name:"Large Dashed",var:e.LineStyle.LargeDashed},{name:"Sparse Dotted",var:e.LineStyle.SparseDotted}];_div;_saveDrawings;constructor(t){this._saveDrawings=t,this._div=document.createElement("div"),this._div.classList.add("context-menu"),G._styles.forEach((t=>{this._div.appendChild(this._makeTextBox(t.name,t.var))})),window.containerDiv.appendChild(this._div)}_makeTextBox(t,e){const i=document.createElement("span");return i.classList.add("context-menu-item"),i.innerText=t,i.addEventListener("click",(()=>{h.lastHoveredObject?.applyOptions({lineStyle:e}),this._saveDrawings()})),i}openMenu(t){this._div.style.top=t.top-30+"px",this._div.style.left=t.right+"px",this._div.style.display="block",setTimeout((()=>document.addEventListener("mousedown",(t=>{this._div.contains(t.target)||this.closeMenu()}))),10)}closeMenu(){document.removeEventListener("click",this.closeMenu),this._div.style.display="none"}}function T(t){const e=[];for(const i of t)0==e.length?e.push(i.toUpperCase()):i==i.toUpperCase()?e.push(" "+i):e.push(i);return e.join("")}class I{saveDrawings;drawingTool;div;hoverItem;items=[];constructor(t,e){this.saveDrawings=t,this.drawingTool=e,this._onRightClick=this._onRightClick.bind(this),this.div=document.createElement("div"),this.div.classList.add("context-menu"),document.body.appendChild(this.div),this.hoverItem=null,document.body.addEventListener("contextmenu",this._onRightClick)}_handleClick=t=>this._onClick(t);_onClick(t){t.target&&(this.div.contains(t.target)||(this.div.style.display="none",document.body.removeEventListener("click",this._handleClick)))}_onRightClick(t){if(!h.hoveredObject)return;for(const t of this.items)this.div.removeChild(t);this.items=[];for(const t of Object.keys(h.hoveredObject._options)){let e;if(t.toLowerCase().includes("color"))e=new S(this.saveDrawings,t);else{if("lineStyle"!==t)continue;e=new G(this.saveDrawings)}let i=t=>e.openMenu(t);this.menuItem(T(t),i,(()=>{document.removeEventListener("click",e.closeMenu),e._div.style.display="none"}))}this.separator(),this.menuItem("Delete Drawing",(()=>this.drawingTool.delete(h.lastHoveredObject))),t.preventDefault(),this.div.style.left=t.clientX+"px",this.div.style.top=t.clientY+"px",this.div.style.display="block",document.body.addEventListener("click",this._handleClick)}menuItem(t,e,i=null){const s=document.createElement("span");s.classList.add("context-menu-item"),this.div.appendChild(s);const o=document.createElement("span");if(o.innerText=t,o.style.pointerEvents="none",s.appendChild(o),i){let t=document.createElement("span");t.innerText="►",t.style.fontSize="8px",t.style.pointerEvents="none",s.appendChild(t)}if(s.addEventListener("mouseover",(()=>{this.hoverItem&&this.hoverItem.closeAction&&this.hoverItem.closeAction(),this.hoverItem={elem:o,action:e,closeAction:i}})),i){let t;s.addEventListener("mouseover",(()=>t=setTimeout((()=>e(s.getBoundingClientRect())),100))),s.addEventListener("mouseout",(()=>clearTimeout(t)))}else s.addEventListener("click",(t=>{e(t),this.div.style.display="none"}));this.items.push(s)}separator(){const t=document.createElement("div");t.style.width="90%",t.style.height="1px",t.style.margin="3px 0px",t.style.backgroundColor=window.pane.borderColor,this.div.appendChild(t),this.items.push(t)}}class M extends w{_type="RayLine";constructor(t,e){super({...t},e),this._point.time=t.time}updatePoints(...t){for(const e of t)e&&(this._point=e);this.requestUpdate()}_onDrag(t){this._addDiffToPoint(this._point,t.logical,t.price),this.requestUpdate()}_mouseIsOverDrawing(t,e=4){if(!t.point)return!1;const i=this.series.priceToCoordinate(this._point.price),s=this._point.time?this.chart.timeScale().timeToCoordinate(this._point.time):null;return!(!i||!s)&&(Math.abs(i-t.point.y)s-e)}}class N extends d{_point={x:null,y:null};constructor(t,e){super(e),this._point=t}draw(t){t.useBitmapCoordinateSpace((t=>{if(null==this._point.x)return;const e=t.context,i=this._point.x*t.horizontalPixelRatio;e.lineWidth=this._options.width,e.strokeStyle=this._options.lineColor,p(e,this._options.lineStyle),e.beginPath(),e.moveTo(i,0),e.lineTo(i,t.bitmapSize.height),e.stroke()}))}}class R extends _{_source;_point={x:null,y:null};constructor(t){super(t),this._source=t}update(){const t=this._source._point,e=this._source.chart.timeScale(),i=this._source.series;this._point.x=t.time?e.timeToCoordinate(t.time):e.logicalToCoordinate(t.logical),this._point.y=i.priceToCoordinate(t.price)}renderer(){return new N(this._point,this._source._options)}}class A{_source;_x=null;constructor(t){this._source=t}update(){if(!this._source.chart||!this._source._point)return;const t=this._source._point,e=this._source.chart.timeScale();this._x=t.time?e.timeToCoordinate(t.time):e.logicalToCoordinate(t.logical)}visible(){return!!this._source._options.text}tickVisible(){return!0}coordinate(){return this._x??0}text(){return this._source._options.text||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class B extends h{_type="VerticalLine";_paneViews;_timeAxisViews;_point;_callbackName;_startDragPoint=null;constructor(t,e,i=null){super(e),this._point=t,this._paneViews=[new R(this)],this._callbackName=i,this._timeAxisViews=[new A(this)]}updateAllViews(){this._paneViews.forEach((t=>t.update())),this._timeAxisViews.forEach((t=>t.update()))}timeAxisViews(){return this._timeAxisViews}updatePoints(...t){for(const e of t)e&&(!e.time&&e.logical&&(e.time=this.series.dataByIndex(e.logical)?.time||null),this._point=e);this.requestUpdate()}get points(){return[this._point]}_moveToState(t){switch(t){case l.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case l.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case l.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=t}_onDrag(t){this._addDiffToPoint(this._point,t.logical,0),this.requestUpdate()}_mouseIsOverDrawing(t,e=4){if(!t.point)return!1;const i=this.chart.timeScale();let s;return s=this._point.time?i.timeToCoordinate(this._point.time):i.logicalToCoordinate(this._point.logical),!!s&&Math.abs(s-t.point.x){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class P{static TREND_SVG='';static HORZ_SVG='';static RAY_SVG='';static BOX_SVG='';static VERT_SVG=P.RAY_SVG;div;activeIcon=null;buttons=[];_commandFunctions;_handlerID;_drawingTool;constructor(t,e,i,s){this._handlerID=t,this._commandFunctions=s,this._drawingTool=new y(e,i,(()=>this.removeActiveAndSave())),this.div=this._makeToolBox(),new I(this.saveDrawings,this._drawingTool),s.push((t=>{if((t.metaKey||t.ctrlKey)&&"KeyZ"===t.code){const t=this._drawingTool.drawings.pop();return t&&this._drawingTool.delete(t),!0}return!1}))}toJSON(){const{...t}=this;return t}_makeToolBox(){let t=document.createElement("div");t.classList.add("toolbox"),this.buttons.push(this._makeToolBoxElement(f,"KeyT",P.TREND_SVG)),this.buttons.push(this._makeToolBoxElement(w,"KeyH",P.HORZ_SVG)),this.buttons.push(this._makeToolBoxElement(M,"KeyR",P.RAY_SVG)),this.buttons.push(this._makeToolBoxElement(L,"KeyB",P.BOX_SVG)),this.buttons.push(this._makeToolBoxElement(B,"KeyV",P.VERT_SVG,!0));for(const e of this.buttons)t.appendChild(e);return t}_makeToolBoxElement(t,e,i,s=!1){const o=document.createElement("div");o.classList.add("toolbox-button");const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.setAttribute("width","29"),n.setAttribute("height","29");const r=document.createElementNS("http://www.w3.org/2000/svg","g");r.innerHTML=i,r.setAttribute("fill",window.pane.color),n.appendChild(r),o.appendChild(n);const a={div:o,group:r,type:t};return o.addEventListener("click",(()=>this._onIconClick(a))),this._commandFunctions.push((t=>this._handlerID===window.handlerInFocus&&(!(!t.altKey||t.code!==e)&&(t.preventDefault(),this._onIconClick(a),!0)))),1==s&&(n.style.transform="rotate(90deg)",n.style.transformBox="fill-box",n.style.transformOrigin="center"),o}_onIconClick(t){this.activeIcon&&(this.activeIcon.div.classList.remove("active-toolbox-button"),window.setCursor("crosshair"),this._drawingTool?.stopDrawing(),this.activeIcon===t)?this.activeIcon=null:(this.activeIcon=t,this.activeIcon.div.classList.add("active-toolbox-button"),window.setCursor("crosshair"),this._drawingTool?.beginDrawing(this.activeIcon.type))}removeActiveAndSave=()=>{window.setCursor("default"),this.activeIcon&&this.activeIcon.div.classList.remove("active-toolbox-button"),this.activeIcon=null,this.saveDrawings()};addNewDrawing(t){this._drawingTool.addNewDrawing(t)}clearDrawings(){this._drawingTool.clearDrawings()}saveDrawings=()=>{const t=[];for(const e of this._drawingTool.drawings)t.push({type:e._type,points:e.points,options:e._options});const e=JSON.stringify(t);window.callbackFunction(`save_drawings${this._handlerID}_~_${e}`)};loadDrawings(t){t.forEach((t=>{switch(t.type){case"Box":this._drawingTool.addNewDrawing(new L(t.points[0],t.points[1],t.options));break;case"TrendLine":this._drawingTool.addNewDrawing(new f(t.points[0],t.points[1],t.options));break;case"HorizontalLine":this._drawingTool.addNewDrawing(new w(t.points[0],t.options));break;case"RayLine":this._drawingTool.addNewDrawing(new M(t.points[0],t.options));break;case"VerticalLine":this._drawingTool.addNewDrawing(new B(t.points[0],t.options))}}))}}class O{makeButton;callbackName;div;isOpen=!1;widget;constructor(t,e,i,s,o,n){this.makeButton=t,this.callbackName=e,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(s+" ↓",null,o,!0,n),this.updateMenuItems(i),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");let t=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";let e=t.x+t.width/2;this.div.style.left=e-this.div.clientWidth/2+"px",this.div.style.top=t.y+t.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(t){this.div.innerHTML="",t.forEach((t=>{let e=this.makeButton(t,null,!1,!1);e.elem.addEventListener("click",(()=>{this._clickHandler(e.elem.innerText)})),e.elem.style.margin="4px 4px",e.elem.style.padding="2px 2px",this.div.appendChild(e.elem)})),this.widget.elem.innerText=t[0]+" ↓"}_clickHandler(t){this.widget.elem.innerText=t+" ↓",window.callbackFunction(`${this.callbackName}_~_${t}`),this.div.style.display="none",this.isOpen=!1}}class V{_handler;_div;left;right;constructor(t){this._handler=t,this._div=document.createElement("div"),this._div.classList.add("topbar");const e=t=>{const e=document.createElement("div");return e.classList.add("topbar-container"),e.style.justifyContent=t,this._div.appendChild(e),e};this.left=e("flex-start"),this.right=e("flex-end")}makeSwitcher(t,e,i,s="left"){const o=document.createElement("div");let n;o.style.margin="4px 12px";const r={elem:o,callbackName:i,intervalElements:t.map((t=>{const i=document.createElement("button");i.classList.add("topbar-button"),i.classList.add("switcher-button"),i.style.margin="0px 2px",i.innerText=t,t==e&&(n=i,i.classList.add("active-switcher-button"));const s=V.getClientWidth(i);return i.style.minWidth=s+1+"px",i.addEventListener("click",(()=>r.onItemClicked(i))),o.appendChild(i),i})),onItemClicked:t=>{t!=n&&(n.classList.remove("active-switcher-button"),t.classList.add("active-switcher-button"),n=t,window.callbackFunction(`${r.callbackName}_~_${t.innerText}`))}};return this.appendWidget(o,s,!0),r}makeTextBoxWidget(t,e="left",i=null){if(i){const s=document.createElement("input");return s.classList.add("topbar-textbox-input"),s.value=t,s.style.width=`${s.value.length+2}ch`,s.addEventListener("focus",(()=>{window.textBoxFocused=!0})),s.addEventListener("input",(t=>{t.preventDefault(),s.style.width=`${s.value.length+2}ch`})),s.addEventListener("keydown",(t=>{"Enter"==t.key&&(t.preventDefault(),s.blur())})),s.addEventListener("blur",(()=>{window.callbackFunction(`${i}_~_${s.value}`),window.textBoxFocused=!1})),this.appendWidget(s,e,!0),s}{const i=document.createElement("div");return i.classList.add("topbar-textbox"),i.innerText=t,this.appendWidget(i,e,!0),i}}makeMenu(t,e,i,s,o){return new O(this.makeButton.bind(this),s,t,e,i,o)}makeButton(t,e,i,s=!0,o="left",n=!1){let r=document.createElement("button");r.classList.add("topbar-button"),r.innerText=t,document.body.appendChild(r),r.style.minWidth=r.clientWidth+1+"px",document.body.removeChild(r);let a={elem:r,callbackName:e};if(e){let t;if(n){let e=!1;t=()=>{e=!e,window.callbackFunction(`${a.callbackName}_~_${e}`),r.style.backgroundColor=e?"var(--active-bg-color)":"",r.style.color=e?"var(--active-color)":""}}else t=()=>window.callbackFunction(`${a.callbackName}_~_${r.innerText}`);r.addEventListener("click",t)}return s&&this.appendWidget(r,o,i),a}makeSeparator(t="left"){const e=document.createElement("div");e.classList.add("topbar-seperator");("left"==t?this.left:this.right).appendChild(e)}appendWidget(t,e,i){const s="left"==e?this.left:this.right;i?("left"==e&&s.appendChild(t),this.makeSeparator(e),"right"==e&&s.appendChild(t)):s.appendChild(t),this._handler.reSize()}static getClientWidth(t){document.body.appendChild(t);const e=t.clientWidth;return document.body.removeChild(t),e}}s();return t.Box=L,t.Handler=class{id;commandFunctions=[];wrapper;div;chart;scale;precision=2;series;volumeSeries;legend;_topBar;toolBox;spinner;_seriesList=[];constructor(t,e,i,s,n){this.reSize=this.reSize.bind(this),this.id=t,this.scale={width:e,height:i},this.wrapper=document.createElement("div"),this.wrapper.classList.add("handler"),this.wrapper.style.float=s,this.div=document.createElement("div"),this.div.style.position="relative",this.wrapper.appendChild(this.div),window.containerDiv.append(this.wrapper),this.chart=this._createChart(),this.series=this.createCandlestickSeries(),this.volumeSeries=this.createVolumeSeries(),this.legend=new o(this),document.addEventListener("keydown",(t=>{for(let e=0;ewindow.handlerInFocus=this.id)),this.reSize(),n&&window.addEventListener("resize",(()=>this.reSize()))}reSize(){let t=0!==this.scale.height&&this._topBar?._div.offsetHeight||0;this.chart.resize(window.innerWidth*this.scale.width,window.innerHeight*this.scale.height-t),this.wrapper.style.width=100*this.scale.width+"%",this.wrapper.style.height=100*this.scale.height+"%",0===this.scale.height||0===this.scale.width?this.toolBox&&(this.toolBox.div.style.display="none"):this.toolBox&&(this.toolBox.div.style.display="flex")}_createChart(){return e.createChart(this.div,{width:window.innerWidth*this.scale.width,height:window.innerHeight*this.scale.height,layout:{textColor:window.pane.color,background:{color:"#000000",type:e.ColorType.Solid},fontSize:12},rightPriceScale:{scaleMargins:{top:.3,bottom:.25}},timeScale:{timeVisible:!0,secondsVisible:!1},crosshair:{mode:e.CrosshairMode.Normal,vertLine:{labelBackgroundColor:"rgb(46, 46, 46)"},horzLine:{labelBackgroundColor:"rgb(55, 55, 55)"}},grid:{vertLines:{color:"rgba(29, 30, 38, 5)"},horzLines:{color:"rgba(29, 30, 58, 5)"}},handleScroll:{vertTouchDrag:!0}})}createCandlestickSeries(){const t="rgba(39, 157, 130, 100)",e="rgba(200, 97, 100, 100)",i=this.chart.addCandlestickSeries({upColor:t,borderUpColor:t,wickUpColor:t,downColor:e,borderDownColor:e,wickDownColor:e});return i.priceScale().applyOptions({scaleMargins:{top:.2,bottom:.2}}),i}createVolumeSeries(){const t=this.chart.addHistogramSeries({color:"#26a69a",priceFormat:{type:"volume"},priceScaleId:"volume_scale"});return t.priceScale().applyOptions({scaleMargins:{top:.8,bottom:0}}),t}createLineSeries(t,e){const i=this.chart.addLineSeries({...e});return this._seriesList.push(i),this.legend.makeSeriesRow(t,i),{name:t,series:i}}createHistogramSeries(t,e){const i=this.chart.addHistogramSeries({...e});return this._seriesList.push(i),this.legend.makeSeriesRow(t,i),{name:t,series:i}}createToolBox(){this.toolBox=new P(this.id,this.chart,this.series,this.commandFunctions),this.div.appendChild(this.toolBox.div)}createTopBar(){return this._topBar=new V(this),this.wrapper.prepend(this._topBar._div),this._topBar}toJSON(){const{chart:t,...e}=this;return e}static syncCharts(t,e,i=!1){function s(t,e){e?(t.chart.setCrosshairPosition(e.value||e.close,e.time,t.series),t.legend.legendHandler(e,!0)):t.chart.clearCrosshairPosition()}function o(t,e){return e.time&&e.seriesData.get(t)||null}const n=t.chart.timeScale(),r=e.chart.timeScale(),a=t=>{t&&n.setVisibleLogicalRange(t)},l=t=>{t&&r.setVisibleLogicalRange(t)},h=i=>{s(e,o(t.series,i))},d=i=>{s(t,o(e.series,i))};let c=e;function p(t,e,s,o,n,r){t.wrapper.addEventListener("mouseover",(()=>{c!==t&&(c=t,e.chart.unsubscribeCrosshairMove(s),t.chart.subscribeCrosshairMove(o),i||(e.chart.timeScale().unsubscribeVisibleLogicalRangeChange(n),t.chart.timeScale().subscribeVisibleLogicalRangeChange(r)))}))}p(e,t,h,d,l,a),p(t,e,d,h,a,l),e.chart.subscribeCrosshairMove(d);const u=r.getVisibleLogicalRange();u&&n.setVisibleLogicalRange(u),i||e.chart.timeScale().subscribeVisibleLogicalRangeChange(a)}static makeSearchBox(t){const e=document.createElement("div");e.classList.add("searchbox"),e.style.display="none";const i=document.createElement("div");i.innerHTML='';const s=document.createElement("input");return s.type="text",e.appendChild(i),e.appendChild(s),t.div.appendChild(e),t.commandFunctions.push((i=>window.handlerInFocus===t.id&&!window.textBoxFocused&&("none"===e.style.display?!!/^[a-zA-Z0-9]$/.test(i.key)&&(e.style.display="flex",s.focus(),!0):("Enter"===i.key||"Escape"===i.key)&&("Enter"===i.key&&window.callbackFunction(`search${t.id}_~_${s.value}`),e.style.display="none",s.value="",!0)))),s.addEventListener("input",(()=>s.value=s.value.toUpperCase())),{window:e,box:s}}static makeSpinner(t){t.spinner=document.createElement("div"),t.spinner.classList.add("spinner"),t.wrapper.appendChild(t.spinner);let e=0;!function i(){t.spinner&&(e+=10,t.spinner.style.transform=`translate(-50%, -50%) rotate(${e}deg)`,requestAnimationFrame(i))}()}static _styleMap={"--bg-color":"backgroundColor","--hover-bg-color":"hoverBackgroundColor","--click-bg-color":"clickBackgroundColor","--active-bg-color":"activeBackgroundColor","--muted-bg-color":"mutedBackgroundColor","--border-color":"borderColor","--color":"color","--active-color":"activeColor"};static setRootStyles(t){const e=document.documentElement.style;for(const[i,s]of Object.entries(this._styleMap))e.setProperty(i,t[s])}},t.HorizontalLine=w,t.Legend=o,t.RayLine=M,t.Table=class{_div;callbackName;borderColor;borderWidth;table;rows={};headings;widths;alignments;footer;header;constructor(t,e,i,s,o,n,r=!1,a,l,h,d,c){this._div=document.createElement("div"),this.callbackName=null,this.borderColor=l,this.borderWidth=h,r?(this._div.style.position="absolute",this._div.style.cursor="move"):(this._div.style.position="relative",this._div.style.float=n),this._div.style.zIndex="2000",this.reSize(t,e),this._div.style.display="flex",this._div.style.flexDirection="column",this._div.style.borderRadius="5px",this._div.style.color="white",this._div.style.fontSize="12px",this._div.style.fontVariantNumeric="tabular-nums",this.table=document.createElement("table"),this.table.style.width="100%",this.table.style.borderCollapse="collapse",this._div.style.overflow="hidden",this.headings=i,this.widths=s.map((t=>100*t+"%")),this.alignments=o;let p=this.table.createTHead().insertRow();for(let t=0;t0?c[t]:a,e.style.color=d[t],p.appendChild(e)}let u,_,m=document.createElement("div");if(m.style.overflowY="auto",m.style.overflowX="hidden",m.style.backgroundColor=a,m.appendChild(this.table),this._div.appendChild(m),window.containerDiv.appendChild(this._div),!r)return;let v=t=>{this._div.style.left=t.clientX-u+"px",this._div.style.top=t.clientY-_+"px"},g=()=>{document.removeEventListener("mousemove",v),document.removeEventListener("mouseup",g)};this._div.addEventListener("mousedown",(t=>{u=t.clientX-this._div.offsetLeft,_=t.clientY-this._div.offsetTop,document.addEventListener("mousemove",v),document.addEventListener("mouseup",g)}))}divToButton(t,e){t.addEventListener("mouseover",(()=>t.style.backgroundColor="rgba(60, 60, 60, 0.6)")),t.addEventListener("mouseout",(()=>t.style.backgroundColor="transparent")),t.addEventListener("mousedown",(()=>t.style.backgroundColor="rgba(60, 60, 60)")),t.addEventListener("click",(()=>window.callbackFunction(e))),t.addEventListener("mouseup",(()=>t.style.backgroundColor="rgba(60, 60, 60, 0.6)"))}newRow(t,e=!1){let i=this.table.insertRow();i.style.cursor="default";for(let s=0;s{t&&(window.cursor=t),document.body.style.cursor=window.cursor},t}({},LightweightCharts);
diff --git a/lightweight_charts/js/index.html b/lightweight_charts/js/index.html
deleted file mode 100644
index 8f2dd943..00000000
--- a/lightweight_charts/js/index.html
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
- lightweight-charts-python
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/lightweight_charts/js/lightweight-charts.js b/lightweight_charts/js/lightweight-charts.js
deleted file mode 100644
index 69033f37..00000000
--- a/lightweight_charts/js/lightweight-charts.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/*!
- * @license
- * TradingView Lightweight Charts™ v4.1.3
- * Copyright (c) 2024 TradingView, Inc.
- * Licensed under Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0
- */
-!function(){"use strict";const t={upColor:"#26a69a",downColor:"#ef5350",wickVisible:!0,borderVisible:!0,borderColor:"#378658",borderUpColor:"#26a69a",borderDownColor:"#ef5350",wickColor:"#737375",wickUpColor:"#26a69a",wickDownColor:"#ef5350"},i={upColor:"#26a69a",downColor:"#ef5350",openVisible:!0,thinBars:!0},n={color:"#2196f3",lineStyle:0,lineWidth:3,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},s={topColor:"rgba( 46, 220, 135, 0.4)",bottomColor:"rgba( 40, 221, 100, 0)",invertFilledArea:!1,lineColor:"#33D778",lineStyle:0,lineWidth:3,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},e={baseValue:{type:"price",price:0},topFillColor1:"rgba(38, 166, 154, 0.28)",topFillColor2:"rgba(38, 166, 154, 0.05)",topLineColor:"rgba(38, 166, 154, 1)",bottomFillColor1:"rgba(239, 83, 80, 0.05)",bottomFillColor2:"rgba(239, 83, 80, 0.28)",bottomLineColor:"rgba(239, 83, 80, 1)",lineWidth:3,lineStyle:0,lineType:0,lineVisible:!0,crosshairMarkerVisible:!0,crosshairMarkerRadius:4,crosshairMarkerBorderColor:"",crosshairMarkerBorderWidth:2,crosshairMarkerBackgroundColor:"",lastPriceAnimation:0,pointMarkersVisible:!1},r={color:"#26a69a",base:0},h={color:"#2196f3"},l={title:"",visible:!0,lastValueVisible:!0,priceLineVisible:!0,priceLineSource:0,priceLineWidth:1,priceLineColor:"",priceLineStyle:2,baseLineVisible:!0,baseLineWidth:1,baseLineColor:"#B2B5BE",baseLineStyle:0,priceFormat:{type:"price",precision:2,minMove:.01}};var a,o;function _(t,i){const n={0:[],1:[t.lineWidth,t.lineWidth],2:[2*t.lineWidth,2*t.lineWidth],3:[6*t.lineWidth,6*t.lineWidth],4:[t.lineWidth,4*t.lineWidth]}[i];t.setLineDash(n)}function u(t,i,n,s){t.beginPath();const e=t.lineWidth%2?.5:0;t.moveTo(n,i+e),t.lineTo(s,i+e),t.stroke()}function c(t,i){if(!t)throw new Error("Assertion failed"+(i?": "+i:""))}function d(t){if(void 0===t)throw new Error("Value is undefined");return t}function f(t){if(null===t)throw new Error("Value is null");return t}function v(t){return f(d(t))}!function(t){t[t.Simple=0]="Simple",t[t.WithSteps=1]="WithSteps",t[t.Curved=2]="Curved"}(a||(a={})),function(t){t[t.Solid=0]="Solid",t[t.Dotted=1]="Dotted",t[t.Dashed=2]="Dashed",t[t.LargeDashed=3]="LargeDashed",t[t.SparseDotted=4]="SparseDotted"}(o||(o={}));const p={khaki:"#f0e68c",azure:"#f0ffff",aliceblue:"#f0f8ff",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",gray:"#808080",green:"#008000",honeydew:"#f0fff0",floralwhite:"#fffaf0",lightblue:"#add8e6",lightcoral:"#f08080",lemonchiffon:"#fffacd",hotpink:"#ff69b4",lightyellow:"#ffffe0",greenyellow:"#adff2f",lightgoldenrodyellow:"#fafad2",limegreen:"#32cd32",linen:"#faf0e6",lightcyan:"#e0ffff",magenta:"#f0f",maroon:"#800000",olive:"#808000",orange:"#ffa500",oldlace:"#fdf5e6",mediumblue:"#0000cd",transparent:"#0000",lime:"#0f0",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",midnightblue:"#191970",orchid:"#da70d6",mediumorchid:"#ba55d3",mediumturquoise:"#48d1cc",orangered:"#ff4500",royalblue:"#4169e1",powderblue:"#b0e0e6",red:"#f00",coral:"#ff7f50",turquoise:"#40e0d0",white:"#fff",whitesmoke:"#f5f5f5",wheat:"#f5deb3",teal:"#008080",steelblue:"#4682b4",bisque:"#ffe4c4",aquamarine:"#7fffd4",aqua:"#0ff",sienna:"#a0522d",silver:"#c0c0c0",springgreen:"#00ff7f",antiquewhite:"#faebd7",burlywood:"#deb887",brown:"#a52a2a",beige:"#f5f5dc",chocolate:"#d2691e",chartreuse:"#7fff00",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cadetblue:"#5f9ea0",tomato:"#ff6347",fuchsia:"#f0f",blue:"#00f",salmon:"#fa8072",blanchedalmond:"#ffebcd",slateblue:"#6a5acd",slategray:"#708090",thistle:"#d8bfd8",tan:"#d2b48c",cyan:"#0ff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",blueviolet:"#8a2be2",black:"#000",darkmagenta:"#8b008b",darkslateblue:"#483d8b",darkkhaki:"#bdb76b",darkorchid:"#9932cc",darkorange:"#ff8c00",darkgreen:"#006400",darkred:"#8b0000",dodgerblue:"#1e90ff",darkslategray:"#2f4f4f",dimgray:"#696969",deepskyblue:"#00bfff",firebrick:"#b22222",forestgreen:"#228b22",indigo:"#4b0082",ivory:"#fffff0",lavenderblush:"#fff0f5",feldspar:"#d19275",indianred:"#cd5c5c",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightskyblue:"#87cefa",lightslategray:"#789",lightslateblue:"#8470ff",snow:"#fffafa",lightseagreen:"#20b2aa",lightsalmon:"#ffa07a",darksalmon:"#e9967a",darkviolet:"#9400d3",mediumpurple:"#9370d8",mediumaquamarine:"#66cdaa",skyblue:"#87ceeb",lavender:"#e6e6fa",lightsteelblue:"#b0c4de",mediumvioletred:"#c71585",mintcream:"#f5fffa",navajowhite:"#ffdead",navy:"#000080",olivedrab:"#6b8e23",palevioletred:"#d87093",violetred:"#d02090",yellow:"#ff0",yellowgreen:"#9acd32",lawngreen:"#7cfc00",pink:"#ffc0cb",paleturquoise:"#afeeee",palegoldenrod:"#eee8aa",darkolivegreen:"#556b2f",darkseagreen:"#8fbc8f",darkturquoise:"#00ced1",peachpuff:"#ffdab9",deeppink:"#ff1493",violet:"#ee82ee",palegreen:"#98fb98",mediumseagreen:"#3cb371",peru:"#cd853f",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",purple:"#800080",seagreen:"#2e8b57",seashell:"#fff5ee",papayawhip:"#ffefd5",mediumslateblue:"#7b68ee",plum:"#dda0dd",mediumspringgreen:"#00fa9a"};function m(t){return t<0?0:t>255?255:Math.round(t)||0}function b(t){return t<=0||t>0?t<0?0:t>1?1:Math.round(1e4*t)/1e4:0}const w=/^#([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?$/i,g=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?$/i,M=/^rgb\(\s*(-?\d{1,10})\s*,\s*(-?\d{1,10})\s*,\s*(-?\d{1,10})\s*\)$/,x=/^rgba\(\s*(-?\d{1,10})\s*,\s*(-?\d{1,10})\s*,\s*(-?\d{1,10})\s*,\s*(-?[\d]{0,10}(?:\.\d+)?)\s*\)$/;function S(t){(t=t.toLowerCase())in p&&(t=p[t]);{const i=x.exec(t)||M.exec(t);if(i)return[m(parseInt(i[1],10)),m(parseInt(i[2],10)),m(parseInt(i[3],10)),b(i.length<5?1:parseFloat(i[4]))]}{const i=g.exec(t);if(i)return[m(parseInt(i[1],16)),m(parseInt(i[2],16)),m(parseInt(i[3],16)),1]}{const i=w.exec(t);if(i)return[m(17*parseInt(i[1],16)),m(17*parseInt(i[2],16)),m(17*parseInt(i[3],16)),1]}throw new Error(`Cannot parse color: ${t}`)}function y(t){const i=S(t);return{t:`rgb(${i[0]}, ${i[1]}, ${i[2]})`,i:(n=i,.199*n[0]+.687*n[1]+.114*n[2]>160?"black":"white")};var n}class k{constructor(){this.h=[]}l(t,i,n){const s={o:t,_:i,u:!0===n};this.h.push(s)}v(t){const i=this.h.findIndex((i=>t===i.o));i>-1&&this.h.splice(i,1)}p(t){this.h=this.h.filter((i=>i._!==t))}m(t,i,n){const s=[...this.h];this.h=this.h.filter((t=>!t.u)),s.forEach((s=>s.o(t,i,n)))}M(){return this.h.length>0}S(){this.h=[]}}function C(t,...i){for(const n of i)for(const i in n)void 0!==n[i]&&("object"!=typeof n[i]||void 0===t[i]||Array.isArray(n[i])?t[i]=n[i]:C(t[i],n[i]));return t}function T(t){return"number"==typeof t&&isFinite(t)}function P(t){return"number"==typeof t&&t%1==0}function R(t){return"string"==typeof t}function D(t){return"boolean"==typeof t}function O(t){const i=t;if(!i||"object"!=typeof i)return i;let n,s,e;for(s in n=Array.isArray(i)?[]:{},i)i.hasOwnProperty(s)&&(e=i[s],n[s]=e&&"object"==typeof e?O(e):e);return n}function A(t){return null!==t}function B(t){return null===t?void 0:t}const V="-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif";function z(t,i,n){return void 0===i&&(i=V),`${n=void 0!==n?`${n} `:""}${t}px ${i}`}class E{constructor(t){this.k={C:1,T:5,P:NaN,R:"",D:"",O:"",A:"",B:0,V:0,I:0,L:0,N:0},this.F=t}W(){const t=this.k,i=this.j(),n=this.H();return t.P===i&&t.D===n||(t.P=i,t.D=n,t.R=z(i,n),t.L=2.5/12*i,t.B=t.L,t.V=i/12*t.T,t.I=i/12*t.T,t.N=0),t.O=this.$(),t.A=this.U(),this.k}$(){return this.F.W().layout.textColor}U(){return this.F.q()}j(){return this.F.W().layout.fontSize}H(){return this.F.W().layout.fontFamily}}class I{constructor(){this.Y=[]}X(t){this.Y=t}K(t,i,n){this.Y.forEach((s=>{s.K(t,i,n)}))}}class L{K(t,i,n){t.useBitmapCoordinateSpace((t=>this.Z(t,i,n)))}}class N extends L{constructor(){super(...arguments),this.G=null}J(t){this.G=t}Z({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(null===this.G||null===this.G.tt)return;const s=this.G.tt,e=this.G,r=Math.max(1,Math.floor(i))%2/2,h=h=>{t.beginPath();for(let l=s.to-1;l>=s.from;--l){const s=e.it[l],a=Math.round(s.nt*i)+r,o=s.st*n,_=h*n+r;t.moveTo(a,o),t.arc(a,o,_,0,2*Math.PI)}t.fill()};e.et>0&&(t.fillStyle=e.rt,h(e.ht+e.et)),t.fillStyle=e.lt,h(e.ht)}}function F(){return{it:[{nt:0,st:0,ot:0,_t:0}],lt:"",rt:"",ht:0,et:0,tt:null}}const W={from:0,to:1};class j{constructor(t,i){this.ut=new I,this.ct=[],this.dt=[],this.ft=!0,this.F=t,this.vt=i,this.ut.X(this.ct)}bt(t){const i=this.F.wt();i.length!==this.ct.length&&(this.dt=i.map(F),this.ct=this.dt.map((t=>{const i=new N;return i.J(t),i})),this.ut.X(this.ct)),this.ft=!0}gt(){return this.ft&&(this.Mt(),this.ft=!1),this.ut}Mt(){const t=2===this.vt.W().mode,i=this.F.wt(),n=this.vt.xt(),s=this.F.St();i.forEach(((i,e)=>{var r;const h=this.dt[e],l=i.yt(n);if(t||null===l||!i.kt())return void(h.tt=null);const a=f(i.Ct());h.lt=l.Tt,h.ht=l.ht,h.et=l.Pt,h.it[0]._t=l._t,h.it[0].st=i.Dt().Rt(l._t,a.Ot),h.rt=null!==(r=l.At)&&void 0!==r?r:this.F.Bt(h.it[0].st/i.Dt().Vt()),h.it[0].ot=n,h.it[0].nt=s.zt(n),h.tt=W}))}}class H extends L{constructor(t){super(),this.Et=t}Z({context:t,bitmapSize:i,horizontalPixelRatio:n,verticalPixelRatio:s}){if(null===this.Et)return;const e=this.Et.It.kt,r=this.Et.Lt.kt;if(!e&&!r)return;const h=Math.round(this.Et.nt*n),l=Math.round(this.Et.st*s);t.lineCap="butt",e&&h>=0&&(t.lineWidth=Math.floor(this.Et.It.et*n),t.strokeStyle=this.Et.It.O,t.fillStyle=this.Et.It.O,_(t,this.Et.It.Nt),function(t,i,n,s){t.beginPath();const e=t.lineWidth%2?.5:0;t.moveTo(i+e,n),t.lineTo(i+e,s),t.stroke()}(t,h,0,i.height)),r&&l>=0&&(t.lineWidth=Math.floor(this.Et.Lt.et*s),t.strokeStyle=this.Et.Lt.O,t.fillStyle=this.Et.Lt.O,_(t,this.Et.Lt.Nt),u(t,l,0,i.width))}}class ${constructor(t){this.ft=!0,this.Ft={It:{et:1,Nt:0,O:"",kt:!1},Lt:{et:1,Nt:0,O:"",kt:!1},nt:0,st:0},this.Wt=new H(this.Ft),this.jt=t}bt(){this.ft=!0}gt(){return this.ft&&(this.Mt(),this.ft=!1),this.Wt}Mt(){const t=this.jt.kt(),i=f(this.jt.Ht()),n=i.$t().W().crosshair,s=this.Ft;if(2===n.mode)return s.Lt.kt=!1,void(s.It.kt=!1);s.Lt.kt=t&&this.jt.Ut(i),s.It.kt=t&&this.jt.qt(),s.Lt.et=n.horzLine.width,s.Lt.Nt=n.horzLine.style,s.Lt.O=n.horzLine.color,s.It.et=n.vertLine.width,s.It.Nt=n.vertLine.style,s.It.O=n.vertLine.color,s.nt=this.jt.Yt(),s.st=this.jt.Xt()}}function U(t,i,n,s,e,r){t.fillRect(i+r,n,s-2*r,r),t.fillRect(i+r,n+e-r,s-2*r,r),t.fillRect(i,n,r,e),t.fillRect(i+s-r,n,r,e)}function q(t,i,n,s,e,r){t.save(),t.globalCompositeOperation="copy",t.fillStyle=r,t.fillRect(i,n,s,e),t.restore()}function Y(t,i){return t.map((t=>0===t?t:t+i))}function X(t,i,n,s,e,r){t.beginPath(),t.lineTo(i+s-r[1],n),0!==r[1]&&t.arcTo(i+s,n,i+s,n+r[1],r[1]),t.lineTo(i+s,n+e-r[2]),0!==r[2]&&t.arcTo(i+s,n+e,i+s-r[2],n+e,r[2]),t.lineTo(i+r[3],n+e),0!==r[3]&&t.arcTo(i,n+e,i,n+e-r[3],r[3]),t.lineTo(i,n+r[0]),0!==r[0]&&t.arcTo(i,n,i+r[0],n,r[0])}function K(t,i,n,s,e,r,h=0,l=[0,0,0,0],a=""){if(t.save(),!h||!a||a===r)return X(t,i,n,s,e,l),t.fillStyle=r,t.fill(),void t.restore();const o=h/2;if("transparent"!==r){X(t,i+h,n+h,s-2*h,e-2*h,Y(l,-h)),t.fillStyle=r,t.fill()}if("transparent"!==a){X(t,i+o,n+o,s-h,e-h,Y(l,-o)),t.lineWidth=h,t.strokeStyle=a,t.closePath(),t.stroke()}t.restore()}function Z(t,i,n,s,e,r,h){t.save(),t.globalCompositeOperation="copy";const l=t.createLinearGradient(0,0,0,e);l.addColorStop(0,r),l.addColorStop(1,h),t.fillStyle=l,t.fillRect(i,n,s,e),t.restore()}class G{constructor(t,i){this.J(t,i)}J(t,i){this.Et=t,this.Kt=i}Vt(t,i){return this.Et.kt?t.P+t.L+t.B:0}K(t,i,n,s){if(!this.Et.kt||0===this.Et.Zt.length)return;const e=this.Et.O,r=this.Kt.t,h=t.useBitmapCoordinateSpace((t=>{const h=t.context;h.font=i.R;const l=this.Gt(t,i,n,s),a=l.Jt,o=(t,i)=>{l.Qt?K(h,a.ti,a.ii,a.ni,a.si,t,a.ei,[a.ht,0,0,a.ht],i):K(h,a.ri,a.ii,a.ni,a.si,t,a.ei,[0,a.ht,a.ht,0],i)};return o(r,"transparent"),this.Et.hi&&(h.fillStyle=e,h.fillRect(a.ri,a.li,a.ai-a.ri,a.oi)),o("transparent",r),this.Et._i&&(h.fillStyle=i.A,h.fillRect(l.Qt?a.ui-a.ei:0,a.ii,a.ei,a.ci-a.ii)),l}));t.useMediaCoordinateSpace((({context:t})=>{const n=h.di;t.font=i.R,t.textAlign=h.Qt?"right":"left",t.textBaseline="middle",t.fillStyle=e,t.fillText(this.Et.Zt,n.fi,(n.ii+n.ci)/2+n.vi)}))}Gt(t,i,n,s){var e;const{context:r,bitmapSize:h,mediaSize:l,horizontalPixelRatio:a,verticalPixelRatio:o}=t,_=this.Et.hi||!this.Et.pi?i.T:0,u=this.Et.mi?i.C:0,c=i.L+this.Kt.bi,d=i.B+this.Kt.wi,f=i.V,v=i.I,p=this.Et.Zt,m=i.P,b=n.gi(r,p),w=Math.ceil(n.Mi(r,p)),g=m+c+d,M=i.C+f+v+w+_,x=Math.max(1,Math.floor(o));let S=Math.round(g*o);S%2!=x%2&&(S+=1);const y=u>0?Math.max(1,Math.floor(u*a)):0,k=Math.round(M*a),C=Math.round(_*a),T=null!==(e=this.Kt.xi)&&void 0!==e?e:this.Kt.Si,P=Math.round(T*o)-Math.floor(.5*o),R=Math.floor(P+x/2-S/2),D=R+S,O="right"===s,A=O?l.width-u:u,B=O?h.width-y:y;let V,z,E;return O?(V=B-k,z=B-C,E=A-_-f-u):(V=B+k,z=B+C,E=A+_+f),{Qt:O,Jt:{ii:R,li:P,ci:D,ni:k,si:S,ht:2*a,ei:y,ti:V,ri:B,ai:z,oi:x,ui:h.width},di:{ii:R/o,ci:D/o,fi:E,vi:b}}}}class J{constructor(t){this.yi={Si:0,t:"#000",wi:0,bi:0},this.ki={Zt:"",kt:!1,hi:!0,pi:!1,At:"",O:"#FFF",_i:!1,mi:!1},this.Ci={Zt:"",kt:!1,hi:!1,pi:!0,At:"",O:"#FFF",_i:!0,mi:!0},this.ft=!0,this.Ti=new(t||G)(this.ki,this.yi),this.Pi=new(t||G)(this.Ci,this.yi)}Zt(){return this.Ri(),this.ki.Zt}Si(){return this.Ri(),this.yi.Si}bt(){this.ft=!0}Vt(t,i=!1){return Math.max(this.Ti.Vt(t,i),this.Pi.Vt(t,i))}Di(){return this.yi.xi||0}Oi(t){this.yi.xi=t}Ai(){return this.Ri(),this.ki.kt||this.Ci.kt}Bi(){return this.Ri(),this.ki.kt}gt(t){return this.Ri(),this.ki.hi=this.ki.hi&&t.W().ticksVisible,this.Ci.hi=this.Ci.hi&&t.W().ticksVisible,this.Ti.J(this.ki,this.yi),this.Pi.J(this.Ci,this.yi),this.Ti}Vi(){return this.Ri(),this.Ti.J(this.ki,this.yi),this.Pi.J(this.Ci,this.yi),this.Pi}Ri(){this.ft&&(this.ki.hi=!0,this.Ci.hi=!1,this.zi(this.ki,this.Ci,this.yi))}}class Q extends J{constructor(t,i,n){super(),this.jt=t,this.Ei=i,this.Ii=n}zi(t,i,n){if(t.kt=!1,2===this.jt.W().mode)return;const s=this.jt.W().horzLine;if(!s.labelVisible)return;const e=this.Ei.Ct();if(!this.jt.kt()||this.Ei.Li()||null===e)return;const r=y(s.labelBackgroundColor);n.t=r.t,t.O=r.i;const h=2/12*this.Ei.P();n.bi=h,n.wi=h;const l=this.Ii(this.Ei);n.Si=l.Si,t.Zt=this.Ei.Ni(l._t,e),t.kt=!0}}const tt=/[1-9]/g;class it{constructor(){this.Et=null}J(t){this.Et=t}K(t,i){if(null===this.Et||!1===this.Et.kt||0===this.Et.Zt.length)return;const n=t.useMediaCoordinateSpace((({context:t})=>(t.font=i.R,Math.round(i.Fi.Mi(t,f(this.Et).Zt,tt)))));if(n<=0)return;const s=i.Wi,e=n+2*s,r=e/2,h=this.Et.ji;let l=this.Et.Si,a=Math.floor(l-r)+.5;a<0?(l+=Math.abs(0-a),a=Math.floor(l-r)+.5):a+e>h&&(l-=Math.abs(h-(a+e)),a=Math.floor(l-r)+.5);const o=a+e,_=Math.ceil(0+i.C+i.T+i.L+i.P+i.B);t.useBitmapCoordinateSpace((({context:t,horizontalPixelRatio:n,verticalPixelRatio:s})=>{const e=f(this.Et);t.fillStyle=e.t;const r=Math.round(a*n),h=Math.round(0*s),l=Math.round(o*n),u=Math.round(_*s),c=Math.round(2*n);if(t.beginPath(),t.moveTo(r,h),t.lineTo(r,u-c),t.arcTo(r,u,r+c,u,c),t.lineTo(l-c,u),t.arcTo(l,u,l,u-c,c),t.lineTo(l,h),t.fill(),e.hi){const r=Math.round(e.Si*n),l=h,a=Math.round((l+i.T)*s);t.fillStyle=e.O;const o=Math.max(1,Math.floor(n)),_=Math.floor(.5*n);t.fillRect(r-_,l,o,a-l)}})),t.useMediaCoordinateSpace((({context:t})=>{const n=f(this.Et),e=0+i.C+i.T+i.L+i.P/2;t.font=i.R,t.textAlign="left",t.textBaseline="middle",t.fillStyle=n.O;const r=i.Fi.gi(t,"Apr0");t.translate(a+s,e+r),t.fillText(n.Zt,0,0)}))}}class nt{constructor(t,i,n){this.ft=!0,this.Wt=new it,this.Ft={kt:!1,t:"#4c525e",O:"white",Zt:"",ji:0,Si:NaN,hi:!0},this.vt=t,this.Hi=i,this.Ii=n}bt(){this.ft=!0}gt(){return this.ft&&(this.Mt(),this.ft=!1),this.Wt.J(this.Ft),this.Wt}Mt(){const t=this.Ft;if(t.kt=!1,2===this.vt.W().mode)return;const i=this.vt.W().vertLine;if(!i.labelVisible)return;const n=this.Hi.St();if(n.Li())return;t.ji=n.ji();const s=this.Ii();if(null===s)return;t.Si=s.Si;const e=n.$i(this.vt.xt());t.Zt=n.Ui(f(e)),t.kt=!0;const r=y(i.labelBackgroundColor);t.t=r.t,t.O=r.i,t.hi=n.W().ticksVisible}}class st{constructor(){this.qi=null,this.Yi=0}Xi(){return this.Yi}Ki(t){this.Yi=t}Dt(){return this.qi}Zi(t){this.qi=t}Gi(t){return[]}Ji(){return[]}kt(){return!0}}var et;!function(t){t[t.Normal=0]="Normal",t[t.Magnet=1]="Magnet",t[t.Hidden=2]="Hidden"}(et||(et={}));class rt extends st{constructor(t,i){super(),this.Qi=null,this.tn=NaN,this.nn=0,this.sn=!0,this.en=new Map,this.rn=!1,this.hn=NaN,this.ln=NaN,this.an=NaN,this.on=NaN,this.Hi=t,this._n=i,this.un=new j(t,this);this.cn=((t,i)=>n=>{const s=i(),e=t();if(n===f(this.Qi).dn())return{_t:e,Si:s};{const t=f(n.Ct());return{_t:n.fn(s,t),Si:s}}})((()=>this.tn),(()=>this.ln));const n=((t,i)=>()=>{const n=this.Hi.St().vn(t()),s=i();return n&&Number.isFinite(s)?{ot:n,Si:s}:null})((()=>this.nn),(()=>this.Yt()));this.pn=new nt(this,t,n),this.mn=new $(this)}W(){return this._n}bn(t,i){this.an=t,this.on=i}wn(){this.an=NaN,this.on=NaN}gn(){return this.an}Mn(){return this.on}xn(t,i,n){this.rn||(this.rn=!0),this.sn=!0,this.Sn(t,i,n)}xt(){return this.nn}Yt(){return this.hn}Xt(){return this.ln}kt(){return this.sn}yn(){this.sn=!1,this.kn(),this.tn=NaN,this.hn=NaN,this.ln=NaN,this.Qi=null,this.wn()}Cn(t){return null!==this.Qi?[this.mn,this.un]:[]}Ut(t){return t===this.Qi&&this._n.horzLine.visible}qt(){return this._n.vertLine.visible}Tn(t,i){this.sn&&this.Qi===t||this.en.clear();const n=[];return this.Qi===t&&n.push(this.Pn(this.en,i,this.cn)),n}Ji(){return this.sn?[this.pn]:[]}Ht(){return this.Qi}Rn(){this.mn.bt(),this.en.forEach((t=>t.bt())),this.pn.bt(),this.un.bt()}Dn(t){return t&&!t.dn().Li()?t.dn():null}Sn(t,i,n){this.On(t,i,n)&&this.Rn()}On(t,i,n){const s=this.hn,e=this.ln,r=this.tn,h=this.nn,l=this.Qi,a=this.Dn(n);this.nn=t,this.hn=isNaN(t)?NaN:this.Hi.St().zt(t),this.Qi=n;const o=null!==a?a.Ct():null;return null!==a&&null!==o?(this.tn=i,this.ln=a.Rt(i,o)):(this.tn=NaN,this.ln=NaN),s!==this.hn||e!==this.ln||h!==this.nn||r!==this.tn||l!==this.Qi}kn(){const t=this.Hi.wt().map((t=>t.Bn().An())).filter(A),i=0===t.length?null:Math.max(...t);this.nn=null!==i?i:NaN}Pn(t,i,n){let s=t.get(i);return void 0===s&&(s=new Q(this,i,n),t.set(i,s)),s}}function ht(t){return"left"===t||"right"===t}class lt{constructor(t){this.Vn=new Map,this.zn=[],this.En=t}In(t,i){const n=function(t,i){return void 0===t?i:{Ln:Math.max(t.Ln,i.Ln),Nn:t.Nn||i.Nn}}(this.Vn.get(t),i);this.Vn.set(t,n)}Fn(){return this.En}Wn(t){const i=this.Vn.get(t);return void 0===i?{Ln:this.En}:{Ln:Math.max(this.En,i.Ln),Nn:i.Nn}}jn(){this.Hn(),this.zn=[{$n:0}]}Un(t){this.Hn(),this.zn=[{$n:1,Ot:t}]}qn(t){this.Yn(),this.zn.push({$n:5,Ot:t})}Hn(){this.Yn(),this.zn.push({$n:6})}Xn(){this.Hn(),this.zn=[{$n:4}]}Kn(t){this.Hn(),this.zn.push({$n:2,Ot:t})}Zn(t){this.Hn(),this.zn.push({$n:3,Ot:t})}Gn(){return this.zn}Jn(t){for(const i of t.zn)this.Qn(i);this.En=Math.max(this.En,t.En),t.Vn.forEach(((t,i)=>{this.In(i,t)}))}static ts(){return new lt(2)}static ns(){return new lt(3)}Qn(t){switch(t.$n){case 0:this.jn();break;case 1:this.Un(t.Ot);break;case 2:this.Kn(t.Ot);break;case 3:this.Zn(t.Ot);break;case 4:this.Xn();break;case 5:this.qn(t.Ot);break;case 6:this.Yn()}}Yn(){const t=this.zn.findIndex((t=>5===t.$n));-1!==t&&this.zn.splice(t,1)}}const at=".";function ot(t,i){if(!T(t))return"n/a";if(!P(i))throw new TypeError("invalid length");if(i<0||i>16)throw new TypeError("invalid length");if(0===i)return t.toString();return("0000000000000000"+t.toString()).slice(-i)}class _t{constructor(t,i){if(i||(i=1),T(t)&&P(t)||(t=100),t<0)throw new TypeError("invalid base");this.Ei=t,this.ss=i,this.es()}format(t){const i=t<0?"−":"";return t=Math.abs(t),i+this.rs(t)}es(){if(this.hs=0,this.Ei>0&&this.ss>0){let t=this.Ei;for(;t>1;)t/=10,this.hs++}}rs(t){const i=this.Ei/this.ss;let n=Math.floor(t),s="";const e=void 0!==this.hs?this.hs:NaN;if(i>1){let r=+(Math.round(t*i)-n*i).toFixed(this.hs);r>=i&&(r-=i,n+=1),s=at+ot(+r.toFixed(this.hs)*this.ss,e)}else n=Math.round(n*i)/i,e>0&&(s=at+ot(0,e));return n.toFixed(0)+s}}class ut extends _t{constructor(t=100){super(t)}format(t){return`${super.format(t)}%`}}class ct{constructor(t){this.ls=t}format(t){let i="";return t<0&&(i="-",t=-t),t<995?i+this.os(t):t<999995?i+this.os(t/1e3)+"K":t<999999995?(t=1e3*Math.round(t/1e3),i+this.os(t/1e6)+"M"):(t=1e6*Math.round(t/1e6),i+this.os(t/1e9)+"B")}os(t){let i;const n=Math.pow(10,this.ls);return i=(t=Math.round(t*n)/n)>=1e-15&&t<1?t.toFixed(this.ls).replace(/\.?0+$/,""):String(t),i.replace(/(\.[1-9]*)0+$/,((t,i)=>i))}}function dt(t,i,n,s,e,r,h){if(0===i.length||s.from>=i.length||s.to<=0)return;const{context:l,horizontalPixelRatio:a,verticalPixelRatio:o}=t,_=i[s.from];let u=r(t,_),c=_;if(s.to-s.from<2){const i=e/2;l.beginPath();const n={nt:_.nt-i,st:_.st},s={nt:_.nt+i,st:_.st};l.moveTo(n.nt*a,n.st*o),l.lineTo(s.nt*a,s.st*o),h(t,u,n,s)}else{const e=(i,n)=>{h(t,u,c,n),l.beginPath(),u=i,c=n};let d=c;l.beginPath(),l.moveTo(_.nt*a,_.st*o);for(let h=s.from+1;h=s.from;--n){const s=i[n];if(s){const i=e(t,s);i!==a&&(l.beginPath(),null!==a&&l.fill(),l.fillStyle=i,a=i);const n=Math.round(s.nt*r)+o,u=s.st*h;l.moveTo(n,u),l.arc(n,u,_,0,2*Math.PI)}}l.fill()}(t,i,l,n,o)}}class Tt extends Ct{Ps(t,i){return i.lt}}function Pt(t,i,n,s,e=0,r=i.length){let h=r-e;for(;0>1,l=e+r;s(i[l],n)===t?(e=l+1,h-=r+1):h=r}return e}const Rt=Pt.bind(null,!0),Dt=Pt.bind(null,!1);function Ot(t,i){return t.ot0&&r=s&&(l=r-1),h>0&&hObject.assign(Object.assign({},t),this.zs.js().Ws(t.ot))))}Hs(){this.Vs=null}Ls(){this.Os&&(this.$s(),this.Os=!1),this.As&&(this.Fs(),this.As=!1),this.Ds&&(this.Us(),this.Ds=!1)}Us(){const t=this.zs.Dt(),i=this.Es.St();if(this.Hs(),i.Li()||t.Li())return;const n=i.qs();if(null===n)return;if(0===this.zs.Bn().Ys())return;const s=this.zs.Ct();null!==s&&(this.Vs=Bt(this.Bs,n,this.Is),this.Xs(t,i,s.Ot),this.Ks())}}class zt extends Vt{constructor(t,i){super(t,i,!0)}Xs(t,i,n){i.Zs(this.Bs,B(this.Vs)),t.Gs(this.Bs,n,B(this.Vs))}Js(t,i){return{ot:t,_t:i,nt:NaN,st:NaN}}$s(){const t=this.zs.js();this.Bs=this.zs.Bn().Qs().map((i=>{const n=i.Ot[3];return this.te(i.ie,n,t)}))}}class Et extends zt{constructor(t,i){super(t,i),this.Ns=new I,this.ne=new yt,this.se=new Tt,this.Ns.X([this.ne,this.se])}te(t,i,n){return Object.assign(Object.assign({},this.Js(t,i)),n.Ws(t))}Ks(){const t=this.zs.W();this.ne.J({us:t.lineType,it:this.Bs,Nt:t.lineStyle,et:t.lineWidth,cs:null,ds:t.invertFilledArea,tt:this.Vs,_s:this.Es.St().ee()}),this.se.J({us:t.lineVisible?t.lineType:void 0,it:this.Bs,Nt:t.lineStyle,et:t.lineWidth,tt:this.Vs,_s:this.Es.St().ee(),Ts:t.pointMarkersVisible?t.pointMarkersRadius||t.lineWidth/2+2:void 0})}}class It extends L{constructor(){super(...arguments),this.Et=null,this.re=0,this.he=0}J(t){this.Et=t}Z({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(null===this.Et||0===this.Et.Bn.length||null===this.Et.tt)return;if(this.re=this.le(i),this.re>=2){Math.max(1,Math.floor(i))%2!=this.re%2&&this.re--}this.he=this.Et.ae?Math.min(this.re,Math.floor(i)):this.re;let s=null;const e=this.he<=this.re&&this.Et.ee>=Math.floor(1.5*i);for(let r=this.Et.tt.from;rf+p-1&&(e=f+p-1,s=e-_+1),t.fillRect(i,s,o-i,e-s+1)}const i=a+m;let s=Math.max(f,Math.round(h.fe*n)-l),e=s+_-1;e>f+p-1&&(e=f+p-1,s=e-_+1),t.fillRect(u+1,s,i-u,e-s+1)}}}le(t){const i=Math.floor(t);return Math.max(i,Math.floor(function(t,i){return Math.floor(.3*t*i)}(f(this.Et).ee,t)))}}class Lt extends Vt{constructor(t,i){super(t,i,!1)}Xs(t,i,n){i.Zs(this.Bs,B(this.Vs)),t.ve(this.Bs,n,B(this.Vs))}pe(t,i,n){return{ot:t,me:i.Ot[0],be:i.Ot[1],we:i.Ot[2],ge:i.Ot[3],nt:NaN,de:NaN,_e:NaN,ue:NaN,fe:NaN}}$s(){const t=this.zs.js();this.Bs=this.zs.Bn().Qs().map((i=>this.te(i.ie,i,t)))}}class Nt extends Lt{constructor(){super(...arguments),this.Ns=new It}te(t,i,n){return Object.assign(Object.assign({},this.pe(t,i,n)),n.Ws(t))}Ks(){const t=this.zs.W();this.Ns.J({Bn:this.Bs,ee:this.Es.St().ee(),ce:t.openVisible,ae:t.thinBars,tt:this.Vs})}}class Ft extends wt{constructor(){super(...arguments),this.ys=new St}fs(t,i){const n=this.G;return this.ys.vs(t,{bs:i.Me,ws:i.xe,gs:i.Se,Ms:i.ye,xs:t.bitmapSize.height,cs:n.cs})}}class Wt extends Ct{constructor(){super(...arguments),this.ke=new St}Ps(t,i){const n=this.G;return this.ke.vs(t,{bs:i.Ce,ws:i.Ce,gs:i.Te,Ms:i.Te,xs:t.bitmapSize.height,cs:n.cs})}}class jt extends zt{constructor(t,i){super(t,i),this.Ns=new I,this.Pe=new Ft,this.Re=new Wt,this.Ns.X([this.Pe,this.Re])}te(t,i,n){return Object.assign(Object.assign({},this.Js(t,i)),n.Ws(t))}Ks(){const t=this.zs.Ct();if(null===t)return;const i=this.zs.W(),n=this.zs.Dt().Rt(i.baseValue.price,t.Ot),s=this.Es.St().ee();this.Pe.J({it:this.Bs,et:i.lineWidth,Nt:i.lineStyle,us:i.lineType,cs:n,ds:!1,tt:this.Vs,_s:s}),this.Re.J({it:this.Bs,et:i.lineWidth,Nt:i.lineStyle,us:i.lineVisible?i.lineType:void 0,Ts:i.pointMarkersVisible?i.pointMarkersRadius||i.lineWidth/2+2:void 0,cs:n,tt:this.Vs,_s:s})}}class Ht extends L{constructor(){super(...arguments),this.Et=null,this.re=0}J(t){this.Et=t}Z(t){if(null===this.Et||0===this.Et.Bn.length||null===this.Et.tt)return;const{horizontalPixelRatio:i}=t;if(this.re=function(t,i){if(t>=2.5&&t<=4)return Math.floor(3*i);const n=1-.2*Math.atan(Math.max(4,t)-4)/(.5*Math.PI),s=Math.floor(t*n*i),e=Math.floor(t*i),r=Math.min(s,e);return Math.max(Math.floor(i),r)}(this.Et.ee,i),this.re>=2){Math.floor(i)%2!=this.re%2&&this.re--}const n=this.Et.Bn;this.Et.De&&this.Oe(t,n,this.Et.tt),this.Et._i&&this.Ae(t,n,this.Et.tt);const s=this.Be(i);(!this.Et._i||this.re>2*s)&&this.Ve(t,n,this.Et.tt)}Oe(t,i,n){if(null===this.Et)return;const{context:s,horizontalPixelRatio:e,verticalPixelRatio:r}=t;let h="",l=Math.min(Math.floor(e),Math.floor(this.Et.ee*e));l=Math.max(Math.floor(e),Math.min(l,this.re));const a=Math.floor(.5*l);let o=null;for(let t=n.from;t2*l)U(s,o,u,_-o+1,c-u+1,l);else{const t=_-o+1;s.fillRect(o,u,t,c-u+1)}a=_}}Ve(t,i,n){if(null===this.Et)return;const{context:s,horizontalPixelRatio:e,verticalPixelRatio:r}=t;let h="";const l=this.Be(e);for(let t=n.from;to||s.fillRect(_,a,u-_+1,o-a+1)}}}class $t extends Lt{constructor(){super(...arguments),this.Ns=new Ht}te(t,i,n){return Object.assign(Object.assign({},this.pe(t,i,n)),n.Ws(t))}Ks(){const t=this.zs.W();this.Ns.J({Bn:this.Bs,ee:this.Es.St().ee(),De:t.wickVisible,_i:t.borderVisible,tt:this.Vs})}}class Ut{constructor(t,i){this.Ie=t,this.Ei=i}K(t,i,n){this.Ie.draw(t,this.Ei,i,n)}}class qt extends Vt{constructor(t,i,n){super(t,i,!1),this.mn=n,this.Ns=new Ut(this.mn.renderer(),(i=>{const n=t.Ct();return null===n?null:t.Dt().Rt(i,n.Ot)}))}Le(t){return this.mn.priceValueBuilder(t)}Ne(t){return this.mn.isWhitespace(t)}$s(){const t=this.zs.js();this.Bs=this.zs.Bn().Qs().map((i=>Object.assign(Object.assign({ot:i.ie,nt:NaN},t.Ws(i.ie)),{Fe:i.We})))}Xs(t,i){i.Zs(this.Bs,B(this.Vs))}Ks(){this.mn.update({bars:this.Bs.map(Yt),barSpacing:this.Es.St().ee(),visibleRange:this.Vs},this.zs.W())}}function Yt(t){return{x:t.nt,time:t.ot,originalData:t.Fe,barColor:t.oe}}class Xt extends L{constructor(){super(...arguments),this.Et=null,this.je=[]}J(t){this.Et=t,this.je=[]}Z({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){if(null===this.Et||0===this.Et.it.length||null===this.Et.tt)return;this.je.length||this.He(i);const s=Math.max(1,Math.floor(n)),e=Math.round(this.Et.$e*n)-Math.floor(s/2),r=e+s;for(let i=this.Et.tt.from;is.qe?s.ui=n.Rs-i-1:n.Rs=s.ui+i+1))}let s=Math.ceil(this.Et.ee*t);for(let t=this.Et.tt.from;t0&&s<4)for(let t=this.Et.tt.from;ts&&(i.Ue>i.qe?i.ui-=1:i.Rs+=1)}}}class Kt extends zt{constructor(){super(...arguments),this.Ns=new Xt}te(t,i,n){return Object.assign(Object.assign({},this.Js(t,i)),n.Ws(t))}Ks(){const t={it:this.Bs,ee:this.Es.St().ee(),tt:this.Vs,$e:this.zs.Dt().Rt(this.zs.W().base,f(this.zs.Ct()).Ot)};this.Ns.J(t)}}class Zt extends zt{constructor(){super(...arguments),this.Ns=new Tt}te(t,i,n){return Object.assign(Object.assign({},this.Js(t,i)),n.Ws(t))}Ks(){const t=this.zs.W(),i={it:this.Bs,Nt:t.lineStyle,us:t.lineVisible?t.lineType:void 0,et:t.lineWidth,Ts:t.pointMarkersVisible?t.pointMarkersRadius||t.lineWidth/2+2:void 0,tt:this.Vs,_s:this.Es.St().ee()};this.Ns.J(i)}}const Gt=/[2-9]/g;class Jt{constructor(t=50){this.Ye=0,this.Xe=1,this.Ke=1,this.Ze={},this.Ge=new Map,this.Je=t}Qe(){this.Ye=0,this.Ge.clear(),this.Xe=1,this.Ke=1,this.Ze={}}Mi(t,i,n){return this.tr(t,i,n).width}gi(t,i,n){const s=this.tr(t,i,n);return((s.actualBoundingBoxAscent||0)-(s.actualBoundingBoxDescent||0))/2}tr(t,i,n){const s=n||Gt,e=String(i).replace(s,"0");if(this.Ge.has(e))return d(this.Ge.get(e)).ir;if(this.Ye===this.Je){const t=this.Ze[this.Ke];delete this.Ze[this.Ke],this.Ge.delete(t),this.Ke++,this.Ye--}t.save(),t.textBaseline="middle";const r=t.measureText(e);return t.restore(),0===r.width&&i.length||(this.Ge.set(e,{ir:r,nr:this.Xe}),this.Ze[this.Xe]=e,this.Ye++,this.Xe++),r}}class Qt{constructor(t){this.sr=null,this.k=null,this.er="right",this.rr=t}hr(t,i,n){this.sr=t,this.k=i,this.er=n}K(t){null!==this.k&&null!==this.sr&&this.sr.K(t,this.k,this.rr,this.er)}}class ti{constructor(t,i,n){this.lr=t,this.rr=new Jt(50),this.ar=i,this.F=n,this.j=-1,this.Wt=new Qt(this.rr)}gt(){const t=this.F._r(this.ar);if(null===t)return null;const i=t.ur(this.ar)?t.cr():this.ar.Dt();if(null===i)return null;const n=t.dr(i);if("overlay"===n)return null;const s=this.F.vr();return s.P!==this.j&&(this.j=s.P,this.rr.Qe()),this.Wt.hr(this.lr.Vi(),s,n),this.Wt}}class ii extends L{constructor(){super(...arguments),this.Et=null}J(t){this.Et=t}pr(t,i){var n;if(!(null===(n=this.Et)||void 0===n?void 0:n.kt))return null;const{st:s,et:e,mr:r}=this.Et;return i>=s-e-7&&i<=s+e+7?{br:this.Et,mr:r}:null}Z({context:t,bitmapSize:i,horizontalPixelRatio:n,verticalPixelRatio:s}){if(null===this.Et)return;if(!1===this.Et.kt)return;const e=Math.round(this.Et.st*s);e<0||e>i.height||(t.lineCap="butt",t.strokeStyle=this.Et.O,t.lineWidth=Math.floor(this.Et.et*n),_(t,this.Et.Nt),u(t,e,0,i.width))}}class ni{constructor(t){this.wr={st:0,O:"rgba(0, 0, 0, 0)",et:1,Nt:0,kt:!1},this.gr=new ii,this.ft=!0,this.zs=t,this.Es=t.$t(),this.gr.J(this.wr)}bt(){this.ft=!0}gt(){return this.zs.kt()?(this.ft&&(this.Mr(),this.ft=!1),this.gr):null}}class si extends ni{constructor(t){super(t)}Mr(){this.wr.kt=!1;const t=this.zs.Dt(),i=t.Sr().Sr;if(2!==i&&3!==i)return;const n=this.zs.W();if(!n.baseLineVisible||!this.zs.kt())return;const s=this.zs.Ct();null!==s&&(this.wr.kt=!0,this.wr.st=t.Rt(s.Ot,s.Ot),this.wr.O=n.baseLineColor,this.wr.et=n.baseLineWidth,this.wr.Nt=n.baseLineStyle)}}class ei extends L{constructor(){super(...arguments),this.Et=null}J(t){this.Et=t}We(){return this.Et}Z({context:t,horizontalPixelRatio:i,verticalPixelRatio:n}){const s=this.Et;if(null===s)return;const e=Math.max(1,Math.floor(i)),r=e%2/2,h=Math.round(s.qe.x*i)+r,l=s.qe.y*n;t.fillStyle=s.yr,t.beginPath();const a=Math.max(2,1.5*s.kr)*i;t.arc(h,l,a,0,2*Math.PI,!1),t.fill(),t.fillStyle=s.Cr,t.beginPath(),t.arc(h,l,s.ht*i,0,2*Math.PI,!1),t.fill(),t.lineWidth=e,t.strokeStyle=s.Tr,t.beginPath(),t.arc(h,l,s.ht*i+e/2,0,2*Math.PI,!1),t.stroke()}}const ri=[{Pr:0,Rr:.25,Dr:4,Or:10,Ar:.25,Br:0,Vr:.4,zr:.8},{Pr:.25,Rr:.525,Dr:10,Or:14,Ar:0,Br:0,Vr:.8,zr:0},{Pr:.525,Rr:1,Dr:14,Or:14,Ar:0,Br:0,Vr:0,zr:0}];function hi(t,i,n,s){return function(t,i){if("transparent"===t)return t;const n=S(t),s=n[3];return`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${i*s})`}(t,n+(s-n)*i)}function li(t,i){const n=t%2600/2600;let s;for(const t of ri)if(n>=t.Pr&&n<=t.Rr){s=t;break}c(void 0!==s,"Last price animation internal logic error");const e=(n-s.Pr)/(s.Rr-s.Pr);return{Cr:hi(i,e,s.Ar,s.Br),Tr:hi(i,e,s.Vr,s.zr),ht:(r=e,h=s.Dr,l=s.Or,h+(l-h)*r)};var r,h,l}class ai{constructor(t){this.Wt=new ei,this.ft=!0,this.Er=!0,this.Ir=performance.now(),this.Lr=this.Ir-1,this.Nr=t}Fr(){this.Lr=this.Ir-1,this.bt()}Wr(){if(this.bt(),2===this.Nr.W().lastPriceAnimation){const t=performance.now(),i=this.Lr-t;if(i>0)return void(i<650&&(this.Lr+=2600));this.Ir=t,this.Lr=t+2600}}bt(){this.ft=!0}jr(){this.Er=!0}kt(){return 0!==this.Nr.W().lastPriceAnimation}Hr(){switch(this.Nr.W().lastPriceAnimation){case 0:return!1;case 1:return!0;case 2:return performance.now()<=this.Lr}}gt(){return this.ft?(this.Mt(),this.ft=!1,this.Er=!1):this.Er&&(this.$r(),this.Er=!1),this.Wt}Mt(){this.Wt.J(null);const t=this.Nr.$t().St(),i=t.qs(),n=this.Nr.Ct();if(null===i||null===n)return;const s=this.Nr.Ur(!0);if(s.qr||!i.Yr(s.ie))return;const e={x:t.zt(s.ie),y:this.Nr.Dt().Rt(s._t,n.Ot)},r=s.O,h=this.Nr.W().lineWidth,l=li(this.Xr(),r);this.Wt.J({yr:r,kr:h,Cr:l.Cr,Tr:l.Tr,ht:l.ht,qe:e})}$r(){const t=this.Wt.We();if(null!==t){const i=li(this.Xr(),t.yr);t.Cr=i.Cr,t.Tr=i.Tr,t.ht=i.ht}}Xr(){return this.Hr()?performance.now()-this.Ir:2599}}function oi(t,i){return xt(Math.min(Math.max(t,12),30)*i)}function _i(t,i){switch(t){case"arrowDown":case"arrowUp":return oi(i,1);case"circle":return oi(i,.8);case"square":return oi(i,.7)}}function ui(t){return function(t){const i=Math.ceil(t);return i%2!=0?i-1:i}(oi(t,1))}function ci(t){return Math.max(oi(t,.1),3)}function di(t,i,n,s,e){const r=_i("square",n),h=(r-1)/2,l=t-h,a=i-h;return s>=l&&s<=l+r&&e>=a&&e<=a+r}function fi(t,i,n,s){const e=(_i("arrowUp",s)-1)/2*n.Kr,r=(xt(s/2)-1)/2*n.Kr;i.beginPath(),t?(i.moveTo(n.nt-e,n.st),i.lineTo(n.nt,n.st-e),i.lineTo(n.nt+e,n.st),i.lineTo(n.nt+r,n.st),i.lineTo(n.nt+r,n.st+e),i.lineTo(n.nt-r,n.st+e),i.lineTo(n.nt-r,n.st)):(i.moveTo(n.nt-e,n.st),i.lineTo(n.nt,n.st+e),i.lineTo(n.nt+e,n.st),i.lineTo(n.nt+r,n.st),i.lineTo(n.nt+r,n.st-e),i.lineTo(n.nt-r,n.st-e),i.lineTo(n.nt-r,n.st)),i.fill()}function vi(t,i,n,s,e,r){return di(i,n,s,e,r)}class pi extends L{constructor(){super(...arguments),this.Et=null,this.rr=new Jt,this.j=-1,this.H="",this.Zr=""}J(t){this.Et=t}hr(t,i){this.j===t&&this.H===i||(this.j=t,this.H=i,this.Zr=z(t,i),this.rr.Qe())}pr(t,i){if(null===this.Et||null===this.Et.tt)return null;for(let n=this.Et.tt.from;n=t&&e<=t+n&&r>=i-h&&r<=i+h}(t.Zt.nt,t.Zt.st,t.Zt.ji,t.Zt.Vt,i,n))||function(t,i,n){if(0===t.Ys)return!1;switch(t.Qr){case"arrowDown":case"arrowUp":return vi(0,t.nt,t.st,t.Ys,i,n);case"circle":return function(t,i,n,s,e){const r=2+_i("circle",n)/2,h=t-s,l=i-e;return Math.sqrt(h*h+l*l)<=r}(t.nt,t.st,t.Ys,i,n);case"square":return di(t.nt,t.st,t.Ys,i,n)}}(t,i,n)}function wi(t,i,n,s,e,r,h,l,a){const o=T(n)?n:n.ge,_=T(n)?n:n.be,u=T(n)?n:n.we,c=T(i.size)?Math.max(i.size,0):1,d=ui(l.ee())*c,f=d/2;switch(t.Ys=d,i.position){case"inBar":return t.st=h.Rt(o,a),void(void 0!==t.Zt&&(t.Zt.st=t.st+f+r+.6*e));case"aboveBar":return t.st=h.Rt(_,a)-f-s.th,void 0!==t.Zt&&(t.Zt.st=t.st-f-.6*e,s.th+=1.2*e),void(s.th+=d+r);case"belowBar":return t.st=h.Rt(u,a)+f+s.ih,void 0!==t.Zt&&(t.Zt.st=t.st+f+r+.6*e,s.ih+=1.2*e),void(s.ih+=d+r)}i.position}class gi{constructor(t,i){this.ft=!0,this.nh=!0,this.sh=!0,this.eh=null,this.Wt=new pi,this.Nr=t,this.Hi=i,this.Et={it:[],tt:null}}bt(t){this.ft=!0,this.sh=!0,"data"===t&&(this.nh=!0)}gt(t){if(!this.Nr.kt())return null;this.ft&&this.rh();const i=this.Hi.W().layout;return this.Wt.hr(i.fontSize,i.fontFamily),this.Wt.J(this.Et),this.Wt}hh(){if(this.sh){if(this.Nr.lh().length>0){const t=this.Hi.St().ee(),i=ci(t),n=1.5*ui(t)+2*i;this.eh={above:n,below:n}}else this.eh=null;this.sh=!1}return this.eh}rh(){const t=this.Nr.Dt(),i=this.Hi.St(),n=this.Nr.lh();this.nh&&(this.Et.it=n.map((t=>({ot:t.time,nt:0,st:0,Ys:0,Qr:t.shape,O:t.color,Gr:t.Gr,mr:t.id,Zt:void 0}))),this.nh=!1);const s=this.Hi.W().layout;this.Et.tt=null;const e=i.qs();if(null===e)return;const r=this.Nr.Ct();if(null===r)return;if(0===this.Et.it.length)return;let h=NaN;const l=ci(i.ee()),a={th:l,ih:l};this.Et.tt=Bt(this.Et.it,e,!0);for(let e=this.Et.tt.from;e0&&(_.Zt={Jr:o.text,nt:0,st:0,ji:0,Vt:0});const u=this.Nr.ah(o.time);null!==u&&wi(_,o,u,a,s.fontSize,l,t,i,r.Ot)}this.ft=!1}}class Mi extends ni{constructor(t){super(t)}Mr(){const t=this.wr;t.kt=!1;const i=this.zs.W();if(!i.priceLineVisible||!this.zs.kt())return;const n=this.zs.Ur(0===i.priceLineSource);n.qr||(t.kt=!0,t.st=n.Si,t.O=this.zs.oh(n.O),t.et=i.priceLineWidth,t.Nt=i.priceLineStyle)}}class xi extends J{constructor(t){super(),this.jt=t}zi(t,i,n){t.kt=!1,i.kt=!1;const s=this.jt;if(!s.kt())return;const e=s.W(),r=e.lastValueVisible,h=""!==s._h(),l=0===e.seriesLastValueMode,a=s.Ur(!1);if(a.qr)return;r&&(t.Zt=this.uh(a,r,l),t.kt=0!==t.Zt.length),(h||l)&&(i.Zt=this.dh(a,r,h,l),i.kt=i.Zt.length>0);const o=s.oh(a.O),_=y(o);n.t=_.t,n.Si=a.Si,i.At=s.$t().Bt(a.Si/s.Dt().Vt()),t.At=o,t.O=_.i,i.O=_.i}dh(t,i,n,s){let e="";const r=this.jt._h();return n&&0!==r.length&&(e+=`${r} `),i&&s&&(e+=this.jt.Dt().fh()?t.ph:t.mh),e.trim()}uh(t,i,n){return i?n?this.jt.Dt().fh()?t.mh:t.ph:t.Zt:""}}function Si(t,i,n,s){const e=Number.isFinite(i),r=Number.isFinite(n);return e&&r?t(i,n):e||r?e?i:n:s}class yi{constructor(t,i){this.bh=t,this.wh=i}gh(t){return null!==t&&(this.bh===t.bh&&this.wh===t.wh)}Mh(){return new yi(this.bh,this.wh)}xh(){return this.bh}Sh(){return this.wh}yh(){return this.wh-this.bh}Li(){return this.wh===this.bh||Number.isNaN(this.wh)||Number.isNaN(this.bh)}Jn(t){return null===t?this:new yi(Si(Math.min,this.xh(),t.xh(),-1/0),Si(Math.max,this.Sh(),t.Sh(),1/0))}kh(t){if(!T(t))return;if(0===this.wh-this.bh)return;const i=.5*(this.wh+this.bh);let n=this.wh-i,s=this.bh-i;n*=t,s*=t,this.wh=i+n,this.bh=i+s}Ch(t){T(t)&&(this.wh+=t,this.bh+=t)}Th(){return{minValue:this.bh,maxValue:this.wh}}static Ph(t){return null===t?null:new yi(t.minValue,t.maxValue)}}class ki{constructor(t,i){this.Rh=t,this.Dh=i||null}Oh(){return this.Rh}Ah(){return this.Dh}Th(){return null===this.Rh?null:{priceRange:this.Rh.Th(),margins:this.Dh||void 0}}static Ph(t){return null===t?null:new ki(yi.Ph(t.priceRange),t.margins)}}class Ci extends ni{constructor(t,i){super(t),this.Bh=i}Mr(){const t=this.wr;t.kt=!1;const i=this.Bh.W();if(!this.zs.kt()||!i.lineVisible)return;const n=this.Bh.Vh();null!==n&&(t.kt=!0,t.st=n,t.O=i.color,t.et=i.lineWidth,t.Nt=i.lineStyle,t.mr=this.Bh.W().id)}}class Ti extends J{constructor(t,i){super(),this.Nr=t,this.Bh=i}zi(t,i,n){t.kt=!1,i.kt=!1;const s=this.Bh.W(),e=s.axisLabelVisible,r=""!==s.title,h=this.Nr;if(!e||!h.kt())return;const l=this.Bh.Vh();if(null===l)return;r&&(i.Zt=s.title,i.kt=!0),i.At=h.$t().Bt(l/h.Dt().Vt()),t.Zt=this.zh(s.price),t.kt=!0;const a=y(s.axisLabelColor||s.color);n.t=a.t;const o=s.axisLabelTextColor||a.i;t.O=o,i.O=o,n.Si=l}zh(t){const i=this.Nr.Ct();return null===i?"":this.Nr.Dt().Ni(t,i.Ot)}}class Pi{constructor(t,i){this.Nr=t,this._n=i,this.Eh=new Ci(t,this),this.lr=new Ti(t,this),this.Ih=new ti(this.lr,t,t.$t())}Lh(t){C(this._n,t),this.bt(),this.Nr.$t().Nh()}W(){return this._n}Fh(){return this.Eh}Wh(){return this.Ih}jh(){return this.lr}bt(){this.Eh.bt(),this.lr.bt()}Vh(){const t=this.Nr,i=t.Dt();if(t.$t().St().Li()||i.Li())return null;const n=t.Ct();return null===n?null:i.Rt(this._n.price,n.Ot)}}class Ri extends st{constructor(t){super(),this.Hi=t}$t(){return this.Hi}}const Di={Bar:(t,i,n,s)=>{var e;const r=i.upColor,h=i.downColor,l=f(t(n,s)),a=v(l.Ot[0])<=v(l.Ot[3]);return{oe:null!==(e=l.O)&&void 0!==e?e:a?r:h}},Candlestick:(t,i,n,s)=>{var e,r,h;const l=i.upColor,a=i.downColor,o=i.borderUpColor,_=i.borderDownColor,u=i.wickUpColor,c=i.wickDownColor,d=f(t(n,s)),p=v(d.Ot[0])<=v(d.Ot[3]);return{oe:null!==(e=d.O)&&void 0!==e?e:p?l:a,Ee:null!==(r=d.At)&&void 0!==r?r:p?o:_,ze:null!==(h=d.Hh)&&void 0!==h?h:p?u:c}},Custom:(t,i,n,s)=>{var e;return{oe:null!==(e=f(t(n,s)).O)&&void 0!==e?e:i.color}},Area:(t,i,n,s)=>{var e,r,h,l;const a=f(t(n,s));return{oe:null!==(e=a.lt)&&void 0!==e?e:i.lineColor,lt:null!==(r=a.lt)&&void 0!==r?r:i.lineColor,ks:null!==(h=a.ks)&&void 0!==h?h:i.topColor,Cs:null!==(l=a.Cs)&&void 0!==l?l:i.bottomColor}},Baseline:(t,i,n,s)=>{var e,r,h,l,a,o;const _=f(t(n,s));return{oe:_.Ot[3]>=i.baseValue.price?i.topLineColor:i.bottomLineColor,Ce:null!==(e=_.Ce)&&void 0!==e?e:i.topLineColor,Te:null!==(r=_.Te)&&void 0!==r?r:i.bottomLineColor,Me:null!==(h=_.Me)&&void 0!==h?h:i.topFillColor1,xe:null!==(l=_.xe)&&void 0!==l?l:i.topFillColor2,Se:null!==(a=_.Se)&&void 0!==a?a:i.bottomFillColor1,ye:null!==(o=_.ye)&&void 0!==o?o:i.bottomFillColor2}},Line:(t,i,n,s)=>{var e,r;const h=f(t(n,s));return{oe:null!==(e=h.O)&&void 0!==e?e:i.color,lt:null!==(r=h.O)&&void 0!==r?r:i.color}},Histogram:(t,i,n,s)=>{var e;return{oe:null!==(e=f(t(n,s)).O)&&void 0!==e?e:i.color}}};class Oi{constructor(t){this.$h=(t,i)=>void 0!==i?i.Ot:this.Nr.Bn().Uh(t),this.Nr=t,this.qh=Di[t.Yh()]}Ws(t,i){return this.qh(this.$h,this.Nr.W(),t,i)}}var Ai;!function(t){t[t.NearestLeft=-1]="NearestLeft",t[t.None=0]="None",t[t.NearestRight=1]="NearestRight"}(Ai||(Ai={}));const Bi=30;class Vi{constructor(){this.Xh=[],this.Kh=new Map,this.Zh=new Map}Gh(){return this.Ys()>0?this.Xh[this.Xh.length-1]:null}Jh(){return this.Ys()>0?this.Qh(0):null}An(){return this.Ys()>0?this.Qh(this.Xh.length-1):null}Ys(){return this.Xh.length}Li(){return 0===this.Ys()}Yr(t){return null!==this.tl(t,0)}Uh(t){return this.il(t)}il(t,i=0){const n=this.tl(t,i);return null===n?null:Object.assign(Object.assign({},this.nl(n)),{ie:this.Qh(n)})}Qs(){return this.Xh}sl(t,i,n){if(this.Li())return null;let s=null;for(const e of n){s=zi(s,this.el(t,i,e))}return s}J(t){this.Zh.clear(),this.Kh.clear(),this.Xh=t}Qh(t){return this.Xh[t].ie}nl(t){return this.Xh[t]}tl(t,i){const n=this.rl(t);if(null===n&&0!==i)switch(i){case-1:return this.hl(t);case 1:return this.ll(t);default:throw new TypeError("Unknown search mode")}return n}hl(t){let i=this.al(t);return i>0&&(i-=1),i!==this.Xh.length&&this.Qh(i)t.iet.ie>i))}_l(t,i,n){let s=null;for(let e=t;es.cl&&(s.cl=t)))}return s}el(t,i,n){if(this.Li())return null;let s=null;const e=f(this.Jh()),r=f(this.An()),h=Math.max(t,e),l=Math.min(i,r),a=Math.ceil(h/Bi)*Bi,o=Math.max(a,Math.floor(l/Bi)*Bi);{const t=this.al(h),e=this.ol(Math.min(l,a,i));s=zi(s,this._l(t,e,n))}let _=this.Kh.get(n);void 0===_&&(_=new Map,this.Kh.set(n,_));for(let t=Math.max(a+1,h);tnew Ii(t)));return this.gl={vl:e,pl:r},r}Ji(){var t,i,n,s;const e=null!==(n=null===(i=(t=this.kl).timeAxisViews)||void 0===i?void 0:i.call(t))&&void 0!==n?n:[];if((null===(s=this.Ml)||void 0===s?void 0:s.vl)===e)return this.Ml.pl;const r=this.Nr.$t().St(),h=e.map((t=>new Ni(t,r)));return this.Ml={vl:e,pl:h},h}Tn(){var t,i,n,s;const e=null!==(n=null===(i=(t=this.kl).priceAxisViews)||void 0===i?void 0:i.call(t))&&void 0!==n?n:[];if((null===(s=this.xl)||void 0===s?void 0:s.vl)===e)return this.xl.pl;const r=this.Nr.Dt(),h=e.map((t=>new Fi(t,r)));return this.xl={vl:e,pl:h},h}Tl(){var t,i,n,s;const e=null!==(n=null===(i=(t=this.kl).priceAxisPaneViews)||void 0===i?void 0:i.call(t))&&void 0!==n?n:[];if((null===(s=this.Sl)||void 0===s?void 0:s.vl)===e)return this.Sl.pl;const r=e.map((t=>new Ii(t)));return this.Sl={vl:e,pl:r},r}Pl(){var t,i,n,s;const e=null!==(n=null===(i=(t=this.kl).timeAxisPaneViews)||void 0===i?void 0:i.call(t))&&void 0!==n?n:[];if((null===(s=this.yl)||void 0===s?void 0:s.vl)===e)return this.yl.pl;const r=e.map((t=>new Ii(t)));return this.yl={vl:e,pl:r},r}Rl(t,i){var n,s,e;return null!==(e=null===(s=(n=this.kl).autoscaleInfo)||void 0===s?void 0:s.call(n,t,i))&&void 0!==e?e:null}pr(t,i){var n,s,e;return null!==(e=null===(s=(n=this.kl).hitTest)||void 0===s?void 0:s.call(n,t,i))&&void 0!==e?e:null}}function ji(t,i,n,s){t.forEach((t=>{i(t).forEach((t=>{t.ml()===n&&s.push(t)}))}))}function Hi(t){return t.Cn()}function $i(t){return t.Tl()}function Ui(t){return t.Pl()}class qi extends Ri{constructor(t,i,n,s,e){super(t),this.Et=new Vi,this.Eh=new Mi(this),this.Dl=[],this.Ol=new si(this),this.Al=null,this.Bl=null,this.Vl=[],this.zl=[],this.El=null,this.Il=[],this._n=i,this.Ll=n;const r=new xi(this);this.en=[r],this.Ih=new ti(r,this,t),"Area"!==n&&"Line"!==n&&"Baseline"!==n||(this.Al=new ai(this)),this.Nl(),this.Fl(e)}S(){null!==this.El&&clearTimeout(this.El)}oh(t){return this._n.priceLineColor||t}Ur(t){const i={qr:!0},n=this.Dt();if(this.$t().St().Li()||n.Li()||this.Et.Li())return i;const s=this.$t().St().qs(),e=this.Ct();if(null===s||null===e)return i;let r,h;if(t){const t=this.Et.Gh();if(null===t)return i;r=t,h=t.ie}else{const t=this.Et.il(s.ui(),-1);if(null===t)return i;if(r=this.Et.Uh(t.ie),null===r)return i;h=t.ie}const l=r.Ot[3],a=this.js().Ws(h,{Ot:r}),o=n.Rt(l,e.Ot);return{qr:!1,_t:l,Zt:n.Ni(l,e.Ot),ph:n.Wl(l),mh:n.jl(l,e.Ot),O:a.oe,Si:o,ie:h}}js(){return null!==this.Bl||(this.Bl=new Oi(this)),this.Bl}W(){return this._n}Lh(t){const i=t.priceScaleId;void 0!==i&&i!==this._n.priceScaleId&&this.$t().Hl(this,i),C(this._n,t),void 0!==t.priceFormat&&(this.Nl(),this.$t().$l()),this.$t().Ul(this),this.$t().ql(),this.mn.bt("options")}J(t,i){this.Et.J(t),this.Yl(),this.mn.bt("data"),this.un.bt("data"),null!==this.Al&&(i&&i.Xl?this.Al.Wr():0===t.length&&this.Al.Fr());const n=this.$t()._r(this);this.$t().Kl(n),this.$t().Ul(this),this.$t().ql(),this.$t().Nh()}Zl(t){this.Vl=t,this.Yl();const i=this.$t()._r(this);this.un.bt("data"),this.$t().Kl(i),this.$t().Ul(this),this.$t().ql(),this.$t().Nh()}Gl(){return this.Vl}lh(){return this.zl}Jl(t){const i=new Pi(this,t);return this.Dl.push(i),this.$t().Ul(this),i}Ql(t){const i=this.Dl.indexOf(t);-1!==i&&this.Dl.splice(i,1),this.$t().Ul(this)}Yh(){return this.Ll}Ct(){const t=this.ta();return null===t?null:{Ot:t.Ot[3],ia:t.ot}}ta(){const t=this.$t().St().qs();if(null===t)return null;const i=t.Rs();return this.Et.il(i,1)}Bn(){return this.Et}ah(t){const i=this.Et.Uh(t);return null===i?null:"Bar"===this.Ll||"Candlestick"===this.Ll||"Custom"===this.Ll?{me:i.Ot[0],be:i.Ot[1],we:i.Ot[2],ge:i.Ot[3]}:i.Ot[3]}na(t){const i=[];ji(this.Il,Hi,"top",i);const n=this.Al;return null!==n&&n.kt()?(null===this.El&&n.Hr()&&(this.El=setTimeout((()=>{this.El=null,this.$t().sa()}),0)),n.jr(),i.push(n),i):i}Cn(){const t=[];this.ea()||t.push(this.Ol),t.push(this.mn,this.Eh,this.un);const i=this.Dl.map((t=>t.Fh()));return t.push(...i),ji(this.Il,Hi,"normal",t),t}ra(){return this.ha(Hi,"bottom")}la(t){return this.ha($i,t)}aa(t){return this.ha(Ui,t)}oa(t,i){return this.Il.map((n=>n.pr(t,i))).filter((t=>null!==t))}Gi(t){return[this.Ih,...this.Dl.map((t=>t.Wh()))]}Tn(t,i){if(i!==this.qi&&!this.ea())return[];const n=[...this.en];for(const t of this.Dl)n.push(t.jh());return this.Il.forEach((t=>{n.push(...t.Tn())})),n}Ji(){const t=[];return this.Il.forEach((i=>{t.push(...i.Ji())})),t}Rl(t,i){if(void 0!==this._n.autoscaleInfoProvider){const n=this._n.autoscaleInfoProvider((()=>{const n=this._a(t,i);return null===n?null:n.Th()}));return ki.Ph(n)}return this._a(t,i)}ua(){return this._n.priceFormat.minMove}ca(){return this.da}Rn(){var t;this.mn.bt(),this.un.bt();for(const t of this.en)t.bt();for(const t of this.Dl)t.bt();this.Eh.bt(),this.Ol.bt(),null===(t=this.Al)||void 0===t||t.bt(),this.Il.forEach((t=>t.Rn()))}Dt(){return f(super.Dt())}yt(t){if(!(("Line"===this.Ll||"Area"===this.Ll||"Baseline"===this.Ll)&&this._n.crosshairMarkerVisible))return null;const i=this.Et.Uh(t);if(null===i)return null;return{_t:i.Ot[3],ht:this.fa(),At:this.va(),Pt:this.pa(),Tt:this.ma(t)}}_h(){return this._n.title}kt(){return this._n.visible}ba(t){this.Il.push(new Wi(t,this))}wa(t){this.Il=this.Il.filter((i=>i.Cl()!==t))}ga(){if(this.mn instanceof qt!=!1)return t=>this.mn.Le(t)}Ma(){if(this.mn instanceof qt!=!1)return t=>this.mn.Ne(t)}ea(){return!ht(this.Dt().xa())}_a(t,i){if(!P(t)||!P(i)||this.Et.Li())return null;const n="Line"===this.Ll||"Area"===this.Ll||"Baseline"===this.Ll||"Histogram"===this.Ll?[3]:[2,1],s=this.Et.sl(t,i,n);let e=null!==s?new yi(s.ul,s.cl):null;if("Histogram"===this.Yh()){const t=this._n.base,i=new yi(t,t);e=null!==e?e.Jn(i):i}let r=this.un.hh();return this.Il.forEach((n=>{const s=n.Rl(t,i);if(null==s?void 0:s.priceRange){const t=new yi(s.priceRange.minValue,s.priceRange.maxValue);e=null!==e?e.Jn(t):t}var h,l,a,o;(null==s?void 0:s.margins)&&(h=r,l=s.margins,r={above:Math.max(null!==(a=null==h?void 0:h.above)&&void 0!==a?a:0,l.above),below:Math.max(null!==(o=null==h?void 0:h.below)&&void 0!==o?o:0,l.below)})})),new ki(e,r)}fa(){switch(this.Ll){case"Line":case"Area":case"Baseline":return this._n.crosshairMarkerRadius}return 0}va(){switch(this.Ll){case"Line":case"Area":case"Baseline":{const t=this._n.crosshairMarkerBorderColor;if(0!==t.length)return t}}return null}pa(){switch(this.Ll){case"Line":case"Area":case"Baseline":return this._n.crosshairMarkerBorderWidth}return 0}ma(t){switch(this.Ll){case"Line":case"Area":case"Baseline":{const t=this._n.crosshairMarkerBackgroundColor;if(0!==t.length)return t}}return this.js().Ws(t).oe}Nl(){switch(this._n.priceFormat.type){case"custom":this.da={format:this._n.priceFormat.formatter};break;case"volume":this.da=new ct(this._n.priceFormat.precision);break;case"percent":this.da=new ut(this._n.priceFormat.precision);break;default:{const t=Math.pow(10,this._n.priceFormat.precision);this.da=new _t(t,this._n.priceFormat.minMove*t)}}null!==this.qi&&this.qi.Sa()}Yl(){const t=this.$t().St();if(!t.ya()||this.Et.Li())return void(this.zl=[]);const i=f(this.Et.Jh());this.zl=this.Vl.map(((n,s)=>{const e=f(t.ka(n.time,!0)),r=et instanceof qi)).reduce(((t,s)=>{if(n.ur(s)||!s.kt())return t;const e=s.Dt(),r=s.Bn();if(e.Li()||!r.Yr(i))return t;const h=r.Uh(i);if(null===h)return t;const l=v(s.Ct());return t.concat([e.Rt(h.Ot[3],l.Ot)])}),[]);if(0===l.length)return s;l.sort(((t,i)=>Math.abs(t-h)-Math.abs(i-h)));const a=l[0];return s=e.fn(a,r),s}}class Xi extends L{constructor(){super(...arguments),this.Et=null}J(t){this.Et=t}Z({context:t,bitmapSize:i,horizontalPixelRatio:n,verticalPixelRatio:s}){if(null===this.Et)return;const e=Math.max(1,Math.floor(n));t.lineWidth=e,function(t,i){t.save(),t.lineWidth%2&&t.translate(.5,.5),i(),t.restore()}(t,(()=>{const r=f(this.Et);if(r.Pa){t.strokeStyle=r.Ra,_(t,r.Da),t.beginPath();for(const s of r.Oa){const r=Math.round(s.Aa*n);t.moveTo(r,-e),t.lineTo(r,i.height+e)}t.stroke()}if(r.Ba){t.strokeStyle=r.Va,_(t,r.za),t.beginPath();for(const n of r.Ea){const r=Math.round(n.Aa*s);t.moveTo(-e,r),t.lineTo(i.width+e,r)}t.stroke()}}))}}class Ki{constructor(t){this.Wt=new Xi,this.ft=!0,this.Qi=t}bt(){this.ft=!0}gt(){if(this.ft){const t=this.Qi.$t().W().grid,i={Ba:t.horzLines.visible,Pa:t.vertLines.visible,Va:t.horzLines.color,Ra:t.vertLines.color,za:t.horzLines.style,Da:t.vertLines.style,Ea:this.Qi.dn().Ia(),Oa:(this.Qi.$t().St().Ia()||[]).map((t=>({Aa:t.coord})))};this.Wt.J(i),this.ft=!1}return this.Wt}}class Zi{constructor(t){this.mn=new Ki(t)}Fh(){return this.mn}}const Gi={La:4,Na:1e-4};function Ji(t,i){const n=100*(t-i)/i;return i<0?-n:n}function Qi(t,i){const n=Ji(t.xh(),i),s=Ji(t.Sh(),i);return new yi(n,s)}function tn(t,i){const n=100*(t-i)/i+100;return i<0?-n:n}function nn(t,i){const n=tn(t.xh(),i),s=tn(t.Sh(),i);return new yi(n,s)}function sn(t,i){const n=Math.abs(t);if(n<1e-15)return 0;const s=Math.log10(n+i.Na)+i.La;return t<0?-s:s}function en(t,i){const n=Math.abs(t);if(n<1e-15)return 0;const s=Math.pow(10,n-i.La)-i.Na;return t<0?-s:s}function rn(t,i){if(null===t)return null;const n=sn(t.xh(),i),s=sn(t.Sh(),i);return new yi(n,s)}function hn(t,i){if(null===t)return null;const n=en(t.xh(),i),s=en(t.Sh(),i);return new yi(n,s)}function ln(t){if(null===t)return Gi;const i=Math.abs(t.Sh()-t.xh());if(i>=1||i<1e-15)return Gi;const n=Math.ceil(Math.abs(Math.log10(i))),s=Gi.La+n;return{La:s,Na:1/Math.pow(10,s)}}class an{constructor(t,i){if(this.Fa=t,this.Wa=i,function(t){if(t<0)return!1;for(let i=t;i>1;i/=10)if(i%10!=0)return!1;return!0}(this.Fa))this.ja=[2,2.5,2];else{this.ja=[];for(let t=this.Fa;1!==t;){if(t%2==0)this.ja.push(2),t/=2;else{if(t%5!=0)throw new Error("unexpected base");this.ja.push(2,2.5),t/=5}if(this.ja.length>100)throw new Error("something wrong with base")}}}Ha(t,i,n){const s=0===this.Fa?0:1/this.Fa;let e=Math.pow(10,Math.max(0,Math.ceil(Math.log10(t-i)))),r=0,h=this.Wa[0];for(;;){const t=Mt(e,s,1e-14)&&e>s+1e-14,i=Mt(e,n*h,1e-14),l=Mt(e,1,1e-14);if(!(t&&i&&l))break;e/=h,h=this.Wa[++r%this.Wa.length]}if(e<=s+1e-14&&(e=s),e=Math.max(1,e),this.ja.length>0&&(l=e,a=1,o=1e-14,Math.abs(l-a)s+1e-14;)e/=h,h=this.ja[++r%this.ja.length];var l,a,o;return e}}class on{constructor(t,i,n,s){this.$a=[],this.Ei=t,this.Fa=i,this.Ua=n,this.qa=s}Ha(t,i){if(t=o?1:-1;let d=null,f=0;for(let n=a-u;n>o;n-=_){const s=this.qa(n,i,!0);null!==d&&Math.abs(s-d)l||(ff(t.Xi())-f(i.Xi())))}var un;!function(t){t[t.Normal=0]="Normal",t[t.Logarithmic=1]="Logarithmic",t[t.Percentage=2]="Percentage",t[t.IndexedTo100=3]="IndexedTo100"}(un||(un={}));const cn=new ut,dn=new _t(100,1);class fn{constructor(t,i,n,s){this.Qa=0,this.io=null,this.Rh=null,this.no=null,this.so={eo:!1,ro:null},this.ho=0,this.lo=0,this.ao=new k,this.oo=new k,this._o=[],this.uo=null,this.co=null,this.do=null,this.fo=null,this.da=dn,this.vo=ln(null),this.po=t,this._n=i,this.mo=n,this.bo=s,this.wo=new on(this,100,this.Mo.bind(this),this.xo.bind(this))}xa(){return this.po}W(){return this._n}Lh(t){if(C(this._n,t),this.Sa(),void 0!==t.mode&&this.So({Sr:t.mode}),void 0!==t.scaleMargins){const i=d(t.scaleMargins.top),n=d(t.scaleMargins.bottom);if(i<0||i>1)throw new Error(`Invalid top margin - expect value between 0 and 1, given=${i}`);if(n<0||n>1)throw new Error(`Invalid bottom margin - expect value between 0 and 1, given=${n}`);if(i+n>1)throw new Error(`Invalid margins - sum of margins must be less than 1, given=${i+n}`);this.yo(),this.co=null}}ko(){return this._n.autoScale}Ja(){return 1===this._n.mode}fh(){return 2===this._n.mode}Co(){return 3===this._n.mode}Sr(){return{Nn:this._n.autoScale,To:this._n.invertScale,Sr:this._n.mode}}So(t){const i=this.Sr();let n=null;void 0!==t.Nn&&(this._n.autoScale=t.Nn),void 0!==t.Sr&&(this._n.mode=t.Sr,2!==t.Sr&&3!==t.Sr||(this._n.autoScale=!0),this.so.eo=!1),1===i.Sr&&t.Sr!==i.Sr&&(!function(t,i){if(null===t)return!1;const n=en(t.xh(),i),s=en(t.Sh(),i);return isFinite(n)&&isFinite(s)}(this.Rh,this.vo)?this._n.autoScale=!0:(n=hn(this.Rh,this.vo),null!==n&&this.Po(n))),1===t.Sr&&t.Sr!==i.Sr&&(n=rn(this.Rh,this.vo),null!==n&&this.Po(n));const s=i.Sr!==this._n.mode;s&&(2===i.Sr||this.fh())&&this.Sa(),s&&(3===i.Sr||this.Co())&&this.Sa(),void 0!==t.To&&i.To!==t.To&&(this._n.invertScale=t.To,this.Ro()),this.oo.m(i,this.Sr())}Do(){return this.oo}P(){return this.mo.fontSize}Vt(){return this.Qa}Oo(t){this.Qa!==t&&(this.Qa=t,this.yo(),this.co=null)}Ao(){if(this.io)return this.io;const t=this.Vt()-this.Bo()-this.Vo();return this.io=t,t}Oh(){return this.zo(),this.Rh}Po(t,i){const n=this.Rh;(i||null===n&&null!==t||null!==n&&!n.gh(t))&&(this.co=null,this.Rh=t)}Li(){return this.zo(),0===this.Qa||!this.Rh||this.Rh.Li()}Eo(t){return this.To()?t:this.Vt()-1-t}Rt(t,i){return this.fh()?t=Ji(t,i):this.Co()&&(t=tn(t,i)),this.xo(t,i)}Gs(t,i,n){this.zo();const s=this.Vo(),e=f(this.Oh()),r=e.xh(),h=e.Sh(),l=this.Ao()-1,a=this.To(),o=l/(h-r),_=void 0===n?0:n.from,u=void 0===n?t.length:n.to,c=this.Io();for(let n=_;nt.Rn()))}Sa(){this.co=null;const t=this.Jo();let i=100;null!==t&&(i=Math.round(1/t.ua())),this.da=dn,this.fh()?(this.da=cn,i=100):this.Co()?(this.da=new _t(100,1),i=100):null!==t&&(this.da=t.ca()),this.wo=new on(this,i,this.Mo.bind(this),this.xo.bind(this)),this.wo.Xa()}Wo(){this.uo=null}Jo(){return this._o[0]||null}Bo(){return this.To()?this._n.scaleMargins.bottom*this.Vt()+this.lo:this._n.scaleMargins.top*this.Vt()+this.ho}Vo(){return this.To()?this._n.scaleMargins.top*this.Vt()+this.ho:this._n.scaleMargins.bottom*this.Vt()+this.lo}zo(){this.so.eo||(this.so.eo=!0,this.i_())}yo(){this.io=null}xo(t,i){if(this.zo(),this.Li())return 0;t=this.Ja()&&t?sn(t,this.vo):t;const n=f(this.Oh()),s=this.Vo()+(this.Ao()-1)*(t-n.xh())/n.yh();return this.Eo(s)}Mo(t,i){if(this.zo(),this.Li())return 0;const n=this.Eo(t),s=f(this.Oh()),e=s.xh()+s.yh()*((n-this.Vo())/(this.Ao()-1));return this.Ja()?en(e,this.vo):e}Ro(){this.co=null,this.wo.Xa()}i_(){const t=this.so.ro;if(null===t)return;let i=null;const n=this.Qo();let s=0,e=0;for(const r of n){if(!r.kt())continue;const n=r.Ct();if(null===n)continue;const h=r.Rl(t.Rs(),t.ui());let l=h&&h.Oh();if(null!==l){switch(this._n.mode){case 1:l=rn(l,this.vo);break;case 2:l=Qi(l,n.Ot);break;case 3:l=nn(l,n.Ot)}if(i=null===i?l:i.Jn(f(l)),null!==h){const t=h.Ah();null!==t&&(s=Math.max(s,t.above),e=Math.max(s,t.below))}}}if(s===this.ho&&e===this.lo||(this.ho=s,this.lo=e,this.co=null,this.yo()),null!==i){if(i.xh()===i.Sh()){const t=this.Jo(),n=5*(null===t||this.fh()||this.Co()?1:t.ua());this.Ja()&&(i=hn(i,this.vo)),i=new yi(i.xh()-n,i.Sh()+n),this.Ja()&&(i=rn(i,this.vo))}if(this.Ja()){const t=hn(i,this.vo),n=ln(t);if(r=n,h=this.vo,r.La!==h.La||r.Na!==h.Na){const s=null!==this.no?hn(this.no,this.vo):null;this.vo=n,i=rn(t,n),null!==s&&(this.no=rn(s,n))}}this.Po(i)}else null===this.Rh&&(this.Po(new yi(-.5,.5)),this.vo=ln(null));var r,h;this.so.eo=!0}Io(){return this.fh()?Ji:this.Co()?tn:this.Ja()?t=>sn(t,this.vo):null}n_(t,i,n){return void 0===i?(void 0===n&&(n=this.ca()),n.format(t)):i(t)}zh(t,i){return this.n_(t,this.bo.priceFormatter,i)}Go(t,i){return this.n_(t,this.bo.percentageFormatter,i)}}class vn{constructor(t,i){this._o=[],this.s_=new Map,this.Qa=0,this.e_=0,this.r_=1e3,this.uo=null,this.h_=new k,this.wl=t,this.Hi=i,this.l_=new Zi(this);const n=i.W();this.a_=this.o_("left",n.leftPriceScale),this.__=this.o_("right",n.rightPriceScale),this.a_.Do().l(this.u_.bind(this,this.a_),this),this.__.Do().l(this.u_.bind(this,this.__),this),this.c_(n)}c_(t){if(t.leftPriceScale&&this.a_.Lh(t.leftPriceScale),t.rightPriceScale&&this.__.Lh(t.rightPriceScale),t.localization&&(this.a_.Sa(),this.__.Sa()),t.overlayPriceScales){const i=Array.from(this.s_.values());for(const n of i){const i=f(n[0].Dt());i.Lh(t.overlayPriceScales),t.localization&&i.Sa()}}}d_(t){switch(t){case"left":return this.a_;case"right":return this.__}return this.s_.has(t)?d(this.s_.get(t))[0].Dt():null}S(){this.$t().f_().p(this),this.a_.Do().p(this),this.__.Do().p(this),this._o.forEach((t=>{t.S&&t.S()})),this.h_.m()}v_(){return this.r_}p_(t){this.r_=t}$t(){return this.Hi}ji(){return this.e_}Vt(){return this.Qa}m_(t){this.e_=t,this.b_()}Oo(t){this.Qa=t,this.a_.Oo(t),this.__.Oo(t),this._o.forEach((i=>{if(this.ur(i)){const n=i.Dt();null!==n&&n.Oo(t)}})),this.b_()}Ta(){return this._o}ur(t){const i=t.Dt();return null===i||this.a_!==i&&this.__!==i}Fo(t,i,n){const s=void 0!==n?n:this.g_().w_+1;this.M_(t,i,s)}jo(t){const i=this._o.indexOf(t);c(-1!==i,"removeDataSource: invalid data source"),this._o.splice(i,1);const n=f(t.Dt()).xa();if(this.s_.has(n)){const i=d(this.s_.get(n)),s=i.indexOf(t);-1!==s&&(i.splice(s,1),0===i.length&&this.s_.delete(n))}const s=t.Dt();s&&s.Ta().indexOf(t)>=0&&s.jo(t),null!==s&&(s.Wo(),this.x_(s)),this.uo=null}dr(t){return t===this.a_?"left":t===this.__?"right":"overlay"}S_(){return this.a_}y_(){return this.__}k_(t,i){t.Uo(i)}C_(t,i){t.qo(i),this.b_()}T_(t){t.Yo()}P_(t,i){t.Xo(i)}R_(t,i){t.Ko(i),this.b_()}D_(t){t.Zo()}b_(){this._o.forEach((t=>{t.Rn()}))}dn(){let t=null;return this.Hi.W().rightPriceScale.visible&&0!==this.__.Ta().length?t=this.__:this.Hi.W().leftPriceScale.visible&&0!==this.a_.Ta().length?t=this.a_:0!==this._o.length&&(t=this._o[0].Dt()),null===t&&(t=this.__),t}cr(){let t=null;return this.Hi.W().rightPriceScale.visible?t=this.__:this.Hi.W().leftPriceScale.visible&&(t=this.a_),t}x_(t){null!==t&&t.ko()&&this.O_(t)}A_(t){const i=this.wl.qs();t.So({Nn:!0}),null!==i&&t.t_(i),this.b_()}B_(){this.O_(this.a_),this.O_(this.__)}V_(){this.x_(this.a_),this.x_(this.__),this._o.forEach((t=>{this.ur(t)&&this.x_(t.Dt())})),this.b_(),this.Hi.Nh()}No(){return null===this.uo&&(this.uo=_n(this._o)),this.uo}z_(){return this.h_}E_(){return this.l_}O_(t){const i=t.Qo();if(i&&i.length>0&&!this.wl.Li()){const i=this.wl.qs();null!==i&&t.t_(i)}t.Rn()}g_(){const t=this.No();if(0===t.length)return{I_:0,w_:0};let i=0,n=0;for(let s=0;sn&&(n=e))}return{I_:i,w_:n}}M_(t,i,n){let s=this.d_(i);if(null===s&&(s=this.o_(i,this.Hi.W().overlayPriceScales)),this._o.push(t),!ht(i)){const n=this.s_.get(i)||[];n.push(t),this.s_.set(i,n)}s.Fo(t),t.Zi(s),t.Ki(n),this.x_(s),this.uo=null}u_(t,i,n){i.Sr!==n.Sr&&this.O_(t)}o_(t,i){const n=Object.assign({visible:!0,autoScale:!0},O(i)),s=new fn(t,n,this.Hi.W().layout,this.Hi.W().localization);return s.Oo(this.Vt()),s}}class pn{constructor(t,i,n=50){this.Ye=0,this.Xe=1,this.Ke=1,this.Ge=new Map,this.Ze=new Map,this.L_=t,this.N_=i,this.Je=n}F_(t){const i=t.time,n=this.N_.cacheKey(i),s=this.Ge.get(n);if(void 0!==s)return s.W_;if(this.Ye===this.Je){const t=this.Ze.get(this.Ke);this.Ze.delete(this.Ke),this.Ge.delete(d(t)),this.Ke++,this.Ye--}const e=this.L_(t);return this.Ge.set(n,{W_:e,nr:this.Xe}),this.Ze.set(this.Xe,n),this.Ye++,this.Xe++,e}}class mn{constructor(t,i){c(t<=i,"right should be >= left"),this.j_=t,this.H_=i}Rs(){return this.j_}ui(){return this.H_}U_(){return this.H_-this.j_+1}Yr(t){return this.j_<=t&&t<=this.H_}gh(t){return this.j_===t.Rs()&&this.H_===t.ui()}}function bn(t,i){return null===t||null===i?t===i:t.gh(i)}class wn{constructor(){this.q_=new Map,this.Ge=null,this.Y_=!1}X_(t){this.Y_=t,this.Ge=null}K_(t,i){this.Z_(i),this.Ge=null;for(let n=i;n{t<=n[0].index?i.push(s):n.splice(Rt(n,t,(i=>i.indexi-t))){if(!this.q_.get(n))continue;const s=i;i=[];const e=s.length;let r=0;const h=d(this.q_.get(n)),l=h.length;let a=1/0,o=-1/0;for(let n=0;n=t&&_-o>=t)i.push(l),o=_;else if(this.Y_)return s}for(;ri.weight?t:i}class xn{constructor(t,i,n,s){this.e_=0,this.eu=null,this.ru=[],this.fo=null,this.do=null,this.hu=new wn,this.lu=new Map,this.au=gn.su(),this.ou=!0,this._u=new k,this.uu=new k,this.cu=new k,this.du=null,this.fu=null,this.vu=[],this._n=i,this.bo=n,this.pu=i.rightOffset,this.mu=i.barSpacing,this.Hi=t,this.N_=s,this.bu(),this.hu.X_(i.uniformDistribution)}W(){return this._n}wu(t){C(this.bo,t),this.gu(),this.bu()}Lh(t,i){var n;C(this._n,t),this._n.fixLeftEdge&&this.Mu(),this._n.fixRightEdge&&this.xu(),void 0!==t.barSpacing&&this.Hi.Kn(t.barSpacing),void 0!==t.rightOffset&&this.Hi.Zn(t.rightOffset),void 0!==t.minBarSpacing&&this.Hi.Kn(null!==(n=t.barSpacing)&&void 0!==n?n:this.mu),this.gu(),this.bu(),this.cu.m()}vn(t){var i,n;return null!==(n=null===(i=this.ru[t])||void 0===i?void 0:i.time)&&void 0!==n?n:null}$i(t){var i;return null!==(i=this.ru[t])&&void 0!==i?i:null}ka(t,i){if(this.ru.length<1)return null;if(this.N_.key(t)>this.N_.key(this.ru[this.ru.length-1].time))return i?this.ru.length-1:null;const n=Rt(this.ru,this.N_.key(t),((t,i)=>this.N_.key(t.time)0}qs(){return this.Su(),this.au.iu()}yu(){return this.Su(),this.au.nu()}ku(){const t=this.qs();if(null===t)return null;const i={from:t.Rs(),to:t.ui()};return this.Cu(i)}Cu(t){const i=Math.round(t.from),n=Math.round(t.to),s=f(this.Tu()),e=f(this.Pu());return{from:f(this.$i(Math.max(s,i))),to:f(this.$i(Math.min(e,n)))}}Ru(t){return{from:f(this.ka(t.from,!0)),to:f(this.ka(t.to,!0))}}ji(){return this.e_}m_(t){if(!isFinite(t)||t<=0)return;if(this.e_===t)return;const i=this.yu(),n=this.e_;if(this.e_=t,this.ou=!0,this._n.lockVisibleTimeRangeOnResize&&0!==n){const i=this.mu*t/n;this.mu=i}if(this._n.fixLeftEdge&&null!==i&&i.Rs()<=0){const i=n-t;this.pu-=Math.round(i/this.mu)+1,this.ou=!0}this.Du(),this.Ou()}zt(t){if(this.Li()||!P(t))return 0;const i=this.Au()+this.pu-t;return this.e_-(i+.5)*this.mu-1}Zs(t,i){const n=this.Au(),s=void 0===i?0:i.from,e=void 0===i?t.length:i.to;for(let i=s;ii/2&&!o?n.needAlignCoordinate=!1:n.needAlignCoordinate=_&&t.index<=l||u&&t.index>=a,c++}return this.vu.length=c,this.fu=this.vu,this.vu}Fu(){this.ou=!0,this.Kn(this._n.barSpacing),this.Zn(this._n.rightOffset)}Wu(t){this.ou=!0,this.eu=t,this.Ou(),this.Mu()}ju(t,i){const n=this.Vu(t),s=this.ee(),e=s+i*(s/10);this.Kn(e),this._n.rightBarStaysOnScroll||this.Zn(this.Iu()+(n-this.Vu(t)))}Uo(t){this.fo&&this.Zo(),null===this.do&&null===this.du&&(this.Li()||(this.do=t,this.Hu()))}qo(t){if(null===this.du)return;const i=gt(this.e_-t,0,this.e_),n=gt(this.e_-f(this.do),0,this.e_);0!==i&&0!==n&&this.Kn(this.du.ee*i/n)}Yo(){null!==this.do&&(this.do=null,this.$u())}Xo(t){null===this.fo&&null===this.du&&(this.Li()||(this.fo=t,this.Hu()))}Ko(t){if(null===this.fo)return;const i=(this.fo-t)/this.ee();this.pu=f(this.du).Iu+i,this.ou=!0,this.Ou()}Zo(){null!==this.fo&&(this.fo=null,this.$u())}Uu(){this.qu(this._n.rightOffset)}qu(t,i=400){if(!isFinite(t))throw new RangeError("offset is required and must be finite number");if(!isFinite(i)||i<=0)throw new RangeError("animationDuration (optional) must be finite positive number");const n=this.pu,s=performance.now();this.Hi.qn({Yu:t=>(t-s)/i>=1,Xu:e=>{const r=(e-s)/i;return r>=1?t:n+(t-n)*r}})}bt(t,i){this.ou=!0,this.ru=t,this.hu.K_(t,i),this.Ou()}Ku(){return this._u}Zu(){return this.uu}Gu(){return this.cu}Au(){return this.eu||0}Ju(t){const i=t.U_();this.Eu(this.e_/i),this.pu=t.ui()-this.Au(),this.Ou(),this.ou=!0,this.Hi.zu(),this.Hi.Nh()}Qu(){const t=this.Tu(),i=this.Pu();null!==t&&null!==i&&this.Ju(new mn(t,i+this._n.rightOffset))}tc(t){const i=new mn(t.from,t.to);this.Ju(i)}Ui(t){return void 0!==this.bo.timeFormatter?this.bo.timeFormatter(t.originalTime):this.N_.formatHorzItem(t.time)}Lu(){const{handleScroll:t,handleScale:i}=this.Hi.W();return!(t.horzTouchDrag||t.mouseWheel||t.pressedMouseMove||t.vertTouchDrag||i.axisDoubleClickReset.time||i.axisPressedMouseMove.time||i.mouseWheel||i.pinch)}Tu(){return 0===this.ru.length?null:0}Pu(){return 0===this.ru.length?null:this.ru.length-1}ic(t){return(this.e_-1-t)/this.mu}Vu(t){const i=this.ic(t),n=this.Au()+this.pu-i;return Math.round(1e6*n)/1e6}Eu(t){const i=this.mu;this.mu=t,this.Du(),i!==this.mu&&(this.ou=!0,this.nc())}Su(){if(!this.ou)return;if(this.ou=!1,this.Li())return void this.sc(gn.su());const t=this.Au(),i=this.e_/this.mu,n=this.pu+t,s=new mn(n-i+1,n);this.sc(new gn(s))}Du(){const t=this.ec();if(this.mut&&(this.mu=t,this.ou=!0)}}ec(){return this._n.fixLeftEdge&&this._n.fixRightEdge&&0!==this.ru.length?this.e_/this.ru.length:this._n.minBarSpacing}Ou(){const t=this.rc();this.pu>t&&(this.pu=t,this.ou=!0);const i=this.hc();null!==i&&this.puthis.lc(t)),this.N_),this.lu.set(t.weight,i)),i.F_(t)}lc(t){return this.N_.formatTickmark(t,this.bo)}sc(t){const i=this.au;this.au=t,bn(i.iu(),this.au.iu())||this._u.m(),bn(i.nu(),this.au.nu())||this.uu.m(),this.nc()}nc(){this.fu=null}gu(){this.nc(),this.lu.clear()}bu(){this.N_.updateFormatter(this.bo)}Mu(){if(!this._n.fixLeftEdge)return;const t=this.Tu();if(null===t)return;const i=this.qs();if(null===i)return;const n=i.Rs()-t;if(n<0){const t=this.pu-n-1;this.Zn(t)}this.Du()}xu(){this.Ou(),this.Du()}}class Sn{K(t,i,n){t.useMediaCoordinateSpace((t=>this.Z(t,i,n)))}fl(t,i,n){t.useMediaCoordinateSpace((t=>this.ac(t,i,n)))}ac(t,i,n){}}class yn extends Sn{constructor(t){super(),this.oc=new Map,this.Et=t}Z(t){}ac(t){if(!this.Et.kt)return;const{context:i,mediaSize:n}=t;let s=0;for(const t of this.Et._c){if(0===t.Zt.length)continue;i.font=t.R;const e=this.uc(i,t.Zt);e>n.width?t.ju=n.width/e:t.ju=1,s+=t.cc*t.ju}let e=0;switch(this.Et.dc){case"top":e=0;break;case"center":e=Math.max((n.height-s)/2,0);break;case"bottom":e=Math.max(n.height-s,0)}i.fillStyle=this.Et.O;for(const t of this.Et._c){i.save();let s=0;switch(this.Et.fc){case"left":i.textAlign="left",s=t.cc/2;break;case"center":i.textAlign="center",s=n.width/2;break;case"right":i.textAlign="right",s=n.width-1-t.cc/2}i.translate(s,e),i.textBaseline="top",i.font=t.R,i.scale(t.ju,t.ju),i.fillText(t.Zt,0,t.vc),i.restore(),e+=t.cc*t.ju}}uc(t,i){const n=this.mc(t.font);let s=n.get(i);return void 0===s&&(s=t.measureText(i).width,n.set(i,s)),s}mc(t){let i=this.oc.get(t);return void 0===i&&(i=new Map,this.oc.set(t,i)),i}}class kn{constructor(t){this.ft=!0,this.Ft={kt:!1,O:"",_c:[],dc:"center",fc:"center"},this.Wt=new yn(this.Ft),this.jt=t}bt(){this.ft=!0}gt(){return this.ft&&(this.Mt(),this.ft=!1),this.Wt}Mt(){const t=this.jt.W(),i=this.Ft;i.kt=t.visible,i.kt&&(i.O=t.color,i.fc=t.horzAlign,i.dc=t.vertAlign,i._c=[{Zt:t.text,R:z(t.fontSize,t.fontFamily,t.fontStyle),cc:1.2*t.fontSize,vc:0,ju:0}])}}class Cn extends st{constructor(t,i){super(),this._n=i,this.mn=new kn(this)}Tn(){return[]}Cn(){return[this.mn]}W(){return this._n}Rn(){this.mn.bt()}}var Tn,Pn,Rn,Dn,On;!function(t){t[t.OnTouchEnd=0]="OnTouchEnd",t[t.OnNextTap=1]="OnNextTap"}(Tn||(Tn={}));class An{constructor(t,i,n){this.bc=[],this.wc=[],this.e_=0,this.gc=null,this.Mc=new k,this.xc=new k,this.Sc=null,this.yc=t,this._n=i,this.N_=n,this.kc=new E(this),this.wl=new xn(this,i.timeScale,this._n.localization,n),this.vt=new rt(this,i.crosshair),this.Cc=new Yi(i.crosshair),this.Tc=new Cn(this,i.watermark),this.Pc(),this.bc[0].p_(2e3),this.Rc=this.Dc(0),this.Oc=this.Dc(1)}$l(){this.Ac(lt.ns())}Nh(){this.Ac(lt.ts())}sa(){this.Ac(new lt(1))}Ul(t){const i=this.Bc(t);this.Ac(i)}Vc(){return this.gc}zc(t){const i=this.gc;this.gc=t,null!==i&&this.Ul(i.Ec),null!==t&&this.Ul(t.Ec)}W(){return this._n}Lh(t){C(this._n,t),this.bc.forEach((i=>i.c_(t))),void 0!==t.timeScale&&this.wl.Lh(t.timeScale),void 0!==t.localization&&this.wl.wu(t.localization),(t.leftPriceScale||t.rightPriceScale)&&this.Mc.m(),this.Rc=this.Dc(0),this.Oc=this.Dc(1),this.$l()}Ic(t,i){if("left"===t)return void this.Lh({leftPriceScale:i});if("right"===t)return void this.Lh({rightPriceScale:i});const n=this.Lc(t);null!==n&&(n.Dt.Lh(i),this.Mc.m())}Lc(t){for(const i of this.bc){const n=i.d_(t);if(null!==n)return{Ht:i,Dt:n}}return null}St(){return this.wl}Nc(){return this.bc}Fc(){return this.Tc}Wc(){return this.vt}jc(){return this.xc}Hc(t,i){t.Oo(i),this.zu()}m_(t){this.e_=t,this.wl.m_(this.e_),this.bc.forEach((i=>i.m_(t))),this.zu()}Pc(t){const i=new vn(this.wl,this);void 0!==t?this.bc.splice(t,0,i):this.bc.push(i);const n=void 0===t?this.bc.length-1:t,s=lt.ns();return s.In(n,{Ln:0,Nn:!0}),this.Ac(s),i}k_(t,i,n){t.k_(i,n)}C_(t,i,n){t.C_(i,n),this.ql(),this.Ac(this.$c(t,2))}T_(t,i){t.T_(i),this.Ac(this.$c(t,2))}P_(t,i,n){i.ko()||t.P_(i,n)}R_(t,i,n){i.ko()||(t.R_(i,n),this.ql(),this.Ac(this.$c(t,2)))}D_(t,i){i.ko()||(t.D_(i),this.Ac(this.$c(t,2)))}A_(t,i){t.A_(i),this.Ac(this.$c(t,2))}Uc(t){this.wl.Uo(t)}qc(t,i){const n=this.St();if(n.Li()||0===i)return;const s=n.ji();t=Math.max(1,Math.min(t,s)),n.ju(t,i),this.zu()}Yc(t){this.Xc(0),this.Kc(t),this.Zc()}Gc(t){this.wl.qo(t),this.zu()}Jc(){this.wl.Yo(),this.Nh()}Xc(t){this.wl.Xo(t)}Kc(t){this.wl.Ko(t),this.zu()}Zc(){this.wl.Zo(),this.Nh()}wt(){return this.wc}Qc(t,i,n,s,e){this.vt.bn(t,i);let r=NaN,h=this.wl.Bu(t);const l=this.wl.qs();null!==l&&(h=Math.min(Math.max(l.Rs(),h),l.ui()));const a=s.dn(),o=a.Ct();null!==o&&(r=a.fn(i,o)),r=this.Cc.Ca(r,h,s),this.vt.xn(h,r,s),this.sa(),e||this.xc.m(this.vt.xt(),{x:t,y:i},n)}td(t,i,n){const s=n.dn(),e=s.Ct(),r=s.Rt(t,f(e)),h=this.wl.ka(i,!0),l=this.wl.zt(f(h));this.Qc(l,r,null,n,!0)}nd(t){this.Wc().yn(),this.sa(),t||this.xc.m(null,null,null)}ql(){const t=this.vt.Ht();if(null!==t){const i=this.vt.gn(),n=this.vt.Mn();this.Qc(i,n,null,t)}this.vt.Rn()}sd(t,i,n){const s=this.wl.vn(0);void 0!==i&&void 0!==n&&this.wl.bt(i,n);const e=this.wl.vn(0),r=this.wl.Au(),h=this.wl.qs();if(null!==h&&null!==s&&null!==e){const i=h.Yr(r),l=this.N_.key(s)>this.N_.key(e),a=null!==t&&t>r&&!l,o=this.wl.W().allowShiftVisibleRangeOnWhitespaceReplacement,_=i&&(!(void 0===n)||o)&&this.wl.W().shiftVisibleRangeOnNewBar;if(a&&!_){const i=t-r;this.wl.Zn(this.wl.Iu()-i)}}this.wl.Wu(t)}Kl(t){null!==t&&t.V_()}_r(t){const i=this.bc.find((i=>i.No().includes(t)));return void 0===i?null:i}zu(){this.Tc.Rn(),this.bc.forEach((t=>t.V_())),this.ql()}S(){this.bc.forEach((t=>t.S())),this.bc.length=0,this._n.localization.priceFormatter=void 0,this._n.localization.percentageFormatter=void 0,this._n.localization.timeFormatter=void 0}ed(){return this.kc}vr(){return this.kc.W()}f_(){return this.Mc}rd(t,i,n){const s=this.bc[0],e=this.hd(i,t,s,n);return this.wc.push(e),1===this.wc.length?this.$l():this.Nh(),e}ld(t){const i=this._r(t),n=this.wc.indexOf(t);c(-1!==n,"Series not found"),this.wc.splice(n,1),f(i).jo(t),t.S&&t.S()}Hl(t,i){const n=f(this._r(t));n.jo(t);const s=this.Lc(i);if(null===s){const s=t.Xi();n.Fo(t,i,s)}else{const e=s.Ht===n?t.Xi():void 0;s.Ht.Fo(t,i,e)}}Qu(){const t=lt.ts();t.jn(),this.Ac(t)}ad(t){const i=lt.ts();i.Un(t),this.Ac(i)}Xn(){const t=lt.ts();t.Xn(),this.Ac(t)}Kn(t){const i=lt.ts();i.Kn(t),this.Ac(i)}Zn(t){const i=lt.ts();i.Zn(t),this.Ac(i)}qn(t){const i=lt.ts();i.qn(t),this.Ac(i)}Hn(){const t=lt.ts();t.Hn(),this.Ac(t)}od(){return this._n.rightPriceScale.visible?"right":"left"}_d(){return this.Oc}q(){return this.Rc}Bt(t){const i=this.Oc,n=this.Rc;if(i===n)return i;if(t=Math.max(0,Math.min(100,Math.round(100*t))),null===this.Sc||this.Sc.ks!==n||this.Sc.Cs!==i)this.Sc={ks:n,Cs:i,ud:new Map};else{const i=this.Sc.ud.get(t);if(void 0!==i)return i}const s=function(t,i,n){const[s,e,r,h]=S(t),[l,a,o,_]=S(i),u=[m(s+n*(l-s)),m(e+n*(a-e)),m(r+n*(o-r)),b(h+n*(_-h))];return`rgba(${u[0]}, ${u[1]}, ${u[2]}, ${u[3]})`}(n,i,t/100);return this.Sc.ud.set(t,s),s}$c(t,i){const n=new lt(i);if(null!==t){const s=this.bc.indexOf(t);n.In(s,{Ln:i})}return n}Bc(t,i){return void 0===i&&(i=2),this.$c(this._r(t),i)}Ac(t){this.yc&&this.yc(t),this.bc.forEach((t=>t.E_().Fh().bt()))}hd(t,i,n,s){const e=new qi(this,t,i,n,s),r=void 0!==t.priceScaleId?t.priceScaleId:this.od();return n.Fo(e,r),ht(r)||e.Lh(t),e}Dc(t){const i=this._n.layout;return"gradient"===i.background.type?0===t?i.background.topColor:i.background.bottomColor:i.background.color}}function Bn(t){return!T(t)&&!R(t)}function Vn(t){return T(t)}!function(t){t[t.Disabled=0]="Disabled",t[t.Continuous=1]="Continuous",t[t.OnDataUpdate=2]="OnDataUpdate"}(Pn||(Pn={})),function(t){t[t.LastBar=0]="LastBar",t[t.LastVisible=1]="LastVisible"}(Rn||(Rn={})),function(t){t.Solid="solid",t.VerticalGradient="gradient"}(Dn||(Dn={})),function(t){t[t.Year=0]="Year",t[t.Month=1]="Month",t[t.DayOfMonth=2]="DayOfMonth",t[t.Time=3]="Time",t[t.TimeWithSeconds=4]="TimeWithSeconds"}(On||(On={}));const zn=t=>t.getUTCFullYear();function En(t,i,n){return i.replace(/yyyy/g,(t=>ot(zn(t),4))(t)).replace(/yy/g,(t=>ot(zn(t)%100,2))(t)).replace(/MMMM/g,((t,i)=>new Date(t.getUTCFullYear(),t.getUTCMonth(),1).toLocaleString(i,{month:"long"}))(t,n)).replace(/MMM/g,((t,i)=>new Date(t.getUTCFullYear(),t.getUTCMonth(),1).toLocaleString(i,{month:"short"}))(t,n)).replace(/MM/g,(t=>ot((t=>t.getUTCMonth()+1)(t),2))(t)).replace(/dd/g,(t=>ot((t=>t.getUTCDate())(t),2))(t))}class In{constructor(t="yyyy-MM-dd",i="default"){this.dd=t,this.fd=i}F_(t){return En(t,this.dd,this.fd)}}class Ln{constructor(t){this.vd=t||"%h:%m:%s"}F_(t){return this.vd.replace("%h",ot(t.getUTCHours(),2)).replace("%m",ot(t.getUTCMinutes(),2)).replace("%s",ot(t.getUTCSeconds(),2))}}const Nn={pd:"yyyy-MM-dd",md:"%h:%m:%s",bd:" ",wd:"default"};class Fn{constructor(t={}){const i=Object.assign(Object.assign({},Nn),t);this.gd=new In(i.pd,i.wd),this.Md=new Ln(i.md),this.xd=i.bd}F_(t){return`${this.gd.F_(t)}${this.xd}${this.Md.F_(t)}`}}function Wn(t){return 60*t*60*1e3}function jn(t){return 60*t*1e3}const Hn=[{Sd:($n=1,1e3*$n),yd:10},{Sd:jn(1),yd:20},{Sd:jn(5),yd:21},{Sd:jn(30),yd:22},{Sd:Wn(1),yd:30},{Sd:Wn(3),yd:31},{Sd:Wn(6),yd:32},{Sd:Wn(12),yd:33}];var $n;function Un(t,i){if(t.getUTCFullYear()!==i.getUTCFullYear())return 70;if(t.getUTCMonth()!==i.getUTCMonth())return 60;if(t.getUTCDate()!==i.getUTCDate())return 50;for(let n=Hn.length-1;n>=0;--n)if(Math.floor(i.getTime()/Hn[n].Sd)!==Math.floor(t.getTime()/Hn[n].Sd))return Hn[n].yd;return 0}function qn(t){let i=t;if(R(t)&&(i=Xn(t)),!Bn(i))throw new Error("time must be of type BusinessDay");const n=new Date(Date.UTC(i.year,i.month-1,i.day,0,0,0,0));return{kd:Math.round(n.getTime()/1e3),Cd:i}}function Yn(t){if(!Vn(t))throw new Error("time must be of type isUTCTimestamp");return{kd:t}}function Xn(t){const i=new Date(t);if(isNaN(i.getTime()))throw new Error(`Invalid date string=${t}, expected format=yyyy-mm-dd`);return{day:i.getUTCDate(),month:i.getUTCMonth()+1,year:i.getUTCFullYear()}}function Kn(t){R(t.time)&&(t.time=Xn(t.time))}class Zn{options(){return this._n}setOptions(t){this._n=t,this.updateFormatter(t.localization)}preprocessData(t){Array.isArray(t)?function(t){t.forEach(Kn)}(t):Kn(t)}createConverterToInternalObj(t){return f(function(t){return 0===t.length?null:Bn(t[0].time)||R(t[0].time)?qn:Yn}(t))}key(t){return"object"==typeof t&&"kd"in t?t.kd:this.key(this.convertHorzItemToInternal(t))}cacheKey(t){const i=t;return void 0===i.Cd?new Date(1e3*i.kd).getTime():new Date(Date.UTC(i.Cd.year,i.Cd.month-1,i.Cd.day)).getTime()}convertHorzItemToInternal(t){return Vn(i=t)?Yn(i):Bn(i)?qn(i):qn(Xn(i));var i}updateFormatter(t){if(!this._n)return;const i=t.dateFormat;this._n.timeScale.timeVisible?this.Td=new Fn({pd:i,md:this._n.timeScale.secondsVisible?"%h:%m:%s":"%h:%m",bd:" ",wd:t.locale}):this.Td=new In(i,t.locale)}formatHorzItem(t){const i=t;return this.Td.F_(new Date(1e3*i.kd))}formatTickmark(t,i){const n=function(t,i,n){switch(t){case 0:case 10:return i?n?4:3:2;case 20:case 21:case 22:case 30:case 31:case 32:case 33:return i?3:2;case 50:return 2;case 60:return 1;case 70:return 0}}(t.weight,this._n.timeScale.timeVisible,this._n.timeScale.secondsVisible),s=this._n.timeScale;if(void 0!==s.tickMarkFormatter){const e=s.tickMarkFormatter(t.originalTime,n,i.locale);if(null!==e)return e}return function(t,i,n){const s={};switch(i){case 0:s.year="numeric";break;case 1:s.month="short";break;case 2:s.day="numeric";break;case 3:s.hour12=!1,s.hour="2-digit",s.minute="2-digit";break;case 4:s.hour12=!1,s.hour="2-digit",s.minute="2-digit",s.second="2-digit"}const e=void 0===t.Cd?new Date(1e3*t.kd):new Date(Date.UTC(t.Cd.year,t.Cd.month-1,t.Cd.day));return new Date(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()).toLocaleString(n,s)}(t.time,n,i.locale)}maxTickMarkWeight(t){let i=t.reduce(Mn,t[0]).weight;return i>30&&i<50&&(i=30),i}fillWeightsForPoints(t,i){!function(t,i=0){if(0===t.length)return;let n=0===i?null:t[i-1].time.kd,s=null!==n?new Date(1e3*n):null,e=0;for(let r=i;r1){const i=Math.ceil(e/(t.length-1)),n=new Date(1e3*(t[0].time.kd-i));t[0].timeWeight=Un(new Date(1e3*t[0].time.kd),n)}}(t,i)}static Pd(t){return C({localization:{dateFormat:"dd MMM 'yy"}},null!=t?t:{})}}function Gn(t){var i=t.width,n=t.height;if(i<0)throw new Error("Negative width is not allowed for Size");if(n<0)throw new Error("Negative height is not allowed for Size");return{width:i,height:n}}function Jn(t,i){return t.width===i.width&&t.height===i.height}var Qn=function(){function t(t){var i=this;this._resolutionListener=function(){return i._onResolutionChanged()},this._resolutionMediaQueryList=null,this._observers=[],this._window=t,this._installResolutionListener()}return t.prototype.dispose=function(){this._uninstallResolutionListener(),this._window=null},Object.defineProperty(t.prototype,"value",{get:function(){return this._window.devicePixelRatio},enumerable:!1,configurable:!0}),t.prototype.subscribe=function(t){var i=this,n={next:t};return this._observers.push(n),{unsubscribe:function(){i._observers=i._observers.filter((function(t){return t!==n}))}}},t.prototype._installResolutionListener=function(){if(null!==this._resolutionMediaQueryList)throw new Error("Resolution listener is already installed");var t=this._window.devicePixelRatio;this._resolutionMediaQueryList=this._window.matchMedia("all and (resolution: ".concat(t,"dppx)")),this._resolutionMediaQueryList.addListener(this._resolutionListener)},t.prototype._uninstallResolutionListener=function(){null!==this._resolutionMediaQueryList&&(this._resolutionMediaQueryList.removeListener(this._resolutionListener),this._resolutionMediaQueryList=null)},t.prototype._reinstallResolutionListener=function(){this._uninstallResolutionListener(),this._installResolutionListener()},t.prototype._onResolutionChanged=function(){var t=this;this._observers.forEach((function(i){return i.next(t._window.devicePixelRatio)})),this._reinstallResolutionListener()},t}();var ts=function(){function t(t,i,n){var s;this._canvasElement=null,this._bitmapSizeChangedListeners=[],this._suggestedBitmapSize=null,this._suggestedBitmapSizeChangedListeners=[],this._devicePixelRatioObservable=null,this._canvasElementResizeObserver=null,this._canvasElement=t,this._canvasElementClientSize=Gn({width:this._canvasElement.clientWidth,height:this._canvasElement.clientHeight}),this._transformBitmapSize=null!=i?i:function(t){return t},this._allowResizeObserver=null===(s=null==n?void 0:n.allowResizeObserver)||void 0===s||s,this._chooseAndInitObserver()}return t.prototype.dispose=function(){var t,i;if(null===this._canvasElement)throw new Error("Object is disposed");null===(t=this._canvasElementResizeObserver)||void 0===t||t.disconnect(),this._canvasElementResizeObserver=null,null===(i=this._devicePixelRatioObservable)||void 0===i||i.dispose(),this._devicePixelRatioObservable=null,this._suggestedBitmapSizeChangedListeners.length=0,this._bitmapSizeChangedListeners.length=0,this._canvasElement=null},Object.defineProperty(t.prototype,"canvasElement",{get:function(){if(null===this._canvasElement)throw new Error("Object is disposed");return this._canvasElement},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"canvasElementClientSize",{get:function(){return this._canvasElementClientSize},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"bitmapSize",{get:function(){return Gn({width:this.canvasElement.width,height:this.canvasElement.height})},enumerable:!1,configurable:!0}),t.prototype.resizeCanvasElement=function(t){this._canvasElementClientSize=Gn(t),this.canvasElement.style.width="".concat(this._canvasElementClientSize.width,"px"),this.canvasElement.style.height="".concat(this._canvasElementClientSize.height,"px"),this._invalidateBitmapSize()},t.prototype.subscribeBitmapSizeChanged=function(t){this._bitmapSizeChangedListeners.push(t)},t.prototype.unsubscribeBitmapSizeChanged=function(t){this._bitmapSizeChangedListeners=this._bitmapSizeChangedListeners.filter((function(i){return i!==t}))},Object.defineProperty(t.prototype,"suggestedBitmapSize",{get:function(){return this._suggestedBitmapSize},enumerable:!1,configurable:!0}),t.prototype.subscribeSuggestedBitmapSizeChanged=function(t){this._suggestedBitmapSizeChangedListeners.push(t)},t.prototype.unsubscribeSuggestedBitmapSizeChanged=function(t){this._suggestedBitmapSizeChangedListeners=this._suggestedBitmapSizeChangedListeners.filter((function(i){return i!==t}))},t.prototype.applySuggestedBitmapSize=function(){if(null!==this._suggestedBitmapSize){var t=this._suggestedBitmapSize;this._suggestedBitmapSize=null,this._resizeBitmap(t),this._emitSuggestedBitmapSizeChanged(t,this._suggestedBitmapSize)}},t.prototype._resizeBitmap=function(t){var i=this.bitmapSize;Jn(i,t)||(this.canvasElement.width=t.width,this.canvasElement.height=t.height,this._emitBitmapSizeChanged(i,t))},t.prototype._emitBitmapSizeChanged=function(t,i){var n=this;this._bitmapSizeChangedListeners.forEach((function(s){return s.call(n,t,i)}))},t.prototype._suggestNewBitmapSize=function(t){var i=this._suggestedBitmapSize,n=Gn(this._transformBitmapSize(t,this._canvasElementClientSize)),s=Jn(this.bitmapSize,n)?null:n;null===i&&null===s||null!==i&&null!==s&&Jn(i,s)||(this._suggestedBitmapSize=s,this._emitSuggestedBitmapSizeChanged(i,s))},t.prototype._emitSuggestedBitmapSizeChanged=function(t,i){var n=this;this._suggestedBitmapSizeChangedListeners.forEach((function(s){return s.call(n,t,i)}))},t.prototype._chooseAndInitObserver=function(){var t=this;this._allowResizeObserver?new Promise((function(t){var i=new ResizeObserver((function(n){t(n.every((function(t){return"devicePixelContentBoxSize"in t}))),i.disconnect()}));i.observe(document.body,{box:"device-pixel-content-box"})})).catch((function(){return!1})).then((function(i){return i?t._initResizeObserver():t._initDevicePixelRatioObservable()})):this._initDevicePixelRatioObservable()},t.prototype._initDevicePixelRatioObservable=function(){var t=this;if(null!==this._canvasElement){var i=is(this._canvasElement);if(null===i)throw new Error("No window is associated with the canvas");this._devicePixelRatioObservable=function(t){return new Qn(t)}(i),this._devicePixelRatioObservable.subscribe((function(){return t._invalidateBitmapSize()})),this._invalidateBitmapSize()}},t.prototype._invalidateBitmapSize=function(){var t,i;if(null!==this._canvasElement){var n=is(this._canvasElement);if(null!==n){var s=null!==(i=null===(t=this._devicePixelRatioObservable)||void 0===t?void 0:t.value)&&void 0!==i?i:n.devicePixelRatio,e=this._canvasElement.getClientRects(),r=void 0!==e[0]?function(t,i){return Gn({width:Math.round(t.left*i+t.width*i)-Math.round(t.left*i),height:Math.round(t.top*i+t.height*i)-Math.round(t.top*i)})}(e[0],s):Gn({width:this._canvasElementClientSize.width*s,height:this._canvasElementClientSize.height*s});this._suggestNewBitmapSize(r)}}},t.prototype._initResizeObserver=function(){var t=this;null!==this._canvasElement&&(this._canvasElementResizeObserver=new ResizeObserver((function(i){var n=i.find((function(i){return i.target===t._canvasElement}));if(n&&n.devicePixelContentBoxSize&&n.devicePixelContentBoxSize[0]){var s=n.devicePixelContentBoxSize[0],e=Gn({width:s.inlineSize,height:s.blockSize});t._suggestNewBitmapSize(e)}})),this._canvasElementResizeObserver.observe(this._canvasElement,{box:"device-pixel-content-box"}))},t}();function is(t){return t.ownerDocument.defaultView}var ns=function(){function t(t,i,n){if(0===i.width||0===i.height)throw new TypeError("Rendering target could only be created on a media with positive width and height");if(this._mediaSize=i,0===n.width||0===n.height)throw new TypeError("Rendering target could only be created using a bitmap with positive integer width and height");this._bitmapSize=n,this._context=t}return t.prototype.useMediaCoordinateSpace=function(t){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),this._context.scale(this._horizontalPixelRatio,this._verticalPixelRatio),t({context:this._context,mediaSize:this._mediaSize})}finally{this._context.restore()}},t.prototype.useBitmapCoordinateSpace=function(t){try{return this._context.save(),this._context.setTransform(1,0,0,1,0,0),t({context:this._context,mediaSize:this._mediaSize,bitmapSize:this._bitmapSize,horizontalPixelRatio:this._horizontalPixelRatio,verticalPixelRatio:this._verticalPixelRatio})}finally{this._context.restore()}},Object.defineProperty(t.prototype,"_horizontalPixelRatio",{get:function(){return this._bitmapSize.width/this._mediaSize.width},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"_verticalPixelRatio",{get:function(){return this._bitmapSize.height/this._mediaSize.height},enumerable:!1,configurable:!0}),t}();function ss(t,i){var n=t.canvasElementClientSize;if(0===n.width||0===n.height)return null;var s=t.bitmapSize;if(0===s.width||0===s.height)return null;var e=t.canvasElement.getContext("2d",i);return null===e?null:new ns(e,n,s)}const es="undefined"!=typeof window;function rs(){return!!es&&window.navigator.userAgent.toLowerCase().indexOf("firefox")>-1}function hs(){return!!es&&/iPhone|iPad|iPod/.test(window.navigator.platform)}function ls(t){return t+t%2}function as(t,i){return t.Rd-i.Rd}function os(t,i,n){const s=(t.Rd-i.Rd)/(t.ot-i.ot);return Math.sign(s)*Math.min(Math.abs(s),n)}class _s{constructor(t,i,n,s){this.Dd=null,this.Od=null,this.Ad=null,this.Bd=null,this.Vd=null,this.zd=0,this.Ed=0,this.Id=t,this.Ld=i,this.Nd=n,this.ss=s}Fd(t,i){if(null!==this.Dd){if(this.Dd.ot===i)return void(this.Dd.Rd=t);if(Math.abs(this.Dd.Rd-t)50)return;let n=0;const s=os(this.Dd,this.Od,this.Ld),e=as(this.Dd,this.Od),r=[s],h=[e];if(n+=e,null!==this.Ad){const t=os(this.Od,this.Ad,this.Ld);if(Math.sign(t)===Math.sign(s)){const i=as(this.Od,this.Ad);if(r.push(t),h.push(i),n+=i,null!==this.Bd){const t=os(this.Ad,this.Bd,this.Ld);if(Math.sign(t)===Math.sign(s)){const i=as(this.Ad,this.Bd);r.push(t),h.push(i),n+=i}}}}let l=0;for(let t=0;t({width:Math.max(t.width,i.width),height:Math.max(t.height,i.height)})});return s.resizeCanvasElement(i),s}function cs(t){var i;t.width=1,t.height=1,null===(i=t.getContext("2d"))||void 0===i||i.clearRect(0,0,1,1)}function ds(t,i,n,s){t.fl&&t.fl(i,n,s)}function fs(t,i,n,s){t.K(i,n,s)}function vs(t,i,n,s){const e=t(n,s);for(const t of e){const n=t.gt();null!==n&&i(n)}}function ps(t){es&&void 0!==window.chrome&&t.addEventListener("mousedown",(t=>{if(1===t.button)return t.preventDefault(),!1}))}class ms{constructor(t,i,n){this.jd=0,this.Hd=null,this.$d={nt:Number.NEGATIVE_INFINITY,st:Number.POSITIVE_INFINITY},this.Ud=0,this.qd=null,this.Yd={nt:Number.NEGATIVE_INFINITY,st:Number.POSITIVE_INFINITY},this.Xd=null,this.Kd=!1,this.Zd=null,this.Gd=null,this.Jd=!1,this.Qd=!1,this.tf=!1,this.if=null,this.nf=null,this.sf=null,this.ef=null,this.rf=null,this.hf=null,this.lf=null,this.af=0,this._f=!1,this.uf=!1,this.cf=!1,this.df=0,this.ff=null,this.vf=!hs(),this.pf=t=>{this.mf(t)},this.bf=t=>{if(this.wf(t)){const i=this.gf(t);if(++this.Ud,this.qd&&this.Ud>1){const{Mf:n}=this.xf(gs(t),this.Yd);n<30&&!this.tf&&this.Sf(i,this.kf.yf),this.Cf()}}else{const i=this.gf(t);if(++this.jd,this.Hd&&this.jd>1){const{Mf:n}=this.xf(gs(t),this.$d);n<5&&!this.Qd&&this.Tf(i,this.kf.Pf),this.Rf()}}},this.Df=t,this.kf=i,this._n=n,this.Of()}S(){null!==this.if&&(this.if(),this.if=null),null!==this.nf&&(this.nf(),this.nf=null),null!==this.ef&&(this.ef(),this.ef=null),null!==this.rf&&(this.rf(),this.rf=null),null!==this.hf&&(this.hf(),this.hf=null),null!==this.sf&&(this.sf(),this.sf=null),this.Af(),this.Rf()}Bf(t){this.ef&&this.ef();const i=this.Vf.bind(this);if(this.ef=()=>{this.Df.removeEventListener("mousemove",i)},this.Df.addEventListener("mousemove",i),this.wf(t))return;const n=this.gf(t);this.Tf(n,this.kf.zf),this.vf=!0}Rf(){null!==this.Hd&&clearTimeout(this.Hd),this.jd=0,this.Hd=null,this.$d={nt:Number.NEGATIVE_INFINITY,st:Number.POSITIVE_INFINITY}}Cf(){null!==this.qd&&clearTimeout(this.qd),this.Ud=0,this.qd=null,this.Yd={nt:Number.NEGATIVE_INFINITY,st:Number.POSITIVE_INFINITY}}Vf(t){if(this.cf||null!==this.Gd)return;if(this.wf(t))return;const i=this.gf(t);this.Tf(i,this.kf.Ef),this.vf=!0}If(t){const i=xs(t.changedTouches,f(this.ff));if(null===i)return;if(this.df=Ms(t),null!==this.lf)return;if(this.uf)return;this._f=!0;const n=this.xf(gs(i),f(this.Gd)),{Lf:s,Nf:e,Mf:r}=n;if(this.Jd||!(r<5)){if(!this.Jd){const t=.5*s,i=e>=t&&!this._n.Ff(),n=t>e&&!this._n.Wf();i||n||(this.uf=!0),this.Jd=!0,this.tf=!0,this.Af(),this.Cf()}if(!this.uf){const n=this.gf(t,i);this.Sf(n,this.kf.jf),ws(t)}}}Hf(t){if(0!==t.button)return;const i=this.xf(gs(t),f(this.Zd)),{Mf:n}=i;if(n>=5&&(this.Qd=!0,this.Rf()),this.Qd){const i=this.gf(t);this.Tf(i,this.kf.$f)}}xf(t,i){const n=Math.abs(i.nt-t.nt),s=Math.abs(i.st-t.st);return{Lf:n,Nf:s,Mf:n+s}}Uf(t){let i=xs(t.changedTouches,f(this.ff));if(null===i&&0===t.touches.length&&(i=t.changedTouches[0]),null===i)return;this.ff=null,this.df=Ms(t),this.Af(),this.Gd=null,this.hf&&(this.hf(),this.hf=null);const n=this.gf(t,i);if(this.Sf(n,this.kf.qf),++this.Ud,this.qd&&this.Ud>1){const{Mf:t}=this.xf(gs(i),this.Yd);t<30&&!this.tf&&this.Sf(n,this.kf.yf),this.Cf()}else this.tf||(this.Sf(n,this.kf.Yf),this.kf.Yf&&ws(t));0===this.Ud&&ws(t),0===t.touches.length&&this.Kd&&(this.Kd=!1,ws(t))}mf(t){if(0!==t.button)return;const i=this.gf(t);if(this.Zd=null,this.cf=!1,this.rf&&(this.rf(),this.rf=null),rs()){this.Df.ownerDocument.documentElement.removeEventListener("mouseleave",this.pf)}if(!this.wf(t))if(this.Tf(i,this.kf.Xf),++this.jd,this.Hd&&this.jd>1){const{Mf:n}=this.xf(gs(t),this.$d);n<5&&!this.Qd&&this.Tf(i,this.kf.Pf),this.Rf()}else this.Qd||this.Tf(i,this.kf.Kf)}Af(){null!==this.Xd&&(clearTimeout(this.Xd),this.Xd=null)}Zf(t){if(null!==this.ff)return;const i=t.changedTouches[0];this.ff=i.identifier,this.df=Ms(t);const n=this.Df.ownerDocument.documentElement;this.tf=!1,this.Jd=!1,this.uf=!1,this.Gd=gs(i),this.hf&&(this.hf(),this.hf=null);{const i=this.If.bind(this),s=this.Uf.bind(this);this.hf=()=>{n.removeEventListener("touchmove",i),n.removeEventListener("touchend",s)},n.addEventListener("touchmove",i,{passive:!1}),n.addEventListener("touchend",s,{passive:!1}),this.Af(),this.Xd=setTimeout(this.Gf.bind(this,t),240)}const s=this.gf(t,i);this.Sf(s,this.kf.Jf),this.qd||(this.Ud=0,this.qd=setTimeout(this.Cf.bind(this),500),this.Yd=gs(i))}Qf(t){if(0!==t.button)return;const i=this.Df.ownerDocument.documentElement;rs()&&i.addEventListener("mouseleave",this.pf),this.Qd=!1,this.Zd=gs(t),this.rf&&(this.rf(),this.rf=null);{const t=this.Hf.bind(this),n=this.mf.bind(this);this.rf=()=>{i.removeEventListener("mousemove",t),i.removeEventListener("mouseup",n)},i.addEventListener("mousemove",t),i.addEventListener("mouseup",n)}if(this.cf=!0,this.wf(t))return;const n=this.gf(t);this.Tf(n,this.kf.tv),this.Hd||(this.jd=0,this.Hd=setTimeout(this.Rf.bind(this),500),this.$d=gs(t))}Of(){this.Df.addEventListener("mouseenter",this.Bf.bind(this)),this.Df.addEventListener("touchcancel",this.Af.bind(this));{const t=this.Df.ownerDocument,i=t=>{this.kf.iv&&(t.composed&&this.Df.contains(t.composedPath()[0])||t.target&&this.Df.contains(t.target)||this.kf.iv())};this.nf=()=>{t.removeEventListener("touchstart",i)},this.if=()=>{t.removeEventListener("mousedown",i)},t.addEventListener("mousedown",i),t.addEventListener("touchstart",i,{passive:!0})}hs()&&(this.sf=()=>{this.Df.removeEventListener("dblclick",this.bf)},this.Df.addEventListener("dblclick",this.bf)),this.Df.addEventListener("mouseleave",this.nv.bind(this)),this.Df.addEventListener("touchstart",this.Zf.bind(this),{passive:!0}),ps(this.Df),this.Df.addEventListener("mousedown",this.Qf.bind(this)),this.sv(),this.Df.addEventListener("touchmove",(()=>{}),{passive:!1})}sv(){void 0===this.kf.ev&&void 0===this.kf.rv&&void 0===this.kf.hv||(this.Df.addEventListener("touchstart",(t=>this.lv(t.touches)),{passive:!0}),this.Df.addEventListener("touchmove",(t=>{if(2===t.touches.length&&null!==this.lf&&void 0!==this.kf.rv){const i=bs(t.touches[0],t.touches[1])/this.af;this.kf.rv(this.lf,i),ws(t)}}),{passive:!1}),this.Df.addEventListener("touchend",(t=>{this.lv(t.touches)})))}lv(t){1===t.length&&(this._f=!1),2!==t.length||this._f||this.Kd?this.av():this.ov(t)}ov(t){const i=this.Df.getBoundingClientRect()||{left:0,top:0};this.lf={nt:(t[0].clientX-i.left+(t[1].clientX-i.left))/2,st:(t[0].clientY-i.top+(t[1].clientY-i.top))/2},this.af=bs(t[0],t[1]),void 0!==this.kf.ev&&this.kf.ev(),this.Af()}av(){null!==this.lf&&(this.lf=null,void 0!==this.kf.hv&&this.kf.hv())}nv(t){if(this.ef&&this.ef(),this.wf(t))return;if(!this.vf)return;const i=this.gf(t);this.Tf(i,this.kf._v),this.vf=!hs()}Gf(t){const i=xs(t.touches,f(this.ff));if(null===i)return;const n=this.gf(t,i);this.Sf(n,this.kf.uv),this.tf=!0,this.Kd=!0}wf(t){return t.sourceCapabilities&&void 0!==t.sourceCapabilities.firesTouchEvents?t.sourceCapabilities.firesTouchEvents:Ms(t){"touchstart"!==t.type&&ws(t)}}}}function bs(t,i){const n=t.clientX-i.clientX,s=t.clientY-i.clientY;return Math.sqrt(n*n+s*s)}function ws(t){t.cancelable&&t.preventDefault()}function gs(t){return{nt:t.pageX,st:t.pageY}}function Ms(t){return t.timeStamp||performance.now()}function xs(t,i){for(let n=0;n{var s,e,r,h;return(null!==(e=null===(s=n.Dt())||void 0===s?void 0:s.xa())&&void 0!==e?e:"")!==i?[]:null!==(h=null===(r=n.la)||void 0===r?void 0:r.call(n,t))&&void 0!==h?h:[]}}class Cs{constructor(t,i,n,s){this.Ei=null,this.gv=null,this.Mv=!1,this.xv=new Jt(200),this.Zr=null,this.Sv=0,this.yv=!1,this.kv=()=>{this.yv||this.Qi.Cv().$t().Nh()},this.Tv=()=>{this.yv||this.Qi.Cv().$t().Nh()},this.Qi=t,this._n=i,this.mo=i.layout,this.kc=n,this.Pv="left"===s,this.Rv=ks("normal",s),this.Dv=ks("top",s),this.Ov=ks("bottom",s),this.Av=document.createElement("div"),this.Av.style.height="100%",this.Av.style.overflow="hidden",this.Av.style.width="25px",this.Av.style.left="0",this.Av.style.position="relative",this.Bv=us(this.Av,Gn({width:16,height:16})),this.Bv.subscribeSuggestedBitmapSizeChanged(this.kv);const e=this.Bv.canvasElement;e.style.position="absolute",e.style.zIndex="1",e.style.left="0",e.style.top="0",this.Vv=us(this.Av,Gn({width:16,height:16})),this.Vv.subscribeSuggestedBitmapSizeChanged(this.Tv);const r=this.Vv.canvasElement;r.style.position="absolute",r.style.zIndex="2",r.style.left="0",r.style.top="0";const h={tv:this.zv.bind(this),Jf:this.zv.bind(this),$f:this.Ev.bind(this),jf:this.Ev.bind(this),iv:this.Iv.bind(this),Xf:this.Lv.bind(this),qf:this.Lv.bind(this),Pf:this.Nv.bind(this),yf:this.Nv.bind(this),zf:this.Fv.bind(this),_v:this.Wv.bind(this)};this.jv=new ms(this.Vv.canvasElement,h,{Ff:()=>!this._n.handleScroll.vertTouchDrag,Wf:()=>!0})}S(){this.jv.S(),this.Vv.unsubscribeSuggestedBitmapSizeChanged(this.Tv),cs(this.Vv.canvasElement),this.Vv.dispose(),this.Bv.unsubscribeSuggestedBitmapSizeChanged(this.kv),cs(this.Bv.canvasElement),this.Bv.dispose(),null!==this.Ei&&this.Ei.$o().p(this),this.Ei=null}Hv(){return this.Av}P(){return this.mo.fontSize}$v(){const t=this.kc.W();return this.Zr!==t.R&&(this.xv.Qe(),this.Zr=t.R),t}Uv(){if(null===this.Ei)return 0;let t=0;const i=this.$v(),n=f(this.Bv.canvasElement.getContext("2d"));n.save();const s=this.Ei.Ia();n.font=this.qv(),s.length>0&&(t=Math.max(this.xv.Mi(n,s[0].Za),this.xv.Mi(n,s[s.length-1].Za)));const e=this.Yv();for(let i=e.length;i--;){const s=this.xv.Mi(n,e[i].Zt());s>t&&(t=s)}const r=this.Ei.Ct();if(null!==r&&null!==this.gv){const i=this.Ei.fn(1,r),s=this.Ei.fn(this.gv.height-2,r);t=Math.max(t,this.xv.Mi(n,this.Ei.Ni(Math.floor(Math.min(i,s))+.11111111111111,r)),this.xv.Mi(n,this.Ei.Ni(Math.ceil(Math.max(i,s))-.11111111111111,r)))}n.restore();const h=t||34;return ls(Math.ceil(i.C+i.T+i.V+i.I+5+h))}Xv(t){null!==this.gv&&Jn(this.gv,t)||(this.gv=t,this.yv=!0,this.Bv.resizeCanvasElement(t),this.Vv.resizeCanvasElement(t),this.yv=!1,this.Av.style.width=`${t.width}px`,this.Av.style.height=`${t.height}px`)}Kv(){return f(this.gv).width}Zi(t){this.Ei!==t&&(null!==this.Ei&&this.Ei.$o().p(this),this.Ei=t,t.$o().l(this.ao.bind(this),this))}Dt(){return this.Ei}Qe(){const t=this.Qi.Zv();this.Qi.Cv().$t().A_(t,f(this.Dt()))}Gv(t){if(null===this.gv)return;if(1!==t){this.Jv(),this.Bv.applySuggestedBitmapSize();const t=ss(this.Bv);null!==t&&(t.useBitmapCoordinateSpace((t=>{this.Qv(t),this.Ae(t)})),this.Qi.tp(t,this.Ov),this.ip(t),this.Qi.tp(t,this.Rv),this.np(t))}this.Vv.applySuggestedBitmapSize();const i=ss(this.Vv);null!==i&&(i.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this.sp(i),this.Qi.tp(i,this.Dv))}ep(){return this.Bv.bitmapSize}rp(t,i,n){const s=this.ep();s.width>0&&s.height>0&&t.drawImage(this.Bv.canvasElement,i,n)}bt(){var t;null===(t=this.Ei)||void 0===t||t.Ia()}zv(t){if(null===this.Ei||this.Ei.Li()||!this._n.handleScale.axisPressedMouseMove.price)return;const i=this.Qi.Cv().$t(),n=this.Qi.Zv();this.Mv=!0,i.k_(n,this.Ei,t.localY)}Ev(t){if(null===this.Ei||!this._n.handleScale.axisPressedMouseMove.price)return;const i=this.Qi.Cv().$t(),n=this.Qi.Zv(),s=this.Ei;i.C_(n,s,t.localY)}Iv(){if(null===this.Ei||!this._n.handleScale.axisPressedMouseMove.price)return;const t=this.Qi.Cv().$t(),i=this.Qi.Zv(),n=this.Ei;this.Mv&&(this.Mv=!1,t.T_(i,n))}Lv(t){if(null===this.Ei||!this._n.handleScale.axisPressedMouseMove.price)return;const i=this.Qi.Cv().$t(),n=this.Qi.Zv();this.Mv=!1,i.T_(n,this.Ei)}Nv(t){this._n.handleScale.axisDoubleClickReset.price&&this.Qe()}Fv(t){if(null===this.Ei)return;!this.Qi.Cv().$t().W().handleScale.axisPressedMouseMove.price||this.Ei.fh()||this.Ei.Co()||this.hp(1)}Wv(t){this.hp(0)}Yv(){const t=[],i=null===this.Ei?void 0:this.Ei;return(n=>{for(let s=0;s{t.fillStyle=n.borderColor;const l=Math.max(1,Math.floor(h)),a=Math.floor(.5*h),o=Math.round(s.T*r);t.beginPath();for(const n of i)t.rect(Math.floor(e*r),Math.round(n.Aa*h)-a,o,l);t.fill()})),t.useMediaCoordinateSpace((({context:t})=>{var r;t.font=this.qv(),t.fillStyle=null!==(r=n.textColor)&&void 0!==r?r:this.mo.textColor,t.textAlign=this.Pv?"right":"left",t.textBaseline="middle";const h=this.Pv?Math.round(e-s.V):Math.round(e+s.T+s.V),l=i.map((i=>this.xv.gi(t,i.Za)));for(let n=i.length;n--;){const s=i[n];t.fillText(s.Za,h,s.Aa+l[n])}}))}Jv(){if(null===this.gv||null===this.Ei)return;let t=this.gv.height/2;const i=[],n=this.Ei.No().slice(),s=this.Qi.Zv(),e=this.$v();this.Ei===s.cr()&&this.Qi.Zv().No().forEach((t=>{s.ur(t)&&n.push(t)}));const r=this.Ei.Ta()[0],h=this.Ei;n.forEach((n=>{const e=n.Tn(s,h);e.forEach((t=>{t.Oi(null),t.Ai()&&i.push(t)})),r===n&&e.length>0&&(t=e[0].Si())})),i.forEach((t=>t.Oi(t.Si())));this.Ei.W().alignLabels&&this.lp(i,e,t)}lp(t,i,n){if(null===this.gv)return;const s=t.filter((t=>t.Si()<=n)),e=t.filter((t=>t.Si()>n));s.sort(((t,i)=>i.Si()-t.Si())),s.length&&e.length&&e.push(s[0]),e.sort(((t,i)=>t.Si()-i.Si()));for(const n of t){const t=Math.floor(n.Vt(i)/2),s=n.Si();s>-t&&sthis.gv.height-t&&sl-r&&n.Oi(l-r)}for(let t=1;t{if(i.Bi()){i.gt(f(this.Ei)).K(t,n,this.xv,s)}}))}sp(t){if(null===this.gv||null===this.Ei)return;const i=this.Qi.Cv().$t(),n=[],s=this.Qi.Zv(),e=i.Wc().Tn(s,this.Ei);e.length&&n.push(e);const r=this.$v(),h=this.Pv?"right":"left";n.forEach((i=>{i.forEach((i=>{i.gt(f(this.Ei)).K(t,r,this.xv,h)}))}))}hp(t){this.Av.style.cursor=1===t?"ns-resize":"default"}ao(){const t=this.Uv();this.Sv{this.yv||null===this.gp||this.Hi().Nh()},this.Tv=()=>{this.yv||null===this.gp||this.Hi().Nh()},this.Mp=t,this.gp=i,this.gp.z_().l(this.xp.bind(this),this,!0),this.Sp=document.createElement("td"),this.Sp.style.padding="0",this.Sp.style.position="relative";const n=document.createElement("div");n.style.width="100%",n.style.height="100%",n.style.position="relative",n.style.overflow="hidden",this.yp=document.createElement("td"),this.yp.style.padding="0",this.kp=document.createElement("td"),this.kp.style.padding="0",this.Sp.appendChild(n),this.Bv=us(n,Gn({width:16,height:16})),this.Bv.subscribeSuggestedBitmapSizeChanged(this.kv);const s=this.Bv.canvasElement;s.style.position="absolute",s.style.zIndex="1",s.style.left="0",s.style.top="0",this.Vv=us(n,Gn({width:16,height:16})),this.Vv.subscribeSuggestedBitmapSizeChanged(this.Tv);const e=this.Vv.canvasElement;e.style.position="absolute",e.style.zIndex="2",e.style.left="0",e.style.top="0",this.Cp=document.createElement("tr"),this.Cp.appendChild(this.yp),this.Cp.appendChild(this.Sp),this.Cp.appendChild(this.kp),this.Tp(),this.jv=new ms(this.Vv.canvasElement,this,{Ff:()=>null===this.pp&&!this.Mp.W().handleScroll.vertTouchDrag,Wf:()=>null===this.pp&&!this.Mp.W().handleScroll.horzTouchDrag})}S(){null!==this.ap&&this.ap.S(),null!==this.op&&this.op.S(),this.Vv.unsubscribeSuggestedBitmapSizeChanged(this.Tv),cs(this.Vv.canvasElement),this.Vv.dispose(),this.Bv.unsubscribeSuggestedBitmapSizeChanged(this.kv),cs(this.Bv.canvasElement),this.Bv.dispose(),null!==this.gp&&this.gp.z_().p(this),this.jv.S()}Zv(){return f(this.gp)}Pp(t){null!==this.gp&&this.gp.z_().p(this),this.gp=t,null!==this.gp&&this.gp.z_().l(Os.prototype.xp.bind(this),this,!0),this.Tp()}Cv(){return this.Mp}Hv(){return this.Cp}Tp(){if(null!==this.gp&&(this.Rp(),0!==this.Hi().wt().length)){if(null!==this.ap){const t=this.gp.S_();this.ap.Zi(f(t))}if(null!==this.op){const t=this.gp.y_();this.op.Zi(f(t))}}}Dp(){null!==this.ap&&this.ap.bt(),null!==this.op&&this.op.bt()}v_(){return null!==this.gp?this.gp.v_():0}p_(t){this.gp&&this.gp.p_(t)}zf(t){if(!this.gp)return;this.Op();const i=t.localX,n=t.localY;this.Ap(i,n,t)}tv(t){this.Op(),this.Bp(),this.Ap(t.localX,t.localY,t)}Ef(t){var i;if(!this.gp)return;this.Op();const n=t.localX,s=t.localY;this.Ap(n,s,t);const e=this.pr(n,s);this.Mp.Vp(null!==(i=null==e?void 0:e.wv)&&void 0!==i?i:null),this.Hi().zc(e&&{Ec:e.Ec,mv:e.mv})}Kf(t){null!==this.gp&&(this.Op(),this.zp(t))}Pf(t){null!==this.gp&&this.Ep(this.dp,t)}yf(t){this.Pf(t)}$f(t){this.Op(),this.Ip(t),this.Ap(t.localX,t.localY,t)}Xf(t){null!==this.gp&&(this.Op(),this.vp=!1,this.Lp(t))}Yf(t){null!==this.gp&&this.zp(t)}uv(t){if(this.vp=!0,null===this.pp){const i={x:t.localX,y:t.localY};this.Np(i,i,t)}}_v(t){null!==this.gp&&(this.Op(),this.gp.$t().zc(null),this.Fp())}Wp(){return this.cp}jp(){return this.dp}ev(){this.fp=1,this.Hi().Hn()}rv(t,i){if(!this.Mp.W().handleScale.pinch)return;const n=5*(i-this.fp);this.fp=i,this.Hi().qc(t.nt,n)}Jf(t){this.vp=!1,this.mp=null!==this.pp,this.Bp();const i=this.Hi().Wc();null!==this.pp&&i.kt()&&(this.bp={x:i.Yt(),y:i.Xt()},this.pp={x:t.localX,y:t.localY})}jf(t){if(null===this.gp)return;const i=t.localX,n=t.localY;if(null===this.pp)this.Ip(t);else{this.mp=!1;const s=f(this.bp),e=s.x+(i-this.pp.x),r=s.y+(n-this.pp.y);this.Ap(e,r,t)}}qf(t){0===this.Cv().W().trackingMode.exitMode&&(this.mp=!0),this.Hp(),this.Lp(t)}pr(t,i){const n=this.gp;return null===n?null:function(t,i,n){const s=t.No(),e=function(t,i,n){var s,e;let r,h;for(const o of t){const t=null!==(e=null===(s=o.oa)||void 0===s?void 0:s.call(o,i,n))&&void 0!==e?e:[];for(const i of t)l=i.zOrder,(!(a=null==r?void 0:r.zOrder)||"top"===l&&"top"!==a||"normal"===l&&"bottom"===a)&&(r=i,h=o)}var l,a;return r&&h?{bv:r,Ec:h}:null}(s,i,n);if("top"===(null==e?void 0:e.bv.zOrder))return Ss(e);for(const r of s){if(e&&e.Ec===r&&"bottom"!==e.bv.zOrder&&!e.bv.isBackground)return Ss(e);const s=ys(r.Cn(t),i,n);if(null!==s)return{Ec:r,vv:s.vv,mv:s.mv};if(e&&e.Ec===r&&"bottom"!==e.bv.zOrder&&e.bv.isBackground)return Ss(e)}return(null==e?void 0:e.bv)?Ss(e):null}(n,t,i)}$p(t,i){f("left"===i?this.ap:this.op).Xv(Gn({width:t,height:this.gv.height}))}Up(){return this.gv}Xv(t){Jn(this.gv,t)||(this.gv=t,this.yv=!0,this.Bv.resizeCanvasElement(t),this.Vv.resizeCanvasElement(t),this.yv=!1,this.Sp.style.width=t.width+"px",this.Sp.style.height=t.height+"px")}qp(){const t=f(this.gp);t.x_(t.S_()),t.x_(t.y_());for(const i of t.Ta())if(t.ur(i)){const n=i.Dt();null!==n&&t.x_(n),i.Rn()}}ep(){return this.Bv.bitmapSize}rp(t,i,n){const s=this.ep();s.width>0&&s.height>0&&t.drawImage(this.Bv.canvasElement,i,n)}Gv(t){if(0===t)return;if(null===this.gp)return;if(t>1&&this.qp(),null!==this.ap&&this.ap.Gv(t),null!==this.op&&this.op.Gv(t),1!==t){this.Bv.applySuggestedBitmapSize();const t=ss(this.Bv);null!==t&&(t.useBitmapCoordinateSpace((t=>{this.Qv(t)})),this.gp&&(this.Yp(t,Ts),this.Xp(t),this.Kp(t),this.Yp(t,Ps),this.Yp(t,Rs)))}this.Vv.applySuggestedBitmapSize();const i=ss(this.Vv);null!==i&&(i.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this.Zp(i),this.Yp(i,Ds))}Gp(){return this.ap}Jp(){return this.op}tp(t,i){this.Yp(t,i)}xp(){null!==this.gp&&this.gp.z_().p(this),this.gp=null}zp(t){this.Ep(this.cp,t)}Ep(t,i){const n=i.localX,s=i.localY;t.M()&&t.m(this.Hi().St().Bu(n),{x:n,y:s},i)}Qv({context:t,bitmapSize:i}){const{width:n,height:s}=i,e=this.Hi(),r=e.q(),h=e._d();r===h?q(t,0,0,n,s,h):Z(t,0,0,n,s,r,h)}Xp(t){const i=f(this.gp).E_().Fh().gt();null!==i&&i.K(t,!1)}Kp(t){const i=this.Hi().Fc();this.Qp(t,Ps,ds,i),this.Qp(t,Ps,fs,i)}Zp(t){this.Qp(t,Ps,fs,this.Hi().Wc())}Yp(t,i){const n=f(this.gp).No();for(const s of n)this.Qp(t,i,ds,s);for(const s of n)this.Qp(t,i,fs,s)}Qp(t,i,n,s){const e=f(this.gp),r=e.$t().Vc(),h=null!==r&&r.Ec===s,l=null!==r&&h&&void 0!==r.mv?r.mv.br:void 0;vs(i,(i=>n(i,t,h,l)),s,e)}Rp(){if(null===this.gp)return;const t=this.Mp,i=this.gp.S_().W().visible,n=this.gp.y_().W().visible;i||null===this.ap||(this.yp.removeChild(this.ap.Hv()),this.ap.S(),this.ap=null),n||null===this.op||(this.kp.removeChild(this.op.Hv()),this.op.S(),this.op=null);const s=t.$t().ed();i&&null===this.ap&&(this.ap=new Cs(this,t.W(),s,"left"),this.yp.appendChild(this.ap.Hv())),n&&null===this.op&&(this.op=new Cs(this,t.W(),s,"right"),this.kp.appendChild(this.op.Hv()))}tm(t){return t.cv&&this.vp||null!==this.pp}im(t){return Math.max(0,Math.min(t,this.gv.width-1))}nm(t){return Math.max(0,Math.min(t,this.gv.height-1))}Ap(t,i,n){this.Hi().Qc(this.im(t),this.nm(i),n,f(this.gp))}Fp(){this.Hi().nd()}Hp(){this.mp&&(this.pp=null,this.Fp())}Np(t,i,n){this.pp=t,this.mp=!1,this.Ap(i.x,i.y,n);const s=this.Hi().Wc();this.bp={x:s.Yt(),y:s.Xt()}}Hi(){return this.Mp.$t()}Lp(t){if(!this.up)return;const i=this.Hi(),n=this.Zv();if(i.D_(n,n.dn()),this._p=null,this.up=!1,i.Zc(),null!==this.wp){const t=performance.now(),n=i.St();this.wp.Pr(n.Iu(),t),this.wp.Yu(t)||i.qn(this.wp)}}Op(){this.pp=null}Bp(){if(!this.gp)return;if(this.Hi().Hn(),document.activeElement!==document.body&&document.activeElement!==document.documentElement)f(document.activeElement).blur();else{const t=document.getSelection();null!==t&&t.removeAllRanges()}!this.gp.dn().Li()&&this.Hi().St().Li()}Ip(t){if(null===this.gp)return;const i=this.Hi(),n=i.St();if(n.Li())return;const s=this.Mp.W(),e=s.handleScroll,r=s.kineticScroll;if((!e.pressedMouseMove||t.cv)&&(!e.horzTouchDrag&&!e.vertTouchDrag||!t.cv))return;const h=this.gp.dn(),l=performance.now();if(null!==this._p||this.tm(t)||(this._p={x:t.clientX,y:t.clientY,kd:l,sm:t.localX,rm:t.localY}),null!==this._p&&!this.up&&(this._p.x!==t.clientX||this._p.y!==t.clientY)){if(t.cv&&r.touch||!t.cv&&r.mouse){const t=n.ee();this.wp=new _s(.2/t,7/t,.997,15/t),this.wp.Fd(n.Iu(),this._p.kd)}else this.wp=null;h.Li()||i.P_(this.gp,h,t.localY),i.Xc(t.localX),this.up=!0}this.up&&(h.Li()||i.R_(this.gp,h,t.localY),i.Kc(t.localX),null!==this.wp&&this.wp.Fd(n.Iu(),l))}}class As{constructor(t,i,n,s,e){this.ft=!0,this.gv=Gn({width:0,height:0}),this.kv=()=>this.Gv(3),this.Pv="left"===t,this.kc=n.ed,this._n=i,this.hm=s,this.lm=e,this.Av=document.createElement("div"),this.Av.style.width="25px",this.Av.style.height="100%",this.Av.style.overflow="hidden",this.Bv=us(this.Av,Gn({width:16,height:16})),this.Bv.subscribeSuggestedBitmapSizeChanged(this.kv)}S(){this.Bv.unsubscribeSuggestedBitmapSizeChanged(this.kv),cs(this.Bv.canvasElement),this.Bv.dispose()}Hv(){return this.Av}Up(){return this.gv}Xv(t){Jn(this.gv,t)||(this.gv=t,this.Bv.resizeCanvasElement(t),this.Av.style.width=`${t.width}px`,this.Av.style.height=`${t.height}px`,this.ft=!0)}Gv(t){if(t<3&&!this.ft)return;if(0===this.gv.width||0===this.gv.height)return;this.ft=!1,this.Bv.applySuggestedBitmapSize();const i=ss(this.Bv);null!==i&&i.useBitmapCoordinateSpace((t=>{this.Qv(t),this.Ae(t)}))}ep(){return this.Bv.bitmapSize}rp(t,i,n){const s=this.ep();s.width>0&&s.height>0&&t.drawImage(this.Bv.canvasElement,i,n)}Ae({context:t,bitmapSize:i,horizontalPixelRatio:n,verticalPixelRatio:s}){if(!this.hm())return;t.fillStyle=this._n.timeScale.borderColor;const e=Math.floor(this.kc.W().C*n),r=Math.floor(this.kc.W().C*s),h=this.Pv?i.width-e:0;t.fillRect(h,0,e,r)}Qv({context:t,bitmapSize:i}){q(t,0,0,i.width,i.height,this.lm())}}function Bs(t){return i=>{var n,s;return null!==(s=null===(n=i.aa)||void 0===n?void 0:n.call(i,t))&&void 0!==s?s:[]}}const Vs=Bs("normal"),zs=Bs("top"),Es=Bs("bottom");class Is{constructor(t,i){this.am=null,this.om=null,this.k=null,this._m=!1,this.gv=Gn({width:0,height:0}),this.um=new k,this.xv=new Jt(5),this.yv=!1,this.kv=()=>{this.yv||this.Mp.$t().Nh()},this.Tv=()=>{this.yv||this.Mp.$t().Nh()},this.Mp=t,this.N_=i,this._n=t.W().layout,this.dm=document.createElement("tr"),this.fm=document.createElement("td"),this.fm.style.padding="0",this.vm=document.createElement("td"),this.vm.style.padding="0",this.Av=document.createElement("td"),this.Av.style.height="25px",this.Av.style.padding="0",this.pm=document.createElement("div"),this.pm.style.width="100%",this.pm.style.height="100%",this.pm.style.position="relative",this.pm.style.overflow="hidden",this.Av.appendChild(this.pm),this.Bv=us(this.pm,Gn({width:16,height:16})),this.Bv.subscribeSuggestedBitmapSizeChanged(this.kv);const n=this.Bv.canvasElement;n.style.position="absolute",n.style.zIndex="1",n.style.left="0",n.style.top="0",this.Vv=us(this.pm,Gn({width:16,height:16})),this.Vv.subscribeSuggestedBitmapSizeChanged(this.Tv);const s=this.Vv.canvasElement;s.style.position="absolute",s.style.zIndex="2",s.style.left="0",s.style.top="0",this.dm.appendChild(this.fm),this.dm.appendChild(this.Av),this.dm.appendChild(this.vm),this.bm(),this.Mp.$t().f_().l(this.bm.bind(this),this),this.jv=new ms(this.Vv.canvasElement,this,{Ff:()=>!0,Wf:()=>!this.Mp.W().handleScroll.horzTouchDrag})}S(){this.jv.S(),null!==this.am&&this.am.S(),null!==this.om&&this.om.S(),this.Vv.unsubscribeSuggestedBitmapSizeChanged(this.Tv),cs(this.Vv.canvasElement),this.Vv.dispose(),this.Bv.unsubscribeSuggestedBitmapSizeChanged(this.kv),cs(this.Bv.canvasElement),this.Bv.dispose()}Hv(){return this.dm}wm(){return this.am}gm(){return this.om}tv(t){if(this._m)return;this._m=!0;const i=this.Mp.$t();!i.St().Li()&&this.Mp.W().handleScale.axisPressedMouseMove.time&&i.Uc(t.localX)}Jf(t){this.tv(t)}iv(){const t=this.Mp.$t();!t.St().Li()&&this._m&&(this._m=!1,this.Mp.W().handleScale.axisPressedMouseMove.time&&t.Jc())}$f(t){const i=this.Mp.$t();!i.St().Li()&&this.Mp.W().handleScale.axisPressedMouseMove.time&&i.Gc(t.localX)}jf(t){this.$f(t)}Xf(){this._m=!1;const t=this.Mp.$t();t.St().Li()&&!this.Mp.W().handleScale.axisPressedMouseMove.time||t.Jc()}qf(){this.Xf()}Pf(){this.Mp.W().handleScale.axisDoubleClickReset.time&&this.Mp.$t().Xn()}yf(){this.Pf()}zf(){this.Mp.$t().W().handleScale.axisPressedMouseMove.time&&this.hp(1)}_v(){this.hp(0)}Up(){return this.gv}Mm(){return this.um}xm(t,i,n){Jn(this.gv,t)||(this.gv=t,this.yv=!0,this.Bv.resizeCanvasElement(t),this.Vv.resizeCanvasElement(t),this.yv=!1,this.Av.style.width=`${t.width}px`,this.Av.style.height=`${t.height}px`,this.um.m(t)),null!==this.am&&this.am.Xv(Gn({width:i,height:t.height})),null!==this.om&&this.om.Xv(Gn({width:n,height:t.height}))}Sm(){const t=this.ym();return Math.ceil(t.C+t.T+t.P+t.L+t.B+t.km)}bt(){this.Mp.$t().St().Ia()}ep(){return this.Bv.bitmapSize}rp(t,i,n){const s=this.ep();s.width>0&&s.height>0&&t.drawImage(this.Bv.canvasElement,i,n)}Gv(t){if(0===t)return;if(1!==t){this.Bv.applySuggestedBitmapSize();const i=ss(this.Bv);null!==i&&(i.useBitmapCoordinateSpace((t=>{this.Qv(t),this.Ae(t),this.Cm(i,Es)})),this.ip(i),this.Cm(i,Vs)),null!==this.am&&this.am.Gv(t),null!==this.om&&this.om.Gv(t)}this.Vv.applySuggestedBitmapSize();const i=ss(this.Vv);null!==i&&(i.useBitmapCoordinateSpace((({context:t,bitmapSize:i})=>{t.clearRect(0,0,i.width,i.height)})),this.Tm([...this.Mp.$t().wt(),this.Mp.$t().Wc()],i),this.Cm(i,zs))}Cm(t,i){const n=this.Mp.$t().wt();for(const s of n)vs(i,(i=>ds(i,t,!1,void 0)),s,void 0);for(const s of n)vs(i,(i=>fs(i,t,!1,void 0)),s,void 0)}Qv({context:t,bitmapSize:i}){q(t,0,0,i.width,i.height,this.Mp.$t()._d())}Ae({context:t,bitmapSize:i,verticalPixelRatio:n}){if(this.Mp.W().timeScale.borderVisible){t.fillStyle=this.Pm();const s=Math.max(1,Math.floor(this.ym().C*n));t.fillRect(0,0,i.width,s)}}ip(t){const i=this.Mp.$t().St(),n=i.Ia();if(!n||0===n.length)return;const s=this.N_.maxTickMarkWeight(n),e=this.ym(),r=i.W();r.borderVisible&&r.ticksVisible&&t.useBitmapCoordinateSpace((({context:t,horizontalPixelRatio:i,verticalPixelRatio:s})=>{t.strokeStyle=this.Pm(),t.fillStyle=this.Pm();const r=Math.max(1,Math.floor(i)),h=Math.floor(.5*i);t.beginPath();const l=Math.round(e.T*s);for(let s=n.length;s--;){const e=Math.round(n[s].coord*i);t.rect(e-h,0,r,l)}t.fill()})),t.useMediaCoordinateSpace((({context:t})=>{const i=e.C+e.T+e.L+e.P/2;t.textAlign="center",t.textBaseline="middle",t.fillStyle=this.$(),t.font=this.qv();for(const e of n)if(e.weight=s){const n=e.needAlignCoordinate?this.Rm(t,e.coord,e.label):e.coord;t.fillText(e.label,n,i)}}))}Rm(t,i,n){const s=this.xv.Mi(t,n),e=s/2,r=Math.floor(i-e)+.5;return r<0?i+=Math.abs(0-r):r+s>this.gv.width&&(i-=Math.abs(this.gv.width-(r+s))),i}Tm(t,i){const n=this.ym();for(const s of t)for(const t of s.Ji())t.gt().K(i,n)}Pm(){return this.Mp.W().timeScale.borderColor}$(){return this._n.textColor}j(){return this._n.fontSize}qv(){return z(this.j(),this._n.fontFamily)}Dm(){return z(this.j(),this._n.fontFamily,"bold")}ym(){null===this.k&&(this.k={C:1,N:NaN,L:NaN,B:NaN,Wi:NaN,T:5,P:NaN,R:"",Fi:new Jt,km:0});const t=this.k,i=this.qv();if(t.R!==i){const n=this.j();t.P=n,t.R=i,t.L=3*n/12,t.B=3*n/12,t.Wi=9*n/12,t.N=0,t.km=4*n/12,t.Fi.Qe()}return this.k}hp(t){this.Av.style.cursor=1===t?"ew-resize":"default"}bm(){const t=this.Mp.$t(),i=t.W();i.leftPriceScale.visible||null===this.am||(this.fm.removeChild(this.am.Hv()),this.am.S(),this.am=null),i.rightPriceScale.visible||null===this.om||(this.vm.removeChild(this.om.Hv()),this.om.S(),this.om=null);const n={ed:this.Mp.$t().ed()},s=()=>i.leftPriceScale.borderVisible&&t.St().W().borderVisible,e=()=>t._d();i.leftPriceScale.visible&&null===this.am&&(this.am=new As("left",i,n,s,e),this.fm.appendChild(this.am.Hv())),i.rightPriceScale.visible&&null===this.om&&(this.om=new As("right",i,n,s,e),this.vm.appendChild(this.om.Hv()))}}const Ls=!!es&&!!navigator.userAgentData&&navigator.userAgentData.brands.some((t=>t.brand.includes("Chromium")))&&!!es&&((null===(Ns=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Ns?void 0:Ns.platform)?"Windows"===navigator.userAgentData.platform:navigator.userAgent.toLowerCase().indexOf("win")>=0);var Ns;class Fs{constructor(t,i,n){var s;this.Om=[],this.Am=0,this.Qa=0,this.e_=0,this.Bm=0,this.Vm=0,this.zm=null,this.Em=!1,this.cp=new k,this.dp=new k,this.xc=new k,this.Im=null,this.Lm=null,this.Nm=t,this._n=i,this.N_=n,this.dm=document.createElement("div"),this.dm.classList.add("tv-lightweight-charts"),this.dm.style.overflow="hidden",this.dm.style.direction="ltr",this.dm.style.width="100%",this.dm.style.height="100%",(s=this.dm).style.userSelect="none",s.style.webkitUserSelect="none",s.style.msUserSelect="none",s.style.MozUserSelect="none",s.style.webkitTapHighlightColor="transparent",this.Fm=document.createElement("table"),this.Fm.setAttribute("cellspacing","0"),this.dm.appendChild(this.Fm),this.Wm=this.jm.bind(this),Ws(this._n)&&this.Hm(!0),this.Hi=new An(this.yc.bind(this),this._n,n),this.$t().jc().l(this.$m.bind(this),this),this.Um=new Is(this,this.N_),this.Fm.appendChild(this.Um.Hv());const e=i.autoSize&&this.qm();let r=this._n.width,h=this._n.height;if(e||0===r||0===h){const i=t.getBoundingClientRect();r=r||i.width,h=h||i.height}this.Ym(r,h),this.Xm(),t.appendChild(this.dm),this.Km(),this.Hi.St().Gu().l(this.Hi.$l.bind(this.Hi),this),this.Hi.f_().l(this.Hi.$l.bind(this.Hi),this)}$t(){return this.Hi}W(){return this._n}Zm(){return this.Om}Gm(){return this.Um}S(){this.Hm(!1),0!==this.Am&&window.cancelAnimationFrame(this.Am),this.Hi.jc().p(this),this.Hi.St().Gu().p(this),this.Hi.f_().p(this),this.Hi.S();for(const t of this.Om)this.Fm.removeChild(t.Hv()),t.Wp().p(this),t.jp().p(this),t.S();this.Om=[],f(this.Um).S(),null!==this.dm.parentElement&&this.dm.parentElement.removeChild(this.dm),this.xc.S(),this.cp.S(),this.dp.S(),this.Jm()}Ym(t,i,n=!1){if(this.Qa===i&&this.e_===t)return;const s=function(t){const i=Math.floor(t.width),n=Math.floor(t.height);return Gn({width:i-i%2,height:n-n%2})}(Gn({width:t,height:i}));this.Qa=s.height,this.e_=s.width;const e=this.Qa+"px",r=this.e_+"px";f(this.dm).style.height=e,f(this.dm).style.width=r,this.Fm.style.height=e,this.Fm.style.width=r,n?this.Qm(lt.ns(),performance.now()):this.Hi.$l()}Gv(t){void 0===t&&(t=lt.ns());for(let i=0;i{let s=0;for(let e=0;e{f("left"===i?this.Um.wm():this.Um.gm()).rp(f(t),n,s)};if(this._n.timeScale.visible){const i=this.Um.ep();if(null!==t){let e=0;this.eb()&&(r("left",e,n),e=f(s.Gp()).ep().width),this.Um.rp(t,e,n),e+=i.width,this.rb()&&r("right",e,n)}n+=i.height}return Gn({width:i,height:n})}_b(){let t=0,i=0,n=0;for(const s of this.Om)this.eb()&&(i=Math.max(i,f(s.Gp()).Uv(),this._n.leftPriceScale.minimumWidth)),this.rb()&&(n=Math.max(n,f(s.Jp()).Uv(),this._n.rightPriceScale.minimumWidth)),t+=s.v_();i=ls(i),n=ls(n);const s=this.e_,e=this.Qa,r=Math.max(s-i-n,0),h=this._n.timeScale.visible;let l=h?Math.max(this.Um.Sm(),this._n.timeScale.minimumHeight):0;var a;l=(a=l)+a%2;const o=0+l,_=e{t.Dp()})),3===(null===(n=this.zm)||void 0===n?void 0:n.Fn())&&(this.zm.Jn(t),this.cb(),this.fb(this.zm),this.vb(this.zm,i),t=this.zm,this.zm=null)),this.Gv(t)}vb(t,i){for(const n of t.Gn())this.Qn(n,i)}fb(t){const i=this.Hi.Nc();for(let n=0;n{if(this.Em=!1,this.Am=0,null!==this.zm){const i=this.zm;this.zm=null,this.Qm(i,t);for(const n of i.Gn())if(5===n.$n&&!n.Ot.Yu(t)){this.$t().qn(n.Ot);break}}})))}cb(){this.Xm()}Xm(){const t=this.Hi.Nc(),i=t.length,n=this.Om.length;for(let t=i;t{const n=i.Bn().il(t);null!==n&&e.set(i,n)}))}let r;if(null!==t){const i=null===(s=this.Hi.St().$i(t))||void 0===s?void 0:s.originalTime;void 0!==i&&(r=i)}const h=this.$t().Vc(),l=null!==h&&h.Ec instanceof qi?h.Ec:void 0,a=null!==h&&void 0!==h.mv?h.mv.mr:void 0;return{wb:r,ie:null!=t?t:void 0,gb:null!=i?i:void 0,Mb:l,xb:e,Sb:a,yb:null!=n?n:void 0}}pb(t,i,n){this.cp.m((()=>this.bb(t,i,n)))}mb(t,i,n){this.dp.m((()=>this.bb(t,i,n)))}$m(t,i,n){this.xc.m((()=>this.bb(t,i,n)))}Km(){const t=this._n.timeScale.visible?"":"none";this.Um.Hv().style.display=t}eb(){return this.Om[0].Zv().S_().W().visible}rb(){return this.Om[0].Zv().y_().W().visible}qm(){return"ResizeObserver"in window&&(this.Im=new ResizeObserver((t=>{const i=t.find((t=>t.target===this.Nm));i&&this.Ym(i.contentRect.width,i.contentRect.height)})),this.Im.observe(this.Nm,{box:"border-box"}),!0)}Jm(){null!==this.Im&&this.Im.disconnect(),this.Im=null}}function Ws(t){return Boolean(t.handleScroll.mouseWheel||t.handleScale.mouseWheel)}function js(t,i){var n={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&i.indexOf(s)<0&&(n[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var e=0;for(s=Object.getOwnPropertySymbols(t);efunction(t,i){return i?i(t):void 0===(n=t).open&&void 0===n.value;var n}(s,h)?Zs({ot:i,ie:n,wb:e},s):Zs(t(i,n,s,e,r),s)}function Js(t){return{Candlestick:Gs(Ys),Bar:Gs(qs),Area:Gs($s),Baseline:Gs(Us),Histogram:Gs(Hs),Line:Gs(Hs),Custom:Gs(Xs)}[t]}function Qs(t){return{ie:0,Cb:new Map,ia:t}}function te(t,i){if(void 0!==t&&0!==t.length)return{Tb:i.key(t[0].ot),Pb:i.key(t[t.length-1].ot)}}function ie(t){let i;return t.forEach((t=>{void 0===i&&(i=t.wb)})),d(i)}class ne{constructor(t){this.Rb=new Map,this.Db=new Map,this.Ob=new Map,this.Ab=[],this.N_=t}S(){this.Rb.clear(),this.Db.clear(),this.Ob.clear(),this.Ab=[]}Bb(t,i){let n=0!==this.Rb.size,s=!1;const e=this.Db.get(t);if(void 0!==e)if(1===this.Db.size)n=!1,s=!0,this.Rb.clear();else for(const i of this.Ab)i.pointData.Cb.delete(t)&&(s=!0);let r=[];if(0!==i.length){const n=i.map((t=>t.time)),e=this.N_.createConverterToInternalObj(i),h=Js(t.Yh()),l=t.ga(),a=t.Ma();r=i.map(((i,r)=>{const o=e(i.time),_=this.N_.key(o);let u=this.Rb.get(_);void 0===u&&(u=Qs(o),this.Rb.set(_,u),s=!0);const c=h(o,u.ie,i,n[r],l,a);return u.Cb.set(t,c),c}))}n&&this.Vb(),this.zb(t,r);let h=-1;if(s){const t=[];this.Rb.forEach((i=>{t.push({timeWeight:0,time:i.ia,pointData:i,originalTime:ie(i.Cb)})})),t.sort(((t,i)=>this.N_.key(t.time)-this.N_.key(i.time))),h=this.Eb(t)}return this.Ib(t,h,function(t,i,n){const s=te(t,n),e=te(i,n);if(void 0!==s&&void 0!==e)return{Xl:s.Pb>=e.Pb&&s.Tb>=e.Tb}}(this.Db.get(t),e,this.N_))}ld(t){return this.Bb(t,[])}Lb(t,i){const n=i;!function(t){void 0===t.wb&&(t.wb=t.time)}(n),this.N_.preprocessData(i);const s=this.N_.createConverterToInternalObj([i])(i.time),e=this.Ob.get(t);if(void 0!==e&&this.N_.key(s)this.N_.key(t.time)this.N_.key(s.ot)?Ks(i)&&n.push(i):Ks(i)?n[n.length-1]=i:n.splice(-1,1),this.Ob.set(t,i.ot)}zb(t,i){0!==i.length?(this.Db.set(t,i.filter(Ks)),this.Ob.set(t,i[i.length-1].ot)):(this.Db.delete(t),this.Ob.delete(t))}Vb(){for(const t of this.Ab)0===t.pointData.Cb.size&&this.Rb.delete(this.N_.key(t.time))}Eb(t){let i=-1;for(let n=0;n{0!==i.length&&(t=Math.max(t,i[i.length-1].ie))})),t}Ib(t,i,n){const s={Wb:new Map,St:{Au:this.Fb()}};if(-1!==i)this.Db.forEach(((i,e)=>{s.Wb.set(e,{We:i,jb:e===t?n:void 0})})),this.Db.has(t)||s.Wb.set(t,{We:[],jb:n}),s.St.Hb=this.Ab,s.St.$b=i;else{const i=this.Db.get(t);s.Wb.set(t,{We:i||[],jb:n})}return s}}function se(t,i){t.ie=i,t.Cb.forEach((t=>{t.ie=i}))}function ee(t){const i={value:t.Ot[3],time:t.wb};return void 0!==t.kb&&(i.customValues=t.kb),i}function re(t){const i=ee(t);return void 0!==t.O&&(i.color=t.O),i}function he(t){const i=ee(t);return void 0!==t.lt&&(i.lineColor=t.lt),void 0!==t.ks&&(i.topColor=t.ks),void 0!==t.Cs&&(i.bottomColor=t.Cs),i}function le(t){const i=ee(t);return void 0!==t.Ce&&(i.topLineColor=t.Ce),void 0!==t.Te&&(i.bottomLineColor=t.Te),void 0!==t.Me&&(i.topFillColor1=t.Me),void 0!==t.xe&&(i.topFillColor2=t.xe),void 0!==t.Se&&(i.bottomFillColor1=t.Se),void 0!==t.ye&&(i.bottomFillColor2=t.ye),i}function ae(t){const i={open:t.Ot[0],high:t.Ot[1],low:t.Ot[2],close:t.Ot[3],time:t.wb};return void 0!==t.kb&&(i.customValues=t.kb),i}function oe(t){const i=ae(t);return void 0!==t.O&&(i.color=t.O),i}function _e(t){const i=ae(t),{O:n,At:s,Hh:e}=t;return void 0!==n&&(i.color=n),void 0!==s&&(i.borderColor=s),void 0!==e&&(i.wickColor=e),i}function ue(t){return{Area:he,Line:re,Baseline:le,Histogram:re,Bar:oe,Candlestick:_e,Custom:ce}[t]}function ce(t){const i=t.wb;return Object.assign(Object.assign({},t.We),{time:i})}const de={vertLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},horzLine:{color:"#9598A1",width:1,style:3,visible:!0,labelVisible:!0,labelBackgroundColor:"#131722"},mode:1},fe={vertLines:{color:"#D6DCDE",style:0,visible:!0},horzLines:{color:"#D6DCDE",style:0,visible:!0}},ve={background:{type:"solid",color:"#FFFFFF"},textColor:"#191919",fontSize:12,fontFamily:V},pe={autoScale:!0,mode:0,invertScale:!1,alignLabels:!0,borderVisible:!0,borderColor:"#2B2B43",entireTextOnly:!1,visible:!1,ticksVisible:!1,scaleMargins:{bottom:.1,top:.2},minimumWidth:0},me={rightOffset:0,barSpacing:6,minBarSpacing:.5,fixLeftEdge:!1,fixRightEdge:!1,lockVisibleTimeRangeOnResize:!1,rightBarStaysOnScroll:!1,borderVisible:!0,borderColor:"#2B2B43",visible:!0,timeVisible:!1,secondsVisible:!0,shiftVisibleRangeOnNewBar:!0,allowShiftVisibleRangeOnWhitespaceReplacement:!1,ticksVisible:!1,uniformDistribution:!1,minimumHeight:0,allowBoldLabels:!0},be={color:"rgba(0, 0, 0, 0)",visible:!1,fontSize:48,fontFamily:V,fontStyle:"",text:"",horzAlign:"center",vertAlign:"center"};function we(){return{width:0,height:0,autoSize:!1,layout:ve,crosshair:de,grid:fe,overlayPriceScales:Object.assign({},pe),leftPriceScale:Object.assign(Object.assign({},pe),{visible:!1}),rightPriceScale:Object.assign(Object.assign({},pe),{visible:!0}),timeScale:me,watermark:be,localization:{locale:es?navigator.language:"",dateFormat:"dd MMM 'yy"},handleScroll:{mouseWheel:!0,pressedMouseMove:!0,horzTouchDrag:!0,vertTouchDrag:!0},handleScale:{axisPressedMouseMove:{time:!0,price:!0},axisDoubleClickReset:{time:!0,price:!0},mouseWheel:!0,pinch:!0},kineticScroll:{mouse:!1,touch:!0},trackingMode:{exitMode:1}}}class ge{constructor(t,i){this.Ub=t,this.qb=i}applyOptions(t){this.Ub.$t().Ic(this.qb,t)}options(){return this.Ei().W()}width(){return ht(this.qb)?this.Ub.sb(this.qb):0}Ei(){return f(this.Ub.$t().Lc(this.qb)).Dt}}function Me(t,i,n){const s=js(t,["time","originalTime"]),e=Object.assign({time:i},s);return void 0!==n&&(e.originalTime=n),e}const xe={color:"#FF0000",price:0,lineStyle:2,lineWidth:1,lineVisible:!0,axisLabelVisible:!0,title:"",axisLabelColor:"",axisLabelTextColor:""};class Se{constructor(t){this.Bh=t}applyOptions(t){this.Bh.Lh(t)}options(){return this.Bh.W()}Yb(){return this.Bh}}class ye{constructor(t,i,n,s,e){this.Xb=new k,this.zs=t,this.Kb=i,this.Zb=n,this.N_=e,this.Gb=s}S(){this.Xb.S()}priceFormatter(){return this.zs.ca()}priceToCoordinate(t){const i=this.zs.Ct();return null===i?null:this.zs.Dt().Rt(t,i.Ot)}coordinateToPrice(t){const i=this.zs.Ct();return null===i?null:this.zs.Dt().fn(t,i.Ot)}barsInLogicalRange(t){if(null===t)return null;const i=new gn(new mn(t.from,t.to)).iu(),n=this.zs.Bn();if(n.Li())return null;const s=n.il(i.Rs(),1),e=n.il(i.ui(),-1),r=f(n.Jh()),h=f(n.An());if(null!==s&&null!==e&&s.ie>e.ie)return{barsBefore:t.from-r,barsAfter:h-t.to};const l={barsBefore:null===s||s.ie===r?t.from-r:s.ie-r,barsAfter:null===e||e.ie===h?h-t.to:h-e.ie};return null!==s&&null!==e&&(l.from=s.wb,l.to=e.wb),l}setData(t){this.N_,this.zs.Yh(),this.Kb.Jb(this.zs,t),this.Qb("full")}update(t){this.zs.Yh(),this.Kb.tw(this.zs,t),this.Qb("update")}dataByIndex(t,i){const n=this.zs.Bn().il(t,i);if(null===n)return null;return ue(this.seriesType())(n)}data(){const t=ue(this.seriesType());return this.zs.Bn().Qs().map((i=>t(i)))}subscribeDataChanged(t){this.Xb.l(t)}unsubscribeDataChanged(t){this.Xb.v(t)}setMarkers(t){this.N_;const i=t.map((t=>Me(t,this.N_.convertHorzItemToInternal(t.time),t.time)));this.zs.Zl(i)}markers(){return this.zs.Gl().map((t=>Me(t,t.originalTime,void 0)))}applyOptions(t){this.zs.Lh(t)}options(){return O(this.zs.W())}priceScale(){return this.Zb.priceScale(this.zs.Dt().xa())}createPriceLine(t){const i=C(O(xe),t),n=this.zs.Jl(i);return new Se(n)}removePriceLine(t){this.zs.Ql(t.Yb())}seriesType(){return this.zs.Yh()}attachPrimitive(t){this.zs.ba(t),t.attached&&t.attached({chart:this.Gb,series:this,requestUpdate:()=>this.zs.$t().$l()})}detachPrimitive(t){this.zs.wa(t),t.detached&&t.detached()}Qb(t){this.Xb.M()&&this.Xb.m(t)}}class ke{constructor(t,i,n){this.iw=new k,this.uu=new k,this.um=new k,this.Hi=t,this.wl=t.St(),this.Um=i,this.wl.Ku().l(this.nw.bind(this)),this.wl.Zu().l(this.sw.bind(this)),this.Um.Mm().l(this.ew.bind(this)),this.N_=n}S(){this.wl.Ku().p(this),this.wl.Zu().p(this),this.Um.Mm().p(this),this.iw.S(),this.uu.S(),this.um.S()}scrollPosition(){return this.wl.Iu()}scrollToPosition(t,i){i?this.wl.qu(t,1e3):this.Hi.Zn(t)}scrollToRealTime(){this.wl.Uu()}getVisibleRange(){const t=this.wl.ku();return null===t?null:{from:t.from.originalTime,to:t.to.originalTime}}setVisibleRange(t){const i={from:this.N_.convertHorzItemToInternal(t.from),to:this.N_.convertHorzItemToInternal(t.to)},n=this.wl.Ru(i);this.Hi.ad(n)}getVisibleLogicalRange(){const t=this.wl.yu();return null===t?null:{from:t.Rs(),to:t.ui()}}setVisibleLogicalRange(t){c(t.from<=t.to,"The from index cannot be after the to index."),this.Hi.ad(t)}resetTimeScale(){this.Hi.Xn()}fitContent(){this.Hi.Qu()}logicalToCoordinate(t){const i=this.Hi.St();return i.Li()?null:i.zt(t)}coordinateToLogical(t){return this.wl.Li()?null:this.wl.Bu(t)}timeToCoordinate(t){const i=this.N_.convertHorzItemToInternal(t),n=this.wl.ka(i,!1);return null===n?null:this.wl.zt(n)}coordinateToTime(t){const i=this.Hi.St(),n=i.Bu(t),s=i.$i(n);return null===s?null:s.originalTime}width(){return this.Um.Up().width}height(){return this.Um.Up().height}subscribeVisibleTimeRangeChange(t){this.iw.l(t)}unsubscribeVisibleTimeRangeChange(t){this.iw.v(t)}subscribeVisibleLogicalRangeChange(t){this.uu.l(t)}unsubscribeVisibleLogicalRangeChange(t){this.uu.v(t)}subscribeSizeChange(t){this.um.l(t)}unsubscribeSizeChange(t){this.um.v(t)}applyOptions(t){this.wl.Lh(t)}options(){return Object.assign(Object.assign({},O(this.wl.W())),{barSpacing:this.wl.ee()})}nw(){this.iw.M()&&this.iw.m(this.getVisibleRange())}sw(){this.uu.M()&&this.uu.m(this.getVisibleLogicalRange())}ew(t){this.um.m(t.width,t.height)}}function Ce(t){if(void 0===t||"custom"===t.type)return;const i=t;void 0!==i.minMove&&void 0===i.precision&&(i.precision=function(t){if(t>=1)return 0;let i=0;for(;i<8;i++){const n=Math.round(t);if(Math.abs(n-t)<1e-8)return i;t*=10}return i}(i.minMove))}function Te(t){return function(t){if(D(t.handleScale)){const i=t.handleScale;t.handleScale={axisDoubleClickReset:{time:i,price:i},axisPressedMouseMove:{time:i,price:i},mouseWheel:i,pinch:i}}else if(void 0!==t.handleScale){const{axisPressedMouseMove:i,axisDoubleClickReset:n}=t.handleScale;D(i)&&(t.handleScale.axisPressedMouseMove={time:i,price:i}),D(n)&&(t.handleScale.axisDoubleClickReset={time:n,price:n})}const i=t.handleScroll;D(i)&&(t.handleScroll={horzTouchDrag:i,vertTouchDrag:i,mouseWheel:i,pressedMouseMove:i})}(t),t}class Pe{constructor(t,i,n){this.rw=new Map,this.hw=new Map,this.lw=new k,this.aw=new k,this.ow=new k,this._w=new ne(i);const s=void 0===n?O(we()):C(O(we()),Te(n));this.N_=i,this.Ub=new Fs(t,s,i),this.Ub.Wp().l((t=>{this.lw.M()&&this.lw.m(this.uw(t()))}),this),this.Ub.jp().l((t=>{this.aw.M()&&this.aw.m(this.uw(t()))}),this),this.Ub.jc().l((t=>{this.ow.M()&&this.ow.m(this.uw(t()))}),this);const e=this.Ub.$t();this.cw=new ke(e,this.Ub.Gm(),this.N_)}remove(){this.Ub.Wp().p(this),this.Ub.jp().p(this),this.Ub.jc().p(this),this.cw.S(),this.Ub.S(),this.rw.clear(),this.hw.clear(),this.lw.S(),this.aw.S(),this.ow.S(),this._w.S()}resize(t,i,n){this.autoSizeActive()||this.Ub.Ym(t,i,n)}addCustomSeries(t,i){const n=v(t),s=Object.assign(Object.assign({},h),n.defaultOptions());return this.dw("Custom",s,i,n)}addAreaSeries(t){return this.dw("Area",s,t)}addBaselineSeries(t){return this.dw("Baseline",e,t)}addBarSeries(t){return this.dw("Bar",i,t)}addCandlestickSeries(i={}){return function(t){void 0!==t.borderColor&&(t.borderUpColor=t.borderColor,t.borderDownColor=t.borderColor),void 0!==t.wickColor&&(t.wickUpColor=t.wickColor,t.wickDownColor=t.wickColor)}(i),this.dw("Candlestick",t,i)}addHistogramSeries(t){return this.dw("Histogram",r,t)}addLineSeries(t){return this.dw("Line",n,t)}removeSeries(t){const i=d(this.rw.get(t)),n=this._w.ld(i);this.Ub.$t().ld(i),this.fw(n),this.rw.delete(t),this.hw.delete(i)}Jb(t,i){this.fw(this._w.Bb(t,i))}tw(t,i){this.fw(this._w.Lb(t,i))}subscribeClick(t){this.lw.l(t)}unsubscribeClick(t){this.lw.v(t)}subscribeCrosshairMove(t){this.ow.l(t)}unsubscribeCrosshairMove(t){this.ow.v(t)}subscribeDblClick(t){this.aw.l(t)}unsubscribeDblClick(t){this.aw.v(t)}priceScale(t){return new ge(this.Ub,t)}timeScale(){return this.cw}applyOptions(t){this.Ub.Lh(Te(t))}options(){return this.Ub.W()}takeScreenshot(){return this.Ub.ib()}autoSizeActive(){return this.Ub.hb()}chartElement(){return this.Ub.lb()}paneSize(){const t=this.Ub.ob();return{height:t.height,width:t.width}}setCrosshairPosition(t,i,n){const s=this.rw.get(n);if(void 0===s)return;const e=this.Ub.$t()._r(s);null!==e&&this.Ub.$t().td(t,i,e)}clearCrosshairPosition(){this.Ub.$t().nd(!0)}dw(t,i,n={},s){Ce(n.priceFormat);const e=C(O(l),O(i),n),r=this.Ub.$t().rd(t,e,s),h=new ye(r,this,this,this,this.N_);return this.rw.set(h,r),this.hw.set(r,h),h}fw(t){const i=this.Ub.$t();i.sd(t.St.Au,t.St.Hb,t.St.$b),t.Wb.forEach(((t,i)=>i.J(t.We,t.jb))),i.zu()}pw(t){return d(this.hw.get(t))}uw(t){const i=new Map;t.xb.forEach(((t,n)=>{const s=n.Yh(),e=ue(s)(t);if("Custom"!==s)c(function(t){return void 0!==t.open||void 0!==t.value}(e));else{const t=n.Ma();c(!t||!1===t(e))}i.set(this.pw(n),e)}));const n=void 0===t.Mb?void 0:this.pw(t.Mb);return{time:t.wb,logical:t.ie,point:t.gb,hoveredSeries:n,hoveredObjectId:t.Sb,seriesData:i,sourceEvent:t.yb}}}function Re(t,i,n){let s;if(R(t)){const i=document.getElementById(t);c(null!==i,`Cannot find element in DOM with id=${t}`),s=i}else s=t;const e=new Pe(s,i,n);return i.setOptions(e.options()),e}const De=Object.assign(Object.assign({},l),h);var Oe=Object.freeze({__proto__:null,get ColorType(){return Dn},get CrosshairMode(){return et},get LastPriceAnimationMode(){return Pn},get LineStyle(){return o},get LineType(){return a},get MismatchDirection(){return Ai},get PriceLineSource(){return Rn},get PriceScaleMode(){return un},get TickMarkType(){return On},get TrackingModeExitMode(){return Tn},createChart:function(t,i){return Re(t,new Zn,Zn.Pd(i))},createChartEx:Re,customSeriesDefaultOptions:De,isBusinessDay:Bn,isUTCTimestamp:Vn,version:function(){return"4.1.3"}});window.LightweightCharts=Oe}();
\ No newline at end of file
diff --git a/lightweight_charts/__init__.py b/lightweight_charts_esistjosh/__init__.py
similarity index 100%
rename from lightweight_charts/__init__.py
rename to lightweight_charts_esistjosh/__init__.py
diff --git a/lightweight_charts_esistjosh/abstract.py b/lightweight_charts_esistjosh/abstract.py
new file mode 100644
index 00000000..66826a4d
--- /dev/null
+++ b/lightweight_charts_esistjosh/abstract.py
@@ -0,0 +1,1821 @@
+import asyncio
+import json
+import os
+from base64 import b64decode
+from datetime import datetime
+from typing import Callable, Union, Literal, List, Optional, Any
+import pandas as pd
+from webview.errors import JavascriptException
+import shutil
+from typing import Optional
+from .table import Table
+from .toolbox import ToolBox
+from .drawings import Box, HorizontalLine, RayLine, TrendLine, TwoPointDrawing, VerticalLine, VerticalSpan
+from .topbar import TopBar
+from .util import (
+ BulkRunScript, Pane, Events, IDGen, as_enum, jbool, js_json, TIME, NUM, FLOAT,
+ LINE_STYLE, MARKER_POSITION, MARKER_SHAPE, CANDLE_SHAPE, CROSSHAIR_MODE,
+ PRICE_SCALE_MODE, TOOLBOX_MODE, marker_position, marker_shape, js_data,
+)
+
+current_dir = os.path.dirname(os.path.abspath(__file__))
+INDEX = os.path.join(current_dir, 'js', 'index.html')
+
+
+class Window:
+ _id_gen = IDGen()
+ handlers = {}
+
+ def __init__(
+ self,
+ script_func: Optional[Callable] = None,
+ js_api_code: Optional[str] = None,
+ run_script: Optional[Callable] = None
+ ):
+ self.loaded = False
+ self.script_func = script_func
+ self.scripts = []
+ self.final_scripts = []
+ self.bulk_run = BulkRunScript(script_func)
+
+ if run_script:
+ self.run_script = run_script
+
+ if js_api_code:
+ self.run_script(f'window.callbackFunction = {js_api_code}')
+
+ def on_js_load(self):
+ if self.loaded:
+ return
+ self.loaded = True
+
+ if hasattr(self, '_return_q'):
+ while not self.run_script_and_get('document.readyState == "complete"'):
+ continue # scary, but works
+
+ initial_script = ''
+ self.scripts.extend(self.final_scripts)
+ for script in self.scripts:
+ initial_script += f'\n{script}'
+ self.script_func(initial_script)
+
+ def run_script(self, script: str, run_last: bool = False):
+ """
+ For advanced users; evaluates JavaScript within the Webview.
+ """
+ if self.script_func is None:
+ raise AttributeError("script_func has not been set")
+ if self.loaded:
+ if self.bulk_run.enabled:
+ self.bulk_run.add_script(script)
+ else:
+ self.script_func(script)
+ elif run_last:
+ self.final_scripts.append(script)
+ else:
+ self.scripts.append(script)
+
+ def run_script_and_get(self, script: str):
+ self.run_script(f'_~_~RETURN~_~_{script}')
+ return self._return_q.get()
+
+ def create_table(
+ self,
+ width: NUM,
+ height: NUM,
+ headings: tuple,
+ widths: Optional[tuple] = None,
+ alignments: Optional[tuple] = None,
+ position: FLOAT = 'left',
+ draggable: bool = False,
+ background_color: str = '#121417',
+ border_color: str = 'rgb(70, 70, 70)',
+ border_width: int = 1,
+ heading_text_colors: Optional[tuple] = None,
+ heading_background_colors: Optional[tuple] = None,
+ return_clicked_cells: bool = False,
+ func: Optional[Callable] = None
+ ) -> 'Table':
+ return Table(*locals().values())
+
+ def create_subchart(
+ self,
+ position: FLOAT = 'left',
+ width: float = 0.5,
+ height: float = 0.5,
+ sync_id: Optional[str] = None,
+ scale_candles_only: bool = False,
+ sync_crosshairs_only: bool = False,
+ toolbox: bool = False
+ ) -> 'AbstractChart':
+ subchart = AbstractChart(
+ self,
+ width,
+ height,
+ scale_candles_only,
+ toolbox,
+ position=position
+ )
+ if not sync_id:
+ return subchart
+ self.run_script(f'''
+ Lib.Handler.syncCharts(
+ {subchart.id},
+ {sync_id},
+ {jbool(sync_crosshairs_only)}
+ )
+ ''', run_last=True)
+ return subchart
+
+ def style(
+ self,
+ background_color: str = '#0c0d0f',
+ hover_background_color: str = '#3c434c',
+ click_background_color: str = '#50565E',
+ active_background_color: str = 'rgba(0, 122, 255, 0.7)',
+ muted_background_color: str = 'rgba(0, 122, 255, 0.3)',
+ border_color: str = '#3C434C',
+ color: str = '#d8d9db',
+ active_color: str = '#ececed'
+ ):
+ self.run_script(f'Lib.Handler.setRootStyles({js_json(locals())});')
+
+
+class SeriesCommon(Pane):
+ def __init__(self, chart: 'AbstractChart', name: str = ''):
+ super().__init__(chart.win)
+ self._chart = chart
+ if hasattr(chart, '_interval'):
+ self._interval = chart._interval
+ else:
+ self._interval = 1
+ self._last_bar = None
+ self.name = name
+ self.num_decimals = 2
+ self.offset = 0
+ self.data = pd.DataFrame()
+ self.markers = {}
+
+ def _set_interval(self, df: pd.DataFrame):
+ if not pd.api.types.is_datetime64_any_dtype(df['time']):
+ df['time'] = pd.to_datetime(df['time'])
+ common_interval = df['time'].diff().value_counts()
+ if common_interval.empty:
+ return
+ self._interval = common_interval.index[0].total_seconds()
+
+ units = [
+ pd.Timedelta(microseconds=df['time'].dt.microsecond.value_counts().index[0]),
+ pd.Timedelta(seconds=df['time'].dt.second.value_counts().index[0]),
+ pd.Timedelta(minutes=df['time'].dt.minute.value_counts().index[0]),
+ pd.Timedelta(hours=df['time'].dt.hour.value_counts().index[0]),
+ pd.Timedelta(days=df['time'].dt.day.value_counts().index[0]),
+ ]
+ self.offset = 0
+ for value in units:
+ value = value.total_seconds()
+ if value == 0:
+ continue
+ elif value >= self._interval:
+ break
+ self.offset = value
+ break
+
+ @staticmethod
+ def _format_labels(data, labels, index, exclude_lowercase):
+ def rename(la, mapper):
+ return [mapper[key] if key in mapper else key for key in la]
+ if 'date' not in labels and 'time' not in labels:
+ labels = labels.str.lower()
+ if exclude_lowercase:
+ labels = rename(labels, {exclude_lowercase.lower(): exclude_lowercase})
+ if 'date' in labels:
+ labels = rename(labels, {'date': 'time'})
+ elif 'time' not in labels:
+ data['time'] = index
+ labels = [*labels, 'time']
+ return labels
+
+ def _df_datetime_format(self, df: pd.DataFrame, exclude_lowercase=None):
+ df = df.copy()
+ df.columns = self._format_labels(df, df.columns, df.index, exclude_lowercase)
+ self._set_interval(df)
+ if not pd.api.types.is_datetime64_any_dtype(df['time']):
+ df['time'] = pd.to_datetime(df['time'])
+ df['time'] = df['time'].astype('int64') // 10 ** 9
+ return df
+
+ def _series_datetime_format(self, series: pd.Series, exclude_lowercase=None):
+ series = series.copy()
+ series.index = self._format_labels(series, series.index, series.name, exclude_lowercase)
+ series['time'] = self._single_datetime_format(series['time'])
+ return series
+
+ def _single_datetime_format(self, arg) -> float:
+ if isinstance(arg, (str, int, float)) or not pd.api.types.is_datetime64_any_dtype(arg):
+ try:
+ arg = pd.to_datetime(arg, unit='ms')
+ except ValueError:
+ arg = pd.to_datetime(arg)
+ arg = self._interval * (arg.timestamp() // self._interval)+self.offset
+ return arg
+
+ def set(self, df: Optional[pd.DataFrame] = None, format_cols: bool = True):
+ if df is None or df.empty:
+ self.run_script(f'{self.id}.series.setData([])')
+ self.data = pd.DataFrame()
+ return
+ if format_cols:
+ df = self._df_datetime_format(df, exclude_lowercase=self.name)
+ if self.name:
+ if self.name not in df:
+ raise NameError(f'No column named "{self.name}".')
+ df = df.rename(columns={self.name: 'value'})
+ self.data = df.copy()
+ self._last_bar = df.iloc[-1]
+ self.run_script(f'{self.id}.series.setData({js_data(df)}); ')
+
+ def update(self, series: pd.Series):
+ series = self._series_datetime_format(series, exclude_lowercase=self.name)
+ if self.name in series.index:
+ series.rename({self.name: 'value'}, inplace=True)
+ if self._last_bar is not None and series['time'] != self._last_bar['time']:
+ self.data.loc[self.data.index[-1]] = self._last_bar
+ self.data = pd.concat([self.data, series.to_frame().T], ignore_index=True)
+ self._last_bar = series
+ self.run_script(f'{self.id}.series.update({js_data(series)})')
+
+ def _init_markers(self):
+ """
+ Creates a markers primitive once for this series,
+ stored at `series.markers`.
+
+ In the JS code, you need something like:
+ import { createSeriesMarkers } from 'lightweight-charts';
+
+ Then we do:
+ series.markers = createSeriesMarkers(series, []);
+ """
+ self.run_script(f"""
+ if (!{self.id}.series.markers) {{
+ {self.id}.series.markers = createSeriesMarkers({self.id}.series, []);
+ }}
+ """)
+
+ def _update_markers(self):
+ """
+ Replaces the old call '{self.id}.series.setMarkers(...)'
+ with the new v5 call:
+ '{self.id}.series.markers.setMarkers(...)'
+ """
+ markers_list = list(self.markers.values()) # from your Python dict
+ markers_json = json.dumps(markers_list)
+ self.run_script(f"""
+ {self.id}.series.markers.setMarkers({markers_json});
+ """)
+
+ # ============ Everything else is mostly unchanged ============
+
+ def marker_list(self, markers: list):
+ """
+ Creates multiple markers.
+ `markers` is a list of dicts, for example:
+ [
+ {"time": "2021-01-21", "position": "below", "shape": "circle", "color": "#2196F3", "text": ""},
+ ...
+ ]
+ Returns a list of new marker IDs.
+ """
+ markers = markers.copy()
+ marker_ids = []
+ for marker in markers:
+ marker_id = self.win._id_gen.generate()
+ self.markers[marker_id] = {
+ "time": self._single_datetime_format(marker['time']),
+ "position": marker_position(marker['position']),
+ "color": marker['color'],
+ "shape": marker_shape(marker['shape']),
+ "text": marker['text'],
+ }
+ marker_ids.append(marker_id)
+ self._update_markers()
+ return marker_ids
+
+ def marker(self,
+ time: Optional[datetime] = None,
+ position: str = 'below',
+ shape: str = 'arrow_up',
+ color: str = '#2196F3',
+ text: str = '') -> str:
+ """
+ Creates a new marker.
+ If no `time` is given, places it at the last bar.
+ Returns the newly generated marker ID.
+ """
+ try:
+ formatted_time = self._last_bar['time'] if not time else self._single_datetime_format(time)
+ except TypeError:
+ raise TypeError('Chart marker created before data was set.')
+ marker_id = self.win._id_gen.generate()
+
+ self.markers[marker_id] = {
+ "time": formatted_time,
+ "position": marker_position(position),
+ "color": color,
+ "shape": marker_shape(shape),
+ "text": text,
+ }
+ self._update_markers()
+ return marker_id
+
+ def remove_marker(self, marker_id: str):
+ """
+ Removes the marker with the given id.
+ """
+ self.markers.pop(marker_id, None)
+ self._update_markers()
+
+ def clear_markers(self):
+ """
+ Clears all markers from this series.
+ """
+ self.markers.clear()
+ self._update_markers()
+
+ def horizontal_line(self, price: NUM, color: str = 'rgb(122, 146, 202)', width: int = 2,
+ style: LINE_STYLE = 'solid', text: str = '', axis_label_visible: bool = True,
+ func: Optional[Callable] = None
+ ) -> 'HorizontalLine':
+ """
+ Creates a horizontal line at the given price.
+ """
+ return HorizontalLine(self, price, color, width, style, text, axis_label_visible, func)
+
+ def trend_line(
+ self,
+ start_time: TIME,
+ start_value: NUM,
+ end_time: TIME,
+ end_value: NUM,
+ round: bool = False,
+ line_color: str = '#1E80F0',
+ width: int = 2,
+ style: LINE_STYLE = 'solid',
+ ) -> TwoPointDrawing:
+ return TrendLine(*locals().values())
+
+ def box(
+ self,
+ start_time: TIME,
+ start_value: NUM,
+ end_time: TIME,
+ end_value: NUM,
+ round: bool = False,
+ color: str = '#1E80F0',
+ fill_color: str = 'rgba(255, 255, 255, 0.2)',
+ width: int = 2,
+ style: LINE_STYLE = 'solid',
+ ) -> TwoPointDrawing:
+ return Box(*locals().values())
+
+ def ray_line(
+ self,
+ start_time: TIME,
+ value: NUM,
+ round: bool = False,
+ color: str = '#1E80F0',
+ width: int = 2,
+ style: LINE_STYLE = 'solid',
+ text: str = ''
+ ) -> RayLine:
+ # TODO
+ return RayLine(*locals().values())
+
+ def vertical_line(
+ self,
+ time: TIME,
+ color: str = '#1E80F0',
+ width: int = 2,
+ style: LINE_STYLE ='solid',
+ text: str = ''
+ ) -> VerticalLine:
+ return VerticalLine(*locals().values())
+
+ def clear_markers(self):
+ """
+ Clears the markers displayed on the data.\n
+ """
+ self.markers.clear()
+ self._update_markers()
+
+ def price_line(self, label_visible: bool = True, line_visible: bool = True, title: str = ''):
+ self.run_script(f'''
+ {self.id}.series.applyOptions({{
+ lastValueVisible: {jbool(label_visible)},
+ priceLineVisible: {jbool(line_visible)},
+ title: '{title}',
+ }})''')
+
+ def precision(self, precision: int):
+ """
+ Sets the precision and minMove.\n
+ :param precision: The number of decimal places.
+ """
+ min_move = 1 / (10**precision)
+ self.run_script(f'''
+ {self.id}.series.applyOptions({{
+ priceFormat: {{precision: {precision}, minMove: {min_move}}}
+ }})''')
+ self.num_decimals = precision
+
+ def hide_data(self):
+ self._toggle_data(False)
+
+ def show_data(self):
+ self._toggle_data(True)
+
+ def _toggle_data(self, arg):
+ self.run_script(f'''
+ {self.id}.series.applyOptions({{visible: {jbool(arg)}}})
+ if ('volumeSeries' in {self.id}) {self.id}.volumeSeries.applyOptions({{visible: {jbool(arg)}}})
+ ''')
+
+ def vertical_span(
+ self,
+ start_time: Union[TIME, tuple, list],
+ end_time: Optional[TIME] = None,
+ color: str = 'rgba(252, 219, 3, 0.2)',
+ round: bool = False
+ ):
+ """
+ Creates a vertical line or span across the chart.\n
+ Start time and end time can be used together, or end_time can be
+ omitted and a single time or a list of times can be passed to start_time.
+ """
+ if round:
+ start_time = self._single_datetime_format(start_time)
+ end_time = self._single_datetime_format(end_time) if end_time else None
+ return VerticalSpan(self, start_time, end_time, color)
+
+
+class Line(SeriesCommon):
+ def __init__(
+ self, chart, name, color, style, width, price_line, price_label,
+ group, legend_symbol, price_scale_id, crosshair_marker=True):
+ super().__init__(chart, name)
+ self.color = color
+ self.group = group # Store group for legend grouping
+ self.legend_symbol = legend_symbol # Store the legend symbol
+
+ # Initialize series with configuration options
+ self.run_script(f'''
+ {self.id} = {self._chart.id}.createLineSeries(
+ "{name}",
+ {{
+ group: '{group}',
+ color: '{color}',
+ lineStyle: {as_enum(style, LINE_STYLE)},
+ lineWidth: {width},
+ lastValueVisible: {jbool(price_label)},
+ priceLineVisible: {jbool(price_line)},
+ crosshairMarkerVisible: {jbool(crosshair_marker)},
+ legendSymbol: '{legend_symbol}',
+ priceScaleId: {f'"{price_scale_id}"' if price_scale_id else 'undefined'}
+ {"""autoscaleInfoProvider: () => ({
+ priceRange: {
+ minValue: 1_000_000_000,
+ maxValue: 0,
+ },
+ }),
+ """ if chart._scale_candles_only else ''}
+ }}
+ )
+ null''')
+
+ def delete(self):
+ """
+ Irreversibly deletes the line, as well as the object that contains the line.
+ """
+ self._chart._lines.remove(self) if self in self._chart._lines else None
+ self.run_script(f'''
+ {self.id}legendItem = {self._chart.id}.legend._lines.find((line) => line.series == {self.id}.series)
+ {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter((item) => item != {self.id}legendItem)
+
+ if ({self.id}legendItem) {{
+ {self._chart.id}.legend.div.removeChild({self.id}legendItem.row)
+ }}
+
+ {self._chart.id}.chart.removeSeries({self.id}.series)
+ delete {self.id}legendItem
+ delete {self.id}
+ ''')
+class Symbols(SeriesCommon):
+ """
+ Represents a custom Symbol series, compatible with the createSymbolSeries JS method.
+ """
+
+ SYMBOL_MAP = {
+ 'circle': '●',
+ 'circles': '●',
+ 'cross': '✚',
+ 'triangleUp': '▲',
+ 'triangleDown': '▼',
+ 'arrowUp': '↑',
+ 'arrowDown': '↓'
+ }
+
+ def __init__(
+ self,
+ chart,
+ name: str,
+ color: str,
+ shape: str,
+ group: str,
+ legend_symbol: str = None,
+ price_scale_id: str = None,
+ crosshair_marker: bool = True,
+ price_line: bool = False,
+ price_label: bool = False,
+ ):
+ """
+ Initializes a Symbol series with configuration options.
+
+ :param chart: The parent chart instance.
+ :param name: Series title.
+ :param color: Color of symbols.
+ :param shape: Shape of the symbols (circle, cross, triangleUp, triangleDown, arrowUp, arrowDown).
+ :param group: Legend group identifier.
+ :param legend_symbol: Optional custom legend symbol; defaults to mapped shape symbol.
+ :param price_scale_id: Optional price scale ID.
+ :param crosshair_marker: Whether to display crosshair markers.
+ :param price_line: Whether to display the price line.
+ :param price_label: Whether to display the price label.
+ """
+ super().__init__(chart, name)
+ self.color = color
+ self.group = group
+ self.shape = shape
+ self.legend_symbol = legend_symbol or self.SYMBOL_MAP.get(shape, shape)
+ self.name = name
+ self.run_script(f'''
+ {self.id} = {self._chart.id}.createSymbolSeries(
+ "{name}",
+ {{
+ group: '{group}',
+ color: '{color}',
+ shape: '{shape}',
+ crosshairMarkerVisible: {str(crosshair_marker).lower()},
+ priceLineVisible: {str(price_line).lower()},
+ lastValueVisible: {str(price_label).lower()},
+ legendSymbol: '{self.legend_symbol}',
+ priceScaleId: {f'"{price_scale_id}"' if price_scale_id else 'undefined'}
+ {"""autoscaleInfoProvider: () => ({
+ priceRange: {
+ minValue: 1_000_000_000,
+ maxValue: 0,
+ },
+ }),""" if chart._scale_candles_only else ''}
+ }}
+ );
+ null;
+ ''')
+
+ def delete(self):
+ """
+ Irreversibly deletes the symbol series, removing it from the chart and legend.
+ """
+ if self in self._chart._lines:
+ self._chart._lines.remove(self)
+
+ self.run_script(f'''
+ const legendItem = {self._chart.id}.legend._lines.find(
+ (line) => line.series === {self.id}.series
+ );
+
+ if (legendItem) {{
+ {self._chart.id}.legend.div.removeChild(legendItem.row);
+ {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter(
+ (item) => item !== legendItem
+ );
+ }}
+
+ {self._chart.id}.chart.removeSeries({self.id}.series);
+ delete legendItem;
+ delete {self.id};
+ ''')
+
+
+class Histogram(SeriesCommon):
+ def __init__(
+ self, chart, name, color, price_line, price_label, group, legend_symbol, scale_margin_top, scale_margin_bottom):
+ super().__init__(chart, name)
+ self.color = color
+ self.group = group # Store group for legend grouping
+ self.legend_symbol = legend_symbol # Store legend symbol
+
+ self.run_script(f'''
+ {self.id} = {chart.id}.createHistogramSeries(
+ "{name}",
+ {{
+ group: '{group}',
+ color: '{color}',
+ lastValueVisible: {jbool(price_label)},
+ priceLineVisible: {jbool(price_line)},
+ legendSymbol: '{legend_symbol}',
+ priceScaleId: '{self.id}',
+ priceFormat: {{type: "volume"}}
+ }},
+ // precision: 2,
+ )
+ {self.id}.series.priceScale().applyOptions({{
+ scaleMargins: {{top:{scale_margin_top}, bottom: {scale_margin_bottom}}}
+ }})''')
+
+ def delete(self):
+ """
+ Irreversibly deletes the histogram.
+ """
+ self.run_script(f'''
+ {self.id}legendItem = {self._chart.id}.legend._lines.find((line) => line.series == {self.id}.series)
+ {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter((item) => item != {self.id}legendItem)
+
+ if ({self.id}legendItem) {{
+ {self._chart.id}.legend.div.removeChild({self.id}legendItem.row)
+ }}
+
+ {self._chart.id}.chart.removeSeries({self.id}.series)
+ delete {self.id}legendItem
+ delete {self.id}
+ ''')
+
+ def scale(self, scale_margin_top: float = 0.0, scale_margin_bottom: float = 0.0):
+ self.run_script(f'''
+ {self.id}.series.priceScale().applyOptions({{
+ scaleMargins: {{top: {scale_margin_top}, bottom: {scale_margin_bottom}}}
+ }})''')
+
+
+
+class Area(SeriesCommon):
+ def __init__(
+ self, chart, name, top_color, bottom_color, invert, line_color,
+ style, width, price_line, price_label, group, legend_symbol, price_scale_id, crosshair_marker=True):
+ super().__init__(chart, name)
+ self.color = line_color
+ self.topColor = top_color
+ self.bottomColor = bottom_color
+ self.group = group # Store group for legend grouping
+ self.legend_symbol = legend_symbol # Store legend symbol
+
+ self.run_script(f'''
+ {self.id} = {self._chart.id}.createAreaSeries(
+ "{name}",
+ {{
+ group: '{group}',
+ topColor: '{top_color}',
+ bottomColor: '{bottom_color}',
+ invertFilledArea: {jbool(invert)},
+ color: '{line_color}',
+ lineColor: '{line_color}',
+ lineStyle: {as_enum(style, LINE_STYLE)},
+ lineWidth: {width},
+ lastValueVisible: {jbool(price_label)},
+ priceLineVisible: {jbool(price_line)},
+ crosshairMarkerVisible: {jbool(crosshair_marker)},
+ legendSymbol: '{legend_symbol}',
+ priceScaleId: {f'"{price_scale_id}"' if price_scale_id else 'undefined'}
+ {"""autoscaleInfoProvider: () => ({
+ priceRange: {
+ minValue: 1_000_000_000,
+ maxValue: 0,
+ },
+ }),
+ """ if chart._scale_candles_only else ''}
+ }}
+ )
+ null''')
+ def delete(self):
+ """
+ Irreversibly deletes the line, as well as the object that contains the line.
+ """
+ self._chart._lines.remove(self) if self in self._chart._lines else None
+ self.run_script(f'''
+ {self.id}legendItem = {self._chart.id}.legend._lines.find((line) => line.series == {self.id}.series)
+ {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter((item) => item != {self.id}legendItem)
+
+ if ({self.id}legendItem) {{
+ {self._chart.id}.legend.div.removeChild({self.id}legendItem.row)
+ }}
+
+ {self._chart.id}.chart.removeSeries({self.id}.series)
+ delete {self.id}legendItem
+ delete {self.id}
+ ''')
+
+
+class Bar(SeriesCommon):
+ def __init__(
+ self, chart, name, up_color, down_color, open_visible, thin_bars,
+ price_line, price_label, group, legend_symbol, price_scale_id):
+ super().__init__(chart, name)
+ self.up_color = up_color
+ self.down_color = down_color
+ self.group = group # Store group for legend grouping
+ self.legend_symbol = legend_symbol if isinstance(legend_symbol, list) else [legend_symbol, legend_symbol] # Store legend symbols
+
+ self.run_script(f'''
+ {self.id} = {chart.id}.createBarSeries(
+ "{name}",
+ {{
+ group: '{group}',
+ color: '{up_color}',
+ upColor: '{up_color}',
+ downColor: '{down_color}',
+ openVisible: {jbool(open_visible)},
+ thinBars: {jbool(thin_bars)},
+ lastValueVisible: {jbool(price_label)},
+ priceLineVisible: {jbool(price_line)},
+ legendSymbol: {json.dumps(self.legend_symbol)},
+ priceScaleId: {f'"{price_scale_id}"' if price_scale_id else 'undefined'}
+ }}
+
+ )''')
+ def set(self, df: Optional[pd.DataFrame] = None):
+ if df is None or df.empty:
+ self.run_script(f'{self.id}.series.setData([])')
+ self.candle_data = pd.DataFrame()
+ return
+ df = self._df_datetime_format(df)
+ self.data = df.copy()
+ self._last_bar = df.iloc[-1]
+ self.run_script(f'{self.id}.series.setData({js_data(df)})')
+
+ def update(self, series: pd.Series, _from_tick=False):
+ """
+ Updates the data from a bar;
+ if series['time'] is the same time as the last bar, the last bar will be overwritten.\n
+ :param series: labels: date/time, open, high, low, close, volume (if using volume).
+ """
+ series = self._series_datetime_format(series) if not _from_tick else series
+ if series['time'] != self._last_bar['time']:
+ self.data.loc[self.data.index[-1]] = self._last_bar
+ self.data = pd.concat([self.data, series.to_frame().T], ignore_index=True)
+ self._chart.events.new_bar._emit(self)
+
+ self._last_bar = series
+ self.run_script(f'{self.id}.series.update({js_data(series)})')
+ def delete(self):
+ """
+ Irreversibly deletes the bar series.
+ """
+ self.run_script(f'''
+ {self.id}legendItem = {self._chart.id}.legend._lines.find((line) => line.series == {self.id}.series)
+ {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter((item) => item != {self.id}legendItem)
+
+ if ({self.id}legendItem) {{
+ {self._chart.id}.legend.div.removeChild({self.id}legendItem.row)
+ }}
+
+ {self._chart.id}.chart.removeSeries({self.id}.series)
+ delete {self.id}legendItem
+ delete {self.id}
+ ''')
+
+class CustomCandle(SeriesCommon):
+ def __init__(
+ self,
+ chart,
+ name: str,
+ up_color: str ,
+ down_color: str ,
+ border_up_color: str,
+ border_down_color: str ,
+ wick_up_color: str ,
+ wick_down_color: str ,
+ wick_visible: bool = True,
+ border_visible: bool= True,
+ bar_width: float = 0.8,
+ radius: Optional[float] = .3,
+ shape: str = 'Rectangle',
+ combineCandles: int = 1,
+ line_width: int = 1,
+ line_style: LINE_STYLE = 'solid',
+ price_line: bool = True,
+ price_label: bool = True,
+ group: str = '',
+ legend_symbol: Union[str, List[str]] = ['⬤', '⬤'],
+ price_scale_id: Optional[str] = None,
+
+ ):
+ super().__init__(chart, name)
+ self.up_color = up_color
+ self.down_color = down_color
+ self.group = group # Store group for legend grouping
+ self.legend_symbol = legend_symbol if isinstance(legend_symbol, list) else [legend_symbol, legend_symbol]
+
+ # Define the radius function as a JavaScript function string if none provided
+
+ # Run the JavaScript to initialize the series with the provided options
+ self.run_script(f'''
+ {self.id} = {chart.id}.createCustomOHLCSeries(
+ "{name}",
+ {{
+ group: '{group}',
+ upColor: '{up_color}',
+ downColor: '{down_color}',
+ borderUpColor: '{border_up_color}',
+ borderDownColor: '{border_down_color}',
+ wickUpColor: '{wick_up_color or border_up_color}',
+ wickDownColor: '{wick_down_color or border_down_color}',
+ wickVisible: {jbool(wick_visible)},
+ borderVisible: {jbool(border_visible)},
+ barSpacing: {bar_width},
+ radius: {radius},
+ shape: '{shape}',
+ lastValueVisible: {jbool(price_label)},
+ priceLineVisible: {jbool(price_line)},
+ legendSymbol: {json.dumps(self.legend_symbol)},
+ priceScaleId: {f'"{price_scale_id}"' if price_scale_id else 'undefined'},
+ seriesType: "Ohlc",
+ chandelierSize: {combineCandles},
+ lineStyle: {as_enum(line_style, LINE_STYLE)},
+ lineWidth: {line_width},
+
+ }}
+ )
+ null''')
+
+ def set(self, df: Optional[pd.DataFrame] = None):
+ if df is None or df.empty:
+ self.run_script(f'{self.id}.series.setData([])')
+ self.data = pd.DataFrame()
+ return
+ df = self._df_datetime_format(df)
+ self.data = df.copy()
+ self._last_bar = df.iloc[-1]
+ self.run_script(f'{self.id}.series.setData({js_data(df)})')
+
+ def update(self, series: pd.Series):
+ series = self._series_datetime_format(series)
+ if series['time'] != self._last_bar['time']:
+ self.data.loc[self.data.index[-1]] = self._last_bar
+ self.data = pd.concat([self.data, series.to_frame().T], ignore_index=True)
+ self._chart.events.new_bar._emit(self)
+
+ self._last_bar = series
+ self.run_script(f'{self.id}.series.update({js_data(series)})')
+
+ def update_from_tick(self, series: pd.Series, cumulative_volume: bool = False):
+ series = self._series_datetime_format(series)
+ price = series['price']
+ time = series['time']
+
+ if self._last_bar is None or time > self._last_bar['time']:
+ # Start new candle from tick
+ bar = pd.Series({
+ 'time': time,
+ 'open': price,
+ 'high': price,
+ 'low': price,
+ 'close': price,
+ 'volume': series.get('volume', 0)
+ })
+ else:
+ # Update current candle with new tick
+ bar = self._last_bar.copy()
+ bar['high'] = max(bar['high'], price)
+ bar['low'] = min(bar['low'], price)
+ bar['close'] = price
+ if 'volume' in series:
+ if cumulative_volume:
+ bar['volume'] += series['volume']
+ else:
+ bar['volume'] = series['volume']
+
+ self._last_bar = bar
+ self.update(bar, _from_tick=True)
+
+class Candlestick(SeriesCommon):
+ def __init__(self, chart: 'AbstractChart'):
+ super().__init__(chart)
+ self._volume_up_color = 'rgba(83,141,131,0.8)'
+ self._volume_down_color = 'rgba(200,127,130,0.8)'
+
+ self.candle_data = pd.DataFrame()
+
+ # self.run_script(f'{self.id}.makeCandlestickSeries()')
+
+ def set(self, df: Optional[pd.DataFrame] = None, keep_drawings=False):
+ """
+ Sets the initial data for the chart.\n
+ :param df: columns: date/time, open, high, low, close, volume (if volume enabled).
+ :param 6: keeps any drawings made through the toolbox. Otherwise, they will be deleted.
+ """
+ if df is None or df.empty:
+ self.run_script(f'{self.id}.series.setData([])')
+ self.run_script(f'{self.id}.volumeSeries.setData([])')
+ self.candle_data = pd.DataFrame()
+ return
+ df = self._df_datetime_format(df)
+ self.candle_data = df.copy()
+ self._last_bar = df.iloc[-1]
+ self.run_script(f'{self.id}.series.setData({js_data(df)})')
+
+ if 'volume' not in df:
+ return
+ volume = df.drop(columns=['open', 'high', 'low', 'close']).rename(columns={'volume': 'value'})
+ volume['color'] = self._volume_down_color
+ volume.loc[df['close'] > df['open'], 'color'] = self._volume_up_color
+ self.run_script(f'{self.id}.volumeSeries.setData({js_data(volume)})')
+
+ for line in self._lines:
+ if line.name not in df.columns:
+ continue
+ line.set(df[['time', line.name]], format_cols=False)
+ # set autoScale to true in case the user has dragged the price scale
+ self.run_script(f'''
+ if (!{self.id}.chart.priceScale("right").options.autoScale)
+ {self.id}.chart.priceScale("right").applyOptions({{autoScale: true}})
+ ''')
+ # TODO keep drawings doesn't work consistenly w
+ if keep_drawings:
+ self.run_script(f'{self._chart.id}.toolBox?._drawingTool.repositionOnTime()')
+ else:
+ self.run_script(f"{self._chart.id}.toolBox?.clearDrawings()")
+
+ def update(self, series: pd.Series, _from_tick=False):
+ """
+ Updates the data from a bar;
+ if series['time'] is the same time as the last bar, the last bar will be overwritten.\n
+ :param series: labels: date/time, open, high, low, close, volume (if using volume).
+ """
+ series = self._series_datetime_format(series) if not _from_tick else series
+ if series['time'] != self._last_bar['time']:
+ self.candle_data.loc[self.candle_data.index[-1]] = self._last_bar
+ self.candle_data = pd.concat([self.candle_data, series.to_frame().T], ignore_index=True)
+ self._chart.events.new_bar._emit(self)
+
+ self._last_bar = series
+ self.run_script(f'{self.id}.series.update({js_data(series)})')
+ if 'volume' not in series:
+ return
+ volume = series.drop(['open', 'high', 'low', 'close']).rename({'volume': 'value'})
+ volume['color'] = self._volume_up_color if series['close'] > series['open'] else self._volume_down_color
+ self.run_script(f'{self.id}.volumeSeries.update({js_data(volume)})')
+
+ def update_from_tick(self, series: pd.Series, cumulative_volume: bool = False):
+ """
+ Updates the data from a tick.\n
+ :param series: labels: date/time, price, volume (if using volume).
+ :param cumulative_volume: Adds the given volume onto the latest bar.
+ """
+ series = self._series_datetime_format(series)
+ if series['time'] < self._last_bar['time']:
+ raise ValueError(f'Trying to update tick of time "{pd.to_datetime(series["time"])}", which occurs before the last bar time of "{pd.to_datetime(self._last_bar["time"])}".')
+ bar = pd.Series(dtype='float64')
+ if series['time'] == self._last_bar['time']:
+ bar = self._last_bar
+ bar['high'] = max(self._last_bar['high'], series['price'])
+ bar['low'] = min(self._last_bar['low'], series['price'])
+ bar['close'] = series['price']
+ if 'volume' in series:
+ if cumulative_volume:
+ bar['volume'] += series['volume']
+ else:
+ bar['volume'] = series['volume']
+ else:
+ for key in ('open', 'high', 'low', 'close'):
+ bar[key] = series['price']
+ bar['time'] = series['time']
+ if 'volume' in series:
+ bar['volume'] = series['volume']
+ self.update(bar, _from_tick=True)
+
+ def price_scale(
+ self,
+ auto_scale: bool = True,
+ mode: PRICE_SCALE_MODE = 'normal',
+ invert_scale: bool = False,
+ align_labels: bool = True,
+ scale_margin_top: float = 0.2,
+ scale_margin_bottom: float = 0.2,
+ border_visible: bool = False,
+ border_color: Optional[str] = None,
+ text_color: Optional[str] = None,
+ entire_text_only: bool = False,
+ visible: bool = True,
+ ticks_visible: bool = False,
+ minimum_width: int = 0
+ ):
+ self.run_script(f'''
+ {self.id}.series.priceScale().applyOptions({{
+ autoScale: {jbool(auto_scale)},
+ mode: {as_enum(mode, PRICE_SCALE_MODE)},
+ invertScale: {jbool(invert_scale)},
+ alignLabels: {jbool(align_labels)},
+ scaleMargins: {{top: {scale_margin_top}, bottom: {scale_margin_bottom}}},
+ borderVisible: {jbool(border_visible)},
+ {f'borderColor: "{border_color}",' if border_color else ''}
+ {f'textColor: "{text_color}",' if text_color else ''}
+ entireTextOnly: {jbool(entire_text_only)},
+ visible: {jbool(visible)},
+ ticksVisible: {jbool(ticks_visible)},
+ minimumWidth: {minimum_width}
+ }})''')
+
+ def candle_style(
+ self, up_color: str = 'rgba(39, 157, 130, 100)', down_color: str = 'rgba(200, 97, 100, 100)',
+ wick_visible: bool = True, border_visible: bool = True, border_up_color: str = '',
+ border_down_color: str = '', wick_up_color: str = '', wick_down_color: str = ''):
+ """
+ Candle styling for each of its parts.\n
+ If only `up_color` and `down_color` are passed, they will color all parts of the candle.
+ """
+ border_up_color = border_up_color if border_up_color else up_color
+ border_down_color = border_down_color if border_down_color else down_color
+ wick_up_color = wick_up_color if wick_up_color else up_color
+ wick_down_color = wick_down_color if wick_down_color else down_color
+ self.run_script(f"{self.id}.series.applyOptions({js_json(locals())})")
+
+ def volume_config(self, scale_margin_top: float = 0.8, scale_margin_bottom: float = 0.0,
+ up_color='rgba(83,141,131,0.8)', down_color='rgba(200,127,130,0.8)'):
+ """
+ Configure volume settings.\n
+ Numbers for scaling must be greater than 0 and less than 1.\n
+ Volume colors must be applied prior to setting/updating the bars.\n
+ """
+ self._volume_up_color = up_color if up_color else self._volume_up_color
+ self._volume_down_color = down_color if down_color else self._volume_down_color
+ self.run_script(f'''
+ {self.id}.volumeSeries.priceScale().applyOptions({{
+ scaleMargins: {{
+ top: {scale_margin_top},
+ bottom: {scale_margin_bottom},
+ }}
+ }})
+ {self.id}.volumeUpColor = "{self._volume_up_color}";
+ {self.id}.volumeDownColor = "{self._volume_down_color}";
+ ''')
+
+class PositionPlot(SeriesCommon):
+ def __init__(
+ self,
+ chart,
+ name: str,
+ side: str = "long", # 'long' or 'short'
+ mode: str = "relative",
+ background_color_stop: str = "rgba(255,0,0,0.2)",
+ background_color_target: str = "rgba(0,255,0,0.2)",
+ price_line: bool = True,
+ price_label: bool = True,
+ group: str = "Position",
+ legend_symbol: str = "⚑",
+ auto: bool = True,
+ ):
+ super().__init__(chart, name)
+ self.group = group
+ self.legend_symbol = legend_symbol
+
+ if side not in ("long", "short"):
+ raise ValueError("side must be 'long' or 'short'")
+ if mode not in ("relative", "absolute"):
+ raise ValueError("mode must be 'relative' or 'absolute'")
+
+ # Create trade series in the JS environment
+ js_code = f"""
+ {self.id} = {chart.id}.createTradeSeries("{name}", {{
+ name: "{name}",
+ group: "{group}",
+ side: "{side}",
+ mode: "{mode}",
+ backgroundColorStop: "{background_color_stop}",
+ backgroundColorTarget: "{background_color_target}",
+ lastValueVisible: {str(price_label).lower()},
+ priceLineVisible: {str(price_line).lower()},
+ legendSymbol: "{legend_symbol}",
+ auto: {str(auto).lower()}
+ }});
+ """
+ try:
+ self.run_script(js_code)
+ except JavascriptException as e:
+ raise RuntimeError(f"Failed to create trade series. JS Error: {e}")
+
+ def set(self, df: Optional[pd.DataFrame] = None, format_cols: bool = True):
+ if df is None or df.empty:
+ self.run_script(f'''{self.id}.series.setData([])''')
+ self.data = pd.DataFrame()
+ return
+ if format_cols:
+ df = self._df_datetime_format(df, exclude_lowercase=self.name)
+ if not df.empty:
+ # if 'entry_price' not in df:
+ # raise NameError(f'No column named "{'entry_price'}".')
+ df['value'] = df['entry']#.rename(columns={self.name: 'value'})
+ self.data = df.copy()
+ self._last_bar = df.iloc[-1]
+ self.run_script(f'''{self.id}.series.setData({js_data(df)}); ''')
+ def delete(self):
+ """
+ Irreversibly deletes the trade series.
+ """
+ self.run_script(f'''
+ {self.id}legendItem = {self._chart.id}.legend._lines.find((line) => line.series == {self.id}.series)
+ {self._chart.id}.legend._lines = {self._chart.id}.legend._lines.filter((item) => item != {self.id}legendItem)
+
+ if ({self.id}legendItem) {{
+ {self._chart.id}.legend.div.removeChild({self.id}legendItem.row)
+ }}
+
+ {self._chart.id}.chart.removeSeries({self.id}.series)
+ delete {self.id}legendItem
+ delete {self.id}
+ ''')
+ def initiate_trade(
+ self,
+ time: Optional[Any] = None,
+ entry: float = 0.0,
+ stop: Optional[float] = None,
+ target: Optional[float] = None,
+ action: str = "entry",
+ amount: float = 1.0,
+ display_info: str = "",
+ ) -> None:
+ """
+ Initiates or updates a trade on the PositionPlot by inserting one new data point
+ into the trade series. If `time` is not provided, this method attempts to fetch
+ the last bar's time from the base series in the trade series' options.
+ """
+ time_str = self._get_time_or_last_bar(time)
+
+ trade_point = {
+ "time": time_str,
+ "entry": entry,
+ "stop": stop if stop is not None else None,
+ "target": target if target is not None else None,
+ "action": action,
+ "amount": amount,
+ "displayInfo": display_info,
+ }
+
+ trade_json = js_data([trade_point])[1:-1] # turn list -> single object
+ js_code = f"{self.id}.series.update({trade_json});"
+ self.run_script(js_code)
+ def close_trade(
+ self,
+ time: Optional[Any] = None,
+ display_info: str = "",
+ ) -> None:
+ """
+ Closes an existing trade on the PositionPlot by sending an update
+ with action='close'. If `time` is not provided, we attempt to fetch
+ the last bar's time from the base series in the trade series' options.
+
+ :param time: The time at which the trade is closed.
+ If None, fetch from the base series' latest bar or fallback to "now".
+ :param display_info: Optional text info to display on the chart regarding the close.
+ """
+ time_str = self._get_time_or_last_bar(time)
+
+ # 3) Build the trade point dictionary, with action='close'
+ trade_point = {
+ "time": time_str,
+ "action": "close",
+ "displayInfo": display_info,
+ }
+
+ # 4) Convert to JS object
+ trade_json = js_data([trade_point])[1:-1] # remove the surrounding [ ]
+
+ # 5) Send the update to the trade series
+ js_code = f"{self.id}.series.update({trade_json});"
+ self.run_script(js_code)
+
+ def _get_time_or_last_bar(self, time: Optional[Any]) -> str:
+ """
+ Returns a JS-friendly time string:
+ - If `time` is provided, convert it.
+ - Otherwise, fetch the last bar's time from baseSeries or fallback to "now".
+ """
+ if time is not None:
+ return self._convert_time(time)
+
+ # No time -> fetch from base series
+ js_fetch_time = f"""
+ (function() {{
+ const baseSeries = {self.id}.series.options().baseSeries;
+ if (!baseSeries) return null;
+ const data = baseSeries.data();
+ if (!data || data.length === 0) return null;
+ return data[data.length - 1].time;
+ }})();
+ """
+ last_bar_time = self.run_script(js_fetch_time)
+ if last_bar_time is None:
+ # fallback to "now"
+ last_bar_time = pd.Timestamp.now().isoformat()
+
+ return self._convert_time(last_bar_time)
+
+class AbstractChart(Candlestick, Pane):
+ def __init__(self, window: Window, width: float = 1.0, height: float = 1.0,
+ scale_candles_only: bool = False,
+ toolbox: Optional[TOOLBOX_MODE] = "disabled",
+ autosize: bool = True, position: FLOAT = 'left',
+ defaults: str = '../defaults', scripts: str = '../scripts'):
+ Pane.__init__(self, window)
+ Candlestick.__init__(self, self)
+ self._lines = []
+ self._scale_candles_only = scale_candles_only
+ self._width = width
+ self._height = height
+ self.events: Events = Events(self)
+ from lightweight_charts_esistjosh.polygon import PolygonAPI
+
+ # Initialize PolygonAPI instance
+ self.polygon: PolygonAPI = PolygonAPI(self)
+
+ # Initialize Lib.Handler JavaScript instance
+ self.run_script(
+ f'{self.id} = new Lib.Handler("{self.id}", {width}, {height}, "{position}", {jbool(autosize)})'
+ )
+
+ self.topbar: TopBar = TopBar(self)
+ if toolbox != "disabled":
+ self.toolbox: ToolBox = ToolBox(self, mode=toolbox)
+
+ # Set and initialize defaults directory
+ self.defaults = defaults or '../defaults'
+ if not os.path.exists(self.defaults):
+ os.makedirs(self.defaults, exist_ok=True)
+ if os.path.exists('../defaults'):
+ shutil.copytree('../defaults', self.defaults, dirs_exist_ok=True)
+ self.set_defaults(self.defaults)
+
+ # Handlers for defaults
+ self.win.handlers['save_defaults'] = self._save_defaults
+ self.events.save_defaults += self._save_defaults
+
+ # Set and initialize scripts directory
+ self.scripts = scripts or '../scripts'
+ if not os.path.exists(self.scripts):
+ os.makedirs(self.scripts, exist_ok=True)
+ if os.path.exists('../scripts'):
+ shutil.copytree('../scripts', self.scripts, dirs_exist_ok=True)
+ self.set_scripts(self.scripts)
+
+ # Handlers for scripts
+ self.win.handlers['save_script'] = self._save_script
+ self.events.save_script += self._save_script
+
+ def _save_script(self, key: str, options: str) -> None:
+ """Save script JSON data to memory and disk."""
+ try:
+ parsed_options = json.loads(options)
+ if not hasattr(self, 'exportedScripts'):
+ self.exportedScripts = {}
+ self.exportedScripts[key] = parsed_options
+
+ scripts_folder = self.scripts if isinstance(self.scripts, str) and self.scripts else "./scripts"
+ if not os.path.exists(scripts_folder):
+ os.makedirs(scripts_folder)
+
+ file_path = os.path.join(scripts_folder, f"{key}.json")
+ with open(file_path, "w", encoding="utf-8") as f:
+ json.dump(parsed_options, f, indent=2)
+ print(f"Script for key '{key}' written to disk at: {file_path}")
+ except Exception as e:
+ print(f"Error saving script for key '{key}': {e}")
+
+ def _save_defaults(self, key: str, options: str) -> None:
+ """Save defaults JSON data to memory and disk."""
+ try:
+ parsed_options = json.loads(options)
+ if not hasattr(self, 'exportedDefaults'):
+ self.exportedDefaults = {}
+ self.exportedDefaults[key] = parsed_options
+
+ defaults_folder = self.defaults if isinstance(self.defaults, str) else "./defaults"
+ if not os.path.exists(defaults_folder):
+ os.makedirs(defaults_folder)
+
+ file_path = os.path.join(defaults_folder, f"{key}.json")
+ with open(file_path, "w", encoding="utf-8") as f:
+ json.dump(parsed_options, f, indent=2)
+ print(f"Defaults for key '{key}' written to disk at: {file_path}")
+ except Exception as e:
+ print(f"Error saving defaults for key '{key}': {e}")
+
+ def set_scripts(self, scripts_dir: str) -> None:
+ """
+ Load and apply JSON scripts from directory to the scriptsManager.
+ """
+ for root, _, files in os.walk(scripts_dir):
+ for filename in files:
+ if filename.endswith('.json'):
+ key = os.path.splitext(filename)[0]
+ file_path = os.path.join(root, filename)
+ try:
+ with open(file_path, 'r', encoding="utf-8") as f:
+ data = json.load(f)
+ json_data = json.dumps(data)
+ js_code = f'{self.id}.scriptsManager.set("{key}", {json_data});'
+ self.run_script(js_code)
+ print(f"Set script for key '{key}' successfully.")
+ except Exception as e:
+ print(f"Error processing script '{file_path}': {e}")
+
+ def set_defaults(self, defaults_dir: str) -> None:
+ """
+ Load and apply JSON defaults from directory to the defaultsManager.
+ Special handling for "chart.json".
+ """
+ for root, _, files in os.walk(defaults_dir):
+ for filename in files:
+ if filename.endswith('.json'):
+ key = os.path.splitext(filename)[0]
+ file_path = os.path.join(root, filename)
+ try:
+ with open(file_path, 'r', encoding="utf-8") as f:
+ data = json.load(f)
+ json_data = json.dumps(data)
+ js_code = f'{self.id}.defaultsManager.set("{key}", {json_data});'
+ self.run_script(js_code)
+ print(f"Set defaults for key '{key}' successfully.")
+
+ if key.lower() == "chart":
+ js_apply = f'{self.id}.chart.applyOptions({{ ...{self.id}.defaultsManager.get("chart") }});'
+ self.run_script(js_apply)
+ print("Applied chart defaults successfully.")
+ except Exception as e:
+ print(f"Error processing defaults '{file_path}': {e}")
+
+ def fit(self):
+ """
+ Fits chart data within the viewport.
+ """
+ self.run_script(f'{self.id}.chart.timeScale().fitContent()')
+
+ def create_line(
+ self,
+ name: str = '',
+ color: str = 'rgba(214, 237, 255, 0.6)',
+ style: LINE_STYLE = 'solid',
+ width: int = 2,
+ price_line: bool = True,
+ price_label: bool = True,
+ group: str = '',
+ legend_symbol: str = '',
+ price_scale_id: Optional[str] = None
+ ) -> Line:
+ """
+ Creates and returns a Line object.
+ """
+
+ symbol_styles = {
+ 'solid':'―',
+ 'dotted':'··',
+ 'dashed':'--',
+ 'large_dashed':'- -',
+ 'sparse_dotted':"· ·",
+ }
+ if legend_symbol == '':
+ legend_symbol = symbol_styles.get(style, '━') # Default to 'solid' if style is unrecognized
+
+ if not isinstance(legend_symbol, str):
+ raise TypeError("legend_symbol must be a string for Line series.")
+
+ self._lines.append(Line(
+ self, name, color, style, width, price_line, price_label,
+ group, legend_symbol, price_scale_id
+ ))
+ return self._lines[-1]
+
+
+ def create_symbol(
+ self,
+ name: str,
+ color: str = 'rgba(214, 237, 255, 0.6)',
+ shape: str = '*',
+ group: str = '',
+ legend_symbol: str = '',
+ price_scale_id: Optional[str] = None,
+ crosshair_marker: bool = True,
+ price_line: bool = False,
+ price_label: bool = False
+ ) -> Symbols:
+ """
+ Creates and returns a Symbols series object.
+ """
+
+ symbol_map = {
+ 'circle': '●',
+ 'circles': '●',
+ 'cross': '✚',
+ 'triangleUp': '▲',
+ 'triangleDown': '▼',
+ 'arrowUp': '↑',
+ 'arrowDown': '↓'
+ }
+
+ if legend_symbol == '':
+ legend_symbol = symbol_map.get(shape, shape)
+
+ symbols_series = Symbols(
+ self, name, color, shape, group, legend_symbol, price_scale_id,
+ crosshair_marker, price_line, price_label
+ )
+ self._lines.append(symbols_series)
+ return symbols_series
+
+ def create_histogram(
+ self,
+ name: str = '',
+ color: str = 'rgba(214, 237, 255, 0.6)',
+ price_line: bool = True,
+ price_label: bool = True,
+ group: str = '',
+ legend_symbol: str = '▥',
+ scale_margin_top: float = 0.0,
+ scale_margin_bottom: float = 0.0
+ ) -> Histogram:
+ """
+ Creates and returns a Histogram object.
+ """
+ if not isinstance(legend_symbol, str):
+ raise TypeError("legend_symbol must be a string for Histogram series.")
+
+ return Histogram(
+ self, name, color, price_line, price_label,
+ group, legend_symbol, scale_margin_top, scale_margin_bottom
+ )
+
+ def create_area(
+ self,
+ name: str = '',
+ top_color: str = 'rgba(0, 100, 0, 0.5)',
+ bottom_color: str = 'rgba(138, 3, 3, 0.5)',
+ invert: bool = False,
+ color: str = 'rgba(0,0,255,1)',
+ style: LINE_STYLE = 'solid',
+ width: int = 2,
+ price_line: bool = True,
+ price_label: bool = True,
+ group: str = '',
+ legend_symbol: str = '◪',
+ price_scale_id: Optional[str] = None
+ ) -> Area:
+ """
+ Creates and returns an Area object.
+ """
+ if not isinstance(legend_symbol, str):
+ raise TypeError("legend_symbol must be a string for Area series.")
+
+ self._lines.append(Area(
+ self, name, top_color, bottom_color, invert, color, style,
+ width, price_line, price_label, group, legend_symbol, price_scale_id
+ ))
+ return self._lines[-1]
+
+ def create_bar(
+ self,
+ name: str = '',
+ up_color: str = '#26a69a',
+ down_color: str = '#ef5350',
+ open_visible: bool = True,
+ thin_bars: bool = True,
+ price_line: bool = True,
+ price_label: bool = True,
+ group: str = '',
+ legend_symbol: Union[str, List[str]] = ['┌', '└'],
+ price_scale_id: Optional[str] = None
+ ) -> Bar:
+ """
+ Creates and returns a Bar object.
+ """
+ if not isinstance(legend_symbol, (str, list)):
+ raise TypeError("legend_symbol must be a string or list of strings for Bar series.")
+ if isinstance(legend_symbol, list) and not all(isinstance(symbol, str) for symbol in legend_symbol):
+ raise TypeError("Each item in legend_symbol list must be a string for Bar series.")
+
+ return Bar(
+ self, name, up_color, down_color, open_visible, thin_bars,
+ price_line, price_label, group, legend_symbol, price_scale_id
+ )
+
+ def create_custom_candle(
+ self,
+ name: str = '',
+ up_color: str = None,
+ down_color: str = None,
+ border_up_color='rgba(0,255,0,1)',
+ border_down_color='rgba(255,0,0,1)',
+ wick_up_color='rgba(0,255,0,1)',
+ wick_down_color='rgba(255,0,0,1)',
+ wick_visible: bool = True,
+ border_visible: bool = True,
+ bar_width: float = 0.8,
+ rounded_radius: Union[float, int] = 100,
+ shape: Literal[CANDLE_SHAPE] = "Rectangle",
+ combineCandles: int = 1,
+ line_width: int = 1,
+ line_style: LINE_STYLE = 'solid',
+ price_line: bool = True,
+ price_label: bool = True,
+ group: str = '',
+ legend_symbol: Union[str, List[str]] = ['⑃', '⑂'],
+ price_scale_id: Optional[str] = None,
+ ) -> CustomCandle:
+ """
+ Creates and returns a CustomCandle object.
+ """
+ # Validate that legend_symbol is either a string or a list of two strings
+ if not isinstance(legend_symbol, (str, list)):
+ raise TypeError("legend_symbol must be a string or list of strings for CustomCandle series.")
+ if isinstance(legend_symbol, list) and len(legend_symbol) != 2:
+ raise ValueError("legend_symbol list must contain exactly two symbols for CustomCandle series.")
+
+ return CustomCandle(
+ self,
+ name=name,
+ up_color=up_color or border_up_color,
+ down_color=down_color or border_down_color,
+ border_up_color=border_up_color or up_color,
+ border_down_color=border_down_color or down_color,
+ wick_up_color=wick_up_color or border_up_color or border_up_color,
+ wick_down_color=wick_down_color or border_down_color or border_down_color,
+ wick_visible=wick_visible,
+ border_visible=border_visible,
+ bar_width=bar_width,
+ radius=rounded_radius,
+ shape=shape,
+ combineCandles=combineCandles,
+ line_style= line_style,
+ line_width= line_width,
+ price_line=price_line,
+ price_label=price_label,
+ group=group,
+ legend_symbol=legend_symbol,
+ price_scale_id=price_scale_id,
+ )
+
+ def plot_position(
+ self,
+ name: str = 'Position',
+ side: str = 'long',
+ mode: str = 'relative',
+ background_color_stop: str = 'rgba(255,0,0,0.2)',
+ background_color_target: str = 'rgba(0,255,0,0.2)',
+ price_line: bool = True,
+ price_label: bool = True,
+ group: str = 'Position',
+ legend_symbol: str = '$',
+ auto: bool = 'true'
+ ) -> 'PositionPlot':
+ """
+ Creates and returns a PositionPlot (Trade) object.
+
+ :param name: Name of the trade series.
+ :param side: 'long' or 'short'.
+ :param mode: 'relative' or 'absolute'.
+ :param background_color_stop: Gradient color for entry-stop line.
+ :param background_color_target: Gradient color for entry-target line.
+ :param price_line: Show the price line.
+ :param price_label: Show the price label on the scale.
+ :param group: Legend group.
+ :param legend_symbol: Symbol for the legend.
+ """
+ self._lines.append(PositionPlot(
+ self,
+ name,
+ side,
+ mode,
+ background_color_stop,
+ background_color_target,
+ price_line,
+ price_label,
+ group,
+ legend_symbol,
+ auto
+ ))
+ return self._lines[-1]
+
+
+
+ def lines(self) -> List[Line]:
+ """
+ Returns all lines for the chart.
+ """
+ return self._lines.copy()
+
+ def set_visible_range(self, start_time: TIME, end_time: TIME):
+ self.run_script(f'''
+ {self.id}.chart.timeScale().setVisibleRange({{
+ from: {pd.to_datetime(start_time).timestamp()},
+ to: {pd.to_datetime(end_time).timestamp()}
+ }})
+ ''')
+
+ def resize(self, width: Optional[float] = None, height: Optional[float] = None):
+ """
+ Resizes the chart within the window.
+ Dimensions should be given as a float between 0 and 1.
+ """
+ self._width = width if width is not None else self._width
+ self._height = height if height is not None else self._height
+ self.run_script(f'''
+ {self.id}.scale.width = {self._width}
+ {self.id}.scale.height = {self._height}
+ {self.id}.reSize()
+ ''')
+
+ def time_scale(self, right_offset: int = 0, min_bar_spacing: float = 0.5,
+ visible: bool = True, time_visible: bool = True, seconds_visible: bool = False,
+ border_visible: bool = True, border_color: Optional[str] = None):
+ """
+ Options for the timescale of the chart.
+ """
+ self.run_script(f'''{self.id}.chart.applyOptions({{timeScale: {js_json(locals())}}})''')
+
+ def layout(self, background_color: str = '#000000', text_color: Optional[str] = None,
+ font_size: Optional[int] = None, font_family: Optional[str] = None):
+ """
+ Global layout options for the chart.
+ """
+ self.run_script(f"""
+ document.getElementById('container').style.backgroundColor = '{background_color}'
+ {self.id}.chart.applyOptions({{
+ layout: {{
+ background: {{color: "{background_color}"}},
+ {f'textColor: "{text_color}",' if text_color else ''}
+ {f'fontSize: {font_size},' if font_size else ''}
+ {f'fontFamily: "{font_family}",' if font_family else ''}
+ }}}})""")
+
+ def grid(self, vert_enabled: bool = True, horz_enabled: bool = True,
+ color: str = 'rgba(29, 30, 38, 5)', style: LINE_STYLE = 'solid'):
+ """
+ Grid styling for the chart.
+ """
+ self.run_script(f"""
+ {self.id}.chart.applyOptions({{
+ grid: {{
+ vertLines: {{
+ visible: {jbool(vert_enabled)},
+ color: "{color}",
+ style: {as_enum(style, LINE_STYLE)},
+ }},
+ horzLines: {{
+ visible: {jbool(horz_enabled)},
+ color: "{color}",
+ style: {as_enum(style, LINE_STYLE)},
+ }},
+ }}
+ }})""")
+
+ def crosshair(
+ self,
+ mode: CROSSHAIR_MODE = 'normal',
+ vert_visible: bool = True,
+ vert_width: int = 1,
+ vert_color: Optional[str] = None,
+ vert_style: LINE_STYLE = 'large_dashed',
+ vert_label_background_color: str = 'rgb(46, 46, 46)',
+ horz_visible: bool = True,
+ horz_width: int = 1,
+ horz_color: Optional[str] = None,
+ horz_style: LINE_STYLE = 'large_dashed',
+ horz_label_background_color: str = 'rgb(55, 55, 55)'
+ ):
+ """
+ Crosshair formatting for its vertical and horizontal axes.
+ """
+ self.run_script(f'''
+ {self.id}.chart.applyOptions({{
+ crosshair: {{
+ mode: {as_enum(mode, CROSSHAIR_MODE)},
+ vertLine: {{
+ visible: {jbool(vert_visible)},
+ width: {vert_width},
+ {f'color: "{vert_color}",' if vert_color else ''}
+ style: {as_enum(vert_style, LINE_STYLE)},
+ labelBackgroundColor: "{vert_label_background_color}"
+ }},
+ horzLine: {{
+ visible: {jbool(horz_visible)},
+ width: {horz_width},
+ {f'color: "{horz_color}",' if horz_color else ''}
+ style: {as_enum(horz_style, LINE_STYLE)},
+ labelBackgroundColor: "{horz_label_background_color}"
+ }}
+ }}
+ }})''')
+
+ def watermark(self, text: str, font_size: int = 44, color: str = 'rgba(180, 180, 200, 0.5)'):
+ """
+ Adds a watermark to the chart.
+ """
+ self.run_script(f'''
+ {self.id}.chart.applyOptions({{
+ watermark: {{
+ visible: true,
+ horzAlign: 'center',
+ vertAlign: 'center',
+ ...{js_json(locals())}
+ }}
+ }})''')
+
+ def legend(self, visible: bool = False, ohlc: bool = True, percent: bool = True, lines: bool = True,
+ color: str = 'rgb(191, 195, 203)', font_size: int = 11, font_family: str = 'Monaco',
+ text: str = '', color_based_on_candle: bool = False):
+ """
+ Configures the legend of the chart.
+ """
+ l_id = f'{self.id}.legend'
+ if not visible:
+ self.run_script(f'''
+ {l_id}.div.style.display = "none"
+ {l_id}.ohlcEnabled = false
+ {l_id}.percentEnabled = false
+ {l_id}.linesEnabled = false
+ ''')
+ return
+ self.run_script(f'''
+ {l_id}.div.style.display = 'flex'
+ {l_id}.ohlcEnabled = {jbool(ohlc)}
+ {l_id}.percentEnabled = {jbool(percent)}
+ {l_id}.linesEnabled = {jbool(lines)}
+ {l_id}.colorBasedOnCandle = {jbool(color_based_on_candle)}
+ {l_id}.div.style.color = '{color}'
+ {l_id}.color = '{color}'
+ {l_id}.div.style.fontSize = '{font_size}px'
+ {l_id}.div.style.fontFamily = '{font_family}'
+ {l_id}.text.innerText = '{text}'
+ ''')
+
+ def spinner(self, visible):
+ self.run_script(f"{self.id}.spinner.style.display = '{'block' if visible else 'none'}'")
+
+ def hotkey(self, modifier_key: Literal['ctrl', 'alt', 'shift', 'meta', None],
+ keys: Union[str, tuple, int], func: Callable):
+ if not isinstance(keys, tuple):
+ keys = (keys,)
+ for key in keys:
+ key = str(key)
+ if key.isalnum() and len(key) == 1:
+ key_code = f'Digit{key}' if key.isdigit() else f'Key{key.upper()}'
+ key_condition = f'event.code === "{key_code}"'
+ else:
+ key_condition = f'event.key === "{key}"'
+ if modifier_key is not None:
+ key_condition += f'&& event.{modifier_key}Key'
+
+ self.run_script(f'''
+ {self.id}.commandFunctions.unshift((event) => {{
+ if ({key_condition}) {{
+ event.preventDefault()
+ window.callbackFunction(`{modifier_key, keys}_~_{key}`)
+ return true
+ }}
+ else return false
+ }})''')
+ self.win.handlers[f'{modifier_key, keys}'] = func
+
+ def create_table(
+ self,
+ width: NUM,
+ height: NUM,
+ headings: tuple,
+ widths: Optional[tuple] = None,
+ alignments: Optional[tuple] = None,
+ position: FLOAT = 'left',
+ draggable: bool = False,
+ background_color: str = '#121417',
+ border_color: str = 'rgb(70, 70, 70)',
+ border_width: int = 1,
+ heading_text_colors: Optional[tuple] = None,
+ heading_background_colors: Optional[tuple] = None,
+ return_clicked_cells: bool = False,
+ func: Optional[Callable] = None
+ ) -> Table:
+ args = locals()
+ del args['self']
+ return self.win.create_table(*args.values())
+
+ def screenshot(self) -> bytes:
+ """
+ Takes a screenshot. This method can only be used after the chart window is visible.
+ :return: a bytes object containing a screenshot of the chart.
+ """
+ serial_data = self.win.run_script_and_get(f'{self.id}.chart.takeScreenshot().toDataURL()')
+ return b64decode(serial_data.split(',')[1])
+
+ def create_subchart(self, position: FLOAT = 'left', width: float = 0.5, height: float = 0.5,
+ sync: Optional[Union[str, bool]] = None, scale_candles_only: bool = False,
+ sync_crosshairs_only: bool = False,
+ toolbox: bool = False) -> 'AbstractChart':
+ if sync is True:
+ sync = self.id
+ args = locals()
+ del args['self']
+ return self.win.create_subchart(*args.values())
diff --git a/lightweight_charts/chart.py b/lightweight_charts_esistjosh/chart.py
similarity index 90%
rename from lightweight_charts/chart.py
rename to lightweight_charts_esistjosh/chart.py
index 305534c8..4c5a1cf8 100644
--- a/lightweight_charts/chart.py
+++ b/lightweight_charts_esistjosh/chart.py
@@ -4,13 +4,11 @@
import typing
import webview
from webview.errors import JavascriptException
-
-from lightweight_charts import abstract
-from .util import parse_event_message, FLOAT
-
+from .util import parse_event_message, FLOAT, TOOLBOX_MODE
+from .abstract import AbstractChart, Window, INDEX
import os
import threading
-
+from typing import Optional
class CallbackAPI:
def __init__(self, emit_queue):
@@ -45,10 +43,11 @@ def create_window(
width, height = active_screen.width, active_screen.height
else:
width, height = screen.width, screen.height
+ webview.settings['ALLOW_DOWNLOADS'] = True
self.windows.append(webview.create_window(
title,
- url=abstract.INDEX,
+ url=INDEX,
js_api=self.callback_api,
width=width,
height=height,
@@ -146,7 +145,7 @@ def exit(self):
self._reset()
-class Chart(abstract.AbstractChart):
+class Chart(AbstractChart):
_main_window_handlers = None
WV: WebviewHandler = WebviewHandler()
@@ -161,32 +160,34 @@ def __init__(
on_top: bool = False,
maximize: bool = False,
debug: bool = False,
- toolbox: bool = False,
+ toolbox: str = "disabled",
inner_width: float = 1.0,
inner_height: float = 1.0,
scale_candles_only: bool = False,
- position: FLOAT = 'left'
+ position: FLOAT = 'left',
+ defaults: str = None,
+ scripts: str = None
):
Chart.WV.debug = debug
self._i = Chart.WV.create_window(
width, height, x, y, screen, on_top, maximize, title
)
- window = abstract.Window(
+ window = Window(
script_func=lambda s: Chart.WV.evaluate_js(self._i, s),
js_api_code='pywebview.api.callback'
)
- abstract.Window._return_q = Chart.WV.return_queue
+ Window._return_q = Chart.WV.return_queue
self.is_alive = True
if Chart._main_window_handlers is None:
- super().__init__(window, inner_width, inner_height, scale_candles_only, toolbox, position=position)
+ super().__init__(window, inner_width, inner_height, scale_candles_only, toolbox, position=position, defaults= defaults, scripts = scripts)
Chart._main_window_handlers = self.win.handlers
else:
window.handlers = Chart._main_window_handlers
- super().__init__(window, inner_width, inner_height, scale_candles_only, toolbox, position=position)
+ super().__init__(window, inner_width, inner_height, scale_candles_only, toolbox, position=position, defaults= defaults, scripts = scripts)
def show(self, block: bool = False):
"""
@@ -204,7 +205,7 @@ def show(self, block: bool = False):
async def show_async(self):
self.show(block=False)
try:
- from lightweight_charts import polygon
+ from lightweight_charts_esistjosh import polygon
[asyncio.create_task(self.polygon.async_set(*args)) for args in polygon._set_on_load]
while 1:
while Chart.WV.emit_queue.empty() and self.is_alive:
diff --git a/lightweight_charts_esistjosh/defaults/area.json b/lightweight_charts_esistjosh/defaults/area.json
new file mode 100644
index 00000000..15b5277f
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/area.json
@@ -0,0 +1,5 @@
+{
+ "lineColor": "#021698",
+ "topColor": "rgba(9, 32, 210, 0.4)",
+ "bottomColor": "rgba(0, 0, 0, 0.5)"
+ }
\ No newline at end of file
diff --git a/lightweight_charts_esistjosh/defaults/bar.json b/lightweight_charts_esistjosh/defaults/bar.json
new file mode 100644
index 00000000..cc3646ae
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/bar.json
@@ -0,0 +1,7 @@
+{
+ "upColor": "#006721",
+ "downColor": "#6E0000",
+ "borderUpColor": "#006721",
+ "borderDownColor": "#6E0000"
+ }
+
\ No newline at end of file
diff --git a/lightweight_charts_esistjosh/defaults/candlestick.json b/lightweight_charts_esistjosh/defaults/candlestick.json
new file mode 100644
index 00000000..19c0bdf7
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/candlestick.json
@@ -0,0 +1,9 @@
+{
+ "upColor": "rgba(0, 103, 33, 0.33)",
+ "downColor": "rgba(110, 0, 0, 0.33)",
+ "borderUpColor": "#006721",
+ "borderDownColor": "#6E0000",
+ "wickUpColor": "#006721",
+ "wickDownColor": "#6E0000"
+ }
+
\ No newline at end of file
diff --git a/lightweight_charts_esistjosh/defaults/chart.json b/lightweight_charts_esistjosh/defaults/chart.json
new file mode 100644
index 00000000..74edecca
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/chart.json
@@ -0,0 +1,154 @@
+{
+ "width": 784,
+ "height": 561,
+ "autoSize": false,
+ "layout": {
+ "background": {
+ "type": "gradient",
+ "color": "#000000",
+ "topColor": "rgba(255, 0, 0, 0.05)",
+ "bottomColor": "rgba(0, 255, 224, 0.02)"
+ },
+ "textColor": "rgba(255, 0, 3, 1)",
+ "fontSize": 12,
+ "fontFamily": "-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif",
+ "panes": {
+ "enableResize": true,
+ "separatorColor": "#E0E3EB",
+ "separatorHoverColor": "rgba(178, 181, 189, 0.2)"
+ },
+ "attributionLogo": true,
+ "colorSpace": "srgb",
+ "colorParsers": []
+ },
+ "crosshair": {
+ "vertLine": {
+ "color": "rgba(255, 28, 0, 1)",
+ "width": 1,
+ "style": 3,
+ "visible": true,
+ "labelVisible": true,
+ "labelBackgroundColor": "rgb(46, 46, 46)"
+ },
+ "horzLine": {
+ "color": "rgba(255, 28, 0, 1)",
+ "width": 1,
+ "style": 3,
+ "visible": true,
+ "labelVisible": true,
+ "labelBackgroundColor": "rgb(55, 55, 55)"
+ },
+ "mode": 1
+ },
+ "grid": {
+ "vertLines": {
+ "color": "rgba(29, 30, 38, 5)",
+ "style": 0,
+ "visible": true
+ },
+ "horzLines": {
+ "color": "rgba(29, 30, 58, 5)",
+ "style": 0,
+ "visible": true
+ }
+ },
+ "overlayPriceScales": {
+ "autoScale": true,
+ "mode": 0,
+ "invertScale": false,
+ "alignLabels": true,
+ "borderVisible": true,
+ "borderColor": "#2B2B43",
+ "entireTextOnly": false,
+ "visible": false,
+ "ticksVisible": false,
+ "scaleMargins": {
+ "bottom": 0,
+ "top": 0.8
+ },
+ "minimumWidth": 0
+ },
+ "leftPriceScale": {
+ "autoScale": true,
+ "mode": 0,
+ "invertScale": false,
+ "alignLabels": true,
+ "borderVisible": true,
+ "borderColor": "#2B2B43",
+ "entireTextOnly": false,
+ "visible": false,
+ "ticksVisible": false,
+ "scaleMargins": {
+ "bottom": 0.1,
+ "top": 0.2
+ },
+ "minimumWidth": 0
+ },
+ "rightPriceScale": {
+ "autoScale": true,
+ "mode": 0,
+ "invertScale": false,
+ "alignLabels": true,
+ "borderVisible": true,
+ "borderColor": "#2B2B43",
+ "entireTextOnly": false,
+ "visible": true,
+ "ticksVisible": false,
+ "scaleMargins": {
+ "bottom": 0.1,
+ "top": 0.2
+ },
+ "minimumWidth": 0
+ },
+ "timeScale": {
+ "rightOffset": 0,
+ "barSpacing": 6,
+ "minBarSpacing": 0.5,
+ "maxBarSpacing": 0,
+ "fixLeftEdge": false,
+ "fixRightEdge": false,
+ "lockVisibleTimeRangeOnResize": false,
+ "rightBarStaysOnScroll": false,
+ "borderVisible": true,
+ "borderColor": "#2B2B43",
+ "visible": true,
+ "timeVisible": true,
+ "secondsVisible": false,
+ "shiftVisibleRangeOnNewBar": true,
+ "allowShiftVisibleRangeOnWhitespaceReplacement": false,
+ "ticksVisible": false,
+ "uniformDistribution": false,
+ "minimumHeight": 0,
+ "allowBoldLabels": true,
+ "ignoreWhitespaceIndices": false
+ },
+ "localization": {
+ "locale": "en-US",
+ "dateFormat": "dd MMM 'yy"
+ },
+ "handleScroll": {
+ "mouseWheel": true,
+ "pressedMouseMove": true,
+ "horzTouchDrag": true,
+ "vertTouchDrag": true
+ },
+ "handleScale": {
+ "axisPressedMouseMove": {
+ "time": true,
+ "price": true
+ },
+ "axisDoubleClickReset": {
+ "time": true,
+ "price": true
+ },
+ "mouseWheel": true,
+ "pinch": true
+ },
+ "kineticScroll": {
+ "mouse": false,
+ "touch": true
+ },
+ "trackingMode": {
+ "exitMode": 1
+ }
+}
diff --git a/lightweight_charts_esistjosh/defaults/histogram.json b/lightweight_charts_esistjosh/defaults/histogram.json
new file mode 100644
index 00000000..ebf50748
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/histogram.json
@@ -0,0 +1,5 @@
+{
+ "color": "#9ACF01",
+ "base": 0
+ }
+
\ No newline at end of file
diff --git a/lightweight_charts_esistjosh/defaults/line.json b/lightweight_charts_esistjosh/defaults/line.json
new file mode 100644
index 00000000..70871200
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/line.json
@@ -0,0 +1,6 @@
+{
+ "color": "#195200",
+ "lineWidth": 2,
+ "crosshairMarkerVisible": true
+ }
+
\ No newline at end of file
diff --git a/lightweight_charts_esistjosh/defaults/ohlc.json b/lightweight_charts_esistjosh/defaults/ohlc.json
new file mode 100644
index 00000000..0756f7c5
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/ohlc.json
@@ -0,0 +1,18 @@
+{
+ "upColor": "rgba(0, 103, 33, 0.175)",
+ "downColor": "rgba(110, 0, 0, 0.175)",
+ "borderUpColor": "#00a921",
+ "borderDownColor": "#aa0000",
+ "wickUpColor": "#006721",
+ "wickDownColor": "#6E0000",
+ "shape": "Rounded",
+ "chandelierSize": 3,
+ "barSpacing": 0.777,
+ "lineStyle": 0,
+ "lineWidth": 1.5,
+ "enableVolumeOpacity": true,
+ "volumeOpacityPeriod": 21,
+ "maxOpacity":0.333,
+ "dynamicCandles": "use Chandelier Size"
+ }
+
\ No newline at end of file
diff --git a/lightweight_charts_esistjosh/defaults/pitchfork.json b/lightweight_charts_esistjosh/defaults/pitchfork.json
new file mode 100644
index 00000000..5d245a22
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/pitchfork.json
@@ -0,0 +1,59 @@
+{
+ "lineColor": "#ffffff",
+ "lineStyle": "LargeDashed",
+ "width": 1,
+ "variant": "standard",
+ "forkLines": [
+ {
+ "value": 1.0,
+ "width": 2,
+ "style": "Solid",
+ "color": "#ff0000",
+ "fillColor": null
+ },
+ {
+ "value": 0.786,
+ "width": 1,
+ "style": "SparseDotted",
+ "color": "#000fff",
+ "fillColor": null
+ },
+ {
+ "value": 0.618,
+ "width": 1,
+ "style": "LargeDashed",
+ "color": "#ffffff",
+ "fillColor": null
+ },
+ {
+ "value": 0.5,
+ "width": 2,
+ "style": "Solid",
+ "color": "#ff0000",
+ "fillColor": null
+ },
+ {
+ "value": 0.382,
+ "width": 1,
+ "style": "LargeDashed",
+ "color": "#ffffff",
+ "fillColor": null
+ },
+ {
+ "value": 0.236,
+ "width": 1,
+ "style": "SparseDotted",
+ "color": "#000fff",
+ "fillColor": null
+ },
+ {
+ "value": 0,
+ "width": 2,
+ "style": "Solid",
+ "color": "#ff0000",
+ "fillColor": null
+ }
+ ],
+ "length": 1.0
+ }
+
\ No newline at end of file
diff --git a/lightweight_charts_esistjosh/defaults/trend-trace.json b/lightweight_charts_esistjosh/defaults/trend-trace.json
new file mode 100644
index 00000000..5bbe313d
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/trend-trace.json
@@ -0,0 +1,26 @@
+{
+ "visible": true,
+ "autoScale": false,
+ "xScaleLock": false,
+ "yScaleLock": false,
+ "color": "#737375",
+ "lineWidth": 1,
+ "upColor": "rgba(0,255,0,.25)",
+ "downColor": "rgba(255,0,0,.25)",
+ "wickVisible": true,
+ "borderVisible": true,
+ "borderColor": "#737375",
+ "borderUpColor": "#1c9d1c",
+ "borderDownColor": "#d5160c",
+ "wickColor": "#737375",
+ "wickUpColor": "#1c9d1c",
+ "wickDownColor": "#d5160c",
+ "radius": 100,
+ "shape": "Rounded",
+ "chandelierSize": 1,
+ "barSpacing": 0.7,
+ "lineStyle": 0,
+ "lineColor": "#ffffff",
+ "width": 1
+ }
+
\ No newline at end of file
diff --git a/lightweight_charts_esistjosh/defaults/volume-profile.json b/lightweight_charts_esistjosh/defaults/volume-profile.json
new file mode 100644
index 00000000..5f25f82f
--- /dev/null
+++ b/lightweight_charts_esistjosh/defaults/volume-profile.json
@@ -0,0 +1,17 @@
+{
+ "visible": true,
+ "sections": 0,
+ "upColor": null,
+ "downColor": null,
+ "borderUpColor": null,
+ "borderDownColor": null,
+ "rightSide": true,
+ "width": 0,
+ "lineColor": "#ffffff",
+ "lineStyle": "Solid",
+ "drawGrid": true,
+ "gridWidth": 1,
+ "gridColor": "rgba(255, 255, 255, 0.125)",
+ "gridLineStyle": "SparseDotted"
+ }
+
\ No newline at end of file
diff --git a/lightweight_charts/drawings.py b/lightweight_charts_esistjosh/drawings.py
similarity index 98%
rename from lightweight_charts/drawings.py
rename to lightweight_charts_esistjosh/drawings.py
index 36a73059..61ed788c 100644
--- a/lightweight_charts/drawings.py
+++ b/lightweight_charts_esistjosh/drawings.py
@@ -4,7 +4,7 @@
from typing import Union, Optional
-from lightweight_charts.util import js_json
+from lightweight_charts_esistjosh.util import js_json
from .util import NUM, Pane, as_enum, LINE_STYLE, TIME, snake_to_camel
@@ -250,7 +250,7 @@ def __init__(self, series: 'SeriesCommon', start_time: Union[TIME, tuple, list],
super().__init__(self._chart.win)
start_time, end_time = pd.to_datetime(start_time), pd.to_datetime(end_time)
self.run_script(f'''
- {self.id} = {self._chart.id}.chart.addHistogramSeries({{
+ {self.id} = {self._chart.id}.chart.addSeries(HistogramSeries,{{
color: '{color}',
priceFormat: {{type: 'volume'}},
priceScaleId: 'vertical_line',
diff --git a/lightweight_charts_esistjosh/js/.old b/lightweight_charts_esistjosh/js/.old
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/lightweight_charts_esistjosh/js/.old
@@ -0,0 +1 @@
+
diff --git a/lightweight_charts_esistjosh/js/bundle.js b/lightweight_charts_esistjosh/js/bundle.js
new file mode 100644
index 00000000..a32894e6
--- /dev/null
+++ b/lightweight_charts_esistjosh/js/bundle.js
@@ -0,0 +1,3 @@
+var Lib=function(e,t,i){"use strict";function s(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(i){if("default"!==i){var s=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,s.get?s:{enumerable:!0,get:function(){return e[i]}})}})),t.default=e,Object.freeze(t)}var n,o=s(i);function r(e){if(void 0===e)throw new Error("Value is undefined");return e}class a{_chart=void 0;_series=void 0;requestUpdate(){this._requestUpdate&&this._requestUpdate()}_requestUpdate;attached({chart:e,series:t,requestUpdate:i}){this._chart=e,this._series=t,this._series.subscribeDataChanged(this._fireDataUpdated),this._requestUpdate=i,this.requestUpdate()}detached(){this._chart=void 0,this._series=void 0,this._requestUpdate=void 0}get chart(){return r(this._chart)}get series(){return r(this._series)}_fireDataUpdated(e){this.dataUpdated&&this.dataUpdated(e)}toJSON(){return{}}fromJSON(e){}}function l(e,t){if(e.startsWith("#"))return function(e,t){if(e=e.replace(/^#/,""),!/^([0-9A-F]{3}){1,2}$/i.test(e))throw new Error("Invalid hex color format.");const[i,s,n]=3===(o=e).length?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)];var o;return`rgba(${i}, ${s}, ${n}, ${t})`}(e,t);{const i=/^rgb(a)?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:,\s*([\d.]+))?\)/i,s=e.match(i);if(s){const e=s[2],i=s[3],n=s[4],o=s[1]?s[5]??"1":"1";return`rgba(${e}, ${i}, ${n}, ${t??o})`}throw new Error("Unsupported color format. Use hex, rgb, or rgba.")}}function c(e,t=.2){let[i,s,n,o=1]=e.startsWith("#")?[...(r=e,3===(r=r.replace(/^#/,"")).length?[parseInt(r[0]+r[0],16),parseInt(r[1]+r[1],16),parseInt(r[2]+r[2],16)]:[parseInt(r.slice(0,2),16),parseInt(r.slice(2,4),16),parseInt(r.slice(4,6),16)]),1]:e.match(/\d+(\.\d+)?/g).map(Number);var r;return i=Math.max(0,Math.min(255,i*(1-t))),s=Math.max(0,Math.min(255,s*(1-t))),n=Math.max(0,Math.min(255,n*(1-t))),e.startsWith("#")?`#${((1<<24)+(Math.round(i)<<16)+(Math.round(s)<<8)+Math.round(n)).toString(16).slice(1)}`:`rgba(${Math.round(i)}, ${Math.round(s)}, ${Math.round(n)}, ${o})`}function h(e,t,i=""){for(const s of Object.keys(e)){const n=i?`${i}.${s}`:s,o=e[s];"object"==typeof o&&null!==o?h(o,t,n):s.toLowerCase().includes("color")&&t(n,o)}}function p(e){if(e.length>100)return 1;let t=1;const i=/^rgba\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(\d?\.?\d+)\s*$/i.exec(e),s=/^hsla\s*\d{1,3}(?:\.\d+)?\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*,\s*(\d?\.?\d+)\s*$/i.exec(e);return i?t=parseFloat(i[1]):s&&(t=parseFloat(s[1])),isNaN(t)?1:Math.max(0,Math.min(1,t))}class d{numbers;cache;constructor(e){this.numbers=e,this.cache=new Map}findClosestIndex(e,t){const i=`${e}:${t}`;if(this.cache.has(i))return this.cache.get(i);const s=this._performSearch(e,t);return this.cache.set(i,s),s}_performSearch(e,t){let i=0,s=this.numbers.length-1;if(e<=this.numbers[0].time)return 0;if(e>=this.numbers[s].time)return s;for(;i<=s;){const t=Math.floor((i+s)/2),n=this.numbers[t].time;if(n===e)return t;n>e?s=t-1:i=t+1}return"left"===t?i:s}}function u(e){switch(e.trim().toLowerCase()){case"rectangle":return n.Rectangle;case"rounded":return n.Rounded;case"ellipse":return n.Ellipse;case"arrow":return n.Arrow;case"3d":return n.Cube;case"polygon":return n.Polygon;case"bar":return n.Bar;case"slanted":return n.Slanted;default:return console.warn(`Unknown CandleShape: ${e}`),n.Rectangle}}function m(e){return e.type===t.ColorType.Solid}function g(e){return e.type===t.ColorType.VerticalGradient}function f(e){return"value"in e}function y(e){return"close"in e&&"open"in e&&"high"in e&&"low"in e}function b(e){return!(!e||"object"!=typeof e)&&("time"in e&&!("value"in e||"open"in e||"close"in e||"high"in e||"low"in e))}function v(e){const t=e.options();return"lineColor"in t||"color"in t}function x(e){return"object"==typeof e&&null!==e&&"function"==typeof e.data&&"function"==typeof e.options}!function(e){e.Rectangle="Rectangle",e.Rounded="Rounded",e.Ellipse="Ellipse",e.Arrow="Arrow",e.Cube="3d",e.Polygon="Polygon",e.Bar="Bar",e.Slanted="Slanted"}(n||(n={}));class _ extends a{static type="Fill Area";_paneViews;_originSeries;_destinationSeries;_bandsData=[];options;_timeIndices;constructor(e,t,i){super();const s=l("#0000FF",.25),n=l("#FF0000",.25),o=v(e)?l(e.options().color||s,.3):l(s,.3),r=v(t)?l(t.options().color||n,.3):l(n,.3);this.options={...S,...i,originColor:i.originColor??o,destinationColor:i.destinationColor??r},this._paneViews=[new C(this)],this._timeIndices=new d([]),this._originSeries=e,this._destinationSeries=t,this._originSeries.subscribeDataChanged((()=>{console.log("Origin series data has changed. Recalculating bands."),this.dataUpdated("full"),this.updateAllViews()})),this._destinationSeries.subscribeDataChanged((()=>{console.log("Destination series data has changed. Recalculating bands."),this.dataUpdated("full"),this.updateAllViews()}))}updateAllViews(){this._paneViews.forEach((e=>e.update()))}applyOptions(e){this.options={...this.options,...e},this.calculateBands(),this.updateAllViews(),super.requestUpdate(),console.log("FillArea options updated:",this.options)}paneViews(){return this._paneViews}attached(e){super.attached(e),this.dataUpdated("full")}dataUpdated(e){if(this.calculateBands(),"full"===e){const e=this._originSeries.data();this._timeIndices=new d([...e])}}calculateBands(){const e=this._originSeries.data(),t=this._destinationSeries.data(),i=this._alignDataLengths([...e],[...t]),s=[];for(let e=0;es){const e=t[s-1];for(;t.lengthi){const t=e[i-1];for(;e.lengthe.lower)).slice(o,r+1)),maxValue:Math.max(...this._bandsData.map((e=>e.upper)).slice(o,r+1))};return{priceRange:{minValue:a.minValue,maxValue:a.maxValue}}}}class w{_viewData;_options;constructor(e){this._viewData=e,this._options=e.options}draw(){}drawBackground(e){const t=this._viewData.data,i=this._options;t.length<2||e.useBitmapCoordinateSpace((e=>{const s=e.context;s.scale(e.horizontalPixelRatio,e.verticalPixelRatio);let n=!1,o=0;for(let e=0;e=o;i--)s.lineTo(t[i].x,t[i].destination);s.closePath(),s.fill()}s.beginPath(),s.moveTo(r.x,r.origin),s.fillStyle=r.isOriginAbove?i.originColor||"rgba(0, 0, 0, 0)":i.destinationColor||"rgba(0, 0, 0, 0)",o=e,n=!0}if(s.lineTo(a.x,a.origin),e===t.length-2||a.isOriginAbove!==r.isOriginAbove){for(let i=e+1;i>=o;i--)s.lineTo(t[i].x,t[i].destination);s.closePath(),s.fill(),n=!1}}i.lineWidth&&(s.lineWidth=i.lineWidth,s.strokeStyle=i.originColor||"rgba(0, 0, 0, 0)",s.stroke())}))}}class C{_source;_data;constructor(e){this._source=e,this._data={data:[],options:this._source.options}}update(){const e=this._source.chart.timeScale();this._data.data=this._source._bandsData.map((t=>({x:e.timeToCoordinate(t.time),origin:this._source._originSeries.priceToCoordinate(t.origin),destination:this._source._destinationSeries.priceToCoordinate(t.destination),isOriginAbove:t.origin>t.destination}))),this._data.options=this._source.options}renderer(){return new w(this._data)}zOrder(){return"bottom"}}const S={originColor:null,destinationColor:null,lineWidth:null};function k(e,t){let i,s;if(void 0!==e.close){i=e.close}else void 0!==e.value&&(i=e.value);if(void 0!==t.close){s=t.close}else void 0!==t.value&&(s=t.value);if(void 0!==i&&void 0!==s){if(i{e&&(window.cursor=e),document.body.style.cursor=window.cursor},window.cursor="default",window.textBoxFocused=!1}const P='\n\n',T='\n\n';class I{contextMenu;handler;constructor(e){this.contextMenu=e.contextMenu,this.handler=e.handler}populateLegendMenu(e,t){this.contextMenu.clearMenu();void 0!==e.seriesList?this.populateGroupMenu(e,t):this.populateSeriesMenu(e,t),this.contextMenu.separator(),this.contextMenu.addMenuItem("Close Menu",(()=>this.contextMenu.hideMenu())),this.contextMenu.showMenu(t)}populateGroupMenu(e,t){if(this.contextMenu.addMenuItem("Rename",(()=>{const t=prompt("Enter new group name:",e.name);t&&""!==t.trim()&&this.renameGroup(e,t.trim())}),!1),this.contextMenu.addMenuItem("Remove",(()=>{confirm(`Are you sure you want to remove the group "${e.name}"? This will also remove all contained series.`)&&(e.seriesList.forEach((e=>{this.handler.legend.removeLegendSeries(e.series),this.handler.removeSeries(e.series)})),this.removeGroup(e))})),this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeries(e)})),e.seriesList&&e.seriesList.length>0){const t=e.seriesList[0].series.getPane().paneIndex(),i=this.handler.chart.panes(),s=`Pane ${t}`,n=()=>{0===t?i.length>1?(e.seriesList.forEach((e=>{e.series.moveToPane(1)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} to pane 1.`)):(e.seriesList.forEach((e=>{e.series.moveToPane(i.length)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} to a new pane at index ${i.length}.`)):(e.seriesList.forEach((e=>{e.series.moveToPane(0)})),console.log(`Default: Moved group "${e.name}" series from pane ${t} back to main pane (0).`))},o=[];for(let t=0;t{e.seriesList.forEach((e=>{e.series.moveToPane(t)})),console.log(`Moved group "${e.name}" series to existing pane ${t}.`)}});o.push({name:"New Pane",action:()=>{e.seriesList.forEach((e=>{e.series.moveToPane(i.length)})),console.log(`Moved group "${e.name}" series to a new pane at index ${i.length}.`)}}),this.contextMenu.addMenuInput(this.contextMenu.div,{type:"hybrid",label:"Move to",sublabel:s,value:s,onChange:e=>{const t=o.find((t=>t.name===e));t&&t.action()},hybridConfig:{defaultAction:n,options:o.map((e=>({name:e.name,action:e.action})))}})}this.contextMenu.showMenu(t)}populateSeriesMenu(e,t){this.contextMenu.addMenuItem("Open Series Menu",(()=>{this.contextMenu.populateSeriesMenu(e.series,t)}),!1),this.contextMenu.addMenuItem("Move to Group ▸",(()=>{this.populateMoveToGroupMenu(e)}),!1),this.contextMenu.addMenuItem("Remove Series",(()=>{confirm(`Are you sure you want to remove the series "${e.name}"?`)&&(this.handler.legend.removeLegendSeries(e.series),this.handler.removeSeries(e.series))})),e.primitives&&this.contextMenu.addMenuItem("Remove Primitives",(()=>{this.removePrimitivesFromSeries(e)})),e.group&&this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeriesFromGroup(e)})),this.contextMenu.showMenu(t)}populateMoveToGroupMenu(e){this.contextMenu.clearMenu();this.handler.legend._groups.forEach((t=>{this.contextMenu.addMenuItem(t.name,(()=>{this.handler.legend.moveSeriesToGroup(e,t)}))})),this.contextMenu.addMenuItem("Create New Group...",(()=>{const t=prompt("Enter new group name:","New Group");t&&""!==t.trim()&&this.createNewGroup(e,t.trim())})),e.group&&this.contextMenu.addMenuItem("Ungroup",(()=>{this.ungroupSeriesFromGroup(e)}))}renameGroup(e,t){e.name=t,e.seriesList.forEach((e=>{e.group=t}));const i=e.row.querySelector(".group-header span");i&&(i.textContent=t),console.log(`Group renamed to: ${t}`)}removeGroup(e){this.handler.legend.removeLegendGroup(e),this.handler.legend._groups=this.handler.legend._groups.filter((t=>t!==e)),console.log(`Group "${e.name}" removed along with its series.`)}createNewGroup(e,t){this.handler.legend.deleteLegendEntry(e),e.group=t,this.handler.legend.addLegendItem(e)}ungroupSeriesFromGroup(e){this.handler.legend.getGroupOfSeries(e.series)&&(this.handler.legend.deleteLegendEntry(e),e.group=void 0,this.handler.legend.addLegendItem(e)),console.log(`Series "${e.name}" removed from its group and is now standalone.`)}removePrimitivesFromSeries(e){e.series.primitives&&(Object.values(e.series.primitives).forEach((t=>{e.series.detachPrimitive(t),console.log(`Primitive removed from series "${e.name}".`)})),e.primitives=void 0),console.log(`All primitives removed from series "${e.name}".`)}ungroupSeries(e){e.seriesList.forEach((e=>{this.handler.legend.deleteLegendEntry(e),e.group=void 0,this.handler.legend.addLegendItem(e)})),this.removeGroup(e),console.log(`All series in group "${e.name}" have been ungrouped and are now standalone.`)}}function A(e){return e.data()[e.data().length-1]}class D{handler;div;seriesContainer;legendMenu;linesEnabled=!1;contextMenu;text;_items=[];_lines=[];_groups=[];constructor(e){this.handler=e,this.div=document.createElement("div"),this.div.classList.add("legend"),this.seriesContainer=document.createElement("div"),this.text=document.createElement("span"),this.contextMenu=this.handler.ContextMenu,this.legendMenu=new I({contextMenu:this.contextMenu,handler:e}),this.setupLegend(),this.legendHandler=this.legendHandler.bind(this),e.chart.subscribeCrosshairMove(this.legendHandler)}setupLegend(){this.div.style.maxWidth=100*this.handler.scale.width-8+"vw",this.div.style.display="none";const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="row",this.seriesContainer.classList.add("series-container"),this.text.style.lineHeight="1.8",e.appendChild(this.seriesContainer),this.div.appendChild(this.text),this.div.appendChild(e),this.handler.div.appendChild(this.div)}legendItemFormat(e,t){return"number"!=typeof e||isNaN(e)?"-":e.toFixed(t).toString().padStart(8," ")}shorthandFormat(e){const t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(1)+"M":t>=1e3?(e/1e3).toFixed(1)+"K":e.toString().padStart(8," ")}createSvgIcon(e){const t=document.createElement("div");t.innerHTML=e.trim();return t.querySelector("svg")}addLegendItem(e){const t=this.mapToSeries(e);if(t.group)return this.addItemToGroup(t,t.group);{const e=this.makeSeriesRow(t,this.seriesContainer);return this._lines.push(t),this._items.push(t),e}}addLegendPrimitive(e,t,i){const s=i||t.constructor.name,n=this._lines.find((t=>t.series===e));if(!n)return void console.warn(`Parent series not found in legend for primitive: ${s}`);n.primitives||(n.primitives=[]);let o=this.seriesContainer.querySelector(`[data-series-id="${n.name}"] .primitives-container`);o||(o=document.createElement("div"),o.classList.add("primitives-container"),o.style.display="none",o.style.marginLeft="20px",o.style.flexDirection="column",n.row.insertAdjacentElement("afterend",o));const r=Array.from(o.children).find((e=>e.getAttribute("data-primitive-type")===s));if(r)return console.warn(`Primitive "${s}" already exists under the parent series.`),r;const a=document.createElement("div");a.classList.add("legend-primitive-row"),a.setAttribute("data-primitive-type",s),a.style.display="flex",a.style.justifyContent="space-between",a.style.marginTop="4px";const l=document.createElement("span");l.innerText=s;const c=document.createElement("div");c.style.cursor="pointer",c.style.display="flex",c.style.alignItems="center";const h=this.createSvgIcon(P),p=this.createSvgIcon(T);c.appendChild(h.cloneNode(!0));let d=!0;c.addEventListener("click",(()=>{d=!d,c.innerHTML="",c.appendChild(d?h.cloneNode(!0):p.cloneNode(!0)),this.togglePrimitive(t,d)})),a.appendChild(l),a.appendChild(c),o.appendChild(a),o.children.length>0&&(o.style.display="block");const u={name:s,primitive:t,row:a};return this._items.push(u),n.primitives.push(u),a}togglePrimitive(e,t){const i=e.options||e._options;if(!i)return void console.warn("Primitive has no options to update.");const s={};if("visible"in i)return s.visible=t,console.log(`Toggling visible option for primitive: ${e.constructor.name} to ${t}`),void e.applyOptions(s);const n="_originalColors";e[n]||(e[n]={});const o=e[n];for(const e of Object.keys(i))e.toLowerCase().includes("color")&&(t?s[e]=o[e]||i[e]:(o[e]||(o[e]=i[e]),s[e]="rgba(0,0,0,0)"));Object.keys(s).length>0&&(console.log(`Updating visibility for primitive: ${e.constructor.name}`),e.applyOptions(s),t&&delete e[n])}findLegendPrimitive(e,t){const i=this._lines.find((t=>t.series===e));if(!i||!i.primitives)return null;return i.primitives.find((e=>e.primitive===t))||null}mapToSeries(e){return{name:e.name,series:e.series,group:e.group||void 0,legendSymbol:e.legendSymbol||[],colors:e.colors||["#000"],seriesType:e.seriesType||"Line",div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div"),extraData:e.extraData||null}}addItemToGroup(e,t){let i=this._groups.find((e=>e.name===t));return i?(i.seriesList.push(e),this.makeSeriesRow(e,i.div),i.row):this.makeSeriesGroup(t,[e])}makeSeriesGroup(e,t){let i=this._groups.find((t=>t.name===e));if(i)return i.seriesList.push(...t),t.forEach((e=>this.makeSeriesRow(e,i.div))),i.row;{const i={name:e,seriesList:t,subGroups:[],div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div")};return this._groups.push(i),this.renderGroup(i,this.seriesContainer),i.row}}makeSeriesRow(e,t){const i=document.createElement("div");i.classList.add("legend-series-row"),i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="space-between",i.style.marginBottom="4px";const s=document.createElement("button");s.classList.add("legend-action-button"),s.innerHTML="◇",s.title="Series Actions",s.style.marginRight="0px",s.style.fontSize="1em",s.style.border="none",s.style.background="none",s.style.cursor="pointer",s.style.color="#ffffff",s.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===s.innerHTML?s.innerHTML="◈":s.innerHTML="◇",this.legendMenu.populateLegendMenu(e,t)}));const n=document.createElement("div");n.classList.add("series-info"),n.style.flex="1";if(["Bar","Candlestick","Ohlc"].includes(e.seriesType||"")){const t="-",i="-",s=e.legendSymbol[0]||"▨",o=e.legendSymbol[1]||s,r=e.colors[0]||"#00FF00",a=e.colors[1]||"#FF0000";n.innerHTML=`\n ${s}\n ${o}\n ${e.name}: O ${t}, \n C ${i}\n `}else n.innerHTML=e.legendSymbol.map(((t,i)=>`${t}`)).join(" ")+` ${e.name}`;const o=document.createElement("div");o.classList.add("legend-toggle-switch"),o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center";const r=this.createSvgIcon(P),a=this.createSvgIcon(T);o.appendChild(r.cloneNode(!0));let l=!0;o.addEventListener("click",(t=>{l=!l,e.series.applyOptions({visible:l}),o.innerHTML="",o.appendChild(l?r.cloneNode(!0):a.cloneNode(!0)),o.setAttribute("aria-pressed",l.toString()),o.classList.toggle("inactive",!l),t.stopPropagation()})),o.setAttribute("role","button"),o.setAttribute("aria-label",`Toggle visibility for ${e.name}`),o.setAttribute("aria-pressed",l.toString()),i.appendChild(s),i.appendChild(n),i.appendChild(o),t.appendChild(i),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)}));const c={...e,div:n,row:i,toggle:o};return this._lines.push(c),this._items.push(c),i}isLegendPrimitive(e){return void 0!==e.primitive&&void 0!==e.row}deleteLegendEntry(e,t){if(t&&!e){const e=this._groups.findIndex((e=>e.name===t));if(-1!==e){const i=this._groups[e];this.seriesContainer.removeChild(i.row),this._groups.splice(e,1),this._items=this._items.filter((e=>e!==i)),console.log(`Group "${t}" removed.`)}else console.warn(`Legend group with name "${t}" not found.`)}else if(e){let i=!1;if(t){const s=this._groups.find((e=>e.name===t));if(s){const n=s.seriesList.findIndex((t=>t.name===e));-1!==n&&(s.seriesList.splice(n,1),0===s.seriesList.length?(this.seriesContainer.removeChild(s.row),this._groups=this._groups.filter((e=>e!==s)),this._items=this._items.filter((e=>e!==s)),console.log(`Group "${t}" is empty and has been removed.`)):this.renderGroup(s,this.seriesContainer),i=!0,console.log(`Series "${e}" removed from group "${t}".`))}else console.warn(`Legend group with name "${t}" not found.`)}if(!i){const t=this._lines.findIndex((t=>t.name===e));if(-1!==t){const s=this._lines[t];this.seriesContainer.removeChild(s.row),this._lines.splice(t,1),this._items=this._items.filter((e=>e!==s)),i=!0,console.log(`Series "${e}" removed.`)}}i||console.warn(`Legend item with name "${e}" not found.`)}else console.warn("No seriesName or groupName provided for deletion.")}removeLegendGroup(e){this.seriesContainer.contains(e.row)&&this.seriesContainer.removeChild(e.row);const t=this._groups.indexOf(e);-1!==t&&this._groups.splice(t,1),this._items=this._items.filter((t=>t!==e)),console.log(`Group "${e.name}" removed from legend.`)}findSeriesAnywhere(e){const t=this._lines.find((t=>t.series===e));if(t)return t;for(const t of this._groups){const i=this.findSeriesInGroup(t,e);if(i)return i}}findSeriesInGroup(e,t){const i=e.seriesList.find((e=>e.series===t));if(i)return i;for(const i of e.subGroups){const e=this.findSeriesInGroup(i,t);if(e)return e}}removeSeriesFromGroupDOM(e,t){if(!e.div||!t.row)return console.warn(`⚠️ Cannot remove series "${t.name}" – missing group div or series row.`),!1;if(e.div.contains(t.row))try{return e.div.removeChild(t.row),console.log(`✅ Removed series "${t.name}" from group "${e.name}".`),!0}catch(i){return console.warn(`⚠️ Error removing series "${t.name}" from group "${e.name}":`,i),!1}return e.subGroups.some((e=>this.removeSeriesFromGroupDOM(e,t)))}removeLegendSeries(e){let t;if(t=x(e)?this.findSeriesAnywhere(e):e,t){if(this._lines=this._lines.filter((e=>e!==t)),this._items=this._items.filter((e=>e!==t)),t.group){const e=this.findGroup(t.group);if(e){if(e.seriesList=e.seriesList.filter((e=>e!==t)),t.row&&e.div.contains(t.row))try{e.div.removeChild(t.row),console.log(`✅ Removed "${t.name}" from group "${e.name}".`)}catch(i){console.warn(`⚠️ Error removing "${t.name}" from group "${e.name}":`,i)}0===e.seriesList.length&&this.removeGroupCompletely(e)}}else if(t.row?.parentElement)try{t.row.parentElement.removeChild(t.row),console.log(`✅ Removed row for standalone series: ${t.name}`)}catch(e){console.warn("⚠️ Error removing standalone series row:",e)}}else console.warn("⚠️ LegendSeries not found in legend.")}removeGroupCompletely(e){if(e.row.parentElement)try{e.row.parentElement.removeChild(e.row)}catch(t){console.warn(`Error removing group "${e.name}":`,t)}this._groups=this._groups.filter((t=>t!==e)),this._items=this._items.filter((t=>t!==e)),console.log(`Group "${e.name}" removed as it became empty.`)}removeLegendPrimitive(e){let t;if(t=this.isLegendPrimitive(e)?e:this._items.find((t=>this.isLegendPrimitive(t)&&t.primitive===e)),!t)return void console.warn("❌ LegendPrimitive not found in legend.");t.row&&t.row.parentElement?t.row.parentElement.removeChild(t.row):console.warn("❌ LegendPrimitive row not found in the DOM.");const i=this._lines.find((e=>e.primitives?.includes(t)));if(i&&(i.primitives=i.primitives.filter((e=>e!==t)),console.log(`✅ Removed primitive "${t.name}" from series "${i.name}".`)),this._items=this._items.filter((e=>e!==t)),t.primitive)try{console.log(`Detaching underlying chart primitive for "${t.name}".`),i?.series.detachPrimitive(t.primitive)}catch(e){console.warn(`⚠️ Failed to detach primitive "${t.name}":`,e)}console.log(`✅ LegendPrimitive "${t.name}" removed from legend.`)}getGroupOfSeries(e){for(const t of this._groups){const i=this.findGroupOfSeriesRecursive(t,e);if(i)return i}}findGroupOfSeriesRecursive(e,t){for(const i of e.seriesList)if(i.series===t)return e.name;for(const i of e.subGroups){const e=this.findGroupOfSeriesRecursive(i,t);if(e)return e}}moveSeriesToGroup(e,t){let i=this._lines.findIndex((t=>t.name===e)),s=null;if(-1!==i)s=this._lines[i];else for(const t of this._groups){const i=t.seriesList.findIndex((t=>t.name===e));if(-1!==i){s=t.seriesList[i],t.seriesList.splice(i,1),0===t.seriesList.length?(this.seriesContainer.removeChild(t.row),this._groups=this._groups.filter((e=>e!==t)),this._items=this._items.filter((e=>e!==t)),console.log(`Group "${t.name}" is empty and has been removed.`)):this.renderGroup(t,this.seriesContainer);break}}if(!s)return void console.warn(`Series "${e}" not found in legend.`);-1!==i?(this.seriesContainer.removeChild(s.row),this._lines.splice(i,1),this._items=this._items.filter((e=>e!==s))):this._items=this._items.filter((e=>e!==s));let n=this.findGroup(t);n?(n.seriesList.push(s),this.makeSeriesRow(s,n.div)):(n={name:t,seriesList:[s],subGroups:[],div:document.createElement("div"),row:document.createElement("div"),toggle:document.createElement("div")},this._groups.push(n),this.renderGroup(n,this.seriesContainer)),this._items.push(s),console.log(`Series "${e}" moved to group "${t}".`)}renderGroup(e,t){e.row.innerHTML="",e.row.style.display="flex",e.row.style.flexDirection="column",e.row.style.width="100%";const i=document.createElement("div");i.classList.add("group-header"),i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="space-between",i.style.cursor="pointer";const s=document.createElement("button");s.classList.add("legend-action-button"),s.innerHTML="◇",s.title="Group Actions",s.style.marginRight="0px",s.style.fontSize="1em",s.style.border="none",s.style.background="none",s.style.cursor="pointer",s.style.color="#ffffff",s.addEventListener("click",(t=>{t.stopPropagation(),t.preventDefault(),"◇"===s.innerHTML?s.innerHTML="◈":s.innerHTML="◇",this.legendMenu.populateLegendMenu(e,t)}));const n=document.createElement("span");n.style.fontWeight="bold",n.innerHTML=e.seriesList.map((e=>e.legendSymbol.map(((t,i)=>`${t}`)).join(" "))).join(" ")+` ${e.name}`;const o=document.createElement("span");o.classList.add("toggle-button"),o.style.marginLeft="auto",o.style.fontSize="1.2em",o.style.cursor="pointer",o.innerHTML="⌲",o.setAttribute("aria-expanded","true"),o.addEventListener("click",(t=>{t.stopPropagation(),"none"===e.div.style.display?(e.div.style.display="block",o.innerHTML="⌲",o.setAttribute("aria-expanded","true")):(e.div.style.display="none",o.innerHTML="☰",o.setAttribute("aria-expanded","false"))})),i.appendChild(s),i.appendChild(n),i.appendChild(o),i.addEventListener("contextmenu",(t=>{t.preventDefault(),this.legendMenu.populateLegendMenu(e,t)})),e.row.appendChild(i),e.div=document.createElement("div"),e.div.style.display="block",e.div.style.marginLeft="10px";for(const t of e.seriesList)this.makeSeriesRow(t,e.div);for(const t of e.subGroups){const i=document.createElement("div");i.style.display="flex",i.style.flexDirection="column",i.style.paddingLeft="5px",this.renderGroup(t,i),e.div.appendChild(i)}e.row.appendChild(e.div),t.contains(e.row)||t.appendChild(e.row),e.row.oncontextmenu=e=>{e.preventDefault()}}legendHandler(e,t=!1){this.updateGroupDisplay(e,null,t),this.updateSeriesDisplay(e,null,t)}updateSeriesDisplay(e,t,i){this._lines&&this._lines.length?this._lines.forEach((t=>{const i=e.seriesData.get(t.series)||A(t.series);if(!i)return;const s=t.seriesType||"Line",n=t.series.options().priceFormat;if("Line"===s||"Area"===s||"Histogram"===s||"Symbol"==s){const e=i;if(null==e.value)return;const s=this.legendItemFormat(e.value,n.precision);t.div.innerHTML=`\n ${t.legendSymbol[0]||"▨"} \n ${t.name}: ${s}`}else if("Bar"===s||"Candlestick"===s||"Ohlc"===s){const{open:e,close:s}=i;if(null==e||null==s)return;const o=this.legendItemFormat(e,n.precision),r=this.legendItemFormat(s,n.precision),a=s>e,l=a?t.colors[0]:t.colors[1],c=a?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${c||"▨"}\n ${t.name}: \n O ${o}, \n C ${r}`}})):console.error("No lines available to update legend.")}updateGroupDisplay(e,t,i){this._groups.forEach((t=>{this.linesEnabled?(t.row.style.display="flex",t.seriesList.forEach((t=>{const i=e.seriesData.get(t.series)||A(t.series);if(!i)return;const s=t.seriesType||"Line",n=t.name,o=t.series.options().priceFormat;if(["Bar","Candlestick","Ohlc"].includes(s)){const{open:e,close:s,high:r,low:a}=i;if(null==e||null==s||null==r||null==a)return;const l=this.legendItemFormat(e,o.precision),c=this.legendItemFormat(s,o.precision),h=s>e,p=h?t.colors[0]:t.colors[1],d=h?t.legendSymbol[0]:t.legendSymbol[1];t.div.innerHTML=`\n ${d||"▨"}\n ${n}: \n O ${l}, \n C ${c}\n `}else{const e="value"in i?i.value:void 0;if(null==e)return;const s=this.legendItemFormat(e,o.precision),r=t.colors[0],a=t.legendSymbol[0]||"▨";t.div.innerHTML=`\n ${a}\n ${n}: ${s}\n `}}))):t.row.style.display="none"}))}findGroup(e,t=this._groups){for(const i of t){if(i.name===e)return i;const t=this.findGroup(e,i.subGroups);if(t)return t}}}const L={lineColor:"#1E80F0",lineStyle:t.LineStyle.Solid,width:4};var N;!function(e){e[e.NONE=0]="NONE",e[e.HOVERING=1]="HOVERING",e[e.DRAGGING=2]="DRAGGING",e[e.DRAGGINGP1=3]="DRAGGINGP1",e[e.DRAGGINGP2=4]="DRAGGINGP2",e[e.DRAGGINGP3=5]="DRAGGINGP3",e[e.DRAGGINGP4=6]="DRAGGINGP4"}(N||(N={}));class O extends a{_paneViews=[];_options;_points=[];_state=N.NONE;_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];constructor(e){super(),this._options={...L,...e}}updateAllViews(){this._paneViews.forEach((e=>e.update()))}paneViews(){return this._paneViews}applyOptions(e){this._options={...this._options,...e},this.requestUpdate()}updatePoints(...e){for(let t=0;ti.name===e&&i.listener===t));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(e){if(this._latestHoverPoint=e.point,O._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverDrawing(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),O.hoveredObject=O.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),O.hoveredObject===this&&(O.hoveredObject=null)}}static _eventToPoint(e,t){if(!t||!e.point||!e.logical)return null;const i=t.coordinateToPrice(e.point.y);return null==i?null:{time:e.time||null,logical:e.logical,price:i.valueOf()}}static _getDiff(e,t){return{logical:e.logical-t.logical,price:e.price-t.price}}_addDiffToPoint(e,t,i){e&&(e.logical=e.logical+t,e.price=e.price+i,e.time=this.series.dataByIndex(e.logical)?.time||null)}_handleMouseDownInteraction=()=>{O._mouseIsDown=!0,this._onMouseDown()};_handleMouseUpInteraction=()=>{O._mouseIsDown=!1,this._moveToState(N.HOVERING)};_handleDragInteraction(e){if(this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1&&this._state!=N.DRAGGINGP2&&this._state!=N.DRAGGINGP3&&this._state!=N.DRAGGINGP4)return;const t=O._eventToPoint(e,this.series);if(!t)return;this._startDragPoint=this._startDragPoint||t;const i=O._getDiff(t,this._startDragPoint);this._onDrag(i),this.requestUpdate(),this._startDragPoint=t}}class V extends O{_paneViews=[];_hovered=!1;linkedObjects=[];constructor(e,t,i){super(),this.points.push(e),this.points.push(t),this._options={...L,...i}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}_mouseIsOverObjects(e){for(const t of this.linkedObjects)for(const i in t){if(i.includes("mouseIsOver")&&"function"==typeof t[i]&&t[i](e))return!0;if(i.includes("_hovered")&&"function"==typeof t[i]&&t[i]())return!0}return!1}_mouseIsOverDrawing(e){const t=this._mouseIsOverTwoPointDrawing(e),i=this._mouseIsOverObjects(e),s=t||i;return console.debug("Mouse over check",{selfResult:t,objectsResult:i,finalResult:s}),s}detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}get p1(){return this.points[0]}get p2(){return this.points[1]}get hovered(){return this._hovered}}class R extends O{_paneViews=[];_hovered=!1;linkedObjects=[];detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}constructor(e,t,i,s){super(),this.points.push(e),this.points.push(t),this.points.push(i),this._options={...L,...s}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}setThirdPoint(e){this.updatePoints(null,null,e)}get p1(){return this.points[0]}get p2(){return this.points[1]}get p3(){return this.points[2]}get hovered(){return this._hovered}}class B extends O{_paneViews=[];_hovered=!1;linkedObjects=[];detach(){this.linkedObjects.forEach((e=>{const t=e.series;t&&t.detachPrimitive(e)})),this.linkedObjects=[],super.detach()}constructor(e,t,i,s,n){super(),this.points.push(e),this.points.push(t),this.points.push(i),this.points.push(s),this._options={...L,...n}}setFirstPoint(e){this.updatePoints(e)}setSecondPoint(e){this.updatePoints(null,e)}setThirdPoint(e){this.updatePoints(null,null,e)}setFourthPoint(e){this.updatePoints(null,null,null,e)}get p1(){return this.points[0]}get p2(){return this.points[1]}get p3(){return this.points[2]}get p4(){return this.points[3]}get hovered(){return this._hovered}}class F{_chart;_series;_finishDrawingCallback=null;_drawings=[];_activeDrawing=null;_isDrawing=!1;_drawingType=null;_tempStartPoint=null;_tempSecondPoint=null;_clickCount=0;constructor(e,t,i=null){this._chart=e,this._series=t,this._finishDrawingCallback=i,this._chart.subscribeClick(this._clickHandler),this._chart.subscribeCrosshairMove(this._moveHandler)}_clickHandler=e=>this._onClick(e);_moveHandler=e=>this._onMouseMove(e);beginDrawing(e){this._drawingType=e,this._isDrawing=!0,this._tempStartPoint=null,this._tempSecondPoint=null,this._clickCount=0}stopDrawing(){this._isDrawing=!1,this._activeDrawing=null,this._tempStartPoint=null,this._tempSecondPoint=null,this._clickCount=0}get drawings(){return this._drawings}addNewDrawing(e){this._series.attachPrimitive(e),this._drawings.push(e)}delete(e){if(null==e)return;const t=this._drawings.indexOf(e);-1!=t&&(this._drawings.splice(t,1),e.detach())}clearDrawings(){for(const e of this._drawings)e.detach();this._drawings=[]}repositionOnTime(){for(const e of this.drawings){const t=[];for(const i of e.points){if(!i){t.push(i);continue}const e=i.time?this._chart.timeScale().coordinateToLogical(this._chart.timeScale().timeToCoordinate(i.time)||0):i.logical;t.push({time:i.time,logical:e,price:i.price})}e.updatePoints(...t)}}_onClick(e){if(!this._isDrawing)return;const t=O._eventToPoint(e,this._series);if(!t)return;let i;if(this._drawingType)if(i=this._drawingType.prototype instanceof B?4:this._drawingType.prototype instanceof R?3:(this._drawingType.prototype,2),3===i){if(null==this._activeDrawing)return null==this._tempStartPoint?(this._tempStartPoint=t,void(this._clickCount=1)):(this._activeDrawing=new this._drawingType(this._tempStartPoint,t,null),this._series.attachPrimitive(this._activeDrawing),this._clickCount=2,void(this._tempStartPoint=null));2===this._clickCount&&(this._activeDrawing.setThirdPoint(t),this._clickCount=3,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}else if(4===i){if(null==this._activeDrawing)return null==this._tempStartPoint?(this._tempStartPoint=t,void(this._clickCount=1)):null==this._tempSecondPoint?(this._tempSecondPoint=t,void(this._clickCount=2)):(this._activeDrawing=new this._drawingType(this._tempStartPoint,this._tempSecondPoint,t,null),this._series.attachPrimitive(this._activeDrawing),this._clickCount=3,this._tempStartPoint=null,void(this._tempSecondPoint=null));3===this._clickCount&&(this._activeDrawing.setFourthPoint(t),this._clickCount=4,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}else null==this._activeDrawing?(this._activeDrawing=new this._drawingType(t,t),this._series.attachPrimitive(this._activeDrawing),this._clickCount=1):(this._activeDrawing.setSecondPoint(t),this._clickCount=2,this._drawings.push(this._activeDrawing),this.stopDrawing(),this._finishDrawingCallback&&this._finishDrawingCallback())}_onMouseMove(e){if(!e)return;for(const t of this._drawings)t._handleHoverInteraction(e);if(!this._isDrawing||!this._activeDrawing)return;const t=O._eventToPoint(e,this._series);if(!t)return;const i=this._drawingType&&this._drawingType.prototype instanceof R;this._drawingType&&this._drawingType.prototype instanceof B?2===this._clickCount?this._activeDrawing.updatePoints(null,null,t,null):3===this._clickCount&&this._activeDrawing.updatePoints(null,null,null,t):i?2===this._clickCount&&this._activeDrawing.updatePoints(null,null,t):this._activeDrawing.setSecondPoint(t)}}class ${_options;constructor(e){this._options=e}}class G extends ${_p1;_p2;_hovered;constructor(e,t,i,s){super(i),this._p1=e,this._p2=t,this._hovered=s}_getScaledCoordinates(e){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y?null:{x1:Math.round(this._p1.x*e.horizontalPixelRatio),y1:Math.round(this._p1.y*e.verticalPixelRatio),x2:Math.round(this._p2.x*e.horizontalPixelRatio),y2:Math.round(this._p2.y*e.verticalPixelRatio)}}_drawEndCircle(e,t,i){const s="#000"===(this._options.lineColor?.toLowerCase()??"")?"#121212":this._options.lineColor;e.context.fillStyle=s,e.context.beginPath(),e.context.arc(t,i,9,0,2*Math.PI),e.context.stroke(),e.context.fill()}}class j extends ${_p1;_p2;_p3;_hovered;constructor(e,t,i,s,n){super(s),this._p1=e,this._p2=t,this._p3=i,this._hovered=n}_getScaledCoordinates(e){return null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y||null===this._p3.x||null===this._p3.y?null:{x1:Math.round(this._p1.x*e.horizontalPixelRatio),y1:Math.round(this._p1.y*e.verticalPixelRatio),x2:Math.round(this._p2.x*e.horizontalPixelRatio),y2:Math.round(this._p2.y*e.verticalPixelRatio),x3:Math.round(this._p3.x*e.horizontalPixelRatio),y3:Math.round(this._p3.y*e.verticalPixelRatio)}}_drawEndCircle(e,t,i){const s="#000"===(this._options.lineColor?.toLowerCase()??"")?"#121212":this._options.lineColor;e.context.fillStyle=s,e.context.beginPath(),e.context.arc(t,i,9,0,2*Math.PI),e.context.stroke(),e.context.fill()}}function U(e,i){const s={[t.LineStyle.Solid]:[],[t.LineStyle.Dotted]:[e.lineWidth,e.lineWidth],[t.LineStyle.Dashed]:[2*e.lineWidth,2*e.lineWidth],[t.LineStyle.LargeDashed]:[6*e.lineWidth,6*e.lineWidth],[t.LineStyle.SparseDotted]:[e.lineWidth,4*e.lineWidth]}[i];e.setLineDash(s)}class z extends G{constructor(e,t,i,s){super(e,t,i,s)}draw(e){e.useBitmapCoordinateSpace((e=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y)return;const t=e.context,i=this._getScaledCoordinates(e);i&&(t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(i.x1,i.y1),t.lineTo(i.x2,i.y2),t.stroke(),this._hovered&&(this._drawEndCircle(e,i.x1,i.y1),this._drawEndCircle(e,i.x2,i.y2)))}))}}class H{_source;constructor(e){this._source=e}}class W extends H{_p1={x:null,y:null};_p2={x:null,y:null};_source;constructor(e){super(e),this._source=e}update(){if(!this._source.p1||!this._source.p2)return;const e=this._source.series,t=e.priceToCoordinate(this._source.p1.price),i=e.priceToCoordinate(this._source.p2.price),s=this._getX(this._source.p1),n=this._getX(this._source.p2);this._p1={x:s,y:t},this._p2={x:n,y:i}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class q extends H{_p1={x:null,y:null};_p2={x:null,y:null};_p3={x:null,y:null};_source;constructor(e){super(e),this._source=e}update(){if(!this._source.p1||!this._source.p2||!this._source.p3)return;const e=this._source.series,t=e.priceToCoordinate(this._source.p1.price),i=e.priceToCoordinate(this._source.p2.price),s=e.priceToCoordinate(this._source.p3.price),n=this._getX(this._source.p1),o=this._getX(this._source.p2),r=this._getX(this._source.p3);this._p1={x:n,y:t},this._p2={x:o,y:i},this._p3={x:r,y:s}}_getX(e){return this._source.chart.timeScale().logicalToCoordinate(e.logical)}}class X extends W{constructor(e){super(e)}renderer(){return new z(this._p1,this._p2,this._source._options,this._source.hovered)}}class J extends V{_type="TrendLine";constructor(e,t,i){super(e,t,i),this._paneViews=[new X(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price)}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint;if(!e)return;const t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);Math.abs(e.x-t.x)<10&&Math.abs(e.y-t.y)<10?this._moveToState(N.DRAGGINGP1):Math.abs(e.x-i.x)<10&&Math.abs(e.y-i.y)<10?this._moveToState(N.DRAGGINGP2):this._moveToState(N.DRAGGING)}_mouseIsOverTwoPointDrawing(e,t=4){if(!e.point)return!1;const i=this._paneViews[0]._p1.x,s=this._paneViews[0]._p1.y,n=this._paneViews[0]._p2.x,o=this._paneViews[0]._p2.y;if(!(i&&n&&s&&o))return!1;const r=e.point.x,a=e.point.y;if(r<=Math.min(i,n)-t||r>=Math.max(i,n)+t)return!1;return Math.abs((o-s)*r-(n-i)*a+n*s-o*i)/Math.sqrt((o-s)**2+(n-i)**2)<=t}}class Y extends G{constructor(e,t,i,s){super(e,t,i,s)}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,i=this._getScaledCoordinates(e);if(!i)return;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.fillStyle=this._options.fillColor;const s=Math.min(i.x1,i.x2),n=Math.min(i.y1,i.y2),o=Math.abs(i.x1-i.x2),r=Math.abs(i.y1-i.y2);t.strokeRect(s,n,o,r),t.fillRect(s,n,o,r),this._hovered&&(this._drawEndCircle(e,s,n),this._drawEndCircle(e,s+o,n),this._drawEndCircle(e,s+o,n+r),this._drawEndCircle(e,s,n+r))}))}}class K extends W{constructor(e){super(e)}renderer(){return new Y(this._p1,this._p2,this._source._options,this._source.hovered)}}const Q={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.2)",...L};class Z extends V{_type="Box";constructor(e,t,i){super(e,t,i),this._options={...Q,...i},this._paneViews=[new K(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._unsubscribe("mouseup",this._handleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGINGP3:case N.DRAGGINGP4:case N.DRAGGING:document.body.style.cursor="grabbing",document.body.addEventListener("mouseup",this._handleMouseUpInteraction),this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price),this._state!=N.DRAGGING&&(this._state==N.DRAGGINGP3&&(this._addDiffToPoint(this.p1,e.logical,0),this._addDiffToPoint(this.p2,0,e.price)),this._state==N.DRAGGINGP4&&(this._addDiffToPoint(this.p1,0,e.price),this._addDiffToPoint(this.p2,e.logical,0)))}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint,t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);const s=10;Math.abs(e.x-t.x)l-d&&rc-d&&a{if(null==this._point.y)return;const t=e.context,i=Math.round(this._point.y*e.verticalPixelRatio),s=this._point.x?this._point.x*e.horizontalPixelRatio:0;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(s,i),t.lineTo(e.bitmapSize.width,i),t.stroke()}))}}class te extends H{_source;_point={x:null,y:null};constructor(e){super(e),this._source=e}update(){const e=this._source._point,t=this._source.chart.timeScale(),i=this._source.series;"RayLine"==this._source._type&&(this._point.x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical)),this._point.y=i.priceToCoordinate(e.price)}renderer(){return new ee(this._point,this._source._options)}}class ie{_source;_y=null;_price=null;constructor(e){this._source=e}update(){if(!this._source.series||!this._source._point)return;this._y=this._source.series.priceToCoordinate(this._source._point.price);const e=this._source.series.options().priceFormat.precision;this._price=this._source._point.price.toFixed(e).toString()}visible(){return!0}tickVisible(){return!0}coordinate(){return this._y??0}text(){return this._source._options.text||this._price||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class se extends O{_type="HorizontalLine";_paneViews;_point;_callbackName;_priceAxisViews;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._point.time=null,this._paneViews=[new te(this)],this._priceAxisViews=[new ie(this)],this._callbackName=i}get points(){return[this._point]}updatePoints(...e){for(const t of e)t&&(this._point.price=t.price);this.requestUpdate()}updateAllViews(){this._paneViews.forEach((e=>e.update())),this._priceAxisViews.forEach((e=>e.update()))}priceAxisViews(){return this._priceAxisViews}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._addDiffToPoint(this._point,0,e.price),this.requestUpdate()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price);return!!i&&Math.abs(i-e.point.y){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class ne extends se{_type="RayLine";constructor(e,t){super({...e},t),this._point.time=e.time}updatePoints(...e){for(const t of e)t&&(this._point=t);this.requestUpdate()}_onDrag(e){this._addDiffToPoint(this._point,e.logical,e.price),this.requestUpdate()}_mouseIsOverTwoPointDrawing(e,t=4){if(!e.point)return!1;const i=this.series.priceToCoordinate(this._point.price),s=this._point.time?this.chart.timeScale().timeToCoordinate(this._point.time):null;return!(!i||!s)&&(Math.abs(i-e.point.y)s-t)}}class oe extends ${_point={x:null,y:null};constructor(e,t){super(t),this._point=e}draw(e){e.useBitmapCoordinateSpace((e=>{if(null==this._point.x)return;const t=e.context,i=this._point.x*e.horizontalPixelRatio;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.beginPath(),t.moveTo(i,0),t.lineTo(i,e.bitmapSize.height),t.stroke()}))}}class re extends H{_source;_point={x:null,y:null};constructor(e){super(e),this._source=e}update(){const e=this._source._point,t=this._source.chart.timeScale(),i=this._source.series;this._point.x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical),this._point.y=i.priceToCoordinate(e.price)}renderer(){return new oe(this._point,this._source._options)}}class ae{_source;_x=null;constructor(e){this._source=e}update(){if(!this._source.chart||!this._source._point)return;const e=this._source._point,t=this._source.chart.timeScale();this._x=e.time?t.timeToCoordinate(e.time):t.logicalToCoordinate(e.logical)}visible(){return!!this._source._options.text}tickVisible(){return!0}coordinate(){return this._x??0}text(){return this._source._options.text||""}textColor(){return"white"}backColor(){return this._source._options.lineColor}}class le extends O{_type="VerticalLine";_paneViews;_timeAxisViews;_point;_callbackName;_startDragPoint=null;constructor(e,t,i=null){super(t),this._point=e,this._paneViews=[new re(this)],this._callbackName=i,this._timeAxisViews=[new ae(this)]}updateAllViews(){this._paneViews.forEach((e=>e.update())),this._timeAxisViews.forEach((e=>e.update()))}timeAxisViews(){return this._timeAxisViews}updatePoints(...e){for(const t of e)t&&(!t.time&&t.logical&&(t.time=this.series.dataByIndex(t.logical)?.time||null),this._point=t);this.requestUpdate()}get points(){return[this._point]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._unsubscribe("mouseup",this._childHandleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._childHandleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._addDiffToPoint(this._point,e.logical,0),this.requestUpdate()}_mouseIsOverDrawing(e,t=4){if(!e.point)return!1;const i=this.chart.timeScale();let s;return s=this._point.time?i.timeToCoordinate(this._point.time):i.logicalToCoordinate(this._point.logical),!!s&&Math.abs(s-e.point.x){this._handleMouseUpInteraction(),this._callbackName&&window.callbackFunction(`${this._callbackName}_~_${this._point.price.toFixed(8)}`)}}class ce extends j{options;variant;width;constructor(e,t,i,s,n,o){super(e,t,i,s,n),this.options=s,this.variant=s.variant??"standard",this.width=o}draw(e){e.useBitmapCoordinateSpace((e=>{if(null===this._p1.x||null===this._p1.y||null===this._p2.x||null===this._p2.y||null===this._p3.x||null===this._p3.y)return;const i=e.context,s=this._getScaledCoordinates(e);if(!s)return;const{x1:n,y1:o,x2:r,y2:a,x3:l,y3:c}=s,h=(r+l)/2,p=(a+c)/2;let d,u,m,g,f,y;const b=this.width-Math.max(this._p1.x,this._p2.x);if("inside"===this.variant){d=h,u=p;const e=(n+r)/2-l,t=(o+a)/2-c;let i=Math.atan2(t,e);Math.cos(i)<0&&(i+=Math.PI),m=d+b*Math.cos(i),g=u+b*Math.sin(i)}else{const{anchorX:e,anchorY:t}=this._computeAnchorPoint(this.variant,n,o,r,a),i=this._lineIntersection(n,o,r,a,h,p,e,t);i?[d,u]=i:(d=n,u=o);const s=h-d;m=d+b,g=u+(Math.abs(s)>1e-9?(p-u)/s:0)*b}if(f=m-d,y=g-u,i.lineWidth=this.options.width,i.strokeStyle=this.options.lineColor,U(i,this.options.lineStyle),U(i,t.LineStyle.Solid),i.beginPath(),i.moveTo(r,a),i.lineTo(l,c),i.stroke(),U(i,this.options.lineStyle),i.beginPath(),i.moveTo(n,o),i.lineTo(r,a),i.stroke(),i.beginPath(),i.moveTo(d,u),i.lineTo(m,g),i.stroke(),i.beginPath(),i.moveTo(r,a),i.lineTo(r+f,a+y),i.stroke(),i.beginPath(),i.moveTo(l,c),i.lineTo(l+f,c+y),i.stroke(),this.options.forkLines&&this.options.forkLines.length>0){const e=this.options.forkLines;for(let t=0;tMath.max(i,n,r)+t)return!1;const h=this._distanceFromSegment(i,s,n,o,l,c),p=this._distanceFromSegment(n,o,r,a,l,c),d=this._distanceFromSegment(i,s,r,a,l,c);return h<=t||p<=t||d<=t}_distanceFromSegment(e,t,i,s,n,o){const r=i-e,a=s-t,l=r*r+a*a;let c,h,p=0!==l?((n-e)*r+(o-t)*a)/l:-1;p<0?(c=e,h=t):p>1?(c=i,h=s):(c=e+p*r,h=t+p*a);const d=n-c,u=o-h;return Math.sqrt(d*d+u*u)}fromJSON(e){if(e.options){const t=e.options;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=e;this.applyOptions({[i]:t[i]})}}}toJSON(){return{options:this._options}}title="PitchFork"}class ue extends G{series;chart;constructor(e,t,i,s,n,o){super(i,s,n,o),this.series=e,this.chart=t}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,i=this._getScaledCoordinates(e);if(!i)return;t.lineWidth=this._options.width,t.strokeStyle=this._options.lineColor,U(t,this._options.lineStyle),t.fillStyle=this._options.fillColor;const s=Math.min(i.x1,i.x2),n=Math.min(i.y1,i.y2),o=Math.abs(i.x1-i.x2),r=Math.abs(i.y1-i.y2);if(t.strokeRect(s,n,o,r),t.fillRect(s,n,o,r),this._p1&&this._p2&&void 0!==this._p1.y&&void 0!==this._p2.y&&void 0!==this._p1.x&&void 0!==this._p2.x){const e=this.series.coordinateToPrice(this._p1.y),i=this.series.coordinateToPrice(this._p2.y),a=this.chart.timeScale().coordinateToTime(this._p1.x),l=this.chart.timeScale().coordinateToTime(this._p2.x),c=(i-e)/e*100;console.log(e),console.log(i);const h=`Price: ${c.toFixed(2)}%`,p=Math.abs(l-a),d=`Time: ${this._formatTimeDifference(p)}`;t.font="12px Arial",t.fillStyle="white",t.textAlign="center",t.textBaseline="middle";const u=s+o/2,m=n-10,g=n+r+10;t.fillText(h,u,m),t.fillText(d,u,g)}this._hovered&&(this._drawEndCircle(e,s,n),this._drawEndCircle(e,s+o,n),this._drawEndCircle(e,s+o,n+r),this._drawEndCircle(e,s,n+r))}))}_formatTimeDifference(e){const t=Math.floor(e),i=Math.floor(t/60),s=Math.floor(i/60),n=Math.floor(s/24);return n>0?`${n}d ${s%24}h`:s>0?`${s}h ${i%60}m`:i>0?`${i}m ${t%60}s`:`${t}s`}}class me extends W{constructor(e){super(e)}renderer(){return new ue(this._source._series,this._source._chart,this._p1,this._p2,this._source._options,this._source.hovered)}}const ge={fillEnabled:!0,fillColor:"rgba(255, 255, 255, 0.0)",lineColor:"#1E80F0",lineStyle:t.LineStyle.Solid,width:1};class fe extends V{_type="Measure";constructor(e,t,i){super(e,t,i),this._options={...ge,...i},this._paneViews=[new me(this)]}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._unsubscribe("mouseup",this._handleMouseUpInteraction),this._subscribe("mousedown",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGINGP3:case N.DRAGGINGP4:case N.DRAGGING:document.body.style.cursor="grabbing",document.body.addEventListener("mouseup",this._handleMouseUpInteraction),this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this.p1,e.logical,e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this.p2,e.logical,e.price),this._state!=N.DRAGGING&&(this._state==N.DRAGGINGP3&&(this._addDiffToPoint(this.p1,e.logical,0),this._addDiffToPoint(this.p2,0,e.price)),this._state==N.DRAGGINGP4&&(this._addDiffToPoint(this.p1,0,e.price),this._addDiffToPoint(this.p2,e.logical,0)))}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint,t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);const s=10;Math.abs(e.x-t.x)l-d&&rc-d&&ae)return!1;if((i+=t[s+1])>=e)return!0}return!1}function Me(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&Se.test(String.fromCharCode(e)):!1!==t&&Ee(e,be)))}function Pe(e,t){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&ke.test(String.fromCharCode(e)):!1!==t&&(Ee(e,be)||Ee(e,ye)))))}var Te=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function Ie(e,t){return new Te(e,{beforeExpr:!0,binop:t})}var Ae={beforeExpr:!0},De={startsExpr:!0},Le={};function Ne(e,t){return void 0===t&&(t={}),t.keyword=e,Le[e]=new Te(e,t)}var Oe={num:new Te("num",De),regexp:new Te("regexp",De),string:new Te("string",De),name:new Te("name",De),privateId:new Te("privateId",De),eof:new Te("eof"),bracketL:new Te("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new Te("]"),braceL:new Te("{",{beforeExpr:!0,startsExpr:!0}),braceR:new Te("}"),parenL:new Te("(",{beforeExpr:!0,startsExpr:!0}),parenR:new Te(")"),comma:new Te(",",Ae),semi:new Te(";",Ae),colon:new Te(":",Ae),dot:new Te("."),question:new Te("?",Ae),questionDot:new Te("?."),arrow:new Te("=>",Ae),template:new Te("template"),invalidTemplate:new Te("invalidTemplate"),ellipsis:new Te("...",Ae),backQuote:new Te("`",De),dollarBraceL:new Te("${",{beforeExpr:!0,startsExpr:!0}),eq:new Te("=",{beforeExpr:!0,isAssign:!0}),assign:new Te("_=",{beforeExpr:!0,isAssign:!0}),incDec:new Te("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new Te("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:Ie("||",1),logicalAND:Ie("&&",2),bitwiseOR:Ie("|",3),bitwiseXOR:Ie("^",4),bitwiseAND:Ie("&",5),equality:Ie("==/!=/===/!==",6),relational:Ie(">/<=/>=",7),bitShift:Ie("<>>/>>>",8),plusMin:new Te("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:Ie("%",10),star:Ie("*",10),slash:Ie("/",10),starstar:new Te("**",{beforeExpr:!0}),coalesce:Ie("??",1),_break:Ne("break"),_case:Ne("case",Ae),_catch:Ne("catch"),_continue:Ne("continue"),_debugger:Ne("debugger"),_default:Ne("default",Ae),_do:Ne("do",{isLoop:!0,beforeExpr:!0}),_else:Ne("else",Ae),_finally:Ne("finally"),_for:Ne("for",{isLoop:!0}),_function:Ne("function",De),_if:Ne("if"),_return:Ne("return",Ae),_switch:Ne("switch"),_throw:Ne("throw",Ae),_try:Ne("try"),_var:Ne("var"),_const:Ne("const"),_while:Ne("while",{isLoop:!0}),_with:Ne("with"),_new:Ne("new",{beforeExpr:!0,startsExpr:!0}),_this:Ne("this",De),_super:Ne("super",De),_class:Ne("class",De),_extends:Ne("extends",Ae),_export:Ne("export"),_import:Ne("import",De),_null:Ne("null",De),_true:Ne("true",De),_false:Ne("false",De),_in:Ne("in",{beforeExpr:!0,binop:7}),_instanceof:Ne("instanceof",{beforeExpr:!0,binop:7}),_typeof:Ne("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:Ne("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:Ne("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},Ve=/\r\n?|\n|\u2028|\u2029/,Re=new RegExp(Ve.source,"g");function Be(e){return 10===e||13===e||8232===e||8233===e}function Fe(e,t,i){void 0===i&&(i=e.length);for(var s=t;s>10),56320+(1023&e)))}var Ye=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Ke=function(e,t){this.line=e,this.column=t};Ke.prototype.offset=function(e){return new Ke(this.line,this.column+e)};var Qe=function(e,t,i){this.start=t,this.end=i,null!==e.sourceFile&&(this.source=e.sourceFile)};function Ze(e,t){for(var i=1,s=0;;){var n=Fe(e,s,t);if(n<0)return new Ke(i,t-s);++i,s=n}}var et={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},tt=!1;function it(e){var t={};for(var i in et)t[i]=e&&He(e,i)?e[i]:et[i];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!tt&&"object"==typeof console&&console.warn&&(tt=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),e&&null!=e.allowHashBang||(t.allowHashBang=t.ecmaVersion>=14),We(t.onToken)){var s=t.onToken;t.onToken=function(e){return s.push(e)}}return We(t.onComment)&&(t.onComment=function(e,t){return function(i,s,n,o,r,a){var l={type:i?"Block":"Line",value:s,start:n,end:o};e.locations&&(l.loc=new Qe(this,r,a)),e.ranges&&(l.range=[n,o]),t.push(l)}}(t,t.onComment)),t}var st=256,nt=259;function ot(e,t){return 2|(e?4:0)|(t?8:0)}var rt=function(e,t,i){this.options=e=it(e),this.sourceFile=e.sourceFile,this.keywords=Xe(we[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var s="";!0!==e.allowReserved&&(s=xe[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(s+=" await")),this.reservedWords=Xe(s);var n=(s?s+" ":"")+xe.strict;this.reservedWordsStrict=Xe(n),this.reservedWordsStrictBind=Xe(n+" "+xe.strictBind),this.input=String(t),this.containsEsc=!1,i?(this.pos=i,this.lineStart=this.input.lastIndexOf("\n",i-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(Ve).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=Oe.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule="module"===e.sourceType,this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(1),this.regexpState=null,this.privateNameStack=[]},at={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};rt.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},at.inFunction.get=function(){return(2&this.currentVarScope().flags)>0},at.inGenerator.get=function(){return(8&this.currentVarScope().flags)>0},at.inAsync.get=function(){return(4&this.currentVarScope().flags)>0},at.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(768&t)return!1;if(2&t)return(4&t)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},at.allowSuper.get=function(){return(64&this.currentThisScope().flags)>0||this.options.allowSuperOutsideMethod},at.allowDirectSuper.get=function(){return(128&this.currentThisScope().flags)>0},at.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},at.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(768&t||2&t&&!(16&t))return!0}return!1},at.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&st)>0},rt.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var i=this,s=0;s=,?^&]/.test(n)||"!"===n&&"="===this.input.charAt(s+1))}e+=t[0].length,Ge.lastIndex=e,e+=Ge.exec(this.input)[0].length,";"===this.input[e]&&e++}},lt.eat=function(e){return this.type===e&&(this.next(),!0)},lt.isContextual=function(e){return this.type===Oe.name&&this.value===e&&!this.containsEsc},lt.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},lt.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},lt.canInsertSemicolon=function(){return this.type===Oe.eof||this.type===Oe.braceR||Ve.test(this.input.slice(this.lastTokEnd,this.start))},lt.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},lt.semicolon=function(){this.eat(Oe.semi)||this.insertSemicolon()||this.unexpected()},lt.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},lt.expect=function(e){this.eat(e)||this.unexpected()},lt.unexpected=function(e){this.raise(null!=e?e:this.start,"Unexpected token")};var ht=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};lt.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var i=t?e.parenthesizedAssign:e.parenthesizedBind;i>-1&&this.raiseRecoverable(i,t?"Assigning to rvalue":"Parenthesized pattern")}},lt.checkExpressionErrors=function(e,t){if(!e)return!1;var i=e.shorthandAssign,s=e.doubleProto;if(!t)return i>=0||s>=0;i>=0&&this.raise(i,"Shorthand property assignments are valid only in destructuring patterns"),s>=0&&this.raiseRecoverable(s,"Redefinition of __proto__ property")},lt.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&s<56320)return!0;if(Me(s,!0)){for(var n=i+1;Pe(s=this.input.charCodeAt(n),!0);)++n;if(92===s||s>55295&&s<56320)return!0;var o=this.input.slice(i,n);if(!Ce.test(o))return!0}return!1},pt.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;Ge.lastIndex=this.pos;var e,t=Ge.exec(this.input),i=this.pos+t[0].length;return!(Ve.test(this.input.slice(this.pos,i))||"function"!==this.input.slice(i,i+8)||i+8!==this.input.length&&(Pe(e=this.input.charCodeAt(i+8))||e>55295&&e<56320))},pt.parseStatement=function(e,t,i){var s,n=this.type,o=this.startNode();switch(this.isLet(e)&&(n=Oe._var,s="let"),n){case Oe._break:case Oe._continue:return this.parseBreakContinueStatement(o,n.keyword);case Oe._debugger:return this.parseDebuggerStatement(o);case Oe._do:return this.parseDoStatement(o);case Oe._for:return this.parseForStatement(o);case Oe._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(o,!1,!e);case Oe._class:return e&&this.unexpected(),this.parseClass(o,!0);case Oe._if:return this.parseIfStatement(o);case Oe._return:return this.parseReturnStatement(o);case Oe._switch:return this.parseSwitchStatement(o);case Oe._throw:return this.parseThrowStatement(o);case Oe._try:return this.parseTryStatement(o);case Oe._const:case Oe._var:return s=s||this.value,e&&"var"!==s&&this.unexpected(),this.parseVarStatement(o,s);case Oe._while:return this.parseWhileStatement(o);case Oe._with:return this.parseWithStatement(o);case Oe.braceL:return this.parseBlock(!0,o);case Oe.semi:return this.parseEmptyStatement(o);case Oe._export:case Oe._import:if(this.options.ecmaVersion>10&&n===Oe._import){Ge.lastIndex=this.pos;var r=Ge.exec(this.input),a=this.pos+r[0].length,l=this.input.charCodeAt(a);if(40===l||46===l)return this.parseExpressionStatement(o,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),n===Oe._import?this.parseImport(o):this.parseExport(o,i);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(o,!0,!e);var c=this.value,h=this.parseExpression();return n===Oe.name&&"Identifier"===h.type&&this.eat(Oe.colon)?this.parseLabeledStatement(o,c,h,e):this.parseExpressionStatement(o,h)}},pt.parseBreakContinueStatement=function(e,t){var i="break"===t;this.next(),this.eat(Oe.semi)||this.insertSemicolon()?e.label=null:this.type!==Oe.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var s=0;s=6?this.eat(Oe.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},pt.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(dt),this.enterScope(0),this.expect(Oe.parenL),this.type===Oe.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var i=this.isLet();if(this.type===Oe._var||this.type===Oe._const||i){var s=this.startNode(),n=i?"let":this.value;return this.next(),this.parseVar(s,!0,n),this.finishNode(s,"VariableDeclaration"),(this.type===Oe._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===s.declarations.length?(this.options.ecmaVersion>=9&&(this.type===Oe._in?t>-1&&this.unexpected(t):e.await=t>-1),this.parseForIn(e,s)):(t>-1&&this.unexpected(t),this.parseFor(e,s))}var o=this.isContextual("let"),r=!1,a=this.containsEsc,l=new ht,c=this.start,h=t>-1?this.parseExprSubscripts(l,"await"):this.parseExpression(!0,l);return this.type===Oe._in||(r=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===Oe._in&&this.unexpected(t),e.await=!0):r&&this.options.ecmaVersion>=8&&(h.start!==c||a||"Identifier"!==h.type||"async"!==h.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),o&&r&&this.raise(h.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(h,!1,l),this.checkLValPattern(h),this.parseForIn(e,h)):(this.checkExpressionErrors(l,!0),t>-1&&this.unexpected(t),this.parseFor(e,h))},pt.parseFunctionStatement=function(e,t,i){return this.next(),this.parseFunction(e,gt|(i?0:ft),!1,t)},pt.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(Oe._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},pt.parseReturnStatement=function(e){return this.inFunction||this.options.allowReturnOutsideFunction||this.raise(this.start,"'return' outside of function"),this.next(),this.eat(Oe.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},pt.parseSwitchStatement=function(e){var t;this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(Oe.braceL),this.labels.push(ut),this.enterScope(0);for(var i=!1;this.type!==Oe.braceR;)if(this.type===Oe._case||this.type===Oe._default){var s=this.type===Oe._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),s?t.test=this.parseExpression():(i&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),i=!0,t.test=null),this.expect(Oe.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},pt.parseThrowStatement=function(e){return this.next(),Ve.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var mt=[];pt.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?32:0),this.checkLValPattern(e,t?4:2),this.expect(Oe.parenR),e},pt.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===Oe._catch){var t=this.startNode();this.next(),this.eat(Oe.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(Oe._finally)?this.parseBlock():null,e.handler||e.finalizer||this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},pt.parseVarStatement=function(e,t,i){return this.next(),this.parseVar(e,!1,t,i),this.semicolon(),this.finishNode(e,"VariableDeclaration")},pt.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(dt),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},pt.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},pt.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},pt.parseLabeledStatement=function(e,t,i,s){for(var n=0,o=this.labels;n=0;a--){var l=this.labels[a];if(l.statementStart!==e.start)break;l.statementStart=this.start,l.kind=r}return this.labels.push({name:t,kind:r,statementStart:this.start}),e.body=this.parseStatement(s?-1===s.indexOf("label")?s+"label":s:"label"),this.labels.pop(),e.label=i,this.finishNode(e,"LabeledStatement")},pt.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},pt.parseBlock=function(e,t,i){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(Oe.braceL),e&&this.enterScope(0);this.type!==Oe.braceR;){var s=this.parseStatement(null);t.body.push(s)}return i&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},pt.parseFor=function(e,t){return e.init=t,this.expect(Oe.semi),e.test=this.type===Oe.semi?null:this.parseExpression(),this.expect(Oe.semi),e.update=this.type===Oe.parenR?null:this.parseExpression(),this.expect(Oe.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},pt.parseForIn=function(e,t){var i=this.type===Oe._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!i||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(i?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=i?this.parseExpression():this.parseMaybeAssign(),this.expect(Oe.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,i?"ForInStatement":"ForOfStatement")},pt.parseVar=function(e,t,i,s){for(e.declarations=[],e.kind=i;;){var n=this.startNode();if(this.parseVarId(n,i),this.eat(Oe.eq)?n.init=this.parseMaybeAssign(t):s||"const"!==i||this.type===Oe._in||this.options.ecmaVersion>=6&&this.isContextual("of")?s||"Identifier"===n.id.type||t&&(this.type===Oe._in||this.isContextual("of"))?n.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.unexpected(),e.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(Oe.comma))break}return e},pt.parseVarId=function(e,t){e.id=this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?1:2,!1)};var gt=1,ft=2;function yt(e,t){var i=t.key.name,s=e[i],n="true";return"MethodDefinition"!==t.type||"get"!==t.kind&&"set"!==t.kind||(n=(t.static?"s":"i")+t.kind),"iget"===s&&"iset"===n||"iset"===s&&"iget"===n||"sget"===s&&"sset"===n||"sset"===s&&"sget"===n?(e[i]="true",!1):!!s||(e[i]=n,!1)}function bt(e,t){var i=e.computed,s=e.key;return!i&&("Identifier"===s.type&&s.name===t||"Literal"===s.type&&s.value===t)}pt.parseFunction=function(e,t,i,s,n){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!s)&&(this.type===Oe.star&&t&ft&&this.unexpected(),e.generator=this.eat(Oe.star)),this.options.ecmaVersion>=8&&(e.async=!!s),t>&&(e.id=4&t&&this.type!==Oe.name?null:this.parseIdent(),!e.id||t&ft||this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?1:2:3));var o=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(ot(e.async,e.generator)),t>||(e.id=this.type===Oe.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,i,!1,n),this.yieldPos=o,this.awaitPos=r,this.awaitIdentPos=a,this.finishNode(e,t>?"FunctionDeclaration":"FunctionExpression")},pt.parseFunctionParams=function(e){this.expect(Oe.parenL),e.params=this.parseBindingList(Oe.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},pt.parseClass=function(e,t){this.next();var i=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var s=this.enterClassBody(),n=this.startNode(),o=!1;for(n.body=[],this.expect(Oe.braceL);this.type!==Oe.braceR;){var r=this.parseClassElement(null!==e.superClass);r&&(n.body.push(r),"MethodDefinition"===r.type&&"constructor"===r.kind?(o&&this.raiseRecoverable(r.start,"Duplicate constructor in the same class"),o=!0):r.key&&"PrivateIdentifier"===r.key.type&&yt(s,r)&&this.raiseRecoverable(r.key.start,"Identifier '#"+r.key.name+"' has already been declared"))}return this.strict=i,this.next(),e.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},pt.parseClassElement=function(e){if(this.eat(Oe.semi))return null;var t=this.options.ecmaVersion,i=this.startNode(),s="",n=!1,o=!1,r="method",a=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(Oe.braceL))return this.parseClassStaticBlock(i),i;this.isClassElementNameStart()||this.type===Oe.star?a=!0:s="static"}if(i.static=a,!s&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==Oe.star||this.canInsertSemicolon()?s="async":o=!0),!s&&(t>=9||!o)&&this.eat(Oe.star)&&(n=!0),!s&&!o&&!n){var l=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?r=l:s=l)}if(s?(i.computed=!1,i.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),i.key.name=s,this.finishNode(i.key,"Identifier")):this.parseClassElementName(i),t<13||this.type===Oe.parenL||"method"!==r||n||o){var c=!i.static&&bt(i,"constructor"),h=c&&e;c&&"method"!==r&&this.raise(i.key.start,"Constructor can't have get/set modifier"),i.kind=c?"constructor":r,this.parseClassMethod(i,n,o,h)}else this.parseClassField(i);return i},pt.isClassElementNameStart=function(){return this.type===Oe.name||this.type===Oe.privateId||this.type===Oe.num||this.type===Oe.string||this.type===Oe.bracketL||this.type.keyword},pt.parseClassElementName=function(e){this.type===Oe.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},pt.parseClassMethod=function(e,t,i,s){var n=e.key;"constructor"===e.kind?(t&&this.raise(n.start,"Constructor can't be a generator"),i&&this.raise(n.start,"Constructor can't be an async method")):e.static&&bt(e,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var o=e.value=this.parseMethod(t,i,s);return"get"===e.kind&&0!==o.params.length&&this.raiseRecoverable(o.start,"getter should have no params"),"set"===e.kind&&1!==o.params.length&&this.raiseRecoverable(o.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===o.params[0].type&&this.raiseRecoverable(o.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},pt.parseClassField=function(e){return bt(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&bt(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(Oe.eq)?(this.enterScope(576),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,"PropertyDefinition")},pt.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(320);this.type!==Oe.braceR;){var i=this.parseStatement(null);e.body.push(i)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},pt.parseClassId=function(e,t){this.type===Oe.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,2,!1)):(!0===t&&this.unexpected(),e.id=null)},pt.parseClassSuper=function(e){e.superClass=this.eat(Oe._extends)?this.parseExprSubscripts(null,!1):null},pt.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},pt.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,i=e.used;if(this.options.checkPrivateFields)for(var s=this.privateNameStack.length,n=0===s?null:this.privateNameStack[s-1],o=0;o=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==Oe.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},pt.parseExport=function(e,t){if(this.next(),this.eat(Oe.star))return this.parseExportAllDeclaration(e,t);if(this.eat(Oe._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==Oe.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var i=0,s=e.specifiers;i=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,"ExportNamedDeclaration")},pt.parseExportDeclaration=function(e){return this.parseStatement(null)},pt.parseExportDefaultDeclaration=function(){var e;if(this.type===Oe._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,4|gt,!1,e)}if(this.type===Oe._class){var i=this.startNode();return this.parseClass(i,"nullableID")}var s=this.parseMaybeAssign();return this.semicolon(),s},pt.checkExport=function(e,t,i){e&&("string"!=typeof t&&(t="Identifier"===t.type?t.name:t.value),He(e,t)&&this.raiseRecoverable(i,"Duplicate export '"+t+"'"),e[t]=!0)},pt.checkPatternExport=function(e,t){var i=t.type;if("Identifier"===i)this.checkExport(e,t,t.start);else if("ObjectPattern"===i)for(var s=0,n=t.properties;s=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},pt.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportSpecifier")},pt.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportDefaultSpecifier")},pt.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,2),this.finishNode(e,"ImportNamespaceSpecifier")},pt.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===Oe.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(Oe.comma)))return e;if(this.type===Oe.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(Oe.braceL);!this.eat(Oe.braceR);){if(t)t=!1;else if(this.expect(Oe.comma),this.afterTrailingComma(Oe.braceR))break;e.push(this.parseImportSpecifier())}return e},pt.parseWithClause=function(){var e=[];if(!this.eat(Oe._with))return e;this.expect(Oe.braceL);for(var t={},i=!0;!this.eat(Oe.braceR);){if(i)i=!1;else if(this.expect(Oe.comma),this.afterTrailingComma(Oe.braceR))break;var s=this.parseImportAttribute(),n="Identifier"===s.key.type?s.key.name:s.key.value;He(t,n)&&this.raiseRecoverable(s.key.start,"Duplicate attribute key '"+n+"'"),t[n]=!0,e.push(s)}return e},pt.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===Oe.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(Oe.colon),this.type!==Oe.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},pt.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===Oe.string){var e=this.parseLiteral(this.value);return Ye.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},pt.adaptDirectivePrologue=function(e){for(var t=0;t=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var vt=rt.prototype;vt.toAssignable=function(e,t,i){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",i&&this.checkPatternErrors(i,!0);for(var s=0,n=e.properties;s=6)switch(this.type){case Oe.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(Oe.bracketR,!0,!0),this.finishNode(e,"ArrayPattern");case Oe.braceL:return this.parseObj(!0)}return this.parseIdent()},vt.parseBindingList=function(e,t,i,s){for(var n=[],o=!0;!this.eat(e);)if(o?o=!1:this.expect(Oe.comma),t&&this.type===Oe.comma)n.push(null);else{if(i&&this.afterTrailingComma(e))break;if(this.type===Oe.ellipsis){var r=this.parseRestBinding();this.parseBindingListItem(r),n.push(r),this.type===Oe.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(e);break}n.push(this.parseAssignableListItem(s))}return n},vt.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},vt.parseBindingListItem=function(e){return e},vt.parseMaybeDefault=function(e,t,i){if(i=i||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(Oe.eq))return i;var s=this.startNodeAt(e,t);return s.left=i,s.right=this.parseMaybeAssign(),this.finishNode(s,"AssignmentPattern")},vt.checkLValSimple=function(e,t,i){void 0===t&&(t=0);var s=0!==t;switch(e.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(e.name)&&this.raiseRecoverable(e.start,(s?"Binding ":"Assigning to ")+e.name+" in strict mode"),s&&(2===t&&"let"===e.name&&this.raiseRecoverable(e.start,"let is disallowed as a lexically bound name"),i&&(He(i,e.name)&&this.raiseRecoverable(e.start,"Argument name clash"),i[e.name]=!0),5!==t&&this.declareName(e.name,t,e.start));break;case"ChainExpression":this.raiseRecoverable(e.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":s&&this.raiseRecoverable(e.start,"Binding member expression");break;case"ParenthesizedExpression":return s&&this.raiseRecoverable(e.start,"Binding parenthesized expression"),this.checkLValSimple(e.expression,t,i);default:this.raise(e.start,(s?"Binding":"Assigning to")+" rvalue")}},vt.checkLValPattern=function(e,t,i){switch(void 0===t&&(t=0),e.type){case"ObjectPattern":for(var s=0,n=e.properties;s=1;e--){var t=this.context[e];if("function"===t.token)return t.generator}return!1},wt.updateContext=function(e){var t,i=this.type;i.keyword&&e===Oe.dot?this.exprAllowed=!1:(t=i.updateContext)?t.call(this,e):this.exprAllowed=i.beforeExpr},wt.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},Oe.parenR.updateContext=Oe.braceR.updateContext=function(){if(1!==this.context.length){var e=this.context.pop();e===_t.b_stat&&"function"===this.curContext().token&&(e=this.context.pop()),this.exprAllowed=!e.isExpr}else this.exprAllowed=!0},Oe.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?_t.b_stat:_t.b_expr),this.exprAllowed=!0},Oe.dollarBraceL.updateContext=function(){this.context.push(_t.b_tmpl),this.exprAllowed=!0},Oe.parenL.updateContext=function(e){var t=e===Oe._if||e===Oe._for||e===Oe._with||e===Oe._while;this.context.push(t?_t.p_stat:_t.p_expr),this.exprAllowed=!0},Oe.incDec.updateContext=function(){},Oe._function.updateContext=Oe._class.updateContext=function(e){!e.beforeExpr||e===Oe._else||e===Oe.semi&&this.curContext()!==_t.p_stat||e===Oe._return&&Ve.test(this.input.slice(this.lastTokEnd,this.start))||(e===Oe.colon||e===Oe.braceL)&&this.curContext()===_t.b_stat?this.context.push(_t.f_stat):this.context.push(_t.f_expr),this.exprAllowed=!1},Oe.colon.updateContext=function(){"function"===this.curContext().token&&this.context.pop(),this.exprAllowed=!0},Oe.backQuote.updateContext=function(){this.curContext()===_t.q_tmpl?this.context.pop():this.context.push(_t.q_tmpl),this.exprAllowed=!1},Oe.star.updateContext=function(e){if(e===Oe._function){var t=this.context.length-1;this.context[t]===_t.f_expr?this.context[t]=_t.f_expr_gen:this.context[t]=_t.f_gen}this.exprAllowed=!0},Oe.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==Oe.dot&&("of"===this.value&&!this.exprAllowed||"yield"===this.value&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var Ct=rt.prototype;function St(e){return"Identifier"===e.type||"ParenthesizedExpression"===e.type&&St(e.expression)}function kt(e){return"MemberExpression"===e.type&&"PrivateIdentifier"===e.property.type||"ChainExpression"===e.type&&kt(e.expression)||"ParenthesizedExpression"===e.type&&kt(e.expression)}Ct.checkPropClash=function(e,t,i){if(!(this.options.ecmaVersion>=9&&"SpreadElement"===e.type||this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var s,n=e.key;switch(n.type){case"Identifier":s=n.name;break;case"Literal":s=String(n.value);break;default:return}var o=e.kind;if(this.options.ecmaVersion>=6)"__proto__"===s&&"init"===o&&(t.proto&&(i?i.doubleProto<0&&(i.doubleProto=n.start):this.raiseRecoverable(n.start,"Redefinition of __proto__ property")),t.proto=!0);else{var r=t[s="$"+s];if(r)("init"===o?this.strict&&r.init||r.get||r.set:r.init||r[o])&&this.raiseRecoverable(n.start,"Redefinition of property");else r=t[s]={init:!1,get:!1,set:!1};r[o]=!0}}},Ct.parseExpression=function(e,t){var i=this.start,s=this.startLoc,n=this.parseMaybeAssign(e,t);if(this.type===Oe.comma){var o=this.startNodeAt(i,s);for(o.expressions=[n];this.eat(Oe.comma);)o.expressions.push(this.parseMaybeAssign(e,t));return this.finishNode(o,"SequenceExpression")}return n},Ct.parseMaybeAssign=function(e,t,i){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var s=!1,n=-1,o=-1,r=-1;t?(n=t.parenthesizedAssign,o=t.trailingComma,r=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new ht,s=!0);var a=this.start,l=this.startLoc;this.type!==Oe.parenL&&this.type!==Oe.name||(this.potentialArrowAt=this.start,this.potentialArrowInForAwait="await"===e);var c=this.parseMaybeConditional(e,t);if(i&&(c=i.call(this,c,a,l)),this.type.isAssign){var h=this.startNodeAt(a,l);return h.operator=this.value,this.type===Oe.eq&&(c=this.toAssignable(c,!1,t)),s||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=c.start&&(t.shorthandAssign=-1),this.type===Oe.eq?this.checkLValPattern(c):this.checkLValSimple(c),h.left=c,this.next(),h.right=this.parseMaybeAssign(e),r>-1&&(t.doubleProto=r),this.finishNode(h,"AssignmentExpression")}return s&&this.checkExpressionErrors(t,!0),n>-1&&(t.parenthesizedAssign=n),o>-1&&(t.trailingComma=o),c},Ct.parseMaybeConditional=function(e,t){var i=this.start,s=this.startLoc,n=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return n;if(this.eat(Oe.question)){var o=this.startNodeAt(i,s);return o.test=n,o.consequent=this.parseMaybeAssign(),this.expect(Oe.colon),o.alternate=this.parseMaybeAssign(e),this.finishNode(o,"ConditionalExpression")}return n},Ct.parseExprOps=function(e,t){var i=this.start,s=this.startLoc,n=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||n.start===i&&"ArrowFunctionExpression"===n.type?n:this.parseExprOp(n,i,s,-1,e)},Ct.parseExprOp=function(e,t,i,s,n){var o=this.type.binop;if(null!=o&&(!n||this.type!==Oe._in)&&o>s){var r=this.type===Oe.logicalOR||this.type===Oe.logicalAND,a=this.type===Oe.coalesce;a&&(o=Oe.logicalAND.binop);var l=this.value;this.next();var c=this.start,h=this.startLoc,p=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,n),c,h,o,n),d=this.buildBinary(t,i,e,p,l,r||a);return(r&&this.type===Oe.coalesce||a&&(this.type===Oe.logicalOR||this.type===Oe.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(d,t,i,s,n)}return e},Ct.buildBinary=function(e,t,i,s,n,o){"PrivateIdentifier"===s.type&&this.raise(s.start,"Private identifier can only be left side of binary expression");var r=this.startNodeAt(e,t);return r.left=i,r.operator=n,r.right=s,this.finishNode(r,o?"LogicalExpression":"BinaryExpression")},Ct.parseMaybeUnary=function(e,t,i,s){var n,o=this.start,r=this.startLoc;if(this.isContextual("await")&&this.canAwait)n=this.parseAwait(s),t=!0;else if(this.type.prefix){var a=this.startNode(),l=this.type===Oe.incDec;a.operator=this.value,a.prefix=!0,this.next(),a.argument=this.parseMaybeUnary(null,!0,l,s),this.checkExpressionErrors(e,!0),l?this.checkLValSimple(a.argument):this.strict&&"delete"===a.operator&&St(a.argument)?this.raiseRecoverable(a.start,"Deleting local variable in strict mode"):"delete"===a.operator&&kt(a.argument)?this.raiseRecoverable(a.start,"Private fields can not be deleted"):t=!0,n=this.finishNode(a,l?"UpdateExpression":"UnaryExpression")}else if(t||this.type!==Oe.privateId){if(n=this.parseExprSubscripts(e,s),this.checkExpressionErrors(e))return n;for(;this.type.postfix&&!this.canInsertSemicolon();){var c=this.startNodeAt(o,r);c.operator=this.value,c.prefix=!1,c.argument=n,this.checkLValSimple(n),this.next(),n=this.finishNode(c,"UpdateExpression")}}else(s||0===this.privateNameStack.length)&&this.options.checkPrivateFields&&this.unexpected(),n=this.parsePrivateIdent(),this.type!==Oe._in&&this.unexpected();return i||!this.eat(Oe.starstar)?n:t?void this.unexpected(this.lastTokStart):this.buildBinary(o,r,n,this.parseMaybeUnary(null,!1,!1,s),"**",!1)},Ct.parseExprSubscripts=function(e,t){var i=this.start,s=this.startLoc,n=this.parseExprAtom(e,t);if("ArrowFunctionExpression"===n.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd))return n;var o=this.parseSubscripts(n,i,s,!1,t);return e&&"MemberExpression"===o.type&&(e.parenthesizedAssign>=o.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=o.start&&(e.parenthesizedBind=-1),e.trailingComma>=o.start&&(e.trailingComma=-1)),o},Ct.parseSubscripts=function(e,t,i,s,n){for(var o=this.options.ecmaVersion>=8&&"Identifier"===e.type&&"async"===e.name&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start==5&&this.potentialArrowAt===e.start,r=!1;;){var a=this.parseSubscript(e,t,i,s,o,r,n);if(a.optional&&(r=!0),a===e||"ArrowFunctionExpression"===a.type){if(r){var l=this.startNodeAt(t,i);l.expression=a,a=this.finishNode(l,"ChainExpression")}return a}e=a}},Ct.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(Oe.arrow)},Ct.parseSubscriptAsyncArrow=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,!0,s)},Ct.parseSubscript=function(e,t,i,s,n,o,r){var a=this.options.ecmaVersion>=11,l=a&&this.eat(Oe.questionDot);s&&l&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var c=this.eat(Oe.bracketL);if(c||l&&this.type!==Oe.parenL&&this.type!==Oe.backQuote||this.eat(Oe.dot)){var h=this.startNodeAt(t,i);h.object=e,c?(h.property=this.parseExpression(),this.expect(Oe.bracketR)):this.type===Oe.privateId&&"Super"!==e.type?h.property=this.parsePrivateIdent():h.property=this.parseIdent("never"!==this.options.allowReserved),h.computed=!!c,a&&(h.optional=l),e=this.finishNode(h,"MemberExpression")}else if(!s&&this.eat(Oe.parenL)){var p=new ht,d=this.yieldPos,u=this.awaitPos,m=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var g=this.parseExprList(Oe.parenR,this.options.ecmaVersion>=8,!1,p);if(n&&!l&&this.shouldParseAsyncArrow())return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=d,this.awaitPos=u,this.awaitIdentPos=m,this.parseSubscriptAsyncArrow(t,i,g,r);this.checkExpressionErrors(p,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=u||this.awaitPos,this.awaitIdentPos=m||this.awaitIdentPos;var f=this.startNodeAt(t,i);f.callee=e,f.arguments=g,a&&(f.optional=l),e=this.finishNode(f,"CallExpression")}else if(this.type===Oe.backQuote){(l||o)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var y=this.startNodeAt(t,i);y.tag=e,y.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(y,"TaggedTemplateExpression")}return e},Ct.parseExprAtom=function(e,t,i){this.type===Oe.slash&&this.readRegexp();var s,n=this.potentialArrowAt===this.start;switch(this.type){case Oe._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),s=this.startNode(),this.next(),this.type!==Oe.parenL||this.allowDirectSuper||this.raise(s.start,"super() call outside constructor of a subclass"),this.type!==Oe.dot&&this.type!==Oe.bracketL&&this.type!==Oe.parenL&&this.unexpected(),this.finishNode(s,"Super");case Oe._this:return s=this.startNode(),this.next(),this.finishNode(s,"ThisExpression");case Oe.name:var o=this.start,r=this.startLoc,a=this.containsEsc,l=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!a&&"async"===l.name&&!this.canInsertSemicolon()&&this.eat(Oe._function))return this.overrideContext(_t.f_expr),this.parseFunction(this.startNodeAt(o,r),0,!1,!0,t);if(n&&!this.canInsertSemicolon()){if(this.eat(Oe.arrow))return this.parseArrowExpression(this.startNodeAt(o,r),[l],!1,t);if(this.options.ecmaVersion>=8&&"async"===l.name&&this.type===Oe.name&&!a&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return l=this.parseIdent(!1),!this.canInsertSemicolon()&&this.eat(Oe.arrow)||this.unexpected(),this.parseArrowExpression(this.startNodeAt(o,r),[l],!0,t)}return l;case Oe.regexp:var c=this.value;return(s=this.parseLiteral(c.value)).regex={pattern:c.pattern,flags:c.flags},s;case Oe.num:case Oe.string:return this.parseLiteral(this.value);case Oe._null:case Oe._true:case Oe._false:return(s=this.startNode()).value=this.type===Oe._null?null:this.type===Oe._true,s.raw=this.type.keyword,this.next(),this.finishNode(s,"Literal");case Oe.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(n,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),p;case Oe.bracketL:return s=this.startNode(),this.next(),s.elements=this.parseExprList(Oe.bracketR,!0,!0,e),this.finishNode(s,"ArrayExpression");case Oe.braceL:return this.overrideContext(_t.b_expr),this.parseObj(!1,e);case Oe._function:return s=this.startNode(),this.next(),this.parseFunction(s,0);case Oe._class:return this.parseClass(this.startNode(),!1);case Oe._new:return this.parseNew();case Oe.backQuote:return this.parseTemplate();case Oe._import:return this.options.ecmaVersion>=11?this.parseExprImport(i):this.unexpected();default:return this.parseExprAtomDefault()}},Ct.parseExprAtomDefault=function(){this.unexpected()},Ct.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===Oe.parenL&&!e)return this.parseDynamicImport(t);if(this.type===Oe.dot){var i=this.startNodeAt(t.start,t.loc&&t.loc.start);return i.name="import",t.meta=this.finishNode(i,"Identifier"),this.parseImportMeta(t)}this.unexpected()},Ct.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(Oe.parenR)?e.options=null:(this.expect(Oe.comma),this.afterTrailingComma(Oe.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(Oe.parenR)||(this.expect(Oe.comma),this.afterTrailingComma(Oe.parenR)||this.unexpected())));else if(!this.eat(Oe.parenR)){var t=this.start;this.eat(Oe.comma)&&this.eat(Oe.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},Ct.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"===this.options.sourceType||this.options.allowImportExportEverywhere||this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},Ct.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},Ct.parseParenExpression=function(){this.expect(Oe.parenL);var e=this.parseExpression();return this.expect(Oe.parenR),e},Ct.shouldParseArrow=function(e){return!this.canInsertSemicolon()},Ct.parseParenAndDistinguishExpression=function(e,t){var i,s=this.start,n=this.startLoc,o=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var r,a=this.start,l=this.startLoc,c=[],h=!0,p=!1,d=new ht,u=this.yieldPos,m=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==Oe.parenR;){if(h?h=!1:this.expect(Oe.comma),o&&this.afterTrailingComma(Oe.parenR,!0)){p=!0;break}if(this.type===Oe.ellipsis){r=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===Oe.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}c.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var g=this.lastTokEnd,f=this.lastTokEndLoc;if(this.expect(Oe.parenR),e&&this.shouldParseArrow(c)&&this.eat(Oe.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=u,this.awaitPos=m,this.parseParenArrowList(s,n,c,t);c.length&&!p||this.unexpected(this.lastTokStart),r&&this.unexpected(r),this.checkExpressionErrors(d,!0),this.yieldPos=u||this.yieldPos,this.awaitPos=m||this.awaitPos,c.length>1?((i=this.startNodeAt(a,l)).expressions=c,this.finishNodeAt(i,"SequenceExpression",g,f)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var y=this.startNodeAt(s,n);return y.expression=i,this.finishNode(y,"ParenthesizedExpression")}return i},Ct.parseParenItem=function(e){return e},Ct.parseParenArrowList=function(e,t,i,s){return this.parseArrowExpression(this.startNodeAt(e,t),i,!1,s)};var Et=[];Ct.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===Oe.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var i=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),i&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var s=this.start,n=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),s,n,!0,!1),this.eat(Oe.parenL)?e.arguments=this.parseExprList(Oe.parenR,this.options.ecmaVersion>=8,!1):e.arguments=Et,this.finishNode(e,"NewExpression")},Ct.parseTemplateElement=function(e){var t=e.isTagged,i=this.startNode();return this.type===Oe.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),i.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):i.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),i.tail=this.type===Oe.backQuote,this.finishNode(i,"TemplateElement")},Ct.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var i=this.startNode();this.next(),i.expressions=[];var s=this.parseTemplateElement({isTagged:t});for(i.quasis=[s];!s.tail;)this.type===Oe.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(Oe.dollarBraceL),i.expressions.push(this.parseExpression()),this.expect(Oe.braceR),i.quasis.push(s=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(i,"TemplateLiteral")},Ct.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(this.type===Oe.name||this.type===Oe.num||this.type===Oe.string||this.type===Oe.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===Oe.star)&&!Ve.test(this.input.slice(this.lastTokEnd,this.start))},Ct.parseObj=function(e,t){var i=this.startNode(),s=!0,n={};for(i.properties=[],this.next();!this.eat(Oe.braceR);){if(s)s=!1;else if(this.expect(Oe.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(Oe.braceR))break;var o=this.parseProperty(e,t);e||this.checkPropClash(o,n,t),i.properties.push(o)}return this.finishNode(i,e?"ObjectPattern":"ObjectExpression")},Ct.parseProperty=function(e,t){var i,s,n,o,r=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(Oe.ellipsis))return e?(r.argument=this.parseIdent(!1),this.type===Oe.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(r,"RestElement")):(r.argument=this.parseMaybeAssign(!1,t),this.type===Oe.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(r,"SpreadElement"));this.options.ecmaVersion>=6&&(r.method=!1,r.shorthand=!1,(e||t)&&(n=this.start,o=this.startLoc),e||(i=this.eat(Oe.star)));var a=this.containsEsc;return this.parsePropertyName(r),!e&&!a&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(r)?(s=!0,i=this.options.ecmaVersion>=9&&this.eat(Oe.star),this.parsePropertyName(r)):s=!1,this.parsePropertyValue(r,e,i,s,n,o,t,a),this.finishNode(r,"Property")},Ct.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var i="get"===e.kind?0:1;if(e.value.params.length!==i){var s=e.value.start;"get"===e.kind?this.raiseRecoverable(s,"getter should have no params"):this.raiseRecoverable(s,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},Ct.parsePropertyValue=function(e,t,i,s,n,o,r,a){(i||s)&&this.type===Oe.colon&&this.unexpected(),this.eat(Oe.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,r),e.kind="init"):this.options.ecmaVersion>=6&&this.type===Oe.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(i,s),e.kind="init"):t||a||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===Oe.comma||this.type===Oe.braceR||this.type===Oe.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((i||s)&&this.unexpected(),this.checkUnreserved(e.key),"await"!==e.key.name||this.awaitIdentPos||(this.awaitIdentPos=n),t?e.value=this.parseMaybeDefault(n,o,this.copyNode(e.key)):this.type===Oe.eq&&r?(r.shorthandAssign<0&&(r.shorthandAssign=this.start),e.value=this.parseMaybeDefault(n,o,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind="init",e.shorthand=!0):this.unexpected():((i||s)&&this.unexpected(),this.parseGetterSetter(e))},Ct.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(Oe.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(Oe.bracketR),e.key;e.computed=!1}return e.key=this.type===Oe.num||this.type===Oe.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},Ct.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},Ct.parseMethod=function(e,t,i){var s=this.startNode(),n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.initFunction(s),this.options.ecmaVersion>=6&&(s.generator=e),this.options.ecmaVersion>=8&&(s.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(64|ot(t,s.generator)|(i?128:0)),this.expect(Oe.parenL),s.params=this.parseBindingList(Oe.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(s,!1,!0,!1),this.yieldPos=n,this.awaitPos=o,this.awaitIdentPos=r,this.finishNode(s,"FunctionExpression")},Ct.parseArrowExpression=function(e,t,i,s){var n=this.yieldPos,o=this.awaitPos,r=this.awaitIdentPos;return this.enterScope(16|ot(i,!1)),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!i),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,s),this.yieldPos=n,this.awaitPos=o,this.awaitIdentPos=r,this.finishNode(e,"ArrowFunctionExpression")},Ct.parseFunctionBody=function(e,t,i,s){var n=t&&this.type!==Oe.braceL,o=this.strict,r=!1;if(n)e.body=this.parseMaybeAssign(s),e.expression=!0,this.checkParams(e,!1);else{var a=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);o&&!a||(r=this.strictDirective(this.end))&&a&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list");var l=this.labels;this.labels=[],r&&(this.strict=!0),this.checkParams(e,!o&&!r&&!t&&!i&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,5),e.body=this.parseBlock(!1,void 0,r&&!o),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=l}this.exitScope()},Ct.isSimpleParamList=function(e){for(var t=0,i=e;t-1||n.functions.indexOf(e)>-1||n.var.indexOf(e)>-1,n.lexical.push(e),this.inModule&&1&n.flags&&delete this.undefinedExports[e]}else if(4===t){this.currentScope().lexical.push(e)}else if(3===t){var o=this.currentScope();s=this.treatFunctionsAsVar?o.lexical.indexOf(e)>-1:o.lexical.indexOf(e)>-1||o.var.indexOf(e)>-1,o.functions.push(e)}else for(var r=this.scopeStack.length-1;r>=0;--r){var a=this.scopeStack[r];if(a.lexical.indexOf(e)>-1&&!(32&a.flags&&a.lexical[0]===e)||!this.treatFunctionsAsVarInScope(a)&&a.functions.indexOf(e)>-1){s=!0;break}if(a.var.push(e),this.inModule&&1&a.flags&&delete this.undefinedExports[e],a.flags&nt)break}s&&this.raiseRecoverable(i,"Identifier '"+e+"' has already been declared")},Pt.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},Pt.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},Pt.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(771&t.flags)return t}},Pt.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(771&t.flags&&!(16&t.flags))return t}};var It=function(e,t,i){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new Qe(e,i)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},At=rt.prototype;function Dt(e,t,i,s){return e.type=t,e.end=i,this.options.locations&&(e.loc.end=s),this.options.ranges&&(e.range[1]=i),e}At.startNode=function(){return new It(this,this.start,this.startLoc)},At.startNodeAt=function(e,t){return new It(this,e,t)},At.finishNode=function(e,t){return Dt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},At.finishNodeAt=function(e,t,i,s){return Dt.call(this,e,t,i,s)},At.copyNode=function(e){var t=new It(this,e.start,this.startLoc);for(var i in e)t[i]=e[i];return t};var Lt="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",Nt=Lt+" Extended_Pictographic",Ot=Nt+" EBase EComp EMod EPres ExtPict",Vt={9:Lt,10:Nt,11:Nt,12:Ot,13:Ot,14:Ot},Rt={9:"",10:"",11:"",12:"",13:"",14:"Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji"},Bt="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",Ft="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",$t=Ft+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",Gt=$t+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",jt=Gt+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Ut=jt+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",zt={9:Ft,10:$t,11:Gt,12:jt,13:Ut,14:Ut+" Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz"},Ht={};function Wt(e){var t=Ht[e]={binary:Xe(Vt[e]+" "+Bt),binaryOfStrings:Xe(Rt[e]),nonBinary:{General_Category:Xe(Bt),Script:Xe(zt[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var qt=0,Xt=[9,10,11,12,13,14];qt=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=Ht[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};function Qt(e){return 105===e||109===e||115===e}function Zt(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function ei(e){return e>=65&&e<=90||e>=97&&e<=122}Kt.prototype.reset=function(e,t,i){var s=-1!==i.indexOf("v"),n=-1!==i.indexOf("u");this.start=0|e,this.source=t+"",this.flags=i,s&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=n&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=n&&this.parser.options.ecmaVersion>=9)},Kt.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},Kt.prototype.at=function(e,t){void 0===t&&(t=!1);var i=this.source,s=i.length;if(e>=s)return-1;var n=i.charCodeAt(e);if(!t&&!this.switchU||n<=55295||n>=57344||e+1>=s)return n;var o=i.charCodeAt(e+1);return o>=56320&&o<=57343?(n<<10)+o-56613888:n},Kt.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var i=this.source,s=i.length;if(e>=s)return s;var n,o=i.charCodeAt(e);return!t&&!this.switchU||o<=55295||o>=57344||e+1>=s||(n=i.charCodeAt(e+1))<56320||n>57343?e+1:e+2},Kt.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},Kt.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Kt.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Kt.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Kt.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var i=this.pos,s=0,n=e;s-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===r&&(s=!0),"v"===r&&(n=!0)}this.options.ecmaVersion>=15&&s&&n&&this.raise(e.start,"Invalid regular expression flag")},Jt.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&function(e){for(var t in e)return!0;return!1}(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Jt.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,i=e.backReferenceNames;t=16;for(t&&(e.branchID=new Yt(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},Jt.regexp_alternative=function(e){for(;e.pos=9&&(i=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!i,!0}return e.pos=t,!1},Jt.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},Jt.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Jt.regexp_eatBracedQuantifier=function(e,t){var i=e.pos;if(e.eat(123)){var s=0,n=-1;if(this.regexp_eatDecimalDigits(e)&&(s=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue),e.eat(125)))return-1!==n&&n=16){var i=this.regexp_eatModifiers(e),s=e.eat(45);if(i||s){for(var n=0;n-1&&e.raise("Duplicate regular expression modifiers")}if(s){var r=this.regexp_eatModifiers(e);i||r||58!==e.current()||e.raise("Invalid regular expression modifiers");for(var a=0;a-1||i.indexOf(l)>-1)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},Jt.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},Jt.regexp_eatModifiers=function(e){for(var t="",i=0;-1!==(i=e.current())&&Qt(i);)t+=Je(i),e.advance();return t},Jt.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Jt.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},Jt.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!Zt(t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatPatternCharacters=function(e){for(var t=e.pos,i=0;-1!==(i=e.current())&&!Zt(i);)e.advance();return e.pos!==t},Jt.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t)&&(e.advance(),!0)},Jt.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,i=e.groupNames[e.lastStringValue];if(i)if(t)for(var s=0,n=i;s=11,s=e.current(i);return e.advance(i),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)&&(s=e.lastIntValue),function(e){return Me(e,!0)||36===e||95===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Jt.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,i=this.options.ecmaVersion>=11,s=e.current(i);return e.advance(i),92===s&&this.regexp_eatRegExpUnicodeEscapeSequence(e,i)&&(s=e.lastIntValue),function(e){return Pe(e,!0)||36===e||95===e||8204===e||8205===e}(s)?(e.lastIntValue=s,!0):(e.pos=t,!1)},Jt.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},Jt.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var i=e.lastIntValue;if(e.switchU)return i>e.maxBackReference&&(e.maxBackReference=i),!0;if(i<=e.numCapturingParens)return!0;e.pos=t}return!1},Jt.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},Jt.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Jt.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Jt.regexp_eatZero=function(e){return 48===e.current()&&!si(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Jt.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},Jt.regexp_eatControlLetter=function(e){var t=e.current();return!!ei(t)&&(e.lastIntValue=t%32,e.advance(),!0)},Jt.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var i,s=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(n&&o>=55296&&o<=56319){var r=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var a=e.lastIntValue;if(a>=56320&&a<=57343)return e.lastIntValue=1024*(o-55296)+(a-56320)+65536,!0}e.pos=r,e.lastIntValue=o}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&((i=e.lastIntValue)>=0&&i<=1114111))return!0;n&&e.raise("Invalid unicode escape"),e.pos=s}return!1},Jt.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1};function ti(e){return ei(e)||95===e}function ii(e){return ti(e)||si(e)}function si(e){return e>=48&&e<=57}function ni(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function oi(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function ri(e){return e>=48&&e<=55}Jt.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(function(e){return 100===e||68===e||115===e||83===e||119===e||87===e}(t))return e.lastIntValue=-1,e.advance(),1;var i=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((i=80===t)||112===t)){var s;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(s=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return i&&2===s&&e.raise("Invalid property name"),s;e.raise("Invalid property name")}return 0},Jt.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var i=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var s=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,i,s),1}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,n)}return 0},Jt.regexp_validateUnicodePropertyNameAndValue=function(e,t,i){He(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(i)||e.raise("Invalid property value")},Jt.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?1:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?2:void e.raise("Invalid property name")},Jt.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";ti(t=e.current());)e.lastStringValue+=Je(t),e.advance();return""!==e.lastStringValue},Jt.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";ii(t=e.current());)e.lastStringValue+=Je(t),e.advance();return""!==e.lastStringValue},Jt.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Jt.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),i=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&2===i&&e.raise("Negated character class may contain strings"),!0}return!1},Jt.regexp_classContents=function(e){return 93===e.current()?1:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),1)},Jt.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var i=e.lastIntValue;!e.switchU||-1!==t&&-1!==i||e.raise("Invalid character class"),-1!==t&&-1!==i&&t>i&&e.raise("Range out of order in character class")}}},Jt.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var i=e.current();(99===i||ri(i))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var s=e.current();return 93!==s&&(e.lastIntValue=s,e.advance(),!0)},Jt.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Jt.regexp_classSetExpression=function(e){var t,i=1;if(this.regexp_eatClassSetRange(e));else if(t=this.regexp_eatClassSetOperand(e)){2===t&&(i=2);for(var s=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?2!==t&&(i=1):e.raise("Invalid character in character class");if(s!==e.pos)return i;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(s!==e.pos)return i}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return i;2===t&&(i=2)}},Jt.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var i=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;return-1!==i&&-1!==s&&i>s&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},Jt.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?1:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Jt.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var i=e.eat(94),s=this.regexp_classContents(e);if(e.eat(93))return i&&2===s&&e.raise("Negated character class may contain strings"),s;e.pos=t}if(e.eat(92)){var n=this.regexp_eatCharacterClassEscape(e);if(n)return n;e.pos=t}return null},Jt.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var i=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return i}else e.raise("Invalid escape");e.pos=t}return null},Jt.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)2===this.regexp_classString(e)&&(t=2);return t},Jt.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?1:2},Jt.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e))||(e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1));var i=e.current();return!(i<0||i===e.lookahead()&&function(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}(i))&&(!function(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}(i)&&(e.advance(),e.lastIntValue=i,!0))},Jt.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!function(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}(t)&&(e.lastIntValue=t,e.advance(),!0)},Jt.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!si(t)&&95!==t)&&(e.lastIntValue=t%32,e.advance(),!0)},Jt.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},Jt.regexp_eatDecimalDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;si(i=e.current());)e.lastIntValue=10*e.lastIntValue+(i-48),e.advance();return e.pos!==t},Jt.regexp_eatHexDigits=function(e){var t=e.pos,i=0;for(e.lastIntValue=0;ni(i=e.current());)e.lastIntValue=16*e.lastIntValue+oi(i),e.advance();return e.pos!==t},Jt.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var i=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*i+e.lastIntValue:e.lastIntValue=8*t+i}else e.lastIntValue=t;return!0}return!1},Jt.regexp_eatOctalDigit=function(e){var t=e.current();return ri(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},Jt.regexp_eatFixedHexDigits=function(e,t){var i=e.pos;e.lastIntValue=0;for(var s=0;s=this.input.length?this.finishToken(Oe.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},li.readToken=function(e){return Me(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},li.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},li.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,i=this.input.indexOf("*/",this.pos+=2);if(-1===i&&this.raise(this.pos-2,"Unterminated comment"),this.pos=i+2,this.options.locations)for(var s=void 0,n=t;(s=Fe(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=s;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,i),t,this.pos,e,this.curPosition())},li.skipLineComment=function(e){for(var t=this.pos,i=this.options.onComment&&this.curPosition(),s=this.input.charCodeAt(this.pos+=e);this.pos8&&e<14||e>=5760&&$e.test(String.fromCharCode(e))))break e;++this.pos}}},li.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var i=this.type;this.type=e,this.value=t,this.updateContext(i)},li.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(Oe.ellipsis)):(++this.pos,this.finishToken(Oe.dot))},li.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(Oe.assign,2):this.finishOp(Oe.slash,1)},li.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),i=1,s=42===e?Oe.star:Oe.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++i,s=Oe.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(Oe.assign,i+1):this.finishOp(s,i)},li.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(Oe.assign,3);return this.finishOp(124===e?Oe.logicalOR:Oe.logicalAND,2)}return 61===t?this.finishOp(Oe.assign,2):this.finishOp(124===e?Oe.bitwiseOR:Oe.bitwiseAND,1)},li.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(Oe.assign,2):this.finishOp(Oe.bitwiseXOR,1)},li.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!Ve.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(Oe.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(Oe.assign,2):this.finishOp(Oe.plusMin,1)},li.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),i=1;return t===e?(i=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+i)?this.finishOp(Oe.assign,i+1):this.finishOp(Oe.bitShift,i)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(i=2),this.finishOp(Oe.relational,i)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},li.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(Oe.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(Oe.arrow)):this.finishOp(61===e?Oe.eq:Oe.prefix,1)},li.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var i=this.input.charCodeAt(this.pos+2);if(i<48||i>57)return this.finishOp(Oe.questionDot,2)}if(63===t){if(e>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(Oe.assign,3);return this.finishOp(Oe.coalesce,2)}}return this.finishOp(Oe.question,1)},li.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,Me(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(Oe.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+Je(e)+"'")},li.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(Oe.parenL);case 41:return++this.pos,this.finishToken(Oe.parenR);case 59:return++this.pos,this.finishToken(Oe.semi);case 44:return++this.pos,this.finishToken(Oe.comma);case 91:return++this.pos,this.finishToken(Oe.bracketL);case 93:return++this.pos,this.finishToken(Oe.bracketR);case 123:return++this.pos,this.finishToken(Oe.braceL);case 125:return++this.pos,this.finishToken(Oe.braceR);case 58:return++this.pos,this.finishToken(Oe.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(Oe.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(Oe.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+Je(e)+"'")},li.finishOp=function(e,t){var i=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,i)},li.readRegexp=function(){for(var e,t,i=this.pos;;){this.pos>=this.input.length&&this.raise(i,"Unterminated regular expression");var s=this.input.charAt(this.pos);if(Ve.test(s)&&this.raise(i,"Unterminated regular expression"),e)e=!1;else{if("["===s)t=!0;else if("]"===s&&t)t=!1;else if("/"===s&&!t)break;e="\\"===s}++this.pos}var n=this.input.slice(i,this.pos);++this.pos;var o=this.pos,r=this.readWord1();this.containsEsc&&this.unexpected(o);var a=this.regexpState||(this.regexpState=new Kt(this));a.reset(i,n,r),this.validateRegExpFlags(a),this.validateRegExpPattern(a);var l=null;try{l=new RegExp(n,r)}catch(e){}return this.finishToken(Oe.regexp,{pattern:n,flags:r,value:l})},li.readInt=function(e,t,i){for(var s=this.options.ecmaVersion>=12&&void 0===t,n=i&&48===this.input.charCodeAt(this.pos),o=this.pos,r=0,a=0,l=0,c=null==t?1/0:t;l=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;a=h,r=r*e+p}}return s&&95===a&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===o||null!=t&&this.pos-o!==t?null:r},li.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var i=this.readInt(e);return null==i&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(i=ci(this.input.slice(t,this.pos)),++this.pos):Me(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(Oe.num,i)},li.readNumber=function(e){var t=this.pos;e||null!==this.readInt(10,void 0,!0)||this.raise(t,"Invalid number");var i=this.pos-t>=2&&48===this.input.charCodeAt(t);i&&this.strict&&this.raise(t,"Invalid number");var s=this.input.charCodeAt(this.pos);if(!i&&!e&&this.options.ecmaVersion>=11&&110===s){var n=ci(this.input.slice(t,this.pos));return++this.pos,Me(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(Oe.num,n)}i&&/[89]/.test(this.input.slice(t,this.pos))&&(i=!1),46!==s||i||(++this.pos,this.readInt(10),s=this.input.charCodeAt(this.pos)),69!==s&&101!==s||i||(43!==(s=this.input.charCodeAt(++this.pos))&&45!==s||++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),Me(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var o,r=(o=this.input.slice(t,this.pos),i?parseInt(o,8):parseFloat(o.replace(/_/g,"")));return this.finishToken(Oe.num,r)},li.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},li.readString=function(e){for(var t="",i=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var s=this.input.charCodeAt(this.pos);if(s===e)break;92===s?(t+=this.input.slice(i,this.pos),t+=this.readEscapedChar(!1),i=this.pos):8232===s||8233===s?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(Be(s)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(i,this.pos++),this.finishToken(Oe.string,t)};var hi={};li.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==hi)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},li.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw hi;this.raise(e,t)},li.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var i=this.input.charCodeAt(this.pos);if(96===i||36===i&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==Oe.template&&this.type!==Oe.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(Oe.template,e)):36===i?(this.pos+=2,this.finishToken(Oe.dollarBraceL)):(++this.pos,this.finishToken(Oe.backQuote));if(92===i)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(Be(i)){switch(e+=this.input.slice(t,this.pos),++this.pos,i){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(i)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},li.readInvalidTemplateToken=function(){for(;this.pos=48&&t<=55){var s=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(s,8);return n>255&&(s=s.slice(0,-1),n=parseInt(s,8)),this.pos+=s.length-1,t=this.input.charCodeAt(this.pos),"0"===s&&56!==t&&57!==t||!this.strict&&!e||this.invalidStringToken(this.pos-1-s.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return Be(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},li.readHexChar=function(e){var t=this.pos,i=this.readInt(16,e);return null===i&&this.invalidStringToken(t,"Bad character escape sequence"),i},li.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,i=this.pos,s=this.options.ecmaVersion>=6;this.pos":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13},bi=17,vi={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:bi,ClassExpression:bi,FunctionExpression:bi,ObjectExpression:bi,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};function xi(e,t){const{generator:i}=e;if(e.write("("),null!=t&&t.length>0){i[t[0].type](t[0],e);const{length:s}=t;for(let n=1;n0){e.write(s);for(let t=1;t0){i.VariableDeclarator(s[0],e);for(let t=1;t0){t.write(s),n&&null!=e.comments&&Si(t,e.comments,o,s);const{length:a}=r;for(let e=0;e0){for(;o0&&t.write(", ");const e=i[o],s=e.type[6];if("D"===s)t.write(e.local.name,e),o++;else{if("N"!==s)break;t.write("* as "+e.local.name,e),o++}}if(o0){t.write(" with { ");for(let e=0;e0)for(let e=0;;){const n=i[e],{name:o}=n.local;if(t.write(o,n),o!==n.exported.name&&t.write(" as "+n.exported.name),!(++e0){t.write(" with { ");for(let i=0;i0){t.write(" with { ");for(let i=0;i "),"O"===e.body.type[0]?(t.write("("),this.ObjectExpression(e.body,t),t.write(")")):this[e.body.type](e.body,t)},ThisExpression(e,t){t.write("this",e)},Super(e,t){t.write("super",e)},RestElement:Pi=function(e,t){t.write("..."),this[e.argument.type](e.argument,t)},SpreadElement:Pi,YieldExpression(e,t){t.write(e.delegate?"yield*":"yield"),e.argument&&(t.write(" "),this[e.argument.type](e.argument,t))},AwaitExpression(e,t){t.write("await ",e),wi(t,e.argument,e)},TemplateLiteral(e,t){const{quasis:i,expressions:s}=e;t.write("`");const{length:n}=s;for(let e=0;e0){const{elements:i}=e,{length:s}=i;for(let e=0;;){const n=i[e];if(null!=n&&this[n.type](n,t),!(++e0){t.write(s),n&&null!=e.comments&&Si(t,e.comments,o,s);const r=","+s,{properties:a}=e,{length:l}=a;for(let e=0;;){const i=a[e];if(n&&null!=i.comments&&Si(t,i.comments,o,s),t.write(o),this[i.type](i,t),!(++e0){const{properties:i}=e,{length:s}=i;for(let e=0;this[i[e].type](i[e],t),++e1)&&("U"!==n[0]||"n"!==n[1]&&"p"!==n[1]||!s.prefix||s.operator[0]!==i||"+"!==i&&"-"!==i)||t.write(" "),o?(t.write(i.length>1?" (":"("),this[n](s,t),t.write(")")):this[n](s,t)}else this[e.argument.type](e.argument,t),t.write(e.operator)},UpdateExpression(e,t){e.prefix?(t.write(e.operator),this[e.argument.type](e.argument,t)):(this[e.argument.type](e.argument,t),t.write(e.operator))},AssignmentExpression(e,t){this[e.left.type](e.left,t),t.write(" "+e.operator+" "),this[e.right.type](e.right,t)},AssignmentPattern(e,t){this[e.left.type](e.left,t),t.write(" = "),this[e.right.type](e.right,t)},BinaryExpression:Ti=function(e,t){const i="in"===e.operator;i&&t.write("("),wi(t,e.left,e,!1),t.write(" "+e.operator+" "),wi(t,e.right,e,!0),i&&t.write(")")},LogicalExpression:Ti,ConditionalExpression(e,t){const{test:i}=e,s=t.expressionsPrecedence[i.type];s===bi||s<=t.expressionsPrecedence.ConditionalExpression?(t.write("("),this[i.type](i,t),t.write(")")):this[i.type](i,t),t.write(" ? "),this[e.consequent.type](e.consequent,t),t.write(" : "),this[e.alternate.type](e.alternate,t)},NewExpression(e,t){t.write("new ");const i=t.expressionsPrecedence[e.callee.type];i===bi||i0&&(this.lineEndSize>0&&(1===s.length?e[i-1]===s:e.endsWith(s))?(this.line+=this.lineEndSize,this.column=0):this.column+=i)}toString(){return this.output}}var Oi=Object.defineProperty,Vi=(e,t,i)=>((e,t,i)=>t in e?Oi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Ri{constructor(){Vi(this,"scopes",[]),Vi(this,"scopeTypes",[]),Vi(this,"scopeCounts",new Map),Vi(this,"contextBoundVars",new Set),Vi(this,"arrayPatternElements",new Set),Vi(this,"rootParams",new Set),Vi(this,"varKinds",new Map),Vi(this,"loopVars",new Set),Vi(this,"loopVarNames",new Map),Vi(this,"paramIdCounter",0),Vi(this,"cacheIdCounter",0),Vi(this,"tempVarCounter",0),this.pushScope("glb")}get nextParamIdArg(){return{type:"Identifier",name:`'p${this.paramIdCounter++}'`}}get nextCacheIdArg(){return{type:"Identifier",name:`'cache_${this.cacheIdCounter++}'`}}pushScope(e){this.scopes.push(new Map),this.scopeTypes.push(e),this.scopeCounts.set(e,(this.scopeCounts.get(e)||0)+1)}popScope(){this.scopes.pop(),this.scopeTypes.pop()}getCurrentScopeType(){return this.scopeTypes[this.scopeTypes.length-1]}getCurrentScopeCount(){return this.scopeCounts.get(this.getCurrentScopeType())||1}addContextBoundVar(e,t=!1){this.contextBoundVars.add(e),t&&this.rootParams.add(e)}addArrayPatternElement(e){this.arrayPatternElements.add(e)}isContextBound(e){return this.contextBoundVars.has(e)}isArrayPatternElement(e){return this.arrayPatternElements.has(e)}isRootParam(e){return this.rootParams.has(e)}addLoopVariable(e,t){this.loopVars.add(e),this.loopVarNames.set(e,t)}getLoopVariableName(e){return this.loopVarNames.get(e)}isLoopVariable(e){return this.loopVars.has(e)}addVariable(e,t){if(this.isContextBound(e))return e;const i=this.scopes[this.scopes.length-1],s=this.scopeTypes[this.scopeTypes.length-1],n=`${s}${this.scopeCounts.get(s)||1}_${e}`;return i.set(e,n),this.varKinds.set(n,t),n}getVariable(e){if(this.loopVars.has(e)){const t=this.loopVarNames.get(e);if(t)return[t,"let"]}if(this.isContextBound(e))return[e,"let"];for(let t=this.scopes.length-1;t>=0;t--){const i=this.scopes[t];if(i.has(e)){const t=i.get(e);return[t,this.varKinds.get(t)||"let"]}}return[e,"let"]}generateTempVar(){return"temp_"+ ++this.tempVarCounter}}//!!!Warning!!! this code is not clean, it was initially written as a PoC then used as transpiler for PineTS
+const Bi="$",Fi={type:"Identifier",name:"undefined"};function $i(e,t){if(e.computed&&"Identifier"===e.property.type){if(t.isLoopVariable(e.property.name))return;if(!t.isContextBound(e.property.name)){const[i,s]=t.getVariable(e.property.name);e.property={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},e.property={type:"MemberExpression",object:e.property,property:{type:"Literal",value:0},computed:!0}}}if(e.computed&&"Identifier"===e.object.type){if(t.isLoopVariable(e.object.name))return;if(!t.isContextBound(e.object.name)){const[i,s]=t.getVariable(e.object.name);e.object={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}if("MemberExpression"===e.property.type){const i=e.property;i._indexTransformed||($i(i,t),i._indexTransformed=!0)}}}function Gi(e,t,i){if(e.object&&"Identifier"===e.object.type&&"Math"===e.object.name)return;const s="if"==i.getCurrentScopeType(),n="els"==i.getCurrentScopeType(),o="for"==i.getCurrentScopeType();!s&&!n&&!o&&e.object&&"Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)||e._indexTransformed||($i(e,i),e._indexTransformed=!0)}function ji(e,t){e.declarations.forEach((i=>{"na"==i.init.name&&(i.init.name="NaN");const s=i.init&&"MemberExpression"===i.init.type&&i.init.object&&("context"===i.init.object.name||i.init.object.name===Bi||"context2"===i.init.object.name),n=i.init&&"MemberExpression"===i.init.type&&i.init.object?.object&&("context"===i.init.object.object.name||i.init.object.object.name===Bi||"context2"===i.init.object.object.name),o=i.init&&"ArrowFunctionExpression"===i.init.type;if(s)return i.id.name&&t.addContextBoundVar(i.id.name),i.id.properties&&i.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})),void(i.init.object.name=Bi);if(n)return i.id.name&&t.addContextBoundVar(i.id.name),i.id.properties&&i.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})),void(i.init.object.object.name=Bi);o&&i.init.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name)}));const r=t.addVariable(i.id.name,e.kind),a=e.kind;i.init&&!o&&("CallExpression"===i.init.type&&"MemberExpression"===i.init.callee.type&&i.init.callee.object&&"Identifier"===i.init.callee.object.type&&t.isContextBound(i.init.callee.object.name)?Ki(i.init,t):di(i.init,{parent:i.init},{Identifier(e,i){e.parent=i.parent,Ui(e,t);const s=e.parent&&"BinaryExpression"===e.parent.type,n=e.parent&&"ConditionalExpression"===e.parent.type;"Identifier"===e.type&&(s||n)&&Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:e.name},property:{type:"Literal",value:0},computed:!0})},CallExpression(e,i,s){"Identifier"===e.callee.type&&(e.callee.parent=e),e.arguments.forEach((t=>{"Identifier"===t.type&&(t.parent=e)})),Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e})))},BinaryExpression(e,t,i){"Identifier"===e.left.type&&(e.left.parent=e),"Identifier"===e.right.type&&(e.right.parent=e),i(e.left,{parent:e}),i(e.right,{parent:e})},MemberExpression(e,i,s){"Identifier"===e.object.type&&(e.object.parent=e),"Identifier"===e.property.type&&(e.property.parent=e),$i(e,t),e.object&&s(e.object,{parent:e})}}));const l={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:a},computed:!1},property:{type:"Identifier",name:r},computed:!1},c=t.isArrayPatternElement(i.id.name),h=!c&&i.init&&"MemberExpression"===i.init.type&&i.init.computed&&i.init.property&&("Literal"===i.init.property.type||"MemberExpression"===i.init.property.type);"MemberExpression"===i.init?.property?.type&&(i.init.property._indexTransformed||($i(i.init.property,t),i.init.property._indexTransformed=!0));const p={type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:l,right:i.init?o||c?i.init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"init"},computed:!1},arguments:h?[l,i.init.object,i.init.property]:[l,i.init]}:{type:"Identifier",name:"undefined"}}};if(c){p.expression.right.object.property.name+=`?.[0][${i.init.property.value}]`;const e=p.expression.right.object;p.expression.right={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"init"},computed:!1},arguments:[l,e]}}o&&(t.pushScope("fn"),di(i.init.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},IfStatement(e,t,i){t.pushScope("if"),i(e.consequent,t),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope()),t.popScope()},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},AssignmentExpression(e,t){zi(e,t)}}),t.popScope()),Object.assign(e,p)}))}function Ui(e,t){if(e.name!==Bi){if("Math"===e.name||"NaN"===e.name||"undefined"===e.name||"Infinity"===e.name||"null"===e.name||e.name.startsWith("'")&&e.name.endsWith("'")||e.name.startsWith('"')&&e.name.endsWith('"')||e.name.startsWith("`")&&e.name.endsWith("`")||t.isLoopVariable(e.name)||t.isContextBound(e.name)&&!t.isRootParam(e.name))return;const i=e.parent&&"MemberExpression"===e.parent.type&&e.parent.object===e&&t.isContextBound(e.name),s=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&"param"===e.parent.callee.property.name;e.parent&&"AssignmentExpression"===e.parent.type&&e.parent.left;const n=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee&&"MemberExpression"===e.parent.callee.type&&t.isContextBound(e.parent.callee.object.name),o=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed,r=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.property===e&&e.parent.parent&&"CallExpression"===e.parent.parent.type&&e.parent.parent.callee&&"MemberExpression"===e.parent.parent.callee.type&&t.isContextBound(e.parent.parent.callee.object.name),a=e.parent&&"CallExpression"===e.parent.type&&e.parent.callee===e;if(i||s||n||r||a){if(a)return;const[i,s]=t.getVariable(e.name);return void Object.assign(e,{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1})}const[l,c]=t.getVariable(e.name),h={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:c},computed:!1},property:{type:"Identifier",name:l},computed:!1};e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e||o?Object.assign(e,h):Object.assign(e,{type:"MemberExpression",object:h,property:{type:"Literal",value:0},computed:!0})}}function zi(e,t){if("Identifier"===e.left.type){const[i,s]=t.getVariable(e.left.name),n={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1};e.left={type:"MemberExpression",object:n,property:{type:"Literal",value:0},computed:!0}}di(e.right,{parent:e.right,inNamespaceCall:!1},{Identifier(e,i,s){"na"==e.name&&(e.name="NaN"),e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type,o=e.parent&&"ConditionalExpression"===e.parent.type,r=t.isContextBound(e.name)&&!t.isRootParam(e.name),a=e.parent&&"MemberExpression"===e.parent.type&&e.parent.computed&&e.parent.object===e,l=e.parent&&e.parent._isParamCall,c=e.parent&&"MemberExpression"===e.parent.type,h="NaN"===e.name;(r||o||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&!c&&!a&&!l&&!h&&Qi(e))},MemberExpression(e,i,s){$i(e,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,s){const n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}})}function Hi(e,t){const i=t.getCurrentScopeType();if(e.argument){if("ArrayExpression"===e.argument.type)e.argument.elements=e.argument.elements.map((e=>{if("Identifier"===e.type){if(t.isContextBound(e.name)&&!t.isRootParam(e.name))return{type:"MemberExpression",object:e,property:{type:"Literal",value:0},computed:!0};const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},property:{type:"Literal",value:0},computed:!0}}return"MemberExpression"===e.type?(e.computed&&"Identifier"===e.object.type&&t.isContextBound(e.object.name)&&!t.isRootParam(e.object.name)||Gi(e,0,t),e):e})),e.argument={type:"ArrayExpression",elements:[e.argument]};else if("BinaryExpression"===e.argument.type)di(e.argument,t,{Identifier(e,t){Ui(e,t),"Identifier"===e.type&&Qi(e)},MemberExpression(e){Gi(e,0,t)}});else if("ObjectExpression"===e.argument.type)e.argument.properties=e.argument.properties.map((e=>{if(e.shorthand){const[i,s]=t.getVariable(e.value.name);return{type:"Property",key:{type:"Identifier",name:e.key.name},value:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},kind:"init",method:!1,shorthand:!1,computed:!1}}return e}));else if("Identifier"===e.argument.type){const[i,s]=t.getVariable(e.argument.name);e.argument={type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1},e.argument={type:"MemberExpression",object:e.argument,property:{type:"Literal",value:0},computed:!0}}"fn"===i&&(e.argument={type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:"precision"}},arguments:[e.argument]})}}function Wi(e,t){if("Identifier"===e.type){if("na"===e.name)return e.name="NaN",e;if(t.isLoopVariable(e.name))return e;if(t.isRootParam(e.name)){const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}if(t.isContextBound(e.name))return e;const[i,s]=t.getVariable(e.name);return{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:i},computed:!1}}return e}function qi(e,t,i){const s=Xi(e.argument,t,i);return{type:"UnaryExpression",operator:e.operator,prefix:e.prefix,argument:s,start:e.start,end:e.end}}function Xi(e,t,i=""){switch(e.type){case"BinaryExpression":return Ji(e,t,i);case"MemberExpression":return{type:"MemberExpression",object:"Identifier"===e.object.type?Wi(e.object,t):e.object,property:e.property,computed:e.computed};case"Identifier":return t.isLoopVariable(e.name)||e.parent&&"MemberExpression"===e.parent.type&&e.parent.property===e?e:{type:"MemberExpression",object:Wi(e,t),property:{type:"Literal",value:0},computed:!0};case"UnaryExpression":return qi(e,t,i)}return e}function Ji(e,t,i){const s=Xi(e.left,t,i),n=Xi(e.right,t,i),o={type:"BinaryExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return di(o,t,{CallExpression(e,t){e._transformed||Ki(e,t)},MemberExpression(e){Gi(e,0,t)}}),o}function Yi(e,t,i){switch(e?.type){case"BinaryExpression":e=Ji(e,i,t);break;case"LogicalExpression":e=function(e,t,i){const s=Xi(e.left,t,i),n=Xi(e.right,t,i),o={type:"LogicalExpression",operator:e.operator,left:s,right:n,start:e.start,end:e.end};return di(o,t,{CallExpression(e,t){e._transformed||Ki(e,t)}}),o}(e,i,t);break;case"ConditionalExpression":return function(e,t,i){return di(e,{parent:e,inNamespaceCall:!1},{Identifier(e,i,s){if("NaN"==e.name)return;if("na"==e.name)return void(e.name="NaN");e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&Qi(e))},MemberExpression(e,i,s){$i(e,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})},CallExpression(e,i,s){const n=e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&t.isContextBound(e.callee.object.name);Ki(e,t),e.arguments.forEach((t=>s(t,{parent:e,inNamespaceCall:n||i.inNamespaceCall})))}}),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Identifier",name:"param"}},arguments:[e,Fi,t.nextParamIdArg],_transformed:!0,_isParamCall:!0}}(e,i,t);case"UnaryExpression":e=qi(e,i,t)}if("MemberExpression"===e.type&&e.computed&&e.property){return{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.object.type&&i.isContextBound(e.object.name)&&!i.isRootParam(e.object.name)?e.object:Wi(e.object,i),"Identifier"!==e.property.type||i.isContextBound(e.property.name)||i.isLoopVariable(e.property.name)?e.property:Wi(e.property,i),i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}if("ObjectExpression"===e.type&&(e.properties=e.properties.map((e=>{if(e.value.name){const[t,s]=i.getVariable(e.value.name);return{type:"Property",key:{type:"Identifier",name:e.key.name},value:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:Bi},property:{type:"Identifier",name:s},computed:!1},property:{type:"Identifier",name:t},computed:!1},kind:"init",method:!1,shorthand:!1,computed:!1}}return e}))),"Identifier"===e.type){if("na"===e.name)return e.name="NaN",e;if(i.isContextBound(e.name)&&!i.isRootParam(e.name))return{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:[e,Fi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}return"CallExpression"===e?.type&&Ki(e,i),{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:t},property:{type:"Identifier",name:"param"},computed:!1},arguments:["Identifier"===e.type?Wi(e,i):e,Fi,i.nextParamIdArg],_transformed:!0,_isParamCall:!0}}function Ki(e,t,i){if(!e._transformed){if(e.callee&&"MemberExpression"===e.callee.type&&e.callee.object&&"Identifier"===e.callee.object.type&&(t.isContextBound(e.callee.object.name)||"math"===e.callee.object.name||"ta"===e.callee.object.name)){const i=e.callee.object.name;e.arguments=e.arguments.map((e=>e._isParamCall?e:Yi(e,i,t))),e._transformed=!0}else e.callee&&"Identifier"===e.callee.type&&(e.arguments=e.arguments.map((e=>e._isParamCall?e:Yi(e,Bi,t))),e._transformed=!0);e.arguments.forEach((e=>{di(e,t,{Identifier(e,i,s){e.parent=i.parent,Ui(e,t);const n=e.parent&&"BinaryExpression"===e.parent.type;(e.parent&&"ConditionalExpression"===e.parent.type||n)&&("MemberExpression"===e.type?$i(e,t):"Identifier"===e.type&&Qi(e))},CallExpression(e,t,i){e._transformed||Ki(e,t)},MemberExpression(e,i,s){Gi(e,0,t),e.object&&s(e.object,{parent:e,inNamespaceCall:i.inNamespaceCall})}})}))}}function Qi(e,t){Object.assign(e,{type:"MemberExpression",object:{type:"Identifier",name:e.name,start:e.start,end:e.end},property:{type:"Literal",value:0},computed:!0,_indexTransformed:!0})}function Zi(e,t,i){if(e.init&&"VariableDeclaration"===e.init.type){const i=e.init.declarations[0],s=i.id.name;t.addLoopVariable(s,s),e.init={type:"VariableDeclaration",kind:e.init.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:s},init:i.init}]},i.init&&di(i.init,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),Ui(e,i),t.popScope())},MemberExpression(e){t.pushScope("for"),Gi(e,0,t),t.popScope()}})}e.test&&di(e.test,t,{Identifier(e,i){!t.isLoopVariable(e.name)&&!e.computed&&(t.pushScope("for"),Ui(e,i),"Identifier"===e.type&&(e.computed=!0,Qi(e)),t.popScope())},MemberExpression(e){t.pushScope("for"),Gi(e,0,t),t.popScope()}}),e.update&&di(e.update,t,{Identifier(e,i){t.isLoopVariable(e.name)||(t.pushScope("for"),Ui(e,i),t.popScope())}}),t.pushScope("for"),i(e.body,t),t.popScope()}function es(e,t,i){e.test&&(t.pushScope("if"),function(e,t){di(e,t,{MemberExpression(e){Gi(e,0,t)},CallExpression(e,t){Ki(e,t)},Identifier(e,i){Ui(e,i);const s="if"===t.getCurrentScopeType();t.isContextBound(e.name)&&!t.isRootParam(e.name)&&s&&Qi(e)}})}(e.test,t),t.popScope()),t.pushScope("if"),i(e.consequent,t),t.popScope(),e.alternate&&(t.pushScope("els"),i(e.alternate,t),t.popScope())}function ts(e){let t="function"==typeof e?e.toString():e;const i=(s=t.trim(),rt.parse(s,{ecmaVersion:"latest",sourceType:"module"}));var s;!function(e){di(e,null,{VariableDeclaration(e,t,i){e.declarations&&e.declarations.length>0&&e.declarations.forEach((t=>{if(t.init&&"ArrowFunctionExpression"===t.init.type&&0!==t.init.start){const i={type:"FunctionDeclaration",id:t.id,params:t.init.params,body:"BlockStatement"===t.init.body.type?t.init.body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:t.init.body}]},async:t.init.async,generator:!1};Object.assign(e,i)}})),e.body&&e.body.body&&e.body.body.forEach((e=>i(e,t)))}})}(i);const n=new Ri;let o;(function(e,t){pi(e,{VariableDeclaration(e){e.declarations.forEach((e=>{const i=e.init&&"MemberExpression"===e.init.type&&e.init.object&&("context"===e.init.object.name||e.init.object.name===Bi||"context2"===e.init.object.name),s=e.init&&"MemberExpression"===e.init.type&&e.init.object?.object&&("context"===e.init.object.object.name||e.init.object.object.name===Bi||"context2"===e.init.object.object.name);(i||s)&&(e.id.name&&t.addContextBoundVar(e.id.name),e.id.properties&&e.id.properties.forEach((e=>{e.key.name&&t.addContextBoundVar(e.key.name)})))}))}})})(i,n),pi(i,{FunctionDeclaration(e){!function(e,t){e.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name,!1)})),e.body&&"BlockStatement"===e.body.type&&(t.pushScope("fn"),di(e.body,t,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Hi(e,t)},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},CallExpression(e,t){Ki(e,t),e.arguments.forEach((e=>{"BinaryExpression"===e.type&&di(e,t,{CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,t)}})}))},MemberExpression(e){Gi(e,0,t)},AssignmentExpression(e,t){zi(e,t)},ForStatement(e,t,i){Zi(e,t,i)},IfStatement(e,t,i){es(e,t,i)},BinaryExpression(e,t,i){di(e,t,{CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,t)}})}}),t.popScope())}(e,n)},ArrowFunctionExpression(e){const t=0===e.start;t&&e.params&&e.params.length>0&&(o=e.params[0].name,e.params[0].name=Bi),function(e,t,i=!1){e.params.forEach((e=>{"Identifier"===e.type&&t.addContextBoundVar(e.name,i)}))}(e,n,t)},VariableDeclaration(e){e.declarations.forEach((t=>{if("ArrayPattern"===t.id.type){const i=n.generateTempVar(),s={type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:i},init:t.init}]};t.id.elements?.forEach((e=>{"Identifier"===e.type&&n.addArrayPatternElement(e.name)}));const o=t.id.elements.map(((t,s)=>({type:"VariableDeclaration",kind:e.kind,declarations:[{type:"VariableDeclarator",id:t,init:{type:"MemberExpression",object:{type:"Identifier",name:i},property:{type:"Literal",value:s},computed:!0}}]})));Object.assign(e,{type:"BlockStatement",body:[s,...o]})}}))},ForStatement(e){}}),di(i,n,{BlockStatement(e,t,i){e.body.forEach((e=>i(e,t)))},ReturnStatement(e,t){Hi(e,t)},VariableDeclaration(e,t){ji(e,t)},Identifier(e,t){Ui(e,t)},CallExpression(e,t){Ki(e,t)},MemberExpression(e){Gi(e,0,n)},AssignmentExpression(e,t){zi(e,t)},FunctionDeclaration(e,t){},ForStatement(e,t,i){Zi(e,t,i)},IfStatement(e,t,i){es(e,t,i)}});const r=function(e,t){const i=new Ni(t);return i.generator[e.type](e,i),i.output}(i);return new Function("",`return ${r}`)(this)}var is=Object.defineProperty,ss=(e,t,i)=>((e,t,i)=>t in e?is(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class ns{constructor(e,t,i,s,n,o,r){this.source=e,this.tickerId=t,this.timeframe=i,this.limit=s,this.sDate=n,this.eDate=o,this.title=r,ss(this,"data",[]),ss(this,"open",[]),ss(this,"high",[]),ss(this,"low",[]),ss(this,"close",[]),ss(this,"volume",[]),ss(this,"hl2",[]),ss(this,"hlc3",[]),ss(this,"ohlc4",[]),ss(this,"openTime",[]),ss(this,"closeTime",[]),ss(this,"_periods"),ss(this,"pineTSCode"),ss(this,"fn"),ss(this,"_readyPromise",null),ss(this,"_ready",!1),this._readyPromise=new Promise((a=>{this.loadMarketData(e,t,i,s,n,o,r).then((e=>{const t=e.reverse();this._periods=t.length,this.data=t;const i=t.map((e=>e.open)),s=t.map((e=>e.close)),n=t.map((e=>e.high)),o=t.map((e=>e.low)),r=t.map((e=>e.volume)),l=t.map((e=>(e.high+e.low+e.close)/3)),c=t.map((e=>(e.high+e.low)/2)),h=t.map((e=>(e.high+e.low+e.open+e.close)/4)),p=t.map((e=>e.openTime)),d=t.map((e=>e.closeTime));this.open=i,this.close=s,this.high=n,this.low=o,this.volume=r,this.hl2=c,this.hlc3=l,this.ohlc4=h,this.openTime=p,this.closeTime=d,this._ready=!0,a(!0)}))}))}get periods(){return this._periods}async loadMarketData(e,t,i,s,n,o,r){return Array.isArray(e)?e:e.getMarketData(t,i,s,n,o,r)}async ready(){if(this._ready)return!0;if(!this._readyPromise)throw new Error("PineTS is not ready");return this._readyPromise}updateData(e){if(!e)throw new Error("Invalid data: newData must be a valid object.");this.data=[e,...this.data],this._periods=this.data.length,this.open=[e.open,...this.open],this.close=[e.close,...this.close],this.high=[e.high,...this.high],this.low=[e.low,...this.low],this.volume=[e.volume,...this.volume],this.hl2=[(e.high+e.low)/2,...this.hl2],this.hlc3=[(e.high+e.low+e.close)/3,...this.hlc3],this.ohlc4=[(e.high+e.low+e.open+e.close)/4,...this.ohlc4],this.openTime=[e.openTime,...this.openTime],this.closeTime=[e.closeTime,...this.closeTime]}async run(e,t,i){if(await this.ready(),t||(t=this._periods),!this.pineTSCode&&!e)throw new Error("Invalid PineTS Code: No pineTSCode supplied/stored.");e=e||this.pineTSCode;const s=new Es({marketData:this.data,source:this.source,tickerId:this.tickerId,timeframe:this.timeframe,limit:this.limit,sDate:this.sDate,eDate:this.eDate,title:this.title});if(s.pineTSCode=e,s.useTACache=i,!this.fn||e&&this.pineTSCode!==e){const t=ts.bind(this);this.fn=t(e),this.pineTSCode=e}const n=this.fn,o=["const","var","let","params"];for(let e=this._periods-t,i=t-1;e((e,t,i)=>t in e?os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class as{constructor(e){this.context=e,rs(this,"script"),rs(this,"pane",0),rs(this,"color",{param:(e,t=0)=>Array.isArray(e)?e[t]:e,rgb:(e,t,i,s)=>s?`rgba(${e}, ${t}, ${i}, ${s})`:`rgb(${e}, ${t}, ${i})`,new:(e,t)=>{if(e&&e.startsWith("#")){const i=e.slice(1),s=parseInt(i.slice(0,2),16),n=parseInt(i.slice(2,4),16),o=parseInt(i.slice(4,6),16);return t?`rgba(${s}, ${n}, ${o}, ${t})`:`rgb(${s}, ${n}, ${o})`}return t?`rgba(${e}, ${t})`:e},white:"white",lime:"lime",green:"green",red:"red",maroon:"maroon",black:"black",gray:"gray",blue:"blue"})}extractPlotOptions(e){const t={};for(let i in e)Array.isArray(e[i])?t[i]=e[i][0]:t[i]=e[i];return t}indicator(e,t,i){this.script=e??t??"PineTS Script",i&&(this.pane=i.overlay?0:1)}plotchar(e,t,i){this.context.plots[t]||(this.context.plots[t]={data:[],options:this.extractPlotOptions(i),title:t}),this.context.plots[t].data.push({time:this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,value:e[0],options:{...this.extractPlotOptions(i),style:"char"}})}plot(e,t,i){this.script&&(i.group=this.script),this.context.plots[t]||(this.context.plots[t]={data:[],options:this.extractPlotOptions(i),title:t,pane:this.pane}),this.context.plots[t].data.push({time:this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,value:e[0],options:this.extractPlotOptions(i)})}na(e){return Array.isArray(e)?isNaN(e[0]):isNaN(e)}nz(e,t=0){const i=Array.isArray(e)?e[0]:e,s=Array.isArray(e)?t[0]:t;return isNaN(i)?s:i}plotcandle(e,t,i,s,n,o){this.script&&(o.group=this.script),this.context.candles[n]||(this.context.candles[n]={data:[],options:this.extractPlotOptions(o),title:n,pane:this.pane});const r=this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,a=e[0],l=t[0],c=i[0],h=s[0];this.context.candles[n].data.push({time:r,open:a,high:l,low:c,close:h,pane:this.pane,options:this.extractPlotOptions(o)})}plotbar(e,t,i,s,n,o){this.script&&(o.group=this.script),this.context.bars[n]||(this.context.bars[n]={data:[],options:this.extractPlotOptions(o),title:n,pane:this.pane});const r=this.context.marketData[this.context.marketData.length-this.context.idx-1].openTime,a=e[0],l=t[0],c=i[0],h=s[0];this.context.bars[n].data.push({time:r,open:a,high:l,low:c,close:h,pane:this.pane,options:this.extractPlotOptions(o)})}fill(e,t,i){this.context.fills[e]||(this.context.fills[e]={plot1:e,plot2:t,options:this.extractPlotOptions(i)})}hline(e,t,i){const s=this.extractPlotOptions(i),n=Array.isArray(e)?e[0]:e;this.context.hlines[t]?(this.context.hlines[t].price=n,this.context.hlines[t].options=s):this.context.hlines[t]={price:n,options:s,pane:this.pane}}}class ls{constructor(e){this.context=e}param(e,t=0){return Array.isArray(e)?[e[t]]:[e]}any(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}int(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}float(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}bool(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}string(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}timeframe(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}time(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}price(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}session(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}source(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}symbol(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}text_area(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}enum(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}color(e,{title:t,group:i}={}){return Array.isArray(e)?e[0]:e}}var cs=Object.defineProperty,hs=(e,t,i)=>((e,t,i)=>t in e?cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class ps{constructor(e){this.context=e,hs(this,"_cache",{})}param(e,t,i){return this.context.params[i]||(this.context.params[i]=[]),Array.isArray(e)?t?(this.context.params[i]=e.slice(t),this.context.params[i].length=e.length,this.context.params[i]):(this.context.params[i]=e.slice(0),this.context.params[i]):(this.context.params[i][0]=e,this.context.params[i])}abs(e){return Math.abs(e[0])}pow(e,t){return Math.pow(e[0],t[0])}sqrt(e){return Math.sqrt(e[0])}log(e){return Math.log(e[0])}ln(e){return Math.log(e[0])}exp(e){return Math.exp(e[0])}floor(e){return Math.floor(e[0])}ceil(e){return Math.ceil(e[0])}round(e){return Math.round(e[0])}random(){return Math.random()}max(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return Math.max(...t)}min(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return Math.min(...t)}sum(e,t){const i=Array.isArray(t)?t[0]:t;return Array.isArray(e)?e.slice(0,i).reduce(((e,t)=>e+t),0):e}sin(e){return Math.sin(e[0])}cos(e){return Math.cos(e[0])}tan(e){return Math.tan(e[0])}acos(e){return Math.acos(e[0])}asin(e){return Math.asin(e[0])}atan(e){return Math.atan(e[0])}avg(...e){const t=e.map((e=>Array.isArray(e)?e[0]:e));return t.reduce(((e,t)=>(Array.isArray(e)?e[0]:e)+(Array.isArray(t)?t[0]:t)),0)/t.length}}var ds=Object.defineProperty,us=(e,t,i)=>((e,t,i)=>t in e?ds(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);const ms=["1","3","5","15","30","45","60","120","180","240","D","W","M"];class gs{constructor(e){this.context=e,us(this,"_cache",{})}param(e,t,i){return this.context.params[i]||(this.context.params[i]=[]),Array.isArray(e)?(this.context.params[i]=t?e.slice(t):e.slice(0),[e[t],i]):(this.context.params[i][0]=e,[e,i])}async security(e,t,i,s=!1,n=!1,o=!1,r=null,a=null){const l=e[0],c=t[0],h=i[0],p=i[1],d=ms.indexOf(this.context.timeframe),u=ms.indexOf(c);if(-1==d||-1==u)throw new Error("Invalid timeframe");if(d>u)throw new Error("Only higher timeframes are supported for now");if(d===u)return h;const m=this.context.data.openTime[0],g=this.context.data.closeTime[0];if(this.context.cache[p]){const e=this.context.cache[p],t=this._findSecContextIdx(m,g,e.data.openTime,e.data.closeTime,n);return-1==t?NaN:e.params[p][t]}const f=await new ns(this.context.source,l,c,this.context.limit||1e3,this.context.sDate,this.context.eDate).run(this.context.pineTSCode);this.context.cache[p]=f;const y=this._findSecContextIdx(m,g,f.data.openTime,f.data.closeTime,n);return-1==y?NaN:f.params[p][y]}_findSecContextIdx(e,t,i,s,n=!1){for(let o=0;o2*e-n[t])),r=Math.floor(Math.sqrt(t));return vs(o,r)}(e.slice(0).reverse(),i),n=this.context.idx;return this.context.precision(s[n])}rma(e,t){const i=Array.isArray(t)?t[0]:t,s=function(e,t){const i=new Array(e.length).fill(NaN),s=1/t;let n=0;for(let i=0;i0?i:0,n[t]=i<0?-i:0}let o=0,r=0;for(let e=1;e<=t;e++)o+=s[e],r+=n[e];o/=t,r/=t,i[t]=0===r?100:100-100/(1+o/r);for(let a=t+1;ae-t)),o=Math.floor(t/2);i[s]=t%2==0?(n[o-1]+n[o])/2:n[o]}return i}(e.slice(0).reverse(),i),n=this.context.idx;return this.context.precision(s[n])}stdev(e,t,i=!0){const s=Array.isArray(t)?t[0]:t,n=Array.isArray(i)?i[0]:i,o=function(e,t,i=!0){const s=new Array(e.length).fill(NaN),n=bs(e,t);for(let o=t-1;op?c[e]=t:c[e]=p;let s=h[e];s>d||i[e-1]c[e]?(a[e]=1,r[e]=h[e]):(a[e]=-1,r[e]=c[e]):i[e]e+t),0)/t,n=p.reduce(((e,t)=>e+t*t),0)/t-i*i,l=Math.sqrt(n);r[d]=o[d]+s*l,a[d]=o[d]-s*l}return l?[o,r,a]:o}(e,this.context.data.volume,t,i),n=this.context.idx;if(void 0!==i&&Array.isArray(s)){const[e,t,i]=s;return[this.context.precision(e[n]),this.context.precision(t[n]),this.context.precision(i[n])]}return this.context.precision(s[n])}swma(e){const t=function(e){const t=e.length,i=new Array(t).fill(NaN);for(let s=3;s((e,t,i)=>t in e?xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,t+"",i);class ws{constructor(e){this.array=e}}class Cs{constructor(e){this.context=e,_s(this,"_cache",{})}param(e,t=0){return Array.isArray(e)?e[t]:e}get(e,t){return e.array[t]}set(e,t,i){e.array[t]=i}push(e,t){e.array.push(t)}sum(e){return e.array.reduce(((e,t)=>e+(isNaN(t)?0:t)),0)}avg(e){return this.sum(e)/e.array.length}min(e,t=0){return[...e.array].sort(((e,t)=>e-t))[t]??this.context.NA}max(e,t=0){return[...e.array].sort(((e,t)=>t-e))[t]??this.context.NA}size(e){return e.array.length}new_bool(e,t=!1){return new ws(Array(e).fill(t))}new_float(e,t=NaN){return new ws(Array(e).fill(t))}new_int(e,t=0){return new ws(Array(e).fill(Math.round(t)))}new_string(e,t=""){return new ws(Array(e).fill(t))}new(e,t){return new ws(Array(e).fill(t))}slice(e,t,i){const s=void 0!==i?i+1:void 0;return new ws(e.array.slice(t,s))}reverse(e){e.array.reverse()}includes(e,t){return e.array.includes(t)}indexof(e,t){return e.array.indexOf(t)}lastindexof(e,t){return e.array.lastIndexOf(t)}stdev(e,t=!0){const i=this.avg(e),s=e.array.map((e=>Math.pow(e-i,2))),n=t?e.array.length:e.array.length-1;return Math.sqrt(this.sum(new ws(s))/n)}variance(e,t=!0){const i=this.avg(e),s=e.array.map((e=>Math.pow(e-i,2))),n=t?e.array.length:e.array.length-1;return this.sum(new ws(s))/n}covariance(e,t,i=!0){if(e.array.length!==t.array.length||e.array.length<2)return NaN;const s=i?e.array.length:e.array.length-1,n=this.avg(e),o=this.avg(t);let r=0;for(let i=0;i0?e.array[0]:this.context.NA}last(e){return e.array.length>0?e.array[e.array.length-1]:this.context.NA}clear(e){e.array.length=0}join(e,t=","){return e.array.join(t)}abs(e){return new ws(e.array.map((e=>Math.abs(e))))}concat(e,t){return e.array.push(...t.array),e}copy(e){return new ws([...e.array])}every(e,t){return e.array.every(t)}fill(e,t,i=0,s){const n=e.array.length,o=void 0!==s?Math.min(s,n):n;for(let s=i;s=0&&t"asc"===t?e-i:i-e))}sort_indices(e,t){const i=e.array.map(((e,t)=>t));return i.sort(((i,s)=>{const n=e.array[i],o=e.array[s];return t?t(n,o):n-o})),new ws(i)}standardize(e){const t=this.avg(e),i=this.stdev(e);return new ws(0===i?e.array.map((()=>0)):e.array.map((e=>(e-t)/i)))}unshift(e,t){e.array.unshift(t)}some(e,t){return e.array.some(t)}}var Ss=Object.defineProperty,ks=(e,t,i)=>((e,t,i)=>t in e?Ss(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);class Es{constructor({marketData:e,source:t,tickerId:i,timeframe:s,limit:n,sDate:o,eDate:r,title:a}){ks(this,"data",{open:[],high:[],low:[],close:[],volume:[],hl2:[],hlc3:[],ohlc4:[]}),ks(this,"cache",{}),ks(this,"useTACache",!1),ks(this,"NA",NaN),ks(this,"math"),ks(this,"ta"),ks(this,"input"),ks(this,"request"),ks(this,"array"),ks(this,"core"),ks(this,"lang"),ks(this,"idx",0),ks(this,"params",{}),ks(this,"const",{}),ks(this,"var",{}),ks(this,"let",{}),ks(this,"result"),ks(this,"plots",{}),ks(this,"candles",{}),ks(this,"bars",{}),ks(this,"fills",{}),ks(this,"hlines",{}),ks(this,"marketData"),ks(this,"source"),ks(this,"tickerId"),ks(this,"timeframe",""),ks(this,"limit"),ks(this,"sDate"),ks(this,"eDate"),ks(this,"group"),ks(this,"pineTSCode"),this.marketData=e,this.source=t,this.tickerId=i,this.timeframe=s,this.limit=n,this.sDate=o,this.eDate=r,this.group=a,this.math=new ps(this),this.ta=new fs(this),this.input=new ls(this),this.request=new gs(this),this.array=new Cs(this);const l=new as(this);this.core={color:l.color,indicator:l.indicator.bind(l),na:l.na.bind(l),nz:l.nz.bind(l),plot:l.plot.bind(l),plotbar:l.plotbar.bind(l),plotchar:l.plotchar.bind(l),plotcandle:l.plotcandle.bind(l),fill:l.fill.bind(l),hline:l.hline.bind(l)}}init(e,t,i=0){return e?!Array.isArray(t)||Array.isArray(t[0])?e[0]=Array.isArray(t?.[0])?t[0]:this.precision(t):e[0]=this.precision(t[t.length-this.idx-1+i]):e=Array.isArray(t)?[this.precision(t[t.length-this.idx-1+i])]:[this.precision(t)],e}precision(e,t=10){return"number"!=typeof e||isNaN(e)?e:Number(e.toFixed(t))}param(e,t,i){return"string"==typeof e||!Array.isArray(e)&&"object"==typeof e?e:(this.params[i]||(this.params[i]=[]),Array.isArray(e)?t?(this.params[i]=e.slice(t),this.params[i].length=e.length,this.params[i]):(this.params[i]=e.slice(0),this.params[i]):(this.params[i][0]=e,this.params[i]))}}var Ms=Object.defineProperty,Ps=(e,t,i)=>((e,t,i)=>t in e?Ms(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i)(e,"symbol"!=typeof t?t+"":t,i);const Ts={1:"1m",3:"3m",5:"5m",15:"15m",30:"30m",45:null,60:"1h",120:"2h",180:null,240:"4h","4H":"4h","1D":"1d",D:"1d","1W":"1w",W:"1w","1M":"1M",M:"1M"};class Is{constructor(e=3e5){Ps(this,"cache"),Ps(this,"cacheDuration"),this.cache=new Map,this.cacheDuration=e}generateKey(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>`${e}:${t}`)).join("|")}get(e){const t=this.generateKey(e),i=this.cache.get(t);return i?Date.now()-i.timestamp>this.cacheDuration?(this.cache.delete(t),null):i.data:null}set(e,t){const i=this.generateKey(e);this.cache.set(i,{data:t,timestamp:Date.now()})}clear(){this.cache.clear()}cleanup(){const e=Date.now();for(const[t,i]of this.cache.entries())e-i.timestamp>this.cacheDuration&&this.cache.delete(t)}}function As(e){let t;if("string"==typeof e){if(t=parseInt(e,10),isNaN(t)){const t=new Date(e);return Math.floor(t.getTime()/1e3)}}else t=e;return t.toString().length>=13?Math.floor(t/1e3):t}new class{constructor(){Ps(this,"cacheManager"),this.cacheManager=new Is(3e5)}async getMarketDataInterval(e,t,i,s){try{const n=Ts[t.toUpperCase()];if(!n)return console.error(`Unsupported timeframe: ${t}`),[];let o=[],r=i;const a=s,l={"1m":6e4,"3m":18e4,"5m":3e5,"15m":9e5,"30m":18e5,"1h":36e5,"2h":72e5,"4h":144e5,"1d":864e5,"1w":6048e5,"1M":2592e6}[n];if(!l)return console.error(`Duration not defined for interval: ${n}`),[];for(;r({openTime:parseInt(e[0]),open:parseFloat(e[1]),high:parseFloat(e[2]),low:parseFloat(e[3]),close:parseFloat(e[4]),volume:parseFloat(e[5]),closeTime:parseInt(e[6]),quoteAssetVolume:parseFloat(e[7]),numberOfTrades:parseInt(e[8]),takerBuyBaseAssetVolume:parseFloat(e[9]),takerBuyQuoteAssetVolume:parseFloat(e[10]),ignore:e[11]})));return this.cacheManager.set(o,h),h}catch(e){return console.error("Error in binance.klines:",e),[]}}};const Ds={...t.customSeriesDefaultOptions,color:"#049981",lineWidth:1,lineStyle:t.LineStyle.Solid,shapeSize:.3,shape:"circles",join:!1,fontSize:.8};function Ls(e,t){if(e._isDecorated)return console.warn("Series is already decorated. Skipping decoration."),e;e._isDecorated=!0;const i=e.setData.bind(e),s=[];let n=null;const o=e.detachPrimitive?.bind(e),r=e.attachPrimitive?.bind(e),a=e.data?.bind(e),l=e.applyOptions?.bind(e),c=e.seriesType(),h=e.options().title;function p(e){const i=s.indexOf(e);-1!==i&&(s.splice(i,1),n===e&&(n=null),o&&o(e),t&&(t.removeLegendPrimitive(e),console.log(`Removed primitive of type "${e.constructor.name}" from legend.`)))}function d(){for(console.log("Detaching all primitives.");s.length>0;){p(s.pop())}console.log("All primitives detached.")}return Object.assign(e,{applyOptions:i=>{if(l&&l(i),t&&void 0!==t._lines){const s=e.seriesType(),n=t._lines.find((t=>t.series===e));if(n&&("Candlestick"===s||"Bar"===s||"Custom"===s&&("upColor"in i||"downColor"in i)?(void 0!==i.upColor&&(n.colors[0]=i.upColor),void 0!==i.downColor&&(n.colors[1]=i.downColor)):"Line"===s||"Histogram"===s||"Custom"===s&&"color"in i?void 0!==i.color&&(n.colors[0]=i.color):"Area"===s&&void 0!==i.lineColor&&(n.colors[0]=i.lineColor),"shape"in i)){const e=(()=>{switch(i.shape){case"circle":case"circles":return"●";case"cross":return"✚";case"triangleUp":return"▲";case"triangleDown":return"▼";case"arrowUp":return"↑";case"arrowDown":return"↓";default:return i.shape}})();n.legendSymbol=e}}},setData:function(t){if(t&&Array.isArray(t)||(t=[...e.data()]),!t||0===t.length)return void i(t);const s=e.seriesType();if("Line"!==s&&"Histogram"!==s&&"Area"!==s&&"Symbol"!=s&&"Custom"!=s||!("value"in t[0])){if(("Bar"===s||"Candlestick"===s||"Custom"===s||"Ohlc"===s)&&"open"in t[0]&&t.every((e=>y(e))))return void i(t)}else if(t.every((e=>f(e))))return void i(t);let n;n="Line"!==s&&"Histogram"!==s&&"Area"!==s&&"Symbol"!==s||!("open"in t[0])?("Bar"!==s&&"Candlestick"!==s&&"Ohlc"!==s||t[0],t.map(((e,i)=>Os(t,s,i)))):t.map(((e,i)=>Os(t,s,i))),i(n)},dataType:function(t){const i=e.data()[0];if(b(i))return null;let s=f(i),n=y(i);if(!s&&!n&&"open"in i&&"high"in i&&"low"in i&&"close"in i&&(n=!0),t){const e=t.data()[0];if(b(e))return!1;let i=f(e),o=y(e);return!i&&!o&&"open"in e&&"high"in e&&"low"in e&&"close"in e&&(o=!0),s&&i||n&&o}return s||n?i:null},dataTransform:function(){const t=e.data();if(!t||0===t.length)return[];const i=t[0];let s;if(y(i)||"open"in i&&"high"in i&&"low"in i&&"close"in i)s="Line";else{if(!f(i))return[...t];s="Candlestick"}return t.map(((t,i)=>Os(e,s,i)))},primitives:s,sync:function(e){const t=e.options().seriesType??"Line",i=a();if(!i)return void console.warn("Source data is missing for synchronization.");const s=[...e.data()];for(let n=s.length;n{const i=[...a()];if(!i||0===i.length)return void console.warn("Source data is missing for synchronization.");const s=e.data().slice(-1)[0],n=i.length-1;if(!s||i[n].time>=s.time){const i=Os(e,t,n);i&&(e.update(i),console.log(`Updated/added bar via "update()" for series type ${e.seriesType}`))}}))},attachPrimitive:function(i,o,a=!0,l=!1){const c=i.constructor.type||i.constructor.name;if(a)d();else{const e=s.findIndex((e=>e.constructor.type===c));-1!==e&&p(s[e])}r&&r(i),s.push(i),n=i,console.log(`Primitive of type "${c}" attached.`),t&&l&&t.addLegendPrimitive(e,i,o)},detachPrimitive:p,detachPrimitives:d,decorated:!0,_type:c,title:h,get primitive(){return n},toJSON:()=>({options:e.options(),data:a()}),fromJSON(t){if(t.data&&i(t.data),t.options){const i=t.options;for(const t in i)if(Object.prototype.hasOwnProperty.call(i,t)){const s=t;e.applyOptions({[s]:i[s]})}}}})}function Ns(e){const t={};switch(e){case"Line":return{...t,title:e,color:"#195200",lineWidth:2,crosshairMarkerVisible:!0};case"Histogram":return{...t,title:e,color:"#9ACF01",base:0};case"Area":return{...t,title:e,lineColor:"#021698",topColor:"rgba(9, 32, 210, 0.4)",bottomColor:"rgba(0, 0, 0, 0.5)"};case"Bar":return{...t,title:e,upColor:"#006721",downColor:"#6E0000",borderUpColor:"#006721",borderDownColor:"#6E0000"};case"Candlestick":return{...t,title:e,upColor:"rgba(0, 103, 33, 0.33)",downColor:"rgba(110, 0, 0, 0.33)",borderUpColor:"#006721",borderDownColor:"#6E0000",wickUpColor:"#006721",wickDownColor:"#6E0000"};case"Ohlc":return{...t,title:e,upColor:"rgba(0, 103, 33, 0.33)",downColor:"rgba(110, 0, 0, 0.33)",borderUpColor:"#006721",borderDownColor:"#6E0000",wickUpColor:"#006721",wickDownColor:"#6E0000",shape:"Rounded",chandelierSize:1,barSpacing:.777,lineStyle:0,lineWidth:1};case"Symbol":return{...t,...Ds,title:e};default:throw new Error(`Unsupported series type: ${e}`)}}function Os(e,t,i){let s;if(Array.isArray(e))s=e;else{if(!e||"function"!=typeof e.data)return console.warn("Invalid source provided to convertDataItem; expected an array or series object."),null;s=[...e.data()]}if(!s||0===s.length)return console.warn("No data available in the source series."),null;const n=s[i];switch(t){case"Line":case"Histogram":case"Area":case"Symbol":if(y(n))return{time:n.time,value:n.close};if(f(n))return{time:n.time,value:n.value};if(b(n))return{time:n.time};break;case"Bar":case"Candlestick":case"Ohlc":if(y(n))return{time:n.time,open:n.open,high:n.high,low:n.low,close:n.close};if(f(n))return{time:n.time,open:n.value,high:n.value,low:n.value,close:n.value};if(b(n))return{time:n.time};break;default:return console.error(`Unsupported target type: ${t}`),{time:n.time}}return console.warn("Could not convert data to the target type."),null}function Vs(e,t,i){const s=e.options(),n=t.split(".");let o=s;for(let e=0;evoid 0!==e.primitives)(e)?e:(console.log("Decorating the series dynamically."),Ls(e,t))}function Fs(e,t){const i={...e.paramMap,...t},s=[...e.sourceSeries.data()];if(!s||!Array.isArray(s)||0===s.length)return;let n;n=s.every(y)?s:s.map($s);e.indicator.calc(n,i).forEach((t=>{const i=e.figures.get(t.key);if(i&&(i.setData(t.data),i.applyOptions({title:t.title}),t.pane&&i.getPane()===e.sourceSeries.getPane())){const e=i.getPane().paneIndex();i.moveToPane(e+t.pane)}})),e.paramMap=i}function $s(e){return{time:e.time,open:e.value,high:e.value,low:e.value,close:e.value}}function Gs(e,t,i,s="Line",n="overwrite"){const{data:o,group:r,options:a,pane:l}=i,c={...js(a)};r&&(c.group=r),t&&(c.title=t);const h="circles"===c.style||"cross"===c.style?"Symbol":s;let p={...Ns(h)||{},...e.defaultsManager.get(h)||{},...c};p.style&&"line"!==p.style&&(p.shape=p.style,delete p.style);const d=o.map((e=>({...e,time:"number"==typeof e.time?As(e.time):e.time}))),u=e.seriesMap.get(t);if(u&&("overwrite"===n||"update"===n))return"update"===n?(u.update(d[d.length-1]),p={...p,...u.options()}):(u.detachPrimitives(),u.setData(d)),void u.applyOptions(p);let m=null;"Line"===s?m="line"!==c.style?e.createSymbolSeries(t,{...p,shape:c.style},l):e.createLineSeries(t,p,l):"Bar"===s?m=e.createBarSeries(t,p,l):"Candlestick"===s||"Ohlc"===s||"Custom"===s&&void 0!==o[0]?.open?m=e.createCustomOHLCSeries?e.createCustomOHLCSeries(t,p):e.createBarSeries(t,p,l):"Histogram"===s?m=e.createHistogramSeries(t,p,l):"Area"===s?m=e.createAreaSeries(t,p,l):(console.warn(`Unsupported series type: ${s}. Defaulting to Line.`),m=e.createLineSeries(t,p,l)),m.series.setData(d),e.legend&&!m.series.decorated&&(m.series=Ls(m.series,e.legend)),e.seriesMap.set(t,m.series)}function js(e){const t={};for(const i in e){const s=Array.isArray(e[i])?e[i][0]:e[i];"linewidth"===i.toLowerCase()?t.lineWidth=s:t[i]=s}return t}function Us(e,t){const{plot1:i,plot2:s,options:n}=t,o=S,r=e.seriesMap.get(i),a=e.seriesMap.get(s);if(!r)return void console.warn(`Origin series with title "${i}" not found.`);if(!a)return void console.warn(`Destination series with title "${s}" not found.`);const l=a.options().title;let c=null;r.primitives[l]?c=r.primitives[l]:(c=new _(r,a,o),r.primitives[l]=c,r.attachPrimitive(c,`Fill ➣ ${a.options().title}`,!1,!0))}function zs(e,t){const i=e.split("."),s={};let n=s;for(let e=0;ee.toUpperCase()))}function Ws(e,i,s){const n=i.timeScale(),o=s??i.addSeries(t.LineSeries);if(!o)return console.warn("No series found. Cannot perform y-axis conversions."),null;if("logical"in e){const t=e,i=n.logicalToCoordinate(t.logical),s=o.priceToCoordinate(t.price);return null===i||null===s?null:{x:i,y:s}}{const t=e,i=n.coordinateToLogical(t.x),s=n.coordinateToTime(t.x),r=o.coordinateToPrice(t.y);return null===i||null===r?null:{time:s,logical:i,price:r}}}function qs(e,t,i,s,n){const o=s-n/2,r=s+n/2;e.beginPath(),e.moveTo(t,o),e.lineTo(t,r),e.lineTo(i,r),e.lineTo(i,o),e.closePath(),e.fill(),e.stroke()}function Xs(e,t,i,s,n,o){const r=i-t,a=o*Math.min(Math.abs(r),Math.abs(n)),l=Math.abs(Math.min(a,r/2,n/2)),c=s-n/2;e.beginPath(),"function"==typeof e.roundRect?e.roundRect(t,c,r,n,l):(e.moveTo(t+l,c),e.lineTo(i-l,c),e.quadraticCurveTo(i,c,i,c+l),e.lineTo(i,c+n-l),e.quadraticCurveTo(i,c+n,i-l,c+n),e.lineTo(t+l,c+n),e.quadraticCurveTo(t,c+n,t,c+n-l),e.lineTo(t,c+l),e.quadraticCurveTo(t,c,t+l,c)),e.closePath(),e.fill(),e.stroke()}function Js(e,t,i,s,n,o){const r=t+(i-t)/2,a=i-t;e.beginPath(),e.ellipse(r,n,Math.abs(a/2),Math.abs(o/2),0,0,2*Math.PI),e.fill(),e.stroke()}function Ys(e,t,i,s,n,o,r,a,l,h,p,d){const u=-Math.max(a,1)*(1-d),m=c(l,.666),g=c(l,.333),f=c(l,.2),y=t-r/2,b=y+a+u,v=y-u,x=b-u;let _,w,C,S;p?(_=n,w=s,C=i,S=o):(_=n,w=i,C=s,S=o),e.fillStyle=g,e.strokeStyle=h,e.beginPath(),e.rect(v,C,a+u-r/2,S-C),e.fill(),e.stroke(),e.fillStyle=f,p?(e.fillStyle=m,e.beginPath(),e.moveTo(y,w),e.lineTo(v,S),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(v,S),e.lineTo(y,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=m,e.beginPath(),e.moveTo(b,_),e.lineTo(x,C),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=f,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(x,C),e.lineTo(b,_),e.closePath(),e.fill(),e.stroke()):(e.fillStyle=f,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(x,C),e.lineTo(b,_),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(b,_),e.lineTo(x,C),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(y,_),e.lineTo(v,C),e.lineTo(v,S),e.lineTo(y,w),e.closePath(),e.fill(),e.stroke(),e.fillStyle=g,e.beginPath(),e.moveTo(y,w),e.lineTo(v,S),e.lineTo(x,S),e.lineTo(b,w),e.closePath(),e.fill(),e.stroke())}function Ks(e,t,i,s,n,o,r,a){const l=s+n/2,c=s-n/2;e.save(),e.beginPath(),a?(e.moveTo(t,l),e.lineTo(i,o),e.lineTo(i,c),e.lineTo(t,r)):(e.moveTo(t,o),e.lineTo(i,l),e.lineTo(i,r),e.lineTo(t,c)),e.closePath(),e.stroke(),e.fill(),e.restore()}function Qs(e,t,i,s,n,o,r,a,l){e.save(),e.beginPath(),l?(e.moveTo(t,a),e.lineTo(t,n+o/2),e.lineTo(s,r),e.lineTo(i,n+o/2),e.lineTo(i,a),e.lineTo(s,n-o/2),e.lineTo(t,a)):(e.moveTo(t,r),e.lineTo(t,n-o/2),e.lineTo(s,a),e.lineTo(i,n-o/2),e.lineTo(i,r),e.lineTo(s,n+o/2),e.lineTo(t,r)),e.closePath(),e.fill(),e.stroke(),e.restore()}function Zs(e,t,i,s,n,o,r){const a=(t+i)/2;e.beginPath(),e.moveTo(a,s),e.lineTo(a,n),e.stroke(),e.beginPath(),e.moveTo(t,o),e.lineTo(a,o),e.stroke(),e.beginPath(),e.moveTo(a,r),e.lineTo(i,r),e.stroke()}function en(e,t,i,s,n,o){const r=s-n/2,a=s+n/2,l=.9*Math.abs(i-t);e.save(),e.beginPath(),o?(e.moveTo(t,r),e.lineTo(t+l,r),e.lineTo(i,a),e.lineTo(i-l,a)):(e.moveTo(i-l,r),e.lineTo(i,r),e.lineTo(t+l,a),e.lineTo(t,a)),e.closePath(),e.fill(),e.stroke(),e.restore()}function tn(e,t,i,s){const n=function(e){if(!e)return null;const t=e.paneSize();return{width:t.width,height:t.height}}(s);if(!n)return!1;const o=n.width*i,r=n.height*i,a=function(e){return e instanceof MouseEvent?(t=e)?{x:t.x,y:t.y}:null:"point"in e&&e.point?e.point:null;var t}(e);if(!a||null==a.x||null==a.y||null==t.x||null==t.y)return!1;const l=Math.abs(t.x-a.x),c=Math.abs(t.y-a.y);return l<=o&&c<=r}function sn(e){let t=0;for(const i of e){if(!i||!Number.isNaN(i.value))break;t++}return t}!function(e){e.Line="Line",e.Histogram="Histogram",e.Area="Area",e.Bar="Bar",e.Candlestick="Candlestick",e.Ohlc="Ohlc",e.Symbol="Symbol",e.Custom="Custom"}(Rs||(Rs={}));const nn={visible:!0,autoScale:!1,xScaleLock:!1,yScaleLock:!1,color:"#737375",lineWidth:1,upColor:"rgba(0,255,0,.25)",downColor:"rgba(255,0,0,.25)",wickVisible:!0,borderVisible:!0,borderColor:"#737375",borderUpColor:"#1c9d1c",borderDownColor:"#d5160c",wickColor:"#737375",wickUpColor:"#1c9d1c",wickDownColor:"#d5160c",radius:100,shape:"Rounded",chandelierSize:1,barSpacing:.8,lineStyle:0,lineColor:"#ffffff",width:1};class on{handler;get data(){return this.convertAndAggregateDataPoints()}get sourceData(){return this._originalData}_originalP1;_originalP2;_barWidth=.8;p1;p2;_options;series;_originalData=[];_originalSlice=[];offset;onComplete;get spatial(){return this.recalculateSpatial()}transform={scale:{x:1,y:1},shift:{x:0,y:0}};constructor(e,t,i,s,n,o){let r,a;this.handler=e,this._options={...n,...nn},Math.min(i.logical,s.logical)===i.logical?(r=i,a=s):(r=s,a=i),this._originalP1={...r},this._originalP2={...a},this.offset=o??0,this.p1=i,this.p2=s,x(t)?(this.series=t,this._originalData=this.series.data().map(((e,t)=>({...e,x1:t,x2:t+1})))):(this.series=this.handler.series||this.handler._seriesList[0],this._originalData=t._originalData);const l=Math.min(this._originalP1.logical,this._originalP2.logical),c=Math.max(this._originalP1.logical,this._originalP2.logical);o&&o>0?(this._originalSlice=this._originalData.slice(c,Math.min(this.series.data().length-1,c+1+o)),console.log("Data Sliced with Offset",l,c,o,"Offset Point:",Math.min(this.series.data().length-1,c+1+o))):(this._originalSlice=this._originalData.slice(l,c+1),console.log("Data Sliced:",l,c)),o&&o>0&&(this._originalSlice=this._originalSlice.map((e=>({...e,x1:e.x1+o,x2:e.x2+o}))),console.log("Adjusted originalSlice with pOffset:",o)),this.transform=this.recalculateSpatial(),this.p1&&this.p2&&this.setPoints(this.p1,this.p2)}setData(e){this._originalSlice=e}setPoints(e,t){let i,s;Math.min(e.logical,t.logical)===e.logical?(i=e,s=t):(i=t,s=e),null===this._originalP1?(this._originalP1={...i},console.log("First point (p1) set:",this._originalP1)):null===this._originalP2&&(this._originalP2={...s},console.log("Second point (p2) set:",this._originalP2)),this.p1=i,this.p2=s,this.recalculateSpatial(),this.processSequence()}updatePoint(e,t){1===e?this.p1=t:2===e&&(this._originalP2||(this._originalP2=t),this.p2=t),this.recalculateSpatial(),this.processSequence()}recalculateSpatial(){if(!(this.p1&&this.p2&&this._originalP1&&this._originalP2))return console.warn("Cannot recalc spatial without valid p1/p2."),{scale:{x:1,y:1},shift:{x:0,y:0}};const e=Math.abs(this._originalP1.logical-this._originalP2.logical),t=Math.abs(this._originalP1.price-this._originalP2.price);if(0===e||0===t)return console.warn("Cannot recalc scale if original points are zero difference."),{scale:{x:1,y:1},shift:{x:0,y:0}};const i=Math.abs(this.p1.logical-this.p2.logical)/e,s=((this._originalP2.price>this._originalP1.price?this.p2.price:this.p1.price)-(this._originalP2.price>this._originalP1.price?this.p1.price:this.p2.price))/t;this._options.xScaleLock||(this.transform.scale.x=i),this._options.yScaleLock||(this.transform.scale.y=s),this._options.autoScale&&i>-1&&i<1&&(this._options.chandelierSize=Math.abs(Math.ceil(1/i)));const n={scale:{x:0!==i?Math.round(100*i)/100:1,y:0!==s?Math.round(100*s)/100:1},shift:{x:this._originalP1.logical-this.p1.logical,y:this._originalP1.price-this.p1.price}};return this._barWidth=Math.abs(this.p1.logical-this.p2.logical)/this._originalData.length,console.log("Spatial recalculated:","scaleX=",n.scale.x,"scaleY=",n.scale.y,"shiftX=",n.shift.x,"shiftY=",n.shift.y),0===n.scale.x||0===n.scale.y?(console.warn("Scale factors cannot be zero."),{scale:{x:1,y:1},shift:{x:0,y:0}}):n}processSequence(){this.p1&&this.p2?(this.convertAndAggregateDataPoints(),this.onComplete&&this.onComplete()):console.warn("Cannot process sequence without valid p1/p2.")}convertAndAggregateDataPoints(){let e=Number.POSITIVE_INFINITY,t=Number.NEGATIVE_INFINITY;const i={...this.spatial};this._originalSlice.forEach((i=>{const s=[];void 0!==i.open&&s.push(i.open),void 0!==i.high&&s.push(i.high),void 0!==i.low&&s.push(i.low),void 0!==i.close&&s.push(i.close),void 0!==i.value&&s.push(i.value);for(const i of s)it&&(t=i)}));const s=t===e?1:t-e,n=this.p1.logical,o=this._originalSlice.map(((t,o)=>{const r=n+o;function a(t,i){if(void 0===t)return;const n=(t-e)/s;return e-i.shift.y+n*i.scale.y*s}const c=a(t.open,i),h=a(t.close,i),p=a(t.high,i),d=a(t.low,i),u=a(t.value,i);if(void 0!==c||void 0!==h||void 0!==p||void 0!==d){const e=(h??0)>(c??0),i=e?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",s=e?this._options.borderUpColor||l(i,1):this._options.borderDownColor||l(i,1),n=e?this._options.wickUpColor||s:this._options.wickDownColor||s;return{open:c,close:h,high:p,low:d,isUp:e,x1:r+this.offset,x2:r+1+this.offset,isInProgress:!1,originalData:{...t,x1:o},barSpacing:this._barWidth,color:i,borderColor:s,wickColor:n,lineStyle:this._options.lineStyle,lineWidth:this._options.lineWidth,shape:this._options.shape??"Rounded"}}return{value:u,isUp:void 0,x1:r+this.offset,x2:r+1+this.offset,isInProgress:!1,originalData:t,barSpacing:this._options.barSpacing??.8}})),r=this._options.chandelierSize??1;if(r<=1)return o;const a=[];for(let e=0;eMath.max(e,t.high||0)),0),a=e.reduce(((e,t)=>Math.min(e,t.low||1/0)),1/0),c=o>i,h=c?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)",p=c?this._options.borderUpColor||l(h,1):this._options.borderDownColor||l(h,1),d=c?this._options.wickUpColor||p:this._options.wickDownColor||p,u=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),m=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return{open:i,high:r,low:a,close:o,isUp:c,x1:s,x2:n,isInProgress:t,color:h,borderColor:p,wickColor:d,shape:this._options.shape??"Rounded",lineStyle:u,lineWidth:m}}{const t=e[0].value??0,i=(e[e.length-1].value??0)>t,o=i?this._options.upColor||"rgba(0,255,0,0.333)":this._options.downColor||"rgba(255,0,0,0.333)";i?this._options.borderUpColor||l(o,1):this._options.borderDownColor||l(o,1);i?this._options.wickUpColor:this._options.wickDownColor;const r=e.reduce(((e,t)=>t.lineStyle??t.originalData?.lineStyle??e),this._options.lineStyle),a=e.reduce(((e,t)=>t.lineWidth??t.originalData?.lineWidth??e),this._options.lineWidth??1);return this._options.shape,{value:t,isUp:i,x1:s,x2:n,color:o,lineStyle:r,lineWidth:a}}}applyOptions(e){this._options={...this._options,...e},this.processSequence()}}class rn extends a{_type="TrendTrace";_paneViews;_sequence;_options;_state=N.NONE;_handler;_source;_originalP1=null;_originalP2=null;p1=null;p2=null;_points=[];title="";static _type="Trend-Trace";_startDragPoint=null;_latestHoverPoint=null;static _mouseIsDown=!1;static hoveredObject=null;static lastHoveredObject=null;_listeners=[];_hovered=!1;constructor(e,t,i,s,n,o){super(),this._handler=e,this._source=t,this._originalP1={...i},this._originalP2={...s};const r=this._source.options(),a=function(e,t){const i={};for(const s in e)Object.prototype.hasOwnProperty.call(t,s)&&(i[s]=t[s]);return i}(nn,r);this._options={...a,...n},this._sequence=this._createSequence({p1:i,p2:s},this._options,o),this.p1=this._sequence.p1,this.p2=this._sequence.p2,this._subscribeEvents(),this._paneViews=[new an(this)]}toJSON(){return{data:this._sequence.data,p1:this._sequence._originalP1,p2:this._sequence._originalP2,options:this._sequence._options}}fromJSON(e){if(e.data&&this._sequence.setData(e.data),e.options){const t=e.options;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)){const i=e;this.applyOptions({[i]:t[i]})}}e.p1&&(this.p1=e.p1),e.p2&&(this.p2=e.p2)}attached(e){super.attached(e),this._originalP1&&this._originalP2&&this._createSequence({p1:this._originalP1,p2:this._originalP2}),this._source=Bs(e.series,this._handler.legend),this.title=e.series.options().title;const i=new(t.defaultHorzScaleBehavior());return{chart:e.chart,series:e.series,requestUpdate:e.requestUpdate,horzScaleBehavior:i}}paneViews(){return this._paneViews}detached(){super.detached(),this._listeners.forEach((({name:e,listener:t})=>{document.body.removeEventListener(e,t)})),this._listeners=[],this._handler?.chart&&(this._handler.chart.unsubscribeCrosshairMove(this._handleMouseMove),this._handler.chart.unsubscribeClick(this._handleMouseDownOrUp)),this._paneViews=[],this._sequence=null,this._options=null,this._source=null,this._originalP1=null,this._originalP2=null,this.p1=null,this.p2=null,console.log("✅ All listeners and references successfully detached.")}_createSequence(e,t,i){let s;return"p1"in e&&"p2"in e?(s=new on(this._handler,this._source,e.p1,e.p2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s):(s=new on(this._handler,e.data,e.data._originalP1,e.data._originalP2,t??this._options,i),s.onComplete=()=>this.updateViewFromSequence(),this.updateViewFromSequence(),s)}applyOptions(e){this._options={...this._options,...e},this._sequence&&this._sequence.applyOptions(this._options),this.requestUpdate()}_pendingUpdate=!1;updateViewFromSequence(){this._pendingUpdate||(this._pendingUpdate=!0,requestAnimationFrame((()=>{super.requestUpdate(),console.log("Updating view with sequence data:",this._sequence?.data),this._pendingUpdate=!1})))}getOptions(){return this._options}_subscribeEvents(){this._handler.chart.subscribeCrosshairMove(this._handleMouseMove),this._handler.chart.subscribeClick(this._handleMouseDownOrUp)}_subscribe(e,t){document.body.addEventListener(e,t),this._listeners.push({name:e,listener:t})}_unsubscribe(e,t){document.body.removeEventListener(e,t);const i=this._listeners.find((i=>i.name===e&&i.listener===t));this._listeners.splice(this._listeners.indexOf(i),1)}_handleHoverInteraction(e){if(this._latestHoverPoint=e.point,rn._mouseIsDown)this._handleDragInteraction(e);else if(this._mouseIsOverSequence(e)){if(this._state!=N.NONE)return;this._moveToState(N.HOVERING),rn.hoveredObject=rn.lastHoveredObject=this}else{if(this._state==N.NONE)return;this._moveToState(N.NONE),rn.hoveredObject===this&&(rn.hoveredObject=null)}}_handleMouseDownOrUp=()=>{this._latestHoverPoint&&(rn._mouseIsDown=!rn._mouseIsDown,rn._mouseIsDown?this._onMouseDown():this._onMouseUp())};_handleMouseMove=e=>{const t=this._eventToPoint(e,this._source);this._latestHoverPoint=t,rn._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPoint(e,1)||this._mouseIsOverPoint(e,2)||this._mouseIsOverSequence(e)?this._state===N.NONE&&this._moveToState(N.HOVERING):this._state!==N.NONE&&this._moveToState(N.NONE)};_onMouseUp(){rn._mouseIsDown=!1,this.chart.applyOptions({handleScroll:!0}),this._moveToState(N.HOVERING),this._startDragPoint=null}_handleDragInteraction(e){if(this._state!==N.DRAGGING&&this._state!==N.DRAGGINGP1&&this._state!==N.DRAGGINGP2)return;const t=this._eventToPoint(e,this.series);if(!t||!this._startDragPoint)return;const i=this._getDiff(t,this._startDragPoint);this._onDrag(i),this._startDragPoint=t,this.requestUpdate()}_mouseIsOverPoint(e,t){const i=1===t?{x:this._paneViews[0]._p1.x,y:this._paneViews[0]._p1.y}:{x:this._paneViews[0]._p2.x,y:this._paneViews[0]._p2.y};return!!this.chart&&tn(e,i,.05,this.chart)}_mouseIsOverSequence(e){if(!e.logical||!e.point)return console.warn("Invalid MouseEventParams: Missing logical or point."),!1;const t=this._source.coordinateToPrice?.(e.point.y);if(null==t)return console.warn("Mouse price could not be determined."),!1;let i=e.time?this._sequence.data.find((t=>t.time===e.time)):void 0;if(i||(i=this._sequence.data.find((t=>Math.round(t.x1)===Math.round(e.logical)))),!i)return console.warn("No matching bar found for the given parameters."),!1;if(null!=i.low&&null!=i.high){const e=.05*(i.high-i.low);return t>=i.low-e&&t<=i.high+e}if(null!=i.value){const e=.05*i.value;return t>=i.value-e&&t<=i.value+e}return console.warn("Bar lacks price information."),!1}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this.requestUpdate(),this._unsubscribe("mousedown",this._handleMouseDownInteraction);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this.requestUpdate(),this._subscribe("mousedown",this._handleMouseDownInteraction),this._unsubscribe("mouseup",this._handleMouseDownInteraction),this.chart.applyOptions({handleScroll:!0});break;case N.DRAGGINGP1:case N.DRAGGINGP2:case N.DRAGGING:document.body.style.cursor="grabbing",this._subscribe("mouseup",this._handleMouseUpInteraction),this.chart.applyOptions({handleScroll:!1})}this._state=e}_addDiffToPoint(e,t,i){e&&(e.logical=e.logical+t,e.price=e.price+i,e.time=this.series.dataByIndex(e.logical)?.time||null)}_onDrag(e){this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP1||this._addDiffToPoint(this._sequence.p1,this._options.xScaleLock&&this._state==N.DRAGGINGP1?0:e.logical,this._options.yScaleLock&&this._state==N.DRAGGINGP1?0:e.price),this._state!=N.DRAGGING&&this._state!=N.DRAGGINGP2||this._addDiffToPoint(this._sequence.p2,this._options.xScaleLock&&this._state==N.DRAGGINGP2?0:e.logical,this._options.yScaleLock&&this._state==N.DRAGGINGP2?0:e.price)}_onMouseDown(){this._startDragPoint=null;const e=this._latestHoverPoint;if(!e)return;const t=this._paneViews[0]._p1,i=this._paneViews[0]._p2;if(!(t.x&&i.x&&t.y&&i.y))return this._moveToState(N.DRAGGING);Math.abs(e.x-t.x)<20&&Math.abs(e.y-t.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGINGP1)):Math.abs(e.x-i.x)<20&&Math.abs(e.y-i.y)<20?(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGINGP2)):(this.chart.applyOptions({handleScroll:!1}),this._moveToState(N.DRAGGING))}_handleMouseDownInteraction=()=>{this._onMouseDown()};_handleMouseUpInteraction=()=>{this._onMouseUp()};_getDiff(e,t){return{logical:e.logical-t.logical,price:e.price-t.price}}_eventToPoint(e,t){if(!t||!e.point||!e.logical)return null;const i=t.coordinateToPrice(e.point.y);return null==i?null:{time:e.time||null,logical:e.logical,price:i.valueOf()}}}class an{_p1={x:null,y:null};_p2={x:null,y:null};_plugin;constructor(e){this._plugin=e}renderer(){if(!this._plugin._sequence)throw new Error("No sequence available for rendering.");return new ln(this._plugin,this._plugin._options,!1)}}class ln extends G{_source;_options;constructor(e,t,i){super(Ws(e._sequence.p1,e.chart,e._source),Ws(e._sequence.p2,e.chart,e._source),t,i),this._source=e,this._options=t}draw(e){e.useBitmapCoordinateSpace((e=>{const t=e.context,{chart:i}=this._source;t.save();const{horizontalPixelRatio:s}=e,n=this._source._sequence.data,o=this._source.chart.timeScale(),r=this._source._source,a=i.timeScale().getVisibleLogicalRange(),l=i.options().width/((a?.to??n.length)-(a?.from??0));if(console.log("barSpace:",l),!r||!o||0===n.length)return void t.restore();const c=n[0].x1,h=n[n.length-1].x2,p=i.timeScale().logicalToCoordinate(c)??0,d=i.timeScale().logicalToCoordinate(h)??p,u=p*s,m=d*s,g=this._source._sequence._originalP2.logical>this._source._sequence._originalP1.logical&&this._source._sequence.p2.logical>this._source._sequence.p1.logical||this._source._sequence._originalP2.logical{const i=u+(g?1:-1)*(t*((m-u)/n.length)*this._source._sequence.spatial.scale.x),s=(t+1)*((m-u)/n.length)*this._source._sequence.spatial.scale.x-(1-(this._options.barSpacing??.8))*(m-u)/n.length/(this._options.chandelierSize??1),o=e.isUp?g?this._options.upColor:this._options.downColor:g?this._options.downColor:this._options.upColor,r=e.isUp?g?this._options.borderUpColor:this._options.borderDownColor:g?this._options.borderDownColor:this._options.borderUpColor,a=e.isUp?g?this._options.wickUpColor:this._options.wickDownColor:g?this._options.wickDownColor:this._options.wickUpColor;return{...e,scaledX1:i,scaledX2:s,color:o,borderColor:r,wickColor:a}})).filter((e=>null!==e));console.log("Scaled bars:",f),this.isOHLCData(n)?(this._options.wickVisible&&this._drawWicks(e,f,l),this._drawCandles(e,f,l)):this.isSingleValueData(n)&&this._drawSingleValueData(e,f),t.restore()}))}_drawSingleValueData(e,t){const{context:i,horizontalPixelRatio:s,verticalPixelRatio:n}=e;i.lineWidth=this._options.lineWidth??1,U(i,this._options.lineStyle??1),i.strokeStyle=this._options.visible?this._options.lineColor??"#ffffff":"rgba(0,0,0,0)",i.beginPath(),t.forEach((e=>{if(null===e.x1||void 0===e.x1)return;const t=e.scaledX1*s,o=(this._source._source?.priceToCoordinate(e.value??0)??0)*n;i.lineTo(t,o),i.stroke()}))}_drawWicks(e,t,i){const{context:s,verticalPixelRatio:n}=e;this._source._sequence._originalP2.price>this._source._sequence._originalP1.price&&this._source._sequence.p2.price>this._source._sequence.p1.price||this._source._sequence._originalP2.pricethis._source._sequence._originalP1.logical&&this._source._sequence.p2.price>this._source._sequence.p1.price;t[0].scaledX1,t[t.length-1].scaledX2;t.length;const r=Math.abs(i);t.forEach(((e,i)=>{const a=(this._options.barSpacing??.8)*r,l=r-a;let c=e.scaledX1,h=c+(e.x2-e.x1+((this._options.chandelierSize??1)>1?1:0))*r-l;if(i{const o=(this._options.barSpacing??.8)*a,l=a-o;if(!e)return;const c=(this._source.series.priceToCoordinate(e.open)??0)*r,h=(this._source.series.priceToCoordinate(e.close)??0)*r,p=(this._source.series.priceToCoordinate(e.high)??0)*r,d=(this._source.series.priceToCoordinate(e.low)??0)*r,u=h>=c,m=Math.min(c,h),g=Math.max(c,h),f=m-g,y=(m+g)/2;let b=e.scaledX1-.5*a,v=b+(e.x2-e.x1+((this._options.chandelierSize??1)>1?1:0))*a-l;if(ivoid 0!==e.open&&void 0!==e.high&&void 0!==e.low&&void 0!==e.close))}isSingleValueData(e){return e.every((e=>void 0!==e.value))}}class cn{handler;static ICONS={import:'',trend:'',horz:'',ray:'',box:'',vert:'',pitch:'',measure:''};fileInput;div;activeIcon=null;buttons=[];_series;_commandFunctions;_handlerID;_drawingTool;constructor(e,t,i,s,n=!0){this.handler=e,this._handlerID=this.handler.id,this._series=i,this._commandFunctions=s,this._drawingTool=new F(t,i,(()=>this.removeActiveAndSave())),s.push((e=>{if((e.metaKey||e.ctrlKey)&&"KeyZ"===e.code){const e=this._drawingTool.drawings.pop();return e&&this._drawingTool.delete(e),!0}return!1}));const o=n?"default":"legacy";this.div=this._createToolBox(e,o),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept=".json",this.fileInput.style.display="none",this.fileInput.addEventListener("change",this._handleFileInput),this.div.appendChild(this.fileInput),e.ContextMenu.setupDrawingTools(this.saveDrawings,this._drawingTool),s.push((e=>{if(this.handler.id!==window.handlerInFocus)return!1;if(e.altKey)for(const[t,i]of Object.keys(cn.ICONS).entries()){const i=["M","T","H","R","B","V","P"][t];if(e.code===`Key${i}`)return e.preventDefault(),this.buttons[t].click(),!0}return!1}))}_createToolBox(e,t){return"default"===t?this._makeToggleToolBox():this._makeToolBox()}_makeToolBox(){const e=document.createElement("div");return e.classList.add("toolbox"),this._registerIcon(e,"measure"),this._registerIcon(e,"trend"),this._registerIcon(e,"horz"),this._registerIcon(e,"ray"),this._registerIcon(e,"box"),this._registerIcon(e,"vert",!0),this._registerIcon(e,"pitch"),this._registerIcon(e,"import"),e}_makeToggleToolBox(){const e=document.createElement("div");e.classList.add("flyout-toolbox"),Object.assign(e.style,{position:"absolute",top:"0",left:"50%",transform:"translateX(-50%)",overflow:"hidden",transition:"height 0.3s ease",zIndex:"1000"});const t=document.createElement("div");t.classList.add("toolbox-content"),Object.assign(t.style,{display:"none",inlineFlex:"row",padding:"5px",backgroundColor:"rgba(0,0,0,0.5)"}),this._registerIcon(t,"measure"),this._registerIcon(t,"trend"),this._registerIcon(t,"horz"),this._registerIcon(t,"ray"),this._registerIcon(t,"box"),this._registerIcon(t,"vert",!0),this._registerIcon(t,"pitch"),this._registerIcon(t,"import"),e.appendChild(t);const i=document.createElement("div");i.textContent="▼",Object.assign(i.style,{width:"15px",height:"15px",textAlign:"center",lineHeight:"15px",cursor:"pointer",color:"#fff",background:"transparent"});let s=!1;return e.style.height="15px",i.onclick=()=>{if(s=!s,s){t.style.display="inline-flex";const s=t.scrollHeight;e.style.height=`${s+15}px`,i.textContent="▲"}else t.style.display="none",e.style.height="15px",i.textContent="▼"},e.appendChild(i),e}static TOOL_CLASSES={import:Z,measure:fe,trend:J,horz:se,ray:ne,box:Z,vert:le,pitch:de};_registerIcon(e,t,i=!1){const s="http://www.w3.org/2000/svg",n=document.createElement("div");n.classList.add("toolbox-button"),n.dataset.tool=t;const o=document.createElementNS(s,"svg");o.setAttribute("width","28"),o.setAttribute("height","28"),o.setAttribute("viewBox","0 0 28 28");const r=document.createElementNS(s,"g");r.innerHTML=cn.ICONS[t],o.appendChild(r),i&&(o.style.transform="rotate(90deg)",o.style.transformBox="fill-box",o.style.transformOrigin="center"),n.appendChild(o),e.appendChild(n);const a={key:t,div:n,group:r,type:cn.TOOL_CLASSES[t]};n.addEventListener("click",(()=>this._onIconClick(a))),this.buttons.push(n),e.appendChild(n)}_onIconClick(e){if("import"!==e.key){if(this.activeIcon&&(this.activeIcon.div.classList.remove("active-toolbox-button"),this._drawingTool.stopDrawing(),this.activeIcon===e))return this.activeIcon=null,void window.setCursor("default");this.activeIcon=e,e.div.classList.add("active-toolbox-button"),window.setCursor("crosshair"),this._drawingTool.beginDrawing(e.type)}else this.fileInput.click()}_handleFileInput=e=>{const t=e.target,i=t.files?.[0];if(!i)return;const s=new FileReader;s.onload=()=>{let e;try{e=JSON.parse(s.result)}catch{return void window.alert("❌ Could not parse that file as JSON.")}const t=e.object??e;"object"==typeof t.p1&&"object"==typeof t.p2&&Array.isArray(t.data)&&"object"==typeof t.options?this._doImport(t,i.name):window.alert("❌ JSON isn’t a valid TrendTrace export.")},s.readAsText(i),t.value=""};_doImport(e,t){const i={logical:e.p1.logical,price:e.p1.price??0,time:e.p1.time??null},s={logical:e.p2.logical,price:e.p2.price??0,time:e.p2.time??null},n=e.data.filter((e=>null!=e.low)).map((e=>e.low)),o=e.data.filter((e=>null!=e.high)).map((e=>e.high));n.length&&(s.price=Math.min(...n)),o.length&&(i.price=Math.max(...o));const r=new Z(i,s,{...Q,lineColor:"rgba(0,0,0,0)",fillColor:"rgba(0,0,0,0)",width:.5});this._drawingTool.addNewDrawing(r);const a=Bs(this._series,this.handler.legend),l=new rn(this.handler,a,i,s,e.options);l.fromJSON({data:e.data,p1:i,p2:s,options:e.options}),a.primitives.TrendTrace=l,a.attachPrimitive(l,`${i.logical} ⥵ ${s.logical}`,!1,!0),r.linkedObjects.push(l),this.saveDrawings()}removeActiveAndSave(){window.setCursor("default"),this.activeIcon&&(this.activeIcon.div.classList.remove("active-toolbox-button"),this.activeIcon=null),this.saveDrawings()}addNewDrawing(e){this._drawingTool.addNewDrawing(e)}clearDrawings(){this._drawingTool.clearDrawings()}saveDrawings=()=>{const e=[];for(const t of this._drawingTool.drawings)e.push({type:t._type,points:t.points,options:t._options});const t=JSON.stringify(e);window.callbackFunction(`save_drawings${this._handlerID}_~_${t}`)};loadDrawings(e){e.forEach((e=>{switch(e.type){case"Box":this._drawingTool.addNewDrawing(new Z(e.points[0],e.points[1],e.options));break;case"TrendLine":this._drawingTool.addNewDrawing(new J(e.points[0],e.points[1],e.options));break;case"HorizontalLine":this._drawingTool.addNewDrawing(new se(e.points[0],e.options));break;case"RayLine":this._drawingTool.addNewDrawing(new ne(e.points[0],e.options));break;case"VerticalLine":this._drawingTool.addNewDrawing(new le(e.points[0],e.options));break;case"PitchFork":this._drawingTool.addNewDrawing(new de(e.points[0],e.points[1],e.points[2],e.options));break;case"Measure":this._drawingTool.addNewDrawing(new fe(e.points[0],e.points[1],e.options))}}))}}const hn={color:"white",border:"none",padding:"5px 10px",cursor:"pointer",borderRadius:"12px",boxShadow:"0 2px 4px rgba(0,0,0,0.2)",transition:"transform 0.2s ease-in-out"};class pn{container;header;editorDiv;resizer;editorInstance=null;closeButton;isResizing=!1;startY=0;startHeight=0;MIN_HEIGHT=100;MAX_HEIGHT=window.innerHeight-50;scripts={};handler;_dataChangeHandlers=new Map;selectedSeries=null;selectedVolumeSeries=null;constructor(e){this.handler=e,this.selectedSeries=this.handler.series,this.selectedVolumeSeries=this.handler.volumeSeries??null,this.container=document.createElement("div"),Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"0",width:"100%",height:"300px",backgroundColor:"#000000",borderTop:"2px solid #222",zIndex:"10000",display:"none",flexDirection:"column"}),this.resizer=document.createElement("div"),Object.assign(this.resizer.style,{height:"5px",width:"100%",backgroundColor:"#111",cursor:"ns-resize",userSelect:"none"}),this.resizer.addEventListener("mousedown",this.onDragStart.bind(this)),document.addEventListener("mousemove",this.onDrag.bind(this)),document.addEventListener("mouseup",this.onDragEnd.bind(this)),this.container.appendChild(this.resizer),this.header=document.createElement("div"),Object.assign(this.header.style,{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px",backgroundColor:"#000"});const t=document.createElement("div");t.style.display="flex",t.style.alignItems="center",t.style.gap="10px";const i=document.createElement("span");i.innerText="PineTS Script Editor ",i.style.color="white",t.appendChild(i);const s=document.createElement("div");s.style.display="flex",s.style.gap="10px";const n=document.createElement("button");n.innerText="Execute",Object.assign(n.style,hn,{backgroundColor:"#2A8D08"}),n.onmouseover=()=>{n.style.transform="scale(1.05)"},n.onmouseout=()=>{n.style.transform="scale(1)"},n.onclick=()=>{this.executePineTS()},s.appendChild(n);const o=document.createElement("div");Object.assign(o.style,{display:"inline-flex",border:"1px solid #0A42FA",borderRadius:"8px",overflow:"hidden",position:"relative"});const r=document.createElement("button");r.innerText="Save",Object.assign(r.style,hn,{backgroundColor:"#0A42FA",borderRadius:"0px"}),r.onmouseover=()=>{r.style.transform="scale(1.05)"},r.onmouseout=()=>{r.style.transform="scale(1)"},r.onclick=()=>{this.saveScript()},o.appendChild(r);const a=document.createElement("button");a.innerText="🛠",Object.assign(a.style,hn,{backgroundColor:"#0A42FA",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),a.onmouseover=()=>{a.style.transform="scale(1.05)"},a.onmouseout=()=>{a.style.transform="scale(1)"},a.onclick=e=>{const t=document.getElementById("save-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="save-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#0A42FA",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});const s=document.createElement("div");s.innerText="Save As",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=()=>{this.saveToFile(),i.remove()},i.appendChild(s);const n=o.getBoundingClientRect();i.style.left=n.left+"px",i.style.top=n.bottom+"px",document.body.appendChild(i)},o.appendChild(a),s.appendChild(o);const l=document.createElement("div");Object.assign(l.style,{display:"inline-flex",border:"1px solid #AC0202",borderRadius:"8px",overflow:"hidden",position:"relative"});const c=document.createElement("button");c.innerText="Script",Object.assign(c.style,hn,{backgroundColor:"#AC0202",borderRadius:"0px"}),c.onmouseover=()=>{c.style.transform="scale(1.05)"},c.onmouseout=()=>{c.style.transform="scale(1)"},c.onclick=()=>{console.log("Current script: "+c.innerText)},l.appendChild(c);const h=document.createElement("button");h.innerText="🗄",Object.assign(h.style,hn,{backgroundColor:"#AC0202",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),h.onmouseover=()=>{h.style.transform="scale(1.05)"},h.onmouseout=()=>{h.style.transform="scale(1)"},h.onclick=e=>{const t=document.getElementById("script-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="script-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#AC0202",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});Object.keys(this.scripts).forEach((e=>{const t=document.createElement("div");t.innerText=e,t.style.padding="5px 10px",t.style.cursor="pointer",t.onclick=()=>{this.scripts[e]&&this.scripts[e].code&&(this.setValue(this.scripts[e].code),c.innerText=e,console.log(`Loaded script "${e}" from memory.`)),i.remove()},i.appendChild(t)}));const s=document.createElement("div");s.innerText="Open...",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=()=>{this.openScriptFromFile(),i.remove()},i.appendChild(s);const n=l.getBoundingClientRect();i.style.left=n.left+"px",i.style.top=n.bottom+"px",document.body.appendChild(i)},l.appendChild(h),s.appendChild(l);const p=document.createElement("div");Object.assign(p.style,{display:"inline-flex",border:"1px solid #696969",borderRadius:"8px",overflow:"hidden",position:"relative"});const d=document.createElement("button");d.innerText="Select Main Series",Object.assign(d.style,hn,{backgroundColor:"#696969",borderRadius:"0px"}),d.onmouseover=()=>{d.style.transform="scale(1.05)"},d.onmouseout=()=>{d.style.transform="scale(1)"},d.onclick=e=>{this.populateMainSeriesSelectMenu(e,(e=>{this.selectedSeries=e,console.log("Selected Main Series:",e)}))},p.appendChild(d);const u=document.createElement("button");u.innerText="∿",Object.assign(u.style,hn,{backgroundColor:"#696969",borderLeft:"1px solid #fff",borderRadius:"0px",padding:"5px"}),u.onmouseover=()=>{u.style.transform="scale(1.05)"},u.onmouseout=()=>{u.style.transform="scale(1)"},u.onclick=e=>{const t=document.getElementById("series-dropdown");if(t)return void t.remove();const i=document.createElement("div");i.id="series-dropdown",Object.assign(i.style,{position:"absolute",backgroundColor:"#696969",color:"white",border:"1px solid #fff",borderRadius:"4px",marginTop:"5px",zIndex:"100000"});const s=document.createElement("div");s.innerText="Select Main Series",s.style.padding="5px 10px",s.style.cursor="pointer",s.onclick=e=>{this.populateMainSeriesSelectMenu(e,(e=>{this.selectedSeries=e,console.log("Selected Main Series:",e)})),i.remove()},i.appendChild(s);const n=document.createElement("div");n.innerText="Select Volume Series",n.style.padding="5px 10px",n.style.cursor="pointer",n.onclick=e=>{this.populateVolumeSeriesSelectMenu(e,(e=>{this.selectedVolumeSeries=e,console.log("Selected Volume Series:",e)})),i.remove()},i.appendChild(n);const o=p.getBoundingClientRect();i.style.left=o.left+"px",i.style.top=o.bottom+"px",document.body.appendChild(i)},p.appendChild(u),s.appendChild(p),t.appendChild(s),this.closeButton=document.createElement("button"),this.closeButton.innerText="Close",Object.assign(this.closeButton.style,hn,{backgroundColor:"#ff0000"}),this.closeButton.onmouseover=()=>{this.closeButton.style.transform="scale(1.05)"},this.closeButton.onmouseout=()=>{this.closeButton.style.transform="scale(1)"},this.closeButton.onclick=()=>this.close(),this.header.appendChild(t),this.header.appendChild(this.closeButton),this.container.appendChild(this.header),this.editorDiv=document.createElement("div"),Object.assign(this.editorDiv.style,{flex:"1",height:"calc(100% - 45px)"}),this.container.appendChild(this.editorDiv),document.body.appendChild(this.container),this.initializeMonaco(),this.loadInitialScript()}initializeMonaco(){let e="";if(this.handler.scriptsManager&&"function"==typeof this.handler.scriptsManager.getLast){const t=this.handler.scriptsManager.getLast();t&&t.code&&(e=t.code)}e||(e="\n\n\n// * @EsIstJosh\n// * This feature implements a variation of PineTS, source : and is \n// * licensed under the GNU AGPL v3.0. V\n// * The original AGPL license text is included in the AGPL_LICENSE file in the repository.\n// * \n// * Note: This file imports modules that remain under the MIT license \n// * The original MIT license text is included in the MIT_LICENSE file in the repository.\n// *\n// * For the full text of the GNU AGPL v3.0, see .\n\n\n// * //-----------------Work in Progress...-------------------//\n// * EXAMPLE SCRIPT CONVERSION // \n// * PINE SCRIPT ⥵ //PINE TS \n// * \n// * //@version=5 ⥵ // @version=5\n// * indicator('Simple EMA','EMA', overlay=true) ⥵ indicator('Simple EMA','EMA', {overlay=true}) \n// * ⥵ \n// * ema9 = ta.ema(close, 9); ⥵ const ema9 = ta.ema(close, 9) \n// * ema18 = ta.ema(close, 18); ⥵ const ema18 = ta.ema(close, 18)\n// * plot(ema9,'EMA9', color= #ff0000, linewidth= 2, style = plot.style_line) ⥵ plot(ema9,'EMA9',{ style: 'line', color: '#ff0000', linewidth: 2 })\n// * plot(ema18,'EMA18', color= #ff7700, linewidth= 2, style = plot.style_line) ⥵ plot(ema18,'EMA18',{ style: 'line', color: '#ff7700', linewidth: 2 })\n\n\n\n indicator('Title', 'TA', { overlay : true })\n // \n const ema1 = ta.ema(close,16)\n const ema2 = ta.ema(close,32)\n const ema3 = ta.ema(close,48)\n const ema4 = ta.ema(close,64)\n const ema5 = ta.ema(close,96)\n const ema6 = ta.ema(close,128)\n plot(ema1,'EMA1',{ style: 'line', color: '#ff0000', linewidth: 2 })\n plot(ema2,'EMA2',{ style: 'cross', color: '#ff7700', linewidth: 2 })\n plot(ema3,'EMA3',{ style: 'circles', color: '#ffee00', linewidth: 2 })\n plot(ema4,'EMA4',{ style: '❖', color: '#00ff00', linewidth: 2 })\n plot(ema5,'EMA5',{ style: 'triangleUp', color: '#0050ff', linewidth: 2 })\n plot(ema6,'EMA6',{ style: 'arrowDown', color: '#ffffff', linewidth: 2 })\n\n fill('EMA1','EMA2')\n fill('EMA2','EMA3')\n fill('EMA3','EMA4')\n fill('EMA4','EMA5')\n fill('EMA5','EMA6')\n\n\n "),this.editorInstance=o.editor.create(this.editorDiv,{value:e,language:"javascript",theme:"vs-dark",automaticLayout:!0}),console.log("Monaco Editor initialized in pane with initial code.")}loadInitialScript(){let e="";if(this.handler.scriptsManager&&"function"==typeof this.handler.scriptsManager.getLast){const t=this.handler.scriptsManager.getLast();t&&t.code&&(e=t.code)}e?(this.setValue(e),console.log("Loaded most recent script from scriptsManager.")):console.log("No saved scripts available in scriptsManager; editor value remains unchanged.")}open(){this.container.style.display="flex",this.editorInstance?.layout(),window.monaco=!0}close(){this.container.style.display="none",window.monaco=!1}setValue(e){this.editorInstance?.setValue(e)}getValue(){return this.editorInstance?.getValue()||""}async executePineTS(){try{const e=this.getValue(),t=/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m,i=e.match(t),s=i?.[2]?i[2].replace(/['"]/g,""):"defaultScript";console.log("Extracted script key:",s);const n=(this.selectedSeries??this.handler.series).options().title,o=(this.selectedVolumeSeries??this.handler.volumeSeries)?.options?.()?.title||"",r=function(e,t=[]){return e.map(((e,i)=>dn(e,t[i]))).filter((e=>null!==e))}([...(this.selectedSeries??this.handler.series).data()],[...this.selectedVolumeSeries?this.selectedVolumeSeries.data():[]]),a=new ns(r,this.handler.series.options().title,"1D"),l=`(context) => { \n \nconst { close, open, high, low, hlc3, volume, hl2, ohlc4 } = context.data;\nconst { plotchar, plot, na, indicator, nz, plotcandle, plotbar, fill} = context.core;\nconst ta = context.ta;\nconst math = context.math;\nconst input = context.input;\n\n${e}\n }`,{plots:c,candles:h,bars:p,fills:d,ta:u}=await a.run(l,void 0,!1);console.log("Plots:",c),console.log("Candles:",h),console.log("Bars:",p);let m=0;if(c)for(const e in c)if(c.hasOwnProperty(e)){Gs(this.handler,e,c[e],void 0,"overwrite");const t=c[e].data;if(Array.isArray(t)){const e=sn(t);e>m&&(m=e)}}if(h)for(const e in h)h.hasOwnProperty(e)&&Gs(this.handler,e,h[e],"Candlestick","overwrite");if(p)for(const e in p)p.hasOwnProperty(e)&&Gs(this.handler,e,p[e],"Bar","overwrite");if(d)for(const e in d)d.hasOwnProperty(e)&&Us(this.handler,d[e]);this.scripts[s]={pineTSInstance:a,ohlc:n,volume:o,code:e,n:m+1};this.handler.seriesMap.get(n);this.replaceScript(s)}catch(e){console.error("Error executing PineTS code:",e)}}replaceScript(e){const t=this.scripts[e];if(!t||!t.ohlc)return void console.warn(`No series information found for script key: ${e}`);const i=t.ohlc,s=this.handler.seriesMap.get(i);if(!s)return void console.warn(`Series with title "${i}" not found.`);const n=s.data().length;if(this._dataChangeHandlers.has(e))try{const t=this._dataChangeHandlers.get(e);s.unsubscribeDataChanged(t),console.log("Unsubscribing old Data Change Handler.... Data Length:",n),this._dataChangeHandlers.delete(e)}catch(t){console.warn(`Error unsubscribing from data changes for script "${e}":`,t)}const o=t=>{try{console.log("Data Changed, updating.... Data Length:",n),this.executeSavedScript(e)}catch(t){console.error(`Error executing saved script for "${e}":`,t)}};this._dataChangeHandlers.set(e,o),s.subscribeDataChanged(o)}async executeSavedScript(e){try{const t=this.scripts[e]?.ohlc,i=this.scripts[e]?.volume,s=this.scripts[e]?.n??void 0;console.log(s);const n=t?this.handler.seriesMap.get(t):null,o=i?this.handler.seriesMap.get(i):null;if(!n)return void console.warn(`Main series with title "${n}" not found.`);const r=dn(n.dataByIndex(n.data().length-1),o?o.dataByIndex(o.data().length-1):void 0),a=this.scripts[e]?.pineTSInstance;if(!a)return void console.warn(`No saved PineTS instance found for key: ${e}`);a.updateData(r);const{plots:l,candles:c,bars:h,fills:p,ta:d}=await a.run(void 0,s,!0);if(console.log("Plots:",l),console.log("Candles:",c),console.log("Bars:",h),l)for(const e in l)l.hasOwnProperty(e)&&Gs(this.handler,e,l[e],void 0,"update");if(c)for(const e in c)l.hasOwnProperty(e)&&Gs(this.handler,e,c[e],"Candlestick","update");if(h)for(const e in h)l.hasOwnProperty(e)&&Gs(this.handler,e,h[e],"Bar","update")}catch(e){console.error("Error executing PineTS code:",e)}}saveScript(e){const t=this.getValue(),i=t.match(/^(?!\s*\/\/)(?!\s*\*)(.*indicator\s*\(\s*['"]([^'"]+)['"])/m),s=i?.[2]?i[2].replace(/['"]/g,""):"defaultScript";this.scripts[s]?this.scripts[s].code=t:this.scripts[s]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:t,pineTSInstance:e??null,n:null},console.log(`Script "${s}" updated in memory.`);const n=this.scripts[s],o=JSON.stringify(n,null,2),r=`save_script_~_${s};;;${o}`;window.callbackFunction(r),console.log(`Script "${s}" sent via callback.`);const a=`save_script_~_cache;;;${o}`;window.callbackFunction(a),console.log('Cache script sent via callback under the name "cache".')}async saveToFile(e){const t=this.getValue(),i=prompt("Enter a new script name/title:","MyNewScript");if(!i)return void console.warn("Save To File canceled or no name provided.");this.scripts[i]={ohlc:(this.selectedSeries??this.handler.series).options().title,volume:(this.selectedVolumeSeries??this.handler.volumeSeries).options().title,code:t,pineTSInstance:e??null,n:null},console.log(`Script saved as "${i}" in memory.`);const s=JSON.stringify(this.scripts[i],null,2),n=`${i}.json`;this.downloadJson(s,n);const o=JSON.stringify(this.scripts[i],null,2);this.downloadJson(o,"cache.json")}openScriptFromFile(){const e=document.createElement("input");e.type="file",e.accept=".json",e.style.display="none",e.onchange=e=>{const t=e.target;if(t.files&&t.files.length>0){const e=t.files[0],i=new FileReader;i.onload=e=>{try{const t=e.target?.result;if("string"==typeof t){const e=JSON.parse(t);e&&e.code?(this.setValue(e.code),console.log("Loaded script from file.")):console.error("The selected file does not contain a valid script with a 'code' property.")}}catch(e){console.error("Error parsing JSON file:",e)}},i.readAsText(e)}},document.body.appendChild(e),e.click(),e.remove()}downloadJson(e,t){try{const i=new Blob([e],{type:"application/json"}),s=URL.createObjectURL(i),n=document.createElement("a");n.href=s,n.download=t,n.click(),URL.revokeObjectURL(s),console.log(`Downloaded ${t}`)}catch(e){console.error("Failed to download data: "+e)}}onDragStart(e){this.isResizing=!0,this.startY=e.clientY,this.startHeight=parseInt(window.getComputedStyle(this.container).height,10),e.preventDefault()}onDrag(e){if(!this.isResizing)return;const t=this.startHeight+(this.startY-e.clientY),i=Math.min(Math.max(t,this.MIN_HEIGHT),this.MAX_HEIGHT);this.container.style.height=`${i}px`,this.editorInstance?.layout()}onDragEnd(e){this.isResizing&&(this.isResizing=!1)}populateMainSeriesSelectMenu(e,t){const i=document.createElement("div");Object.assign(i.style,{position:"absolute",top:`${e.clientY}px`,left:`${e.clientX}px`,backgroundColor:"#333",color:"white",padding:"10px",borderRadius:"4px",zIndex:"100000"});const s=document.createElement("ul");Object.assign(s.style,{listStyle:"none",margin:"0",padding:"0"});const n=Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})));this.handler.volumeSeries&&n.push({label:"Volume",value:this.handler.volumeSeries}),n.forEach((e=>{const n=document.createElement("li");n.innerText=e.label,n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(e.value),document.body.removeChild(i)},s.appendChild(n)}));const o=document.createElement("li");o.innerText="Cancel",o.style.cursor="pointer",o.style.padding="5px",o.onclick=()=>{document.body.removeChild(i)},s.appendChild(o),i.appendChild(s),document.body.appendChild(i)}populateVolumeSeriesSelectMenu(e,t){const i=document.createElement("div");Object.assign(i.style,{position:"absolute",top:`${e.clientY}px`,left:`${e.clientX}px`,backgroundColor:"#333",color:"white",padding:"10px",borderRadius:"4px",zIndex:"100000"});const s=document.createElement("ul");Object.assign(s.style,{listStyle:"none",margin:"0",padding:"0"});const n=document.createElement("li");n.innerText="None",n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(null),document.body.removeChild(i)},s.appendChild(n);const o=Array.from(this.handler.seriesMap.entries()).map((([e,t])=>({label:e,value:t})));this.handler.volumeSeries&&o.push({label:"Volume",value:this.handler.volumeSeries}),o.forEach((e=>{const n=document.createElement("li");n.innerText=e.label,n.style.cursor="pointer",n.style.padding="5px",n.onclick=()=>{t(e.value),document.body.removeChild(i)},s.appendChild(n)}));const r=document.createElement("li");r.innerText="Cancel",r.style.cursor="pointer",r.style.padding="5px",r.onclick=()=>{document.body.removeChild(i)},s.appendChild(r),i.appendChild(s),document.body.appendChild(i)}}function dn(e,t){let i;return i="number"==typeof e.time?e.time:new Date(e.time).getTime(),isNaN(i)?(console.warn(`Invalid time format: ${e.time}`),null):{...e,openTime:i,closeTime:i+86399,volume:void 0!==e.volume?Number(e.volume):void 0!==t?Number(t.value):0}}class un{makeButton;callbackName;div;isOpen=!1;widget;constructor(e,t,i,s,n,o){this.makeButton=e,this.callbackName=o,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(i+" ↓",null,s,!0,n),this.updateMenuItems(t),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");let e=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";let t=e.x+e.width/2;this.div.style.left=t-this.div.clientWidth/2+"px",this.div.style.top=e.y+e.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(e){this.div.innerHTML="",e.forEach((e=>{let t=this.makeButton(e,null,!1,!1);t.elem.addEventListener("click",(()=>{this._clickHandler(t.elem.innerText)})),t.elem.style.margin="4px 4px",t.elem.style.padding="2px 2px",this.div.appendChild(t.elem)})),this.widget.elem.innerText=e[0]+" ↓"}_clickHandler(e){this.widget.elem.innerText=e+" ↓",window.callbackFunction(`${this.callbackName??"undefined"}_~_${e}`),this.div.style.display="none",this.isOpen=!1}}class mn{makeButton;div;isOpen=!1;widget;globalCallback;constructor(e,t,i,s,n,o,r){this.makeButton=e,this.globalCallback=r,this.div=document.createElement("div"),this.div.classList.add("topbar-menu"),this.widget=this.makeButton(i+" ↓",null,s,!0,n),this.updateMenuItems(t),this.widget.elem.addEventListener("click",(()=>{if(this.isOpen=!this.isOpen,!this.isOpen)return void(this.div.style.display="none");const e=this.widget.elem.getBoundingClientRect();this.div.style.display="flex",this.div.style.flexDirection="column";const t=e.x+e.width/2;this.div.style.left=t-this.div.clientWidth/2+"px",this.div.style.top=e.y+e.height+"px"})),document.body.appendChild(this.div)}updateMenuItems(e){this.div.innerHTML="",e.forEach((e=>{const t=this.makeButton(e.label,null,!1,!1);t.elem.addEventListener("click",(()=>{this._clickHandler(e)})),t.elem.style.margin="4px 4px",t.elem.style.padding="2px 2px",this.div.appendChild(t.elem)})),e.length>0&&(this.widget.elem.innerText=e[0].label+" ↓")}_clickHandler(e){this.widget.elem.innerText=e.label+" ↓",e.callback?e.callback():this.globalCallback?this.globalCallback(e.label):window.callbackFunction(`${e.label}`),this.div.style.display="none",this.isOpen=!1}}class gn{_handler;_div;left;right;codeEditor;constructor(e){this._handler=e,this._div=document.createElement("div"),this._div.classList.add("topbar");const t=e=>{const t=document.createElement("div");return t.classList.add("topbar-container"),t.style.justifyContent=e,this._div.appendChild(t),t};this.left=t("flex-start"),this.right=t("flex-end"),this.codeEditor=new pn(this._handler),this.makeChartMenu([{label:"Add Series",callback:()=>this.openCSVFile("add")},{label:"Edit Series",callback:()=>this.openCSVFile("edit")}],"Add Series",!0,"left"),this.makeButton("{}=> ƒ",!0,!0,"right",!1,void 0,(()=>this.codeEditor.open()))}makeSwitcher(e,t,i,s="left"){const n=document.createElement("div");let o;n.style.margin="4px 12px";const r={elem:n,callbackName:i,intervalElements:e.map((e=>{const i=document.createElement("button");i.classList.add("topbar-button"),i.classList.add("switcher-button"),i.style.margin="0px 2px",i.innerText=e,e==t&&(o=i,i.classList.add("active-switcher-button"));const s=gn.getClientWidth(i);return i.style.minWidth=s+1+"px",i.addEventListener("click",(()=>r.onItemClicked(i))),n.appendChild(i),i})),onItemClicked:e=>{e!=o&&(o.classList.remove("active-switcher-button"),e.classList.add("active-switcher-button"),o=e,window.callbackFunction(`${r.callbackName}_~_${e.innerText}`))}};return this.appendWidget(n,s,!0),r}makeTextBoxWidget(e,t="left",i=void 0){if(i&&"string"==typeof i){const s=document.createElement("input");return s.classList.add("topbar-textbox-input"),s.value=e,s.style.width=`${s.value.length+2}ch`,s.addEventListener("focus",(()=>{window.textBoxFocused=!0})),s.addEventListener("input",(e=>{e.preventDefault(),s.style.width=`${s.value.length+2}ch`})),s.addEventListener("keydown",(e=>{"Enter"==e.key&&(e.preventDefault(),s.blur())})),s.addEventListener("blur",(()=>{window.callbackFunction(`${i}_~_${s.value}`),window.textBoxFocused=!1})),this.appendWidget(s,t,!0),s}{const i=document.createElement("div");return i.classList.add("topbar-textbox"),i.innerText=e,this.appendWidget(i,t,!0),i}}makeMenu(e,t,i,s,n){return new un(this.makeButton.bind(this),e,t,i,s,n)}makeChartMenu(e,t,i,s,n,o){return new mn(this.makeButton.bind(this),e,t,i,s,n,o)}makeButton(e,t,i=!0,s="left",n=!1,o,r){let a=document.createElement("button");a.classList.add("topbar-button"),a.innerText=e,document.body.appendChild(a),a.style.minWidth=`${a.clientWidth+1}px`,document.body.removeChild(a);let l=!1;return a.addEventListener("click",(()=>{n?(l=!l,a.style.backgroundColor=l?"var(--active-bg-color)":"",a.style.color=l?"var(--active-color)":"",o&&window.callbackFunction(`${o}_~_${l}`)):o&&window.callbackFunction(`${o}_~_${a.innerText}`),r&&r()})),i&&this.appendWidget(a,s,t),{elem:a,callbackName:o}}makeSliderWidget(e,t,i,s,n,o="left"){const r=document.createElement("div");r.classList.add("topbar-slider-container"),r.style.display="flex",r.style.alignItems="center",r.style.margin="4px 12px";const a=document.createElement("span");a.classList.add("topbar-slider-label"),a.style.marginRight="8px",a.innerText=s.toString();const l=document.createElement("input");return l.classList.add("topbar-slider"),l.type="range",l.min=e.toString(),l.max=t.toString(),l.step=i.toString(),l.value=s.toString(),l.style.cursor="pointer",l.addEventListener("input",(()=>{a.innerText=l.value,window.callbackFunction(`${n}_~_${l.value}`)})),r.appendChild(a),r.appendChild(l),this.appendWidget(r,o,!0),r}makeSeparator(e="left"){const t=document.createElement("div");t.classList.add("topbar-seperator");("left"==e?this.left:this.right).appendChild(t)}appendWidget(e,t,i){const s="left"==t?this.left:this.right;i?("left"==t&&s.appendChild(e),this.makeSeparator(t),"right"==t&&s.appendChild(e)):s.appendChild(e),this._handler.reSize()}openCSVFile(e){const t=document.createElement("input");t.type="file",t.accept=".csv",t.style.display="none",t.addEventListener("change",(t=>{const i=t.target;if(i.files&&i.files.length>0){const t=i.files[0],s=new FileReader;s.onload=i=>{const s=i.target?.result,n=this.parseCSV(s);if(0===n.length)return void alert("The CSV file is empty.");const o=["time","open","high","low","close"],r=Object.keys(n[0]);if(o.every((e=>r.includes(e))))try{if("edit"===e)this._handler.series.setData(n),console.log("Series data updated successfully.");else if("add"===e){const e=t.name.replace(/\.[^/.]+$/,"");this._handler.createCustomOHLCSeries(e,{}).series.setData(n),console.log("New series added successfully.")}}catch(e){console.error("Error updating chart data:",e)}else alert("The selected CSV does not contain all required OHLCV columns: "+o.join(", "))},s.readAsText(t)}})),document.body.appendChild(t),t.click(),document.body.removeChild(t)}parseCSV(e){const t=e.split(/\r?\n/).filter((e=>e.trim().length>0));if(0===t.length)return[];let i=t[0].split(",").map((e=>e.trim()));const s=i.map((e=>e.toLowerCase()));if(!s.includes("time"))if(s.includes("date")){const e=s.indexOf("date");i[e]="time"}else i[0]="time";return t.slice(1).map((e=>{const t=e.split(",").map((e=>e.trim())),s={};return i.forEach(((e,i)=>{const n=Number(t[i]);s[e]=isNaN(n)?t[i]:n})),s}))}static getClientWidth(e){document.body.appendChild(e);const t=e.clientWidth;return document.body.removeChild(e),t}}const fn={title:"",followMode:"tracking",horizontalDeadzoneWidth:45,verticalDeadzoneHeight:100,verticalSpacing:20,topOffset:20};class yn{_chart;_element;_titleElement;_priceElement;_dateElement;_timeElement;_options;_lastTooltipWidth=null;constructor(e,t){this._options={...fn,...t},this._chart=e;const i=document.createElement("div");vn(i,{display:"flex","flex-direction":"column","align-items":"center",position:"absolute",transform:"translate(calc(0px - 50%), 0px)",opacity:"0",left:"0%",top:"0","z-index":"100","background-color":"white","border-radius":"4px",padding:"5px 10px","font-family":"-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif","font-size":"12px","font-weight":"400","box-shadow":"0px 2px 4px rgba(0, 0, 0, 0.2)","line-height":"16px","pointer-events":"none",color:"#131722"});const s=document.createElement("div");vn(s,{"font-size":"12px","line-height":"24px","font-weight":"590"}),bn(s,this._options.title),i.appendChild(s);const n=document.createElement("div");vn(n,{"font-size":"12px","line-height":"18px","font-weight":"590"}),bn(n,""),i.appendChild(n);const o=document.createElement("div");vn(o,{color:"#787B86"}),bn(o,""),i.appendChild(o);const r=document.createElement("div");vn(r,{color:"#787B86"}),bn(r,""),i.appendChild(r),this._element=i,this._titleElement=s,this._priceElement=n,this._dateElement=o,this._timeElement=r;const a=this._chart.chartElement();a.appendChild(this._element);const l=a.parentElement;if(!l)return void console.error("Chart Element is not attached to the page.");const c=getComputedStyle(l).position;"relative"!==c&&"absolute"!==c&&console.error("Chart Element position is expected be `relative` or `absolute`.")}destroy(){this._chart&&this._element&&this._chart.chartElement().removeChild(this._element)}applyOptions(e){this._options={...this._options,...e}}options(){return this._options}updateTooltipContent(e){if(!this._element)return void console.warn("Tooltip element not found.");const t=this._element.getBoundingClientRect();this._lastTooltipWidth=t.width,void 0!==e.title&&this._titleElement?(console.log(`Setting title: ${e.title}`),bn(this._titleElement,e.title)):console.warn("Title element is missing or title data is undefined."),bn(this._priceElement,e.price),bn(this._dateElement,e.date),bn(this._timeElement,e.time)}updatePosition(e){if(!this._chart||!this._element)return;if(this._element.style.opacity=e.visible?"1":"0",!e.visible)return;const t=this._calculateXPosition(e,this._chart),i=this._calculateYPosition(e);this._element.style.transform=`translate(${t}, ${i})`}_calculateXPosition(e,t){const i=e.paneX+t.priceScale("left").width(),s=this._lastTooltipWidth?Math.ceil(this._lastTooltipWidth/2):this._options.horizontalDeadzoneWidth;return`calc(${Math.min(Math.max(s,i),t.timeScale().width()-s)}px - 50%)`}_calculateYPosition(e){if("top"==this._options.followMode)return`${this._options.topOffset}px`;const t=e.paneY,i=t<=this._options.verticalSpacing+this._options.verticalDeadzoneHeight;return`calc(${t+(i?1:-1)*this._options.verticalSpacing}px${i?"":" - 100%"})`}}function bn(e,t){e&&t!==e.innerText&&(e.innerText=t,e.style.display=t?"block":"none")}function vn(e,t){for(const[i,s]of Object.entries(t))e.style.setProperty(i,s)}function xn(e,t,i=1,s){const n=Math.round(t*e),o=Math.round(i*t),r=function(e){return Math.floor(.5*e)}(o);return{position:n-r,length:o}}class _n{_data;constructor(e){this._data=e}draw(e){this._data.visible&&e.useBitmapCoordinateSpace((e=>{const t=e.context,i=xn(this._data.x,e.horizontalPixelRatio,1);t.fillStyle=this._data.color,t.fillRect(i.position,this._data.topMargin*e.verticalPixelRatio,i.length,e.bitmapSize.height)}))}}class wn{_data;constructor(e){this._data=e}update(e){this._data=e}renderer(){return new _n(this._data)}zOrder(){return"bottom"}}const Cn={lineColor:"rgba(0, 0, 0, 0.2)",priceExtractor:e=>void 0!==e.value?e.value.toFixed(2):void 0!==e.close?e.close.toFixed(2):""};class Sn{_options;_tooltip=void 0;_paneViews;_data={x:0,visible:!1,color:"rgba(0, 0, 0, 0.2)",topMargin:0};_attachedParams;constructor(e){this._options={...Cn,...e},this._data.color=this._options.lineColor,this._paneViews=[new wn(this._data)]}attached(e){this._attachedParams=e;const t=this.series();if(t){const e=t.options(),i=e.lineColor||e.color||"rgba(0,0,0,0.2)";this._options.autoColor&&this.applyOptions({lineColor:i})}this._setCrosshairMode(),e.chart.subscribeCrosshairMove(this._moveHandler),this._createTooltipElement()}detached(){const e=this.chart();e&&e.unsubscribeCrosshairMove(this._moveHandler),this._hideCrosshair(),this._hideTooltip()}paneViews(){return this._paneViews}updateAllViews(){this._paneViews.forEach((e=>e.update(this._data)))}setData(e){this._data=e,this.updateAllViews(),this._attachedParams?.requestUpdate()}currentColor(){return this._options.lineColor}chart(){return this._attachedParams?.chart}series(){return this._attachedParams?.series}applyOptions(e){this._options={...this._options,...e},e.lineColor&&this.setData({...this._data,color:e.lineColor}),this._tooltip&&this._tooltip.applyOptions({...this._options.tooltip}),this._attachedParams?.requestUpdate()}_setCrosshairMode(){const e=this.chart();if(!e)throw new Error("Unable to change crosshair mode because the chart instance is undefined");e.applyOptions({crosshair:{mode:t.CrosshairMode.Magnet,vertLine:{visible:!1,labelVisible:!1},horzLine:{visible:!1,labelVisible:!1}}})}_moveHandler=e=>this._onMouseMove(e);switch(e){if(this.series()===e)return void console.log("Tooltip is already attached to this series.");this._hideCrosshair(),e.attachPrimitive(this,"Tooltip",!0,!1);const t=e.options(),i=t.lineColor||t.color||"rgba(0,0,0,0.2)";this._options.autoColor&&this.applyOptions({lineColor:i}),console.log("Switched tooltip to the new series.")}_hideCrosshair(){this._hideTooltip(),this.setData({x:0,visible:!1,color:this._options.lineColor,topMargin:0})}_hideTooltip(){this._tooltip&&(this._tooltip.updateTooltipContent({title:"",price:"",date:"",time:""}),this._tooltip.updatePosition({paneX:0,paneY:0,visible:!1}))}_onMouseMove(e){const t=this.chart(),i=this.series(),s=e.logical;if(!s||!t||!i)return void this._hideCrosshair();const n=e.seriesData.get(i);if(!n)return void this._hideCrosshair();const o=this._options.priceExtractor(n),r=t.timeScale().logicalToCoordinate(s),[a,l]=function(e){if(!e)return["",""];const t=new Date(e),i=t.getFullYear(),s=t.toLocaleString("default",{month:"short"});return[`${t.getDate().toString().padStart(2,"0")} ${s} ${i}`,`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}`]}(e.time?As(e.time):void 0);if(this._tooltip){const t=i.options()?.title||"Unknown Series",s=this._tooltip.options(),n="top"===s.followMode?s.topOffset+10:0;this.setData({x:r??0,visible:null!==r,color:this._options.lineColor,topMargin:n}),this._tooltip.updateTooltipContent({title:t,price:o,date:a,time:l}),this._tooltip.updatePosition({paneX:e.point?.x??0,paneY:e.point?.y??0,visible:!0})}}_createTooltipElement(){const e=this.chart();if(!e)throw new Error("Unable to create Tooltip element. Chart not attached");this._tooltip=new yn(e,{...this._options.tooltip})}}let kn=class e{colorOption;static colors=["#EBB0B0","#E9CEA1","#E5DF80","#ADEB97","#A3C3EA","#D8BDED","#E15F5D","#E1B45F","#E2D947","#4BE940","#639AE1","#D7A0E8","#E42C2A","#E49D30","#E7D827","#3CFF0A","#3275E4","#B06CE3","#F3000D","#EE9A14","#F1DA13","#2DFC0F","#1562EE","#BB00EF","#B50911","#E3860E","#D2BD11","#48DE0E","#1455B4","#6E009F","#7C1713","#B76B12","#8D7A13","#479C12","#165579","#51007E"];_div;saveDrawings;opacity=0;_opacitySlider;_opacityLabel;rgba;constructor(t,i){this.colorOption=i,this.saveDrawings=t,this._div=document.createElement("div"),this._div.classList.add("color-picker");let s=document.createElement("div");s.style.margin="10px",s.style.display="flex",s.style.flexWrap="wrap",e.colors.forEach((e=>s.appendChild(this.makeColorBox(e))));let n=document.createElement("div");n.style.backgroundColor=window.pane.borderColor,n.style.height="1px",n.style.width="130px";let o=document.createElement("div");o.style.margin="10px";let r=document.createElement("div");r.style.color="lightgray",r.style.fontSize="12px",r.innerText="Opacity",this._opacityLabel=document.createElement("div"),this._opacityLabel.style.color="lightgray",this._opacityLabel.style.fontSize="12px",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%",this._opacitySlider.oninput=()=>{this._opacityLabel.innerText=this._opacitySlider.value+"%",this.opacity=parseInt(this._opacitySlider.value)/100,this.updateColor()},o.appendChild(r),o.appendChild(this._opacitySlider),o.appendChild(this._opacityLabel),this._div.appendChild(s),this._div.appendChild(n),this._div.appendChild(o),window.containerDiv.appendChild(this._div)}_updateOpacitySlider(){this._opacitySlider.value=(100*this.opacity).toString(),this._opacityLabel.innerText=this._opacitySlider.value+"%"}makeColorBox(t){const i=document.createElement("div");i.style.width="18px",i.style.height="18px",i.style.borderRadius="3px",i.style.margin="3px",i.style.boxSizing="border-box",i.style.backgroundColor=t,i.addEventListener("mouseover",(()=>i.style.border="2px solid lightgray")),i.addEventListener("mouseout",(()=>i.style.border="none"));const s=e.extractRGBA(t);return i.addEventListener("click",(()=>{this.rgba=s,this.updateColor()})),i}static extractRGBA(e){const t=document.createElement("div");t.style.color=e,document.body.appendChild(t);const i=getComputedStyle(t).color;document.body.removeChild(t);const s=i.match(/\d+/g)?.map(Number);if(!s)return[];let n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],n]}updateColor(){if(!O.lastHoveredObject||!this.rgba)return;const e=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`;O.lastHoveredObject.applyOptions({[this.colorOption]:e}),this.saveDrawings()}openMenu(t){O.lastHoveredObject&&(this.rgba=e.extractRGBA(O.lastHoveredObject._options[this.colorOption]),this.opacity=this.rgba[3],this._updateOpacitySlider(),this._div.style.top=t.top-30+"px",this._div.style.left=t.right+"px",this._div.style.display="flex",setTimeout((()=>document.addEventListener("mousedown",(e=>{this._div.contains(e.target)||this.closeMenu()}))),10))}closeMenu(){document.body.removeEventListener("click",this.closeMenu),this._div.style.display="none"}};class En{container;_opacitySlider;_opacity_label;exitButton;color="#ff0000";rgba;opacity;applySelection;customColors;constructor(e,t,i){this.applySelection=t,this.rgba=En.extractRGBA(e),this.opacity=this.rgba[3],this.container=document.createElement("div"),this.container.classList.add("color-picker"),this.container.style.display="flex",this.container.style.flexDirection="column",this.container.style.width="200px",this.container.style.height="350px",this.container.style.position="relative";const s=this.createColorGrid(),n=this.createOpacityUI();this.exitButton=this.createExitButton(),this.customColors=i??void 0,this.container.appendChild(s),this.container.appendChild(this.createSeparator()),this.customColors&&0!==this.customColors.length&&this.createCustomColorSection(),this.container.appendChild(this.createSeparator()),this.container.appendChild(n),this.container.appendChild(this.exitButton)}createCustomColorSection(){if(!this.customColors||0===this.customColors.length)return null;const e=document.createElement("div");e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="center",e.style.margin="8px 0";const t=document.createElement("div");t.innerText="Custom Colors",t.style.fontSize="14px",t.style.color="white",e.appendChild(t);const i=document.createElement("div");i.style.display="flex",i.style.flexWrap="wrap",i.style.justifyContent="center",i.style.gap="5px";const s=e=>{const t=document.createElement("div");return t.style.width="20px",t.style.height="20px",t.style.borderRadius="4px",t.style.cursor="pointer",t.style.border="1px solid #999",t.style.backgroundColor=e,t.title=e,t.addEventListener("click",(()=>{this.updateTargetColor()})),t};this.customColors.forEach((e=>{i.appendChild(s(e))}));const n=document.createElement("div");return n.style.width="20px",n.style.height="20px",n.style.borderRadius="4px",n.style.cursor="pointer",n.style.border="1px solid #999",n.style.backgroundColor="rgba(0,0,0,0)",n.style.display="flex",n.style.justifyContent="center",n.style.alignItems="center",n.style.color="#999",n.style.fontSize="16px",n.innerText="+",n.title="Add custom color",n.addEventListener("click",(e=>{const t=document.createElement("input");t.type="color",t.value=this.color,t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t),t.addEventListener("input",(()=>{this.color=t.value,this.updateTargetColor(),this.customColors.includes(this.color)||(this.customColors.push(this.color),i.appendChild(s(this.color)),this.saveColors()),document.body.removeChild(t)}),{once:!0}),t.click()})),i.appendChild(n),e.appendChild(i),e}saveColors(){const e=`save_defaults_colors_~_${JSON.stringify(this.customColors,null,2)}`;window.callbackFunction(e)}createExitButton(){const e=document.createElement("div");return e.innerText="✕",e.title="Close",e.style.position="absolute",e.style.bottom="5px",e.style.right="5px",e.style.width="20px",e.style.height="20px",e.style.cursor="pointer",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center",e.style.fontSize="16px",e.style.backgroundColor="#ccc",e.style.borderRadius="50%",e.style.color="#000",e.style.boxShadow="0 1px 3px rgba(0,0,0,0.3)",e.addEventListener("mouseover",(()=>{e.style.backgroundColor="#e74c3c",e.style.color="#fff"})),e.addEventListener("mouseout",(()=>{e.style.backgroundColor="#ccc",e.style.color="#000"})),e.addEventListener("click",(()=>{this.closeMenu()})),e}createColorGrid(){const e=document.createElement("div");e.style.display="grid",e.style.gridTemplateColumns="repeat(7, 1fr)",e.style.gap="5px",e.style.overflowY="auto",e.style.flex="1";return En.generateFullSpectrumColors(9).forEach((t=>{const i=this.createColorBox(t);e.appendChild(i)})),e}createColorBox(e){const t=document.createElement("div");return t.style.aspectRatio="1",t.style.borderRadius="6px",t.style.backgroundColor=e,t.style.cursor="pointer",t.addEventListener("click",(()=>{this.rgba=En.extractRGBA(e),this.updateTargetColor()})),t}static generateFullSpectrumColors(e){const t=[];for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(255, ${i}, 0, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(${i}, 255, 0, 1)`);for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(0, 255, ${i}, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(0, ${i}, 255, 1)`);for(let i=0;i<=255;i+=Math.floor(255/e))t.push(`rgba(${i}, 0, 255, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(255, 0, ${i}, 1)`);for(let i=255;i>=0;i-=Math.floor(255/e))t.push(`rgba(${i}, ${i}, ${i}, 1)`);return t}createOpacityUI(){const e=document.createElement("div");e.style.margin="10px",e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="center";const t=document.createElement("div");return t.style.color="lightgray",t.style.fontSize="12px",t.innerText="Opacity",this._opacitySlider=document.createElement("input"),this._opacitySlider.type="range",this._opacitySlider.min="0",this._opacitySlider.max="100",this._opacitySlider.value=(100*this.opacity).toString(),this._opacitySlider.style.width="80%",this._opacity_label=document.createElement("div"),this._opacity_label.style.color="lightgray",this._opacity_label.style.fontSize="12px",this._opacity_label.innerText=`${this._opacitySlider.value}%`,this._opacitySlider.oninput=()=>{this._opacity_label.innerText=`${this._opacitySlider.value}%`,this.opacity=parseInt(this._opacitySlider.value)/100,this.updateTargetColor()},e.appendChild(t),e.appendChild(this._opacitySlider),e.appendChild(this._opacity_label),e}createSeparator(){const e=document.createElement("div");return e.style.height="1px",e.style.width="100%",e.style.backgroundColor="#ccc",e.style.margin="5px 0",e}openMenu(e,t,i){this.applySelection=i,this.container.style.display="block",document.body.appendChild(this.container);const s=this.container.offsetWidth||150,n=this.container.offsetHeight||250,o=e.clientX,r=e.clientY,a=window.innerWidth,l=window.innerHeight;let c=o+t;const h=c+s>a?o-s:c,p=r+n>l?l-n-10:r;this.container.style.left=`${h}px`,this.container.style.top=`${p}px`,this.container.style.display="flex",this.container.style.position="absolute",this.exitButton.style.bottom="5px",this.exitButton.style.right="5px";const d=e=>{const t=this.container.getBoundingClientRect(),i=t.left-s,o=t.right+s,r=t.top-n,a=t.bottom+n;(e.clientXo||e.clientYa)&&(this.closeMenu(),document.removeEventListener("mousemove",d))};this.container.addEventListener("mouseenter",(()=>{document.addEventListener("mousemove",d)})),this.container.addEventListener("mouseleave",(()=>{document.removeEventListener("mousemove",d),this.closeMenu()})),document.addEventListener("mousedown",this._handleOutsideClick.bind(this),{once:!0})}closeMenu(){this.container.style.display="none",document.removeEventListener("mousedown",this._handleOutsideClick)}_handleOutsideClick(e){this.container.contains(e.target)||this.closeMenu()}static extractRGBA(e){const t=document.createElement("div");t.style.color=e,document.body.appendChild(t);const i=getComputedStyle(t).color;document.body.removeChild(t);const s=i.match(/\d+/g)?.map(Number)||[0,0,0],n=i.includes("rgba")?parseFloat(i.split(",")[3]):1;return[s[0],s[1],s[2],n]}getElement(){return this.container}update(e,t){this.rgba=En.extractRGBA(e),this.opacity=this.rgba[3],this.applySelection=t,this.updateTargetColor()}updateTargetColor(){this.color=`rgba(${this.rgba[0]}, ${this.rgba[1]}, ${this.rgba[2]}, ${this.opacity})`,this.applySelection(this.color)}}class Mn{static _styles=[{name:"Solid",var:t.LineStyle.Solid},{name:"Dotted",var:t.LineStyle.Dotted},{name:"Dashed",var:t.LineStyle.Dashed},{name:"Large Dashed",var:t.LineStyle.LargeDashed},{name:"Sparse Dotted",var:t.LineStyle.SparseDotted}];_div;_saveDrawings;constructor(e){this._saveDrawings=e,this._div=document.createElement("div"),this._div.classList.add("context-menu"),Mn._styles.forEach((e=>{this._div.appendChild(this._makeTextBox(e.name,e.var))})),window.containerDiv.appendChild(this._div)}_makeTextBox(e,t){const i=document.createElement("span");return i.classList.add("context-menu-item"),i.innerText=e,i.addEventListener("click",(()=>{O.lastHoveredObject?.applyOptions({lineStyle:t}),this._saveDrawings()})),i}openMenu(e){this._div.style.top=e.top-30+"px",this._div.style.left=e.right+"px",this._div.style.display="block",setTimeout((()=>document.addEventListener("mousedown",(e=>{this._div.contains(e.target)||this.closeMenu()}))),10)}closeMenu(){document.removeEventListener("click",this.closeMenu),this._div.style.display="none"}}const Pn={visible:!0,sections:0,upColor:void 0,downColor:void 0,borderUpColor:void 0,borderDownColor:void 0,rightSide:!0,width:0,lineColor:"#ffffff",lineStyle:t.LineStyle.Solid,drawGrid:!0,gridWidth:1,gridColor:"rgba(255, 255, 255, 0.125)",gridLineStyle:t.LineStyle.SparseDotted};class Tn extends a{p1;p2;_listeners=[];visibleRange=null;_originalData;_currentSlice=null;_vpData;_paneViews;_options;_pendingUpdate=!1;_state=N.NONE;_latestHoverPoint=null;_startDragPoint=null;static _mouseIsDown=!1;_hovered=!1;chart_;series_;constructor(e,t=Pn,i,s){super(),this.chart_=e.chart,this.series_=e.series;const n=this.series_.data(),o=e.volumeSeries.data(),r=this.chart_.timeScale();this.visibleRange=r.getVisibleLogicalRange(),i&&s?(this.p1=i,this.p2=s):(this.p1={time:null,logical:this.visibleRange?.from??0,price:0},this.p2={time:null,logical:this.visibleRange?.to??this.series.data().length-1,price:0}),this._options={...Pn,...t},o.length>0&&o.every((e=>"value"in e))?this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:o[t]?.value||0}))):(console.warn('[ProfileProcessor] volumeData is empty or missing "value" property.'),this._originalData=n.map(((e,t)=>({...e,x1:t,x2:t,volume:0})))),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this._paneViews=[new In(this)],this._subscribeEvents(),this.update()}_handleDomMouseDown=()=>{};_handleDomMouseUp=()=>{this._onMouseUp()};_subscribe(e,t){document.addEventListener(e,t),this._listeners.push({name:e,listener:t})}_unsubscribe(e,t){document.removeEventListener(e,t);const i=this._listeners.findIndex((i=>i.name===e&&i.listener===t));-1!==i&&this._listeners.splice(i,1)}_subscribeEvents(){this.p1&&this.p2&&this.p1.time&&this.p2.time?(this.chart_.subscribeCrosshairMove(this._handleMouseMove),this.chart_.subscribeClick(this._handleMouseDownOrUp),this._listeners.push({name:"crosshairMove",listener:this._handleMouseMove},{name:"click",listener:this._handleMouseDownOrUp})):(this.chart_.timeScale().subscribeVisibleLogicalRangeChange(this._handleVisibleLogicalRangeChange),this._listeners.push({name:"visibleLogicalRangeChange",listener:this._handleVisibleLogicalRangeChange}))}_handleVisibleLogicalRangeChange=()=>{const e=this.chart_.timeScale();if(this.visibleRange=e.getVisibleLogicalRange(),!this.visibleRange||!this.series_)return void console.warn("[VolumeProfile] Visible range or source series is undefined.");this.p1={time:null,logical:this.visibleRange.from??0,price:0},this.p2={time:null,logical:this.visibleRange.to??this.series_.data().length-1,price:0},this.sliceData();const t=this.calculateVolumeProfile();t?(this._vpData=t,this.updateAllViews(),this.requestUpdate()):console.warn("[VolumeProfile] Failed to process Volume Profile data on visible range change.")};_handleMouseMove=e=>{const t=this._eventToPoint(e);this._latestHoverPoint=t,Tn._mouseIsDown?this._handleDragInteraction(e):this._mouseIsOverPointCanvas(e,1)||this._mouseIsOverPointCanvas(e,2)?this._state===N.NONE&&this._moveToState(N.HOVERING):this._state!==N.NONE&&this._moveToState(N.NONE)};_handleMouseDownOrUp=()=>{Tn._mouseIsDown=!Tn._mouseIsDown,Tn._mouseIsDown?this._onMouseDown():this._onMouseUp(),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()};_onMouseDown(){if(this._startDragPoint=this._latestHoverPoint,!this._startDragPoint||!this.p1||!this.p2)return;const e=this._mouseIsOverPointRaw(this._startDragPoint,this.p1),t=this._mouseIsOverPointRaw(this._startDragPoint,this.p2);e?this._moveToState(N.DRAGGINGP1):t?this._moveToState(N.DRAGGINGP2):this._moveToState(N.DRAGGING)}_onMouseUp(){Tn._mouseIsDown=!1,this._startDragPoint=null,this._moveToState(N.HOVERING),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_handleDragInteraction(e){if(this._state!==N.DRAGGING&&this._state!==N.DRAGGINGP1&&this._state!==N.DRAGGINGP2)return;const t=this._eventToPoint(e);if(!t||!this._startDragPoint)return;const i={logical:t.logical-this._startDragPoint.logical,price:t.price-this._startDragPoint.price};this._onDrag(i),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update(),this._startDragPoint=t}_onDrag(e){this.p1&&this.p2&&(this._state===N.DRAGGING?(this._addDiffToPoint(this.p1,e.logical,e.price),this._addDiffToPoint(this.p2,e.logical,e.price)):this._state===N.DRAGGINGP1?this._addDiffToPoint(this.p1,e.logical,e.price):this._state===N.DRAGGINGP2&&this._addDiffToPoint(this.p2,e.logical,e.price),this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update())}_addDiffToPoint(e,t,i){e.logical=e.logical+t,e.price=e.price+i}_mouseIsOverPointRaw(e,t){if(!e)return!1;return Math.abs(e.logical-t.logical)<1&&Math.abs(e.price-t.price)<1}_mouseIsOverPointCanvas(e,t){if(!e.point||!this.p1||!this.p2)return!1;const i=Ws(1===t?this.p1:this.p2,this.chart_,this.series_),s=e.point.x-i.x,n=e.point.y-i.y;return s*s+n*n<100}_moveToState(e){switch(e){case N.NONE:document.body.style.cursor="default",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case N.HOVERING:document.body.style.cursor="pointer",this._hovered=!0,this._subscribe("mousedown",this._handleDomMouseDown),this._unsubscribe("mouseup",this._handleDomMouseUp);break;case N.DRAGGING:case N.DRAGGINGP1:case N.DRAGGINGP2:document.body.style.cursor="grabbing",this._hovered=!1,this._unsubscribe("mousedown",this._handleDomMouseDown),this._subscribe("mouseup",this._handleDomMouseUp)}this._state=e,this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}_eventToPoint(e){if(!e.point||null==e.logical)return null;const t=this.series_.coordinateToPrice(e.point.y);return null==t?null:{time:e.time??null,logical:e.logical,price:t.valueOf()}}sliceData(){if(!this.p1||!this.p2)return;const e=Math.min(this.p1.logical,this.p2.logical),t=Math.max(this.p1.logical,this.p2.logical);this._currentSlice=this._originalData.slice(Math.max(0,e),Math.min(t+1,this._originalData.length-1))}calculateDynamicSections(e,t,i){if(e<=0||i<=t)return 10;const s=e/20,n=(i-t)/5,o=2*Math.max(1,Math.floor(Math.max(s,n)));return Math.max(5,o)}calculateVolumeProfile(){const e=Math.min(this.visibleRange.to,this._originalData.length-1)-Math.max(this.visibleRange.from,0);let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;const s=[];let n;if(this._currentSlice&&this._currentSlice.length>0){for(const e of this._currentSlice){const s=e.close??e.open;void 0!==s&&(t=Math.min(t,s),i=Math.max(i,s))}t!==Number.POSITIVE_INFINITY&&i!==Number.NEGATIVE_INFINITY||(t=0,i=1);let o=void 0!==this._options.sections&&this._options.sections>0?this._options.sections:this.calculateDynamicSections(e,t,i);const r=(i===t?1:i-t)/o;for(let e=0;e=i&&t=(e.open??0),i=e.volume||0;t?o+=i:a+=i}}const c=o>=a,h=c?this._options.upColor??l(this.series_.options().upColor,.1)??"rgba(0,128,0,0.1)":this._options.downColor??l(this.series_.options().downColor,.1)??"rgba(128,0,0,0.1)",p=c?this._options.borderUpColor??l(this.series_.options().upColor,.5)??"rgba(0,128,0,0.66)":this._options.borderDownColor??l(this.series_.options().downColor,.5)??"rgba(128,0,0,0.66)";s.push({price:i,upData:o,downData:a,color:this._options.visible?h:"rgba(0,0,0,0)",borderColor:this._options.visible?p:"rgba(0,0,0,0)",minPrice:i,maxPrice:n})}n=this._options.rightSide?this._currentSlice[this._currentSlice.length-1].time:this._currentSlice[0].time}else n=Date.now().toString();return this.update(),{time:n,profile:s,width:this._options.width??20,visibleRange:this.visibleRange}}update(){this._pendingUpdate||(this._pendingUpdate=!0,requestAnimationFrame((()=>{super.requestUpdate(),this.updateAllViews(),console.log("VolumeProfile updated p1=",this.p1,"p2=",this.p2),this._pendingUpdate=!1})))}updateAllViews(){this._paneViews.forEach((e=>e.update()))}paneViews(){return this._paneViews}autoscaleInfo(){return this._vpData.profile.length?{priceRange:{minValue:this._vpData.profile[0].minPrice,maxValue:this._vpData.profile[this._vpData.profile.length-1].maxPrice}}:null}applyOptions(e){this._options={...this._options,...e},this.sliceData(),this._vpData=this.calculateVolumeProfile(),this.update()}}class In{_source;_x=null;_width=0;_items=[];_maxVolume;visibleRange=null;_p1={x:null,y:null};_p2={x:null,y:null};constructor(e){this._source=e,this._maxVolume=this._source._vpData.profile.reduce(((e,t)=>Math.max(e,t.upData+t.downData)),0)}update(){if(!this._source.p1||!this._source.p2)return;const e=this._source._vpData,t=this._source.chart_,i=this._source.series_,s=t.timeScale();this._x=s.timeToCoordinate(e.time)??null;const n=s.options().barSpacing??1,o=Math.max(0,Math.min(this._source.p1.logical,this._source.p2.logical)),r=Math.min(Math.max(this._source.p1.logical,this._source.p2.logical),this._source._originalData.length-1);if(this._width=(e.width&&0!==e.width?e.width:(r-o)/3)*n,this._p1=Ws(this._source.p1,t,i),this._p2=Ws(this._source.p2,t,i),this._items=[],e.profile.length){this._maxVolume=e.profile.reduce(((e,t)=>Math.max(e,t.upData+t.downData)),0);for(const t of e.profile){const e=i.priceToCoordinate(t.maxPrice),s=i.priceToCoordinate(t.minPrice);if(null==e||null==s){this._items.push({y1:null,y2:null,combinedWidth:0,upWidth:0,downWidth:0,color:t.color,borderColor:t.borderColor});continue}const n=t.upData+t.downData,o=this._maxVolume>0?this._width*(n/this._maxVolume):0;let r=0,a=0;n>0&&(r=t.upData/n*o,a=t.downData/n*o),this._items.push({y1:e,y2:s,combinedWidth:o,upWidth:r,downWidth:a,color:t.color,borderColor:t.borderColor})}}}renderer(){return new An({x:this._x,width:this._width,items:this._items,visibleRange:{from:this._source.chart.timeScale().logicalToCoordinate(Math.max(0,this._source.visibleRange.from)),to:this._source.chart.timeScale().logicalToCoordinate(Math.min(this._source.series.data().length-1,this._source.visibleRange.to))},maxVolume:this._maxVolume,maxBars:this._source.series.data().length},this._p1,this._p2,this._source._options,!1)}zOrder(){return"bottom"}}class An extends G{_data;options;p1;p2;constructor(e,t,i,s,n){super(t,i,s,n),this._data=e,this.options=s,this.p1=t,this.p2=i}draw(){}drawBackground(e){console.log(`[VolumeProfileRenderer] draw() called with rightSide: ${this.options.rightSide}`),e.useBitmapCoordinateSpace((e=>{let t=e.context;this._drawGrid(t,e),U(t,this.options.lineStyle),this._data.items.forEach((i=>{if(null===i.y1||null===i.y2)return;if(null===this._data.x)return;const s=Math.min(i.y1,i.y2)*e.verticalPixelRatio,n=Math.abs(i.y2-i.y1)*e.verticalPixelRatio,o=i.upWidth+i.downWidth,r=o*e.horizontalPixelRatio;let a;a=this.options.rightSide?(this._data.x-o)*e.horizontalPixelRatio:this._data.x*e.horizontalPixelRatio;const l=Math.min(Math.max(.25*n,2),25);if(n>0){t.beginPath(),this._drawRoundedRect(t,a,s,r,n,l),t.strokeStyle=i.borderColor,t.lineWidth=1,t.stroke();const c=Math.max(i.upWidth,i.downWidth)*e.horizontalPixelRatio;let h;h=this.options.rightSide?a+(o-c):a,t.beginPath(),this._drawRoundedRect(t,h,s,c,n,l),t.fillStyle=i.color,t.fill()}}))}))}_drawGrid(e,i){const{items:s,x:n}=this._data;if(!s||0===s.length||null===n)return;if(!this.options.drawGrid)return;let o;o=void 0!==this.options.gridWidth&&1!==this.options.gridWidth?this.options.gridWidth*i.horizontalPixelRatio:(this._data.visibleRange.to-this._data.visibleRange.from)*i.horizontalPixelRatio,e.strokeStyle=this.options.visible?this.options.gridColor||"rgba(255, 255, 255, 0.2)":"rgba(0,0,0,0)",U(e,this.options.gridLineStyle||t.LineStyle.Solid),s.forEach((t=>{if(null===t.y1||null===t.y2)return;const s=(t.upWidth+t.downWidth)*i.horizontalPixelRatio;let r,a;this.options.rightSide?(r=n-o,a=n-s):(r=n+s,a=n+o);const l=t.y1*i.verticalPixelRatio,c=t.y2*i.verticalPixelRatio;e.beginPath(),e.moveTo(r,l),e.lineTo(a,l),e.stroke(),e.beginPath(),e.moveTo(r,c),e.lineTo(a,c),e.stroke()}))}_drawRoundedRect(e,t,i,s,n,o){const r=Math.abs(Math.min(o,s/2,n/2));e.beginPath(),s>0&&o>0&&(this.options.rightSide?(e.moveTo(t+r,i),e.lineTo(t+s,i),e.lineTo(t+s,i+n),e.lineTo(t+r,i+n),e.arcTo(t,i+n,t,i+n-r,r),e.lineTo(t,i+r),e.arcTo(t,i,t+r,i,r)):(e.moveTo(t,i),e.lineTo(t+s-r,i),e.arcTo(t+s,i,t+s,i+r,r),e.lineTo(t+s,i+n-r),e.arcTo(t+s,i+n,t+s-r,i+n,r),e.lineTo(t,i+n),e.lineTo(t,i)),e.closePath())}}function Dn(e,t){if(e.length0){let t=e[0];s[0]=t;for(let n=1;n0===i?0:t-e[i-1])),s=i.map((e=>Math.max(e,0))),n=i.map((e=>Math.max(-e,0))),o=Ln(s,t),r=Ln(n,t);return 0===r?100:0===o?0:100-100/(1+o/r)}function On(e,t,i){for(let s=0;s=o?t:i}}function Vn(e,t,i){const s=e&&t in e?e[t]:i;return Array.isArray(s)?s.map((e=>Number(e))):[Number(s)]}function Rn(e,t){return t{if(o1?`_${t+1}`:""),d="ALMA"+i+(l>1?` #${t+1}`:"");c.push({key:p,title:d,type:"line",data:h})}return c}},Fn=(e,t)=>{let i=0;return e.forEach((e=>{const s=e.close-t;i+=s*s})),Math.sqrt(i/e.length)},$n={name:"Bollinger Bands",shortName:"BOLL",shouldOhlc:!0,paramMap:{length:{defaultValue:[20],type:"numberArray"},multiplier:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=Vn(t,"length",this.paramMap.length.defaultValue),s=Vn(t,"multiplier",this.paramMap.multiplier.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{if(l+=t.close,i>=r-1){const s=l/r,n=e.slice(i-(r-1),i+1),o=Fn(n,s);c.push({time:t.time,value:s+a*o}),h.push({time:t.time,value:s}),p.push({time:t.time,value:s-a*o}),l-=e[i-(r-1)].close}else c.push({time:t.time,value:NaN}),h.push({time:t.time,value:NaN}),p.push({time:t.time,value:NaN})}));const d=n>1?`_${t+1}`:"";o.push({key:`boll_up${d}`,title:`BOLL_UP${r}${d}`,type:"line",data:c}),o.push({key:`boll_mid${d}`,title:`BOLL_MID${r}${d}`,type:"line",data:h}),o.push({key:`boll_dn${d}`,title:`BOLL_DN${r}${d}`,type:"line",data:p})}return o}},Gn={name:"Exponential Moving Average",shortName:"EMA",shouldOhlc:!0,paramMap:{length:{defaultValue:[6,12,20],type:"numberArray"}},calc(e,t){const i=Vn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{let o=0,r=0;const a=[];e.forEach(((i,s)=>{if(r+=i.close,s===t-1)o=r/t;else if(s>t-1){const e=2/(t+1);o=(i.close-o)*e+o}s>=t-1?(a.push({time:i.time,value:o}),r-=e[s-(t-1)].close):a.push({time:i.time,value:NaN})}));const l="ema"+(i.length>1?`_${n+1}`:""),c="EMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:l,title:c,type:"line",data:a})})),s}},jn={name:"Highest High",shortName:"HH",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Vn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="HH"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Un={name:"Linear Regression",shortName:"LINREG",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Vn(t,"length",this.paramMap.length.defaultValue),s=e.map((e=>e.close)),n=[];return i.forEach(((t,o)=>{const r=[];e.forEach(((e,i)=>{if(ie+t),0),r=(s*i.reduce(((e,t,i)=>e+i*t),0)-n*o)/(s*(s*(s-1)*(2*s-1)/6)-n*n);return(o-r*n)/s+r*(s-1)}(s.slice(i-(t-1),i+1),t,0);r.push({time:e.time,value:n})}));const a="linreg"+(i.length>1?`_${o+1}`:""),l="LINREG"+t+(i.length>1?` #${o+1}`:"");n.push({key:a,title:l,type:"line",data:r})})),n}},zn={name:"Lowest Low",shortName:"LL",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Vn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(s1?`_${n+1}`:""),a="LL"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Hn={name:"Median",shortName:"Median",shouldOhlc:!0,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Vn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];e.forEach(((i,s)=>{if(se.close));n.sort(((e,t)=>e-t));const r=Math.floor(n.length/2),a=n.length%2==0?(n[r-1]+n[r])/2:n[r];o.push({time:i.time,value:a})}));const r="median"+(i.length>1?`_${n+1}`:""),a="Median"+t+(i.length>1?` #${n+1}`:"");s.push({key:r,title:a,type:"line",data:o})})),s}},Wn={name:"Moving Average",shortName:"MA",shouldOhlc:!0,paramMap:{length:{defaultValue:[5,10,30,60],type:"numberArray"}},calc(e,t){const i=Vn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=[];let r=0;e.forEach(((i,s)=>{if(r+=i.close,s>=t-1){const n=r/t;o.push({time:i.time,value:n}),r-=e[s-(t-1)].close}else o.push({time:i.time,value:NaN})}));const a="ma"+(i.length>1?`_${n+1}`:""),l="MA"+t+(i.length>1?` #${n+1}`:"");s.push({key:a,title:l,type:"line",data:o})})),s}},qn={name:"Rolling Moving Average",shortName:"RMA",shouldOhlc:!1,paramMap:{length:{defaultValue:[14],type:"numberArray"}},calc(e,t){const i=Vn(t,"length",this.paramMap.length.defaultValue),s=[];return i.forEach(((t,n)=>{const o=1/t;let r=0;const a=[];e.forEach(((e,t)=>{r=0===t?e.close:o*e.close+(1-o)*r,a.push({time:e.time,value:r})}));const l="rma"+(i.length>1?`_${n+1}`:""),c="RMA"+t+(i.length>1?` #${n+1}`:"");s.push({key:l,title:c,type:"line",data:a})})),s}},Xn={name:"Simple Moving Average",shortName:"SMA",shouldOhlc:!0,paramMap:{n:{defaultValue:[12],type:"numberArray"},k:{defaultValue:[2],type:"numberArray"}},calc(e,t){const i=Vn(t,"n",this.paramMap.n.defaultValue),s=Vn(t,"k",this.paramMap.k.defaultValue),n=Math.max(i.length,s.length),o=[];for(let t=0;t{l+=t.close,i>=r-1?(c=i===r-1?l/r:(t.close*a+c*(r-a))/r,l-=e[i-(r-1)].close,h.push({time:t.time,value:c})):h.push({time:t.time,value:NaN})}));const p="sma"+(n>1?`_${t+1}`:""),d="SMA"+r+","+a+(n>1?` #${t+1}`:"");o.push({key:p,title:d,type:"line",data:h})}return o}},Jn={name:"Stop and Reverse",shortName:"SAR",shouldOhlc:!0,paramMap:{accStart:{defaultValue:[.02],type:"numberArray"},accStep:{defaultValue:[.02],type:"numberArray"},accMax:{defaultValue:[.2],type:"numberArray"}},calc(e,t){const i=Vn(t,"accStart",this.paramMap.accStart.defaultValue),s=Vn(t,"accStep",this.paramMap.accStep.defaultValue),n=Vn(t,"accMax",this.paramMap.accMax.defaultValue),o=Math.max(i.length,s.length,n.length),r=[];for(let t=0;t{0!==i?(1===i&&(u=t.close>e[0].close,p=u?t.high:t.low,d=u?e[0].low:e[0].high,m.push({time:e[0].time,value:d})),d+=h*(p-d),u?t.lowp&&(p=t.high,h=Math.min(h+l,c)):t.high>d?(u=!0,d=p,h=a,p=t.high):t.low