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