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] 실제 서버 내에서 테스트를 위한 머지 #152

Closed
wants to merge 51 commits into from
Closed
Changes from 1 commit
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
edb326f
✨ feat: 실시간 체결가 웹소켓 연결 코드 작성#56
uuuo3o Nov 14, 2024
b266468
🔧 fix: status pending 조건 추가 #53
sieunie Nov 15, 2024
57d1174
🔧 fix: 매도/매수 체결 시 쿼리문 수정 #53
sieunie Nov 15, 2024
139bc4a
➕ add: 사용자 보유 주식 테이블 유니크 조건 추가 #53
sieunie Nov 15, 2024
b2fb455
🔧 fix: user id 로직 수정 #53
sieunie Nov 15, 2024
e81574e
➕ add: 에러 로그 추가 #53
sieunie Nov 15, 2024
e0c8c27
➕ add: 매수시 가용 자산 체크 로직 추가 #53
sieunie Nov 15, 2024
2371d93
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
sieunie Nov 15, 2024
3b7999d
🔧 fix: 매수시 가용 자산 체크 로직 수정 #53
sieunie Nov 15, 2024
8ae299c
🔧 fix: 매수시 보유 주식 평균가 업데이트 쿼리 수정 #53
sieunie Nov 15, 2024
e454dc2
🔧 fix: 보유 주식 평균가 타입 수정 #53
sieunie Nov 15, 2024
1e6a838
Merge branch 'dev' of https://github.com/boostcampwm-2024/web16-JuGa …
uuuo3o Nov 15, 2024
d68955b
✨ feat: 실시간 체결가 웹소켓 연결 코드 작성 및 test.html 생성#56
uuuo3o Nov 15, 2024
d1b6eef
Merge pull request #122 from boostcampwm-2024/feature/api/execute-#53
sieunie Nov 15, 2024
b34356d
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 18, 2024
43f5c1e
🔧 fix : alpha 서버 CD/CD 워크플로우 수정
jinddings Nov 18, 2024
f8b6560
🚚 rename :alpha 서버 워크플로우 rename
jinddings Nov 18, 2024
22fe6b8
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
jinddings Nov 18, 2024
0ed0871
✨ feat: 실시간 체결가 웹소켓 연결 코드 작성 및 test.html 생성#127
uuuo3o Nov 18, 2024
5feaf13
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 18, 2024
e15169b
🔥 remove: 불필요한 html 파일 삭제#127
uuuo3o Nov 18, 2024
279bd4b
📝 docs: swagger에 응답 타입 수정 및 불필요한 코드 삭제
uuuo3o Nov 18, 2024
03ac949
✨ feat: 모의 도메인용 함수 추가#127
uuuo3o Nov 18, 2024
5212038
✨ feat: SSE로 실시간 데이터 전송 로직 작성#127
uuuo3o Nov 18, 2024
e6cf90a
🔧 fix: cors 연결 설정에 불필요한 주소가 포함되어있던 부분 수정#127
uuuo3o Nov 18, 2024
9a4eaf2
🔧 fix: 소켓 연결 종료 시 1분 간격으로 재연결 로직 추가 #126
sieunie Nov 18, 2024
cfe7b06
Merge branch 'dev' of https://github.com/boostcampwm-2024/web16-JuGa …
jinddings Nov 18, 2024
0f3e141
🔧 fix : alpha, production ENV 분리
jinddings Nov 18, 2024
bd58ed3
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 18, 2024
4df492a
♻️ refactor: requestApi 메소드 모든 서비스에서 사용하도록 변경
sieunie Nov 18, 2024
b6ec95c
♻️ refactor: 다른 서비스에서 사용되는 서비스를 domain-service로 변경
sieunie Nov 18, 2024
52152b9
♻️ refactor: stock index controller 로직 줄이고 service로 위임
sieunie Nov 18, 2024
3e85e3d
✨ feat: 주식 종목코드도 함께 반환할 수 있도록 구현
uuuo3o Nov 18, 2024
c825569
Merge pull request #129 from boostcampwm-2024/feature/socket/stockTra…
uuuo3o Nov 19, 2024
693df66
Merge pull request #131 from boostcampwm-2024/fix/socket
uuuo3o Nov 19, 2024
df57558
Merge pull request #139 from boostcampwm-2024/refactor/api/topfive
uuuo3o Nov 19, 2024
14242bc
Merge branch 'back/main' into refactor-J188
sieunie Nov 19, 2024
dab1f7b
🔧 fix: websocket 경로 수정
sieunie Nov 19, 2024
f7b9673
🔧 fix: 불필요한 try-catch문 및 logger 삭제
sieunie Nov 19, 2024
c07c5bc
♻️ refactor: 불필요한 logger 삭제
sieunie Nov 19, 2024
405e2d3
Merge pull request #134 from boostcampwm-2024/refactor-J188
sieunie Nov 19, 2024
8d60390
🔧 fix: 매도/매수 시 종목 코드 isNotEmpty 확인 추가
sieunie Nov 19, 2024
c0d2270
Merge pull request #143 from boostcampwm-2024/fix/order
sieunie Nov 19, 2024
49edc8f
✨ feat: 주식 주문에 사용할 상한가, 하한가 추가#144
uuuo3o Nov 19, 2024
a02a4fa
Merge pull request #147 from boostcampwm-2024/feature/api/stockDetail…
uuuo3o Nov 19, 2024
22dd87d
🔧 fix : cookie를 이용한 accessToken validate(#4)
jinddings Nov 19, 2024
d4d977b
♻️ refactor : lint 오류 수정
jinddings Nov 19, 2024
328b163
🔧 fix : docker timezone 변경
jinddings Nov 19, 2024
650fdf2
🔧 fix : 명령어에서 sudo 제거
jinddings Nov 19, 2024
c7aa9ab
🔧 fix : credential 설정 추가
jinddings Nov 19, 2024
5b0200c
🔧 fix :
jinddings Nov 19, 2024
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
Prev Previous commit
Next Next commit
✨ feat: 실시간 체결가 웹소켓 연결 코드 작성 및 test.html 생성#127
uuuo3o committed Nov 18, 2024

Verified

This commit was signed with the committer’s verified signature.
snyk-bot Snyk bot
commit 0ed0871209e8b38a21ac8352da211c4976b64fcd
143 changes: 104 additions & 39 deletions BE/src/stock/trade/history/stock-trade-history-socket.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { Injectable, Logger } from '@nestjs/common';
import {
Injectable,
Logger,
OnModuleInit,
} from '@nestjs/common';
import { SocketGateway } from '../../../websocket/socket.gateway';
import { BaseSocketService } from '../../../websocket/base-socket.service';
import { WebSocket } from 'ws';
import axios from 'axios';
import { SocketConnectTokenInterface } from '../../../websocket/interface/socket.interface';

interface TradeHistoryData {
stck_prpr: string; // 체결가(주식 현재가)
@@ -10,56 +16,115 @@ interface TradeHistoryData {
}

@Injectable()
export class StockTradeHistorySocketService {
export class StockTradeHistorySocketService implements OnModuleInit {
private TR_ID = 'H0STCNT0';
private readonly logger = new Logger('StockTradeHistorySocketService');
private subscribedStocks = new Set<string>();
private socket: WebSocket;
private socketConnectionKey: string;

constructor(
private readonly socketGateway: SocketGateway,
private readonly baseSocketService: BaseSocketService,
) {
baseSocketService.registerSocketOpenHandler(() => {
this.logger.debug('trade-history 소켓 연결 성공');
this.subscribedStocks.forEach((stockCode) => {
this.baseSocketService.registerCode(this.TR_ID, stockCode);
});
});

baseSocketService.registerSocketDataHandler(
this.TR_ID,
(dataList: string[]) => {
try {
const stockCode = dataList[0];

const tradeData: TradeHistoryData = {
stck_prpr: dataList[2],
cntg_vol: dataList[12],
prdy_ctrt: dataList[5],
stck_cntg_hour: dataList[1],
};

const eventName = `trade-history/${stockCode}`;
this.logger.debug(`Emitting trade data for ${stockCode}`);
this.socketGateway.sendStockTradeHistoryValueToClient(
eventName,
tradeData,
constructor(private readonly socketGateway: SocketGateway) {}

async onModuleInit() {
this.socketConnectionKey = await this.getSocketConnectionKey();
this.socket = new WebSocket(process.env.KOREA_INVESTMENT_TEST_SOCKET_URL);

this.socket.onopen = () => {
this.registerCode(this.TR_ID, '005930');
};

this.socket.onmessage = (event) => {
const data =
typeof event.data === 'string'
? event.data.split('|')
: JSON.stringify(event.data);

if (data.length < 2) {
const json = JSON.parse(data[0]);
if (json.body)
this.logger.log(
`한국투자증권 웹소켓 연결: ${json.body.msg1}`,
json.header.tr_id,
);
} catch (error) {
this.logger.error('Error processing trade data:', error);
this.logger.error('Raw data was:', dataList);
}
},
if (json.header.tr_id === 'PINGPONG')
this.socket.pong(JSON.stringify(json));
return;
}

const dataList = data[3].split('^');

if (Number(dataList[1]) % 500 === 0)
this.logger.log(`한국투자증권 데이터 수신 성공 (5분 단위)`, data[1]);

console.log(dataList);
};

this.socket.onclose = () => {
this.logger.warn(`한국투자증권 소켓 연결 종료`);
};
}

registerCode(trId: string, trKey: string) {
this.socket.send(
JSON.stringify({
header: {
approval_key: this.socketConnectionKey,
custtype: 'P',
tr_type: '1',
'content-type': 'utf-8',
},
body: {
input: {
tr_id: trId,
tr_key: trKey,
},
},
}),
);
}

unregisterCode(trId: string, trKey: string) {
this.socket.send(
JSON.stringify({
header: {
approval_key: this.socketConnectionKey,
custtype: 'P',
tr_type: '2',
'content-type': 'utf-8',
},
body: {
input: {
tr_id: trId,
tr_key: trKey,
},
},
}),
);
}

subscribeByCode(stockCode: string) {
this.baseSocketService.registerCode(this.TR_ID, stockCode);
this.subscribedStocks.add(stockCode);
}

unsubscribeByCode(stockCode: string) {
this.baseSocketService.unregisterCode(this.TR_ID, stockCode);
this.subscribedStocks.delete(stockCode);
}

async getSocketConnectionKey() {
if (this.socketConnectionKey) {
return this.socketConnectionKey;
}

const response = await axios.post<SocketConnectTokenInterface>(
'https://openapivts.koreainvestment.com:29443/oauth2/Approval',
{
grant_type: 'client_credentials',
appkey: process.env.KOREA_INVESTMENT_TEST_APP_KEY,
secretkey: process.env.KOREA_INVESTMENT_TEST_APP_SECRET,
},
);

this.socketConnectionKey = response.data.approval_key;
return this.socketConnectionKey;
}
}