5 Commits

Author SHA1 Message Date
38cdffc2b9 hts with only two SMAs 2025-07-21 21:20:39 +02:00
d2c45cac12 wyswietlanie wykresu chodzi jak powinno 2025-07-17 00:21:14 +02:00
2a556781da switching TF, multi indicators on chart 2025-07-16 00:28:42 +02:00
4305e1cb02 changes styles 2025-07-15 22:05:29 +02:00
68d8bc9880 measurment tooltip + one week data from binance 2025-07-15 20:27:43 +02:00
9 changed files with 616 additions and 122 deletions

3
.gitignore vendored
View File

@ -1 +1,2 @@
*.csv
*.csv
historical_data_1m.json

50
app.py
View File

@ -31,24 +31,43 @@ current_bar = {} # To track the currently forming 1-minute candle
# --- Historical Data Streaming ---
def stream_historical_data(sid):
"""
Fetches the last week of historical 1-minute kline data from Binance,
saves it to a file, and sends it to the connected client.
"""
try:
logging.info(f"Starting historical data stream for SID={sid}")
client = Client()
num_chunks = 6
chunk_size_days = 15
end_date = datetime.utcnow()
all_klines = []
for i in range(num_chunks):
start_date = end_date - timedelta(days=chunk_size_days)
logging.info(f"Fetching chunk {i + 1}/{num_chunks} for SID={sid}")
new_klines = client.get_historical_klines(SYMBOL, Client.KLINE_INTERVAL_1MINUTE, str(start_date), str(end_date))
if new_klines:
all_klines.extend(new_klines)
socketio.emit('history_progress', {'progress': ((i + 1) / num_chunks) * 100}, to=sid)
end_date = start_date
socketio.sleep(0.05)
# --- NEW SOLUTION: Load data for the last week ---
logging.info(f"Fetching historical data for the last 7 days for SID={sid}")
# The `python-binance` library allows using relative date strings.
# This single call is more efficient for this use case.
all_klines = client.get_historical_klines(
SYMBOL,
Client.KLINE_INTERVAL_1MINUTE,
start_str="1 week ago UTC" # Fetches data starting from 8 weeks ago until now
)
# --- ORIGINAL SOLUTION COMMENTED OUT ---
# num_chunks = 6
# chunk_size_days = 15
# end_date = datetime.utcnow()
# all_klines = []
#
# for i in range(num_chunks):
# start_date = end_date - timedelta(days=chunk_size_days)
# logging.info(f"Fetching chunk {i + 1}/{num_chunks} for SID={sid}")
# new_klines = client.get_historical_klines(SYMBOL, Client.KLINE_INTERVAL_1MINUTE, str(start_date), str(end_date))
# if new_klines:
# all_klines.extend(new_klines)
# # The progress emission is no longer needed for a single API call
# # socketio.emit('history_progress', {'progress': ((i + 1) / num_chunks) * 100}, to=sid)
# end_date = start_date
# socketio.sleep(0.05)
# --- END OF ORIGINAL SOLUTION ---
# The rest of the function processes the `all_klines` data as before
seen = set()
unique_klines = [kline for kline in sorted(all_klines, key=lambda x: x[0]) if tuple(kline) not in seen and not seen.add(tuple(kline))]
@ -57,6 +76,7 @@ def stream_historical_data(sid):
logging.info(f"Finished data stream for SID={sid}. Sending final payload of {len(unique_klines)} klines.")
socketio.emit('history_finished', {'klines_1m': unique_klines}, to=sid)
except Exception as e:
logging.error(f"Error in stream_historical_data for SID={sid}: {e}", exc_info=True)
socketio.emit('history_error', {'message': str(e)}, to=sid)
@ -123,4 +143,4 @@ def index():
# --- Main Application Execution ---
if __name__ == '__main__':
logging.info("Starting Flask-SocketIO server...")
socketio.run(app, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=True, debug=False)
socketio.run(app, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=True, debug=False)

File diff suppressed because one or more lines are too long

View File

@ -14,7 +14,7 @@ const BB_INDICATOR = {
bb1_len_upper: 20, bb1_std_upper: 1.6, bb1_len_lower: 20, bb1_std_lower: 1.6,
bb2_len_upper: 20, bb2_std_upper: 2.4, bb2_len_lower: 20, bb2_std_lower: 2.4,
bb3_len_upper: 20, bb3_std_upper: 3.3, bb3_len_lower: 20, bb3_std_lower: 3.3,
},
},
calculateFull: calculateFullBollingerBands,
};

60
static/hts.js Normal file
View File

@ -0,0 +1,60 @@
/**
* HTS (High-Tech SMAs) - Combined Fast and Slow SMA Indicator
* This indicator displays both Fast SMA and Slow SMA on the same chart
*/
const HTS_INDICATOR = {
name: 'HTS',
label: 'HTS (Fast & Slow SMA)',
usesBaseData: false, // This indicator uses the chart's currently displayed data
params: [
{ name: 'fastPeriod', type: 'number', defaultValue: 33, min: 2, label: 'Fast SMA Period' },
{ name: 'slowPeriod', type: 'number', defaultValue: 133, min: 2, label: 'Slow SMA Period' },
],
calculateFull: calculateFullHTS,
};
function calculateFullHTS(data, params) {
const fastPeriod = params.fastPeriod;
const slowPeriod = params.slowPeriod;
if (!data || data.length < Math.max(fastPeriod, slowPeriod)) {
return {
fastSMA: [],
slowSMA: []
};
}
// Calculate Fast SMA
const fastSMA = calculateSMA(data, fastPeriod);
// Calculate Slow SMA
const slowSMA = calculateSMA(data, slowPeriod);
return {
fastSMA: fastSMA,
slowSMA: slowSMA
};
}
function calculateSMA(data, period) {
if (!data || data.length < period) return [];
let smaData = [];
let sum = 0;
// Calculate initial sum for the first period
for (let i = 0; i < period; i++) {
sum += data[i].close;
}
// Add the first SMA point
smaData.push({ time: data[period - 1].time, value: sum / period });
// Calculate remaining SMA points using sliding window
for (let i = period; i < data.length; i++) {
sum = sum - data[i - period].close + data[i].close;
smaData.push({ time: data[i].time, value: sum / period });
}
return smaData;
}

View File

@ -6,18 +6,31 @@
* @returns {Object} A manager object with public methods to control indicators.
*/
function createIndicatorManager(chart, baseCandleDataRef, displayedCandleDataRef) {
// --- FIX: --- Added `debounceTimerId` to each slot object to track pending updates.
const indicatorSlots = [
{ id: 1, cellId: 'indicator-cell-1', series: [], definition: null, params: {}, calculator: null },
{ id: 2, cellId: 'indicator-cell-2', series: [], definition: null, params: {}, calculator: null },
{ id: 3, cellId: 'indicator-cell-3', series: [], definition: null, params: {}, calculator: null },
{ id: 4, cellId: 'indicator-cell-4', series: [], definition: null, params: {}, calculator: null },
{ id: 1, cellId: 'indicator-cell-1', series: [], definition: null, params: {}, calculator: null, debounceTimerId: null },
{ id: 2, cellId: 'indicator-cell-2', series: [], definition: null, params: {}, calculator: null, debounceTimerId: null },
{ id: 3, cellId: 'indicator-cell-3', series: [], definition: null, params: {}, calculator: null, debounceTimerId: null },
{ id: 4, cellId: 'indicator-cell-4', series: [], definition: null, params: {}, calculator: null, debounceTimerId: null },
];
// **FIX**: Updated colors object to match your styling request.
const colors = {
bb: { bb1_upper: '#FF9800', bb1_lower: '#FF9800', bb2_upper: '#2196F3', bb2_lower: '#2196F3', bb3_upper: '#9C27B0', bb3_lower: '#9C27B0' },
bb: {
bb1_upper: 'rgba(128, 25, 34, 0.5)',
bb2_upper: 'rgba(128, 25, 34, 0.75)',
bb3_upper: 'rgba(128, 25, 34, 1)',
bb1_lower: 'rgba(6, 95, 6, 0.5)',
bb2_lower: 'rgba(6, 95, 6, 0.75)',
bb3_lower: 'rgba(6, 95, 6, 1.0)',
},
hurst: { topBand: '#787b86', bottomBand: '#787b86', topBand_h: '#673ab7', bottomBand_h: '#673ab7' },
default: ['#00BCD4', '#FFEB3B', '#4CAF50', '#E91E63'] // Cyan, Yellow, Green, Pink
hts: {
fastSMA: '#00bcd4', // Cyan blue for Fast SMA
slowSMA: '#ff5252' // Red for Slow SMA
},
fast_sma: '#00bcd4',
slow_sma: '#ff5252',
default: ['#00BCD4', '#FFEB3B', '#4CAF50', '#E91E63']
};
function populateDropdowns() {
@ -46,12 +59,19 @@ function createIndicatorManager(chart, baseCandleDataRef, displayedCandleDataRef
const slot = indicatorSlots.find(s => s.id === slotId);
if (!slot) return;
// --- FIX: --- Cancel any pending debounced update from the previous indicator's controls.
// This is the core of the fix, preventing the race condition.
if (slot.debounceTimerId) {
clearTimeout(slot.debounceTimerId);
slot.debounceTimerId = null;
}
slot.series.forEach(s => chart.removeSeries(s));
slot.series = [];
slot.definition = null;
slot.params = {};
slot.calculator = null;
const controlsContainer = document.querySelector(`#${slot.cellId} .indicator-controls`);
controlsContainer.innerHTML = '';
@ -61,12 +81,12 @@ function createIndicatorManager(chart, baseCandleDataRef, displayedCandleDataRef
if (!definition) return;
slot.definition = definition;
definition.params.forEach(param => {
const label = document.createElement('label');
label.textContent = param.label || param.name;
label.style.fontSize = '12px';
const input = document.createElement('input');
input.type = param.type;
input.value = param.defaultValue;
@ -75,13 +95,14 @@ function createIndicatorManager(chart, baseCandleDataRef, displayedCandleDataRef
input.className = 'input-field';
slot.params[param.name] = input.type === 'number' ? parseFloat(input.value) : input.value;
let debounceTimer;
input.addEventListener('input', () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
// --- FIX: --- Use the slot's `debounceTimerId` property to manage the timeout.
clearTimeout(slot.debounceTimerId);
slot.debounceTimerId = setTimeout(() => {
slot.params[param.name] = input.type === 'number' ? parseFloat(input.value) : input.value;
updateIndicator(slot.id, true);
}, 500);
slot.debounceTimerId = null; // Clear the ID after the function has run.
}, 500);
});
const controlGroup = document.createElement('div');
controlGroup.style.display = 'flex';
@ -96,55 +117,58 @@ function createIndicatorManager(chart, baseCandleDataRef, displayedCandleDataRef
function updateIndicator(slotId, isFullRecalculation = false) {
const slot = indicatorSlots.find(s => s.id === slotId);
const candleDataForCalc = (slot.definition.usesBaseData) ? baseCandleDataRef : displayedCandleDataRef;
if (!slot || !slot.definition) return;
const candleDataForCalc = (slot.definition.usesBaseData) ? baseCandleDataRef : displayedCandleDataRef;
if (candleDataForCalc.length === 0) return;
if (!slot || !slot.definition || candleDataForCalc.length === 0) return;
if (isFullRecalculation) {
slot.series.forEach(s => chart.removeSeries(s));
slot.series = [];
const indicatorResult = slot.definition.calculateFull(candleDataForCalc, slot.params);
if (typeof indicatorResult === 'object' && !Array.isArray(indicatorResult)) {
Object.keys(indicatorResult).forEach(key => {
const seriesData = indicatorResult[key];
const indicatorNameLower = slot.definition.name.toLowerCase();
const series = chart.addLineSeries({
color: (colors[indicatorNameLower] && colors[indicatorNameLower][key]) ? colors[indicatorNameLower][key] : colors.default[slot.id - 1],
lineWidth: 1, // **FIX**: Set line width to 1px
title: '', // **FIX**: Remove title label
lastValueVisible: false, // **FIX**: Remove price label on the right
priceLineVisible: false, // **FIX**: Remove dotted horizontal line
lineWidth: 1,
title: '',
lastValueVisible: false,
priceLineVisible: false,
});
series.setData(seriesData);
slot.series.push(series);
});
} else {
const indicatorNameLower = slot.definition.name.toLowerCase();
const indicatorColor = colors[indicatorNameLower] || slot.definition.color || colors.default[slot.id - 1];
const series = chart.addLineSeries({
color: colors.default[slot.id - 1],
lineWidth: 1, // **FIX**: Set line width to 1px
title: '', // **FIX**: Remove title label
lastValueVisible: false, // **FIX**: Remove price label on the right
priceLineVisible: false, // **FIX**: Remove dotted horizontal line
color: indicatorColor,
lineWidth: 1,
title: '',
lastValueVisible: false,
priceLineVisible: false,
});
series.setData(indicatorResult);
slot.series.push(series);
}
if (slot.definition.createRealtime) {
slot.calculator = slot.definition.createRealtime(slot.params);
slot.calculator.prime(candleDataForCalc);
}
} else if (slot.calculator) {
// **FIX**: This is the lightweight real-time update logic
const lastCandle = candleDataForCalc[candleDataForCalc.length - 1];
if (!lastCandle) return;
const newPoint = slot.calculator.update(lastCandle);
if (newPoint && typeof newPoint === 'object') {
if (slot.series.length > 1) { // Multi-line indicator
if (slot.series.length > 1) { // Multi-line indicator
Object.keys(newPoint).forEach((key, index) => {
if (slot.series[index] && newPoint[key]) {
slot.series[index].update(newPoint[key]);
@ -156,20 +180,37 @@ function createIndicatorManager(chart, baseCandleDataRef, displayedCandleDataRef
}
}
}
function recalculateAllAfterHistory(baseData, displayedData) {
baseCandleDataRef = baseData;
displayedCandleDataRef = displayedData;
indicatorSlots.forEach(slot => {
if (slot.definition) updateIndicator(slot.id, true);
baseCandleDataRef = baseData;
displayedCandleDataRef = displayedData;
// --- FIX: --- Clear any pending debounced updates from parameter changes.
// This prevents a stale update from a parameter input from running after
// the chart has already been reset for a new timeframe.
indicatorSlots.forEach(slot => {
if (slot.debounceTimerId) {
clearTimeout(slot.debounceTimerId);
slot.debounceTimerId = null;
}
});
// --- FIX: --- Defer the full recalculation to the next frame.
// This prevents a race condition where indicators are removed/added while the chart
// is still processing the main series' `setData` operation from a timeframe change.
setTimeout(() => {
indicatorSlots.forEach(slot => {
if (slot.definition) {
updateIndicator(slot.id, true);
}
});
}, 0);
}
// **FIX**: New lightweight function for real-time updates
function updateAllOnNewCandle() {
indicatorSlots.forEach(slot => {
if (slot.definition) {
updateIndicator(slot.id, false); // Perform a lightweight update
updateIndicator(slot.id, false);
}
});
}
@ -177,6 +218,6 @@ function createIndicatorManager(chart, baseCandleDataRef, displayedCandleDataRef
return {
populateDropdowns,
recalculateAllAfterHistory,
updateAllOnNewCandle, // Expose the new function
updateAllOnNewCandle,
};
}

View File

@ -6,7 +6,7 @@
* 3. Add the indicator's definition object (e.g., RSI_INDICATOR) to this array.
*/
const AVAILABLE_INDICATORS = [
SMA_INDICATOR,
HTS_INDICATOR,
EMA_INDICATOR,
BB_INDICATOR, // Added the new Bollinger Bands indicator
HURST_INDICATOR // Added the new Hurst Bands indicator

View File

@ -1,14 +1,29 @@
/**
* Indicator Definition Object for SMA.
* Indicator Definition Object for Fast SMA.
*/
const SMA_INDICATOR = {
name: 'SMA',
label: 'Simple Moving Average',
const FAST_SMA_INDICATOR = {
name: 'FAST_SMA',
label: 'Fast SMA',
usesBaseData: false, // This simple indicator uses the chart's currently displayed data
params: [
{ name: 'period', type: 'number', defaultValue: 20, min: 2 },
{ name: 'period', type: 'number', defaultValue: 33, min: 2 },
],
calculateFull: calculateFullSMA,
color: '#00bcd4',
};
/**
* Indicator Definition Object for Slow SMA.
*/
const SLOW_SMA_INDICATOR = {
name: 'SLOW_SMA',
label: 'Slow SMA',
usesBaseData: false, // This simple indicator uses the chart's currently displayed data
params: [
{ name: 'period', type: 'number', defaultValue: 133, min: 2 },
],
calculateFull: calculateFullSMA,
color: '#ff5252',
};
function calculateFullSMA(data, params) {

View File

@ -5,11 +5,12 @@
<script src="https://unpkg.com/lightweight-charts@4.1.3/dist/lightweight-charts.standalone.production.js"></script>
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
<!-- Indicator & Aggregation Scripts -->
<!-- NOTE: These 'url_for' will not work in a static HTML file. -->
<!-- They are placeholders for a Flask environment. For a standalone file, you would link directly to the JS files. -->
<script src="{{ url_for('static', filename='candle-aggregator.js') }}"></script>
<script src="{{ url_for('static', filename='sma.js') }}"></script>
<script src="{{ url_for('static', filename='hts.js') }}"></script>
<script src="{{ url_for('static', filename='ema.js') }}"></script>
<script src="{{ url_for('static', filename='bb.js') }}"></script>
<script src="{{ url_for('static',filename='bb.js') }}"></script>
<script src="{{ url_for('static', filename='hurst.js') }}"></script>
<script src="{{ url_for('static', filename='indicators.js') }}"></script>
<script src="{{ url_for('static', filename='indicator-manager.js') }}"></script>
@ -19,6 +20,13 @@
--background-dark: #161A25; --container-dark: #1E222D; --border-color: #2A2E39;
--text-primary: #D1D4DC; --text-secondary: #8A91A0; --button-bg: #363A45;
--button-hover-bg: #434651; --accent-orange: #F0B90B; --green: #26a69a; --red: #ef5350;
/* Colors for measure tool */
--measure-tool-up-bg: rgba(41, 98, 255, 0.2);
--measure-tool-up-border: #2962FF;
--measure-tool-down-bg: rgba(239, 83, 80, 0.2);
--measure-tool-down-border: #ef5350;
--measure-tool-text: #FFFFFF;
}
body {
background-color: var(--background-dark); color: var(--text-primary);
@ -30,7 +38,8 @@
border-bottom: 1px solid var(--border-color); margin-bottom: 20px;
}
.header h1 { margin: 0; font-size: 24px; }
#chart { width: 90%; max-width: 1400px; height: 500px; }
#chart-wrapper { position: relative; width: 90%; max-width: 1400px; height: 500px; }
#chart { width: 100%; height: 100%; }
.control-panel {
display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 15px; width: 90%; max-width: 1400px; padding: 20px 0;
@ -48,20 +57,9 @@
border-radius: 5px; cursor: pointer; transition: background-color 0.3s, color 0.3s;
}
.action-button:hover, .control-cell select:hover { background-color: var(--button-hover-bg); }
#analyzeButton:hover { color: var(--accent-orange); }
.input-field { width: 60px; }
.analysis-section {
width: 90%; max-width: 1400px; background-color: var(--container-dark);
border: 1px solid var(--border-color); border-radius: 8px; padding: 20px;
margin-top: 10px; text-align: center;
}
#analysisResult {
margin-top: 15px; font-size: 0.95rem; line-height: 1.6; text-align: left;
white-space: pre-wrap; color: var(--text-primary); background-color: var(--background-dark);
padding: 15px; border-radius: 5px; min-height: 50px;
}
#candle-timer { font-size: 2rem; font-weight: 500; color: var(--accent-orange); }
#timeframe-select { margin-top: 10px; }
#timeframe-display { margin-top: 10px; min-width: 60px; }
.progress-bar-container {
width: 80%; height: 4px; background-color: var(--button-bg);
border-radius: 2px; margin-top: 10px; overflow: hidden;
@ -70,6 +68,44 @@
width: 0%; height: 100%; background-color: var(--green);
transition: width 0.4s ease-out;
}
/* --- Styles for Measure Tool --- */
#measure-tool {
position: absolute; top: 0; left: 0; width: 100%; height: 100%;
pointer-events: none; overflow: hidden; z-index: 10;
}
#measure-box { position: absolute; }
#measure-svg { position: absolute; width: 100%; height: 100%; top: 0; left: 0; }
#measure-tooltip {
position: absolute; color: var(--measure-tool-text); padding: 4px 8px;
border-radius: 4px; font-size: 11px; line-height: 1.2;
display: flex; flex-direction: column; align-items: center; justify-content: center;
}
/* --- Styles for Timeframe Modal --- */
.modal-overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background-color: rgba(0, 0, 0, 0.7);
display: none; /* Hidden by default */
justify-content: center; align-items: center; z-index: 1000;
}
.modal {
background-color: var(--container-dark); padding: 25px; border-radius: 8px;
border: 1px solid var(--border-color); text-align: center;
width: 300px; box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}
.modal h2 {
margin-top: 0; margin-bottom: 20px; font-size: 18px; color: var(--text-primary);
}
.modal .input-field {
width: 100%; box-sizing: border-box; font-size: 24px;
padding: 10px; margin-bottom: 10px; text-align: center;
}
.modal #timeframe-preview-text {
color: var(--text-secondary); font-size: 14px; margin-top: 0;
margin-bottom: 20px; min-height: 20px;
}
.modal .action-button { width: 100%; }
</style>
</head>
<body>
@ -77,25 +113,21 @@
<h1 id="chart-title">{{ symbol }} Chart</h1>
</div>
<div id="chart"></div>
<div id="chart-wrapper">
<div id="chart"></div>
<div id="measure-tool" style="display: none;">
<div id="measure-box"></div>
<svg id="measure-svg"></svg>
<div id="measure-tooltip"></div>
</div>
</div>
<div class="control-panel">
<div class="control-cell">
<h3>Candle Closes In</h3>
<div id="candle-timer">--:--</div>
<select id="timeframe-select">
<option value="1">1m</option>
<option value="2">2m</option>
<option value="3">3m</option>
<option value="4">4m</option>
<option value="5">5m</option>
<option value="6">6m</option>
<option value="7">7m</option>
<option value="8">8m</option>
<option value="9">9m</option>
<option value="10">10m</option>
</select>
<div id="progress-container" class="progress-bar-container">
<div id="timeframe-display" class="action-button">1m</div>
<div id="progress-container" class="progress-bar-container">
<div class="progress-bar"></div>
</div>
</div>
@ -105,10 +137,14 @@
<div class="control-cell" id="indicator-cell-4"></div>
</div>
<div class="analysis-section">
<h3>Analysis ✨</h3>
<button id="analyzeButton" class="action-button">Analyze Recent Price Action</button>
<div id="analysisResult">Click the button for AI analysis.</div>
<!-- Timeframe Modal -->
<div id="timeframe-modal-overlay" class="modal-overlay">
<div id="timeframe-modal" class="modal">
<h2>Change interval</h2>
<input type="number" id="timeframe-input" class="input-field" min="1" placeholder="Enter minutes"/>
<p id="timeframe-preview-text"></p>
<button id="timeframe-confirm-btn" class="action-button">OK</button>
</div>
</div>
<script>
@ -118,22 +154,93 @@
width: chartElement.clientWidth, height: 500,
layout: { background: { type: 'solid', color: '#1E222D' }, textColor: '#D1D4DC' },
grid: { vertLines: { color: '#2A2E39' }, horzLines: { color: '#2A2E39' } },
timeScale: { timeVisible: true, secondsVisible: true }
timeScale: { timeVisible: true, secondsVisible: true },
crosshair: {
mode: LightweightCharts.CrosshairMode.Normal,
},
});
const candlestickSeries = chart.addCandlestickSeries({
upColor: '#26a69a', downColor: '#ef5350', borderDownColor: '#ef5350',
borderUpColor: '#26a69a', wickDownColor: '#ef5350', wickUpColor: '#26a69a',
upColor: 'rgba(255, 152, 0, 1.0)', downColor: 'rgba(255, 152, 0, 0.66)', borderDownColor: 'rgba(255, 152, 0, 0.66)',
borderUpColor: 'rgba(255, 152, 0, 1.0)', wickDownColor: 'rgba(255, 152, 0, 0.66)', wickUpColor: 'rgba(255, 152, 0, 1.0)'
});
const originalAddLineSeries = chart.addLineSeries;
chart.addLineSeries = function(options) {
const newOptions = { ...options, crosshairMarkerVisible: false, };
return originalAddLineSeries.call(this, newOptions);
};
let baseCandleData1m = [];
let displayedCandleData = [];
let manager;
let currentTimeframeMinutes = 1;
const timeframeSelect = document.getElementById('timeframe-select');
const candleTimerDiv = document.getElementById('candle-timer');
const chartTitle = document.getElementById('chart-title');
const progressContainer = document.getElementById('progress-container');
const progressBar = document.querySelector('.progress-bar');
const measureToolEl = document.getElementById('measure-tool');
const measureBoxEl = document.getElementById('measure-box');
const measureSvgEl = document.getElementById('measure-svg');
const measureTooltipEl = document.getElementById('measure-tooltip');
let measureState = { active: false, finished: false, startPoint: null, endPoint: null };
let isRedrawScheduled = false;
const timeframeDisplay = document.getElementById('timeframe-display');
const modalOverlay = document.getElementById('timeframe-modal-overlay');
const modalInput = document.getElementById('timeframe-input');
const modalPreviewText = document.getElementById('timeframe-preview-text');
const modalConfirmBtn = document.getElementById('timeframe-confirm-btn');
function openModal(initialValue = '') {
modalOverlay.style.display = 'flex';
modalInput.value = initialValue;
updatePreviewText();
modalInput.focus();
modalInput.select();
}
function closeModal() {
modalOverlay.style.display = 'none';
}
function updatePreviewText() {
const value = modalInput.value;
if (value && parseInt(value) > 0) {
modalPreviewText.textContent = `${value} minute${parseInt(value) > 1 ? 's' : ''}`;
} else {
modalPreviewText.textContent = '';
}
}
function confirmTimeframe() {
const newTimeframe = parseInt(modalInput.value);
if (newTimeframe && newTimeframe > 0) {
currentTimeframeMinutes = newTimeframe;
timeframeDisplay.textContent = `${newTimeframe}m`;
updateChartForTimeframe(true);
closeModal();
}
}
timeframeDisplay.addEventListener('click', () => openModal(currentTimeframeMinutes));
modalConfirmBtn.addEventListener('click', confirmTimeframe);
modalInput.addEventListener('input', updatePreviewText);
modalInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') confirmTimeframe(); });
modalOverlay.addEventListener('click', (e) => { if (e.target === modalOverlay) closeModal(); });
window.addEventListener('keydown', (e) => {
if (modalOverlay.style.display === 'flex' && e.key === 'Escape') {
closeModal();
}
else if (modalOverlay.style.display !== 'flex' && !isNaN(parseInt(e.key)) && !e.ctrlKey && !e.metaKey) {
const activeEl = document.activeElement;
if (activeEl.tagName !== 'INPUT' && activeEl.tagName !== 'TEXTAREA') {
e.preventDefault();
openModal(e.key);
}
}
});
manager = createIndicatorManager(chart, baseCandleData1m, displayedCandleData);
manager.populateDropdowns();
@ -147,58 +254,308 @@
socket.on('history_finished', (data) => {
if (!data || !data.klines_1m) return;
progressBar.style.width = '100%';
baseCandleData1m = data.klines_1m.map(k => ({
time: k[0] / 1000, open: parseFloat(k[1]), high: parseFloat(k[2]),
low: parseFloat(k[3]), close: parseFloat(k[4])
}));
updateChartForTimeframe(true); // Initial load, fit content
updateChartForTimeframe(true);
setTimeout(() => { progressContainer.style.display = 'none'; }, 500);
});
socket.on('candle_update', (candle) => {
candlestickSeries.update(candle);
// --- MODIFICATION START: Rewritten candle update and creation logic ---
function handleLiveUpdate(update) {
if (baseCandleData1m.length === 0 || displayedCandleData.length === 0) return;
// First, ensure the base 1m data is up-to-date.
const lastBaseCandle = baseCandleData1m[baseCandleData1m.length - 1];
if (update.time > lastBaseCandle.time) {
baseCandleData1m.push(update);
} else if (update.time === lastBaseCandle.time) {
baseCandleData1m[baseCandleData1m.length - 1] = update;
}
const candleDurationSeconds = currentTimeframeMinutes * 60;
let lastDisplayedCandle = displayedCandleData[displayedCandleData.length - 1];
// Check if the update belongs to the currently forming displayed candle
if (update.time >= lastDisplayedCandle.time && update.time < lastDisplayedCandle.time + candleDurationSeconds) {
// It does, so just update the High, Low, and Close prices
lastDisplayedCandle.high = Math.max(lastDisplayedCandle.high, update.high);
lastDisplayedCandle.low = Math.min(lastDisplayedCandle.low, update.low);
lastDisplayedCandle.close = update.close;
candlestickSeries.update(lastDisplayedCandle);
} else if (update.time >= lastDisplayedCandle.time + candleDurationSeconds) {
// This update is for a NEW candle.
const newCandleTime = Math.floor(update.time / candleDurationSeconds) * candleDurationSeconds;
// Create the new candle. Its O,H,L,C are all from this first tick.
const newCandle = {
time: newCandleTime,
open: update.open,
high: update.high,
low: update.low,
close: update.close,
};
displayedCandleData.push(newCandle);
candlestickSeries.update(newCandle);
// Since a new candle has been formed, we should recalculate indicators
manager.recalculateAllAfterHistory(baseCandleData1m, displayedCandleData);
}
}
let latestCandleUpdate = null;
let isUpdateScheduled = false;
function processLatestUpdate() {
if (latestCandleUpdate) {
handleLiveUpdate(latestCandleUpdate);
latestCandleUpdate = null;
}
isUpdateScheduled = false;
}
socket.on('candle_update', (update) => {
latestCandleUpdate = update;
if (!isUpdateScheduled) {
isUpdateScheduled = true;
requestAnimationFrame(processLatestUpdate);
}
});
socket.on('candle_closed', (closedCandle) => {
const lastBaseCandle = baseCandleData1m.length > 0 ? baseCandleData1m[baseCandleData1m.length - 1] : null;
if (lastBaseCandle && lastBaseCandle.time === closedCandle.time) {
baseCandleData1m[baseCandleData1m.length - 1] = closedCandle;
// This handler's primary job is to ensure data integrity by using the final, closed 1m candle.
// 1. Update the master 1-minute data array with the final version of the candle.
const candleIndex = baseCandleData1m.findIndex(c => c.time === closedCandle.time);
if (candleIndex !== -1) {
baseCandleData1m[candleIndex] = closedCandle;
} else {
// This case might happen if connection was lost and we missed updates for this candle
baseCandleData1m.push(closedCandle);
baseCandleData1m.sort((a, b) => a.time - b.time); // Keep it sorted just in case
}
if (displayedCandleData.length === 0) return;
// 2. Determine which displayed candle this closed 1m candle belongs to.
const candleDurationSeconds = currentTimeframeMinutes * 60;
const bucketTime = Math.floor(closedCandle.time / candleDurationSeconds) * candleDurationSeconds;
// 3. Find the displayed candle that needs to be corrected with final data.
const displayedCandleToUpdate = displayedCandleData.find(c => c.time === bucketTime);
if (!displayedCandleToUpdate) {
console.warn("Could not find a displayed candle to update for closed 1m candle at", new Date(closedCandle.time * 1000).toISOString());
// As a fallback, a full redraw can fix inconsistencies.
// updateChartForTimeframe(true);
return;
}
// 4. Find all 1m source candles for this bucket.
const sourceCandles = baseCandleData1m.filter(c =>
c.time >= bucketTime && c.time < bucketTime + candleDurationSeconds
);
// 5. If we have source candles, aggregate them to get the CORRECT final data.
if (sourceCandles.length > 0) {
const finalCandle = {
time: bucketTime,
open: sourceCandles[0].open,
high: Math.max(...sourceCandles.map(c => c.high)),
low: Math.min(...sourceCandles.map(c => c.low)),
close: sourceCandles[sourceCandles.length - 1].close
};
// 6. Update the specific candle in the displayed data array
const displayedIndex = displayedCandleData.findIndex(c => c.time === bucketTime);
if (displayedIndex !== -1) {
displayedCandleData[displayedIndex] = finalCandle;
}
// 7. Update the series on the chart and recalculate indicators for accuracy.
candlestickSeries.update(finalCandle);
manager.recalculateAllAfterHistory(baseCandleData1m, displayedCandleData);
}
updateChartForTimeframe(false); // Subsequent update, preserve zoom
});
// --- MODIFICATION END ---
function updateChartForTimeframe(isInitialLoad = false) {
const selectedIntervalMinutes = parseInt(timeframeSelect.value, 10);
function updateChartForTimeframe(isFullReset = false) {
if (baseCandleData1m.length === 0) return;
const visibleRange = isInitialLoad ? null : chart.timeScale().getVisibleLogicalRange();
const newCandleData = aggregateCandles(baseCandleData1m, selectedIntervalMinutes);
const visibleTimeRange = isFullReset ? null : chart.timeScale().getVisibleTimeRange();
const newCandleData = aggregateCandles(baseCandleData1m, currentTimeframeMinutes);
if (newCandleData.length > 0) {
displayedCandleData = newCandleData;
candlestickSeries.setData(displayedCandleData);
chartTitle.textContent = `{{ symbol }} Chart (${selectedIntervalMinutes}m)`;
chartTitle.textContent = `{{ symbol }} Chart (${currentTimeframeMinutes}m)`;
manager.recalculateAllAfterHistory(baseCandleData1m, displayedCandleData);
if (visibleRange) {
chart.timeScale().setVisibleLogicalRange(visibleRange);
if (visibleTimeRange) {
chart.timeScale().setVisibleRange(visibleTimeRange);
} else {
chart.timeScale().fitContent();
}
}
}
timeframeSelect.addEventListener('change', () => updateChartForTimeframe(true));
function clearMeasureTool() {
measureState = { active: false, finished: false, startPoint: null, endPoint: null };
measureToolEl.style.display = 'none';
measureSvgEl.innerHTML = '';
}
function formatDuration(seconds) {
const d = Math.floor(seconds / (3600*24));
const h = Math.floor(seconds % (3600*24) / 3600);
const m = Math.floor(seconds % 3600 / 60);
let result = '';
if (d > 0) result += `${d}d `;
if (h > 0) result += `${h}h `;
if (m > 0) result += `${m}m`;
return result.trim() || '0m';
}
function drawMeasureTool() {
if (!measureState.startPoint || !measureState.endPoint) return;
const startCoord = {
x: chart.timeScale().timeToCoordinate(measureState.startPoint.time),
y: candlestickSeries.priceToCoordinate(measureState.startPoint.price)
};
const endCoord = {
x: chart.timeScale().timeToCoordinate(measureState.endPoint.time),
y: candlestickSeries.priceToCoordinate(measureState.endPoint.price)
};
if (startCoord.x === null || startCoord.y === null || endCoord.x === null || endCoord.y === null) {
measureToolEl.style.display = 'none';
return;
}
measureToolEl.style.display = 'block';
const isUp = measureState.endPoint.price >= measureState.startPoint.price;
const boxColor = isUp ? 'var(--measure-tool-up-bg)' : 'var(--measure-tool-down-bg)';
const borderColor = isUp ? 'var(--measure-tool-up-border)' : 'var(--measure-tool-down-border)';
measureBoxEl.style.backgroundColor = boxColor;
measureBoxEl.style.borderColor = borderColor;
measureTooltipEl.style.backgroundColor = borderColor;
const minX = Math.min(startCoord.x, endCoord.x);
const maxX = Math.max(startCoord.x, endCoord.x);
const minY = Math.min(startCoord.y, endCoord.y);
const maxY = Math.max(startCoord.y, endCoord.y);
measureBoxEl.style.left = `${minX}px`;
measureBoxEl.style.top = `${minY}px`;
measureBoxEl.style.width = `${maxX - minX}px`;
measureBoxEl.style.height = `${maxY - minY}px`;
const midX = minX + (maxX - minX) / 2;
const midY = minY + (maxY - minY) / 2;
const arrowSize = 5;
const isTimeGoingForward = measureState.endPoint.time >= measureState.startPoint.time;
let hArrowPoints = isTimeGoingForward
? `${maxX - arrowSize},${midY - arrowSize} ${maxX},${midY} ${maxX - arrowSize},${midY + arrowSize}`
: `${minX + arrowSize},${midY - arrowSize} ${minX},${midY} ${minX + arrowSize},${midY + arrowSize}`;
let vArrowPoints = isUp
? `${midX - arrowSize},${minY + arrowSize} ${midX},${minY} ${midX + arrowSize},${minY + arrowSize}`
: `${midX - arrowSize},${maxY - arrowSize} ${midX},${maxY} ${midX + arrowSize},${maxY - arrowSize}`;
measureSvgEl.innerHTML = `
<line x1="${minX}" y1="${midY}" x2="${maxX}" y2="${midY}" stroke="${borderColor}" stroke-width="1"/>
<polygon points="${hArrowPoints}" fill="${borderColor}" />
<line x1="${midX}" y1="${minY}" x2="${midX}" y2="${maxY}" stroke="${borderColor}" stroke-width="1"/>
<polygon points="${vArrowPoints}" fill="${borderColor}" />
`;
const priceChange = measureState.endPoint.price - measureState.startPoint.price;
const pctChange = (priceChange / measureState.startPoint.price) * 100;
const timeDifference = measureState.endPoint.time - measureState.startPoint.time;
const bars = Math.round(timeDifference / (currentTimeframeMinutes * 60));
const duration = formatDuration(Math.abs(timeDifference));
measureTooltipEl.innerHTML = `
<div>${priceChange.toFixed(2)} (${pctChange.toFixed(2)}%)</div>
<div>${bars} bars, ${duration}</div>
`;
measureTooltipEl.style.left = `${midX}px`;
const tooltipMargin = 8;
if (isUp) {
measureTooltipEl.style.top = `${minY}px`;
measureTooltipEl.style.transform = `translate(-50%, calc(-100% - ${tooltipMargin}px))`;
} else {
measureTooltipEl.style.top = `${maxY}px`;
measureTooltipEl.style.transform = `translate(-50%, ${tooltipMargin}px)`;
}
}
const onMeasureMove = (param) => {
if (!measureState.active || !param.point) return;
measureState.endPoint.time = chart.timeScale().coordinateToTime(param.point.x);
measureState.endPoint.price = candlestickSeries.coordinateToPrice(param.point.y);
if (!measureState.endPoint.time || !measureState.endPoint.price) return;
drawMeasureTool();
};
const onMeasureUp = () => {
measureState.active = false;
measureState.finished = true;
chart.unsubscribeCrosshairMove(onMeasureMove);
};
let priceScaleDragState = { isDragging: false };
function priceScaleRedrawLoop() {
if (!priceScaleDragState.isDragging) return;
drawMeasureTool();
requestAnimationFrame(priceScaleRedrawLoop);
}
chartElement.addEventListener('mousedown', (e) => {
if (!measureState.finished) return;
const rect = chartElement.getBoundingClientRect();
const priceScaleWidth = chart.priceScale('right').width();
if (e.clientX > rect.left + rect.width - priceScaleWidth) {
priceScaleDragState.isDragging = true;
requestAnimationFrame(priceScaleRedrawLoop);
}
});
window.addEventListener('mouseup', () => {
if (priceScaleDragState.isDragging) {
priceScaleDragState.isDragging = false;
}
});
chart.timeScale().subscribeVisibleTimeRangeChange(() => {
if (measureState.finished) {
drawMeasureTool();
}
});
chart.subscribeCrosshairMove(() => {
if (measureState.finished && !isRedrawScheduled) {
isRedrawScheduled = true;
requestAnimationFrame(() => {
drawMeasureTool();
isRedrawScheduled = false;
});
}
});
chart.subscribeClick((param) => {
if (measureState.finished) {
clearMeasureTool();
return;
}
if (!param.point || !param.sourceEvent.shiftKey) return;
if (measureState.active) {
onMeasureUp();
return;
}
clearMeasureTool();
const time = chart.timeScale().coordinateToTime(param.point.x);
const price = candlestickSeries.coordinateToPrice(param.point.y);
if (!time || !price) return;
measureState.startPoint = { time, price };
measureState.endPoint = { time, price };
measureState.active = true;
measureToolEl.style.display = 'block';
drawMeasureTool();
chart.subscribeCrosshairMove(onMeasureMove);
});
setInterval(() => {
const selectedIntervalSeconds = parseInt(timeframeSelect.value, 10) * 60;
const selectedIntervalSeconds = currentTimeframeMinutes * 60;
const now = new Date().getTime() / 1000;
const secondsRemaining = Math.floor(selectedIntervalSeconds - (now % selectedIntervalSeconds));
const minutes = Math.floor(secondsRemaining / 60);