# Fractrade ExecutionClient

The ExecutionClient is a Python client that executes trading actions received via WebSocket from the Fractrade platform.

### Overview <a href="#overview" id="overview"></a>

The Fractrade platform (fractrade.xyz) allows you to create trading agents that generate trading actions. Each agent has a dedicated WebSocket connection that broadcasts these actions. The ExecutionClient connects to this WebSocket and executes the trading actions locally on your machine.

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

The client handles the following action types:

1. **EXECUTE\_HYPERLIQUID\_PERP\_TRADE**: Execute perpetual trades (open/close positions)
2. **SET\_HYPERLIQUID\_PERP\_STOP\_LOSS**: Set stop loss orders
3. **SET\_HYPERLIQUID\_PERP\_TAKE\_PROFIT**: Set take profit orders

### Installation <a href="#installation" id="installation"></a>

```bash
pip install fractrade-executor
```

### Configuration <a href="#configuration" id="configuration"></a>

The executor requires the following environment variables:

```bash
# Required
FRAC_WS_URL=wss://your-websocket-url
FRAC_USER_TOKEN=your-user-token
HYPERLIQUID_PRIVATE_KEY=your-private-key
HYPERLIQUID_PUBLIC_ADDRESS=your-wallet-address

# Optional
LOGLEVEL=INFO  # Set to DEBUG for more detailed logs
```

### Basic Usage <a href="#basic-usage" id="basic-usage"></a>

```python
from fractrade_executor.executor import FractradeExecutor

async def main():
    # Create and start the executor
    executor = FractradeExecutor()

    try:
        await executor.start()
        print("Executor running. Press Ctrl+C to stop.")

        # Wait for shutdown event
        await executor._shutdown_event.wait()

    except KeyboardInterrupt:
        print("Shutting down...")
    finally:
        await executor.stop()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
```

### Advanced Usage <a href="#advanced-usage" id="advanced-usage"></a>

You can customize the executor by subclassing `FractradeExecutor` and overriding its methods:

```python
class CustomExecutor(FractradeExecutor):
    async def handle_hyperliquid_perp_trade(self, config):
        """Custom trade handling logic"""
        self.logger.info("Processing trade: %s", config)
        return await super().handle_hyperliquid_perp_trade(config)

    async def handle_set_hyperliquid_perp_stop_loss(self, config):
        """Custom stop loss handling logic"""
        self.logger.info("Setting stop loss: %s", config)
        return await super().handle_set_hyperliquid_perp_stop_loss(config)

    async def handle_set_hyperliquid_perp_take_profit(self, config):
        """Custom take profit handling logic"""
        self.logger.info("Setting take profit: %s", config)
        return await super().handle_set_hyperliquid_perp_take_profit(config)
```

### WebSocket Messages <a href="#websocket-messages" id="websocket-messages"></a>

The executor receives WebSocket messages in the following format:

```json
{
    "type": "ACTION",
    "data": {
        "action_id": "execute_hyperliquid_perp_trade",
        "config": {
            "position": {
                "symbol": "BTC",
                "size": "0.01",
                "side": "BUY",
                "reduce_only": false
            },
            "metadata": {
                "event_id": "...",
                "price": 50000.0,
                "leverage": 10
            }
        }
    }
}
```

### Error Handling <a href="#error-handling" id="error-handling"></a>

The executor includes comprehensive error handling and logging:

* Connection errors are automatically retried
* Trade execution errors are logged with details
* Invalid messages are logged and skipped
* Graceful shutdown on interruption

### Logging <a href="#logging" id="logging"></a>

The executor uses Python's standard logging module. Set the `LOGLEVEL` environment variable to control log output:

```bash
LOGLEVEL=DEBUG  # For detailed debugging
LOGLEVEL=INFO   # For normal operation
LOGLEVEL=WARNING  # For minimal output
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://fractrade.gitbook.io/fractrade/developers/fractrade-executionclient.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
