annotations work and a re saved

This commit is contained in:
Dobromir Popov
2025-10-18 23:26:54 +03:00
parent 38d6a01f8e
commit 7646137f11
7 changed files with 771 additions and 60 deletions

View File

@@ -138,17 +138,39 @@ class AnnotationDashboard:
@self.server.route('/')
def index():
"""Main dashboard page"""
"""Main dashboard page - loads existing annotations"""
try:
# Get current annotations
# Get all existing annotations
annotations = self.annotation_manager.get_annotations()
# Convert to serializable format
annotations_data = []
for ann in annotations:
if hasattr(ann, '__dict__'):
ann_dict = ann.__dict__
else:
ann_dict = ann
# Ensure all fields are JSON serializable
annotations_data.append({
'annotation_id': ann_dict.get('annotation_id'),
'symbol': ann_dict.get('symbol'),
'timeframe': ann_dict.get('timeframe'),
'entry': ann_dict.get('entry'),
'exit': ann_dict.get('exit'),
'direction': ann_dict.get('direction'),
'profit_loss_pct': ann_dict.get('profit_loss_pct'),
'notes': ann_dict.get('notes', ''),
'created_at': ann_dict.get('created_at')
})
logger.info(f"Loading dashboard with {len(annotations_data)} existing annotations")
# Prepare template data
template_data = {
'current_symbol': 'ETH/USDT',
'timeframes': ['1s', '1m', '1h', '1d'],
'annotations': [ann.__dict__ if hasattr(ann, '__dict__') else ann
for ann in annotations]
'annotations': annotations_data
}
return render_template('annotation_dashboard.html', **template_data)
@@ -261,16 +283,72 @@ class AnnotationDashboard:
@self.server.route('/api/save-annotation', methods=['POST'])
def save_annotation():
"""Save a new annotation"""
"""Save a new annotation with full market context"""
try:
data = request.get_json()
# Create annotation
# Capture market state at entry and exit times
entry_market_state = {}
exit_market_state = {}
if self.data_loader:
try:
# Parse timestamps
entry_time = datetime.fromisoformat(data['entry']['timestamp'].replace('Z', '+00:00'))
exit_time = datetime.fromisoformat(data['exit']['timestamp'].replace('Z', '+00:00'))
# Fetch market data for all timeframes at entry time
timeframes = ['1s', '1m', '1h', '1d']
for tf in timeframes:
df = self.data_loader.get_data(
symbol=data['symbol'],
timeframe=tf,
end_time=entry_time,
limit=100
)
if df is not None and not df.empty:
entry_market_state[f'ohlcv_{tf}'] = {
'timestamps': df.index.strftime('%Y-%m-%d %H:%M:%S').tolist(),
'open': df['open'].tolist(),
'high': df['high'].tolist(),
'low': df['low'].tolist(),
'close': df['close'].tolist(),
'volume': df['volume'].tolist()
}
# Fetch market data at exit time
for tf in timeframes:
df = self.data_loader.get_data(
symbol=data['symbol'],
timeframe=tf,
end_time=exit_time,
limit=100
)
if df is not None and not df.empty:
exit_market_state[f'ohlcv_{tf}'] = {
'timestamps': df.index.strftime('%Y-%m-%d %H:%M:%S').tolist(),
'open': df['open'].tolist(),
'high': df['high'].tolist(),
'low': df['low'].tolist(),
'close': df['close'].tolist(),
'volume': df['volume'].tolist()
}
logger.info(f"Captured market state: {len(entry_market_state)} timeframes at entry, {len(exit_market_state)} at exit")
except Exception as e:
logger.error(f"Error capturing market state: {e}")
# Create annotation with market context
annotation = self.annotation_manager.create_annotation(
entry_point=data['entry'],
exit_point=data['exit'],
symbol=data['symbol'],
timeframe=data['timeframe']
timeframe=data['timeframe'],
entry_market_state=entry_market_state,
exit_market_state=exit_market_state
)
# Save annotation

View File

@@ -6,13 +6,14 @@ class AnnotationManager {
constructor(chartManager) {
this.chartManager = chartManager;
this.pendingAnnotation = null;
this.editingAnnotation = null;
this.enabled = true;
console.log('AnnotationManager initialized');
}
/**
* Handle chart click for marking entry/exit
* Handle chart click for marking entry/exit or editing
*/
handleChartClick(clickData) {
if (!this.enabled) {
@@ -20,6 +21,12 @@ class AnnotationManager {
return;
}
// Check if we're editing an existing annotation
if (this.editingAnnotation) {
this.handleEditClick(clickData);
return;
}
if (!this.pendingAnnotation) {
// Mark entry point
this.markEntry(clickData);
@@ -29,6 +36,95 @@ class AnnotationManager {
}
}
/**
* Handle click while editing an annotation
*/
handleEditClick(clickData) {
const editing = this.editingAnnotation;
const original = editing.original;
if (editing.editMode === 'entry') {
// Update entry point
const newAnnotation = {
...original,
entry: {
timestamp: clickData.timestamp,
price: clickData.price,
index: clickData.index
}
};
// Recalculate P&L
const entryPrice = newAnnotation.entry.price;
const exitPrice = newAnnotation.exit.price;
newAnnotation.direction = exitPrice > entryPrice ? 'LONG' : 'SHORT';
newAnnotation.profit_loss_pct = ((exitPrice - entryPrice) / entryPrice) * 100;
// Delete old annotation and save new one
this.deleteAndSaveAnnotation(editing.annotation_id, newAnnotation);
} else if (editing.editMode === 'exit') {
// Update exit point
const newAnnotation = {
...original,
exit: {
timestamp: clickData.timestamp,
price: clickData.price,
index: clickData.index
}
};
// Recalculate P&L
const entryPrice = newAnnotation.entry.price;
const exitPrice = newAnnotation.exit.price;
newAnnotation.direction = exitPrice > entryPrice ? 'LONG' : 'SHORT';
newAnnotation.profit_loss_pct = ((exitPrice - entryPrice) / entryPrice) * 100;
// Delete old annotation and save new one
this.deleteAndSaveAnnotation(editing.annotation_id, newAnnotation);
}
// Clear editing mode
this.editingAnnotation = null;
window.showSuccess('Annotation updated');
}
/**
* Delete old annotation and save updated one
*/
deleteAndSaveAnnotation(oldId, newAnnotation) {
// Delete old
fetch('/api/delete-annotation', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({annotation_id: oldId})
})
.then(() => {
// Save new
return fetch('/api/save-annotation', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(newAnnotation)
});
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Update app state
window.appState.annotations = window.appState.annotations.filter(a => a.annotation_id !== oldId);
window.appState.annotations.push(data.annotation);
// Update UI
window.renderAnnotationsList(window.appState.annotations);
this.chartManager.removeAnnotation(oldId);
this.chartManager.addAnnotation(data.annotation);
}
})
.catch(error => {
window.showError('Failed to update annotation: ' + error.message);
});
}
/**
* Mark entry point
*/

View File

@@ -139,11 +139,27 @@ class ChartManager {
annotations: []
};
// Add click handler for annotations
// Add click handler for chart
plotElement.on('plotly_click', (eventData) => {
this.handleChartClick(timeframe, eventData);
});
// Add click handler for annotations
plotElement.on('plotly_clickannotation', (eventData) => {
const annotationName = eventData.annotation.name;
if (annotationName) {
const parts = annotationName.split('_');
const action = parts[0]; // 'entry', 'exit', or 'delete'
const annotationId = parts[1];
if (action === 'delete') {
this.handleAnnotationClick(annotationId, 'delete');
} else {
this.handleAnnotationClick(annotationId, 'edit');
}
}
});
// Add hover handler to update info
plotElement.on('plotly_hover', (eventData) => {
this.updateChartInfo(timeframe, eventData);
@@ -159,10 +175,23 @@ class ChartManager {
if (!eventData.points || eventData.points.length === 0) return;
const point = eventData.points[0];
// Get the actual price from candlestick data
let price;
if (point.data.type === 'candlestick') {
// For candlestick, use close price
price = point.data.close[point.pointIndex];
} else if (point.data.type === 'bar') {
// Skip volume bar clicks
return;
} else {
price = point.y;
}
const clickData = {
timeframe: timeframe,
timestamp: point.x,
price: point.close || point.y,
price: price,
index: point.pointIndex
};
@@ -255,7 +284,7 @@ class ChartManager {
const entryPrice = ann.entry.price;
const exitPrice = ann.exit.price;
// Entry marker
// Entry marker (clickable)
plotlyAnnotations.push({
x: entryTime,
y: entryPrice,
@@ -266,10 +295,12 @@ class ChartManager {
color: ann.direction === 'LONG' ? '#10b981' : '#ef4444'
},
xanchor: 'center',
yanchor: 'bottom'
yanchor: 'bottom',
captureevents: true,
name: `entry_${ann.annotation_id}`
});
// Exit marker
// Exit marker (clickable)
plotlyAnnotations.push({
x: exitTime,
y: exitPrice,
@@ -280,10 +311,12 @@ class ChartManager {
color: ann.direction === 'LONG' ? '#10b981' : '#ef4444'
},
xanchor: 'center',
yanchor: 'top'
yanchor: 'top',
captureevents: true,
name: `exit_${ann.annotation_id}`
});
// P&L label
// P&L label with delete button
const midTime = new Date((new Date(entryTime).getTime() + new Date(exitTime).getTime()) / 2);
const midPrice = (entryPrice + exitPrice) / 2;
const pnlColor = ann.profit_loss_pct >= 0 ? '#10b981' : '#ef4444';
@@ -291,7 +324,7 @@ class ChartManager {
plotlyAnnotations.push({
x: midTime,
y: midPrice,
text: `${ann.profit_loss_pct >= 0 ? '+' : ''}${ann.profit_loss_pct.toFixed(2)}%`,
text: `${ann.profit_loss_pct >= 0 ? '+' : ''}${ann.profit_loss_pct.toFixed(2)}% 🗑️`,
showarrow: true,
arrowhead: 0,
ax: 0,
@@ -304,10 +337,12 @@ class ChartManager {
bgcolor: '#1f2937',
bordercolor: pnlColor,
borderwidth: 1,
borderpad: 4
borderpad: 4,
captureevents: true,
name: `delete_${ann.annotation_id}`
});
// Connecting line
// Connecting line (clickable for selection)
plotlyShapes.push({
type: 'line',
x0: entryTime,
@@ -318,7 +353,8 @@ class ChartManager {
color: ann.direction === 'LONG' ? '#10b981' : '#ef4444',
width: 2,
dash: 'dash'
}
},
name: `line_${ann.annotation_id}`
});
});
@@ -331,6 +367,25 @@ class ChartManager {
console.log(`Updated ${timeframeAnnotations.length} annotations for ${timeframe}`);
}
/**
* Handle annotation click for editing/deleting
*/
handleAnnotationClick(annotationId, action) {
console.log(`Annotation ${action}:`, annotationId);
if (action === 'delete') {
if (confirm('Delete this annotation?')) {
if (window.deleteAnnotation) {
window.deleteAnnotation(annotationId);
}
}
} else if (action === 'edit') {
if (window.appState && window.appState.chartManager) {
window.appState.chartManager.editAnnotation(annotationId);
}
}
}
/**
* Highlight annotation
*/
@@ -366,27 +421,88 @@ class ChartManager {
}
/**
* Edit annotation
* Edit annotation - allows moving entry/exit points
*/
editAnnotation(annotationId) {
const annotation = this.annotations[annotationId];
if (!annotation) return;
// Remove from charts
this.removeAnnotation(annotationId);
// Show edit dialog
const action = prompt(
'Edit annotation:\n' +
'1 - Move entry point\n' +
'2 - Move exit point\n' +
'3 - Delete annotation\n' +
'Enter choice (1-3):',
'1'
);
// Set as pending annotation for editing
if (window.appState && window.appState.annotationManager) {
window.appState.annotationManager.pendingAnnotation = {
annotation_id: annotationId,
symbol: annotation.symbol,
timeframe: annotation.timeframe,
entry: annotation.entry,
isEditing: true
};
if (action === '1') {
// Move entry point
window.showSuccess('Click on chart to set new entry point');
document.getElementById('pending-annotation-status').style.display = 'block';
// Store annotation for editing
if (window.appState && window.appState.annotationManager) {
window.appState.annotationManager.editingAnnotation = {
annotation_id: annotationId,
original: annotation,
editMode: 'entry'
};
// Remove current annotation from display
this.removeAnnotation(annotationId);
// Show exit marker as reference
const chart = this.charts[annotation.timeframe];
if (chart) {
Plotly.relayout(chart.plotId, {
annotations: [{
x: annotation.exit.timestamp,
y: annotation.exit.price,
text: '▼ (exit)',
showarrow: true,
arrowhead: 2,
ax: 0,
ay: 40,
font: {size: 14, color: '#9ca3af'}
}]
});
}
}
} else if (action === '2') {
// Move exit point
window.showSuccess('Click on chart to set new exit point');
if (window.appState && window.appState.annotationManager) {
window.appState.annotationManager.editingAnnotation = {
annotation_id: annotationId,
original: annotation,
editMode: 'exit'
};
// Remove current annotation from display
this.removeAnnotation(annotationId);
// Show entry marker as reference
const chart = this.charts[annotation.timeframe];
if (chart) {
Plotly.relayout(chart.plotId, {
annotations: [{
x: annotation.entry.timestamp,
y: annotation.entry.price,
text: '▲ (entry)',
showarrow: true,
arrowhead: 2,
ax: 0,
ay: -40,
font: {size: 14, color: '#9ca3af'}
}]
});
}
}
} else if (action === '3') {
// Delete
this.handleAnnotationClick(annotationId, 'delete');
}
}

View File

@@ -43,7 +43,7 @@
{% block extra_js %}
<script>
// Initialize application state
const appState = {
window.appState = {
currentSymbol: '{{ current_symbol }}',
currentTimeframes: {{ timeframes | tojson }},
annotations: {{ annotations | tojson }},
@@ -54,26 +54,29 @@
trainingController: null
};
// Initialize components when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
// Initialize chart manager
appState.chartManager = new ChartManager('chart-container', appState.currentTimeframes);
// Initialize annotation manager
appState.annotationManager = new AnnotationManager(appState.chartManager);
// Initialize time navigator
appState.timeNavigator = new TimeNavigator(appState.chartManager);
// Initialize training controller
appState.trainingController = new TrainingController();
// Load initial data
loadInitialData();
// Setup keyboard shortcuts
setupKeyboardShortcuts();
});
// Initialize components when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
// Initialize chart manager
window.appState.chartManager = new ChartManager('chart-container', window.appState.currentTimeframes);
// Initialize annotation manager
window.appState.annotationManager = new AnnotationManager(window.appState.chartManager);
// Initialize time navigator
window.appState.timeNavigator = new TimeNavigator(window.appState.chartManager);
// Initialize training controller
window.appState.trainingController = new TrainingController();
// Load initial data
loadInitialData();
// Setup keyboard shortcuts
setupKeyboardShortcuts();
// Setup global functions
setupGlobalFunctions();
});
function loadInitialData() {
// Fetch initial chart data
@@ -90,11 +93,11 @@
.then(response => response.json())
.then(data => {
if (data.success) {
appState.chartManager.initializeCharts(data.chart_data);
window.appState.chartManager.initializeCharts(data.chart_data);
// Load existing annotations
appState.annotations.forEach(annotation => {
appState.chartManager.addAnnotation(annotation);
window.appState.annotations.forEach(annotation => {
window.appState.chartManager.addAnnotation(annotation);
});
} else {
showError('Failed to load chart data: ' + data.error.message);
@@ -110,18 +113,40 @@
// Arrow left - navigate backward
if (e.key === 'ArrowLeft') {
e.preventDefault();
appState.timeNavigator.scrollBackward();
if (window.appState.timeNavigator) {
window.appState.timeNavigator.scrollBackward();
}
}
// Arrow right - navigate forward
else if (e.key === 'ArrowRight') {
e.preventDefault();
appState.timeNavigator.scrollForward();
if (window.appState.timeNavigator) {
window.appState.timeNavigator.scrollForward();
}
}
// Space - mark point (if chart is focused)
else if (e.key === ' ' && e.target.tagName !== 'INPUT') {
e.preventDefault();
// Trigger mark at current crosshair position
appState.annotationManager.markCurrentPosition();
if (window.appState.annotationManager) {
window.appState.annotationManager.markCurrentPosition();
}
}
// Escape - cancel pending annotation
else if (e.key === 'Escape') {
e.preventDefault();
if (window.appState.annotationManager) {
window.appState.annotationManager.pendingAnnotation = null;
document.getElementById('pending-annotation-status').style.display = 'none';
showSuccess('Annotation cancelled');
}
}
// Enter - complete annotation (if pending)
else if (e.key === 'Enter' && e.target.tagName !== 'INPUT') {
e.preventDefault();
if (window.appState.annotationManager && window.appState.annotationManager.pendingAnnotation) {
showSuccess('Click on chart to mark exit point');
}
}
});
}
@@ -169,5 +194,86 @@
bsToast.show();
toast.addEventListener('hidden.bs.toast', () => toast.remove());
}
function setupGlobalFunctions() {
// Make functions globally available
window.showError = showError;
window.showSuccess = showSuccess;
window.renderAnnotationsList = renderAnnotationsList;
window.deleteAnnotation = deleteAnnotation;
window.highlightAnnotation = highlightAnnotation;
}
function renderAnnotationsList(annotations) {
const listElement = document.getElementById('annotations-list');
if (!listElement) return;
listElement.innerHTML = '';
annotations.forEach(annotation => {
const item = document.createElement('div');
item.className = 'annotation-item mb-2 p-2 border rounded';
item.innerHTML = `
<div class="d-flex justify-content-between align-items-center">
<div>
<small class="text-muted">${annotation.timeframe}</small>
<div class="fw-bold ${annotation.profit_loss_pct >= 0 ? 'text-success' : 'text-danger'}">
${annotation.direction} ${annotation.profit_loss_pct >= 0 ? '+' : ''}${annotation.profit_loss_pct.toFixed(2)}%
</div>
<small class="text-muted">
${new Date(annotation.entry.timestamp).toLocaleString()}
</small>
</div>
<div class="btn-group btn-group-sm">
<button class="btn btn-outline-primary btn-sm" onclick="highlightAnnotation('${annotation.annotation_id}')" title="Highlight">
<i class="fas fa-eye"></i>
</button>
<button class="btn btn-outline-danger btn-sm" onclick="deleteAnnotation('${annotation.annotation_id}')" title="Delete">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
`;
listElement.appendChild(item);
});
}
function deleteAnnotation(annotationId) {
if (!confirm('Delete this annotation?')) return;
fetch('/api/delete-annotation', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({annotation_id: annotationId})
})
.then(response => response.json())
.then(data => {
if (data.success) {
// Remove from app state
window.appState.annotations = window.appState.annotations.filter(a => a.annotation_id !== annotationId);
// Update UI
renderAnnotationsList(window.appState.annotations);
// Remove from chart
if (window.appState.chartManager) {
window.appState.chartManager.removeAnnotation(annotationId);
}
showSuccess('Annotation deleted');
} else {
showError('Failed to delete annotation: ' + data.error.message);
}
})
.catch(error => {
showError('Network error: ' + error.message);
});
}
function highlightAnnotation(annotationId) {
if (window.appState.chartManager) {
window.appState.chartManager.highlightAnnotation(annotationId);
}
}
</script>
{% endblock %}