DATA/UPBIT/daemon/target/day_time_code_1.php
<?php
// day_time_code_1.php (시간 간격 단순 시장가 매수)

// 1. [지갑 & DB 공유] 데몬 스코프 상속
global $upbit, $db_upbit;

// [추가] 매매 장부 데이터 갱신 파일 로드
include_once('./db_trading.php');

// 2. [실행 여부 체크]
if (($row['x2_run'] ?? '') != '1') return;

// 3. [기본 옵션 가져오기]
$coin_symbol = trim($row['x2_coin']);
$buy_money   = (int)preg_replace('/[^0-9]/', '', $row['wr_subject']);

if (!$coin_symbol || $buy_money <= 0) return;

// 4. [쿨다운 가드] 65초 이내 재실행 금지
static $last_fire = [];
$fire_key = ($row['wr_id'] ?? '0') . '_' . basename(__FILE__);
$now_ts   = time();
if (isset($last_fire[$fire_key]) && ($now_ts - $last_fire[$fire_key]) < 65) return;

// 5. [잔고 체크] 보유 현금이 5500원 이하거나 매수금액보다 적으면 패스
try {
    $cash_stmt = $db_upbit->prepare(
        "SELECT cash_balance FROM daemon_upbit_Ticker_user
         ORDER BY collected_at DESC LIMIT 1"
    );
    $cash_stmt->execute();
    $cash_row     = $cash_stmt->fetch(PDO::FETCH_ASSOC);
    $cash_balance = $cash_row ? (float)$cash_row['cash_balance'] : 0;
} catch (Throwable $e) {
    echo "[" . date('Y-m-d H:i:s') . "] ($coin_symbol) 잔고 조회 실패: " . $e->getMessage() . "\n";
    return;
}

if ($cash_balance <= 5500) {
    echo "[" . date('Y-m-d H:i:s') . "] ($coin_symbol) 잔고 부족(" . number_format($cash_balance) . "원) - 매수 패스\n";
    return;
}
if ($cash_balance < $buy_money) {
    echo "[" . date('Y-m-d H:i:s') . "] ($coin_symbol) 잔고 부족(" . number_format($cash_balance) . "원) - 매수 패스\n";
    return;
}

// 6. [매수 실행]
try {
    $result   = $upbit->buy_market_order($coin_symbol, $buy_money);
    $log_time = date('Y-m-d H:i:s');

    if (isset($result['uuid']) || isset($result['id'])) {
        $last_fire[$fire_key] = $now_ts; // ★ 성공 직후 쿨다운 기록
        echo "[$log_time] (간격매수) $coin_symbol : " . number_format($buy_money) . "원 발사 성공!\n";

        record_trading($db_upbit, [
            'cron_id'       => $row['wr_id'],
            'market'        => $coin_symbol,
            'side'          => 'bid',
            'ord_type'      => 'price',
            'req_price'     => $buy_money,
            'trigger_type'  => 'interval',
            'trigger_value' => null,
            'response'      => $result,
            'result'        => 'success',
        ]);
    } else {
        $msg = isset($result['error']['message']) ? $result['error']['message'] : '알 수 없는 오류';
        echo "[$log_time] (간격매수) $coin_symbol 실패... 이유: $msg\n";

        record_trading($db_upbit, [
            'cron_id'       => $row['wr_id'],
            'market'        => $coin_symbol,
            'side'          => 'bid',
            'ord_type'      => 'price',
            'req_price'     => $buy_money,
            'trigger_type'  => 'interval',
            'trigger_value' => null,
            'response'      => $result,
            'result'        => 'fail',
            'message'       => $msg,
        ]);
    }
} catch (Throwable $e) {
    echo "[" . date('Y-m-d H:i:s') . "] ($coin_symbol) 매수 예외 발생: " . $e->getMessage() . "\n";
}
?>