shape editing

This commit is contained in:
2026-03-02 22:49:45 -04:00
parent f4da40706c
commit bf7af2b426
18 changed files with 2236 additions and 209 deletions

View File

@@ -0,0 +1,36 @@
# Chart Context Awareness
## When Users Reference "The Chart"
When a user asks about "this chart", "the chart", "what I'm viewing", or similar references to their current view:
1. **Chart info is automatically available** — The dynamic system prompt includes current chart state (symbol, interval, timeframe)
2. **Check if chart is visible** — If ChartStore fields (symbol, interval) are `None`, the user is on a narrow screen (mobile) and no chart is visible
3. **When chart is visible:**
- **NEVER** ask the user to upload an image or tell you what symbol they're looking at
- **Just use `execute_python()`** — It automatically loads the chart data from what they're viewing
- Inside your Python script, `df` contains the data and `chart_context` has the metadata
- Use `plot_ohlc(df)` to create beautiful candlestick charts
4. **When chart is NOT visible (symbol is None):**
- Let the user know they can view charts on a wider screen
- You can still help with analysis using `get_historical_data()` if they specify a symbol
## Common Questions This Applies To
- "Can you see this chart?"
- "What are the swing highs and lows?"
- "Is this in an uptrend?"
- "What's the current price?"
- "Analyze this chart"
- "What am I looking at?"
## Data Analysis Workflow
1. **Chart context is automatic** → Symbol, interval, and timeframe are in the dynamic system prompt (if chart is visible)
2. **Check ChartStore** → If symbol/interval are `None`, no chart is visible (mobile view)
3. **Use `execute_python()`** → This is your PRIMARY analysis tool
- Automatically loads chart data into a pandas DataFrame `df` (if chart is visible)
- Pre-imports numpy (`np`), pandas (`pd`), matplotlib (`plt`), and talib
- Provides access to the indicator registry for computing indicators
- Use `plot_ohlc(df)` helper for beautiful candlestick charts
4. **Only use `get_chart_data()`** → For simple data inspection without analysis

View File

@@ -0,0 +1,115 @@
# Python Analysis Tool Reference
## Python Analysis (`execute_python`) - Your Primary Tool
**ALWAYS use `execute_python()` when the user asks for:**
- Technical indicators (RSI, MACD, Bollinger Bands, moving averages, etc.)
- Chart visualizations or plots
- Statistical calculations or market analysis
- Pattern detection or trend analysis
- Any computational analysis of price data
## Why `execute_python()` is preferred:
- Chart data (`df`) is automatically loaded from ChartStore (visible time range) when chart is visible
- If no chart is visible (symbol is None), `df` will be None - but you can still load alternative data!
- Full pandas/numpy/talib stack pre-imported
- Use `plot_ohlc(df)` for instant professional candlestick charts
- Access to 150+ indicators via `indicator_registry`
- **Access to DataStores and registry** - order_store, chart_store, datasource_registry
- **Can load ANY symbol/timeframe** using datasource_registry even when df is None
- **Results include plots as image URLs** that are automatically displayed to the user
- Prints and return values are included in the response
## CRITICAL: Plots are automatically shown to the user
When you create a matplotlib figure (via `plot_ohlc()` or `plt.figure()`), it is automatically:
1. Saved as a PNG image
2. Returned in the response as a URL (e.g., `/uploads/plot_abc123.png`)
3. **Displayed in the user's chat interface** - they see the image immediately
You MUST use `execute_python()` with `plot_ohlc()` or matplotlib whenever the user wants to see a chart or plot.
## IMPORTANT: Never use `get_historical_data()` for chart analysis
- `get_historical_data()` requires manual timestamp calculation and is only for custom queries
- When analyzing what the user is viewing, ALWAYS use `execute_python()` which automatically loads the correct data
- The `df` DataFrame in `execute_python()` is pre-loaded with the exact time range the user is viewing
## Example workflows:
### Computing an indicator and plotting (when chart is visible)
```python
execute_python("""
df['RSI'] = talib.RSI(df['close'], 14)
fig = plot_ohlc(df, title='Price with RSI')
df[['close', 'RSI']].tail(10)
""")
```
### Multi-indicator analysis (when chart is visible)
```python
execute_python("""
df['SMA20'] = df['close'].rolling(20).mean()
df['BB_upper'] = df['close'].rolling(20).mean() + 2 * df['close'].rolling(20).std()
df['BB_lower'] = df['close'].rolling(20).mean() - 2 * df['close'].rolling(20).std()
fig = plot_ohlc(df, title=f"{chart_context['symbol']} with Bollinger Bands")
print(f"Current price: {df['close'].iloc[-1]:.2f}")
print(f"20-period SMA: {df['SMA20'].iloc[-1]:.2f}")
""")
```
### Loading alternative data (works even when chart not visible or for different symbols)
```python
execute_python("""
from datetime import datetime, timedelta
# Get data source
binance = datasource_registry.get_source('binance')
# Load data for any symbol/timeframe
end_time = datetime.now()
start_time = end_time - timedelta(days=7)
result = await binance.get_history(
symbol='ETH/USDT',
interval='1h',
start=int(start_time.timestamp()),
end=int(end_time.timestamp())
)
# Convert to DataFrame
rows = [{'time': pd.to_datetime(bar.time, unit='s'), **bar.data} for bar in result.bars]
eth_df = pd.DataFrame(rows).set_index('time')
# Analyze and plot
eth_df['RSI'] = talib.RSI(eth_df['close'], 14)
fig = plot_ohlc(eth_df, title='ETH/USDT 1h - RSI Analysis')
print(f"ETH RSI: {eth_df['RSI'].iloc[-1]:.2f}")
""")
```
### Access stores to see current state
```python
execute_python("""
print(f"Current symbol: {chart_store.chart_state.symbol}")
print(f"Current interval: {chart_store.chart_state.interval}")
print(f"Number of orders: {len(order_store.orders)}")
""")
```
## Only use `get_chart_data()` for:
- Quick inspection of raw bar data
- When you just need the data structure without analysis
## Quick Reference: Common Tasks
| User Request | Tool to Use | Example |
|--------------|-------------|---------|
| "Show me RSI" | `execute_python()` | `df['RSI'] = talib.RSI(df['close'], 14); plot_ohlc(df)` |
| "What's the current price?" | `execute_python()` | `print(f"Current: {df['close'].iloc[-1]}")` |
| "Is this bullish?" | `execute_python()` | Compute SMAs, trend, and analyze |
| "Add Bollinger Bands" | `execute_python()` | Compute bands, use `plot_ohlc(df, title='BB')` |
| "Find swing highs" | `execute_python()` | Use pandas logic to detect patterns |
| "Plot ETH even though I'm viewing BTC" | `execute_python()` | Use `datasource_registry.get_source('binance')` to load ETH data |
| "What indicators exist?" | `search_indicators()` | Search by category or query |
| "What chart am I viewing?" | N/A - automatic | Chart info is in dynamic system prompt |
| "Check my orders" | `execute_python()` | `print(order_store.orders)` |
| "Read other stores" | `read_sync_state(store_name)` | For TraderState, StrategyState, etc. |

View File

@@ -59,140 +59,6 @@ You have access to:
- Past strategy discussions and decisions
- Relevant context retrieved automatically based on current conversation
## Important Behavioral Rules
### Chart Context Awareness
When a user asks about "this chart", "the chart", "what I'm viewing", or similar references to their current view:
1. **Chart info is automatically available** — The dynamic system prompt includes current chart state (symbol, interval, timeframe)
2. **Check if chart is visible** — If ChartStore fields (symbol, interval) are `None`, the user is on a narrow screen (mobile) and no chart is visible
3. **When chart is visible:**
- **NEVER** ask the user to upload an image or tell you what symbol they're looking at
- **Just use `execute_python()`** — It automatically loads the chart data from what they're viewing
- Inside your Python script, `df` contains the data and `chart_context` has the metadata
- Use `plot_ohlc(df)` to create beautiful candlestick charts
4. **When chart is NOT visible (symbol is None):**
- Let the user know they can view charts on a wider screen
- You can still help with analysis using `get_historical_data()` if they specify a symbol
This applies to questions like: "Can you see this chart?", "What are the swing highs and lows?", "Is this in an uptrend?", "What's the current price?", "Analyze this chart", "What am I looking at?"
### Data Analysis Workflow
1. **Chart context is automatic** → Symbol, interval, and timeframe are in the dynamic system prompt (if chart is visible)
2. **Check ChartStore** → If symbol/interval are `None`, no chart is visible (mobile view)
3. **Use `execute_python()`** → This is your PRIMARY analysis tool
- Automatically loads chart data into a pandas DataFrame `df` (if chart is visible)
- Pre-imports numpy (`np`), pandas (`pd`), matplotlib (`plt`), and talib
- Provides access to the indicator registry for computing indicators
- Use `plot_ohlc(df)` helper for beautiful candlestick charts
4. **Only use `get_chart_data()`** → For simple data inspection without analysis
### Python Analysis (`execute_python`) - Your Primary Tool
**ALWAYS use `execute_python()` when the user asks for:**
- Technical indicators (RSI, MACD, Bollinger Bands, moving averages, etc.)
- Chart visualizations or plots
- Statistical calculations or market analysis
- Pattern detection or trend analysis
- Any computational analysis of price data
**Why `execute_python()` is preferred:**
- Chart data (`df`) is automatically loaded from ChartStore (visible time range) when chart is visible
- If no chart is visible (symbol is None), `df` will be None - but you can still load alternative data!
- Full pandas/numpy/talib stack pre-imported
- Use `plot_ohlc(df)` for instant professional candlestick charts
- Access to 150+ indicators via `indicator_registry`
- **Access to DataStores and registry** - order_store, chart_store, datasource_registry
- **Can load ANY symbol/timeframe** using datasource_registry even when df is None
- **Results include plots as image URLs** that are automatically displayed to the user
- Prints and return values are included in the response
**CRITICAL: Plots are automatically shown to the user**
When you create a matplotlib figure (via `plot_ohlc()` or `plt.figure()`), it is automatically:
1. Saved as a PNG image
2. Returned in the response as a URL (e.g., `/uploads/plot_abc123.png`)
3. **Displayed in the user's chat interface** - they see the image immediately
You MUST use `execute_python()` with `plot_ohlc()` or matplotlib whenever the user wants to see a chart or plot.
**IMPORTANT: Never use `get_historical_data()` for chart analysis**
- `get_historical_data()` requires manual timestamp calculation and is only for custom queries
- When analyzing what the user is viewing, ALWAYS use `execute_python()` which automatically loads the correct data
- The `df` DataFrame in `execute_python()` is pre-loaded with the exact time range the user is viewing
**Example workflows:**
```python
# Computing an indicator and plotting (when chart is visible)
execute_python("""
df['RSI'] = talib.RSI(df['close'], 14)
fig = plot_ohlc(df, title='Price with RSI')
df[['close', 'RSI']].tail(10)
""")
# Multi-indicator analysis (when chart is visible)
execute_python("""
df['SMA20'] = df['close'].rolling(20).mean()
df['BB_upper'] = df['close'].rolling(20).mean() + 2 * df['close'].rolling(20).std()
df['BB_lower'] = df['close'].rolling(20).mean() - 2 * df['close'].rolling(20).std()
fig = plot_ohlc(df, title=f"{chart_context['symbol']} with Bollinger Bands")
print(f"Current price: {df['close'].iloc[-1]:.2f}")
print(f"20-period SMA: {df['SMA20'].iloc[-1]:.2f}")
""")
# Loading alternative data (works even when chart not visible or for different symbols)
execute_python("""
from datetime import datetime, timedelta
# Get data source
binance = datasource_registry.get_source('binance')
# Load data for any symbol/timeframe
end_time = datetime.now()
start_time = end_time - timedelta(days=7)
result = await binance.get_history(
symbol='ETH/USDT',
interval='1h',
start=int(start_time.timestamp()),
end=int(end_time.timestamp())
)
# Convert to DataFrame
rows = [{'time': pd.to_datetime(bar.time, unit='s'), **bar.data} for bar in result.bars]
eth_df = pd.DataFrame(rows).set_index('time')
# Analyze and plot
eth_df['RSI'] = talib.RSI(eth_df['close'], 14)
fig = plot_ohlc(eth_df, title='ETH/USDT 1h - RSI Analysis')
print(f"ETH RSI: {eth_df['RSI'].iloc[-1]:.2f}")
""")
# Access stores to see current state
execute_python("""
print(f"Current symbol: {chart_store.chart_state.symbol}")
print(f"Current interval: {chart_store.chart_state.interval}")
print(f"Number of orders: {len(order_store.orders)}")
""")
```
**Only use `get_chart_data()` for:**
- Quick inspection of raw bar data
- When you just need the data structure without analysis
### Quick Reference: Common Tasks
| User Request | Tool to Use | Example |
|--------------|-------------|---------|
| "Show me RSI" | `execute_python()` | `df['RSI'] = talib.RSI(df['close'], 14); plot_ohlc(df)` |
| "What's the current price?" | `execute_python()` | `print(f"Current: {df['close'].iloc[-1]}")` |
| "Is this bullish?" | `execute_python()` | Compute SMAs, trend, and analyze |
| "Add Bollinger Bands" | `execute_python()` | Compute bands, use `plot_ohlc(df, title='BB')` |
| "Find swing highs" | `execute_python()` | Use pandas logic to detect patterns |
| "Plot ETH even though I'm viewing BTC" | `execute_python()` | Use `datasource_registry.get_source('binance')` to load ETH data |
| "What indicators exist?" | `search_indicators()` | Search by category or query |
| "What chart am I viewing?" | N/A - automatic | Chart info is in dynamic system prompt |
| "Check my orders" | `execute_python()` | `print(order_store.orders)` |
| "Read other stores" | `read_sync_state(store_name)` | For TraderState, StrategyState, etc. |
## Working with Users
1. **Understand Intent**: Ask clarifying questions about strategy goals
@@ -200,3 +66,7 @@ print(f"Number of orders: {len(order_store.orders)}")
3. **Validate**: Ensure strategy makes sense before generating code
4. **Test**: Encourage backtesting and paper trading first
5. **Monitor**: Help users interpret live strategy behavior
---
**Note**: Additional context documents are loaded automatically to provide detailed operational guidelines. See memory files for specifics on chart context, shape drawing, Python analysis, and more.

View File

@@ -0,0 +1,612 @@
# TradingView Shapes and Drawings Reference
This document describes the various drawing shapes and studies available in TradingView charts, their properties, and control points. This information is useful for the AI agent to understand, create, and manipulate chart drawings.
## Shape Structure
All shapes follow a common structure:
- **id**: Unique identifier (string) - This is the TradingView-assigned ID after the shape is created
- **type**: Shape type identifier (string)
- **points**: Array of control points (each with `time` in Unix seconds and `price` as float)
- **color**: Color as hex string (e.g., '#FF0000') or color name (e.g., 'red')
- **line_width**: Line thickness in pixels (integer)
- **line_style**: One of: 'solid', 'dashed', 'dotted'
- **properties**: Dictionary of additional shape-specific properties
- **symbol**: Trading pair symbol (e.g., 'BINANCE:BTC/USDT')
- **created_at**: Creation timestamp (Unix seconds)
- **modified_at**: Last modification timestamp (Unix seconds)
- **original_id**: Optional string - The ID you requested when creating the shape, before TradingView assigned its own ID
## Understanding Shape ID Mapping
When you create a shape using `create_or_update_shape()`, there's an important ID mapping process:
1. **You specify an ID**: You provide a `shape_id` parameter (e.g., "my-support-line")
2. **TradingView assigns its own ID**: When the shape is rendered in TradingView, it gets a new internal ID (e.g., "shape_0x1a2b3c4d")
3. **ID remapping occurs**: The shape in the store is updated:
- The `id` field becomes TradingView's ID
- The `original_id` field preserves your requested ID
4. **Tracking your shapes**: To find shapes you created, search by `original_id`
### Example ID Mapping Flow
```python
# Step 1: Agent creates a shape with a specific ID
await create_or_update_shape(
shape_id="agent-support-50k",
shape_type="horizontal_line",
points=[{"time": 1678886400, "price": 50000}],
color="#00FF00"
)
# Step 2: Shape is synced to client and created in TradingView
# TradingView assigns ID: "shape_0x1a2b3c4d"
# Step 3: Shape in store is updated with:
# {
# "id": "shape_0x1a2b3c4d", # TradingView's ID
# "original_id": "agent-support-50k", # Your requested ID
# "type": "horizontal_line",
# ...
# }
# Step 4: To find your shape later, use shape_ids (searches both id and original_id)
my_shapes = search_shapes(
shape_ids=['agent-support-50k'],
symbol="BINANCE:BTC/USDT"
)
if my_shapes:
print(f"Found my support line!")
print(f"TradingView ID: {my_shapes[0]['id']}")
print(f"My requested ID: {my_shapes[0]['original_id']}")
# Or use the dedicated original_ids parameter
my_shapes = search_shapes(
original_ids=['agent-support-50k'],
symbol="BINANCE:BTC/USDT"
)
if my_shapes:
print(f"Found my support line!")
print(f"TradingView ID: {my_shapes[0]['id']}")
print(f"My requested ID: {my_shapes[0]['original_id']}")
```
### Why ID Mapping Matters
- **Shape identification**: You need to know which TradingView shape corresponds to the shape you created
- **Updates and deletions**: To modify or delete a shape, you need its TradingView ID (the `id` field)
- **Bidirectional sync**: The mapping ensures both the agent and TradingView can reference the same shape
### Best Practices for Shape IDs
1. **Use descriptive IDs**: Choose meaningful names like `support-btc-50k` or `trendline-daily-uptrend`
2. **Search by original ID**: Use `shape_ids` or `original_ids` parameters in `search_shapes()` to find your shapes
- `shape_ids` searches both the actual ID and original_id (more flexible)
- `original_ids` searches only the original_id field (more specific)
3. **Store important IDs**: If you need to reference a shape multiple times, store its TradingView ID after retrieval
4. **Understand the timing**: The ID remapping happens asynchronously after shape creation
## Common Shape Types
Use TradingView's native shape type names directly.
### 1. Trendline
**Type**: `trend_line`
**Control Points**: 2
- Point 1: Start of the line (time, price)
- Point 2: End of the line (time, price)
**Common Use Cases**:
- Support/resistance lines
- Trend identification
- Price channels (when paired)
**Example**:
```json
{
"id": "trendline-1",
"type": "trend_line",
"points": [
{"time": 1640000000, "price": 45000.0},
{"time": 1650000000, "price": 50000.0}
],
"color": "#2962FF",
"line_width": 2,
"line_style": "solid"
}
```
### 2. Horizontal Line
**Type**: `horizontal_line`
**Control Points**: 1
- Point 1: Y-level (time can be any value, only price matters)
**Common Use Cases**:
- Support/resistance levels
- Price targets
- Stop-loss levels
- Key psychological levels
**Properties**:
- `extend_left`: Boolean, extend line to the left
- `extend_right`: Boolean, extend line to the right
**Example**:
```json
{
"id": "support-1",
"type": "horizontal_line",
"points": [{"time": 1640000000, "price": 42000.0}],
"color": "#089981",
"line_width": 2,
"line_style": "dashed",
"properties": {
"extend_left": true,
"extend_right": true
}
}
```
### 3. Vertical Line
**Type**: `vertical_line`
**Control Points**: 1
- Point 1: X-time (price can be any value, only time matters)
**Common Use Cases**:
- Mark important events
- Session boundaries
- Earnings releases
- Economic data releases
**Properties**:
- `extend_top`: Boolean, extend line upward
- `extend_bottom`: Boolean, extend line downward
**Example**:
```json
{
"id": "event-marker-1",
"type": "vertical_line",
"points": [{"time": 1640000000, "price": 0}],
"color": "#787B86",
"line_width": 1,
"line_style": "dotted"
}
```
### 4. Rectangle
**Type**: `rectangle`
**Control Points**: 2
- Point 1: Top-left corner (time, price)
- Point 2: Bottom-right corner (time, price)
**Common Use Cases**:
- Consolidation zones
- Support/resistance zones
- Supply/demand areas
- Value areas
**Properties**:
- `fill_color`: Fill color with opacity (e.g., '#2962FF33')
- `fill`: Boolean, whether to fill the rectangle
- `extend_left`: Boolean
- `extend_right`: Boolean
**Example**:
```json
{
"id": "zone-1",
"type": "rectangle",
"points": [
{"time": 1640000000, "price": 50000.0},
{"time": 1650000000, "price": 48000.0}
],
"color": "#2962FF",
"line_width": 1,
"line_style": "solid",
"properties": {
"fill": true,
"fill_color": "#2962FF33"
}
}
```
### 5. Fibonacci Retracement
**Type**: `fib_retracement`
**Control Points**: 2
- Point 1: Start of the move (swing low or high)
- Point 2: End of the move (swing high or low)
**Common Use Cases**:
- Identify potential support/resistance levels
- Find retracement targets
- Measure pullback depth
**Properties**:
- `levels`: Array of Fibonacci levels to display
- Default: [0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0]
- `extend_lines`: Boolean, extend levels beyond the price range
- `reverse`: Boolean, reverse the direction
**Example**:
```json
{
"id": "fib-1",
"type": "fib_retracement",
"points": [
{"time": 1640000000, "price": 42000.0},
{"time": 1650000000, "price": 52000.0}
],
"color": "#2962FF",
"line_width": 1,
"properties": {
"levels": [0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0],
"extend_lines": true
}
}
```
### 6. Fibonacci Extension
**Type**: `fib_trend_ext`
**Control Points**: 3
- Point 1: Start of initial move
- Point 2: End of initial move (retracement start)
- Point 3: End of retracement
**Common Use Cases**:
- Project price targets
- Extension levels beyond 100%
- Measure continuation patterns
**Properties**:
- `levels`: Array of extension levels
- Common: [0, 0.618, 1.0, 1.618, 2.618, 4.236]
### 7. Parallel Channel
**Type**: `parallel_channel`
**Control Points**: 3
- Point 1: First point on main trendline
- Point 2: Second point on main trendline
- Point 3: Point on parallel line (determines channel width)
**Common Use Cases**:
- Price channels
- Regression channels
- Pitchforks
**Properties**:
- `extend_left`: Boolean
- `extend_right`: Boolean
- `fill`: Boolean, fill the channel
- `fill_color`: Fill color with opacity
### 8. Arrow
**Type**: `arrow`
**Control Points**: 2
- Point 1: Arrow start (time, price)
- Point 2: Arrow end (time, price)
**Common Use Cases**:
- Indicate price movement direction
- Mark entry/exit points
- Show relationships between events
**Properties**:
- `arrow_style`: One of: 'simple', 'filled', 'hollow'
- `text`: Optional text label
**Example**:
```json
{
"id": "entry-arrow",
"type": "arrow",
"points": [
{"time": 1640000000, "price": 44000.0},
{"time": 1641000000, "price": 48000.0}
],
"color": "#089981",
"line_width": 2,
"properties": {
"arrow_style": "filled",
"text": "Long Entry"
}
}
```
### 9. Text/Label
**Type**: `text`
**Control Points**: 1
- Point 1: Text anchor position (time, price)
**Common Use Cases**:
- Annotations
- Notes
- Labels for patterns
- Mark key levels
**Properties**:
- `text`: The text content (string)
- `font_size`: Font size in points (integer)
- `font_family`: Font family name
- `bold`: Boolean
- `italic`: Boolean
- `background`: Boolean, show background
- `background_color`: Background color
- `text_color`: Text color (can differ from line color)
**Example**:
```json
{
"id": "note-1",
"type": "text",
"points": [{"time": 1640000000, "price": 48000.0}],
"color": "#131722",
"properties": {
"text": "Resistance Zone",
"font_size": 14,
"bold": true,
"background": true,
"background_color": "#FFE600",
"text_color": "#131722"
}
}
```
### 10. Single-Point Markers
Various single-point marker shapes are available for annotating charts:
**Types**: `arrow_up` | `arrow_down` | `flag` | `emoji` | `icon` | `sticker` | `note` | `anchored_text` | `anchored_note` | `long_position` | `short_position`
**Control Points**: 1
- Point 1: Marker position (time, price)
**Common Use Cases**:
- Mark entry/exit points
- Flag important events
- Add visual markers to key levels
- Annotate patterns
- Track positions
**Properties** (vary by type):
- `text`: Text content for text-based markers
- `emoji`: Emoji character for emoji type
- `icon`: Icon identifier for icon type
**Examples**:
```json
{
"id": "long-entry-1",
"type": "long_position",
"points": [{"time": 1640000000, "price": 44000.0}],
"color": "#089981"
}
```
```json
{
"id": "flag-1",
"type": "flag",
"points": [{"time": 1640000000, "price": 50000.0}],
"color": "#F23645",
"properties": {
"text": "Important Event"
}
}
```
```json
{
"id": "note-1",
"type": "anchored_note",
"points": [{"time": 1640000000, "price": 48000.0}],
"color": "#FFE600",
"properties": {
"text": "Watch this level"
}
}
```
### 11. Circle/Ellipse
**Type**: `circle`
**Control Points**: 2 or 3
- 2 points: Defines bounding box (creates ellipse)
- 3 points: Center + radius points
**Common Use Cases**:
- Highlight areas
- Markup patterns
- Mark consolidation zones
**Properties**:
- `fill`: Boolean
- `fill_color`: Fill color with opacity
### 12. Path (Free Drawing)
**Type**: `path`
**Control Points**: Variable (3+)
- Multiple points defining a path
**Common Use Cases**:
- Custom patterns
- Freeform markup
- Complex annotations
**Properties**:
- `closed`: Boolean, whether to close the path
- `smooth`: Boolean, smooth the path with curves
### 13. Pitchfork (Andrew's Pitchfork)
**Type**: `pitchfork`
**Control Points**: 3
- Point 1: Pivot/starting point
- Point 2: First extreme (high or low)
- Point 3: Second extreme (opposite of point 2)
**Common Use Cases**:
- Trend channels
- Support/resistance levels
- Median line analysis
**Properties**:
- `extend_lines`: Boolean
- `style`: One of: 'standard', 'schiff', 'modified_schiff'
### 14. Gann Fan
**Type**: `gannbox_fan`
**Control Points**: 2
- Point 1: Origin point
- Point 2: Defines the unit size/scale
**Common Use Cases**:
- Time and price analysis
- Geometric angles (1x1, 1x2, 2x1, etc.)
**Properties**:
- `angles`: Array of angles to display
- Default: [82.5, 75, 71.25, 63.75, 45, 26.25, 18.75, 15, 7.5]
### 15. Head and Shoulders
**Type**: `head_and_shoulders`
**Control Points**: 5
- Point 1: Left shoulder low
- Point 2: Left shoulder high
- Point 3: Head low
- Point 4: Right shoulder high
- Point 5: Right shoulder low (neckline point)
**Common Use Cases**:
- Pattern recognition markup
- Reversal pattern identification
**Properties**:
- `target_line`: Boolean, show target line
## Special Properties
### Time-Based Properties
- All times are Unix timestamps in seconds
- Use `Math.floor(Date.now() / 1000)` for current time in JavaScript
- Use `int(time.time())` for current time in Python
### Color Formats
- Hex: `#RRGGBB` (e.g., `#2962FF`)
- Hex with alpha: `#RRGGBBAA` (e.g., `#2962FF33` for 20% opacity)
- Named colors: `red`, `blue`, `green`, etc.
- RGB: `rgb(41, 98, 255)`
- RGBA: `rgba(41, 98, 255, 0.2)`
### Line Styles
- `solid`: Continuous line
- `dashed`: Dashed line (— — —)
- `dotted`: Dotted line (· · ·)
## Best Practices
1. **ID Naming**: Use descriptive IDs that indicate the purpose
- Good: `support-btc-42k`, `trendline-uptrend-1`
- Bad: `shape1`, `line`
2. **Color Consistency**: Use consistent colors for similar types
- Green (#089981) for bullish/support
- Red (#F23645) for bearish/resistance
- Blue (#2962FF) for neutral/informational
3. **Time Alignment**: Ensure times align with actual candles when possible
4. **Layer Management**: Use different line widths to indicate importance
- Key levels: 2-3px
- Secondary levels: 1px
- Reference lines: 1px dotted
5. **Symbol Association**: Always set the `symbol` field to associate shapes with specific charts
## Agent Usage Examples
### Drawing a Support Level
When user says "draw support at 42000":
```python
await create_or_update_shape(
shape_id=f"support-{int(time.time())}",
shape_type='horizontal_line',
points=[{'time': current_time, 'price': 42000.0}],
color='#089981',
line_width=2,
line_style='solid',
symbol=chart_store.chart_state.symbol,
properties={'extend_left': True, 'extend_right': True}
)
```
### Finding Shapes in Visible Range
When user asks "what drawings are on the chart?":
```python
shapes = search_shapes(
start_time=chart_store.chart_state.start_time,
end_time=chart_store.chart_state.end_time,
symbol=chart_store.chart_state.symbol
)
```
### Getting Specific Shapes by ID
When user says "show me the details of trendline-1":
```python
# shape_ids parameter searches BOTH the actual ID and original_id fields
shapes = search_shapes(
shape_ids=['trendline-1']
)
```
Or to get selected shapes:
```python
selected_ids = chart_store.chart_state.selected_shapes
if selected_ids:
shapes = search_shapes(shape_ids=selected_ids)
```
### Finding Shapes by Original ID
When you need to find shapes you created using the original ID you specified:
```python
# Use the dedicated original_ids parameter
my_shapes = search_shapes(
original_ids=['my-support-line', 'my-trendline']
)
# Or use shape_ids (which searches both id and original_id)
my_shapes = search_shapes(
shape_ids=['my-support-line', 'my-trendline']
)
for shape in my_shapes:
print(f"Original ID: {shape['original_id']}")
print(f"TradingView ID: {shape['id']}")
print(f"Type: {shape['type']}")
```
### Searching Without Time Filter
When user asks "show me all support lines":
```python
support_lines = search_shapes(
shape_type='horizontal_line',
symbol=chart_store.chart_state.symbol
)
```
### Drawing a Trendline
When user says "draw an uptrend from the lows":
```python
# Find swing lows using execute_python
# Then create trendline
await create_or_update_shape(
shape_id=f"trendline-{int(time.time())}",
shape_type='trend_line',
points=[
{'time': swing_low_1_time, 'price': swing_low_1_price},
{'time': swing_low_2_time, 'price': swing_low_2_price}
],
color='#2962FF',
line_width=2,
symbol=chart_store.chart_state.symbol
)
```