measurment tooltip + one week data from binance
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@ -1 +1,2 @@
|
|||||||
*.csv
|
*.csv
|
||||||
|
historical_data_1m.json
|
||||||
|
|||||||
46
app.py
46
app.py
@ -31,24 +31,43 @@ current_bar = {} # To track the currently forming 1-minute candle
|
|||||||
|
|
||||||
# --- Historical Data Streaming ---
|
# --- Historical Data Streaming ---
|
||||||
def stream_historical_data(sid):
|
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:
|
try:
|
||||||
logging.info(f"Starting historical data stream for SID={sid}")
|
logging.info(f"Starting historical data stream for SID={sid}")
|
||||||
client = Client()
|
client = Client()
|
||||||
num_chunks = 6
|
|
||||||
chunk_size_days = 15
|
|
||||||
end_date = datetime.utcnow()
|
|
||||||
all_klines = []
|
|
||||||
|
|
||||||
for i in range(num_chunks):
|
# --- NEW SOLUTION: Load data for the last week ---
|
||||||
start_date = end_date - timedelta(days=chunk_size_days)
|
logging.info(f"Fetching historical data for the last 7 days for SID={sid}")
|
||||||
logging.info(f"Fetching chunk {i + 1}/{num_chunks} for SID={sid}")
|
# The `python-binance` library allows using relative date strings.
|
||||||
new_klines = client.get_historical_klines(SYMBOL, Client.KLINE_INTERVAL_1MINUTE, str(start_date), str(end_date))
|
# This single call is more efficient for this use case.
|
||||||
if new_klines:
|
all_klines = client.get_historical_klines(
|
||||||
all_klines.extend(new_klines)
|
SYMBOL,
|
||||||
socketio.emit('history_progress', {'progress': ((i + 1) / num_chunks) * 100}, to=sid)
|
Client.KLINE_INTERVAL_1MINUTE,
|
||||||
end_date = start_date
|
start_str="1 week ago UTC" # Fetches data starting from 7 days ago until now
|
||||||
socketio.sleep(0.05)
|
)
|
||||||
|
|
||||||
|
# --- 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()
|
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))]
|
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.")
|
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)
|
socketio.emit('history_finished', {'klines_1m': unique_klines}, to=sid)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Error in stream_historical_data for SID={sid}: {e}", exc_info=True)
|
logging.error(f"Error in stream_historical_data for SID={sid}: {e}", exc_info=True)
|
||||||
socketio.emit('history_error', {'message': str(e)}, to=sid)
|
socketio.emit('history_error', {'message': str(e)}, to=sid)
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@ -19,6 +19,13 @@
|
|||||||
--background-dark: #161A25; --container-dark: #1E222D; --border-color: #2A2E39;
|
--background-dark: #161A25; --container-dark: #1E222D; --border-color: #2A2E39;
|
||||||
--text-primary: #D1D4DC; --text-secondary: #8A91A0; --button-bg: #363A45;
|
--text-primary: #D1D4DC; --text-secondary: #8A91A0; --button-bg: #363A45;
|
||||||
--button-hover-bg: #434651; --accent-orange: #F0B90B; --green: #26a69a; --red: #ef5350;
|
--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 {
|
body {
|
||||||
background-color: var(--background-dark); color: var(--text-primary);
|
background-color: var(--background-dark); color: var(--text-primary);
|
||||||
@ -30,7 +37,8 @@
|
|||||||
border-bottom: 1px solid var(--border-color); margin-bottom: 20px;
|
border-bottom: 1px solid var(--border-color); margin-bottom: 20px;
|
||||||
}
|
}
|
||||||
.header h1 { margin: 0; font-size: 24px; }
|
.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 {
|
.control-panel {
|
||||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||||
gap: 15px; width: 90%; max-width: 1400px; padding: 20px 0;
|
gap: 15px; width: 90%; max-width: 1400px; padding: 20px 0;
|
||||||
@ -48,18 +56,7 @@
|
|||||||
border-radius: 5px; cursor: pointer; transition: background-color 0.3s, color 0.3s;
|
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); }
|
.action-button:hover, .control-cell select:hover { background-color: var(--button-hover-bg); }
|
||||||
#analyzeButton:hover { color: var(--accent-orange); }
|
|
||||||
.input-field { width: 60px; }
|
.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); }
|
#candle-timer { font-size: 2rem; font-weight: 500; color: var(--accent-orange); }
|
||||||
#timeframe-select { margin-top: 10px; }
|
#timeframe-select { margin-top: 10px; }
|
||||||
.progress-bar-container {
|
.progress-bar-container {
|
||||||
@ -70,6 +67,40 @@
|
|||||||
width: 0%; height: 100%; background-color: var(--green);
|
width: 0%; height: 100%; background-color: var(--green);
|
||||||
transition: width 0.4s ease-out;
|
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;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@ -77,7 +108,14 @@
|
|||||||
<h1 id="chart-title">{{ symbol }} Chart</h1>
|
<h1 id="chart-title">{{ symbol }} Chart</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div id="chart-wrapper">
|
||||||
<div id="chart"></div>
|
<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-panel">
|
||||||
<div class="control-cell">
|
<div class="control-cell">
|
||||||
@ -89,11 +127,6 @@
|
|||||||
<option value="3">3m</option>
|
<option value="3">3m</option>
|
||||||
<option value="4">4m</option>
|
<option value="4">4m</option>
|
||||||
<option value="5">5m</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>
|
</select>
|
||||||
<div id="progress-container" class="progress-bar-container">
|
<div id="progress-container" class="progress-bar-container">
|
||||||
<div class="progress-bar"></div>
|
<div class="progress-bar"></div>
|
||||||
@ -105,12 +138,6 @@
|
|||||||
<div class="control-cell" id="indicator-cell-4"></div>
|
<div class="control-cell" id="indicator-cell-4"></div>
|
||||||
</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>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', (event) => {
|
document.addEventListener('DOMContentLoaded', (event) => {
|
||||||
const chartElement = document.getElementById('chart');
|
const chartElement = document.getElementById('chart');
|
||||||
@ -135,6 +162,13 @@
|
|||||||
const progressContainer = document.getElementById('progress-container');
|
const progressContainer = document.getElementById('progress-container');
|
||||||
const progressBar = document.querySelector('.progress-bar');
|
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;
|
||||||
|
|
||||||
manager = createIndicatorManager(chart, baseCandleData1m, displayedCandleData);
|
manager = createIndicatorManager(chart, baseCandleData1m, displayedCandleData);
|
||||||
manager.populateDropdowns();
|
manager.populateDropdowns();
|
||||||
|
|
||||||
@ -147,21 +181,16 @@
|
|||||||
|
|
||||||
socket.on('history_finished', (data) => {
|
socket.on('history_finished', (data) => {
|
||||||
if (!data || !data.klines_1m) return;
|
if (!data || !data.klines_1m) return;
|
||||||
|
|
||||||
progressBar.style.width = '100%';
|
progressBar.style.width = '100%';
|
||||||
|
|
||||||
baseCandleData1m = data.klines_1m.map(k => ({
|
baseCandleData1m = data.klines_1m.map(k => ({
|
||||||
time: k[0] / 1000, open: parseFloat(k[1]), high: parseFloat(k[2]),
|
time: k[0] / 1000, open: parseFloat(k[1]), high: parseFloat(k[2]),
|
||||||
low: parseFloat(k[3]), close: parseFloat(k[4])
|
low: parseFloat(k[3]), close: parseFloat(k[4])
|
||||||
}));
|
}));
|
||||||
|
updateChartForTimeframe(true);
|
||||||
updateChartForTimeframe(true); // Initial load, fit content
|
|
||||||
setTimeout(() => { progressContainer.style.display = 'none'; }, 500);
|
setTimeout(() => { progressContainer.style.display = 'none'; }, 500);
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('candle_update', (candle) => {
|
socket.on('candle_update', (candle) => candlestickSeries.update(candle));
|
||||||
candlestickSeries.update(candle);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on('candle_closed', (closedCandle) => {
|
socket.on('candle_closed', (closedCandle) => {
|
||||||
const lastBaseCandle = baseCandleData1m.length > 0 ? baseCandleData1m[baseCandleData1m.length - 1] : null;
|
const lastBaseCandle = baseCandleData1m.length > 0 ? baseCandleData1m[baseCandleData1m.length - 1] : null;
|
||||||
@ -170,15 +199,13 @@
|
|||||||
} else {
|
} else {
|
||||||
baseCandleData1m.push(closedCandle);
|
baseCandleData1m.push(closedCandle);
|
||||||
}
|
}
|
||||||
updateChartForTimeframe(false); // Subsequent update, preserve zoom
|
updateChartForTimeframe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
function updateChartForTimeframe(isInitialLoad = false) {
|
function updateChartForTimeframe(isFullReset = false) {
|
||||||
const selectedIntervalMinutes = parseInt(timeframeSelect.value, 10);
|
const selectedIntervalMinutes = parseInt(timeframeSelect.value, 10);
|
||||||
if (baseCandleData1m.length === 0) return;
|
if (baseCandleData1m.length === 0) return;
|
||||||
|
const visibleRange = isFullReset ? null : chart.timeScale().getVisibleLogicalRange();
|
||||||
const visibleRange = isInitialLoad ? null : chart.timeScale().getVisibleLogicalRange();
|
|
||||||
|
|
||||||
const newCandleData = aggregateCandles(baseCandleData1m, selectedIntervalMinutes);
|
const newCandleData = aggregateCandles(baseCandleData1m, selectedIntervalMinutes);
|
||||||
|
|
||||||
if (newCandleData.length > 0) {
|
if (newCandleData.length > 0) {
|
||||||
@ -186,17 +213,202 @@
|
|||||||
candlestickSeries.setData(displayedCandleData);
|
candlestickSeries.setData(displayedCandleData);
|
||||||
chartTitle.textContent = `{{ symbol }} Chart (${selectedIntervalMinutes}m)`;
|
chartTitle.textContent = `{{ symbol }} Chart (${selectedIntervalMinutes}m)`;
|
||||||
manager.recalculateAllAfterHistory(baseCandleData1m, displayedCandleData);
|
manager.recalculateAllAfterHistory(baseCandleData1m, displayedCandleData);
|
||||||
|
if (visibleRange) chart.timeScale().setVisibleLogicalRange(visibleRange);
|
||||||
if (visibleRange) {
|
else chart.timeScale().fitContent();
|
||||||
chart.timeScale().setVisibleLogicalRange(visibleRange);
|
|
||||||
} else {
|
|
||||||
chart.timeScale().fitContent();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
timeframeSelect.addEventListener('change', () => updateChartForTimeframe(true));
|
timeframeSelect.addEventListener('change', () => updateChartForTimeframe(true));
|
||||||
|
|
||||||
|
// --- Measure Tool Logic ---
|
||||||
|
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;
|
||||||
|
if (isTimeGoingForward) {
|
||||||
|
hArrowPoints = `${maxX - arrowSize},${midY - arrowSize} ${maxX},${midY} ${maxX - arrowSize},${midY + arrowSize}`;
|
||||||
|
} else {
|
||||||
|
hArrowPoints = `${minX + arrowSize},${midY - arrowSize} ${minX},${midY} ${minX + arrowSize},${midY + arrowSize}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let vArrowPoints;
|
||||||
|
if (isUp) {
|
||||||
|
vArrowPoints = `${midX - arrowSize},${minY + arrowSize} ${midX},${minY} ${midX + arrowSize},${minY + arrowSize}`;
|
||||||
|
} else {
|
||||||
|
vArrowPoints = `${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 / (parseInt(timeframeSelect.value, 10) * 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);
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- High-performance scaling logic for price axis drag ---
|
||||||
|
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();
|
||||||
|
const chartWidth = rect.width;
|
||||||
|
if (e.clientX > rect.left + chartWidth - priceScaleWidth) {
|
||||||
|
priceScaleDragState.isDragging = true;
|
||||||
|
requestAnimationFrame(priceScaleRedrawLoop);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('mouseup', () => {
|
||||||
|
if (priceScaleDragState.isDragging) {
|
||||||
|
priceScaleDragState.isDragging = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// --- End high-performance scaling logic ---
|
||||||
|
|
||||||
|
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(() => {
|
setInterval(() => {
|
||||||
const selectedIntervalSeconds = parseInt(timeframeSelect.value, 10) * 60;
|
const selectedIntervalSeconds = parseInt(timeframeSelect.value, 10) * 60;
|
||||||
const now = new Date().getTime() / 1000;
|
const now = new Date().getTime() / 1000;
|
||||||
|
|||||||
Reference in New Issue
Block a user