adx hatasını çözerseniz oldukça başarılı.
mevcut fakat, paylaşabileceğim hali budur.
manuel ve tek coin için başka bir bot daha vereyim test edilmedi(sinyal olmadığı için)
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Binance Futures Trading Bot</title>
<!-- Bootstrap CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<!-- Chart.js -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.min.css" rel="stylesheet">
<style>
body {
padding-top: 20px;
background-color: #f5f5f5;
}
.card {
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
}
.card-header {
background-color: #f8f9fa;
border-bottom: 1px solid #e3e6f0;
font-weight: bold;
}
.indicator {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 5px;
}
.indicator-green {
background-color: #28a745;
}
.indicator-red {
background-color: #dc3545;
}
.indicator-yellow {
background-color: #ffc107;
}
.table td, .table th {
vertical-align: middle;
}
.signal-buy {
color: #28a745;
font-weight: bold;
}
.signal-sell {
color: #dc3545;
font-weight: bold;
}
.signal-neutral {
color: #6c757d;
}
#tradingChart {
height: 300px;
}
</style>
</head>
<body>
<div class="container">
<div class="row mb-4">
<div class="col-12">
<div class="d-flex justify-content-between align-items-center">
<h1>Binance Futures Trading Bot</h1>
<div>
<span id="botStatus" class="badge bg-danger">Stopped</span>
<button id="toggleBot" class="btn btn-success ms-2">Start Bot</button>
</div>
</div>
</div>
</div>
<div class="row">
<!-- Market Overview -->
<div class="col-md-8">
<div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
<span>Market Overview</span>
<div>
<select id="symbolSelect" class="form-select form-select-sm d-inline-block" style="width: auto;">
<option value="BTCUSDT">BTCUSDT</option>
<option value="ETHUSDT">ETHUSDT</option>
<option value="BNBUSDT">BNBUSDT</option>
<option value="SOLUSDT">SOLUSDT</option>
</select>
<select id="intervalSelect" class="form-select form-select-sm d-inline-block ms-2" style="width: auto;">
<option value="1m">1m</option>
<option value="5m">5m</option>
<option value="15m">15m</option>
<option value="1h" selected>1h</option>
<option value="4h">4h</option>
<option value="1d">1d</option>
</select>
</div>
</div>
<div class="card-body">
<canvas id="tradingChart"></canvas>
</div>
</div>
<!-- Technical Indicators -->
<div class="card">
<div class="card-header">
Technical Indicators
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<table class="table table-sm">
<tbody>
<tr>
<td>EMA(50)</td>
<td id="ema50">--</td>
<td id="ema50Status"></td>
</tr>
<tr>
<td>EMA(200)</td>
<td id="ema200">--</td>
<td></td>
</tr>
<tr>
<td>ADX</td>
<td id="adx">--</td>
<td id="adxStatus"></td>
</tr>
<tr>
<td>MACD</td>
<td id="macd">--</td>
<td id="macdStatus"></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-6">
<table class="table table-sm">
<tbody>
<tr>
<td>VWAP</td>
<td id="vwap">--</td>
<td id="vwapStatus"></td>
</tr>
<tr>
<td>Pivot Level</td>
<td id="pivotLevel">--</td>
<td id="pivotStatus"></td>
</tr>
<tr>
<td>ATR</td>
<td id="atr">--</td>
<td id="atrStatus"></td>
</tr>
<tr>
<td>Price Pattern</td>
<td id="pricePattern">--</td>
<td id="patternStatus"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="alert mt-3 text-center" id="signalAlert">
<strong id="signalText">Waiting for signal...</strong>
</div>
</div>
</div>
</div>
<!-- Account Overview -->
<div class="col-md-4">
<!-- Bot Settings -->
<div class="card">
<div class="card-header">
Bot Settings
</div>
<div class="card-body">
<form id="settingsForm">
<div class="mb-3">
<label class="form-label">Trading Pair</label>
<select id="tradingPair" class="form-select">
<option value="BTCUSDT">BTCUSDT</option>
<option value="ETHUSDT">ETHUSDT</option>
<option value="BNBUSDT">BNBUSDT</option>
<option value="SOLUSDT">SOLUSDT</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Interval</label>
<select id="tradingInterval" class="form-select">
<option value="1m">1 Minute</option>
<option value="5m">5 Minutes</option>
<option value="15m">15 Minutes</option>
<option value="1h" selected>1 Hour</option>
<option value="4h">4 Hours</option>
<option value="1d">1 Day</option>
</select>
</div>
<div class="mb-3">
<label class="form-label">Trade Amount (USDT)</label>
<input type="number" id="tradeAmount" class="form-control" value="100">
</div>
<div class="mb-3">
<label class="form-label">ATR Threshold</label>
<input type="number" id="atrThreshold" class="form-control" value="50">
</div>
<button type="submit" class="btn btn-primary">Save Settings</button>
</form>
</div>
</div>
<!-- Account Balance -->
<div class="card">
<div class="card-header">
Account Balance
</div>
<div class="card-body">
<table class="table table-sm">
<tbody id="balanceTable">
<tr>
<td>USDT</td>
<td class="text-end">0.00</td>
</tr>
<tr>
<td>BTC</td>
<td class="text-end">0.00</td>
</tr>
</tbody>
</table>
<button id="refreshBalance" class="btn btn-sm btn-outline-secondary">Refresh</button>
</div>
</div>
<!-- Open Positions -->
<div class="card">
<div class="card-header">
Open Positions
</div>
<div class="card-body">
<table class="table table-sm" id="positionsTable">
<thead>
<tr>
<th>Symbol</th>
<th>Size</th>
<th>PnL</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3" class="text-center">No open positions</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Recent Trades -->
<div class="card">
<div class="card-header">
Recent Trades
</div>
<div class="card-body">
<table class="table table-sm" id="tradesTable">
<thead>
<tr>
<th>Symbol</th>
<th>Side</th>
<th>Price</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="4" class="text-center">No recent trades</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
<!-- Chart.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.min.js"></script>
<script>
$(document).ready(function() {
// Global variables
let chart;
let botRunning = false;
let intervalId;
const API_URL = 'api.php'; // Backend PHP endpoint
// Initialize
initializeChart();
updateMarketData();
checkBotStatus();
// Event handlers
$('#toggleBot').on('click', toggleBot);
$('#symbolSelect, #intervalSelect').on('change', updateMarketData);
$('#refreshBalance').on('click', loadAccountBalance);
$('#settingsForm').on('submit', saveSettings);
// Initialize Chart
function initializeChart() {
const ctx = document.getElementById('tradingChart').getContext('2d');
chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Price',
data: [],
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: false
}
}
}
});
}
// Load and update market data
function updateMarketData() {
const symbol = $('#symbolSelect').val();
const interval = $('#intervalSelect').val();
$.ajax({
url: `${API_URL}?action=analyze&symbol=${symbol}&interval=${interval}`,
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
updateChart(response.analysis);
updateIndicators(response.analysis);
updateSignal(response.signal);
} else {
showError('Failed to fetch market data');
}
},
error: function() {
showError('Failed to connect to API');
}
});
}
// Update chart with new data
function updateChart(analysis) {
// For a real implementation, you would format the actual market data
// This is a placeholder that would be replaced with real data
const timestamps = Array.from({length: 50}, (_, i) => new Date(Date.now() - i * 3600000).toLocaleTimeString());
const prices = Array.from({length: 50}, (_, i) => 40000 + Math.random() * 2000);
chart.data.labels = timestamps.reverse();
chart.data.datasets[0].data = prices.reverse();
chart.update();
}
// Update technical indicators display
function updateIndicators(analysis) {
// Update EMA values
$('#ema50').text(analysis.ema50.toFixed(2));
$('#ema200').text(analysis.ema200.toFixed(2));
// Update ADX
$('#adx').text(analysis.adx.toFixed(2));
// Update MACD
$('#macd').text(analysis.macd.toFixed(6));
// Update VWAP
$('#vwap').text(analysis.vwap.toFixed(2));
// Update Pivot
$('#pivotLevel').text(analysis.pivotLevel.toFixed(2));
// Update ATR
$('#atr').text(analysis.atr.toFixed(2));
// Update Price Pattern
let patternText = '';
if (analysis.higherHighs && analysis.higherLows) {
patternText = 'Uptrend';
$('#patternStatus').html('<span class="indicator indicator-green"></span>');
} else if (analysis.lowerHighs && analysis.lowerLows) {
patternText = 'Downtrend';
$('#patternStatus').html('<span class="indicator indicator-red"></span>');
} else {
patternText = 'Sideways';
$('#patternStatus').html('<span class="indicator indicator-yellow"></span>');
}
$('#pricePattern').text(patternText);
// Update indicator status
$('#ema50Status').html(analysis.ema50 > analysis.ema200 ?
'<span class="indicator indicator-green"></span>' :
'<span class="indicator indicator-red"></span>');
$('#adxStatus').html(analysis.adx > 25 ?
'<span class="indicator indicator-green"></span>' :
'<span class="indicator indicator-red"></span>');
$('#macdStatus').html(analysis.macd > analysis.macdSignal ?
'<span class="indicator indicator-green"></span>' :
'<span class="indicator indicator-red"></span>');
$('#vwapStatus').html(analysis.close > analysis.vwap ?
'<span class="indicator indicator-green"></span>' :
'<span class="indicator indicator-red"></span>');
$('#pivotStatus').html(analysis.close > analysis.pivotLevel ?
'<span class="indicator indicator-green"></span>' :
'<span class="indicator indicator-red"></span>');
$('#atrStatus').html(analysis.atr > $('#atrThreshold').val() ?
'<span class="indicator indicator-green"></span>' :
'<span class="indicator indicator-red"></span>');
}
// Update signal display
function updateSignal(signal) {
let alertClass = 'alert-secondary';
let signalClass = 'signal-neutral';
if (signal === 'BUY') {
alertClass = 'alert-success';
signalClass = 'signal-buy';
} else if (signal === 'SELL') {
alertClass = 'alert-danger';
signalClass = 'signal-sell';
}
$('#signalAlert').removeClass('alert-success alert-danger alert-secondary').addClass(alertClass);
$('#signalText').removeClass('signal-buy signal-sell signal-neutral').addClass(signalClass).text(`Signal: ${signal}`);
}
// Toggle bot status
function toggleBot() {
const action = botRunning ? 'stop' : 'start';
$.ajax({
url: `${API_URL}?action=${action}`,
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
botRunning = action === 'start';
updateBotStatusUI();
if (botRunning) {
// Start automatic data refresh
intervalId = setInterval(refreshData, 30000); // Refresh every 30 seconds
} else {
// Stop automatic refresh
clearInterval(intervalId);
}
} else {
showError(`Failed to ${action} bot`);
}
},
error: function() {
showError('Failed to connect to API');
}
});
}
// Check bot status on page load
function checkBotStatus() {
$.ajax({
url: `${API_URL}?action=status`,
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
botRunning = response.running;
updateBotStatusUI();
if (botRunning) {
// Start automatic data refresh
intervalId = setInterval(refreshData, 30000); // Refresh every 30 seconds
}
}
}
});
// Load initial data
loadAccountBalance();
loadOpenPositions();
loadTradeHistory();
}
// Update bot status UI
function updateBotStatusUI() {
if (botRunning) {
$('#botStatus').removeClass('bg-danger').addClass('bg-success').text('Running');
$('#toggleBot').removeClass('btn-success').addClass('btn-danger').text('Stop Bot');
} else {
$('#botStatus').removeClass('bg-success').addClass('bg-danger').text('Stopped');
$('#toggleBot').removeClass('btn-danger').addClass('btn-success').text('Start Bot');
}
}
// Refresh all data
function refreshData() {
updateMarketData();
loadAccountBalance();
loadOpenPositions();
loadTradeHistory();
}
// Load account balance
function loadAccountBalance() {
$.ajax({
url: `${API_URL}?action=balance`,
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
updateBalanceTable(response.balance);
}
}
});
}
// Update balance table
function updateBalanceTable(balances) {
let tableHtml = '';
for (const asset in balances) {
tableHtml += `
<tr>
<td>${asset}</td>
<td class="text-end">${balances[asset].available.toFixed(asset === 'USDT' ? 2 : 8)}</td>
</tr>
`;
}
$('#balanceTable').html(tableHtml);
}
// Load open positions
function loadOpenPositions() {
$.ajax({
url: `${API_URL}?action=positions`,
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
updatePositionsTable(response.positions);
}
}
});
}
// Update positions table
function updatePositionsTable(positions) {
let tableHtml = '';
if (positions.length === 0) {
tableHtml = '<tr><td colspan="3" class="text-center">No open positions</td></tr>';
} else {
positions.forEach(function(position) {
const pnlClass = position.unRealizedProfit >= 0 ? 'text-success' : 'text-danger';
tableHtml += `
<tr>
<td>${position.symbol}</td>
<td>${position.positionAmt}</td>
<td class="${pnlClass}">${position.unRealizedProfit.toFixed(2)}</td>
</tr>
`;
});
}
$('#positionsTable tbody').html(tableHtml);
}
// Load trade history
function loadTradeHistory() {
$.ajax({
url: `${API_URL}?action=history`,
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
updateTradesTable(response.history);
}
}
});
}
// Update trades table
function updateTradesTable(trades) {
let tableHtml = '';
if (trades.length === 0) {
tableHtml = '<tr><td colspan="4" class="text-center">No recent trades</td></tr>';
} else {
trades.forEach(function(trade) {
const side = trade.isBuyer ? 'BUY' : 'SELL';
const sideClass = trade.isBuyer ? 'text-success' : 'text-danger';
const time = new Date(trade.time).toLocaleString();
tableHtml += `
<tr>
<td>${trade.symbol}</td>
<td class="${sideClass}">${side}</td>
<td>${parseFloat(trade.price).toFixed(2)}</td>
<td>${time}</td>
</tr>
`;
});
}
$('#tradesTable tbody').html(tableHtml);
}
// Save bot settings
function saveSettings(e) {
e.preventDefault();
const settings = {
symbol: $('#tradingPair').val(),
interval: $('#tradingInterval').val(),
tradeAmount: parseFloat($('#tradeAmount').val()),
atrThreshold: parseFloat($('#atrThreshold').val())
};
$.ajax({
url: `${API_URL}?action=settings`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(settings),
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
showSuccess('Settings saved successfully');
// Update chart symbol and interval if needed
if ($('#symbolSelect').val() !== settings.symbol) {
$('#symbolSelect').val(settings.symbol);
}
if ($('#intervalSelect').val() !== settings.interval) {
$('#intervalSelect').val(settings.interval);
}
updateMarketData();
} else {
showError('Failed to save settings');
}
},
error: function() {
showError('Failed to connect to API');
}
});
}
// Show error message
function showError(message) {
alert(`Error: ${message}`);
}
// Show success message
function showSuccess(message) {
alert(`Success: ${message}`);
}
});
</script>
</body>
</html>api.php
<?php
// Binance Futures Trading Bot - Backend Implementation
// This script handles the connection to Binance API and executes trading logic
// Configuration
define('API_KEY', 'YOUR_BINANCE_API_KEY');
define('API_SECRET', 'YOUR_BINANCE_API_SECRET');
define('SYMBOL', 'BTCUSDT'); // Default trading pair
define('INTERVAL', '4h'); // Default timeframe
define('QUANTITY', 0.001); // Default trading quantity
define('ATR_THRESHOLD', 50); // Default ATR threshold
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Request handling
header('Content-Type: application/json');
session_start();
// Router
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
case 'start':
startBot();
break;
case 'stop':
stopBot();
break;
case 'status':
getBotStatus();
break;
case 'settings':
updateSettings();
break;
case 'balance':
getAccountBalance();
break;
case 'positions':
getOpenPositions();
break;
case 'history':
getTradeHistory();
break;
case 'analyze':
analyzeMarket();
break;
default:
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
function startBot() {
// Set status in session
$_SESSION['bot_running'] = true;
$_SESSION['bot_start_time'] = time();
echo json_encode([
'status' => 'success',
'message' => 'Bot started successfully',
'timestamp' => date('Y-m-d H:i:s')
]);
}
function stopBot() {
// Set status in session
$_SESSION['bot_running'] = false;
echo json_encode([
'status' => 'success',
'message' => 'Bot stopped successfully',
'timestamp' => date('Y-m-d H:i:s')
]);
}
function getBotStatus() {
$running = isset($_SESSION['bot_running']) ? $_SESSION['bot_running'] : false;
$startTime = isset($_SESSION['bot_start_time']) ? $_SESSION['bot_start_time'] : null;
echo json_encode([
'status' => 'success',
'running' => $running,
'start_time' => $startTime ? date('Y-m-d H:i:s', $startTime) : null,
'uptime' => $startTime ? (time() - $startTime) : 0
]);
}
function updateSettings() {
// Get JSON data from request
$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
echo json_encode(['status' => 'error', 'message' => 'Invalid settings data']);
return;
}
// Save settings to session
$_SESSION['settings'] = $data;
echo json_encode([
'status' => 'success',
'message' => 'Settings updated successfully',
'settings' => $data
]);
}
function getAccountBalance() {
// Connect to Binance API
$balance = getBinanceAccountBalance();
echo json_encode([
'status' => 'success',
'balance' => $balance
]);
}
function getOpenPositions() {
// Connect to Binance API
$positions = getBinanceOpenPositions();
echo json_encode([
'status' => 'success',
'positions' => $positions
]);
}
function getTradeHistory() {
// Connect to Binance API
$history = getBinanceTradeHistory();
echo json_encode([
'status' => 'success',
'history' => $history
]);
}
function analyzeMarket() {
// Get parameters from request
$symbol = isset($_GET['symbol']) ? $_GET['symbol'] : SYMBOL;
$interval = isset($_GET['interval']) ? $_GET['interval'] : INTERVAL;
// Fetch market data from Binance
$marketData = getBinanceMarketData($symbol, $interval);
// Apply technical indicators
$analysis = calculateIndicators($marketData);
// Determine buy/sell signals
$signal = determineSignal($analysis);
echo json_encode([
'status' => 'success',
'timestamp' => date('Y-m-d H:i:s'),
'symbol' => $symbol,
'interval' => $interval,
'analysis' => $analysis,
'signal' => $signal
]);
}
// Binance API Functions
function getBinanceSignature($query_string) {
return hash_hmac('sha256', $query_string, API_SECRET);
}
function binanceApiRequest($url, $method = 'GET', $params = []) {
$curl = curl_init();
// Add timestamp for API request
$params['timestamp'] = round(microtime(true) * 1000);
// Build query string
$query_string = http_build_query($params);
// Generate signature
$signature = getBinanceSignature($query_string);
// Add signature to params
$query_string .= "&signature={$signature}";
// Prepare URL
$url = "https://fapi.binance.com/fapi/v1/{$url}?{$query_string}";
// Set cURL options
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"X-MBX-APIKEY: " . API_KEY
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return ['error' => "cURL Error #:" . $err];
} else {
return json_decode($response, true);
}
}
function getBinanceAccountBalance() {
// In a real implementation, you would call Binance's account endpoint
// This is a simplified example
$response = binanceApiRequest("account", "GET");
// For testing purposes
if (!isset($response['assets'])) {
return [
'USDT' => ['available' => 1000.00, 'total' => 1200.00],
'BTC' => ['available' => 0.05, 'total' => 0.05]
];
}
$balances = [];
foreach ($response['assets'] as $asset) {
$balances[$asset['asset']] = [
'available' => floatval($asset['availableBalance']),
'total' => floatval($asset['walletBalance'])
];
}
return $balances;
}
function getBinanceOpenPositions() {
// In a real implementation, you would call Binance's positions endpoint
// This is a simplified example
$response = binanceApiRequest("positionRisk", "GET");
// For testing purposes
if (!isset($response[0])) {
return [
[
'symbol' => 'BTCUSDT',
'positionAmt' => 0.01,
'entryPrice' => 40000,
'markPrice' => 41000,
'unRealizedProfit' => 10,
'liquidationPrice' => 35000
]
];
}
$positions = [];
foreach ($response as $position) {
if (floatval($position['positionAmt']) != 0) {
$positions[] = [
'symbol' => $position['symbol'],
'positionAmt' => floatval($position['positionAmt']),
'entryPrice' => floatval($position['entryPrice']),
'markPrice' => floatval($position['markPrice']),
'unRealizedProfit' => floatval($position['unRealizedProfit']),
'liquidationPrice' => floatval($position['liquidationPrice'])
];
}
}
return $positions;
}
function getBinanceTradeHistory() {
// In a real implementation, you would call Binance's trade history endpoint
// This is a simplified example
$response = binanceApiRequest("userTrades", "GET", ['symbol' => SYMBOL]);
// For testing purposes
if (!isset($response[0])) {
return [
[
'symbol' => 'BTCUSDT',
'id' => 123456,
'orderId' => 987654,
'price' => 40000,
'qty' => 0.01,
'quoteQty' => 400,
'time' => time() - 3600,
'isBuyer' => true
],
[
'symbol' => 'BTCUSDT',
'id' => 123457,
'orderId' => 987655,
'price' => 41000,
'qty' => 0.01,
'quoteQty' => 410,
'time' => time() - 1800,
'isBuyer' => false
]
];
}
return $response;
}
function getBinanceMarketData($symbol, $interval) {
// Endpoint for candlestick data
$url = "https://fapi.binance.com/fapi/v1/klines?symbol={$symbol}&interval={$interval}&limit=500";
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return ['error' => "cURL Error #:" . $err];
}
$data = json_decode($response, true);
$formattedData = [];
foreach ($data as $candle) {
$formattedData[] = [
'timestamp' => $candle[0],
'open' => floatval($candle[1]),
'high' => floatval($candle[2]),
'low' => floatval($candle[3]),
'close' => floatval($candle[4]),
'volume' => floatval($candle[5]),
'close_time' => $candle[6],
'quote_asset_volume' => floatval($candle[7]),
'number_of_trades' => $candle[8],
'taker_buy_base_asset_volume' => floatval($candle[9]),
'taker_buy_quote_asset_volume' => floatval($candle[10])
];
}
return $formattedData;
}
// Technical analysis functions
function calculateIndicators($marketData) {
$closes = array_column($marketData, 'close');
$highs = array_column($marketData, 'high');
$lows = array_column($marketData, 'low');
// EMA calculations
$ema50 = calculateEMA($closes, 50);
$ema200 = calculateEMA($closes, 200);
// ADX calculation
$adx = calculateADX($highs, $lows, $closes, 14);
// MACD calculation
$macd = calculateMACD($closes);
// VWAP calculation
$volumes = array_column($marketData, 'volume');
$vwap = calculateVWAP($marketData);
// Pivot Points
$pivotLevel = calculatePivotPoint($marketData);
// ATR calculation
$atr = calculateATR($highs, $lows, $closes, 14);
// Higher Highs, Higher Lows, Lower Highs, Lower Lows
$patterns = identifyPricePatterns($highs, $lows, 5);
$lastClose = end($closes);
return [
'ema50' => end($ema50),
'ema200' => end($ema200),
'adx' => end($adx),
'macd' => end($macd['macd']),
'macdSignal' => end($macd['signal']),
'vwap' => end($vwap),
'pivotLevel' => $pivotLevel,
'atr' => end($atr),
'higherHighs' => $patterns['higherHighs'],
'higherLows' => $patterns['higherLows'],
'lowerHighs' => $patterns['lowerHighs'],
'lowerLows' => $patterns['lowerLows'],
'close' => $lastClose
];
}
function calculateEMA($prices, $period) {
$multiplier = 2 / ($period + 1);
$ema = [];
// Use SMA for the first value
$sma = array_sum(array_slice($prices, 0, $period)) / $period;
$ema[] = $sma;
// Calculate EMA for remaining prices
for ($i = $period; $i < count($prices); $i++) {
$ema[] = ($prices[$i] - end($ema)) * $multiplier + end($ema);
}
return $ema;
}
function calculateADX($high, $low, $close, $period) {
// This is a simplified ADX calculation
// In a real implementation, you would need a more accurate calculation
$adx = [];
for ($i = $period; $i < count($close); $i++) {
// Simplified calculation
$adx[] = 25 + (rand(-5, 5)); // Random value around 25 for testing
}
return $adx;
}
function calculateMACD($prices, $fastPeriod = 12, $slowPeriod = 26, $signalPeriod = 9) {
$fastEMA = calculateEMA($prices, $fastPeriod);
$slowEMA = calculateEMA($prices, $slowPeriod);
// Calculate MACD line
$macdLine = [];
for ($i = 0; $i < count($slowEMA); $i++) {
$macdLine[] = $fastEMA[$i + (count($fastEMA) - count($slowEMA))] - $slowEMA[$i];
}
// Calculate Signal line (EMA of MACD line)
$signalLine = calculateEMA($macdLine, $signalPeriod);
// Calculate Histogram
$histogram = [];
for ($i = 0; $i < count($signalLine); $i++) {
$histogram[] = $macdLine[$i + (count($macdLine) - count($signalLine))] - $signalLine[$i];
}
return [
'macd' => $macdLine,
'signal' => $signalLine,
'histogram' => $histogram
];
}
function calculateVWAP($marketData) {
$vwap = [];
$cumulativeTPV = 0; // Total Price * Volume
$cumulativeVolume = 0;
foreach ($marketData as $candle) {
$typicalPrice = ($candle['high'] + $candle['low'] + $candle['close']) / 3;
$volume = $candle['volume'];
$cumulativeTPV += $typicalPrice * $volume;
$cumulativeVolume += $volume;
$vwap[] = $cumulativeTPV / $cumulativeVolume;
}
return $vwap;
}
function calculatePivotPoint($marketData) {
// Using the last complete day for calculation
$lastDay = end($marketData);
$high = $lastDay['high'];
$low = $lastDay['low'];
$close = $lastDay['close'];
// Classical pivot point
$pivot = ($high + $low + $close) / 3;
return $pivot;
}
function calculateATR($highs, $lows, $closes, $period) {
$trueRanges = [];
$atr = [];
// Calculate True Range for the first period
for ($i = 1; $i < count($closes); $i++) {
$highLowRange = $highs[$i] - $lows[$i];
$highClosePrevRange = abs($highs[$i] - $closes[$i - 1]);
$lowClosePrevRange = abs($lows[$i] - $closes[$i - 1]);
$trueRanges[] = max($highLowRange, $highClosePrevRange, $lowClosePrevRange);
}
// First ATR value is simple average
$firstATR = array_sum(array_slice($trueRanges, 0, $period)) / $period;
$atr[] = $firstATR;
// Calculate remaining ATR values
for ($i = 1; $i < count($trueRanges) - $period + 1; $i++) {
$atr[] = (($atr[$i - 1] * ($period - 1)) + $trueRanges[$i + $period - 1]) / $period;
}
return $atr;
}
function identifyPricePatterns($highs, $lows, $lookback) {
$recentHighs = array_slice($highs, -$lookback);
$recentLows = array_slice($lows, -$lookback);
$higherHighs = true;
$higherLows = true;
$lowerHighs = true;
$lowerLows = true;
// Check for higher highs and higher lows (uptrend)
for ($i = 1; $i < count($recentHighs); $i++) {
if ($recentHighs[$i] <= $recentHighs[$i - 1]) {
$higherHighs = false;
}
if ($recentLows[$i] <= $recentLows[$i - 1]) {
$higherLows = false;
}
}
// Check for lower highs and lower lows (downtrend)
for ($i = 1; $i < count($recentHighs); $i++) {
if ($recentHighs[$i] >= $recentHighs[$i - 1]) {
$lowerHighs = false;
}
if ($recentLows[$i] >= $recentLows[$i - 1]) {
$lowerLows = false;
}
}
return [
'higherHighs' => $higherHighs,
'higherLows' => $higherLows,
'lowerHighs' => $lowerHighs,
'lowerLows' => $lowerLows
];
}
function determineSignal($analysis) {
// Buy signal conditions
$buyConditions =
$analysis['ema50'] > $analysis['ema200'] &&
$analysis['adx'] > 25 &&
$analysis['macd'] > $analysis['macdSignal'] &&
$analysis['close'] > $analysis['vwap'] &&
$analysis['close'] > $analysis['pivotLevel'] &&
$analysis['atr'] > getATRThreshold() &&
$analysis['higherHighs'] &&
$analysis['higherLows'];
// Sell signal conditions
$sellConditions =
$analysis['ema50'] < $analysis['ema200'] &&
$analysis['adx'] > 25 &&
$analysis['macd'] < $analysis['macdSignal'] &&
$analysis['close'] < $analysis['vwap'] &&
$analysis['close'] < $analysis['pivotLevel'] &&
$analysis['atr'] > getATRThreshold() &&
$analysis['lowerHighs'] &&
$analysis['lowerLows'];
if ($buyConditions) {
return 'BUY';
} elseif ($sellConditions) {
return 'SELL';
} else {
return 'NEUTRAL';
}
}
function getATRThreshold() {
// Get from settings or use default
return isset($_SESSION['settings']['atrThreshold']) ? $_SESSION['settings']['atrThreshold'] : ATR_THRESHOLD;
}
// Place market order (simplified example)
function placeBinanceOrder($symbol, $side, $quantity) {
$params = [
'symbol' => $symbol,
'side' => $side, // BUY or SELL
'type' => 'MARKET',
'quantity' => $quantity
];
return binanceApiRequest("order", "POST", $params);
}Testnet testi yapılmadı dikkatli kullanın.. sağlıklı veri 4h 12h olur genelde scalping için uygun değildir.