# 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
)
```
