전략알림 수정

This commit is contained in:
Macbook
2026-05-27 16:51:57 +09:00
parent d7ceb8cbfd
commit aca895e9fd
13 changed files with 701 additions and 123 deletions
@@ -57,6 +57,14 @@ public class StrategyController {
return ResponseEntity.ok(conditionTimeframes.collectForStrategyList(id)); return ResponseEntity.ok(conditionTimeframes.collectForStrategyList(id));
} }
/** TIMEFRAME 래핑 누락 DSL 보정 (3분봉 전략이 1분봉으로 평가되는 경우) */
@PostMapping("/{id}/repair-timeframes")
public ResponseEntity<StrategyDto> repairTimeframes(@PathVariable Long id) {
return service.repairTimeframeWrappers(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
/** 전략 삭제 */ /** 전략 삭제 */
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) { public ResponseEntity<Void> delete(@PathVariable Long id) {
@@ -72,7 +72,13 @@ public class StrategyConditionTimeframeService {
private void collectFromNode(JsonNode node, Set<String> out) { private void collectFromNode(JsonNode node, Set<String> out) {
if (node == null || node.isNull()) return; if (node == null || node.isNull()) return;
if (collectTimeframesFromNode(node, out)) return; if (collectTimeframesFromNode(node, out)) return;
// TIMEFRAME 래핑 없는 레거시 트리 — 기본 1m
Set<String> explicit = StrategyDslTimeframeNormalizer.collectExplicitCandleTypes(node);
if (!explicit.isEmpty()) {
out.addAll(explicit);
return;
}
// TIMEFRAME·명시 분봉 없음 — 기본 1m
out.add("1m"); out.add("1m");
} }
@@ -0,0 +1,137 @@
package com.goldenchart.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
/**
* 전략 DSL에 TIMEFRAME 래핑이 없으면 평가 분봉을 추론해 래핑한다.
* (프론트 encodeConditionForSave 와 동일 목적)
*/
@Component
@RequiredArgsConstructor
public class StrategyDslTimeframeNormalizer {
private final ObjectMapper objectMapper;
public JsonNode normalize(JsonNode root) {
if (root == null || root.isNull()) return root;
if (hasTimeframeScope(root)) return root;
String primary = inferPrimaryCandleType(root);
ObjectNode wrapped = objectMapper.createObjectNode();
wrapped.put("id", UUID.randomUUID().toString());
wrapped.put("type", "TIMEFRAME");
wrapped.put("candleType", primary);
ArrayNode children = objectMapper.createArrayNode();
children.add(root);
wrapped.set("children", children);
return wrapped;
}
public String normalizeJson(String json) {
if (json == null || json.isBlank()) return json;
try {
JsonNode root = objectMapper.readTree(json);
JsonNode normalized = normalize(root);
return objectMapper.writeValueAsString(normalized);
} catch (Exception e) {
return json;
}
}
/** 루트 TIMEFRAME 또는 AND|OR + 전부 TIMEFRAME 자식 */
public static boolean hasTimeframeScope(JsonNode node) {
if (node == null || node.isNull()) return false;
String type = node.path("type").asText("");
if ("TIMEFRAME".equals(type)) return true;
if ("AND".equals(type) || "OR".equals(type)) {
JsonNode children = node.path("children");
if (children.isArray() && !children.isEmpty()) {
for (JsonNode c : children) {
if (!"TIMEFRAME".equals(c.path("type").asText(""))) return false;
}
return true;
}
}
return findNestedTimeframe(node) != null;
}
private static JsonNode findNestedTimeframe(JsonNode node) {
if (node == null || node.isNull()) return null;
if ("TIMEFRAME".equals(node.path("type").asText(""))) return node;
JsonNode children = node.path("children");
if (children.isArray()) {
for (JsonNode c : children) {
JsonNode found = findNestedTimeframe(c);
if (found != null) return found;
}
}
JsonNode child = node.path("child");
if (!child.isMissingNode() && !child.isNull()) return findNestedTimeframe(child);
return null;
}
/**
* 트리에서 명시적 분봉 수집 — CONDITION 의 left/rightCandleType, TIMEFRAME 노드.
*/
public static Set<String> collectExplicitCandleTypes(JsonNode node) {
Set<String> out = new LinkedHashSet<>();
collectExplicitCandleTypes(node, out);
return out;
}
private static void collectExplicitCandleTypes(JsonNode node, Set<String> out) {
if (node == null || node.isNull()) return;
String type = node.path("type").asText("");
if ("TIMEFRAME".equals(type)) {
out.add(LiveStrategyTimeframeService.normalize(node.path("candleType").asText("1m")));
}
if ("CONDITION".equals(type)) {
JsonNode cond = node.path("condition");
if (!cond.isMissingNode() && !cond.isNull()) {
if (cond.has("leftCandleType") && !cond.path("leftCandleType").asText("").isBlank()) {
out.add(LiveStrategyTimeframeService.normalize(cond.path("leftCandleType").asText()));
}
if (cond.has("rightCandleType") && !cond.path("rightCandleType").asText("").isBlank()) {
out.add(LiveStrategyTimeframeService.normalize(cond.path("rightCandleType").asText()));
}
}
}
JsonNode children = node.path("children");
if (children.isArray()) {
for (JsonNode c : children) collectExplicitCandleTypes(c, out);
}
JsonNode child = node.path("child");
if (!child.isMissingNode() && !child.isNull()) collectExplicitCandleTypes(child, out);
}
public static String inferPrimaryCandleType(JsonNode node) {
JsonNode nested = findNestedTimeframe(node);
if (nested != null) {
return LiveStrategyTimeframeService.normalize(nested.path("candleType").asText("1m"));
}
Set<String> explicit = collectExplicitCandleTypes(node);
if (explicit.isEmpty()) return "1m";
Set<String> non1m = new LinkedHashSet<>();
for (String ct : explicit) {
if (!"1m".equals(ct)) non1m.add(ct);
}
if (non1m.size() == 1) return non1m.iterator().next();
if (non1m.size() > 1) return non1m.iterator().next();
if (explicit.size() == 1) return explicit.iterator().next();
return explicit.iterator().next();
}
}
@@ -22,6 +22,7 @@ public class StrategyService {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final StrategyConditionTimeframeService conditionTimeframes; private final StrategyConditionTimeframeService conditionTimeframes;
private final LiveStrategyEvaluator liveStrategyEvaluator; private final LiveStrategyEvaluator liveStrategyEvaluator;
private final StrategyDslTimeframeNormalizer dslTimeframeNormalizer;
// ── 조회 ────────────────────────────────────────────────────────────────── // ── 조회 ──────────────────────────────────────────────────────────────────
@@ -56,9 +57,13 @@ public class StrategyService {
try { try {
entity.setBuyConditionJson( entity.setBuyConditionJson(
dto.getBuyCondition() != null ? objectMapper.writeValueAsString(dto.getBuyCondition()) : null); dto.getBuyCondition() != null
? dslTimeframeNormalizer.normalizeJson(objectMapper.writeValueAsString(dto.getBuyCondition()))
: null);
entity.setSellConditionJson( entity.setSellConditionJson(
dto.getSellCondition() != null ? objectMapper.writeValueAsString(dto.getSellCondition()) : null); dto.getSellCondition() != null
? dslTimeframeNormalizer.normalizeJson(objectMapper.writeValueAsString(dto.getSellCondition()))
: null);
} catch (Exception e) { } catch (Exception e) {
log.warn("전략 DSL 직렬화 실패: {}", e.getMessage()); log.warn("전략 DSL 직렬화 실패: {}", e.getMessage());
} }
@@ -69,6 +74,37 @@ public class StrategyService {
return toDto(saved); return toDto(saved);
} }
/**
* DB에 저장된 매수/매도 DSL에 TIMEFRAME 래핑이 없으면 보정 후 저장.
* (편집기 재저장 없이 기존 3분봉 전략 등을 즉시 수정할 때)
*/
@Transactional
public Optional<StrategyDto> repairTimeframeWrappers(Long id) {
return repository.findById(id).map(entity -> {
boolean changed = false;
if (entity.getBuyConditionJson() != null && !entity.getBuyConditionJson().isBlank()) {
String fixed = dslTimeframeNormalizer.normalizeJson(entity.getBuyConditionJson());
if (!fixed.equals(entity.getBuyConditionJson())) {
entity.setBuyConditionJson(fixed);
changed = true;
}
}
if (entity.getSellConditionJson() != null && !entity.getSellConditionJson().isBlank()) {
String fixed = dslTimeframeNormalizer.normalizeJson(entity.getSellConditionJson());
if (!fixed.equals(entity.getSellConditionJson())) {
entity.setSellConditionJson(fixed);
changed = true;
}
}
if (!changed) return toDto(entity);
GcStrategy saved = repository.save(entity);
conditionTimeframes.invalidate(saved.getId());
liveStrategyEvaluator.invalidateStrategy(saved.getId());
log.info("[Strategy] TIMEFRAME 래핑 보정 strategyId={}", id);
return toDto(saved);
});
}
// ── 삭제 ────────────────────────────────────────────────────────────────── // ── 삭제 ──────────────────────────────────────────────────────────────────
@Transactional @Transactional
@@ -107,7 +107,8 @@ public class StrategyTriggerBranchEvaluator {
return new BranchScope("SINGLE", List.of(new BranchDef(ct, sub != null && !sub.isNull() ? sub : node))); return new BranchScope("SINGLE", List.of(new BranchDef(ct, sub != null && !sub.isNull() ? sub : node)));
} }
return new BranchScope("SINGLE", List.of(new BranchDef("1m", node))); String inferred = StrategyDslTimeframeNormalizer.inferPrimaryCandleType(node);
return new BranchScope("SINGLE", List.of(new BranchDef(inferred, node)));
} }
/** 레거시 DSL — 루트가 TIMEFRAME이 아닐 때 하위 TIMEFRAME 래퍼 탐색 */ /** 레거시 DSL — 루트가 TIMEFRAME이 아닐 때 하위 TIMEFRAME 래퍼 탐색 */
+66
View File
@@ -11243,6 +11243,72 @@ html.theme-light .tam-disclaimer { color: #90a4ae; }
color: var(--text); color: var(--text);
overflow: hidden; overflow: hidden;
} }
.tnl-page--with-right .tnl-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: row;
overflow: hidden;
}
.tnl-page--with-right .tnl-main {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.tnl-page--with-right .tnl-right {
flex: 0 0 min(380px, 38vw);
width: min(380px, 38vw);
min-width: 300px;
max-width: 420px;
display: flex;
flex-direction: column;
border-left: 1px solid var(--border);
background: var(--bg2);
overflow: hidden;
}
.tnl-right-tabs {
flex-shrink: 0;
border-bottom: 1px solid var(--border);
}
.tnl-right-body {
flex: 1;
min-height: 0;
overflow: hidden;
display: flex;
flex-direction: column;
}
.tnl-page--with-right .ptd-right-body {
flex: 1;
min-height: 0;
}
.tnl-page--with-right .ptd-split-panel--right {
height: 100%;
}
.tnl-page--with-right .ptd-ob-stack--fill {
height: 100%;
}
.tnl-row--selected {
border-color: var(--accent, #7aa2f7);
box-shadow: 0 0 0 1px rgba(122, 162, 247, 0.35);
}
.tnl-row-action {
flex-shrink: 0;
align-self: center;
margin-right: 4px;
padding: 6px 10px;
font-size: 11px;
border-radius: 4px;
border: 1px solid var(--border);
background: var(--bg3);
color: var(--text2);
cursor: pointer;
}
.tnl-row-action:hover {
color: var(--text);
border-color: var(--accent, #7aa2f7);
}
.tnl-header { .tnl-header {
padding: 20px 24px 12px; padding: 20px 24px 12px;
border-bottom: 1px solid var(--border); border-bottom: 1px solid var(--border);
+5
View File
@@ -1719,6 +1719,11 @@ function App() {
{menuPage === 'notifications' && ( {menuPage === 'notifications' && (
<TradeNotificationListPage <TradeNotificationListPage
theme={theme} theme={theme}
tickers={marketTickers}
defaultMarket={symbol}
paperTradingEnabled={paperTradingEnabled}
paperAutoTradeEnabled={paperAutoTradeEnabled}
onPaperOrderFilled={handlePaperOrderFilled}
onGoToChart={market => { onGoToChart={market => {
goToMarketChart(market); goToMarketChart(market);
setMenuPage('chart'); setMenuPage('chart');
@@ -1,18 +1,52 @@
/** /**
* 매매 시그널 알림 목록 화면 * 매매 시그널 알림 목록 화면 — 좌: 알림 목록, 우: 매매·호가 (가상매매 우측 패널과 동일)
*/ */
import React, { useCallback } from 'react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { Theme } from '../types'; import type { Theme, TradeOrderFillRequest } from '../types';
import type { TickerData } from '../hooks/useMarketTicker';
import { useTradeNotification, type TradeNotificationItem } from '../contexts/TradeNotificationContext'; import { useTradeNotification, type TradeNotificationItem } from '../contexts/TradeNotificationContext';
import { buildSignalDetailRows, formatSignalPrice, getSignalHeadline } from '../utils/tradeSignalDisplay'; import { buildSignalDetailRows, formatSignalPrice, getSignalHeadline } from '../utils/tradeSignalDisplay';
import { loadPaperSummary, type PaperSummaryDto } from '../utils/backendApi';
import { coerceFiniteNumber } from '../utils/safeFormat';
import TradeOrderPanel from './TradeOrderPanel';
import { OrderbookPanel } from './OrderbookPanel';
import PaperSplitPanel from './paper/PaperSplitPanel';
import { useUpbitOrderbook } from '../hooks/useUpbitOrderbook';
import { useUpbitRecentTrades } from '../hooks/useUpbitRecentTrades';
import '../styles/virtualTradingDashboard.css';
type RightTab = 'trade' | 'orderbook';
interface Props { interface Props {
theme: Theme; theme: Theme;
onGoToChart: (market: string) => void; onGoToChart: (market: string) => void;
tickers?: Map<string, TickerData>;
defaultMarket?: string;
paperTradingEnabled?: boolean;
paperAutoTradeEnabled?: boolean;
onPaperOrderFilled?: () => void;
} }
function fillBothSides(
market: string,
price: number,
setFillBuy: React.Dispatch<React.SetStateAction<TradeOrderFillRequest | null>>,
setFillSell: React.Dispatch<React.SetStateAction<TradeOrderFillRequest | null>>,
) {
const seq = Date.now();
setFillBuy({ market, price, side: 'buy', seq });
setFillSell({ market, price, side: 'sell', seq: seq + 1 });
}
export const TradeNotificationListPage: React.FC<Props> = ({ theme, onGoToChart }) => { export const TradeNotificationListPage: React.FC<Props> = ({
theme,
onGoToChart,
tickers,
defaultMarket = 'KRW-BTC',
paperTradingEnabled = true,
paperAutoTradeEnabled = false,
onPaperOrderFilled,
}) => {
const { const {
allNotifications, allNotifications,
unreadCount, unreadCount,
@@ -22,23 +56,97 @@ export const TradeNotificationListPage: React.FC<Props> = ({ theme, onGoToChart
refreshHistory, refreshHistory,
} = useTradeNotification(); } = useTradeNotification();
const [filter, setFilter] = React.useState<'all' | 'unread'>('all'); const [filter, setFilter] = useState<'all' | 'unread'>('all');
const [selectedMarket, setSelectedMarket] = useState(defaultMarket);
const [selectedNotifyId, setSelectedNotifyId] = useState<string | null>(null);
const [rightTab, setRightTab] = useState<RightTab>('trade');
const [fillBuy, setFillBuy] = useState<TradeOrderFillRequest | null>(null);
const [fillSell, setFillSell] = useState<TradeOrderFillRequest | null>(null);
const [summary, setSummary] = useState<PaperSummaryDto | null>(null);
const orderAnchorRef = useRef<HTMLDivElement>(null);
const refreshPaperData = useCallback(async () => {
try {
const s = await loadPaperSummary();
setSummary(s);
} catch {
setSummary(null);
}
onPaperOrderFilled?.();
}, [onPaperOrderFilled]);
useEffect(() => {
void refreshPaperData();
}, [refreshPaperData]);
const tradePrice = useMemo(
() => coerceFiniteNumber(tickers?.get(selectedMarket)?.tradePrice),
[tickers, selectedMarket],
);
const posQty = useMemo(() => {
const p = summary?.positions?.find(x => x.symbol === selectedMarket);
return coerceFiniteNumber(p?.quantity) ?? 0;
}, [summary?.positions, selectedMarket]);
const { orderbook, wsStatus: obWsStatus, spread } = useUpbitOrderbook(selectedMarket);
const { trades: recentTrades, strength: tradeStrength } = useUpbitRecentTrades(selectedMarket);
const selectedTicker = tickers?.get(selectedMarket);
const orderbookPrevClose = selectedTicker
? (selectedTicker.tradePrice ?? 0) - (selectedTicker.changePrice ?? 0)
: 0;
const orderbookTickerInfo = selectedTicker ? {
tradePrice: selectedTicker.tradePrice,
changeRate: selectedTicker.changeRate,
changePrice: selectedTicker.changePrice,
accTradePrice24: selectedTicker.accTradePrice24,
accTradeVolume24: selectedTicker.accTradeVolume24,
highPrice: selectedTicker.highPrice,
lowPrice: selectedTicker.lowPrice,
openingPrice: selectedTicker.openingPrice,
} : undefined;
const handleSelectMarket = useCallback((market: string, price?: number) => {
setSelectedMarket(market);
const p = price ?? coerceFiniteNumber(tickers?.get(market)?.tradePrice);
if (p != null && p > 0) {
fillBothSides(market, p, setFillBuy, setFillSell);
}
setRightTab('trade');
}, [tickers]);
const handleNotificationSelect = useCallback((item: TradeNotificationItem) => {
if (!item.isRead) markAsRead(item.id);
setSelectedNotifyId(item.id);
const price = coerceFiniteNumber(item.price);
if (price != null && price > 0) {
fillBothSides(item.market, price, setFillBuy, setFillSell);
} else {
handleSelectMarket(item.market);
}
setRightTab('trade');
}, [markAsRead, handleSelectMarket]);
const handleOrderbookRowClick = useCallback((price: number, rowType: 'ask' | 'bid') => {
setRightTab('trade');
const side = rowType === 'bid' ? 'buy' : 'sell';
const req: TradeOrderFillRequest = { market: selectedMarket, price, side, seq: Date.now() };
if (side === 'buy') setFillBuy(req);
else setFillSell(req);
}, [selectedMarket]);
const filtered = filter === 'unread' const filtered = filter === 'unread'
? allNotifications.filter(n => !n.isRead) ? allNotifications.filter(n => !n.isRead)
: allNotifications; : allNotifications;
const handleRow = useCallback((item: TradeNotificationItem) => {
if (!item.isRead) markAsRead(item.id);
openDetail(item, { centered: true });
}, [markAsRead, openDetail]);
return ( return (
<div className={`tnl-page app ${theme}`}> <div className={`tnl-page tnl-page--with-right bps-page--vtd app ${theme}`}>
<div className="tnl-body">
<div className="tnl-main">
<div className="tnl-header"> <div className="tnl-header">
<h1 className="tnl-title"> </h1> <h1 className="tnl-title"> </h1>
<p className="tnl-sub"> <p className="tnl-sub">
BUY/SELL . · . · .
</p> </p>
<div className="tnl-toolbar"> <div className="tnl-toolbar">
<span className="tnl-chip tnl-chip--warn"> {unreadCount}</span> <span className="tnl-chip tnl-chip--warn"> {unreadCount}</span>
@@ -77,15 +185,16 @@ export const TradeNotificationListPage: React.FC<Props> = ({ theme, onGoToChart
{filtered.map(item => { {filtered.map(item => {
const isBuy = item.signalType === 'BUY'; const isBuy = item.signalType === 'BUY';
const detailRows = buildSignalDetailRows(item); const detailRows = buildSignalDetailRows(item);
const isSelected = selectedNotifyId === item.id;
return ( return (
<li <li
key={item.id} key={item.id}
className={`tnl-row ${!item.isRead ? 'tnl-row--unread' : ''}`} className={`tnl-row ${!item.isRead ? 'tnl-row--unread' : ''}${isSelected ? ' tnl-row--selected' : ''}`}
> >
<button <button
type="button" type="button"
className="tnl-row-main" className="tnl-row-main"
onClick={() => handleRow(item)} onClick={() => handleNotificationSelect(item)}
> >
<span className={`tnl-signal ${isBuy ? 'tnl-signal--buy' : 'tnl-signal--sell'}`}> <span className={`tnl-signal ${isBuy ? 'tnl-signal--buy' : 'tnl-signal--sell'}`}>
{item.signalType} {item.signalType}
@@ -104,6 +213,17 @@ export const TradeNotificationListPage: React.FC<Props> = ({ theme, onGoToChart
</span> </span>
{!item.isRead && <span className="tnl-dot" aria-hidden />} {!item.isRead && <span className="tnl-dot" aria-hidden />}
</button> </button>
<button
type="button"
className="tnl-row-action"
title="상세 보기"
onClick={() => {
if (!item.isRead) markAsRead(item.id);
openDetail(item, { centered: true });
}}
>
</button>
<button <button
type="button" type="button"
className="tnl-row-chart" className="tnl-row-chart"
@@ -122,6 +242,94 @@ export const TradeNotificationListPage: React.FC<Props> = ({ theme, onGoToChart
)} )}
</div> </div>
</div> </div>
<aside className="tnl-right" aria-label="매매·호가">
<div className="bps-right-tabs tnl-right-tabs">
<button
type="button"
className={`bps-right-tab${rightTab === 'trade' ? ' bps-right-tab--on' : ''}`}
onClick={() => setRightTab('trade')}
>
</button>
<button
type="button"
className={`bps-right-tab${rightTab === 'orderbook' ? ' bps-right-tab--on' : ''}`}
onClick={() => setRightTab('orderbook')}
>
</button>
</div>
<div className="tnl-right-body ptd-right-body" ref={orderAnchorRef}>
{rightTab === 'trade' ? (
<PaperSplitPanel
className="ptd-split-panel--right"
topTitle="매수"
bottomTitle="매도"
top={(
<div className="ptd-order-card">
<TradeOrderPanel
side="buy"
market={selectedMarket}
tradePrice={tradePrice}
availableKrw={coerceFiniteNumber(summary?.cashBalance) ?? 0}
fillRequest={fillBuy}
searchAnchorRef={orderAnchorRef}
onMarketSelect={m => handleSelectMarket(m)}
showSymbolField
paperTradingEnabled={paperTradingEnabled}
paperAutoTradeEnabled={paperAutoTradeEnabled}
onPaperOrderFilled={() => void refreshPaperData()}
/>
</div>
)}
bottom={(
<div className="ptd-order-card">
<TradeOrderPanel
side="sell"
market={selectedMarket}
tradePrice={tradePrice}
availableCoinQty={posQty}
fillRequest={fillSell}
onMarketSelect={m => handleSelectMarket(m)}
showSymbolField={false}
paperTradingEnabled={paperTradingEnabled}
paperAutoTradeEnabled={paperAutoTradeEnabled}
onPaperOrderFilled={() => void refreshPaperData()}
/>
</div>
)}
/>
) : (
<div className="rsp-ob-stack ptd-ob-stack--fill">
<div className="rsp-trade-card rsp-ob-card">
<div className="rsp-trade-card-title rsp-ob-card-title"> </div>
<div className="rsp-trade-card-body rsp-ob-card-body">
<OrderbookPanel
market={selectedMarket}
asks={orderbook.asks}
bids={orderbook.bids}
totalAskSize={orderbook.totalAskSize}
totalBidSize={orderbook.totalBidSize}
wsStatus={obWsStatus}
bestAsk={spread.bestAsk}
bestBid={spread.bestBid}
spread={spread.spread}
spreadPct={spread.pct}
prevClose={orderbookPrevClose}
tickerInfo={orderbookTickerInfo}
recentTrades={recentTrades}
tradeStrength={tradeStrength}
onRowClick={handleOrderbookRowClick}
/>
</div>
</div>
</div>
)}
</div>
</aside>
</div>
</div>
); );
}; };
@@ -45,6 +45,7 @@ export const TradeSignalSnackbar: React.FC<Props> = ({
toastNotifications, toastNotifications,
dismissToast, dismissToast,
dismissToasts, dismissToasts,
dismissAllToasts,
openDetail, openDetail,
} = useTradeNotification(); } = useTradeNotification();
@@ -94,10 +95,10 @@ export const TradeSignalSnackbar: React.FC<Props> = ({
const dismissAll = useCallback(() => { const dismissAll = useCallback(() => {
if (toastNotifications.length === 0) return; if (toastNotifications.length === 0) return;
dismissToasts(toastNotifications.map(n => n.id)); dismissAllToasts();
setPageIndex(0); setPageIndex(0);
positionsRef.current = {}; positionsRef.current = {};
}, [dismissToasts, toastNotifications]); }, [dismissAllToasts, toastNotifications.length]);
const dismissCurrentPage = useCallback(() => { const dismissCurrentPage = useCallback(() => {
const ids = pageItems.map(i => i.id); const ids = pageItems.map(i => i.id);
@@ -122,6 +122,8 @@ export const TradeNotificationProvider: React.FC<ProviderProps> = ({
}) => { }) => {
const alertSoundId = normalizeTradeAlertSoundId(soundId) as TradeAlertSoundId; const alertSoundId = normalizeTradeAlertSoundId(soundId) as TradeAlertSoundId;
const [readIds, setReadIds] = useState<Set<string>>(() => loadReadIds()); const [readIds, setReadIds] = useState<Set<string>>(() => loadReadIds());
const readIdsRef = useRef(readIds);
readIdsRef.current = readIds;
const [toastNotifications, setToastNotifications] = useState<TradeNotificationItem[]>([]); const [toastNotifications, setToastNotifications] = useState<TradeNotificationItem[]>([]);
const toastNotificationsRef = useRef(toastNotifications); const toastNotificationsRef = useRef(toastNotifications);
toastNotificationsRef.current = toastNotifications; toastNotificationsRef.current = toastNotifications;
@@ -137,15 +139,32 @@ export const TradeNotificationProvider: React.FC<ProviderProps> = ({
const refreshHistory = useCallback(async () => { const refreshHistory = useCallback(async () => {
try { try {
const dtos = await loadTradeSignals(); const dtos = await loadTradeSignals();
const items = dtos.map(d => dtoToItem(d, readIds)); /** dismiss 직후 비동기 완료 시 state readIds가 늦게 반영되는 것 방지 */
const read = loadReadIds();
const items = dtos.map(d => dtoToItem(d, read));
let newlyArrived: TradeNotificationItem[] = [];
setAllNotifications(prev => { setAllNotifications(prev => {
const isBoot = prev.length === 0; newlyArrived = items.filter(
const newlyArrived = items.filter(
item => !item.isRead && !prev.some(p => p.id === item.id), item => !item.isRead && !prev.some(p => p.id === item.id),
); );
if (!isBoot && popupEnabled && newlyArrived.length > 0) { const map = new Map<string, TradeNotificationItem>();
for (const n of items) {
const wasRead = read.has(n.id) || prev.find(p => p.id === n.id)?.isRead;
map.set(n.id, wasRead ? { ...n, isRead: true } : n);
}
for (const n of prev) {
if (!map.has(n.id)) map.set(n.id, n);
else if (n.isRead) map.set(n.id, { ...map.get(n.id)!, isRead: true });
}
return [...map.values()]
.sort((a, b) => b.receivedAt - a.receivedAt)
.slice(0, MAX_HISTORY);
});
if (popupEnabled && newlyArrived.length > 0) {
setToastNotifications(tprev => { setToastNotifications(tprev => {
const map = new Map(tprev.map(t => [t.id, t])); const map = new Map(tprev.map(t => [t.id, t]));
for (const n of newlyArrived) map.set(n.id, n); for (const n of newlyArrived) map.set(n.id, n);
@@ -155,20 +174,10 @@ export const TradeNotificationProvider: React.FC<ProviderProps> = ({
playTradeAlertSound(alertSoundId); playTradeAlertSound(alertSoundId);
} }
} }
const map = new Map<string, TradeNotificationItem>();
for (const n of items) map.set(n.id, n);
for (const n of prev) {
if (!map.has(n.id)) map.set(n.id, n);
}
return [...map.values()]
.sort((a, b) => b.receivedAt - a.receivedAt)
.slice(0, MAX_HISTORY);
});
} catch (e) { } catch (e) {
console.warn('[TradeNotification] 이력 로드 실패:', e); console.warn('[TradeNotification] 이력 로드 실패:', e);
} }
}, [readIds, popupEnabled, soundEnabled, alertSoundId]); }, [popupEnabled, soundEnabled, alertSoundId]);
useEffect(() => { useEffect(() => {
void refreshHistory(); void refreshHistory();
@@ -179,6 +188,7 @@ export const TradeNotificationProvider: React.FC<ProviderProps> = ({
const next = new Set(prev); const next = new Set(prev);
next.add(id); next.add(id);
saveReadIds(next); saveReadIds(next);
readIdsRef.current = next;
return next; return next;
}); });
setToastNotifications(prev => prev.filter(n => n.id !== id)); setToastNotifications(prev => prev.filter(n => n.id !== id));
@@ -195,6 +205,7 @@ export const TradeNotificationProvider: React.FC<ProviderProps> = ({
const next = new Set(prev); const next = new Set(prev);
next.delete(id); next.delete(id);
saveReadIds(next); saveReadIds(next);
readIdsRef.current = next;
return next; return next;
}); });
const item: TradeNotificationItem = { const item: TradeNotificationItem = {
@@ -238,16 +249,30 @@ export const TradeNotificationProvider: React.FC<ProviderProps> = ({
const dismissToasts = useCallback((ids: string[]) => { const dismissToasts = useCallback((ids: string[]) => {
if (ids.length === 0) return; if (ids.length === 0) return;
const idSet = new Set(ids); const idSet = new Set(ids);
const toastSnapshot = toastNotificationsRef.current;
setReadIds(r => { setReadIds(r => {
const next = new Set(r); const next = new Set(r);
ids.forEach(i => next.add(i)); ids.forEach(i => next.add(i));
saveReadIds(next); saveReadIds(next);
readIdsRef.current = next;
return next; return next;
}); });
setToastNotifications(prev => prev.filter(n => !idSet.has(n.id))); setToastNotifications(prev => prev.filter(n => !idSet.has(n.id)));
setAllNotifications(all => setAllNotifications(all => {
all.map(n => (idSet.has(n.id) ? { ...n, isRead: true } : n)), const byId = new Map(all.map(n => [n.id, n]));
); for (const id of ids) {
const existing = byId.get(id);
if (existing) {
byId.set(id, { ...existing, isRead: true });
} else {
const fromToast = toastSnapshot.find(n => n.id === id);
if (fromToast) byId.set(id, { ...fromToast, isRead: true });
}
}
return [...byId.values()]
.sort((a, b) => b.receivedAt - a.receivedAt)
.slice(0, MAX_HISTORY);
});
}, []); }, []);
const dismissAllToasts = useCallback(() => { const dismissAllToasts = useCallback(() => {
@@ -259,24 +284,33 @@ export const TradeNotificationProvider: React.FC<ProviderProps> = ({
const next = new Set(r); const next = new Set(r);
idSet.forEach(i => next.add(i)); idSet.forEach(i => next.add(i));
saveReadIds(next); saveReadIds(next);
readIdsRef.current = next;
return next; return next;
}); });
setToastNotifications([]); setToastNotifications([]);
setAllNotifications(all => setAllNotifications(all => {
all.map(n => (idSet.has(n.id) ? { ...n, isRead: true } : n)), const byId = new Map(all.map(n => [n.id, n]));
); for (const n of snapshot) {
const existing = byId.get(n.id);
byId.set(n.id, existing ? { ...existing, isRead: true } : { ...n, isRead: true });
}
return [...byId.values()]
.sort((a, b) => b.receivedAt - a.receivedAt)
.slice(0, MAX_HISTORY);
});
}, []); }, []);
const markAllAsRead = useCallback(() => { const markAllAsRead = useCallback(() => {
setAllNotifications(prev => { setAllNotifications(prev => {
const nextRead = new Set(readIds); const nextRead = new Set(loadReadIds());
prev.forEach(n => nextRead.add(n.id)); prev.forEach(n => nextRead.add(n.id));
saveReadIds(nextRead); saveReadIds(nextRead);
readIdsRef.current = nextRead;
setReadIds(nextRead); setReadIds(nextRead);
return prev.map(n => ({ ...n, isRead: true })); return prev.map(n => ({ ...n, isRead: true }));
}); });
setToastNotifications([]); setToastNotifications([]);
}, [readIds]); }, []);
const openDetail = useCallback((item: TradeNotificationItem, options?: { centered?: boolean }) => { const openDetail = useCallback((item: TradeNotificationItem, options?: { centered?: boolean }) => {
setDetailCentered(options?.centered ?? false); setDetailCentered(options?.centered ?? false);
+5
View File
@@ -1129,6 +1129,11 @@ export async function loadStrategyTimeframes(strategyId: number): Promise<string
return list?.length ? list : ['1m']; return list?.length ? list : ['1m'];
} }
/** DB DSL TIMEFRAME 래핑 보정 (3분봉 전략이 1m으로 평가되는 레거시 수정) */
export async function repairStrategyTimeframes(strategyId: number): Promise<void> {
await request(`/strategies/${strategyId}/repair-timeframes`, { method: 'POST' });
}
/** 차트 실시간 파이프라인 pin (STOMP warm-up) */ /** 차트 실시간 파이프라인 pin (STOMP warm-up) */
export async function pinCandleWatch(market: string, candleType: string): Promise<void> { export async function pinCandleWatch(market: string, candleType: string): Promise<void> {
try { try {
+71 -5
View File
@@ -1,4 +1,4 @@
import type { LogicNode } from './strategyTypes'; import type { LogicNode, ConditionDSL } from './strategyTypes';
import { generateNodeId } from './strategyTypes'; import { generateNodeId } from './strategyTypes';
import { subtreeToFlatOrphans } from './strategyFlowLayout'; import { subtreeToFlatOrphans } from './strategyFlowLayout';
import { import {
@@ -82,16 +82,79 @@ export function updateBranchRoot(
}; };
} }
/** START 분봉 변경 시 조건 노드의 left/rightCandleType 동기화 */
function syncSubtreeCandleTypes(node: LogicNode | null, candleType: string): LogicNode | null {
if (!node) return null;
const ct = normalizeStartCandleType(candleType);
if (node.type === 'CONDITION' && node.condition) {
const cond = node.condition as ConditionDSL;
return {
...node,
condition: {
...cond,
leftCandleType: ct,
rightCandleType: ct,
},
};
}
if (node.children?.length) {
return {
...node,
children: node.children.map(c => syncSubtreeCandleTypes(c, ct)).filter(Boolean) as LogicNode[],
};
}
return node;
}
function collectExplicitCandleTypesFromTree(node: LogicNode | null, out: Set<string>): void {
if (!node) return;
if (node.type === 'TIMEFRAME' && node.candleType) {
out.add(normalizeStartCandleType(node.candleType));
}
if (node.type === 'CONDITION' && node.condition) {
const c = node.condition as ConditionDSL;
if (c.leftCandleType) out.add(normalizeStartCandleType(c.leftCandleType));
if (c.rightCandleType) out.add(normalizeStartCandleType(c.rightCandleType));
}
node.children?.forEach(ch => collectExplicitCandleTypesFromTree(ch, out));
}
function inferPrimaryCandleFromTree(root: LogicNode | null): string {
const set = new Set<string>();
collectExplicitCandleTypesFromTree(root, set);
const non1m = [...set].filter(ct => ct !== '1m');
if (non1m.length >= 1) return non1m[0];
if (set.size >= 1) return [...set][0];
return DEFAULT_START_CANDLE;
}
export function updateStartCandleType( export function updateStartCandleType(
state: EditorConditionState, state: EditorConditionState,
startId: string, startId: string,
candleType: string, candleType: string,
): EditorConditionState { ): EditorConditionState {
const ct = normalizeStartCandleType(candleType);
const nextMeta = {
...state.startMeta,
[startId]: { candleType: ct },
};
if (startId === START_NODE_ID) {
return { return {
...state, ...state,
startMeta: { startMeta: nextMeta,
...state.startMeta, root: syncSubtreeCandleTypes(state.root, ct),
[startId]: { candleType: normalizeStartCandleType(candleType) }, };
}
return {
...state,
startMeta: nextMeta,
extraRoots: {
...state.extraRoots,
[startId]: syncSubtreeCandleTypes(state.extraRoots[startId] ?? null, ct),
}, },
}; };
} }
@@ -225,9 +288,12 @@ export function decodeConditionForEditor(dsl: LogicNode | null): EditorCondition
}; };
} }
const inferred = inferPrimaryCandleFromTree(dsl);
return { return {
root: dsl, root: dsl,
startMeta: defaultStartMeta(), startMeta: {
[START_NODE_ID]: { candleType: inferred },
},
extraStartIds: [], extraStartIds: [],
extraRoots: {}, extraRoots: {},
startCombineOp: DEFAULT_START_COMBINE_OP, startCombineOp: DEFAULT_START_COMBINE_OP,
+6 -1
View File
@@ -1,4 +1,4 @@
import { loadStrategyTimeframes, pinCandleWatch } from './backendApi'; import { loadStrategyTimeframes, pinCandleWatch, repairStrategyTimeframes } from './backendApi';
import { normalizeStartCandleType } from './strategyStartNodes'; import { normalizeStartCandleType } from './strategyStartNodes';
/** 전략 DSL 평가 분봉 전체 pin — 1m 집계·상위 봉 warm-up */ /** 전략 DSL 평가 분봉 전체 pin — 1m 집계·상위 봉 warm-up */
@@ -6,6 +6,11 @@ export async function pinStrategyEvaluationTimeframes(
market: string, market: string,
strategyId: number, strategyId: number,
): Promise<string[]> { ): Promise<string[]> {
try {
await repairStrategyTimeframes(strategyId);
} catch {
/* 서버 미배포·권한 등 — timeframes 조회만 진행 */
}
const raw = await loadStrategyTimeframes(strategyId); const raw = await loadStrategyTimeframes(strategyId);
const timeframes = [...new Set(raw.map(tf => normalizeStartCandleType(tf)))]; const timeframes = [...new Set(raw.map(tf => normalizeStartCandleType(tf)))];
if (timeframes.length === 0) timeframes.push('1m'); if (timeframes.length === 0) timeframes.push('1m');