# Agent Websocket API

The Fractrade platform provides websocket endpoints for real-time data and action streaming for every agent.

### Action Websocket <a href="#action-websocket" id="action-websocket"></a>

The Action websocket allows you to receive real-time actions from your agents.

#### Endpoint <a href="#endpoint" id="endpoint"></a>

```
wss://api.fractrade.xyz/ws/actions/{agent_id}
```

#### Authentication <a href="#authentication" id="authentication"></a>

Authentication is required to connect to the websocket. You can authenticate using your API key and secret:

```
wss://api.fractrade.xyz/ws/actions/{agent_id}?api_key={api_key}&api_secret={api_secret}
```

#### Message Format <a href="#message-format" id="message-format"></a>

Messages are sent in JSON format. Each message contains an action object:

```json
{
  "action_id": "action-uuid",
  "action_type": "EXECUTE_HYPERLIQUID_PERP_TRADE",
  "agent_id": "agent-uuid",
  "config": {
    "position": {
      "asset": "BTC",
      "size": 0.1,
      "side": "LONG",
      "leverage": 10,
      "exchange": "hyperliquid"
    }
  },
  "created_at": "2023-01-01T00:00:00Z",
  "status": "PENDING"
}
```

#### Action Types <a href="#action-types" id="action-types"></a>

The following action types are published to the websocket:

| Action Type                        | Description                      |
| ---------------------------------- | -------------------------------- |
| `EXECUTE_HYPERLIQUID_PERP_TRADE`   | Execute a trade on Hyperliquid   |
| `SET_HYPERLIQUID_PERP_STOP_LOSS`   | Set a stop loss on Hyperliquid   |
| `SET_HYPERLIQUID_PERP_TAKE_PROFIT` | Set a take profit on Hyperliquid |

Note: `SEND_TELEGRAM` actions are not published to the websocket as they are only used internally for sending notifications to Telegram.

#### Example: Connecting with Python <a href="#example-connecting-with-python" id="example-connecting-with-python"></a>

```python
import websocket
import json
import threading
import rel

def on_message(ws, message):
    action = json.loads(message)
    print(f"Received action: {action}")

    # Process the action
    action_type = action['action_type']
    config = action['config']

    if action_type == 'EXECUTE_HYPERLIQUID_PERP_TRADE':
        # Handle trade execution
        position = config['position']
        print(f"Trade signal: {position}")

        # Execute the trade using your own logic
        # ...

def on_error(ws, error):
    print(f"Error: {error}")

def on_close(ws, close_status_code, close_msg):
    print(f"Connection closed: {close_msg}")

def on_open(ws):
    print("Connection opened")

if __name__ == "__main__":
    # Replace with your actual values
    agent_id = "your-agent-id"
    api_key = "your-api-key"
    api_secret = "your-api-secret"

    # Create websocket connection
    ws_url = f"wss://api.fractrade.xyz/ws/actions/{agent_id}?api_key={api_key}&api_secret={api_secret}"

    ws = websocket.WebSocketApp(
        ws_url,
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )

    # Set dispatcher to automatic reconnection
    ws.run_forever(dispatcher=rel)
    rel.signal(2, rel.abort)  # Keyboard Interrupt
    rel.dispatch()
```

#### Example: Connecting with JavaScript <a href="#example-connecting-with-javascript" id="example-connecting-with-javascript"></a>

```javascript
const WebSocket = require('ws');

// Replace with your actual values
const agentId = 'your-agent-id';
const apiKey = 'your-api-key';
const apiSecret = 'your-api-secret';

// Create websocket connection
const wsUrl = `wss://api.fractrade.xyz/ws/actions/${agentId}?api_key=${apiKey}&api_secret=${apiSecret}`;
const ws = new WebSocket(wsUrl);

ws.on('open', function open() {
  console.log('Connection opened');
});

ws.on('message', function incoming(data) {
  const action = JSON.parse(data);
  console.log('Received action:', action);

  // Process the action
  const actionType = action.action_type;
  const config = action.config;

  if (actionType === 'EXECUTE_HYPERLIQUID_PERP_TRADE') {
    // Handle trade execution
    const position = config.position;
    console.log('Trade signal:', position);

    // Execute the trade using your own logic
    // ...
  }
});

ws.on('error', function error(err) {
  console.log('Error:', err);
});

ws.on('close', function close() {
  console.log('Connection closed');
});
```

### User Channel Websocket <a href="#user-channel-websocket" id="user-channel-websocket"></a>

For users who want to receive actions from all their agents, you can connect to the user channel websocket:

```
wss://api.fractrade.xyz/ws/user/{user_id}
```

This endpoint requires user authentication and will stream all actions from all agents owned by the user.

### Rate Limits <a href="#rate-limits" id="rate-limits"></a>

* Maximum 10 concurrent connections per user
* Maximum 100 messages per minute per connection

### Error Codes <a href="#error-codes" id="error-codes"></a>

| Code | Description           |
| ---- | --------------------- |
| 1000 | Normal closure        |
| 1001 | Going away            |
| 1002 | Protocol error        |
| 1003 | Unsupported data      |
| 1008 | Policy violation      |
| 1011 | Internal server error |

\
