Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BE] 3.02 주식차트 정보 기능 구현 수정 #6 #47

Merged
merged 6 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface AccessTokenInterface {
access_token: string;
access_token_token_expired: string;
token_type: string;
expires_in: number;
}
16 changes: 10 additions & 6 deletions BE/src/koreaInvestment/korea.investment.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import axios from 'axios';
import { UnauthorizedException } from '@nestjs/common';
import { getFullURL } from '../util/getFullURL';
import { AccessTokenInterface } from './interface/korea.investment.interface';

export class KoreaInvestmentService {
private accessToken: string;
Expand All @@ -9,19 +12,20 @@ export class KoreaInvestmentService {
if (this.accessToken && this.tokenExpireTime > new Date()) {
return this.accessToken;
}
const response = await axios.post(
`${process.env.KOREA_INVESTMENT_BASE_URL}/oauth2/tokenP`,
{
const response = await axios
.post<AccessTokenInterface>(getFullURL('/oauth2/tokenP'), {
grant_type: 'client_credentials',
appkey: process.env.KOREA_INVESTMENT_APP_KEY,
appsecret: process.env.KOREA_INVESTMENT_APP_SECRET,
},
);
})
.catch(() => {
throw new UnauthorizedException('액세스 토큰을 조회하지 못했습니다.');
});

const { data } = response;

this.accessToken = data.access_token;
this.tokenExpireTime = new Date(Date.now() + +data.expires_in);
this.tokenExpireTime = new Date(data.access_token_token_expired);

return this.accessToken;
}
Expand Down
17 changes: 0 additions & 17 deletions BE/src/stock/index/dto/stock.index.list.element.dto.ts

This file was deleted.

14 changes: 6 additions & 8 deletions BE/src/stock/index/dto/stock.index.response.element.dto.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { ApiProperty } from '@nestjs/swagger';
import { StockIndexValueElementDto } from './stock.index.value.element.dto';
import { StockIndexListElementDto } from './stock.index.list.element.dto';
import { StockIndexListChartElementDto } from './stock.index.list.chart.element.dto';

export class StockIndexResponseElementDto {
@ApiProperty({
description: '코스피: 0001, 코스닥: 1001, 코스피200: 2001, KSQ150: 3003',
})
code: string;

@ApiProperty({ description: '실시간 값', type: StockIndexValueElementDto })
value: StockIndexValueElementDto;

@ApiProperty({ description: '실시간 차트', type: StockIndexListElementDto })
chart: StockIndexListElementDto;
@ApiProperty({
description: '실시간 차트',
type: [StockIndexListChartElementDto],
})
chart: StockIndexListChartElementDto[];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 여기가 어제 그룹 리뷰 때 말한 잘못 만들었다고 수정하신다고 하신 부분인가요?! 어떤 식으로 변경됐는지 나중에 한번 설명 기대하겠습니다ㅎㅎ

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네넵 이 부분이랑 소켓 이벤트 발생시키고 response 전달하는 부분도 수정했습니다!

}
22 changes: 5 additions & 17 deletions BE/src/stock/index/dto/stock.index.value.element.dto.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,21 @@
import { ApiProperty } from '@nestjs/swagger';

export class StockIndexValueElementDto {
constructor(
code: string,
value: string,
diff: string,
diffRate: string,
sign: string,
) {
this.code = code;
this.value = value;
constructor(value: string, diff: string, diffRate: string, sign: string) {
this.curr_value = value;
this.diff = diff;
this.diffRate = diffRate;
this.diff_rate = diffRate;
this.sign = sign;
}

@ApiProperty({
description: '코스피: 0001, 코스닥: 1001, 코스피200: 2001, KSQ150: 3003',
})
code: string;

@ApiProperty({ description: '주가 지수' })
value: string;
curr_value: string;

@ApiProperty({ description: '전일 대비 등락' })
diff: string;

@ApiProperty({ description: '전일 대비 등락률' })
diffRate: string;
diff_rate: string;

@ApiProperty({ description: '부호... 인데 추후에 알아봐야 함' })
sign: string;
Expand Down
11 changes: 6 additions & 5 deletions BE/src/stock/index/stock.index.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,22 +70,18 @@ export class StockIndexController {

const stockIndexResponse = new StockIndexResponseDto();
stockIndexResponse.KOSPI = {
code: '0001',
value: kospiValue,
chart: kospiChart,
};
stockIndexResponse.KOSDAQ = {
code: '1001',
value: kosdaqValue,
chart: kosdaqChart,
};
stockIndexResponse.KOSPI200 = {
code: '2001',
value: kospi200Value,
chart: kospi200Chart,
};
stockIndexResponse.KSQ150 = {
code: '3003',
value: ksq150Value,
chart: ksq150Chart,
};
Expand Down Expand Up @@ -115,6 +111,11 @@ export class StockIndexController {
), // KSQ150
]);

this.socketGateway.sendStockIndexListToClient(stockLists);
this.socketGateway.sendStockIndexListToClient({
KOSPI: stockLists[0],
KOSDAQ: stockLists[1],
KOSPI200: stockLists[2],
KSQ150: stockLists[3],
});
}
}
101 changes: 47 additions & 54 deletions BE/src/stock/index/stock.index.service.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Injectable } from '@nestjs/common';
import { Injectable, InternalServerErrorException } from '@nestjs/common';
import axios from 'axios';
import { StockIndexListChartElementDto } from './dto/stock.index.list.chart.element.dto';
import { StockIndexListElementDto } from './dto/stock.index.list.element.dto';
import { StockIndexValueElementDto } from './dto/stock.index.value.element.dto';
import {
StockIndexChartInterface,
StockIndexValueInterface,
} from './interface/stock.index.interface';
import { getFullURL } from '../../util/getFullURL';
import { getHeader } from '../../util/getHeader';

@Injectable()
export class StockIndexService {
Expand All @@ -16,18 +17,12 @@ export class StockIndexService {
accessToken,
);

if (result.rt_cd !== '0')
throw new Error('데이터를 정상적으로 조회하지 못했습니다.');

return new StockIndexListElementDto(
code,
result.output.map((element) => {
return new StockIndexListChartElementDto(
element.bsop_hour,
element.bstp_nmix_prpr,
);
}),
);
return result.output.map((element) => {
return new StockIndexListChartElementDto(
element.bsop_hour,
element.bstp_nmix_prpr,
);
});
}

async getDomesticStockIndexValueByCode(code: string, accessToken: string) {
Expand All @@ -36,40 +31,39 @@ export class StockIndexService {
accessToken,
);

if (result.rt_cd !== '0')
throw new Error('데이터를 정상적으로 조회하지 못했습니다.');
const data = result.output;

return new StockIndexValueElementDto(
code,
result.output.bstp_nmix_prpr,
result.output.bstp_nmix_prdy_vrss,
result.output.bstp_nmix_prdy_ctrt,
result.output.prdy_vrss_sign,
data.bstp_nmix_prpr,
data.bstp_nmix_prdy_vrss,
data.bstp_nmix_prdy_ctrt,
data.prdy_vrss_sign,
);
}

private async requestDomesticStockIndexListApi(
code: string,
accessToken: string,
) {
const response = await axios.get<StockIndexChartInterface>(
`${process.env.KOREA_INVESTMENT_BASE_URL}/uapi/domestic-stock/v1/quotations/inquire-index-timeprice`,
{
headers: {
'content-type': 'application/json; charset=utf-8',
authorization: `Bearer ${accessToken}`,
appkey: process.env.KOREA_INVESTMENT_APP_KEY,
appsecret: process.env.KOREA_INVESTMENT_APP_SECRET,
tr_id: 'FHPUP02110200',
custtype: 'P',
},
params: {
fid_input_hour_1: 300,
fid_cond_mrkt_div_code: 'U',
fid_input_iscd: code,
const response = await axios
.get<StockIndexChartInterface>(
getFullURL(
'/uapi/domestic-stock/v1/quotations/inquire-index-timeprice',
),
{
headers: getHeader(accessToken, 'FHPUP02110200'),
params: {
fid_input_hour_1: 300,
fid_cond_mrkt_div_code: 'U',
fid_input_iscd: code,
},
},
},
);
)
.catch(() => {
throw new InternalServerErrorException(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 저도 에러 처리를 그냥 log만 찍어놓듯이 작성해놨는데 이렇게 수정해봐야겠어요!

'주가 지수 차트 정보를 조회하지 못했습니다.',
);
});

return response.data;
}
Expand All @@ -78,23 +72,22 @@ export class StockIndexService {
code: string,
accessToken: string,
) {
const response = await axios.get<StockIndexValueInterface>(
`${process.env.KOREA_INVESTMENT_BASE_URL}/uapi/domestic-stock/v1/quotations/inquire-index-price`,
{
headers: {
'content-type': 'application/json; charset=utf-8',
authorization: `Bearer ${accessToken}`,
appkey: process.env.KOREA_INVESTMENT_APP_KEY,
appsecret: process.env.KOREA_INVESTMENT_APP_SECRET,
tr_id: 'FHPUP02100000',
custtype: 'P',
},
params: {
fid_cond_mrkt_div_code: 'U',
fid_input_iscd: code,
const response = await axios
.get<StockIndexValueInterface>(
getFullURL('/uapi/domestic-stock/v1/quotations/inquire-index-price'),
{
headers: getHeader(accessToken, 'FHPUP02100000'),
params: {
fid_cond_mrkt_div_code: 'U',
fid_input_iscd: code,
},
},
},
);
)
.catch(() => {
throw new InternalServerErrorException(
'주가 지수 값 정보를 조회하지 못했습니다.',
);
});

return response.data;
}
Expand Down
8 changes: 4 additions & 4 deletions BE/src/websocket/socket.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ export class SocketGateway {
@WebSocketServer()
private server: Server;

sendStockIndexListToClient(stockIndex) {
this.server.emit('index', stockIndex);
sendStockIndexListToClient(stockChart) {
this.server.emit('chart', stockChart);
}

sendStockIndexValueToClient(stockIndexValue) {
this.server.emit('indexValue', stockIndexValue);
sendStockIndexValueToClient(event, stockIndexValue) {
this.server.emit(event, stockIndexValue);
}
}
15 changes: 11 additions & 4 deletions BE/src/websocket/socket.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import axios from 'axios';
import { SocketGateway } from './socket.gateway';
import { StockIndexValueElementDto } from '../stock/index/dto/stock.index.value.element.dto';
import { SocketConnectTokenInterface } from './interface/socket.interface';
import { getFullURL } from '../util/getFullURL';

@Injectable()
export class SocketService implements OnModuleInit {
Expand All @@ -12,13 +13,19 @@ export class SocketService implements OnModuleInit {
H0UPCNT0: this.handleStockIndexValue.bind(this),
};

private STOCK_CODE = {
'0001': 'KOSPI',
'1001': 'KOSDAQ',
'2001': 'KOSPI200',
'3003': 'KSQ150',
};

constructor(private readonly socketGateway: SocketGateway) {}

async onModuleInit() {
const socketConnectionKey = await this.getSocketConnectionKey();

const url = 'ws://ops.koreainvestment.com:21000';
this.socket = new WebSocket(url);
this.socket = new WebSocket(process.env.KOREA_INVESTMENT_SOCKET_URL);

this.socket.onopen = () => {
this.registerStockIndexByCode('0001', socketConnectionKey); // 코스피
Expand All @@ -41,8 +48,8 @@ export class SocketService implements OnModuleInit {
private handleStockIndexValue(responseData: string) {
const responseList = responseData.split('^');
this.socketGateway.sendStockIndexValueToClient(
this.STOCK_CODE[responseList[0]],
new StockIndexValueElementDto(
responseList[0],
responseList[2],
responseList[4],
responseList[9],
Expand All @@ -53,7 +60,7 @@ export class SocketService implements OnModuleInit {

private async getSocketConnectionKey() {
const response = await axios.post<SocketConnectTokenInterface>(
`${process.env.KOREA_INVESTMENT_BASE_URL}/oauth2/Approval`,
getFullURL('/oauth2/Approval'),
{
grant_type: 'client_credentials',
appkey: process.env.KOREA_INVESTMENT_APP_KEY,
Expand Down