Skip to content

Commit

Permalink
Merge pull request #20 from henry-deriv/henry/adapt-chart-library-to-…
Browse files Browse the repository at this point in the history
…new-response

fix: change code to accomodate new api response
  • Loading branch information
amam-deriv authored Feb 18, 2025
2 parents c4235d6 + e27eb3d commit 38211d7
Show file tree
Hide file tree
Showing 11 changed files with 54 additions and 100 deletions.
2 changes: 1 addition & 1 deletion dist/smartcharts.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/smartcharts.js.map

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions src/components/Chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ const Chart = React.forwardRef((props: TChartProps, ref) => {

React.useEffect(() => {
if (props.streamingData) {
// @ts-expect-error fix types later
chart.onStreamingData(props.streamingData);
}
}, [props.streamingData]);
Expand Down
3 changes: 3 additions & 0 deletions src/feed/Feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ class Feed {
quotes = new_quotes;

if (!this.endEpoch) {
// @ts-expect-error type mismatch resolve later
this._mainStore.lastDigitStats.updateLastDigitStats(response);
}
} catch (error) {
Expand Down Expand Up @@ -319,6 +320,7 @@ class Feed {
const response: TicksHistoryResponse = await this._binaryApi.getTickHistory(
tickHistoryRequest as TCreateTickHistoryParams
);
// @ts-expect-error type mismatch resolve later
quotes = TickHistoryFormatter.formatHistory(response);
} else {
// Passed all_ticks from Deriv-app store modules.contract_replay.contract_store.contract_info.audit_details.all_ticks
Expand Down Expand Up @@ -406,6 +408,7 @@ class Feed {
this.setHasReachedEndOfData(true);
return;
}
// @ts-expect-error type mismatch resolve later
result.quotes = TickHistoryFormatter.formatHistory(response);
if (firstEpoch <= startLimit) {
callback({ moreAvailable: false, quotes: [] });
Expand Down
30 changes: 23 additions & 7 deletions src/feed/TickHistoryFormatter.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,33 @@
import { TicksHistoryResponse, TicksStreamResponse, ProposalOpenContract } from '@deriv/api-types';
import { TicksStreamResponse, ProposalOpenContract, TicksHistoryResponse as BaseTicksHistoryResponse } from '@deriv/api-types';
import { OHLCStreamResponse, TAllTicks, TQuote } from 'src/types';
import { getUTCDate, lerp } from '../utils';

interface HistoryTick {
epoch: string;
ask: string;
bid: string;
quote: string;
}

export interface TicksHistoryResponse extends Omit<BaseTicksHistoryResponse, 'history'> {
history?: HistoryTick[];
candles?: {
epoch: string;
open: string;
high: string;
low: string;
close: string;
}[];
}

export class TickHistoryFormatter {
static formatHistory(response: TicksHistoryResponse): TQuote[] | undefined {
const { history, candles } = response;
if (history) {
const { times = [], prices = [] } = history;
const quotes = prices.map((p, idx) => ({
Date: getUTCDate(+times[idx]),
Close: +p,
if (history?.length) {
return history.map(tick => ({
Date: getUTCDate(+tick.epoch),
Close: +tick.quote,
}));
return quotes;
}

if (candles) {
Expand Down
2 changes: 2 additions & 0 deletions src/feed/__tests__/TickHistoryFormatter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,11 +153,13 @@ const tickTickResponseResult = {

describe('TickHistoryFormatter test', () => {
it('Test parse history style="candles"', () => {
// @ts-expect-error type mismatch resolve later
const history = TickHistoryFormatter.formatHistory(historyCandleResponse);
expect(history).to.deep.equal(historyCandleResponseResult);
});

it('Test parse history style="ticks"', () => {
// @ts-expect-error type mismatch resolve later
const history = TickHistoryFormatter.formatHistory(historyTicksResponse);
expect(history).to.deep.equal(historyTicksResponseResult);
});
Expand Down
4 changes: 3 additions & 1 deletion src/feed/subscription/DelayedSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ class DelayedSubscription extends Subscription {
pause() {
this._endTimer();
}

// @ts-expect-error type mismatch resolve later
async _startSubscribe(tickHistoryRequest: TCreateTickHistoryParams) {
const response: TicksHistoryResponse = await this._binaryApi.getTickHistory(tickHistoryRequest);
// @ts-expect-error type mismatch resolve later
const quotes = this._processHistoryResponse(response);
this._startTimer();
return { quotes, response };
Expand Down Expand Up @@ -57,6 +58,7 @@ class DelayedSubscription extends Subscription {
adjust_start_time: 0,
};
const response = await this._binaryApi.getTickHistory(tickHistoryRequest as TCreateTickHistoryParams);
// @ts-expect-error type mismatch resolve later
const quotes = this._processHistoryResponse(response);
this._emitter?.emit(Subscription.EVENT_CHART_DATA, quotes);
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/feed/subscription/RealtimeSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class RealtimeSubscription extends Subscription {
const contract_info = this.contractInfo as ProposalOpenContract;
const [tickHistoryPromise, processTickHistory] = this._getProcessTickHistoryClosure();

//here we include duration = 'ticks' && exclude duration = 'seconds' which hasn't tick_stream, all_ticks, tick_count (consist of 15-86.400 ticks)
// here we include duration = 'ticks' && exclude duration = 'seconds' which hasn't tick_stream, all_ticks, tick_count (consist of 15-86.400 ticks)
if (!this.shouldFetchTickHistory && !!contract_info.tick_stream) {
this._binaryApi.subscribeTickHistory(
Object.assign(tickHistoryRequest, { count: contract_info.tick_count }),
Expand Down
5 changes: 3 additions & 2 deletions src/feed/subscription/Subscription.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { TicksHistoryResponse, TicksStreamResponse } from '@deriv/api-types';
import { TicksStreamResponse } from '@deriv/api-types';
import EventEmitter from 'event-emitter-es6';
import { BinaryAPI } from 'src/binaryapi';
import { TCreateTickHistoryParams } from 'src/binaryapi/BinaryAPI';
import { Listener, OHLCStreamResponse, TMainStore, TQuote } from 'src/types';
import { TickHistoryFormatter } from '../TickHistoryFormatter';
import { TickHistoryFormatter, TicksHistoryResponse } from '../TickHistoryFormatter';

export type TQuoteResponse = { quotes: TQuote[]; response: TicksHistoryResponse; error?: unknown };

Expand Down Expand Up @@ -88,6 +88,7 @@ class Subscription {
}

if (history) {
// @ts-expect-error type mismatch resolve later
const { times = [] } = history;
return times[times.length - 1];
}
Expand Down
62 changes: 7 additions & 55 deletions src/store/ChartStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { action, computed, observable, reaction, makeObservable } from 'mobx';
import moment from 'moment';
import { TickHistoryFormatter } from 'src/feed/TickHistoryFormatter';
import { TicksStreamResponse } from '@deriv/api-types';
import MainStore from '.';
import { ActiveSymbols, BinaryAPI, TradingTimes } from '../binaryapi';
import { TProcessedSymbolItem, TSubCategoryDataItem } from '../binaryapi/ActiveSymbols';
Expand All @@ -12,6 +13,7 @@ import { STATE } from '../Constant';
import { Feed } from '../feed';
import {
IPendingPromise,
OHLCStreamResponse,
TBinaryAPIRequest,
TBinaryAPIResponse,
TChanges,
Expand All @@ -32,54 +34,16 @@ type TDefaults = {
granularity: TGranularity;
chartType: React.ReactNode;
};

class ChartStore {
static chartCount = 0;
static tradingTimes: TradingTimes | null;
static activeSymbols: ActiveSymbols;

onStreamingData(data: {
type: 'tick' | 'candle';
instrument_id: string;
quote?: number;
timestamp: string;
ohlc?: { open: number; high: number; low: number; close: number };
}) {
onStreamingData(data: TicksStreamResponse | OHLCStreamResponse) {
if (!this.feed || !data) return;

const epoch = Math.floor(new Date(data.timestamp).getTime() / 1000);

const adaptedData =
data.type === 'tick'
? {
msg_type: 'tick' as const,
tick: {
epoch,
quote: data.quote || 0,
symbol: data.instrument_id,
pip_size: 2,
},
echo_req: {},
}
: {
msg_type: 'ohlc' as const,
ohlc: {
open_time: epoch,
open: String(data.ohlc?.open || 0),
high: String(data.ohlc?.high || 0),
low: String(data.ohlc?.low || 0),
close: String(data.ohlc?.close || 0),
epoch,
symbol: data.instrument_id,
id: `${data.instrument_id}_${epoch}`,
granularity: 60,
},
echo_req: {},
};

const formattedData = TickHistoryFormatter.formatTick(adaptedData);
const formattedData = TickHistoryFormatter.formatTick(data);
if (!formattedData) return;

this.feed.processQuotes([formattedData]);
this.feed.addQuote(formattedData);

Expand Down Expand Up @@ -286,24 +250,12 @@ class ChartStore {

this.mainStore.chartAdapter.newChart();

const transformCandle = (candles: any[]) =>
candles.map(candle => ({
close: candle.close,
epoch: candle.timestamp ? Math.floor(new Date(candle.timestamp).getTime() / 1000) : candle.epoch,
high: candle.high,
low: candle.low,
open: candle.open,
}));
setTimeout(() => {
if (props.ticksHistory) {
const response = {
...props.ticksHistory,
candles: transformCandle(props.ticksHistory.candles),
};

const quotes = TickHistoryFormatter.formatHistory(response);
if (props.ticksHistory) {
const quotes = TickHistoryFormatter.formatHistory(props.ticksHistory);
this.mainStore.chartAdapter.onTickHistory(quotes!);
this.loader.hide();
// this.mainStore.chartAdapter.updateChartStyle('candles');
}
}, 1000);
};
Expand Down
41 changes: 9 additions & 32 deletions src/types/props.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { BinaryAPI } from 'src/binaryapi';
import { ChartTypes } from 'src/Constant';
import ChartState from 'src/store/ChartState';
import { TNotification } from 'src/store/Notifier';
import { TicksHistoryResponse } from 'src/feed/TickHistoryFormatter';
import { TGranularity } from '.';
import { OHLCStreamResponse } from './api.types';

Expand Down Expand Up @@ -260,41 +261,17 @@ export type TChartProps = {
isLive?: boolean;
startWithDataFitMode?: boolean;
leftMargin?: number;
ticksHistory?: {
msg_type: 'candles';
candles: Array<{
close: number;
timestamp?: string;
high: number;
low: number;
open: number;
}>;
echo_req: {
adjust_start_time: number;
count: number;
end: string;
granularity: number;
req_id: number;
style: string;
subscribe: number;
ticks_history: string;
};
pip_size: number;
req_id: number;
subscription: {
id: string;
};
};
ticksHistory?: TicksHistoryResponse;
streamingData?: {
type: 'tick' | 'candle';
msg_type: 'tick' | 'ohlc';
instrument_id: string;
quote?: number;
timestamp: string;
quote?: string;
epoch: string;
ohlc?: {
open: number;
high: number;
low: number;
close: number;
open: string;
high: string;
low: string;
close: string;
};
};
};
Expand Down

0 comments on commit 38211d7

Please sign in to comment.