<?php
// day_target_code.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. [시/분/일/요일 조건 체크]
$now_dt = new DateTime();
$current_hi = $now_dt->format('H:i');
$current_day = (int)$now_dt->format('j'); // 일 (1~31)
$current_wday= (int)$now_dt->format('w'); // 요일 (0=일, 6=토)
$target_hi = sprintf("%02d:%02d", $row['x2_hour'], $row['x2_min']);
// 시/분 불일치면 패스
if ($current_hi !== $target_hi) return;
// 일 , 요일 - 시/분
$day_ok = empty($row['x2_day']) || (int)$row['x2_day'] === $current_day;
$week_ok = ($row['x2_week'] === '' || $row['x2_week'] === null) || (int)$row['x2_week'] === $current_wday;
if (!$day_ok && !$week_ok) return;
// 5. [쿨다운 가드] 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;
// 6. [잔고 체크]
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;
}
// 7. [매수 실행]
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' => 'target_time',
'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' => 'target_time',
'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";
}
?>