Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…-SpringServer- into feature/#58-대시보드-관련-api-구현
  • Loading branch information
Astin01 committed Aug 20, 2024
2 parents 10a658c + fc63009 commit ef530fa
Show file tree
Hide file tree
Showing 11 changed files with 152 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseTimeEntity {

@CreatedDate private LocalDateTime createdDate;
@CreatedDate private LocalDateTime createdAt;

@LastModifiedDate private LocalDateTime modifiedDate;
@LastModifiedDate private LocalDateTime updatedAt;
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@

import com.quantweb.springserver.domain.stock.dto.response.StockResponseDto;
import com.quantweb.springserver.domain.stock.service.StockService;

import com.quantweb.springserver.domain.sales_transaction_history.dto.response.TransactionHistoryResponseDto;
import com.quantweb.springserver.domain.sales_transaction_history.service.TransactionHistoryService;

import org.springframework.web.bind.annotation.*;

import com.quantweb.springserver.domain.auth.config.Authenticated;
Expand Down Expand Up @@ -35,6 +39,7 @@ public class BackTestController {

private final BackTestService backTestService;
private final StockService stockService;
private final TransactionHistoryService transactionHistoryService;

@PostMapping("/{userId}")
@Operation(summary = "백테스트 실행하기 API",description = "")
Expand All @@ -43,8 +48,8 @@ public class BackTestController {
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "BACKTEST400", description = "백테스트 이름이 중복되었습니다.",content = @Content(schema = @Schema(implementation = EntityResponse.class))),
})
@Authenticated
public Object backTest(@AuthenticationPrincipal @PathVariable("userId") Long userId, @RequestBody BackTestInput backTestInput) {
return backTestService.backtestAndSave(userId, backTestInput);
public ResponseEntity<BackTestResponseDto> backTest(@AuthenticationPrincipal @PathVariable("userId") Long userId, @RequestBody BackTestInput backTestInput) {
return ResponseEntity.ok(backTestService.backtestAndSave(userId, backTestInput));
}

@GetMapping("/{backtestId}/details")
Expand All @@ -57,6 +62,7 @@ public Object backTest(@AuthenticationPrincipal @PathVariable("userId") Long use
@Parameter(name = "backtestId", description = "조회할 백테스트 Id"),

})
@Authenticated
public ResponseEntity<BackTestDetailsDto.GetBackTestDto> getResultDetails(@PathVariable("backtestId") Long backtestId){

BackTestDetailsDto.GetBackTestDto resultDto = backTestService.getDetailsResult(backtestId);
Expand Down Expand Up @@ -101,4 +107,22 @@ public ResponseEntity<List<BackTestResponseDto>> getMyBacktests(@PathVariable("u
return ResponseEntity.ok(resultDto);
}

@GetMapping("/{backtestId}/histories")
@Operation(summary = "백테스트 매매내역 조회 API",description = "")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "COMMON200",description = "OK, 성공"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "BACKTEST404", description = "백테스트가 존재하지 않습니다.",content = @Content(schema = @Schema(implementation = EntityResponse.class))),
})
@Parameters({
@Parameter(name = "backtestId", description = "조회할 백테스트 Id"),

})
@Authenticated
public ResponseEntity<TransactionHistoryResponseDto> getTrasactionHistory(@PathVariable("backtestId") Long backtestId){

TransactionHistoryResponseDto resultDto = transactionHistoryService.getTransactionHistory(backtestId);

return ResponseEntity.ok(resultDto);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,10 @@ public static BackTest toBackTest(User user, BackTestInput backTestInput, Invest
.build();
}

// public static BackTestDetailsDto.BackTestResponseDto toBackTestResultDto(BackTest backTest){
//
// return BackTestDetailsDto.BackTestResponseDto.builder()
//// .accumulatedProfit(backTest.getRealizedProfit())
//// .mdd()
//// .totalAssest()
//// .initInvestFund()
//// .evaluatedProfit()
//// .realizedProfit()
//// .marketShared()
//// .investCategories()
// .build();
// }


public static BackTestDetailsDto.GetBackTestDto toBackTestResultDto(BackTest backTest,
List<DailyPercentage> dailyPercentages, List<DailyPercentageUs500> dailyPercentageUs500s,
List<Mdd> mdds, List<MddUs500> mddUs500s){
List<DailyPercentage> dailyPercentages, List<DailyPercentageUs500> dailyPercentageUs500s,
List<Mdd> mdds, List<MddUs500> mddUs500s){

BackTestDetailsDto.GetBackTestDto.DailyCumulativeReturn dailyCumulativeReturn = toDailyCumulativeReturn(dailyPercentages, dailyPercentageUs500s);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.quantweb.springserver.domain.back_test.repository;


import org.springframework.data.jpa.repository.JpaRepository;

import com.quantweb.springserver.domain.back_test.entity.BackTest;
Expand All @@ -10,7 +11,6 @@
public interface BackTestRepository extends JpaRepository<BackTest, Long> {

Boolean existsByName(String name);

Optional<List<BackTest>> findAllByUserId(Long userId);

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,8 @@ public class InvestmentSimulation extends BaseTimeEntity {

@OneToOne(mappedBy = "investmentSimulation", fetch = FetchType.LAZY)
private Graph graph;

public void updateMarketShared(){
this.marketShared = !marketShared;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ public interface MarketRepository extends JpaRepository<Market, Long> {
@Query("SELECT m FROM Market m Join m.investmentSimulation i WHERE i.investStartDate >= :currentDate ORDER BY m.subscribeNum DESC")
Page<Market> findAllInvestmentSimulationByRecommend(Pageable pageable);
//마켓 백 테스트 전략 검색
@Query("SELECT DISTINCT m FROM Market m JOIN m.marketTags t WHERE M.name LIKE%:keyword% OR t.tag LIKE%:keyword% AND m.investmentSimulation IS NULL")
@Query("SELECT DISTINCT m FROM Market m JOIN m.marketTags t WHERE m.name LIKE%:keyword% OR t.tag LIKE%:keyword% AND m.investmentSimulation IS NULL")
Page<Market> findAllBackTestBySearch(@Param("keyword") String keyword, Pageable pageable);

//마켓 모의 투자 검색
@Query("SELECT DISTINCT m FROM Market m JOIN m.marketTags t WHERE M.name LIKE%:keyword% OR t.tag LIKE%:keyword% AND m.backTest IS NULL")
@Query("SELECT DISTINCT m FROM Market m JOIN m.marketTags t WHERE m.name LIKE%:keyword% OR t.tag LIKE%:keyword% AND m.backTest IS NULL")
Page<Market> findAllInvestmentSimulationBySearch(@Param("keyword") String keyword, Pageable pageable);

List<Market> findAllByUserId(Long userId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@

import com.quantweb.springserver.domain.back_test.DTO.response.InvestmentResultDto;
import com.quantweb.springserver.domain.back_test.entity.BackTest;
import com.quantweb.springserver.domain.sales_transaction_history.dto.response.TransactionHistoryResponseDto;
import com.quantweb.springserver.domain.sales_transaction_history.entity.SalesTransactionHistory;
import com.quantweb.springserver.domain.sales_transaction_history.entity.TransactionType;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

public class TransactionHistoryConverter {

Expand All @@ -20,4 +23,44 @@ public static SalesTransactionHistory toTransactionHistory(InvestmentResultDto.T
.investmentSimulation(null)
.build();
}

public static TransactionHistoryResponseDto.TransactionHistory toTransactionHistoryResult(SalesTransactionHistory transactionHistories){

return TransactionHistoryResponseDto.TransactionHistory.builder()
// .transactionDate(transactionHistories.getDateTime())
// .stockName(transactionHistories.getTicker())
// .period()
// .realizedProfit()
// .profitPercentage()
// .buyQuantity()
// .buyPrice()
// .sellQuantity()
// .sellPrice()
// .status()
// .fee()
// .transactionHistoryGraph()
.build();
}

public static TransactionHistoryResponseDto.TransactionHistoryGraph toTransactionHistoryGraph(SalesTransactionHistory transactionHistories){

return TransactionHistoryResponseDto.TransactionHistoryGraph.builder()
.date(transactionHistories.getDateTime())
.amount(transactionHistories.getQuantity())
.action(transactionHistories.getType())
.ticker(transactionHistories.getTicker())
.build();
}

public static TransactionHistoryResponseDto toTransactionHistoryResultDto(List<SalesTransactionHistory> transactionHistories){

List<TransactionHistoryResponseDto.TransactionHistoryGraph> graphs = transactionHistories.stream()
.map(TransactionHistoryConverter::toTransactionHistoryGraph)
.toList();

return TransactionHistoryResponseDto.builder()
//.transactionHistories()
.transactionHistoryGraph(graphs)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.quantweb.springserver.domain.sales_transaction_history.dto.request;


public class TransactionHistoryRequestDto {


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.quantweb.springserver.domain.sales_transaction_history.dto.response;

import com.quantweb.springserver.domain.sales_transaction_history.entity.TransactionType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.util.List;

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
public class TransactionHistoryResponseDto {

private List<TransactionHistory> transactionHistories;

private List<TransactionHistoryGraph> transactionHistoryGraph; //매매내역 - 그래프

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
public static class TransactionHistory {
private LocalDate transactionDate; //거래일시
private String stockName; //종목
private LocalDate period; //평균보유기간
private Integer realizedProfit; //실현손익
private Float profitPercentage; //수익률
private Float buyQuantity; //매수수량
private Float sellQuantity; //매도수량
private Long buyPrice; //매수금액
private Long sellPrice; //매도금액
private TransactionType status; //상태: 거래완료
private Integer fee; //수수료
}

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
public static class TransactionHistoryGraph {
private LocalDate date;
private Long amount;
private TransactionType action;
private String ticker;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,10 @@
import com.quantweb.springserver.domain.sales_transaction_history.entity.SalesTransactionHistory;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;
import java.util.Optional;

public interface TransactionHistoryRepository extends JpaRepository<SalesTransactionHistory,Long> {

Optional<List<SalesTransactionHistory>> findAllByBackTestId(Long backtestId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
import com.quantweb.springserver.domain.back_test.DTO.response.InvestmentResultDto;
import com.quantweb.springserver.domain.back_test.entity.BackTest;
import com.quantweb.springserver.domain.sales_transaction_history.converter.TransactionHistoryConverter;
import com.quantweb.springserver.domain.sales_transaction_history.dto.response.TransactionHistoryResponseDto;
import com.quantweb.springserver.domain.sales_transaction_history.entity.SalesTransactionHistory;
import com.quantweb.springserver.domain.sales_transaction_history.repository.TransactionHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
Expand All @@ -22,6 +25,12 @@ public void saveTransactionHistory(ArrayList<InvestmentResultDto.TransactionHist
transactionHistory.forEach(th -> {
transactionHistoryRepository.save(TransactionHistoryConverter.toTransactionHistory(th, backTest));
});
}

public TransactionHistoryResponseDto getTransactionHistory(Long backtestId){

List<SalesTransactionHistory> transactionHistories = transactionHistoryRepository.findAllByBackTestId(backtestId).orElseThrow(() -> new RuntimeException("백테스트가 존재하지 않습니다."));

return TransactionHistoryConverter.toTransactionHistoryResultDto(transactionHistories);
}
}

0 comments on commit ef530fa

Please sign in to comment.