DATA/UPBIT/daemon/target/day_time_code_7.php
<?php
// day_time_code_7.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']);
$loss_ratio  = (float)preg_replace('/[^0-9.]/', '', $row['x2_loss_ratio']);
$currency    = trim(str_replace('KRW-', '', $coin_symbol));

if (!$coin_symbol || $buy_money <= 0 || $loss_ratio <= 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. [자산 조회]
try {
    $asset_stmt = $db_upbit->prepare(
        "SELECT balance, profit_rate, profit_amount, cash_balance, collected_at
         FROM daemon_upbit_Ticker_user
         WHERE currency = ?
         ORDER BY collected_at DESC LIMIT 1"
    );
    $asset_stmt->execute([$currency]);
    $asset = $asset_stmt->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    echo "[" . date('Y-m-d H:i:s') . "] ($coin_symbol) 자산 조회 실패: " . $e->getMessage() . "\n";
    return;
}

if (!$asset) {
    echo "[" . date('Y-m-d H:i:s') . "] ($coin_symbol) 자산 데이터 없음. 패스.\n";
    return;
}

$ts = strtotime($asset['collected_at']);
if ($ts === false) {
    echo "[" . date('Y-m-d H:i:s') . "] ($coin_symbol) collected_at 파싱 실패. 패스.\n";
    return;
}
if ((time() - $ts) > 60) {
    echo "[" . date('Y-m-d H:i:s') . "] ($coin_symbol) 자산 데이터 오래됨. 패스.\n";
    return;
}

$profit_rate   = (float)$asset['profit_rate'];
$profit_amount = (float)$asset['profit_amount'];
$cash_balance  = (float)$asset['cash_balance'];
$log_time      = date('Y-m-d H:i:s');

// 6. [잔고 체크]
if ($cash_balance <= 5500) {
    echo "[$log_time] ($coin_symbol) 잔고 부족(" . number_format($cash_balance) . "원) - 매수 패스\n";
    return;
}
if ($cash_balance < $buy_money) {
    echo "[$log_time] ($coin_symbol) 잔고 부족(" . number_format($cash_balance) . "원) - 매수 패스\n";
    return;
}

// 7. [핵심 조건] 손실률이 지정 비율 이상일 때만 타격
if ($profit_rate > -$loss_ratio) {
    echo "[$log_time] ($coin_symbol) 손실률(" . $profit_rate . "%) < 지정비율(-" . $loss_ratio . "%) - 매수 패스\n";
    return;
}

// 8. [매수 실행]
try {
    $result = $upbit->buy_market_order($coin_symbol, $buy_money);

    if (isset($result['uuid']) || isset($result['id'])) {
        $last_fire[$fire_key] = $now_ts;
        echo "[$log_time] (손실률매수) $coin_symbol : " . number_format($buy_money) . "원 발사 성공! "
           . "(손실률: " . $profit_rate . "% / 손익: " . number_format($profit_amount) . "원)\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_loss_rate',
            'trigger_value' => $profit_rate,
            '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_loss_rate',
            'trigger_value' => $profit_rate,
            'response'      => $result,
            'result'        => 'fail',
            'message'       => $msg,
        ]);
    }
} catch (Throwable $e) {
    echo "[$log_time] ($coin_symbol) 매수 예외 발생: " . $e->getMessage() . "\n";
}
?>