Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
Expand Up @@ -34,9 +34,6 @@
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
Expand Down Expand Up @@ -90,44 +87,29 @@ public final class EvaluatingBotRuntime implements BotRuntimeLifecycle {
private final EvaluationRunRecorder runRecorder;
private final PositionMetricSource positionMetricSource;
private final ExecutionGateStateSource executionGateStateSource;
private final TradingSessionCounter tradingSessionCounter;
private final BasicPlanInterpreter interpreter = new BasicPlanInterpreter();
private final BasicStrategyExecutor executor = new BasicStrategyExecutor();
private final BasicCandidateConverger converger = new BasicCandidateConverger();
private final Map<UUID, RegisteredBot> bots = new ConcurrentHashMap<>();

public EvaluatingBotRuntime(
CandidateBatchProcessor processor,
OrderCandidateBatchAdapter adapter,
BotScopeResolver scopeResolver,
EvaluationRunRecorder runRecorder) {
this(processor, adapter, scopeResolver, runRecorder,
PositionMetricSource.none(), ExecutionGateStateSource.none());
}

public EvaluatingBotRuntime(
CandidateBatchProcessor processor,
OrderCandidateBatchAdapter adapter,
BotScopeResolver scopeResolver,
EvaluationRunRecorder runRecorder,
PositionMetricSource positionMetricSource) {
this(processor, adapter, scopeResolver, runRecorder,
positionMetricSource, ExecutionGateStateSource.none());
}

public EvaluatingBotRuntime(
CandidateBatchProcessor processor,
OrderCandidateBatchAdapter adapter,
BotScopeResolver scopeResolver,
EvaluationRunRecorder runRecorder,
PositionMetricSource positionMetricSource,
ExecutionGateStateSource executionGateStateSource) {
ExecutionGateStateSource executionGateStateSource,
TradingSessionCounter tradingSessionCounter) {
this.processor = Objects.requireNonNull(processor, "processor");
this.adapter = Objects.requireNonNull(adapter, "adapter");
this.scopeResolver = Objects.requireNonNull(scopeResolver, "scopeResolver");
this.runRecorder = Objects.requireNonNull(runRecorder, "runRecorder");
this.positionMetricSource = Objects.requireNonNull(positionMetricSource, "positionMetricSource");
this.executionGateStateSource =
Objects.requireNonNull(executionGateStateSource, "executionGateStateSource");
this.tradingSessionCounter =
Objects.requireNonNull(tradingSessionCounter, "tradingSessionCounter");
}

@Override
Expand All @@ -146,7 +128,8 @@ public void start(LoadedExecutionPlan plan, PreparedWarmup warmup, EvaluationWin
}

bots.put(plan.botId(), new RegisteredBot(
plan.botId(), interpreted, instrumentStates, calculator, evaluationTimeframe, window));
plan.botId(), interpreted, instrumentStates, calculator, evaluationTimeframe, window,
tradingSessionCounter));
log.info("bot {} registered for evaluation over {} instruments within {}",
plan.botId(), interpreted.subscribedInstruments().size(), window);
}
Expand Down Expand Up @@ -482,6 +465,7 @@ private static final class RegisteredBot {
private final BoundedWindowFeatureCalculator calculator;
private final Set<StrategyEvaluationTimeframe> evaluationTimeframes;
private final EvaluationWindow window;
private final TradingSessionCounter tradingSessionCounter;
private final Map<UUID, BasicMarketSignalState> signalStates = new LinkedHashMap<>();
private final Map<UUID, PositionTracker> positionTrackers = new LinkedHashMap<>();
private final Map<String, ExecutionGate> executionGates = new LinkedHashMap<>();
Expand All @@ -492,13 +476,15 @@ private RegisteredBot(
Map<UUID, InstrumentRuntimeState> instrumentStates,
BoundedWindowFeatureCalculator calculator,
Set<StrategyEvaluationTimeframe> evaluationTimeframes,
EvaluationWindow window) {
EvaluationWindow window,
TradingSessionCounter tradingSessionCounter) {
this.botId = botId;
this.plan = plan;
this.instrumentStates = new LinkedHashMap<>(instrumentStates);
this.calculator = calculator;
this.evaluationTimeframes = Set.copyOf(evaluationTimeframes);
this.window = window;
this.tradingSessionCounter = tradingSessionCounter;
}

private UUID botId() {
Expand Down Expand Up @@ -540,7 +526,7 @@ private PositionTracker positionTracker(UUID instrumentId, PositionSnapshot snap
return current;
}
clearExecutionGates(instrumentId);
PositionTracker replacement = new PositionTracker(snapshot);
PositionTracker replacement = new PositionTracker(snapshot, tradingSessionCounter);
positionTrackers.put(instrumentId, replacement);
return replacement;
}
Expand All @@ -554,7 +540,8 @@ private void clearPositionTracker(UUID instrumentId) {
private ExecutionGate executionGate(
String flowId, UUID instrumentId, Supplier<ExecutionGateSnapshot> snapshot) {
return executionGates.computeIfAbsent(
flowId + ":" + instrumentId, ignored -> new ExecutionGate(snapshot.get()));
flowId + ":" + instrumentId,
ignored -> new ExecutionGate(snapshot.get(), tradingSessionCounter));
}

private void clearExecutionGates(UUID instrumentId) {
Expand All @@ -568,13 +555,17 @@ static final class ExecutionGate {
private int barsSinceExecution;
private Instant lastExecutionAt;
private boolean conditionRearmed = true;
private final TradingSessionCounter tradingSessionCounter;

ExecutionGate() {
this(ExecutionGateSnapshot.empty());
ExecutionGate(TradingSessionCounter tradingSessionCounter) {
this(ExecutionGateSnapshot.empty(), tradingSessionCounter);
}

ExecutionGate(ExecutionGateSnapshot snapshot) {
ExecutionGate(
ExecutionGateSnapshot snapshot, TradingSessionCounter tradingSessionCounter) {
Objects.requireNonNull(snapshot, "snapshot");
this.tradingSessionCounter =
Objects.requireNonNull(tradingSessionCounter, "tradingSessionCounter");
executions = snapshot.executions();
lastExecutionAt = snapshot.lastExecutionAt();
conditionRearmed = executions == 0;
Expand Down Expand Up @@ -604,7 +595,8 @@ boolean accepts(
|| switch (policy.waitMode()) {
case "조건 재충족" -> conditionRearmed;
case "N봉 이후" -> barsSinceExecution >= policy.waitInterval();
case "N거래일 이후" -> tradingDaysSince(lastExecutionAt, occurredAt)
case "N거래일 이후" -> tradingSessionCounter.elapsed(
lastExecutionAt, occurredAt)
>= policy.waitInterval();
default -> false;
};
Expand All @@ -618,18 +610,6 @@ boolean accepts(
return true;
}

private static long tradingDaysSince(Instant start, Instant end) {
LocalDate cursor = start.atZone(ZoneId.of("America/New_York")).toLocalDate();
LocalDate through = end.atZone(ZoneId.of("America/New_York")).toLocalDate();
long days = 0;
while (cursor.isBefore(through)) {
cursor = cursor.plusDays(1);
if (cursor.getDayOfWeek().getValue() <= 5) {
days++;
}
}
return days;
}
}

/** Mutable market and feature ordering for exactly one bot/instrument pair. */
Expand Down Expand Up @@ -664,21 +644,22 @@ private OrderedIncrementalFeatureRuntime features() {
}

static final class PositionTracker {
private static final ZoneId MARKET_ZONE = ZoneId.of("America/New_York");
private final BigDecimal averageEntryPrice;
private BigDecimal averageEntryPrice;
private final Instant openedAt;
private final TradingSessionCounter tradingSessionCounter;
private BigDecimal peakPrice;
private final Map<String, Long> closedBars = new LinkedHashMap<>();

PositionTracker(PositionSnapshot snapshot) {
PositionTracker(PositionSnapshot snapshot, TradingSessionCounter tradingSessionCounter) {
this.averageEntryPrice = snapshot.averageEntryPrice();
this.openedAt = snapshot.openedAt();
this.tradingSessionCounter =
Objects.requireNonNull(tradingSessionCounter, "tradingSessionCounter");
this.peakPrice = averageEntryPrice;
}

private boolean matches(PositionSnapshot snapshot) {
return averageEntryPrice.compareTo(snapshot.averageEntryPrice()) == 0
&& openedAt.equals(snapshot.openedAt());
return new PositionSnapshot(averageEntryPrice, openedAt).samePositionCycle(snapshot);
}

void publish(
Expand All @@ -687,11 +668,13 @@ void publish(
BigDecimal price,
Instant occurredAt,
Map<String, String> marketValues) {
averageEntryPrice = snapshot.averageEntryPrice();
peakPrice = peakPrice.max(price);
BigDecimal currentReturn = percentage(price.subtract(averageEntryPrice), averageEntryPrice);
BigDecimal peakReturn = percentage(peakPrice.subtract(averageEntryPrice), averageEntryPrice);
BigDecimal drawdown = percentage(peakPrice.subtract(price), peakPrice);
values.put("position.averageEntryPrice", averageEntryPrice.toPlainString());
values.put("position.openedAt", openedAt.toString());
values.put("position.returnPercent", currentReturn.toPlainString());
values.put("position.peakReturnPercent", peakReturn.toPlainString());
values.put("position.drawdownPercent", drawdown.toPlainString());
Expand All @@ -702,10 +685,8 @@ void publish(
values.put("position.holdingBars." + resolution,
Long.toString(closedBars.getOrDefault(resolution, 0L)));
}
LocalDate opened = openedAt.atZone(MARKET_ZONE).toLocalDate();
LocalDate current = occurredAt.atZone(MARKET_ZONE).toLocalDate();
values.put("position.holdingTradingDays",
Long.toString(tradingWeekdaysBetween(opened, current)));
Long.toString(tradingSessionCounter.elapsed(openedAt, occurredAt)));
}

/**
Expand All @@ -726,17 +707,6 @@ private static BigDecimal percentage(BigDecimal numerator, BigDecimal denominato
.divide(denominator, 8, java.math.RoundingMode.HALF_EVEN);
}

private static long tradingWeekdaysBetween(LocalDate start, LocalDate end) {
long count = 0;
for (long day = 0; day <= Math.max(0, ChronoUnit.DAYS.between(start, end)); day++) {
java.time.DayOfWeek weekday = start.plusDays(day).getDayOfWeek();
if (weekday != java.time.DayOfWeek.SATURDAY
&& weekday != java.time.DayOfWeek.SUNDAY) {
count++;
}
}
return Math.max(0, count - 1);
}
}

/** The canonical ids of one flow, which a candidate batch cannot be written without. */
Expand Down Expand Up @@ -810,5 +780,20 @@ public record PositionSnapshot(BigDecimal averageEntryPrice, Instant openedAt) {
throw new IllegalArgumentException("averageEntryPrice must be positive");
}
}

/**
* A position cycle lasts from the first opening fill until the position is fully closed.
* Scale-in and partial-exit fills may change the average price without starting a new
* cycle, while a later re-entry has a new opening instant.
*/
boolean samePositionCycle(PositionSnapshot other) {
return other != null && openedAt.equals(other.openedAt());
}
}

/** Counts elapsed sessions from the same official calendar used by market evaluation. */
@FunctionalInterface
public interface TradingSessionCounter {
long elapsed(Instant start, Instant end);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.idea2strategy.trading.worker.candidate.OrderCandidateBatchAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.simple.JdbcClient;

/**
Expand Down Expand Up @@ -39,16 +40,26 @@ PostgresExecutionGateStateSource executionGateStateSource(JdbcClient jdbc) {
return new PostgresExecutionGateStateSource(jdbc);
}

@Bean
PostgresTradingSessionCounter tradingSessionCounter(
JdbcClient jdbc,
@Value("${idea2strategy.market-data.exchange-mic:XNYS}") String exchangeMic,
@Value("${idea2strategy.market-data.calendar-version:exchange-calendars/XNYS}")
String calendarVersion) {
return new PostgresTradingSessionCounter(jdbc, exchangeMic, calendarVersion);
}

@Bean
EvaluatingBotRuntime evaluatingBotRuntime(
CandidateBatchProcessor processor,
OrderCandidateBatchAdapter adapter,
PostgresBotScopeResolver scopeResolver,
PostgresEvaluationRunRecorder runRecorder,
PostgresPositionMetricSource positionMetricSource,
PostgresExecutionGateStateSource executionGateStateSource) {
PostgresExecutionGateStateSource executionGateStateSource,
PostgresTradingSessionCounter tradingSessionCounter) {
return new EvaluatingBotRuntime(
processor, adapter, scopeResolver, runRecorder,
positionMetricSource, executionGateStateSource);
positionMetricSource, executionGateStateSource, tradingSessionCounter);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,19 @@ public Optional<EvaluatingBotRuntime.PositionSnapshot> resolve(UUID botId, UUID
&& position.costBasis() != null
&& position.openedAt() != null)
.map(position -> new EvaluatingBotRuntime.PositionSnapshot(
position.costBasis().divide(
position.quantity(), 8, java.math.RoundingMode.HALF_UP),
averageEntryPrice(position.costBasis(), position.quantity()),
position.openedAt().toInstant()));
}

static BigDecimal averageEntryPrice(BigDecimal costBasis, BigDecimal quantity) {
Objects.requireNonNull(costBasis, "costBasis");
Objects.requireNonNull(quantity, "quantity");
if (quantity.signum() <= 0) {
throw new IllegalArgumentException("quantity must be positive");
}
return costBasis.divide(quantity, 8, java.math.RoundingMode.HALF_EVEN);
}

private record RawPosition(
BigDecimal quantity, BigDecimal costBasis, OffsetDateTime openedAt) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package com.idea2strategy.trading.worker.runtime;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Objects;
import org.springframework.jdbc.core.simple.JdbcClient;

/** Counts elapsed sessions from the versioned canonical market calendar. */
final class PostgresTradingSessionCounter
implements EvaluatingBotRuntime.TradingSessionCounter {

private static final ZoneId MARKET_ZONE = ZoneId.of("America/New_York");
private static final String COUNT = """
select count(*) filter (
where session_date > :startDate
and session_date <= :endDate
and cast(session_type as varchar) <> 'CLOSED'
) as elapsed,
coalesce(bool_or(session_date = :startDate
and cast(session_type as varchar) <> 'CLOSED'), false) as start_session,
coalesce(bool_or(session_date = :endDate
and cast(session_type as varchar) <> 'CLOSED'), false) as end_session
from market_data.trading_sessions
where exchange_mic = :exchangeMic
and calendar_version = :calendarVersion
and session_date between :startDate and :endDate
""";

private final JdbcClient jdbc;
private final String exchangeMic;
private final String calendarVersion;

PostgresTradingSessionCounter(
JdbcClient jdbc, String exchangeMic, String calendarVersion) {
this.jdbc = Objects.requireNonNull(jdbc, "jdbc");
this.exchangeMic = requireText(exchangeMic, "exchangeMic");
this.calendarVersion = requireText(calendarVersion, "calendarVersion");
}

@Override
public long elapsed(Instant start, Instant end) {
Objects.requireNonNull(start, "start");
Objects.requireNonNull(end, "end");
LocalDate startDate = start.atZone(MARKET_ZONE).toLocalDate();
LocalDate endDate = end.atZone(MARKET_ZONE).toLocalDate();
if (endDate.isBefore(startDate)) {
throw new IllegalArgumentException("end must not precede start");
}
SessionCount count = jdbc.sql(COUNT)
.param("exchangeMic", exchangeMic)
.param("calendarVersion", calendarVersion)
.param("startDate", startDate)
.param("endDate", endDate)
.query((resultSet, rowNumber) -> new SessionCount(
resultSet.getLong("elapsed"),
resultSet.getBoolean("start_session"),
resultSet.getBoolean("end_session")))
.single();
if (!count.startSession() || !count.endSession()) {
throw new IllegalStateException(
"pinned market calendar does not cover both active session boundaries: "
+ startDate + ".." + endDate + " (" + calendarVersion + ")");
}
return count.elapsed();
}

private static String requireText(String value, String field) {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException(field + " must not be blank");
}
return value;
}

private record SessionCount(long elapsed, boolean startSession, boolean endSession) {}
}
Loading