Skip to content

Commit

Permalink
Merge pull request #1536 from bancorprotocol/issue-#1504
Browse files Browse the repository at this point in the history
[Interactive Chart] Zoom & Pan
  • Loading branch information
GrandSchtroumpf authored Oct 15, 2024
2 parents 52b51c6 + a52dc25 commit 7140b69
Show file tree
Hide file tree
Showing 48 changed files with 280 additions and 102 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified e2e/screenshots/strategy/overlapping/Overlapping/create/form.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified e2e/screenshots/strategy/overlapping/Overlapping/deposit/form.png
Binary file modified e2e/screenshots/strategy/overlapping/Overlapping/undercut/form.png
Binary file modified e2e/screenshots/strategy/overlapping/Overlapping/withdraw/form.png
47 changes: 12 additions & 35 deletions src/components/strategies/common/StrategyChartHistory.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
D3ChartCandlesticks,
OnPriceUpdates,
} from 'components/strategies/common/d3Chart';
import { CandlestickData, D3ChartSettingsProps, D3ChartWrapper } from 'libs/d3';
import { D3ChartSettingsProps, D3ChartWrapper } from 'libs/d3';
import { useSearch } from '@tanstack/react-router';
import { useGetTokenPriceHistory } from 'libs/queries/extApi/tokenPrice';
import { TradeSearch } from 'libs/routing';
Expand Down Expand Up @@ -32,48 +32,27 @@ const chartSettings: D3ChartSettingsProps = {
const getBounds = (
order0: BaseOrder,
order1: BaseOrder,
data: CandlestickData[] = [],
direction?: 'none' | 'buy' | 'sell'
): ChartPrices => {
const min = Math.min(...data.map((d) => d.low)).toString();
const max = Math.max(...data.map((d) => d.high)).toString();
if (direction === 'none') {
return {
buy: { min, max },
sell: { min, max },
buy: { min: '', max: '' },
sell: { min: '', max: '' },
};
} else if (direction === 'buy') {
return {
buy: {
min: order0.min || '0',
max: order0.max || max,
},
sell: {
min: min,
max: max,
},
buy: { min: order0.min, max: order0.max },
sell: { min: '', max: '' },
};
} else if (direction === 'sell') {
return {
buy: {
min: min,
max: max,
},
sell: {
min: order1.min || '0',
max: order1.max || max,
},
buy: { min: '', max: '' },
sell: { min: order1.min, max: order1.max },
};
} else {
return {
buy: {
min: order0.min || min,
max: order0.max || max,
},
sell: {
min: order1.min || min,
max: order1.max || max,
},
buy: { min: order0.min, max: order0.max },
sell: { min: order1.min, max: order1.max },
};
}
};
Expand Down Expand Up @@ -112,9 +91,7 @@ export const StrategyChartHistory: FC<Props> = (props) => {
buy: { min: order0.min || '0', max: order0.max || '0' },
sell: { min: order1.min || '0', max: order1.max || '0' },
});
const [bounds, setBounds] = useState(
getBounds(order0, order1, [], direction)
);
const [bounds, setBounds] = useState(getBounds(order0, order1, direction));

const updatePrices: OnPriceUpdates = ({ buy, sell }) => {
const newPrices = {
Expand Down Expand Up @@ -149,8 +126,8 @@ export const StrategyChartHistory: FC<Props> = (props) => {
}, [order0.min, order0.max, order1.min, order1.max]);

useEffect(() => {
setBounds(getBounds(order0, order1, data, direction));
}, [order0, order1, data, direction]);
setBounds(getBounds(order0, order1, direction));
}, [order0, order1, direction]);

const priceChartType = config.ui.priceChart;
if (priceChartType === 'tradingView') {
Expand Down
98 changes: 79 additions & 19 deletions src/components/strategies/common/d3Chart/D3ChartCandlesticks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ import {
scaleBand,
D3ChartSettings,
} from 'libs/d3';
import { useMemo } from 'react';
import { useMemo, useState } from 'react';
import { prettifyNumber } from 'utils/helpers';
import { Candlesticks } from 'components/strategies/common/d3Chart/Candlesticks';
import { D3ChartDisposable } from './disposable/D3ChartDisposable';
import { TradeTypes } from 'libs/routing/routes/trade';
import { Activity } from 'libs/queries/extApi/activity';
import { D3ChartIndicators } from './D3ChartIndicators';
import { D3ZoomEvent, ZoomTransform, select, zoom } from 'd3';
import { D3Pointer } from './D3Pointer';

export type ChartPrices<T = string> = {
buy: { min: T; max: T };
Expand All @@ -42,6 +44,40 @@ export interface D3ChartCandlesticksProps {
activities?: Activity[];
}

const useZoom = (dms: D3ChartSettings, data: CandlestickData[]) => {
const [transform, setTransform] = useState<ZoomTransform>();
let k = 0;
const selection = select<SVGSVGElement, unknown>('#interactive-chart');
const chartArea = select<SVGSVGElement, unknown>('.chart-area');
const zoomHandler = zoom<SVGSVGElement, unknown>()
.scaleExtent([0.5, Math.ceil(data.length / 10)])
.translateExtent([
[-0.5 * dms.width, 0],
[1.5 * dms.width, 0],
])
.on('start', (e: D3ZoomEvent<Element, any>) => (k = e.transform.k))
.on('zoom', (e: D3ZoomEvent<Element, any>) => {
if (e.transform.k === k) chartArea.style('cursor', 'grab');
setTransform(e.transform);
})
.on('end', () => chartArea.style('cursor', ''));
selection.call(zoomHandler);
return transform;
};

const getDateRange = (range: number[]) => {
if (!range.length) return [];
const points: string[] = [];
const first = range[0];
const step = range[1] - first;
const start = Math.floor(-0.5 * range.length);
const end = Math.ceil(range.length * 1.5);
for (let i = start; i < end; i++) {
points.push((first + i * step).toString());
}
return points;
};

export const D3ChartCandlesticks = (props: D3ChartCandlesticksProps) => {
const {
data,
Expand All @@ -59,17 +95,32 @@ export const D3ChartCandlesticks = (props: D3ChartCandlesticksProps) => {
activities,
} = props;

const xScale = useMemo(
() =>
scaleBand()
.domain(data.map((d) => d.date.toString()))
.range([0, dms.boundedWidth])
.paddingInner(0.5),
[data, dms.boundedWidth]
);
const zoomTransform = useZoom(dms, data);

const xScale = useMemo(() => {
const zoomX = (d: number) => (zoomTransform ? zoomTransform.applyX(d) : d);
return scaleBand()
.domain(getDateRange(data.map((d) => d.date)))
.range([dms.boundedWidth * -0.5, dms.boundedWidth * 1.5].map(zoomX))
.paddingInner(0.5);
}, [data, dms.boundedWidth, zoomTransform]);

const xTicks = useMemo(() => {
const length = xScale.domain().length;
const ratio = Math.ceil(zoomTransform?.k ?? 1);
const target = Math.floor((dms.boundedWidth * ratio) / 80);
const numberOfTicks = Math.max(1, target);
const m = Math.ceil(length / numberOfTicks);
return xScale.domain().filter((_, i) => i % m === m - 1);
}, [dms.boundedWidth, xScale, zoomTransform]);

const yDomain = useMemo(() => {
const candles = data.filter((point) => xScale(point.date.toString())! > 0);
return getDomain(candles, bounds, marketPrice);
}, [bounds, data, marketPrice, xScale]);

const y = useLinearScale({
domain: getDomain(data, bounds, marketPrice),
domain: yDomain,
range: [dms.boundedHeight, 0],
domainTolerance: 0.1,
});
Expand All @@ -78,14 +129,31 @@ export const D3ChartCandlesticks = (props: D3ChartCandlesticksProps) => {
return (
<>
<Candlesticks xScale={xScale} yScale={y.scale} data={data} />
<D3Pointer xScale={xScale} yScale={y.scale} dms={dms} />
<rect
className="chart-area cursor-crosshair"
x="0"
y="0"
width={dms.boundedWidth}
height={dms.boundedHeight}
fillOpacity="0"
/>
{activities?.length && (
<D3ChartIndicators
xScale={xScale}
yScale={y.scale}
boundHeight={dms.boundedHeight}
activities={activities}
/>
)}
<XAxis xScale={xScale} dms={dms} xTicks={xTicks} />
<D3YAxisRight
ticks={y.ticks}
dms={dms}
formatter={(value) => {
return prettifyNumber(value, { decimals: 100, abbreviate: true });
}}
/>
<XAxis xScale={xScale} dms={dms} />
{marketPrice && (
<D3ChartHandleLine
dms={dms}
Expand Down Expand Up @@ -129,14 +197,6 @@ export const D3ChartCandlesticks = (props: D3ChartCandlesticksProps) => {
spread={Number(overlappingSpread)}
/>
)}
{activities?.length && (
<D3ChartIndicators
xScale={xScale}
yScale={y.scale}
boundHeight={dms.boundedHeight}
activities={activities}
/>
)}
</>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const D3ChartHandleLine = ({ lineProps, ...props }: Props) => {
const lineWidth = dms.boundedWidth + 5;

return (
<g className={selector}>
<g className={cn(selector, isDraggable && !readonly && 'cursor-ns-resize')}>
<line
x1={0}
x2={lineWidth}
Expand All @@ -45,10 +45,7 @@ export const D3ChartHandleLine = ({ lineProps, ...props }: Props) => {
/>
<g
transform={`translate(${lineWidth},-${handleDms.height / 2})`}
className={cn(
isDraggable && !readonly && 'cursor-ns-resize',
handleClassName
)}
className={handleClassName}
>
<rect y={y} {...handleDms} fill={color} rx={4} />
{label && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,16 @@ export const D3ChartIndicators = (props: D3ChartIndicatorsProps) => {
})}
{trades.map((indicator, i) => {
const { x, y } = indicator;
const isBelowAxis = yScale(y) > height - 10;
const translateY = Math.min(yScale(y), height - 10);
return (
<IndicatorTooltip key={i} indicator={indicator}>
<g transform={`translate(${xScale(x.toString())},${yScale(y)})`}>
<g transform={`translate(${xScale(x.toString())},${translateY})`}>
<circle
cx={xScale.bandwidth() / 2}
cy={xScale.bandwidth() / 2}
r={5}
fill="white"
fill={isBelowAxis ? 'url(#svg-brand-gradient)' : 'white'}
stroke="black"
/>
</g>
Expand Down
Loading

0 comments on commit 7140b69

Please sign in to comment.