Commit 259db7d7 authored by web's avatar web

up

parents
Pipeline #837 failed with stages
File added
MIT License
Copyright (c) 2025 CaduceusMetaverseProtocol
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# dexchain-frontend
dexchain-frontend
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
experimental: {
optimizePackageImports: ["@chakra-ui/react"],
},
};
export default nextConfig;
{
"name": "dex-dapp",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@rainbow-me/rainbowkit": "^2.2.1",
"@tanstack/react-query": "^5.62.2",
"antd": "^5.24.1",
"axios": "^1.7.9",
"dayjs": "^1.11.13",
"ethers": "^6.13.4",
"next": "15.0.3",
"react": "19.0.0-rc-66855b96-20241106",
"react-dom": "19.0.0-rc-66855b96-20241106",
"react-tradingview-widget": "^1.3.2",
"viem": "2.x",
"wagmi": "^2.13.3"
},
"devDependencies": {
"@chakra-ui/cli": "^3.2.3",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"postcss": "^8",
"tailwindcss": "3.3.1",
"typescript": "^5"
}
}
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
var TradingView=function(e){"use strict";var t,i,o,r,n,a,s,l,d,c,h,g,u,C,S,p,m,y,_,T,b,P,L,A,w,f,v,I,O,R,D,V,k,E,F,W,M,B,N,U,x,H,j,z,G,$,J,q,K,Z,Q,Y,X,ee,te,ie,oe,re,ne,ae,se,le,de,ce,he;(t=e.ActionId||(e.ActionId={})).UnknownAction="UnknownAction",t.Spinner="Spinner",t.Loading="Loading",t.AlertAdd="Alert.Add",t.AlertEdit="Alert.Edit",t.AlertsClone="Alerts.Clone",t.AlertsRemove="Alerts.Remove",t.AlertsRemoveAll="Alerts.RemoveAll",t.AlertsRemoveFiltered="Alerts.RemoveFiltered",t.AlertsRemoveAllInactive="Alerts.RemoveAllInactive",t.AlertsRemoveFires="Alerts.RemoveFires",t.AlertsRestart="Alerts.Restart",t.AlertsRestartAllInactive="Alerts.RestartAllInactive",t.AlertsRestartFilteredInactive="Alerts.RestartFilteredInactive",t.AlertsStop="Alerts.Stop",t.AlertsStopAll="Alerts.StopAll",t.AlertsStopFilteredActive="Alerts.StopFilteredActive",t.AlertsExportFiresToCSV="Alerts.ExportFiresToCSV",t.AlertsLogClear="AlertsLog.Clear",t.ChartAddIndicatorToAllCharts="Chart.AddIndicatorToAllCharts",t.ChartAddSymbolToWatchList="Chart.AddSymbolToWatchList",t.ChartAlertLabelToggleExtendLines="Chart.AlertLabel.ToggleExtendLines",t.ChartApplyIndicatorsToAllCharts="Chart.ApplyIndicatorsToAllCharts",t.ChartIndicatorApplyChildIndicator="Chart.Indicator.ApplyChildIndicator",t.ChartIndicatorApplyFinancials="Chart.Indicator.ApplyFinancials",t.ChartIndicatorAbout="Chart.Indicator.About",t.ChartIndicatorPineLogs="Chart.Indicator.PineLogs",t.ChartIndicatorPineSource="Chart.Indicator.PineSource",t.ChartIndicatorAddFavorites="Chart.Indicator.AddFavorites",t.ChartChangeTimeZone="Chart.ChangeTimeZone",t.ChartClipboardCopyPrice="Chart.Clipboard.CopyPrice",t.ChartClipboardCopyLineTools="Chart.Clipboard.CopyLineTools",t.ChartClipboardCopySource="Chart.Clipboard.CopySource",t.ChartClipboardPasteSource="Chart.Clipboard.PasteSource",t.ChartCrosshairLockVerticalCursor="Chart.Crosshair.LockVerticalCursor",t.ChartCrosshairPlusButtonDrawHorizontalLine="Chart.Crosshair.PlusButton.DrawHorizontalLine",t.ChartCustomActionId="Chart.CustomActionId",t.ChartDialogsShowChangeInterval="Chart.Dialogs.ShowChangeInterval",t.ChartDialogsShowChangeSymbol="Chart.Dialogs.ShowChangeSymbol",t.ChartDialogsShowCompareOrAddSymbol="Chart.Dialogs.ShowCompareOrAddSymbol",t.ChartDialogsShowGeneralSettings="Chart.Dialogs.ShowGeneralSettings",t.ChartDialogsShowGeneralSettingsLegendTab="Chart.Dialogs.ShowGeneralSettings.LegendTab",t.ChartDialogsShowGeneralSettingsSymbolTab="Chart.Dialogs.ShowGeneralSettings.SymbolTab",t.ChartDialogsShowGeneralScalesTab="Chart.Dialogs.ShowGeneralSettings.ScalesTab",t.ChartDialogsShowGeneralSettingsEventsAndAlertsTab="Chart.Dialogs.ShowGeneralSettings.EventsAndAlertsTab",t.ChartDialogsShowGoToDate="Chart.Dialogs.ShowGoToDate",t.ChartDialogsShowInsertIndicators="Chart.Dialogs.ShowInsertIndicators",t.ChartDialogsShowInsertFinancials="Chart.Dialogs.ShowInsertFinancials",t.ChartDialogsShowSymbolInfo="Chart.Dialogs.ShowSymbolInfo",t.ChartDrawingToolbarToggleVisibility="Chart.DrawingToolbar.ToggleVisibility",t.ChartExternalActionId="Chart.ExternalActionId",t.ChartFavoriteDrawingToolsToolbarHide="Chart.FavoriteDrawingToolsToolbar.Hide",t.ChartIndicatorShowSettingsDialog="Chart.Indicator.ShowSettingsDialog",t.ChartLegendToggleLastDayChangeValuesVisibility="Chart.Legend.ToggleLastDayChangeValuesVisibility",t.ChartLinkingGroupSync="Chart.LinkingGroupSync",t.ChartLinkingGroupSyncChangeGroup="Chart.LinkingGroupSync.ChangeGroup",t.ChartLegendToggleBarChangeValuesVisibility="Chart.Legend.ToggleBarChangeValuesVisibility",t.ChartLegendTogglePriceSourceVisibility="Chart.Legend.TogglePriceSourceVisibility",t.ChartLegendToggleIndicatorArgumentsVisibility="Chart.Legend.ToggleIndicatorArgumentsVisibility",t.ChartLegendToggleIndicatorTitlesVisibility="Chart.Legend.ToggleIndicatorTitlesVisibility",t.ChartLegendToggleIndicatorValuesVisibility="Chart.Legend.ToggleIndicatorValuesVisibility",t.ChartLegendToggleOhlcValuesVisibility="Chart.Legend.ToggleOhlcValuesVisibility",t.ChartLegendToggleOpenMarketStatusVisibility="Chart.Legend.ToggleOpenMarketStatusVisibility",t.ChartLegendToggleSymbolVisibility="Chart.Legend.ToggleSymbolVisibility",t.ChartLegendToggleVolumeVisibility="Chart.Legend.ToggleVolumeVisibility",t.ChartLines="Chart.Lines",t.ChartLinesToggleBidAskLinesVisibility="Chart.Lines.ToggleBidAskLinesVisibility",t.ChartLinesToggleHighLowLinesVisibility="Chart.Lines.ToggleHighLowLinesVisibility",t.ChartLinesToggleAverageLineVisibility="Chart.Lines.ToggleAverageLineVisibility",t.ChartLinesTogglePrePostMarketLineVisibility="Chart.Lines.TogglePrePostMarketLineVisibility",t.ChartLinesTogglePrePostMarketPriceLineVisibility="Chart.Lines.TogglePrePostMarketPriceLineVisibility",t.ChartLinesToggleSeriesPrevCloseLineVisibility="Chart.Lines.ToggleSeriesPrevCloseLineVisibility",t.ChartLinesToggleSeriesPriceLineVisibility="Chart.Lines.ToggleSeriesPriceLineVisibility",t.ChartLineToolBarsPatternToggleFlipped="Chart.LineTool.BarsPattern.ToggleFlipped",t.ChartLineToolBarsPatternToggleMirrored="Chart.LineTool.BarsPattern.ToggleMirrored",t.ChartLineToolClone="Chart.LineTool.Clone",t.ChartLineToolCreateLimitOrderFromState="Chart.LineTool.CreateLimitOrderFromState",t.ChartLineToolElliotChangeDegreeProperty="Chart.LineTool.Elliot.ChangeDegreeProperty",t.ChartLineToolNoSync="Chart.LineTool.NoSync",t.ChartLineToolPitchforkChangeTypeToInside="Chart.LineTool.Pitchfork.ChangeTypeToInside",t.ChartLineToolPitchforkChangeTypeToModifiedSchiff="Chart.LineTool.Pitchfork.ChangeTypeToModifiedSchiff",t.ChartLineToolPitchforkChangeTypeToOriginal="Chart.LineTool.Pitchfork.ChangeTypeToOriginal",t.ChartLineToolPitchforkChangeTypeToSchiff="Chart.LineTool.Pitchfork.ChangeTypeToSchiff",t.ChartLineToolSyncInLayout="Chart.LineTool.SyncInLayout",t.ChartLineToolSyncGlobally="Chart.LineTool.SyncGlobally",t.ChartLineToolTemplates="Chart.LineTool.Templates",t.ChartLineToolTemplatesApply="Chart.LineTool.Templates.Apply",t.ChartLineToolTemplatesApplyDefaults="Chart.LineTool.Templates.ApplyDefaults",t.ChartLineToolTemplatesSaveAs="Chart.LineTool.Templates.SaveAs",t.ChartLineToolToolbarChangeFontSizeProperty="Chart.LineTool.Toolbar.ChangeFontSizeProperty",t.ChartLineToolToolbarChangeLineStyleToDashed="Chart.LineTool.Toolbar.ChangeLineStyleToDashed",t.ChartLineToolToolbarChangeLineStyleToDotted="Chart.LineTool.Toolbar.ChangeLineStyleToDotted",t.ChartLineToolToolbarChangeLineStyleToSolid="Chart.LineTool.Toolbar.ChangeLineStyleToSolid",t.ChartMarksToggleVisibility="Chart.Marks.ToggleVisibility",t.ChartMoveChartInLayout="Chart.MoveChartInLayout",t.ChartMoveChartInLayoutBack="Chart.MoveChartInLayout.Back",t.ChartMoveChartInLayoutForward="Chart.MoveChartInLayout.Forward",t.ChartTpoResetAllMergesAndSplits="Chart.TPO.ResetAllMergesAndSplits",t.ChartTpoSplitBlock="Chart.TPO.SplitBlock",t.ChartTpoMergeBlock="Chart.TPO.MergeBlock",t.ChartObjectTreeShow="Chart.ObjectTree.Show",t.ChartDataWindowShow="Chart.DataWindow.Show",t.ChartPaneControlsDeletePane="Chart.PaneControls.DeletePane",t.ChartPaneControlsMaximizePane="Chart.PaneControls.MaximizePane",t.ChartPaneControlsMinimizePane="Chart.PaneControls.MinimizePane",t.ChartPaneControlsMovePaneDown="Chart.PaneControls.MovePaneDown",t.ChartPaneControlsMovePaneUp="Chart.PaneControls.MovePaneUp",t.ChartPaneControlsCollapsePane="Chart.PaneControls.CollapsePane",t.ChartPaneControlsRestorePane="Chart.PaneControls.RestorePane",t.ChartPriceScaleLabels="Chart.PriceScale.Labels",t.ChartPriceScaleLabelsToggleBidAskLabelsVisibility="Chart.PriceScale.Labels.ToggleBidAskLabelsVisibility",t.ChartPriceScaleLabelsToggleHighLowPriceLabelsVisibility="Chart.PriceScale.Labels.ToggleHighLowPriceLabelsVisibility",t.ChartPriceScaleLabelsToggleAveragePriceLabelVisibility="Chart.PriceScale.Labels.ToggleAveragePriceLabelVisibility",t.ChartPriceScaleLabelsToggleIndicatorsNameLabelsVisibility="Chart.PriceScale.Labels.ToggleIndicatorsNameLabelsVisibility",t.ChartPriceScaleLabelsToggleIndicatorsValueLabelsVisibility="Chart.PriceScale.Labels.ToggleIndicatorsValueLabelsVisibility",t.ChartPriceScaleLabelsTogglePrePostMarketLabelsVisibility="Chart.PriceScale.Labels.TogglePrePostMarketLabelsVisibility",t.ChartPriceScaleLabelsToggleNoOverlappingLabelsVisibility="Chart.PriceScale.Labels.ToggleNoOverlappingLabelsVisibility",t.ChartPriceScaleLabelsToggleSeriesLastValueVisibility="Chart.PriceScale.Labels.ToggleSeriesLastValueVisibility",t.ChartPriceScaleLabelsToggleSymbolNameLabelsVisibility="Chart.PriceScale.Labels.ToggleSymbolNameLabelsVisibility",t.ChartPriceScaleLabelsToggleSymbolPrevCloseValueVisibility="Chart.PriceScale.Labels.ToggleSymbolPrevCloseValueVisibility",t.ChartPriceScaleMergeAllScales="Chart.PriceScale.MergeAllScales",t.ChartPriceScaleMergeAllScalesToLeft="Chart.PriceScale.MergeAllScalesToLeft",t.ChartPriceScaleMergeAllScalesToRight="Chart.PriceScale.MergeAllScalesToRight",t.ChartPriceScaleMoveToLeft="Chart.PriceScale.MoveToLeft",t.ChartPriceScaleMoveToRight="Chart.PriceScale.MoveToRight",t.ChartPriceScaleReset="Chart.PriceScale.Reset",t.ChartPriceScaleToggleAddOrderPlusButtonVisibility="Chart.PriceScale.ToggleAddOrderPlusButtonVisibility",t.ChartPriceScaleToggleAutoScale="Chart.PriceScale.ToggleAutoScale",t.ChartPriceScaleToggleAutoScaleSeriesOnly="Chart.PriceScale.ToggleAutoScaleSeriesOnly",t.ChartPriceScaleToggleCountdownToBarCloseVisibility="Chart.PriceScale.ToggleCountdownToBarCloseVisibility",t.ChartPriceScaleToggleIndexedTo100="Chart.PriceScale.ToggleIndexedTo100",t.ChartPriceScaleToggleInvertScale="Chart.PriceScale.ToggleInvertScale",t.ChartPriceScaleToggleLogarithmic="Chart.PriceScale.ToggleLogarithmic",t.ChartPriceScaleTogglePercentage="Chart.PriceScale.TogglePercentage",t.ChartPriceScaleToggleRegular="Chart.PriceScale.ToggleRegular",t.ChartRedo="Chart.Redo",t.ChartRemoveAllIndicators="Chart.RemoveAllIndicators",t.ChartRemoveAllIndicatorsAndLineTools="Chart.RemoveAllIndicatorsAndLineTools",t.ChartRemoveAllLineTools="Chart.RemoveAllLineTools",t.ChartScalesReset="Chart.Scales.Reset",t.ChartScalesToggleLockPriceToBarRatio="Chart.Scales.ToggleLockPriceToBarRatio",t.ChartScrollToLineTool="Chart.ScrollToLineTool",t.ChartSelectedObjectHide="Chart.SelectedObject.Hide",t.ChartSelectedObjectRemove="Chart.SelectedObject.Remove",t.ChartSelectedObjectShow="Chart.SelectedObject.Show",t.ChartSelectedObjectShowSettingsDialog="Chart.SelectedObject.ShowSettingsDialog",t.ChartSelectedObjectToggleLocked="Chart.SelectedObject.ToggleLocked",t.ChartSeriesPriceScaleToggleAutoScale="Chart.Series.PriceScale.ToggleAutoScale",t.ChartSeriesPriceScaleToggleIndexedTo100="Chart.Series.PriceScale.ToggleIndexedTo100",t.ChartSeriesPriceScaleToggleInvertPriceScale="Chart.Series.PriceScale.ToggleInvertPriceScale",t.ChartSeriesPriceScaleToggleLogarithmic="Chart.Series.PriceScale.ToggleLogarithmic",t.ChartSeriesPriceScaleTogglePercentage="Chart.Series.PriceScale.TogglePercentage",t.ChartSeriesPriceScaleToggleRegular="Chart.Series.PriceScale.ToggleRegular",t.ChartSessionBreaksToggleVisibility="Chart.SessionBreaks.ToggleVisibility",t.ChartSetSession="Chart.SetSession",t.ChartSourceChangePriceScale="Chart.Source.ChangePriceScale",t.ChartSourceMergeDown="Chart.Source.MergeDown",t.ChartSourceMergeUp="Chart.Source.MergeUp",t.ChartSourceMoveToNoScale="Chart.Source.MoveToNoScale",t.ChartSourceMoveToOtherScale="Chart.Source.MoveToOtherScale",t.ChartSourceMoveToPane="Chart.Source.MoveToPane",t.ChartSourceUnmergeDown="Chart.Source.UnmergeDown",t.ChartSourceUnmergeUp="Chart.Source.UnmergeUp",t.ChartSourceVisualOrder="Chart.Source.VisualOrder",t.ChartSourceVisualOrderBringForward="Chart.Source.VisualOrder.BringForward",t.ChartSourceVisualOrderBringToFront="Chart.Source.VisualOrder.BringToFront",t.ChartSourceVisualOrderSendBackward="Chart.Source.VisualOrder.SendBackward",t.ChartSourceVisualOrderSendToBack="Chart.Source.VisualOrder.SendToBack",t.ChartSourceResetInputPoints="Chart.Source.ResetInputPoints",t.ChartThemeApply="Chart.Theme.Apply",t.ChartThemeApplyCustom="Chart.Theme.Apply.Custom",t.ChartThemeSaveAs="Chart.Theme.SaveAs",t.ChartTimeScaleReset="Chart.TimeScale.Reset",t.ChartUndo="Chart.Undo",t.ChartShowAllIdeas="Chart.ShowAllIdeas",t.ChartShowIdeasOfFollowedUsers="Chart.ShowIdeasOfFollowedUsers",t.ChartShowMyIdeasOnly="Chart.ShowMyIdeasOnly",t.ChartToggleVisibilityAllLineTools="Chart.ToggleVisibility.AllLineTools",t.ChartToggleVisibilityContinuousContractSwitch="Chart.ToggleVisibility.ContinuousContractSwitch",t.ChartToggleVisibilityContractExpiration="Chart.ToggleVisibility.ContractExpiration",t.ChartToggleVisibilityDividends="Chart.ToggleVisibility.Dividends",t.ChartToggleVisibilityEarnings="Chart.ToggleVisibility.Earnings",t.ChartToggleVisibilityEconomicEvents="Chart.ToggleVisibility.EconomicEvents",t.ChartToggleVisibilitySplits="Chart.ToggleVisibility.Splits",t.ChartToggleVisibilityLatestNewsAndMinds="Chart.ToggleVisibility.LatestNewsAndMinds",t.ChartSourceIntervalsVisibility="Chart.Source.IntervalsVisibility",t.ChartSourceIntervalsVisibilityCurrentAndAbove="Chart.Source.IntervalsVisibility.CurrentAndAbove",t.ChartSourceIntervalsVisibilityCurrentAndBelow="Chart.Source.IntervalsVisibility.CurrentAndBelow",t.ChartSourceIntervalsVisibilityOnlyCurrent="Chart.Source.IntervalsVisibility.Current",t.ChartSourceIntervalsVisibilityAll="Chart.Source.IntervalsVisibility.All",t.NoteCreate="Note.Create",t.NoteEdit="Note.Edit",t.NoteRemove="Note.Remove",t.ObjectsTreeCreateGroup="ObjectsTree.CreateGroup",t.ObjectsTreeRemoveItem="ObjectsTree.RemoveItem",t.ObjectsTreeRenameItem="ObjectsTree.RenameItem",t.ObjectsTreeToggleItemLocked="ObjectsTree.ToggleItemLocked",t.ObjectsTreeToggleItemVisibility="ObjectsTree.ToggleItemVisibility",t.PineEditorConsoleCopyMessage="PineEditor.Console.CopyMessage",t.PineEditorConsoleToggleVisibility="PineEditor.Console.ToggleVisibility",t.PineEditorConsoleClear="PineEditor.Console.Clear",t.ScreenerAddSymbolToCompare="Screener.AddSymbolToCompare",t.ScreenerColumnRemove="Screener.Column.Remove",t.ScreenerFilterChange="Screener.Filter.Change",t.ScreenerFilterReset="Screener.Filter.Reset",t.ScreenerOpenSymbolChart="Screener.OpenSymbolChart",t.ScreenerOpenSymbolOverview="Screener.OpenSymbolOverview",t.ScreenerToggleVisibilityCurrency="Screener.ToggleVisibility.Currency",t.ScreenerToggleVisibilityDescription="Screener.ToggleVisibility.Description",t.ScreenerToggleVisibilityRating="Screener.ToggleVisibility.Rating",t.ScreenerToggleVisibilitySymbolType="Screener.ToggleVisibility.SymbolType",t.TradingCancelOrder="Trading.CancelOrder",t.TradingClosePosition="Trading.ClosePosition",t.TradingCustomActionId="Trading.CustomActionId",t.TradingDOMPlaceLimitOrder="Trading.DOMPlaceLimitOrder",t.TradingDOMPlaceMarketOrder="Trading.DOMPlaceMarketOrder",t.TradingDOMPlaceStopLimitOrder="Trading.DOMPlaceStopLimitOrder",t.TradingDOMPlaceStopOrder="Trading.DOMPlaceStopOrder",t.TradingEditOrder="Trading.EditOrder",t.TradingModifyPosition="Trading.ModifyPosition",t.TradingReversePosition="Trading.ReversePosition",t.TradingSellBuyButtonsToggleVisibility="Trading.SellBuyButtonsToggleVisibility",t.TradingTradeFromChart="Trading.TradeFromChart",t.TradingNoOverlapMode="Trading.NoOverlapMode",t.TradingShowSelectBrokerPanel="Trading.ShowSelectBrokerPanel",t.TradingOrderTitle="Trading.OrderTitle",t.TradingPositionTitle="Trading.PositionTitle",t.WatchlistActions="Watchlist.Actions",t.WatchlistAddSelectedSymbolsToCompare="Watchlist.AddSelectedSymbolsToCompare ",t.WatchlistAddSymbolToCompare="Watchlist.AddSymbolToCompare",t.WatchlistAddSymbolToSection="Watchlist.AddSymbolToSection",t.WatchlistChangeFlaggedGroupColor="Watchlist.ChangeFlaggedGroupColor",t.WatchlistAddSymbol="Watchlist.AddSymbol",t.WatchlistCreate="Watchlist.Create",t.WatchlistAddSelectedSymbols="Watchlist.AddSelectedSymbols",t.WatchlistAddSelectedSymbolsLists="Watchlist.AddSelectedSymbols.Lists",t.WatchlistGetDisplayedTickerDescription="Watchlist.GetDisplayedTickerDescription",t.WatchlistCreateSection="Watchlist.CreateSection",t.WatchlistFlagSelectedSymbols="Watchlist.FlagSelectedSymbols",t.WatchlistFlagSymbol="Watchlist.FlagSymbol",t.WatchlistOpenSymbolChart="Watchlist.OpenSymbolChart",t.WatchlistOpenSymbolOverview="Watchlist.OpenSymbolOverview",t.WatchlistRemoveSection="Watchlist.RemoveSection",t.WatchlistRemoveSymbol="Watchlist.RemoveSymbol",t.WatchlistRenameSection="Watchlist.RenameSection",t.WatchlistUnflagAllSymbols="Watchlist.UnflagAllSymbols",t.WatchlistUnflagSelectedSymbols="Watchlist.UnflagSelectedSymbols",t.WatchlistUnflagSymbol="Watchlist.UnflagSymbol",function(e){e.extractErrorReason=function(e){return e.params[1]}}(i||(i={})),function(e){e.Default="default",e.FullSingleSession="full_single_session"}(o||(o={})),(r=e.TimeFrameType||(e.TimeFrameType={})).PeriodBack="period-back",r.TimeRange="time-range",function(e){e.PeriodBack="period-back",e.TimeRange="time-range"}(n||(n={})),(a=e.MarketStatus||(e.MarketStatus={})).Open="market",a.Pre="pre_market",a.Post="post_market",a.Close="out_of_session",a.Holiday="holiday",(s=e.MenuItemType||(e.MenuItemType={})).Separator="separator",s.Action="action",(l=e.ClearMarksMode||(e.ClearMarksMode={}))[l.All=0]="All",l[l.BarMarks=1]="BarMarks",l[l.TimeScaleMarks=2]="TimeScaleMarks",(d=e.LineStudyPlotStyle||(e.LineStudyPlotStyle={}))[d.Line=0]="Line",d[d.Histogram=1]="Histogram",d[d.Cross=3]="Cross",d[d.Area=4]="Area",d[d.Columns=5]="Columns",d[d.Circles=6]="Circles",d[d.LineWithBreaks=7]="LineWithBreaks",d[d.AreaWithBreaks=8]="AreaWithBreaks",d[d.StepLine=9]="StepLine",d[d.StepLineWithDiamonds=10]="StepLineWithDiamonds",d[d.StepLineWithBreaks=11]="StepLineWithBreaks",(c=e.StudyPlotType||(e.StudyPlotType={})).Line="line",c.Colorer="colorer",c.BarColorer="bar_colorer",c.BgColorer="bg_colorer",c.TextColorer="text_colorer",c.OhlcColorer="ohlc_colorer",c.CandleWickColorer="wick_colorer",c.CandleBorderColorer="border_colorer",c.UpColorer="up_colorer",c.DownColorer="down_colorer",c.Shapes="shapes",c.Chars="chars",c.Arrows="arrows",c.Data="data",c.DataOffset="dataoffset",c.OhlcOpen="ohlc_open",c.OhlcHigh="ohlc_high",c.OhlcLow="ohlc_low",c.OhlcClose="ohlc_close",function(e){e.AlertCondition="alertcondition"}(h||(h={})),(g=e.StudyPlotDisplayTarget||(e.StudyPlotDisplayTarget={}))[g.None=0]="None",g[g.Pane=1]="Pane",g[g.DataWindow=2]="DataWindow",g[g.PriceScale=4]="PriceScale",g[g.StatusLine=8]="StatusLine",g[g.All=15]="All",function(e){e[e.None=0]="None",e[e.Pane=1]="Pane",e[e.DataWindow=2]="DataWindow",e[e.PriceScale=4]="PriceScale",e[e.StatusLine=8]="StatusLine",e[e.All=15]="All"}(u||(u={})),(C=e.OhlcStudyPlotStyle||(e.OhlcStudyPlotStyle={})).OhlcBars="ohlc_bars",C.OhlcCandles="ohlc_candles",function(e){e.Auto="auto",e.Tiny="tiny",e.Small="small",e.Normal="normal",e.Large="large",e.Huge="huge"}(S||(S={})),(p=e.StudyInputType||(e.StudyInputType={})).Integer="integer",p.Float="float",p.Price="price",p.Bool="bool",p.Text="text",p.Symbol="symbol",p.Session="session",p.Source="source",p.Resolution="resolution",p.Time="time",p.BarTime="bar_time",p.Color="color",p.Textarea="text_area",function(e){e[e.None=0]="None",e[e.DataWindow=2]="DataWindow",e[e.StatusLine=8]="StatusLine",e[e.All=15]="All"}(m||(m={})),function(e){e.InitialCapital="initial_capital",e.Currency="currency",e.DefaultQTYValue="default_qty_value",e.DefaultQTYType="default_qty_type",e.Pyramiding="pyramiding",e.ComissionValue="commission_value",e.ComissionType="commission_type",e.BacktestFillLimitsAssumtion="backtest_fill_limits_assumption",e.Slippage="slippage",e.CalcOnOrderFills="calc_on_order_fills",e.CalcOnEveryTick="calc_on_every_tick",e.MarginLong="margin_long",e.MarginShort="margin_short",e.UseBarMagnifier="use_bar_magnifier",e.ProcessOrdersOnClose="process_orders_on_close",e.FillOrdersOnStandardOHLC="fill_orders_on_standard_ohlc"}(y||(y={})),function(e){e.Fixed="fixed",e.CashPerOrder="cash_per_order",e.PercentOfEquity="percent_of_equity"}(_||(_={})),function(e){e.Percent="percent",e.CashPerContract="cash_per_contract",e.CashPerOrder="cash_per_order"}(T||(T={})),function(e){e.FirstBar="first_visible_bar_time",e.LastBar="last_visible_bar_time",e.Realtime="subscribeRealtime"}(b||(b={})),function(e){e.FgColor="__chart_fgcolor",e.BgColor="__chart_bgcolor"}(P||(P={})),(L=e.StudyTargetPriceScale||(e.StudyTargetPriceScale={}))[L.Right=0]="Right",L[L.Left=1]="Left",L[L.NoScale=2]="NoScale",function(e){e[e.Right=0]="Right",e[e.Left=1]="Left",e[e.None=2]="None"}(A||(A={})),(w=e.FilledAreaType||(e.FilledAreaType={})).TypePlots="plot_plot",w.TypeHlines="hline_hline",function(e){e[e.StopLoss=0]="StopLoss",e[e.TrailingStop=1]="TrailingStop",e[e.GuaranteedStop=2]="GuaranteedStop"}(f||(f={})),function(e){e.Symbol="symbol"}(v||(v={})),function(e){e[e.PopUp=0]="PopUp",e[e.Notification=1]="Notification"}(I||(I={})),function(e){e[e.CONNECTED=1]="CONNECTED",e[e.CONNECTING=2]="CONNECTING",e[e.DISCONNECTED=3]="DISCONNECTED",e[e.ERROR=4]="ERROR"}(O||(O={})),(R=e.ConnectionStatus||(e.ConnectionStatus={}))[R.Connected=1]="Connected",R[R.Connecting=2]="Connecting",R[R.Disconnected=3]="Disconnected",R[R.Error=4]="Error",function(e){e[e.LIMIT=1]="LIMIT",e[e.MARKET=2]="MARKET",e[e.STOP=3]="STOP",e[e.STOPLIMIT=4]="STOPLIMIT"}(D||(D={})),(V=e.OrderType||(e.OrderType={}))[V.Limit=1]="Limit",V[V.Market=2]="Market",V[V.Stop=3]="Stop",V[V.StopLimit=4]="StopLimit",function(e){e[e.BUY=1]="BUY",e[e.SELL=-1]="SELL"}(k||(k={})),(E=e.Side||(e.Side={}))[E.Buy=1]="Buy",E[E.Sell=-1]="Sell",function(e){e[e.CANCELED=1]="CANCELED",e[e.FILLED=2]="FILLED",e[e.INACTIVE=3]="INACTIVE",e[e.PLACING=4]="PLACING",e[e.REJECTED=5]="REJECTED",e[e.WORKING=6]="WORKING"}(F||(F={})),function(e){e[e.ALL=0]="ALL",e[e.CANCELED=1]="CANCELED",e[e.FILLED=2]="FILLED",e[e.INACTIVE=3]="INACTIVE",e[e.REJECTED=5]="REJECTED",e[e.WORKING=6]="WORKING"}(W||(W={})),(M=e.OrderStatus||(e.OrderStatus={}))[M.Canceled=1]="Canceled",M[M.Filled=2]="Filled",M[M.Inactive=3]="Inactive",M[M.Placing=4]="Placing",M[M.Rejected=5]="Rejected",M[M.Working=6]="Working",(B=e.OrderStatusFilter||(e.OrderStatusFilter={}))[B.All=0]="All",B[B.Canceled=1]="Canceled",B[B.Filled=2]="Filled",B[B.Inactive=3]="Inactive",B[B.Rejected=5]="Rejected",B[B.Working=6]="Working",function(e){e[e.Order=1]="Order",e[e.Position=2]="Position"}(N||(N={})),function(e){e[e.ORDER=1]="ORDER",e[e.POSITION=2]="POSITION"}(U||(U={})),(x=e.ParentType||(e.ParentType={}))[x.Order=1]="Order",x[x.Position=2]="Position",x[x.IndividualPosition=3]="IndividualPosition",function(e){e[e.StopLoss=0]="StopLoss",e[e.TakeProfit=1]="TakeProfit",e[e.TrailingStop=2]="TrailingStop",e[e.GuaranteedStop=3]="GuaranteedStop"}(H||(H={})),function(e){e[e.LIMITPRICE=1]="LIMITPRICE",e[e.STOPPRICE=2]="STOPPRICE",e[e.TAKEPROFIT=3]="TAKEPROFIT",e[e.STOPLOSS=4]="STOPLOSS"}(j||(j={})),(z=e.OrderTicketFocusControl||(e.OrderTicketFocusControl={}))[z.LimitPrice=1]="LimitPrice",z[z.StopPrice=2]="StopPrice",z[z.TakeProfit=3]="TakeProfit",z[z.StopLoss=4]="StopLoss",z[z.Quantity=5]="Quantity",function(e){e[e.ERROR=0]="ERROR",e[e.SUCCESS=1]="SUCCESS"}(G||(G={})),($=e.NotificationType||(e.NotificationType={}))[$.Error=0]="Error",$[$.Success=1]="Success",function(e){e[e.Demo=1]="Demo",e[e.Real=0]="Real"}(J||(J={})),(q=e.OrderOrPositionMessageType||(e.OrderOrPositionMessageType={})).Information="information",q.Warning="warning",q.Error="error",function(e){e.Demo="demo",e.Live="live"}(K||(K={})),function(e){e[e.LogOut=0]="LogOut",e[e.FailedRestoring=1]="FailedRestoring",e[e.Offline=2]="Offline",e[e.APIError=3]="APIError",e[e.TwoFactorRequired=4]="TwoFactorRequired",e[e.CancelAuthorization=5]="CancelAuthorization",e[e.TimeOutForAuthorization=6]="TimeOutForAuthorization",e[e.OauthError=7]="OauthError",e[e.BrokenConnection=8]="BrokenConnection",e[e.FailedSignIn=9]="FailedSignIn"}(Z||(Z={})),function(e){e[e.None=0]="None",e[e.Pips=1]="Pips",e[e.Ticks=2]="Ticks"}(Q||(Q={})),function(e){e.Halted="HALTED",e.NotShortable="NOT-SHORTABLE",e.HardToBorrow="HARD-TO-BORROW"}(Y||(Y={})),function(e){e[e.Limit=1]="Limit",e[e.Stop=2]="Stop"}(X||(X={})),function(e){e.Disallowed="disallowed",e.Allowed="allowed",e.AllowedWithWarning="allowed_with_warning"}(ee||(ee={})),function(e){e.PlaceOrder="place_order",e.ModifyOrder="modify_order",e.CancelOrder="cancel_order",e.ModifyPosition="modify_position",e.ClosePosition="close_position",e.ModifyIndividualPosition="modify_individual_position",e.CloseIndividualPosition="close_individual_position",e.CloseNetPosition="close_net_position"}(te||(te={})),(ie=e.StandardFormatterName||(e.StandardFormatterName={})).Date="date",ie.DateOrDateTime="dateOrDateTime",ie.Default="default",ie.Fixed="fixed",ie.FixedInCurrency="fixedInCurrency",ie.VariablePrecision="variablePrecision",ie.FormatQuantity="formatQuantity",ie.FormatPrice="formatPrice",ie.FormatPriceForexSup="formatPriceForexSup",ie.FormatPriceInCurrency="formatPriceInCurrency",ie.IntegerSeparated="integerSeparated",ie.LocalDate="localDate",ie.LocalDateOrDateTime="localDateOrDateTime",ie.Percentage="percentage",ie.Pips="pips",ie.Profit="profit",ie.ProfitInInstrumentCurrency="profitInInstrumentCurrency",ie.Side="side",ie.PositionSide="positionSide",ie.Status="status",ie.Symbol="symbol",ie.Text="text",ie.Type="type",ie.MarginPercent="marginPercent",ie.Empty="empty",(oe=e.OverridePriceAxisLastValueMode||(e.OverridePriceAxisLastValueMode={}))[oe.LastPriceAndPercentageValue=0]="LastPriceAndPercentageValue",oe[oe.LastValueAccordingToScale=1]="LastValueAccordingToScale",(re=e.OverrideLineStyle||(e.OverrideLineStyle={}))[re.Solid=0]="Solid",re[re.Dotted=1]="Dotted",re[re.Dashed=2]="Dashed",function(e){e[e.Offline=0]="Offline",e[e.Resolving=1]="Resolving",e[e.Loading=2]="Loading",e[e.Ready=3]="Ready",e[e.InvalidSymbol=4]="InvalidSymbol",e[e.Snapshot=5]="Snapshot",e[e.EOD=6]="EOD",e[e.Pulse=7]="Pulse",e[e.Delayed=8]="Delayed",e[e.DelayedSteaming=9]="DelayedSteaming",e[e.NoBars=10]="NoBars",e[e.Replay=11]="Replay",e[e.Error=12]="Error",e[e.CalculationError=13]="CalculationError",e[e.UnsupportedResolution=14]="UnsupportedResolution"}(ne||(ne={})),function(e){e[e.Markers=0]="Markers",e[e.Stepline=1]="Stepline",e[e.Simple=2]="Simple"}(ae||(ae={})),(se=e.ChartStyle||(e.ChartStyle={}))[se.Bar=0]="Bar",se[se.Candle=1]="Candle",se[se.Line=2]="Line",se[se.Area=3]="Area",se[se.Renko=4]="Renko",se[se.Kagi=5]="Kagi",se[se.PnF=6]="PnF",se[se.LineBreak=7]="LineBreak",se[se.HeikinAshi=8]="HeikinAshi",se[se.HollowCandle=9]="HollowCandle",se[se.Baseline=10]="Baseline",se[se.Range=11]="Range",se[se.HiLo=12]="HiLo",se[se.Column=13]="Column",se[se.LineWithMarkers=14]="LineWithMarkers",se[se.Stepline=15]="Stepline",se[se.HLCArea=16]="HLCArea",se[se.VolFootprint=17]="VolFootprint",se[se.TPO=18]="TPO",se[se.VolCandle=19]="VolCandle",se[se.SVP=20]="SVP",(le=e.TimeHoursFormat||(e.TimeHoursFormat={})).TwentyFourHours="24-hours",le.TwelveHours="12-hours",function(e){e[e.Initial=2]="Initial",e[e.SeriesZOrderIsAlwaysZero=3]="SeriesZOrderIsAlwaysZero",e[e.Current=3]="Current"}(de||(de={})),(ce=e.PlDisplay||(e.PlDisplay={}))[ce.Money=0]="Money",ce[ce.Pips=1]="Pips",ce[ce.Percentage=2]="Percentage",(he=e.TradedGroupHorizontalAlignment||(e.TradedGroupHorizontalAlignment={}))[he.Left=0]="Left",he[he.Center=1]="Center",he[he.Right=2]="Right";e.PlDisplay.Money,e.PlDisplay.Money,e.TradedGroupHorizontalAlignment.Right;var ge,ue,Ce,Se,pe,me,ye,_e,Te,be,Pe,Le,Ae,we,fe;function ve(e,t){const i={...e};for(const o in t)"object"!=typeof e[o]||null===e[o]||Array.isArray(e[o])?void 0!==t[o]&&(i[o]=t[o]):i[o]=ve(e[o],t[o]);return i}!function(e){e[e.Background=0]="Background",e[e.Foreground=1]="Foreground",e[e.Topmost=2]="Topmost"}(ge||(ge={})),function(e){e[e.Unavailable=0]="Unavailable",e[e.AvailableReadonlyAlwaysDisabled=1]="AvailableReadonlyAlwaysDisabled",e[e.AvailableReadonlyAlwaysEnabled=2]="AvailableReadonlyAlwaysEnabled",e[e.Available=3]="Available"}(ue||(ue={})),function(e){e[e.ViewportChangeUserAction=0]="ViewportChangeUserAction",e[e.DataUpdate=1]="DataUpdate",e[e.SeriesRestart=2]="SeriesRestart",e[e.SeriesCompleted=3]="SeriesCompleted",e[e.StudyCreation=4]="StudyCreation"}(Ce||(Ce={})),function(e){e[e.Chart=0]="Chart"}(Se||(Se={})),(pe=e.VisibilityType||(e.VisibilityType={})).AlwaysOn="alwaysOn",pe.VisibleOnMouseOver="visibleOnMouseOver",pe.AlwaysOff="alwaysOff",(me=e.PriceScaleMode||(e.PriceScaleMode={}))[me.Normal=0]="Normal",me[me.Log=1]="Log",me[me.Percentage=2]="Percentage",me[me.IndexedTo100=3]="IndexedTo100",(ye=e.SeriesType||(e.SeriesType={}))[ye.Bars=0]="Bars",ye[ye.Candles=1]="Candles",ye[ye.Line=2]="Line",ye[ye.Area=3]="Area",ye[ye.HeikenAshi=8]="HeikenAshi",ye[ye.HollowCandles=9]="HollowCandles",ye[ye.Baseline=10]="Baseline",ye[ye.HiLo=12]="HiLo",ye[ye.Column=13]="Column",ye[ye.LineWithMarkers=14]="LineWithMarkers",ye[ye.Stepline=15]="Stepline",ye[ye.HLCArea=16]="HLCArea",ye[ye.VolCandle=19]="VolCandle",ye[ye.Renko=4]="Renko",ye[ye.Kagi=5]="Kagi",ye[ye.PointAndFigure=6]="PointAndFigure",ye[ye.LineBreak=7]="LineBreak",function(e){e.Value="_seriesId"}(_e||(_e={})),(Te=e.HHistDirection||(e.HHistDirection={})).LeftToRight="left_to_right",Te.RightToLeft="right_to_left",function(e){e.Relative="relative",e.Absolute="absolute"}(be||(be={})),function(e){e.UpDown="Up/Down",e.Total="Total",e.Delta="Delta"}(Pe||(Pe={})),(Le=e.MarkLocation||(e.MarkLocation={})).AboveBar="AboveBar",Le.BelowBar="BelowBar",Le.Top="Top",Le.Bottom="Bottom",Le.Right="Right",Le.Left="Left",Le.Absolute="Absolute",Le.AbsoluteUp="AbsoluteUp",Le.AbsoluteDown="AbsoluteDown",function(e){e.Left="left",e.Center="center",e.Right="right"}(Ae||(Ae={})),function(e){e.Top="top",e.Middle="middle",e.Bottom="bottom"}(we||(we={})),(fe=e.LineStyle||(e.LineStyle={}))[fe.Solid=0]="Solid",fe[fe.Dotted=1]="Dotted",fe[fe.Dashed=2]="Dashed";const Ie={width:800,height:500,interval:"1D",timezone:"Etc/UTC",container:"",library_path:"",locale:"en",widgetbar:{details:!1,watchlist:!1,news:!1,datawindow:!1,watchlist_settings:{default_symbols:[]}},overrides:{"mainSeriesProperties.showCountdown":!1},studies_overrides:{},trading_customization:{position:{},order:{}},brokerConfig:{configFlags:{}},fullscreen:!1,autosize:!1,disabled_features:[],enabled_features:[],debug:!1,logo:{},time_frames:[{text:"5y",resolution:"1W"},{text:"1y",resolution:"1W"},{text:"6m",resolution:"120"},{text:"3m",resolution:"60"},{text:"1m",resolution:"30"},{text:"5d",resolution:"5"},{text:"1d",resolution:"1"}],client_id:"0",user_id:"0",charts_storage_api_version:"1.0",favorites:{intervals:[],chartTypes:[],indicators:[],drawingTools:[]}},Oe=JSON.parse('[{"iso":"ar","dir":"rtl","language":"ar"},{"iso":"pt","dir":"ltr","language":"pt"},{"iso":"ca","dir":"ltr","language":"ca_ES"},{"iso":"cs","dir":"ltr","language":"cs"},{"iso":"de","dir":"ltr","language":"de"},{"iso":"en","dir":"ltr","language":"en"},{"iso":"es","dir":"ltr","language":"es"},{"iso":"fa","dir":"rtl","language":"fa"},{"iso":"fr","dir":"ltr","language":"fr"},{"iso":"he","dir":"rtl","language":"he_IL"},{"iso":"hu","dir":"ltr","language":"hu_HU"},{"iso":"id","dir":"ltr","language":"id_ID"},{"iso":"en","dir":"ltr","language":"en"},{"iso":"it","dir":"ltr","language":"it"},{"iso":"ja","dir":"ltr","language":"ja"},{"iso":"ko","dir":"ltr","language":"ko"},{"iso":"ms","dir":"ltr","language":"ms_MY"},{"iso":"pl","dir":"ltr","language":"pl"},{"iso":"ru","dir":"ltr","language":"ru"},{"iso":"sv","dir":"ltr","language":"sv"},{"iso":"th","dir":"ltr","language":"th"},{"iso":"tr","dir":"ltr","language":"tr"},{"iso":"vi","dir":"ltr","language":"vi"},{"iso":"zh-Hans","dir":"ltr","language":"zh"},{"iso":"zh-Hant","dir":"ltr","language":"zh_TW"},{"iso":"el","dir":"ltr","language":"el"},{"iso":"nl","dir":"ltr","language":"nl_NL"},{"iso":"ro","dir":"ltr","language":"ro"}]');let Re=!1;function De(){return"CL v28.4.0 (internal id c30d174a @ 2024-11-29T13:11:24.945Z)"}const Ve=class{constructor(e){var t,i;if(this._id=`tradingview_${(1048576*(1+Math.random())|0).toString(16).substring(1)}`,this._ready=!1,this._readyHandlers=[],this._onWindowResize=this._autoResizeChart.bind(this),!e.datafeed)throw new Error("Datafeed is not defined");(null===(t=e.overrides)||void 0===t?void 0:t["mainSeriesProperties.priceAxisProperties.lockScale"])&&(console.warn("mainSeriesProperties.priceAxisProperties.lockScale can not be set to true within the widget constructor"),delete e.overrides["mainSeriesProperties.priceAxisProperties.lockScale"]),this._options=ve(Ie,e);"dark"===(null!==(i=this._options.theme)&&void 0!==i?i:"light").toLowerCase()&&void 0===this._options.loading_screen&&(this._options.loading_screen={backgroundColor:"#131722"}),(this._options.debug||this._options.debug_broker)&&(Re||(Re=!0,console.log("Using CL v28.4.0 (internal id c30d174a @ 2024-11-29T13:11:24.945Z)"))),this._innerWindowLoaded=new Promise((e=>{this._innerWindowResolver=e})),this._create()}setDebugMode(e){this._innerAPI().setDebugMode(e)}onChartReady(e){this._ready?e.call(this):this._readyHandlers.push(e)}headerReady(){return this._innerWindowLoaded.then((()=>this._innerWindow().headerReady()))}onGrayedObjectClicked(e){this._doWhenInnerApiLoaded((t=>{t.onGrayedObjectClicked(e)}))}onShortcut(e,t){this._doWhenInnerWindowLoaded((i=>{i.createShortcutAction(e,t)}))}subscribe(e,t){this._doWhenInnerApiLoaded((i=>{i.subscribe(e,t)}))}unsubscribe(e,t){this._doWhenInnerApiLoaded((i=>{i.unsubscribe(e,t)}))}chart(e){return this._innerAPI().chart(e)}getLanguage(){return this._options.locale}setSymbol(e,t,i){this._innerAPI().changeSymbol(e,t,i)}remove(){window.removeEventListener("resize",this._onWindowResize),this._readyHandlers.splice(0,this._readyHandlers.length),delete window[this._id],this._iFrame.parentNode&&this._iFrame.parentNode.removeChild(this._iFrame)}closePopupsAndDialogs(){this._doWhenInnerApiLoaded((e=>{e.closePopupsAndDialogs()}))}selectLineTool(e,t){this._innerAPI().selectLineTool(e,t)}selectedLineTool(){return this._innerAPI().selectedLineTool()}save(e,t){this._innerAPI().saveChart(e,t)}load(e,t){this._innerAPI().loadChart({json:e,extendedData:t})}getSavedCharts(e){this._innerAPI().getSavedCharts(e)}loadChartFromServer(e){this._innerAPI().loadChartFromServer(e)}saveChartToServer(e,t,i){this._innerAPI().saveChartToServer(e,t,i)}removeChartFromServer(e,t){this._innerAPI().removeChartFromServer(e,t)}onContextMenu(e){this._doWhenInnerApiLoaded((t=>{t.onContextMenu(e)}))}createButton(e){return this._innerWindow().createButton(e)}createDropdown(e){return this._innerWindow().createDropdown(e)}showNoticeDialog(e){this._doWhenInnerApiLoaded((t=>{t.showNoticeDialog(e)}))}showConfirmDialog(e){this._doWhenInnerApiLoaded((t=>{t.showConfirmDialog(e)}))}showLoadChartDialog(){this._innerAPI().showLoadChartDialog()}showSaveAsChartDialog(){this._innerAPI().showSaveAsChartDialog()}symbolInterval(){return this._innerAPI().getSymbolInterval()}mainSeriesPriceFormatter(){return this._innerAPI().mainSeriesPriceFormatter()}getIntervals(){return this._innerAPI().getIntervals()}getStudiesList(){return this._innerAPI().getStudiesList()}getStudyInputs(e){return this._innerAPI().getStudyInputs(e)}getStudyStyles(e){return this._innerAPI().getStudyStyles(e)}addCustomCSSFile(e){this._innerWindow().addCustomCSSFile(e)}applyOverrides(e){this._options=ve(this._options,{overrides:e}),this._doWhenInnerWindowLoaded((t=>{t.applyOverrides(e)}))}applyStudiesOverrides(e){this._doWhenInnerWindowLoaded((t=>{t.applyStudiesOverrides(e)}))}watchList(){return this._innerAPI().watchlist()}news(){return this._innerAPI().news()}widgetbar(){return this._innerAPI().widgetbar()}activeChart(){return this._innerAPI().activeChart()}activeChartIndex(){return this._innerAPI().activeChartIndex()}setActiveChart(e){return this._innerAPI().setActiveChart(e)}chartsCount(){return this._innerAPI().chartsCount()}layout(){return this._innerAPI().layout()}setLayout(e){this._innerAPI().setLayout(e)}layoutName(){return this._innerAPI().layoutName()}resetLayoutSizes(e){this._innerAPI().resetLayoutSizes(e)}changeTheme(e,t){return this._innerWindow().changeTheme(e,t)}getTheme(){return this._innerWindow().getTheme()}takeScreenshot(){this._doWhenInnerApiLoaded((e=>{e.takeScreenshot()}))}lockAllDrawingTools(){return this._innerAPI().lockAllDrawingTools()}hideAllDrawingTools(){return this._innerAPI().hideAllDrawingTools()}drawOnAllChartsEnabled(){return this._innerAPI().drawOnAllChartsEnabled()}drawOnAllCharts(e){this._innerAPI().drawOnAllCharts(e)}magnetEnabled(){return this._innerAPI().magnetEnabled()}magnetMode(){return this._innerAPI().magnetMode()}undoRedoState(){return this._innerAPI().undoRedoState()}setIntervalLinkingEnabled(e){this._innerAPI().setIntervalLinkingEnabled(e)}setDateRangeLinkingEnabled(e){this._innerAPI().setDateRangeLinkingEnabled(e)}setTimeFrame(e){this._innerAPI().setTimeFrame(e)}symbolSync(){return this._innerAPI().symbolSync()}intervalSync(){return this._innerAPI().intervalSync()}crosshairSync(){return this._innerAPI().crosshairSync()}timeSync(){return this._innerAPI().timeSync()}dateRangeSync(){return this._innerAPI().dateRangeSync()}setFeatureEnabled(e,t){this._innerAPI().setFeatureEnabled(e,t)}getAllFeatures(){return this._innerWindow().getAllFeatures()}clearUndoHistory(){return this._innerAPI().clearUndoHistory()}undo(){return this._innerAPI().undo()}redo(){return this._innerAPI().redo()}startFullscreen(){this._innerAPI().startFullscreen()}exitFullscreen(){this._innerAPI().exitFullscreen()}takeClientScreenshot(e){return this._innerAPI().takeClientScreenshot(e)}navigationButtonsVisibility(){return this._innerWindow().getNavigationButtonsVisibility()}paneButtonsVisibility(){return this._innerWindow().getPaneButtonsVisibility()}dateFormat(){return this._innerWindow().getDateFormat()}timeHoursFormat(){return this._innerWindow().getTimeHoursFormat()}currencyAndUnitVisibility(){return this._innerWindow().getCurrencyAndUnitVisibility()}supportedChartTypes(){return this._innerAPI().supportedChartTypes()}watermark(){return this._innerAPI().watermark()}customSymbolStatus(){return this._innerWindow().customSymbolStatus()}setCSSCustomProperty(e,t){if(!1===e.startsWith("--"))throw new Error("customPropertyName should begin with a double hyphen");this._innerWindow().document.body.style.setProperty(e,t)}getCSSCustomPropertyValue(e){if(!1===e.startsWith("--"))throw new Error("customPropertyName should begin with a double hyphen");const t=this._innerWindow().document.body,i=t.style.getPropertyValue(e);if(i)return i;return getComputedStyle(t).getPropertyValue(e)}unloadUnusedCharts(){this._innerAPI().unloadUnusedCharts()}async customThemes(){return this._innerWindow().customThemes()}linking(){return this._innerAPI().linking}_innerAPI(){return this._innerWindow().tradingViewApi}_innerWindow(){return this._iFrame.contentWindow}_doWhenInnerWindowLoaded(e){this._ready?e(this._innerWindow()):this._innerWindowLoaded.then((()=>{e(this._innerWindow())}))}_doWhenInnerApiLoaded(e){this._doWhenInnerWindowLoaded((t=>{t.doWhenApiIsReady((()=>e(this._innerAPI())))}))}_autoResizeChart(){this._options.fullscreen&&(this._iFrame.style.height=window.innerHeight+"px",ke&&setTimeout((()=>{this._iFrame.style.height=window.innerHeight+"px"}),30))}async _create(){var e,t,i,o;const r=null!==(t=null===(e=this._options.enabled_features)||void 0===e?void 0:e.includes("iframe_loading_same_origin"))&&void 0!==t&&t,n=r||null!==(o=null===(i=this._options.enabled_features)||void 0===i?void 0:i.includes("iframe_loading_compatibility_mode"))&&void 0!==o&&o,[a,s]=this._render(!n,r),l=this._options.container,d="string"==typeof l?document.getElementById(l):l;if(null===d)throw new Error(`There is no such element - #${this._options.container}`);d.innerHTML=a,this._iFrame=d.querySelector(`#${this._id}`);const c=this._iFrame;r&&await this._innerWindowEvent("sameOriginLoad"),n&&(c.contentWindow?(c.contentWindow.document.open(),c.contentWindow.document.write(s),c.contentWindow.document.close()):console.warn("Unable to locate contentWindow for the created iframe. Please try disabling the `iframe_loading_compatibility_mode` featureset.")),this._innerWindow().addEventListener("innerWindowLoad",function(e,t){if(void 0===e)throw new Error(`${t} is undefined`);return e}(this._innerWindowResolver,"_innerWindowResolver"),{once:!0}),(this._options.autosize||this._options.fullscreen)&&(c.style.width="100%",this._options.fullscreen||(c.style.height="100%")),window.addEventListener("resize",this._onWindowResize),this._onWindowResize(),this._innerWindowLoaded.then((()=>{try{this._innerWindow().widgetReady((()=>{this._ready=!0;for(const e of this._readyHandlers)try{e.call(this)}catch(e){console.error(e)}this._innerWindow().initializationFinished()}))}catch(e){if(e instanceof Error&&/widgetReady is not a function/.test(e.message))throw new Error(`There was an error when loading the library. Usually this error means the library failed to load its static files. Check that the library files are available at ${window.location.host}/${this._options.library_path||""} or correct the library_path option.`)}}))}_innerWindowEvent(e){return new Promise((t=>{this._innerWindow().addEventListener(e,t,{once:!0})}))}_render(e,t){var i;const o=window;if(o[this._id]={datafeed:this._options.datafeed,customFormatters:this._options.custom_formatters,brokerFactory:this._options.broker_factory,overrides:this._options.overrides,studiesOverrides:this._options.studies_overrides,tradingCustomization:this._options.trading_customization,disabledFeatures:this._options.disabled_features,enabledFeatures:this._options.enabled_features,brokerConfig:this._options.broker_config||this._options.brokerConfig,restConfig:this._options.restConfig,favorites:this._options.favorites,logo:this._options.logo,numeric_formatting:this._options.numeric_formatting,rss_news_feed:this._options.rss_news_feed,rss_news_title:this._options.rss_news_title,newsProvider:this._options.news_provider,loadLastChart:this._options.load_last_chart,saveLoadAdapter:this._options.save_load_adapter,loading_screen:this._options.loading_screen,settingsAdapter:this._options.settings_adapter,getCustomIndicators:this._options.custom_indicators_getter,additionalSymbolInfoFields:this._options.additional_symbol_info_fields,headerWidgetButtonsMode:this._options.header_widget_buttons_mode,customTranslateFunction:this._options.custom_translate_function,symbolSearchComplete:this._options.symbol_search_complete,contextMenu:this._options.context_menu,settingsOverrides:this._options.settings_overrides,timeframe:this._options.timeframe,customTimezones:this._options.custom_timezones,customChartDescriptionFunction:this._options.custom_chart_description_function,customThemes:this._options.custom_themes},this._options.saved_data)o[this._id].chartContent={json:this._options.saved_data},this._options.saved_data_meta_info&&(o[this._id].chartContentExtendedData=this._options.saved_data_meta_info);else if(!this._options.load_last_chart&&!this._options.symbol)throw new Error("Symbol is not defined: either 'symbol' or 'load_last_chart' option must be set");if(this._options.library_path&&!this._options.library_path.endsWith("/")&&console.warn("library_path option should contain a trailing forward slash"),this._options.locale){const e=encodeURIComponent(this._options.locale);Oe.findIndex((t=>t.language===e))>=0||(console.warn("locale isn't supported. Using default of `en`."),this._options.locale="en")}const r=function(e,t){var i;const o=new URL(`${e||""}`,location.href).href,r=JSON.parse('["bundles/runtime.45222d21327e712692d2.js","bundles/__LANG__.5826.82f25d5636541df34beb.js","bundles/9662.03109f673cda5962c847.css","bundles/7346.a2efeed47130dd4e832c.js","bundles/library.cb873585ffc0b08e6bdf.js"]'),n=encodeURIComponent(t),a=null!==(i=Oe.find((e=>e.language===n)))&&void 0!==i?i:{iso:"en",dir:"ltr"},s=`lang="${a.iso}" dir="${a.dir}"`,l=`\n${function(e,t,i){if(void 0===e)return"";const o=[],r=[];for(const n of e)n.endsWith(".js")?o.push(`<script defer crossorigin="anonymous" src="${n.replace("__LANG__",i)}"><\/script>`):n.endsWith(".css")&&r.push(`<link type="text/css" href="${t?n.replace(/\.css$/i,".rtl.css"):n}" rel="stylesheet"/>`);return[...o,...r].join("\n")}(r,"rtl"===a.dir,n)}\n`;return`<!DOCTYPE html><html ${(d={bundles:l,localeLanguage:n,htmlAttrs:s,libraryPath:o}).htmlAttrs}><head><base href="${d.libraryPath}"><meta charset="utf-8"><script>window===window.parent&&(location.href="about:blank")<\/script> ${d.bundles} </head><body class="chart-page unselectable on-widget"><div class="loading-indicator" id="loading-indicator"></div><script>var JSServer={},__initialEnabledFeaturesets=["charting_library"]<\/script><script>(function() {\n\t\twindow.urlParams = (function () {\n\t\t\tvar match,\n\t\t\t\tpl\t = /\\+/g, // Regex for replacing addition symbol with a space\n\t\t\t\tsearch = /([^&=]+)=?([^&]*)/g,\n\t\t\t\tdecode = function (s) { return decodeURIComponent(s.replace(pl, ' ')).replace(/<\\/?[^>]+(>|$)/g, ''); },\n\t\t\t\tquery = function() {\n\t\t\t\t\t// We don't use hash on the url because: safari 13 throws an error if you attempt this\n\t\t\t\t\t// on a blob, and safari 14 will strip hash from blob urls.\n\t\t\t\t\tif (frameElement && frameElement.dataset.widgetOptions) {\n\t\t\t\t\t\treturn frameElement.dataset.widgetOptions;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow "Unexpected use of this page";\n\t\t\t\t\t}\n\t\t\t\t}(),\n\t\t\t\tresult = {};\n\n\t\t\twhile (match = search.exec(query)) {\n\t\t\t\tresult[decode(match[1])] = decode(match[2]);\n\t\t\t}\n\n\t\t\tvar additionalSettingsObject = window.parent[result.uid];\n\n\t\t\tvar customObjectNames = ['datafeed', 'customFormatters', 'brokerFactory', 'save_load_adapter', 'customTranslateFunction', 'contextMenu'];\n\n\t\t\tfor (var p in additionalSettingsObject) {\n\t\t\t\tif (customObjectNames.indexOf(p) === -1) {\n\t\t\t\t\tresult[p] = JSON.stringify(additionalSettingsObject[p]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t})();\n\n\t\twindow.locale = urlParams.locale;\n\t\twindow.language = urlParams.locale; // a very big attention needed here\n\t\twindow.customTranslateFunction = window.parent[urlParams.uid].customTranslateFunction;\n\t\twindow.customChartDescriptionFunction = window.parent[urlParams.uid].customChartDescriptionFunction;\n\n\t\twindow.addCustomCSSFile = function(href) {\n\t\t\tvar link = document.createElement('link');\n\t\t\tlink.setAttribute('type', 'text/css');\n\t\t\tlink.setAttribute('rel', 'stylesheet');\n\t\t\tlink.setAttribute('href', href);\n\t\t\tlink.setAttribute('cross-origin', 'anonymous');\n\n\t\t\twindow.loadedCustomCss = new Promise((resolve) => {\n\t\t\t\tlink.onload = resolve;\n\t\t\t\tlink.onerror = resolve;\n\t\t\t});\n\t\t\tdocument.body.appendChild(link);\n\t\t};\n\n\t\twindow.loadedCustomCss = Promise.resolve();\n\t\tif (!!urlParams.customCSS) {\n\t\t\twindow.addCustomCSSFile(urlParams.customCSS);\n\t\t}\n\n\t\tvar loadingScreenParams = {};\n\n\t\tif (typeof urlParams.loading_screen === 'string') {\n\t\t\ttry {\n\t\t\t\tloadingScreenParams = JSON.parse(urlParams.loading_screen);\n\t\t\t} catch(e) {}\n\t\t}\n\n\t\tvar loadingIndicatorElement = document.getElementById('loading-indicator');\n\n\t\tif (loadingScreenParams.backgroundColor) {\n\t\t\tloadingIndicatorElement.style = 'background-color: ' + loadingScreenParams.backgroundColor;\n\t\t}\n\n\t\t!function(){"use strict";var t,e=new WeakMap;!function(t){t[t.Element=1]="Element",t[t.Document=9]="Document"}(t||(t={}));var n={mini:"xsmall",xxsmall:"xxsmall",xsmall:"xsmall",small:"small",medium:"medium",large:"large"};var s,i,o,r,l,c=(void 0===l&&(l=""),s='<div class="tv-spinner '.concat(l,'" role="progressbar"></div>'),o=function(n,s){var i,o;return i=null==s?document.documentElement:s.nodeType===t.Document?s.documentElement:s,e&&(o=e.get(i)),o||((o=i.ownerDocument.createRange()).selectNodeContents(i),e&&e.set(i,o)),o.createContextualFragment(n)}(s,i),null!==(r=o.firstElementChild)&&o.removeChild(r),r),a=function(){function t(t){this._shown=!1,this._el=c.cloneNode(!0),this.setSize(n[t||"large"])}return t.prototype.spin=function(t){return this._el.classList.add("tv-spinner--shown"),void 0===this._container&&(this._container=t,void 0!==t&&t.appendChild(this._el)),this._shown=!0,this},t.prototype.stop=function(t){return t&&void 0!==this._container&&this._container.removeChild(this._el),this._el&&this._el.classList.remove("tv-spinner--shown"),this._shown=!1,this},t.prototype.setStyle=function(t){var e=this;return Object.keys(t).forEach((function(n){var s=t[n];void 0!==s&&e._el.style.setProperty(n,s)})),this},t.prototype.style=function(){return this._el.style},t.prototype.setSize=function(t){var e=void 0!==t?"tv-spinner--size_".concat(t):"";return this._el.className="tv-spinner ".concat(e," ").concat(this._shown?"tv-spinner--shown":""),this},t.prototype.getEl=function(){return this._el},t.prototype.destroy=function(){this.stop(),delete this._el,delete this._container},t}();window.Spinner=a}();\n\n\n\t\tvar spinnerColor = (loadingScreenParams.foregroundColor) ? loadingScreenParams.foregroundColor : undefined;\n\n\t\tvar loadingSpinner = new Spinner('large').setStyle({\n\t\t\t'--tv-spinner-color': spinnerColor,\n\t\t\tzIndex: String(2e9),\n\t\t});\n\t\tloadingSpinner.getEl().classList.add('spinner');\n\t\tloadingSpinner.spin(loadingIndicatorElement);\n\t})();<\/script></body></html>`;var d}(this._options.library_path||"",this._options.locale);let n=new URL("about:blank");if(e){const e=new Blob([r],{type:"text/html"}),t=URL.createObjectURL(e);n=new URL(t)}else if(t){const e=null!==(i=this._options.library_path)&&void 0!==i?i:"/";n=new URL(e+"sameorigin.html",location.origin)}const a="symbol="+encodeURIComponent(this._options.symbol||"")+"&interval="+encodeURIComponent(this._options.interval)+(this._options.toolbar_bg?"&toolbarbg="+encodeURIComponent(this._options.toolbar_bg.replace("#","")):"")+(this._options.studies_access?"&studiesAccess="+encodeURIComponent(JSON.stringify(this._options.studies_access)):"")+"&widgetbar="+encodeURIComponent(JSON.stringify(this._options.widgetbar))+(this._options.drawings_access?"&drawingsAccess="+encodeURIComponent(JSON.stringify(this._options.drawings_access)):"")+"&timeFrames="+encodeURIComponent(JSON.stringify(this._options.time_frames))+"&locale="+encodeURIComponent(this._options.locale)+"&uid="+encodeURIComponent(this._id)+"&clientId="+encodeURIComponent(String(this._options.client_id))+"&userId="+encodeURIComponent(String(this._options.user_id))+(this._options.charts_storage_url?"&chartsStorageUrl="+encodeURIComponent(this._options.charts_storage_url):"")+(this._options.charts_storage_api_version?"&chartsStorageVer="+encodeURIComponent(this._options.charts_storage_api_version):"")+(this._options.custom_css_url?"&customCSS="+encodeURIComponent(this._options.custom_css_url):"")+(this._options.custom_font_family?"&customFontFamily="+encodeURIComponent(this._options.custom_font_family):"")+(this._options.auto_save_delay?"&autoSaveDelay="+encodeURIComponent(String(this._options.auto_save_delay)):"")+"&debug="+encodeURIComponent(String(this._options.debug))+(this._options.debug_broker?"&debugBroker="+encodeURIComponent(String(this._options.debug_broker)):"")+(this._options.snapshot_url?"&snapshotUrl="+encodeURIComponent(this._options.snapshot_url):"")+(this._options.timezone?"&timezone="+encodeURIComponent(this._options.timezone):"")+(this._options.study_count_limit?"&studyCountLimit="+encodeURIComponent(String(this._options.study_count_limit)):"")+(this._options.symbol_search_request_delay?"&ssreqdelay="+encodeURIComponent(String(this._options.symbol_search_request_delay)):"")+(this._options.compare_symbols?"&compareSymbols="+encodeURIComponent(JSON.stringify(this._options.compare_symbols)):"")+(this._options.theme?"&theme="+encodeURIComponent(String(this._options.theme)):"")+(this._options.header_widget_buttons_mode?"&header_widget_buttons_mode="+encodeURIComponent(String(this._options.header_widget_buttons_mode)):"")+(this._options.time_scale?"&time_scale="+encodeURIComponent(JSON.stringify(this._options.time_scale)):"");return[`<iframe\n\t\tversion="CL v28.4.0 (internal id c30d174a @ 2024-11-29T13:11:24.945Z)" id="${this._id}" name="${this._id}" src="${n.href}" data-widget-options="${a}"\n\t\t${this._options.autosize||this._options.fullscreen?"":`width="${this._options.width}" height="${this._options.height}"`} title="Financial Chart" frameborder="0" allowTransparency="true" scrolling="no" allowfullscreen style="display:block;">\n\t</iframe>`,r]}};"undefined"!=typeof window&&(window.TradingView=window.TradingView||{},window.TradingView.version=De);const ke=!("undefined"==typeof window||!window.navigator||!window.navigator.userAgent)&&window.navigator.userAgent.includes("CriOS");return e.version=De,e.widget=Ve,e}({});
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
\ No newline at end of file
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
\ No newline at end of file
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
\ No newline at end of file
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.TradingViewDatafeed=t():e.TradingViewDatafeed=t()}(globalThis,(()=>(()=>{"use strict";var e={137:(e,t)=>{function s(e,t){if(void 0===e)throw new Error("".concat(null!=t?t:"Value"," is undefined"));return e}function o(e,t){if(null===e)throw new Error("".concat(null!=t?t:"Value"," is null"));return e}t.hu=void 0,t.hu=function(e,t){if(!e)throw new Error("Assertion failed".concat(t?": ".concat(t):""))}}},t={};function s(o){var n=t[o];if(void 0!==n)return n.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,s),i.exports}s.d=(e,t)=>{for(var o in t)s.o(t,o)&&!s.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{const{miniCssF:e}=s;s.miniCssF=t=>self.document&&"rtl"===self.document.dir?e(t).replace(/\.css$/,".rtl.css"):e(t)})();var o={};return(()=>{function e(e,t=!1){const{searchParams:s}=new URL(String(location));let o="true"===s.get("mobileapp_new"),n="true"===s.get("mobileapp");if(!t){const e=function(e){const t=e+"=",s=document.cookie.split(";");for(let e=0;e<s.length;e++){let o=s[e];for(;" "===o.charAt(0);)o=o.substring(1,o.length);if(0===o.indexOf(t))return o.substring(t.length,o.length)}return null}("tv_app")||"";o||(o=["android","android_nps"].includes(e)),n||(n="ios"===e)}return!("new"!==e&&"any"!==e||!o)||!("new"===e||!n)}s.r(o),s.d(o,{TradingViewDatafeed:()=>ke});const t=()=>{},n="~m~";class i{constructor(e,t={}){this.sessionid=null,this.connected=!1,this._timeout=null,this._base=e,this._options={timeout:t.timeout||2e4,connectionType:t.connectionType}}connect(){this._socket=new WebSocket(this._prepareUrl()),this._socket.onmessage=e=>{if("string"!=typeof e.data)throw new TypeError(`The WebSocket message should be a string. Recieved ${Object.prototype.toString.call(e.data)}`);this._onData(e.data)},this._socket.onclose=this._onClose.bind(this),this._socket.onerror=this._onError.bind(this)}send(e){this._socket&&this._socket.send(this._encode(e))}disconnect(){this._clearIdleTimeout(),this._socket&&(this._socket.onmessage=t,this._socket.onclose=t,this._socket.onerror=t,this._socket.close())}_clearIdleTimeout(){null!==this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}_encode(e){let t,s="";const o=Array.isArray(e)?e:[e],r=o.length;for(let e=0;e<r;e++)t=null===o[e]||void 0===o[e]?"":i._stringify(o[e]),s+=n+t.length+n+t;return s}_decode(e){const t=[];let s,o;do{if(e.substring(0,3)!==n)return t;s="",o="";const i=(e=e.substring(3)).length;for(let t=0;t<i;t++){if(o=Number(e.substring(t,t+1)),Number(e.substring(t,t+1))!==o){e=e.substring(s.length+n.length),s=Number(s);break}s+=o}t.push(e.substring(0,s)),e=e.substring(s)}while(""!==e);return t}_onData(e){this._setTimeout();const t=this._decode(e),s=t.length
;for(let e=0;e<s;e++)this._onMessage(t[e])}_setTimeout(){this._clearIdleTimeout(),this._timeout=setTimeout(this._onTimeout.bind(this),this._options.timeout)}_onTimeout(){this.disconnect(),this._onDisconnect({code:4e3,reason:"socket.io timeout",wasClean:!1})}_onMessage(e){this.sessionid?this._checkIfHeartbeat(e)?this._onHeartbeat(e.slice(3)):this._checkIfJson(e)?this._base.onMessage(JSON.parse(e.slice(3))):this._base.onMessage(e):(this.sessionid=e,this._onConnect())}_checkIfHeartbeat(e){return this._checkMessageType(e,"h")}_checkIfJson(e){return this._checkMessageType(e,"j")}_checkMessageType(e,t){return e.substring(0,3)==="~"+t+"~"}_onHeartbeat(e){this.send("~h~"+e)}_onConnect(){this.connected=!0,this._base.onConnect()}_onDisconnect(e){this._clear(),this._base.onDisconnect(e),this.sessionid=null}_clear(){this.connected=!1}_prepareUrl(){const t=c(this._base.host);if(t.pathname+="socket.io/websocket",t.protocol="wss:",t.searchParams.append("from",window.location.pathname.slice(1,50)),t.searchParams.append("date",window.BUILD_TIME||""),e("any")&&t.searchParams.append("client","mobile"),this._options.connectionType&&t.searchParams.append("type",this._options.connectionType),window.WEBSOCKET_PARAMS_ANALYTICS){const{ws_page_uri:e,ws_ancestor_origin:s}=window.WEBSOCKET_PARAMS_ANALYTICS;e&&t.searchParams.append("page-uri",e),s&&t.searchParams.append("ancestor-origin",s)}return t.href}_onClose(e){this._clearIdleTimeout(),this._onDisconnect(e)}_onError(e){this._clearIdleTimeout(),this._clear(),this._base.emit("error",[e]),this.sessionid=null}static _stringify(e){return"[object Object]"===Object.prototype.toString.call(e)?"~j~"+JSON.stringify(e):String(e)}}class r{constructor(e,t){this.host=e,this._connecting=!1,this._events={},this.transport=this._getTransport(t)}isConnected(){return!!this.transport&&this.transport.connected}isConnecting(){return this._connecting}connect(){this.isConnected()||(this._connecting&&this.disconnect(),this._connecting=!0,this.transport.connect())}send(e){this.transport&&this.transport.connected&&this.transport.send(e)}disconnect(){this.transport&&this.transport.disconnect()}on(e,t){e in this._events||(this._events[e]=[]),this._events[e].push(t)}offAll(){this._events={}}onMessage(e){this.emit("message",[e])}emit(e,t=[]){if(e in this._events){const s=this._events[e].concat(),o=s.length;for(let e=0;e<o;e++)s[e].apply(this,t)}}onConnect(){this.clear(),this.emit("connect")}onDisconnect(e){this.emit("disconnect",[e])}clear(){this._connecting=!1}_getTransport(e){return new i(this,e)}}function c(e){const t=-1!==e.indexOf("/")?new URL(e):new URL("wss://"+e);if("wss:"!==t.protocol&&"https:"!==t.protocol)throw new Error("Invalid websocket base "+e);return t.pathname.endsWith("/")||(t.pathname+="/"),t.search="",t.username="",t.password="",t}const a=Number(window.TELEMETRY_WS_ERROR_LOGS_THRESHOLD)||0;class l{constructor(e,t={}){this._queueStack=[],this._logsQueue=[],this._telemetryObjectsQueue=[],this._reconnectCount=0,this._redirectCount=0,this._errorsCount=0,this._errorsInfoSent=!1,this._connectionStart=null,
this._connectionEstablished=null,this._reconnectTimeout=null,this._onlineCancellationToken=null,this._isConnectionForbidden=!1,this._initialHost=t.initialHost||null,this._suggestedHost=e,this._proHost=t.proHost,this._reconnectHost=t.reconnectHost,this._noReconnectAfterTimeout=!0===t.noReconnectAfterTimeout,this._dataRequestTimeout=t.dataRequestTimeout,this._connectionType=t.connectionType,this._doConnect(),t.pingRequired&&-1===window.location.search.indexOf("noping")&&this._startPing()}connect(){this._tryConnect()}resetCounters(){this._reconnectCount=0,this._redirectCount=0}setLogger(e,t){this._logger=e,this._getLogHistory=t,this._flushLogs()}setTelemetry(e){this._telemetry=e,this._telemetry.reportSent.subscribe(this,this._onTelemetrySent),this._flushTelemetry()}onReconnect(e){this._onReconnect=e}isConnected(){return!!this._socket&&this._socket.isConnected()}isConnecting(){return!!this._socket&&this._socket.isConnecting()}on(e,t){return!!this._socket&&("connect"===e&&this._socket.isConnected()?t():"disconnect"===e?this._disconnectCallbacks.push(t):this._socket.on(e,t),!0)}getSessionId(){return this._socket&&this._socket.transport?this._socket.transport.sessionid:null}send(e){return this.isConnected()?(this._socket.send(e),!0):(this._queueMessage(e),!1)}getConnectionEstablished(){return this._connectionEstablished}getHost(){const e=this._tryGetProHost();return null!==e?e:this._reconnectHost&&this._reconnectCount>3?this._reconnectHost:this._suggestedHost}getReconnectCount(){return this._reconnectCount}getRedirectCount(){return this._redirectCount}getConnectionStart(){return this._connectionStart}disconnect(){this._clearReconnectTimeout(),(this.isConnected()||this.isConnecting())&&(this._propagateDisconnect(),this._disconnectCallbacks=[],this._closeSocket())}forbidConnection(){this._isConnectionForbidden=!0,this.disconnect()}allowConnection(){this._isConnectionForbidden=!1,this.connect()}isMaxRedirects(){return this._redirectCount>=20}isMaxReconnects(){return this._reconnectCount>=20}getPingInfo(){return this._pingInfo||null}_tryGetProHost(){return window.TradingView&&window.TradingView.onChartPage&&"battle"===window.environment&&!this._redirectCount&&-1===window.location.href.indexOf("ws_host")?this._initialHost?this._initialHost:void 0!==window.user&&window.user.pro_plan?this._proHost||this._suggestedHost:null:null}_queueMessage(e){0===this._queueStack.length&&this._logMessage(0,"Socket is not connected. Queued a message"),this._queueStack.push(e)}_processMessageQueue(){0!==this._queueStack.length&&(this._logMessage(0,"Processing queued messages"),this._queueStack.forEach(this.send.bind(this)),this._logMessage(0,"Processed "+this._queueStack.length+" messages"),this._queueStack=[])}_onDisconnect(e){this._noReconnectAfterTimeout||null!==this._reconnectTimeout||(this._reconnectTimeout=setTimeout(this._tryReconnect.bind(this),5e3)),this._clearOnlineCancellationToken();let t="disconnect session:"+this.getSessionId();e&&(t+=", code:"+e.code+", reason:"+e.reason,1005===e.code&&this._sendTelemetry("websocket_code_1005")),
this._logMessage(0,t),this._propagateDisconnect(e),this._closeSocket(),this._queueStack=[]}_closeSocket(){null!==this._socket&&(this._socket.offAll(),this._socket.disconnect(),this._socket=null)}_logMessage(e,t){const s={method:e,message:t};this._logger?this._flushLogMessage(s):(s.message=`[${(new Date).toISOString()}] ${s.message}`,this._logsQueue.push(s))}_flushLogMessage(e){switch(e.method){case 2:this._logger.logDebug(e.message);break;case 3:this._logger.logError(e.message);break;case 0:this._logger.logInfo(e.message);break;case 1:this._logger.logNormal(e.message)}}_flushLogs(){this._flushLogMessage({method:1,message:"messages from queue. Start."}),this._logsQueue.forEach((e=>{this._flushLogMessage(e)})),this._flushLogMessage({method:1,message:"messages from queue. End."}),this._logsQueue=[]}_sendTelemetry(e,t){const s={event:e,params:t};this._telemetry?this._flushTelemetryObject(s):this._telemetryObjectsQueue.push(s)}_flushTelemetryObject(e){this._telemetry.sendChartReport(e.event,e.params,!1)}_flushTelemetry(){this._telemetryObjectsQueue.forEach((e=>{this._flushTelemetryObject(e)})),this._telemetryObjectsQueue=[]}_doConnect(){this._socket&&(this._socket.isConnected()||this._socket.isConnecting())||(this._clearOnlineCancellationToken(),this._host=this.getHost(),this._socket=new r(this._host,{timeout:this._dataRequestTimeout,connectionType:this._connectionType}),this._logMessage(0,"Connecting to "+this._host),this._bindEvents(),this._disconnectCallbacks=[],this._connectionStart=performance.now(),this._connectionEstablished=null,this._socket.connect(),performance.mark("SWSC",{detail:"Start WebSocket connection"}),this._socket.on("connect",(()=>{performance.mark("EWSC",{detail:"End WebSocket connection"}),performance.measure("WebSocket connection delay","SWSC","EWSC")})))}_propagateDisconnect(e){const t=this._disconnectCallbacks.length;for(let s=0;s<t;s++)this._disconnectCallbacks[s](e||{})}_bindEvents(){this._socket&&(this._socket.on("connect",(()=>{const e=this.getSessionId();if("string"==typeof e){const t=JSON.parse(e);if(t.redirect)return this._redirectCount+=1,this._suggestedHost=t.redirect,this.isMaxRedirects()&&this._sendTelemetry("redirect_bailout"),void this._redirect()}this._connectionEstablished=performance.now(),this._processMessageQueue(),this._logMessage(0,"connect session:"+e)})),this._socket.on("disconnect",this._onDisconnect.bind(this)),this._socket.on("close",this._onDisconnect.bind(this)),this._socket.on("error",(e=>{this._logMessage(0,new Date+" session:"+this.getSessionId()+" websocket error:"+JSON.stringify(e)),this._sendTelemetry("websocket_error"),this._errorsCount++,!this._errorsInfoSent&&this._errorsCount>=a&&(void 0!==this._lastConnectCallStack&&(this._sendTelemetry("websocket_error_connect_stack",{text:this._lastConnectCallStack}),delete this._lastConnectCallStack),void 0!==this._getLogHistory&&this._sendTelemetry("websocket_error_log",{text:this._getLogHistory(50).join("\n")}),this._errorsInfoSent=!0)})))}_redirect(){this.disconnect(),this._reconnectWhenOnline()}_tryReconnect(){
this._tryConnect()&&(this._reconnectCount+=1)}_tryConnect(){return!this._isConnectionForbidden&&(this._clearReconnectTimeout(),this._lastConnectCallStack=new Error(`WebSocket connect stack. Is connected: ${this.isConnected()}.`).stack||"",!this.isConnected()&&(this.disconnect(),this._reconnectWhenOnline(),!0))}_clearOnlineCancellationToken(){this._onlineCancellationToken&&(this._onlineCancellationToken(),this._onlineCancellationToken=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_reconnectWhenOnline(){if(navigator.onLine)return this._logMessage(0,"Network status: online - trying to connect"),this._doConnect(),void(this._onReconnect&&this._onReconnect());this._logMessage(0,"Network status: offline - wait until online"),this._onlineCancellationToken=function(e){let t=e;const s=()=>{window.removeEventListener("online",s),t&&t()};return window.addEventListener("online",s),()=>{t=null}}((()=>{this._logMessage(0,"Network status changed to online - trying to connect"),this._doConnect(),this._onReconnect&&this._onReconnect()}))}_onTelemetrySent(e){"websocket_error"in e&&(this._errorsCount=0,this._errorsInfoSent=!1)}_startPing(){if(this._pingIntervalId)return;const e=c(this.getHost());e.pathname+="ping",e.protocol="https:";let t=0,s=0;const o=e=>{this._pingInfo=this._pingInfo||{max:0,min:1/0,avg:0};const o=(new Date).getTime()-e;o>this._pingInfo.max&&(this._pingInfo.max=o),o<this._pingInfo.min&&(this._pingInfo.min=o),t+=o,s++,this._pingInfo.avg=t/s,s>=10&&this._pingIntervalId&&(clearInterval(this._pingIntervalId),delete this._pingIntervalId)};this._pingIntervalId=setInterval((()=>{const t=(new Date).getTime(),s=new XMLHttpRequest;s.open("GET",e,!0),s.send(),s.onreadystatechange=()=>{s.readyState===XMLHttpRequest.DONE&&200===s.status&&o(t)}}),1e4)}}const h="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";function d(){return function(e){let t="";for(let s=0;s<e;++s){const e=Math.floor(Math.random()*h.length);t+=h[e]}return t}(12)}function _(e){return e.index=e.i,e.value=e.v,delete e.i,delete e.v,e}function u(e){for(const t of Object.keys(e))e[t].t&&(e[t].turnaround=e[t].t),e[t].s&&!e[t].series&&(e[t].series=e[t].s.map(_)),e[t].st&&!e[t].series&&(e[t].series=e[t].st.map(_))}class g{chart_create_session(e){return[e,"library_datafeed"]}resolve_symbol(e,t,s){return[e,t,s]}create_series(e,t,s,o,n,i){return[e,t,s,o,n,i,""]}remove_series(e,t){return[e,t]}unpack(e){const t=JSON.parse(e);t.m&&t.p&&(t.method=t.m,t.params=t.p,t.time=t.t);const s=t.params[1];switch(t.method){case"du":t.method="data_update",u(s);break;case"timescale_update":u(s)}return t}}var m=s(137);const b="undefined"!=typeof window?window:{};let f=!1;try{localStorage.getItem(""),f=!0}catch(e){}var y;!function(e){e[e.ERROR=1]="ERROR",e[e.WARNING=2]="WARNING",e[e.INFO=3]="INFO",e[e.NORMAL=4]="NORMAL",e[e.DEBUG=5]="DEBUG"}(y||(y={}));let p=0;const S="tv.logger.loglevel",C="tv.logger.logHighRate",I=[];let E=null,v=null,w=null,k=NaN,T=y.WARNING,R=!1;function O(e){
e=Math.max(y.ERROR,Math.min(y.DEBUG,e)),T=e,P()}function A(e){return new Date(e.timestamp).toISOString()+":"+e.subSystemId+":"+e.message.replace(/"/g,"'")}b.lget=(e,t)=>{const s=function(e,t){let s=I.reduce(((e,t)=>e.concat(t)),[]);return s.sort(((e,t)=>e.id-t.id)),void 0!==t&&(s=s.filter((e=>e.subSystemId===t))),"number"==typeof e&&(s=s.slice(-e)),s}(e,t).map(A);return function(e,t){let s,o=0,n=0;for(s=e.length-1;s>=1&&(o+=8*(1+encodeURIComponent(e[s]).length),!(s-1>0&&(n=8*(1+encodeURIComponent(e[s-1]).length),o+n>t)));s--);return e.slice(s)}(s,75497472)};function M(e,t,s,o){if(t===v&&o.id===w)return;const n=new Date;if(e<=y.NORMAL&&function(e,t,s,o,n){"function"==typeof structuredClone&&(t=structuredClone(t));const i={id:p,message:t,subSystemId:o,timestamp:Number(e)};p+=1,s.push(i),void 0!==n&&s.length>n&&s.splice(0,1)}(n,t,s,o.id,o.maxCount),e<=T&&(!o.highRate||R)&&(!E||o.id.match(E))){const s=n.toISOString()+":"+o.id+":"+t;switch(e){case y.DEBUG:console.debug(s);break;case y.INFO:case y.NORMAL:o.color?console.log("%c"+s,"color: "+o.color):console.log(s);break;case y.WARNING:console.warn(s);break;case y.ERROR:console.error(s)}v=t,w=o.id,k&&clearTimeout(k),k=setTimeout((()=>{v=null,w=null,k=NaN}),1e3)}}function B(e,t={}){const s=[];I.push(s);const o=Object.assign(t,{id:e});function n(e){return t=>M(e,String(t),s,o)}return{logDebug:n(y.DEBUG),logError:n(y.ERROR),logInfo:n(y.INFO),logNormal:n(y.NORMAL),logWarn:n(y.WARNING)}}const N=B("logger");b.lon=(e,t)=>{O(y.DEBUG),N.logNormal("Debug logging enabled"),R=Boolean(e),E=t||null,P()},b.loff=()=>{O(y.INFO),N.logInfo("Debug logging disabled")};function P(){try{f&&(localStorage.setItem(C,String(R)),localStorage.setItem(S,String(T)))}catch(e){N.logWarn(`Cannot save logger state (level: ${T}, high-rate: ${R}) to localStorage: ${e.message}`)}}!function(){R=!!f&&"true"===localStorage.getItem(C);let e=parseInt(f&&localStorage.getItem(S)||"");Number.isNaN(e)&&(e=y.WARNING),O(e),N.logNormal(`Init with settings - level: ${T}, high-rate: ${R}`)}(),b.performance&&b.performance.now?N.logNormal(`Sync logger and perf times, now is ${b.performance.now()}`):N.logWarn("Perf time is not available");B("Common.InitData"),window.initData;var D;!function(e){e[e.Medium=0]="Medium",e[e.Large=1]="Large"}(D||(D={}));class L{constructor(e){(0,m.hu)(""!==e,"S3 base url must be a non-empty string"),this._baseUrl=e}getSymbolLogoUrl(e,t){switch((0,m.hu)(""!==e,"logo id must be a non-empty string"),t){case D.Medium:return this._baseUrl+`${e}.svg`;case D.Large:return this._baseUrl+`${e}--big.svg`}}getCountryFlagUrl(e,t){return this.getSymbolLogoUrl("country/"+e,t)}getCryptoLogoUrl(e,t){return this.getSymbolLogoUrl("crypto/"+e,t)}getProviderLogoUrl(e,t){return this.getSymbolLogoUrl("provider/"+e,t)}getSourceLogoUrl(e,t){return this.getSymbolLogoUrl("source/"+e,t)}getBlockchainContractLogoUrl(e,t){return this.getSymbolLogoUrl("blockchain/"+e,t)}}const U="https://s3-symbol-logo.tradingview.com/",H=new L(U);function q(e){return 2!==e.length?e:function(e){return e.some((e=>X(e)))}(e)&&!function(e){
return e.some((e=>(e.includes("currency")||e.includes("country"))&&!X(e)))}(e)?e.filter((e=>!X(e))):e}function X(e){return e.includes("currency/USD")||e.includes("country/US")}function x(e){const t={},s=q(function(e,t=D.Medium){const s=e.logoid,o=e["base-currency-logoid"],n=e["currency-logoid"],i=s&&H.getSymbolLogoUrl(s,t);if(i)return[i];const r=o&&H.getSymbolLogoUrl(o,t),c=n&&H.getSymbolLogoUrl(n,t);return r&&c?[r,c]:r?[r]:c?[c]:[]}(e,D.Medium));s.length>=1&&(t.logo_urls=s);const o=e.country?H.getCountryFlagUrl(e.country,D.Medium):void 0,n=e.provider_id?H.getProviderLogoUrl(e.provider_id,D.Medium):void 0;return(o||n)&&(t.exchange_logo=o||n),t}function W(){let e,t;return{promise:new Promise(((s,o)=>{e=s,t=o})),reject:t,resolve:e}}function F(e){return"="+JSON.stringify(G(e))}function G(e){return Object.keys(e).sort().reduce(((t,s)=>("[object Object]"===Object.prototype.toString.call(e[s])?t[s]=G(e[s]):t[s]=e[s],t)),{})}function $(e){return Boolean(e.inputs)||function(e){return Boolean(e.replay)}(e)||e.session||e.adjustment||e["currency-id"]||e["unit-id"]?F(e):e.symbol}const Q=["1","5","15","30","45","60","120","180","240","1D","1W","1M"],j={supports_marks:!1,supports_timescale_marks:!0,supported_resolutions:Q,exchanges:[{value:"",name:"",desc:""}],symbols_types:[{name:"All",value:""},{name:"Stock",value:"stock"},{name:"Forex",value:"forex"},{name:"Index",value:"index"},{name:"Crypto",value:"crypto"}],is_tradingview_data:!0};const K=B("LibraryTVDatafeed.Session",{highRate:!0});function V(e){return`r,${e.from}:${e.to}`}function Y(e){return[e.ticker,e.currency_code,e.unit_id,e.subsession_id].filter((e=>!!e)).join("_#_")}function J(e){return"series_completed"===e.method}function Z(e){return"series_error"===e.method}function z(e){return"series_loading"===e.method}function ee(e){return"symbol_error"===e.method}function te(e){return"symbol_resolved"===e.method}function se(e){return"timescale_update"===e.method}function oe(e){return"data_update"===e.method}function ne(e,t){const s=[],[,o]=t.params;if(void 0===o[e])return s;const n=o[e].s||[];for(let e=0;e<n.length;e++){const[t,o,i,r,c,a]=n[e].value;s.push({time:1e3*t,open:o,high:i,low:r,close:c,volume:a})}return s}function ie(){return"lib_sess_"+d()}function re(){return"s_"+d()}function ce(){return"sym_"+d()}class ae{constructor(e,t,s){var o,n;this._dataHandleModule=new g,this._realtimeSubscriberCallbacks={},this._getBarsResult={bars:[],meta:{}},this._symbolInfoHashes=new Set,this._sessionId=ie(),this._seriesId=re(),this._symbolId=ce(),this._isSessionCreated=!1,this._isSeriesCreated=!1,this._isSeriesLoading=!1,this._deferredGetBarsPromise=W(),this._deferredResolveSymbolPromise=W(),this._wsBackendConnection=e,this._quotesProvider=t,this._partialSymbolInfoForResolve=s,this._symbolStringForResolve=(o=s.ticker,void 0===(n={currencyCode:s.currency_code,unitId:s.unit_id,session:s.subsession_id})?o:$({symbol:o,session:n.session})),this._symbolInfoHashes.add(Y(s)),this._wsBackendConnection.on("message",(e=>setTimeout((()=>this._onWsBackendMessage(e)),0)))}hasSymbol(e,t){
const s=this._symbolInfoHashes.has(Y(e)),o=t===this._resolution;return s&&(!this._isSeriesCreated||o)}hasSubscriber(e){return void 0!==this._realtimeSubscriberCallbacks[e]}async resolveSymbol(){return void 0!==this._symbolInfo?this._symbolInfo:(this._isSessionCreated||(this._isSessionCreated=!0,this._sessionId=ie(),this._sendRequest("chart_create_session",[this._sessionId])),this._symbolId=ce(),this._sendRequest("resolve_symbol",[this._sessionId,this._symbolId,this._symbolStringForResolve]),this._deferredResolveSymbolPromise.promise)}async getBars(e,t){return await this.resolveSymbol(),this._isSeriesCreated?(this._sendRequest("request_more_data",[this._sessionId,this._seriesId,t.countBack]),this._deferredGetBarsPromise.promise):(this._resolution=e,this._isSeriesCreated=!0,this._seriesId=re(),this._sendRequest("create_series",[this._sessionId,this._seriesId,"t",this._symbolId,this._resolution,t.countBack,V(t)]),this._deferredGetBarsPromise.promise)}subscribeBars(e,t){this._realtimeSubscriberCallbacks[t]=e}unsubscribeBars(e){delete this._realtimeSubscriberCallbacks[e],0===Object.keys(this._realtimeSubscriberCallbacks).length&&(K.logInfo("Deleting session because there are no realtime subscribers"),this._isSessionCreated=!1,this._isSeriesCreated=!1,this._symbolInfo=void 0,this._sendRequest("chart_delete_session",[this._sessionId]))}_sendRequest(e,t){const s=JSON.stringify({m:e,p:t});K.logDebug(`Send message ${s}`),this._wsBackendConnection.send(s)}async _onWsBackendMessage(e){if("string"!=typeof e)return;const t=this._dataHandleModule.unpack(e);if(function(e){return Z(e)||J(e)||z(e)||ee(e)||te(e)||se(e)||oe(e)}(t)&&function(e){return Z(e)?e.params[1]:e.params[0]}(t)===this._sessionId)if(K.logDebug(`Receive message ${e}`),ee(t))this._deferredResolveSymbolPromise.reject(t.params[2]);else{if(te(t)){const e=function(e){const t={...e,base_name:e.base_name?[e.base_name]:void 0,timezone:e.timezone,format:e.format||"price",supported_resolutions:e.supported_resolutions||Q,data_status:void 0,subsessions:e.subsessions,ticker:e.full_name,has_daily:!0,daily_multipliers:["1"],has_weekly_and_monthly:!0,weekly_multipliers:["1"],monthly_multipliers:["1","12"]};switch(e.delay){case void 0:case 0:t.data_status="streaming";break;case-1:t.data_status="endofday";break;default:t.data_status="delayed_streaming"}return t}(t.params[2]);await this._tryInjectLogosFromQuoteData(this._partialSymbolInfoForResolve.ticker,e),this._symbolInfo=e,this._symbolInfoHashes.add(Y(this._symbolInfo)),this._symbolInfoHashes.add(Y({...this._symbolInfo,ticker:t.params[2].pro_name})),this._symbolInfoHashes.add(Y({...this._symbolInfo,ticker:this._partialSymbolInfoForResolve.ticker}));const s=void 0===this._symbolInfo.original_currency_code,o=void 0===this._symbolInfo.original_unit_id;return s&&(this._symbolInfoHashes.add(Y({...this._symbolInfo,currency_code:void 0})),this._symbolInfoHashes.add(Y({...this._symbolInfo,ticker:t.params[2].pro_name,currency_code:void 0})),this._symbolInfoHashes.add(Y({...this._symbolInfo,ticker:this._partialSymbolInfoForResolve.ticker,
currency_code:void 0}))),o&&(this._symbolInfoHashes.add(Y({...this._symbolInfo,unit_id:void 0})),this._symbolInfoHashes.add(Y({...this._symbolInfo,ticker:t.params[2].pro_name,unit_id:void 0})),this._symbolInfoHashes.add(Y({...this._symbolInfo,ticker:this._partialSymbolInfoForResolve.ticker,unit_id:void 0}))),s&&o&&(this._symbolInfoHashes.add(Y({...this._symbolInfo,unit_id:void 0,currency_code:void 0})),this._symbolInfoHashes.add(Y({...this._symbolInfo,ticker:t.params[2].pro_name,unit_id:void 0,currency_code:void 0})),this._symbolInfoHashes.add(Y({...this._symbolInfo,ticker:this._partialSymbolInfoForResolve.ticker,unit_id:void 0,currency_code:void 0}))),K.logInfo(`Resolved ${this._symbolInfo.ticker} hashes ${[...this._symbolInfoHashes.values()].join(", ")}`),void this._deferredResolveSymbolPromise.resolve(e)}if(Z(t))this._deferredGetBarsPromise.reject(t.params[4]);else{if(z(t))return this._isSeriesLoading=!0,void this._clearGetBarsResult();if(oe(t)||se(t))if(this._isSeriesLoading)this._getBarsResult.bars=ne(this._seriesId,t).concat(this._getBarsResult.bars);else{const e=ne(this._seriesId,t)[0];for(const t of Object.keys(this._realtimeSubscriberCallbacks))this._realtimeSubscriberCallbacks[t](e)}else{if(J(t)){this._isSeriesLoading=!1;const e=t.params[4],s=void 0!==e&&void 0!==e.data_completed;return 0===this._getBarsResult.bars.length&&s&&(this._getBarsResult.meta.noData=!0),this._deferredGetBarsPromise.resolve(this._getBarsResult),void(this._deferredGetBarsPromise=W())}K.logError(`Unhandled message: ${t.method}, ${JSON.stringify(t.params)}`)}}}}_clearGetBarsResult(){this._getBarsResult.bars=[],this._getBarsResult.meta={}}async _tryInjectLogosFromQuoteData(e,t){try{const s=e,o=function(e,t){const s=t.filter((t=>"ok"===t.s&&t.n===e)).map((e=>e.v));return s.length<1?null:s[0]}(s,await this._quotesProvider.getQuoteData(s));if(!o)throw new Error;const n=function(e){const t={};return e["base-currency-logoid"]&&!e["base-currency-logoid"].startsWith(U)&&(t["base-currency-logoid"]=H.getSymbolLogoUrl(e["base-currency-logoid"],D.Medium)),e["currency-logoid"]&&!e["currency-logoid"].startsWith(U)&&(t["currency-logoid"]=H.getSymbolLogoUrl(e["currency-logoid"],D.Medium)),e.logoid&&!e.logoid.startsWith(U)&&(t.logoid=H.getSymbolLogoUrl(e.logoid,D.Medium)),e.provider_id&&!e.provider_id.startsWith(U)&&(t.provider_id=H.getProviderLogoUrl(e.provider_id,D.Medium)),e.country_code&&!e.country_code.startsWith(U)&&(t.country=H.getCountryFlagUrl(e.country_code,D.Medium)),t}(o);n.logoid&&(t.logo_urls=[n.logoid]),n["base-currency-logoid"]&&n["currency-logoid"]&&(t.logo_urls=[n["base-currency-logoid"],n["currency-logoid"]]),t.exchange_logo=n.country||n.provider_id}catch(t){const s=t instanceof Error?t.message:"(no error message)";K.logError(`Unable to get quote data for ${e} while resolving symbol info: ${s}`)}}}const le=B("LibraryTVDatafeed.HistoryResolveDataPulseProvider");function he(e){if(void 0===e.ticker)throw new Error("ticker is undefined in symbol information");return e}class de{constructor(e,t,s){this._sessions=[],
this._wsBackendConnection=e,this._quotesProvider=t,this._exchangeAllowDeny=s}async resolveSymbol(e,t){const s={ticker:e,currency_code:null==t?void 0:t.currencyCode,unit_id:null==t?void 0:t.unitId,subsession_id:(null==t?void 0:t.session)||"regular"},o=this._ensureSessionForSymbol(s),n=await o.resolveSymbol();if(!this._exchangeAllowDeny.isExchangeAllowed(n.listed_exchange))throw new Error("unknown_symbol");return n}async getBars(e,t,s){const o=this._ensureSessionForSymbol(he(e),t);return await o.getBars(t,s)}subscribeBars(e,t,s,o){this._ensureSessionForSymbol(he(e),t).subscribeBars(s,o)}unsubscribeBars(e){const t=this._findSymbolSeriesSessionBySubscriber(e);void 0!==t&&t.unsubscribeBars(e)}_ensureSessionForSymbol(e,t){let s=this._sessions.find((s=>s.hasSymbol(e,t)));return void 0===s&&(le.logInfo(`Creating session for ${e.ticker} ${t||"(no resolution)"}`),s=new ae(this._wsBackendConnection,this._quotesProvider,e),this._sessions.push(s)),s}_findSymbolSeriesSessionBySubscriber(e){return this._sessions.find((t=>t.hasSubscriber(e)))}}const _e=B("LibraryTVDatafeed.QuotesProvider",{highRate:!0}),ue=["ch","chp","short_name","exchange","original_name","description","lp","ask","bid","open_price","high_price","low_price","prev_close_price","volume","spread","logoid","base-currency-logoid","currency-logoid","country","country_code","provider_id","sector","listed_exchange","industry"],ge=["dividend_amount_recent","dividend_ex_date_recent","dividend_payout_ratio_ttm","earnings_release_date_fq_h","earnings_per_share_forecast_fq_h","earnings_per_share_fq_h","earnings_fiscal_period_fq_h"];class me{constructor(e){this._isConnected=!1,this._sessionId="qs_"+d(),this._mostRecentQuoteDataBySymbol=new Map,this._dataHandleModule=new g,this._listenerGuidsBySymbol=new Map,this._callbackByListenerGuid=new Map,this._completedQuotes=new Set,this._quoteCompletionPromises=new Map,this._quoteCompletionPromiseRevolvers=new Map,this._currentSymbols=new Set,this._wsBackendConnection=e,this._bindSocketEvents()}async getQuotes(e,t,s){try{const s=await this._getQuoteData(e);_e.logDebug(`getQuotes ${JSON.stringify(e)} ${JSON.stringify(s)}`),t(s)}catch(e){s(e instanceof Error?e.message:"Unknown error")}}subscribeQuotes(e,t,s,o){const n=e.concat(t),i=[];for(const e of n){const t=this._listenerGuidsBySymbol.get(e);void 0===t?(i.push(e),this._listenerGuidsBySymbol.set(e,new Set([o]))):t.add(o)}this._callbackByListenerGuid.set(o,s),this._addSymbols(i),this._sendRequest("quote_fast_symbols",[this._sessionId,...t])}unsubscribeQuotes(e){const t=[];for(const[s,o]of this._listenerGuidsBySymbol)o.has(e)&&(t.push(s),o.delete(e));this._callbackByListenerGuid.delete(e),t.forEach((e=>this._currentSymbols.delete(e))),this._sendRequest("quote_remove_symbols",[this._sessionId,...t])}async getQuoteData(e){return this._getQuoteData([e])}async _getQuoteData(e){const t=[],s=e.filter((e=>!this._currentSymbols.has(e)));this._addSymbols(s);const o=e.map((e=>this._quoteCompletionPromises.get(e))).filter(Boolean),n=new Promise((e=>setTimeout(e,5e3)))
;await Promise.race([n,Promise.all(o)]);for(const s of e){const e=this._mostRecentQuoteDataBySymbol.get(s);void 0!==e&&t.push({s:"ok",v:e,n:s})}return t}_addSymbols(e){const t=new Set;for(let s=0;s<e.length;s++)t.has(e[s])||this._currentSymbols.has(e[s])||t.add(e[s]);t.forEach((e=>{this._quoteCompletionPromises.set(e,new Promise((t=>{this._quoteCompletionPromiseRevolvers.set(e,t)}))),this._currentSymbols.add(e)})),this._sendRequest("quote_add_symbols",[this._sessionId,...t])}_bindSocketEvents(){this._wsBackendConnection.on("connect",(()=>{this._onConnect()})),this._wsBackendConnection.on("message",(e=>{this._onMessage(e)})),this._wsBackendConnection.on("disconnect",(()=>{_e.logError("disconnect")}))}_onMessage(e){var t,s;const o=this._unpack(e);if("protocol_switched"!==o.method){if("protocol_error"===o.method)return _e.logError(e),void this._wsBackendConnection.disconnect();if("critical_error"===o.method)return _e.logError(e),void this._wsBackendConnection.disconnect();var n;if("qsd"===o.method||"quote_completed"===o.method)switch(_e.logDebug(`Receive message ${e}`),o.method){case"qsd":{const[,e]=o.params;if("error"===e.s){_e.logError(e.errmsg||"qsd error");break}const i=e.n,r=null!==(t=this._listenerGuidsBySymbol.get(i))&&void 0!==t?t:[],c={...this._mostRecentQuoteDataBySymbol.get(i)||{},...e.v};c.listed_exchange&&(c.exchange=c.listed_exchange),this._mostRecentQuoteDataBySymbol.set(i,c),e.v=(n=c,{...n,logoid:void 0,provider_id:void 0,"base-currency-logoid":void 0,"currency-logoid":void 0});for(const t of r)null===(s=this._callbackByListenerGuid.get(t))||void 0===s||s([e]);break}case"quote_completed":{const[,e]=o.params;this._completedQuotes.add(e);const t=this._quoteCompletionPromiseRevolvers.get(e);t&&t();break}}}}_unpack(e){return this._dataHandleModule.unpack(e)}_onConnect(){this._isConnected?_e.logWarn("_onConnected called again"):(this._isConnected=!0,this._sendRequest("quote_create_session",[this._sessionId]),this._sendRequest("quote_set_fields",[this._sessionId,...ue,...ge]))}_sendRequest(e,t){const s=JSON.stringify({m:e,p:t});_e.logDebug(`Send message ${s}`),this._wsBackendConnection.send(s)}}const be=B("Fetch");function fe(e,t,s={}){{const{logOnErrorStatus:o=!0,logBodyOnError:n=!1}=s;t=t||{},function(e){return new URL(e,document.baseURI).origin===location.origin}(e)&&(t.headers?t.headers instanceof Headers||(t.headers=new Headers(t.headers)):t.headers=new Headers,window.locale&&t.headers.set("X-Language",window.locale),t.headers.set("X-Requested-With","XMLHttpRequest")),void 0===t.credentials&&(t.credentials="same-origin");const i=window.fetch(e,t);return i.then((s=>{if(!s.ok&&o){let o="";t.method&&(o+=`${t.method.toUpperCase()} `),o+=e,o+=`. Status ${s.status}`,s.statusText&&(o+=`. ${s.statusText}`),s.headers.via&&(o+=`. Via: ${s.headers.via}`),n&&"string"==typeof t.body&&(o+=`. Body: ${t.body.slice(0,1024)}`),be.logError(o)}return s}),(s=>{if(s&&"AbortError"===s.name)return;let o="";t.method&&(o+=`${t.method.toUpperCase()} `),o+=e,navigator.onLine?o+=`. ${s}`:o+=". User is offline.",be.logError(o)})),i}}
class ye{constructor(e){this._quoteDataProvider=e}async getTimescaleMarks(e,t,s,o){const n=[],i=e.name,r=await this._getQuoteValues(i);return r?(this._populateEarningsMarkers(r,n,i,t,s),this._populateDividendsMarkers(r,n,i,t,s),n):n}async getMarks(e,t,s,o){return[]}async _getQuoteValues(e){const t=(await this._quoteDataProvider(e)).find((t=>t.n===e));return t&&"ok"===t.s?t.v:null}_populateEarningsMarkers(e,t,s,o,n){var i;if(i=e,Boolean(i.earnings_release_date_fq_h&&i.earnings_per_share_forecast_fq_h&&i.earnings_fiscal_period_fq_h&&i.earnings_per_share_fq_h))for(let i=0;i<e.earnings_release_date_fq_h.length;i++){const r=e.earnings_release_date_fq_h[i];if(r>n||r<o)continue;const c=e.earnings_fiscal_period_fq_h[i],a=e.earnings_per_share_forecast_fq_h[i],l=e.earnings_per_share_fq_h[i],h=l>=a;t.push({id:`${s}-E-${c}`,time:r,color:h?"green":"red",label:"E",shape:h?"earningUp":"earningDown",tooltip:[`Earnings \t${c}`,`Forecast: \t${a}`,`Actual: \t${l}`]})}}_populateDividendsMarkers(e,t,s,o,n){if(i=e,!Boolean(i.dividend_ex_date_recent&&i.dividend_amount_recent))return;var i;const r=e.dividend_ex_date_recent;if(r>n||r<o)return;const c=e.dividend_amount_recent,a=e.dividend_payout_ratio_ttm,l=["Dividends",`Ex Date: \t${new Date(1e3*r).toDateString()}`,`Amount: \t${c.toFixed(2)}`];a&&l.push(`Payout Ratio (TTM): ${a.toFixed()}%`),t.push({id:`${s}-D-${r}`,time:r,color:"blue",label:"D",shape:"circle",tooltip:l})}}
const pe=JSON.parse('["ACTIVTRADES","ADX","AFTERPRIME","AMEX","ASX","ASX24","ATHEX","BASESWAP","BCS","BER","BET","BINANCE","BINANCEUS","BINGX","BIST","BISWAP","BITAZZA","BITBNS","BITFINEX","BITFLYER","BITGET","BITHUMB","BITKUB","BITMART","BITMEX","BITRUE","BITSTAMP","BITTREX","BLACKBULL","BLOFIN","BME","BMFBOVESPA","BNC","BSE","BTSE","BVB","BVC","BX","BYBIT","CAMELOT","CAMELOT3ARBITRUM","CAPITALCOM","CAPITALCOMSB","CBOE","CBOEEU","CBOT","CBOT_MINI","CFFEX","CFI","CHIXAU","CITYINDEX","CITYINDEXSB","CME","CME_MINI","COINBASE","COINBASE2","COINEX","COMEX","COMEX_MINI","COT","COT2","COT3","CRYPTO","CRYPTOCAP","CRYPTOCAP_OLD","CRYPTOCOM","CRYPTOINDEX","CSE","CSECY","CSELK","CSEMA","CURVE","DEFILLAMA","DELTA","DERIBIT","DUS","DYDX","EASYMARKETS","ECONOMICS","EGX","EIGHTCAP","ERRANTE","EUREX","FINRA","FOREXCOM","FPMARKETS","FRED","FTX","FUSIONMARKETS","FWB","FX","FXOPEN","FX_IDC","GATEIO","GBEBROKERS","GEMINI","GETTEX","GPW","HAM","HAN","HITBTC","HNX","HONEYSWAP","HSI","HTX","IBKR","ICEEUR","ICMARKETS","IDX","IG","INDEX","JFX","JSE","KATANA","KRAKEN","KSE","KUCOIN","LUNARCRUSH","MARKETSCOM","MATBAROFEX","MERCADO","MEXC","MGEX","MIL","MILSEDEX","MMFINANCE","MSEI","MTGOX","MUN","NASDAQ","NCDEX","NEO","NEWCONNECT","NGM","NSENG","NYMEX","NYMEX_MINI","NYSE","OANDA","OKCOIN","OKX","OMXBALTIC","OMXCOP","OMXHEX","OMXICE","OMXNORDIC","OMXRSE","OMXSTO","OMXTSE","OMXVSE","ORCA","ORCA_NEW","OSE","OSMOSIS","OTC","PANCAKESWAP","PANCAKESWAP3BSC","PANCAKESWAP3ETH","PANGOLIN","PEPPERSTONE","PEPPERSTONESB","PHEMEX","PHILLIPNOVA","PIONEX","POLONIEX","PSECZ","PULSEX","PYTH","QSE","QUICKSWAP","QUICKSWAP3POLYGON","QUICKSWAP3POLYGONZKEVM","RAYDIUM","RAYDIUM_NEW","RUS","SAXO","SIX","SKILLING","SPARKS","SPOOKYSWAP","SPREADEX","SPREADEXSB","SSE","SUSHISWAP","SUSHISWAPPOLYGON","SWB","SZSE","TASE","TASTYFX","THINKMARKETS","THRUSTER3","TIMEX","TOCOM","TOKENIZE","TPEX","TRADEGATE","TRADENATION","TRADENATIONSB","TRADERJOE","TRADU","TSX","TSXV","TURQUOISE","TVC","UNISWAP","UNISWAP3ARBITRUM","UNISWAP3AVALANCHE","UNISWAP3BASE","UNISWAP3BSC","UNISWAP3ETH","UNISWAP3OPTIMISM","UNISWAP3POLYGON","UPBIT","UPCOM","USI","VANTAGE","VELOCITY","VELODROME","VIE","VOLMEX","VVSFINANCE","WHITEBIT","WHSELFINVEST","WOONETWORK","XETR","XEXCHANGE","ZCE","ZOOMEX"]'),Se=new Set(pe);class Ce{constructor(e){this._exchangeAllowDeny=new Map(Object.entries(null!=e?e:{}))}isExchangeAllowed(e){const t=this._exchangeAllowDeny.has("*")&&!1===this._exchangeAllowDeny.get("*"),s=this._exchangeAllowDeny.has(e)&&!1===this._exchangeAllowDeny.get(e),o=this._exchangeAllowDeny.has(e)&&!0===this._exchangeAllowDeny.get(e),n=Se.has(e);return!s&&(o||n&&!t)}}const Ie=B("LibraryTVDatafeed.TradingViewDatafeed");function Ee(e){try{return new URL(e).hostname}catch(t){return e.replace(we,"").split(":")[0]}}function ve(){if(document.location.ancestorOrigins&&document.location.ancestorOrigins.length)return document.location.ancestorOrigins[document.location.ancestorOrigins.length-1];try{return new URL(document.referrer).origin}catch(e){return document.location.origin}}const we=new RegExp("^http(s)?://")
;class ke extends class{constructor(e,t,s,o,n,i,r,c){var a;this._isConnected=!1,this._searchResultExchangePredicate=e=>this._exchangeAllowDeny.isExchangeAllowed(e.exchange)||void 0!==e.prefix&&this._exchangeAllowDeny.isExchangeAllowed(e.prefix),this._wsBackendConnection=e,this._historyProvider=t,this._resolveProvider=s,this._dataPulseProvider=o,this._quotesProvider=n,this._marksProvider=i,this._options=c,this._token=(a=null==c?void 0:c.token)?`widget_user_token-${a}£-!${Ee(ve())}`:void 0,this._exchangeAllowDeny=r,this._bindSocketEvents()}onReady(e){this._onReadyCallback=e,this._isConnected&&setTimeout((()=>{this._callOnReadyCallback()}),0),this._wsBackendConnection.isConnected()||this._wsBackendConnection.isConnecting()||(this._wsBackendConnection.onReconnect(this._bindSocketEvents.bind(this)),this._wsBackendConnection.connect())}async searchSymbols(e,t,s,o){const n=new URL("https://symbol-search.tradingview.com/local_search/");n.searchParams.set("text",e),n.searchParams.set("exchange",t),n.searchParams.set("type",s),n.searchParams.set("tradable","1");try{const e=await fe(n.toString());if(!e.ok)throw new Error(`${e.status}: ${e.statusText}`);o((await e.json()).filter(this._searchResultExchangePredicate).map((e=>{var t;const s=x(e),o=`${e.prefix||e.exchange}:${e.symbol}`;return{...s,...e,ticker:null!==(t=e.ticker)&&void 0!==t?t:o}})))}catch(e){"string"==typeof e&&Ie.logError(e),e instanceof Error&&Ie.logError(e.message),o([])}}resolveSymbol(e,t,s,o){this._resolveProvider.resolveSymbol(e,o).then((e=>t(e))).catch((e=>{e instanceof Error?s(e.message):s("string"!=typeof e?"An unknown error has occurred while trying to resolve the symbol.":e)}))}getBars(e,t,s,o,n){this._historyProvider.getBars(e,t,s).then((e=>o(e.bars,e.meta))).catch((e=>{e instanceof Error?n(`An error has occurred within the datafeed. Error reported: ${e.message}`):n("An unknown error has occurred with the datafeed.")}))}subscribeBars(e,t,s,o,n){this._dataPulseProvider.subscribeBars(e,t,s,o)}unsubscribeBars(e){this._dataPulseProvider.unsubscribeBars(e)}getQuotes(e,t,s){this._quotesProvider.getQuotes(e,t,s)}subscribeQuotes(e,t,s,o){this._quotesProvider.subscribeQuotes(e,t,s,o)}unsubscribeQuotes(e){this._quotesProvider.unsubscribeQuotes(e)}async getTimescaleMarks(e,t,s,o,n){o(await this._marksProvider.getTimescaleMarks(e,t,s,n))}_bindSocketEvents(){this._wsBackendConnection.on("connect",(()=>{this._onConnect()})),this._wsBackendConnection.on("disconnect",(()=>{Ie.logError("disconnect")}))}_onConnect(){this._isConnected?Ie.logError("_onConnected called again"):(this._wsBackendConnection.send(JSON.stringify({m:"set_auth_token",p:[this._token||"widget_user_token"]})),this._isConnected=!0,this._onReadyCallback&&this._callOnReadyCallback())}_callOnReadyCallback(){var e,t;this._onReadyCallback&&this._onReadyCallback((t={supports_timescale_marks:!1!==(null===(e=this._options)||void 0===e?void 0:e.displayTimescaleMarks)},{...j,...t}))}}{constructor(e){var t;window.WEBSOCKET_PARAMS_ANALYTICS={ws_page_uri:window.location.href.replace(we,"")};const s=Ee(ve())
;s&&(window.WEBSOCKET_PARAMS_ANALYTICS.ws_ancestor_origin=s);const o=new Ce(null==e?void 0:e.exchangeAllowDeny),n=new l(null!==(t=null==e?void 0:e.websocketUrl)&&void 0!==t?t:"widgetdata.tradingview.com"),i=new me(n),r=new de(n,i,o),c=new ye((e=>i.getQuoteData(e)));super(n,r,r,r,i,c,o,e)}}})(),o})()));
\ No newline at end of file
"use strict";
!function() {
if (window.TradingView && window.TradingView.host && !window.TradingView.reoloadTvjs)
return;
var e = {
"color-cold-gray-300": "#B2B5BE",
"color-brand": "#2962FF",
"color-brand-hover": "#1E53E5",
"color-brand-active": "#1848CC"
};
const t = new RegExp("^http(s)?:(//)?");
var o, i, r, n, a, s, d, l = "-apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif", c = {
host: null == window.location.host.match(/tradingview\.com|pyrrosinvestment\.com/i) ? "https://s.tradingview.com" : "https://www.tradingview.com",
ideasHost: "https://www.tradingview.com",
chatHost: "https://www.tradingview.com",
widgetHost: "https://www.tradingview-widget.com",
getHost: function(e) {
return e.useWidgetHost ? c.widgetHost : c.host
},
embedStylesForCopyright: function() {
var t = document.createElement("style");
return t.innerHTML = ".tradingview-widget-copyright {font-size: 13px !important; line-height: 32px !important; text-align: center !important; vertical-align: middle !important; font-family: " + l + " !important; color: " + e["color-cold-gray-300"] + " !important;} .tradingview-widget-copyright .blue-text {color: " + e["color-brand"] + " !important;} .tradingview-widget-copyright a {text-decoration: none !important; color: " + e["color-cold-gray-300"] + " !important;} .tradingview-widget-copyright a:visited {color: " + e["color-cold-gray-300"] + " !important;} .tradingview-widget-copyright a:hover .blue-text {color: " + e["color-brand-hover"] + " !important;} .tradingview-widget-copyright a:active .blue-text {color: " + e["color-brand-active"] + " !important;} .tradingview-widget-copyright a:visited .blue-text {color: " + e["color-brand"] + " !important;}",
t
},
embedStylesForFullHeight: function(e, t, o) {
var i = t ? "calc(" + e + " - 32px)" : e
, r = document.querySelector("#" + o);
r.parentElement.style.height = i,
r.style.height = "100%"
},
gId: function() {
return "tradingview_" + (1048576 * (1 + Math.random()) | 0).toString(16).substring(1)
},
isPersentHeight: function(e) {
return "%" === e
},
getSuffix: function(e) {
var t = e.toString().match(/(%|px|em|ex)/);
return t ? t[0] : "px"
},
hasCopyright: function(e) {
var t = document.getElementById(e)
, o = t && t.parentElement;
return !!o && !!o.querySelector(".tradingview-widget-copyright")
},
calculateWidgetHeight: function(e, t) {
var o = parseInt(e)
, i = this.getSuffix(e)
, r = this.isPersentHeight(i)
, n = t && this.hasCopyright(t);
return r && t && (this.embedStylesForFullHeight(o + i, n, t),
n) ? 100 + i : n ? "calc(" + o + i + " - 32px)" : o + i
},
onready: function(e) {
window.addEventListener ? window.addEventListener("DOMContentLoaded", e, !1) : window.attachEvent("onload", e)
},
bindEvent: function(e, t, o) {
e.addEventListener ? e.addEventListener(t, o, !1) : e.attachEvent && e.attachEvent("on" + t, o)
},
unbindEvent: function(e, t, o) {
e.removeEventListener ? e.removeEventListener(t, o, !1) : e.detachEvent && e.detachEvent("on" + t, o)
},
cloneSimpleObject: function(e) {
if (null == e || "object" != typeof e)
return e;
var t = e.constructor();
for (var o in e)
e.hasOwnProperty(o) && (t[o] = e[o]);
return t
},
isArray: function(e) {
return "[object Array]" === Object.prototype.toString.call(e)
},
generateUtmForUrlParams: function(e) {
var t = {
utm_source: window.location.hostname,
utm_medium: c.hasCopyright(e.container) ? "widget_new" : "widget"
};
return e.type && (t.utm_campaign = e.type,
"chart" === e.type && (t.utm_term = e.symbol)),
t
},
getPageUriString: function() {
const e = location.href
, o = this.invalidUrl(e);
return o || e.replace(t, "")
},
invalidUrl: function(e) {
try {
const o = new URL(e);
return t.test(o.protocol) ? null : "__NHTTP__"
} catch (e) {
return "__FAIL__"
}
},
getWidgetTitleAttribute: function(e, t) {
return e || `${t.replace("-", " ")} TradingView widget`
},
WidgetAbstract: function() {},
MediumWidget: function(e) {
this.id = c.gId();
const t = c.calculateWidgetHeight(e.height || 400, e.container_id);
let o;
switch (e.chartType) {
case "candlesticks":
{
const {chartType: t, upColor: i, downColor: r, borderUpColor: n, borderDownColor: a, wickUpColor: s, wickDownColor: d} = e;
o = {
chartType: t,
upColor: i,
downColor: r,
borderUpColor: n,
borderDownColor: a,
wickUpColor: s,
wickDownColor: d
};
break
}
case "bars":
{
const {chartType: t, upColor: i, downColor: r} = e;
o = {
chartType: t,
upColor: i,
downColor: r
};
break
}
case "line":
{
const {chartType: t, color: i, colorGrowing: r, colorFalling: n, lineWidth: a} = e;
o = {
chartType: t,
color: i,
colorGrowing: r,
colorFalling: n,
lineWidth: a
};
break
}
default:
{
const {chartType: t="area", lineColor: i=e.trendLineColor || "", lineColorGrowing: r, lineColorFalling: n, topColor: a=e.underLineColor || "", bottomColor: s=e.underLineBottomColor || "", lineWidth: d} = e;
o = {
chartType: t,
lineColor: i,
lineColorGrowing: r,
lineColorFalling: n,
topColor: a,
bottomColor: s,
lineWidth: d
};
break
}
}
this.options = {
container: e.container_id || "",
width: c.WidgetAbstract.prototype.fixSize(e.width) || "",
height: c.WidgetAbstract.prototype.fixSize(t) || "",
symbols: e.symbols,
greyText: e.greyText || "",
symbols_description: e.symbols_description || "",
large_chart_url: e.large_chart_url || "",
customer: e.customer || "",
backgroundColor: e.backgroundColor || "",
gridLineColor: e.gridLineColor || "",
fontColor: e.fontColor || "",
fontSize: e.fontSize || "",
widgetFontColor: e.widgetFontColor || "",
timeAxisBackgroundColor: e.timeAxisBackgroundColor || "",
chartOnly: !!e.chartOnly,
locale: e.locale,
colorTheme: e.colorTheme,
isTransparent: e.isTransparent,
useWidgetHost: Boolean(e.useWidgetHost),
showFloatingTooltip: e.showFloatingTooltip,
valuesTracking: e.valuesTracking,
changeMode: e.changeMode,
dateFormat: e.dateFormat,
timeHoursFormat: e.timeHoursFormat,
showVolume: e.showVolume,
showMA: e.showMA,
volumeUpColor: e.volumeUpColor,
volumeDownColor: e.volumeDownColor,
maLineColor: e.maLineColor,
maLineWidth: e.maLineWidth,
maLength: e.maLength,
hideDateRanges: e.hideDateRanges,
hideMarketStatus: e.hideMarketStatus,
hideSymbolLogo: e.hideSymbolLogo,
scalePosition: e.scalePosition,
scaleMode: e.scaleMode,
fontFamily: e.fontFamily,
noTimeScale: e.noTimeScale,
...o
},
this.create()
},
widget: function(e) {
this.id = e.id || c.gId();
var t = c.getUrlParams()
, o = e.tvwidgetsymbol || t.tvwidgetsymbol || t.symbol || e.symbol || "NASDAQ:AAPL"
, i = e.logo || "";
i.src && (i = i.src),
i && i.replace(".png", "");
var r = c.calculateWidgetHeight(e.height || 500, e.container_id);
this.options = {
width: e.width || 800,
height: r,
symbol: o,
interval: e.interval || "1",
range: e.range || "",
timezone: e.timezone || "",
autosize: e.autosize,
hide_top_toolbar: e.hide_top_toolbar,
hide_side_toolbar: e.hide_side_toolbar,
hide_legend: e.hide_legend,
hide_volume: e.hide_volume,
allow_symbol_change: e.allow_symbol_change,
save_image: void 0 === e.save_image || e.save_image,
container: e.container_id || "",
watchlist: e.watchlist || [],
compareSymbols: e.compareSymbols || [],
editablewatchlist: !!e.editablewatchlist,
studies: e.studies || [],
theme: e.theme || "",
style: e.style || "",
extended_hours: void 0 === e.extended_hours ? void 0 : +e.extended_hours,
details: !!e.details,
calendar: !!e.calendar,
hotlist: !!e.hotlist,
hideideasbutton: !!e.hideideasbutton,
widgetbar_width: +e.widgetbar_width || void 0,
withdateranges: e.withdateranges || "",
customer: e.customer || i || "",
venue: e.venue,
symbology: e.symbology,
logo: i,
show_popup_button: !!e.show_popup_button,
popup_height: e.popup_height || "",
popup_width: e.popup_width || "",
studies_overrides: e.studies_overrides,
overrides: e.overrides,
enabled_features: e.enabled_features,
disabled_features: e.disabled_features,
publish_source: e.publish_source || "",
whotrades: e.whotrades || void 0,
locale: e.locale,
referral_id: e.referral_id,
no_referral_id: e.no_referral_id,
fundamental: e.fundamental,
percentage: e.percentage,
hidevolume: e.hidevolume,
padding: e.padding,
greyText: e.greyText || "",
horztouchdrag: e.horztouchdrag,
verttouchdrag: e.verttouchdrag,
useWidgetHost: Boolean(e.useWidgetHost),
backgroundColor: e.backgroundColor,
gridColor: e.gridColor,
doNotStoreSettings: e.doNotStoreSettings
},
e.cme && (this.options.customer = "cme"),
isFinite(e.widgetbar_width) && e.widgetbar_width > 0 && (this.options.widgetbar_width = e.widgetbar_width),
this._ready_handlers = [],
this.create()
},
chart: function(e) {
this.id = c.gId(),
this.options = {
width: e.width || 640,
height: e.height || 500,
container: e.container_id || "",
realtime: e.realtime,
chart: e.chart,
locale: e.locale,
type: "chart",
autosize: e.autosize,
mobileStatic: e.mobileStatic
},
this._ready_handlers = [],
this.create()
},
stream: function(e) {
console.warn("We're sorry, the Stream widget is discontinued")
},
EventsWidget: function(e) {
this.id = c.gId(),
this.options = {
container: e.container_id || "",
width: e.width || 486,
height: e.height || 670,
currency: e.currencyFilter || "",
importance: e.importanceFilter || "",
type: "economic-calendar"
},
this.create(e)
},
IdeasStreamWidget: function(e) {
console.warn("We're sorry, the Ideas Stream widget is discontinued")
},
IdeaWidget: function() {
console.warn("We're sorry, the Idea Preview widget is discontinued")
},
ChatWidgetEmbed: function(e) {
console.warn("We're sorry, the Chat widget is discontinued")
}
};
c.WidgetAbstract.prototype = {
widgetId: "unknown",
fixSize: function(e) {
return /^[0-9]+(\.|,[0-9])*$/.test(e) ? e + "px" : e
},
width: function() {
return this.options.autosize ? "100%" : c.WidgetAbstract.prototype.fixSize(this.options.width)
},
height: function() {
return this.options.autosize ? "100%" : c.WidgetAbstract.prototype.fixSize(this.options.height)
},
addWrapperFrame: function(e) {
const t = document.createElement("div");
return t.id = this.id + "-wrapper",
t.style.cssText = "position: relative;box-sizing: content-box;margin: 0 auto !important;padding: 0 !important;font-family: " + l + ";",
t.style.width = c.WidgetAbstract.prototype.width.call(this),
t.style.height = c.WidgetAbstract.prototype.height.call(this),
t.appendChild(e),
t
}
},
c.EventsWidget.prototype = {
widgetId: "events",
create: function() {
var e = this.render();
h(e, this.options)
},
render: function() {
var e = new URL(c.getHost(this.options));
e.pathname = "/eventswidgetembed/",
c.addUrlParams(e, {
currency: this.options.currency,
importance: this.options.importance
}),
this.options.type = "events",
c.addUrlParams(e, c.generateUtmForUrlParams(this.options));
const t = document.createElement("iframe");
return t.title = c.getWidgetTitleAttribute(this.options.iframeTitle, this.widgetId),
t.lang = this.options.iframeLang || "en",
t.width = this.options.width,
this.options.height && (t.height = this.options.height),
t.setAttribute("frameBorder", "0"),
t.setAttribute("scrolling", "no"),
t.src = e,
t
}
},
c.MediumWidget.prototype = {
widgetId: "symbol-overview",
create: function() {
const e = this.render();
h(e, this.options)
},
render: function() {
const e = Object.create(null);
for (const t of ["symbols", "width", "height", "colorTheme", "backgroundColor", "gridLineColor", "fontColor", "widgetFontColor", "underLineColor", "underLineBottomColor", "trendLineColor", "activeTickerBackgroundColor", "timeAxisBackgroundColor", "scalePosition", "scaleMode", "chartType", "color", "colorGrowing", "colorFalling", "lineColor", "lineColorGrowing", "lineColorFalling", "topColor", "bottomColor", "upColor", "downColor", "borderUpColor", "borderDownColor", "wickUpColor", "wickDownColor", "fontFamily", "fontSize", "noTimeScale", "valuesTracking", "changeMode", "dateFormat", "timeHoursFormat", "lineWidth", "volumeUpColor", "volumeDownColor", "chartOnly", "isTransparent", "showFloatingTooltip", "showVolume", "showMA", "maLineColor", "maLineWidth", "maLength", "hideDateRanges", "hideMarketStatus", "hideSymbolLogo"])
this.options[t] && (e[t] = this.options[t]);
e["page-uri"] = c.getPageUriString(),
this.options.type = "symbol-overview";
const t = c.generateUtmForUrlParams(this.options);
for (var o of Object.keys(t))
e[o] = t[o];
const i = new URL("/embed-widget/symbol-overview/",c.getHost(this.options));
this.options.customer && (i.pathname += this.options.customer + "/"),
this.options.locale && i.searchParams.append("locale", this.options.locale),
i.hash = encodeURIComponent(JSON.stringify(e));
const r = document.createElement("iframe");
return r.title = c.getWidgetTitleAttribute(this.options.iframeTitle, this.widgetId),
r.lang = this.options.iframeLang || "en",
r.id = this.id,
r.style.cssText = "margin: 0 !important;padding: 0 !important;",
this.options.width && (r.style.width = this.options.width),
this.options.height && (r.style.height = this.options.height),
r.setAttribute("frameBorder", "0"),
r.setAttribute("allowTransparency", "true"),
r.setAttribute("scrolling", "no"),
r.src = i.href,
r
},
remove: function() {
var e = document.getElementById("tradingview_widget");
e.parentNode.removeChild(e)
}
},
c.widget.prototype = {
widgetId: "advanced-chart",
create: function() {
this.options.type = this.options.fundamental ? "fundamental" : "chart",
this.iframe = this.render();
var e = this;
let t = this.iframe;
this.options.noLogoOverlay || (t = c.WidgetAbstract.prototype.addWrapperFrame.call(this, t)),
h(t, this.options);
var o = document.getElementById("tradingview-copyright");
o && o.parentElement && o.parentElement.removeChild(o),
this.postMessage = c.postMessageWrapper(this.iframe.contentWindow, this.id),
c.bindEvent(this.iframe, "load", (function() {
e.postMessage.get("widgetReady", {}, (function() {
var t;
for (e._ready = !0,
t = e._ready_handlers.length; t--; )
e._ready_handlers[t].call(e)
}
))
}
)),
e.postMessage.on("openChartInPopup", (function(t) {
for (var o = c.cloneSimpleObject(e.options), i = ["symbol", "interval"], r = i.length - 1; r >= 0; r--) {
var n = i[r]
, a = t[n];
a && (o[n] = a)
}
o.show_popup_button = !1;
var s = e.options.popup_width || 900
, d = e.options.popup_height || 600
, l = (screen.width - s) / 2
, h = (screen.height - d) / 2
, g = window.open(e.generateUrl(o), "_blank", "resizable=yes, top=" + h + ", left=" + l + ", width=" + s + ", height=" + d);
g && (g.opener = null)
}
))
},
ready: function(e) {
this._ready ? e.call(this) : this._ready_handlers.push(e)
},
render: function() {
const e = document.createElement("iframe");
return e.title = c.getWidgetTitleAttribute(this.options.iframeTitle, this.widgetId),
e.lang = this.options.iframeLang || "en",
e.id = this.id,
e.style.cssText = "width: 100%; height: 100%; margin: 0 !important; padding: 0 !important;",
e.setAttribute("frameBorder", "0"),
e.setAttribute("allowTransparency", "true"),
e.setAttribute("scrolling", "no"),
e.setAttribute("allowfullscreen", "true"),
e.src = this.generateUrl(),
e
},
generateUrl: function(e) {
var t;
function o(e, t, o) {
let i = g(t, o);
"object" == typeof i && (i = JSON.stringify(i)),
void 0 !== i && "" !== i && (a[e] = i)
}
function i(e, t, i) {
o(e, void 0 === t ? void 0 : t ? "1" : i)
}
t = "cme" === (e = e || this.options).customer ? "/cmewidgetembed/" : e.customer ? "/" + e.customer + "/widgetembed/" : "/widgetembed/";
var r = c.getHost(e);
const n = new URL(r + t);
n.searchParams.append("hideideas", "1"),
n.searchParams.append("overrides", JSON.stringify(g(e.overrides, {}))),
n.searchParams.append("enabled_features", JSON.stringify(g(e.enabled_features, []))),
n.searchParams.append("disabled_features", JSON.stringify(g(e.disabled_features, []))),
e.locale && n.searchParams.append("locale", e.locale);
const a = Object.create(null);
return a.symbol = e.symbol,
a.frameElementId = this.id,
a.interval = e.interval,
o("range", e.range),
i("hide_top_toolbar", e.hide_top_toolbar),
i("hide_legend", e.hide_legend),
i("hide_side_toolbar", e.hide_side_toolbar, "0"),
i("allow_symbol_change", e.allow_symbol_change, "0"),
i("save_image", e.save_image, "0"),
i("doNotStoreSettings", e.doNotStoreSettings),
o("backgroundColor", e.backgroundColor),
o("gridColor", e.gridColor),
e.watchlist && e.watchlist.length && e.watchlist.join && o("watchlist", e.watchlist.join("")),
e.compareSymbols && e.compareSymbols.length && o("compareSymbols", e.compareSymbols),
i("editablewatchlist", e.editablewatchlist),
i("details", e.details),
i("calendar", e.calendar),
i("hotlist", e.hotlist),
e.studies && c.isArray(e.studies) && ("string" == typeof e.studies[0] ? o("studies", e.studies.join("")) : o("studies", e.studies)),
i("horztouchdrag", e.horztouchdrag, "0"),
i("verttouchdrag", e.verttouchdrag, "0"),
o("widgetbar_width", e.widgetbar_width),
o("theme", e.theme),
o("style", e.style),
o("extended_hours", e.extended_hours),
o("timezone", e.timezone),
i("hideideasbutton", e.hideideasbutton),
i("withdateranges", e.withdateranges),
i("hide_volume", e.hide_volume),
o("padding", e.padding),
i("show_popup_button", e.show_popup_button),
o("padding", e.padding),
o("studies_overrides", e.studies_overrides, {}),
o("publish_source", e.publish_source),
o("venue", e.venue),
o("symbology", e.symbology),
o("whotrades", e.whotrades),
o("referral_id", e.referral_id),
i("no_referral_id", e.no_referral_id),
o("fundamental", e.fundamental),
o("percentage", e.percentage),
o("utm_source", window.location.hostname),
o("utm_medium", c.hasCopyright(e.container) ? "widget_new" : "widget"),
o("utm_campaign", e.type),
r !== c.host && o("supportHost", c.host),
e.type && "chart" === e.type && o("utm_term", e.symbol),
o("page-uri", c.getPageUriString()),
`${n}#${encodeURIComponent(JSON.stringify(a))}`
},
image: function(e) {
this.postMessage.get("imageURL", {}, (function(t) {
var o = c.host + "/x/" + t + "/";
e(o)
}
))
},
subscribeToQuote: function(e) {
var t = document.getElementById(this.id);
this.postMessage.post(t.contentWindow, "quoteSubscribe"),
this.postMessage.on("quoteUpdate", e)
},
getSymbolInfo: function(e) {
this.postMessage.get("symbolInfo", {}, e)
},
remove: function() {
var e = document.getElementById(this.id);
e.parentNode.removeChild(e)
},
reload: function() {
var e = document.getElementById(this.id);
e.parentNode.replaceChild(this.render(), e)
}
},
c.chart.prototype = {
widgetId: "published-chart",
create: function() {
const e = this.render()
, t = c.WidgetAbstract.prototype.addWrapperFrame.call(this, e);
var o, i = this;
h(t, this.options),
o = document.getElementById(this.id),
c.bindEvent(o, "load", (function() {
var e;
for (i._ready = !0,
e = i._ready_handlers.length; e--; )
i._ready_handlers[e].call(i)
}
)),
c.onready((function() {
var e = !1;
if (document.querySelector && document.querySelector('a[href$="/v/' + i.options.chart + '/"]') && (e = !0),
!e)
for (var t = document.getElementsByTagName("a"), r = new RegExp("/v/" + i.options.chart + "/$"), n = new RegExp("/chart/([0-9a-zA-Z:+*-/()]+)/" + i.options.chart), a = 0; a < t.length; a++)
if (r.test(t[a].href) || n.test(t[a].href)) {
e = !0;
break
}
e && (o.src += "#nolinks",
o.name = "nolinks")
}
))
},
ready: c.widget.prototype.ready,
render: function() {
var e = new URL(`${c.host}/embed/${this.options.chart}`);
c.addUrlParams(e, {
method: "script",
locale: this.options.locale
}, !0),
this.options.type = "chart",
c.addUrlParams(e, c.generateUtmForUrlParams(this.options));
const t = document.createElement("iframe");
return t.title = c.getWidgetTitleAttribute(this.options.iframeTitle, this.widgetId),
t.lang = this.options.iframeLang || "en",
t.id = this.id,
t.style.cssText = "width: 100%; height: 100%; margin: 0 !important; padding: 0 !important;",
t.setAttribute("frameBorder", "0"),
t.setAttribute("allowTransparency", "true"),
t.setAttribute("scrolling", "no"),
t.setAttribute("allowfullscreen", "true"),
t.src = e.href,
t
},
toggleFullscreen: function(e) {
var t = document.getElementById(this.id);
document.fullscreenElement === t ? document.exitFullscreen() : t.requestFullscreen()
},
getSymbolInfo: function(e) {
this.postMessage.get("symbolInfo", {}, e)
}
},
c.postMessageWrapper = (i = {},
r = {},
n = {},
a = 0,
s = 0,
d = "TradingView",
window.addEventListener && window.addEventListener("message", (function(e) {
var t;
try {
t = JSON.parse(e.data)
} catch (e) {
return
}
if (t && t.provider && t.provider === d)
if (t.source = e.source,
"get" === t.type) {
if (!r[t.name])
return;
r[t.name].forEach((function(e) {
"function" == typeof e && e.call(t, t.data, (function(e) {
var i = {
id: t.id,
type: "on",
name: t.name,
client_id: t.client_id,
data: e,
provider: d
};
o.postMessage(JSON.stringify(i), "*")
}
))
}
))
} else if ("on" === t.type)
i[t.client_id] && i[t.client_id][t.id] && (i[t.client_id][t.id].call(t, t.data),
delete i[t.client_id][t.id]);
else if ("post" === t.type) {
if (!r[t.name])
return;
r[t.name].forEach((function(e) {
"function" == typeof e && e.call(t, t.data, (function() {}
))
}
))
}
}
)),
function(e, t) {
return i[t] = {},
n[t] = e,
o = e,
{
on: function(e, t, o) {
r[e] && o || (r[e] = []),
r[e].push(t)
},
off: function(e, t) {
if (!r[e])
return !1;
var o = r[e].indexOf(t);
o > -1 && r[e].splice(o, 1)
},
get: function(e, o, r) {
var s = {
id: a++,
type: "get",
name: e,
client_id: t,
data: o,
provider: d
};
i[t][s.id] = r,
n[t].postMessage(JSON.stringify(s), "*")
},
post: function(e, t, o) {
var i = {
id: s++,
type: "post",
name: t,
data: o,
provider: d
};
e && "function" == typeof e.postMessage && e.postMessage(JSON.stringify(i), "*")
}
}
}
),
c.getUrlParams = function() {
for (var e = /\+/g, t = /([^&=]+)=?([^&]*)/g, o = window.location.search.substring(1), i = t.exec(o), r = function(t) {
return decodeURIComponent(t.replace(e, " "))
}, n = {}; i; )
n[r(i[1])] = r(i[2]),
i = t.exec(o);
return n
}
,
c.createUrlParams = function(e) {
var t = [];
for (var o in e)
e.hasOwnProperty(o) && null != e[o] && t.push(encodeURIComponent(o) + "=" + encodeURIComponent(e[o]));
return t.join("&")
}
,
c.addUrlParams = function(e, t, o) {
for (var i in t)
t.hasOwnProperty(i) && (o ? t[i] : null != t[i]) && e.searchParams.set(i, t[i]);
return e
}
;
var h = function(e, t) {
var o = document.getElementById(t.container);
if (o) {
o.innerHTML = "",
o.appendChild(e);
var i = o.parentElement && o.parentElement.querySelector(".tradingview-widget-copyright");
if (i) {
i.style.width = o.querySelector("iframe").style.width;
var r = i.querySelector("a");
if (r) {
var n = r.getAttribute("href");
if (n)
try {
const e = new URL(n);
c.addUrlParams(e, c.generateUtmForUrlParams(t)),
r.setAttribute("href", e.toString())
} catch (e) {
console.log(`Cannot update link UTM params, href="${n}"`)
}
}
}
} else
document.currentScript.parentNode.insertBefore(e, document.currentScript.nextSibling);
const a = c.embedStylesForCopyright()
, s = function() {
const e = document.querySelector("script[nonce]");
return e && (e.nonce || e.getAttribute("nonce"))
}();
s && a.setAttribute("nonce", s),
document.body.appendChild(a)
};
function g(e, t) {
return null != e ? e : t
}
window.TradingView ? function e(t, o) {
for (var i in o)
"object" == typeof o[i] && t.hasOwnProperty(i) ? e(t[i], o[i]) : t[i] = o[i];
return t
}(window.TradingView, c) : window.TradingView = c
}();
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
\ No newline at end of file
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
\ No newline at end of file
File added
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #000;
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: linear-gradient(to bottom, transparent, rgb(var(--background-end-rgb))) rgb(var(--background-start-rgb));
font-family: Arial, Helvetica, sans-serif;
}
.text-inherit {
color: inherit
}
.text-primary {
--tw-text-opacity: 1;
color: rgb(255 196 49/var(--tw-text-opacity))
}
.text-red-500 {
--tw-text-opacity: 1;
color: rgb(239 68 68/var(--tw-text-opacity))
}
.text-success {
--tw-text-opacity: 1;
color: rgb(53 178 111/var(--tw-text-opacity))
}
.text-white {
--tw-text-opacity: 1;
color: rgb(255 255 255/var(--tw-text-opacity))
}
.text-yellow-800 {
--tw-text-opacity: 1;
color: rgb(133 77 14/var(--tw-text-opacity))
}
.underline {
text-decoration-line: underline
}
.accent-primary {
accent-color: #ffc431
}
.\!border-primary {
--tw-border-opacity: 1!important;
border-color: rgb(255 196 49/var(--tw-border-opacity))!important
}
.border-danger {
--tw-border-opacity: 1;
border-color: rgb(242 77 91/var(--tw-border-opacity))
}
.border-gray-200 {
--tw-border-opacity: 1;
border-color: rgb(135 134 139/var(--tw-border-opacity))
}
.border-gray-300 {
--tw-border-opacity: 1;
border-color: rgb(62 61 64/var(--tw-border-opacity))
}
.border-gray-600 {
--tw-border-opacity: 1;
border-color: rgb(32 32 32/var(--tw-border-opacity))
}
.border-neutral-700 {
--tw-border-opacity: 1;
border-color: rgb(64 64 64/var(--tw-border-opacity))
}
.border-primary {
--tw-border-opacity: 1;
border-color: rgb(255 196 49/var(--tw-border-opacity))
}
.border-transparent {
border-color: transparent
}
.border-white\/20 {
border-color: hsla(0,0%,100%,.2)
}
.\!bg-gray-800 {
--tw-bg-opacity: 1!important;
background-color: rgb(20 20 20/var(--tw-bg-opacity))!important
}
.bg-\[\#202020b3\] {
background-color: #202020b3
}
.bg-\[\#312300\] {
--tw-bg-opacity: 1;
background-color: rgb(49 35 0/var(--tw-bg-opacity))
}
.bg-\[\#343332\] {
--tw-bg-opacity: 1;
background-color: rgb(52 51 50/var(--tw-bg-opacity))
}
.bg-\[\#681A21\] {
--tw-bg-opacity: 1;
background-color: rgb(104 26 33/var(--tw-bg-opacity))
}
.bg-\[\#ffc43133\] {
background-color: #ffc43133
}
.bg-black {
--tw-bg-opacity: 1;
background-color: rgb(0 0 0/var(--tw-bg-opacity))
}
.bg-black\/25 {
background-color: rgba(0,0,0,.25)
}
.bg-black\/30 {
background-color: rgba(0,0,0,.3)
}
.bg-danger {
--tw-bg-opacity: 1;
background-color: rgb(242 77 91/var(--tw-bg-opacity))
}
.bg-danger-disabled {
--tw-bg-opacity: 1;
background-color: rgb(52 51 50/var(--tw-bg-opacity))
}
.bg-danger-hover {
--tw-bg-opacity: 1;
background-color: rgb(217 69 81/var(--tw-bg-opacity))
}
.bg-gray-200 {
--tw-bg-opacity: 1;
background-color: rgb(135 134 139/var(--tw-bg-opacity))
}
.bg-gray-300 {
--tw-bg-opacity: 1;
background-color: rgb(62 61 64/var(--tw-bg-opacity))
}
.bg-gray-400 {
--tw-bg-opacity: 1;
background-color: rgb(52 51 50/var(--tw-bg-opacity))
}
.bg-gray-500 {
--tw-bg-opacity: 1;
background-color: rgb(39 39 43/var(--tw-bg-opacity))
}
.bg-gray-700 {
--tw-bg-opacity: 1;
background-color: rgb(26 26 26/var(--tw-bg-opacity))
}
.bg-gray-800 {
--tw-bg-opacity: 1;
background-color: rgb(20 20 20/var(--tw-bg-opacity))
}
.bg-gray-900 {
--tw-bg-opacity: 1;
background-color: rgb(16 16 16/var(--tw-bg-opacity))
}
.bg-primary {
--tw-bg-opacity: 1;
background-color: rgb(255 196 49/var(--tw-bg-opacity))
}
.bg-primary-500,.bg-primary-darker {
--tw-bg-opacity: 1;
background-color: rgb(92 66 0/var(--tw-bg-opacity));
}
.bg-primary-disabled {
--tw-bg-opacity: 1;
background-color: rgb(52 51 50/var(--tw-bg-opacity))
}
.bg-success {
--tw-bg-opacity: 1;
background-color: rgb(53 178 111/var(--tw-bg-opacity))
}
.bg-success-500 {
--tw-bg-opacity: 1;
background-color: rgb(11 77 41/var(--tw-bg-opacity))
}
.bg-transparent {
background-color: transparent
}
.bg-yellow-100 {
--tw-bg-opacity: 1;
background-color: rgb(254 249 195/var(--tw-bg-opacity))
}
.bg-gradient-to-l {
background-image: linear-gradient(to left,var(--tw-gradient-stops))
}
.bg-gradient-to-r {
background-image: linear-gradient(to right,var(--tw-gradient-stops))
}
.from-gray-500 {
--tw-gradient-from: #27272b var(--tw-gradient-from-position);
--tw-gradient-from-position: ;
--tw-gradient-to: rgba(39,39,43,0) var(--tw-gradient-from-position);
--tw-gradient-to-position: ;
--tw-gradient-stops: var(--tw-gradient-from),var(--tw-gradient-to)
}
.from-20\% {
--tw-gradient-from-position: 20%
}
.to-gray-500\/0 {
--tw-gradient-to: rgba(39,39,43,0) var(--tw-gradient-to-position);
--tw-gradient-to-position:
}
.to-100\% {
--tw-gradient-to-position: 100%
}
.fill-black {
fill: #000
}
.fill-primary {
fill: #ffc431
}
.button-danger {
--tw-bg-opacity: 1;
background-color: rgb(242 77 91/var(--tw-bg-opacity));
--tw-text-opacity: 1;
color: rgb(255 255 255/var(--tw-text-opacity));
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(.4,0,.2,1);
transition-duration: .2s
}
.button-danger:hover {
transition-timing-function: cubic-bezier(0,0,.2,1);
--tw-bg-opacity: 1;
background-color: rgb(217 69 81/var(--tw-bg-opacity))
}
.button-danger:active,.button-danger:focus {
--tw-bg-opacity: 1;
background-color: rgb(242 97 108/var(--tw-bg-opacity))
}
.button-success {
--tw-bg-opacity: 1;
background-color: rgb(53 178 111/var(--tw-bg-opacity));
--tw-text-opacity: 1;
color: rgb(255 255 255/var(--tw-text-opacity));
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(.4,0,.2,1);
transition-duration: .2s
}
.button-success:hover {
transition-timing-function: cubic-bezier(0,0,.2,1);
--tw-bg-opacity: 1;
background-color: rgb(46 153 95/var(--tw-bg-opacity))
}
.button-success:active,.button-success:focus {
--tw-bg-opacity: 1;
background-color: rgb(76 191 129/var(--tw-bg-opacity))
}
.button-outline {
border-width: 1px;
--tw-border-opacity: 1;
border-color: rgb(255 196 49/var(--tw-border-opacity));
background-color: transparent;
--tw-text-opacity: 1;
color: rgb(255 255 255/var(--tw-text-opacity));
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(.4,0,.2,1);
transition-duration: .2s
}
.button-outline:hover {
transition-timing-function: cubic-bezier(0,0,.2,1);
background-color: rgb(255 255 255/var(--tw-bg-opacity));
--tw-bg-opacity: 0.05
}
.button-outline:active,.button-outline:focus {
--tw-bg-opacity: 1;
background-color: rgb(255 196 49/var(--tw-bg-opacity));
--tw-text-opacity: 1;
color: rgb(16 16 16/var(--tw-text-opacity))
}
.button-outline-primary {
--tw-bg-opacity: 1;
background-color: rgb(49 35 0/var(--tw-bg-opacity));
--tw-text-opacity: 1;
color: rgb(255 196 49/var(--tw-text-opacity));
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;
transition-property: color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;
transition-timing-function: cubic-bezier(.4,0,.2,1);
transition-duration: .2s
}
.button-outline-primary:hover {
transition-timing-function: cubic-bezier(0,0,.2,1)
}
.button-danger:disabled,.button-danger:disabled:hover,.button-outline-primary:disabled,.button-outline-primary:disabled:hover,.button-outline:disabled,.button-outline:disabled:hover,.button-primary:disabled,.button-primary:disabled:hover,.button-secondary:disabled,.button-secondary:disabled:hover,.button-success:disabled,.button-success:disabled:hover {
border-style: none;
--tw-bg-opacity: 1;
background-color: rgb(62 61 64/var(--tw-bg-opacity));
--tw-text-opacity: 1;
color: rgb(135 134 139/var(--tw-text-opacity))
}
\ No newline at end of file
import "./globals.css";
import '@rainbow-me/rainbowkit/styles.css';
import { Providers } from '@/providers/wagmiProvider';
// import { ChakraProvider, extendTheme } from '@chakra-ui/react';
// const theme = extendTheme({
// // 使用默认主题的扩展
// });
import Header from '@/components/Header';
function RootLayout({ children }: { children: React.ReactNode }) {
return (
// <ChakraProvider theme={theme}>
<html lang="en" suppressHydrationWarning>
<head>
</head>
<body>
<main className='flex min-h-screen flex-col bg-gray-900'>
<Providers>
<Header />
{children}
</Providers>
</main>
</body>
</html>
// </ChakraProvider>
);
}
export default RootLayout;
"use client";
import { useState } from "react";
import { ethers } from "ethers";
import { useAccount, useWriteContract, useReadContract, useSendTransaction, useWaitForTransactionReceipt } from "wagmi";
import { useMakeOrder } from '@/utils/api'
import { Segmented } from 'antd';
import MarketTrade from "@/components/MarketTrade";
import OrderBook from "@/components/OrderBook";
import OpenOrders from "@/components/OpenOrders";
import TradingViewChart from "@/components/TradingViewChart";
import OrderHistory from "@/components/OrderHistory";
import TradHistory from '@/components/TradHistory';
const USDC_Address = "0x9250C869F063a44121a0F46364302643bb4E68D3";
const WBTC_Address = "0xe47d6011bD57E05025DBEcD82987834E1E31e7c3";
const DEX_Address = "0x8B1c2430908D719bFF0D880e54EB2B1C498d06E6";
const erc20ABI = [
{
"constant": false,
"inputs": [
{
"name": "spender",
"type": "address"
},
{
"name": "amount",
"type": "uint256"
}
],
"name": "approve",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "owner",
"type": "address"
},
{
"name": "spender",
"type": "address"
}
],
"name": "allowance",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [{ "name": "account", "type": "address" }],
"name": "balanceOf",
"outputs": [{ "name": "", "type": "uint256" }],
"payable": false,
"stateMutability": "view",
"type": "function"
}
];
function Page() {
const { writeContract } = useWriteContract();
const { address } = useAccount();
const {
data: hash,
isPending,
sendTransaction
} = useSendTransaction()
const { isLoading: isConfirming, isSuccess: isConfirmed } =
useWaitForTransactionReceipt({
hash,
})
const [currentTable, setCurrentTable] = useState(1)
const [currentList, setCurrentList] = useState('marketTrades')
const [currentLimit, setCurrentLimit] = useState('buy')
const [buyOrder, setBuyOrder]: any = useState({
price: '',
amount: '',
})
const [sellOrder, setSellOrder] = useState({
price: '',
amount: '',
})
const { mutate, isPending: isMakingOrder, isError, error, isSuccess } = useMakeOrder(makeOrderCallback)
const { data: usdcAllowance } = useReadContract({
abi: erc20ABI,
address: USDC_Address,
functionName: "allowance",
args: [address, DEX_Address],
});
const { data: wbtcAllowance } = useReadContract({
abi: erc20ABI,
address: WBTC_Address,
functionName: "allowance",
args: [address, DEX_Address],
});
const { data: usdcBalance, isLoading: isLoadingUsdc, error: usdcError } = useReadContract({
abi: erc20ABI,
address: USDC_Address,
functionName: 'balanceOf',
args: [address],
});
// 查询 WBTC 余额
const { data: wbtcBalance, isLoading: isLoadingWbtc, error: wbtcError } = useReadContract({
abi: erc20ABI,
address: WBTC_Address,
functionName: 'balanceOf',
args: [address],
});
console.log(usdcBalance, wbtcBalance)
// 确保 usdcBalance 和 wbtcBalance 是 BigNumberish 类型
const formattedUsdcBalance = usdcBalance ? Number(ethers.formatUnits(usdcBalance.toString())).toFixed(5) : '0';
const formattedWbtcBalance = wbtcBalance ? Number(ethers.formatUnits(wbtcBalance.toString())).toFixed(5) : '0';
console.log(formattedUsdcBalance, formattedWbtcBalance)
async function makeOrderCallback(resData: any) {
try {
if (!resData || !resData.data || resData.data.code !== 200) return
resData = resData.data.data[0]
const approvalPromises = [];
if (Number(usdcAllowance) === 0) {
const usdc_approveTx: any = await writeContract({
abi: erc20ABI,
address: USDC_Address,
functionName: "approve",
args: [DEX_Address, ethers.MaxUint256],
});
const usdc_approvePromise = new Promise((resolve, reject) => {
const { isLoading, isSuccess } = useWaitForTransactionReceipt({
hash: usdc_approveTx.hash,
});
if (isSuccess) {
console.log('USDC approved');
resolve(true);
} else if (isLoading) {
console.log('Waiting for USDC approval...');
} else {
reject(new Error('USDC approval failed'));
}
});
approvalPromises.push(usdc_approvePromise);
}
if (Number(wbtcAllowance) === 0) {
const wbtc_approveTx: any = await writeContract({
abi: erc20ABI,
address: WBTC_Address,
functionName: "approve",
args: [DEX_Address, ethers.MaxUint256],
});
const wbtc_approvePromise = new Promise((resolve, reject) => {
const { isLoading, isSuccess } = useWaitForTransactionReceipt({
hash: wbtc_approveTx.hash,
});
if (isSuccess) {
console.log('WBTC approved');
resolve(true);
} else if (isLoading) {
console.log('Waiting for WBTC approval...');
} else {
reject(new Error('WBTC approval failed'));
}
});
approvalPromises.push(wbtc_approvePromise);
}
await Promise.all(approvalPromises);
if (Number(usdcAllowance) > 0 && Number(wbtcAllowance) > 0) {
console.log('approved')
const tx: any = {
to: resData.to,
value: ethers.parseEther(resData.value), // 发送金额 (以太),转换为 Wei 单位
data: '0x' + resData.data,
gas: parseInt(resData.gas_limit),
gasPrice: parseInt(resData.gas_price),
};
sendTransaction(tx)
}
} catch (error) {
console.log(error)
}
}
async function createOrder(type: string) {
try {
const order = type === 'buy' ? buyOrder : sellOrder
if (!order.price || !order.amount) return
const orderData = {
user: address,
amount: String(order.amount),
price: String(order.price),
side: type === 'buy' ? 0 : 1,
pair: '0x8b1c2430908d719bff0d880e54eb2b1c498d06e6'
};
mutate(orderData);
} catch (error) {
}
}
return (
<div className="flex max-h-full w-full flex-1 items-stretch">
<div className="flex max-h-full w-full flex-col">
<div className="hidden min-h-full md:flex md:flex-col">
<div className="flex w-full flex-1 flex-col max-h-[calc(100vh-300px)]">
<div className="flex min-h-full flex-1 items-start">
<div className="h-full w-full flex-1 bg-black">
<TradingViewChart symbol="" />
</div>
<div className="flex h-full h-[calc(100vh-300px)] w-80 flex-col gap-y-4 overflow-y-hidden rounded border border-gray-300 bg-black py-4">
<div className="flex items-center gap-x-6 text-[14px] font-bold border-b border-gray-300 px-4">
<p className={`${currentList === 'marketTrades' ? 'text-white border-white' : 'text-[#909090] border-transparent'} border-b-2 pb-2 cursor-pointer hover:text-white`} onClick={() => setCurrentList('marketTrades')}>Last trades</p>
<p className={`${currentList === 'Orderbook' ? 'text-white border-white' : 'text-[#909090] border-transparent'} border-b-2 pb-2 cursor-pointer hover:text-white`} onClick={() => setCurrentList('Orderbook')}>Order book</p>
</div>
{currentList === 'marketTrades' ? <div className="flex h-[323px] w-full flex-col rounded bg-black md:h-full px-4">
<div className="mt-4 flex w-full items-center gap-x-3 md:mt-0">
<p className="w-1/3 text-left text-[10px] text-gray-200">Price (USDT)</p>
<p className="w-1/3 text-center text-[10px] text-gray-200">Size (BTC)</p>
<p className="w-1/3 text-right text-[10px] text-gray-200">Time</p>
</div>
<MarketTrade />
</div> : <div className="flex h-[323px] w-full flex-col rounded bg-black px-4 md:h-full">
<div className="mt-4 flex w-full items-center gap-x-3 md:mt-0">
<p className="w-1/2 text-left text-[10px] text-gray-200">Price (USDT)</p>
<p className="w-1/2 text-right text-[10px] text-gray-200">Amount (BTC)</p>
<p className="w-1/2 text-left text-[10px] text-gray-200">Total (BTC)</p>
</div>
<OrderBook />
</div>}
</div>
<div className="h-full">
<div className="fixed bottom-0 z-20 h-full w-80 flex-col justify-start rounded border-y border-gray-300 bg-black md:relative md:flex py-4">
<div className="md:block">
<div className="my-8 flex items-center gap-x-6 text-[14px] md:mb-4 md:mt-0 border-b border-gray-300 px-4">
<p className="font-semibold text-white border-b-2 pb-2">Trade</p>
</div>
{/* <Segmented options={['Buy', 'Sell']} block /> */}
<div className="px-4">
<div className="w-full flex justify-between items-center px-1 py-1 bg-gray-700 h-[36px] mb-4 rounded-md">
<button onClick={() => setCurrentLimit('buy')} className={`${currentLimit === 'buy' ? 'text-white bg-[#25a750]' : 'text-white'} w-[50%] h-full rounded cursor-pointer text-xs`} >Buy</button>
<button onClick={() => setCurrentLimit('sell')} className={`${currentLimit === 'sell' ? 'text-white bg-[#ca3f64]' : 'text-white'} w-[50%] h-full rounded cursor-pointer text-xs`} >Sell</button>
</div>
<div className="flex justify-center gap-6">
{currentLimit === 'buy' && <div className="flex w-full flex-col md:w-full">
<div className="flex w-full flex-col gap-y-3 md:w-full null ">
<div className="flex h-8 w-full flex-col items-center justify-center rounded border bg-gray-700 p-2 border-transparent">
<div className="flex h-full w-full items-center text-xs">
<p className="text-gray-200">Price</p>
<input type="number" value={buyOrder.price} onChange={(e) => setBuyOrder({ ...buyOrder, price: e.target.value })} placeholder="0.0" className="mx-1 w-full flex-1 bg-transparent outline-none placeholder:text-gray-200 text-left text-white" />
<p className="text-white">USDT</p>
</div>
</div>
<div className="flex h-8 w-full flex-col items-center justify-center rounded border bg-gray-700 p-2 border-transparent">
<div className="flex h-full w-full items-center text-xs">
<p className="text-gray-200">Amount</p>
<input type="number" value={buyOrder.amount} onChange={(e) => setBuyOrder({ ...buyOrder, amount: e.target.value })} placeholder="0.0" className="mx-1 w-full flex-1 bg-transparent outline-none placeholder:text-gray-200 text-left text-white" />
<p className="text-white">BTC</p>
</div>
</div>
<div className="flex h-8 w-full flex-col items-center justify-center rounded border bg-gray-700 p-2 md:mt-4 border-transparent">
<div className="flex h-full w-full items-center text-xs">
<p className="text-gray-200">Total</p>
<input type="number" defaultValue={Number(buyOrder.price * buyOrder.amount).toFixed(1)} placeholder="0.0" className="mx-1 w-full flex-1 bg-transparent outline-none placeholder:text-gray-200 text-left text-white" />
<p className="text-white">USDT</p>
</div>
</div>
<span className="flex h-4 items-center text-[9px] text-danger"></span>
<button disabled={isPending || isMakingOrder} onClick={() => createOrder('buy')} className="inline-flex h-10 items-center justify-center gap-2 rounded px-4 text-[14px] font-semibold transition duration-100 ease-out hover:ease-in button-success text-[14px] text-white">
Buy BTC
</button>
</div>
</div>}
{currentLimit === 'sell' && <div className="flex w-full flex-col md:w-full">
<div className="flex w-full flex-col gap-y-3 md:w-full null ">
<div className="flex h-8 w-full flex-col items-center justify-center rounded border bg-gray-700 p-2 border-transparent">
<div className="flex h-full w-full items-center text-xs">
<p className="text-gray-200">Price</p>
<input type="number" placeholder="0.0" className="mx-1 w-full flex-1 bg-transparent outline-none placeholder:text-gray-200 text-left text-white" />
<p className="text-white">USDT</p>
</div>
</div>
<div className="flex h-8 w-full flex-col items-center justify-center rounded border bg-gray-700 p-2 border-transparent">
<div className="flex h-full w-full items-center text-xs">
<p className="text-gray-200">Amount</p>
<input type="number" placeholder="0.0" className="mx-1 w-full flex-1 bg-transparent outline-none placeholder:text-gray-200 text-left text-white" />
<p className="text-white">BTC</p>
</div>
</div>
<div className="flex h-8 w-full flex-col items-center justify-center rounded border bg-gray-700 p-2 md:mt-4 border-transparent">
<div className="flex h-full w-full items-center text-xs">
<p className="text-gray-200">Total</p>
<input type="number" placeholder="0.0" className="mx-1 w-full flex-1 bg-transparent outline-none placeholder:text-gray-200 text-left text-white" />
<p className="text-white">USDT</p>
</div>
</div>
<span className="flex h-4 items-center text-[9px] text-danger"></span>
<button disabled={isPending || isMakingOrder} onClick={() => createOrder('sell')} className="inline-flex h-10 items-center justify-center gap-2 rounded px-4 text-[14px] font-semibold transition duration-100 ease-out hover:ease-in button-danger text-[14px] text-white">
Sell BTC
</button>
</div>
</div>}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="flex w-full border-t border-gray-300 md:h-[300px]">
<div className="h-full flex-1 border-r border-gray-300">
<div className="relative mt-4 flex h-[234px] w-full flex-col rounded bg-black p-4 md:mt-0 md:h-full md:p-4">
<div className="flex items-center">
<div className="flex w-2/4 gap-x-4">
<div className={`cursor-pointer rounded text-center text-[14px] font-bold text-[#909090] transition-all hover:text-white ${currentTable === 1 && 'text-white'}`} onClick={() => setCurrentTable(1)}>Open Orders (0)</div>
<div className={`cursor-pointer rounded text-center text-[14px] font-bold text-[#909090] transition-all hover:text-white ${currentTable === 2 && 'text-white'}`} onClick={() => setCurrentTable(2)}>Order History (0)</div>
<div className={`cursor-pointer rounded text-center text-[14px] font-bold text-[#909090] transition-all hover:text-white ${currentTable === 3 && 'text-white'}`} onClick={() => setCurrentTable(3)}>Trade History (0)</div>
</div>
<div className="flex w-2/4 items-center justify-end gap-x-4">
{/* <button className="inline-flex h-10 items-center justify-center gap-2 rounded px-4 text-[14px] font-semibold transition duration-100 ease-out hover:ease-in button-outline h-8 px-6 py-3 font-normal text-white">Order Management</button> */}
{
false && <div className="flex cursor-pointer items-center gap-x-1 font-bold">
<input type="checkbox" className="accent-primary md:bg-transparent" />
<p className="text-xs text-white"> Hide Other Pairs</p>
</div>
}
</div>
</div>
{currentTable === 1 && <OpenOrders />}
{currentTable === 2 && <OrderHistory />}
{currentTable === 3 && <TradHistory />}
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default Page;
'use client';
import { ConnectButton } from '@rainbow-me/rainbowkit';
import { useEffect, useState } from 'react';
import { useGetPairStat, useGetPairList } from '@/utils/api';
function Page() {
const pair = '0x8b1c2430908d719bff0d880e54eb2b1c498d06e6'
const { data, error, isLoading, refetch } = useGetPairStat(pair);
const { data: pairListData, error: pairListError, isLoading: pairListLoading } = useGetPairList();
const [showPairList, setShowPairList] = useState(false);
useEffect(() => {
const intervalId = setInterval(() => {
refetch(); // 每隔 3 秒触发一次请求
}, 3000);
if(error instanceof Error) clearInterval(intervalId);
// 清除定时器,防止内存泄漏
return () => {
clearInterval(intervalId);
};
}, [refetch, error]);
// if (isLoading) {
// return <div>Loading...</div>;
// }
// if (error instanceof Error) {
// return <div>Error: {error.message}</div>;
// }
const pairList = pairListData?.data.data;
let statData = data?.data.data[0] || {
pair: '',
price: '0.00',
high: '0.00',
low: '0.00',
base_volume: '0.00',
quote_volume: '0.00',
change: '0.00',
};
console.log(statData)
return (
<>
<div
className='flex items-center justify-between bg-black px-4 py-[14px] md:max-h-16 md:px-6 md:py-3'
>
<div className='flex h-10 items-center'>
<div className="relative mt-4 hidden items-center md:mt-0 md:flex">
<div className="relative mr-4 ml-4 pr-4 shrink-0">
<div className="flex cursor-pointer items-center rounded-md px-0.5 hover:bg-gray-hover" onClick={() => setShowPairList(!showPairList)}>
<div className="flex flex-col items-start font-bold text-white">
<div className="flex space-x-2">
BTC/USDT
</div>
{/* <div className="rounded-[4px] bg-primary-500 px-2 py-1 text-xxs leading-none text-primary">spot</div> */}
</div>
</div>
{
showPairList && <div className="absolute left-0 top-14 z-40 h-[400px] flex-col border-gray-300 bg-gray-500 p-4 md:w-[560px] ">
{/* <div className="flex items-center gap-x-4">
<p className="cursor-pointer text-sm font-bold text-primary">Search crypto</p>
</div> */}
<div className="flex items-center rounded bg-gray-700 px-4 py-2 md:bg-gray-700 mt-3 md:bg-gray-700">
<input type="text" className='w-full bg-transparent text-gray-200 outline-none' placeholder="Search crypto" />
</div>
<div className="mt-3 flex items-center space-x-2">
<div className="w-2/4 text-left text-xs text-gray-200">Pair</div>
<div className="w-1/4 text-left text-xs text-gray-200">Last Price</div>
<div className="w-1/4 text-left text-xs text-gray-200">Change</div>
{/* <div className="w-20 pr-2 text-right text-xs text-gray-200">Chain</div> */}
</div>
<div className="-mr-4 mt-2 flex h-[210px] flex-col overflow-y-scroll pr-4">
{
pairList?.map((item: any, index: number) => {
return (
<div key={index} className="flex cursor-pointer items-center space-x-2 py-1 hover:opacity-80">
<div className="flex w-2/4 items-center text-left text-xs">
<a href="" className='flex-1 font-bold text-white'>{item.pair}</a>
</div>
<a href="" className="w-1/4 text-left text-xs text-white">${item.last_price}</a>
<a href="" className="w-1/4 text-left text-xs text-white">{item.change}%</a>
{/* <a href="" className="flex w-20 items-center justify-end pr-2 text-white">T</a> */}
</div>
)
})
}
</div>
</div>
}
</div>
<div className="mr-4 flex flex-col items-start gap-y-2 text-right md:mr-6 md:gap-y-0">
<p className="text-xs text-gray-200">Price</p>
<p className={`text-xs font-bold text-white md:text-[14px]`}>{statData.price} </p>
</div>
<div className="mr-4 flex flex-col items-start gap-y-2 text-right md:mr-6 md:gap-y-0">
<p className="text-xs text-gray-200">24h change</p>
<p className={`text-xs font-bold md:text-[14px] ${statData && statData.change.toString().includes('-') ? 'text-red-500' : 'text-success'}`}>{statData.change}%</p>
</div>
<div className="mr-4 flex flex-col items-start gap-y-2 text-right md:mr-6 md:gap-y-0">
<p className="text-xs text-gray-200">24h High</p>
<p className='text-xs font-bold text-white md:text-[14px]'>{statData.high}</p>
</div>
<div className="mr-4 flex flex-col items-start gap-y-2 text-right md:mr-6 md:gap-y-0">
<p className="text-xs text-gray-200">24h Low</p>
<p className='text-xs font-bold text-white md:text-[14px]'>{statData.low}</p>
</div>
<div className="mr-4 flex flex-col items-start gap-y-2 text-right md:mr-6 md:gap-y-0">
<p className="text-xs text-gray-200">24h Volume ({statData.base_token})</p>
<p className='text-xs font-bold text-white md:text-[14px]'>{statData.base_volume}</p>
</div>
<div className="mr-4 flex flex-col items-start gap-y-2 text-right md:mr-6 md:gap-y-0">
<p className="text-xs text-gray-200">24h Volume</p>
<p className='text-xs font-bold text-white md:text-[14px]'>{statData.quote_volume}</p>
</div>
</div>
</div>
<ConnectButton showBalance={false} />
</div>
{showPairList && <div className="fixed left-0 top-[64px] z-30 h-full w-full bg-black opacity-60" onClick={() => setShowPairList(false)}></div>}
</>
);
}
export default Page;
"use client";
import dayjs from 'dayjs'
import { useGetPairTradeHistory } from '@/utils/api'
export default function MarketTrade() {
const pair = '0x8b1c2430908d719bff0d880e54eb2b1c498d06e6'
const { data, error, isLoading, refetch } = useGetPairTradeHistory(pair);
// if (isLoading) {
// return <div className='no-scrollbar mt-2 flex w-full flex-col overflow-y-scroll'>Loading...</div>;
// }
// if (error instanceof Error) {
// return <div>Error: {error.message}</div>;
// }
let tradData = data?.data.data && data?.data.data.slice(0, 40);
function formatTime(timestamp: number) {
return dayjs(timestamp * 1000).format('MM-DD HH:mm:ss')
}
return (
<div className="no-scrollbar mt-2 flex w-full flex-col overflow-y-scroll min-h-[calc(100vh-300px)]">
{tradData && tradData.map((item: any, index: number) =>
<div key={index} className="item-center flex h-[26px] w-full cursor-pointer py-1 text-xs hover:opacity-80 md:h-[28px] green-blink">
<p className={`w-1/3 text-left ${item.side === 0 ? 'text-success' : 'text-red-500'}`}>{item.price}</p>
<p className="w-1/3 text-center text-white">{item.amount && item.amount.slice(0, 8)}</p>
<a href="#" className="w-1/3 text-right text-white">{formatTime(item.time)}</a>
</div>)}
</div>
)
}
\ No newline at end of file
"use client";
import { useAccount } from 'wagmi';
import { useEffect } from 'react';
import { useGetUserOpenOrders } from '@/utils/api';
import dayjs from 'dayjs'
export default function OpenOrders() {
const { address } = useAccount();
console.log(address)
const params = {
"address": '0x2D4E6b96bD85248d13020D392e99558abFb4f74C',
"limit": 20,
"offset": 0,
"orderBy": "date", //price
"orderDirection": "desc",
"pair": "0x8b1c2430908d719bff0d880e54eb2b1c498d06e6"
}
const { mutate, isPending, isError, error, isSuccess, data } = useGetUserOpenOrders()
useEffect(() => {
mutate(params)
}, [])
if(isPending) return <p>Loading...</p>
// if(isError) return <p>Error: {error.message}</p>
// if(isSuccess && data && data.length === 0) return <p>No open orders</p>
const orderData = isSuccess && data && data.data.data
console.log(orderData)
function formatTime(timestamp: number) {
return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}
return (
<div className="no-scrollbar flex flex-1 flex-col overflow-scroll">
<div className="mt-4 flex w-full items-center border-b border-gray-300 pb-2 text-xs text-white">
<p className="flex w-1/4 cursor-pointer items-center gap-x-1 text-left md:w-[16%]">Date </p>
<p className="w-1/4 text-center ">Pair</p>
<p className="flex w-1/4 cursor-pointer items-center gap-x-1 text-center md:w-[8%]">Side </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Price </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Amount </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">executed </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Filled </p>
</div>
{isSuccess && orderData && orderData?.map((order: any, index: number) => {
return <div key={index}>
<div className="flex w-full items-center border-b border-gray-300 py-2 text-xs text-white">
<p className="flex w-1/4 items-center gap-x-1 text-left md:w-[16%]">{formatTime(order.date)}</p>
<p className="w-1/4 text-center">{order.pairName}</p>
<p className="flex w-1/4 items-center gap-x-1 text-center md:w-[8%]">{order.side}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.price}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.total}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.executed}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.filled}%</p>
</div>
</div>
})}
</div>
)
}
\ No newline at end of file
"use client";
import dayjs from 'dayjs'
import { useGetPairOrderList } from '@/utils/api'
export default function OrderBook() {
const pair = '0x8b1c2430908d719bff0d880e54eb2b1c498d06e6'
const { data, error, isLoading, refetch } = useGetPairOrderList(pair);
// if (isLoading) {
// return <div>Loading...</div>;
// }
// if (error instanceof Error) {
// return <div>Error: {error.message}</div>;
// }
let bitsData = data?.data.data && data?.data.data[0].bids;
let asksData = data?.data.data && data?.data.data[0].asks;
return (
<div className="no-scrollbar flex flex-col w-full items-start overflow-y-scroll min-h-[calc(100vh-300px)]">
<div className="mt-2 flex w-full flex-col">
{asksData && asksData.map((item: any, index: number) =>
<div key={index} className="item-center flex h-[26px] w-full cursor-pointer py-1 text-xs hover:opacity-80 md:h-[28px]">
<p className={`mr-2 w-1/2 text-left text-red-500`}>{item.price}</p>
<p className="mr-2 w-1/2 text-right text-white">{item.amount && item.amount.slice(0, 8)}</p>
<p className="mr-2 w-1/2 text-right text-white">{item.price && item.amount && (Number(item.price) * Number(item.amount)).toFixed(6)}</p>
</div>)}
</div>
<div className="mt-2 flex w-full flex-col">
{bitsData && bitsData.map((item: any, index: number) =>
<div key={index} className="item-center flex h-[26px] w-full cursor-pointer py-1 text-xs hover:opacity-80 md:h-[28px]">
<p className="mr-2 w-1/2 text-left text-success">{item.price}</p>
<p className={`mr-2 w-1/2 text-right text-white`}>{item.amount && item.amount}</p>
<p className="mr-2 w-1/2 text-right text-white">{item.price && item.amount && (Number(item.price) * Number(item.amount)).toFixed(6)}</p>
</div>)}
</div>
</div>
)
}
\ No newline at end of file
"use client";
import { useAccount } from 'wagmi';
import { useEffect } from 'react';
import { useGetUserOrderHistory } from '@/utils/api';
import dayjs from 'dayjs'
export default function OrderHistory() {
const { address } = useAccount();
console.log(address)
const params = {
"address": '0x2D4E6b96bD85248d13020D392e99558abFb4f74C',
"limit": 20,
"offset": 0,
"orderBy": "date", //price
"orderDirection": "desc",
"pair": "0x8b1c2430908d719bff0d880e54eb2b1c498d06e6"
}
const { mutate, isPending, isError, error, isSuccess, data } = useGetUserOrderHistory()
useEffect(() => {
mutate(params)
}, [])
if(isPending) return <p>Loading...</p>
// if(isError) return <p>Error: {error.message}</p>
// if(isSuccess && data && data.length === 0) return <p>No open orders</p>
const orderData = isSuccess && data && data.data.data
console.log(orderData)
function formatTime(timestamp: number) {
return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}
return (
<div className="no-scrollbar flex flex-1 flex-col overflow-scroll">
<div className="mt-4 flex w-full items-center border-b border-gray-300 pb-2 text-xs text-white">
<p className="flex cursor-pointer flex-row items-center gap-x-1 text-left md:w-[16%] ">Order Time </p>
<p className="w-1/4 text-center">Pair</p>
<p className="flex w-1/4 cursor-pointer items-center gap-x-1 text-center md:w-[8%]">Side </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Price </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Amount </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Executed </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Status </p>
</div>
{isSuccess && orderData && orderData?.map((order: any, index: number) => {
return <div key={index}>
<div className="flex w-full items-center border-b border-gray-300 py-2 text-xs text-white">
<p className="flex w-1/4 items-center gap-x-1 text-left md:w-[16%]">{formatTime(order.date)}</p>
<p className="w-1/4 text-center">{order.pairName}</p>
<p className="flex w-1/4 items-center gap-x-1 text-center md:w-[8%]">{order.side}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.price}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.total}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.executed}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.status}</p>
</div>
</div>
})}
</div>
)
}
\ No newline at end of file
"use client";
import { useAccount } from 'wagmi';
import { useEffect } from 'react';
import { useGetUserTradeHistory } from '@/utils/api';
import dayjs from 'dayjs'
export default function TradHistory() {
const { address } = useAccount();
console.log(address)
const params = {
"address": '0x2D4E6b96bD85248d13020D392e99558abFb4f74C',
"limit": 20,
"offset": 0,
"orderBy": "date", //price
"orderDirection": "desc",
"pair": "0x8b1c2430908d719bff0d880e54eb2b1c498d06e6"
}
const { mutate, isPending, isError, error, isSuccess, data } = useGetUserTradeHistory()
useEffect(() => {
mutate(params)
}, [])
if (isPending) return <p>Loading...</p>
// if (isError) return <p>Error: {error.message}</p>
// if (isSuccess && data && data.length === 0) return <p>No open orders</p>
const orderData = isSuccess && data && data.data.data
console.log(orderData)
function formatTime(timestamp: number) {
return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}
return (
<div className="no-scrollbar flex flex-1 flex-col overflow-scroll">
<div className="mt-4 flex w-full items-center border-b border-gray-300 pb-2 text-xs text-white">
<p className="flex w-1/4 cursor-pointer items-center gap-x-1 text-left md:w-[16%]">Date </p>
<p className="w-1/4 text-center">Pair</p>
<p className="flex w-1/4 cursor-pointer items-center gap-x-1 text-center md:w-[8%]">Side </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Price </p>
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Executed </p>
{/* <p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Total </p> */}
{/* <p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Role </p> */}
<p className="hidden w-[10%] cursor-pointer items-center gap-x-1 text-left md:flex">Fee </p>
</div>
{isSuccess && orderData && orderData?.map((order: any, index: number) => {
return <div key={index}>
<div className="flex w-full items-center border-b border-gray-300 py-2 text-xs text-white">
<p className="flex w-1/4 items-center gap-x-1 text-left md:w-[16%]">{formatTime(order.date)}</p>
<p className="w-1/4 text-center">{order.pairName}</p>
<p className="flex w-1/4 items-center gap-x-1 text-center md:w-[8%]">{order.side}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.price}</p>
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.executed}</p>
{/* <p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.total}</p> */}
{/* <p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.role}</p> */}
<p className="hidden w-[10%] items-center gap-x-1 text-left md:flex">{order.fee}</p>
</div>
</div>
})}
</div>
)
}
\ No newline at end of file
// components/TradingViewChart.tsx
import { useEffect } from 'react';
import { BinanceDataFeed } from '../utils/BianceDatafeed';
interface TradingViewChartProps {
symbol: string;
interval?: string;
}
const TradingViewChart: React.FC<TradingViewChartProps> = ({ symbol = 'BTCUSDT', interval = 'D' }) => {
useEffect(() => {
if (typeof window !== "undefined") {
const script = document.createElement('script');
script.src = "https://s3.tradingview.com/tv.js";
script.async = true;
script.onload = () => {
console.log(123)
new window.TradingView.widget({
autosize: true,
symbol: symbol || "BTCUSDT",
interval: interval,
container_id: "tradingview_chart",
theme: 'dark',
datafeed: new BinanceDataFeed(),
library_path: "/charting_library/",
style: '1',
locale: 'en',
toolbar_bg: '#f1f3f6',
enable_publishing: false,
withdateranges: true,
// allow_symbol_change: true,s
hide_side_toolbar: false,
details: true,
studies: [],
});
};
document.body.appendChild(script);
// 清理函数
return () => {
// 在组件卸载时移除脚本
// document.body.removeChild(script);
script.remove();
};
}
}, [symbol, interval]);
return <div id="tradingview_chart" style={{ height: '100%', width: '100%' }}></div>;
};
export default TradingViewChart;
// global.d.ts
interface Window {
TradingView: any;
Datafeeds: any;
}
\ No newline at end of file
'use client';
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { WagmiProvider } from 'wagmi';
// import { useRouter } from 'next/router';
import { RainbowKitProvider, type Locale, darkTheme } from '@rainbow-me/rainbowkit';
import { config } from '../wagmi';
const queryClient = new QueryClient();
export function Providers({ children }: { children: React.ReactNode }) {
// const { locale } = useRouter() as { locale: Locale };
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient} >
<RainbowKitProvider locale={'en'} theme={darkTheme()}>{children}</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
);
}
export class BinanceDataFeed {
onReady(callback: (config: any) => void) {
console.log('onReady called');
const config = {
supports_marks: false,
supports_time: true,
supported_resolutions: ['1', '5', '15', '30', '60', 'D', 'W', 'M'],
};
setTimeout(() => callback(config), 0);
}
resolveSymbol(symbolName: string, onSymbolResolvedCallback: (symbolInfo: any) => void) {
console.log('resolveSymbol called with symbol:')
const symbolInfo = {
name: symbolName,
ticker: symbolName,
description: `${symbolName} on Binance`,
type: 'crypto',
session: '24x7',
exchange: 'Binance',
minmov: 1,
pricescale: 100,
has_intraday: true,
supported_resolutions: ['1', '5', '15', '30', '60', 'D', 'W', 'M'],
volume_precision: 2,
data_status: 'streaming',
};
setTimeout(() => onSymbolResolvedCallback(symbolInfo), 0);
}
getBars(
symbolInfo: any,
resolution: string,
from: number,
to: number,
onHistoryCallback: (bars: any[], { noData }: { noData: boolean }) => void,
onErrorCallback: (reason: string) => void
) {
console.log(`getBars called with symbol: ${symbolInfo.ticker}, resolution: ${resolution}, from: ${from}, to: ${to}`)
const interval = this.mapResolution(resolution);
fetch(
`https://api.binance.com/api/v3/klines?symbol=${symbolInfo.ticker}&interval=${interval}&startTime=${from * 1000}&endTime=${to * 1000}`
)
.then((response) => response.json())
.then((data) => {
const bars = data.map((item: any) => ({
time: item[0], // 开盘时间 (毫秒)
open: parseFloat(item[1]),
high: parseFloat(item[2]),
low: parseFloat(item[3]),
close: parseFloat(item[4]),
volume: parseFloat(item[5]),
}));
onHistoryCallback(bars, { noData: bars.length === 0 });
})
.catch((error) => {
console.error('Error fetching Binance data:', error);
onErrorCallback('Error fetching data');
});
}
subscribeBars(
symbolInfo: any,
resolution: string,
onRealtimeCallback: (bar: any) => void,
subscriberUID: string
) {
const interval = this.mapResolution(resolution);
const ws = new WebSocket(
`wss://stream.binance.com:9443/ws/${symbolInfo.ticker.toLowerCase()}@kline_${interval}`
);
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.k.x) {
const bar = {
time: message.k.t,
open: parseFloat(message.k.o),
high: parseFloat(message.k.h),
low: parseFloat(message.k.l),
close: parseFloat(message.k.c),
volume: parseFloat(message.k.v),
};
onRealtimeCallback(bar);
}
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
mapResolution(resolution: string): string {
const resolutionMap: { [key: string]: string } = {
'1': '1m',
'5': '5m',
'15': '15m',
'30': '30m',
'60': '1h',
'D': '1d',
'W': '1w',
'M': '1M',
};
return resolutionMap[resolution] || '1m';
}
}
\ No newline at end of file
import axios, { AxiosResponse } from 'axios';
import { useQuery, useMutation, UseQueryResult, UseMutationResult } from '@tanstack/react-query';
const BASE_URL = 'http://3.114.44.103:38088/api/v1';
const api = {
getPairList: () => axios.get(`${BASE_URL}/pair-list`),
getPairStat: (pair: string) => axios.get(`${BASE_URL}/pair-trade-info/${pair}`),
getPairOrderList: (pair: string) => axios.get(`${BASE_URL}/pair-order-list/${pair}`),
getPairTradeHistory: (pair: string) => axios.get(`${BASE_URL}/pair-trade-history/${pair}`),
makeOrder: (orderData: any) => axios.post(`${BASE_URL}/user-make-order`, orderData),
getUserOpenOrders: (data: any) => axios.post(`${BASE_URL}/user-open-orders`, data),
getUserOrderHistory: (data: any) => axios.post(`${BASE_URL}/user-order-history`, data),
getUserTradeHistory: (data: any) => axios.post(`${BASE_URL}/user-trade-history`, data),
};
// 封装的 get 请求,使用 react-query 的 useQuery 钩子
export const useGetPairList = (): UseQueryResult<AxiosResponse<any>, Error> => {
return useQuery({ queryKey: ['pairList'], queryFn: () => api.getPairList() });
};
export const useGetPairStat = (pair: string): UseQueryResult<any, Error> => {
return useQuery({ queryKey: ['pairStat', pair], queryFn: () => api.getPairStat(pair) });
};
export const useGetPairOrderList = (pair: string): UseQueryResult<any, Error> => {
return useQuery({ queryKey: ['pairOrderList', pair], queryFn: () => api.getPairOrderList(pair) });
};
export const useGetPairTradeHistory = (pair: string): UseQueryResult<any, Error> => {
return useQuery({ queryKey: ['pairTradeHistory', pair], queryFn: () => api.getPairTradeHistory(pair) });
};
// 封装的 post 请求,使用 react-query 的 useMutation 钩子
export const useMakeOrder = (onSuccessCallback: (data: any) => void): UseMutationResult<any, Error, any> => {
return useMutation({
mutationFn: (orderData: any) => api.makeOrder(orderData),
onSuccess: (data) => {
// 请求成功后执行的操作
console.log('Order placed successfully:', data);
onSuccessCallback(data); // 调用传入的回调函数
},
onError: (error) => {
// 请求失败时的操作
console.error('Error placing order:', error);
},
});
};
export const useGetUserOpenOrders = (): UseMutationResult<any, Error, any> => {
return useMutation({ mutationFn: (data: any) => api.getUserOpenOrders(data) });
};
export const useGetUserOrderHistory = (): UseMutationResult<any, Error, any> => {
return useMutation({ mutationFn: (data: any) => api.getUserOrderHistory(data) });
};
export const useGetUserTradeHistory = (): UseMutationResult<any, Error, any> => {
return useMutation({ mutationFn: (data:any) => api.getUserTradeHistory(data) });
};
import { getDefaultConfig, Chain } from '@rainbow-me/rainbowkit';
import {
arbitrum,
base,
mainnet,
optimism,
polygon,
sepolia,
} from 'wagmi/chains';
const dexTestnet = {
id: 100199,
name: 'DEX Testnet',
iconBackground: '#ffc431',
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
rpcUrls: {
default: { http: ['http://18.168.16.120:30088'] },
},
blockExplorers: {
default: { name: 'dex', url: 'https://snowtrace.io' },
},
} as const satisfies Chain;
export const config = getDefaultConfig({
appName: 'RainbowKit demo',
projectId: 'YOUR_PROJECT_ID',
chains: [
dexTestnet,
mainnet,
polygon,
optimism,
arbitrum,
base,
...(process.env.NEXT_PUBLIC_ENABLE_TESTNETS === 'true' ? [sepolia] : []),
],
ssr: true,
});
import type { Config } from "tailwindcss";
export default {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
data: {
'md-trade-footer-h': '24px',
'md-header-h': '64px',
},
},
},
plugins: [],
} satisfies Config;
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment