@orderly.network/ui-tradingview 2.8.1 → 2.8.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
3
  var jsxRuntime = require('react/jsx-runtime');
4
- var R = require('react');
4
+ var React3 = require('react');
5
5
  var i18n = require('@orderly.network/i18n');
6
- var ui$1 = require('@orderly.network/ui');
6
+ var ui = require('@orderly.network/ui');
7
7
  var hooks = require('@orderly.network/hooks');
8
8
  var types = require('@orderly.network/types');
9
9
  var utils = require('@orderly.network/utils');
@@ -11,12 +11,4089 @@ var dateFns = require('date-fns');
11
11
 
12
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
13
 
14
- var R__default = /*#__PURE__*/_interopDefault(R);
14
+ var React3__default = /*#__PURE__*/_interopDefault(React3);
15
15
 
16
- var Jr=Object.defineProperty;var K=(r,e)=>()=>(r&&(e=r(r=0)),e);var Ve=(r,e)=>{for(var t in e)Jr(r,t,{get:e[t],enumerable:true});};var $,ke,lt,ar,lr,cr,ur,dr,pr,mr,gr,hr,Z=K(()=>{$=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 12 12",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Caret-down",children:jsxRuntime.jsx("path",{id:"Vector",d:"M3.00349 3.9978C2.59149 3.9978 2.36564 4.4653 2.61289 4.7948C2.98789 5.2948 5.23784 8.29479 5.61289 8.79479C5.81289 9.06128 6.20974 9.06128 6.40974 8.79479L9.40974 4.7948C9.65694 4.4653 9.41554 3.9978 9.00349 3.9978H3.00349Z"})})}),ke=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 18 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Display settings",children:jsxRuntime.jsx("path",{id:"Union",fillRule:"evenodd",clipRule:"evenodd",d:"M15.0571 10.9856L11.6295 5.06523L8.71377 10.8968C8.38933 11.5456 7.54464 11.7223 6.98733 11.2579L5.75311 10.2294L2.83709 14.7654L1.57532 13.9543L4.49134 9.41824C4.97892 8.65978 6.0207 8.49981 6.71338 9.07705L7.58387 9.80246L10.5991 3.77192C10.9997 2.97082 12.1302 2.93624 12.579 3.71137L14.6517 7.29147C14.7714 7.03643 15.0305 6.85983 15.3309 6.85983C15.7451 6.85983 16.0809 7.19562 16.0809 7.60983C16.0809 8.02405 15.7451 8.35983 15.3309 8.35983C15.31 8.35983 15.2892 8.35897 15.2687 8.35729L16.3553 10.2341L15.0571 10.9856ZM2.58093 6.85983C2.16672 6.85983 1.83093 7.19562 1.83093 7.60983C1.83093 8.02405 2.16672 8.35983 2.58093 8.35983C2.99515 8.35983 3.33093 8.02405 3.33093 7.60983C3.33093 7.19562 2.99515 6.85983 2.58093 6.85983ZM4.83093 6.85983C4.41672 6.85983 4.08093 7.19562 4.08093 7.60983C4.08093 8.02405 4.41672 8.35983 4.83093 8.35983C5.24515 8.35983 5.58093 8.02405 5.58093 7.60983C5.58093 7.19562 5.24515 6.85983 4.83093 6.85983ZM6.33093 7.60983C6.33093 7.19562 6.66672 6.85983 7.08093 6.85983C7.49515 6.85983 7.83093 7.19562 7.83093 7.60983C7.83093 8.02405 7.49515 8.35983 7.08093 8.35983C6.66672 8.35983 6.33093 8.02405 6.33093 7.60983ZM11.5809 6.85983C11.1667 6.85983 10.8309 7.19562 10.8309 7.60983C10.8309 8.02405 11.1667 8.35983 11.5809 8.35983C11.9951 8.35983 12.3309 8.02405 12.3309 7.60983C12.3309 7.19562 11.9951 6.85983 11.5809 6.85983Z"})})}),lt=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 18 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Indicators",children:jsxRuntime.jsx("path",{id:"Union",fillRule:"evenodd",clipRule:"evenodd",d:"M9.74483 2.25C8.96145 2.25 8.26885 2.76459 8.04549 3.51818L7.46202 5.48254H5.06262V7.08339H6.98652L5.00539 13.7532L4.31554 13.1112L3.22498 14.2831L4.4777 15.4489C5.08739 16.015 6.08317 15.7469 6.32134 14.945L8.65649 7.08339H11.6032V5.48254H9.13198L9.58033 3.97311C9.60167 3.90112 9.66833 3.85084 9.74483 3.85084H11.69V2.25H9.74483ZM10.6234 11.2354L10.2638 11.5172C10.0153 11.712 9.65591 11.6684 9.46115 11.4199C9.26639 11.1713 9.30998 10.812 9.55852 10.6172L10.1451 10.1575C10.5693 9.82514 11.1868 9.94011 11.4642 10.4005L11.4682 10.407L12.1304 11.5752L13.4594 10.3111C13.6882 10.0935 14.05 10.1025 14.2677 10.3313C14.4853 10.5601 14.4763 10.922 14.2475 11.1396L12.7116 12.6006L13.3897 13.797L13.6482 13.4503C13.8369 13.1972 14.1951 13.145 14.4483 13.3337C14.7014 13.5225 14.7536 13.8807 14.5649 14.1338L13.9917 14.9025L13.94 14.9457C13.5178 15.2981 12.8837 15.1886 12.6003 14.7226L12.5958 14.7151L11.8576 13.4129L10.3563 14.841C10.1275 15.0586 9.76561 15.0495 9.54798 14.8208C9.33036 14.592 9.3394 14.2301 9.56819 14.0125L11.2764 12.3875L10.6234 11.2354Z"})})}),ar=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 18 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Setting",children:jsxRuntime.jsx("path",{id:"Vector",d:"M6.72589 1.84154C5.66239 2.17904 4.74515 2.72954 3.93665 3.48254C3.6869 3.71504 3.6104 4.09604 3.7724 4.39604C4.37315 5.50679 3.74464 6.69554 2.38939 6.76379C2.05789 6.78029 1.76465 7.0263 1.68665 7.34955C1.5524 7.9083 1.49915 8.37629 1.49915 8.98979C1.49915 9.50504 1.55464 10.0885 1.66339 10.6075C1.73089 10.9315 2.0129 11.1648 2.3429 11.1933C3.7064 11.311 4.3814 12.3513 3.7724 13.6773C3.6374 13.972 3.6989 14.3245 3.93665 14.545C4.73315 15.2815 5.64814 15.8013 6.72589 16.1388C7.03339 16.2348 7.38064 16.1185 7.56964 15.8575C8.40364 14.7033 9.6134 14.6995 10.4054 15.8575C10.5921 16.1298 10.9341 16.261 11.2491 16.162C12.2894 15.8343 13.2584 15.277 14.0616 14.545C14.3091 14.3193 14.3744 13.954 14.2259 13.654C13.6019 12.3948 14.3197 11.239 15.6082 11.2165C15.9502 11.2105 16.2547 10.9863 16.3349 10.654C16.4647 10.1163 16.4991 9.64829 16.4991 8.98979C16.4991 8.42429 16.4324 7.86704 16.3116 7.32629C16.2351 6.98354 15.9359 6.74054 15.5849 6.73979C14.3167 6.73754 13.6056 5.49104 14.2259 4.39604C14.3984 4.09154 14.3444 3.71804 14.0849 3.48254C13.2674 2.74004 12.2706 2.15954 11.2259 1.84154C10.9049 1.74404 10.5636 1.86404 10.3821 2.14604C9.65764 3.27179 8.30465 3.29129 7.5929 2.17004C7.41065 1.88204 7.04989 1.73879 6.72589 1.84154ZM11.2844 3.43455C11.7966 3.64905 12.2009 3.8733 12.6651 4.22505C12.1206 5.9478 13.0439 7.73729 14.9564 8.17304C15.0036 8.48279 14.9991 8.67029 14.9991 8.98979C14.9991 9.37154 15.0044 9.50579 14.9609 9.78179C13.0566 10.1763 12.1146 11.9155 12.6449 13.7538C12.1889 14.0845 11.8626 14.314 11.2904 14.5353C9.94639 13.1673 8.0804 13.1073 6.7079 14.5443C6.1724 14.3088 5.76066 14.0995 5.34441 13.7478C5.86041 11.881 4.98815 10.2693 3.05165 9.7803C2.9654 9.4383 2.9999 8.4723 3.0494 8.17905C5.0519 7.69905 5.8409 5.92679 5.34365 4.21979C5.78315 3.88904 6.1784 3.6483 6.69215 3.4398C7.9859 4.75605 9.92839 4.8873 11.2844 3.43455ZM8.99915 5.98979C7.3424 5.98979 5.99915 7.33304 5.99915 8.98979C5.99915 10.6473 7.3424 11.9898 8.99915 11.9898C10.6559 11.9898 11.9991 10.6473 11.9991 8.98979C11.9991 7.33304 10.6559 5.98979 8.99915 5.98979ZM8.99915 7.48979C9.8279 7.48979 10.4991 8.16179 10.4991 8.98979C10.4991 9.81855 9.8279 10.4898 8.99915 10.4898C8.1704 10.4898 7.49915 9.81855 7.49915 8.98979C7.49915 8.16179 8.1704 7.48979 8.99915 7.48979Z"})})}),lr=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Bars",children:jsxRuntime.jsx("path",{id:"Union",fillRule:"evenodd",clipRule:"evenodd",d:"M12.5 15.5C12.5 15.7761 12.7239 16 13 16H14C14.2761 16 14.5 15.7761 14.5 15.5V14H16C16.2761 14 16.5 13.7761 16.5 13.5V12.5C16.5 12.2239 16.2761 12 16 12H14.5V2.5C14.5 2.22386 14.2761 2 14 2H13C12.7239 2 12.5 2.22386 12.5 2.5V4H11C10.7239 4 10.5 4.22386 10.5 4.5V5.5C10.5 5.77614 10.7239 6 11 6H12.5V15.5ZM5.5 17.5C5.5 17.7761 5.72386 18 6 18H7C7.27614 18 7.5 17.7761 7.5 17.5V10H9C9.27614 10 9.5 9.77614 9.5 9.5V8.5C9.5 8.22386 9.27614 8 9 8H7.5V4.5C7.5 4.22386 7.27614 4 7 4H6C5.72386 4 5.5 4.22386 5.5 4.5V14H4C3.72386 14 3.5 14.2239 3.5 14.5V15.5C3.5 15.7761 3.72386 16 4 16H5.5V17.5Z"})})}),cr=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Candles",children:jsxRuntime.jsx("path",{id:"Union",fillRule:"evenodd",clipRule:"evenodd",d:"M7.25 2.5V4H8.5C8.77614 4 9 4.22386 9 4.5V15.5C9 15.7761 8.77614 16 8.5 16H7.25V17.5C7.25 17.7761 7.02614 18 6.75 18H6.25C5.97386 18 5.75 17.7761 5.75 17.5V16H4.5C4.22386 16 4 15.7761 4 15.5V4.5C4 4.22386 4.22386 4 4.5 4H5.75V2.5C5.75 2.22386 5.97386 2 6.25 2H6.75C7.02614 2 7.25 2.22386 7.25 2.5ZM5.5 5.5V14.5H7.5V5.5H5.5ZM14.25 4.5V7H15.5C15.7761 7 16 7.22386 16 7.5V15.5C16 15.7761 15.7761 16 15.5 16H14.25V17.5C14.25 17.7761 14.0261 18 13.75 18H13.25C12.9739 18 12.75 17.7761 12.75 17.5V16H11.5C11.2239 16 11 15.7761 11 15.5V7.5C11 7.22386 11.2239 7 11.5 7H12.75V4.5C12.75 4.22386 12.9739 4 13.25 4H13.75C14.0261 4 14.25 4.22386 14.25 4.5ZM12.5 8.5V14.5H14.5V8.5H12.5Z"})})}),ur=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsxs("g",{id:"Hollow Candles",children:[jsxRuntime.jsx("path",{id:"Subtract",fillRule:"evenodd",clipRule:"evenodd",d:"M5.5 14.5V5.5H7.5V14.5H5.5Z",fill:"white",fillOpacity:"0.12"}),jsxRuntime.jsx("path",{id:"Union",fillRule:"evenodd",clipRule:"evenodd",d:"M7.25 2.5V4H8.5C8.77614 4 9 4.22386 9 4.5V15.5C9 15.7761 8.77614 16 8.5 16H7.25V17.5C7.25 17.7761 7.02614 18 6.75 18H6.25C5.97386 18 5.75 17.7761 5.75 17.5V16H4.5C4.22386 16 4 15.7761 4 15.5V4.5C4 4.22386 4.22386 4 4.5 4H5.75V2.5C5.75 2.22386 5.97386 2 6.25 2H6.75C7.02614 2 7.25 2.22386 7.25 2.5ZM5.5 5.5V14.5H7.5V5.5H5.5ZM14.25 4.5V7H15.5C15.7761 7 16 7.22386 16 7.5V15.5C16 15.7761 15.7761 16 15.5 16H14.25V17.5C14.25 17.7761 14.0261 18 13.75 18H13.25C12.9739 18 12.75 17.7761 12.75 17.5V16H11.5C11.2239 16 11 15.7761 11 15.5V7.5C11 7.22386 11.2239 7 11.5 7H12.75V4.5C12.75 4.22386 12.9739 4 13.25 4H13.75C14.0261 4 14.25 4.22386 14.25 4.5ZM12.5 8.5V14.5H14.5V8.5H12.5Z"})]})}),dr=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Line",children:jsxRuntime.jsx("path",{id:"Vector 16 (Stroke)",fillRule:"evenodd",clipRule:"evenodd",d:"M18.3 2.72288C18.542 2.85596 18.6303 3.15999 18.4972 3.40195L13.495 12.4968C13.0776 13.2557 12.1061 13.5044 11.3754 13.0394L7.19878 10.3816L2.97738 17.558C2.83737 17.796 2.53092 17.8754 2.2929 17.7354L1.43097 17.2284C1.19295 17.0884 1.1135 16.7819 1.25351 16.5439L5.73746 8.92122C6.16792 8.18943 7.1194 7.96045 7.83567 8.41626L11.9995 11.0659L16.7448 2.43811C16.8778 2.19615 17.1819 2.10788 17.4238 2.24096L18.3 2.72288Z"})})}),pr=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsxs("g",{id:"Area",children:[jsxRuntime.jsx("path",{id:"Vector 16 (Stroke)",fillRule:"evenodd",clipRule:"evenodd",d:"M18.3 2.72288C18.542 2.85596 18.6303 3.15999 18.4972 3.40195L13.495 12.4968C13.0776 13.2557 12.1061 13.5044 11.3754 13.0394L7.19878 10.3816L2.97738 17.558C2.83737 17.796 2.53092 17.8754 2.2929 17.7354L1.43097 17.2284C1.19295 17.0884 1.1135 16.7819 1.25351 16.5439L5.73746 8.92122C6.16792 8.18943 7.1194 7.96045 7.83567 8.41626L11.9995 11.0659L16.7448 2.43811C16.8778 2.19615 17.1819 2.10788 17.4238 2.24096L18.3 2.72288Z"}),jsxRuntime.jsx("path",{id:"Subtract",fillRule:"evenodd",clipRule:"evenodd",d:"M2.7608 17.7562C2.84602 17.899 3.00106 18 3.19016 18H16.362C17.4665 18 18.362 17.1046 18.362 16V3.94663C18.362 3.86618 18.3453 3.79397 18.3162 3.73108L13.495 12.4968C13.0776 13.2557 12.1061 13.5044 11.3754 13.0394L7.19881 10.3816L2.9774 17.558C2.92465 17.6477 2.84826 17.7148 2.7608 17.7562Z",fill:"white",fillOpacity:"0.12"})]})}),mr=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 20 20",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Baseline",children:jsxRuntime.jsx("path",{id:"Union",fillRule:"evenodd",clipRule:"evenodd",d:"M6.05938 2.93544C6.55642 1.71198 8.27766 1.68139 8.81785 2.88642L11.4361 8.72723H9.24438L7.4717 4.77279L5.86521 8.72723H3.70647L6.05938 2.93544ZM13.9282 14.2865L13.0051 12.2272H10.8133L12.5586 16.1204C13.088 17.3014 14.7641 17.3026 15.2952 16.1224L17.048 12.2272H14.8549L13.9282 14.2865ZM2.28459 12.2272H4.44333L1.85293 18.6036L0 17.8509L2.28459 12.2272ZM16.4299 8.72723H18.623L19.3384 7.13759L17.5145 6.31686L16.4299 8.72723ZM1.42645 10.2272C1.42645 9.95109 1.65031 9.72723 1.92645 9.72723H2.92645C3.20259 9.72723 3.42645 9.95109 3.42645 10.2272V10.7272C3.42645 11.0034 3.20259 11.2272 2.92645 11.2272H1.92645C1.65031 11.2272 1.42645 11.0034 1.42645 10.7272V10.2272ZM4.42645 10.2272C4.42645 9.95109 4.65031 9.72723 4.92645 9.72723H5.92645C6.20259 9.72723 6.42645 9.95109 6.42645 10.2272V10.7272C6.42645 11.0034 6.20259 11.2272 5.92645 11.2272H4.92645C4.65031 11.2272 4.42645 11.0034 4.42645 10.7272V10.2272ZM7.92645 9.72723C7.65031 9.72723 7.42645 9.95109 7.42645 10.2272V10.7272C7.42645 11.0034 7.65031 11.2272 7.92645 11.2272H8.92645C9.20259 11.2272 9.42645 11.0034 9.42645 10.7272V10.2272C9.42645 9.95109 9.20259 9.72723 8.92645 9.72723H7.92645ZM10.4265 10.2272C10.4265 9.95109 10.6503 9.72723 10.9265 9.72723H11.9265C12.2026 9.72723 12.4265 9.95109 12.4265 10.2272V10.7272C12.4265 11.0034 12.2026 11.2272 11.9265 11.2272H10.9265C10.6503 11.2272 10.4265 11.0034 10.4265 10.7272V10.2272ZM13.9265 9.72723C13.6503 9.72723 13.4265 9.95109 13.4265 10.2272V10.7272C13.4265 11.0034 13.6503 11.2272 13.9265 11.2272H14.9265C15.2026 11.2272 15.4265 11.0034 15.4265 10.7272V10.2272C15.4265 9.95109 15.2026 9.72723 14.9265 9.72723H13.9265ZM16.4265 10.2272C16.4265 9.95109 16.6503 9.72723 16.9265 9.72723H17.9265C18.2026 9.72723 18.4265 9.95109 18.4265 10.2272V10.7272C18.4265 11.0034 18.2026 11.2272 17.9265 11.2272H16.9265C16.6503 11.2272 16.4265 11.0034 16.4265 10.7272V10.2272Z"})})}),gr=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 12 12",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Unselected",children:jsxRuntime.jsx("path",{id:"Vector",d:"M6.00684 0.999023C3.24544 0.999023 1.00684 3.23752 1.00684 5.99902C1.00684 8.76051 3.24544 10.999 6.00684 10.999C8.76834 10.999 11.0068 8.76051 11.0068 5.99902C11.0068 3.23752 8.76834 0.999023 6.00684 0.999023ZM6.00684 1.99902C8.21584 1.99902 10.0068 3.79002 10.0068 5.99902C10.0068 8.20801 8.21584 9.99901 6.00684 9.99901C3.79769 9.99901 2.00684 8.20801 2.00684 5.99902C2.00684 3.79002 3.79769 1.99902 6.00684 1.99902Z",fill:"white",fillOpacity:"0.2"})})}),hr=r=>jsxRuntime.jsx("svg",{viewBox:"0 0 12 12",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...r,children:jsxRuntime.jsx("g",{id:"Selected-Multiple Choices-fill",children:jsxRuntime.jsx("path",{id:"Subtract",fillRule:"evenodd",clipRule:"evenodd",d:"M1.00684 5.99902C1.00684 3.23752 3.24544 0.999023 6.00684 0.999023C8.76834 0.999023 11.0068 3.23752 11.0068 5.99902C11.0068 8.76051 8.76834 10.999 6.00684 10.999C3.24544 10.999 1.00684 8.76051 1.00684 5.99902ZM8.49243 3.65563C8.60602 3.54726 8.76156 3.49957 8.91068 3.49957C9.05981 3.49957 9.21534 3.54726 9.32893 3.65563C9.5567 3.87231 9.5567 4.23649 9.32893 4.45317L5.25362 8.33706C5.02644 8.55374 4.6443 8.55374 4.41712 8.33706L2.67014 6.67253C2.44296 6.45585 2.44296 6.09161 2.67014 5.87499C2.89791 5.65831 3.28004 5.65831 3.50722 5.87499L4.83537 7.1407L8.49243 3.65563Z",fill:"#608CFF"})})});});var Lr={};Ve(Lr,{default:()=>Lo});var Io,Lo,Or=K(()=>{Z();Io=r=>{let[e,t]=R.useState(false),{t:i}=i18n.useTranslation(),o=R.useMemo(()=>[{icon:jsxRuntime.jsx(lr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.bars"),value:"0"},{icon:jsxRuntime.jsx(cr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.candles"),value:"1"},{icon:jsxRuntime.jsx(ur,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.hollowCandles"),value:"9"},{icon:jsxRuntime.jsx(dr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.line"),value:"2"},{icon:jsxRuntime.jsx(pr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.area"),value:"3"},{icon:jsxRuntime.jsx(mr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.baseline"),value:"10"}],[i]),s=R.useMemo(()=>{let n=o.find(a=>a.value===r.lineType);return n?n.icon:o[1].icon},[r.lineType]);return jsxRuntime.jsxs(ui$1.DropdownMenuRoot,{open:e,onOpenChange:t,children:[jsxRuntime.jsx(ui$1.DropdownMenuTrigger,{asChild:true,children:jsxRuntime.jsx(ui$1.Box,{className:ui$1.cn("oui-w-[18px] oui-h-[18px] oui-cursor-pointer oui-text-base-contrast-36 hover:oui-text-base-contrast-80",e&&"oui-text-base-contrast-80"),children:s})}),jsxRuntime.jsx(ui$1.DropdownMenuPortal,{children:jsxRuntime.jsx(ui$1.DropdownMenuContent,{onCloseAutoFocus:n=>n.preventDefault(),onClick:n=>n.stopPropagation(),align:"start",sideOffset:20,className:"oui-bg-base-8",children:jsxRuntime.jsx(ui$1.Flex,{direction:"column",gap:4,px:5,py:5,width:240,justify:"start",itemAlign:"start",children:o.map(n=>jsxRuntime.jsxs(ui$1.Flex,{justify:"start",itemAlign:"center",gap:2,className:ui$1.cn("oui-text-base-contrast-36 oui-cursor-pointer oui-w-full hover:oui-text-base-contrast",r.lineType===n.value&&"oui-text-base-contrast"),onClick:()=>r.changeLineType(n.value),children:[n.icon,jsxRuntime.jsx(ui$1.Text,{className:"oui-text-sm",children:n.label})]},n.value))})})})]})},Lo=Io;});var wr={};Ve(wr,{MobileTimeInterval:()=>xr,TimeInterval:()=>Ao});var Pr,Ao,Bo,xr,Vo,Rr=K(()=>{Z();Pr=()=>{let{t:r}=i18n.useTranslation();return {mobileTimeIntervalMoreMap:R.useMemo(()=>[[{value:"3",label:r("tradingView.timeInterval.3m")},{value:"5",label:r("tradingView.timeInterval.5m")},{value:"30",label:r("tradingView.timeInterval.30m")},{value:"120",label:r("tradingView.timeInterval.2h")}],[{value:"360",label:r("tradingView.timeInterval.6h")},{value:"720",label:r("tradingView.timeInterval.12h")},{value:"3d",label:r("tradingView.timeInterval.3d")},{value:"1M",label:r("tradingView.timeInterval.1M")}]],[r])}},Ao=r=>hooks.useMediaQuery(types.MEDIA_TABLET)?jsxRuntime.jsx(xr,{...r}):jsxRuntime.jsx(Bo,{...r}),Bo=r=>{let{t:e}=i18n.useTranslation(),t=R.useMemo(()=>[{value:"1",label:e("tradingView.timeInterval.1m")},{value:"3",label:e("tradingView.timeInterval.3m")},{value:"5",label:e("tradingView.timeInterval.5m")},{value:"15",label:e("tradingView.timeInterval.15m")},{value:"30",label:e("tradingView.timeInterval.30m")},{value:"60",label:e("tradingView.timeInterval.1h")},{value:"240",label:e("tradingView.timeInterval.4h")},{value:"720",label:e("tradingView.timeInterval.12h")},{value:"1D",label:e("tradingView.timeInterval.1d")},{value:"1W",label:e("tradingView.timeInterval.1w")},{value:"1M",label:e("tradingView.timeInterval.1M")}],[e]);return jsxRuntime.jsx("div",{className:ui$1.cn("oui-text-2xs oui-text-base-contrast-36 oui-flex oui-gap-[2px] oui-items-center oui-mr-3 oui-font-semibold","oui-overflow-hidden"),children:t.map(i=>jsxRuntime.jsx("div",{className:ui$1.cn("oui-cursor-pointer oui-px-2","hover:oui-text-base-contrast-80","oui-break-normal oui-whitespace-nowrap",r.interval===i.value&&"oui-text-base-contrast-80 oui-bg-white/[.06] oui-rounded"),id:i.value,onClick:()=>r.changeInterval(i.value),children:i.label},i.value))})},xr=r=>{let{t:e}=i18n.useTranslation(),t=R.useMemo(()=>[{value:"1",label:e("tradingView.timeInterval.1m")},{value:"15",label:e("tradingView.timeInterval.15m")},{value:"60",label:e("tradingView.timeInterval.1h")},{value:"240",label:e("tradingView.timeInterval.4h")},{value:"1D",label:e("tradingView.timeInterval.1d")},{value:"1W",label:e("tradingView.timeInterval.1w")}],[e]),{mobileTimeIntervalMoreMap:i}=Pr(),o=R.useMemo(()=>{for(let s of i)for(let n of s)if(n.value===r.interval)return n.label;return null},[r.interval,i]);return jsxRuntime.jsxs(ui$1.Flex,{justify:"start",itemAlign:"center",gap:3,className:ui$1.cn("oui-text-2xs oui-text-base-contrast-36","oui-overflow-hidden"),children:[jsxRuntime.jsx("div",{className:" oui-flex oui-gap-1 oui-items-center oui-mr-3 oui-font-semibold",children:t.map(s=>jsxRuntime.jsx("div",{className:ui$1.cn("oui-px-2","oui-break-normal oui-whitespace-nowrap",r.interval===s.value&&"oui-text-base-contrast-80 oui-bg-white/[.06] oui-rounded"),onClick:()=>r.changeInterval(s.value),children:s.label},s.value))}),jsxRuntime.jsx(Vo,{...r,children:o?jsxRuntime.jsx("div",{className:"oui-text-base-contrast-80",children:o}):jsxRuntime.jsx(ui$1.Text,{className:"oui-break-normal oui-whitespace-nowrap",children:e("tradingView.timeInterval.more")})})]})},Vo=r=>{let[e,t]=R__default.default.useState(false),{mobileTimeIntervalMoreMap:i}=Pr();return jsxRuntime.jsxs(ui$1.DropdownMenuRoot,{open:e,onOpenChange:t,children:[jsxRuntime.jsx(ui$1.DropdownMenuTrigger,{asChild:true,children:jsxRuntime.jsxs("div",{className:"oui-flex oui-justify-start oui-items-center oui-gap-0.5",children:[r.children,jsxRuntime.jsx($,{className:ui$1.cn("oui-w-3 oui-h-3",e&&"oui-text-base-contrast-80 oui-rotate-180")})]})}),jsxRuntime.jsx(ui$1.DropdownMenuPortal,{children:jsxRuntime.jsx(ui$1.DropdownMenuContent,{onCloseAutoFocus:o=>o.preventDefault(),onClick:o=>o.stopPropagation(),align:"start",alignOffset:0,sideOffset:0,className:ui$1.cn("oui-markets-dropdown-menu-content oui-bg-base-9 oui-w-screen oui-flex oui-flex-col oui-gap-2 oui-p-3"),children:i.map((o,s)=>jsxRuntime.jsx("div",{className:"oui-flex oui-gap-2",children:o.map(n=>jsxRuntime.jsx("div",{className:ui$1.cn("oui-w-full oui-text-2xs oui-flex oui-items-center oui-justify-center oui-h-6 oui-rounded",n.value===r.interval?"oui-text-base-contrast oui-bg-primary-darken":"oui-text-base-contrast-36 oui-bg-base-5"),onClick:()=>{r.changeInterval(n.value);},children:jsxRuntime.jsx("div",{children:n.label})},n.value))},s))})})]})};});var Er,kr=K(()=>{Z();Er=r=>{let{displayControlState:e,changeDisplayControlState:t}=r,[i,o]=R.useState(false),{t:s}=i18n.useTranslation(),n=R.useMemo(()=>[{label:s("common.position"),id:"position"},{label:s("tradingView.displayControl.buySell"),id:"buySell"},{label:s("tradingView.displayControl.limitOrders"),id:"limitOrders"},{label:s("tradingView.displayControl.stopOrders"),id:"stopOrders"},{label:s("common.tpsl"),id:"tpsl"},{label:s("tpsl.positionTpsl"),id:"positionTpsl"},{label:s("orderEntry.orderType.trailingStop"),id:"trailingStop"}],[s]);return jsxRuntime.jsx(jsxRuntime.Fragment,{children:jsxRuntime.jsxs(ui$1.DropdownMenuRoot,{open:i,onOpenChange:o,children:[jsxRuntime.jsx(ui$1.DropdownMenuTrigger,{asChild:true,children:jsxRuntime.jsxs(ui$1.Flex,{justify:"start",itemAlign:"center",className:"oui-gap-[2px] oui-cursor-pointer oui-text-base-contrast-36 hover:oui-text-base-contrast-80",children:[jsxRuntime.jsx(ke,{className:ui$1.cn("oui-w-[18px] oui-h-[18px] ",i&&"oui-text-base-contrast-80")}),jsxRuntime.jsx($,{className:ui$1.cn("oui-w-3 oui-h-3",i&&"oui-text-base-contrast-80 oui-rotate-180")})]})}),jsxRuntime.jsx(ui$1.DropdownMenuPortal,{children:jsxRuntime.jsx(ui$1.DropdownMenuContent,{onCloseAutoFocus:a=>a.preventDefault(),onClick:a=>a.stopPropagation(),align:"start",className:"oui-bg-base-8",children:jsxRuntime.jsx(ui$1.Flex,{direction:"column",gap:4,px:5,py:5,width:240,justify:"start",itemAlign:"start",children:n.map(a=>jsxRuntime.jsxs(ui$1.Flex,{justify:"between",itemAlign:"center",className:"oui-w-full",children:[jsxRuntime.jsx(ui$1.Text,{className:ui$1.cn("oui-text-sm oui-text-base-contrast-80",!e[a.id]&&"oui-text-base-contrast-36"),children:a.label}),jsxRuntime.jsx(ui$1.Switch,{className:"oui-h-4 oui-w-8",checked:e[a.id],onCheckedChange:c=>{t({...e,[a.id]:c});}})]},a.id))})})})]})})};});var Mr,Dr=K(()=>{Z();Mr=r=>{let[e,t]=R.useState(false),{t:i}=i18n.useTranslation(),o=R.useMemo(()=>[[{label:i("common.position"),id:"position"},{label:i("tradingView.displayControl.limitOrders"),id:"limitOrders"}],[{label:i("tradingView.displayControl.stopOrders"),id:"stopOrders"},{label:i("common.tpsl"),id:"tpsl"}],[{label:i("tpsl.positionTpsl"),id:"positionTpsl"},{label:i("tradingView.displayControl.buySell"),id:"buySell"}],[{label:i("orderEntry.orderType.trailingStop"),id:"trailingStop"},{}]],[i]);return jsxRuntime.jsxs(ui$1.DropdownMenuRoot,{open:e,onOpenChange:t,children:[jsxRuntime.jsx(ui$1.DropdownMenuTrigger,{asChild:true,children:jsxRuntime.jsxs("div",{className:ui$1.cn("oui-flex oui-items-center oui-justify-center oui-gap-0.5 oui-text-base-contrast-36",e&&"oui-text-base-contrast-8"),children:[jsxRuntime.jsx(ke,{className:ui$1.cn("oui-size-[18px] ",e&&"oui-text-base-contrast-80")}),jsxRuntime.jsx($,{className:ui$1.cn("oui-size-3",e&&"oui-rotate-180 oui-text-base-contrast-80")})]})}),jsxRuntime.jsx(ui$1.DropdownMenuPortal,{children:jsxRuntime.jsx(ui$1.DropdownMenuContent,{onCloseAutoFocus:s=>s.preventDefault(),onClick:s=>s.stopPropagation(),align:"start",alignOffset:0,sideOffset:0,className:ui$1.cn("oui-tradingview-display-control-dropdown-menu-content oui-flex oui-w-screen oui-flex-col oui-gap-2 oui-bg-base-9 oui-p-3"),children:o.map((s,n)=>jsxRuntime.jsx("div",{className:"oui-flex oui-gap-2",children:s.map((a,c)=>jsxRuntime.jsx("div",{className:ui$1.cn("oui-flex oui-h-6 oui-w-full oui-items-center oui-justify-between","oui-rounded oui-px-2 oui-text-2xs",a.id&&"oui-bg-base-5",r.displayControlState[a.id]?"oui-text-base-contrast":"oui-text-base-contrast-36"),onClick:()=>{a.id&&r.changeDisplayControlState({...r.displayControlState,[a.id]:!r.displayControlState[a.id]});},children:a.id&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{children:a.label}),r.displayControlState[a.id]?jsxRuntime.jsx(hr,{className:"oui-size-3"}):jsxRuntime.jsx(gr,{className:"oui-size-3"})]})},a.id||c))},n))})})]})};});var ht={};Ve(ht,{DesktopDisplayControl:()=>Er,MobileDisplayControl:()=>Mr});var ft=K(()=>{kr();Dr();});var Xr="#008676",ei="#D92D6B",Ne="#131519",ti="#00B49E",ri="#FF447C",ii="#333948",oi="#FFFFFF",ni="#F4F7F9",si="regular 11px Manrope",It={upColor:Xr,downColor:ei,chartBG:Ne,pnlUpColor:ti,pnlDownColor:ri,pnlZoreColor:ii,textColor:oi,qtyTextColor:ni,font:si,volumeUpColor:"#0C3E3A",volumeDownColor:"#5A1E36",closeIcon:"rgba(255, 255, 255, 0.8)"},Lt=(r,e)=>{let t={"paneProperties.background":r.chartBG,"paneProperties.backgroundType":"solid","mainSeriesProperties.candleStyle.upColor":r.upColor,"mainSeriesProperties.candleStyle.downColor":r.downColor,"mainSeriesProperties.candleStyle.borderColor":r.upColor,"mainSeriesProperties.candleStyle.borderUpColor":r.upColor,"mainSeriesProperties.candleStyle.borderDownColor":r.downColor,"mainSeriesProperties.candleStyle.wickUpColor":r.upColor,"mainSeriesProperties.candleStyle.wickDownColor":r.downColor,"paneProperties.separatorColor":"#2B2833","paneProperties.vertGridProperties.color":"#26232F","paneProperties.horzGridProperties.color":"#26232F","scalesProperties.fontSize":e?8:12,"scalesProperties.textColor":"#97969B","paneProperties.legendProperties.showSeriesTitle":!e,"mainSeriesProperties.statusViewStyle.symbolTextSource":"ticker"},i={"volume.volume.color.0":r.volumeDownColor,"volume.volume.color.1":r.volumeUpColor};return {overrides:t,studiesOverrides:i}},ce="Orderly",I=r=>r.includes(":")?r.split(":")[1]:r,ue=r=>r.startsWith(`${ce}:`)?r:`${ce}:${r}`;var ci=(r,e)=>{let i,o=s=>[null,"limit","MARKET","STOP_MARKET","STOP_LIMIT"][s];return {symbolInfo:async s=>(i=e.getSymbolInfo(I(s)),{qty:{min:i?.baseMin??0,max:i?.baseMax??0,step:i?.baseTick??0},pipValue:0,pipSize:i?.quoteTick??0,minTick:i?.quoteTick??0,description:""}),placeOrder:async s=>{let n=["SELL","BUY"][+(s.side>0)],a=s.qty.toString();(s.limitPrice??0).toString();(s.stopPrice??0).toString();let u=I(s.symbol),m=o(s.type);m==="MARKET"?e.sendMarketOrder({side:n,order_quantity:a,symbol:u,order_type:types.OrderType.MARKET}):"LIMIT";},orders:()=>[],positions:()=>[],executions:()=>[],connectionStatus:()=>1,chartContextMenuActions:s=>r.defaultContextMenuActions(s),isTradable:async()=>true,accountManagerInfo:()=>({}),currentAccount:()=>"1",accountsMetainfo:async()=>[{id:"1"}],remove:()=>r?.silentOrdersPlacement().unsubscribe()}},Ot=ci;function V(r){return r===void 0?"":typeof r=="string"?r:r.message}var pe=class{constructor(e,t,i){this._datafeedUrl=e,this._requester=t,this._limitedServerResponse=i;}getBars(e,t,i){let o={symbol:e.ticker||"",resolution:t,from:i.from,to:i.to};return i.countBack!==void 0&&(o.countback=i.countBack),e.currency_code!==void 0&&(o.currencyCode=e.currency_code),e.unit_id!==void 0&&(o.unitId=e.unit_id),new Promise(async(s,n)=>{try{let a=await this._requester.sendRequest(this._datafeedUrl,"history",o),c=this._processHistoryResponse(a);this._limitedServerResponse&&await this._processTruncatedResponse(c,o),s(c);}catch(a){if(a instanceof Error||typeof a=="string"){let c=V(a);n(c);}}})}async _processTruncatedResponse(e,t){let i=e.bars.length;try{for(;this._limitedServerResponse&&this._limitedServerResponse.maxResponseLength>0&&this._limitedServerResponse.maxResponseLength===i&&t.from<t.to;){t.countback&&(t.countback=t.countback-i),this._limitedServerResponse.expectedOrder==="earliestFirst"?t.from=Math.round(e.bars[e.bars.length-1].time/1e3):t.to=Math.round(e.bars[0].time/1e3);let o=await this._requester.sendRequest(this._datafeedUrl,"history",t),s=this._processHistoryResponse(o);i=s.bars.length,this._limitedServerResponse.expectedOrder==="earliestFirst"?(s.bars[0].time===e.bars[e.bars.length-1].time&&s.bars.shift(),e.bars.push(...s.bars)):(s.bars[s.bars.length-1].time===e.bars[0].time&&s.bars.pop(),e.bars.unshift(...s.bars));}}catch(o){if(o instanceof Error||typeof o=="string"){V(o);}}}_processHistoryResponse(e){if(e.s!=="ok"&&e.s!=="no_data")throw new Error(e.errmsg);let t=[],i={noData:false};if(e.s==="no_data")i.noData=true,i.nextTime=e.nextTime;else {let o=e.v!==void 0,s=e.o!==void 0;for(let n=0;n<e.t.length;++n){let a={time:e.t[n]*1e3,close:parseFloat(e.c[n]),open:parseFloat(e.c[n]),high:parseFloat(e.c[n]),low:parseFloat(e.c[n])};s&&(a.open=parseFloat(e.o[n]),a.high=parseFloat(e.h[n]),a.low=parseFloat(e.l[n])),o&&(a.volume=parseFloat(e.v[n])),t.push(a);}}return {bars:t,meta:i}}};var me=class{constructor(e){e&&(this._headers=e);}sendRequest(e,t,i){if(i!==void 0){let s=Object.keys(i);s.length!==0&&(t+="?"),t+=s.map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(i[n].toString())}`).join("&");}""+t;let o={credentials:"same-origin"};return this._headers!==void 0&&(o.headers=this._headers),fetch(`${e}/${t}`,o).then(s=>s.text()).then(s=>JSON.parse(s))}};function f(r,e,t,i){let o=r[e];return Array.isArray(o)&&(!i||Array.isArray(o[0]))?o[t]:o}function ge(r,e,t){return r+(e!==void 0?"_%|#|%_"+e:"")+(t!==void 0?"_%|#|%_"+t:"")}var he=class{constructor(e,t,i){this._exchangesList=["Orderly"];this._symbolsInfo={};this._symbolsList=[];this._datafeedUrl=e,this._datafeedSupportedResolutions=t,this._requester=i,this._readyPromise=this._init(),this._readyPromise.catch(o=>{});}resolveSymbol(e,t,i){return this._readyPromise.then(()=>{let o=this._symbolsInfo[ge(e,t,i)];return o===void 0?Promise.reject("invalid symbol"):Promise.resolve(o)})}searchSymbols(e,t,i,o){return this._readyPromise.then(()=>{let s=[],n=e.length===0;e=e.toUpperCase();for(let c of this._symbolsList){let l=this._symbolsInfo[c];if(l===void 0||i.length>0&&l.type!==i||t&&t.length>0&&l.exchange!==t)continue;let u=l.name.toUpperCase().indexOf(e),m=l.description.toUpperCase().indexOf(e);if((n||u>=0||m>=0)&&!s.some(g=>g.symbolInfo===l)){let g=u>=0?u:8e3+m;s.push({symbolInfo:l,weight:g});}}let a=s.sort((c,l)=>c.weight-l.weight).slice(0,o).map(c=>{let l=c.symbolInfo;return {symbol:l.name,full_name:`${l.exchange}:${l.name}`,description:l.description,exchange:l.exchange,params:[],type:l.type,ticker:l.name}});return Promise.resolve(a)})}_init(){let e=[],t={};for(let i of this._exchangesList)t[i]||(t[i]=true,e.push(this._requestExchangeData(i)));return Promise.all(e).then(()=>{this._symbolsList.sort();})}_requestExchangeData(e){return new Promise((t,i)=>{this._requester.sendRequest(this._datafeedUrl,"symbol_info",{group:e}).then(o=>{try{this._onExchangeDataReceived(e,o);}catch(s){i(s instanceof Error?s:new Error(`SymbolsStorage: Unexpected exception ${s}`));return}t();}).catch(o=>{`${e}${V(o)}`,t();});})}_onExchangeDataReceived(e,t){let i=0;try{let o=t.symbol.length,s=t.ticker!==void 0;for(;i<o;++i){let n=t.symbol[i],a=f(t,"exchange-listed",i),c=f(t,"exchange-traded",i),l=c+":"+n,u=f(t,"currency-code",i),m=f(t,"unit-id",i),y=s?f(t,"ticker",i):n,g={ticker:y,name:n,base_name:[a+":"+n],listed_exchange:a,exchange:c,currency_code:u,original_currency_code:f(t,"original-currency-code",i),unit_id:m,original_unit_id:f(t,"original-unit-id",i),unit_conversion_types:f(t,"unit-conversion-types",i,!0),description:f(t,"description",i),has_intraday:q(f(t,"has-intraday",i),!1),visible_plots_set:q(f(t,"visible-plots-set",i),"ohlcv"),minmov:f(t,"minmovement",i)||f(t,"minmov",i)||0,minmove2:f(t,"minmove2",i)||f(t,"minmov2",i),fractional:f(t,"fractional",i),pricescale:f(t,"pricescale",i),type:f(t,"type",i),session:f(t,"session-regular",i),session_holidays:f(t,"session-holidays",i),corrections:f(t,"corrections",i),timezone:f(t,"timezone",i),supported_resolutions:q(f(t,"supported-resolutions",i,!0),this._datafeedSupportedResolutions),has_daily:q(f(t,"has-daily",i),!0),intraday_multipliers:q(f(t,"intraday-multipliers",i,!0),["1","5","15","30","60"]),has_weekly_and_monthly:f(t,"has-weekly-and-monthly",i),has_empty_bars:f(t,"has-empty-bars",i),volume_precision:q(f(t,"volume-precision",i),0),format:"price"};this._symbolsInfo[y]=g,this._symbolsInfo[n]=g,this._symbolsInfo[l]=g,(u!==void 0||m!==void 0)&&(this._symbolsInfo[ge(y,u,m)]=g,this._symbolsInfo[ge(n,u,m)]=g,this._symbolsInfo[ge(l,u,m)]=g),this._symbolsList.push(n);}}catch(o){throw new Error(`SymbolsStorage: API error when processing exchange ${e} symbol #${i} (${t.symbol[i]}): ${Object(o).message}`)}}};function q(r,e){return r!==void 0?r:e}var fe=class{constructor(e){this._configuration=xt();this._symbolsStorage=null;this._datafeedURL=e,this._requester=new me,this._historyProvider=new pe(e,this._requester),this._configurationReadyPromise=this._requestConfiguration().then(t=>{t===null&&(t=xt()),this._setupWithConfiguration(t);});}getBars(e,t,i,o,s){this._historyProvider.getBars(e,t,i).then(n=>{o(n.bars,n.meta);}).catch(s);}onReady(e){this._configurationReadyPromise.then(()=>{e(this._configuration);});}searchSymbols(e,t,i,o){if(this._symbolsStorage===null)throw new Error("Datafeed: inconsistent configuration (symbols storage)");this._symbolsStorage.searchSymbols(e,t,i,30).then(o).catch(o.bind(null,[]));}resolveSymbol(e,t,i,o){let s=o&&o.currencyCode,n=o&&o.unitId;function c(l){t(l);}if(this._symbolsStorage===null)throw new Error("Datafeed: inconsistent configuration (symbols storage)");this._symbolsStorage.resolveSymbol(e,s,n).then(c).catch(i);}getMarks(){}getTimescaleMarks(){}getServerTime(){}_requestConfiguration(){return this._send("config").catch(e=>(`${V(e)}`,null))}_send(e,t){return this._requester.sendRequest(this._datafeedURL,e,t)}_setupWithConfiguration(e){if(this._configuration=e,e.exchanges===void 0&&(e.exchanges=[]),!e.supports_search&&!e.supports_group_request)throw new Error("Unsupported datafeed configuration. Must either support search, or support group request");(e.supports_group_request||!e.supports_search)&&(this._symbolsStorage=new he(this._datafeedURL,e.supported_resolutions||[],this._requester)),`${JSON.stringify(e)}`;}};function xt(){return {supports_search:false,supports_group_request:true,supported_resolutions:["1","3","5","15","30","60","120","240","480","720","1D","3D","1W","1M"],supports_marks:false,supports_timescale_marks:false}}var be=class{constructor(){this.subscribers=new Map;}subscribe(e,t){return this.subscribers.has(e)||this.subscribers.set(e,[]),this.subscribers.get(e).push(t),()=>{this.unsubscribe(e,t);}}unsubscribe(e,t){if(this.subscribers.has(e)){let i=this.subscribers.get(e);this.subscribers.set(e,i.filter(o=>o!==t)),this.subscribers.get(e).length===0&&this.subscribers.delete(e);}}publish(e,t){this.subscribers.has(e)&&this.subscribers.get(e).forEach(o=>{o(t);});}};var He=r=>{let e="1d";switch(r){case "1":e="1m";break;case "3":e="3m";break;case "5":e="5m";break;case "15":e="15m";break;case "30":e="30m";break;case "60":e="1h";break;case "120":e="2h";break;case "240":e="4h";break;case "480":e="8h";break;case "720":e="12h";break;case "D":case "1D":e="1d";break;case "3D":e="3d";break;case "1W":e="1w";break;case "1M":e="1M ";break;}return e},N={interval:"TradingviewSDK.lastUsedTimeBasedResolution",lineType:"TradingviewSDK.lastUsedStyle",displayControlSetting:"TradingviewSDK.displaySetting"};var Fe=(r,e)=>`${r}kline_${e}`,ui=r=>["trade"].map(t=>`${r}@${t}`),k=class k{constructor(e){this.klineSubscribeIdMap=new Map;this.klineOnTickCallback=new Map;this.subscribeCachedTopics=new Map;this.wsInstance=null;this.klineData=new Map;return k._created||(this.wsInstance=e,k._instance=this,k._created=true),k._instance}subscribeKline(e,t,i,o){let s=He(i);this.klineSubscribeIdMap.set(e,{symbol:t,resolution:i});let n=Fe(t,s);if(this.klineOnTickCallback.has(n)){let a=this.klineOnTickCallback.get(n);a[e]=o;}else {this.klineOnTickCallback.set(n,{[e]:o});let a=this.wsInstance?.subscribe({event:"subscribe",topic:`${t}@kline_${s}`,id:`${t}@kline_${s}`,ts:new Date().getTime()},{onMessage:c=>{let{open:l,close:u,high:m,low:y,volume:g,startTime:b}=c,z=Fe(c.symbol,c.type);this.updateKline(z,{time:b,close:u,open:l,high:m,low:y,volume:g});}});this.subscribeCachedTopics.set(`${t}@kline_${s}`,a);}}unsubscribeKline(e){if(!this.klineSubscribeIdMap.has(e))return;let{symbol:t,resolution:i}=this.klineSubscribeIdMap.get(e),o=He(i),s=Fe(t,o);if(this.klineOnTickCallback.has(s)){let n=this.klineOnTickCallback.get(s);delete n[e],Object.keys(n).length===0&&(this.klineOnTickCallback.delete(s),this.subscribeCachedTopics.get(`${t}@kline_${o}`)());}delete this.klineSubscribeIdMap[e];}subscribeSymbol(e){ui(e).forEach(i=>{if(!this.subscribeCachedTopics.has(i)){let o=this.wsInstance?.subscribe({event:"subscribe",topic:i,id:i,ts:new Date().getTime()},{onMessage:s=>{this.updateKlineByLastPrice(s.symbol,s.price);}});this.subscribeCachedTopics.set(i,o);}});}updateKlineByLastPrice(e,t){this.klineOnTickCallback.forEach((i,o)=>{if(o.startsWith(e)){let s=this.klineData.get(o);s&&this.updateKline(o,{...s,close:t});}});}updateKline(e,t){let i=this.klineOnTickCallback.get(e);i&&t&&(this.klineData.set(e,t),Object.keys(i).forEach(o=>{let s=i[o];s&&typeof s=="function"&&s(t);}));}};k._created=false,k._instance=null;var G=k;var di=(()=>{let r=0;return ()=>r++})(),ye=class extends fe{constructor(t,i){let o=`${t}/tv`;super(o);this.bbosMap=new Map;this.tickersMap=new Map;this.eventBus=new be;this._subscribeQuoteMap=new Map,this._prefixId=di(),this._publicWs=new G(i),this.bbosMap=new Map,i.on("tickers",s=>{for(let n of s.data)n.change=n.close-n.open,n.perChange=n.open?+(100*n.change/n.open).toFixed(2):0,this.tickersMap.set(n.symbol,n);this.eventBus.publish("tickerUpdate",{message:"ticker"});}),i.subscribe({event:"subscribe",topic:"bbos"},{formatter:s=>s,onMessage:s=>{for(let n of s.data)this.bbosMap.set(n.symbol,{ask:n.ask,bid:n.bid,askSize:n.askSize,bidSize:n.bidSize});this.eventBus.publish("tickerUpdate",{message:"bbos"});}});}remove(){Array.from(this._subscribeQuoteMap.values()).forEach(t=>t?.());}getSubscriptionId(t){return `${this._prefixId}${t}`}subscribeBars(t,i,o,s,n){window.onResetCacheNeededCallback=n,this._publicWs.subscribeKline(`${this._prefixId}${s}`,t.ticker,i,o);}unsubscribeBars(t){this._publicWs.unsubscribeKline(`${this._prefixId}${t}`);}getQuotes(t,i){let o=this.getSubscriptionId("getQuotes");this.unsubscribeQuotes("getQuotes");let s=this.eventBus.subscribe("tickerUpdate",n=>{let a=new Map;t.forEach(c=>{let l=this.bbosMap.get(I(c)),u=this.tickersMap.get(I(c));if(!l||!u)return;let m={...u,ask:l.ask,bid:l.bid};a.set(I(c),m);}),a.size&&i(Array.from(a.values()).map(c=>this._toUDFTicker(c)));});this._subscribeQuoteMap.set(o,s);}subscribeQuotes(t,i,o,s){let n=`${this._prefixId}${s}`;if(t.length>0){this.unsubscribeQuotes(n);let a=this.eventBus.subscribe("tickerUpdate",c=>{let l=new Map;t.forEach(u=>{let m=this.bbosMap.get(I(u)),y=this.tickersMap.get(I(u));if(!m||!y)return;let g={...y,ask:m.ask,bid:m.bid};l.set(I(u),g);}),l.size&&o(Array.from(l.values()).map(u=>this._toUDFTicker(u)));});this._subscribeQuoteMap.set(n,a);}}unsubscribeQuotes(t){let i=this.getSubscriptionId(t),o=this._subscribeQuoteMap.get(i);o&&(o(),this._subscribeQuoteMap.delete(i));}_toUDFTicker(t){return {n:ue(t.symbol),s:"ok",v:{ask:t.ask,bid:t.bid,ch:t.change,chp:t.perChange/100,description:"",exchange:ce,hight_price:t.high,low_price:t.low,lp:t.close,open_price:t.open,prev_close_price:0,volume:t.volume}}}};var mi=2,gi="--",Ke=["BRACKET","STOP_BRACKET"],Ce=["POSITIONAL_TP_SL","TP_SL"];var qe=r=>r.root_algo_order_id!==r.algo_order_id&&(r.algo_type==="TAKE_PROFIT"||r.algo_type==="STOP_LOSS"),hi=r=>!!r&&Ke.includes(r);var Ge=r=>r.type==="CLOSE_POSITION",Et=r=>Ge(r)&&r.is_activated,kt=r=>qe(r)&&r.is_activated,We=r=>r.root_algo_order_algo_type==="TP_SL"||hi(r.root_algo_order_algo_type)&&r.is_activated,Mt=(r,e)=>{let t=r.algo_type,i={TAKE_PROFIT:i18n.i18n.t("tpsl.takeProfit"),STOP_LOSS:i18n.i18n.t("tpsl.stopLoss")}[t];return i||null},Dt=r=>{let e=new Map,t=1;return [...r].reverse().filter(We).forEach(i=>{i.root_algo_order_id&&!e.has(i.root_algo_order_id)&&e.set(i.root_algo_order_id,t++);}),e},At=(r,e)=>{let t=Math.abs(r.type==="CLOSE_POSITION"?e.balance:r.quantity),i=r.side==="SELL"?1:-1,o=e.open.toString();return {estPnl:new utils.Decimal(r.trigger_price).minus(o??0).times(t).times(i).toString(),quantity:t,openPrice:o}},Bt=r=>r!==void 0&&r!==""?new utils.Decimal(r).todp(mi,utils.Decimal.ROUND_FLOOR):gi;function Qe(){let[r,{cancelOrder:e,cancelAlgoOrder:t,cancelTPSLChildOrder:i}]=hooks.useOrderStream({status:types.OrderStatus.INCOMPLETE});return R.useCallback(o=>{if(o.algo_order_id){if(Ce.includes(o.root_algo_order_algo_type)){let s=r?.find(a=>a.algo_order_id===o.root_algo_order_id);return s.child_orders.every(a=>!!a.trigger_price)?i(o.algo_order_id,o.root_algo_order_id):t(s.algo_order_id,o.symbol).then()}return t(o.algo_order_id,o.symbol).then()}return e(o.order_id,o.symbol).then()},[e,r])}function $e(r){hooks.useEventEmitter();let [,{updateOrder:t,cancelAlgoOrder:i,updateAlgoOrder:o,updateTPSLOrder:s}]=hooks.useOrderStream({status:types.OrderStatus.INCOMPLETE});return R.useCallback((n,a)=>{if(n.algo_order_id)if(Ce.includes(n.root_algo_order_algo_type)){let l=[{order_id:n.algo_order_id,trigger_price:new utils.Decimal(a.value).toString()}];return s(n.root_algo_order_id,l).then(u=>{}).catch(u=>{r&&r.error(u.message);})}else {if(Ke.includes(n.algo_type))return o(n.algo_order_id,{order_price:new utils.Decimal(a.value).toString()}).then(l=>{}).catch(l=>{r&&r.error(l.message);});{let l={quantity:n.quantity,trigger_price:n.trigger_price,symbol:n.symbol,price:n.price,algo_order_id:n.algo_order_id};return n.order_tag&&(l.order_tag=n.order_tag),n.client_order_id&&(l.client_order_id=n.client_order_id),a.type==="price"&&(l.price=new utils.Decimal(a.value).toString()),a.type==="trigger_price"&&(l.trigger_price=new utils.Decimal(a.value).toString()),o(n.algo_order_id,l).then(u=>{}).catch(u=>{r&&r.error(u.message);})}}let c={order_price:n.price?.toString(),order_quantity:n.quantity.toString(),symbol:n.symbol,order_type:n.type,side:n.side,visible_quantity:0,reduce_only:n.reduce_only};return new utils.Decimal(n.visible_quantity??n.visible??0).eq(n.quantity)&&delete c.visible_quantity,Object.keys(n).includes("reduce_only")||delete c.reduce_only,n.order_tag&&(c.order_tag=n.order_tag),n.client_order_id&&(c.client_order_id=n.client_order_id),a.type==="price"&&(c.order_price=new utils.Decimal(a.value).toString()),t(n.order_id,c).then(l=>{}).catch(l=>{r.error(l.message);})},[t])}function Ze(r){let {onSubmit:e}=hooks.useOrderEntry_deprecated({symbol:r,side:types.OrderSide.BUY,order_type:types.OrderType.MARKET},{watchOrderbook:true});return {sendLimitOrder:()=>{},sendMarketOrder:s=>(s.reduce_only=false,e(s).catch(n=>{ui$1.toast.error(n);}))}}var wi=r=>e=>r(e),Ri=({closeConfirm:r,colorConfig:e,onToast:t,mode:i,symbol:o})=>{let s=Qe(),n=$e(t),a=hooks.useSymbolsInfo(),c=R.useCallback(g=>r&&r(g),[r]),{sendMarketOrder:l,sendLimitOrder:u}=Ze(o),m=R.useCallback(g=>{if(a)return {baseMin:a[g]("base_min"),baseMax:a[g]("base_max"),baseTick:a[g]("base_tick"),quoteTick:a[g]("quote_tick")}},[a]),y=R.useRef({cancelOrder:s,closePosition:c,editOrder:n,colorConfig:e,sendLimitOrder:u,getSymbolInfo:m,sendMarketOrder:wi(l),mode:i});return R.useEffect(()=>{y.current.getSymbolInfo=m;},[a]),R.useEffect(()=>{y.current.sendLimitOrder=u,y.current.sendMarketOrder=l;},[u,l]),R.useEffect(()=>{y.current.closePosition=c;},[r]),R.useEffect(()=>{y.current.cancelOrder=s;},[s]),y.current},Nt=Ri;var Ut={1:{startOf:"minute",period:0},3:{startOf:"hour",period:3*60*1e3},5:{startOf:"hour",period:5*60*1e3},15:{startOf:"hour",period:15*60*1e3},30:{startOf:"hour",period:30*60*1e3},60:{startOf:"hour",period:0},120:{startOf:"day",period:2*60*60*1e3},240:{startOf:"day",period:4*60*60*1e3},480:{startOf:"day",period:8*60*60*1e3},720:{startOf:"day",period:12*60*60*1e3},D:{startOf:"day",period:0},"1D":{startOf:"day",period:0},"3D":{startOf:"year",period:3*24*60*60*1e3},"5D":{startOf:"year",period:5*24*60*60*1e3},"1W":{startOf:"week",period:0},"1M":{startOf:"month",period:0}};function Ft(r,e,t,i){let{startOf:o,period:s}=Ut[t],n=new Date(r.updated_time).getTime(),a=dateFns.startOfSecond(n).getTime();o==="minute"?a=dateFns.startOfMinute(n).getTime():o==="hour"?a=dateFns.startOfHour(n).getTime():o==="day"?a=dateFns.startOfDay(n).getTime():o==="month"?a=dateFns.startOfMonth(n).getTime():o==="year"?a=dateFns.startOfYear(n).getTime():o==="week"?a=dateFns.startOfWeek(n).getTime():o==="month"&&(a=dateFns.startOfMonth(n).getTime());let c=s===0?a:Math.floor((n-a)/s)*s+a;e[c]||(e[c]={BUY:[],SELL:[]}),e[c][r.side].length<5&&(e[c][r.side].push(r),i.push(r));}var Kt=(r,e)=>{let t=[],i={};return Ut[e]?(r.forEach(o=>{if(o.child_orders)for(let s of o.child_orders)s.is_activated&&s.algo_status===types.OrderStatus.FILLED&&Ft(s,i,e,t);else Ft(o,i,e,t);}),t):[]};var _e=class r{constructor(e,t){this.interval="1D";this.changeInterval=e=>{let t=()=>{this.renderExecutions(this.filledOrders,this.basePriceDecimal),this.instance.activeChart().onDataLoaded().unsubscribe(null,t);};this.interval=e,this.instance.activeChart().onDataLoaded().subscribe(null,t);};this.instance=e,this.executions=[],this.filledOrders=[],this.basePriceDecimal=0,this.broker=t,this.subscribeIntervalChange();}async subscribeIntervalChange(){this.interval=this.instance.symbolInterval().interval;let e=this.changeInterval;this.instance.activeChart().onIntervalChanged().subscribe(null,e);}renderExecutions(e,t){this.filledOrders=e,this.basePriceDecimal=t,this.interval&&(this.removeAll(),Kt(e,this.interval).forEach(i=>{this.executions.push(this.drawExecution(i,t));}));}removeAll(){this.executions.forEach(e=>e.remove()),this.executions=[];}static getExecutionInfo(e,t){let i=e.side,o=e.average_executed_price||e.child_orders?.find(n=>!!n.average_executed_price)?.average_executed_price||0,s=new utils.Decimal(o).todp(t,utils.Decimal.ROUND_FLOOR).toString();return `${i==="BUY"?i18n.i18n.t("common.buy"):i18n.i18n.t("common.sell")} ${e.total_executed_quantity} @${utils.commify(s)}`}drawExecution(e,t){let i=e.side,o=e.average_executed_price||e.child_orders?.find(a=>!!a.average_executed_price)?.average_executed_price||0,s=new Date(e.updated_time).getTime()/1e3,n=this.broker.colorConfig;return this.instance.activeChart().createExecutionShape().setArrowHeight(9).setTooltip(r.getExecutionInfo(e,t)).setTime(s).setPrice(o).setArrowColor(i==="BUY"?n.upColor:n.downColor).setDirection(i==="BUY"?"buy":"sell")}unsubscribeIntervalChange(){let e=this.changeInterval;try{this.instance.activeChart().onIntervalChanged().unsubscribe(null,e);}catch(t){t instanceof Error&&t.message;}}destroy(){this.removeAll(),this.unsubscribeIntervalChange();}};var J=r=>{if(r!=null)return r.algo_order_id||r.order_id};var Se=class{constructor(){this.quantityTpslNoMap=new Map,this.tpslPnlMap=new Map,this.positions=null;}getQuantityTpslNoMap(){return this.quantityTpslNoMap}getTpslPnlMap(){return this.tpslPnlMap}getFormattedEstPnl(e){if(this.positions===null)return "";let t=this.positions[0];if(!t)return "";let{estPnl:i}=At(e,t);return Bt(i)}prepareTpslPnlMap(e){let t=[];return e.forEach(i=>{let o=J(i);if(o&&kt(i)){let s=this.tpslPnlMap.get(o),n=this.getFormattedEstPnl(i);s!==n&&(t.push(o),this.tpslPnlMap.set(o,n));}}),t}prepareQuantityTpslNoMap(e){this.quantityTpslNoMap=Dt(e);}recalculatePnl(e,t){return this.positions=e,this.prepareTpslPnlMap(t)}clear(){this.positions=null,this.quantityTpslNoMap.clear(),this.tpslPnlMap.clear();}};var P=class P{constructor(e,t){this.instance=e,this.pendingOrderLineMap=new Map,this.pendingOrders=[],this.broker=t,this.tpslCalService=new Se;}renderPendingOrders(e){e&&(this.pendingOrders=e),this.cleanOldPendingOrders(this.pendingOrders),this.tpslCalService.prepareTpslPnlMap(this.pendingOrders),this.tpslCalService.prepareQuantityTpslNoMap(this.pendingOrders),this.pendingOrders.forEach(t=>this.renderPendingOrder(t));}updatePositions(e){let t=this.tpslCalService.recalculatePnl(e,this.pendingOrders);this.pendingOrders.filter(i=>t.includes(J(i))).forEach(i=>this.renderPendingOrder(i));}renderPendingOrder(e){let t=P.getOrderId(e);if(!t)return;let i=this.drawOrderLine(t,e);i&&this.pendingOrderLineMap.set(t,i);}cleanOldPendingOrders(e){let t=new Set(e.map(i=>P.getOrderId(i)));this.pendingOrderLineMap.forEach((i,o)=>!t.has(o)&&this.removePendingOrder(o));}removePendingOrder(e){if(e===void 0)return;let t=this.pendingOrderLineMap.get(e);t&&(this.pendingOrderLineMap.delete(e),t.remove());}getBaseOrderLine(){let e=this.broker.colorConfig;return this.instance.activeChart().createOrderLine().setCancelTooltip(i18n.i18n.t("orders.cancelOrder")).setQuantityTextColor(e.qtyTextColor).setQuantityBackgroundColor(e.chartBG).setBodyBackgroundColor(e.chartBG).setCancelButtonBackgroundColor(e.chartBG).setLineStyle(1).setBodyFont(e.font).setQuantityFont(e.font)}static getCombinationType(e){let{algo_type:t,type:i}=e;if((t==="STOP_LOSS"||t==="TAKE_PROFIT"||t==="STOP")&&i==="LIMIT")return "STOP_LIMIT";if((t==="STOP_LOSS"||t==="TAKE_PROFIT"||t==="STOP")&&i==="MARKET")return "STOP_MARKET";if(t==="BRACKET"){if(i==="LIMIT")return "BRACKET_LIMIT";if(i==="MARKET")return "BRACKET_MARKET"}return t==="TRAILING_STOP"?"TRAILING_STOP":"LIMIT"}static getText(e){let t=P.getCombinationType(e);return t==="STOP_LIMIT"||t==="STOP_MARKET"||t==="STOP_BRACKET_LIMIT"||t==="STOP_BRACKET_MARKET"?e.type==="LIMIT"?`${i18n.i18n.t("orderEntry.orderType.stopLimit")} ${utils.commify(e.price)}`:i18n.i18n.t("orderEntry.orderType.stopMarket"):t==="TRAILING_STOP"?i18n.i18n.t("orderEntry.trailing"):i18n.i18n.t("orderEntry.orderType.limit")}static getOrderPrice(e){return e.algo_type==="TRAILING_STOP"?utils.getTrailingStopPrice(e):e.trigger_price||e.price}getTPSLTextWithTpsl(e,t){return J(t),e}getTPSLText(e){let t=Mt(e,this.tpslCalService.getQuantityTpslNoMap());return t?this.getTPSLTextWithTpsl(t,e):null}getOrderQuantity(e){if(e.algo_order_id){if(Et(e)||Ge(e))return "100%";if(We(e)){let i=new utils.Decimal(e.quantity).minus(e.executed??0).div(new utils.Decimal(e.position_qty)).mul(100).todp(2).toNumber();return `${Math.min(Math.abs(i),100).toString()}%`}}return utils.commify(new utils.Decimal(e.quantity).toString())}drawOrderLine(e,t){let i=qe(t)?this.getTPSLText(t):P.getText(t);if(i===null)return null;let o=this.broker.colorConfig,s=this.pendingOrderLineMap.get(e)??this.getBaseOrderLine(),n=t.side==="BUY"?o.upColor:o.downColor;t.side==="BUY"?o.pnlUpColor:o.pnlDownColor;let c=P.getOrderPrice(t),l=100,u=this.getOrderQuantity(t),m=o.textColor;return s.setText(i).setCancelButtonIconColor(o.closeIcon).setCancelButtonBorderColor(n).setBodyTextColor(m).setBodyBorderColor(n).setQuantityBorderColor(n).setQuantityTextColor(n).setLineColor(n).setLineLength(l).setQuantity(u??"").setPrice(c),this.broker.mode!==3?(s.onCancel(null,()=>this.broker.cancelOrder(t)),this.applyEditOnMove(s,t)):s.setEditable(false).setCancellable(false),s}static getOrderEditKey(e){let t=this.getCombinationType(e);if(["LIMIT","BRACKET_LIMIT"].includes(t))return "price";if(t==="STOP_LIMIT"||t==="STOP_MARKET"||e.rootAlgoOrderAlgoType==="POSITIONAL_TP_SL"||e.rootAlgoOrderAlgoType==="TP_SL"||e.rootAlgoOrderAlgoType==="BRACKET"||e.rootAlgoOrderAlgoType==="STOP_BRACKET")return "trigger_price"}applyEditOnMove(e,t){let i=P.getOrderEditKey(t);i&&e.onMove(()=>{this.broker.editOrder(t,{type:i,value:`${e.getPrice()}`}).then(o=>{o.success||this.renderPendingOrder(t);}).catch(()=>this.renderPendingOrder(t));});}removeAll(){this.pendingOrderLineMap.forEach(e=>e.remove()),this.pendingOrderLineMap.clear(),this.pendingOrders=[],this.tpslCalService.clear();}};P.getOrderId=e=>{if(e!=null)return e.algo_order_id||e.order_id};var Te=P;var Ie=class r{constructor(e,t){this.instance=e,this.currentSymbol="",this.broker=t,this.positionLines={},this.lastPositions=null;}renderPositions(e){if(e===null||e.length===0){this.removePositions();return}this.lastPositions?.length!==e.length&&this.removePositions(),e[0].symbol!==this.currentSymbol&&(this.removePositions(),this.currentSymbol=e[0].symbol),e.forEach((t,i)=>this.drawPositionLine(t,i)),this.lastPositions=e;}getBasePositionLine(){return this.instance.activeChart().createPositionLine().setTooltip(i18n.i18n.t("positions.closePosition")).setQuantityBackgroundColor(this.broker.colorConfig.chartBG).setCloseButtonBackgroundColor(this.broker.colorConfig.chartBG).setBodyTextColor(this.broker.colorConfig.textColor).setQuantityTextColor(this.broker.colorConfig.qtyTextColor).setBodyFont(this.broker.colorConfig.font).setQuantityFont(this.broker.colorConfig.font).setLineLength(100).setLineStyle(1)}static getPositionQuantity(e){return utils.commify(new utils.Decimal(e).todp(4,utils.Decimal.ROUND_DOWN).toString())}static getPositionPnL(e,t){let i=i18n.i18n.t("tpsl.pnl"),o=new utils.Decimal(e).toFixed(t,utils.Decimal.ROUND_DOWN);return new utils.Decimal(e).eq(0)?`${i} 0`:new utils.Decimal(e).greaterThan(0)?`${i} +${utils.commify(o)}`:`${i} ${utils.commify(o)}`}removePositions(){Object.keys(this.positionLines).forEach(e=>{this.positionLines[Number(e)].remove(),delete this.positionLines[Number(e)];});}drawPositionLine(e,t){let i=this.broker.colorConfig,o=e.unrealPnl>=0,s=e.balance>=0,n=i.pnlZoreColor,a=new utils.Decimal(e.unrealPnl);a.greaterThan(0)?n=i.upColor:a.lessThan(0)&&(n=i.downColor);o?i.pnlUpColor:i.pnlDownColor;let l=s?i.upColor:i.downColor,u=new utils.Decimal(e.open).toNumber();this.positionLines[t]=this.positionLines[t]??this.getBasePositionLine(),this.positionLines[t].setQuantity(r.getPositionQuantity(e.balance)).setPrice(u).setCloseButtonIconColor(i.closeIcon).setCloseButtonBorderColor(l).setBodyBackgroundColor(n).setQuantityTextColor(l).setBodyBorderColor(n).setLineColor(l).setQuantityBorderColor(l).setText(r.getPositionPnL(e.unrealPnl,e.unrealPnlDecimal)),this.broker.mode!==3&&this.positionLines[t].onClose(null,()=>{this.broker.closePosition(e);});}};var Ye=10;var Le=class{constructor(e,t){this.interactiveMode=0;this.tpslElRemoveTimer=null;this.currentPosition=null;this.tpslOrderLine=null;this.tpslPnLVerticalLineEntityId=null;this.tpslVerticalLineTime=null;this.tpslStartCircleEntityId=null;this.tpslEndCircleEntityId=null;this.threshold=10;this.lastArgs=null;this.instance=e,this.broker=t,this.lastPositions=null,this.tpslElRemoveTimer=null,this.currentPosition=null,this.bindEvent();}bindEvent(){this.chart.crossHairMoved().subscribe(null,e=>{if(this.lastArgs=e,this.interactiveMode===2){this.clearTpslElRemoveTimer();return}let t=this.getIntersectantPosition(e);if(!(this.currentPosition&&t&&this.currentPosition.symbol===t.symbol)){if(!t){this.clearTPSLElements();return}t&&(this.clearTpslElRemoveTimer(),this.currentPosition=t,this.createTPSLTriggerButton(e));}});}clearTpslElRemoveTimer(){this.tpslElRemoveTimer&&(clearTimeout(this.tpslElRemoveTimer),this.tpslElRemoveTimer=null);}showTPSLDialog(e){let t=new utils.Decimal(e.price).minus(this.currentPosition.open).mul(this.currentPosition?.balance??0);ui$1.modal.show("TPSLSimpleDialogId",{title:t.gt(0)?i18n.i18n.t("tpsl.TPOrderConfirm"):i18n.i18n.t("tpsl.SLOrderConfirm"),triggerPrice:e.price,type:t.gt(0)?"tp":"sl",symbol:this.currentPosition.symbol,onComplete:()=>{this.clearTPSLElements(),this.chart.setScrollEnabled(true),this.chart.setZoomEnabled(true),this.interactiveMode=0;},showAdvancedTPSLDialog:i=>{this.showAdvancedTPSLDialog({type:t.gt(0)?"tp":"sl",triggerPrice:e.price,qty:i.qty});}}).then(()=>{},i=>{}).finally(()=>{this.clearTPSLElements(),this.chart.setScrollEnabled(true),this.chart.setZoomEnabled(true),this.interactiveMode=0;});}showAdvancedTPSLDialog({type:e,triggerPrice:t,qty:i}){ui$1.modal.show("TPSLDialogId",{withTriggerPrice:true,type:e,triggerPrice:t,symbol:this.currentPosition?.symbol,qty:i,onComplete:()=>{this.clearTPSLElements(),this.chart.setScrollEnabled(true),this.chart.setZoomEnabled(true),this.interactiveMode=0;}}).then(()=>{},o=>{}).finally(()=>{this.clearTPSLElements(),this.chart.setScrollEnabled(true),this.chart.setZoomEnabled(true),this.interactiveMode=0;});}updatePositions(e){this.lastPositions=e,this.threshold=this.generateThreshold();}generateThreshold(){let e=this.chart.getPanes()[0]?.getRightPriceScales()[0];if(!e)return Ye;try{let t=e.getVisiblePriceRange();if(!t)return Ye;let i=t.to-t.from,o=i*.02;return Math.min(o,i)}catch{return Ye}}drawTPSL(e){let{price:t}=e,i=new utils.Decimal(t).minus(this.currentPosition.open).mul(this.currentPosition?.balance??0),{tpslOrderLine:o,verticalLine:s}=this.ensureTPSLElements({price:t,pnl:i}),n=i.gt(0)?i18n.i18n.t("tpsl.tp"):i18n.i18n.t("tpsl.sl"),a=i.gt(0)?this.broker.colorConfig.upColor:this.broker.colorConfig.downColor;o?.setText(`${n} ${i.toDecimalPlaces(2).toNumber()}`).setBodyTextColor(a).setBodyBorderColor(a).setLineColor(a),this.tpslVerticalLineTime&&s?.setPoints([{price:this.currentPosition?.open,time:this.tpslVerticalLineTime},{time:this.tpslVerticalLineTime,price:t}]);}ensureTPSLElements(e){let t=this.tpslOrderLine,i;if(t||(this.tpslOrderLine=this.createTPSLOrderLine()),this.tpslPnLVerticalLineEntityId&&(i=this.chart.getShapeById(this.tpslPnLVerticalLineEntityId)),!i){if(!this.currentPosition||!this.tpslVerticalLineTime)return {};this.tpslPnLVerticalLineEntityId=this.chart.createMultipointShape([{price:this.currentPosition.open,time:this.tpslVerticalLineTime},{time:this.tpslVerticalLineTime,price:e.price}],{shape:"trend_line",lock:true,disableSave:true,disableSelection:true,disableUndo:true,zOrder:"top",overrides:{linecolor:"rgba(255,255,255, 0.2)",linewidth:1,rightEnd:1,leftEnd:1}});}return i?.setProperties({linecolor:e.pnl.gt(0)?this.broker.colorConfig.upColor:this.broker.colorConfig.downColor,linewidth:1}),{tpslOrderLine:t,verticalLine:i}}createTPSLTriggerButton(e){this.tpslOrderLine||(this.tpslOrderLine=this.createTPSLOrderLine()),this.tpslOrderLine.onMove(()=>{let t=this.tpslOrderLine?.getPrice();this.showTPSLDialog({price:t??0});}),this.tpslOrderLine.onMoving(()=>{this.interactiveMode=2;let t=this.tpslOrderLine?.getPrice();this.verticalLineTime(),this.drawTPSL({price:t??0});});}createTPSLOrderLine(){return this.chart.createOrderLine().setCancellable(false).setExtendLeft(true).setTooltip(i18n.i18n.t("tpsl.dragToSet")).setPrice(this.currentPosition.open).setLineLength(-200,"pixel").setText(i18n.i18n.t("common.tpsl")).setQuantity("").setBodyTextColor(this.broker.colorConfig.textColor).setBodyBackgroundColor(this.broker.colorConfig.chartBG).setBodyBorderColor(this.broker.colorConfig.pnlZoreColor).setQuantityBackgroundColor(this.broker.colorConfig.chartBG).setQuantityBorderColor(this.broker.colorConfig.pnlZoreColor).setQuantityTextColor(this.broker.colorConfig.qtyTextColor).setBodyFont(this.broker.colorConfig.font).setQuantityFont(this.broker.colorConfig.font).setLineStyle(3)}verticalLineTime(){let e=this.chart.getVisibleRange();this.tpslVerticalLineTime=this.getTimeAtPercentage(e.from,e.to,90);}clearTPSLElements(){this.tpslElRemoveTimer||(this.tpslElRemoveTimer=setTimeout(()=>{this.currentPosition=null,this.tpslOrderLine&&(this.tpslOrderLine.remove(),this.tpslOrderLine=null),this.tpslPnLVerticalLineEntityId&&(this.chart.removeEntity(this.tpslPnLVerticalLineEntityId),this.tpslPnLVerticalLineEntityId=null),this.tpslElRemoveTimer=null;},100));}getIntersectantPosition(e){if(!Array.isArray(this.lastPositions)||this.lastPositions.length===0)return null;let{price:t,time:i}=e,o=null;for(let s of this.lastPositions)if(s&&Math.abs(s.open-t)<this.threshold){o=s;break}return o}get chart(){return this.instance.activeChart()}getTimeAtPercentage(e,t,i){if(typeof e!="number"||typeof t!="number"||typeof i!="number"||i<0||i>100||e>t)return null;let o=t-e,s=i/100,n=o*s,a=e+n;return Math.round(a)}};var Oe=class{constructor(e,t,i){this.instance=e,this.positionLineService=new Ie(e,i),this.orderLineService=new Te(e,i),this.executionService=new _e(e,i),this.tpslService=new Le(e,i);}async renderPositions(e){await this.chartReady(),await this.onDataLoaded(),this.positionLineService.renderPositions(e),this.orderLineService.updatePositions(e),this.tpslService.updatePositions(e);}async renderPendingOrders(e){await this.chartReady(),this.orderLineService.renderPendingOrders(e);}async renderFilledOrders(e,t){await this.chartReady(),await this.onDataLoaded(),this.executionService.renderExecutions(e,t);}remove(){this.orderLineService.removeAll(),this.positionLineService.removePositions(),this.executionService.destroy();}onDataLoaded(){return this.instance.activeChart().symbolExt()?Promise.resolve():new Promise(e=>this.instance.activeChart().onDataLoaded().subscribe(null,()=>{e();},true))}chartReady(){return new Promise(e=>this.instance.onChartReady(()=>{try{this.instance.activeChart().dataReady(()=>e());}catch(t){t.toString().includes("tradingViewApi");}}))}};function et(r,e){let[t,i]=R.useState(),o=R.useRef(),{state:s}=hooks.useAccount(),[n]=hooks.useLocalStorage("unPnlPriceBasis","markPrice"),[{rows:a},c]=hooks.usePositionStream(r,{calcMode:n}),[l]=hooks.useOrderStream({status:types.OrderStatus.INCOMPLETE,symbol:r}),m=hooks.useSymbolsInfo()?.[r],y=m("quote_dp"),[g]=hooks.useOrderStream({symbol:r,status:types.OrderStatus.FILLED,size:500}),b=R.useRef((S,v,A,F)=>{o.current&&o.current.remove(),o.current=new Oe(S,v,A),i(o.current);}),z=R.useRef(()=>{o.current?.remove(),o.current=void 0;});return R.useEffect(()=>{if(s.status<types.AccountStatusEnum.EnableTrading&&s.status!==types.AccountStatusEnum.EnableTradingWithoutConnected){t?.renderPositions([]);return}if(!e||!e.position){t?.renderPositions([]);return}let S=(a??[]).filter(v=>v.symbol===r).map(v=>({symbol:v.symbol,open:v.average_open_price,balance:v.position_qty,closablePosition:9999,unrealPnl:v.unrealized_pnl??0,interest:0,unrealPnlDecimal:2,basePriceDecimal:4}));t?.renderPositions(S);},[t,a,r,e,s]),R.useEffect(()=>{if(!e||!e.buySell){t?.renderFilledOrders([],6);return}let S=g?.filter(v=>v.symbol===r);t?.renderFilledOrders(S??[],y??6);},[t,g,r,y,e]),R.useEffect(()=>{let S=[],v=[],A=[],F=[],B=[],U=[];if(s.status<types.AccountStatusEnum.EnableTrading&&s.status!==types.AccountStatusEnum.EnableTradingWithoutConnected){t?.renderPendingOrders([]);return}let ne=(a??[]).find(C=>C.symbol===r);l?.forEach(C=>{if(r===C.symbol){if(!C.algo_order_id)A.push(C);else if(C.algo_order_id)if(C.algo_type==="POSITIONAL_TP_SL")for(let T of C.child_orders)T.root_algo_order_algo_type=C.algo_type,T.trigger_price&&T.status!==types.OrderStatus.FILLED&&v.push(T);else if(C.algo_type==="TP_SL"){if(ne)for(let T of C.child_orders)T.root_algo_order_algo_type=C.algo_type,T.position_qty=ne.position_qty,T.trigger_price&&T.status!==types.OrderStatus.FILLED&&S.push(T);}else C.algo_type==="STOP_LOSS"||C.algo_type==="TAKE_PROFIT"?F.push(C):C.algo_type==="BRACKET"?B.push(C):C.algo_type==="TRAILING_STOP"&&C.is_activated&&C.extreme_price&&U.push(C);}}),e&&(e.positionTpsl||(v=[]),e.tpsl||(S=[]),e.limitOrders||(A=[],B=[]),e.stopOrders||(F=[]),e.trailingStop||(U=[])),t?.renderPendingOrders(S.concat(v).concat(A).concat(F).concat(B).concat(U));},[t,l,r,e,a,s.status]),[b.current,z.current]}function Wi(r){r.setBrokerConnectionAdapter=function(e){let t={subscribe:()=>{},unsubscribe:()=>{},unsubscribeAll:()=>{}};Object.defineProperty(e,"_ordersCache",{get:function(){return {start:()=>{},stop:()=>{},update:()=>{},partialUpdate:()=>{},fullUpdate:()=>{},getObjects:async()=>[],updateDelegate:t,partialUpdateDelegate:t}},set:()=>{}}),e._waitForOrderModification=async()=>true,this._adapter=e;};}function Qi(r,e){r.onChartReady(()=>{e.silentOrdersPlacement().subscribe(t=>{t||(e.silentOrdersPlacement().setValue(true),r&&(r._iFrame.contentDocument.querySelector(".wrapper-3X2QgaDd").className="wrapper-3X2QgaDd highButtons-3X2QgaDd"),e.sellBuyButtonsVisibility()?.setValue(false));});});}function tt(r,e){Wi(e),Qi(r,e);}var Yt=(r,e)=>new Promise(t=>{let i=r.querySelector(e);i&&t(i);let o=new MutationObserver(()=>{let s=r.querySelector(e);s&&(t(s),o.disconnect());});o.observe(r,{childList:true,subtree:true});});var we=class{constructor({iframeDocument:e}){this.iframeDocument=e;}defaultHack(){this.showFavoriteStarByDefault();}showFavoriteStarByDefault(){Yt(this.iframeDocument,".dropdown-2R6OKuTS").then(()=>{this.iframeDocument.querySelectorAll(".toolbox-2IihgTnv.showOnHover-2IihgTnv").forEach(t=>{t.style.opacity="1";});});}};var $i=r=>{let e=["header_symbol_search","volume_force_overlay","trading_account_manager","drawing_templates","open_account_manager","right_toolbar","support_multicharts","header_layouttoggle","order_panel","order_info","trading_notifications","display_market_status","broker_button","add_to_watchlist","chart_crosshair_menu","header_fullscreen_button","header_widget"];return r===3&&(e=[...e,"left_toolbar","timeframes_toolbar","go_to_date","timezone_menu","create_volume_indicator_by_default","buy_sell_buttons"]),r===0?e=[...e,"header_widget","left_toolbar","timeframes_toolbar","buy_sell_buttons"]:r===1&&(e=[...e,"left_toolbar","timeframes_toolbar","buy_sell_buttons"]),e};function rt(r,e){return {...r,disabled_features:$i(e),enabled_features:["hide_left_toolbar_by_default","order_panel_close_button","iframe_loading_compatibility_mode"],auto_save_delay:.1,broker_config:{configFlags:{supportStopLimitOrders:true,supportReversePosition:false}}}}var it=r=>`${r}_adapter`,Re={"trading.chart.proterty":JSON.stringify({showSellBuyButtons:0,noConfirmEnabled:1,qweqrq:0,showPricesWithZeroVolume:1,showSpread:1,orderExecutedSoundParams:'{"enabled":0,"name":"alert/alarm_clock"}'}),"hint.startFocusedZoom":"true"},D=new Map;var Zi=(r,e,t)=>{let i=it(r);try{let o=e,s=o?JSON.parse(o):void 0,n=t?JSON.parse(t):Re;return o&&D.set(r,o),t&&D.set(i,t),{savedData:s,adapterSetting:n}}catch{}return {savedData:void 0,adapterSetting:Re}},Jt=async(r,e)=>{let t=it(r),i=localStorage.getItem(r)||"",o=localStorage.getItem(t)||"";try{if(D.has(r)&&D.has(t))return {savedData:JSON.parse(D.get(r)),adapterSetting:JSON.parse(D.get(t))}}catch{}return Zi(r,i,o)},Xt=async(r,e,t)=>{e&&(localStorage.setItem(r,e),D.set(r,e));},er=async(r,e,t)=>{let i=it(r);e&&(localStorage.setItem(i,e),D.set(i,e));};var tr=(r,e)=>{let t=null,i=(...o)=>{t&&window.clearTimeout(t),t=setTimeout(()=>{r(...o);},e);};return i.cancel=()=>{t&&window.clearTimeout(t),t=null;},i},zi="chartProp_default",rr=300,Ee=class{constructor(e){this._instance=null;this._onClick=null;this._datafeed=null;this._chartKey=zi;this._adapterSetting=Re;this._savedData=null;this._isLoggedIn=false;this.debounceSaveChart=tr(()=>{try{this._instance?.save(e=>{Object.is(this._savedData,e)||(this._savedData=e,Xt(this._chartKey,JSON.stringify(e),this._isLoggedIn));});}catch{}},rr*2);this.debounceSaveChartAdapterSetting=tr(()=>{er(this._chartKey,JSON.stringify(this._adapterSetting),this._isLoggedIn);},rr);this._create(e);}remove(){this.unsubscribeClick(),this._datafeed?.remove(),this._broker?.remove(),this._instance?.remove(),this.debounceSaveChart.cancel(),this.debounceSaveChartAdapterSetting.cancel();}updateOverrides(e){this.instance&&this.instance.applyOverrides(e);}setSymbol(e,t,i){try{this._instance?.onChartReady(()=>{let o=t??this._instance?.symbolInterval()?.interval;o||(o=1),this._instance?.setSymbol(e,o,i);});}catch{}}executeActionById(e){try{this._instance?.onChartReady(()=>{this._instance?.activeChart().executeActionById(e);});}catch{}}changeLineType(e){try{this._instance?.onChartReady(()=>{this._instance?.activeChart().setChartType(e);});}catch{}}subscribeClick(e){this._onClick=e,this._instance?.onChartReady(()=>{this._instance?._iFrame.contentDocument?.addEventListener("click",this._onClick);});}unsubscribeClick(){this._instance?._iFrame.contentDocument?.removeEventListener("click",this._onClick);}get instance(){return this._instance}chartHack(){this._instance?.onChartReady(()=>{let e=this._instance._iFrame.contentWindow.document;new we({iframeDocument:e}).defaultHack();});}subscribeAutoSave(){this._instance?.onChartReady(()=>{this._instance?.subscribe("onAutoSaveNeeded",()=>{this.debounceSaveChart();}),this._instance?.activeChart().onVisibleRangeChanged().subscribe(null,()=>{this.debounceSaveChart();});});}async _create({options:e,chartKey:t,mode:i,onClick:o}){let s=e.getBroker,n={fullscreen:e.fullscreen??true,autosize:e.autosize??false,timezone:e.timezone,symbol:e.symbol,library_path:e.libraryPath,interval:e.interval??"1",custom_css_url:e.customCssUrl,custom_font_family:e.customFontFamily,datafeed:e.datafeed,studies_overrides:e.studiesOverrides,locale:e.locale,theme:e.theme,loading_screen:e.loadingScreen,overrides:e.overrides,container:e.container,favorites:{intervals:["1","3","5","15","30","60","240","1D","1W","1M"],chartTypes:["Area","Line"]},broker_factory:s?l=>(this._broker&&this._broker.remove(),this._broker=s(this._instance,l),this._broker):void 0};this._datafeed=e.datafeed,t&&(this._chartKey=t);let{savedData:a,adapterSetting:c}=await Jt(this._chartKey,this._isLoggedIn);this._adapterSetting=c,this._savedData=a,this._instance=new TradingView.widget({...rt(n,i),interval:c["chart.lastUsedTimeBasedResolution"]??n.interval,saved_data:a,settings_adapter:{initialSettings:c,setValue:(l,u)=>{this._adapterSetting={...this._adapterSetting,[l]:u},this.debounceSaveChartAdapterSetting();},removeValue:()=>{}}}),this._instance.onChartReady(()=>{e.symbol&&this._instance?.activeChart().symbol()!==I(e.symbol)&&this.setSymbol(e.symbol);}),this.subscribeAutoSave(),this.subscribeClick(o),this.chartHack();}};var ao="SDK_Tradingview",lo="SDK_Moblie_Tradingview",co=r=>r?lo:ao,uo=r=>r==="id"?"id_ID":r;function at(r){let{scriptSRC:e,libraryPath:t,customCssUrl:i,overrides:o,studiesOverrides:s,symbol:n,theme:a,loadingScreen:c,mode:l,colorConfig:u,locale:m=uo,classNames:y}=r,g=i18n.useLocaleCode(),b=R.useRef(null),z=hooks.useConfig("apiBaseUrl"),{state:S}=hooks.useAccount(),[v,A]=R.useState(types.OrderSide.SELL),F=hooks.useSymbolsInfo(),[B,U]=hooks.useLocalStorage(types.TradingviewFullscreenKey,false),{onSubmit:ne,submitting:C}=hooks.useOrderEntry_deprecated({symbol:n??"",side:v,order_type:types.OrderType.MARKET},{watchOrderbook:true}),[T,Vr]=R.useState(()=>{let d=localStorage.getItem(N.displayControlSetting);return d?JSON.parse(d):{position:true,buySell:true,limitOrders:true,stopOrders:true,tpsl:true,positionTpsl:true,trailingStop:true}}),[Ct,Nr]=R.useState(()=>{let d=localStorage.getItem(N.interval);return d||"15"}),[Hr,Fr]=R.useState(()=>{let d=localStorage.getItem(N.lineType);return d||"1"}),De=hooks.useMediaQuery(types.MEDIA_TABLET),Ae=R.useMemo(()=>Object.assign({},It,u??{}),[u]),Ur=R.useMemo(()=>typeof c=="object"?c:{backgroundColor:Ne},[c]),se=hooks.useWS(),[j,Kr]=R.useState(false),qr=d=>{let ae=F[n];if(!ae)return;let le=new utils.Decimal(d.balance).greaterThan(0)?types.OrderSide.SELL:types.OrderSide.BUY,St={order_quantity:new utils.Decimal(d.balance).abs().toNumber(),symbol:n,order_type:types.OrderType.MARKET,side:le,reduce_only:true};A(le),ui$1.modal.show("MarketCloseConfirmID",{base:ae("base"),quantity:d.balance,onConfirm:async()=>ne(St).catch(Y=>{typeof Y=="string"?ui$1.toast.error(Y):ui$1.toast.error(Y.message);}),submitting:C});},E=R.useRef(null),vt=R.useMemo(()=>!(S.status<types.AccountStatusEnum.EnableTrading&&S.status!==types.AccountStatusEnum.EnableTradingWithoutConnected),[S]),_t=Nt({closeConfirm:qr,colorConfig:Ae,onToast:ui$1.toast,symbol:n??"",mode:l}),[Gr,Wr]=et(n,T),Qr=()=>{U(!B),r.onFullScreenChange?.(!B);},$r=d=>{b.current&&(localStorage.setItem(N.interval,d),Nr(d),b.current?.setSymbol(n??"",d));},Zr=d=>{b.current&&(localStorage.setItem(N.lineType,d),Fr(d),b.current?.changeLineType(Number(d)));},zr=d=>{localStorage.setItem(N.displayControlSetting,JSON.stringify(d)),Vr(d);},jr=()=>{b.current&&b.current.executeActionById("chartProperties");},Yr=()=>{b.current&&b.current.executeActionById("insertIndicator");};return R.useEffect(()=>{if(e&&E.current&&!j){let d=document.createElement("script");d.setAttribute("data-nscript","afterInteractive"),d.src=e,d.async=true,d.type="text/javascript",d.onload=()=>{Kr(true);},d.onerror=()=>{},E.current.appendChild(d);}},[E,j,e]),R.useEffect(()=>{if(!n||!j||!e)return;let d=Lt(Ae,De),ae=o?Object.assign({},d.overrides,o):d.overrides,le=s?Object.assign({},d.studiesOverrides,s):d.studiesOverrides;if(E.current){let Y={options:{fullscreen:false,autosize:true,symbol:ue(n),locale:typeof m=="function"?m(g):m,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,container:E.current,libraryPath:t,customCssUrl:i,interval:Ct??"1",theme:a??"dark",loadingScreen:Ur??{},overrides:ae,studiesOverrides:le,datafeed:new ye(z,se),contextMenu:{items_processor:async Be=>Be},getBroker:(Be,Tt)=>(tt(Be,Tt),Ot(Tt,_t))},chartKey:co(De),mode:l,onClick:()=>{}};b.current=new Ee(Y);}return ()=>{b.current?.remove();}},[j,De,l,b,E,j,e,Ae,m,g]),R.useEffect(()=>{se.on("status:change",d=>{!d.isPrivate&&d.isReconnect&&typeof window.onResetCacheNeededCallback=="function"&&(window.onResetCacheNeededCallback(),b.current?.instance&&b.current?.instance.activeChart()?.resetData());},"tradingview");},[se]),R.useEffect(()=>(b.current&&b.current?.instance&&b.current?.instance?.onChartReady(()=>{vt&&b.current?.instance&&Gr(b.current.instance,void 0,_t,E.current);}),()=>{Wr();}),[b.current,vt]),R.useEffect(()=>{if(!n||!b.current)return;b.current?.setSymbol(n);let d=new G(se);return d.subscribeSymbol(n),()=>{d.unsubscribeKline(n);}},[n]),{tradingViewScriptSrc:e,chartRef:E,changeDisplaySetting:zr,displayControlState:T,interval:Ct,changeInterval:$r,lineType:Hr,changeLineType:Zr,openChartSetting:jr,openChartIndicators:Yr,symbol:n,onFullScreenChange:Qr,classNames:y,fullscreen:B}}Z();var yr=r=>{let{url:e,children:t}=r;return jsxRuntime.jsx("span",{onClick:()=>window.open(e),className:"oui-cursor-pointer oui-px-0.5 oui-text-primary-light oui-underline",children:t})},Cr=()=>{let{t:r}=i18n.useTranslation();return jsxRuntime.jsx("div",{className:"oui-absolute oui-inset-0 oui-z-0 oui-flex oui-flex-col oui-items-center oui-justify-start oui-p-2 oui-text-base-contrast-80 md:oui-justify-center md:oui-p-10",children:jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("p",{className:"oui-mb-6 oui-text-xs",children:r("tradingView.noScriptSrc")}),jsxRuntime.jsx("p",{className:"oui-mb-3 oui-pl-0 oui-text-2xs oui-text-base-contrast-54 md:oui-pl-2 md:oui-text-base md:oui-text-base-contrast-80",children:jsxRuntime.jsx(i18n.Trans,{i18nKey:"tradingView.noScriptSrc.1",components:[jsxRuntime.jsx(yr,{url:"https://www.tradingview.com/advanced-charts"},"tradingview-advanced-charts")]})}),jsxRuntime.jsx("p",{className:"oui-pl-0 oui-text-2xs oui-text-base-contrast-54 md:oui-pl-2 md:oui-text-base md:oui-text-base-contrast-80",children:jsxRuntime.jsx(i18n.Trans,{i18nKey:"tradingView.noScriptSrc.2",components:[jsxRuntime.jsx(yr,{url:"https://orderly.network/docs/sdks/react/components/trading#tradingviewconfig"},"tradingview-config")]})})]})})};var go=r=>jsxRuntime.jsx("div",{className:"top-toolbar oui-flex oui-h-[44px] oui-justify-between md:oui-justify-start oui-items-center oui-p-2 md:oui-px-3 md:oui-pt-3 md:oui-pb-[14px]",children:r.children}),vr=go;var ln=R__default.default.lazy(()=>Promise.resolve().then(()=>(Or(),Lr))),Br=R__default.default.lazy(()=>Promise.resolve().then(()=>(Rr(),wr)).then(r=>({default:r.TimeInterval}))),cn=R__default.default.lazy(()=>Promise.resolve().then(()=>(ft(),ht)).then(r=>({default:r.MobileDisplayControl}))),un=R__default.default.lazy(()=>Promise.resolve().then(()=>(ft(),ht)).then(r=>({default:r.DesktopDisplayControl}))),bt=({children:r,onClick:e})=>jsxRuntime.jsx(ui$1.Box,{onClick:e,className:"oui-cursor-pointer oui-w-[18px] oui-h-[18px] oui-text-base-contrast-36 hover:oui-text-base-contrast-80",children:r}),dn=r=>jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 18 18",fill:"currentColor",...r,children:jsxRuntime.jsx("path",{d:"M15.0008 2.24304C14.8088 2.24304 14.6085 2.30755 14.4615 2.4538L11.2508 5.66455V3.74304H9.75079V7.49304C9.75079 7.90704 10.0868 8.24304 10.5008 8.24304H14.2508V6.74304H12.3285L15.54 3.53229C15.8325 3.23904 15.8325 2.74705 15.54 2.4538C15.393 2.30755 15.1928 2.24304 15.0008 2.24304ZM3.7508 9.74303V11.243H5.67231L2.46156 14.4538C2.16906 14.747 2.16906 15.239 2.46156 15.5323C2.75481 15.8248 3.2468 15.8248 3.54005 15.5323L6.7508 12.3215V14.243H8.25079V10.493C8.25079 10.079 7.9148 9.74303 7.5008 9.74303H3.7508Z"})}),pn=r=>jsxRuntime.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 18 18",fill:"currentColor",...r,children:jsxRuntime.jsx("path",{d:"M7.49219 9.74304C7.30026 9.74304 7.09964 9.80755 6.95309 9.9538L3.74219 13.1646V11.243H2.24219V14.993C2.24219 15.407 2.57796 15.743 2.99219 15.743H6.74219V14.243H4.82031L8.03121 11.0323C8.32416 10.739 8.32416 10.247 8.03121 9.9538C7.88481 9.80755 7.68404 9.74304 7.49219 9.74304ZM11.2509 2.24304V3.74304H13.1728L9.96186 6.9538C9.66899 7.24705 9.66899 7.73904 9.96186 8.03229C10.2547 8.32479 10.7471 8.32479 11.04 8.03229L14.2509 4.82153V6.74304H15.7509V2.99304C15.7509 2.57904 15.4151 2.24304 15.0009 2.24304H11.2509Z"})}),yt=R.forwardRef((r,e)=>{let{chartRef:t,interval:i,changeDisplaySetting:o,displayControlState:s,tradingViewScriptSrc:n,changeInterval:a,lineType:c,changeLineType:l,openChartSetting:u,openChartIndicators:m,onFullScreenChange:y}=r,g=hooks.useMediaQuery(types.MEDIA_TABLET);return jsxRuntime.jsx("div",{ref:e,className:ui$1.cn("oui-relative oui-size-full",r.classNames?.root),children:n?jsxRuntime.jsxs("div",{className:ui$1.cn("oui-absolute oui-inset-0 oui-z-[1] oui-flex oui-flex-col",r.classNames?.content),children:[jsxRuntime.jsx(vr,{children:g?jsxRuntime.jsxs(ui$1.Flex,{gapX:2,width:"100%",justify:"between",className:"oui-hide-scrollbar oui-overflow-x-scroll",children:[jsxRuntime.jsx(R__default.default.Suspense,{fallback:null,children:jsxRuntime.jsx(Br,{interval:i??"15",changeInterval:a})}),jsxRuntime.jsx(bt,{onClick:m,children:jsxRuntime.jsx(lt,{})}),jsxRuntime.jsx(R__default.default.Suspense,{fallback:null,children:jsxRuntime.jsx(cn,{displayControlState:s,changeDisplayControlState:o})})]}):jsxRuntime.jsxs(ui$1.Flex,{justify:"between",itemAlign:"center",width:"100%",children:[jsxRuntime.jsxs(ui$1.Flex,{children:[jsxRuntime.jsx(R__default.default.Suspense,{fallback:null,children:jsxRuntime.jsx(Br,{interval:i??"1",changeInterval:a})}),jsxRuntime.jsx(ui$1.Divider,{direction:"vertical",className:"oui-h-4",mx:2,intensity:8}),jsxRuntime.jsxs(ui$1.Flex,{justify:"start",itemAlign:"center",gap:2,children:[jsxRuntime.jsx(R__default.default.Suspense,{fallback:null,children:jsxRuntime.jsx(un,{displayControlState:s,changeDisplayControlState:o})}),jsxRuntime.jsx(bt,{onClick:m,children:jsxRuntime.jsx(lt,{})}),jsxRuntime.jsx(R__default.default.Suspense,{fallback:null,children:jsxRuntime.jsx(ln,{lineType:c,changeLineType:l})}),jsxRuntime.jsx(bt,{onClick:u,children:jsxRuntime.jsx(ar,{})})]})]}),jsxRuntime.jsx(ui$1.Flex,{children:r.fullscreen?jsxRuntime.jsx(dn,{className:"oui-text-base-contrast-54 hover:oui-text-base-contrast oui-cursor-pointer",onClick:y}):jsxRuntime.jsx(pn,{className:"oui-text-base-contrast-54 hover:oui-text-base-contrast oui-cursor-pointer",onClick:y})})]})}),jsxRuntime.jsx("div",{ref:t,className:"oui-size-full oui-overflow-hidden"})]}):jsxRuntime.jsx(Cr,{})})});var gn=R.forwardRef((r,e)=>{let t=at(r);return jsxRuntime.jsx(yt,{...t,ref:e})});
16
+ var __defProp = Object.defineProperty;
17
+ var __getOwnPropNames = Object.getOwnPropertyNames;
18
+ var __esm = (fn, res) => function __init() {
19
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
20
+ };
21
+ var __export = (target, all) => {
22
+ for (var name in all)
23
+ __defProp(target, name, { get: all[name], enumerable: true });
24
+ };
25
+ var CaretIcon, DisplaySettingIcon, IndicatorsIcon, SettingIcon, BarIcon, CandlesIcon, HollowCandlesIcon, LineIcon, AreaIcon, BaseLineIcon, UnSelectIcon, SelectedIcon;
26
+ var init_icons = __esm({
27
+ "src/icons/index.tsx"() {
28
+ CaretIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
29
+ "svg",
30
+ {
31
+ viewBox: "0 0 12 12",
32
+ fill: "currentColor",
33
+ xmlns: "http://www.w3.org/2000/svg",
34
+ ...props,
35
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Caret-down", children: /* @__PURE__ */ jsxRuntime.jsx(
36
+ "path",
37
+ {
38
+ id: "Vector",
39
+ d: "M3.00349 3.9978C2.59149 3.9978 2.36564 4.4653 2.61289 4.7948C2.98789 5.2948 5.23784 8.29479 5.61289 8.79479C5.81289 9.06128 6.20974 9.06128 6.40974 8.79479L9.40974 4.7948C9.65694 4.4653 9.41554 3.9978 9.00349 3.9978H3.00349Z"
40
+ }
41
+ ) })
42
+ }
43
+ );
44
+ DisplaySettingIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
45
+ "svg",
46
+ {
47
+ viewBox: "0 0 18 18",
48
+ fill: "currentColor",
49
+ xmlns: "http://www.w3.org/2000/svg",
50
+ ...props,
51
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Display settings", children: /* @__PURE__ */ jsxRuntime.jsx(
52
+ "path",
53
+ {
54
+ id: "Union",
55
+ fillRule: "evenodd",
56
+ clipRule: "evenodd",
57
+ d: "M15.0571 10.9856L11.6295 5.06523L8.71377 10.8968C8.38933 11.5456 7.54464 11.7223 6.98733 11.2579L5.75311 10.2294L2.83709 14.7654L1.57532 13.9543L4.49134 9.41824C4.97892 8.65978 6.0207 8.49981 6.71338 9.07705L7.58387 9.80246L10.5991 3.77192C10.9997 2.97082 12.1302 2.93624 12.579 3.71137L14.6517 7.29147C14.7714 7.03643 15.0305 6.85983 15.3309 6.85983C15.7451 6.85983 16.0809 7.19562 16.0809 7.60983C16.0809 8.02405 15.7451 8.35983 15.3309 8.35983C15.31 8.35983 15.2892 8.35897 15.2687 8.35729L16.3553 10.2341L15.0571 10.9856ZM2.58093 6.85983C2.16672 6.85983 1.83093 7.19562 1.83093 7.60983C1.83093 8.02405 2.16672 8.35983 2.58093 8.35983C2.99515 8.35983 3.33093 8.02405 3.33093 7.60983C3.33093 7.19562 2.99515 6.85983 2.58093 6.85983ZM4.83093 6.85983C4.41672 6.85983 4.08093 7.19562 4.08093 7.60983C4.08093 8.02405 4.41672 8.35983 4.83093 8.35983C5.24515 8.35983 5.58093 8.02405 5.58093 7.60983C5.58093 7.19562 5.24515 6.85983 4.83093 6.85983ZM6.33093 7.60983C6.33093 7.19562 6.66672 6.85983 7.08093 6.85983C7.49515 6.85983 7.83093 7.19562 7.83093 7.60983C7.83093 8.02405 7.49515 8.35983 7.08093 8.35983C6.66672 8.35983 6.33093 8.02405 6.33093 7.60983ZM11.5809 6.85983C11.1667 6.85983 10.8309 7.19562 10.8309 7.60983C10.8309 8.02405 11.1667 8.35983 11.5809 8.35983C11.9951 8.35983 12.3309 8.02405 12.3309 7.60983C12.3309 7.19562 11.9951 6.85983 11.5809 6.85983Z"
58
+ }
59
+ ) })
60
+ }
61
+ );
62
+ IndicatorsIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
63
+ "svg",
64
+ {
65
+ viewBox: "0 0 18 18",
66
+ fill: "currentColor",
67
+ xmlns: "http://www.w3.org/2000/svg",
68
+ ...props,
69
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Indicators", children: /* @__PURE__ */ jsxRuntime.jsx(
70
+ "path",
71
+ {
72
+ id: "Union",
73
+ fillRule: "evenodd",
74
+ clipRule: "evenodd",
75
+ d: "M9.74483 2.25C8.96145 2.25 8.26885 2.76459 8.04549 3.51818L7.46202 5.48254H5.06262V7.08339H6.98652L5.00539 13.7532L4.31554 13.1112L3.22498 14.2831L4.4777 15.4489C5.08739 16.015 6.08317 15.7469 6.32134 14.945L8.65649 7.08339H11.6032V5.48254H9.13198L9.58033 3.97311C9.60167 3.90112 9.66833 3.85084 9.74483 3.85084H11.69V2.25H9.74483ZM10.6234 11.2354L10.2638 11.5172C10.0153 11.712 9.65591 11.6684 9.46115 11.4199C9.26639 11.1713 9.30998 10.812 9.55852 10.6172L10.1451 10.1575C10.5693 9.82514 11.1868 9.94011 11.4642 10.4005L11.4682 10.407L12.1304 11.5752L13.4594 10.3111C13.6882 10.0935 14.05 10.1025 14.2677 10.3313C14.4853 10.5601 14.4763 10.922 14.2475 11.1396L12.7116 12.6006L13.3897 13.797L13.6482 13.4503C13.8369 13.1972 14.1951 13.145 14.4483 13.3337C14.7014 13.5225 14.7536 13.8807 14.5649 14.1338L13.9917 14.9025L13.94 14.9457C13.5178 15.2981 12.8837 15.1886 12.6003 14.7226L12.5958 14.7151L11.8576 13.4129L10.3563 14.841C10.1275 15.0586 9.76561 15.0495 9.54798 14.8208C9.33036 14.592 9.3394 14.2301 9.56819 14.0125L11.2764 12.3875L10.6234 11.2354Z"
76
+ }
77
+ ) })
78
+ }
79
+ );
80
+ SettingIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
81
+ "svg",
82
+ {
83
+ viewBox: "0 0 18 18",
84
+ fill: "currentColor",
85
+ xmlns: "http://www.w3.org/2000/svg",
86
+ ...props,
87
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Setting", children: /* @__PURE__ */ jsxRuntime.jsx(
88
+ "path",
89
+ {
90
+ id: "Vector",
91
+ d: "M6.72589 1.84154C5.66239 2.17904 4.74515 2.72954 3.93665 3.48254C3.6869 3.71504 3.6104 4.09604 3.7724 4.39604C4.37315 5.50679 3.74464 6.69554 2.38939 6.76379C2.05789 6.78029 1.76465 7.0263 1.68665 7.34955C1.5524 7.9083 1.49915 8.37629 1.49915 8.98979C1.49915 9.50504 1.55464 10.0885 1.66339 10.6075C1.73089 10.9315 2.0129 11.1648 2.3429 11.1933C3.7064 11.311 4.3814 12.3513 3.7724 13.6773C3.6374 13.972 3.6989 14.3245 3.93665 14.545C4.73315 15.2815 5.64814 15.8013 6.72589 16.1388C7.03339 16.2348 7.38064 16.1185 7.56964 15.8575C8.40364 14.7033 9.6134 14.6995 10.4054 15.8575C10.5921 16.1298 10.9341 16.261 11.2491 16.162C12.2894 15.8343 13.2584 15.277 14.0616 14.545C14.3091 14.3193 14.3744 13.954 14.2259 13.654C13.6019 12.3948 14.3197 11.239 15.6082 11.2165C15.9502 11.2105 16.2547 10.9863 16.3349 10.654C16.4647 10.1163 16.4991 9.64829 16.4991 8.98979C16.4991 8.42429 16.4324 7.86704 16.3116 7.32629C16.2351 6.98354 15.9359 6.74054 15.5849 6.73979C14.3167 6.73754 13.6056 5.49104 14.2259 4.39604C14.3984 4.09154 14.3444 3.71804 14.0849 3.48254C13.2674 2.74004 12.2706 2.15954 11.2259 1.84154C10.9049 1.74404 10.5636 1.86404 10.3821 2.14604C9.65764 3.27179 8.30465 3.29129 7.5929 2.17004C7.41065 1.88204 7.04989 1.73879 6.72589 1.84154ZM11.2844 3.43455C11.7966 3.64905 12.2009 3.8733 12.6651 4.22505C12.1206 5.9478 13.0439 7.73729 14.9564 8.17304C15.0036 8.48279 14.9991 8.67029 14.9991 8.98979C14.9991 9.37154 15.0044 9.50579 14.9609 9.78179C13.0566 10.1763 12.1146 11.9155 12.6449 13.7538C12.1889 14.0845 11.8626 14.314 11.2904 14.5353C9.94639 13.1673 8.0804 13.1073 6.7079 14.5443C6.1724 14.3088 5.76066 14.0995 5.34441 13.7478C5.86041 11.881 4.98815 10.2693 3.05165 9.7803C2.9654 9.4383 2.9999 8.4723 3.0494 8.17905C5.0519 7.69905 5.8409 5.92679 5.34365 4.21979C5.78315 3.88904 6.1784 3.6483 6.69215 3.4398C7.9859 4.75605 9.92839 4.8873 11.2844 3.43455ZM8.99915 5.98979C7.3424 5.98979 5.99915 7.33304 5.99915 8.98979C5.99915 10.6473 7.3424 11.9898 8.99915 11.9898C10.6559 11.9898 11.9991 10.6473 11.9991 8.98979C11.9991 7.33304 10.6559 5.98979 8.99915 5.98979ZM8.99915 7.48979C9.8279 7.48979 10.4991 8.16179 10.4991 8.98979C10.4991 9.81855 9.8279 10.4898 8.99915 10.4898C8.1704 10.4898 7.49915 9.81855 7.49915 8.98979C7.49915 8.16179 8.1704 7.48979 8.99915 7.48979Z"
92
+ }
93
+ ) })
94
+ }
95
+ );
96
+ BarIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
97
+ "svg",
98
+ {
99
+ viewBox: "0 0 20 20",
100
+ fill: "currentColor",
101
+ xmlns: "http://www.w3.org/2000/svg",
102
+ ...props,
103
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Bars", children: /* @__PURE__ */ jsxRuntime.jsx(
104
+ "path",
105
+ {
106
+ id: "Union",
107
+ fillRule: "evenodd",
108
+ clipRule: "evenodd",
109
+ d: "M12.5 15.5C12.5 15.7761 12.7239 16 13 16H14C14.2761 16 14.5 15.7761 14.5 15.5V14H16C16.2761 14 16.5 13.7761 16.5 13.5V12.5C16.5 12.2239 16.2761 12 16 12H14.5V2.5C14.5 2.22386 14.2761 2 14 2H13C12.7239 2 12.5 2.22386 12.5 2.5V4H11C10.7239 4 10.5 4.22386 10.5 4.5V5.5C10.5 5.77614 10.7239 6 11 6H12.5V15.5ZM5.5 17.5C5.5 17.7761 5.72386 18 6 18H7C7.27614 18 7.5 17.7761 7.5 17.5V10H9C9.27614 10 9.5 9.77614 9.5 9.5V8.5C9.5 8.22386 9.27614 8 9 8H7.5V4.5C7.5 4.22386 7.27614 4 7 4H6C5.72386 4 5.5 4.22386 5.5 4.5V14H4C3.72386 14 3.5 14.2239 3.5 14.5V15.5C3.5 15.7761 3.72386 16 4 16H5.5V17.5Z"
110
+ }
111
+ ) })
112
+ }
113
+ );
114
+ CandlesIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
115
+ "svg",
116
+ {
117
+ viewBox: "0 0 20 20",
118
+ fill: "currentColor",
119
+ xmlns: "http://www.w3.org/2000/svg",
120
+ ...props,
121
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Candles", children: /* @__PURE__ */ jsxRuntime.jsx(
122
+ "path",
123
+ {
124
+ id: "Union",
125
+ fillRule: "evenodd",
126
+ clipRule: "evenodd",
127
+ d: "M7.25 2.5V4H8.5C8.77614 4 9 4.22386 9 4.5V15.5C9 15.7761 8.77614 16 8.5 16H7.25V17.5C7.25 17.7761 7.02614 18 6.75 18H6.25C5.97386 18 5.75 17.7761 5.75 17.5V16H4.5C4.22386 16 4 15.7761 4 15.5V4.5C4 4.22386 4.22386 4 4.5 4H5.75V2.5C5.75 2.22386 5.97386 2 6.25 2H6.75C7.02614 2 7.25 2.22386 7.25 2.5ZM5.5 5.5V14.5H7.5V5.5H5.5ZM14.25 4.5V7H15.5C15.7761 7 16 7.22386 16 7.5V15.5C16 15.7761 15.7761 16 15.5 16H14.25V17.5C14.25 17.7761 14.0261 18 13.75 18H13.25C12.9739 18 12.75 17.7761 12.75 17.5V16H11.5C11.2239 16 11 15.7761 11 15.5V7.5C11 7.22386 11.2239 7 11.5 7H12.75V4.5C12.75 4.22386 12.9739 4 13.25 4H13.75C14.0261 4 14.25 4.22386 14.25 4.5ZM12.5 8.5V14.5H14.5V8.5H12.5Z"
128
+ }
129
+ ) })
130
+ }
131
+ );
132
+ HollowCandlesIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
133
+ "svg",
134
+ {
135
+ viewBox: "0 0 20 20",
136
+ fill: "currentColor",
137
+ xmlns: "http://www.w3.org/2000/svg",
138
+ ...props,
139
+ children: /* @__PURE__ */ jsxRuntime.jsxs("g", { id: "Hollow Candles", children: [
140
+ /* @__PURE__ */ jsxRuntime.jsx(
141
+ "path",
142
+ {
143
+ id: "Subtract",
144
+ fillRule: "evenodd",
145
+ clipRule: "evenodd",
146
+ d: "M5.5 14.5V5.5H7.5V14.5H5.5Z",
147
+ fill: "white",
148
+ fillOpacity: "0.12"
149
+ }
150
+ ),
151
+ /* @__PURE__ */ jsxRuntime.jsx(
152
+ "path",
153
+ {
154
+ id: "Union",
155
+ fillRule: "evenodd",
156
+ clipRule: "evenodd",
157
+ d: "M7.25 2.5V4H8.5C8.77614 4 9 4.22386 9 4.5V15.5C9 15.7761 8.77614 16 8.5 16H7.25V17.5C7.25 17.7761 7.02614 18 6.75 18H6.25C5.97386 18 5.75 17.7761 5.75 17.5V16H4.5C4.22386 16 4 15.7761 4 15.5V4.5C4 4.22386 4.22386 4 4.5 4H5.75V2.5C5.75 2.22386 5.97386 2 6.25 2H6.75C7.02614 2 7.25 2.22386 7.25 2.5ZM5.5 5.5V14.5H7.5V5.5H5.5ZM14.25 4.5V7H15.5C15.7761 7 16 7.22386 16 7.5V15.5C16 15.7761 15.7761 16 15.5 16H14.25V17.5C14.25 17.7761 14.0261 18 13.75 18H13.25C12.9739 18 12.75 17.7761 12.75 17.5V16H11.5C11.2239 16 11 15.7761 11 15.5V7.5C11 7.22386 11.2239 7 11.5 7H12.75V4.5C12.75 4.22386 12.9739 4 13.25 4H13.75C14.0261 4 14.25 4.22386 14.25 4.5ZM12.5 8.5V14.5H14.5V8.5H12.5Z"
158
+ }
159
+ )
160
+ ] })
161
+ }
162
+ );
163
+ LineIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
164
+ "svg",
165
+ {
166
+ viewBox: "0 0 20 20",
167
+ fill: "currentColor",
168
+ xmlns: "http://www.w3.org/2000/svg",
169
+ ...props,
170
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Line", children: /* @__PURE__ */ jsxRuntime.jsx(
171
+ "path",
172
+ {
173
+ id: "Vector 16 (Stroke)",
174
+ fillRule: "evenodd",
175
+ clipRule: "evenodd",
176
+ d: "M18.3 2.72288C18.542 2.85596 18.6303 3.15999 18.4972 3.40195L13.495 12.4968C13.0776 13.2557 12.1061 13.5044 11.3754 13.0394L7.19878 10.3816L2.97738 17.558C2.83737 17.796 2.53092 17.8754 2.2929 17.7354L1.43097 17.2284C1.19295 17.0884 1.1135 16.7819 1.25351 16.5439L5.73746 8.92122C6.16792 8.18943 7.1194 7.96045 7.83567 8.41626L11.9995 11.0659L16.7448 2.43811C16.8778 2.19615 17.1819 2.10788 17.4238 2.24096L18.3 2.72288Z"
177
+ }
178
+ ) })
179
+ }
180
+ );
181
+ AreaIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
182
+ "svg",
183
+ {
184
+ viewBox: "0 0 20 20",
185
+ fill: "currentColor",
186
+ xmlns: "http://www.w3.org/2000/svg",
187
+ ...props,
188
+ children: /* @__PURE__ */ jsxRuntime.jsxs("g", { id: "Area", children: [
189
+ /* @__PURE__ */ jsxRuntime.jsx(
190
+ "path",
191
+ {
192
+ id: "Vector 16 (Stroke)",
193
+ fillRule: "evenodd",
194
+ clipRule: "evenodd",
195
+ d: "M18.3 2.72288C18.542 2.85596 18.6303 3.15999 18.4972 3.40195L13.495 12.4968C13.0776 13.2557 12.1061 13.5044 11.3754 13.0394L7.19878 10.3816L2.97738 17.558C2.83737 17.796 2.53092 17.8754 2.2929 17.7354L1.43097 17.2284C1.19295 17.0884 1.1135 16.7819 1.25351 16.5439L5.73746 8.92122C6.16792 8.18943 7.1194 7.96045 7.83567 8.41626L11.9995 11.0659L16.7448 2.43811C16.8778 2.19615 17.1819 2.10788 17.4238 2.24096L18.3 2.72288Z"
196
+ }
197
+ ),
198
+ /* @__PURE__ */ jsxRuntime.jsx(
199
+ "path",
200
+ {
201
+ id: "Subtract",
202
+ fillRule: "evenodd",
203
+ clipRule: "evenodd",
204
+ d: "M2.7608 17.7562C2.84602 17.899 3.00106 18 3.19016 18H16.362C17.4665 18 18.362 17.1046 18.362 16V3.94663C18.362 3.86618 18.3453 3.79397 18.3162 3.73108L13.495 12.4968C13.0776 13.2557 12.1061 13.5044 11.3754 13.0394L7.19881 10.3816L2.9774 17.558C2.92465 17.6477 2.84826 17.7148 2.7608 17.7562Z",
205
+ fill: "white",
206
+ fillOpacity: "0.12"
207
+ }
208
+ )
209
+ ] })
210
+ }
211
+ );
212
+ BaseLineIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
213
+ "svg",
214
+ {
215
+ viewBox: "0 0 20 20",
216
+ fill: "currentColor",
217
+ xmlns: "http://www.w3.org/2000/svg",
218
+ ...props,
219
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Baseline", children: /* @__PURE__ */ jsxRuntime.jsx(
220
+ "path",
221
+ {
222
+ id: "Union",
223
+ fillRule: "evenodd",
224
+ clipRule: "evenodd",
225
+ d: "M6.05938 2.93544C6.55642 1.71198 8.27766 1.68139 8.81785 2.88642L11.4361 8.72723H9.24438L7.4717 4.77279L5.86521 8.72723H3.70647L6.05938 2.93544ZM13.9282 14.2865L13.0051 12.2272H10.8133L12.5586 16.1204C13.088 17.3014 14.7641 17.3026 15.2952 16.1224L17.048 12.2272H14.8549L13.9282 14.2865ZM2.28459 12.2272H4.44333L1.85293 18.6036L0 17.8509L2.28459 12.2272ZM16.4299 8.72723H18.623L19.3384 7.13759L17.5145 6.31686L16.4299 8.72723ZM1.42645 10.2272C1.42645 9.95109 1.65031 9.72723 1.92645 9.72723H2.92645C3.20259 9.72723 3.42645 9.95109 3.42645 10.2272V10.7272C3.42645 11.0034 3.20259 11.2272 2.92645 11.2272H1.92645C1.65031 11.2272 1.42645 11.0034 1.42645 10.7272V10.2272ZM4.42645 10.2272C4.42645 9.95109 4.65031 9.72723 4.92645 9.72723H5.92645C6.20259 9.72723 6.42645 9.95109 6.42645 10.2272V10.7272C6.42645 11.0034 6.20259 11.2272 5.92645 11.2272H4.92645C4.65031 11.2272 4.42645 11.0034 4.42645 10.7272V10.2272ZM7.92645 9.72723C7.65031 9.72723 7.42645 9.95109 7.42645 10.2272V10.7272C7.42645 11.0034 7.65031 11.2272 7.92645 11.2272H8.92645C9.20259 11.2272 9.42645 11.0034 9.42645 10.7272V10.2272C9.42645 9.95109 9.20259 9.72723 8.92645 9.72723H7.92645ZM10.4265 10.2272C10.4265 9.95109 10.6503 9.72723 10.9265 9.72723H11.9265C12.2026 9.72723 12.4265 9.95109 12.4265 10.2272V10.7272C12.4265 11.0034 12.2026 11.2272 11.9265 11.2272H10.9265C10.6503 11.2272 10.4265 11.0034 10.4265 10.7272V10.2272ZM13.9265 9.72723C13.6503 9.72723 13.4265 9.95109 13.4265 10.2272V10.7272C13.4265 11.0034 13.6503 11.2272 13.9265 11.2272H14.9265C15.2026 11.2272 15.4265 11.0034 15.4265 10.7272V10.2272C15.4265 9.95109 15.2026 9.72723 14.9265 9.72723H13.9265ZM16.4265 10.2272C16.4265 9.95109 16.6503 9.72723 16.9265 9.72723H17.9265C18.2026 9.72723 18.4265 9.95109 18.4265 10.2272V10.7272C18.4265 11.0034 18.2026 11.2272 17.9265 11.2272H16.9265C16.6503 11.2272 16.4265 11.0034 16.4265 10.7272V10.2272Z"
226
+ }
227
+ ) })
228
+ }
229
+ );
230
+ UnSelectIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
231
+ "svg",
232
+ {
233
+ viewBox: "0 0 12 12",
234
+ fill: "currentColor",
235
+ xmlns: "http://www.w3.org/2000/svg",
236
+ ...props,
237
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Unselected", children: /* @__PURE__ */ jsxRuntime.jsx(
238
+ "path",
239
+ {
240
+ id: "Vector",
241
+ d: "M6.00684 0.999023C3.24544 0.999023 1.00684 3.23752 1.00684 5.99902C1.00684 8.76051 3.24544 10.999 6.00684 10.999C8.76834 10.999 11.0068 8.76051 11.0068 5.99902C11.0068 3.23752 8.76834 0.999023 6.00684 0.999023ZM6.00684 1.99902C8.21584 1.99902 10.0068 3.79002 10.0068 5.99902C10.0068 8.20801 8.21584 9.99901 6.00684 9.99901C3.79769 9.99901 2.00684 8.20801 2.00684 5.99902C2.00684 3.79002 3.79769 1.99902 6.00684 1.99902Z",
242
+ fill: "white",
243
+ fillOpacity: "0.2"
244
+ }
245
+ ) })
246
+ }
247
+ );
248
+ SelectedIcon = (props) => /* @__PURE__ */ jsxRuntime.jsx(
249
+ "svg",
250
+ {
251
+ viewBox: "0 0 12 12",
252
+ fill: "currentColor",
253
+ xmlns: "http://www.w3.org/2000/svg",
254
+ ...props,
255
+ children: /* @__PURE__ */ jsxRuntime.jsx("g", { id: "Selected-Multiple Choices-fill", children: /* @__PURE__ */ jsxRuntime.jsx(
256
+ "path",
257
+ {
258
+ id: "Subtract",
259
+ fillRule: "evenodd",
260
+ clipRule: "evenodd",
261
+ d: "M1.00684 5.99902C1.00684 3.23752 3.24544 0.999023 6.00684 0.999023C8.76834 0.999023 11.0068 3.23752 11.0068 5.99902C11.0068 8.76051 8.76834 10.999 6.00684 10.999C3.24544 10.999 1.00684 8.76051 1.00684 5.99902ZM8.49243 3.65563C8.60602 3.54726 8.76156 3.49957 8.91068 3.49957C9.05981 3.49957 9.21534 3.54726 9.32893 3.65563C9.5567 3.87231 9.5567 4.23649 9.32893 4.45317L5.25362 8.33706C5.02644 8.55374 4.6443 8.55374 4.41712 8.33706L2.67014 6.67253C2.44296 6.45585 2.44296 6.09161 2.67014 5.87499C2.89791 5.65831 3.28004 5.65831 3.50722 5.87499L4.83537 7.1407L8.49243 3.65563Z",
262
+ fill: "#608CFF"
263
+ }
264
+ ) })
265
+ }
266
+ );
267
+ }
268
+ });
17
269
 
18
- exports.TradingviewUI = yt;
19
- exports.TradingviewWidget = gn;
20
- exports.useTradingviewScript = at;
270
+ // src/components/lineType/index.tsx
271
+ var lineType_exports = {};
272
+ __export(lineType_exports, {
273
+ default: () => lineType_default
274
+ });
275
+ var LineType, lineType_default;
276
+ var init_lineType = __esm({
277
+ "src/components/lineType/index.tsx"() {
278
+ init_icons();
279
+ LineType = (props) => {
280
+ const [open, setOpen] = React3.useState(false);
281
+ const { t } = i18n.useTranslation();
282
+ const lineTypeList = React3.useMemo(() => {
283
+ return [
284
+ {
285
+ icon: /* @__PURE__ */ jsxRuntime.jsx(BarIcon, { fill: "currentColor", className: "oui-w-5 oui-h-5" }),
286
+ label: t("tradingView.lineType.bars"),
287
+ value: "0"
288
+ },
289
+ {
290
+ icon: /* @__PURE__ */ jsxRuntime.jsx(CandlesIcon, { fill: "currentColor", className: "oui-w-5 oui-h-5" }),
291
+ label: t("tradingView.lineType.candles"),
292
+ value: "1"
293
+ },
294
+ {
295
+ icon: /* @__PURE__ */ jsxRuntime.jsx(HollowCandlesIcon, { fill: "currentColor", className: "oui-w-5 oui-h-5" }),
296
+ label: t("tradingView.lineType.hollowCandles"),
297
+ value: "9"
298
+ },
299
+ {
300
+ icon: /* @__PURE__ */ jsxRuntime.jsx(LineIcon, { fill: "currentColor", className: "oui-w-5 oui-h-5" }),
301
+ label: t("tradingView.lineType.line"),
302
+ value: "2"
303
+ },
304
+ {
305
+ icon: /* @__PURE__ */ jsxRuntime.jsx(AreaIcon, { fill: "currentColor", className: "oui-w-5 oui-h-5" }),
306
+ label: t("tradingView.lineType.area"),
307
+ value: "3"
308
+ },
309
+ {
310
+ icon: /* @__PURE__ */ jsxRuntime.jsx(BaseLineIcon, { fill: "currentColor", className: "oui-w-5 oui-h-5" }),
311
+ label: t("tradingView.lineType.baseline"),
312
+ value: "10"
313
+ }
314
+ ];
315
+ }, [t]);
316
+ const currentLineTypeIcon = React3.useMemo(() => {
317
+ const data = lineTypeList.find((item) => item.value === props.lineType);
318
+ if (data) {
319
+ return data.icon;
320
+ }
321
+ return lineTypeList[1].icon;
322
+ }, [props.lineType]);
323
+ return /* @__PURE__ */ jsxRuntime.jsxs(ui.DropdownMenuRoot, { open, onOpenChange: setOpen, children: [
324
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsx(
325
+ ui.Box,
326
+ {
327
+ className: ui.cn(
328
+ "oui-w-[18px] oui-h-[18px] oui-cursor-pointer oui-text-base-contrast-36 hover:oui-text-base-contrast-80",
329
+ open && "oui-text-base-contrast-80"
330
+ ),
331
+ children: currentLineTypeIcon
332
+ }
333
+ ) }),
334
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenuPortal, { children: /* @__PURE__ */ jsxRuntime.jsx(
335
+ ui.DropdownMenuContent,
336
+ {
337
+ onCloseAutoFocus: (e) => e.preventDefault(),
338
+ onClick: (e) => e.stopPropagation(),
339
+ align: "start",
340
+ sideOffset: 20,
341
+ className: "oui-bg-base-8",
342
+ children: /* @__PURE__ */ jsxRuntime.jsx(
343
+ ui.Flex,
344
+ {
345
+ direction: "column",
346
+ gap: 4,
347
+ px: 5,
348
+ py: 5,
349
+ width: 240,
350
+ justify: "start",
351
+ itemAlign: "start",
352
+ children: lineTypeList.map((item) => /* @__PURE__ */ jsxRuntime.jsxs(
353
+ ui.Flex,
354
+ {
355
+ justify: "start",
356
+ itemAlign: "center",
357
+ gap: 2,
358
+ className: ui.cn(
359
+ "oui-text-base-contrast-36 oui-cursor-pointer oui-w-full hover:oui-text-base-contrast",
360
+ props.lineType === item.value && "oui-text-base-contrast"
361
+ ),
362
+ onClick: () => props.changeLineType(item.value),
363
+ children: [
364
+ item.icon,
365
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "oui-text-sm", children: item.label })
366
+ ]
367
+ },
368
+ item.value
369
+ ))
370
+ }
371
+ )
372
+ }
373
+ ) })
374
+ ] });
375
+ };
376
+ lineType_default = LineType;
377
+ }
378
+ });
379
+
380
+ // src/components/timeInterval/index.tsx
381
+ var timeInterval_exports = {};
382
+ __export(timeInterval_exports, {
383
+ MobileTimeInterval: () => MobileTimeInterval,
384
+ TimeInterval: () => TimeInterval
385
+ });
386
+ var useMobileTimeIntervalMoreMap, TimeInterval, DesktopTimeInterval, MobileTimeInterval, DropDownTimeInterval;
387
+ var init_timeInterval = __esm({
388
+ "src/components/timeInterval/index.tsx"() {
389
+ init_icons();
390
+ useMobileTimeIntervalMoreMap = () => {
391
+ const { t } = i18n.useTranslation();
392
+ const mobileTimeIntervalMoreMap = React3.useMemo(() => {
393
+ return [
394
+ [
395
+ {
396
+ value: "3",
397
+ label: t("tradingView.timeInterval.3m")
398
+ },
399
+ {
400
+ value: "5",
401
+ label: t("tradingView.timeInterval.5m")
402
+ },
403
+ {
404
+ value: "30",
405
+ label: t("tradingView.timeInterval.30m")
406
+ },
407
+ {
408
+ value: "120",
409
+ label: t("tradingView.timeInterval.2h")
410
+ }
411
+ ],
412
+ [
413
+ {
414
+ value: "360",
415
+ label: t("tradingView.timeInterval.6h")
416
+ },
417
+ {
418
+ value: "720",
419
+ label: t("tradingView.timeInterval.12h")
420
+ },
421
+ {
422
+ value: "3d",
423
+ label: t("tradingView.timeInterval.3d")
424
+ },
425
+ {
426
+ value: "1M",
427
+ label: t("tradingView.timeInterval.1M")
428
+ }
429
+ ]
430
+ ];
431
+ }, [t]);
432
+ return { mobileTimeIntervalMoreMap };
433
+ };
434
+ TimeInterval = (props) => {
435
+ const isMobile = hooks.useMediaQuery(types.MEDIA_TABLET);
436
+ if (isMobile) {
437
+ return /* @__PURE__ */ jsxRuntime.jsx(MobileTimeInterval, { ...props });
438
+ }
439
+ return /* @__PURE__ */ jsxRuntime.jsx(DesktopTimeInterval, { ...props });
440
+ };
441
+ DesktopTimeInterval = (props) => {
442
+ const { t } = i18n.useTranslation();
443
+ const timeIntervalMap = React3.useMemo(() => {
444
+ return [
445
+ {
446
+ value: "1",
447
+ label: t("tradingView.timeInterval.1m")
448
+ },
449
+ {
450
+ value: "3",
451
+ label: t("tradingView.timeInterval.3m")
452
+ },
453
+ {
454
+ value: "5",
455
+ label: t("tradingView.timeInterval.5m")
456
+ },
457
+ {
458
+ value: "15",
459
+ label: t("tradingView.timeInterval.15m")
460
+ },
461
+ {
462
+ value: "30",
463
+ label: t("tradingView.timeInterval.30m")
464
+ },
465
+ {
466
+ value: "60",
467
+ label: t("tradingView.timeInterval.1h")
468
+ },
469
+ {
470
+ value: "240",
471
+ label: t("tradingView.timeInterval.4h")
472
+ },
473
+ {
474
+ value: "720",
475
+ label: t("tradingView.timeInterval.12h")
476
+ },
477
+ {
478
+ value: "1D",
479
+ label: t("tradingView.timeInterval.1d")
480
+ },
481
+ {
482
+ value: "1W",
483
+ label: t("tradingView.timeInterval.1w")
484
+ },
485
+ {
486
+ value: "1M",
487
+ label: t("tradingView.timeInterval.1M")
488
+ }
489
+ ];
490
+ }, [t]);
491
+ return /* @__PURE__ */ jsxRuntime.jsx(
492
+ "div",
493
+ {
494
+ className: ui.cn(
495
+ "oui-text-2xs oui-text-base-contrast-36 oui-flex oui-gap-[2px] oui-items-center oui-mr-3 oui-font-semibold",
496
+ "oui-overflow-hidden"
497
+ ),
498
+ children: timeIntervalMap.map((item) => /* @__PURE__ */ jsxRuntime.jsx(
499
+ "div",
500
+ {
501
+ className: ui.cn(
502
+ "oui-cursor-pointer oui-px-2",
503
+ "hover:oui-text-base-contrast-80",
504
+ "oui-break-normal oui-whitespace-nowrap",
505
+ props.interval === item.value && "oui-text-base-contrast-80 oui-bg-white/[.06] oui-rounded"
506
+ ),
507
+ id: item.value,
508
+ onClick: () => props.changeInterval(item.value),
509
+ children: item.label
510
+ },
511
+ item.value
512
+ ))
513
+ }
514
+ );
515
+ };
516
+ MobileTimeInterval = (props) => {
517
+ const { t } = i18n.useTranslation();
518
+ const mobileTimeIntervalDefaultMap = React3.useMemo(() => {
519
+ return [
520
+ {
521
+ value: "1",
522
+ label: t("tradingView.timeInterval.1m")
523
+ },
524
+ {
525
+ value: "15",
526
+ label: t("tradingView.timeInterval.15m")
527
+ },
528
+ {
529
+ value: "60",
530
+ label: t("tradingView.timeInterval.1h")
531
+ },
532
+ {
533
+ value: "240",
534
+ label: t("tradingView.timeInterval.4h")
535
+ },
536
+ {
537
+ value: "1D",
538
+ label: t("tradingView.timeInterval.1d")
539
+ },
540
+ {
541
+ value: "1W",
542
+ label: t("tradingView.timeInterval.1w")
543
+ }
544
+ ];
545
+ }, [t]);
546
+ const { mobileTimeIntervalMoreMap } = useMobileTimeIntervalMoreMap();
547
+ const currentIntervalIsInExpand = React3.useMemo(() => {
548
+ for (const row of mobileTimeIntervalMoreMap) {
549
+ for (const item of row) {
550
+ if (item.value === props.interval) {
551
+ return item.label;
552
+ }
553
+ }
554
+ }
555
+ return null;
556
+ }, [props.interval, mobileTimeIntervalMoreMap]);
557
+ return /* @__PURE__ */ jsxRuntime.jsxs(
558
+ ui.Flex,
559
+ {
560
+ justify: "start",
561
+ itemAlign: "center",
562
+ gap: 3,
563
+ className: ui.cn(
564
+ "oui-text-2xs oui-text-base-contrast-36",
565
+ "oui-overflow-hidden"
566
+ ),
567
+ children: [
568
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: " oui-flex oui-gap-1 oui-items-center oui-mr-3 oui-font-semibold", children: mobileTimeIntervalDefaultMap.map((item) => /* @__PURE__ */ jsxRuntime.jsx(
569
+ "div",
570
+ {
571
+ className: ui.cn(
572
+ "oui-px-2",
573
+ "oui-break-normal oui-whitespace-nowrap",
574
+ props.interval === item.value && "oui-text-base-contrast-80 oui-bg-white/[.06] oui-rounded"
575
+ ),
576
+ onClick: () => props.changeInterval(item.value),
577
+ children: item.label
578
+ },
579
+ item.value
580
+ )) }),
581
+ /* @__PURE__ */ jsxRuntime.jsx(DropDownTimeInterval, { ...props, children: currentIntervalIsInExpand ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "oui-text-base-contrast-80", children: currentIntervalIsInExpand }) : /* @__PURE__ */ jsxRuntime.jsx(ui.Text, { className: "oui-break-normal oui-whitespace-nowrap", children: t("tradingView.timeInterval.more") }) })
582
+ ]
583
+ }
584
+ );
585
+ };
586
+ DropDownTimeInterval = (props) => {
587
+ const [open, setOpen] = React3__default.default.useState(false);
588
+ const { mobileTimeIntervalMoreMap } = useMobileTimeIntervalMoreMap();
589
+ return /* @__PURE__ */ jsxRuntime.jsxs(ui.DropdownMenuRoot, { open, onOpenChange: setOpen, children: [
590
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "oui-flex oui-justify-start oui-items-center oui-gap-0.5", children: [
591
+ props.children,
592
+ /* @__PURE__ */ jsxRuntime.jsx(
593
+ CaretIcon,
594
+ {
595
+ className: ui.cn(
596
+ "oui-w-3 oui-h-3",
597
+ open && "oui-text-base-contrast-80 oui-rotate-180"
598
+ )
599
+ }
600
+ )
601
+ ] }) }),
602
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenuPortal, { children: /* @__PURE__ */ jsxRuntime.jsx(
603
+ ui.DropdownMenuContent,
604
+ {
605
+ onCloseAutoFocus: (e) => e.preventDefault(),
606
+ onClick: (e) => e.stopPropagation(),
607
+ align: "start",
608
+ alignOffset: 0,
609
+ sideOffset: 0,
610
+ className: ui.cn(
611
+ "oui-markets-dropdown-menu-content oui-bg-base-9 oui-w-screen oui-flex oui-flex-col oui-gap-2 oui-p-3"
612
+ ),
613
+ children: mobileTimeIntervalMoreMap.map((row, id) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: "oui-flex oui-gap-2", children: row.map((item) => /* @__PURE__ */ jsxRuntime.jsx(
614
+ "div",
615
+ {
616
+ className: ui.cn(
617
+ "oui-w-full oui-text-2xs oui-flex oui-items-center oui-justify-center oui-h-6 oui-rounded",
618
+ item.value === props.interval ? "oui-text-base-contrast oui-bg-primary-darken" : "oui-text-base-contrast-36 oui-bg-base-5"
619
+ ),
620
+ onClick: () => {
621
+ props.changeInterval(item.value);
622
+ },
623
+ children: /* @__PURE__ */ jsxRuntime.jsx("div", { children: item.label })
624
+ },
625
+ item.value
626
+ )) }, id))
627
+ }
628
+ ) })
629
+ ] });
630
+ };
631
+ }
632
+ });
633
+ var DesktopDisplayControl;
634
+ var init_displayControl_desktop = __esm({
635
+ "src/components/displayControl/displayControl.desktop.tsx"() {
636
+ init_icons();
637
+ DesktopDisplayControl = (props) => {
638
+ const { displayControlState, changeDisplayControlState } = props;
639
+ const [open, setOpen] = React3.useState(false);
640
+ const { t } = i18n.useTranslation();
641
+ const displayControlMap = React3.useMemo(() => {
642
+ return [
643
+ {
644
+ label: t("common.position"),
645
+ id: "position"
646
+ },
647
+ {
648
+ label: t("tradingView.displayControl.buySell"),
649
+ id: "buySell"
650
+ },
651
+ {
652
+ label: t("tradingView.displayControl.limitOrders"),
653
+ id: "limitOrders"
654
+ },
655
+ {
656
+ label: t("tradingView.displayControl.stopOrders"),
657
+ id: "stopOrders"
658
+ },
659
+ {
660
+ label: t("common.tpsl"),
661
+ id: "tpsl"
662
+ },
663
+ {
664
+ label: t("tpsl.positionTpsl"),
665
+ id: "positionTpsl"
666
+ },
667
+ {
668
+ label: t("orderEntry.orderType.trailingStop"),
669
+ id: "trailingStop"
670
+ }
671
+ ];
672
+ }, [t]);
673
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: /* @__PURE__ */ jsxRuntime.jsxs(ui.DropdownMenuRoot, { open, onOpenChange: setOpen, children: [
674
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
675
+ ui.Flex,
676
+ {
677
+ justify: "start",
678
+ itemAlign: "center",
679
+ className: "oui-gap-[2px] oui-cursor-pointer oui-text-base-contrast-36 hover:oui-text-base-contrast-80",
680
+ children: [
681
+ /* @__PURE__ */ jsxRuntime.jsx(
682
+ DisplaySettingIcon,
683
+ {
684
+ className: ui.cn(
685
+ "oui-w-[18px] oui-h-[18px] ",
686
+ open && "oui-text-base-contrast-80"
687
+ )
688
+ }
689
+ ),
690
+ /* @__PURE__ */ jsxRuntime.jsx(
691
+ CaretIcon,
692
+ {
693
+ className: ui.cn(
694
+ "oui-w-3 oui-h-3",
695
+ open && "oui-text-base-contrast-80 oui-rotate-180"
696
+ )
697
+ }
698
+ )
699
+ ]
700
+ }
701
+ ) }),
702
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenuPortal, { children: /* @__PURE__ */ jsxRuntime.jsx(
703
+ ui.DropdownMenuContent,
704
+ {
705
+ onCloseAutoFocus: (e) => e.preventDefault(),
706
+ onClick: (e) => e.stopPropagation(),
707
+ align: "start",
708
+ className: "oui-bg-base-8",
709
+ children: /* @__PURE__ */ jsxRuntime.jsx(
710
+ ui.Flex,
711
+ {
712
+ direction: "column",
713
+ gap: 4,
714
+ px: 5,
715
+ py: 5,
716
+ width: 240,
717
+ justify: "start",
718
+ itemAlign: "start",
719
+ children: displayControlMap.map((item) => /* @__PURE__ */ jsxRuntime.jsxs(
720
+ ui.Flex,
721
+ {
722
+ justify: "between",
723
+ itemAlign: "center",
724
+ className: "oui-w-full",
725
+ children: [
726
+ /* @__PURE__ */ jsxRuntime.jsx(
727
+ ui.Text,
728
+ {
729
+ className: ui.cn(
730
+ "oui-text-sm oui-text-base-contrast-80",
731
+ !displayControlState[item.id] && "oui-text-base-contrast-36"
732
+ ),
733
+ children: item.label
734
+ }
735
+ ),
736
+ /* @__PURE__ */ jsxRuntime.jsx(
737
+ ui.Switch,
738
+ {
739
+ className: "oui-h-4 oui-w-8",
740
+ checked: displayControlState[item.id],
741
+ onCheckedChange: (checked) => {
742
+ changeDisplayControlState({
743
+ ...displayControlState,
744
+ [item.id]: checked
745
+ });
746
+ }
747
+ }
748
+ )
749
+ ]
750
+ },
751
+ item.id
752
+ ))
753
+ }
754
+ )
755
+ }
756
+ ) })
757
+ ] }) });
758
+ };
759
+ }
760
+ });
761
+ var MobileDisplayControl;
762
+ var init_displayControl_mobile = __esm({
763
+ "src/components/displayControl/displayControl.mobile.tsx"() {
764
+ init_icons();
765
+ MobileDisplayControl = (props) => {
766
+ const [open, setOpen] = React3.useState(false);
767
+ const { t } = i18n.useTranslation();
768
+ const mobileDisplayControlMap = React3.useMemo(() => {
769
+ return [
770
+ [
771
+ {
772
+ label: t("common.position"),
773
+ id: "position"
774
+ },
775
+ {
776
+ label: t("tradingView.displayControl.limitOrders"),
777
+ id: "limitOrders"
778
+ }
779
+ ],
780
+ [
781
+ {
782
+ label: t("tradingView.displayControl.stopOrders"),
783
+ id: "stopOrders"
784
+ },
785
+ {
786
+ label: t("common.tpsl"),
787
+ id: "tpsl"
788
+ }
789
+ ],
790
+ [
791
+ {
792
+ label: t("tpsl.positionTpsl"),
793
+ id: "positionTpsl"
794
+ },
795
+ {
796
+ label: t("tradingView.displayControl.buySell"),
797
+ id: "buySell"
798
+ }
799
+ ],
800
+ [
801
+ {
802
+ label: t("orderEntry.orderType.trailingStop"),
803
+ id: "trailingStop"
804
+ },
805
+ // placeholder
806
+ {}
807
+ ]
808
+ ];
809
+ }, [t]);
810
+ return /* @__PURE__ */ jsxRuntime.jsxs(ui.DropdownMenuRoot, { open, onOpenChange: setOpen, children: [
811
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
812
+ "div",
813
+ {
814
+ className: ui.cn(
815
+ "oui-flex oui-items-center oui-justify-center oui-gap-0.5 oui-text-base-contrast-36",
816
+ open && "oui-text-base-contrast-8"
817
+ ),
818
+ children: [
819
+ /* @__PURE__ */ jsxRuntime.jsx(
820
+ DisplaySettingIcon,
821
+ {
822
+ className: ui.cn(
823
+ "oui-size-[18px] ",
824
+ open && "oui-text-base-contrast-80"
825
+ )
826
+ }
827
+ ),
828
+ /* @__PURE__ */ jsxRuntime.jsx(
829
+ CaretIcon,
830
+ {
831
+ className: ui.cn(
832
+ "oui-size-3",
833
+ open && "oui-rotate-180 oui-text-base-contrast-80"
834
+ )
835
+ }
836
+ )
837
+ ]
838
+ }
839
+ ) }),
840
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownMenuPortal, { children: /* @__PURE__ */ jsxRuntime.jsx(
841
+ ui.DropdownMenuContent,
842
+ {
843
+ onCloseAutoFocus: (e) => e.preventDefault(),
844
+ onClick: (e) => e.stopPropagation(),
845
+ align: "start",
846
+ alignOffset: 0,
847
+ sideOffset: 0,
848
+ className: ui.cn(
849
+ "oui-tradingview-display-control-dropdown-menu-content oui-flex oui-w-screen oui-flex-col oui-gap-2 oui-bg-base-9 oui-p-3"
850
+ ),
851
+ children: mobileDisplayControlMap.map((row, id) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: "oui-flex oui-gap-2", children: row.map((item, index) => {
852
+ return /* @__PURE__ */ jsxRuntime.jsx(
853
+ "div",
854
+ {
855
+ className: ui.cn(
856
+ "oui-flex oui-h-6 oui-w-full oui-items-center oui-justify-between",
857
+ "oui-rounded oui-px-2 oui-text-2xs",
858
+ item.id && "oui-bg-base-5",
859
+ props.displayControlState[item.id] ? "oui-text-base-contrast" : "oui-text-base-contrast-36"
860
+ ),
861
+ onClick: () => {
862
+ if (!item.id) {
863
+ return;
864
+ }
865
+ props.changeDisplayControlState({
866
+ ...props.displayControlState,
867
+ [item.id]: !props.displayControlState[item.id]
868
+ });
869
+ },
870
+ children: item.id && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
871
+ /* @__PURE__ */ jsxRuntime.jsx("div", { children: item.label }),
872
+ props.displayControlState[item.id] ? /* @__PURE__ */ jsxRuntime.jsx(SelectedIcon, { className: "oui-size-3" }) : /* @__PURE__ */ jsxRuntime.jsx(UnSelectIcon, { className: "oui-size-3" })
873
+ ] })
874
+ },
875
+ item.id || index
876
+ );
877
+ }) }, id))
878
+ }
879
+ ) })
880
+ ] });
881
+ };
882
+ }
883
+ });
884
+
885
+ // src/components/displayControl/index.tsx
886
+ var displayControl_exports = {};
887
+ __export(displayControl_exports, {
888
+ DesktopDisplayControl: () => DesktopDisplayControl,
889
+ MobileDisplayControl: () => MobileDisplayControl
890
+ });
891
+ var init_displayControl = __esm({
892
+ "src/components/displayControl/index.tsx"() {
893
+ init_displayControl_desktop();
894
+ init_displayControl_mobile();
895
+ }
896
+ });
897
+
898
+ // src/utils/chart.util.ts
899
+ var upColor = "#008676";
900
+ var downColor = "#D92D6B";
901
+ var chartBG = "#131519";
902
+ var pnlUpColor = "#00B49E";
903
+ var pnlDownColor = "#FF447C";
904
+ var pnlZoreColor = "#333948";
905
+ var textColor = "#FFFFFF";
906
+ var qtyTextColor = "#F4F7F9";
907
+ var font = "regular 11px Manrope";
908
+ var defaultColorConfig = {
909
+ upColor,
910
+ downColor,
911
+ chartBG,
912
+ pnlUpColor,
913
+ pnlDownColor,
914
+ pnlZoreColor,
915
+ textColor,
916
+ qtyTextColor,
917
+ font,
918
+ volumeUpColor: "#0C3E3A",
919
+ volumeDownColor: "#5A1E36",
920
+ closeIcon: "rgba(255, 255, 255, 0.8)"
921
+ };
922
+ var getOveriides = (colorConfig, isMobile) => {
923
+ const overrides = {
924
+ "paneProperties.background": colorConfig.chartBG,
925
+ // "paneProperties.background": "#ffff00",
926
+ // "mainSeriesProperties.style": 1,
927
+ "paneProperties.backgroundType": "solid",
928
+ // "paneProperties.background": "#151822",
929
+ "mainSeriesProperties.candleStyle.upColor": colorConfig.upColor,
930
+ "mainSeriesProperties.candleStyle.downColor": colorConfig.downColor,
931
+ "mainSeriesProperties.candleStyle.borderColor": colorConfig.upColor,
932
+ "mainSeriesProperties.candleStyle.borderUpColor": colorConfig.upColor,
933
+ "mainSeriesProperties.candleStyle.borderDownColor": colorConfig.downColor,
934
+ "mainSeriesProperties.candleStyle.wickUpColor": colorConfig.upColor,
935
+ "mainSeriesProperties.candleStyle.wickDownColor": colorConfig.downColor,
936
+ "paneProperties.separatorColor": "#2B2833",
937
+ "paneProperties.vertGridProperties.color": "#26232F",
938
+ "paneProperties.horzGridProperties.color": "#26232F",
939
+ "scalesProperties.fontSize": isMobile ? 8 : 12,
940
+ "scalesProperties.textColor": "#97969B",
941
+ "paneProperties.legendProperties.showSeriesTitle": isMobile ? false : true,
942
+ "mainSeriesProperties.statusViewStyle.symbolTextSource": "ticker"
943
+ };
944
+ const studiesOverrides = {
945
+ "volume.volume.color.0": colorConfig.volumeDownColor,
946
+ "volume.volume.color.1": colorConfig.volumeUpColor
947
+ };
948
+ return {
949
+ overrides,
950
+ studiesOverrides
951
+ };
952
+ };
953
+ var EXCHANGE = "Orderly";
954
+ var withoutExchangePrefix = (symbol) => symbol.includes(":") ? symbol.split(":")[1] : symbol;
955
+ var withExchangePrefix = (symbol) => symbol.startsWith(`${EXCHANGE}:`) ? symbol : `${EXCHANGE}:${symbol}`;
956
+ var getBrokerAdapter = (host, broker) => {
957
+ let _symbolInfo;
958
+ const getOrderCombinationType = (orderType) => {
959
+ return [
960
+ null,
961
+ "limit",
962
+ "MARKET" /* MARKET */,
963
+ "STOP_MARKET" /* STOP_MARKET */,
964
+ "STOP_LIMIT" /* STOP_LIMIT */
965
+ ][orderType];
966
+ };
967
+ return {
968
+ symbolInfo: async (symbol2) => {
969
+ _symbolInfo = broker.getSymbolInfo(withoutExchangePrefix(symbol2));
970
+ return {
971
+ qty: {
972
+ min: _symbolInfo?.baseMin ?? 0,
973
+ max: _symbolInfo?.baseMax ?? 0,
974
+ step: _symbolInfo?.baseTick ?? 0
975
+ },
976
+ pipValue: 0,
977
+ pipSize: _symbolInfo?.quoteTick ?? 0,
978
+ minTick: _symbolInfo?.quoteTick ?? 0,
979
+ description: ""
980
+ };
981
+ },
982
+ placeOrder: async (order) => {
983
+ const side = ["SELL" /* SELL */, "BUY" /* BUY */][+(order.side > 0)];
984
+ const quantity = order.qty.toString();
985
+ (order.limitPrice ?? 0).toString();
986
+ (order.stopPrice ?? 0).toString();
987
+ const symbol2 = withoutExchangePrefix(order.symbol);
988
+ const orderCombinationType = getOrderCombinationType(order.type);
989
+ if (orderCombinationType === "MARKET" /* MARKET */) {
990
+ broker.sendMarketOrder({ side, order_quantity: quantity, symbol: symbol2, order_type: types.OrderType.MARKET });
991
+ }
992
+ },
993
+ orders: () => [],
994
+ positions: () => [],
995
+ executions: () => [],
996
+ connectionStatus: () => 1,
997
+ chartContextMenuActions: (context) => host.defaultContextMenuActions(context),
998
+ isTradable: async () => true,
999
+ accountManagerInfo: () => ({}),
1000
+ currentAccount: () => "1",
1001
+ accountsMetainfo: async () => [{ id: "1" }],
1002
+ remove: () => host?.silentOrdersPlacement().unsubscribe()
1003
+ };
1004
+ };
1005
+ var getBrokerAdapter_default = getBrokerAdapter;
1006
+ function logMessage(message) {
1007
+ }
1008
+ function getErrorMessage(error) {
1009
+ if (error === void 0) {
1010
+ return "";
1011
+ }
1012
+ if (typeof error === "string") {
1013
+ return error;
1014
+ }
1015
+ return error.message;
1016
+ }
1017
+
1018
+ // src/tradingviewAdapter/datafeed/history-provider.ts
1019
+ var HistoryProvider = class {
1020
+ constructor(datafeedUrl, requester, limitedServerResponse) {
1021
+ this._datafeedUrl = datafeedUrl;
1022
+ this._requester = requester;
1023
+ this._limitedServerResponse = limitedServerResponse;
1024
+ }
1025
+ getBars(symbolInfo, resolution, periodParams) {
1026
+ const requestParams = {
1027
+ symbol: symbolInfo.ticker || "",
1028
+ resolution,
1029
+ from: periodParams.from,
1030
+ to: periodParams.to
1031
+ };
1032
+ if (periodParams.countBack !== void 0) {
1033
+ requestParams.countback = periodParams.countBack;
1034
+ }
1035
+ if (symbolInfo.currency_code !== void 0) {
1036
+ requestParams.currencyCode = symbolInfo.currency_code;
1037
+ }
1038
+ if (symbolInfo.unit_id !== void 0) {
1039
+ requestParams.unitId = symbolInfo.unit_id;
1040
+ }
1041
+ return new Promise(
1042
+ async (resolve, reject) => {
1043
+ try {
1044
+ const initialResponse = await this._requester.sendRequest(
1045
+ this._datafeedUrl,
1046
+ "history",
1047
+ requestParams
1048
+ );
1049
+ const result = this._processHistoryResponse(initialResponse);
1050
+ if (this._limitedServerResponse) {
1051
+ await this._processTruncatedResponse(result, requestParams);
1052
+ }
1053
+ resolve(result);
1054
+ } catch (e) {
1055
+ if (e instanceof Error || typeof e === "string") {
1056
+ const reasonString = getErrorMessage(e);
1057
+ reject(reasonString);
1058
+ }
1059
+ }
1060
+ }
1061
+ );
1062
+ }
1063
+ async _processTruncatedResponse(result, requestParams) {
1064
+ let lastResultLength = result.bars.length;
1065
+ try {
1066
+ while (this._limitedServerResponse && this._limitedServerResponse.maxResponseLength > 0 && this._limitedServerResponse.maxResponseLength === lastResultLength && requestParams.from < requestParams.to) {
1067
+ if (requestParams.countback) {
1068
+ requestParams.countback = requestParams.countback - lastResultLength;
1069
+ }
1070
+ if (this._limitedServerResponse.expectedOrder === "earliestFirst") {
1071
+ requestParams.from = Math.round(
1072
+ result.bars[result.bars.length - 1].time / 1e3
1073
+ );
1074
+ } else {
1075
+ requestParams.to = Math.round(result.bars[0].time / 1e3);
1076
+ }
1077
+ const followupResponse = await this._requester.sendRequest(
1078
+ this._datafeedUrl,
1079
+ "history",
1080
+ requestParams
1081
+ );
1082
+ const followupResult = this._processHistoryResponse(followupResponse);
1083
+ lastResultLength = followupResult.bars.length;
1084
+ if (this._limitedServerResponse.expectedOrder === "earliestFirst") {
1085
+ if (followupResult.bars[0].time === result.bars[result.bars.length - 1].time) {
1086
+ followupResult.bars.shift();
1087
+ }
1088
+ result.bars.push(...followupResult.bars);
1089
+ } else {
1090
+ if (followupResult.bars[followupResult.bars.length - 1].time === result.bars[0].time) {
1091
+ followupResult.bars.pop();
1092
+ }
1093
+ result.bars.unshift(...followupResult.bars);
1094
+ }
1095
+ }
1096
+ } catch (e) {
1097
+ if (e instanceof Error || typeof e === "string") {
1098
+ getErrorMessage(e);
1099
+ }
1100
+ }
1101
+ }
1102
+ _processHistoryResponse(response) {
1103
+ if (response.s !== "ok" && response.s !== "no_data") {
1104
+ throw new Error(response.errmsg);
1105
+ }
1106
+ const bars = [];
1107
+ const meta = {
1108
+ noData: false
1109
+ };
1110
+ if (response.s === "no_data") {
1111
+ meta.noData = true;
1112
+ meta.nextTime = response.nextTime;
1113
+ } else {
1114
+ const volumePresent = response.v !== void 0;
1115
+ const ohlPresent = response.o !== void 0;
1116
+ for (let i = 0; i < response.t.length; ++i) {
1117
+ const barValue = {
1118
+ time: response.t[i] * 1e3,
1119
+ close: parseFloat(response.c[i]),
1120
+ open: parseFloat(response.c[i]),
1121
+ high: parseFloat(response.c[i]),
1122
+ low: parseFloat(response.c[i])
1123
+ };
1124
+ if (ohlPresent) {
1125
+ barValue.open = parseFloat(
1126
+ response.o[i]
1127
+ );
1128
+ barValue.high = parseFloat(
1129
+ response.h[i]
1130
+ );
1131
+ barValue.low = parseFloat(response.l[i]);
1132
+ }
1133
+ if (volumePresent) {
1134
+ barValue.volume = parseFloat(
1135
+ response.v[i]
1136
+ );
1137
+ }
1138
+ bars.push(barValue);
1139
+ }
1140
+ }
1141
+ return {
1142
+ bars,
1143
+ meta
1144
+ };
1145
+ }
1146
+ };
1147
+
1148
+ // src/tradingviewAdapter/datafeed/requester.ts
1149
+ var Requester = class {
1150
+ constructor(headers) {
1151
+ if (headers) {
1152
+ this._headers = headers;
1153
+ }
1154
+ }
1155
+ sendRequest(datafeedUrl, urlPath, params) {
1156
+ if (params !== void 0) {
1157
+ const paramKeys = Object.keys(params);
1158
+ if (paramKeys.length !== 0) {
1159
+ urlPath += "?";
1160
+ }
1161
+ urlPath += paramKeys.map((key) => {
1162
+ return `${encodeURIComponent(key)}=${encodeURIComponent(
1163
+ params[key].toString()
1164
+ )}`;
1165
+ }).join("&");
1166
+ }
1167
+ const options = { credentials: "same-origin" };
1168
+ if (this._headers !== void 0) {
1169
+ options.headers = this._headers;
1170
+ }
1171
+ return fetch(`${datafeedUrl}/${urlPath}`, options).then((response) => response.text()).then((responseTest) => JSON.parse(responseTest));
1172
+ }
1173
+ };
1174
+
1175
+ // src/tradingviewAdapter/datafeed/symbol-storage.ts
1176
+ function extractField(data, field, arrayIndex, valueIsArray) {
1177
+ const value = data[field];
1178
+ if (Array.isArray(value) && (!valueIsArray || Array.isArray(value[0]))) {
1179
+ return value[arrayIndex];
1180
+ }
1181
+ return value;
1182
+ }
1183
+ function symbolKey(symbol, currency, unit) {
1184
+ return symbol + (currency !== void 0 ? "_%|#|%_" + currency : "") + (unit !== void 0 ? "_%|#|%_" + unit : "");
1185
+ }
1186
+ var SymbolsStorage = class {
1187
+ constructor(datafeedUrl, datafeedSupportedResolutions, requester) {
1188
+ this._exchangesList = ["Orderly"];
1189
+ this._symbolsInfo = {};
1190
+ this._symbolsList = [];
1191
+ this._datafeedUrl = datafeedUrl;
1192
+ this._datafeedSupportedResolutions = datafeedSupportedResolutions;
1193
+ this._requester = requester;
1194
+ this._readyPromise = this._init();
1195
+ this._readyPromise.catch((error) => {
1196
+ });
1197
+ }
1198
+ // BEWARE: this function does not consider symbol's exchange
1199
+ resolveSymbol(symbolName, currencyCode, unitId) {
1200
+ return this._readyPromise.then(() => {
1201
+ const symbolInfo = this._symbolsInfo[symbolKey(symbolName, currencyCode, unitId)];
1202
+ if (symbolInfo === void 0) {
1203
+ return Promise.reject("invalid symbol");
1204
+ }
1205
+ return Promise.resolve(symbolInfo);
1206
+ });
1207
+ }
1208
+ searchSymbols(searchString, exchange, symbolType, maxSearchResults) {
1209
+ return this._readyPromise.then(() => {
1210
+ const weightedResult = [];
1211
+ const queryIsEmpty = searchString.length === 0;
1212
+ searchString = searchString.toUpperCase();
1213
+ for (const symbolName of this._symbolsList) {
1214
+ const symbolInfo = this._symbolsInfo[symbolName];
1215
+ if (symbolInfo === void 0) {
1216
+ continue;
1217
+ }
1218
+ if (symbolType.length > 0 && symbolInfo.type !== symbolType) {
1219
+ continue;
1220
+ }
1221
+ if (exchange && exchange.length > 0 && symbolInfo.exchange !== exchange) {
1222
+ continue;
1223
+ }
1224
+ const positionInName = symbolInfo.name.toUpperCase().indexOf(searchString);
1225
+ const positionInDescription = symbolInfo.description.toUpperCase().indexOf(searchString);
1226
+ if (queryIsEmpty || positionInName >= 0 || positionInDescription >= 0) {
1227
+ const alreadyExists = weightedResult.some(
1228
+ (item) => item.symbolInfo === symbolInfo
1229
+ );
1230
+ if (!alreadyExists) {
1231
+ const weight = positionInName >= 0 ? positionInName : 8e3 + positionInDescription;
1232
+ weightedResult.push({ symbolInfo, weight });
1233
+ }
1234
+ }
1235
+ }
1236
+ const result = weightedResult.sort(
1237
+ (item1, item2) => item1.weight - item2.weight
1238
+ ).slice(0, maxSearchResults).map((item) => {
1239
+ const symbolInfo = item.symbolInfo;
1240
+ return {
1241
+ symbol: symbolInfo.name,
1242
+ full_name: `${symbolInfo.exchange}:${symbolInfo.name}`,
1243
+ description: symbolInfo.description,
1244
+ exchange: symbolInfo.exchange,
1245
+ params: [],
1246
+ type: symbolInfo.type,
1247
+ ticker: symbolInfo.name
1248
+ };
1249
+ });
1250
+ return Promise.resolve(result);
1251
+ });
1252
+ }
1253
+ _init() {
1254
+ const promises = [];
1255
+ const alreadyRequestedExchanges = {};
1256
+ for (const exchange of this._exchangesList) {
1257
+ if (alreadyRequestedExchanges[exchange]) {
1258
+ continue;
1259
+ }
1260
+ alreadyRequestedExchanges[exchange] = true;
1261
+ promises.push(this._requestExchangeData(exchange));
1262
+ }
1263
+ return Promise.all(promises).then(() => {
1264
+ this._symbolsList.sort();
1265
+ });
1266
+ }
1267
+ _requestExchangeData(exchange) {
1268
+ return new Promise(
1269
+ (resolve, reject) => {
1270
+ this._requester.sendRequest(this._datafeedUrl, "symbol_info", {
1271
+ group: exchange
1272
+ }).then((response) => {
1273
+ try {
1274
+ this._onExchangeDataReceived(exchange, response);
1275
+ } catch (error) {
1276
+ reject(
1277
+ error instanceof Error ? error : new Error(`SymbolsStorage: Unexpected exception ${error}`)
1278
+ );
1279
+ return;
1280
+ }
1281
+ resolve();
1282
+ }).catch((reason) => {
1283
+ logMessage(
1284
+ `SymbolsStorage: Request data for exchange '${exchange}' failed, reason=${getErrorMessage(
1285
+ reason
1286
+ )}`
1287
+ );
1288
+ resolve();
1289
+ });
1290
+ }
1291
+ );
1292
+ }
1293
+ _onExchangeDataReceived(exchange, data) {
1294
+ let symbolIndex = 0;
1295
+ try {
1296
+ const symbolsCount = data.symbol.length;
1297
+ const tickerPresent = data.ticker !== void 0;
1298
+ for (; symbolIndex < symbolsCount; ++symbolIndex) {
1299
+ const symbolName = data.symbol[symbolIndex];
1300
+ const listedExchange = extractField(
1301
+ data,
1302
+ "exchange-listed",
1303
+ symbolIndex
1304
+ );
1305
+ const tradedExchange = extractField(
1306
+ data,
1307
+ "exchange-traded",
1308
+ symbolIndex
1309
+ );
1310
+ const fullName = tradedExchange + ":" + symbolName;
1311
+ const currencyCode = extractField(data, "currency-code", symbolIndex);
1312
+ const unitId = extractField(data, "unit-id", symbolIndex);
1313
+ const ticker = tickerPresent ? extractField(data, "ticker", symbolIndex) : symbolName;
1314
+ const symbolInfo = {
1315
+ ticker,
1316
+ name: symbolName,
1317
+ base_name: [listedExchange + ":" + symbolName],
1318
+ listed_exchange: listedExchange,
1319
+ exchange: tradedExchange,
1320
+ currency_code: currencyCode,
1321
+ original_currency_code: extractField(
1322
+ data,
1323
+ "original-currency-code",
1324
+ symbolIndex
1325
+ ),
1326
+ unit_id: unitId,
1327
+ original_unit_id: extractField(data, "original-unit-id", symbolIndex),
1328
+ unit_conversion_types: extractField(
1329
+ data,
1330
+ "unit-conversion-types",
1331
+ symbolIndex,
1332
+ true
1333
+ ),
1334
+ description: extractField(data, "description", symbolIndex),
1335
+ has_intraday: definedValueOrDefault(
1336
+ extractField(data, "has-intraday", symbolIndex),
1337
+ false
1338
+ ),
1339
+ // show volume at the bottom by default: https://github.com/tradingview/charting_library/issues/8306
1340
+ visible_plots_set: definedValueOrDefault(
1341
+ extractField(data, "visible-plots-set", symbolIndex),
1342
+ "ohlcv"
1343
+ ),
1344
+ minmov: extractField(data, "minmovement", symbolIndex) || extractField(data, "minmov", symbolIndex) || 0,
1345
+ minmove2: extractField(data, "minmove2", symbolIndex) || extractField(data, "minmov2", symbolIndex),
1346
+ fractional: extractField(data, "fractional", symbolIndex),
1347
+ pricescale: extractField(data, "pricescale", symbolIndex),
1348
+ type: extractField(data, "type", symbolIndex),
1349
+ session: extractField(data, "session-regular", symbolIndex),
1350
+ session_holidays: extractField(data, "session-holidays", symbolIndex),
1351
+ corrections: extractField(data, "corrections", symbolIndex),
1352
+ timezone: extractField(data, "timezone", symbolIndex),
1353
+ supported_resolutions: definedValueOrDefault(
1354
+ extractField(data, "supported-resolutions", symbolIndex, true),
1355
+ this._datafeedSupportedResolutions
1356
+ ),
1357
+ has_daily: definedValueOrDefault(
1358
+ extractField(data, "has-daily", symbolIndex),
1359
+ true
1360
+ ),
1361
+ intraday_multipliers: definedValueOrDefault(
1362
+ extractField(data, "intraday-multipliers", symbolIndex, true),
1363
+ ["1", "5", "15", "30", "60"]
1364
+ ),
1365
+ has_weekly_and_monthly: extractField(
1366
+ data,
1367
+ "has-weekly-and-monthly",
1368
+ symbolIndex
1369
+ ),
1370
+ has_empty_bars: extractField(data, "has-empty-bars", symbolIndex),
1371
+ volume_precision: definedValueOrDefault(
1372
+ extractField(data, "volume-precision", symbolIndex),
1373
+ 0
1374
+ ),
1375
+ format: "price"
1376
+ };
1377
+ this._symbolsInfo[ticker] = symbolInfo;
1378
+ this._symbolsInfo[symbolName] = symbolInfo;
1379
+ this._symbolsInfo[fullName] = symbolInfo;
1380
+ if (currencyCode !== void 0 || unitId !== void 0) {
1381
+ this._symbolsInfo[symbolKey(ticker, currencyCode, unitId)] = symbolInfo;
1382
+ this._symbolsInfo[symbolKey(symbolName, currencyCode, unitId)] = symbolInfo;
1383
+ this._symbolsInfo[symbolKey(fullName, currencyCode, unitId)] = symbolInfo;
1384
+ }
1385
+ this._symbolsList.push(symbolName);
1386
+ }
1387
+ } catch (error) {
1388
+ throw new Error(
1389
+ `SymbolsStorage: API error when processing exchange ${exchange} symbol #${symbolIndex} (${data.symbol[symbolIndex]}): ${Object(error).message}`
1390
+ );
1391
+ }
1392
+ }
1393
+ };
1394
+ function definedValueOrDefault(value, defaultValue) {
1395
+ return value !== void 0 ? value : defaultValue;
1396
+ }
1397
+
1398
+ // src/tradingviewAdapter/datafeed/abstract-datafeed.ts
1399
+ var AbstractDatafeed = class {
1400
+ constructor(datafeedURL) {
1401
+ this._configuration = defaultConfiguration();
1402
+ this._symbolsStorage = null;
1403
+ this._datafeedURL = datafeedURL;
1404
+ this._requester = new Requester();
1405
+ this._historyProvider = new HistoryProvider(datafeedURL, this._requester);
1406
+ this._configurationReadyPromise = this._requestConfiguration().then(
1407
+ (configuration) => {
1408
+ if (configuration === null) {
1409
+ configuration = defaultConfiguration();
1410
+ }
1411
+ this._setupWithConfiguration(configuration);
1412
+ }
1413
+ );
1414
+ }
1415
+ getBars(symbolInfo, resolution, periodParams, onResult, onError) {
1416
+ this._historyProvider.getBars(symbolInfo, resolution, periodParams).then((result) => {
1417
+ onResult(result.bars, result.meta);
1418
+ }).catch(onError);
1419
+ }
1420
+ onReady(callback) {
1421
+ this._configurationReadyPromise.then(() => {
1422
+ callback(this._configuration);
1423
+ });
1424
+ }
1425
+ searchSymbols(userInput, exchange, symbolType, onResult) {
1426
+ if (this._symbolsStorage === null) {
1427
+ throw new Error("Datafeed: inconsistent configuration (symbols storage)");
1428
+ }
1429
+ this._symbolsStorage.searchSymbols(
1430
+ userInput,
1431
+ exchange,
1432
+ symbolType,
1433
+ 30 /* SearchItemsLimit */
1434
+ ).then(onResult).catch(onResult.bind(null, []));
1435
+ }
1436
+ resolveSymbol(symbolName, onResolve, onError, extension) {
1437
+ const currencyCode = extension && extension.currencyCode;
1438
+ const unitId = extension && extension.unitId;
1439
+ function onResultReady(symbolInfo) {
1440
+ onResolve(symbolInfo);
1441
+ }
1442
+ if (this._symbolsStorage === null) {
1443
+ throw new Error("Datafeed: inconsistent configuration (symbols storage)");
1444
+ }
1445
+ this._symbolsStorage.resolveSymbol(symbolName, currencyCode, unitId).then(onResultReady).catch(onError);
1446
+ }
1447
+ getMarks() {
1448
+ }
1449
+ getTimescaleMarks() {
1450
+ }
1451
+ getServerTime() {
1452
+ }
1453
+ _requestConfiguration() {
1454
+ return this._send("config").catch(
1455
+ (reason) => {
1456
+ logMessage(
1457
+ `Datafeed: Cannot get datafeed configuration - use default, error=${getErrorMessage(
1458
+ reason
1459
+ )}`
1460
+ );
1461
+ return null;
1462
+ }
1463
+ );
1464
+ }
1465
+ _send(urlPath, params) {
1466
+ return this._requester.sendRequest(this._datafeedURL, urlPath, params);
1467
+ }
1468
+ _setupWithConfiguration(configurationData) {
1469
+ this._configuration = configurationData;
1470
+ if (configurationData.exchanges === void 0) {
1471
+ configurationData.exchanges = [];
1472
+ }
1473
+ if (!configurationData.supports_search && !configurationData.supports_group_request) {
1474
+ throw new Error(
1475
+ "Unsupported datafeed configuration. Must either support search, or support group request"
1476
+ );
1477
+ }
1478
+ if (configurationData.supports_group_request || !configurationData.supports_search) {
1479
+ this._symbolsStorage = new SymbolsStorage(
1480
+ this._datafeedURL,
1481
+ configurationData.supported_resolutions || [],
1482
+ this._requester
1483
+ );
1484
+ }
1485
+ logMessage(
1486
+ `Datafeed: Initialized with ${JSON.stringify(configurationData)}`
1487
+ );
1488
+ }
1489
+ };
1490
+ function defaultConfiguration() {
1491
+ return {
1492
+ supports_search: false,
1493
+ supports_group_request: true,
1494
+ supported_resolutions: [
1495
+ "1",
1496
+ "3",
1497
+ "5",
1498
+ "15",
1499
+ "30",
1500
+ "60",
1501
+ "120",
1502
+ "240",
1503
+ "480",
1504
+ "720",
1505
+ "1D",
1506
+ "3D",
1507
+ "1W",
1508
+ "1M"
1509
+ ],
1510
+ supports_marks: false,
1511
+ supports_timescale_marks: false
1512
+ };
1513
+ }
1514
+
1515
+ // src/tradingviewAdapter/datafeed/eventBus.ts
1516
+ var MultiBroadcastEventBus = class {
1517
+ constructor() {
1518
+ this.subscribers = /* @__PURE__ */ new Map();
1519
+ }
1520
+ subscribe(eventName, callback) {
1521
+ if (!this.subscribers.has(eventName)) {
1522
+ this.subscribers.set(eventName, []);
1523
+ }
1524
+ const callbacks = this.subscribers.get(eventName);
1525
+ callbacks.push(callback);
1526
+ return () => {
1527
+ this.unsubscribe(eventName, callback);
1528
+ };
1529
+ }
1530
+ unsubscribe(eventName, callback) {
1531
+ if (this.subscribers.has(eventName)) {
1532
+ const callbacks = this.subscribers.get(eventName);
1533
+ this.subscribers.set(
1534
+ eventName,
1535
+ callbacks.filter((cb) => cb !== callback)
1536
+ );
1537
+ if (this.subscribers.get(eventName).length === 0) {
1538
+ this.subscribers.delete(eventName);
1539
+ }
1540
+ }
1541
+ }
1542
+ publish(eventName, data) {
1543
+ if (this.subscribers.has(eventName)) {
1544
+ const callbacks = this.subscribers.get(eventName);
1545
+ callbacks.forEach((callback) => {
1546
+ callback(data);
1547
+ });
1548
+ }
1549
+ }
1550
+ };
1551
+
1552
+ // src/utils/common.util.ts
1553
+ var mapResolution = (resolution) => {
1554
+ let time = "1d";
1555
+ switch (resolution) {
1556
+ case "1" /* RESOLUTION_1m */:
1557
+ time = "1m";
1558
+ break;
1559
+ case "3" /* RESOLUTION_3m */:
1560
+ time = "3m";
1561
+ break;
1562
+ case "5" /* RESOLUTION_5m */:
1563
+ time = "5m";
1564
+ break;
1565
+ case "15" /* RESOLUTION_15m */:
1566
+ time = "15m";
1567
+ break;
1568
+ case "30" /* RESOLUTION_30m */:
1569
+ time = "30m";
1570
+ break;
1571
+ case "60" /* RESOLUTION_60m */:
1572
+ time = "1h";
1573
+ break;
1574
+ case "120" /* RESOLUTION_120m */:
1575
+ time = "2h";
1576
+ break;
1577
+ case "240" /* RESOLUTION_240m */:
1578
+ time = "4h";
1579
+ break;
1580
+ case "480" /* RESOLUTION_480m */:
1581
+ time = "8h";
1582
+ break;
1583
+ case "720" /* RESOLUTION_720m */:
1584
+ time = "12h";
1585
+ break;
1586
+ case "D" /* RESOLUTION_D */:
1587
+ case "1D" /* RESOLUTION_1D */:
1588
+ time = "1d";
1589
+ break;
1590
+ case "3D" /* RESOLUTION_3D */:
1591
+ time = "3d";
1592
+ break;
1593
+ case "1W" /* RESOLUTION_1W */:
1594
+ time = "1w";
1595
+ break;
1596
+ case "1M" /* RESOLUTION_1M */:
1597
+ time = "1M ";
1598
+ break;
1599
+ }
1600
+ return time;
1601
+ };
1602
+ var TradingViewSDKLocalstorageKey = {
1603
+ interval: "TradingviewSDK.lastUsedTimeBasedResolution",
1604
+ lineType: "TradingviewSDK.lastUsedStyle",
1605
+ displayControlSetting: "TradingviewSDK.displaySetting"
1606
+ };
1607
+
1608
+ // src/tradingviewAdapter/datafeed/websocket.service.ts
1609
+ var getKlineKey = (symbol, type) => `${symbol}kline_${type}`;
1610
+ var getSymbolTopics = (symbol) => {
1611
+ const symbolTopics = ["trade"];
1612
+ return symbolTopics.map((topic) => `${symbol}@${topic}`);
1613
+ };
1614
+ var _WebsocketService = class _WebsocketService {
1615
+ constructor(ws) {
1616
+ this.klineSubscribeIdMap = /* @__PURE__ */ new Map();
1617
+ this.klineOnTickCallback = /* @__PURE__ */ new Map();
1618
+ this.subscribeCachedTopics = /* @__PURE__ */ new Map();
1619
+ this.wsInstance = null;
1620
+ this.klineData = /* @__PURE__ */ new Map();
1621
+ if (!_WebsocketService._created) {
1622
+ this.wsInstance = ws;
1623
+ _WebsocketService._instance = this;
1624
+ _WebsocketService._created = true;
1625
+ }
1626
+ return _WebsocketService._instance;
1627
+ }
1628
+ subscribeKline(subscribeId, symbol, resolution, onTickCallback) {
1629
+ const time = mapResolution(resolution);
1630
+ this.klineSubscribeIdMap.set(subscribeId, { symbol, resolution });
1631
+ const klineKey = getKlineKey(symbol, time);
1632
+ if (this.klineOnTickCallback.has(klineKey)) {
1633
+ const value = this.klineOnTickCallback.get(klineKey);
1634
+ value[subscribeId] = onTickCallback;
1635
+ } else {
1636
+ this.klineOnTickCallback.set(klineKey, {
1637
+ [subscribeId]: onTickCallback
1638
+ });
1639
+ const unsub = this.wsInstance?.subscribe(
1640
+ {
1641
+ event: "subscribe",
1642
+ topic: `${symbol}@kline_${time}`,
1643
+ id: `${symbol}@kline_${time}`,
1644
+ ts: (/* @__PURE__ */ new Date()).getTime()
1645
+ },
1646
+ {
1647
+ onMessage: (data) => {
1648
+ const { open, close, high, low, volume, startTime } = data;
1649
+ const key = getKlineKey(data.symbol, data.type);
1650
+ this.updateKline(key, {
1651
+ time: startTime,
1652
+ close,
1653
+ open,
1654
+ high,
1655
+ low,
1656
+ volume
1657
+ });
1658
+ }
1659
+ }
1660
+ );
1661
+ this.subscribeCachedTopics.set(`${symbol}@kline_${time}`, unsub);
1662
+ }
1663
+ }
1664
+ unsubscribeKline(subscribeId) {
1665
+ if (!this.klineSubscribeIdMap.has(subscribeId)) {
1666
+ return;
1667
+ }
1668
+ const { symbol, resolution } = this.klineSubscribeIdMap.get(subscribeId);
1669
+ const time = mapResolution(resolution);
1670
+ const klineKey = getKlineKey(symbol, time);
1671
+ if (this.klineOnTickCallback.has(klineKey)) {
1672
+ const value = this.klineOnTickCallback.get(klineKey);
1673
+ delete value[subscribeId];
1674
+ if (Object.keys(value).length === 0) {
1675
+ this.klineOnTickCallback.delete(klineKey);
1676
+ const unsub = this.subscribeCachedTopics.get(`${symbol}@kline_${time}`);
1677
+ unsub();
1678
+ }
1679
+ }
1680
+ delete this.klineSubscribeIdMap[subscribeId];
1681
+ }
1682
+ subscribeSymbol(symbol) {
1683
+ const symbolTopics = getSymbolTopics(symbol);
1684
+ symbolTopics.forEach((topic) => {
1685
+ if (!this.subscribeCachedTopics.has(topic)) {
1686
+ const unsub = this.wsInstance?.subscribe(
1687
+ {
1688
+ event: "subscribe",
1689
+ topic,
1690
+ id: topic,
1691
+ ts: (/* @__PURE__ */ new Date()).getTime()
1692
+ },
1693
+ {
1694
+ onMessage: (data) => {
1695
+ this.updateKlineByLastPrice(data.symbol, data.price);
1696
+ }
1697
+ }
1698
+ );
1699
+ this.subscribeCachedTopics.set(topic, unsub);
1700
+ }
1701
+ });
1702
+ }
1703
+ updateKlineByLastPrice(symbol, lastPrice) {
1704
+ this.klineOnTickCallback.forEach((_, key) => {
1705
+ if (key.startsWith(symbol)) {
1706
+ const klineData = this.klineData.get(key);
1707
+ if (klineData) {
1708
+ this.updateKline(key, { ...klineData, close: lastPrice });
1709
+ }
1710
+ }
1711
+ });
1712
+ }
1713
+ updateKline(key, cbParams) {
1714
+ const onTickCbs = this.klineOnTickCallback.get(key);
1715
+ if (onTickCbs && cbParams) {
1716
+ this.klineData.set(key, cbParams);
1717
+ Object.keys(onTickCbs).forEach((key2) => {
1718
+ const onTickCb = onTickCbs[key2];
1719
+ if (onTickCb && typeof onTickCb === "function") {
1720
+ onTickCb(cbParams);
1721
+ }
1722
+ });
1723
+ }
1724
+ }
1725
+ };
1726
+ _WebsocketService._created = false;
1727
+ _WebsocketService._instance = null;
1728
+ var WebsocketService = _WebsocketService;
1729
+
1730
+ // src/tradingviewAdapter/datafeed/datafeed.ts
1731
+ var getAutoIncrementId = /* @__PURE__ */ (() => {
1732
+ let id = 0;
1733
+ return () => id++;
1734
+ })();
1735
+ var Datafeed = class extends AbstractDatafeed {
1736
+ constructor(apiUrl, ws) {
1737
+ const datafeedURL = `${apiUrl}/tv`;
1738
+ super(datafeedURL);
1739
+ this.bbosMap = /* @__PURE__ */ new Map();
1740
+ this.tickersMap = /* @__PURE__ */ new Map();
1741
+ this.eventBus = new MultiBroadcastEventBus();
1742
+ this._subscribeQuoteMap = /* @__PURE__ */ new Map();
1743
+ this._prefixId = getAutoIncrementId();
1744
+ this._publicWs = new WebsocketService(ws);
1745
+ this.bbosMap = /* @__PURE__ */ new Map();
1746
+ ws.on("tickers", (message) => {
1747
+ for (const ticker of message.data) {
1748
+ ticker.change = ticker.close - ticker.open;
1749
+ ticker.perChange = ticker.open ? +(100 * ticker.change / ticker.open).toFixed(2) : 0;
1750
+ this.tickersMap.set(ticker.symbol, ticker);
1751
+ }
1752
+ this.eventBus.publish("tickerUpdate", { message: "ticker" });
1753
+ });
1754
+ ws.subscribe(
1755
+ {
1756
+ event: "subscribe",
1757
+ topic: `bbos`
1758
+ },
1759
+ {
1760
+ formatter: (message) => message,
1761
+ onMessage: (message) => {
1762
+ for (const bbo of message.data) {
1763
+ this.bbosMap.set(bbo.symbol, {
1764
+ ask: bbo.ask,
1765
+ bid: bbo.bid,
1766
+ askSize: bbo.askSize,
1767
+ bidSize: bbo.bidSize
1768
+ });
1769
+ }
1770
+ this.eventBus.publish("tickerUpdate", { message: "bbos" });
1771
+ }
1772
+ }
1773
+ );
1774
+ }
1775
+ remove() {
1776
+ Array.from(this._subscribeQuoteMap.values()).forEach((s) => s?.());
1777
+ }
1778
+ getSubscriptionId(listenerGuid) {
1779
+ return `${this._prefixId}${listenerGuid}`;
1780
+ }
1781
+ subscribeBars(symbolInfo, resolution, onTick, listenerGuid, onResetCacheNeededCallback) {
1782
+ window.onResetCacheNeededCallback = onResetCacheNeededCallback;
1783
+ this._publicWs.subscribeKline(
1784
+ `${this._prefixId}${listenerGuid}`,
1785
+ symbolInfo.ticker,
1786
+ resolution,
1787
+ onTick
1788
+ );
1789
+ }
1790
+ unsubscribeBars(listenerGuid) {
1791
+ this._publicWs.unsubscribeKline(`${this._prefixId}${listenerGuid}`);
1792
+ }
1793
+ getQuotes(symbols, onDataCallback) {
1794
+ const subscriptionId = this.getSubscriptionId("getQuotes");
1795
+ this.unsubscribeQuotes("getQuotes");
1796
+ const unsub = this.eventBus.subscribe("tickerUpdate", (msg) => {
1797
+ const dataMap = /* @__PURE__ */ new Map();
1798
+ symbols.forEach((symbol) => {
1799
+ const bbo = this.bbosMap.get(withoutExchangePrefix(symbol));
1800
+ const ticker = this.tickersMap.get(withoutExchangePrefix(symbol));
1801
+ if (!bbo || !ticker) {
1802
+ return;
1803
+ }
1804
+ const data = {
1805
+ ...ticker,
1806
+ ask: bbo.ask,
1807
+ bid: bbo.bid
1808
+ };
1809
+ dataMap.set(withoutExchangePrefix(symbol), data);
1810
+ });
1811
+ if (!dataMap.size) {
1812
+ return;
1813
+ }
1814
+ onDataCallback(
1815
+ Array.from(dataMap.values()).map(
1816
+ (symbolData) => this._toUDFTicker(symbolData)
1817
+ )
1818
+ );
1819
+ });
1820
+ this._subscribeQuoteMap.set(subscriptionId, unsub);
1821
+ }
1822
+ subscribeQuotes(symbols, fastSymbols, onRealtimeCallback, listenerGuid) {
1823
+ const subscriptionId = `${this._prefixId}${listenerGuid}`;
1824
+ if (symbols.length > 0) {
1825
+ this.unsubscribeQuotes(subscriptionId);
1826
+ const unsub = this.eventBus.subscribe("tickerUpdate", (msg) => {
1827
+ const dataMap = /* @__PURE__ */ new Map();
1828
+ symbols.forEach((symbol) => {
1829
+ const bbo = this.bbosMap.get(withoutExchangePrefix(symbol));
1830
+ const ticker = this.tickersMap.get(withoutExchangePrefix(symbol));
1831
+ if (!bbo || !ticker) {
1832
+ return;
1833
+ }
1834
+ const data = {
1835
+ ...ticker,
1836
+ ask: bbo.ask,
1837
+ bid: bbo.bid
1838
+ };
1839
+ dataMap.set(withoutExchangePrefix(symbol), data);
1840
+ });
1841
+ if (!dataMap.size) {
1842
+ return;
1843
+ }
1844
+ onRealtimeCallback(
1845
+ Array.from(dataMap.values()).map(
1846
+ (symbolData) => this._toUDFTicker(symbolData)
1847
+ )
1848
+ );
1849
+ });
1850
+ this._subscribeQuoteMap.set(subscriptionId, unsub);
1851
+ }
1852
+ }
1853
+ unsubscribeQuotes(listenerGuid) {
1854
+ const subscriptionId = this.getSubscriptionId(listenerGuid);
1855
+ const unsub = this._subscribeQuoteMap.get(subscriptionId);
1856
+ if (unsub) {
1857
+ unsub();
1858
+ this._subscribeQuoteMap.delete(subscriptionId);
1859
+ }
1860
+ }
1861
+ _toUDFTicker(t) {
1862
+ return {
1863
+ n: withExchangePrefix(t.symbol),
1864
+ s: "ok",
1865
+ v: {
1866
+ ask: t.ask,
1867
+ bid: t.bid,
1868
+ ch: t.change,
1869
+ chp: t.perChange / 100,
1870
+ description: "",
1871
+ exchange: EXCHANGE,
1872
+ hight_price: t.high,
1873
+ low_price: t.low,
1874
+ lp: t.close,
1875
+ open_price: t.open,
1876
+ prev_close_price: 0,
1877
+ volume: t.volume
1878
+ }
1879
+ };
1880
+ }
1881
+ };
1882
+ var EST_TPSL_PNL_DECIMAL = 2;
1883
+ var textDash = "--";
1884
+ var BracketAlgoType = ["BRACKET" /* BRACKET */, "STOP_BRACKET" /* STOP_BRACKET */];
1885
+ var TpslAlgoType = ["POSITIONAL_TP_SL" /* POSITIONAL_TP_SL */, "TP_SL" /* TP_SL */];
1886
+ var isTpslOrder = (order) => order.root_algo_order_id !== order.algo_order_id && (order.algo_type === "TAKE_PROFIT" /* TAKE_PROFIT */ || order.algo_type === "STOP_LOSS" /* STOP_LOSS */);
1887
+ var isBracketAlgoType = (algoType) => !!algoType && BracketAlgoType.includes(algoType);
1888
+ var isPositionTpsl = (order) => order.type === "CLOSE_POSITION" /* CLOSE_POSITION */;
1889
+ var isActivatedPositionTpsl = (order) => isPositionTpsl(order) && order.is_activated;
1890
+ var isActivatedTpslOrder = (order) => isTpslOrder(order) && order.is_activated;
1891
+ var isActivatedQuantityTpsl = (order) => order.root_algo_order_algo_type === "TP_SL" /* TP_SL */ || isBracketAlgoType(order.root_algo_order_algo_type) && order.is_activated;
1892
+ var getTpslTag = (order, quantityTpslNoMap) => {
1893
+ const algoType = order.algo_type;
1894
+ const suffix = {
1895
+ ["TAKE_PROFIT" /* TAKE_PROFIT */]: i18n.i18n.t("tpsl.takeProfit"),
1896
+ ["STOP_LOSS" /* STOP_LOSS */]: i18n.i18n.t("tpsl.stopLoss")
1897
+ }[algoType];
1898
+ if (!suffix) {
1899
+ return null;
1900
+ }
1901
+ return suffix;
1902
+ };
1903
+ var buildQuantityTpslNoMap = (orders) => {
1904
+ const quantityTpslNoMap = /* @__PURE__ */ new Map();
1905
+ let idx = 1;
1906
+ [...orders].reverse().filter(isActivatedQuantityTpsl).forEach((order) => {
1907
+ if (order.root_algo_order_id && !quantityTpslNoMap.has(order.root_algo_order_id)) {
1908
+ quantityTpslNoMap.set(order.root_algo_order_id, idx++);
1909
+ }
1910
+ });
1911
+ return quantityTpslNoMap;
1912
+ };
1913
+ var getTpslEstPnl = (tpslOrder, position) => {
1914
+ const quantity = Math.abs(
1915
+ tpslOrder.type === "CLOSE_POSITION" /* CLOSE_POSITION */ ? position.balance : tpslOrder.quantity
1916
+ );
1917
+ const sideFlag = tpslOrder.side === "SELL" /* SELL */ ? 1 : -1;
1918
+ const openPrice = position.open.toString();
1919
+ const estPnl = new utils.Decimal(tpslOrder.trigger_price).minus(openPrice ?? 0).times(quantity).times(sideFlag).toString();
1920
+ return { estPnl, quantity, openPrice };
1921
+ };
1922
+ var formatPnl = (pnl) => {
1923
+ return pnl !== void 0 && pnl !== "" ? new utils.Decimal(pnl).todp(EST_TPSL_PNL_DECIMAL, utils.Decimal.ROUND_FLOOR) : textDash;
1924
+ };
1925
+ function useCancelOrder() {
1926
+ const [
1927
+ pendingOrders,
1928
+ { cancelOrder, cancelAlgoOrder, cancelTPSLChildOrder }
1929
+ ] = hooks.useOrderStream({
1930
+ status: types.OrderStatus.INCOMPLETE
1931
+ });
1932
+ return React3.useCallback(
1933
+ (order) => {
1934
+ if (order.algo_order_id) {
1935
+ if (TpslAlgoType.includes(order.root_algo_order_algo_type)) {
1936
+ const rootOrder = pendingOrders?.find(
1937
+ (item) => item.algo_order_id === order.root_algo_order_id
1938
+ );
1939
+ const isEditActivated = rootOrder.child_orders.every(
1940
+ (item) => !!item.trigger_price
1941
+ );
1942
+ if (isEditActivated) {
1943
+ return cancelTPSLChildOrder(
1944
+ order.algo_order_id,
1945
+ order.root_algo_order_id
1946
+ );
1947
+ }
1948
+ return cancelAlgoOrder(rootOrder.algo_order_id, order.symbol).then();
1949
+ }
1950
+ return cancelAlgoOrder(order.algo_order_id, order.symbol).then();
1951
+ }
1952
+ return cancelOrder(order.order_id, order.symbol).then();
1953
+ },
1954
+ [cancelOrder, pendingOrders]
1955
+ );
1956
+ }
1957
+ function useEditOrder(onToast) {
1958
+ hooks.useEventEmitter();
1959
+ const [, { updateOrder, cancelAlgoOrder, updateAlgoOrder, updateTPSLOrder }] = hooks.useOrderStream({
1960
+ status: types.OrderStatus.INCOMPLETE
1961
+ });
1962
+ return React3.useCallback(
1963
+ (order, lineValue) => {
1964
+ if (order.algo_order_id) {
1965
+ if (TpslAlgoType.includes(order.root_algo_order_algo_type)) {
1966
+ const algoParams = [
1967
+ {
1968
+ order_id: order.algo_order_id,
1969
+ trigger_price: new utils.Decimal(lineValue.value).toString()
1970
+ }
1971
+ ];
1972
+ return updateTPSLOrder(order.root_algo_order_id, algoParams).then((res) => {
1973
+ }).catch((e) => {
1974
+ if (onToast) {
1975
+ onToast.error(e.message);
1976
+ }
1977
+ });
1978
+ } else if (BracketAlgoType.includes(order.algo_type)) {
1979
+ return updateAlgoOrder(order.algo_order_id, {
1980
+ order_price: new utils.Decimal(lineValue.value).toString()
1981
+ }).then((res) => {
1982
+ }).catch((e) => {
1983
+ if (onToast) {
1984
+ onToast.error(e.message);
1985
+ }
1986
+ });
1987
+ } else {
1988
+ const values2 = {
1989
+ quantity: order.quantity,
1990
+ trigger_price: order.trigger_price,
1991
+ symbol: order.symbol,
1992
+ price: order.price,
1993
+ // order_type: order.type,
1994
+ // side: order.side,
1995
+ // reduce_only: Boolean(order.reduce_only),
1996
+ algo_order_id: order.algo_order_id
1997
+ };
1998
+ if (order.order_tag) {
1999
+ values2.order_tag = order.order_tag;
2000
+ }
2001
+ if (order.client_order_id) {
2002
+ values2.client_order_id = order.client_order_id;
2003
+ }
2004
+ if (lineValue.type === "price") {
2005
+ values2.price = new utils.Decimal(lineValue.value).toString();
2006
+ }
2007
+ if (lineValue.type === "trigger_price") {
2008
+ values2.trigger_price = new utils.Decimal(lineValue.value).toString();
2009
+ }
2010
+ return updateAlgoOrder(order.algo_order_id, values2).then((res) => {
2011
+ }).catch((e) => {
2012
+ if (onToast) {
2013
+ onToast.error(e.message);
2014
+ }
2015
+ });
2016
+ }
2017
+ }
2018
+ const values = {
2019
+ order_price: order.price?.toString(),
2020
+ order_quantity: order.quantity.toString(),
2021
+ symbol: order.symbol,
2022
+ order_type: order.type,
2023
+ side: order.side,
2024
+ visible_quantity: 0,
2025
+ reduce_only: order.reduce_only
2026
+ };
2027
+ if (new utils.Decimal(order.visible_quantity ?? order.visible ?? 0).eq(
2028
+ order.quantity
2029
+ )) {
2030
+ delete values.visible_quantity;
2031
+ }
2032
+ if (!Object.keys(order).includes("reduce_only")) {
2033
+ delete values.reduce_only;
2034
+ }
2035
+ if (order.order_tag) {
2036
+ values.order_tag = order.order_tag;
2037
+ }
2038
+ if (order.client_order_id) {
2039
+ values.client_order_id = order.client_order_id;
2040
+ }
2041
+ if (lineValue.type === "price") {
2042
+ values.order_price = new utils.Decimal(lineValue.value).toString();
2043
+ }
2044
+ return updateOrder(order.order_id, values).then((res) => {
2045
+ }).catch((e) => {
2046
+ onToast.error(e.message);
2047
+ });
2048
+ },
2049
+ [updateOrder]
2050
+ );
2051
+ }
2052
+ function useSendOrder(symbol) {
2053
+ const { onSubmit: _sendMarketOrder } = hooks.useOrderEntry_deprecated(
2054
+ {
2055
+ symbol,
2056
+ side: types.OrderSide.BUY,
2057
+ order_type: types.OrderType.MARKET
2058
+ },
2059
+ {
2060
+ watchOrderbook: true
2061
+ }
2062
+ );
2063
+ const sendLimitOrder = () => {
2064
+ };
2065
+ const sendMarketOrder = (data) => {
2066
+ data.reduce_only = false;
2067
+ return _sendMarketOrder(data).catch((e) => {
2068
+ ui.toast.error(e);
2069
+ });
2070
+ };
2071
+ return {
2072
+ sendLimitOrder,
2073
+ sendMarketOrder
2074
+ };
2075
+ }
2076
+ var createBrokerMethod = (method) => {
2077
+ return (params) => method(params);
2078
+ };
2079
+ var useBroker = ({
2080
+ closeConfirm,
2081
+ colorConfig,
2082
+ onToast,
2083
+ mode,
2084
+ symbol
2085
+ }) => {
2086
+ const cancelOrder = useCancelOrder();
2087
+ const editOrder = useEditOrder(onToast);
2088
+ const symbolData = hooks.useSymbolsInfo();
2089
+ const closePosition = React3.useCallback(
2090
+ (position) => closeConfirm && closeConfirm(position),
2091
+ [closeConfirm]
2092
+ );
2093
+ const { sendMarketOrder, sendLimitOrder } = useSendOrder(symbol);
2094
+ const getSymbolInfo = React3.useCallback(
2095
+ (symbol2) => {
2096
+ if (!symbolData) {
2097
+ return;
2098
+ }
2099
+ return {
2100
+ baseMin: symbolData[symbol2]("base_min"),
2101
+ baseMax: symbolData[symbol2]("base_max"),
2102
+ baseTick: symbolData[symbol2]("base_tick"),
2103
+ quoteTick: symbolData[symbol2]("quote_tick")
2104
+ };
2105
+ },
2106
+ [symbolData]
2107
+ );
2108
+ const broker = React3.useRef({
2109
+ cancelOrder,
2110
+ closePosition,
2111
+ editOrder,
2112
+ colorConfig,
2113
+ sendLimitOrder,
2114
+ getSymbolInfo,
2115
+ sendMarketOrder: createBrokerMethod(sendMarketOrder),
2116
+ mode
2117
+ });
2118
+ React3.useEffect(() => {
2119
+ broker.current.getSymbolInfo = getSymbolInfo;
2120
+ }, [symbolData]);
2121
+ React3.useEffect(() => {
2122
+ broker.current.sendLimitOrder = sendLimitOrder;
2123
+ broker.current.sendMarketOrder = sendMarketOrder;
2124
+ }, [sendLimitOrder, sendMarketOrder]);
2125
+ React3.useEffect(() => {
2126
+ broker.current.closePosition = closePosition;
2127
+ }, [closeConfirm]);
2128
+ React3.useEffect(() => {
2129
+ broker.current.cancelOrder = cancelOrder;
2130
+ }, [cancelOrder]);
2131
+ return broker.current;
2132
+ };
2133
+ var useBroker_default = useBroker;
2134
+ var IntervalMap = {
2135
+ 1: { startOf: "minute", period: 0 },
2136
+ 3: { startOf: "hour", period: 3 * 60 * 1e3 },
2137
+ 5: { startOf: "hour", period: 5 * 60 * 1e3 },
2138
+ 15: { startOf: "hour", period: 15 * 60 * 1e3 },
2139
+ 30: { startOf: "hour", period: 30 * 60 * 1e3 },
2140
+ 60: { startOf: "hour", period: 0 },
2141
+ 120: { startOf: "day", period: 2 * 60 * 60 * 1e3 },
2142
+ 240: { startOf: "day", period: 4 * 60 * 60 * 1e3 },
2143
+ 480: { startOf: "day", period: 8 * 60 * 60 * 1e3 },
2144
+ 720: { startOf: "day", period: 12 * 60 * 60 * 1e3 },
2145
+ D: { startOf: "day", period: 0 },
2146
+ // default day interval shown as D instead of 1D
2147
+ "1D": { startOf: "day", period: 0 },
2148
+ "3D": { startOf: "year", period: 3 * 24 * 60 * 60 * 1e3 },
2149
+ "5D": { startOf: "year", period: 5 * 24 * 60 * 60 * 1e3 },
2150
+ "1W": { startOf: "week", period: 0 },
2151
+ "1M": { startOf: "month", period: 0 }
2152
+ };
2153
+ function collectionOrders(order, collection, interval, orderList) {
2154
+ const { startOf, period } = IntervalMap[interval];
2155
+ const time = new Date(order.updated_time).getTime();
2156
+ let base = dateFns.startOfSecond(time).getTime();
2157
+ if (startOf === "minute") {
2158
+ base = dateFns.startOfMinute(time).getTime();
2159
+ } else if (startOf === "hour") {
2160
+ base = dateFns.startOfHour(time).getTime();
2161
+ } else if (startOf === "day") {
2162
+ base = dateFns.startOfDay(time).getTime();
2163
+ } else if (startOf === "month") {
2164
+ base = dateFns.startOfMonth(time).getTime();
2165
+ } else if (startOf === "year") {
2166
+ base = dateFns.startOfYear(time).getTime();
2167
+ } else if (startOf === "week") {
2168
+ base = dateFns.startOfWeek(time).getTime();
2169
+ } else if (startOf === "month") {
2170
+ base = dateFns.startOfMonth(time).getTime();
2171
+ }
2172
+ const group = period === 0 ? base : Math.floor((time - base) / period) * period + base;
2173
+ if (!collection[group]) {
2174
+ collection[group] = { ["BUY" /* BUY */]: [], ["SELL" /* SELL */]: [] };
2175
+ }
2176
+ if (collection[group][order.side].length < 5) {
2177
+ collection[group][order.side].push(order);
2178
+ orderList.push(order);
2179
+ }
2180
+ }
2181
+ var limitOrdersByInterval = (orders, interval) => {
2182
+ const res = [];
2183
+ const collection = {};
2184
+ if (!IntervalMap[interval]) {
2185
+ return [];
2186
+ }
2187
+ orders.forEach((order) => {
2188
+ if (order.child_orders) {
2189
+ for (const child of order.child_orders) {
2190
+ if (child.is_activated && child.algo_status === types.OrderStatus.FILLED) {
2191
+ collectionOrders(child, collection, interval, res);
2192
+ }
2193
+ }
2194
+ } else {
2195
+ collectionOrders(order, collection, interval, res);
2196
+ }
2197
+ });
2198
+ return res;
2199
+ };
2200
+ var ExecutionService = class _ExecutionService {
2201
+ constructor(instance, broker) {
2202
+ this.interval = "1D";
2203
+ this.changeInterval = (interval) => {
2204
+ const rerenderExecutions = () => {
2205
+ this.renderExecutions(this.filledOrders, this.basePriceDecimal);
2206
+ this.instance.activeChart().onDataLoaded().unsubscribe(null, rerenderExecutions);
2207
+ };
2208
+ this.interval = interval;
2209
+ this.instance.activeChart().onDataLoaded().subscribe(null, rerenderExecutions);
2210
+ };
2211
+ this.instance = instance;
2212
+ this.executions = [];
2213
+ this.filledOrders = [];
2214
+ this.basePriceDecimal = 0;
2215
+ this.broker = broker;
2216
+ this.subscribeIntervalChange();
2217
+ }
2218
+ async subscribeIntervalChange() {
2219
+ this.interval = this.instance.symbolInterval().interval;
2220
+ const changeInterval = this.changeInterval;
2221
+ this.instance.activeChart().onIntervalChanged().subscribe(null, changeInterval);
2222
+ }
2223
+ renderExecutions(filledOrders, basePriceDecimal) {
2224
+ this.filledOrders = filledOrders;
2225
+ this.basePriceDecimal = basePriceDecimal;
2226
+ if (!this.interval) {
2227
+ return;
2228
+ }
2229
+ this.removeAll();
2230
+ limitOrdersByInterval(filledOrders, this.interval).forEach((order) => {
2231
+ this.executions.push(this.drawExecution(order, basePriceDecimal));
2232
+ });
2233
+ }
2234
+ removeAll() {
2235
+ this.executions.forEach((execution) => execution.remove());
2236
+ this.executions = [];
2237
+ }
2238
+ static getExecutionInfo(order, basePriceDecimal) {
2239
+ const side = order.side;
2240
+ const avgExecPrice = order.average_executed_price || order.child_orders?.find((child) => !!child.average_executed_price)?.average_executed_price || 0;
2241
+ const excutedNumber = new utils.Decimal(avgExecPrice).todp(basePriceDecimal, utils.Decimal.ROUND_FLOOR).toString();
2242
+ return `${side === "BUY" /* BUY */ ? i18n.i18n.t("common.buy") : i18n.i18n.t("common.sell")} ${order.total_executed_quantity} @${utils.commify(excutedNumber)}`;
2243
+ }
2244
+ drawExecution(order, basePriceDecimal) {
2245
+ const side = order.side;
2246
+ const avgExecPrice = order.average_executed_price || order.child_orders?.find((child) => !!child.average_executed_price)?.average_executed_price || 0;
2247
+ const timestamp = new Date(order.updated_time).getTime() / 1e3;
2248
+ const colorConfig = this.broker.colorConfig;
2249
+ return this.instance.activeChart().createExecutionShape().setArrowHeight(9).setTooltip(_ExecutionService.getExecutionInfo(order, basePriceDecimal)).setTime(timestamp).setPrice(avgExecPrice).setArrowColor(
2250
+ side === "BUY" /* BUY */ ? colorConfig.upColor : colorConfig.downColor
2251
+ ).setDirection(side === "BUY" /* BUY */ ? "buy" : "sell");
2252
+ }
2253
+ unsubscribeIntervalChange() {
2254
+ const changeInterval = this.changeInterval;
2255
+ try {
2256
+ this.instance.activeChart().onIntervalChanged().unsubscribe(null, changeInterval);
2257
+ } catch (e) {
2258
+ if (e instanceof Error && e.message === "Cannot read properties of null (reading 'tradingViewApi')") ;
2259
+ }
2260
+ }
2261
+ destroy() {
2262
+ this.removeAll();
2263
+ this.unsubscribeIntervalChange();
2264
+ }
2265
+ };
2266
+
2267
+ // src/tradingviewAdapter/renderer/order.util.ts
2268
+ var getOrderId = (order) => {
2269
+ if (order === null || order === void 0) {
2270
+ return void 0;
2271
+ }
2272
+ return order.algo_order_id || order.order_id;
2273
+ };
2274
+
2275
+ // src/tradingviewAdapter/renderer/tpslCal.service.ts
2276
+ var TpslCalService = class {
2277
+ constructor() {
2278
+ this.quantityTpslNoMap = /* @__PURE__ */ new Map();
2279
+ this.tpslPnlMap = /* @__PURE__ */ new Map();
2280
+ this.positions = null;
2281
+ }
2282
+ getQuantityTpslNoMap() {
2283
+ return this.quantityTpslNoMap;
2284
+ }
2285
+ getTpslPnlMap() {
2286
+ return this.tpslPnlMap;
2287
+ }
2288
+ getFormattedEstPnl(tpslOrder) {
2289
+ if (this.positions === null) {
2290
+ return "";
2291
+ }
2292
+ const position = this.positions[0];
2293
+ if (!position) {
2294
+ return "";
2295
+ }
2296
+ const { estPnl } = getTpslEstPnl(tpslOrder, position);
2297
+ return formatPnl(estPnl);
2298
+ }
2299
+ prepareTpslPnlMap(newPendingOrders) {
2300
+ const changed = [];
2301
+ newPendingOrders.forEach((order) => {
2302
+ const orderId = getOrderId(order);
2303
+ if (orderId && isActivatedTpslOrder(order)) {
2304
+ const prevPnl = this.tpslPnlMap.get(orderId);
2305
+ const newPnl = this.getFormattedEstPnl(order);
2306
+ if (prevPnl !== newPnl) {
2307
+ changed.push(orderId);
2308
+ this.tpslPnlMap.set(orderId, newPnl);
2309
+ }
2310
+ }
2311
+ });
2312
+ return changed;
2313
+ }
2314
+ prepareQuantityTpslNoMap(newPendingOrders) {
2315
+ this.quantityTpslNoMap = buildQuantityTpslNoMap(newPendingOrders);
2316
+ }
2317
+ recalculatePnl(positions, pendingOrders) {
2318
+ this.positions = positions;
2319
+ return this.prepareTpslPnlMap(pendingOrders);
2320
+ }
2321
+ clear() {
2322
+ this.positions = null;
2323
+ this.quantityTpslNoMap.clear();
2324
+ this.tpslPnlMap.clear();
2325
+ }
2326
+ };
2327
+
2328
+ // src/tradingviewAdapter/renderer/orderLine.service.ts
2329
+ var _OrderLineService = class _OrderLineService {
2330
+ constructor(instance, broker) {
2331
+ this.instance = instance;
2332
+ this.pendingOrderLineMap = /* @__PURE__ */ new Map();
2333
+ this.pendingOrders = [];
2334
+ this.broker = broker;
2335
+ this.tpslCalService = new TpslCalService();
2336
+ }
2337
+ renderPendingOrders(newPendingOrders) {
2338
+ if (newPendingOrders) {
2339
+ this.pendingOrders = newPendingOrders;
2340
+ }
2341
+ this.cleanOldPendingOrders(this.pendingOrders);
2342
+ this.tpslCalService.prepareTpslPnlMap(this.pendingOrders);
2343
+ this.tpslCalService.prepareQuantityTpslNoMap(this.pendingOrders);
2344
+ this.pendingOrders.forEach((order) => this.renderPendingOrder(order));
2345
+ }
2346
+ updatePositions(positions) {
2347
+ const changed = this.tpslCalService.recalculatePnl(
2348
+ positions,
2349
+ this.pendingOrders
2350
+ );
2351
+ this.pendingOrders.filter((order) => changed.includes(getOrderId(order))).forEach((order) => this.renderPendingOrder(order));
2352
+ }
2353
+ renderPendingOrder(order) {
2354
+ const orderId = _OrderLineService.getOrderId(order);
2355
+ if (!orderId) {
2356
+ return;
2357
+ }
2358
+ const orderLine = this.drawOrderLine(orderId, order);
2359
+ if (orderLine) {
2360
+ this.pendingOrderLineMap.set(orderId, orderLine);
2361
+ }
2362
+ }
2363
+ cleanOldPendingOrders(newPendingOrders) {
2364
+ const newOrderIdSet = new Set(
2365
+ newPendingOrders.map((order) => _OrderLineService.getOrderId(order))
2366
+ );
2367
+ this.pendingOrderLineMap.forEach(
2368
+ (_, orderId) => !newOrderIdSet.has(orderId) && this.removePendingOrder(orderId)
2369
+ );
2370
+ }
2371
+ removePendingOrder(orderId) {
2372
+ if (orderId === void 0) {
2373
+ return;
2374
+ }
2375
+ const orderLine = this.pendingOrderLineMap.get(orderId);
2376
+ if (orderLine) {
2377
+ this.pendingOrderLineMap.delete(orderId);
2378
+ orderLine.remove();
2379
+ }
2380
+ }
2381
+ getBaseOrderLine() {
2382
+ const colorConfig = this.broker.colorConfig;
2383
+ return this.instance.activeChart().createOrderLine().setCancelTooltip(i18n.i18n.t("orders.cancelOrder")).setQuantityTextColor(colorConfig.qtyTextColor).setQuantityBackgroundColor(colorConfig.chartBG).setBodyBackgroundColor(colorConfig.chartBG).setCancelButtonBackgroundColor(colorConfig.chartBG).setLineStyle(1).setBodyFont(colorConfig.font).setQuantityFont(colorConfig.font);
2384
+ }
2385
+ static getCombinationType(order) {
2386
+ const { algo_type: algoType, type } = order;
2387
+ if ((algoType === "STOP_LOSS" /* STOP_LOSS */ || algoType === "TAKE_PROFIT" /* TAKE_PROFIT */ || algoType === "STOP" /* STOP */) && type === "LIMIT" /* LIMIT */) {
2388
+ return "STOP_LIMIT" /* STOP_LIMIT */;
2389
+ }
2390
+ if ((algoType === "STOP_LOSS" /* STOP_LOSS */ || algoType === "TAKE_PROFIT" /* TAKE_PROFIT */ || algoType === "STOP" /* STOP */) && type === "MARKET" /* MARKET */) {
2391
+ return "STOP_MARKET" /* STOP_MARKET */;
2392
+ }
2393
+ if (algoType === "BRACKET" /* BRACKET */) {
2394
+ if (type === "LIMIT" /* LIMIT */) {
2395
+ return "BRACKET_LIMIT" /* BRACKET_LIMIT */;
2396
+ }
2397
+ if (type === "MARKET" /* MARKET */) {
2398
+ return "BRACKET_MARKET" /* BRACKET_MARKET */;
2399
+ }
2400
+ }
2401
+ if (algoType === "TRAILING_STOP" /* TRAILING_STOP */) {
2402
+ return "TRAILING_STOP" /* TRAILING_STOP */;
2403
+ }
2404
+ return "LIMIT" /* LIMIT */;
2405
+ }
2406
+ static getText(pendingOrder) {
2407
+ const orderCombinationType = _OrderLineService.getCombinationType(pendingOrder);
2408
+ if (orderCombinationType === "STOP_LIMIT" /* STOP_LIMIT */ || orderCombinationType === "STOP_MARKET" /* STOP_MARKET */ || orderCombinationType === "STOP_BRACKET_LIMIT" /* STOP_BRACKET_LIMIT */ || orderCombinationType === "STOP_BRACKET_MARKET" /* STOP_BRACKET_MARKET */) {
2409
+ if (pendingOrder.type === "LIMIT" /* LIMIT */) {
2410
+ return `${i18n.i18n.t("orderEntry.orderType.stopLimit")} ${utils.commify(
2411
+ pendingOrder.price
2412
+ )}`;
2413
+ }
2414
+ return i18n.i18n.t("orderEntry.orderType.stopMarket");
2415
+ }
2416
+ if (orderCombinationType === "TRAILING_STOP" /* TRAILING_STOP */) {
2417
+ return i18n.i18n.t("orderEntry.trailing");
2418
+ }
2419
+ return i18n.i18n.t("orderEntry.orderType.limit");
2420
+ }
2421
+ static getOrderPrice(pendingOrder) {
2422
+ if (pendingOrder.algo_type === "TRAILING_STOP" /* TRAILING_STOP */) {
2423
+ return utils.getTrailingStopPrice(pendingOrder);
2424
+ }
2425
+ return pendingOrder.trigger_price || pendingOrder.price;
2426
+ }
2427
+ getTPSLTextWithTpsl(text, pendingOrder) {
2428
+ const orderId = getOrderId(pendingOrder);
2429
+ if (!orderId) {
2430
+ return text;
2431
+ }
2432
+ return text;
2433
+ }
2434
+ getTPSLText(pendingOrder) {
2435
+ const tpslTypeText = getTpslTag(
2436
+ pendingOrder,
2437
+ this.tpslCalService.getQuantityTpslNoMap()
2438
+ );
2439
+ if (tpslTypeText) {
2440
+ return this.getTPSLTextWithTpsl(tpslTypeText, pendingOrder);
2441
+ }
2442
+ return null;
2443
+ }
2444
+ getOrderQuantity(pendingOrder) {
2445
+ if (pendingOrder.algo_order_id) {
2446
+ if (isActivatedPositionTpsl(pendingOrder) || isPositionTpsl(pendingOrder)) {
2447
+ return "100%";
2448
+ }
2449
+ if (isActivatedQuantityTpsl(pendingOrder)) {
2450
+ const qty = new utils.Decimal(pendingOrder.quantity).minus(
2451
+ pendingOrder.executed ?? 0
2452
+ );
2453
+ const per = qty.div(new utils.Decimal(pendingOrder.position_qty)).mul(100).todp(2).toNumber();
2454
+ return `${Math.min(Math.abs(per), 100).toString()}%`;
2455
+ }
2456
+ }
2457
+ return utils.commify(new utils.Decimal(pendingOrder.quantity).toString());
2458
+ }
2459
+ drawOrderLine(orderId, pendingOrder) {
2460
+ const text = isTpslOrder(pendingOrder) ? this.getTPSLText(pendingOrder) : _OrderLineService.getText(pendingOrder);
2461
+ if (text === null) {
2462
+ return null;
2463
+ }
2464
+ const colorConfig = this.broker.colorConfig;
2465
+ const orderLine = this.pendingOrderLineMap.get(orderId) ?? this.getBaseOrderLine();
2466
+ const color = pendingOrder.side === "BUY" /* BUY */ ? colorConfig.upColor : colorConfig.downColor;
2467
+ pendingOrder.side === "BUY" /* BUY */ ? colorConfig.pnlUpColor : colorConfig.pnlDownColor;
2468
+ const price = _OrderLineService.getOrderPrice(pendingOrder);
2469
+ const lineLength = 100;
2470
+ const quantity = this.getOrderQuantity(pendingOrder);
2471
+ const textColor2 = colorConfig.textColor;
2472
+ orderLine.setText(text).setCancelButtonIconColor(colorConfig.closeIcon).setCancelButtonBorderColor(color).setBodyTextColor(textColor2).setBodyBorderColor(color).setQuantityBorderColor(color).setQuantityTextColor(color).setLineColor(color).setLineLength(lineLength).setQuantity(quantity ?? "").setPrice(price);
2473
+ if (this.broker.mode !== 3 /* MOBILE */) {
2474
+ orderLine.onCancel(null, () => this.broker.cancelOrder(pendingOrder));
2475
+ this.applyEditOnMove(orderLine, pendingOrder);
2476
+ } else {
2477
+ orderLine.setEditable(false).setCancellable(false);
2478
+ }
2479
+ return orderLine;
2480
+ }
2481
+ static getOrderEditKey(pendingOrder) {
2482
+ const orderCombinationType = this.getCombinationType(pendingOrder);
2483
+ if (["LIMIT" /* LIMIT */, "BRACKET_LIMIT" /* BRACKET_LIMIT */].includes(
2484
+ orderCombinationType
2485
+ )) {
2486
+ return "price";
2487
+ }
2488
+ if (orderCombinationType === "STOP_LIMIT" /* STOP_LIMIT */ || orderCombinationType === "STOP_MARKET" /* STOP_MARKET */ || pendingOrder.rootAlgoOrderAlgoType === "POSITIONAL_TP_SL" /* POSITIONAL_TP_SL */ || pendingOrder.rootAlgoOrderAlgoType === "TP_SL" /* TP_SL */ || pendingOrder.rootAlgoOrderAlgoType === "BRACKET" /* BRACKET */ || pendingOrder.rootAlgoOrderAlgoType === "STOP_BRACKET" /* STOP_BRACKET */) {
2489
+ return "trigger_price";
2490
+ }
2491
+ }
2492
+ applyEditOnMove(orderLine, pendingOrder) {
2493
+ const editKey = _OrderLineService.getOrderEditKey(pendingOrder);
2494
+ if (!editKey) {
2495
+ return;
2496
+ }
2497
+ orderLine.onMove(() => {
2498
+ this.broker.editOrder(pendingOrder, {
2499
+ type: editKey,
2500
+ value: `${orderLine.getPrice()}`
2501
+ }).then((res) => {
2502
+ if (!res.success) {
2503
+ this.renderPendingOrder(pendingOrder);
2504
+ }
2505
+ }).catch(() => this.renderPendingOrder(pendingOrder));
2506
+ });
2507
+ }
2508
+ removeAll() {
2509
+ this.pendingOrderLineMap.forEach((orderLine) => orderLine.remove());
2510
+ this.pendingOrderLineMap.clear();
2511
+ this.pendingOrders = [];
2512
+ this.tpslCalService.clear();
2513
+ }
2514
+ };
2515
+ _OrderLineService.getOrderId = (order) => {
2516
+ if (order === null || order === void 0) {
2517
+ return void 0;
2518
+ }
2519
+ return order.algo_order_id || order.order_id;
2520
+ };
2521
+ var OrderLineService = _OrderLineService;
2522
+ var PositionLineService = class _PositionLineService {
2523
+ constructor(instance, broker) {
2524
+ this.instance = instance;
2525
+ this.currentSymbol = "";
2526
+ this.broker = broker;
2527
+ this.positionLines = {};
2528
+ this.lastPositions = null;
2529
+ }
2530
+ renderPositions(positions) {
2531
+ if (positions === null || positions.length === 0) {
2532
+ this.removePositions();
2533
+ return;
2534
+ }
2535
+ if (this.lastPositions?.length !== positions.length) {
2536
+ this.removePositions();
2537
+ }
2538
+ if (positions[0].symbol !== this.currentSymbol) {
2539
+ this.removePositions();
2540
+ this.currentSymbol = positions[0].symbol;
2541
+ }
2542
+ positions.forEach((position, idx) => this.drawPositionLine(position, idx));
2543
+ this.lastPositions = positions;
2544
+ }
2545
+ getBasePositionLine() {
2546
+ return this.instance.activeChart().createPositionLine().setTooltip(i18n.i18n.t("positions.closePosition")).setQuantityBackgroundColor(this.broker.colorConfig.chartBG).setCloseButtonBackgroundColor(this.broker.colorConfig.chartBG).setBodyTextColor(this.broker.colorConfig.textColor).setQuantityTextColor(this.broker.colorConfig.qtyTextColor).setBodyFont(this.broker.colorConfig.font).setQuantityFont(this.broker.colorConfig.font).setLineLength(100).setLineStyle(1);
2547
+ }
2548
+ static getPositionQuantity(balance) {
2549
+ return utils.commify(new utils.Decimal(balance).todp(4, utils.Decimal.ROUND_DOWN).toString());
2550
+ }
2551
+ static getPositionPnL(unrealPnl, decimal) {
2552
+ const text = i18n.i18n.t("tpsl.pnl");
2553
+ const pnl = new utils.Decimal(unrealPnl).toFixed(decimal, utils.Decimal.ROUND_DOWN);
2554
+ if (new utils.Decimal(unrealPnl).eq(0)) {
2555
+ return `${text} 0`;
2556
+ }
2557
+ if (new utils.Decimal(unrealPnl).greaterThan(0)) {
2558
+ return `${text} +${utils.commify(pnl)}`;
2559
+ }
2560
+ return `${text} ${utils.commify(pnl)}`;
2561
+ }
2562
+ removePositions() {
2563
+ Object.keys(this.positionLines).forEach((lineId) => {
2564
+ this.positionLines[Number(lineId)].remove();
2565
+ delete this.positionLines[Number(lineId)];
2566
+ });
2567
+ }
2568
+ drawPositionLine(position, idx) {
2569
+ const colorConfig = this.broker.colorConfig;
2570
+ const isPositiveUnrealPnl = position.unrealPnl >= 0;
2571
+ const isPositiveBalance = position.balance >= 0;
2572
+ let pnlColor = colorConfig.pnlZoreColor;
2573
+ const pnlDecimal = new utils.Decimal(position.unrealPnl);
2574
+ if (pnlDecimal.greaterThan(0)) {
2575
+ pnlColor = colorConfig.upColor;
2576
+ } else if (pnlDecimal.lessThan(0)) {
2577
+ pnlColor = colorConfig.downColor;
2578
+ }
2579
+ isPositiveUnrealPnl ? colorConfig.pnlUpColor : colorConfig.pnlDownColor;
2580
+ const sideColor = isPositiveBalance ? colorConfig.upColor : colorConfig.downColor;
2581
+ const price = new utils.Decimal(position.open).toNumber();
2582
+ this.positionLines[idx] = this.positionLines[idx] ?? this.getBasePositionLine();
2583
+ this.positionLines[idx].setQuantity(_PositionLineService.getPositionQuantity(position.balance)).setPrice(price).setCloseButtonIconColor(colorConfig.closeIcon).setCloseButtonBorderColor(sideColor).setBodyBackgroundColor(pnlColor).setQuantityTextColor(sideColor).setBodyBorderColor(pnlColor).setLineColor(sideColor).setQuantityBorderColor(sideColor).setText(
2584
+ _PositionLineService.getPositionPnL(
2585
+ position.unrealPnl,
2586
+ position.unrealPnlDecimal
2587
+ )
2588
+ );
2589
+ if (this.broker.mode !== 3 /* MOBILE */) {
2590
+ this.positionLines[idx].onClose(null, () => {
2591
+ this.broker.closePosition(position);
2592
+ });
2593
+ }
2594
+ }
2595
+ };
2596
+ var DEFAULT_THRESHOLD = 10;
2597
+ var TPSLService = class {
2598
+ constructor(instance, broker) {
2599
+ this.interactiveMode = 0 /* NONE */;
2600
+ this.tpslElRemoveTimer = null;
2601
+ this.currentPosition = null;
2602
+ this.tpslOrderLine = null;
2603
+ this.tpslPnLVerticalLineEntityId = null;
2604
+ this.tpslVerticalLineTime = null;
2605
+ this.tpslStartCircleEntityId = null;
2606
+ this.tpslEndCircleEntityId = null;
2607
+ this.threshold = 10;
2608
+ this.lastArgs = null;
2609
+ this.instance = instance;
2610
+ this.broker = broker;
2611
+ this.lastPositions = null;
2612
+ this.tpslElRemoveTimer = null;
2613
+ this.currentPosition = null;
2614
+ this.bindEvent();
2615
+ }
2616
+ bindEvent() {
2617
+ this.chart.crossHairMoved().subscribe(null, (args) => {
2618
+ this.lastArgs = args;
2619
+ if (this.interactiveMode === 2 /* TP_SL_DRAGGING */) {
2620
+ this.clearTpslElRemoveTimer();
2621
+ return;
2622
+ }
2623
+ const position = this.getIntersectantPosition(args);
2624
+ if (this.currentPosition && position && this.currentPosition.symbol === position.symbol) {
2625
+ return;
2626
+ }
2627
+ if (!position) {
2628
+ this.clearTPSLElements();
2629
+ return;
2630
+ }
2631
+ if (position) {
2632
+ this.clearTpslElRemoveTimer();
2633
+ this.currentPosition = position;
2634
+ this.createTPSLTriggerButton(args);
2635
+ }
2636
+ });
2637
+ }
2638
+ clearTpslElRemoveTimer() {
2639
+ if (this.tpslElRemoveTimer) {
2640
+ clearTimeout(this.tpslElRemoveTimer);
2641
+ this.tpslElRemoveTimer = null;
2642
+ }
2643
+ }
2644
+ showTPSLDialog(params) {
2645
+ const pnl = new utils.Decimal(params.price).minus(this.currentPosition.open).mul(this.currentPosition?.balance ?? 0);
2646
+ ui.modal.show("TPSLSimpleDialogId", {
2647
+ title: pnl.gt(0) ? i18n.i18n.t("tpsl.TPOrderConfirm") : i18n.i18n.t("tpsl.SLOrderConfirm"),
2648
+ triggerPrice: params.price,
2649
+ type: pnl.gt(0) ? "tp" : "sl",
2650
+ symbol: this.currentPosition.symbol,
2651
+ onComplete: () => {
2652
+ this.clearTPSLElements();
2653
+ this.chart.setScrollEnabled(true);
2654
+ this.chart.setZoomEnabled(true);
2655
+ this.interactiveMode = 0 /* NONE */;
2656
+ },
2657
+ showAdvancedTPSLDialog: (options) => {
2658
+ this.showAdvancedTPSLDialog({
2659
+ type: pnl.gt(0) ? "tp" : "sl",
2660
+ triggerPrice: params.price,
2661
+ qty: options.qty
2662
+ });
2663
+ }
2664
+ }).then(
2665
+ () => {
2666
+ },
2667
+ (err) => {
2668
+ }
2669
+ ).finally(() => {
2670
+ this.clearTPSLElements();
2671
+ this.chart.setScrollEnabled(true);
2672
+ this.chart.setZoomEnabled(true);
2673
+ this.interactiveMode = 0 /* NONE */;
2674
+ });
2675
+ }
2676
+ showAdvancedTPSLDialog({
2677
+ type,
2678
+ triggerPrice,
2679
+ qty
2680
+ }) {
2681
+ ui.modal.show("TPSLDialogId", {
2682
+ withTriggerPrice: true,
2683
+ type,
2684
+ triggerPrice,
2685
+ symbol: this.currentPosition?.symbol,
2686
+ qty,
2687
+ onComplete: () => {
2688
+ this.clearTPSLElements();
2689
+ this.chart.setScrollEnabled(true);
2690
+ this.chart.setZoomEnabled(true);
2691
+ this.interactiveMode = 0 /* NONE */;
2692
+ }
2693
+ }).then(
2694
+ () => {
2695
+ },
2696
+ (err) => {
2697
+ }
2698
+ ).finally(() => {
2699
+ this.clearTPSLElements();
2700
+ this.chart.setScrollEnabled(true);
2701
+ this.chart.setZoomEnabled(true);
2702
+ this.interactiveMode = 0 /* NONE */;
2703
+ });
2704
+ }
2705
+ updatePositions(positions) {
2706
+ this.lastPositions = positions;
2707
+ this.threshold = this.generateThreshold();
2708
+ }
2709
+ /**
2710
+ * Generates a threshold value for position intersection detection.
2711
+ * The threshold is calculated as 2% of the visible price range but is capped
2712
+ * to ensure it never exceeds the actual price range (highest - lowest price).
2713
+ *
2714
+ * @returns The calculated threshold value, or DEFAULT_THRESHOLD if calculation fails
2715
+ */
2716
+ generateThreshold() {
2717
+ const priceScale = this.chart.getPanes()[0]?.getRightPriceScales()[0];
2718
+ if (!priceScale) {
2719
+ return DEFAULT_THRESHOLD;
2720
+ }
2721
+ try {
2722
+ const priceRange = priceScale.getVisiblePriceRange();
2723
+ if (!priceRange) {
2724
+ return DEFAULT_THRESHOLD;
2725
+ }
2726
+ const priceWidth = priceRange.to - priceRange.from;
2727
+ const calculatedThreshold = priceWidth * 0.02;
2728
+ const threshold = Math.min(calculatedThreshold, priceWidth);
2729
+ return threshold;
2730
+ } catch (error) {
2731
+ return DEFAULT_THRESHOLD;
2732
+ }
2733
+ }
2734
+ drawTPSL(params) {
2735
+ const { price } = params;
2736
+ const pnl = new utils.Decimal(price).minus(this.currentPosition.open).mul(this.currentPosition?.balance ?? 0);
2737
+ const { tpslOrderLine, verticalLine } = this.ensureTPSLElements({
2738
+ price,
2739
+ pnl
2740
+ });
2741
+ const direction = pnl.gt(0) ? i18n.i18n.t("tpsl.tp") : i18n.i18n.t("tpsl.sl");
2742
+ const color = pnl.gt(0) ? this.broker.colorConfig.upColor : this.broker.colorConfig.downColor;
2743
+ tpslOrderLine?.setText(`${direction} ${pnl.toDecimalPlaces(2).toNumber()}`).setBodyTextColor(color).setBodyBorderColor(color).setLineColor(color);
2744
+ if (this.tpslVerticalLineTime) {
2745
+ verticalLine?.setPoints([
2746
+ { price: this.currentPosition?.open, time: this.tpslVerticalLineTime },
2747
+ { time: this.tpslVerticalLineTime, price }
2748
+ ]);
2749
+ }
2750
+ }
2751
+ ensureTPSLElements(params) {
2752
+ const tpslOrderLine = this.tpslOrderLine;
2753
+ let verticalLine;
2754
+ if (!tpslOrderLine) {
2755
+ this.tpslOrderLine = this.createTPSLOrderLine();
2756
+ }
2757
+ if (this.tpslPnLVerticalLineEntityId) {
2758
+ verticalLine = this.chart.getShapeById(this.tpslPnLVerticalLineEntityId);
2759
+ }
2760
+ if (!verticalLine) {
2761
+ if (!this.currentPosition || !this.tpslVerticalLineTime) {
2762
+ return {};
2763
+ }
2764
+ this.tpslPnLVerticalLineEntityId = this.chart.createMultipointShape(
2765
+ [
2766
+ {
2767
+ price: this.currentPosition.open,
2768
+ time: this.tpslVerticalLineTime
2769
+ },
2770
+ { time: this.tpslVerticalLineTime, price: params.price }
2771
+ ],
2772
+ {
2773
+ shape: "trend_line",
2774
+ // shape: "parallel_channel",
2775
+ lock: true,
2776
+ disableSave: true,
2777
+ disableSelection: true,
2778
+ disableUndo: true,
2779
+ zOrder: "top",
2780
+ overrides: {
2781
+ linecolor: "rgba(255,255,255, 0.2)",
2782
+ linewidth: 1,
2783
+ rightEnd: 1,
2784
+ leftEnd: 1
2785
+ }
2786
+ }
2787
+ );
2788
+ }
2789
+ verticalLine?.setProperties({
2790
+ linecolor: params.pnl.gt(0) ? this.broker.colorConfig.upColor : this.broker.colorConfig.downColor,
2791
+ linewidth: 1
2792
+ });
2793
+ return {
2794
+ tpslOrderLine,
2795
+ verticalLine
2796
+ };
2797
+ }
2798
+ createTPSLTriggerButton(params) {
2799
+ if (!this.tpslOrderLine) {
2800
+ this.tpslOrderLine = this.createTPSLOrderLine();
2801
+ }
2802
+ this.tpslOrderLine.onMove(() => {
2803
+ const price = this.tpslOrderLine?.getPrice();
2804
+ this.showTPSLDialog({ price: price ?? 0 });
2805
+ });
2806
+ this.tpslOrderLine.onMoving(() => {
2807
+ this.interactiveMode = 2 /* TP_SL_DRAGGING */;
2808
+ const price = this.tpslOrderLine?.getPrice();
2809
+ this.verticalLineTime();
2810
+ this.drawTPSL({ price: price ?? 0 });
2811
+ });
2812
+ }
2813
+ createTPSLOrderLine() {
2814
+ return this.chart.createOrderLine().setCancellable(false).setExtendLeft(true).setTooltip(i18n.i18n.t("tpsl.dragToSet")).setPrice(this.currentPosition.open).setLineLength(-200, "pixel").setText(i18n.i18n.t("common.tpsl")).setQuantity("").setBodyTextColor(this.broker.colorConfig.textColor).setBodyBackgroundColor(this.broker.colorConfig.chartBG).setBodyBorderColor(this.broker.colorConfig.pnlZoreColor).setQuantityBackgroundColor(this.broker.colorConfig.chartBG).setQuantityBorderColor(this.broker.colorConfig.pnlZoreColor).setQuantityTextColor(this.broker.colorConfig.qtyTextColor).setBodyFont(this.broker.colorConfig.font).setQuantityFont(this.broker.colorConfig.font).setLineStyle(3);
2815
+ }
2816
+ verticalLineTime() {
2817
+ const range = this.chart.getVisibleRange();
2818
+ this.tpslVerticalLineTime = this.getTimeAtPercentage(
2819
+ range.from,
2820
+ range.to,
2821
+ 90
2822
+ );
2823
+ }
2824
+ clearTPSLElements() {
2825
+ if (this.tpslElRemoveTimer) {
2826
+ return;
2827
+ }
2828
+ this.tpslElRemoveTimer = setTimeout(() => {
2829
+ this.currentPosition = null;
2830
+ if (this.tpslOrderLine) {
2831
+ this.tpslOrderLine.remove();
2832
+ this.tpslOrderLine = null;
2833
+ }
2834
+ if (this.tpslPnLVerticalLineEntityId) {
2835
+ this.chart.removeEntity(this.tpslPnLVerticalLineEntityId);
2836
+ this.tpslPnLVerticalLineEntityId = null;
2837
+ }
2838
+ this.tpslElRemoveTimer = null;
2839
+ }, 100);
2840
+ }
2841
+ getIntersectantPosition(params) {
2842
+ if (!Array.isArray(this.lastPositions) || this.lastPositions.length === 0) {
2843
+ return null;
2844
+ }
2845
+ const { price, time } = params;
2846
+ let intersectantPosition = null;
2847
+ for (const position of this.lastPositions) {
2848
+ if (position) {
2849
+ if (Math.abs(position.open - price) < this.threshold) {
2850
+ intersectantPosition = position;
2851
+ break;
2852
+ }
2853
+ }
2854
+ }
2855
+ return intersectantPosition;
2856
+ }
2857
+ get chart() {
2858
+ return this.instance.activeChart();
2859
+ }
2860
+ getTimeAtPercentage(startTime, endTime, percentage) {
2861
+ if (typeof startTime !== "number" || typeof endTime !== "number" || typeof percentage !== "number") {
2862
+ return null;
2863
+ }
2864
+ if (percentage < 0 || percentage > 100) {
2865
+ return null;
2866
+ }
2867
+ if (startTime > endTime) {
2868
+ return null;
2869
+ }
2870
+ const duration = endTime - startTime;
2871
+ const factor = percentage / 100;
2872
+ const offset = duration * factor;
2873
+ const targetTime = startTime + offset;
2874
+ return Math.round(targetTime);
2875
+ }
2876
+ };
2877
+
2878
+ // src/tradingviewAdapter/renderer/renderer.ts
2879
+ var Renderer = class {
2880
+ constructor(instance, host, broker) {
2881
+ this.instance = instance;
2882
+ this.positionLineService = new PositionLineService(instance, broker);
2883
+ this.orderLineService = new OrderLineService(instance, broker);
2884
+ this.executionService = new ExecutionService(instance, broker);
2885
+ this.tpslService = new TPSLService(instance, broker);
2886
+ }
2887
+ async renderPositions(positions) {
2888
+ await this.chartReady();
2889
+ await this.onDataLoaded();
2890
+ this.positionLineService.renderPositions(positions);
2891
+ this.orderLineService.updatePositions(positions);
2892
+ this.tpslService.updatePositions(positions);
2893
+ }
2894
+ async renderPendingOrders(pendingOrders) {
2895
+ await this.chartReady();
2896
+ this.orderLineService.renderPendingOrders(pendingOrders);
2897
+ }
2898
+ async renderFilledOrders(filledOrders, basePriceDecimal) {
2899
+ await this.chartReady();
2900
+ await this.onDataLoaded();
2901
+ this.executionService.renderExecutions(filledOrders, basePriceDecimal);
2902
+ }
2903
+ remove() {
2904
+ this.orderLineService.removeAll();
2905
+ this.positionLineService.removePositions();
2906
+ this.executionService.destroy();
2907
+ }
2908
+ onDataLoaded() {
2909
+ if (this.instance.activeChart().symbolExt()) {
2910
+ return Promise.resolve();
2911
+ }
2912
+ return new Promise(
2913
+ (resolve) => this.instance.activeChart().onDataLoaded().subscribe(
2914
+ null,
2915
+ () => {
2916
+ resolve();
2917
+ },
2918
+ true
2919
+ )
2920
+ );
2921
+ }
2922
+ chartReady() {
2923
+ return new Promise(
2924
+ (resolve) => this.instance.onChartReady(() => {
2925
+ try {
2926
+ this.instance.activeChart().dataReady(() => resolve());
2927
+ } catch (err) {
2928
+ if (err.toString().includes("tradingViewApi")) ;
2929
+ }
2930
+ })
2931
+ );
2932
+ }
2933
+ };
2934
+
2935
+ // src/tradingviewAdapter/hooks/useCreateRenderer.ts
2936
+ function useCreateRenderer(symbol, displayControlSetting) {
2937
+ const [renderer, setRenderer] = React3.useState();
2938
+ const rendererRef = React3.useRef();
2939
+ const { state } = hooks.useAccount();
2940
+ const [unPnlPriceBasis] = hooks.useLocalStorage("unPnlPriceBasis", "markPrice");
2941
+ const [{ rows: positions }, positionsInfo] = hooks.usePositionStream(symbol, {
2942
+ calcMode: unPnlPriceBasis
2943
+ });
2944
+ const [pendingOrders] = hooks.useOrderStream({
2945
+ status: types.OrderStatus.INCOMPLETE,
2946
+ symbol
2947
+ });
2948
+ const config = hooks.useSymbolsInfo();
2949
+ const symbolInfo = config?.[symbol];
2950
+ const quote_dp = symbolInfo("quote_dp");
2951
+ const [fillOrders] = hooks.useOrderStream({
2952
+ symbol,
2953
+ status: types.OrderStatus.FILLED,
2954
+ size: 500
2955
+ });
2956
+ const createRenderer = React3.useRef(
2957
+ (instance, host, broker, container) => {
2958
+ if (rendererRef.current) {
2959
+ rendererRef.current.remove();
2960
+ }
2961
+ rendererRef.current = new Renderer(instance, host, broker);
2962
+ setRenderer(rendererRef.current);
2963
+ }
2964
+ );
2965
+ const removeRenderer = React3.useRef(() => {
2966
+ rendererRef.current?.remove();
2967
+ rendererRef.current = void 0;
2968
+ });
2969
+ React3.useEffect(() => {
2970
+ if (state.status < types.AccountStatusEnum.EnableTrading && state.status !== types.AccountStatusEnum.EnableTradingWithoutConnected) {
2971
+ renderer?.renderPositions([]);
2972
+ return;
2973
+ }
2974
+ if (!displayControlSetting || !displayControlSetting.position) {
2975
+ renderer?.renderPositions([]);
2976
+ return;
2977
+ }
2978
+ const positionList = (positions ?? []).filter((_) => _.symbol === symbol).map((item) => {
2979
+ return {
2980
+ symbol: item.symbol,
2981
+ open: item.average_open_price,
2982
+ balance: item.position_qty,
2983
+ closablePosition: 9999,
2984
+ // @ts-ignore
2985
+ unrealPnl: item.unrealized_pnl ?? 0,
2986
+ interest: 0,
2987
+ unrealPnlDecimal: 2,
2988
+ basePriceDecimal: 4
2989
+ };
2990
+ });
2991
+ renderer?.renderPositions(positionList);
2992
+ }, [renderer, positions, symbol, displayControlSetting, state]);
2993
+ React3.useEffect(() => {
2994
+ if (!displayControlSetting || !displayControlSetting.buySell) {
2995
+ renderer?.renderFilledOrders([], 6);
2996
+ return;
2997
+ }
2998
+ const currentSymbolFillOrders = fillOrders?.filter(
2999
+ (item) => item.symbol === symbol
3000
+ );
3001
+ renderer?.renderFilledOrders(currentSymbolFillOrders ?? [], quote_dp ?? 6);
3002
+ }, [renderer, fillOrders, symbol, quote_dp, displayControlSetting]);
3003
+ React3.useEffect(() => {
3004
+ let tpslOrder = [];
3005
+ let positionTpsl = [];
3006
+ let limitOrder = [];
3007
+ let stopOrder = [];
3008
+ let bracketOrder = [];
3009
+ let trailingStopOrder = [];
3010
+ if (state.status < types.AccountStatusEnum.EnableTrading && state.status !== types.AccountStatusEnum.EnableTradingWithoutConnected) {
3011
+ renderer?.renderPendingOrders([]);
3012
+ return;
3013
+ }
3014
+ const symbolPosition = (positions ?? []).find(
3015
+ (item) => item.symbol === symbol
3016
+ );
3017
+ pendingOrders?.forEach((order) => {
3018
+ if (symbol !== order.symbol) {
3019
+ return;
3020
+ }
3021
+ if (!order.algo_order_id) {
3022
+ limitOrder.push(order);
3023
+ } else if (order.algo_order_id) {
3024
+ if (order.algo_type === "POSITIONAL_TP_SL" /* POSITIONAL_TP_SL */) {
3025
+ for (const child_order of order.child_orders) {
3026
+ child_order.root_algo_order_algo_type = order.algo_type;
3027
+ if (child_order.trigger_price && child_order.status !== types.OrderStatus.FILLED) {
3028
+ positionTpsl.push(child_order);
3029
+ }
3030
+ }
3031
+ } else if (order.algo_type === "TP_SL" /* TP_SL */) {
3032
+ if (symbolPosition) {
3033
+ for (const child_order of order.child_orders) {
3034
+ child_order.root_algo_order_algo_type = order.algo_type;
3035
+ child_order.position_qty = symbolPosition.position_qty;
3036
+ if (child_order.trigger_price && child_order.status !== types.OrderStatus.FILLED) {
3037
+ tpslOrder.push(child_order);
3038
+ }
3039
+ }
3040
+ }
3041
+ } else if (order.algo_type === "STOP_LOSS" /* STOP_LOSS */ || order.algo_type === "TAKE_PROFIT" /* TAKE_PROFIT */) {
3042
+ stopOrder.push(order);
3043
+ } else if (order.algo_type === "BRACKET" /* BRACKET */) {
3044
+ bracketOrder.push(order);
3045
+ } else if (order.algo_type === "TRAILING_STOP" /* TRAILING_STOP */) {
3046
+ if (order.is_activated && order.extreme_price) {
3047
+ trailingStopOrder.push(order);
3048
+ }
3049
+ }
3050
+ }
3051
+ });
3052
+ if (displayControlSetting) {
3053
+ if (!displayControlSetting.positionTpsl) {
3054
+ positionTpsl = [];
3055
+ }
3056
+ if (!displayControlSetting.tpsl) {
3057
+ tpslOrder = [];
3058
+ }
3059
+ if (!displayControlSetting.limitOrders) {
3060
+ limitOrder = [];
3061
+ bracketOrder = [];
3062
+ }
3063
+ if (!displayControlSetting.stopOrders) {
3064
+ stopOrder = [];
3065
+ }
3066
+ if (!displayControlSetting.trailingStop) {
3067
+ trailingStopOrder = [];
3068
+ }
3069
+ }
3070
+ renderer?.renderPendingOrders(
3071
+ tpslOrder.concat(positionTpsl).concat(limitOrder).concat(stopOrder).concat(bracketOrder).concat(trailingStopOrder)
3072
+ );
3073
+ }, [
3074
+ renderer,
3075
+ pendingOrders,
3076
+ symbol,
3077
+ displayControlSetting,
3078
+ positions,
3079
+ state.status
3080
+ ]);
3081
+ return [createRenderer.current, removeRenderer.current];
3082
+ }
3083
+
3084
+ // src/tradingviewAdapter/renderer/brokerHostHandler.ts
3085
+ function preventDefaultRenderHack(host) {
3086
+ host.setBrokerConnectionAdapter = function(adapter) {
3087
+ const delegate = {
3088
+ subscribe: () => {
3089
+ },
3090
+ unsubscribe: () => {
3091
+ },
3092
+ unsubscribeAll: () => {
3093
+ }
3094
+ };
3095
+ Object.defineProperty(adapter, "_ordersCache", {
3096
+ get: function() {
3097
+ return {
3098
+ start: () => {
3099
+ },
3100
+ stop: () => {
3101
+ },
3102
+ update: () => {
3103
+ },
3104
+ partialUpdate: () => {
3105
+ },
3106
+ fullUpdate: () => {
3107
+ },
3108
+ getObjects: async () => [],
3109
+ updateDelegate: delegate,
3110
+ partialUpdateDelegate: delegate
3111
+ };
3112
+ },
3113
+ set: () => {
3114
+ }
3115
+ });
3116
+ adapter._waitForOrderModification = async () => true;
3117
+ this._adapter = adapter;
3118
+ };
3119
+ }
3120
+ function forceSilentOrdersPlacement(instance, host) {
3121
+ instance.onChartReady(() => {
3122
+ host.silentOrdersPlacement().subscribe((val) => {
3123
+ if (!val) {
3124
+ host.silentOrdersPlacement().setValue(true);
3125
+ if (instance) {
3126
+ instance._iFrame.contentDocument.querySelector(
3127
+ ".wrapper-3X2QgaDd"
3128
+ ).className = "wrapper-3X2QgaDd highButtons-3X2QgaDd";
3129
+ }
3130
+ host.sellBuyButtonsVisibility()?.setValue(false);
3131
+ }
3132
+ });
3133
+ });
3134
+ }
3135
+ function brokerHostHandler(instance, host) {
3136
+ preventDefaultRenderHack(host);
3137
+ forceSilentOrdersPlacement(instance, host);
3138
+ }
3139
+
3140
+ // src/tradingviewAdapter/widget/util.ts
3141
+ var waitForElm = (iframeDocument, selector) => {
3142
+ return new Promise((resolve) => {
3143
+ const initialIframe = iframeDocument.querySelector(selector);
3144
+ if (initialIframe) {
3145
+ resolve(initialIframe);
3146
+ }
3147
+ const observer = new MutationObserver(() => {
3148
+ const iframe = iframeDocument.querySelector(selector);
3149
+ if (iframe) {
3150
+ resolve(iframe);
3151
+ observer.disconnect();
3152
+ }
3153
+ });
3154
+ observer.observe(iframeDocument, {
3155
+ childList: true,
3156
+ subtree: true
3157
+ });
3158
+ });
3159
+ };
3160
+
3161
+ // src/tradingviewAdapter/widget/chart_hack.ts
3162
+ var ChartHack = class {
3163
+ constructor({ iframeDocument }) {
3164
+ this.iframeDocument = iframeDocument;
3165
+ }
3166
+ defaultHack() {
3167
+ this.showFavoriteStarByDefault();
3168
+ }
3169
+ showFavoriteStarByDefault() {
3170
+ waitForElm(this.iframeDocument, ".dropdown-2R6OKuTS").then(() => {
3171
+ const items = this.iframeDocument.querySelectorAll(
3172
+ ".toolbox-2IihgTnv.showOnHover-2IihgTnv"
3173
+ );
3174
+ items.forEach((item) => {
3175
+ item.style.opacity = "1";
3176
+ });
3177
+ });
3178
+ }
3179
+ };
3180
+
3181
+ // src/tradingviewAdapter/widget/option.ts
3182
+ var getDisabledFeatures = (mode) => {
3183
+ let disabledFeatures = [
3184
+ "header_symbol_search",
3185
+ "volume_force_overlay",
3186
+ "trading_account_manager",
3187
+ "drawing_templates",
3188
+ "open_account_manager",
3189
+ "right_toolbar",
3190
+ "support_multicharts",
3191
+ "header_layouttoggle",
3192
+ "order_panel",
3193
+ "order_info",
3194
+ "trading_notifications",
3195
+ "display_market_status",
3196
+ "broker_button",
3197
+ "add_to_watchlist",
3198
+ "chart_crosshair_menu",
3199
+ "header_fullscreen_button",
3200
+ "header_widget"
3201
+ ];
3202
+ if (mode === 3 /* MOBILE */) {
3203
+ disabledFeatures = [
3204
+ ...disabledFeatures,
3205
+ "left_toolbar",
3206
+ "timeframes_toolbar",
3207
+ "go_to_date",
3208
+ "timezone_menu",
3209
+ // add volume back
3210
+ "create_volume_indicator_by_default",
3211
+ "buy_sell_buttons"
3212
+ ];
3213
+ }
3214
+ if (mode === 0 /* BASIC */) {
3215
+ disabledFeatures = [
3216
+ ...disabledFeatures,
3217
+ "header_widget",
3218
+ "left_toolbar",
3219
+ "timeframes_toolbar",
3220
+ "buy_sell_buttons"
3221
+ ];
3222
+ } else if (mode === 1 /* ADVANCED */) {
3223
+ disabledFeatures = [
3224
+ ...disabledFeatures,
3225
+ "left_toolbar",
3226
+ "timeframes_toolbar",
3227
+ "buy_sell_buttons"
3228
+ ];
3229
+ }
3230
+ return disabledFeatures;
3231
+ };
3232
+ function getOptions(options, mode, externalEnabledFeatures, externalDisabledFeatures) {
3233
+ const defaultEnabledFeatures = [
3234
+ "hide_left_toolbar_by_default",
3235
+ "order_panel_close_button",
3236
+ "iframe_loading_compatibility_mode"
3237
+ ];
3238
+ const mergedEnabledFeatures = Array.from(
3239
+ /* @__PURE__ */ new Set([...defaultEnabledFeatures, ...externalEnabledFeatures || []])
3240
+ );
3241
+ const defaultDisabledFeatures = getDisabledFeatures(mode);
3242
+ const mergedDisabledFeatures = Array.from(
3243
+ /* @__PURE__ */ new Set([...defaultDisabledFeatures, ...externalDisabledFeatures || []])
3244
+ );
3245
+ return {
3246
+ ...options,
3247
+ disabled_features: mergedDisabledFeatures,
3248
+ enabled_features: mergedEnabledFeatures,
3249
+ auto_save_delay: 0.1,
3250
+ broker_config: {
3251
+ configFlags: {
3252
+ supportStopLimitOrders: true,
3253
+ supportReversePosition: false
3254
+ }
3255
+ }
3256
+ };
3257
+ }
3258
+
3259
+ // src/tradingviewAdapter/widget/persistUtils.ts
3260
+ var getChartSettingAdapterKey = (chartKey) => `${chartKey}_adapter`;
3261
+ var defaultSettings = {
3262
+ "trading.chart.proterty": JSON.stringify({
3263
+ showSellBuyButtons: 0,
3264
+ noConfirmEnabled: 1,
3265
+ qweqrq: 0,
3266
+ showPricesWithZeroVolume: 1,
3267
+ showSpread: 1,
3268
+ orderExecutedSoundParams: '{"enabled":0,"name":"alert/alarm_clock"}'
3269
+ }),
3270
+ "hint.startFocusedZoom": "true"
3271
+ };
3272
+ var chartCacheMap = /* @__PURE__ */ new Map();
3273
+ var parseAndCacheChartData = (chartKey, savedDataString, adapterSettingString) => {
3274
+ const settingAdapterKey = getChartSettingAdapterKey(chartKey);
3275
+ try {
3276
+ const transformedSavedDataString = savedDataString;
3277
+ const savedData = transformedSavedDataString ? JSON.parse(transformedSavedDataString) : void 0;
3278
+ const adapterSetting = adapterSettingString ? JSON.parse(adapterSettingString) : defaultSettings;
3279
+ if (transformedSavedDataString) {
3280
+ chartCacheMap.set(chartKey, transformedSavedDataString);
3281
+ }
3282
+ if (adapterSettingString) {
3283
+ chartCacheMap.set(settingAdapterKey, adapterSettingString);
3284
+ }
3285
+ return { savedData, adapterSetting };
3286
+ } catch (e) {
3287
+ }
3288
+ return { savedData: void 0, adapterSetting: defaultSettings };
3289
+ };
3290
+ var getChartData = async (chartKey, isLoggedIn) => {
3291
+ const settingAdapterKey = getChartSettingAdapterKey(chartKey);
3292
+ const localStorageSavedData = localStorage.getItem(chartKey) || "";
3293
+ const localStorageAdapterSetting = localStorage.getItem(settingAdapterKey) || "";
3294
+ try {
3295
+ if (chartCacheMap.has(chartKey) && chartCacheMap.has(settingAdapterKey)) {
3296
+ return {
3297
+ savedData: JSON.parse(chartCacheMap.get(chartKey)),
3298
+ adapterSetting: JSON.parse(chartCacheMap.get(settingAdapterKey))
3299
+ };
3300
+ }
3301
+ } catch (e) {
3302
+ }
3303
+ return parseAndCacheChartData(
3304
+ chartKey,
3305
+ localStorageSavedData,
3306
+ localStorageAdapterSetting
3307
+ );
3308
+ };
3309
+ var saveChartData = async (chartKey, setting, isLoggedIn) => {
3310
+ if (setting) {
3311
+ localStorage.setItem(chartKey, setting);
3312
+ chartCacheMap.set(chartKey, setting);
3313
+ }
3314
+ };
3315
+ var saveChartAdapterSetting = async (chartKey, setting, isLoggedIn) => {
3316
+ const settingAdapterKey = getChartSettingAdapterKey(chartKey);
3317
+ if (setting) {
3318
+ localStorage.setItem(settingAdapterKey, setting);
3319
+ chartCacheMap.set(settingAdapterKey, setting);
3320
+ }
3321
+ };
3322
+
3323
+ // src/tradingviewAdapter/widget/index.ts
3324
+ var debounce = (func, delay) => {
3325
+ let timer = null;
3326
+ const debounced = (...args) => {
3327
+ timer && window.clearTimeout(timer);
3328
+ timer = setTimeout(() => {
3329
+ func(...args);
3330
+ }, delay);
3331
+ };
3332
+ debounced.cancel = () => {
3333
+ timer && window.clearTimeout(timer);
3334
+ timer = null;
3335
+ };
3336
+ return debounced;
3337
+ };
3338
+ var DEFAULT_SETTINGS_KEY = "chartProp_default";
3339
+ var DEBOUNCE_SAVE_TIME = 300;
3340
+ var Widget = class {
3341
+ constructor(props) {
3342
+ this._instance = null;
3343
+ this._onClick = null;
3344
+ this._datafeed = null;
3345
+ this._chartKey = DEFAULT_SETTINGS_KEY;
3346
+ this._adapterSetting = defaultSettings;
3347
+ this._savedData = null;
3348
+ this._isLoggedIn = false;
3349
+ this.debounceSaveChart = debounce(() => {
3350
+ try {
3351
+ this._instance?.save((chartProps) => {
3352
+ if (!Object.is(this._savedData, chartProps)) {
3353
+ this._savedData = chartProps;
3354
+ saveChartData(
3355
+ this._chartKey,
3356
+ JSON.stringify(chartProps),
3357
+ this._isLoggedIn
3358
+ );
3359
+ }
3360
+ });
3361
+ } catch (e) {
3362
+ }
3363
+ }, DEBOUNCE_SAVE_TIME * 2);
3364
+ this.debounceSaveChartAdapterSetting = debounce(() => {
3365
+ saveChartAdapterSetting(
3366
+ this._chartKey,
3367
+ JSON.stringify(this._adapterSetting),
3368
+ this._isLoggedIn
3369
+ );
3370
+ }, DEBOUNCE_SAVE_TIME);
3371
+ this._create(props);
3372
+ }
3373
+ remove() {
3374
+ this.unsubscribeClick();
3375
+ this._datafeed?.remove();
3376
+ this._broker?.remove();
3377
+ this._instance?.remove();
3378
+ this.debounceSaveChart.cancel();
3379
+ this.debounceSaveChartAdapterSetting.cancel();
3380
+ }
3381
+ updateOverrides(overrides) {
3382
+ if (!this.instance) {
3383
+ return;
3384
+ }
3385
+ this.instance.applyOverrides(overrides);
3386
+ }
3387
+ setSymbol(symbol, interval, callback) {
3388
+ try {
3389
+ this._instance?.onChartReady(() => {
3390
+ let currentInterval = interval ?? this._instance?.symbolInterval()?.interval;
3391
+ if (!currentInterval) {
3392
+ currentInterval = 1;
3393
+ }
3394
+ this._instance?.setSymbol(symbol, currentInterval, callback);
3395
+ });
3396
+ } catch (e) {
3397
+ }
3398
+ }
3399
+ executeActionById(actionId) {
3400
+ try {
3401
+ this._instance?.onChartReady(() => {
3402
+ this._instance?.activeChart().executeActionById(actionId);
3403
+ });
3404
+ } catch (e) {
3405
+ }
3406
+ }
3407
+ changeLineType(lineType) {
3408
+ try {
3409
+ this._instance?.onChartReady(() => {
3410
+ this._instance?.activeChart().setChartType(lineType);
3411
+ });
3412
+ } catch (e) {
3413
+ }
3414
+ }
3415
+ subscribeClick(onClick) {
3416
+ this._onClick = onClick;
3417
+ this._instance?.onChartReady(() => {
3418
+ this._instance?._iFrame.contentDocument?.addEventListener(
3419
+ "click",
3420
+ this._onClick
3421
+ );
3422
+ });
3423
+ }
3424
+ unsubscribeClick() {
3425
+ this._instance?._iFrame.contentDocument?.removeEventListener(
3426
+ "click",
3427
+ this._onClick
3428
+ );
3429
+ }
3430
+ get instance() {
3431
+ return this._instance;
3432
+ }
3433
+ chartHack() {
3434
+ this._instance?.onChartReady(() => {
3435
+ const iframeDocument = this._instance._iFrame.contentWindow.document;
3436
+ new ChartHack({ iframeDocument }).defaultHack();
3437
+ });
3438
+ }
3439
+ subscribeAutoSave() {
3440
+ this._instance?.onChartReady(() => {
3441
+ this._instance?.subscribe("onAutoSaveNeeded", () => {
3442
+ this.debounceSaveChart();
3443
+ });
3444
+ this._instance?.activeChart().onVisibleRangeChanged().subscribe(null, () => {
3445
+ this.debounceSaveChart();
3446
+ });
3447
+ });
3448
+ }
3449
+ async _create({
3450
+ options,
3451
+ chartKey,
3452
+ mode,
3453
+ onClick,
3454
+ enabled_features,
3455
+ disabled_features
3456
+ }) {
3457
+ const getBroker = options.getBroker;
3458
+ const widgetOptions = {
3459
+ fullscreen: options.fullscreen ?? true,
3460
+ autosize: options.autosize ?? false,
3461
+ timezone: options.timezone,
3462
+ symbol: options.symbol,
3463
+ library_path: options.libraryPath,
3464
+ interval: options.interval ?? "1",
3465
+ custom_css_url: options.customCssUrl,
3466
+ custom_font_family: options.customFontFamily,
3467
+ datafeed: options.datafeed,
3468
+ studies_overrides: options.studiesOverrides,
3469
+ locale: options.locale,
3470
+ theme: options.theme,
3471
+ loading_screen: options.loadingScreen,
3472
+ overrides: options.overrides,
3473
+ container: options.container,
3474
+ favorites: {
3475
+ intervals: [
3476
+ "1",
3477
+ "3",
3478
+ "5",
3479
+ "15",
3480
+ "30",
3481
+ "60",
3482
+ "240",
3483
+ "1D",
3484
+ "1W",
3485
+ "1M"
3486
+ ],
3487
+ chartTypes: ["Area", "Line"]
3488
+ },
3489
+ broker_factory: getBroker ? (host) => {
3490
+ if (this._broker) {
3491
+ this._broker.remove();
3492
+ }
3493
+ this._broker = getBroker(
3494
+ this._instance,
3495
+ host
3496
+ );
3497
+ return this._broker;
3498
+ } : void 0
3499
+ };
3500
+ this._datafeed = options.datafeed;
3501
+ if (chartKey) {
3502
+ this._chartKey = chartKey;
3503
+ }
3504
+ const { savedData, adapterSetting } = await getChartData(
3505
+ this._chartKey,
3506
+ this._isLoggedIn
3507
+ );
3508
+ this._adapterSetting = adapterSetting;
3509
+ this._savedData = savedData;
3510
+ this._instance = new TradingView.widget({
3511
+ ...getOptions(widgetOptions, mode, enabled_features, disabled_features),
3512
+ interval: adapterSetting["chart.lastUsedTimeBasedResolution"] ?? widgetOptions.interval,
3513
+ saved_data: savedData,
3514
+ settings_adapter: {
3515
+ initialSettings: adapterSetting,
3516
+ setValue: (key, value) => {
3517
+ this._adapterSetting = { ...this._adapterSetting, [key]: value };
3518
+ this.debounceSaveChartAdapterSetting();
3519
+ },
3520
+ removeValue: () => {
3521
+ }
3522
+ }
3523
+ });
3524
+ this._instance.onChartReady(() => {
3525
+ if (options.symbol && this._instance?.activeChart().symbol() !== withoutExchangePrefix(options.symbol)) {
3526
+ this.setSymbol(options.symbol);
3527
+ }
3528
+ });
3529
+ this.subscribeAutoSave();
3530
+ this.subscribeClick(onClick);
3531
+ this.chartHack();
3532
+ }
3533
+ };
3534
+
3535
+ // src/components/tradingview.script.ts
3536
+ var CHART_KEY = "SDK_Tradingview";
3537
+ var MOBILE_CHART_KEY = "SDK_Moblie_Tradingview";
3538
+ var getChartKey = (isMobile) => {
3539
+ return isMobile ? MOBILE_CHART_KEY : CHART_KEY;
3540
+ };
3541
+ var defaultLocale = (localeCode) => {
3542
+ return localeCode === "id" ? "id_ID" : localeCode === "tc" ? "zh_TW" : localeCode;
3543
+ };
3544
+ function useTradingviewScript(props) {
3545
+ const {
3546
+ scriptSRC: tradingViewScriptSrc,
3547
+ libraryPath,
3548
+ customCssUrl: tradingViewCustomCssUrl,
3549
+ overrides: customerOverrides,
3550
+ studiesOverrides: customerStudiesOverrides,
3551
+ symbol,
3552
+ theme,
3553
+ loadingScreen: customerLoadingScreen,
3554
+ mode,
3555
+ colorConfig: customerColorConfig,
3556
+ locale = defaultLocale,
3557
+ classNames,
3558
+ enabled_features,
3559
+ disabled_features
3560
+ } = props;
3561
+ const localeCode = i18n.useLocaleCode();
3562
+ const chart = React3.useRef(null);
3563
+ const apiBaseUrl = hooks.useConfig("apiBaseUrl");
3564
+ const { state: accountState } = hooks.useAccount();
3565
+ const [side, setSide] = React3.useState(types.OrderSide.SELL);
3566
+ const symbolsInfo = hooks.useSymbolsInfo();
3567
+ const [fullscreen, setFullscreen] = hooks.useLocalStorage(
3568
+ types.TradingviewFullscreenKey,
3569
+ false
3570
+ );
3571
+ const { onSubmit, submitting } = hooks.useOrderEntry_deprecated(
3572
+ {
3573
+ symbol: symbol ?? "",
3574
+ side,
3575
+ order_type: types.OrderType.MARKET
3576
+ },
3577
+ {
3578
+ watchOrderbook: true
3579
+ }
3580
+ );
3581
+ const [displayControlState, setDisplayControlState] = React3.useState(() => {
3582
+ const displaySettingInfo = localStorage.getItem(
3583
+ TradingViewSDKLocalstorageKey.displayControlSetting
3584
+ );
3585
+ if (displaySettingInfo) {
3586
+ return JSON.parse(displaySettingInfo);
3587
+ }
3588
+ return {
3589
+ position: true,
3590
+ buySell: true,
3591
+ limitOrders: true,
3592
+ stopOrders: true,
3593
+ tpsl: true,
3594
+ positionTpsl: true,
3595
+ trailingStop: true
3596
+ };
3597
+ });
3598
+ const [interval, setInterval] = React3.useState(() => {
3599
+ const lastUsedInterval = localStorage.getItem(
3600
+ TradingViewSDKLocalstorageKey.interval
3601
+ );
3602
+ if (!lastUsedInterval) {
3603
+ return "15";
3604
+ }
3605
+ return lastUsedInterval;
3606
+ });
3607
+ const [lineType, setLineType] = React3.useState(() => {
3608
+ const lastUsedLineType = localStorage.getItem(
3609
+ TradingViewSDKLocalstorageKey.lineType
3610
+ );
3611
+ if (!lastUsedLineType) {
3612
+ return "1";
3613
+ }
3614
+ return lastUsedLineType;
3615
+ });
3616
+ const isMobile = hooks.useMediaQuery(types.MEDIA_TABLET);
3617
+ const colorConfig = React3.useMemo(
3618
+ () => Object.assign({}, defaultColorConfig, customerColorConfig ?? {}),
3619
+ [customerColorConfig]
3620
+ );
3621
+ const loadingScreen = React3.useMemo(() => {
3622
+ if (typeof customerLoadingScreen === "object") {
3623
+ return customerLoadingScreen;
3624
+ }
3625
+ return {
3626
+ backgroundColor: chartBG
3627
+ };
3628
+ }, [customerLoadingScreen]);
3629
+ const ws = hooks.useWS();
3630
+ const [chartingLibrarySciprtReady, setChartingLibrarySciprtReady] = React3.useState(false);
3631
+ const closePositionConfirmCallback = (data) => {
3632
+ const symbolInfo = symbolsInfo[symbol];
3633
+ if (!symbolInfo) {
3634
+ return;
3635
+ }
3636
+ const side2 = new utils.Decimal(data.balance).greaterThan(0) ? types.OrderSide.SELL : types.OrderSide.BUY;
3637
+ const order = {
3638
+ // order_price: undefined,
3639
+ order_quantity: new utils.Decimal(data.balance).abs().toNumber(),
3640
+ symbol,
3641
+ order_type: types.OrderType.MARKET,
3642
+ side: side2,
3643
+ reduce_only: true
3644
+ };
3645
+ setSide(side2);
3646
+ ui.modal.show("MarketCloseConfirmID", {
3647
+ base: symbolInfo("base"),
3648
+ quantity: data.balance,
3649
+ onConfirm: async () => {
3650
+ return onSubmit(order).catch((error) => {
3651
+ if (typeof error === "string") {
3652
+ ui.toast.error(error);
3653
+ } else {
3654
+ ui.toast.error(error.message);
3655
+ }
3656
+ });
3657
+ },
3658
+ submitting
3659
+ });
3660
+ };
3661
+ const chartRef = React3.useRef(null);
3662
+ const isLoggedIn = React3.useMemo(() => {
3663
+ if (accountState.status < types.AccountStatusEnum.EnableTrading && accountState.status !== types.AccountStatusEnum.EnableTradingWithoutConnected) {
3664
+ return false;
3665
+ }
3666
+ return true;
3667
+ }, [accountState]);
3668
+ const broker = useBroker_default({
3669
+ closeConfirm: closePositionConfirmCallback,
3670
+ colorConfig,
3671
+ onToast: ui.toast,
3672
+ symbol: symbol ?? "",
3673
+ mode
3674
+ });
3675
+ const [createRenderer, removeRenderer] = useCreateRenderer(
3676
+ symbol,
3677
+ displayControlState
3678
+ );
3679
+ const onFullScreenChange = () => {
3680
+ if (fullscreen) {
3681
+ setFullscreen(false);
3682
+ } else {
3683
+ setFullscreen(true);
3684
+ }
3685
+ props.onFullScreenChange?.(!fullscreen);
3686
+ };
3687
+ const changeInterval = (newInterval) => {
3688
+ if (!chart.current) {
3689
+ return;
3690
+ }
3691
+ localStorage.setItem(TradingViewSDKLocalstorageKey.interval, newInterval);
3692
+ setInterval(newInterval);
3693
+ chart.current?.setSymbol(symbol ?? "", newInterval);
3694
+ };
3695
+ const changeLineType = (newLineType) => {
3696
+ if (!chart.current) {
3697
+ return;
3698
+ }
3699
+ localStorage.setItem(TradingViewSDKLocalstorageKey.lineType, newLineType);
3700
+ setLineType(newLineType);
3701
+ chart.current?.changeLineType(Number(newLineType));
3702
+ };
3703
+ const changeDisplaySetting = (newSetting) => {
3704
+ localStorage.setItem(
3705
+ TradingViewSDKLocalstorageKey.displayControlSetting,
3706
+ JSON.stringify(newSetting)
3707
+ );
3708
+ setDisplayControlState(newSetting);
3709
+ };
3710
+ const openChartSetting = () => {
3711
+ if (!chart.current) {
3712
+ return;
3713
+ }
3714
+ chart.current.executeActionById("chartProperties");
3715
+ };
3716
+ const openChartIndicators = () => {
3717
+ if (!chart.current) {
3718
+ return;
3719
+ }
3720
+ chart.current.executeActionById("insertIndicator");
3721
+ };
3722
+ React3.useEffect(() => {
3723
+ if (!tradingViewScriptSrc) {
3724
+ return;
3725
+ }
3726
+ if (!chartRef.current) {
3727
+ return;
3728
+ }
3729
+ if (!chartingLibrarySciprtReady) {
3730
+ const script = document.createElement("script");
3731
+ script.setAttribute("data-nscript", "afterInteractive");
3732
+ script.src = tradingViewScriptSrc;
3733
+ script.async = true;
3734
+ script.type = "text/javascript";
3735
+ script.onload = () => {
3736
+ setChartingLibrarySciprtReady(true);
3737
+ };
3738
+ script.onerror = () => {
3739
+ };
3740
+ chartRef.current.appendChild(script);
3741
+ }
3742
+ }, [chartRef, chartingLibrarySciprtReady, tradingViewScriptSrc]);
3743
+ React3.useEffect(() => {
3744
+ if (!symbol) {
3745
+ return;
3746
+ }
3747
+ if (!chartingLibrarySciprtReady || !tradingViewScriptSrc) {
3748
+ return;
3749
+ }
3750
+ const defaultOverrides = getOveriides(colorConfig, isMobile);
3751
+ const overrides = customerOverrides ? Object.assign({}, defaultOverrides.overrides, customerOverrides) : defaultOverrides.overrides;
3752
+ const studiesOverrides = customerStudiesOverrides ? Object.assign(
3753
+ {},
3754
+ defaultOverrides.studiesOverrides,
3755
+ customerStudiesOverrides
3756
+ ) : defaultOverrides.studiesOverrides;
3757
+ if (chartRef.current) {
3758
+ const options = {
3759
+ // fullscreen: fullscreen ?? false,
3760
+ fullscreen: false,
3761
+ autosize: true,
3762
+ symbol: withExchangePrefix(symbol),
3763
+ locale: typeof locale === "function" ? locale(localeCode) : locale,
3764
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
3765
+ container: chartRef.current,
3766
+ libraryPath,
3767
+ customCssUrl: tradingViewCustomCssUrl,
3768
+ interval: interval ?? "1",
3769
+ theme: theme ?? "dark",
3770
+ loadingScreen: loadingScreen ?? {},
3771
+ overrides,
3772
+ studiesOverrides,
3773
+ datafeed: new Datafeed(apiBaseUrl, ws),
3774
+ contextMenu: {
3775
+ items_processor: async (defaultItems) => {
3776
+ return defaultItems;
3777
+ }
3778
+ },
3779
+ // todo broker effect sell/buy
3780
+ getBroker: (instance, host) => {
3781
+ brokerHostHandler(instance, host);
3782
+ return getBrokerAdapter_default(host, broker);
3783
+ }
3784
+ // getBroker: undefined,
3785
+ };
3786
+ const chartProps = {
3787
+ options,
3788
+ chartKey: getChartKey(isMobile),
3789
+ mode,
3790
+ onClick: () => {
3791
+ },
3792
+ enabled_features,
3793
+ disabled_features
3794
+ };
3795
+ chart.current = new Widget(chartProps);
3796
+ }
3797
+ return () => {
3798
+ chart.current?.remove();
3799
+ };
3800
+ }, [
3801
+ chartingLibrarySciprtReady,
3802
+ isMobile,
3803
+ mode,
3804
+ chart,
3805
+ chartRef,
3806
+ chartingLibrarySciprtReady,
3807
+ tradingViewScriptSrc,
3808
+ colorConfig,
3809
+ locale,
3810
+ localeCode
3811
+ ]);
3812
+ React3.useEffect(() => {
3813
+ ws.on(
3814
+ "status:change",
3815
+ (message) => {
3816
+ if (!message.isPrivate && message.isReconnect) {
3817
+ if (typeof window.onResetCacheNeededCallback === "function") {
3818
+ window.onResetCacheNeededCallback();
3819
+ if (chart.current?.instance) {
3820
+ chart.current?.instance.activeChart()?.resetData();
3821
+ }
3822
+ }
3823
+ }
3824
+ },
3825
+ "tradingview"
3826
+ );
3827
+ }, [ws]);
3828
+ React3.useEffect(() => {
3829
+ if (chart.current && chart.current?.instance) {
3830
+ chart.current?.instance?.onChartReady(() => {
3831
+ if (isLoggedIn && chart.current?.instance) {
3832
+ createRenderer(
3833
+ chart.current.instance,
3834
+ void 0,
3835
+ broker,
3836
+ chartRef.current
3837
+ );
3838
+ }
3839
+ });
3840
+ }
3841
+ return () => {
3842
+ removeRenderer();
3843
+ };
3844
+ }, [chart.current, isLoggedIn]);
3845
+ React3.useEffect(() => {
3846
+ if (!symbol || !chart.current) {
3847
+ return;
3848
+ }
3849
+ chart.current?.setSymbol(symbol);
3850
+ const service = new WebsocketService(ws);
3851
+ service.subscribeSymbol(symbol);
3852
+ return () => {
3853
+ service.unsubscribeKline(symbol);
3854
+ };
3855
+ }, [symbol]);
3856
+ return {
3857
+ tradingViewScriptSrc,
3858
+ chartRef,
3859
+ changeDisplaySetting,
3860
+ displayControlState,
3861
+ interval,
3862
+ changeInterval,
3863
+ lineType,
3864
+ changeLineType,
3865
+ openChartSetting,
3866
+ openChartIndicators,
3867
+ symbol,
3868
+ onFullScreenChange,
3869
+ classNames,
3870
+ fullscreen
3871
+ };
3872
+ }
3873
+
3874
+ // src/components/tradingview.ui.tsx
3875
+ init_icons();
3876
+ var Link = (props) => {
3877
+ const { url, children } = props;
3878
+ return /* @__PURE__ */ jsxRuntime.jsx(
3879
+ "span",
3880
+ {
3881
+ onClick: () => window.open(url),
3882
+ className: "oui-cursor-pointer oui-px-0.5 oui-text-primary-light oui-underline",
3883
+ children
3884
+ }
3885
+ );
3886
+ };
3887
+ var NoTradingview = () => {
3888
+ const { t } = i18n.useTranslation();
3889
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "oui-absolute oui-inset-0 oui-z-0 oui-flex oui-flex-col oui-items-center oui-justify-start oui-p-2 oui-text-base-contrast-80 md:oui-justify-center md:oui-p-10", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
3890
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "oui-mb-6 oui-text-xs", children: t("tradingView.noScriptSrc") }),
3891
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "oui-mb-3 oui-pl-0 oui-text-2xs oui-text-base-contrast-54 md:oui-pl-2 md:oui-text-base md:oui-text-base-contrast-80", children: /* @__PURE__ */ jsxRuntime.jsx(
3892
+ i18n.Trans,
3893
+ {
3894
+ i18nKey: "tradingView.noScriptSrc.1",
3895
+ components: [
3896
+ /* @__PURE__ */ jsxRuntime.jsx(
3897
+ Link,
3898
+ {
3899
+ url: "https://www.tradingview.com/advanced-charts"
3900
+ },
3901
+ "tradingview-advanced-charts"
3902
+ )
3903
+ ]
3904
+ }
3905
+ ) }),
3906
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "oui-pl-0 oui-text-2xs oui-text-base-contrast-54 md:oui-pl-2 md:oui-text-base md:oui-text-base-contrast-80", children: /* @__PURE__ */ jsxRuntime.jsx(
3907
+ i18n.Trans,
3908
+ {
3909
+ i18nKey: "tradingView.noScriptSrc.2",
3910
+ components: [
3911
+ /* @__PURE__ */ jsxRuntime.jsx(
3912
+ Link,
3913
+ {
3914
+ url: "https://orderly.network/docs/sdks/react/components/trading#tradingviewconfig"
3915
+ },
3916
+ "tradingview-config"
3917
+ )
3918
+ ]
3919
+ }
3920
+ ) })
3921
+ ] }) });
3922
+ };
3923
+ var TopBar = (props) => {
3924
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "top-toolbar oui-flex oui-h-[44px] oui-justify-between md:oui-justify-start oui-items-center oui-p-2 md:oui-px-3 md:oui-pt-3 md:oui-pb-[14px]", children: props.children });
3925
+ };
3926
+ var topBar_default = TopBar;
3927
+ var LazyLineType = React3__default.default.lazy(() => Promise.resolve().then(() => (init_lineType(), lineType_exports)));
3928
+ var LazyTimeInterval = React3__default.default.lazy(
3929
+ () => Promise.resolve().then(() => (init_timeInterval(), timeInterval_exports)).then((mod) => ({ default: mod.TimeInterval }))
3930
+ );
3931
+ var LazyMobileDisplayControl = React3__default.default.lazy(
3932
+ () => Promise.resolve().then(() => (init_displayControl(), displayControl_exports)).then((mod) => ({
3933
+ default: mod.MobileDisplayControl
3934
+ }))
3935
+ );
3936
+ var LazyDesktopDisplayControl = React3__default.default.lazy(
3937
+ () => Promise.resolve().then(() => (init_displayControl(), displayControl_exports)).then((mod) => ({
3938
+ default: mod.DesktopDisplayControl
3939
+ }))
3940
+ );
3941
+ var OperateButton = ({ children, onClick }) => {
3942
+ return /* @__PURE__ */ jsxRuntime.jsx(
3943
+ ui.Box,
3944
+ {
3945
+ onClick,
3946
+ className: "oui-cursor-pointer oui-w-[18px] oui-h-[18px] oui-text-base-contrast-36 hover:oui-text-base-contrast-80",
3947
+ children
3948
+ }
3949
+ );
3950
+ };
3951
+ var ZoomOutIcon = (props) => {
3952
+ return /* @__PURE__ */ jsxRuntime.jsx(
3953
+ "svg",
3954
+ {
3955
+ xmlns: "http://www.w3.org/2000/svg",
3956
+ width: "18",
3957
+ height: "18",
3958
+ viewBox: "0 0 18 18",
3959
+ fill: "currentColor",
3960
+ ...props,
3961
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M15.0008 2.24304C14.8088 2.24304 14.6085 2.30755 14.4615 2.4538L11.2508 5.66455V3.74304H9.75079V7.49304C9.75079 7.90704 10.0868 8.24304 10.5008 8.24304H14.2508V6.74304H12.3285L15.54 3.53229C15.8325 3.23904 15.8325 2.74705 15.54 2.4538C15.393 2.30755 15.1928 2.24304 15.0008 2.24304ZM3.7508 9.74303V11.243H5.67231L2.46156 14.4538C2.16906 14.747 2.16906 15.239 2.46156 15.5323C2.75481 15.8248 3.2468 15.8248 3.54005 15.5323L6.7508 12.3215V14.243H8.25079V10.493C8.25079 10.079 7.9148 9.74303 7.5008 9.74303H3.7508Z" })
3962
+ }
3963
+ );
3964
+ };
3965
+ var ZoomInIcon = (props) => {
3966
+ return /* @__PURE__ */ jsxRuntime.jsx(
3967
+ "svg",
3968
+ {
3969
+ xmlns: "http://www.w3.org/2000/svg",
3970
+ width: "18",
3971
+ height: "18",
3972
+ viewBox: "0 0 18 18",
3973
+ fill: "currentColor",
3974
+ ...props,
3975
+ children: /* @__PURE__ */ jsxRuntime.jsx("path", { d: "M7.49219 9.74304C7.30026 9.74304 7.09964 9.80755 6.95309 9.9538L3.74219 13.1646V11.243H2.24219V14.993C2.24219 15.407 2.57796 15.743 2.99219 15.743H6.74219V14.243H4.82031L8.03121 11.0323C8.32416 10.739 8.32416 10.247 8.03121 9.9538C7.88481 9.80755 7.68404 9.74304 7.49219 9.74304ZM11.2509 2.24304V3.74304H13.1728L9.96186 6.9538C9.66899 7.24705 9.66899 7.73904 9.96186 8.03229C10.2547 8.32479 10.7471 8.32479 11.04 8.03229L14.2509 4.82153V6.74304H15.7509V2.99304C15.7509 2.57904 15.4151 2.24304 15.0009 2.24304H11.2509Z" })
3976
+ }
3977
+ );
3978
+ };
3979
+ var TradingviewUI = React3.forwardRef((props, ref) => {
3980
+ const {
3981
+ chartRef,
3982
+ interval,
3983
+ changeDisplaySetting,
3984
+ displayControlState,
3985
+ tradingViewScriptSrc,
3986
+ changeInterval,
3987
+ lineType,
3988
+ changeLineType,
3989
+ openChartSetting,
3990
+ openChartIndicators,
3991
+ onFullScreenChange
3992
+ } = props;
3993
+ const isMobile = hooks.useMediaQuery(types.MEDIA_TABLET);
3994
+ return /* @__PURE__ */ jsxRuntime.jsx(
3995
+ "div",
3996
+ {
3997
+ ref,
3998
+ className: ui.cn("oui-relative oui-size-full", props.classNames?.root),
3999
+ children: !tradingViewScriptSrc ? /* @__PURE__ */ jsxRuntime.jsx(NoTradingview, {}) : /* @__PURE__ */ jsxRuntime.jsxs(
4000
+ "div",
4001
+ {
4002
+ className: ui.cn(
4003
+ "oui-absolute oui-inset-0 oui-z-[1] oui-flex oui-flex-col",
4004
+ props.classNames?.content
4005
+ ),
4006
+ children: [
4007
+ /* @__PURE__ */ jsxRuntime.jsx(topBar_default, { children: isMobile ? /* @__PURE__ */ jsxRuntime.jsxs(
4008
+ ui.Flex,
4009
+ {
4010
+ gapX: 2,
4011
+ width: "100%",
4012
+ justify: "between",
4013
+ className: "oui-hide-scrollbar oui-overflow-x-scroll",
4014
+ children: [
4015
+ /* @__PURE__ */ jsxRuntime.jsx(React3__default.default.Suspense, { fallback: null, children: /* @__PURE__ */ jsxRuntime.jsx(
4016
+ LazyTimeInterval,
4017
+ {
4018
+ interval: interval ?? "15",
4019
+ changeInterval
4020
+ }
4021
+ ) }),
4022
+ /* @__PURE__ */ jsxRuntime.jsx(OperateButton, { onClick: openChartIndicators, children: /* @__PURE__ */ jsxRuntime.jsx(IndicatorsIcon, {}) }),
4023
+ /* @__PURE__ */ jsxRuntime.jsx(React3__default.default.Suspense, { fallback: null, children: /* @__PURE__ */ jsxRuntime.jsx(
4024
+ LazyMobileDisplayControl,
4025
+ {
4026
+ displayControlState,
4027
+ changeDisplayControlState: changeDisplaySetting
4028
+ }
4029
+ ) })
4030
+ ]
4031
+ }
4032
+ ) : /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { justify: "between", itemAlign: "center", width: "100%", children: [
4033
+ /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { children: [
4034
+ /* @__PURE__ */ jsxRuntime.jsx(React3__default.default.Suspense, { fallback: null, children: /* @__PURE__ */ jsxRuntime.jsx(
4035
+ LazyTimeInterval,
4036
+ {
4037
+ interval: interval ?? "1",
4038
+ changeInterval
4039
+ }
4040
+ ) }),
4041
+ /* @__PURE__ */ jsxRuntime.jsx(
4042
+ ui.Divider,
4043
+ {
4044
+ direction: "vertical",
4045
+ className: "oui-h-4",
4046
+ mx: 2,
4047
+ intensity: 8
4048
+ }
4049
+ ),
4050
+ /* @__PURE__ */ jsxRuntime.jsxs(ui.Flex, { justify: "start", itemAlign: "center", gap: 2, children: [
4051
+ /* @__PURE__ */ jsxRuntime.jsx(React3__default.default.Suspense, { fallback: null, children: /* @__PURE__ */ jsxRuntime.jsx(
4052
+ LazyDesktopDisplayControl,
4053
+ {
4054
+ displayControlState,
4055
+ changeDisplayControlState: changeDisplaySetting
4056
+ }
4057
+ ) }),
4058
+ /* @__PURE__ */ jsxRuntime.jsx(OperateButton, { onClick: openChartIndicators, children: /* @__PURE__ */ jsxRuntime.jsx(IndicatorsIcon, {}) }),
4059
+ /* @__PURE__ */ jsxRuntime.jsx(React3__default.default.Suspense, { fallback: null, children: /* @__PURE__ */ jsxRuntime.jsx(
4060
+ LazyLineType,
4061
+ {
4062
+ lineType,
4063
+ changeLineType
4064
+ }
4065
+ ) }),
4066
+ /* @__PURE__ */ jsxRuntime.jsx(OperateButton, { onClick: openChartSetting, children: /* @__PURE__ */ jsxRuntime.jsx(SettingIcon, {}) })
4067
+ ] })
4068
+ ] }),
4069
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Flex, { children: props.fullscreen ? /* @__PURE__ */ jsxRuntime.jsx(
4070
+ ZoomOutIcon,
4071
+ {
4072
+ className: "oui-text-base-contrast-54 hover:oui-text-base-contrast oui-cursor-pointer",
4073
+ onClick: onFullScreenChange
4074
+ }
4075
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
4076
+ ZoomInIcon,
4077
+ {
4078
+ className: "oui-text-base-contrast-54 hover:oui-text-base-contrast oui-cursor-pointer",
4079
+ onClick: onFullScreenChange
4080
+ }
4081
+ ) })
4082
+ ] }) }),
4083
+ /* @__PURE__ */ jsxRuntime.jsx("div", { ref: chartRef, className: "oui-size-full oui-overflow-hidden" })
4084
+ ]
4085
+ }
4086
+ )
4087
+ }
4088
+ );
4089
+ });
4090
+ var TradingviewWidget = React3.forwardRef((props, ref) => {
4091
+ const state = useTradingviewScript(props);
4092
+ return /* @__PURE__ */ jsxRuntime.jsx(TradingviewUI, { ...state, ref });
4093
+ });
4094
+
4095
+ exports.TradingviewUI = TradingviewUI;
4096
+ exports.TradingviewWidget = TradingviewWidget;
4097
+ exports.useTradingviewScript = useTradingviewScript;
21
4098
  //# sourceMappingURL=out.js.map
22
4099
  //# sourceMappingURL=index.js.map