UNPKG

@orderly.network/ui-tradingview

Version:

10 lines (9 loc) 75.7 kB
import go, { forwardRef, useState, useMemo, useRef, useEffect, useCallback } from 'react'; import { useMediaQuery, useConfig, useAccount, useSymbolsInfo, useLocalStorage, useOrderEntry_deprecated, useWS, usePositionStream, useOrderStream, useEventEmitter } from '@orderly.network/hooks'; import { useTranslation, Trans, useLocaleCode, i18n } from '@orderly.network/i18n'; import { MEDIA_TABLET, OrderSide, TradingviewFullscreenKey, OrderType, AccountStatusEnum, OrderStatus } from '@orderly.network/types'; import { cn, Flex, Divider, DropdownMenuRoot, DropdownMenuTrigger, DropdownMenuPortal, DropdownMenuContent, Text, Switch, Box, toast, modal } from '@orderly.network/ui'; import { Decimal, commify } from '@orderly.network/utils'; import { startOfSecond, startOfMinute, startOfHour, startOfDay, startOfMonth, startOfYear, startOfWeek } from 'date-fns'; import { jsx, jsxs, Fragment } from 'react/jsx-runtime'; var qr="#008676",Gr="#D92D6B",ke="#131519",Wr="#00B49E",Qr="#FF447C",$r="#333948",Zr="#FFFFFF",zr="#F4F7F9",jr="regular 11px Manrope",ht={upColor:qr,downColor:Gr,chartBG:ke,pnlUpColor:Wr,pnlDownColor:Qr,pnlZoreColor:$r,textColor:Zr,qtyTextColor:zr,font:jr,volumeUpColor:"#0C3E3A",volumeDownColor:"#5A1E36",closeIcon:"rgba(255, 255, 255, 0.8)"},ft=(i,e)=>{let t={"paneProperties.background":i.chartBG,"paneProperties.backgroundType":"solid","mainSeriesProperties.candleStyle.upColor":i.upColor,"mainSeriesProperties.candleStyle.downColor":i.downColor,"mainSeriesProperties.candleStyle.borderColor":i.upColor,"mainSeriesProperties.candleStyle.borderUpColor":i.upColor,"mainSeriesProperties.candleStyle.borderDownColor":i.downColor,"mainSeriesProperties.candleStyle.wickUpColor":i.upColor,"mainSeriesProperties.candleStyle.wickDownColor":i.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"},r={"volume.volume.color.0":i.volumeDownColor,"volume.volume.color.1":i.volumeUpColor};return {overrides:t,studiesOverrides:r}},oe="Orderly",L=i=>i.includes(":")?i.split(":")[1]:i,ne=i=>i.startsWith(`${oe}:`)?i:`${oe}:${i}`;var Xr=(i,e)=>{let r,o=s=>[null,"limit","MARKET","STOP_MARKET","STOP_LIMIT"][s];return {symbolInfo:async s=>(r=e.getSymbolInfo(L(s)),{qty:{min:r?.baseMin??0,max:r?.baseMax??0,step:r?.baseTick??0},pipValue:0,pipSize:r?.quoteTick??0,minTick:r?.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=L(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=>i.defaultContextMenuActions(s),isTradable:async()=>true,accountManagerInfo:()=>({}),currentAccount:()=>"1",accountsMetainfo:async()=>[{id:"1"}],remove:()=>i?.silentOrdersPlacement().unsubscribe()}},bt=Xr;function B(i){return i===void 0?"":typeof i=="string"?i:i.message}var ae=class{constructor(e,t,r){this._datafeedUrl=e,this._requester=t,this._limitedServerResponse=r;}getBars(e,t,r){let o={symbol:e.ticker||"",resolution:t,from:r.from,to:r.to};return r.countBack!==void 0&&(o.countback=r.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=B(a);n(c);}}})}async _processTruncatedResponse(e,t){let r=e.bars.length;try{for(;this._limitedServerResponse&&this._limitedServerResponse.maxResponseLength>0&&this._limitedServerResponse.maxResponseLength===r&&t.from<t.to;){t.countback&&(t.countback=t.countback-r),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);r=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"){B(o);}}}_processHistoryResponse(e){if(e.s!=="ok"&&e.s!=="no_data")throw new Error(e.errmsg);let t=[],r={noData:false};if(e.s==="no_data")r.noData=true,r.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:r}}};var le=class{constructor(e){e&&(this._headers=e);}sendRequest(e,t,r){if(r!==void 0){let s=Object.keys(r);s.length!==0&&(t+="?"),t+=s.map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(r[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 h(i,e,t,r){let o=i[e];return Array.isArray(o)&&(!r||Array.isArray(o[0]))?o[t]:o}function ce(i,e,t){return i+(e!==void 0?"_%|#|%_"+e:"")+(t!==void 0?"_%|#|%_"+t:"")}var ue=class{constructor(e,t,r){this._exchangesList=["Orderly"];this._symbolsInfo={};this._symbolsList=[];this._datafeedUrl=e,this._datafeedSupportedResolutions=t,this._requester=r,this._readyPromise=this._init(),this._readyPromise.catch(o=>{});}resolveSymbol(e,t,r){return this._readyPromise.then(()=>{let o=this._symbolsInfo[ce(e,t,r)];return o===void 0?Promise.reject("invalid symbol"):Promise.resolve(o)})}searchSymbols(e,t,r,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||r.length>0&&l.type!==r||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 r of this._exchangesList)t[r]||(t[r]=true,e.push(this._requestExchangeData(r)));return Promise.all(e).then(()=>{this._symbolsList.sort();})}_requestExchangeData(e){return new Promise((t,r)=>{this._requester.sendRequest(this._datafeedUrl,"symbol_info",{group:e}).then(o=>{try{this._onExchangeDataReceived(e,o);}catch(s){r(s instanceof Error?s:new Error(`SymbolsStorage: Unexpected exception ${s}`));return}t();}).catch(o=>{`${e}${B(o)}`,t();});})}_onExchangeDataReceived(e,t){let r=0;try{let o=t.symbol.length,s=t.ticker!==void 0;for(;r<o;++r){let n=t.symbol[r],a=h(t,"exchange-listed",r),c=h(t,"exchange-traded",r),l=c+":"+n,u=h(t,"currency-code",r),m=h(t,"unit-id",r),f=s?h(t,"ticker",r):n,g={ticker:f,name:n,base_name:[a+":"+n],listed_exchange:a,exchange:c,currency_code:u,original_currency_code:h(t,"original-currency-code",r),unit_id:m,original_unit_id:h(t,"original-unit-id",r),unit_conversion_types:h(t,"unit-conversion-types",r,!0),description:h(t,"description",r),has_intraday:F(h(t,"has-intraday",r),!1),visible_plots_set:F(h(t,"visible-plots-set",r),"ohlcv"),minmov:h(t,"minmovement",r)||h(t,"minmov",r)||0,minmove2:h(t,"minmove2",r)||h(t,"minmov2",r),fractional:h(t,"fractional",r),pricescale:h(t,"pricescale",r),type:h(t,"type",r),session:h(t,"session-regular",r),session_holidays:h(t,"session-holidays",r),corrections:h(t,"corrections",r),timezone:h(t,"timezone",r),supported_resolutions:F(h(t,"supported-resolutions",r,!0),this._datafeedSupportedResolutions),has_daily:F(h(t,"has-daily",r),!0),intraday_multipliers:F(h(t,"intraday-multipliers",r,!0),["1","5","15","30","60"]),has_weekly_and_monthly:h(t,"has-weekly-and-monthly",r),has_empty_bars:h(t,"has-empty-bars",r),volume_precision:F(h(t,"volume-precision",r),0),format:"price"};this._symbolsInfo[f]=g,this._symbolsInfo[n]=g,this._symbolsInfo[l]=g,(u!==void 0||m!==void 0)&&(this._symbolsInfo[ce(f,u,m)]=g,this._symbolsInfo[ce(n,u,m)]=g,this._symbolsInfo[ce(l,u,m)]=g),this._symbolsList.push(n);}}catch(o){throw new Error(`SymbolsStorage: API error when processing exchange ${e} symbol #${r} (${t.symbol[r]}): ${Object(o).message}`)}}};function F(i,e){return i!==void 0?i:e}var de=class{constructor(e){this._configuration=Ct();this._symbolsStorage=null;this._datafeedURL=e,this._requester=new le,this._historyProvider=new ae(e,this._requester),this._configurationReadyPromise=this._requestConfiguration().then(t=>{t===null&&(t=Ct()),this._setupWithConfiguration(t);});}getBars(e,t,r,o,s){this._historyProvider.getBars(e,t,r).then(n=>{o(n.bars,n.meta);}).catch(s);}onReady(e){this._configurationReadyPromise.then(()=>{e(this._configuration);});}searchSymbols(e,t,r,o){if(this._symbolsStorage===null)throw new Error("Datafeed: inconsistent configuration (symbols storage)");this._symbolsStorage.searchSymbols(e,t,r,30).then(o).catch(o.bind(null,[]));}resolveSymbol(e,t,r,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(r);}getMarks(){}getTimescaleMarks(){}getServerTime(){}_requestConfiguration(){return this._send("config").catch(e=>(`${B(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 ue(this._datafeedURL,e.supported_resolutions||[],this._requester)),`${JSON.stringify(e)}`;}};function Ct(){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 pe=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 r=this.subscribers.get(e);this.subscribers.set(e,r.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 Me=i=>{let e="1d";switch(i){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},V={interval:"TradingviewSDK.lastUsedTimeBasedResolution",lineType:"TradingviewSDK.lastUsedStyle",displayControlSetting:"TradingviewSDK.displaySetting"};var De=(i,e)=>`${i}kline_${e}`,ei=i=>["trade"].map(t=>`${i}@${t}`),R=class R{constructor(e){this.klineSubscribeIdMap=new Map;this.klineOnTickCallback=new Map;this.subscribeCachedTopics=new Map;this.wsInstance=null;this.klineData=new Map;return R._created||(this.wsInstance=e,R._instance=this,R._created=true),R._instance}subscribeKline(e,t,r,o){let s=Me(r);this.klineSubscribeIdMap.set(e,{symbol:t,resolution:r});let n=De(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:f,volume:g,startTime:b}=c,W=De(c.symbol,c.type);this.updateKline(W,{time:b,close:u,open:l,high:m,low:f,volume:g});}});this.subscribeCachedTopics.set(`${t}@kline_${s}`,a);}}unsubscribeKline(e){if(!this.klineSubscribeIdMap.has(e))return;let{symbol:t,resolution:r}=this.klineSubscribeIdMap.get(e),o=Me(r),s=De(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){ei(e).forEach(r=>{if(!this.subscribeCachedTopics.has(r)){let o=this.wsInstance?.subscribe({event:"subscribe",topic:r,id:r,ts:new Date().getTime()},{onMessage:s=>{this.updateKlineByLastPrice(s.symbol,s.price);}});this.subscribeCachedTopics.set(r,o);}});}updateKlineByLastPrice(e,t){this.klineOnTickCallback.forEach((r,o)=>{if(o.startsWith(e)){let s=this.klineData.get(o);s&&this.updateKline(o,{...s,close:t});}});}updateKline(e,t){let r=this.klineOnTickCallback.get(e);r&&t&&(this.klineData.set(e,t),Object.keys(r).forEach(o=>{let s=r[o];s&&typeof s=="function"&&s(t);}));}};R._created=false,R._instance=null;var U=R;var ti=(()=>{let i=0;return ()=>i++})(),me=class extends de{constructor(t,r){let o=`${t}/tv`;super(o);this.bbosMap=new Map;this.tickersMap=new Map;this.eventBus=new pe;this._subscribeQuoteMap=new Map,this._prefixId=ti(),this._publicWs=new U(r),this.bbosMap=new Map,r.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"});}),r.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,r,o,s,n){window.onResetCacheNeededCallback=n,this._publicWs.subscribeKline(`${this._prefixId}${s}`,t.ticker,r,o);}unsubscribeBars(t){this._publicWs.unsubscribeKline(`${this._prefixId}${t}`);}getQuotes(t,r){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(L(c)),u=this.tickersMap.get(L(c));if(!l||!u)return;let m={...u,ask:l.ask,bid:l.bid};a.set(L(c),m);}),a.size&&r(Array.from(a.values()).map(c=>this._toUDFTicker(c)));});this._subscribeQuoteMap.set(o,s);}subscribeQuotes(t,r,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(L(u)),f=this.tickersMap.get(L(u));if(!m||!f)return;let g={...f,ask:m.ask,bid:m.bid};l.set(L(u),g);}),l.size&&o(Array.from(l.values()).map(u=>this._toUDFTicker(u)));});this._subscribeQuoteMap.set(n,a);}}unsubscribeQuotes(t){let r=this.getSubscriptionId(t),o=this._subscribeQuoteMap.get(r);o&&(o(),this._subscribeQuoteMap.delete(r));}_toUDFTicker(t){return {n:ne(t.symbol),s:"ok",v:{ask:t.ask,bid:t.bid,ch:t.change,chp:t.perChange/100,description:"",exchange:oe,hight_price:t.high,low_price:t.low,lp:t.close,open_price:t.open,prev_close_price:0,volume:t.volume}}}};var ii=2,oi="--",Be=["BRACKET","STOP_BRACKET"],ge=["POSITIONAL_TP_SL","TP_SL"];var Ve=i=>i.root_algo_order_id!==i.algo_order_id&&(i.algo_type==="TAKE_PROFIT"||i.algo_type==="STOP_LOSS"),ni=i=>!!i&&Be.includes(i);var Ne=i=>i.type==="CLOSE_POSITION",St=i=>Ne(i)&&i.is_activated,Tt=i=>Ve(i)&&i.is_activated,He=i=>i.root_algo_order_algo_type==="TP_SL"||ni(i.root_algo_order_algo_type)&&i.is_activated,It=(i,e)=>{let t=i.algo_type,r={TAKE_PROFIT:i18n.t("tpsl.takeProfit"),STOP_LOSS:i18n.t("tpsl.stopLoss")}[t];return r||null},Lt=i=>{let e=new Map,t=1;return [...i].reverse().filter(He).forEach(r=>{r.root_algo_order_id&&!e.has(r.root_algo_order_id)&&e.set(r.root_algo_order_id,t++);}),e},Ot=(i,e)=>{let t=Math.abs(i.type==="CLOSE_POSITION"?e.balance:i.quantity),r=i.side==="SELL"?1:-1,o=e.open.toString();return {estPnl:new Decimal(i.trigger_price).minus(o??0).times(t).times(r).toString(),quantity:t,openPrice:o}},Pt=i=>i!==void 0&&i!==""?new Decimal(i).todp(ii,Decimal.ROUND_FLOOR):oi;function Fe(){let[i,{cancelOrder:e,cancelAlgoOrder:t,cancelTPSLChildOrder:r}]=useOrderStream({status:OrderStatus.INCOMPLETE});return useCallback(o=>{if(o.algo_order_id){if(ge.includes(o.root_algo_order_algo_type)){let s=i?.find(a=>a.algo_order_id===o.root_algo_order_id);return s.child_orders.every(a=>!!a.trigger_price)?r(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,i])}function Ue(i){useEventEmitter();let [,{updateOrder:t,cancelAlgoOrder:r,updateAlgoOrder:o,updateTPSLOrder:s}]=useOrderStream({status:OrderStatus.INCOMPLETE});return useCallback((n,a)=>{if(n.algo_order_id)if(ge.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=>{i&&i.error(u.message);})}else {if(Be.includes(n.algo_type))return o(n.algo_order_id,{order_price:new Decimal(a.value).toString()}).then(l=>{}).catch(l=>{i&&i.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),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=>{i&&i.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),a.type==="price"&&(c.order_price=new Decimal(a.value).toString()),t(n.order_id,c).then(l=>{}).catch(l=>{i.error(l.message);})},[t])}function Ke(i){let {onSubmit:e}=useOrderEntry_deprecated({symbol:i,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 Ci=i=>e=>i(e),vi=({closeConfirm:i,colorConfig:e,onToast:t,mode:r,symbol:o})=>{let s=Fe(),n=Ue(t),a=useSymbolsInfo(),c=useCallback(g=>i&&i(g),[i]),{sendMarketOrder:l,sendLimitOrder:u}=Ke(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]),f=useRef({cancelOrder:s,closePosition:c,editOrder:n,colorConfig:e,sendLimitOrder:u,getSymbolInfo:m,sendMarketOrder:Ci(l),mode:r});return useEffect(()=>{f.current.getSymbolInfo=m;},[a]),useEffect(()=>{f.current.sendLimitOrder=u,f.current.sendMarketOrder=l;},[u,l]),useEffect(()=>{f.current.closePosition=c;},[i]),useEffect(()=>{f.current.cancelOrder=s;},[s]),f.current},wt=vi;var kt={1:{startOf:"minute",period:0},3:{startOf:"hour",period:3*60*1e3},5:{startOf:"hour",period:5*60*1e3},15:{startOf:"hour",period:15*60*1e3},30:{startOf:"hour",period:30*60*1e3},60:{startOf:"hour",period:0},120:{startOf:"day",period:2*60*60*1e3},240:{startOf:"day",period:4*60*60*1e3},480:{startOf:"day",period:8*60*60*1e3},720:{startOf:"day",period:12*60*60*1e3},D:{startOf:"day",period:0},"1D":{startOf:"day",period:0},"3D":{startOf:"year",period:3*24*60*60*1e3},"5D":{startOf:"year",period:5*24*60*60*1e3},"1W":{startOf:"week",period:0},"1M":{startOf:"month",period:0}};function Et(i,e,t,r){let{startOf:o,period:s}=kt[t],n=new Date(i.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][i.side].length<5&&(e[c][i.side].push(i),r.push(i));}var Mt=(i,e)=>{let t=[],r={};return kt[e]?(i.forEach(o=>{if(o.child_orders)for(let s of o.child_orders)s.is_activated&&s.algo_status===OrderStatus.FILLED&&Et(s,r,e,t);else Et(o,r,e,t);}),t):[]};var fe=class i{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(),Mt(e,this.interval).forEach(r=>{this.executions.push(this.drawExecution(r,t));}));}removeAll(){this.executions.forEach(e=>e.remove()),this.executions=[];}static getExecutionInfo(e,t){let r=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 `${r==="BUY"?i18n.t("common.buy"):i18n.t("common.sell")} ${e.total_executed_quantity} @${commify(s)}`}drawExecution(e,t){let r=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(i.getExecutionInfo(e,t)).setTime(s).setPrice(o).setArrowColor(r==="BUY"?n.upColor:n.downColor).setDirection(r==="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 z=i=>{if(i!=null)return i.algo_order_id||i.order_id};var be=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:r}=Ot(e,t);return Pt(r)}prepareTpslPnlMap(e){let t=[];return e.forEach(r=>{let o=z(r);if(o&&Tt(r)){let s=this.tpslPnlMap.get(o),n=this.getFormattedEstPnl(r);s!==n&&(t.push(o),this.tpslPnlMap.set(o,n));}}),t}prepareQuantityTpslNoMap(e){this.quantityTpslNoMap=Lt(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 be;}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(r=>t.includes(z(r))).forEach(r=>this.renderPendingOrder(r));}renderPendingOrder(e){let t=P.getOrderId(e);if(!t)return;let r=this.drawOrderLine(t,e);r&&this.pendingOrderLineMap.set(t,r);}cleanOldPendingOrders(e){let t=new Set(e.map(r=>P.getOrderId(r)));this.pendingOrderLineMap.forEach((r,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:r}=e;if((t==="STOP_LOSS"||t==="TAKE_PROFIT"||t==="STOP")&&r==="LIMIT")return "STOP_LIMIT";if((t==="STOP_LOSS"||t==="TAKE_PROFIT"||t==="STOP")&&r==="MARKET")return "STOP_MARKET";if(t==="BRACKET"){if(r==="LIMIT")return "BRACKET_LIMIT";if(r==="MARKET")return "BRACKET_MARKET"}return "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"):i18n.t("orderEntry.orderType.limit")}static getOrderPrice(e){return e.trigger_price||e.price}getTPSLTextWithTpsl(e,t){return z(t),e}getTPSLText(e){let t=It(e,this.tpslCalService.getQuantityTpslNoMap());return t?this.getTPSLTextWithTpsl(t,e):null}getOrderQuantity(e){if(e.algo_order_id){if(St(e)||Ne(e))return "100%";if(He(e)){let r=new Decimal(e.quantity).minus(e.executed??0).div(new Decimal(e.position_qty)).mul(100).todp(2).toNumber();return `${Math.min(Math.abs(r),100).toString()}%`}}return commify(new Decimal(e.quantity).toString())}drawOrderLine(e,t){let r=Ve(t)?this.getTPSLText(t):P.getText(t);if(r===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(r).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 r=P.getOrderEditKey(t);e.onMove(()=>{this.broker.editOrder(t,{type:r,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 Ce=P;var ve=class i{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,r)=>this.drawPositionLine(t,r)),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 r=i18n.t("tpsl.pnl"),o=new Decimal(e).toFixed(t,Decimal.ROUND_DOWN);return new Decimal(e).eq(0)?`${r} 0`:new Decimal(e).greaterThan(0)?`${r} +${commify(o)}`:`${r} ${commify(o)}`}removePositions(){Object.keys(this.positionLines).forEach(e=>{this.positionLines[Number(e)].remove(),delete this.positionLines[Number(e)];});}drawPositionLine(e,t){let r=this.broker.colorConfig,o=e.unrealPnl>=0,s=e.balance>=0,n=r.pnlZoreColor,a=new Decimal(e.unrealPnl);a.greaterThan(0)?n=r.upColor:a.lessThan(0)&&(n=r.downColor);o?r.pnlUpColor:r.pnlDownColor;let l=s?r.upColor:r.downColor,u=new Decimal(e.open).toNumber();this.positionLines[t]=this.positionLines[t]??this.getBasePositionLine(),this.positionLines[t].setQuantity(i.getPositionQuantity(e.balance)).setPrice(u).setCloseButtonIconColor(r.closeIcon).setCloseButtonBorderColor(l).setBodyBackgroundColor(n).setQuantityTextColor(l).setBodyBorderColor(n).setLineColor(l).setQuantityBorderColor(l).setText(i.getPositionPnL(e.unrealPnl,e.unrealPnlDecimal)),this.broker.mode!==3&&this.positionLines[t].onClose(null,()=>{this.broker.closePosition(e);});}};var _e=class{constructor(e,t){this.interactiveMode=0;this.timer=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.timer=null,this.currentPosition=null,this.bindEvent();}bindEvent(){this.chart.crossHairMoved().subscribe(null,e=>{if(this.lastArgs=e,this.interactiveMode===2)return;let t=this.getIntersectantPosition(e);if(!(this.currentPosition&&t&&this.currentPosition.symbol===t.symbol)){if(this.currentPosition&&!t){this.removeTPSLTriggerButton(),this.currentPosition=null;return}t&&(this.currentPosition=t,this.createTPSLTriggerButton(e));}});}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:r=>{this.showAdvancedTPSLDialog({type:t.gt(0)?"tp":"sl",triggerPrice:e.price,qty:r.qty});}}).then(()=>{},r=>{}).finally(()=>{this.clearTPSLElements(),this.chart.setScrollEnabled(true),this.chart.setZoomEnabled(true),this.interactiveMode=0;});}showAdvancedTPSLDialog({type:e,triggerPrice:t,qty:r}){modal.show("TPSLDialogId",{withTriggerPrice:true,type:e,triggerPrice:t,symbol:this.currentPosition?.symbol,qty:r,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 t=this.chart.getPanes()[0].getRightPriceScales()[0].getVisiblePriceRange();return t?(t.to-t.from)*.02:10}drawTPSL(e){let{price:t}=e,r=new Decimal(t).minus(this.currentPosition.open).mul(this.currentPosition?.balance??0),{tpslOrderLine:o,verticalLine:s}=this.ensureTPSLElements({price:t,pnl:r}),n=r.gt(0)?i18n.t("tpsl.tp"):i18n.t("tpsl.sl"),a=r.gt(0)?this.broker.colorConfig.upColor:this.broker.colorConfig.downColor;o?.setText(`${n} ${r.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,r;if(t||(this.tpslOrderLine=this.createTPSLOrderLine()),this.tpslPnLVerticalLineEntityId&&(r=this.chart.getShapeById(this.tpslPnLVerticalLineEntityId)),!r){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:"arrow",lock:true,disableSave:true,disableSelection:true,disableUndo:true,zOrder:"top",overrides:{linecolor:"rgba(255,255,255, 0.2)",linewidth:1}});}return r?.setProperties({linecolor:e.pnl.gt(0)?this.broker.colorConfig.upColor:this.broker.colorConfig.downColor,linewidth:1}),{tpslOrderLine:t,verticalLine:r}}createTPSLTriggerButton(e){this.tpslOrderLine||(this.tpslOrderLine=this.createTPSLOrderLine()),this.tpslOrderLine.onMove(()=>{let t=this.tpslOrderLine?.getPrice();this.showTPSLDialog({price:t??0});}),this.tpslOrderLine.onMoving(()=>{let t=this.tpslOrderLine?.getPrice();this.interactiveMode=2,this.verticalLineTime(),this.drawTPSL({price:t??0});});}createTPSLOrderLine(){return this.chart.createOrderLine().setCancellable(false).setExtendLeft(true).setTooltip(i18n.t("tpsl.dragToSet")).setPrice(this.currentPosition.open).setLineLength(-200,"pixel").setText(i18n.t("tpsl.advanced.title")).setQuantity("").setBodyTextColor(this.broker.colorConfig.textColor).setBodyBackgroundColor(this.broker.colorConfig.chartBG).setBodyBorderColor(this.broker.colorConfig.pnlZoreColor).setQuantityBackgroundColor(this.broker.colorConfig.chartBG).setQuantityBorderColor(this.broker.colorConfig.pnlZoreColor).setQuantityTextColor(this.broker.colorConfig.qtyTextColor).setBodyFont(this.broker.colorConfig.font).setQuantityFont(this.broker.colorConfig.font).setLineStyle(1)}verticalLineTime(){let e=this.chart.getVisibleRange();this.tpslVerticalLineTime=this.getTimeAtPercentage(e.from,e.to,90);}removeTPSLTriggerButton(){this.tpslOrderLine&&(this.tpslOrderLine.remove(),this.tpslOrderLine=null);}clearTPSLElements(){this.tpslOrderLine&&(this.tpslOrderLine.remove(),this.tpslOrderLine=null),this.tpslPnLVerticalLineEntityId&&(this.chart.removeEntity(this.tpslPnLVerticalLineEntityId),this.tpslPnLVerticalLineEntityId=null);}getIntersectantPosition(e){if(!Array.isArray(this.lastPositions)||this.lastPositions.length===0)return null;let{price:t,time:r}=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,r){if(typeof e!="number"||typeof t!="number"||typeof r!="number"||r<0||r>100||e>t)return null;let o=t-e,s=r/100,n=o*s,a=e+n;return Math.round(a)}};var Se=class{constructor(e,t,r){this.instance=e,this.positionLineService=new ve(e,r),this.orderLineService=new Ce(e,r),this.executionService=new fe(e,r),this.tpslService=new _e(e,r);}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 $e(i,e){let[t,r]=useState(),o=useRef(),{state:s}=useAccount(),[n]=useLocalStorage("unPnlPriceBasis","markPrice"),[{rows:a},c]=usePositionStream(i,{calcMode:n}),[l]=useOrderStream({status:OrderStatus.INCOMPLETE,symbol:i}),m=useSymbolsInfo()?.[i],f=m("quote_dp"),[g]=useOrderStream({symbol:i,status:OrderStatus.FILLED,size:500}),b=useRef((T,_,D,H)=>{o.current&&o.current.remove(),o.current=new Se(T,_,D),r(o.current);}),W=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 T=(a??[]).filter(_=>_.symbol===i).map(_=>({symbol:_.symbol,open:_.average_open_price,balance:_.position_qty,closablePosition:9999,unrealPnl:_.unrealized_pnl??0,interest:0,unrealPnlDecimal:2,basePriceDecimal:4}));t?.renderPositions(T);},[t,a,i,e,s]),useEffect(()=>{if(!e||!e.buySell){t?.renderFilledOrders([],6);return}let T=g?.filter(_=>_.symbol===i);t?.renderFilledOrders(T??[],f??6);},[t,g,i,f,e]),useEffect(()=>{let T=[],_=[],D=[],H=[],A=[];if(s.status<AccountStatusEnum.EnableTrading&&s.status!==AccountStatusEnum.EnableTradingWithoutConnected){t?.renderPendingOrders([]);return}let Q=(a??[]).find(C=>C.symbol===i);l?.forEach(C=>{if(i===C.symbol){if(!C.algo_order_id)D.push(C);else if(C.algo_order_id)if(C.algo_type==="POSITIONAL_TP_SL")for(let I of C.child_orders)I.root_algo_order_algo_type=C.algo_type,I.trigger_price&&I.status!==OrderStatus.FILLED&&_.push(I);else if(C.algo_type==="TP_SL"){if(Q)for(let I of C.child_orders)I.root_algo_order_algo_type=C.algo_type,I.position_qty=Q.position_qty,I.trigger_price&&I.status!==OrderStatus.FILLED&&T.push(I);}else C.algo_type==="STOP_LOSS"||C.algo_type==="TAKE_PROFIT"?H.push(C):C.algo_type==="BRACKET"&&A.push(C);}}),e&&(e.positionTpsl||(_=[]),e.tpsl||(T=[]),e.limitOrders||(D=[],A=[]),e.stopOrders||(H=[])),t?.renderPendingOrders(T.concat(_).concat(D).concat(H).concat(A));},[t,l,i,e,a,s.status]),[b.current,W.current]}function Di(i){i.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 Ai(i,e){i.onChartReady(()=>{e.silentOrdersPlacement().subscribe(t=>{t||(e.silentOrdersPlacement().setValue(true),i&&(i._iFrame.contentDocument.querySelector(".wrapper-3X2QgaDd").className="wrapper-3X2QgaDd highButtons-3X2QgaDd"),e.sellBuyButtonsVisibility()?.setValue(false));});});}function Ze(i,e){Di(e),Ai(i,e);}var Kt=(i,e)=>new Promise(t=>{let r=i.querySelector(e);r&&t(r);let o=new MutationObserver(()=>{let s=i.querySelector(e);s&&(t(s),o.disconnect());});o.observe(i,{childList:true,subtree:true});});var Le=class{constructor({iframeDocument:e}){this.iframeDocument=e;}defaultHack(){this.showFavoriteStarByDefault();}showFavoriteStarByDefault(){Kt(this.iframeDocument,".dropdown-2R6OKuTS").then(()=>{this.iframeDocument.querySelectorAll(".toolbox-2IihgTnv.showOnHover-2IihgTnv").forEach(t=>{t.style.opacity="1";});});}};var Bi=i=>{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 i===3&&(e=[...e,"left_toolbar","timeframes_toolbar","go_to_date","timezone_menu","create_volume_indicator_by_default","buy_sell_buttons"]),i===0?e=[...e,"header_widget","left_toolbar","timeframes_toolbar","buy_sell_buttons"]:i===1&&(e=[...e,"left_toolbar","timeframes_toolbar","buy_sell_buttons"]),e};function ze(i,e){return {...i,disabled_features:Bi(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 je=i=>`${i}_adapter`,Oe={"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"},k=new Map;var Vi=(i,e,t)=>{let r=je(i);try{let o=e,s=o?JSON.parse(o):void 0,n=t?JSON.parse(t):Oe;return o&&k.set(i,o),t&&k.set(r,t),{savedData:s,adapterSetting:n}}catch{}return {savedData:void 0,adapterSetting:Oe}},qt=async(i,e)=>{let t=je(i),r=localStorage.getItem(i)||"",o=localStorage.getItem(t)||"";try{if(k.has(i)&&k.has(t))return {savedData:JSON.parse(k.get(i)),adapterSetting:JSON.parse(k.get(t))}}catch{}return Vi(i,r,o)},Gt=async(i,e,t)=>{e&&(localStorage.setItem(i,e),k.set(i,e));},Wt=async(i,e,t)=>{let r=je(i);e&&(localStorage.setItem(r,e),k.set(r,e));};var Qt=(i,e)=>{let t=null,r=(...o)=>{t&&window.clearTimeout(t),t=setTimeout(()=>{i(...o);},e);};return r.cancel=()=>{t&&window.clearTimeout(t),t=null;},r},Ni="chartProp_default",$t=300,Pe=class{constructor(e){this._instance=null;this._onClick=null;this._datafeed=null;this._chartKey=Ni;this._adapterSetting=Oe;this._savedData=null;this._isLoggedIn=false;this.debounceSaveChart=Qt(()=>{try{this._instance?.save(e=>{Object.is(this._savedData,e)||(this._savedData=e,Gt(this._chartKey,JSON.stringify(e),this._isLoggedIn));});}catch{}},$t*2);this.debounceSaveChartAdapterSetting=Qt(()=>{Wt(this._chartKey,JSON.stringify(this._adapterSetting),this._isLoggedIn);},$t);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,r){try{this._instance?.onChartReady(()=>{let o=t??this._instance?.symbolInterval()?.interval;o||(o=1),this._instance?.setSymbol(e,o,r);});}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 Le({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:r,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 qt(this._chartKey,this._isLoggedIn);this._adapterSetting=c,this._savedData=a,this._instance=new TradingView.widget({...ze(n,r),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()!==L(e.symbol)&&this.setSymbol(e.symbol);}),this.subscribeAutoSave(),this.subscribeClick(o),this.chartHack();}};var ji="SDK_Tradingview",Yi="SDK_Moblie_Tradingview",Ji=i=>i?Yi:ji,Xi=i=>i==="id"?"id_ID":i;function et(i){let{scriptSRC:e,libraryPath:t,customCssUrl:r,overrides:o,studiesOverrides:s,symbol:n,theme:a,loadingScreen:c,mode:l,colorConfig:u,locale:m=Xi,classNames:f}=i,g=useLocaleCode(),b=useRef(),W=useConfig("apiBaseUrl"),{state:T}=useAccount(),[_,D]=useState(OrderSide.SELL),H=useSymbolsInfo(),[A,Q]=useLocalStorage(TradingviewFullscreenKey,false),{onSubmit:C,submitting:I}=useOrderEntry_deprecated({symbol:n??"",side:_,order_type:OrderType.MARKET},{watchOrderbook:true}),[ct,xr]=useState(()=>{let d=localStorage.getItem(V.displayControlSetting);return d?JSON.parse(d):{position:true,buySell:true,limitOrders:true,stopOrders:true,tpsl:true,positionTpsl:true}}),[ut,wr]=useState(()=>{let d=localStorage.getItem(V.interval);return d||"15"}),[Rr,Er]=useState(()=>{let d=localStorage.getItem(V.lineType);return d||"1"}),we=useMediaQuery(MEDIA_TABLET),Re=useMemo(()=>Object.assign({},ht,u??{}),[u]),kr=useMemo(()=>typeof c=="object"?c:{backgroundColor:ke},[c]),te=useWS(),[$,Mr]=useState(false),Dr=d=>{let re=H[n];if(!re)return;let ie=new Decimal(d.balance).greaterThan(0)?OrderSide.SELL:OrderSide.BUY,mt={order_quantity:new Decimal(d.balance).abs().toNumber(),symbol:n,order_type:OrderType.MARKET,side:ie,reduce_only:true};D(ie),modal.show("MarketCloseConfirmID",{base:re("base"),quantity:d.balance,onConfirm:async()=>C(mt).catch(Z=>{typeof Z=="string"?toast.error(Z):toast.error(Z.message);}),submitting:I});},w=useRef(null),dt=useMemo(()=>!(T.status<AccountStatusEnum.EnableTrading&&T.status!==AccountStatusEnum.EnableTradingWithoutConnected),[T]),pt=wt({closeConfirm:Dr,colorConfig:Re,onToast:toast,symbol:n??"",mode:l}),[Ar,Br]=$e(n,ct),Vr=()=>{Q(!A),i.onFullScreenChange?.(!A);},Nr=d=>{b.current&&(localStorage.setItem(V.interval,d),wr(d),b.current.setSymbol(n,d));},Hr=d=>{b.current&&(localStorage.setItem(V.lineType,d),Er(d),b.current.changeLineType(Number(d)));},Fr=d=>{localStorage.setItem(V.displayControlSetting,JSON.stringify(d)),xr(d);},Ur=()=>{b.current&&b.current.executeActionById("chartProperties");},Kr=()=>{b.current&&b.current.executeActionById("insertIndicator");};return useEffect(()=>{if(e&&w.current&&!$){let d=document.createElement("script");d.setAttribute("data-nscript","afterInteractive"),d.src=e,d.async=true,d.type="text/javascript",d.onload=()=>{Mr(true);},d.onerror=()=>{},w.current.appendChild(d);}},[w,$,e]),useEffect(()=>{if(!n||!$||!e)return;let d=ft(Re,we),re=o?Object.assign({},d.overrides,o):d.overrides,ie=s?Object.assign({},d.studiesOverrides,s):d.studiesOverrides;if(w.current){let Z={options:{fullscreen:false,autosize:true,symbol:ne(n),locale:typeof m=="function"?m(g):m,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,container:w.current,libraryPath:t,customCssUrl:r,interval:ut??"1",theme:a??"dark",loadingScreen:kr??{},overrides:re,studiesOverrides:ie,datafeed:new me(W,te),contextMenu:{items_processor:async Ee=>Ee},getBroker:(Ee,gt)=>(Ze(Ee,gt),bt(gt,pt))},chartKey:Ji(we),mode:l,onClick:()=>{}};b.current=new Pe(Z);}return ()=>{b.current?.remove();}},[$,we,l,b,w,$,e,Re,m,g]),useEffect(()=>{te.on("status:change",d=>{!d.isPrivate&&d.isReconnect&&typeof window.onResetCacheNeededCallback=="function"&&(window.onResetCacheNeededCallback(),b.current?.instance.activeChart()?.resetData());},"tradingview");},[te]),useEffect(()=>(b.current&&b.current.instance&&b.current.instance.onChartReady(()=>{dt&&b.current.instance&&Ar(b.current.instance,void 0,pt,w.current);}),()=>{Br();}),[b.current,dt]),useEffect(()=>{if(!n||!b.current)return;b.current?.setSymbol(n);let d=new U(te);return d.subscribeSymbol(n),()=>{d.unsubscribeKline(n);}},[n]),{tradingViewScriptSrc:e,chartRef:w,changeDisplaySetting:Fr,displayControlState:ct,interval:ut,changeInterval:Nr,lineType:Rr,changeLineType:Hr,openChartSetting:Ur,openChartIndicators:Kr,symbol:n,onFullScreenChange:Vr,classNames:f,fullscreen:A}}var J=i=>jsx("svg",{viewBox:"0 0 12 12",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...i,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"})})}),tt=i=>jsx("svg",{viewBox:"0 0 18 18",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",...i,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.