Skip to content

Commit

Permalink
Add working ticker class
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewdowns committed Apr 9, 2021
1 parent 8c82a05 commit bc63b48
Show file tree
Hide file tree
Showing 8 changed files with 175 additions and 26 deletions.
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export * from './lib';
export { default as CryptoCurrencies } from './types/CryptoCurrencies';
export { default as FiatCurrencies } from './types/FiatCurrencies';
export { default as getCurrencySymbol } from './utils/getCurrencySymbol';
107 changes: 107 additions & 0 deletions src/lib/Ticker/Ticker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import CryptoCurrencies from '../../types/CryptoCurrencies';
import FiatCurrencies from '../../types/FiatCurrencies';
import getCurrencySymbol from '../../utils/getCurrencySymbol';

type TickerConfig = {
base: CryptoCurrencies | FiatCurrencies;
quote: CryptoCurrencies | FiatCurrencies;
frequency?: number;
request: () => Promise<number>;
onUpdate?: (price: number) => void;
onError?: (e: any) => void;
}

type TickerHistory = Array<{
price: number;
date: Date;
}>;

class Ticker {
private readonly _baseName: string;
private readonly _baseSymbol: string;

private readonly _quoteName: string;
private readonly _quoteSymbol: string;

private readonly _frequency: number;
private readonly _request: () => Promise<number>;
private readonly _onUpdate?: (price: number) => void;
private readonly _onError?: (e: any) => void;

private _price: number = 0;
private _history: TickerHistory = [];

private _interval: NodeJS.Timeout | undefined = undefined;
private _fetching: boolean = false;

constructor(config: TickerConfig) {
const baseSymbol = getCurrencySymbol(config.base);
if (!baseSymbol) throw new Error('Invalid base currency.');

const quoteSymbol = getCurrencySymbol(config.quote);
if (!quoteSymbol) throw new Error('Invalid quote currency.');

this._baseName = config.base.toString();
this._baseSymbol = baseSymbol;

this._quoteName = config.quote.toString();
this._quoteSymbol = quoteSymbol;

this._frequency = config.frequency || 1000;
this._request = config.request;
this._onUpdate = config.onUpdate;
this._onError = config.onError;
}

public get baseName(): string { return this._baseName; }
public get baseSymbol(): string { return this._baseSymbol; }

public get quoteName(): string { return this._quoteName; }
public get quoteSymbol(): string { return this._quoteSymbol; }

public get price(): number { return this._price; }
public get history(): TickerHistory { return this._history; }

public get active(): boolean { return this._interval !== undefined; }

public update(): void {
if (!this._fetching) {
this._fetching = true;
this._request()
.then(price => {
this._price = price;
this._history.push({ price, date: new Date() });
if (this._onUpdate) this._onUpdate(price);
})
.catch(e => {
if (this._onError) this._onError(e);
})
.finally(() => {
this._fetching = false;
});
}
}

public start(): void {
if (this._interval === undefined) {
this._interval = setInterval(() => {
this.update();
}, this._frequency);
}
}

public stop(): void {
if (this._interval !== undefined) {
clearTimeout(this._interval);
this._interval = undefined;
}
}

public reset(): void {
this.stop();
this._price = 0;
this._history = [];
}
}

export default Ticker;
1 change: 1 addition & 0 deletions src/lib/Ticker/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './Ticker';
1 change: 1 addition & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as Ticker } from './Ticker';
57 changes: 39 additions & 18 deletions src/types/CryptoCurrencies.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,43 @@
enum CryptoCurrencies {
ADA,
ALGO,
ATOM,
BNB,
BTC,
DASH,
DOT,
DAI,
DNT,
ETH,
GLM,
LINK,
LTC,
REN,
STORJ,
XLM,
XTZ,
XRP
AAVE = 'Aave',
ADA = 'Cardano',
ALGO = 'Algorland',
ATOM = 'Cosmos',
AVAX = 'Avalanche',
BAT = 'Basic Attention Token',
BCH = 'Bitcoin Cash',
BNB = 'Binance Coin',
BTC = 'Bitcoin',
BUSD = 'Binance USD',
COMP = 'Compound',
DASH = 'Dash',
DAI = 'Dai',
DOT = 'Polkadot',
DNT = 'District0x',
EOS = 'EOS',
ETC = 'Ethereum Classic',
ETH = 'Ethereum',
FIL = 'Filecoin',
GLM = 'Golem',
GRT = 'The Graph',
LINK = 'Chainlink',
LTC = 'Litecoin',
MKR = 'Maker',
NEO = 'Neo',
ONT = 'Ontology',
REN = 'Ren',
REP = 'Augur',
STORJ = 'Storj',
USDC = 'USD Coin',
USDT = 'Tether',
VET = 'VeChain',
XLM = 'Stellar',
XMR = 'Monero',
XTZ = 'Tezos',
XRP = 'Ripple',
YFI = 'yearn.finance',
ZEC = 'Zcash',
ZRX = '0x'
}

export default CryptoCurrencies;
11 changes: 9 additions & 2 deletions src/types/FiatCurrencies.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
enum FiatCurrencies {
AUD = 'Australian Dollar',
CAD = 'Canadian Dollar',
CHF = 'Swiss Franc',
CNY = 'Chinese Yuan',
EUR = 'Euro',
USD = 'US Dollar'
GBP = 'Pound Sterling',
JPY = 'Japanese Yen',
MXN = 'Mexican Peso',
USD = 'United States Dollar'
}

export default FiatCurrencies;
export default FiatCurrencies;
14 changes: 14 additions & 0 deletions src/utils/getCurrencySymbol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import CryptoCurrencies from '../types/CryptoCurrencies';
import FiatCurrencies from '../types/FiatCurrencies';

function getCurrencySymbol(currency: CryptoCurrencies | FiatCurrencies): string | undefined {
return Object.keys(CryptoCurrencies).find(key => {
const crypto = CryptoCurrencies[key as keyof typeof CryptoCurrencies];
if (currency === crypto) return key;
}) || Object.keys(FiatCurrencies).find(key => {
const fiat = FiatCurrencies[key as keyof typeof FiatCurrencies];
if (currency === fiat) return key;
});
}

export default getCurrencySymbol;
8 changes: 2 additions & 6 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"compilerOptions": {
"target": "ESNEXT",
"module": "ESNEXT",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
Expand All @@ -10,10 +10,6 @@
"removeComments": false,
"strict": true,
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"~types/*": ["./src/types/*"]
},
"esModuleInterop": true,
"resolveJsonModule": true,
"experimentalDecorators": true,
Expand All @@ -27,4 +23,4 @@
"exclude": [
"node_modules"
]
}
}

0 comments on commit bc63b48

Please # to comment.