@orderly.network/ui-tradingview 2.8.1 → 2.8.2

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,14 +1,4091 @@
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 '@orderly.network/i18n';
4
- import { cn as cn$1, Flex, Divider, Box, toast, modal, DropdownMenuRoot, DropdownMenuTrigger, DropdownMenuPortal, DropdownMenuContent, Text, Switch } from '@orderly.network/ui';
4
+ import { cn, Flex, Divider, Box, toast, modal, DropdownMenuRoot, DropdownMenuTrigger, DropdownMenuPortal, DropdownMenuContent, Text, Switch } from '@orderly.network/ui';
5
5
  import { useMediaQuery, useConfig, useAccount, useSymbolsInfo, useLocalStorage, useOrderEntry_deprecated, useWS, usePositionStream, useOrderStream, useEventEmitter } from '@orderly.network/hooks';
6
6
  import { MEDIA_TABLET, OrderSide, TradingviewFullscreenKey, OrderType, AccountStatusEnum, OrderStatus } from '@orderly.network/types';
7
7
  import { Decimal, commify, getTrailingStopPrice } from '@orderly.network/utils';
8
8
  import { startOfSecond, startOfMinute, startOfHour, startOfDay, startOfMonth, startOfYear, startOfWeek } from 'date-fns';
9
9
 
10
- var Jr=Object.defineProperty;var K=(r,e)=>()=>(r&&(e=r(r=0)),e);var Ve=(r,e)=>{for(var t in e)Jr(r,t,{get:e[t],enumerable:true});};var $,ke,lt,ar,lr,cr,ur,dr,pr,mr,gr,hr,Z=K(()=>{$=r=>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"})})}),ke=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"})})}),lt=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"})})}),ar=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"})})}),lr=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"})})}),cr=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"})})}),ur=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"})]})}),dr=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"})})}),pr=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"})]})}),mr=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"})})}),gr=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"})})}),hr=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 Lr={};Ve(Lr,{default:()=>Lo});var Io,Lo,Or=K(()=>{Z();Io=r=>{let[e,t]=useState(false),{t:i}=useTranslation(),o=useMemo(()=>[{icon:jsx(lr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.bars"),value:"0"},{icon:jsx(cr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.candles"),value:"1"},{icon:jsx(ur,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.hollowCandles"),value:"9"},{icon:jsx(dr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.line"),value:"2"},{icon:jsx(pr,{fill:"currentColor",className:"oui-w-5 oui-h-5"}),label:i("tradingView.lineType.area"),value:"3"},{icon:jsx(mr,{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$1("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$1("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))})})})]})},Lo=Io;});var wr={};Ve(wr,{MobileTimeInterval:()=>xr,TimeInterval:()=>Ao});var Pr,Ao,Bo,xr,Vo,Rr=K(()=>{Z();Pr=()=>{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])}},Ao=r=>useMediaQuery(MEDIA_TABLET)?jsx(xr,{...r}):jsx(Bo,{...r}),Bo=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$1("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$1("oui-cursor-pointer oui-px-2","hover:oui-text-base-contrast-80","oui-break-normal oui-whitespace-nowrap",r.interval===i.value&&"oui-text-base-contrast-80 oui-bg-white/[.06] oui-rounded"),id:i.value,onClick:()=>r.changeInterval(i.value),children:i.label},i.value))})},xr=r=>{let{t:e}=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}=Pr(),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$1("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$1("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(Vo,{...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")})})]})},Vo=r=>{let[e,t]=R.useState(false),{mobileTimeIntervalMoreMap:i}=Pr();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$1("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$1("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$1("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 Er,kr=K(()=>{Z();Er=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(ke,{className:cn$1("oui-w-[18px] oui-h-[18px] ",i&&"oui-text-base-contrast-80")}),jsx($,{className:cn$1("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$1("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 Mr,Dr=K(()=>{Z();Mr=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$1("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(ke,{className:cn$1("oui-size-[18px] ",e&&"oui-text-base-contrast-80")}),jsx($,{className:cn$1("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$1("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$1("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(hr,{className:"oui-size-3"}):jsx(gr,{className:"oui-size-3"})]})},a.id||c))},n))})})]})};});var ht={};Ve(ht,{DesktopDisplayControl:()=>Er,MobileDisplayControl:()=>Mr});var ft=K(()=>{kr();Dr();});var Xr="#008676",ei="#D92D6B",Ne="#131519",ti="#00B49E",ri="#FF447C",ii="#333948",oi="#FFFFFF",ni="#F4F7F9",si="regular 11px Manrope",It={upColor:Xr,downColor:ei,chartBG:Ne,pnlUpColor:ti,pnlDownColor:ri,pnlZoreColor:ii,textColor:oi,qtyTextColor:ni,font:si,volumeUpColor:"#0C3E3A",volumeDownColor:"#5A1E36",closeIcon:"rgba(255, 255, 255, 0.8)"},Lt=(r,e)=>{let t={"paneProperties.background":r.chartBG,"paneProperties.backgroundType":"solid","mainSeriesProperties.candleStyle.upColor":r.upColor,"mainSeriesProperties.candleStyle.downColor":r.downColor,"mainSeriesProperties.candleStyle.borderColor":r.upColor,"mainSeriesProperties.candleStyle.borderUpColor":r.upColor,"mainSeriesProperties.candleStyle.borderDownColor":r.downColor,"mainSeriesProperties.candleStyle.wickUpColor":r.upColor,"mainSeriesProperties.candleStyle.wickDownColor":r.downColor,"paneProperties.separatorColor":"#2B2833","paneProperties.vertGridProperties.color":"#26232F","paneProperties.horzGridProperties.color":"#26232F","scalesProperties.fontSize":e?8:12,"scalesProperties.textColor":"#97969B","paneProperties.legendProperties.showSeriesTitle":!e,"mainSeriesProperties.statusViewStyle.symbolTextSource":"ticker"},i={"volume.volume.color.0":r.volumeDownColor,"volume.volume.color.1":r.volumeUpColor};return {overrides:t,studiesOverrides:i}},ce="Orderly",I=r=>r.includes(":")?r.split(":")[1]:r,ue=r=>r.startsWith(`${ce}:`)?r:`${ce}:${r}`;var ci=(r,e)=>{let i,o=s=>[null,"limit","MARKET","STOP_MARKET","STOP_LIMIT"][s];return {symbolInfo:async s=>(i=e.getSymbolInfo(I(s)),{qty:{min:i?.baseMin??0,max:i?.baseMax??0,step:i?.baseTick??0},pipValue:0,pipSize:i?.quoteTick??0,minTick:i?.quoteTick??0,description:""}),placeOrder:async s=>{let n=["SELL","BUY"][+(s.side>0)],a=s.qty.toString();(s.limitPrice??0).toString();(s.stopPrice??0).toString();let u=I(s.symbol),m=o(s.type);m==="MARKET"?e.sendMarketOrder({side:n,order_quantity:a,symbol:u,order_type:OrderType.MARKET}):"LIMIT";},orders:()=>[],positions:()=>[],executions:()=>[],connectionStatus:()=>1,chartContextMenuActions:s=>r.defaultContextMenuActions(s),isTradable:async()=>true,accountManagerInfo:()=>({}),currentAccount:()=>"1",accountsMetainfo:async()=>[{id:"1"}],remove:()=>r?.silentOrdersPlacement().unsubscribe()}},Ot=ci;function V(r){return r===void 0?"":typeof r=="string"?r:r.message}var pe=class{constructor(e,t,i){this._datafeedUrl=e,this._requester=t,this._limitedServerResponse=i;}getBars(e,t,i){let o={symbol:e.ticker||"",resolution:t,from:i.from,to:i.to};return i.countBack!==void 0&&(o.countback=i.countBack),e.currency_code!==void 0&&(o.currencyCode=e.currency_code),e.unit_id!==void 0&&(o.unitId=e.unit_id),new Promise(async(s,n)=>{try{let a=await this._requester.sendRequest(this._datafeedUrl,"history",o),c=this._processHistoryResponse(a);this._limitedServerResponse&&await this._processTruncatedResponse(c,o),s(c);}catch(a){if(a instanceof Error||typeof a=="string"){let c=V(a);n(c);}}})}async _processTruncatedResponse(e,t){let i=e.bars.length;try{for(;this._limitedServerResponse&&this._limitedServerResponse.maxResponseLength>0&&this._limitedServerResponse.maxResponseLength===i&&t.from<t.to;){t.countback&&(t.countback=t.countback-i),this._limitedServerResponse.expectedOrder==="earliestFirst"?t.from=Math.round(e.bars[e.bars.length-1].time/1e3):t.to=Math.round(e.bars[0].time/1e3);let o=await this._requester.sendRequest(this._datafeedUrl,"history",t),s=this._processHistoryResponse(o);i=s.bars.length,this._limitedServerResponse.expectedOrder==="earliestFirst"?(s.bars[0].time===e.bars[e.bars.length-1].time&&s.bars.shift(),e.bars.push(...s.bars)):(s.bars[s.bars.length-1].time===e.bars[0].time&&s.bars.pop(),e.bars.unshift(...s.bars));}}catch(o){if(o instanceof Error||typeof o=="string"){V(o);}}}_processHistoryResponse(e){if(e.s!=="ok"&&e.s!=="no_data")throw new Error(e.errmsg);let t=[],i={noData:false};if(e.s==="no_data")i.noData=true,i.nextTime=e.nextTime;else {let o=e.v!==void 0,s=e.o!==void 0;for(let n=0;n<e.t.length;++n){let a={time:e.t[n]*1e3,close:parseFloat(e.c[n]),open:parseFloat(e.c[n]),high:parseFloat(e.c[n]),low:parseFloat(e.c[n])};s&&(a.open=parseFloat(e.o[n]),a.high=parseFloat(e.h[n]),a.low=parseFloat(e.l[n])),o&&(a.volume=parseFloat(e.v[n])),t.push(a);}}return {bars:t,meta:i}}};var me=class{constructor(e){e&&(this._headers=e);}sendRequest(e,t,i){if(i!==void 0){let s=Object.keys(i);s.length!==0&&(t+="?"),t+=s.map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(i[n].toString())}`).join("&");}""+t;let o={credentials:"same-origin"};return this._headers!==void 0&&(o.headers=this._headers),fetch(`${e}/${t}`,o).then(s=>s.text()).then(s=>JSON.parse(s))}};function f(r,e,t,i){let o=r[e];return Array.isArray(o)&&(!i||Array.isArray(o[0]))?o[t]:o}function ge(r,e,t){return r+(e!==void 0?"_%|#|%_"+e:"")+(t!==void 0?"_%|#|%_"+t:"")}var he=class{constructor(e,t,i){this._exchangesList=["Orderly"];this._symbolsInfo={};this._symbolsList=[];this._datafeedUrl=e,this._datafeedSupportedResolutions=t,this._requester=i,this._readyPromise=this._init(),this._readyPromise.catch(o=>{});}resolveSymbol(e,t,i){return this._readyPromise.then(()=>{let o=this._symbolsInfo[ge(e,t,i)];return o===void 0?Promise.reject("invalid symbol"):Promise.resolve(o)})}searchSymbols(e,t,i,o){return this._readyPromise.then(()=>{let s=[],n=e.length===0;e=e.toUpperCase();for(let c of this._symbolsList){let l=this._symbolsInfo[c];if(l===void 0||i.length>0&&l.type!==i||t&&t.length>0&&l.exchange!==t)continue;let u=l.name.toUpperCase().indexOf(e),m=l.description.toUpperCase().indexOf(e);if((n||u>=0||m>=0)&&!s.some(g=>g.symbolInfo===l)){let g=u>=0?u:8e3+m;s.push({symbolInfo:l,weight:g});}}let a=s.sort((c,l)=>c.weight-l.weight).slice(0,o).map(c=>{let l=c.symbolInfo;return {symbol:l.name,full_name:`${l.exchange}:${l.name}`,description:l.description,exchange:l.exchange,params:[],type:l.type,ticker:l.name}});return Promise.resolve(a)})}_init(){let e=[],t={};for(let i of this._exchangesList)t[i]||(t[i]=true,e.push(this._requestExchangeData(i)));return Promise.all(e).then(()=>{this._symbolsList.sort();})}_requestExchangeData(e){return new Promise((t,i)=>{this._requester.sendRequest(this._datafeedUrl,"symbol_info",{group:e}).then(o=>{try{this._onExchangeDataReceived(e,o);}catch(s){i(s instanceof Error?s:new Error(`SymbolsStorage: Unexpected exception ${s}`));return}t();}).catch(o=>{`${e}${V(o)}`,t();});})}_onExchangeDataReceived(e,t){let i=0;try{let o=t.symbol.length,s=t.ticker!==void 0;for(;i<o;++i){let n=t.symbol[i],a=f(t,"exchange-listed",i),c=f(t,"exchange-traded",i),l=c+":"+n,u=f(t,"currency-code",i),m=f(t,"unit-id",i),y=s?f(t,"ticker",i):n,g={ticker:y,name:n,base_name:[a+":"+n],listed_exchange:a,exchange:c,currency_code:u,original_currency_code:f(t,"original-currency-code",i),unit_id:m,original_unit_id:f(t,"original-unit-id",i),unit_conversion_types:f(t,"unit-conversion-types",i,!0),description:f(t,"description",i),has_intraday:q(f(t,"has-intraday",i),!1),visible_plots_set:q(f(t,"visible-plots-set",i),"ohlcv"),minmov:f(t,"minmovement",i)||f(t,"minmov",i)||0,minmove2:f(t,"minmove2",i)||f(t,"minmov2",i),fractional:f(t,"fractional",i),pricescale:f(t,"pricescale",i),type:f(t,"type",i),session:f(t,"session-regular",i),session_holidays:f(t,"session-holidays",i),corrections:f(t,"corrections",i),timezone:f(t,"timezone",i),supported_resolutions:q(f(t,"supported-resolutions",i,!0),this._datafeedSupportedResolutions),has_daily:q(f(t,"has-daily",i),!0),intraday_multipliers:q(f(t,"intraday-multipliers",i,!0),["1","5","15","30","60"]),has_weekly_and_monthly:f(t,"has-weekly-and-monthly",i),has_empty_bars:f(t,"has-empty-bars",i),volume_precision:q(f(t,"volume-precision",i),0),format:"price"};this._symbolsInfo[y]=g,this._symbolsInfo[n]=g,this._symbolsInfo[l]=g,(u!==void 0||m!==void 0)&&(this._symbolsInfo[ge(y,u,m)]=g,this._symbolsInfo[ge(n,u,m)]=g,this._symbolsInfo[ge(l,u,m)]=g),this._symbolsList.push(n);}}catch(o){throw new Error(`SymbolsStorage: API error when processing exchange ${e} symbol #${i} (${t.symbol[i]}): ${Object(o).message}`)}}};function q(r,e){return r!==void 0?r:e}var fe=class{constructor(e){this._configuration=xt();this._symbolsStorage=null;this._datafeedURL=e,this._requester=new me,this._historyProvider=new pe(e,this._requester),this._configurationReadyPromise=this._requestConfiguration().then(t=>{t===null&&(t=xt()),this._setupWithConfiguration(t);});}getBars(e,t,i,o,s){this._historyProvider.getBars(e,t,i).then(n=>{o(n.bars,n.meta);}).catch(s);}onReady(e){this._configurationReadyPromise.then(()=>{e(this._configuration);});}searchSymbols(e,t,i,o){if(this._symbolsStorage===null)throw new Error("Datafeed: inconsistent configuration (symbols storage)");this._symbolsStorage.searchSymbols(e,t,i,30).then(o).catch(o.bind(null,[]));}resolveSymbol(e,t,i,o){let s=o&&o.currencyCode,n=o&&o.unitId;function c(l){t(l);}if(this._symbolsStorage===null)throw new Error("Datafeed: inconsistent configuration (symbols storage)");this._symbolsStorage.resolveSymbol(e,s,n).then(c).catch(i);}getMarks(){}getTimescaleMarks(){}getServerTime(){}_requestConfiguration(){return this._send("config").catch(e=>(`${V(e)}`,null))}_send(e,t){return this._requester.sendRequest(this._datafeedURL,e,t)}_setupWithConfiguration(e){if(this._configuration=e,e.exchanges===void 0&&(e.exchanges=[]),!e.supports_search&&!e.supports_group_request)throw new Error("Unsupported datafeed configuration. Must either support search, or support group request");(e.supports_group_request||!e.supports_search)&&(this._symbolsStorage=new he(this._datafeedURL,e.supported_resolutions||[],this._requester)),`${JSON.stringify(e)}`;}};function xt(){return {supports_search:false,supports_group_request:true,supported_resolutions:["1","3","5","15","30","60","120","240","480","720","1D","3D","1W","1M"],supports_marks:false,supports_timescale_marks:false}}var be=class{constructor(){this.subscribers=new Map;}subscribe(e,t){return this.subscribers.has(e)||this.subscribers.set(e,[]),this.subscribers.get(e).push(t),()=>{this.unsubscribe(e,t);}}unsubscribe(e,t){if(this.subscribers.has(e)){let i=this.subscribers.get(e);this.subscribers.set(e,i.filter(o=>o!==t)),this.subscribers.get(e).length===0&&this.subscribers.delete(e);}}publish(e,t){this.subscribers.has(e)&&this.subscribers.get(e).forEach(o=>{o(t);});}};var He=r=>{let e="1d";switch(r){case "1":e="1m";break;case "3":e="3m";break;case "5":e="5m";break;case "15":e="15m";break;case "30":e="30m";break;case "60":e="1h";break;case "120":e="2h";break;case "240":e="4h";break;case "480":e="8h";break;case "720":e="12h";break;case "D":case "1D":e="1d";break;case "3D":e="3d";break;case "1W":e="1w";break;case "1M":e="1M ";break;}return e},N={interval:"TradingviewSDK.lastUsedTimeBasedResolution",lineType:"TradingviewSDK.lastUsedStyle",displayControlSetting:"TradingviewSDK.displaySetting"};var Fe=(r,e)=>`${r}kline_${e}`,ui=r=>["trade"].map(t=>`${r}@${t}`),k=class k{constructor(e){this.klineSubscribeIdMap=new Map;this.klineOnTickCallback=new Map;this.subscribeCachedTopics=new Map;this.wsInstance=null;this.klineData=new Map;return k._created||(this.wsInstance=e,k._instance=this,k._created=true),k._instance}subscribeKline(e,t,i,o){let s=He(i);this.klineSubscribeIdMap.set(e,{symbol:t,resolution:i});let n=Fe(t,s);if(this.klineOnTickCallback.has(n)){let a=this.klineOnTickCallback.get(n);a[e]=o;}else {this.klineOnTickCallback.set(n,{[e]:o});let a=this.wsInstance?.subscribe({event:"subscribe",topic:`${t}@kline_${s}`,id:`${t}@kline_${s}`,ts:new Date().getTime()},{onMessage:c=>{let{open:l,close:u,high:m,low:y,volume:g,startTime:b}=c,z=Fe(c.symbol,c.type);this.updateKline(z,{time:b,close:u,open:l,high:m,low:y,volume:g});}});this.subscribeCachedTopics.set(`${t}@kline_${s}`,a);}}unsubscribeKline(e){if(!this.klineSubscribeIdMap.has(e))return;let{symbol:t,resolution:i}=this.klineSubscribeIdMap.get(e),o=He(i),s=Fe(t,o);if(this.klineOnTickCallback.has(s)){let n=this.klineOnTickCallback.get(s);delete n[e],Object.keys(n).length===0&&(this.klineOnTickCallback.delete(s),this.subscribeCachedTopics.get(`${t}@kline_${o}`)());}delete this.klineSubscribeIdMap[e];}subscribeSymbol(e){ui(e).forEach(i=>{if(!this.subscribeCachedTopics.has(i)){let o=this.wsInstance?.subscribe({event:"subscribe",topic:i,id:i,ts:new Date().getTime()},{onMessage:s=>{this.updateKlineByLastPrice(s.symbol,s.price);}});this.subscribeCachedTopics.set(i,o);}});}updateKlineByLastPrice(e,t){this.klineOnTickCallback.forEach((i,o)=>{if(o.startsWith(e)){let s=this.klineData.get(o);s&&this.updateKline(o,{...s,close:t});}});}updateKline(e,t){let i=this.klineOnTickCallback.get(e);i&&t&&(this.klineData.set(e,t),Object.keys(i).forEach(o=>{let s=i[o];s&&typeof s=="function"&&s(t);}));}};k._created=false,k._instance=null;var G=k;var di=(()=>{let r=0;return ()=>r++})(),ye=class extends fe{constructor(t,i){let o=`${t}/tv`;super(o);this.bbosMap=new Map;this.tickersMap=new Map;this.eventBus=new be;this._subscribeQuoteMap=new Map,this._prefixId=di(),this._publicWs=new G(i),this.bbosMap=new Map,i.on("tickers",s=>{for(let n of s.data)n.change=n.close-n.open,n.perChange=n.open?+(100*n.change/n.open).toFixed(2):0,this.tickersMap.set(n.symbol,n);this.eventBus.publish("tickerUpdate",{message:"ticker"});}),i.subscribe({event:"subscribe",topic:"bbos"},{formatter:s=>s,onMessage:s=>{for(let n of s.data)this.bbosMap.set(n.symbol,{ask:n.ask,bid:n.bid,askSize:n.askSize,bidSize:n.bidSize});this.eventBus.publish("tickerUpdate",{message:"bbos"});}});}remove(){Array.from(this._subscribeQuoteMap.values()).forEach(t=>t?.());}getSubscriptionId(t){return `${this._prefixId}${t}`}subscribeBars(t,i,o,s,n){window.onResetCacheNeededCallback=n,this._publicWs.subscribeKline(`${this._prefixId}${s}`,t.ticker,i,o);}unsubscribeBars(t){this._publicWs.unsubscribeKline(`${this._prefixId}${t}`);}getQuotes(t,i){let o=this.getSubscriptionId("getQuotes");this.unsubscribeQuotes("getQuotes");let s=this.eventBus.subscribe("tickerUpdate",n=>{let a=new Map;t.forEach(c=>{let l=this.bbosMap.get(I(c)),u=this.tickersMap.get(I(c));if(!l||!u)return;let m={...u,ask:l.ask,bid:l.bid};a.set(I(c),m);}),a.size&&i(Array.from(a.values()).map(c=>this._toUDFTicker(c)));});this._subscribeQuoteMap.set(o,s);}subscribeQuotes(t,i,o,s){let n=`${this._prefixId}${s}`;if(t.length>0){this.unsubscribeQuotes(n);let a=this.eventBus.subscribe("tickerUpdate",c=>{let l=new Map;t.forEach(u=>{let m=this.bbosMap.get(I(u)),y=this.tickersMap.get(I(u));if(!m||!y)return;let g={...y,ask:m.ask,bid:m.bid};l.set(I(u),g);}),l.size&&o(Array.from(l.values()).map(u=>this._toUDFTicker(u)));});this._subscribeQuoteMap.set(n,a);}}unsubscribeQuotes(t){let i=this.getSubscriptionId(t),o=this._subscribeQuoteMap.get(i);o&&(o(),this._subscribeQuoteMap.delete(i));}_toUDFTicker(t){return {n:ue(t.symbol),s:"ok",v:{ask:t.ask,bid:t.bid,ch:t.change,chp:t.perChange/100,description:"",exchange:ce,hight_price:t.high,low_price:t.low,lp:t.close,open_price:t.open,prev_close_price:0,volume:t.volume}}}};var mi=2,gi="--",Ke=["BRACKET","STOP_BRACKET"],Ce=["POSITIONAL_TP_SL","TP_SL"];var qe=r=>r.root_algo_order_id!==r.algo_order_id&&(r.algo_type==="TAKE_PROFIT"||r.algo_type==="STOP_LOSS"),hi=r=>!!r&&Ke.includes(r);var Ge=r=>r.type==="CLOSE_POSITION",Et=r=>Ge(r)&&r.is_activated,kt=r=>qe(r)&&r.is_activated,We=r=>r.root_algo_order_algo_type==="TP_SL"||hi(r.root_algo_order_algo_type)&&r.is_activated,Mt=(r,e)=>{let t=r.algo_type,i={TAKE_PROFIT:i18n.t("tpsl.takeProfit"),STOP_LOSS:i18n.t("tpsl.stopLoss")}[t];return i||null},Dt=r=>{let e=new Map,t=1;return [...r].reverse().filter(We).forEach(i=>{i.root_algo_order_id&&!e.has(i.root_algo_order_id)&&e.set(i.root_algo_order_id,t++);}),e},At=(r,e)=>{let t=Math.abs(r.type==="CLOSE_POSITION"?e.balance:r.quantity),i=r.side==="SELL"?1:-1,o=e.open.toString();return {estPnl:new Decimal(r.trigger_price).minus(o??0).times(t).times(i).toString(),quantity:t,openPrice:o}},Bt=r=>r!==void 0&&r!==""?new Decimal(r).todp(mi,Decimal.ROUND_FLOOR):gi;function Qe(){let[r,{cancelOrder:e,cancelAlgoOrder:t,cancelTPSLChildOrder:i}]=useOrderStream({status:OrderStatus.INCOMPLETE});return useCallback(o=>{if(o.algo_order_id){if(Ce.includes(o.root_algo_order_algo_type)){let s=r?.find(a=>a.algo_order_id===o.root_algo_order_id);return s.child_orders.every(a=>!!a.trigger_price)?i(o.algo_order_id,o.root_algo_order_id):t(s.algo_order_id,o.symbol).then()}return t(o.algo_order_id,o.symbol).then()}return e(o.order_id,o.symbol).then()},[e,r])}function $e(r){useEventEmitter();let [,{updateOrder:t,cancelAlgoOrder:i,updateAlgoOrder:o,updateTPSLOrder:s}]=useOrderStream({status:OrderStatus.INCOMPLETE});return useCallback((n,a)=>{if(n.algo_order_id)if(Ce.includes(n.root_algo_order_algo_type)){let l=[{order_id:n.algo_order_id,trigger_price:new Decimal(a.value).toString()}];return s(n.root_algo_order_id,l).then(u=>{}).catch(u=>{r&&r.error(u.message);})}else {if(Ke.includes(n.algo_type))return o(n.algo_order_id,{order_price:new 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 Ze(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 wi=r=>e=>r(e),Ri=({closeConfirm:r,colorConfig:e,onToast:t,mode:i,symbol:o})=>{let s=Qe(),n=$e(t),a=useSymbolsInfo(),c=useCallback(g=>r&&r(g),[r]),{sendMarketOrder:l,sendLimitOrder:u}=Ze(o),m=useCallback(g=>{if(a)return {baseMin:a[g]("base_min"),baseMax:a[g]("base_max"),baseTick:a[g]("base_tick"),quoteTick:a[g]("quote_tick")}},[a]),y=useRef({cancelOrder:s,closePosition:c,editOrder:n,colorConfig:e,sendLimitOrder:u,getSymbolInfo:m,sendMarketOrder:wi(l),mode:i});return useEffect(()=>{y.current.getSymbolInfo=m;},[a]),useEffect(()=>{y.current.sendLimitOrder=u,y.current.sendMarketOrder=l;},[u,l]),useEffect(()=>{y.current.closePosition=c;},[r]),useEffect(()=>{y.current.cancelOrder=s;},[s]),y.current},Nt=Ri;var Ut={1:{startOf:"minute",period:0},3:{startOf:"hour",period:3*60*1e3},5:{startOf:"hour",period:5*60*1e3},15:{startOf:"hour",period:15*60*1e3},30:{startOf:"hour",period:30*60*1e3},60:{startOf:"hour",period:0},120:{startOf:"day",period:2*60*60*1e3},240:{startOf:"day",period:4*60*60*1e3},480:{startOf:"day",period:8*60*60*1e3},720:{startOf:"day",period:12*60*60*1e3},D:{startOf:"day",period:0},"1D":{startOf:"day",period:0},"3D":{startOf:"year",period:3*24*60*60*1e3},"5D":{startOf:"year",period:5*24*60*60*1e3},"1W":{startOf:"week",period:0},"1M":{startOf:"month",period:0}};function Ft(r,e,t,i){let{startOf:o,period:s}=Ut[t],n=new Date(r.updated_time).getTime(),a=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 Kt=(r,e)=>{let t=[],i={};return Ut[e]?(r.forEach(o=>{if(o.child_orders)for(let s of o.child_orders)s.is_activated&&s.algo_status===OrderStatus.FILLED&&Ft(s,i,e,t);else Ft(o,i,e,t);}),t):[]};var _e=class r{constructor(e,t){this.interval="1D";this.changeInterval=e=>{let t=()=>{this.renderExecutions(this.filledOrders,this.basePriceDecimal),this.instance.activeChart().onDataLoaded().unsubscribe(null,t);};this.interval=e,this.instance.activeChart().onDataLoaded().subscribe(null,t);};this.instance=e,this.executions=[],this.filledOrders=[],this.basePriceDecimal=0,this.broker=t,this.subscribeIntervalChange();}async subscribeIntervalChange(){this.interval=this.instance.symbolInterval().interval;let e=this.changeInterval;this.instance.activeChart().onIntervalChanged().subscribe(null,e);}renderExecutions(e,t){this.filledOrders=e,this.basePriceDecimal=t,this.interval&&(this.removeAll(),Kt(e,this.interval).forEach(i=>{this.executions.push(this.drawExecution(i,t));}));}removeAll(){this.executions.forEach(e=>e.remove()),this.executions=[];}static getExecutionInfo(e,t){let i=e.side,o=e.average_executed_price||e.child_orders?.find(n=>!!n.average_executed_price)?.average_executed_price||0,s=new 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 J=r=>{if(r!=null)return r.algo_order_id||r.order_id};var Se=class{constructor(){this.quantityTpslNoMap=new Map,this.tpslPnlMap=new Map,this.positions=null;}getQuantityTpslNoMap(){return this.quantityTpslNoMap}getTpslPnlMap(){return this.tpslPnlMap}getFormattedEstPnl(e){if(this.positions===null)return "";let t=this.positions[0];if(!t)return "";let{estPnl:i}=At(e,t);return Bt(i)}prepareTpslPnlMap(e){let t=[];return e.forEach(i=>{let o=J(i);if(o&&kt(i)){let s=this.tpslPnlMap.get(o),n=this.getFormattedEstPnl(i);s!==n&&(t.push(o),this.tpslPnlMap.set(o,n));}}),t}prepareQuantityTpslNoMap(e){this.quantityTpslNoMap=Dt(e);}recalculatePnl(e,t){return this.positions=e,this.prepareTpslPnlMap(t)}clear(){this.positions=null,this.quantityTpslNoMap.clear(),this.tpslPnlMap.clear();}};var P=class P{constructor(e,t){this.instance=e,this.pendingOrderLineMap=new Map,this.pendingOrders=[],this.broker=t,this.tpslCalService=new Se;}renderPendingOrders(e){e&&(this.pendingOrders=e),this.cleanOldPendingOrders(this.pendingOrders),this.tpslCalService.prepareTpslPnlMap(this.pendingOrders),this.tpslCalService.prepareQuantityTpslNoMap(this.pendingOrders),this.pendingOrders.forEach(t=>this.renderPendingOrder(t));}updatePositions(e){let t=this.tpslCalService.recalculatePnl(e,this.pendingOrders);this.pendingOrders.filter(i=>t.includes(J(i))).forEach(i=>this.renderPendingOrder(i));}renderPendingOrder(e){let t=P.getOrderId(e);if(!t)return;let i=this.drawOrderLine(t,e);i&&this.pendingOrderLineMap.set(t,i);}cleanOldPendingOrders(e){let t=new Set(e.map(i=>P.getOrderId(i)));this.pendingOrderLineMap.forEach((i,o)=>!t.has(o)&&this.removePendingOrder(o));}removePendingOrder(e){if(e===void 0)return;let t=this.pendingOrderLineMap.get(e);t&&(this.pendingOrderLineMap.delete(e),t.remove());}getBaseOrderLine(){let e=this.broker.colorConfig;return this.instance.activeChart().createOrderLine().setCancelTooltip(i18n.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 J(t),e}getTPSLText(e){let t=Mt(e,this.tpslCalService.getQuantityTpslNoMap());return t?this.getTPSLTextWithTpsl(t,e):null}getOrderQuantity(e){if(e.algo_order_id){if(Et(e)||Ge(e))return "100%";if(We(e)){let i=new 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=qe(t)?this.getTPSLText(t):P.getText(t);if(i===null)return null;let o=this.broker.colorConfig,s=this.pendingOrderLineMap.get(e)??this.getBaseOrderLine(),n=t.side==="BUY"?o.upColor:o.downColor;t.side==="BUY"?o.pnlUpColor:o.pnlDownColor;let c=P.getOrderPrice(t),l=100,u=this.getOrderQuantity(t),m=o.textColor;return s.setText(i).setCancelButtonIconColor(o.closeIcon).setCancelButtonBorderColor(n).setBodyTextColor(m).setBodyBorderColor(n).setQuantityBorderColor(n).setQuantityTextColor(n).setLineColor(n).setLineLength(l).setQuantity(u??"").setPrice(c),this.broker.mode!==3?(s.onCancel(null,()=>this.broker.cancelOrder(t)),this.applyEditOnMove(s,t)):s.setEditable(false).setCancellable(false),s}static getOrderEditKey(e){let t=this.getCombinationType(e);if(["LIMIT","BRACKET_LIMIT"].includes(t))return "price";if(t==="STOP_LIMIT"||t==="STOP_MARKET"||e.rootAlgoOrderAlgoType==="POSITIONAL_TP_SL"||e.rootAlgoOrderAlgoType==="TP_SL"||e.rootAlgoOrderAlgoType==="BRACKET"||e.rootAlgoOrderAlgoType==="STOP_BRACKET")return "trigger_price"}applyEditOnMove(e,t){let i=P.getOrderEditKey(t);i&&e.onMove(()=>{this.broker.editOrder(t,{type:i,value:`${e.getPrice()}`}).then(o=>{o.success||this.renderPendingOrder(t);}).catch(()=>this.renderPendingOrder(t));});}removeAll(){this.pendingOrderLineMap.forEach(e=>e.remove()),this.pendingOrderLineMap.clear(),this.pendingOrders=[],this.tpslCalService.clear();}};P.getOrderId=e=>{if(e!=null)return e.algo_order_id||e.order_id};var Te=P;var Ie=class r{constructor(e,t){this.instance=e,this.currentSymbol="",this.broker=t,this.positionLines={},this.lastPositions=null;}renderPositions(e){if(e===null||e.length===0){this.removePositions();return}this.lastPositions?.length!==e.length&&this.removePositions(),e[0].symbol!==this.currentSymbol&&(this.removePositions(),this.currentSymbol=e[0].symbol),e.forEach((t,i)=>this.drawPositionLine(t,i)),this.lastPositions=e;}getBasePositionLine(){return this.instance.activeChart().createPositionLine().setTooltip(i18n.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 Ye=10;var Le=class{constructor(e,t){this.interactiveMode=0;this.tpslElRemoveTimer=null;this.currentPosition=null;this.tpslOrderLine=null;this.tpslPnLVerticalLineEntityId=null;this.tpslVerticalLineTime=null;this.tpslStartCircleEntityId=null;this.tpslEndCircleEntityId=null;this.threshold=10;this.lastArgs=null;this.instance=e,this.broker=t,this.lastPositions=null,this.tpslElRemoveTimer=null,this.currentPosition=null,this.bindEvent();}bindEvent(){this.chart.crossHairMoved().subscribe(null,e=>{if(this.lastArgs=e,this.interactiveMode===2){this.clearTpslElRemoveTimer();return}let t=this.getIntersectantPosition(e);if(!(this.currentPosition&&t&&this.currentPosition.symbol===t.symbol)){if(!t){this.clearTPSLElements();return}t&&(this.clearTpslElRemoveTimer(),this.currentPosition=t,this.createTPSLTriggerButton(e));}});}clearTpslElRemoveTimer(){this.tpslElRemoveTimer&&(clearTimeout(this.tpslElRemoveTimer),this.tpslElRemoveTimer=null);}showTPSLDialog(e){let t=new 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 Ye;try{let t=e.getVisiblePriceRange();if(!t)return Ye;let i=t.to-t.from,o=i*.02;return Math.min(o,i)}catch{return Ye}}drawTPSL(e){let{price:t}=e,i=new 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("common.tpsl")).setQuantity("").setBodyTextColor(this.broker.colorConfig.textColor).setBodyBackgroundColor(this.broker.colorConfig.chartBG).setBodyBorderColor(this.broker.colorConfig.pnlZoreColor).setQuantityBackgroundColor(this.broker.colorConfig.chartBG).setQuantityBorderColor(this.broker.colorConfig.pnlZoreColor).setQuantityTextColor(this.broker.colorConfig.qtyTextColor).setBodyFont(this.broker.colorConfig.font).setQuantityFont(this.broker.colorConfig.font).setLineStyle(3)}verticalLineTime(){let e=this.chart.getVisibleRange();this.tpslVerticalLineTime=this.getTimeAtPercentage(e.from,e.to,90);}clearTPSLElements(){this.tpslElRemoveTimer||(this.tpslElRemoveTimer=setTimeout(()=>{this.currentPosition=null,this.tpslOrderLine&&(this.tpslOrderLine.remove(),this.tpslOrderLine=null),this.tpslPnLVerticalLineEntityId&&(this.chart.removeEntity(this.tpslPnLVerticalLineEntityId),this.tpslPnLVerticalLineEntityId=null),this.tpslElRemoveTimer=null;},100));}getIntersectantPosition(e){if(!Array.isArray(this.lastPositions)||this.lastPositions.length===0)return null;let{price:t,time:i}=e,o=null;for(let s of this.lastPositions)if(s&&Math.abs(s.open-t)<this.threshold){o=s;break}return o}get chart(){return this.instance.activeChart()}getTimeAtPercentage(e,t,i){if(typeof e!="number"||typeof t!="number"||typeof i!="number"||i<0||i>100||e>t)return null;let o=t-e,s=i/100,n=o*s,a=e+n;return Math.round(a)}};var Oe=class{constructor(e,t,i){this.instance=e,this.positionLineService=new Ie(e,i),this.orderLineService=new Te(e,i),this.executionService=new _e(e,i),this.tpslService=new Le(e,i);}async renderPositions(e){await this.chartReady(),await this.onDataLoaded(),this.positionLineService.renderPositions(e),this.orderLineService.updatePositions(e),this.tpslService.updatePositions(e);}async renderPendingOrders(e){await this.chartReady(),this.orderLineService.renderPendingOrders(e);}async renderFilledOrders(e,t){await this.chartReady(),await this.onDataLoaded(),this.executionService.renderExecutions(e,t);}remove(){this.orderLineService.removeAll(),this.positionLineService.removePositions(),this.executionService.destroy();}onDataLoaded(){return this.instance.activeChart().symbolExt()?Promise.resolve():new Promise(e=>this.instance.activeChart().onDataLoaded().subscribe(null,()=>{e();},true))}chartReady(){return new Promise(e=>this.instance.onChartReady(()=>{try{this.instance.activeChart().dataReady(()=>e());}catch(t){t.toString().includes("tradingViewApi");}}))}};function et(r,e){let[t,i]=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],y=m("quote_dp"),[g]=useOrderStream({symbol:r,status:OrderStatus.FILLED,size:500}),b=useRef((S,v,A,F)=>{o.current&&o.current.remove(),o.current=new Oe(S,v,A),i(o.current);}),z=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 S=(a??[]).filter(v=>v.symbol===r).map(v=>({symbol:v.symbol,open:v.average_open_price,balance:v.position_qty,closablePosition:9999,unrealPnl:v.unrealized_pnl??0,interest:0,unrealPnlDecimal:2,basePriceDecimal:4}));t?.renderPositions(S);},[t,a,r,e,s]),useEffect(()=>{if(!e||!e.buySell){t?.renderFilledOrders([],6);return}let S=g?.filter(v=>v.symbol===r);t?.renderFilledOrders(S??[],y??6);},[t,g,r,y,e]),useEffect(()=>{let S=[],v=[],A=[],F=[],B=[],U=[];if(s.status<AccountStatusEnum.EnableTrading&&s.status!==AccountStatusEnum.EnableTradingWithoutConnected){t?.renderPendingOrders([]);return}let ne=(a??[]).find(C=>C.symbol===r);l?.forEach(C=>{if(r===C.symbol){if(!C.algo_order_id)A.push(C);else if(C.algo_order_id)if(C.algo_type==="POSITIONAL_TP_SL")for(let T of C.child_orders)T.root_algo_order_algo_type=C.algo_type,T.trigger_price&&T.status!==OrderStatus.FILLED&&v.push(T);else if(C.algo_type==="TP_SL"){if(ne)for(let T of C.child_orders)T.root_algo_order_algo_type=C.algo_type,T.position_qty=ne.position_qty,T.trigger_price&&T.status!==OrderStatus.FILLED&&S.push(T);}else C.algo_type==="STOP_LOSS"||C.algo_type==="TAKE_PROFIT"?F.push(C):C.algo_type==="BRACKET"?B.push(C):C.algo_type==="TRAILING_STOP"&&C.is_activated&&C.extreme_price&&U.push(C);}}),e&&(e.positionTpsl||(v=[]),e.tpsl||(S=[]),e.limitOrders||(A=[],B=[]),e.stopOrders||(F=[]),e.trailingStop||(U=[])),t?.renderPendingOrders(S.concat(v).concat(A).concat(F).concat(B).concat(U));},[t,l,r,e,a,s.status]),[b.current,z.current]}function Wi(r){r.setBrokerConnectionAdapter=function(e){let t={subscribe:()=>{},unsubscribe:()=>{},unsubscribeAll:()=>{}};Object.defineProperty(e,"_ordersCache",{get:function(){return {start:()=>{},stop:()=>{},update:()=>{},partialUpdate:()=>{},fullUpdate:()=>{},getObjects:async()=>[],updateDelegate:t,partialUpdateDelegate:t}},set:()=>{}}),e._waitForOrderModification=async()=>true,this._adapter=e;};}function Qi(r,e){r.onChartReady(()=>{e.silentOrdersPlacement().subscribe(t=>{t||(e.silentOrdersPlacement().setValue(true),r&&(r._iFrame.contentDocument.querySelector(".wrapper-3X2QgaDd").className="wrapper-3X2QgaDd highButtons-3X2QgaDd"),e.sellBuyButtonsVisibility()?.setValue(false));});});}function tt(r,e){Wi(e),Qi(r,e);}var Yt=(r,e)=>new Promise(t=>{let i=r.querySelector(e);i&&t(i);let o=new MutationObserver(()=>{let s=r.querySelector(e);s&&(t(s),o.disconnect());});o.observe(r,{childList:true,subtree:true});});var we=class{constructor({iframeDocument:e}){this.iframeDocument=e;}defaultHack(){this.showFavoriteStarByDefault();}showFavoriteStarByDefault(){Yt(this.iframeDocument,".dropdown-2R6OKuTS").then(()=>{this.iframeDocument.querySelectorAll(".toolbox-2IihgTnv.showOnHover-2IihgTnv").forEach(t=>{t.style.opacity="1";});});}};var $i=r=>{let e=["header_symbol_search","volume_force_overlay","trading_account_manager","drawing_templates","open_account_manager","right_toolbar","support_multicharts","header_layouttoggle","order_panel","order_info","trading_notifications","display_market_status","broker_button","add_to_watchlist","chart_crosshair_menu","header_fullscreen_button","header_widget"];return r===3&&(e=[...e,"left_toolbar","timeframes_toolbar","go_to_date","timezone_menu","create_volume_indicator_by_default","buy_sell_buttons"]),r===0?e=[...e,"header_widget","left_toolbar","timeframes_toolbar","buy_sell_buttons"]:r===1&&(e=[...e,"left_toolbar","timeframes_toolbar","buy_sell_buttons"]),e};function rt(r,e){return {...r,disabled_features:$i(e),enabled_features:["hide_left_toolbar_by_default","order_panel_close_button","iframe_loading_compatibility_mode"],auto_save_delay:.1,broker_config:{configFlags:{supportStopLimitOrders:true,supportReversePosition:false}}}}var it=r=>`${r}_adapter`,Re={"trading.chart.proterty":JSON.stringify({showSellBuyButtons:0,noConfirmEnabled:1,qweqrq:0,showPricesWithZeroVolume:1,showSpread:1,orderExecutedSoundParams:'{"enabled":0,"name":"alert/alarm_clock"}'}),"hint.startFocusedZoom":"true"},D=new Map;var Zi=(r,e,t)=>{let i=it(r);try{let o=e,s=o?JSON.parse(o):void 0,n=t?JSON.parse(t):Re;return o&&D.set(r,o),t&&D.set(i,t),{savedData:s,adapterSetting:n}}catch{}return {savedData:void 0,adapterSetting:Re}},Jt=async(r,e)=>{let t=it(r),i=localStorage.getItem(r)||"",o=localStorage.getItem(t)||"";try{if(D.has(r)&&D.has(t))return {savedData:JSON.parse(D.get(r)),adapterSetting:JSON.parse(D.get(t))}}catch{}return Zi(r,i,o)},Xt=async(r,e,t)=>{e&&(localStorage.setItem(r,e),D.set(r,e));},er=async(r,e,t)=>{let i=it(r);e&&(localStorage.setItem(i,e),D.set(i,e));};var tr=(r,e)=>{let t=null,i=(...o)=>{t&&window.clearTimeout(t),t=setTimeout(()=>{r(...o);},e);};return i.cancel=()=>{t&&window.clearTimeout(t),t=null;},i},zi="chartProp_default",rr=300,Ee=class{constructor(e){this._instance=null;this._onClick=null;this._datafeed=null;this._chartKey=zi;this._adapterSetting=Re;this._savedData=null;this._isLoggedIn=false;this.debounceSaveChart=tr(()=>{try{this._instance?.save(e=>{Object.is(this._savedData,e)||(this._savedData=e,Xt(this._chartKey,JSON.stringify(e),this._isLoggedIn));});}catch{}},rr*2);this.debounceSaveChartAdapterSetting=tr(()=>{er(this._chartKey,JSON.stringify(this._adapterSetting),this._isLoggedIn);},rr);this._create(e);}remove(){this.unsubscribeClick(),this._datafeed?.remove(),this._broker?.remove(),this._instance?.remove(),this.debounceSaveChart.cancel(),this.debounceSaveChartAdapterSetting.cancel();}updateOverrides(e){this.instance&&this.instance.applyOverrides(e);}setSymbol(e,t,i){try{this._instance?.onChartReady(()=>{let o=t??this._instance?.symbolInterval()?.interval;o||(o=1),this._instance?.setSymbol(e,o,i);});}catch{}}executeActionById(e){try{this._instance?.onChartReady(()=>{this._instance?.activeChart().executeActionById(e);});}catch{}}changeLineType(e){try{this._instance?.onChartReady(()=>{this._instance?.activeChart().setChartType(e);});}catch{}}subscribeClick(e){this._onClick=e,this._instance?.onChartReady(()=>{this._instance?._iFrame.contentDocument?.addEventListener("click",this._onClick);});}unsubscribeClick(){this._instance?._iFrame.contentDocument?.removeEventListener("click",this._onClick);}get instance(){return this._instance}chartHack(){this._instance?.onChartReady(()=>{let e=this._instance._iFrame.contentWindow.document;new we({iframeDocument:e}).defaultHack();});}subscribeAutoSave(){this._instance?.onChartReady(()=>{this._instance?.subscribe("onAutoSaveNeeded",()=>{this.debounceSaveChart();}),this._instance?.activeChart().onVisibleRangeChanged().subscribe(null,()=>{this.debounceSaveChart();});});}async _create({options:e,chartKey:t,mode:i,onClick:o}){let s=e.getBroker,n={fullscreen:e.fullscreen??true,autosize:e.autosize??false,timezone:e.timezone,symbol:e.symbol,library_path:e.libraryPath,interval:e.interval??"1",custom_css_url:e.customCssUrl,custom_font_family:e.customFontFamily,datafeed:e.datafeed,studies_overrides:e.studiesOverrides,locale:e.locale,theme:e.theme,loading_screen:e.loadingScreen,overrides:e.overrides,container:e.container,favorites:{intervals:["1","3","5","15","30","60","240","1D","1W","1M"],chartTypes:["Area","Line"]},broker_factory:s?l=>(this._broker&&this._broker.remove(),this._broker=s(this._instance,l),this._broker):void 0};this._datafeed=e.datafeed,t&&(this._chartKey=t);let{savedData:a,adapterSetting:c}=await Jt(this._chartKey,this._isLoggedIn);this._adapterSetting=c,this._savedData=a,this._instance=new TradingView.widget({...rt(n,i),interval:c["chart.lastUsedTimeBasedResolution"]??n.interval,saved_data:a,settings_adapter:{initialSettings:c,setValue:(l,u)=>{this._adapterSetting={...this._adapterSetting,[l]:u},this.debounceSaveChartAdapterSetting();},removeValue:()=>{}}}),this._instance.onChartReady(()=>{e.symbol&&this._instance?.activeChart().symbol()!==I(e.symbol)&&this.setSymbol(e.symbol);}),this.subscribeAutoSave(),this.subscribeClick(o),this.chartHack();}};var ao="SDK_Tradingview",lo="SDK_Moblie_Tradingview",co=r=>r?lo:ao,uo=r=>r==="id"?"id_ID":r;function at(r){let{scriptSRC:e,libraryPath:t,customCssUrl:i,overrides:o,studiesOverrides:s,symbol:n,theme:a,loadingScreen:c,mode:l,colorConfig:u,locale:m=uo,classNames:y}=r,g=useLocaleCode(),b=useRef(null),z=useConfig("apiBaseUrl"),{state:S}=useAccount(),[v,A]=useState(OrderSide.SELL),F=useSymbolsInfo(),[B,U]=useLocalStorage(TradingviewFullscreenKey,false),{onSubmit:ne,submitting:C}=useOrderEntry_deprecated({symbol:n??"",side:v,order_type:OrderType.MARKET},{watchOrderbook:true}),[T,Vr]=useState(()=>{let d=localStorage.getItem(N.displayControlSetting);return d?JSON.parse(d):{position:true,buySell:true,limitOrders:true,stopOrders:true,tpsl:true,positionTpsl:true,trailingStop:true}}),[Ct,Nr]=useState(()=>{let d=localStorage.getItem(N.interval);return d||"15"}),[Hr,Fr]=useState(()=>{let d=localStorage.getItem(N.lineType);return d||"1"}),De=useMediaQuery(MEDIA_TABLET),Ae=useMemo(()=>Object.assign({},It,u??{}),[u]),Ur=useMemo(()=>typeof c=="object"?c:{backgroundColor:Ne},[c]),se=useWS(),[j,Kr]=useState(false),qr=d=>{let ae=F[n];if(!ae)return;let le=new Decimal(d.balance).greaterThan(0)?OrderSide.SELL:OrderSide.BUY,St={order_quantity:new Decimal(d.balance).abs().toNumber(),symbol:n,order_type:OrderType.MARKET,side:le,reduce_only:true};A(le),modal.show("MarketCloseConfirmID",{base:ae("base"),quantity:d.balance,onConfirm:async()=>ne(St).catch(Y=>{typeof Y=="string"?toast.error(Y):toast.error(Y.message);}),submitting:C});},E=useRef(null),vt=useMemo(()=>!(S.status<AccountStatusEnum.EnableTrading&&S.status!==AccountStatusEnum.EnableTradingWithoutConnected),[S]),_t=Nt({closeConfirm:qr,colorConfig:Ae,onToast:toast,symbol:n??"",mode:l}),[Gr,Wr]=et(n,T),Qr=()=>{U(!B),r.onFullScreenChange?.(!B);},$r=d=>{b.current&&(localStorage.setItem(N.interval,d),Nr(d),b.current?.setSymbol(n??"",d));},Zr=d=>{b.current&&(localStorage.setItem(N.lineType,d),Fr(d),b.current?.changeLineType(Number(d)));},zr=d=>{localStorage.setItem(N.displayControlSetting,JSON.stringify(d)),Vr(d);},jr=()=>{b.current&&b.current.executeActionById("chartProperties");},Yr=()=>{b.current&&b.current.executeActionById("insertIndicator");};return useEffect(()=>{if(e&&E.current&&!j){let d=document.createElement("script");d.setAttribute("data-nscript","afterInteractive"),d.src=e,d.async=true,d.type="text/javascript",d.onload=()=>{Kr(true);},d.onerror=()=>{},E.current.appendChild(d);}},[E,j,e]),useEffect(()=>{if(!n||!j||!e)return;let d=Lt(Ae,De),ae=o?Object.assign({},d.overrides,o):d.overrides,le=s?Object.assign({},d.studiesOverrides,s):d.studiesOverrides;if(E.current){let Y={options:{fullscreen:false,autosize:true,symbol:ue(n),locale:typeof m=="function"?m(g):m,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,container:E.current,libraryPath:t,customCssUrl:i,interval:Ct??"1",theme:a??"dark",loadingScreen:Ur??{},overrides:ae,studiesOverrides:le,datafeed:new ye(z,se),contextMenu:{items_processor:async Be=>Be},getBroker:(Be,Tt)=>(tt(Be,Tt),Ot(Tt,_t))},chartKey:co(De),mode:l,onClick:()=>{}};b.current=new Ee(Y);}return ()=>{b.current?.remove();}},[j,De,l,b,E,j,e,Ae,m,g]),useEffect(()=>{se.on("status:change",d=>{!d.isPrivate&&d.isReconnect&&typeof window.onResetCacheNeededCallback=="function"&&(window.onResetCacheNeededCallback(),b.current?.instance&&b.current?.instance.activeChart()?.resetData());},"tradingview");},[se]),useEffect(()=>(b.current&&b.current?.instance&&b.current?.instance?.onChartReady(()=>{vt&&b.current?.instance&&Gr(b.current.instance,void 0,_t,E.current);}),()=>{Wr();}),[b.current,vt]),useEffect(()=>{if(!n||!b.current)return;b.current?.setSymbol(n);let d=new G(se);return d.subscribeSymbol(n),()=>{d.unsubscribeKline(n);}},[n]),{tradingViewScriptSrc:e,chartRef:E,changeDisplaySetting:zr,displayControlState:T,interval:Ct,changeInterval:$r,lineType:Hr,changeLineType:Zr,openChartSetting:jr,openChartIndicators:Yr,symbol:n,onFullScreenChange:Qr,classNames:y,fullscreen:B}}Z();var yr=r=>{let{url:e,children:t}=r;return jsx("span",{onClick:()=>window.open(e),className:"oui-cursor-pointer oui-px-0.5 oui-text-primary-light oui-underline",children:t})},Cr=()=>{let{t:r}=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(yr,{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(yr,{url:"https://orderly.network/docs/sdks/react/components/trading#tradingviewconfig"},"tradingview-config")]})})]})})};var go=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}),vr=go;var ln=R.lazy(()=>Promise.resolve().then(()=>(Or(),Lr))),Br=R.lazy(()=>Promise.resolve().then(()=>(Rr(),wr)).then(r=>({default:r.TimeInterval}))),cn=R.lazy(()=>Promise.resolve().then(()=>(ft(),ht)).then(r=>({default:r.MobileDisplayControl}))),un=R.lazy(()=>Promise.resolve().then(()=>(ft(),ht)).then(r=>({default:r.DesktopDisplayControl}))),bt=({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}),dn=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"})}),pn=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"})}),yt=forwardRef((r,e)=>{let{chartRef:t,interval:i,changeDisplaySetting:o,displayControlState:s,tradingViewScriptSrc:n,changeInterval:a,lineType:c,changeLineType:l,openChartSetting:u,openChartIndicators:m,onFullScreenChange:y}=r,g=useMediaQuery(MEDIA_TABLET);return jsx("div",{ref:e,className:cn$1("oui-relative oui-size-full",r.classNames?.root),children:n?jsxs("div",{className:cn$1("oui-absolute oui-inset-0 oui-z-[1] oui-flex oui-flex-col",r.classNames?.content),children:[jsx(vr,{children:g?jsxs(Flex,{gapX:2,width:"100%",justify:"between",className:"oui-hide-scrollbar oui-overflow-x-scroll",children:[jsx(R.Suspense,{fallback:null,children:jsx(Br,{interval:i??"15",changeInterval:a})}),jsx(bt,{onClick:m,children:jsx(lt,{})}),jsx(R.Suspense,{fallback:null,children:jsx(cn,{displayControlState:s,changeDisplayControlState:o})})]}):jsxs(Flex,{justify:"between",itemAlign:"center",width:"100%",children:[jsxs(Flex,{children:[jsx(R.Suspense,{fallback:null,children:jsx(Br,{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(un,{displayControlState:s,changeDisplayControlState:o})}),jsx(bt,{onClick:m,children:jsx(lt,{})}),jsx(R.Suspense,{fallback:null,children:jsx(ln,{lineType:c,changeLineType:l})}),jsx(bt,{onClick:u,children:jsx(ar,{})})]})]}),jsx(Flex,{children:r.fullscreen?jsx(dn,{className:"oui-text-base-contrast-54 hover:oui-text-base-contrast oui-cursor-pointer",onClick:y}):jsx(pn,{className:"oui-text-base-contrast-54 hover:oui-text-base-contrast oui-cursor-pointer",onClick:y})})]})}),jsx("div",{ref:t,className:"oui-size-full oui-overflow-hidden"})]}):jsx(Cr,{})})});var gn=forwardRef((r,e)=>{let t=at(r);return jsx(yt,{...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 { yt as TradingviewUI, gn as TradingviewWidget, at 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: "#0C3E3A",
913
+ volumeDownColor: "#5A1E36",
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
+ };
938
+ const studiesOverrides = {
939
+ "volume.volume.color.0": colorConfig.volumeDownColor,
940
+ "volume.volume.color.1": colorConfig.volumeUpColor
941
+ };
942
+ return {
943
+ overrides,
944
+ studiesOverrides
945
+ };
946
+ };
947
+ var EXCHANGE = "Orderly";
948
+ var withoutExchangePrefix = (symbol) => symbol.includes(":") ? symbol.split(":")[1] : symbol;
949
+ var withExchangePrefix = (symbol) => symbol.startsWith(`${EXCHANGE}:`) ? symbol : `${EXCHANGE}:${symbol}`;
950
+ var getBrokerAdapter = (host, broker) => {
951
+ let _symbolInfo;
952
+ const getOrderCombinationType = (orderType) => {
953
+ return [
954
+ null,
955
+ "limit",
956
+ "MARKET" /* MARKET */,
957
+ "STOP_MARKET" /* STOP_MARKET */,
958
+ "STOP_LIMIT" /* STOP_LIMIT */
959
+ ][orderType];
960
+ };
961
+ return {
962
+ symbolInfo: async (symbol2) => {
963
+ _symbolInfo = broker.getSymbolInfo(withoutExchangePrefix(symbol2));
964
+ return {
965
+ qty: {
966
+ min: _symbolInfo?.baseMin ?? 0,
967
+ max: _symbolInfo?.baseMax ?? 0,
968
+ step: _symbolInfo?.baseTick ?? 0
969
+ },
970
+ pipValue: 0,
971
+ pipSize: _symbolInfo?.quoteTick ?? 0,
972
+ minTick: _symbolInfo?.quoteTick ?? 0,
973
+ description: ""
974
+ };
975
+ },
976
+ placeOrder: async (order) => {
977
+ const side = ["SELL" /* SELL */, "BUY" /* BUY */][+(order.side > 0)];
978
+ const quantity = order.qty.toString();
979
+ (order.limitPrice ?? 0).toString();
980
+ (order.stopPrice ?? 0).toString();
981
+ const symbol2 = withoutExchangePrefix(order.symbol);
982
+ const orderCombinationType = getOrderCombinationType(order.type);
983
+ if (orderCombinationType === "MARKET" /* MARKET */) {
984
+ broker.sendMarketOrder({ side, order_quantity: quantity, symbol: symbol2, order_type: OrderType.MARKET });
985
+ }
986
+ },
987
+ orders: () => [],
988
+ positions: () => [],
989
+ executions: () => [],
990
+ connectionStatus: () => 1,
991
+ chartContextMenuActions: (context) => host.defaultContextMenuActions(context),
992
+ isTradable: async () => true,
993
+ accountManagerInfo: () => ({}),
994
+ currentAccount: () => "1",
995
+ accountsMetainfo: async () => [{ id: "1" }],
996
+ remove: () => host?.silentOrdersPlacement().unsubscribe()
997
+ };
998
+ };
999
+ var getBrokerAdapter_default = getBrokerAdapter;
1000
+ function logMessage(message) {
1001
+ }
1002
+ function getErrorMessage(error) {
1003
+ if (error === void 0) {
1004
+ return "";
1005
+ }
1006
+ if (typeof error === "string") {
1007
+ return error;
1008
+ }
1009
+ return error.message;
1010
+ }
1011
+
1012
+ // src/tradingviewAdapter/datafeed/history-provider.ts
1013
+ var HistoryProvider = class {
1014
+ constructor(datafeedUrl, requester, limitedServerResponse) {
1015
+ this._datafeedUrl = datafeedUrl;
1016
+ this._requester = requester;
1017
+ this._limitedServerResponse = limitedServerResponse;
1018
+ }
1019
+ getBars(symbolInfo, resolution, periodParams) {
1020
+ const requestParams = {
1021
+ symbol: symbolInfo.ticker || "",
1022
+ resolution,
1023
+ from: periodParams.from,
1024
+ to: periodParams.to
1025
+ };
1026
+ if (periodParams.countBack !== void 0) {
1027
+ requestParams.countback = periodParams.countBack;
1028
+ }
1029
+ if (symbolInfo.currency_code !== void 0) {
1030
+ requestParams.currencyCode = symbolInfo.currency_code;
1031
+ }
1032
+ if (symbolInfo.unit_id !== void 0) {
1033
+ requestParams.unitId = symbolInfo.unit_id;
1034
+ }
1035
+ return new Promise(
1036
+ async (resolve, reject) => {
1037
+ try {
1038
+ const initialResponse = await this._requester.sendRequest(
1039
+ this._datafeedUrl,
1040
+ "history",
1041
+ requestParams
1042
+ );
1043
+ const result = this._processHistoryResponse(initialResponse);
1044
+ if (this._limitedServerResponse) {
1045
+ await this._processTruncatedResponse(result, requestParams);
1046
+ }
1047
+ resolve(result);
1048
+ } catch (e) {
1049
+ if (e instanceof Error || typeof e === "string") {
1050
+ const reasonString = getErrorMessage(e);
1051
+ reject(reasonString);
1052
+ }
1053
+ }
1054
+ }
1055
+ );
1056
+ }
1057
+ async _processTruncatedResponse(result, requestParams) {
1058
+ let lastResultLength = result.bars.length;
1059
+ try {
1060
+ while (this._limitedServerResponse && this._limitedServerResponse.maxResponseLength > 0 && this._limitedServerResponse.maxResponseLength === lastResultLength && requestParams.from < requestParams.to) {
1061
+ if (requestParams.countback) {
1062
+ requestParams.countback = requestParams.countback - lastResultLength;
1063
+ }
1064
+ if (this._limitedServerResponse.expectedOrder === "earliestFirst") {
1065
+ requestParams.from = Math.round(
1066
+ result.bars[result.bars.length - 1].time / 1e3
1067
+ );
1068
+ } else {
1069
+ requestParams.to = Math.round(result.bars[0].time / 1e3);
1070
+ }
1071
+ const followupResponse = await this._requester.sendRequest(
1072
+ this._datafeedUrl,
1073
+ "history",
1074
+ requestParams
1075
+ );
1076
+ const followupResult = this._processHistoryResponse(followupResponse);
1077
+ lastResultLength = followupResult.bars.length;
1078
+ if (this._limitedServerResponse.expectedOrder === "earliestFirst") {
1079
+ if (followupResult.bars[0].time === result.bars[result.bars.length - 1].time) {
1080
+ followupResult.bars.shift();
1081
+ }
1082
+ result.bars.push(...followupResult.bars);
1083
+ } else {
1084
+ if (followupResult.bars[followupResult.bars.length - 1].time === result.bars[0].time) {
1085
+ followupResult.bars.pop();
1086
+ }
1087
+ result.bars.unshift(...followupResult.bars);
1088
+ }
1089
+ }
1090
+ } catch (e) {
1091
+ if (e instanceof Error || typeof e === "string") {
1092
+ getErrorMessage(e);
1093
+ }
1094
+ }
1095
+ }
1096
+ _processHistoryResponse(response) {
1097
+ if (response.s !== "ok" && response.s !== "no_data") {
1098
+ throw new Error(response.errmsg);
1099
+ }
1100
+ const bars = [];
1101
+ const meta = {
1102
+ noData: false
1103
+ };
1104
+ if (response.s === "no_data") {
1105
+ meta.noData = true;
1106
+ meta.nextTime = response.nextTime;
1107
+ } else {
1108
+ const volumePresent = response.v !== void 0;
1109
+ const ohlPresent = response.o !== void 0;
1110
+ for (let i = 0; i < response.t.length; ++i) {
1111
+ const barValue = {
1112
+ time: response.t[i] * 1e3,
1113
+ close: parseFloat(response.c[i]),
1114
+ open: parseFloat(response.c[i]),
1115
+ high: parseFloat(response.c[i]),
1116
+ low: parseFloat(response.c[i])
1117
+ };
1118
+ if (ohlPresent) {
1119
+ barValue.open = parseFloat(
1120
+ response.o[i]
1121
+ );
1122
+ barValue.high = parseFloat(
1123
+ response.h[i]
1124
+ );
1125
+ barValue.low = parseFloat(response.l[i]);
1126
+ }
1127
+ if (volumePresent) {
1128
+ barValue.volume = parseFloat(
1129
+ response.v[i]
1130
+ );
1131
+ }
1132
+ bars.push(barValue);
1133
+ }
1134
+ }
1135
+ return {
1136
+ bars,
1137
+ meta
1138
+ };
1139
+ }
1140
+ };
1141
+
1142
+ // src/tradingviewAdapter/datafeed/requester.ts
1143
+ var Requester = class {
1144
+ constructor(headers) {
1145
+ if (headers) {
1146
+ this._headers = headers;
1147
+ }
1148
+ }
1149
+ sendRequest(datafeedUrl, urlPath, params) {
1150
+ if (params !== void 0) {
1151
+ const paramKeys = Object.keys(params);
1152
+ if (paramKeys.length !== 0) {
1153
+ urlPath += "?";
1154
+ }
1155
+ urlPath += paramKeys.map((key) => {
1156
+ return `${encodeURIComponent(key)}=${encodeURIComponent(
1157
+ params[key].toString()
1158
+ )}`;
1159
+ }).join("&");
1160
+ }
1161
+ const options = { credentials: "same-origin" };
1162
+ if (this._headers !== void 0) {
1163
+ options.headers = this._headers;
1164
+ }
1165
+ return fetch(`${datafeedUrl}/${urlPath}`, options).then((response) => response.text()).then((responseTest) => JSON.parse(responseTest));
1166
+ }
1167
+ };
1168
+
1169
+ // src/tradingviewAdapter/datafeed/symbol-storage.ts
1170
+ function extractField(data, field, arrayIndex, valueIsArray) {
1171
+ const value = data[field];
1172
+ if (Array.isArray(value) && (!valueIsArray || Array.isArray(value[0]))) {
1173
+ return value[arrayIndex];
1174
+ }
1175
+ return value;
1176
+ }
1177
+ function symbolKey(symbol, currency, unit) {
1178
+ return symbol + (currency !== void 0 ? "_%|#|%_" + currency : "") + (unit !== void 0 ? "_%|#|%_" + unit : "");
1179
+ }
1180
+ var SymbolsStorage = class {
1181
+ constructor(datafeedUrl, datafeedSupportedResolutions, requester) {
1182
+ this._exchangesList = ["Orderly"];
1183
+ this._symbolsInfo = {};
1184
+ this._symbolsList = [];
1185
+ this._datafeedUrl = datafeedUrl;
1186
+ this._datafeedSupportedResolutions = datafeedSupportedResolutions;
1187
+ this._requester = requester;
1188
+ this._readyPromise = this._init();
1189
+ this._readyPromise.catch((error) => {
1190
+ });
1191
+ }
1192
+ // BEWARE: this function does not consider symbol's exchange
1193
+ resolveSymbol(symbolName, currencyCode, unitId) {
1194
+ return this._readyPromise.then(() => {
1195
+ const symbolInfo = this._symbolsInfo[symbolKey(symbolName, currencyCode, unitId)];
1196
+ if (symbolInfo === void 0) {
1197
+ return Promise.reject("invalid symbol");
1198
+ }
1199
+ return Promise.resolve(symbolInfo);
1200
+ });
1201
+ }
1202
+ searchSymbols(searchString, exchange, symbolType, maxSearchResults) {
1203
+ return this._readyPromise.then(() => {
1204
+ const weightedResult = [];
1205
+ const queryIsEmpty = searchString.length === 0;
1206
+ searchString = searchString.toUpperCase();
1207
+ for (const symbolName of this._symbolsList) {
1208
+ const symbolInfo = this._symbolsInfo[symbolName];
1209
+ if (symbolInfo === void 0) {
1210
+ continue;
1211
+ }
1212
+ if (symbolType.length > 0 && symbolInfo.type !== symbolType) {
1213
+ continue;
1214
+ }
1215
+ if (exchange && exchange.length > 0 && symbolInfo.exchange !== exchange) {
1216
+ continue;
1217
+ }
1218
+ const positionInName = symbolInfo.name.toUpperCase().indexOf(searchString);
1219
+ const positionInDescription = symbolInfo.description.toUpperCase().indexOf(searchString);
1220
+ if (queryIsEmpty || positionInName >= 0 || positionInDescription >= 0) {
1221
+ const alreadyExists = weightedResult.some(
1222
+ (item) => item.symbolInfo === symbolInfo
1223
+ );
1224
+ if (!alreadyExists) {
1225
+ const weight = positionInName >= 0 ? positionInName : 8e3 + positionInDescription;
1226
+ weightedResult.push({ symbolInfo, weight });
1227
+ }
1228
+ }
1229
+ }
1230
+ const result = weightedResult.sort(
1231
+ (item1, item2) => item1.weight - item2.weight
1232
+ ).slice(0, maxSearchResults).map((item) => {
1233
+ const symbolInfo = item.symbolInfo;
1234
+ return {
1235
+ symbol: symbolInfo.name,
1236
+ full_name: `${symbolInfo.exchange}:${symbolInfo.name}`,
1237
+ description: symbolInfo.description,
1238
+ exchange: symbolInfo.exchange,
1239
+ params: [],
1240
+ type: symbolInfo.type,
1241
+ ticker: symbolInfo.name
1242
+ };
1243
+ });
1244
+ return Promise.resolve(result);
1245
+ });
1246
+ }
1247
+ _init() {
1248
+ const promises = [];
1249
+ const alreadyRequestedExchanges = {};
1250
+ for (const exchange of this._exchangesList) {
1251
+ if (alreadyRequestedExchanges[exchange]) {
1252
+ continue;
1253
+ }
1254
+ alreadyRequestedExchanges[exchange] = true;
1255
+ promises.push(this._requestExchangeData(exchange));
1256
+ }
1257
+ return Promise.all(promises).then(() => {
1258
+ this._symbolsList.sort();
1259
+ });
1260
+ }
1261
+ _requestExchangeData(exchange) {
1262
+ return new Promise(
1263
+ (resolve, reject) => {
1264
+ this._requester.sendRequest(this._datafeedUrl, "symbol_info", {
1265
+ group: exchange
1266
+ }).then((response) => {
1267
+ try {
1268
+ this._onExchangeDataReceived(exchange, response);
1269
+ } catch (error) {
1270
+ reject(
1271
+ error instanceof Error ? error : new Error(`SymbolsStorage: Unexpected exception ${error}`)
1272
+ );
1273
+ return;
1274
+ }
1275
+ resolve();
1276
+ }).catch((reason) => {
1277
+ logMessage(
1278
+ `SymbolsStorage: Request data for exchange '${exchange}' failed, reason=${getErrorMessage(
1279
+ reason
1280
+ )}`
1281
+ );
1282
+ resolve();
1283
+ });
1284
+ }
1285
+ );
1286
+ }
1287
+ _onExchangeDataReceived(exchange, data) {
1288
+ let symbolIndex = 0;
1289
+ try {
1290
+ const symbolsCount = data.symbol.length;
1291
+ const tickerPresent = data.ticker !== void 0;
1292
+ for (; symbolIndex < symbolsCount; ++symbolIndex) {
1293
+ const symbolName = data.symbol[symbolIndex];
1294
+ const listedExchange = extractField(
1295
+ data,
1296
+ "exchange-listed",
1297
+ symbolIndex
1298
+ );
1299
+ const tradedExchange = extractField(
1300
+ data,
1301
+ "exchange-traded",
1302
+ symbolIndex
1303
+ );
1304
+ const fullName = tradedExchange + ":" + symbolName;
1305
+ const currencyCode = extractField(data, "currency-code", symbolIndex);
1306
+ const unitId = extractField(data, "unit-id", symbolIndex);
1307
+ const ticker = tickerPresent ? extractField(data, "ticker", symbolIndex) : symbolName;
1308
+ const symbolInfo = {
1309
+ ticker,
1310
+ name: symbolName,
1311
+ base_name: [listedExchange + ":" + symbolName],
1312
+ listed_exchange: listedExchange,
1313
+ exchange: tradedExchange,
1314
+ currency_code: currencyCode,
1315
+ original_currency_code: extractField(
1316
+ data,
1317
+ "original-currency-code",
1318
+ symbolIndex
1319
+ ),
1320
+ unit_id: unitId,
1321
+ original_unit_id: extractField(data, "original-unit-id", symbolIndex),
1322
+ unit_conversion_types: extractField(
1323
+ data,
1324
+ "unit-conversion-types",
1325
+ symbolIndex,
1326
+ true
1327
+ ),
1328
+ description: extractField(data, "description", symbolIndex),
1329
+ has_intraday: definedValueOrDefault(
1330
+ extractField(data, "has-intraday", symbolIndex),
1331
+ false
1332
+ ),
1333
+ // show volume at the bottom by default: https://github.com/tradingview/charting_library/issues/8306
1334
+ visible_plots_set: definedValueOrDefault(
1335
+ extractField(data, "visible-plots-set", symbolIndex),
1336
+ "ohlcv"
1337
+ ),
1338
+ minmov: extractField(data, "minmovement", symbolIndex) || extractField(data, "minmov", symbolIndex) || 0,
1339
+ minmove2: extractField(data, "minmove2", symbolIndex) || extractField(data, "minmov2", symbolIndex),
1340
+ fractional: extractField(data, "fractional", symbolIndex),
1341
+ pricescale: extractField(data, "pricescale", symbolIndex),
1342
+ type: extractField(data, "type", symbolIndex),
1343
+ session: extractField(data, "session-regular", symbolIndex),
1344
+ session_holidays: extractField(data, "session-holidays", symbolIndex),
1345
+ corrections: extractField(data, "corrections", symbolIndex),
1346
+ timezone: extractField(data, "timezone", symbolIndex),
1347
+ supported_resolutions: definedValueOrDefault(
1348
+ extractField(data, "supported-resolutions", symbolIndex, true),
1349
+ this._datafeedSupportedResolutions
1350
+ ),
1351
+ has_daily: definedValueOrDefault(
1352
+ extractField(data, "has-daily", symbolIndex),
1353
+ true
1354
+ ),
1355
+ intraday_multipliers: definedValueOrDefault(
1356
+ extractField(data, "intraday-multipliers", symbolIndex, true),
1357
+ ["1", "5", "15", "30", "60"]
1358
+ ),
1359
+ has_weekly_and_monthly: extractField(
1360
+ data,
1361
+ "has-weekly-and-monthly",
1362
+ symbolIndex
1363
+ ),
1364
+ has_empty_bars: extractField(data, "has-empty-bars", symbolIndex),
1365
+ volume_precision: definedValueOrDefault(
1366
+ extractField(data, "volume-precision", symbolIndex),
1367
+ 0
1368
+ ),
1369
+ format: "price"
1370
+ };
1371
+ this._symbolsInfo[ticker] = symbolInfo;
1372
+ this._symbolsInfo[symbolName] = symbolInfo;
1373
+ this._symbolsInfo[fullName] = symbolInfo;
1374
+ if (currencyCode !== void 0 || unitId !== void 0) {
1375
+ this._symbolsInfo[symbolKey(ticker, currencyCode, unitId)] = symbolInfo;
1376
+ this._symbolsInfo[symbolKey(symbolName, currencyCode, unitId)] = symbolInfo;
1377
+ this._symbolsInfo[symbolKey(fullName, currencyCode, unitId)] = symbolInfo;
1378
+ }
1379
+ this._symbolsList.push(symbolName);
1380
+ }
1381
+ } catch (error) {
1382
+ throw new Error(
1383
+ `SymbolsStorage: API error when processing exchange ${exchange} symbol #${symbolIndex} (${data.symbol[symbolIndex]}): ${Object(error).message}`
1384
+ );
1385
+ }
1386
+ }
1387
+ };
1388
+ function definedValueOrDefault(value, defaultValue) {
1389
+ return value !== void 0 ? value : defaultValue;
1390
+ }
1391
+
1392
+ // src/tradingviewAdapter/datafeed/abstract-datafeed.ts
1393
+ var AbstractDatafeed = class {
1394
+ constructor(datafeedURL) {
1395
+ this._configuration = defaultConfiguration();
1396
+ this._symbolsStorage = null;
1397
+ this._datafeedURL = datafeedURL;
1398
+ this._requester = new Requester();
1399
+ this._historyProvider = new HistoryProvider(datafeedURL, this._requester);
1400
+ this._configurationReadyPromise = this._requestConfiguration().then(
1401
+ (configuration) => {
1402
+ if (configuration === null) {
1403
+ configuration = defaultConfiguration();
1404
+ }
1405
+ this._setupWithConfiguration(configuration);
1406
+ }
1407
+ );
1408
+ }
1409
+ getBars(symbolInfo, resolution, periodParams, onResult, onError) {
1410
+ this._historyProvider.getBars(symbolInfo, resolution, periodParams).then((result) => {
1411
+ onResult(result.bars, result.meta);
1412
+ }).catch(onError);
1413
+ }
1414
+ onReady(callback) {
1415
+ this._configurationReadyPromise.then(() => {
1416
+ callback(this._configuration);
1417
+ });
1418
+ }
1419
+ searchSymbols(userInput, exchange, symbolType, onResult) {
1420
+ if (this._symbolsStorage === null) {
1421
+ throw new Error("Datafeed: inconsistent configuration (symbols storage)");
1422
+ }
1423
+ this._symbolsStorage.searchSymbols(
1424
+ userInput,
1425
+ exchange,
1426
+ symbolType,
1427
+ 30 /* SearchItemsLimit */
1428
+ ).then(onResult).catch(onResult.bind(null, []));
1429
+ }
1430
+ resolveSymbol(symbolName, onResolve, onError, extension) {
1431
+ const currencyCode = extension && extension.currencyCode;
1432
+ const unitId = extension && extension.unitId;
1433
+ function onResultReady(symbolInfo) {
1434
+ onResolve(symbolInfo);
1435
+ }
1436
+ if (this._symbolsStorage === null) {
1437
+ throw new Error("Datafeed: inconsistent configuration (symbols storage)");
1438
+ }
1439
+ this._symbolsStorage.resolveSymbol(symbolName, currencyCode, unitId).then(onResultReady).catch(onError);
1440
+ }
1441
+ getMarks() {
1442
+ }
1443
+ getTimescaleMarks() {
1444
+ }
1445
+ getServerTime() {
1446
+ }
1447
+ _requestConfiguration() {
1448
+ return this._send("config").catch(
1449
+ (reason) => {
1450
+ logMessage(
1451
+ `Datafeed: Cannot get datafeed configuration - use default, error=${getErrorMessage(
1452
+ reason
1453
+ )}`
1454
+ );
1455
+ return null;
1456
+ }
1457
+ );
1458
+ }
1459
+ _send(urlPath, params) {
1460
+ return this._requester.sendRequest(this._datafeedURL, urlPath, params);
1461
+ }
1462
+ _setupWithConfiguration(configurationData) {
1463
+ this._configuration = configurationData;
1464
+ if (configurationData.exchanges === void 0) {
1465
+ configurationData.exchanges = [];
1466
+ }
1467
+ if (!configurationData.supports_search && !configurationData.supports_group_request) {
1468
+ throw new Error(
1469
+ "Unsupported datafeed configuration. Must either support search, or support group request"
1470
+ );
1471
+ }
1472
+ if (configurationData.supports_group_request || !configurationData.supports_search) {
1473
+ this._symbolsStorage = new SymbolsStorage(
1474
+ this._datafeedURL,
1475
+ configurationData.supported_resolutions || [],
1476
+ this._requester
1477
+ );
1478
+ }
1479
+ logMessage(
1480
+ `Datafeed: Initialized with ${JSON.stringify(configurationData)}`
1481
+ );
1482
+ }
1483
+ };
1484
+ function defaultConfiguration() {
1485
+ return {
1486
+ supports_search: false,
1487
+ supports_group_request: true,
1488
+ supported_resolutions: [
1489
+ "1",
1490
+ "3",
1491
+ "5",
1492
+ "15",
1493
+ "30",
1494
+ "60",
1495
+ "120",
1496
+ "240",
1497
+ "480",
1498
+ "720",
1499
+ "1D",
1500
+ "3D",
1501
+ "1W",
1502
+ "1M"
1503
+ ],
1504
+ supports_marks: false,
1505
+ supports_timescale_marks: false
1506
+ };
1507
+ }
1508
+
1509
+ // src/tradingviewAdapter/datafeed/eventBus.ts
1510
+ var MultiBroadcastEventBus = class {
1511
+ constructor() {
1512
+ this.subscribers = /* @__PURE__ */ new Map();
1513
+ }
1514
+ subscribe(eventName, callback) {
1515
+ if (!this.subscribers.has(eventName)) {
1516
+ this.subscribers.set(eventName, []);
1517
+ }
1518
+ const callbacks = this.subscribers.get(eventName);
1519
+ callbacks.push(callback);
1520
+ return () => {
1521
+ this.unsubscribe(eventName, callback);
1522
+ };
1523
+ }
1524
+ unsubscribe(eventName, callback) {
1525
+ if (this.subscribers.has(eventName)) {
1526
+ const callbacks = this.subscribers.get(eventName);
1527
+ this.subscribers.set(
1528
+ eventName,
1529
+ callbacks.filter((cb) => cb !== callback)
1530
+ );
1531
+ if (this.subscribers.get(eventName).length === 0) {
1532
+ this.subscribers.delete(eventName);
1533
+ }
1534
+ }
1535
+ }
1536
+ publish(eventName, data) {
1537
+ if (this.subscribers.has(eventName)) {
1538
+ const callbacks = this.subscribers.get(eventName);
1539
+ callbacks.forEach((callback) => {
1540
+ callback(data);
1541
+ });
1542
+ }
1543
+ }
1544
+ };
1545
+
1546
+ // src/utils/common.util.ts
1547
+ var mapResolution = (resolution) => {
1548
+ let time = "1d";
1549
+ switch (resolution) {
1550
+ case "1" /* RESOLUTION_1m */:
1551
+ time = "1m";
1552
+ break;
1553
+ case "3" /* RESOLUTION_3m */:
1554
+ time = "3m";
1555
+ break;
1556
+ case "5" /* RESOLUTION_5m */:
1557
+ time = "5m";
1558
+ break;
1559
+ case "15" /* RESOLUTION_15m */:
1560
+ time = "15m";
1561
+ break;
1562
+ case "30" /* RESOLUTION_30m */:
1563
+ time = "30m";
1564
+ break;
1565
+ case "60" /* RESOLUTION_60m */:
1566
+ time = "1h";
1567
+ break;
1568
+ case "120" /* RESOLUTION_120m */:
1569
+ time = "2h";
1570
+ break;
1571
+ case "240" /* RESOLUTION_240m */:
1572
+ time = "4h";
1573
+ break;
1574
+ case "480" /* RESOLUTION_480m */:
1575
+ time = "8h";
1576
+ break;
1577
+ case "720" /* RESOLUTION_720m */:
1578
+ time = "12h";
1579
+ break;
1580
+ case "D" /* RESOLUTION_D */:
1581
+ case "1D" /* RESOLUTION_1D */:
1582
+ time = "1d";
1583
+ break;
1584
+ case "3D" /* RESOLUTION_3D */:
1585
+ time = "3d";
1586
+ break;
1587
+ case "1W" /* RESOLUTION_1W */:
1588
+ time = "1w";
1589
+ break;
1590
+ case "1M" /* RESOLUTION_1M */:
1591
+ time = "1M ";
1592
+ break;
1593
+ }
1594
+ return time;
1595
+ };
1596
+ var TradingViewSDKLocalstorageKey = {
1597
+ interval: "TradingviewSDK.lastUsedTimeBasedResolution",
1598
+ lineType: "TradingviewSDK.lastUsedStyle",
1599
+ displayControlSetting: "TradingviewSDK.displaySetting"
1600
+ };
1601
+
1602
+ // src/tradingviewAdapter/datafeed/websocket.service.ts
1603
+ var getKlineKey = (symbol, type) => `${symbol}kline_${type}`;
1604
+ var getSymbolTopics = (symbol) => {
1605
+ const symbolTopics = ["trade"];
1606
+ return symbolTopics.map((topic) => `${symbol}@${topic}`);
1607
+ };
1608
+ var _WebsocketService = class _WebsocketService {
1609
+ constructor(ws) {
1610
+ this.klineSubscribeIdMap = /* @__PURE__ */ new Map();
1611
+ this.klineOnTickCallback = /* @__PURE__ */ new Map();
1612
+ this.subscribeCachedTopics = /* @__PURE__ */ new Map();
1613
+ this.wsInstance = null;
1614
+ this.klineData = /* @__PURE__ */ new Map();
1615
+ if (!_WebsocketService._created) {
1616
+ this.wsInstance = ws;
1617
+ _WebsocketService._instance = this;
1618
+ _WebsocketService._created = true;
1619
+ }
1620
+ return _WebsocketService._instance;
1621
+ }
1622
+ subscribeKline(subscribeId, symbol, resolution, onTickCallback) {
1623
+ const time = mapResolution(resolution);
1624
+ this.klineSubscribeIdMap.set(subscribeId, { symbol, resolution });
1625
+ const klineKey = getKlineKey(symbol, time);
1626
+ if (this.klineOnTickCallback.has(klineKey)) {
1627
+ const value = this.klineOnTickCallback.get(klineKey);
1628
+ value[subscribeId] = onTickCallback;
1629
+ } else {
1630
+ this.klineOnTickCallback.set(klineKey, {
1631
+ [subscribeId]: onTickCallback
1632
+ });
1633
+ const unsub = this.wsInstance?.subscribe(
1634
+ {
1635
+ event: "subscribe",
1636
+ topic: `${symbol}@kline_${time}`,
1637
+ id: `${symbol}@kline_${time}`,
1638
+ ts: (/* @__PURE__ */ new Date()).getTime()
1639
+ },
1640
+ {
1641
+ onMessage: (data) => {
1642
+ const { open, close, high, low, volume, startTime } = data;
1643
+ const key = getKlineKey(data.symbol, data.type);
1644
+ this.updateKline(key, {
1645
+ time: startTime,
1646
+ close,
1647
+ open,
1648
+ high,
1649
+ low,
1650
+ volume
1651
+ });
1652
+ }
1653
+ }
1654
+ );
1655
+ this.subscribeCachedTopics.set(`${symbol}@kline_${time}`, unsub);
1656
+ }
1657
+ }
1658
+ unsubscribeKline(subscribeId) {
1659
+ if (!this.klineSubscribeIdMap.has(subscribeId)) {
1660
+ return;
1661
+ }
1662
+ const { symbol, resolution } = this.klineSubscribeIdMap.get(subscribeId);
1663
+ const time = mapResolution(resolution);
1664
+ const klineKey = getKlineKey(symbol, time);
1665
+ if (this.klineOnTickCallback.has(klineKey)) {
1666
+ const value = this.klineOnTickCallback.get(klineKey);
1667
+ delete value[subscribeId];
1668
+ if (Object.keys(value).length === 0) {
1669
+ this.klineOnTickCallback.delete(klineKey);
1670
+ const unsub = this.subscribeCachedTopics.get(`${symbol}@kline_${time}`);
1671
+ unsub();
1672
+ }
1673
+ }
1674
+ delete this.klineSubscribeIdMap[subscribeId];
1675
+ }
1676
+ subscribeSymbol(symbol) {
1677
+ const symbolTopics = getSymbolTopics(symbol);
1678
+ symbolTopics.forEach((topic) => {
1679
+ if (!this.subscribeCachedTopics.has(topic)) {
1680
+ const unsub = this.wsInstance?.subscribe(
1681
+ {
1682
+ event: "subscribe",
1683
+ topic,
1684
+ id: topic,
1685
+ ts: (/* @__PURE__ */ new Date()).getTime()
1686
+ },
1687
+ {
1688
+ onMessage: (data) => {
1689
+ this.updateKlineByLastPrice(data.symbol, data.price);
1690
+ }
1691
+ }
1692
+ );
1693
+ this.subscribeCachedTopics.set(topic, unsub);
1694
+ }
1695
+ });
1696
+ }
1697
+ updateKlineByLastPrice(symbol, lastPrice) {
1698
+ this.klineOnTickCallback.forEach((_, key) => {
1699
+ if (key.startsWith(symbol)) {
1700
+ const klineData = this.klineData.get(key);
1701
+ if (klineData) {
1702
+ this.updateKline(key, { ...klineData, close: lastPrice });
1703
+ }
1704
+ }
1705
+ });
1706
+ }
1707
+ updateKline(key, cbParams) {
1708
+ const onTickCbs = this.klineOnTickCallback.get(key);
1709
+ if (onTickCbs && cbParams) {
1710
+ this.klineData.set(key, cbParams);
1711
+ Object.keys(onTickCbs).forEach((key2) => {
1712
+ const onTickCb = onTickCbs[key2];
1713
+ if (onTickCb && typeof onTickCb === "function") {
1714
+ onTickCb(cbParams);
1715
+ }
1716
+ });
1717
+ }
1718
+ }
1719
+ };
1720
+ _WebsocketService._created = false;
1721
+ _WebsocketService._instance = null;
1722
+ var WebsocketService = _WebsocketService;
1723
+
1724
+ // src/tradingviewAdapter/datafeed/datafeed.ts
1725
+ var getAutoIncrementId = /* @__PURE__ */ (() => {
1726
+ let id = 0;
1727
+ return () => id++;
1728
+ })();
1729
+ var Datafeed = class extends AbstractDatafeed {
1730
+ constructor(apiUrl, ws) {
1731
+ const datafeedURL = `${apiUrl}/tv`;
1732
+ super(datafeedURL);
1733
+ this.bbosMap = /* @__PURE__ */ new Map();
1734
+ this.tickersMap = /* @__PURE__ */ new Map();
1735
+ this.eventBus = new MultiBroadcastEventBus();
1736
+ this._subscribeQuoteMap = /* @__PURE__ */ new Map();
1737
+ this._prefixId = getAutoIncrementId();
1738
+ this._publicWs = new WebsocketService(ws);
1739
+ this.bbosMap = /* @__PURE__ */ new Map();
1740
+ ws.on("tickers", (message) => {
1741
+ for (const ticker of message.data) {
1742
+ ticker.change = ticker.close - ticker.open;
1743
+ ticker.perChange = ticker.open ? +(100 * ticker.change / ticker.open).toFixed(2) : 0;
1744
+ this.tickersMap.set(ticker.symbol, ticker);
1745
+ }
1746
+ this.eventBus.publish("tickerUpdate", { message: "ticker" });
1747
+ });
1748
+ ws.subscribe(
1749
+ {
1750
+ event: "subscribe",
1751
+ topic: `bbos`
1752
+ },
1753
+ {
1754
+ formatter: (message) => message,
1755
+ onMessage: (message) => {
1756
+ for (const bbo of message.data) {
1757
+ this.bbosMap.set(bbo.symbol, {
1758
+ ask: bbo.ask,
1759
+ bid: bbo.bid,
1760
+ askSize: bbo.askSize,
1761
+ bidSize: bbo.bidSize
1762
+ });
1763
+ }
1764
+ this.eventBus.publish("tickerUpdate", { message: "bbos" });
1765
+ }
1766
+ }
1767
+ );
1768
+ }
1769
+ remove() {
1770
+ Array.from(this._subscribeQuoteMap.values()).forEach((s) => s?.());
1771
+ }
1772
+ getSubscriptionId(listenerGuid) {
1773
+ return `${this._prefixId}${listenerGuid}`;
1774
+ }
1775
+ subscribeBars(symbolInfo, resolution, onTick, listenerGuid, onResetCacheNeededCallback) {
1776
+ window.onResetCacheNeededCallback = onResetCacheNeededCallback;
1777
+ this._publicWs.subscribeKline(
1778
+ `${this._prefixId}${listenerGuid}`,
1779
+ symbolInfo.ticker,
1780
+ resolution,
1781
+ onTick
1782
+ );
1783
+ }
1784
+ unsubscribeBars(listenerGuid) {
1785
+ this._publicWs.unsubscribeKline(`${this._prefixId}${listenerGuid}`);
1786
+ }
1787
+ getQuotes(symbols, onDataCallback) {
1788
+ const subscriptionId = this.getSubscriptionId("getQuotes");
1789
+ this.unsubscribeQuotes("getQuotes");
1790
+ const unsub = this.eventBus.subscribe("tickerUpdate", (msg) => {
1791
+ const dataMap = /* @__PURE__ */ new Map();
1792
+ symbols.forEach((symbol) => {
1793
+ const bbo = this.bbosMap.get(withoutExchangePrefix(symbol));
1794
+ const ticker = this.tickersMap.get(withoutExchangePrefix(symbol));
1795
+ if (!bbo || !ticker) {
1796
+ return;
1797
+ }
1798
+ const data = {
1799
+ ...ticker,
1800
+ ask: bbo.ask,
1801
+ bid: bbo.bid
1802
+ };
1803
+ dataMap.set(withoutExchangePrefix(symbol), data);
1804
+ });
1805
+ if (!dataMap.size) {
1806
+ return;
1807
+ }
1808
+ onDataCallback(
1809
+ Array.from(dataMap.values()).map(
1810
+ (symbolData) => this._toUDFTicker(symbolData)
1811
+ )
1812
+ );
1813
+ });
1814
+ this._subscribeQuoteMap.set(subscriptionId, unsub);
1815
+ }
1816
+ subscribeQuotes(symbols, fastSymbols, onRealtimeCallback, listenerGuid) {
1817
+ const subscriptionId = `${this._prefixId}${listenerGuid}`;
1818
+ if (symbols.length > 0) {
1819
+ this.unsubscribeQuotes(subscriptionId);
1820
+ const unsub = this.eventBus.subscribe("tickerUpdate", (msg) => {
1821
+ const dataMap = /* @__PURE__ */ new Map();
1822
+ symbols.forEach((symbol) => {
1823
+ const bbo = this.bbosMap.get(withoutExchangePrefix(symbol));
1824
+ const ticker = this.tickersMap.get(withoutExchangePrefix(symbol));
1825
+ if (!bbo || !ticker) {
1826
+ return;
1827
+ }
1828
+ const data = {
1829
+ ...ticker,
1830
+ ask: bbo.ask,
1831
+ bid: bbo.bid
1832
+ };
1833
+ dataMap.set(withoutExchangePrefix(symbol), data);
1834
+ });
1835
+ if (!dataMap.size) {
1836
+ return;
1837
+ }
1838
+ onRealtimeCallback(
1839
+ Array.from(dataMap.values()).map(
1840
+ (symbolData) => this._toUDFTicker(symbolData)
1841
+ )
1842
+ );
1843
+ });
1844
+ this._subscribeQuoteMap.set(subscriptionId, unsub);
1845
+ }
1846
+ }
1847
+ unsubscribeQuotes(listenerGuid) {
1848
+ const subscriptionId = this.getSubscriptionId(listenerGuid);
1849
+ const unsub = this._subscribeQuoteMap.get(subscriptionId);
1850
+ if (unsub) {
1851
+ unsub();
1852
+ this._subscribeQuoteMap.delete(subscriptionId);
1853
+ }
1854
+ }
1855
+ _toUDFTicker(t) {
1856
+ return {
1857
+ n: withExchangePrefix(t.symbol),
1858
+ s: "ok",
1859
+ v: {
1860
+ ask: t.ask,
1861
+ bid: t.bid,
1862
+ ch: t.change,
1863
+ chp: t.perChange / 100,
1864
+ description: "",
1865
+ exchange: EXCHANGE,
1866
+ hight_price: t.high,
1867
+ low_price: t.low,
1868
+ lp: t.close,
1869
+ open_price: t.open,
1870
+ prev_close_price: 0,
1871
+ volume: t.volume
1872
+ }
1873
+ };
1874
+ }
1875
+ };
1876
+ var EST_TPSL_PNL_DECIMAL = 2;
1877
+ var textDash = "--";
1878
+ var BracketAlgoType = ["BRACKET" /* BRACKET */, "STOP_BRACKET" /* STOP_BRACKET */];
1879
+ var TpslAlgoType = ["POSITIONAL_TP_SL" /* POSITIONAL_TP_SL */, "TP_SL" /* TP_SL */];
1880
+ 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 */);
1881
+ var isBracketAlgoType = (algoType) => !!algoType && BracketAlgoType.includes(algoType);
1882
+ var isPositionTpsl = (order) => order.type === "CLOSE_POSITION" /* CLOSE_POSITION */;
1883
+ var isActivatedPositionTpsl = (order) => isPositionTpsl(order) && order.is_activated;
1884
+ var isActivatedTpslOrder = (order) => isTpslOrder(order) && order.is_activated;
1885
+ var isActivatedQuantityTpsl = (order) => order.root_algo_order_algo_type === "TP_SL" /* TP_SL */ || isBracketAlgoType(order.root_algo_order_algo_type) && order.is_activated;
1886
+ var getTpslTag = (order, quantityTpslNoMap) => {
1887
+ const algoType = order.algo_type;
1888
+ const suffix = {
1889
+ ["TAKE_PROFIT" /* TAKE_PROFIT */]: i18n.t("tpsl.takeProfit"),
1890
+ ["STOP_LOSS" /* STOP_LOSS */]: i18n.t("tpsl.stopLoss")
1891
+ }[algoType];
1892
+ if (!suffix) {
1893
+ return null;
1894
+ }
1895
+ return suffix;
1896
+ };
1897
+ var buildQuantityTpslNoMap = (orders) => {
1898
+ const quantityTpslNoMap = /* @__PURE__ */ new Map();
1899
+ let idx = 1;
1900
+ [...orders].reverse().filter(isActivatedQuantityTpsl).forEach((order) => {
1901
+ if (order.root_algo_order_id && !quantityTpslNoMap.has(order.root_algo_order_id)) {
1902
+ quantityTpslNoMap.set(order.root_algo_order_id, idx++);
1903
+ }
1904
+ });
1905
+ return quantityTpslNoMap;
1906
+ };
1907
+ var getTpslEstPnl = (tpslOrder, position) => {
1908
+ const quantity = Math.abs(
1909
+ tpslOrder.type === "CLOSE_POSITION" /* CLOSE_POSITION */ ? position.balance : tpslOrder.quantity
1910
+ );
1911
+ const sideFlag = tpslOrder.side === "SELL" /* SELL */ ? 1 : -1;
1912
+ const openPrice = position.open.toString();
1913
+ const estPnl = new Decimal(tpslOrder.trigger_price).minus(openPrice ?? 0).times(quantity).times(sideFlag).toString();
1914
+ return { estPnl, quantity, openPrice };
1915
+ };
1916
+ var formatPnl = (pnl) => {
1917
+ return pnl !== void 0 && pnl !== "" ? new Decimal(pnl).todp(EST_TPSL_PNL_DECIMAL, Decimal.ROUND_FLOOR) : textDash;
1918
+ };
1919
+ function useCancelOrder() {
1920
+ const [
1921
+ pendingOrders,
1922
+ { cancelOrder, cancelAlgoOrder, cancelTPSLChildOrder }
1923
+ ] = useOrderStream({
1924
+ status: OrderStatus.INCOMPLETE
1925
+ });
1926
+ return useCallback(
1927
+ (order) => {
1928
+ if (order.algo_order_id) {
1929
+ if (TpslAlgoType.includes(order.root_algo_order_algo_type)) {
1930
+ const rootOrder = pendingOrders?.find(
1931
+ (item) => item.algo_order_id === order.root_algo_order_id
1932
+ );
1933
+ const isEditActivated = rootOrder.child_orders.every(
1934
+ (item) => !!item.trigger_price
1935
+ );
1936
+ if (isEditActivated) {
1937
+ return cancelTPSLChildOrder(
1938
+ order.algo_order_id,
1939
+ order.root_algo_order_id
1940
+ );
1941
+ }
1942
+ return cancelAlgoOrder(rootOrder.algo_order_id, order.symbol).then();
1943
+ }
1944
+ return cancelAlgoOrder(order.algo_order_id, order.symbol).then();
1945
+ }
1946
+ return cancelOrder(order.order_id, order.symbol).then();
1947
+ },
1948
+ [cancelOrder, pendingOrders]
1949
+ );
1950
+ }
1951
+ function useEditOrder(onToast) {
1952
+ useEventEmitter();
1953
+ const [, { updateOrder, cancelAlgoOrder, updateAlgoOrder, updateTPSLOrder }] = useOrderStream({
1954
+ status: OrderStatus.INCOMPLETE
1955
+ });
1956
+ return useCallback(
1957
+ (order, lineValue) => {
1958
+ if (order.algo_order_id) {
1959
+ if (TpslAlgoType.includes(order.root_algo_order_algo_type)) {
1960
+ const algoParams = [
1961
+ {
1962
+ order_id: order.algo_order_id,
1963
+ trigger_price: new Decimal(lineValue.value).toString()
1964
+ }
1965
+ ];
1966
+ return updateTPSLOrder(order.root_algo_order_id, algoParams).then((res) => {
1967
+ }).catch((e) => {
1968
+ if (onToast) {
1969
+ onToast.error(e.message);
1970
+ }
1971
+ });
1972
+ } else if (BracketAlgoType.includes(order.algo_type)) {
1973
+ return updateAlgoOrder(order.algo_order_id, {
1974
+ order_price: new Decimal(lineValue.value).toString()
1975
+ }).then((res) => {
1976
+ }).catch((e) => {
1977
+ if (onToast) {
1978
+ onToast.error(e.message);
1979
+ }
1980
+ });
1981
+ } else {
1982
+ const values2 = {
1983
+ quantity: order.quantity,
1984
+ trigger_price: order.trigger_price,
1985
+ symbol: order.symbol,
1986
+ price: order.price,
1987
+ // order_type: order.type,
1988
+ // side: order.side,
1989
+ // reduce_only: Boolean(order.reduce_only),
1990
+ algo_order_id: order.algo_order_id
1991
+ };
1992
+ if (order.order_tag) {
1993
+ values2.order_tag = order.order_tag;
1994
+ }
1995
+ if (order.client_order_id) {
1996
+ values2.client_order_id = order.client_order_id;
1997
+ }
1998
+ if (lineValue.type === "price") {
1999
+ values2.price = new Decimal(lineValue.value).toString();
2000
+ }
2001
+ if (lineValue.type === "trigger_price") {
2002
+ values2.trigger_price = new Decimal(lineValue.value).toString();
2003
+ }
2004
+ return updateAlgoOrder(order.algo_order_id, values2).then((res) => {
2005
+ }).catch((e) => {
2006
+ if (onToast) {
2007
+ onToast.error(e.message);
2008
+ }
2009
+ });
2010
+ }
2011
+ }
2012
+ const values = {
2013
+ order_price: order.price?.toString(),
2014
+ order_quantity: order.quantity.toString(),
2015
+ symbol: order.symbol,
2016
+ order_type: order.type,
2017
+ side: order.side,
2018
+ visible_quantity: 0,
2019
+ reduce_only: order.reduce_only
2020
+ };
2021
+ if (new Decimal(order.visible_quantity ?? order.visible ?? 0).eq(
2022
+ order.quantity
2023
+ )) {
2024
+ delete values.visible_quantity;
2025
+ }
2026
+ if (!Object.keys(order).includes("reduce_only")) {
2027
+ delete values.reduce_only;
2028
+ }
2029
+ if (order.order_tag) {
2030
+ values.order_tag = order.order_tag;
2031
+ }
2032
+ if (order.client_order_id) {
2033
+ values.client_order_id = order.client_order_id;
2034
+ }
2035
+ if (lineValue.type === "price") {
2036
+ values.order_price = new Decimal(lineValue.value).toString();
2037
+ }
2038
+ return updateOrder(order.order_id, values).then((res) => {
2039
+ }).catch((e) => {
2040
+ onToast.error(e.message);
2041
+ });
2042
+ },
2043
+ [updateOrder]
2044
+ );
2045
+ }
2046
+ function useSendOrder(symbol) {
2047
+ const { onSubmit: _sendMarketOrder } = useOrderEntry_deprecated(
2048
+ {
2049
+ symbol,
2050
+ side: OrderSide.BUY,
2051
+ order_type: OrderType.MARKET
2052
+ },
2053
+ {
2054
+ watchOrderbook: true
2055
+ }
2056
+ );
2057
+ const sendLimitOrder = () => {
2058
+ };
2059
+ const sendMarketOrder = (data) => {
2060
+ data.reduce_only = false;
2061
+ return _sendMarketOrder(data).catch((e) => {
2062
+ toast.error(e);
2063
+ });
2064
+ };
2065
+ return {
2066
+ sendLimitOrder,
2067
+ sendMarketOrder
2068
+ };
2069
+ }
2070
+ var createBrokerMethod = (method) => {
2071
+ return (params) => method(params);
2072
+ };
2073
+ var useBroker = ({
2074
+ closeConfirm,
2075
+ colorConfig,
2076
+ onToast,
2077
+ mode,
2078
+ symbol
2079
+ }) => {
2080
+ const cancelOrder = useCancelOrder();
2081
+ const editOrder = useEditOrder(onToast);
2082
+ const symbolData = useSymbolsInfo();
2083
+ const closePosition = useCallback(
2084
+ (position) => closeConfirm && closeConfirm(position),
2085
+ [closeConfirm]
2086
+ );
2087
+ const { sendMarketOrder, sendLimitOrder } = useSendOrder(symbol);
2088
+ const getSymbolInfo = useCallback(
2089
+ (symbol2) => {
2090
+ if (!symbolData) {
2091
+ return;
2092
+ }
2093
+ return {
2094
+ baseMin: symbolData[symbol2]("base_min"),
2095
+ baseMax: symbolData[symbol2]("base_max"),
2096
+ baseTick: symbolData[symbol2]("base_tick"),
2097
+ quoteTick: symbolData[symbol2]("quote_tick")
2098
+ };
2099
+ },
2100
+ [symbolData]
2101
+ );
2102
+ const broker = useRef({
2103
+ cancelOrder,
2104
+ closePosition,
2105
+ editOrder,
2106
+ colorConfig,
2107
+ sendLimitOrder,
2108
+ getSymbolInfo,
2109
+ sendMarketOrder: createBrokerMethod(sendMarketOrder),
2110
+ mode
2111
+ });
2112
+ useEffect(() => {
2113
+ broker.current.getSymbolInfo = getSymbolInfo;
2114
+ }, [symbolData]);
2115
+ useEffect(() => {
2116
+ broker.current.sendLimitOrder = sendLimitOrder;
2117
+ broker.current.sendMarketOrder = sendMarketOrder;
2118
+ }, [sendLimitOrder, sendMarketOrder]);
2119
+ useEffect(() => {
2120
+ broker.current.closePosition = closePosition;
2121
+ }, [closeConfirm]);
2122
+ useEffect(() => {
2123
+ broker.current.cancelOrder = cancelOrder;
2124
+ }, [cancelOrder]);
2125
+ return broker.current;
2126
+ };
2127
+ var useBroker_default = useBroker;
2128
+ var IntervalMap = {
2129
+ 1: { startOf: "minute", period: 0 },
2130
+ 3: { startOf: "hour", period: 3 * 60 * 1e3 },
2131
+ 5: { startOf: "hour", period: 5 * 60 * 1e3 },
2132
+ 15: { startOf: "hour", period: 15 * 60 * 1e3 },
2133
+ 30: { startOf: "hour", period: 30 * 60 * 1e3 },
2134
+ 60: { startOf: "hour", period: 0 },
2135
+ 120: { startOf: "day", period: 2 * 60 * 60 * 1e3 },
2136
+ 240: { startOf: "day", period: 4 * 60 * 60 * 1e3 },
2137
+ 480: { startOf: "day", period: 8 * 60 * 60 * 1e3 },
2138
+ 720: { startOf: "day", period: 12 * 60 * 60 * 1e3 },
2139
+ D: { startOf: "day", period: 0 },
2140
+ // default day interval shown as D instead of 1D
2141
+ "1D": { startOf: "day", period: 0 },
2142
+ "3D": { startOf: "year", period: 3 * 24 * 60 * 60 * 1e3 },
2143
+ "5D": { startOf: "year", period: 5 * 24 * 60 * 60 * 1e3 },
2144
+ "1W": { startOf: "week", period: 0 },
2145
+ "1M": { startOf: "month", period: 0 }
2146
+ };
2147
+ function collectionOrders(order, collection, interval, orderList) {
2148
+ const { startOf, period } = IntervalMap[interval];
2149
+ const time = new Date(order.updated_time).getTime();
2150
+ let base = startOfSecond(time).getTime();
2151
+ if (startOf === "minute") {
2152
+ base = startOfMinute(time).getTime();
2153
+ } else if (startOf === "hour") {
2154
+ base = startOfHour(time).getTime();
2155
+ } else if (startOf === "day") {
2156
+ base = startOfDay(time).getTime();
2157
+ } else if (startOf === "month") {
2158
+ base = startOfMonth(time).getTime();
2159
+ } else if (startOf === "year") {
2160
+ base = startOfYear(time).getTime();
2161
+ } else if (startOf === "week") {
2162
+ base = startOfWeek(time).getTime();
2163
+ } else if (startOf === "month") {
2164
+ base = startOfMonth(time).getTime();
2165
+ }
2166
+ const group = period === 0 ? base : Math.floor((time - base) / period) * period + base;
2167
+ if (!collection[group]) {
2168
+ collection[group] = { ["BUY" /* BUY */]: [], ["SELL" /* SELL */]: [] };
2169
+ }
2170
+ if (collection[group][order.side].length < 5) {
2171
+ collection[group][order.side].push(order);
2172
+ orderList.push(order);
2173
+ }
2174
+ }
2175
+ var limitOrdersByInterval = (orders, interval) => {
2176
+ const res = [];
2177
+ const collection = {};
2178
+ if (!IntervalMap[interval]) {
2179
+ return [];
2180
+ }
2181
+ orders.forEach((order) => {
2182
+ if (order.child_orders) {
2183
+ for (const child of order.child_orders) {
2184
+ if (child.is_activated && child.algo_status === OrderStatus.FILLED) {
2185
+ collectionOrders(child, collection, interval, res);
2186
+ }
2187
+ }
2188
+ } else {
2189
+ collectionOrders(order, collection, interval, res);
2190
+ }
2191
+ });
2192
+ return res;
2193
+ };
2194
+ var ExecutionService = class _ExecutionService {
2195
+ constructor(instance, broker) {
2196
+ this.interval = "1D";
2197
+ this.changeInterval = (interval) => {
2198
+ const rerenderExecutions = () => {
2199
+ this.renderExecutions(this.filledOrders, this.basePriceDecimal);
2200
+ this.instance.activeChart().onDataLoaded().unsubscribe(null, rerenderExecutions);
2201
+ };
2202
+ this.interval = interval;
2203
+ this.instance.activeChart().onDataLoaded().subscribe(null, rerenderExecutions);
2204
+ };
2205
+ this.instance = instance;
2206
+ this.executions = [];
2207
+ this.filledOrders = [];
2208
+ this.basePriceDecimal = 0;
2209
+ this.broker = broker;
2210
+ this.subscribeIntervalChange();
2211
+ }
2212
+ async subscribeIntervalChange() {
2213
+ this.interval = this.instance.symbolInterval().interval;
2214
+ const changeInterval = this.changeInterval;
2215
+ this.instance.activeChart().onIntervalChanged().subscribe(null, changeInterval);
2216
+ }
2217
+ renderExecutions(filledOrders, basePriceDecimal) {
2218
+ this.filledOrders = filledOrders;
2219
+ this.basePriceDecimal = basePriceDecimal;
2220
+ if (!this.interval) {
2221
+ return;
2222
+ }
2223
+ this.removeAll();
2224
+ limitOrdersByInterval(filledOrders, this.interval).forEach((order) => {
2225
+ this.executions.push(this.drawExecution(order, basePriceDecimal));
2226
+ });
2227
+ }
2228
+ removeAll() {
2229
+ this.executions.forEach((execution) => execution.remove());
2230
+ this.executions = [];
2231
+ }
2232
+ static getExecutionInfo(order, basePriceDecimal) {
2233
+ const side = order.side;
2234
+ const avgExecPrice = order.average_executed_price || order.child_orders?.find((child) => !!child.average_executed_price)?.average_executed_price || 0;
2235
+ const excutedNumber = new Decimal(avgExecPrice).todp(basePriceDecimal, Decimal.ROUND_FLOOR).toString();
2236
+ return `${side === "BUY" /* BUY */ ? i18n.t("common.buy") : i18n.t("common.sell")} ${order.total_executed_quantity} @${commify(excutedNumber)}`;
2237
+ }
2238
+ drawExecution(order, basePriceDecimal) {
2239
+ const side = order.side;
2240
+ const avgExecPrice = order.average_executed_price || order.child_orders?.find((child) => !!child.average_executed_price)?.average_executed_price || 0;
2241
+ const timestamp = new Date(order.updated_time).getTime() / 1e3;
2242
+ const colorConfig = this.broker.colorConfig;
2243
+ return this.instance.activeChart().createExecutionShape().setArrowHeight(9).setTooltip(_ExecutionService.getExecutionInfo(order, basePriceDecimal)).setTime(timestamp).setPrice(avgExecPrice).setArrowColor(
2244
+ side === "BUY" /* BUY */ ? colorConfig.upColor : colorConfig.downColor
2245
+ ).setDirection(side === "BUY" /* BUY */ ? "buy" : "sell");
2246
+ }
2247
+ unsubscribeIntervalChange() {
2248
+ const changeInterval = this.changeInterval;
2249
+ try {
2250
+ this.instance.activeChart().onIntervalChanged().unsubscribe(null, changeInterval);
2251
+ } catch (e) {
2252
+ if (e instanceof Error && e.message === "Cannot read properties of null (reading 'tradingViewApi')") ;
2253
+ }
2254
+ }
2255
+ destroy() {
2256
+ this.removeAll();
2257
+ this.unsubscribeIntervalChange();
2258
+ }
2259
+ };
2260
+
2261
+ // src/tradingviewAdapter/renderer/order.util.ts
2262
+ var getOrderId = (order) => {
2263
+ if (order === null || order === void 0) {
2264
+ return void 0;
2265
+ }
2266
+ return order.algo_order_id || order.order_id;
2267
+ };
2268
+
2269
+ // src/tradingviewAdapter/renderer/tpslCal.service.ts
2270
+ var TpslCalService = class {
2271
+ constructor() {
2272
+ this.quantityTpslNoMap = /* @__PURE__ */ new Map();
2273
+ this.tpslPnlMap = /* @__PURE__ */ new Map();
2274
+ this.positions = null;
2275
+ }
2276
+ getQuantityTpslNoMap() {
2277
+ return this.quantityTpslNoMap;
2278
+ }
2279
+ getTpslPnlMap() {
2280
+ return this.tpslPnlMap;
2281
+ }
2282
+ getFormattedEstPnl(tpslOrder) {
2283
+ if (this.positions === null) {
2284
+ return "";
2285
+ }
2286
+ const position = this.positions[0];
2287
+ if (!position) {
2288
+ return "";
2289
+ }
2290
+ const { estPnl } = getTpslEstPnl(tpslOrder, position);
2291
+ return formatPnl(estPnl);
2292
+ }
2293
+ prepareTpslPnlMap(newPendingOrders) {
2294
+ const changed = [];
2295
+ newPendingOrders.forEach((order) => {
2296
+ const orderId = getOrderId(order);
2297
+ if (orderId && isActivatedTpslOrder(order)) {
2298
+ const prevPnl = this.tpslPnlMap.get(orderId);
2299
+ const newPnl = this.getFormattedEstPnl(order);
2300
+ if (prevPnl !== newPnl) {
2301
+ changed.push(orderId);
2302
+ this.tpslPnlMap.set(orderId, newPnl);
2303
+ }
2304
+ }
2305
+ });
2306
+ return changed;
2307
+ }
2308
+ prepareQuantityTpslNoMap(newPendingOrders) {
2309
+ this.quantityTpslNoMap = buildQuantityTpslNoMap(newPendingOrders);
2310
+ }
2311
+ recalculatePnl(positions, pendingOrders) {
2312
+ this.positions = positions;
2313
+ return this.prepareTpslPnlMap(pendingOrders);
2314
+ }
2315
+ clear() {
2316
+ this.positions = null;
2317
+ this.quantityTpslNoMap.clear();
2318
+ this.tpslPnlMap.clear();
2319
+ }
2320
+ };
2321
+
2322
+ // src/tradingviewAdapter/renderer/orderLine.service.ts
2323
+ var _OrderLineService = class _OrderLineService {
2324
+ constructor(instance, broker) {
2325
+ this.instance = instance;
2326
+ this.pendingOrderLineMap = /* @__PURE__ */ new Map();
2327
+ this.pendingOrders = [];
2328
+ this.broker = broker;
2329
+ this.tpslCalService = new TpslCalService();
2330
+ }
2331
+ renderPendingOrders(newPendingOrders) {
2332
+ if (newPendingOrders) {
2333
+ this.pendingOrders = newPendingOrders;
2334
+ }
2335
+ this.cleanOldPendingOrders(this.pendingOrders);
2336
+ this.tpslCalService.prepareTpslPnlMap(this.pendingOrders);
2337
+ this.tpslCalService.prepareQuantityTpslNoMap(this.pendingOrders);
2338
+ this.pendingOrders.forEach((order) => this.renderPendingOrder(order));
2339
+ }
2340
+ updatePositions(positions) {
2341
+ const changed = this.tpslCalService.recalculatePnl(
2342
+ positions,
2343
+ this.pendingOrders
2344
+ );
2345
+ this.pendingOrders.filter((order) => changed.includes(getOrderId(order))).forEach((order) => this.renderPendingOrder(order));
2346
+ }
2347
+ renderPendingOrder(order) {
2348
+ const orderId = _OrderLineService.getOrderId(order);
2349
+ if (!orderId) {
2350
+ return;
2351
+ }
2352
+ const orderLine = this.drawOrderLine(orderId, order);
2353
+ if (orderLine) {
2354
+ this.pendingOrderLineMap.set(orderId, orderLine);
2355
+ }
2356
+ }
2357
+ cleanOldPendingOrders(newPendingOrders) {
2358
+ const newOrderIdSet = new Set(
2359
+ newPendingOrders.map((order) => _OrderLineService.getOrderId(order))
2360
+ );
2361
+ this.pendingOrderLineMap.forEach(
2362
+ (_, orderId) => !newOrderIdSet.has(orderId) && this.removePendingOrder(orderId)
2363
+ );
2364
+ }
2365
+ removePendingOrder(orderId) {
2366
+ if (orderId === void 0) {
2367
+ return;
2368
+ }
2369
+ const orderLine = this.pendingOrderLineMap.get(orderId);
2370
+ if (orderLine) {
2371
+ this.pendingOrderLineMap.delete(orderId);
2372
+ orderLine.remove();
2373
+ }
2374
+ }
2375
+ getBaseOrderLine() {
2376
+ const colorConfig = this.broker.colorConfig;
2377
+ 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);
2378
+ }
2379
+ static getCombinationType(order) {
2380
+ const { algo_type: algoType, type } = order;
2381
+ if ((algoType === "STOP_LOSS" /* STOP_LOSS */ || algoType === "TAKE_PROFIT" /* TAKE_PROFIT */ || algoType === "STOP" /* STOP */) && type === "LIMIT" /* LIMIT */) {
2382
+ return "STOP_LIMIT" /* STOP_LIMIT */;
2383
+ }
2384
+ if ((algoType === "STOP_LOSS" /* STOP_LOSS */ || algoType === "TAKE_PROFIT" /* TAKE_PROFIT */ || algoType === "STOP" /* STOP */) && type === "MARKET" /* MARKET */) {
2385
+ return "STOP_MARKET" /* STOP_MARKET */;
2386
+ }
2387
+ if (algoType === "BRACKET" /* BRACKET */) {
2388
+ if (type === "LIMIT" /* LIMIT */) {
2389
+ return "BRACKET_LIMIT" /* BRACKET_LIMIT */;
2390
+ }
2391
+ if (type === "MARKET" /* MARKET */) {
2392
+ return "BRACKET_MARKET" /* BRACKET_MARKET */;
2393
+ }
2394
+ }
2395
+ if (algoType === "TRAILING_STOP" /* TRAILING_STOP */) {
2396
+ return "TRAILING_STOP" /* TRAILING_STOP */;
2397
+ }
2398
+ return "LIMIT" /* LIMIT */;
2399
+ }
2400
+ static getText(pendingOrder) {
2401
+ const orderCombinationType = _OrderLineService.getCombinationType(pendingOrder);
2402
+ 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 */) {
2403
+ if (pendingOrder.type === "LIMIT" /* LIMIT */) {
2404
+ return `${i18n.t("orderEntry.orderType.stopLimit")} ${commify(
2405
+ pendingOrder.price
2406
+ )}`;
2407
+ }
2408
+ return i18n.t("orderEntry.orderType.stopMarket");
2409
+ }
2410
+ if (orderCombinationType === "TRAILING_STOP" /* TRAILING_STOP */) {
2411
+ return i18n.t("orderEntry.trailing");
2412
+ }
2413
+ return i18n.t("orderEntry.orderType.limit");
2414
+ }
2415
+ static getOrderPrice(pendingOrder) {
2416
+ if (pendingOrder.algo_type === "TRAILING_STOP" /* TRAILING_STOP */) {
2417
+ return getTrailingStopPrice(pendingOrder);
2418
+ }
2419
+ return pendingOrder.trigger_price || pendingOrder.price;
2420
+ }
2421
+ getTPSLTextWithTpsl(text, pendingOrder) {
2422
+ const orderId = getOrderId(pendingOrder);
2423
+ if (!orderId) {
2424
+ return text;
2425
+ }
2426
+ return text;
2427
+ }
2428
+ getTPSLText(pendingOrder) {
2429
+ const tpslTypeText = getTpslTag(
2430
+ pendingOrder,
2431
+ this.tpslCalService.getQuantityTpslNoMap()
2432
+ );
2433
+ if (tpslTypeText) {
2434
+ return this.getTPSLTextWithTpsl(tpslTypeText, pendingOrder);
2435
+ }
2436
+ return null;
2437
+ }
2438
+ getOrderQuantity(pendingOrder) {
2439
+ if (pendingOrder.algo_order_id) {
2440
+ if (isActivatedPositionTpsl(pendingOrder) || isPositionTpsl(pendingOrder)) {
2441
+ return "100%";
2442
+ }
2443
+ if (isActivatedQuantityTpsl(pendingOrder)) {
2444
+ const qty = new Decimal(pendingOrder.quantity).minus(
2445
+ pendingOrder.executed ?? 0
2446
+ );
2447
+ const per = qty.div(new Decimal(pendingOrder.position_qty)).mul(100).todp(2).toNumber();
2448
+ return `${Math.min(Math.abs(per), 100).toString()}%`;
2449
+ }
2450
+ }
2451
+ return commify(new Decimal(pendingOrder.quantity).toString());
2452
+ }
2453
+ drawOrderLine(orderId, pendingOrder) {
2454
+ const text = isTpslOrder(pendingOrder) ? this.getTPSLText(pendingOrder) : _OrderLineService.getText(pendingOrder);
2455
+ if (text === null) {
2456
+ return null;
2457
+ }
2458
+ const colorConfig = this.broker.colorConfig;
2459
+ const orderLine = this.pendingOrderLineMap.get(orderId) ?? this.getBaseOrderLine();
2460
+ const color = pendingOrder.side === "BUY" /* BUY */ ? colorConfig.upColor : colorConfig.downColor;
2461
+ pendingOrder.side === "BUY" /* BUY */ ? colorConfig.pnlUpColor : colorConfig.pnlDownColor;
2462
+ const price = _OrderLineService.getOrderPrice(pendingOrder);
2463
+ const lineLength = 100;
2464
+ const quantity = this.getOrderQuantity(pendingOrder);
2465
+ const textColor2 = colorConfig.textColor;
2466
+ orderLine.setText(text).setCancelButtonIconColor(colorConfig.closeIcon).setCancelButtonBorderColor(color).setBodyTextColor(textColor2).setBodyBorderColor(color).setQuantityBorderColor(color).setQuantityTextColor(color).setLineColor(color).setLineLength(lineLength).setQuantity(quantity ?? "").setPrice(price);
2467
+ if (this.broker.mode !== 3 /* MOBILE */) {
2468
+ orderLine.onCancel(null, () => this.broker.cancelOrder(pendingOrder));
2469
+ this.applyEditOnMove(orderLine, pendingOrder);
2470
+ } else {
2471
+ orderLine.setEditable(false).setCancellable(false);
2472
+ }
2473
+ return orderLine;
2474
+ }
2475
+ static getOrderEditKey(pendingOrder) {
2476
+ const orderCombinationType = this.getCombinationType(pendingOrder);
2477
+ if (["LIMIT" /* LIMIT */, "BRACKET_LIMIT" /* BRACKET_LIMIT */].includes(
2478
+ orderCombinationType
2479
+ )) {
2480
+ return "price";
2481
+ }
2482
+ 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 */) {
2483
+ return "trigger_price";
2484
+ }
2485
+ }
2486
+ applyEditOnMove(orderLine, pendingOrder) {
2487
+ const editKey = _OrderLineService.getOrderEditKey(pendingOrder);
2488
+ if (!editKey) {
2489
+ return;
2490
+ }
2491
+ orderLine.onMove(() => {
2492
+ this.broker.editOrder(pendingOrder, {
2493
+ type: editKey,
2494
+ value: `${orderLine.getPrice()}`
2495
+ }).then((res) => {
2496
+ if (!res.success) {
2497
+ this.renderPendingOrder(pendingOrder);
2498
+ }
2499
+ }).catch(() => this.renderPendingOrder(pendingOrder));
2500
+ });
2501
+ }
2502
+ removeAll() {
2503
+ this.pendingOrderLineMap.forEach((orderLine) => orderLine.remove());
2504
+ this.pendingOrderLineMap.clear();
2505
+ this.pendingOrders = [];
2506
+ this.tpslCalService.clear();
2507
+ }
2508
+ };
2509
+ _OrderLineService.getOrderId = (order) => {
2510
+ if (order === null || order === void 0) {
2511
+ return void 0;
2512
+ }
2513
+ return order.algo_order_id || order.order_id;
2514
+ };
2515
+ var OrderLineService = _OrderLineService;
2516
+ var PositionLineService = class _PositionLineService {
2517
+ constructor(instance, broker) {
2518
+ this.instance = instance;
2519
+ this.currentSymbol = "";
2520
+ this.broker = broker;
2521
+ this.positionLines = {};
2522
+ this.lastPositions = null;
2523
+ }
2524
+ renderPositions(positions) {
2525
+ if (positions === null || positions.length === 0) {
2526
+ this.removePositions();
2527
+ return;
2528
+ }
2529
+ if (this.lastPositions?.length !== positions.length) {
2530
+ this.removePositions();
2531
+ }
2532
+ if (positions[0].symbol !== this.currentSymbol) {
2533
+ this.removePositions();
2534
+ this.currentSymbol = positions[0].symbol;
2535
+ }
2536
+ positions.forEach((position, idx) => this.drawPositionLine(position, idx));
2537
+ this.lastPositions = positions;
2538
+ }
2539
+ getBasePositionLine() {
2540
+ 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);
2541
+ }
2542
+ static getPositionQuantity(balance) {
2543
+ return commify(new Decimal(balance).todp(4, Decimal.ROUND_DOWN).toString());
2544
+ }
2545
+ static getPositionPnL(unrealPnl, decimal) {
2546
+ const text = i18n.t("tpsl.pnl");
2547
+ const pnl = new Decimal(unrealPnl).toFixed(decimal, Decimal.ROUND_DOWN);
2548
+ if (new Decimal(unrealPnl).eq(0)) {
2549
+ return `${text} 0`;
2550
+ }
2551
+ if (new Decimal(unrealPnl).greaterThan(0)) {
2552
+ return `${text} +${commify(pnl)}`;
2553
+ }
2554
+ return `${text} ${commify(pnl)}`;
2555
+ }
2556
+ removePositions() {
2557
+ Object.keys(this.positionLines).forEach((lineId) => {
2558
+ this.positionLines[Number(lineId)].remove();
2559
+ delete this.positionLines[Number(lineId)];
2560
+ });
2561
+ }
2562
+ drawPositionLine(position, idx) {
2563
+ const colorConfig = this.broker.colorConfig;
2564
+ const isPositiveUnrealPnl = position.unrealPnl >= 0;
2565
+ const isPositiveBalance = position.balance >= 0;
2566
+ let pnlColor = colorConfig.pnlZoreColor;
2567
+ const pnlDecimal = new Decimal(position.unrealPnl);
2568
+ if (pnlDecimal.greaterThan(0)) {
2569
+ pnlColor = colorConfig.upColor;
2570
+ } else if (pnlDecimal.lessThan(0)) {
2571
+ pnlColor = colorConfig.downColor;
2572
+ }
2573
+ isPositiveUnrealPnl ? colorConfig.pnlUpColor : colorConfig.pnlDownColor;
2574
+ const sideColor = isPositiveBalance ? colorConfig.upColor : colorConfig.downColor;
2575
+ const price = new Decimal(position.open).toNumber();
2576
+ this.positionLines[idx] = this.positionLines[idx] ?? this.getBasePositionLine();
2577
+ 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(
2578
+ _PositionLineService.getPositionPnL(
2579
+ position.unrealPnl,
2580
+ position.unrealPnlDecimal
2581
+ )
2582
+ );
2583
+ if (this.broker.mode !== 3 /* MOBILE */) {
2584
+ this.positionLines[idx].onClose(null, () => {
2585
+ this.broker.closePosition(position);
2586
+ });
2587
+ }
2588
+ }
2589
+ };
2590
+ var DEFAULT_THRESHOLD = 10;
2591
+ var TPSLService = class {
2592
+ constructor(instance, broker) {
2593
+ this.interactiveMode = 0 /* NONE */;
2594
+ this.tpslElRemoveTimer = null;
2595
+ this.currentPosition = null;
2596
+ this.tpslOrderLine = null;
2597
+ this.tpslPnLVerticalLineEntityId = null;
2598
+ this.tpslVerticalLineTime = null;
2599
+ this.tpslStartCircleEntityId = null;
2600
+ this.tpslEndCircleEntityId = null;
2601
+ this.threshold = 10;
2602
+ this.lastArgs = null;
2603
+ this.instance = instance;
2604
+ this.broker = broker;
2605
+ this.lastPositions = null;
2606
+ this.tpslElRemoveTimer = null;
2607
+ this.currentPosition = null;
2608
+ this.bindEvent();
2609
+ }
2610
+ bindEvent() {
2611
+ this.chart.crossHairMoved().subscribe(null, (args) => {
2612
+ this.lastArgs = args;
2613
+ if (this.interactiveMode === 2 /* TP_SL_DRAGGING */) {
2614
+ this.clearTpslElRemoveTimer();
2615
+ return;
2616
+ }
2617
+ const position = this.getIntersectantPosition(args);
2618
+ if (this.currentPosition && position && this.currentPosition.symbol === position.symbol) {
2619
+ return;
2620
+ }
2621
+ if (!position) {
2622
+ this.clearTPSLElements();
2623
+ return;
2624
+ }
2625
+ if (position) {
2626
+ this.clearTpslElRemoveTimer();
2627
+ this.currentPosition = position;
2628
+ this.createTPSLTriggerButton(args);
2629
+ }
2630
+ });
2631
+ }
2632
+ clearTpslElRemoveTimer() {
2633
+ if (this.tpslElRemoveTimer) {
2634
+ clearTimeout(this.tpslElRemoveTimer);
2635
+ this.tpslElRemoveTimer = null;
2636
+ }
2637
+ }
2638
+ showTPSLDialog(params) {
2639
+ const pnl = new Decimal(params.price).minus(this.currentPosition.open).mul(this.currentPosition?.balance ?? 0);
2640
+ modal.show("TPSLSimpleDialogId", {
2641
+ title: pnl.gt(0) ? i18n.t("tpsl.TPOrderConfirm") : i18n.t("tpsl.SLOrderConfirm"),
2642
+ triggerPrice: params.price,
2643
+ type: pnl.gt(0) ? "tp" : "sl",
2644
+ symbol: this.currentPosition.symbol,
2645
+ onComplete: () => {
2646
+ this.clearTPSLElements();
2647
+ this.chart.setScrollEnabled(true);
2648
+ this.chart.setZoomEnabled(true);
2649
+ this.interactiveMode = 0 /* NONE */;
2650
+ },
2651
+ showAdvancedTPSLDialog: (options) => {
2652
+ this.showAdvancedTPSLDialog({
2653
+ type: pnl.gt(0) ? "tp" : "sl",
2654
+ triggerPrice: params.price,
2655
+ qty: options.qty
2656
+ });
2657
+ }
2658
+ }).then(
2659
+ () => {
2660
+ },
2661
+ (err) => {
2662
+ }
2663
+ ).finally(() => {
2664
+ this.clearTPSLElements();
2665
+ this.chart.setScrollEnabled(true);
2666
+ this.chart.setZoomEnabled(true);
2667
+ this.interactiveMode = 0 /* NONE */;
2668
+ });
2669
+ }
2670
+ showAdvancedTPSLDialog({
2671
+ type,
2672
+ triggerPrice,
2673
+ qty
2674
+ }) {
2675
+ modal.show("TPSLDialogId", {
2676
+ withTriggerPrice: true,
2677
+ type,
2678
+ triggerPrice,
2679
+ symbol: this.currentPosition?.symbol,
2680
+ qty,
2681
+ onComplete: () => {
2682
+ this.clearTPSLElements();
2683
+ this.chart.setScrollEnabled(true);
2684
+ this.chart.setZoomEnabled(true);
2685
+ this.interactiveMode = 0 /* NONE */;
2686
+ }
2687
+ }).then(
2688
+ () => {
2689
+ },
2690
+ (err) => {
2691
+ }
2692
+ ).finally(() => {
2693
+ this.clearTPSLElements();
2694
+ this.chart.setScrollEnabled(true);
2695
+ this.chart.setZoomEnabled(true);
2696
+ this.interactiveMode = 0 /* NONE */;
2697
+ });
2698
+ }
2699
+ updatePositions(positions) {
2700
+ this.lastPositions = positions;
2701
+ this.threshold = this.generateThreshold();
2702
+ }
2703
+ /**
2704
+ * Generates a threshold value for position intersection detection.
2705
+ * The threshold is calculated as 2% of the visible price range but is capped
2706
+ * to ensure it never exceeds the actual price range (highest - lowest price).
2707
+ *
2708
+ * @returns The calculated threshold value, or DEFAULT_THRESHOLD if calculation fails
2709
+ */
2710
+ generateThreshold() {
2711
+ const priceScale = this.chart.getPanes()[0]?.getRightPriceScales()[0];
2712
+ if (!priceScale) {
2713
+ return DEFAULT_THRESHOLD;
2714
+ }
2715
+ try {
2716
+ const priceRange = priceScale.getVisiblePriceRange();
2717
+ if (!priceRange) {
2718
+ return DEFAULT_THRESHOLD;
2719
+ }
2720
+ const priceWidth = priceRange.to - priceRange.from;
2721
+ const calculatedThreshold = priceWidth * 0.02;
2722
+ const threshold = Math.min(calculatedThreshold, priceWidth);
2723
+ return threshold;
2724
+ } catch (error) {
2725
+ return DEFAULT_THRESHOLD;
2726
+ }
2727
+ }
2728
+ drawTPSL(params) {
2729
+ const { price } = params;
2730
+ const pnl = new Decimal(price).minus(this.currentPosition.open).mul(this.currentPosition?.balance ?? 0);
2731
+ const { tpslOrderLine, verticalLine } = this.ensureTPSLElements({
2732
+ price,
2733
+ pnl
2734
+ });
2735
+ const direction = pnl.gt(0) ? i18n.t("tpsl.tp") : i18n.t("tpsl.sl");
2736
+ const color = pnl.gt(0) ? this.broker.colorConfig.upColor : this.broker.colorConfig.downColor;
2737
+ tpslOrderLine?.setText(`${direction} ${pnl.toDecimalPlaces(2).toNumber()}`).setBodyTextColor(color).setBodyBorderColor(color).setLineColor(color);
2738
+ if (this.tpslVerticalLineTime) {
2739
+ verticalLine?.setPoints([
2740
+ { price: this.currentPosition?.open, time: this.tpslVerticalLineTime },
2741
+ { time: this.tpslVerticalLineTime, price }
2742
+ ]);
2743
+ }
2744
+ }
2745
+ ensureTPSLElements(params) {
2746
+ const tpslOrderLine = this.tpslOrderLine;
2747
+ let verticalLine;
2748
+ if (!tpslOrderLine) {
2749
+ this.tpslOrderLine = this.createTPSLOrderLine();
2750
+ }
2751
+ if (this.tpslPnLVerticalLineEntityId) {
2752
+ verticalLine = this.chart.getShapeById(this.tpslPnLVerticalLineEntityId);
2753
+ }
2754
+ if (!verticalLine) {
2755
+ if (!this.currentPosition || !this.tpslVerticalLineTime) {
2756
+ return {};
2757
+ }
2758
+ this.tpslPnLVerticalLineEntityId = this.chart.createMultipointShape(
2759
+ [
2760
+ {
2761
+ price: this.currentPosition.open,
2762
+ time: this.tpslVerticalLineTime
2763
+ },
2764
+ { time: this.tpslVerticalLineTime, price: params.price }
2765
+ ],
2766
+ {
2767
+ shape: "trend_line",
2768
+ // shape: "parallel_channel",
2769
+ lock: true,
2770
+ disableSave: true,
2771
+ disableSelection: true,
2772
+ disableUndo: true,
2773
+ zOrder: "top",
2774
+ overrides: {
2775
+ linecolor: "rgba(255,255,255, 0.2)",
2776
+ linewidth: 1,
2777
+ rightEnd: 1,
2778
+ leftEnd: 1
2779
+ }
2780
+ }
2781
+ );
2782
+ }
2783
+ verticalLine?.setProperties({
2784
+ linecolor: params.pnl.gt(0) ? this.broker.colorConfig.upColor : this.broker.colorConfig.downColor,
2785
+ linewidth: 1
2786
+ });
2787
+ return {
2788
+ tpslOrderLine,
2789
+ verticalLine
2790
+ };
2791
+ }
2792
+ createTPSLTriggerButton(params) {
2793
+ if (!this.tpslOrderLine) {
2794
+ this.tpslOrderLine = this.createTPSLOrderLine();
2795
+ }
2796
+ this.tpslOrderLine.onMove(() => {
2797
+ const price = this.tpslOrderLine?.getPrice();
2798
+ this.showTPSLDialog({ price: price ?? 0 });
2799
+ });
2800
+ this.tpslOrderLine.onMoving(() => {
2801
+ this.interactiveMode = 2 /* TP_SL_DRAGGING */;
2802
+ const price = this.tpslOrderLine?.getPrice();
2803
+ this.verticalLineTime();
2804
+ this.drawTPSL({ price: price ?? 0 });
2805
+ });
2806
+ }
2807
+ createTPSLOrderLine() {
2808
+ 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);
2809
+ }
2810
+ verticalLineTime() {
2811
+ const range = this.chart.getVisibleRange();
2812
+ this.tpslVerticalLineTime = this.getTimeAtPercentage(
2813
+ range.from,
2814
+ range.to,
2815
+ 90
2816
+ );
2817
+ }
2818
+ clearTPSLElements() {
2819
+ if (this.tpslElRemoveTimer) {
2820
+ return;
2821
+ }
2822
+ this.tpslElRemoveTimer = setTimeout(() => {
2823
+ this.currentPosition = null;
2824
+ if (this.tpslOrderLine) {
2825
+ this.tpslOrderLine.remove();
2826
+ this.tpslOrderLine = null;
2827
+ }
2828
+ if (this.tpslPnLVerticalLineEntityId) {
2829
+ this.chart.removeEntity(this.tpslPnLVerticalLineEntityId);
2830
+ this.tpslPnLVerticalLineEntityId = null;
2831
+ }
2832
+ this.tpslElRemoveTimer = null;
2833
+ }, 100);
2834
+ }
2835
+ getIntersectantPosition(params) {
2836
+ if (!Array.isArray(this.lastPositions) || this.lastPositions.length === 0) {
2837
+ return null;
2838
+ }
2839
+ const { price, time } = params;
2840
+ let intersectantPosition = null;
2841
+ for (const position of this.lastPositions) {
2842
+ if (position) {
2843
+ if (Math.abs(position.open - price) < this.threshold) {
2844
+ intersectantPosition = position;
2845
+ break;
2846
+ }
2847
+ }
2848
+ }
2849
+ return intersectantPosition;
2850
+ }
2851
+ get chart() {
2852
+ return this.instance.activeChart();
2853
+ }
2854
+ getTimeAtPercentage(startTime, endTime, percentage) {
2855
+ if (typeof startTime !== "number" || typeof endTime !== "number" || typeof percentage !== "number") {
2856
+ return null;
2857
+ }
2858
+ if (percentage < 0 || percentage > 100) {
2859
+ return null;
2860
+ }
2861
+ if (startTime > endTime) {
2862
+ return null;
2863
+ }
2864
+ const duration = endTime - startTime;
2865
+ const factor = percentage / 100;
2866
+ const offset = duration * factor;
2867
+ const targetTime = startTime + offset;
2868
+ return Math.round(targetTime);
2869
+ }
2870
+ };
2871
+
2872
+ // src/tradingviewAdapter/renderer/renderer.ts
2873
+ var Renderer = class {
2874
+ constructor(instance, host, broker) {
2875
+ this.instance = instance;
2876
+ this.positionLineService = new PositionLineService(instance, broker);
2877
+ this.orderLineService = new OrderLineService(instance, broker);
2878
+ this.executionService = new ExecutionService(instance, broker);
2879
+ this.tpslService = new TPSLService(instance, broker);
2880
+ }
2881
+ async renderPositions(positions) {
2882
+ await this.chartReady();
2883
+ await this.onDataLoaded();
2884
+ this.positionLineService.renderPositions(positions);
2885
+ this.orderLineService.updatePositions(positions);
2886
+ this.tpslService.updatePositions(positions);
2887
+ }
2888
+ async renderPendingOrders(pendingOrders) {
2889
+ await this.chartReady();
2890
+ this.orderLineService.renderPendingOrders(pendingOrders);
2891
+ }
2892
+ async renderFilledOrders(filledOrders, basePriceDecimal) {
2893
+ await this.chartReady();
2894
+ await this.onDataLoaded();
2895
+ this.executionService.renderExecutions(filledOrders, basePriceDecimal);
2896
+ }
2897
+ remove() {
2898
+ this.orderLineService.removeAll();
2899
+ this.positionLineService.removePositions();
2900
+ this.executionService.destroy();
2901
+ }
2902
+ onDataLoaded() {
2903
+ if (this.instance.activeChart().symbolExt()) {
2904
+ return Promise.resolve();
2905
+ }
2906
+ return new Promise(
2907
+ (resolve) => this.instance.activeChart().onDataLoaded().subscribe(
2908
+ null,
2909
+ () => {
2910
+ resolve();
2911
+ },
2912
+ true
2913
+ )
2914
+ );
2915
+ }
2916
+ chartReady() {
2917
+ return new Promise(
2918
+ (resolve) => this.instance.onChartReady(() => {
2919
+ try {
2920
+ this.instance.activeChart().dataReady(() => resolve());
2921
+ } catch (err) {
2922
+ if (err.toString().includes("tradingViewApi")) ;
2923
+ }
2924
+ })
2925
+ );
2926
+ }
2927
+ };
2928
+
2929
+ // src/tradingviewAdapter/hooks/useCreateRenderer.ts
2930
+ function useCreateRenderer(symbol, displayControlSetting) {
2931
+ const [renderer, setRenderer] = useState();
2932
+ const rendererRef = useRef();
2933
+ const { state } = useAccount();
2934
+ const [unPnlPriceBasis] = useLocalStorage("unPnlPriceBasis", "markPrice");
2935
+ const [{ rows: positions }, positionsInfo] = usePositionStream(symbol, {
2936
+ calcMode: unPnlPriceBasis
2937
+ });
2938
+ const [pendingOrders] = useOrderStream({
2939
+ status: OrderStatus.INCOMPLETE,
2940
+ symbol
2941
+ });
2942
+ const config = useSymbolsInfo();
2943
+ const symbolInfo = config?.[symbol];
2944
+ const quote_dp = symbolInfo("quote_dp");
2945
+ const [fillOrders] = useOrderStream({
2946
+ symbol,
2947
+ status: OrderStatus.FILLED,
2948
+ size: 500
2949
+ });
2950
+ const createRenderer = useRef(
2951
+ (instance, host, broker, container) => {
2952
+ if (rendererRef.current) {
2953
+ rendererRef.current.remove();
2954
+ }
2955
+ rendererRef.current = new Renderer(instance, host, broker);
2956
+ setRenderer(rendererRef.current);
2957
+ }
2958
+ );
2959
+ const removeRenderer = useRef(() => {
2960
+ rendererRef.current?.remove();
2961
+ rendererRef.current = void 0;
2962
+ });
2963
+ useEffect(() => {
2964
+ if (state.status < AccountStatusEnum.EnableTrading && state.status !== AccountStatusEnum.EnableTradingWithoutConnected) {
2965
+ renderer?.renderPositions([]);
2966
+ return;
2967
+ }
2968
+ if (!displayControlSetting || !displayControlSetting.position) {
2969
+ renderer?.renderPositions([]);
2970
+ return;
2971
+ }
2972
+ const positionList = (positions ?? []).filter((_) => _.symbol === symbol).map((item) => {
2973
+ return {
2974
+ symbol: item.symbol,
2975
+ open: item.average_open_price,
2976
+ balance: item.position_qty,
2977
+ closablePosition: 9999,
2978
+ // @ts-ignore
2979
+ unrealPnl: item.unrealized_pnl ?? 0,
2980
+ interest: 0,
2981
+ unrealPnlDecimal: 2,
2982
+ basePriceDecimal: 4
2983
+ };
2984
+ });
2985
+ renderer?.renderPositions(positionList);
2986
+ }, [renderer, positions, symbol, displayControlSetting, state]);
2987
+ useEffect(() => {
2988
+ if (!displayControlSetting || !displayControlSetting.buySell) {
2989
+ renderer?.renderFilledOrders([], 6);
2990
+ return;
2991
+ }
2992
+ const currentSymbolFillOrders = fillOrders?.filter(
2993
+ (item) => item.symbol === symbol
2994
+ );
2995
+ renderer?.renderFilledOrders(currentSymbolFillOrders ?? [], quote_dp ?? 6);
2996
+ }, [renderer, fillOrders, symbol, quote_dp, displayControlSetting]);
2997
+ useEffect(() => {
2998
+ let tpslOrder = [];
2999
+ let positionTpsl = [];
3000
+ let limitOrder = [];
3001
+ let stopOrder = [];
3002
+ let bracketOrder = [];
3003
+ let trailingStopOrder = [];
3004
+ if (state.status < AccountStatusEnum.EnableTrading && state.status !== AccountStatusEnum.EnableTradingWithoutConnected) {
3005
+ renderer?.renderPendingOrders([]);
3006
+ return;
3007
+ }
3008
+ const symbolPosition = (positions ?? []).find(
3009
+ (item) => item.symbol === symbol
3010
+ );
3011
+ pendingOrders?.forEach((order) => {
3012
+ if (symbol !== order.symbol) {
3013
+ return;
3014
+ }
3015
+ if (!order.algo_order_id) {
3016
+ limitOrder.push(order);
3017
+ } else if (order.algo_order_id) {
3018
+ if (order.algo_type === "POSITIONAL_TP_SL" /* POSITIONAL_TP_SL */) {
3019
+ for (const child_order of order.child_orders) {
3020
+ child_order.root_algo_order_algo_type = order.algo_type;
3021
+ if (child_order.trigger_price && child_order.status !== OrderStatus.FILLED) {
3022
+ positionTpsl.push(child_order);
3023
+ }
3024
+ }
3025
+ } else if (order.algo_type === "TP_SL" /* TP_SL */) {
3026
+ if (symbolPosition) {
3027
+ for (const child_order of order.child_orders) {
3028
+ child_order.root_algo_order_algo_type = order.algo_type;
3029
+ child_order.position_qty = symbolPosition.position_qty;
3030
+ if (child_order.trigger_price && child_order.status !== OrderStatus.FILLED) {
3031
+ tpslOrder.push(child_order);
3032
+ }
3033
+ }
3034
+ }
3035
+ } else if (order.algo_type === "STOP_LOSS" /* STOP_LOSS */ || order.algo_type === "TAKE_PROFIT" /* TAKE_PROFIT */) {
3036
+ stopOrder.push(order);
3037
+ } else if (order.algo_type === "BRACKET" /* BRACKET */) {
3038
+ bracketOrder.push(order);
3039
+ } else if (order.algo_type === "TRAILING_STOP" /* TRAILING_STOP */) {
3040
+ if (order.is_activated && order.extreme_price) {
3041
+ trailingStopOrder.push(order);
3042
+ }
3043
+ }
3044
+ }
3045
+ });
3046
+ if (displayControlSetting) {
3047
+ if (!displayControlSetting.positionTpsl) {
3048
+ positionTpsl = [];
3049
+ }
3050
+ if (!displayControlSetting.tpsl) {
3051
+ tpslOrder = [];
3052
+ }
3053
+ if (!displayControlSetting.limitOrders) {
3054
+ limitOrder = [];
3055
+ bracketOrder = [];
3056
+ }
3057
+ if (!displayControlSetting.stopOrders) {
3058
+ stopOrder = [];
3059
+ }
3060
+ if (!displayControlSetting.trailingStop) {
3061
+ trailingStopOrder = [];
3062
+ }
3063
+ }
3064
+ renderer?.renderPendingOrders(
3065
+ tpslOrder.concat(positionTpsl).concat(limitOrder).concat(stopOrder).concat(bracketOrder).concat(trailingStopOrder)
3066
+ );
3067
+ }, [
3068
+ renderer,
3069
+ pendingOrders,
3070
+ symbol,
3071
+ displayControlSetting,
3072
+ positions,
3073
+ state.status
3074
+ ]);
3075
+ return [createRenderer.current, removeRenderer.current];
3076
+ }
3077
+
3078
+ // src/tradingviewAdapter/renderer/brokerHostHandler.ts
3079
+ function preventDefaultRenderHack(host) {
3080
+ host.setBrokerConnectionAdapter = function(adapter) {
3081
+ const delegate = {
3082
+ subscribe: () => {
3083
+ },
3084
+ unsubscribe: () => {
3085
+ },
3086
+ unsubscribeAll: () => {
3087
+ }
3088
+ };
3089
+ Object.defineProperty(adapter, "_ordersCache", {
3090
+ get: function() {
3091
+ return {
3092
+ start: () => {
3093
+ },
3094
+ stop: () => {
3095
+ },
3096
+ update: () => {
3097
+ },
3098
+ partialUpdate: () => {
3099
+ },
3100
+ fullUpdate: () => {
3101
+ },
3102
+ getObjects: async () => [],
3103
+ updateDelegate: delegate,
3104
+ partialUpdateDelegate: delegate
3105
+ };
3106
+ },
3107
+ set: () => {
3108
+ }
3109
+ });
3110
+ adapter._waitForOrderModification = async () => true;
3111
+ this._adapter = adapter;
3112
+ };
3113
+ }
3114
+ function forceSilentOrdersPlacement(instance, host) {
3115
+ instance.onChartReady(() => {
3116
+ host.silentOrdersPlacement().subscribe((val) => {
3117
+ if (!val) {
3118
+ host.silentOrdersPlacement().setValue(true);
3119
+ if (instance) {
3120
+ instance._iFrame.contentDocument.querySelector(
3121
+ ".wrapper-3X2QgaDd"
3122
+ ).className = "wrapper-3X2QgaDd highButtons-3X2QgaDd";
3123
+ }
3124
+ host.sellBuyButtonsVisibility()?.setValue(false);
3125
+ }
3126
+ });
3127
+ });
3128
+ }
3129
+ function brokerHostHandler(instance, host) {
3130
+ preventDefaultRenderHack(host);
3131
+ forceSilentOrdersPlacement(instance, host);
3132
+ }
3133
+
3134
+ // src/tradingviewAdapter/widget/util.ts
3135
+ var waitForElm = (iframeDocument, selector) => {
3136
+ return new Promise((resolve) => {
3137
+ const initialIframe = iframeDocument.querySelector(selector);
3138
+ if (initialIframe) {
3139
+ resolve(initialIframe);
3140
+ }
3141
+ const observer = new MutationObserver(() => {
3142
+ const iframe = iframeDocument.querySelector(selector);
3143
+ if (iframe) {
3144
+ resolve(iframe);
3145
+ observer.disconnect();
3146
+ }
3147
+ });
3148
+ observer.observe(iframeDocument, {
3149
+ childList: true,
3150
+ subtree: true
3151
+ });
3152
+ });
3153
+ };
3154
+
3155
+ // src/tradingviewAdapter/widget/chart_hack.ts
3156
+ var ChartHack = class {
3157
+ constructor({ iframeDocument }) {
3158
+ this.iframeDocument = iframeDocument;
3159
+ }
3160
+ defaultHack() {
3161
+ this.showFavoriteStarByDefault();
3162
+ }
3163
+ showFavoriteStarByDefault() {
3164
+ waitForElm(this.iframeDocument, ".dropdown-2R6OKuTS").then(() => {
3165
+ const items = this.iframeDocument.querySelectorAll(
3166
+ ".toolbox-2IihgTnv.showOnHover-2IihgTnv"
3167
+ );
3168
+ items.forEach((item) => {
3169
+ item.style.opacity = "1";
3170
+ });
3171
+ });
3172
+ }
3173
+ };
3174
+
3175
+ // src/tradingviewAdapter/widget/option.ts
3176
+ var getDisabledFeatures = (mode) => {
3177
+ let disabledFeatures = [
3178
+ "header_symbol_search",
3179
+ "volume_force_overlay",
3180
+ "trading_account_manager",
3181
+ "drawing_templates",
3182
+ "open_account_manager",
3183
+ "right_toolbar",
3184
+ "support_multicharts",
3185
+ "header_layouttoggle",
3186
+ "order_panel",
3187
+ "order_info",
3188
+ "trading_notifications",
3189
+ "display_market_status",
3190
+ "broker_button",
3191
+ "add_to_watchlist",
3192
+ "chart_crosshair_menu",
3193
+ "header_fullscreen_button",
3194
+ "header_widget"
3195
+ ];
3196
+ if (mode === 3 /* MOBILE */) {
3197
+ disabledFeatures = [
3198
+ ...disabledFeatures,
3199
+ "left_toolbar",
3200
+ "timeframes_toolbar",
3201
+ "go_to_date",
3202
+ "timezone_menu",
3203
+ // add volume back
3204
+ "create_volume_indicator_by_default",
3205
+ "buy_sell_buttons"
3206
+ ];
3207
+ }
3208
+ if (mode === 0 /* BASIC */) {
3209
+ disabledFeatures = [
3210
+ ...disabledFeatures,
3211
+ "header_widget",
3212
+ "left_toolbar",
3213
+ "timeframes_toolbar",
3214
+ "buy_sell_buttons"
3215
+ ];
3216
+ } else if (mode === 1 /* ADVANCED */) {
3217
+ disabledFeatures = [
3218
+ ...disabledFeatures,
3219
+ "left_toolbar",
3220
+ "timeframes_toolbar",
3221
+ "buy_sell_buttons"
3222
+ ];
3223
+ }
3224
+ return disabledFeatures;
3225
+ };
3226
+ function getOptions(options, mode, externalEnabledFeatures, externalDisabledFeatures) {
3227
+ const defaultEnabledFeatures = [
3228
+ "hide_left_toolbar_by_default",
3229
+ "order_panel_close_button",
3230
+ "iframe_loading_compatibility_mode"
3231
+ ];
3232
+ const mergedEnabledFeatures = Array.from(
3233
+ /* @__PURE__ */ new Set([...defaultEnabledFeatures, ...externalEnabledFeatures || []])
3234
+ );
3235
+ const defaultDisabledFeatures = getDisabledFeatures(mode);
3236
+ const mergedDisabledFeatures = Array.from(
3237
+ /* @__PURE__ */ new Set([...defaultDisabledFeatures, ...externalDisabledFeatures || []])
3238
+ );
3239
+ return {
3240
+ ...options,
3241
+ disabled_features: mergedDisabledFeatures,
3242
+ enabled_features: mergedEnabledFeatures,
3243
+ auto_save_delay: 0.1,
3244
+ broker_config: {
3245
+ configFlags: {
3246
+ supportStopLimitOrders: true,
3247
+ supportReversePosition: false
3248
+ }
3249
+ }
3250
+ };
3251
+ }
3252
+
3253
+ // src/tradingviewAdapter/widget/persistUtils.ts
3254
+ var getChartSettingAdapterKey = (chartKey) => `${chartKey}_adapter`;
3255
+ var defaultSettings = {
3256
+ "trading.chart.proterty": JSON.stringify({
3257
+ showSellBuyButtons: 0,
3258
+ noConfirmEnabled: 1,
3259
+ qweqrq: 0,
3260
+ showPricesWithZeroVolume: 1,
3261
+ showSpread: 1,
3262
+ orderExecutedSoundParams: '{"enabled":0,"name":"alert/alarm_clock"}'
3263
+ }),
3264
+ "hint.startFocusedZoom": "true"
3265
+ };
3266
+ var chartCacheMap = /* @__PURE__ */ new Map();
3267
+ var parseAndCacheChartData = (chartKey, savedDataString, adapterSettingString) => {
3268
+ const settingAdapterKey = getChartSettingAdapterKey(chartKey);
3269
+ try {
3270
+ const transformedSavedDataString = savedDataString;
3271
+ const savedData = transformedSavedDataString ? JSON.parse(transformedSavedDataString) : void 0;
3272
+ const adapterSetting = adapterSettingString ? JSON.parse(adapterSettingString) : defaultSettings;
3273
+ if (transformedSavedDataString) {
3274
+ chartCacheMap.set(chartKey, transformedSavedDataString);
3275
+ }
3276
+ if (adapterSettingString) {
3277
+ chartCacheMap.set(settingAdapterKey, adapterSettingString);
3278
+ }
3279
+ return { savedData, adapterSetting };
3280
+ } catch (e) {
3281
+ }
3282
+ return { savedData: void 0, adapterSetting: defaultSettings };
3283
+ };
3284
+ var getChartData = async (chartKey, isLoggedIn) => {
3285
+ const settingAdapterKey = getChartSettingAdapterKey(chartKey);
3286
+ const localStorageSavedData = localStorage.getItem(chartKey) || "";
3287
+ const localStorageAdapterSetting = localStorage.getItem(settingAdapterKey) || "";
3288
+ try {
3289
+ if (chartCacheMap.has(chartKey) && chartCacheMap.has(settingAdapterKey)) {
3290
+ return {
3291
+ savedData: JSON.parse(chartCacheMap.get(chartKey)),
3292
+ adapterSetting: JSON.parse(chartCacheMap.get(settingAdapterKey))
3293
+ };
3294
+ }
3295
+ } catch (e) {
3296
+ }
3297
+ return parseAndCacheChartData(
3298
+ chartKey,
3299
+ localStorageSavedData,
3300
+ localStorageAdapterSetting
3301
+ );
3302
+ };
3303
+ var saveChartData = async (chartKey, setting, isLoggedIn) => {
3304
+ if (setting) {
3305
+ localStorage.setItem(chartKey, setting);
3306
+ chartCacheMap.set(chartKey, setting);
3307
+ }
3308
+ };
3309
+ var saveChartAdapterSetting = async (chartKey, setting, isLoggedIn) => {
3310
+ const settingAdapterKey = getChartSettingAdapterKey(chartKey);
3311
+ if (setting) {
3312
+ localStorage.setItem(settingAdapterKey, setting);
3313
+ chartCacheMap.set(settingAdapterKey, setting);
3314
+ }
3315
+ };
3316
+
3317
+ // src/tradingviewAdapter/widget/index.ts
3318
+ var debounce = (func, delay) => {
3319
+ let timer = null;
3320
+ const debounced = (...args) => {
3321
+ timer && window.clearTimeout(timer);
3322
+ timer = setTimeout(() => {
3323
+ func(...args);
3324
+ }, delay);
3325
+ };
3326
+ debounced.cancel = () => {
3327
+ timer && window.clearTimeout(timer);
3328
+ timer = null;
3329
+ };
3330
+ return debounced;
3331
+ };
3332
+ var DEFAULT_SETTINGS_KEY = "chartProp_default";
3333
+ var DEBOUNCE_SAVE_TIME = 300;
3334
+ var Widget = class {
3335
+ constructor(props) {
3336
+ this._instance = null;
3337
+ this._onClick = null;
3338
+ this._datafeed = null;
3339
+ this._chartKey = DEFAULT_SETTINGS_KEY;
3340
+ this._adapterSetting = defaultSettings;
3341
+ this._savedData = null;
3342
+ this._isLoggedIn = false;
3343
+ this.debounceSaveChart = debounce(() => {
3344
+ try {
3345
+ this._instance?.save((chartProps) => {
3346
+ if (!Object.is(this._savedData, chartProps)) {
3347
+ this._savedData = chartProps;
3348
+ saveChartData(
3349
+ this._chartKey,
3350
+ JSON.stringify(chartProps),
3351
+ this._isLoggedIn
3352
+ );
3353
+ }
3354
+ });
3355
+ } catch (e) {
3356
+ }
3357
+ }, DEBOUNCE_SAVE_TIME * 2);
3358
+ this.debounceSaveChartAdapterSetting = debounce(() => {
3359
+ saveChartAdapterSetting(
3360
+ this._chartKey,
3361
+ JSON.stringify(this._adapterSetting),
3362
+ this._isLoggedIn
3363
+ );
3364
+ }, DEBOUNCE_SAVE_TIME);
3365
+ this._create(props);
3366
+ }
3367
+ remove() {
3368
+ this.unsubscribeClick();
3369
+ this._datafeed?.remove();
3370
+ this._broker?.remove();
3371
+ this._instance?.remove();
3372
+ this.debounceSaveChart.cancel();
3373
+ this.debounceSaveChartAdapterSetting.cancel();
3374
+ }
3375
+ updateOverrides(overrides) {
3376
+ if (!this.instance) {
3377
+ return;
3378
+ }
3379
+ this.instance.applyOverrides(overrides);
3380
+ }
3381
+ setSymbol(symbol, interval, callback) {
3382
+ try {
3383
+ this._instance?.onChartReady(() => {
3384
+ let currentInterval = interval ?? this._instance?.symbolInterval()?.interval;
3385
+ if (!currentInterval) {
3386
+ currentInterval = 1;
3387
+ }
3388
+ this._instance?.setSymbol(symbol, currentInterval, callback);
3389
+ });
3390
+ } catch (e) {
3391
+ }
3392
+ }
3393
+ executeActionById(actionId) {
3394
+ try {
3395
+ this._instance?.onChartReady(() => {
3396
+ this._instance?.activeChart().executeActionById(actionId);
3397
+ });
3398
+ } catch (e) {
3399
+ }
3400
+ }
3401
+ changeLineType(lineType) {
3402
+ try {
3403
+ this._instance?.onChartReady(() => {
3404
+ this._instance?.activeChart().setChartType(lineType);
3405
+ });
3406
+ } catch (e) {
3407
+ }
3408
+ }
3409
+ subscribeClick(onClick) {
3410
+ this._onClick = onClick;
3411
+ this._instance?.onChartReady(() => {
3412
+ this._instance?._iFrame.contentDocument?.addEventListener(
3413
+ "click",
3414
+ this._onClick
3415
+ );
3416
+ });
3417
+ }
3418
+ unsubscribeClick() {
3419
+ this._instance?._iFrame.contentDocument?.removeEventListener(
3420
+ "click",
3421
+ this._onClick
3422
+ );
3423
+ }
3424
+ get instance() {
3425
+ return this._instance;
3426
+ }
3427
+ chartHack() {
3428
+ this._instance?.onChartReady(() => {
3429
+ const iframeDocument = this._instance._iFrame.contentWindow.document;
3430
+ new ChartHack({ iframeDocument }).defaultHack();
3431
+ });
3432
+ }
3433
+ subscribeAutoSave() {
3434
+ this._instance?.onChartReady(() => {
3435
+ this._instance?.subscribe("onAutoSaveNeeded", () => {
3436
+ this.debounceSaveChart();
3437
+ });
3438
+ this._instance?.activeChart().onVisibleRangeChanged().subscribe(null, () => {
3439
+ this.debounceSaveChart();
3440
+ });
3441
+ });
3442
+ }
3443
+ async _create({
3444
+ options,
3445
+ chartKey,
3446
+ mode,
3447
+ onClick,
3448
+ enabled_features,
3449
+ disabled_features
3450
+ }) {
3451
+ const getBroker = options.getBroker;
3452
+ const widgetOptions = {
3453
+ fullscreen: options.fullscreen ?? true,
3454
+ autosize: options.autosize ?? false,
3455
+ timezone: options.timezone,
3456
+ symbol: options.symbol,
3457
+ library_path: options.libraryPath,
3458
+ interval: options.interval ?? "1",
3459
+ custom_css_url: options.customCssUrl,
3460
+ custom_font_family: options.customFontFamily,
3461
+ datafeed: options.datafeed,
3462
+ studies_overrides: options.studiesOverrides,
3463
+ locale: options.locale,
3464
+ theme: options.theme,
3465
+ loading_screen: options.loadingScreen,
3466
+ overrides: options.overrides,
3467
+ container: options.container,
3468
+ favorites: {
3469
+ intervals: [
3470
+ "1",
3471
+ "3",
3472
+ "5",
3473
+ "15",
3474
+ "30",
3475
+ "60",
3476
+ "240",
3477
+ "1D",
3478
+ "1W",
3479
+ "1M"
3480
+ ],
3481
+ chartTypes: ["Area", "Line"]
3482
+ },
3483
+ broker_factory: getBroker ? (host) => {
3484
+ if (this._broker) {
3485
+ this._broker.remove();
3486
+ }
3487
+ this._broker = getBroker(
3488
+ this._instance,
3489
+ host
3490
+ );
3491
+ return this._broker;
3492
+ } : void 0
3493
+ };
3494
+ this._datafeed = options.datafeed;
3495
+ if (chartKey) {
3496
+ this._chartKey = chartKey;
3497
+ }
3498
+ const { savedData, adapterSetting } = await getChartData(
3499
+ this._chartKey,
3500
+ this._isLoggedIn
3501
+ );
3502
+ this._adapterSetting = adapterSetting;
3503
+ this._savedData = savedData;
3504
+ this._instance = new TradingView.widget({
3505
+ ...getOptions(widgetOptions, mode, enabled_features, disabled_features),
3506
+ interval: adapterSetting["chart.lastUsedTimeBasedResolution"] ?? widgetOptions.interval,
3507
+ saved_data: savedData,
3508
+ settings_adapter: {
3509
+ initialSettings: adapterSetting,
3510
+ setValue: (key, value) => {
3511
+ this._adapterSetting = { ...this._adapterSetting, [key]: value };
3512
+ this.debounceSaveChartAdapterSetting();
3513
+ },
3514
+ removeValue: () => {
3515
+ }
3516
+ }
3517
+ });
3518
+ this._instance.onChartReady(() => {
3519
+ if (options.symbol && this._instance?.activeChart().symbol() !== withoutExchangePrefix(options.symbol)) {
3520
+ this.setSymbol(options.symbol);
3521
+ }
3522
+ });
3523
+ this.subscribeAutoSave();
3524
+ this.subscribeClick(onClick);
3525
+ this.chartHack();
3526
+ }
3527
+ };
3528
+
3529
+ // src/components/tradingview.script.ts
3530
+ var CHART_KEY = "SDK_Tradingview";
3531
+ var MOBILE_CHART_KEY = "SDK_Moblie_Tradingview";
3532
+ var getChartKey = (isMobile) => {
3533
+ return isMobile ? MOBILE_CHART_KEY : CHART_KEY;
3534
+ };
3535
+ var defaultLocale = (localeCode) => {
3536
+ return localeCode === "id" ? "id_ID" : localeCode === "tc" ? "zh_TW" : localeCode;
3537
+ };
3538
+ function useTradingviewScript(props) {
3539
+ const {
3540
+ scriptSRC: tradingViewScriptSrc,
3541
+ libraryPath,
3542
+ customCssUrl: tradingViewCustomCssUrl,
3543
+ overrides: customerOverrides,
3544
+ studiesOverrides: customerStudiesOverrides,
3545
+ symbol,
3546
+ theme,
3547
+ loadingScreen: customerLoadingScreen,
3548
+ mode,
3549
+ colorConfig: customerColorConfig,
3550
+ locale = defaultLocale,
3551
+ classNames,
3552
+ enabled_features,
3553
+ disabled_features
3554
+ } = props;
3555
+ const localeCode = useLocaleCode();
3556
+ const chart = useRef(null);
3557
+ const apiBaseUrl = useConfig("apiBaseUrl");
3558
+ const { state: accountState } = useAccount();
3559
+ const [side, setSide] = useState(OrderSide.SELL);
3560
+ const symbolsInfo = useSymbolsInfo();
3561
+ const [fullscreen, setFullscreen] = useLocalStorage(
3562
+ TradingviewFullscreenKey,
3563
+ false
3564
+ );
3565
+ const { onSubmit, submitting } = useOrderEntry_deprecated(
3566
+ {
3567
+ symbol: symbol ?? "",
3568
+ side,
3569
+ order_type: OrderType.MARKET
3570
+ },
3571
+ {
3572
+ watchOrderbook: true
3573
+ }
3574
+ );
3575
+ const [displayControlState, setDisplayControlState] = useState(() => {
3576
+ const displaySettingInfo = localStorage.getItem(
3577
+ TradingViewSDKLocalstorageKey.displayControlSetting
3578
+ );
3579
+ if (displaySettingInfo) {
3580
+ return JSON.parse(displaySettingInfo);
3581
+ }
3582
+ return {
3583
+ position: true,
3584
+ buySell: true,
3585
+ limitOrders: true,
3586
+ stopOrders: true,
3587
+ tpsl: true,
3588
+ positionTpsl: true,
3589
+ trailingStop: true
3590
+ };
3591
+ });
3592
+ const [interval, setInterval] = useState(() => {
3593
+ const lastUsedInterval = localStorage.getItem(
3594
+ TradingViewSDKLocalstorageKey.interval
3595
+ );
3596
+ if (!lastUsedInterval) {
3597
+ return "15";
3598
+ }
3599
+ return lastUsedInterval;
3600
+ });
3601
+ const [lineType, setLineType] = useState(() => {
3602
+ const lastUsedLineType = localStorage.getItem(
3603
+ TradingViewSDKLocalstorageKey.lineType
3604
+ );
3605
+ if (!lastUsedLineType) {
3606
+ return "1";
3607
+ }
3608
+ return lastUsedLineType;
3609
+ });
3610
+ const isMobile = useMediaQuery(MEDIA_TABLET);
3611
+ const colorConfig = useMemo(
3612
+ () => Object.assign({}, defaultColorConfig, customerColorConfig ?? {}),
3613
+ [customerColorConfig]
3614
+ );
3615
+ const loadingScreen = useMemo(() => {
3616
+ if (typeof customerLoadingScreen === "object") {
3617
+ return customerLoadingScreen;
3618
+ }
3619
+ return {
3620
+ backgroundColor: chartBG
3621
+ };
3622
+ }, [customerLoadingScreen]);
3623
+ const ws = useWS();
3624
+ const [chartingLibrarySciprtReady, setChartingLibrarySciprtReady] = useState(false);
3625
+ const closePositionConfirmCallback = (data) => {
3626
+ const symbolInfo = symbolsInfo[symbol];
3627
+ if (!symbolInfo) {
3628
+ return;
3629
+ }
3630
+ const side2 = new Decimal(data.balance).greaterThan(0) ? OrderSide.SELL : OrderSide.BUY;
3631
+ const order = {
3632
+ // order_price: undefined,
3633
+ order_quantity: new Decimal(data.balance).abs().toNumber(),
3634
+ symbol,
3635
+ order_type: OrderType.MARKET,
3636
+ side: side2,
3637
+ reduce_only: true
3638
+ };
3639
+ setSide(side2);
3640
+ modal.show("MarketCloseConfirmID", {
3641
+ base: symbolInfo("base"),
3642
+ quantity: data.balance,
3643
+ onConfirm: async () => {
3644
+ return onSubmit(order).catch((error) => {
3645
+ if (typeof error === "string") {
3646
+ toast.error(error);
3647
+ } else {
3648
+ toast.error(error.message);
3649
+ }
3650
+ });
3651
+ },
3652
+ submitting
3653
+ });
3654
+ };
3655
+ const chartRef = useRef(null);
3656
+ const isLoggedIn = useMemo(() => {
3657
+ if (accountState.status < AccountStatusEnum.EnableTrading && accountState.status !== AccountStatusEnum.EnableTradingWithoutConnected) {
3658
+ return false;
3659
+ }
3660
+ return true;
3661
+ }, [accountState]);
3662
+ const broker = useBroker_default({
3663
+ closeConfirm: closePositionConfirmCallback,
3664
+ colorConfig,
3665
+ onToast: toast,
3666
+ symbol: symbol ?? "",
3667
+ mode
3668
+ });
3669
+ const [createRenderer, removeRenderer] = useCreateRenderer(
3670
+ symbol,
3671
+ displayControlState
3672
+ );
3673
+ const onFullScreenChange = () => {
3674
+ if (fullscreen) {
3675
+ setFullscreen(false);
3676
+ } else {
3677
+ setFullscreen(true);
3678
+ }
3679
+ props.onFullScreenChange?.(!fullscreen);
3680
+ };
3681
+ const changeInterval = (newInterval) => {
3682
+ if (!chart.current) {
3683
+ return;
3684
+ }
3685
+ localStorage.setItem(TradingViewSDKLocalstorageKey.interval, newInterval);
3686
+ setInterval(newInterval);
3687
+ chart.current?.setSymbol(symbol ?? "", newInterval);
3688
+ };
3689
+ const changeLineType = (newLineType) => {
3690
+ if (!chart.current) {
3691
+ return;
3692
+ }
3693
+ localStorage.setItem(TradingViewSDKLocalstorageKey.lineType, newLineType);
3694
+ setLineType(newLineType);
3695
+ chart.current?.changeLineType(Number(newLineType));
3696
+ };
3697
+ const changeDisplaySetting = (newSetting) => {
3698
+ localStorage.setItem(
3699
+ TradingViewSDKLocalstorageKey.displayControlSetting,
3700
+ JSON.stringify(newSetting)
3701
+ );
3702
+ setDisplayControlState(newSetting);
3703
+ };
3704
+ const openChartSetting = () => {
3705
+ if (!chart.current) {
3706
+ return;
3707
+ }
3708
+ chart.current.executeActionById("chartProperties");
3709
+ };
3710
+ const openChartIndicators = () => {
3711
+ if (!chart.current) {
3712
+ return;
3713
+ }
3714
+ chart.current.executeActionById("insertIndicator");
3715
+ };
3716
+ useEffect(() => {
3717
+ if (!tradingViewScriptSrc) {
3718
+ return;
3719
+ }
3720
+ if (!chartRef.current) {
3721
+ return;
3722
+ }
3723
+ if (!chartingLibrarySciprtReady) {
3724
+ const script = document.createElement("script");
3725
+ script.setAttribute("data-nscript", "afterInteractive");
3726
+ script.src = tradingViewScriptSrc;
3727
+ script.async = true;
3728
+ script.type = "text/javascript";
3729
+ script.onload = () => {
3730
+ setChartingLibrarySciprtReady(true);
3731
+ };
3732
+ script.onerror = () => {
3733
+ };
3734
+ chartRef.current.appendChild(script);
3735
+ }
3736
+ }, [chartRef, chartingLibrarySciprtReady, tradingViewScriptSrc]);
3737
+ useEffect(() => {
3738
+ if (!symbol) {
3739
+ return;
3740
+ }
3741
+ if (!chartingLibrarySciprtReady || !tradingViewScriptSrc) {
3742
+ return;
3743
+ }
3744
+ const defaultOverrides = getOveriides(colorConfig, isMobile);
3745
+ const overrides = customerOverrides ? Object.assign({}, defaultOverrides.overrides, customerOverrides) : defaultOverrides.overrides;
3746
+ const studiesOverrides = customerStudiesOverrides ? Object.assign(
3747
+ {},
3748
+ defaultOverrides.studiesOverrides,
3749
+ customerStudiesOverrides
3750
+ ) : defaultOverrides.studiesOverrides;
3751
+ if (chartRef.current) {
3752
+ const options = {
3753
+ // fullscreen: fullscreen ?? false,
3754
+ fullscreen: false,
3755
+ autosize: true,
3756
+ symbol: withExchangePrefix(symbol),
3757
+ locale: typeof locale === "function" ? locale(localeCode) : locale,
3758
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
3759
+ container: chartRef.current,
3760
+ libraryPath,
3761
+ customCssUrl: tradingViewCustomCssUrl,
3762
+ interval: interval ?? "1",
3763
+ theme: theme ?? "dark",
3764
+ loadingScreen: loadingScreen ?? {},
3765
+ overrides,
3766
+ studiesOverrides,
3767
+ datafeed: new Datafeed(apiBaseUrl, ws),
3768
+ contextMenu: {
3769
+ items_processor: async (defaultItems) => {
3770
+ return defaultItems;
3771
+ }
3772
+ },
3773
+ // todo broker effect sell/buy
3774
+ getBroker: (instance, host) => {
3775
+ brokerHostHandler(instance, host);
3776
+ return getBrokerAdapter_default(host, broker);
3777
+ }
3778
+ // getBroker: undefined,
3779
+ };
3780
+ const chartProps = {
3781
+ options,
3782
+ chartKey: getChartKey(isMobile),
3783
+ mode,
3784
+ onClick: () => {
3785
+ },
3786
+ enabled_features,
3787
+ disabled_features
3788
+ };
3789
+ chart.current = new Widget(chartProps);
3790
+ }
3791
+ return () => {
3792
+ chart.current?.remove();
3793
+ };
3794
+ }, [
3795
+ chartingLibrarySciprtReady,
3796
+ isMobile,
3797
+ mode,
3798
+ chart,
3799
+ chartRef,
3800
+ chartingLibrarySciprtReady,
3801
+ tradingViewScriptSrc,
3802
+ colorConfig,
3803
+ locale,
3804
+ localeCode
3805
+ ]);
3806
+ useEffect(() => {
3807
+ ws.on(
3808
+ "status:change",
3809
+ (message) => {
3810
+ if (!message.isPrivate && message.isReconnect) {
3811
+ if (typeof window.onResetCacheNeededCallback === "function") {
3812
+ window.onResetCacheNeededCallback();
3813
+ if (chart.current?.instance) {
3814
+ chart.current?.instance.activeChart()?.resetData();
3815
+ }
3816
+ }
3817
+ }
3818
+ },
3819
+ "tradingview"
3820
+ );
3821
+ }, [ws]);
3822
+ useEffect(() => {
3823
+ if (chart.current && chart.current?.instance) {
3824
+ chart.current?.instance?.onChartReady(() => {
3825
+ if (isLoggedIn && chart.current?.instance) {
3826
+ createRenderer(
3827
+ chart.current.instance,
3828
+ void 0,
3829
+ broker,
3830
+ chartRef.current
3831
+ );
3832
+ }
3833
+ });
3834
+ }
3835
+ return () => {
3836
+ removeRenderer();
3837
+ };
3838
+ }, [chart.current, isLoggedIn]);
3839
+ useEffect(() => {
3840
+ if (!symbol || !chart.current) {
3841
+ return;
3842
+ }
3843
+ chart.current?.setSymbol(symbol);
3844
+ const service = new WebsocketService(ws);
3845
+ service.subscribeSymbol(symbol);
3846
+ return () => {
3847
+ service.unsubscribeKline(symbol);
3848
+ };
3849
+ }, [symbol]);
3850
+ return {
3851
+ tradingViewScriptSrc,
3852
+ chartRef,
3853
+ changeDisplaySetting,
3854
+ displayControlState,
3855
+ interval,
3856
+ changeInterval,
3857
+ lineType,
3858
+ changeLineType,
3859
+ openChartSetting,
3860
+ openChartIndicators,
3861
+ symbol,
3862
+ onFullScreenChange,
3863
+ classNames,
3864
+ fullscreen
3865
+ };
3866
+ }
3867
+
3868
+ // src/components/tradingview.ui.tsx
3869
+ init_icons();
3870
+ var Link = (props) => {
3871
+ const { url, children } = props;
3872
+ return /* @__PURE__ */ jsx(
3873
+ "span",
3874
+ {
3875
+ onClick: () => window.open(url),
3876
+ className: "oui-cursor-pointer oui-px-0.5 oui-text-primary-light oui-underline",
3877
+ children
3878
+ }
3879
+ );
3880
+ };
3881
+ var NoTradingview = () => {
3882
+ const { t } = useTranslation();
3883
+ 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: [
3884
+ /* @__PURE__ */ jsx("p", { className: "oui-mb-6 oui-text-xs", children: t("tradingView.noScriptSrc") }),
3885
+ /* @__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(
3886
+ Trans,
3887
+ {
3888
+ i18nKey: "tradingView.noScriptSrc.1",
3889
+ components: [
3890
+ /* @__PURE__ */ jsx(
3891
+ Link,
3892
+ {
3893
+ url: "https://www.tradingview.com/advanced-charts"
3894
+ },
3895
+ "tradingview-advanced-charts"
3896
+ )
3897
+ ]
3898
+ }
3899
+ ) }),
3900
+ /* @__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(
3901
+ Trans,
3902
+ {
3903
+ i18nKey: "tradingView.noScriptSrc.2",
3904
+ components: [
3905
+ /* @__PURE__ */ jsx(
3906
+ Link,
3907
+ {
3908
+ url: "https://orderly.network/docs/sdks/react/components/trading#tradingviewconfig"
3909
+ },
3910
+ "tradingview-config"
3911
+ )
3912
+ ]
3913
+ }
3914
+ ) })
3915
+ ] }) });
3916
+ };
3917
+ var TopBar = (props) => {
3918
+ 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 });
3919
+ };
3920
+ var topBar_default = TopBar;
3921
+ var LazyLineType = React3.lazy(() => Promise.resolve().then(() => (init_lineType(), lineType_exports)));
3922
+ var LazyTimeInterval = React3.lazy(
3923
+ () => Promise.resolve().then(() => (init_timeInterval(), timeInterval_exports)).then((mod) => ({ default: mod.TimeInterval }))
3924
+ );
3925
+ var LazyMobileDisplayControl = React3.lazy(
3926
+ () => Promise.resolve().then(() => (init_displayControl(), displayControl_exports)).then((mod) => ({
3927
+ default: mod.MobileDisplayControl
3928
+ }))
3929
+ );
3930
+ var LazyDesktopDisplayControl = React3.lazy(
3931
+ () => Promise.resolve().then(() => (init_displayControl(), displayControl_exports)).then((mod) => ({
3932
+ default: mod.DesktopDisplayControl
3933
+ }))
3934
+ );
3935
+ var OperateButton = ({ children, onClick }) => {
3936
+ return /* @__PURE__ */ jsx(
3937
+ Box,
3938
+ {
3939
+ onClick,
3940
+ className: "oui-cursor-pointer oui-w-[18px] oui-h-[18px] oui-text-base-contrast-36 hover:oui-text-base-contrast-80",
3941
+ children
3942
+ }
3943
+ );
3944
+ };
3945
+ var ZoomOutIcon = (props) => {
3946
+ return /* @__PURE__ */ jsx(
3947
+ "svg",
3948
+ {
3949
+ xmlns: "http://www.w3.org/2000/svg",
3950
+ width: "18",
3951
+ height: "18",
3952
+ viewBox: "0 0 18 18",
3953
+ fill: "currentColor",
3954
+ ...props,
3955
+ 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" })
3956
+ }
3957
+ );
3958
+ };
3959
+ var ZoomInIcon = (props) => {
3960
+ return /* @__PURE__ */ jsx(
3961
+ "svg",
3962
+ {
3963
+ xmlns: "http://www.w3.org/2000/svg",
3964
+ width: "18",
3965
+ height: "18",
3966
+ viewBox: "0 0 18 18",
3967
+ fill: "currentColor",
3968
+ ...props,
3969
+ 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" })
3970
+ }
3971
+ );
3972
+ };
3973
+ var TradingviewUI = forwardRef((props, ref) => {
3974
+ const {
3975
+ chartRef,
3976
+ interval,
3977
+ changeDisplaySetting,
3978
+ displayControlState,
3979
+ tradingViewScriptSrc,
3980
+ changeInterval,
3981
+ lineType,
3982
+ changeLineType,
3983
+ openChartSetting,
3984
+ openChartIndicators,
3985
+ onFullScreenChange
3986
+ } = props;
3987
+ const isMobile = useMediaQuery(MEDIA_TABLET);
3988
+ return /* @__PURE__ */ jsx(
3989
+ "div",
3990
+ {
3991
+ ref,
3992
+ className: cn("oui-relative oui-size-full", props.classNames?.root),
3993
+ children: !tradingViewScriptSrc ? /* @__PURE__ */ jsx(NoTradingview, {}) : /* @__PURE__ */ jsxs(
3994
+ "div",
3995
+ {
3996
+ className: cn(
3997
+ "oui-absolute oui-inset-0 oui-z-[1] oui-flex oui-flex-col",
3998
+ props.classNames?.content
3999
+ ),
4000
+ children: [
4001
+ /* @__PURE__ */ jsx(topBar_default, { children: isMobile ? /* @__PURE__ */ jsxs(
4002
+ Flex,
4003
+ {
4004
+ gapX: 2,
4005
+ width: "100%",
4006
+ justify: "between",
4007
+ className: "oui-hide-scrollbar oui-overflow-x-scroll",
4008
+ children: [
4009
+ /* @__PURE__ */ jsx(React3.Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
4010
+ LazyTimeInterval,
4011
+ {
4012
+ interval: interval ?? "15",
4013
+ changeInterval
4014
+ }
4015
+ ) }),
4016
+ /* @__PURE__ */ jsx(OperateButton, { onClick: openChartIndicators, children: /* @__PURE__ */ jsx(IndicatorsIcon, {}) }),
4017
+ /* @__PURE__ */ jsx(React3.Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
4018
+ LazyMobileDisplayControl,
4019
+ {
4020
+ displayControlState,
4021
+ changeDisplayControlState: changeDisplaySetting
4022
+ }
4023
+ ) })
4024
+ ]
4025
+ }
4026
+ ) : /* @__PURE__ */ jsxs(Flex, { justify: "between", itemAlign: "center", width: "100%", children: [
4027
+ /* @__PURE__ */ jsxs(Flex, { children: [
4028
+ /* @__PURE__ */ jsx(React3.Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
4029
+ LazyTimeInterval,
4030
+ {
4031
+ interval: interval ?? "1",
4032
+ changeInterval
4033
+ }
4034
+ ) }),
4035
+ /* @__PURE__ */ jsx(
4036
+ Divider,
4037
+ {
4038
+ direction: "vertical",
4039
+ className: "oui-h-4",
4040
+ mx: 2,
4041
+ intensity: 8
4042
+ }
4043
+ ),
4044
+ /* @__PURE__ */ jsxs(Flex, { justify: "start", itemAlign: "center", gap: 2, children: [
4045
+ /* @__PURE__ */ jsx(React3.Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
4046
+ LazyDesktopDisplayControl,
4047
+ {
4048
+ displayControlState,
4049
+ changeDisplayControlState: changeDisplaySetting
4050
+ }
4051
+ ) }),
4052
+ /* @__PURE__ */ jsx(OperateButton, { onClick: openChartIndicators, children: /* @__PURE__ */ jsx(IndicatorsIcon, {}) }),
4053
+ /* @__PURE__ */ jsx(React3.Suspense, { fallback: null, children: /* @__PURE__ */ jsx(
4054
+ LazyLineType,
4055
+ {
4056
+ lineType,
4057
+ changeLineType
4058
+ }
4059
+ ) }),
4060
+ /* @__PURE__ */ jsx(OperateButton, { onClick: openChartSetting, children: /* @__PURE__ */ jsx(SettingIcon, {}) })
4061
+ ] })
4062
+ ] }),
4063
+ /* @__PURE__ */ jsx(Flex, { children: props.fullscreen ? /* @__PURE__ */ jsx(
4064
+ ZoomOutIcon,
4065
+ {
4066
+ className: "oui-text-base-contrast-54 hover:oui-text-base-contrast oui-cursor-pointer",
4067
+ onClick: onFullScreenChange
4068
+ }
4069
+ ) : /* @__PURE__ */ jsx(
4070
+ ZoomInIcon,
4071
+ {
4072
+ className: "oui-text-base-contrast-54 hover:oui-text-base-contrast oui-cursor-pointer",
4073
+ onClick: onFullScreenChange
4074
+ }
4075
+ ) })
4076
+ ] }) }),
4077
+ /* @__PURE__ */ jsx("div", { ref: chartRef, className: "oui-size-full oui-overflow-hidden" })
4078
+ ]
4079
+ }
4080
+ )
4081
+ }
4082
+ );
4083
+ });
4084
+ var TradingviewWidget = forwardRef((props, ref) => {
4085
+ const state = useTradingviewScript(props);
4086
+ return /* @__PURE__ */ jsx(TradingviewUI, { ...state, ref });
4087
+ });
4088
+
4089
+ export { TradingviewUI, TradingviewWidget, useTradingviewScript };
13
4090
  //# sourceMappingURL=out.js.map
14
4091
  //# sourceMappingURL=index.mjs.map