Skip to content

Commit

Permalink
fix: 매수, 매도 에러 수정 및 퍼센티지 api 에러처리
Browse files Browse the repository at this point in the history
  • Loading branch information
SeungGwan123 committed Nov 19, 2024
1 parent 23d949b commit 2c96980
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 65 deletions.
36 changes: 24 additions & 12 deletions packages/server/src/account/account.repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DataSource, Repository } from 'typeorm';
import { DataSource, Repository, QueryRunner } from 'typeorm';
import { Account } from './account.entity';
import { Injectable } from '@nestjs/common';
import { User } from 'src/auth/user.entity';
Expand All @@ -12,7 +12,7 @@ export class AccountRepository extends Repository<Account> {
const account = new Account();
account.KRW = 300000000;
account.USDT = 300000;
account.BTC = 10;
account.BTC = 0;
account.user = adminUser;
await this.save(account);
console.log('admin 계정에 Account가 성공적으로 생성되었습니다.');
Expand All @@ -26,15 +26,27 @@ export class AccountRepository extends Repository<Account> {
return account[moneyType];
}
async updateAccountCurrency(typeGiven, accountBalance, accountId, queryRunner) {
try{
const updateData = {
id: accountId,
[typeGiven]: accountBalance,
};

await queryRunner.manager.save(Account, updateData);
}catch(error){
console.log(error)
}
try{
await queryRunner.manager
.createQueryBuilder()
.update(Account)
.set({
[typeGiven]: accountBalance,
})
.where('id = :id', { id: accountId })
.execute();
}catch(error){
console.log(error)
}
}
async updateAccountBTC(id, quantity, queryRunner){
await queryRunner.manager
.createQueryBuilder()
.update(Account)
.set({
BTC: quantity,
})
.where('id = :id', { id: id })
.execute();
}
}
5 changes: 4 additions & 1 deletion packages/server/src/asset/asset.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,10 @@ export class AssetRepository extends Repository<Asset> {
await queryRunner.manager
.createQueryBuilder()
.update(Asset)
.set({ price: asset.price })
.set({
price: asset.price,
quantity: asset.quantity
})
.where('assetId = :assetId', { assetId: asset.assetId })
.execute();
} catch (e) {
Expand Down
18 changes: 11 additions & 7 deletions packages/server/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,19 @@ export class AuthService {
}

async logout(userId: number): Promise<{ message: string }> {
const user = await this.userRepository.findOneBy({ id: userId });
try{
const user = await this.userRepository.findOneBy({ id: userId });

if (!user) {
throw new Error('User not found');
}
if (!user) {
throw new Error('User not found');
}

if (user.isGuest) {
await this.userRepository.delete({ id: userId });
return { message: 'Guest user data successfully deleted' };
if (user.isGuest) {
await this.userRepository.delete({ id: userId });
return { message: 'Guest user data successfully deleted' };
}
}catch(error){
console.error(error)
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/auth/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ export const jwtConstants = {

export const DEFAULT_KRW = 30000000;
export const DEFAULT_USDT = 300000;
export const DEFAULT_BTC = 10;
export const DEFAULT_BTC = 0;
64 changes: 41 additions & 23 deletions packages/server/src/trade/trade-ask.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ export class AskService implements OnModuleInit {
}

async calculatePercentBuy(user, moneyType: string, percent: number) {
const account = await this.accountRepository.findOne({
where : {user: {id: user.userId}}
})
const asset = await this.assetRepository.findOne({
where:{
account: {id: user.userId},
account: {id: account.id},
assetName: moneyType
}
})
Expand All @@ -58,24 +61,10 @@ export class AskService implements OnModuleInit {
code: 422,
});
}
const userAsset = await this.checkCurrency(user, askDto, queryRunner);
userAsset.quantity -= askDto.receivedAmount
if(userAsset.quantity !==0){
await this.assetRepository.updateAssetQuantity(
userAsset,
queryRunner,
)
}else {
await this.assetRepository.delete({
assetId: userAsset.assetId
})
}

await this.tradeRepository.createTrade(askDto, user.userId,'sell', queryRunner);
await queryRunner.commitTransaction();
const temp = await this.assetRepository.findOne({
where: {assetId: userAsset.assetId}
})
console.log(temp.quantity)

return {
code: 200,
message: '거래가 정상적으로 등록되었습니다.',
Expand Down Expand Up @@ -121,12 +110,16 @@ export class AskService implements OnModuleInit {
userId,
} = askDto;
try {
const account = await this.accountRepository.findOne({
where: { user : { id : userId } }
})
const userAsset = await this.assetRepository.findOne({
where: {
account: { id: userId },
account: { id: account.id },
assetName: typeGiven
},
});
if(!userAsset) return;
askDto.assetBalance = userAsset.quantity;
askDto.asset = userAsset;
const currentCoinOrderbook =
Expand All @@ -138,6 +131,12 @@ export class AskService implements OnModuleInit {
});
if (!tradeData) break;
const result = await this.executeTrade(askDto, order, tradeData);
if(askDto.asset.quantity ===0){
await this.assetRepository.delete({
assetId: askDto.asset.assetId
})
break;
}
if (!result) break;
}

Expand All @@ -160,15 +159,17 @@ export class AskService implements OnModuleInit {
userId,
tradeId,
asset,
typeGiven,
assetBalance,
typeReceived,
krw
} = askDto;
let result = false;
try {
const buyData = { ...tradeData };
buyData.quantity =
tradeData.quantity >= bid_size ? bid_size : tradeData.quantity;
buyData.price = bid_price;
buyData.price = bid_price * krw;
await this.tradeHistoryRepository.createTradeHistory(
userId,
buyData,
Expand All @@ -177,21 +178,36 @@ export class AskService implements OnModuleInit {

if (assetBalance !== 0) {
asset.price =
asset.price * asset.quantity - krw * buyData.quantity;
asset.price - buyData.price * buyData.quantity;
asset.quantity -= buyData.quantity;
await this.assetRepository.updateAssetPrice(asset, queryRunner);
}

const account = await this.accountRepository.findOne({
where: { user : { id : userId } }
})

if(typeGiven === "BTC"){
const BTC_QUANTITY = account.BTC - buyData.quantity
await this.accountRepository.updateAccountBTC(account.id, BTC_QUANTITY, queryRunner)
}
const change = account[typeReceived] + buyData.price * buyData.quantity
console.log("account : "+account[typeReceived])
console.log("change : "+buyData.price*buyData.quantity)
console.log("result : "+change)
await this.accountRepository.updateAccountCurrency(typeReceived, change, account.id, queryRunner)


tradeData.quantity -= buyData.quantity;

if (tradeData.quantity === 0) {
await this.tradeRepository.deleteTrade(tradeId, queryRunner);
} else
} else{
await this.tradeRepository.updateTradeTransaction(
tradeData,
queryRunner,
);

}
await queryRunner.commitTransaction();
result = true;
} catch (error) {
Expand Down Expand Up @@ -233,14 +249,16 @@ export class AskService implements OnModuleInit {
});
const availableTrades = await this.tradeRepository.searchSellTrade(coinPrice);
availableTrades.forEach((trade) => {
const krw = coinLatestInfo.get(["KRW",trade.tradeCurrency].join("-")).trade_price;
const another = coinLatestInfo.get([trade.assetName,trade.tradeCurrency].join("-")).trade_price;
const askDto = {
userId: trade.user.id,
typeGiven: trade.tradeCurrency, //건네주는 통화
typeReceived: trade.assetName, //건네받을 통화 타입
receivedPrice: trade.price, //건네받을 통화 가격
receivedAmount: trade.quantity, //건네 받을 통화 갯수
tradeId: trade.tradeId,
krw: coinLatestInfo.get(["KRW",trade.assetName].join("-")),
krw: another/krw
};
this.askTradeService(askDto);
});
Expand Down
47 changes: 26 additions & 21 deletions packages/server/src/trade/trade-bid.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,8 @@ export class BidService implements OnModuleInit {
});
const accountBalance = userAccount[typeGiven];
const accountResult = accountBalance - givenAmount;
console.error(`accountResult : ${accountResult}`)

if (accountResult < 0){
console.error(`매수 희망 금액 : ${givenAmount}`)
console.error(`계좌 잔액 : ${accountBalance}`)
console.error(`accountResult : ${accountResult}`)
throw new UnprocessableEntityException({
message: '자산이 부족합니다.',
code: 422,
Expand All @@ -111,17 +108,17 @@ export class BidService implements OnModuleInit {
userId,
} = bidDto;
try {
const account = await this.accountRepository.findOne({
where: {
user: { id: userId },
},
});
bidDto.accountBalance = account[typeGiven];
bidDto.account = account;
const currentCoinOrderbook =
this.coinDataUpdaterService.getCoinOrderbookByBid(bidDto);
for(const order of currentCoinOrderbook){
if (order.ask_price > receivedPrice) break;
const account = await this.accountRepository.findOne({
where: {
user: { id: userId },
},
});
bidDto.accountBalance = account[typeGiven];
bidDto.account = account;
const tradeData = await this.tradeRepository.findOne({
where: { tradeId: tradeId },
});
Expand Down Expand Up @@ -156,9 +153,9 @@ export class BidService implements OnModuleInit {
let result = false;
try {
const buyData = {...tradeData};

buyData.quantity = buyData.quantity >= ask_size ? ask_size : buyData.quantity;
buyData.price = ask_price;
buyData.price = ask_price * krw;

await this.tradeHistoryRepository.createTradeHistory(
userId,
Expand All @@ -167,34 +164,40 @@ export class BidService implements OnModuleInit {
);

const asset = await this.assetRepository.findOne({
where: { account: {id: account.accountId}, assetName: typeReceived },
where: { account: {id: account.id}, assetName: typeReceived },
});

if (asset) {
asset.price =
asset.price * asset.quantity + krw * buyData.quantity;
asset.price + buyData.price * buyData.quantity;
asset.quantity += buyData.quantity;

await this.assetRepository.updateAssetQuantityPrice(asset, queryRunner);
} else {
await this.assetRepository.createAsset(
bidDto,
buyData.price,
buyData.price * buyData.quantity,
buyData.quantity,
queryRunner,
);
}

tradeData.quantity -= buyData.quantity;

if (tradeData.quantity === 0) {
await this.tradeRepository.deleteTrade(tradeId, queryRunner);
} else await this.tradeRepository.updateTradeTransaction(tradeData, queryRunner);
const temp = await this.tradeRepository.findOne({
where: {tradeId: tradeData.tradeId}
})

const change = (tradeData.price - buyData.price) * buyData.quantity;
const returnChange = change + account[typeGiven]
const new_asset = await this.assetRepository.findOne({
where: {account:{id:account.id}, assetName: "BTC"}
})

if(typeReceived === "BTC"){
const BTC_QUANTITY = new_asset ? asset.quantity : buyData.quantity;
await this.accountRepository.updateAccountBTC(account.id, BTC_QUANTITY, queryRunner)
}

await this.accountRepository.updateAccountCurrency(typeGiven,returnChange, account.id, queryRunner);

Expand Down Expand Up @@ -239,14 +242,16 @@ export class BidService implements OnModuleInit {
});
const availableTrades = await this.tradeRepository.searchBuyTrade(coinPrice);
availableTrades.forEach((trade) => {
const krw = coinLatestInfo.get(["KRW",trade.assetName].join("-")).trade_price
const another = coinLatestInfo.get([trade.tradeCurrency,trade.assetName].join("-")).trade_price
const bidDto = {
userId: trade.user.id,
typeGiven: trade.tradeCurrency, //건네주는 통화
typeReceived: trade.assetName, //건네받을 통화 타입
receivedPrice: trade.price, //건네받을 통화 가격
receivedAmount: trade.quantity, //건네 받을 통화 갯수
tradeId: trade.tradeId,
krw: coinLatestInfo.get(["KRW",trade.assetName].join("-")),
krw: another/krw
};
this.bidTradeService(bidDto);
});
Expand Down

0 comments on commit 2c96980

Please sign in to comment.