laplace-api 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/jest.config.js CHANGED
@@ -2,4 +2,5 @@ module.exports = {
2
2
  preset: 'ts-jest',
3
3
  testEnvironment: 'node',
4
4
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
5
+ rootDir: './src',
5
6
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "laplace-api",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Client library for Laplace API for the US stock market and BIST (Istanbul stock market) fundamental financial data.",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -35,14 +35,18 @@
35
35
  },
36
36
  "homepage": "https://github.com/Laplace-Analytics/laplace-api-js#readme",
37
37
  "dependencies": {
38
+ "@types/uuid": "^10.0.0",
38
39
  "axios": "^1.7.7",
39
40
  "dotenv": "^16.4.5",
40
41
  "envalid": "^8.0.0",
42
+ "event-source-polyfill": "^1.0.31",
41
43
  "mongodb": "^6.8.0",
44
+ "uuid": "^10.0.0",
42
45
  "winston": "^3.14.2"
43
46
  },
44
47
  "devDependencies": {
45
48
  "@types/axios": "^0.14.0",
49
+ "@types/event-source-polyfill": "^1.0.5",
46
50
  "@types/jest": "^29.5.12",
47
51
  "@types/mongodb": "^4.0.7",
48
52
  "@types/node": "^22.5.4",
@@ -0,0 +1,92 @@
1
+ import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+ import { Logger } from 'winston';
3
+ import { LaplaceConfiguration } from '../utilities/configuration';
4
+ import { EventSourcePolyfill } from 'event-source-polyfill';
5
+
6
+
7
+ export class Client {
8
+ private cli: AxiosInstance;
9
+ private baseUrl: string;
10
+ private apiKey: string;
11
+ private logger: Logger;
12
+
13
+ constructor(cfg: LaplaceConfiguration, logger: Logger) {
14
+ this.cli = axios.create();
15
+ this.baseUrl = cfg.baseURL;
16
+ this.apiKey = cfg.apiKey;
17
+ this.logger = logger;
18
+ }
19
+
20
+ async sendRequest<T>(config: AxiosRequestConfig): Promise<T> {
21
+ try {
22
+ const response = await this.cli.request<T>({
23
+ ...config,
24
+ baseURL: this.baseUrl,
25
+ headers: {
26
+ ...config.headers,
27
+ Authorization: `Bearer ${this.apiKey}`,
28
+ },
29
+ });
30
+
31
+ return response.data;
32
+ } catch (error) {
33
+ if (axios.isAxiosError(error) && error.response) {
34
+ throw new Error(`Unexpected status code: ${error.response.status}, body: ${JSON.stringify(error.response.data)}`);
35
+ }
36
+ throw error;
37
+ }
38
+ }
39
+
40
+ sendSSERequest<T>(url: string): { events: AsyncIterable<T>, cancel: () => void } {
41
+ const source = axios.CancelToken.source();
42
+ var apiKey = this.apiKey;
43
+
44
+ const events: AsyncIterable<T> = {
45
+ async *[Symbol.asyncIterator]() {
46
+ try {
47
+ const response = await axios.get(url, {
48
+ headers: {
49
+ Authorization: `Bearer ${apiKey}`,
50
+ },
51
+ responseType: 'stream',
52
+ cancelToken: source.token,
53
+ });
54
+
55
+ const reader = response.data;
56
+ const decoder = new TextDecoder();
57
+
58
+ for await (const chunk of reader) {
59
+ const text = decoder.decode(chunk);
60
+ const lines = text.split('\n').filter(line => line.trim() !== '');
61
+
62
+ for (const line of lines) {
63
+ if (line.startsWith('data: ')) {
64
+ const data = line.slice(6);
65
+ try {
66
+ const parsedData = JSON.parse(data) as T;
67
+ yield parsedData;
68
+ } catch (error) {
69
+ console.error(`Error parsing event data: ${error}`);
70
+ }
71
+ }
72
+ }
73
+ }
74
+ } catch (error) {
75
+ if (!axios.isCancel(error)) {
76
+ console.error(`SSE error: ${error}`);
77
+ }
78
+ }
79
+ },
80
+ };
81
+
82
+ const cancel = () => {
83
+ source.cancel('Request cancelled by user');
84
+ };
85
+
86
+ return { events, cancel };
87
+ }
88
+ }
89
+
90
+ export function createClient(cfg: LaplaceConfiguration, logger: Logger): Client {
91
+ return new Client(cfg, logger);
92
+ }
@@ -19,6 +19,10 @@ export enum Locale {
19
19
  En = 'en',
20
20
  }
21
21
 
22
+ export enum SortBy {
23
+ PriceChange = "price_change"
24
+ }
25
+
22
26
  export interface Collection {
23
27
  id: string;
24
28
  title: string;
@@ -0,0 +1,93 @@
1
+ import { Client } from './client';
2
+ import { Collection, CollectionDetail, CollectionType, Region, Locale, SortBy } from './collections';
3
+
4
+ export enum CollectionStatus {
5
+ Active = 'active',
6
+ Inactive = 'inactive',
7
+ }
8
+
9
+ export interface LocaleString {
10
+ [key: string]: string;
11
+ }
12
+
13
+ export interface CreateCustomThemeParams {
14
+ title: LocaleString;
15
+ description?: LocaleString;
16
+ region?: Region[];
17
+ image_url?: string;
18
+ image?: string;
19
+ avatar_url?: string;
20
+ stocks: string[]; // Using string instead of ObjectID
21
+ order?: number;
22
+ status: CollectionStatus;
23
+ meta_data?: Record<string, any>;
24
+ }
25
+
26
+ export interface UpdateCustomThemeParams {
27
+ title?: LocaleString;
28
+ description?: LocaleString;
29
+ image_url?: string;
30
+ image?: string;
31
+ avatar_url?: string;
32
+ stockIds?: string[]; // Using string instead of ObjectID
33
+ status?: CollectionStatus;
34
+ meta_data?: Record<string, any>;
35
+ }
36
+
37
+ export class CustomThemeClient extends Client {
38
+ private async getAllCollectionsPrivate(collectionType: CollectionType, locale: Locale): Promise<Collection[]> {
39
+ return this.sendRequest<Collection[]>({
40
+ method: 'GET',
41
+ url: `/api/v1/${collectionType}`,
42
+ params: { locale },
43
+ });
44
+ }
45
+
46
+ private async getCollectionDetailPrivate(id: string, collectionType: CollectionType, locale: Locale, sortBy: SortBy | null): Promise<CollectionDetail> {
47
+ var params = {}
48
+ if (sortBy) {
49
+ params = { locale, sortBy };
50
+ } else {
51
+ params = { locale };
52
+ }
53
+ return this.sendRequest<CollectionDetail>({
54
+ method: 'GET',
55
+ url: `/api/v1/${collectionType}/${id}`,
56
+ params: params,
57
+ });
58
+ }
59
+
60
+
61
+ async getAllCustomThemes(locale: Locale): Promise<Collection[]> {
62
+ return this.getAllCollectionsPrivate(CollectionType.CustomTheme, locale);
63
+ }
64
+
65
+ async getCustomThemeDetail(id: string, locale: Locale, sortBy: SortBy): Promise<CollectionDetail> {
66
+ return this.getCollectionDetailPrivate(id, CollectionType.CustomTheme, locale, sortBy);
67
+ }
68
+
69
+ async createCustomTheme(params: CreateCustomThemeParams): Promise<string> {
70
+ const response = await this.sendRequest<string>({
71
+ method: 'POST',
72
+ url: `/api/v1/custom-theme`,
73
+ data: params,
74
+ });
75
+
76
+ return response;
77
+ }
78
+
79
+ async updateCustomTheme(id: string, params: UpdateCustomThemeParams): Promise<void> {
80
+ await this.sendRequest<void>({
81
+ method: 'PATCH',
82
+ url: `/api/v1/custom-theme/${id}`,
83
+ data: params,
84
+ });
85
+ }
86
+
87
+ async deleteCustomTheme(id: string): Promise<void> {
88
+ await this.sendRequest<void>({
89
+ method: 'DELETE',
90
+ url: `/api/v1/custom-theme/${id}`,
91
+ });
92
+ }
93
+ }
@@ -0,0 +1,78 @@
1
+ import { Client } from './client';
2
+ import { Region } from './collections';
3
+
4
+ export interface StockDividend {
5
+ date: Date;
6
+ dividendAmount: number;
7
+ dividendRatio: number;
8
+ netDividendAmount: number;
9
+ netDividendRatio: number;
10
+ priceThen: number;
11
+ }
12
+
13
+ export interface StockStats {
14
+ previousClose: number;
15
+ ytdReturn: number;
16
+ yearlyReturn: number;
17
+ marketCap: number;
18
+ peRatio: number;
19
+ pbRatio: number;
20
+ yearLow: number;
21
+ yearHigh: number;
22
+ threeYear: number;
23
+ fiveYear: number;
24
+ symbol: string;
25
+ }
26
+
27
+ export enum StockStatsKey {
28
+ PreviousClose = 'previous_close',
29
+ YtdReturn = 'ytd_return',
30
+ YearlyReturn = 'yearly_return',
31
+ MarketCap = 'market_cap',
32
+ FK = 'fk',
33
+ PDDD = 'pddd',
34
+ YearLow = 'year_low',
35
+ YearHigh = 'year_high',
36
+ ThreeYearReturn = '3_year_return',
37
+ FiveYearReturn = '5_year_return',
38
+ LatestPrice = 'latest_price'
39
+ }
40
+
41
+ export interface TopMover {
42
+ symbol: string;
43
+ percentChange: number;
44
+ }
45
+ export class FinancialFundamentalsClient extends Client {
46
+ async getStockDividends(symbol: string, region: Region): Promise<StockDividend[]> {
47
+ const url = new URL(`${this['baseUrl']}/api/v1/stock/dividends`);
48
+ url.searchParams.append('symbol', symbol);
49
+ url.searchParams.append('region', region);
50
+
51
+ return this.sendRequest<StockDividend[]>({
52
+ method: 'GET',
53
+ url: url.toString(),
54
+ });
55
+ }
56
+
57
+ async getStockStats(symbols: string[], keys: StockStatsKey[], region: Region): Promise<StockStats[]> {
58
+ const url = new URL(`${this['baseUrl']}/api/v1/stock/stats`);
59
+ url.searchParams.append('symbols', symbols.join(','));
60
+ url.searchParams.append('region', region);
61
+ url.searchParams.append('keys', keys.join(','));
62
+
63
+ return this.sendRequest<StockStats[]>({
64
+ method: 'GET',
65
+ url: url.toString(),
66
+ });
67
+ }
68
+
69
+ async getTopMovers(region: Region): Promise<TopMover[]> {
70
+ const url = new URL(`${this['baseUrl']}/api/v1/stock/top-movers`);
71
+ url.searchParams.append('region', region);
72
+
73
+ return this.sendRequest<TopMover[]>({
74
+ method: 'GET',
75
+ url: url.toString(),
76
+ });
77
+ }
78
+ }
@@ -0,0 +1,162 @@
1
+ import { Client } from './client';
2
+ import { Region, Locale } from './collections';
3
+
4
+ export interface StockSectorFinancialRatioComparison {
5
+ metric_name: string;
6
+ normalizedValue: number;
7
+ details: StockSectorFinancialRatioComparisonDetail[];
8
+ }
9
+
10
+ export interface StockSectorFinancialRatioComparisonDetail {
11
+ slug: string;
12
+ value: number;
13
+ sectorAverage: number;
14
+ }
15
+
16
+ export interface StockHistoricalRatios {
17
+ symbol: string;
18
+ data: StockHistoricalRatiosData[];
19
+ formatting: Record<string, StockHistoricalRatiosFormatting>;
20
+ }
21
+
22
+ export interface StockHistoricalRatiosData {
23
+ fiscalYear: number;
24
+ fiscalQuarter: number;
25
+ values: Record<string, StockHistoricalRatiosValue>;
26
+ }
27
+
28
+ export interface StockHistoricalRatiosValue {
29
+ value: number;
30
+ sectorAverage: number;
31
+ }
32
+
33
+ export interface StockHistoricalRatiosFormatting {
34
+ slug: string;
35
+ precision: number;
36
+ multiplier: number;
37
+ suffix: string;
38
+ prefix: string;
39
+ interval: string;
40
+ description: string;
41
+ }
42
+
43
+ export enum HistoricalRatiosKey {
44
+ PriceToEarningsRatio = 'pe-ratio',
45
+ ReturnOnEquity = 'roe',
46
+ ReturnOnAssets = 'roa',
47
+ ReturnOnCapital = 'roic',
48
+ }
49
+
50
+ export interface StockHistoricalRatiosDescription {
51
+ slug: string;
52
+ name: string;
53
+ suffix: string;
54
+ prefix: string;
55
+ display: boolean;
56
+ precision: number;
57
+ multiplier: number;
58
+ description: string;
59
+ interval: string;
60
+ }
61
+
62
+ export interface HistoricalFinancialSheets {
63
+ sheets: HistoricalFinancialSheet[];
64
+ }
65
+
66
+ export interface HistoricalFinancialSheet {
67
+ period: string;
68
+ rows: HistoricalFinancialSheetRow[];
69
+ }
70
+
71
+ export interface HistoricalFinancialSheetRow {
72
+ description: string;
73
+ value: number;
74
+ lineCodeId: number;
75
+ indentLevel: number;
76
+ firstAncestorLineCodeId: number;
77
+ sectionLineCodeId: number;
78
+ }
79
+
80
+ export enum FinancialSheetType {
81
+ IncomeStatement = 'incomeStatement',
82
+ BalanceSheet = 'balanceSheet',
83
+ CashFlow = 'cashFlowStatement',
84
+ }
85
+
86
+ export enum FinancialSheetPeriod {
87
+ Annual = 'annual',
88
+ Quarterly = 'quarterly',
89
+ Cumulative = 'cumulative',
90
+ }
91
+
92
+ export enum Currency {
93
+ USD = 'USD',
94
+ TRY = 'TRY',
95
+ EUR = 'EUR',
96
+ }
97
+
98
+ export interface FinancialSheetDate {
99
+ day: number;
100
+ month: number;
101
+ year: number;
102
+ }
103
+
104
+ export class FinancialClient extends Client {
105
+ async getFinancialRatioComparison(symbol: string, region: Region): Promise<StockSectorFinancialRatioComparison[]> {
106
+ const url = new URL(`${this['baseUrl']}/api/v1/stock/financial-ratio-comparison`);
107
+ url.searchParams.append('symbol', symbol);
108
+ url.searchParams.append('region', region);
109
+
110
+ return this.sendRequest<StockSectorFinancialRatioComparison[]>({
111
+ method: 'GET',
112
+ url: url.toString(),
113
+ });
114
+ }
115
+
116
+ async getHistoricalRatios(symbol: string, keys: HistoricalRatiosKey[], region: Region): Promise<StockHistoricalRatios> {
117
+ const url = new URL(`${this['baseUrl']}/api/v1/stock/historical-ratios`);
118
+ url.searchParams.append('symbol', symbol);
119
+ url.searchParams.append('region', region);
120
+ url.searchParams.append('slugs', keys.join(','));
121
+
122
+ return this.sendRequest<StockHistoricalRatios>({
123
+ method: 'GET',
124
+ url: url.toString(),
125
+ });
126
+ }
127
+
128
+ async getHistoricalRatiosDescriptions(locale: Locale, region: Region): Promise<StockHistoricalRatiosDescription[]> {
129
+ const url = new URL(`${this['baseUrl']}/api/v1/stock/historical-ratios/descriptions`);
130
+ url.searchParams.append('locale', locale);
131
+ url.searchParams.append('region', region);
132
+
133
+ return this.sendRequest<StockHistoricalRatiosDescription[]>({
134
+ method: 'GET',
135
+ url: url.toString(),
136
+ });
137
+ }
138
+
139
+ async getHistoricalFinancialSheets(
140
+ symbol: string,
141
+ from: FinancialSheetDate,
142
+ to: FinancialSheetDate,
143
+ sheetType: FinancialSheetType,
144
+ period: FinancialSheetPeriod,
145
+ currency: Currency,
146
+ region: Region
147
+ ): Promise<HistoricalFinancialSheets> {
148
+ const url = new URL(`${this['baseUrl']}/api/v1/stock/historical-financial-sheets`);
149
+ url.searchParams.append('symbol', symbol);
150
+ url.searchParams.append('from', `${from.year.toString().padStart(4, '0')}-${from.month.toString().padStart(2, '0')}-${from.day.toString().padStart(2, '0')}`);
151
+ url.searchParams.append('to', `${to.year.toString().padStart(4, '0')}-${to.month.toString().padStart(2, '0')}-${to.day.toString().padStart(2, '0')}`);
152
+ url.searchParams.append('sheetType', sheetType);
153
+ url.searchParams.append('periodType', period);
154
+ url.searchParams.append('currency', currency);
155
+ url.searchParams.append('region', region);
156
+
157
+ return this.sendRequest<HistoricalFinancialSheets>({
158
+ method: 'GET',
159
+ url: url.toString(),
160
+ });
161
+ }
162
+ }
@@ -0,0 +1,44 @@
1
+ import { Client } from './client';
2
+ import { Region } from './collections';
3
+ import { v4 as uuidv4 } from 'uuid';
4
+
5
+ async function* getLivePrice<T>(
6
+ client: Client,
7
+ symbols: string[],
8
+ region: Region
9
+ ): AsyncGenerator<T, void, undefined> {
10
+ const streamId = uuidv4();
11
+ const url = `${client["baseUrl"]}/api/v1/stock/price/live?filter=${symbols.join(',')}&region=${region}&stream=${streamId}`;
12
+
13
+ const { events, cancel } = client.sendSSERequest<T>(url);
14
+
15
+ try {
16
+ yield* events;
17
+ } finally {
18
+ cancel();
19
+ }
20
+ }
21
+
22
+ export interface BISTStockLiveData {
23
+ s: string; // Symbol
24
+ ch: number; // DailyPercentChange
25
+ p: number; // ClosePrice
26
+ }
27
+
28
+ export interface USStockLiveData {
29
+ s: string; // Symbol
30
+ bp: number; // BidPrice
31
+ ap: number; // AskPrice
32
+ }
33
+
34
+ export class LivePriceClient {
35
+ constructor(private client: Client) {}
36
+
37
+ getLivePriceForBIST(symbols: string[], region: Region): AsyncGenerator<BISTStockLiveData, void, undefined> {
38
+ return getLivePrice<BISTStockLiveData>(this.client, symbols, region);
39
+ }
40
+
41
+ getLivePriceForUS(symbols: string[], region: Region): AsyncGenerator<USStockLiveData, void, undefined> {
42
+ return getLivePrice<USStockLiveData>(this.client, symbols, region);
43
+ }
44
+ }
@@ -3,7 +3,7 @@ import * as dotenv from 'dotenv';
3
3
  import { findModuleRoot } from '../utilities/fs';
4
4
  import { loadGlobal, LaplaceConfiguration } from '../utilities/configuration';
5
5
 
6
- const testConfig = './utilities/test.env';
6
+ const testConfig = './src/utilities/test.env';
7
7
 
8
8
  class ClientTestSuite {
9
9
  config: LaplaceConfiguration | null = null;
@@ -0,0 +1,123 @@
1
+ import { Logger } from 'winston';
2
+ import { LaplaceConfiguration } from '../utilities/configuration';
3
+ import { CustomThemeClient, CollectionStatus, CreateCustomThemeParams, UpdateCustomThemeParams } from '../client/custom_theme';
4
+ import { Region, Locale, SortBy } from '../client/collections';
5
+ import { Stock, StockClient } from '../client/stocks';
6
+ import './client_test_suite';
7
+
8
+ describe('CustomTheme', () => {
9
+ let client: CustomThemeClient;
10
+ let stocksClient: StockClient;
11
+
12
+ beforeAll(() => {
13
+ const config = (global as any).testSuite.config as LaplaceConfiguration;
14
+ const logger: Logger = {
15
+ info: jest.fn(),
16
+ error: jest.fn(),
17
+ warn: jest.fn(),
18
+ debug: jest.fn(),
19
+ } as unknown as Logger;
20
+
21
+ client = new CustomThemeClient(config, logger);
22
+ stocksClient = new StockClient(config, logger);
23
+ });
24
+
25
+ test('GetAllCustomThemes', async () => {
26
+ const resp = await client.getAllCustomThemes(Locale.Tr);
27
+ expect(resp).not.toBeEmpty();
28
+ });
29
+
30
+ test('CreateUpdateDeleteCustomTheme', async () => {
31
+ const stocks = await stocksClient.getAllStocks(Region.Tr);
32
+ expect(stocks).not.toBeEmpty();
33
+
34
+ const createParams: CreateCustomThemeParams = {
35
+ title: {
36
+ [Locale.Tr]: 'Test Custom Theme',
37
+ },
38
+ description: {
39
+ [Locale.Tr]: 'Test Custom Theme Description',
40
+ },
41
+ region: [Region.Tr],
42
+ image_url: 'Test Custom Theme Image URL',
43
+ image: 'Test Custom Theme Image',
44
+ avatar_url: 'Test Custom Theme Avatar Image',
45
+ stocks: [stocks[0].id, stocks[1].id],
46
+ status: CollectionStatus.Active,
47
+ };
48
+
49
+ const id = await testCreateCustomTheme(client, createParams);
50
+ await testGetDetails(id, Locale.Tr, client, createParams);
51
+
52
+ let updateParams: UpdateCustomThemeParams = {
53
+ stockIds: [stocks[0].id, stocks[2].id],
54
+ };
55
+ await testUpdateCustomTheme(id, client, updateParams);
56
+ applyUpdateParams(updateParams, createParams);
57
+ await testGetDetails(id, Locale.Tr, client, createParams);
58
+
59
+ updateParams = {
60
+ title: {
61
+ [Locale.Tr]: 'Test Custom Theme Title Updated',
62
+ [Locale.En]: 'Test Custom Theme Title Updated',
63
+ },
64
+ description: {
65
+ [Locale.Tr]: 'Test Custom Theme Description Updated',
66
+ [Locale.En]: 'Test Custom Theme Description Updated',
67
+ },
68
+ };
69
+ await testUpdateCustomTheme(id, client, updateParams);
70
+ applyUpdateParams(updateParams, createParams);
71
+ await testGetDetails(id, Locale.Tr, client, createParams);
72
+ await testGetDetails(id, Locale.En, client, createParams);
73
+
74
+ updateParams = {
75
+ status: CollectionStatus.Inactive,
76
+ };
77
+ await testUpdateCustomTheme(id, client, updateParams);
78
+ applyUpdateParams(updateParams, createParams);
79
+ await testGetDetails(id, Locale.Tr, client, createParams);
80
+
81
+ await testDeleteCustomTheme(id, client);
82
+ await expect(client.getCustomThemeDetail(id, Locale.Tr, SortBy.PriceChange)).rejects.toThrow();
83
+ }, 10000); // Increase the timeout value to 10000 milliseconds);
84
+ });
85
+
86
+ async function testCreateCustomTheme(client: CustomThemeClient, createParams: CreateCustomThemeParams): Promise<string> {
87
+ const resp = await client.createCustomTheme(createParams);
88
+ expect(resp).not.toBeEmpty();
89
+ return resp;
90
+ }
91
+
92
+ async function testGetDetails(id: string, locale: Locale, client: CustomThemeClient, createParams: CreateCustomThemeParams) {
93
+ const resp = await client.getCustomThemeDetail(id, locale, SortBy.PriceChange);
94
+ expect(resp).not.toBeEmpty();
95
+
96
+ expect(resp.title).toBe(createParams.title[locale]);
97
+ expect(resp.description).toBe(createParams.description?.[locale]);
98
+ expect(resp.region).toEqual(createParams.region);
99
+ expect(resp.imageUrl).toBe(createParams.image_url);
100
+ expect(resp.image).toBe(createParams.image);
101
+ expect(resp.avatarUrl).toBe(createParams.avatar_url);
102
+ expect(resp.stocks.map((stock: Stock) => stock.id)).toEqual(createParams.stocks);
103
+ expect(resp.status).toBe(createParams.status);
104
+ }
105
+
106
+ async function testUpdateCustomTheme(id: string, client: CustomThemeClient, updateParams: UpdateCustomThemeParams) {
107
+ await client.updateCustomTheme(id, updateParams);
108
+ }
109
+
110
+ function applyUpdateParams(updateParams: UpdateCustomThemeParams, createParams: CreateCustomThemeParams) {
111
+ if (updateParams.stockIds) createParams.stocks = updateParams.stockIds;
112
+ if (updateParams.title) createParams.title = updateParams.title;
113
+ if (updateParams.description) createParams.description = updateParams.description;
114
+ if (updateParams.image_url) createParams.image_url = updateParams.image_url;
115
+ if (updateParams.image) createParams.image = updateParams.image;
116
+ if (updateParams.avatar_url) createParams.avatar_url = updateParams.avatar_url;
117
+ if (updateParams.status) createParams.status = updateParams.status;
118
+ if (updateParams.meta_data) createParams.meta_data = updateParams.meta_data;
119
+ }
120
+
121
+ async function testDeleteCustomTheme(id: string, client: CustomThemeClient) {
122
+ await client.deleteCustomTheme(id);
123
+ }
@@ -0,0 +1,51 @@
1
+ import { Logger } from 'winston';
2
+ import { LaplaceConfiguration } from '../utilities/configuration';
3
+ import { Client, createClient } from '../client/client';
4
+ import { FinancialFundamentalsClient } from '../client/financial_fundamentals';
5
+ import { Region } from '../client/collections';
6
+ import { StockStatsKey } from '../client/financial_fundamentals';
7
+ import './client_test_suite';
8
+
9
+ describe('FinancialFundamentals', () => {
10
+ let client: Client;
11
+ let stockClient: FinancialFundamentalsClient;
12
+
13
+ beforeAll(() => {
14
+ const config = (global as any).testSuite.config as LaplaceConfiguration;
15
+ const logger: Logger = {
16
+ info: jest.fn(),
17
+ error: jest.fn(),
18
+ warn: jest.fn(),
19
+ debug: jest.fn(),
20
+ } as unknown as Logger;
21
+
22
+ stockClient = new FinancialFundamentalsClient(config, logger);
23
+ });
24
+
25
+ test('GetStockDividends', async () => {
26
+ const resp = await stockClient.getStockDividends('TUPRS', Region.Tr);
27
+ expect(resp).not.toBeEmpty();
28
+ });
29
+
30
+ test('GetStockStats', async () => {
31
+ const resp = await stockClient.getStockStats(['TUPRS'], [
32
+ StockStatsKey.PreviousClose,
33
+ StockStatsKey.YtdReturn,
34
+ StockStatsKey.YearlyReturn,
35
+ StockStatsKey.MarketCap,
36
+ StockStatsKey.FK,
37
+ StockStatsKey.PDDD,
38
+ StockStatsKey.YearLow,
39
+ StockStatsKey.YearHigh,
40
+ StockStatsKey.ThreeYearReturn,
41
+ StockStatsKey.FiveYearReturn,
42
+ StockStatsKey.LatestPrice,
43
+ ], Region.Tr);
44
+ expect(resp).not.toBeEmpty();
45
+ });
46
+
47
+ test('GetTopMovers', async () => {
48
+ const resp = await stockClient.getTopMovers(Region.Tr);
49
+ expect(resp).not.toBeEmpty();
50
+ });
51
+ });
@@ -0,0 +1,51 @@
1
+ import { Logger } from 'winston';
2
+ import { LaplaceConfiguration } from '../utilities/configuration';
3
+ import { Client, createClient } from '../client/client';
4
+ import { FinancialClient, HistoricalRatiosKey, FinancialSheetType, FinancialSheetPeriod, Currency } from '../client/financial_ratios';
5
+ import { Region, Locale } from '../client/collections';
6
+ import './client_test_suite';
7
+
8
+ describe('FinancialRatios', () => {
9
+ let client: Client;
10
+ let financialClient: FinancialClient;
11
+
12
+ beforeAll(() => {
13
+ const config = (global as any).testSuite.config as LaplaceConfiguration;
14
+ const logger: Logger = {
15
+ info: jest.fn(),
16
+ error: jest.fn(),
17
+ warn: jest.fn(),
18
+ debug: jest.fn(),
19
+ } as unknown as Logger;
20
+
21
+ financialClient = new FinancialClient(config, logger);
22
+ });
23
+
24
+ test('GetFinancialRatioComparison', async () => {
25
+ const resp = await financialClient.getFinancialRatioComparison('TUPRS', Region.Tr);
26
+ expect(resp).not.toBeEmpty();
27
+ });
28
+
29
+ test('GetHistoricalRatios', async () => {
30
+ const resp = await financialClient.getHistoricalRatios('TUPRS', [HistoricalRatiosKey.PriceToEarningsRatio], Region.Tr);
31
+ expect(resp).not.toBeEmpty();
32
+ });
33
+
34
+ test('GetHistoricalRatiosDescriptions', async () => {
35
+ const resp = await financialClient.getHistoricalRatiosDescriptions(Locale.Tr, Region.Tr);
36
+ expect(resp).not.toBeEmpty();
37
+ });
38
+
39
+ test('GetHistoricalFinancialSheets', async () => {
40
+ const resp = await financialClient.getHistoricalFinancialSheets(
41
+ 'TUPRS',
42
+ { year: 2022, month: 1, day: 1 },
43
+ { year: 2023, month: 1, day: 1 },
44
+ FinancialSheetType.BalanceSheet,
45
+ FinancialSheetPeriod.Annual,
46
+ Currency.EUR,
47
+ Region.Tr
48
+ );
49
+ expect(resp).not.toBeEmpty();
50
+ });
51
+ });
@@ -0,0 +1,57 @@
1
+ import { Logger } from 'winston';
2
+ import { LaplaceConfiguration } from '../utilities/configuration';
3
+ import { Client, createClient } from '../client/client';
4
+ import { LivePriceClient, BISTStockLiveData, USStockLiveData } from '../client/live_price';
5
+ import { Region } from '../client/collections';
6
+ import './client_test_suite';
7
+
8
+ describe('LivePrice', () => {
9
+ let client: Client;
10
+ let livePriceClient: LivePriceClient;
11
+
12
+ beforeAll(() => {
13
+ const config = (global as any).testSuite.config as LaplaceConfiguration;
14
+ const logger: Logger = {
15
+ info: jest.fn(),
16
+ error: jest.fn(),
17
+ warn: jest.fn(),
18
+ debug: jest.fn(),
19
+ } as unknown as Logger;
20
+
21
+ client = createClient(config, logger);
22
+ livePriceClient = new LivePriceClient(client);
23
+ });
24
+
25
+ const testLivePrice = async (
26
+ symbols: string[],
27
+ region: Region,
28
+ getLivePriceFunc: (symbols: string[], region: Region) => AsyncGenerator<BISTStockLiveData | USStockLiveData, void, unknown>
29
+ ) => {
30
+ const livePriceGenerator = getLivePriceFunc.call(livePriceClient, symbols, region);
31
+ let livePriceCount = 0;
32
+
33
+ try {
34
+ for await (const livePrice of livePriceGenerator) {
35
+ expect(livePrice).not.toBeEmpty();
36
+ livePriceCount++;
37
+ if (livePriceCount > 3) {
38
+ break;
39
+ }
40
+ }
41
+ } catch (error) {
42
+ throw new Error(`Error occurred during live price retrieval: ${error}`);
43
+ }
44
+
45
+ expect(livePriceCount).toBeGreaterThan(0);
46
+ };
47
+
48
+ test('BISTLivePrice', async () => {
49
+ const symbols = ['TUPRS', 'SASA', 'THYAO', 'GARAN', 'YKBN'];
50
+ await testLivePrice(symbols, Region.Tr, livePriceClient.getLivePriceForBIST);
51
+ }, 10000);
52
+
53
+ test('USLivePrice', async () => {
54
+ const symbols = ['AAPL', 'GOOGL', 'MSFT', 'AMZN', 'META'];
55
+ await testLivePrice(symbols, Region.Us, livePriceClient.getLivePriceForUS);
56
+ }, 10000);
57
+ });
package/tsconfig.json CHANGED
@@ -6,8 +6,12 @@
6
6
  "strict": true,
7
7
  "esModuleInterop": true,
8
8
  "types": ["jest", "node"],
9
- "typeRoots": ["./node_modules/@types", "./types"]
9
+ "moduleResolution": "node",
10
+ "typeRoots": ["./node_modules/@types", "./src/types"]
10
11
  },
11
- "include": ["src/**/*", "jest.setup.ts"],
12
- "exclude": ["node_modules", "**/*.spec.ts"]
12
+ "include": ["src/**/*", "src/jest.setup.ts"],
13
+ "exclude": ["node_modules", "**/*.spec.ts"],
14
+ "paths": {
15
+ "@/*": ["src/*"]
16
+ }
13
17
  }
package/client/client.ts DELETED
@@ -1,41 +0,0 @@
1
- import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
- import { Logger } from 'winston';
3
- import { LaplaceConfiguration } from '../utilities/configuration';
4
-
5
- export class Client {
6
- private cli: AxiosInstance;
7
- private baseUrl: string;
8
- private apiKey: string;
9
- private logger: Logger;
10
-
11
- constructor(cfg: LaplaceConfiguration, logger: Logger) {
12
- this.cli = axios.create();
13
- this.baseUrl = cfg.baseURL;
14
- this.apiKey = cfg.apiKey;
15
- this.logger = logger;
16
- }
17
-
18
- async sendRequest<T>(config: AxiosRequestConfig): Promise<T> {
19
- try {
20
- const response = await this.cli.request<T>({
21
- ...config,
22
- baseURL: this.baseUrl,
23
- headers: {
24
- ...config.headers,
25
- Authorization: `Bearer ${this.apiKey}`,
26
- },
27
- });
28
-
29
- return response.data;
30
- } catch (error) {
31
- if (axios.isAxiosError(error) && error.response) {
32
- throw new Error(`Unexpected status code: ${error.response.status}, body: ${JSON.stringify(error.response.data)}`);
33
- }
34
- throw error;
35
- }
36
- }
37
- }
38
-
39
- export function createClient(cfg: LaplaceConfiguration, logger: Logger): Client {
40
- return new Client(cfg, logger);
41
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes