### Momentum Strategy - Python Example Source: https://context7.com/oasisprotocol/wt3/llms.txt Provides a Python example for generating trading signals using the `MomentumStrategy`. This includes configuration of risk management parameters and retrieving signals for a specific coin. ```APIDOC ## Momentum Strategy - Signal Generation ### Description Generates trading signals using RSI and moving average indicators with automatic risk management. This Python code demonstrates how to initialize and configure the `MomentumStrategy` and obtain trading signals. ### Method Client-side Python Library ### Endpoint N/A (Internal strategy logic) ### Parameters None for strategy initialization, but can be configured. ### Request Example ```python import asyncio from signal_service_example.core.momentum_strategy import MomentumStrategy async def main(): # Initialize strategy with default parameters strategy = MomentumStrategy() # Configure strategy parameters (optional) strategy.risk_per_trade = 0.02 # Risk 2% per trade strategy.reward_risk_ratio = 3.0 # Target 3:1 reward:risk strategy.max_leverage = 5.0 # Maximum 5x leverage strategy.min_trade_size_usd = 100.0 # Minimum $100 trade # Get signal for specific coin signal = await strategy.get_signal('ETH') # Process signal if signal['trade_decision']: decision = signal['trade_decision'] print(f"Trade Action: {decision['action']}") print(f"Direction: {decision['direction']}") print(f"Confidence: {decision['confidence']}") print(f"Position Size: {decision['strategy']['position_size_coin']} ETH") print(f"Leverage: {decision['strategy']['leverage']}x") print(f"Stop Loss: ${decision['strategy']['stop_loss']}") print(f"Take Profit: ${decision['strategy']['take_profit']}") # Check current position if signal['current_position']: position = signal['current_position'] print(f"Current Position: {position['direction']} {position['size']}") asyncio.run(main()) ``` ### Response #### Success Response - The `signal` variable will contain a dictionary with trading signal information, structured similarly to the `GET /signal/{coin}` response. #### Response Example (from `signal` variable) ```json { "timestamp": 1703001234, "trade_decision": { "action": "open", "direction": "long", "confidence": 0.85, "coin": "ETH", "strategy": { "position_size_coin": 0.15, "leverage": 3.5, "stop_loss": 2200.0, "take_profit": 2500.0 } }, "current_position": { "size": 0.0, "direction": "NONE", "entry_price": null } } ``` ``` -------------------------------- ### Install Python Dependencies with uv Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Installs Python dependencies for the WT3 project using the uv package manager. uv will automatically create and manage a virtual environment for the project. ```bash uv sync ``` -------------------------------- ### Signal Client - Python Integration Example Source: https://context7.com/oasisprotocol/wt3/llms.txt Demonstrates how to initialize and use the `SignalClient` in Python to retrieve trading predictions from the signal service. Includes automatic service discovery, health checks, and retry logic. ```APIDOC ## Signal Client Initialization and Usage ### Description Initializes the signal client to retrieve trading predictions from the signal service with automatic fallback support. This Python code snippet shows how to connect, wait for service health, and fetch predictions. ### Method Client-side Python Library ### Endpoint N/A (Connects to signal service endpoints) ### Parameters None for client initialization. ### Request Example ```python import asyncio from wt3.clients.signal import SignalClient async def main(): # Initialize client with automatic service discovery client = SignalClient() # Wait for signal service to become healthy is_healthy = await client.wait_for_health(timeout=30) if not is_healthy: raise Exception("Signal service unavailable") # Get trading prediction with retry logic prediction = await client.get_prediction(max_retries=3) if prediction: trade_decision = prediction.get('trade_decision') if trade_decision: print(f"Action: {trade_decision['action']}") print(f"Coin: {trade_decision['coin']}") print(f"Direction: {trade_decision['direction']}") print(f"Confidence: {trade_decision['confidence']}") # Clean up await client.close() asyncio.run(main()) ``` ### Response #### Success Response - The `prediction` variable will contain a dictionary similar to the response of the `GET /signal/{coin}` endpoint. #### Response Example (from `prediction` variable) ```json { "timestamp": 1703001234, "trade_decision": { "action": "open", "direction": "long", "confidence": 0.85, "coin": "BTC", "strategy": { "position_size_coin": 0.1, "leverage": 2.0, "stop_loss": 42000.0, "take_profit": 46000.0 } }, "current_position": { "size": 0.0, "direction": "NONE", "entry_price": null } } ``` ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Installs the uv package manager, a modern Python package manager, using a curl script. This is a prerequisite for setting up the local development environment for WT3. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Deploy WT3 with Docker Compose and Oasis ROFL (Bash) Source: https://context7.com/oasisprotocol/wt3/llms.txt This bash script provides instructions for deploying the WT3 system using Docker Compose. It covers building Docker images, pushing them to a registry, inspecting image digests for security, updating the compose file, and initializing, creating, building, updating, and checking the status of the deployment with Oasis ROFL. It requires Docker and Oasis ROFL to be installed. ```bash # Build Docker images with proper tagging docker build -t yourusername/wt3:latest . docker build -t yourusername/wt3-signal:latest -f Dockerfile.signal . # Push to Docker Hub docker push yourusername/wt3:latest docker push yourusername/wt3-signal:latest # Get image digests for security docker inspect --format='{{index .RepoDigests 0}}' yourusername/wt3:latest # Output: yourusername/wt3@sha256:abc123... docker inspect --format='{{index .RepoDigests 0}}' yourusername/wt3-signal:latest # Output: yourusername/wt3-signal@sha256:def456... # Update compose.yaml with digests cat > compose.yaml << 'EOF' version: '3.8' services: wt3: image: docker.io/yourusername/wt3@sha256:abc123... restart: always volumes: - /storage/data:/storage/data environment: - SIGNAL_SERVICE_URL=http://signal-service:8001 signal-service: image: docker.io/yourusername/wt3-signal@sha256:def456... restart: always ports: - "8001:8001" EOF # Initialize and deploy with ROFL oasis rofl init oasis rofl create oasis rofl build oasis rofl update # Check deployment status oasis rofl status ``` -------------------------------- ### Configure Environment Variables for WT3 (Bash) Source: https://context7.com/oasisprotocol/wt3/llms.txt This bash script demonstrates how to create an .env file for configuring environment variables for the WT3 system. It shows examples for setting the SIGNAL_SERVICE_URL for local development and placeholders for sensitive information like PRIVATE_KEY. This file is typically used by Docker or other deployment tools to inject configuration. ```bash # .env file for local development cat > .env << 'EOF' # Trading Configuration SIGNAL_SERVICE_URL=http://localhost:8001 PRIVATE_KEY=0xYOUR_PRIVATE_KEY_HERE ``` -------------------------------- ### Run Local Signal Service Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Runs the example signal service for local development using uv. This service generates trading signals and is essential for testing the WT3 agent locally. ```bash uv run python -m src.signal_service_example ``` -------------------------------- ### Get Docker Image Digests Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Retrieves the SHA256 digests for the built Docker images. These digests are used to ensure the integrity and immutability of the deployed images in production. ```bash docker inspect --format='{{index .RepoDigests 0}}' yourusername/wt3:latest docker inspect --format='{{index .RepoDigests 0}}' yourusername/wt3-signal:latest ``` -------------------------------- ### Get Trading Signal for BTC (Bash) Source: https://context7.com/oasisprotocol/wt3/llms.txt Retrieves momentum-based trading signals for Bitcoin (BTC), including complete strategy parameters. The response details trade decisions like action, direction, confidence, and specific strategy parameters such as position size, leverage, stop-loss, and take-profit. It also indicates the current position if one exists. ```bash curl -X GET http://localhost:8001/signal/BTC # Response { "timestamp": 1703001234, "trade_decision": { "action": "open", "direction": "long", "confidence": 0.85, "coin": "BTC", "strategy": { "position_size_coin": 0.1, "leverage": 2.0, "stop_loss": 42000.0, "take_profit": 46000.0 } }, "current_position": { "size": 0.0, "direction": "NONE", "entry_price": null } } # Example with existing position { "timestamp": 1703001234, "trade_decision": null, "current_position": { "size": 0.1, "direction": "LONG", "entry_price": 43000.0 } } ``` -------------------------------- ### Signal Service - Get Trading Signal Source: https://context7.com/oasisprotocol/wt3/llms.txt Retrieves momentum-based trading signals for a specific cryptocurrency. This endpoint provides detailed trading decisions, including strategy parameters and current position information. ```APIDOC ## GET /signal/{coin} ### Description Retrieves momentum-based trading signals for a specific cryptocurrency with complete strategy parameters. ### Method GET ### Endpoint `/signal/{coin}` ### Parameters #### Path Parameters - **coin** (string) - Required - The cryptocurrency symbol for which to retrieve trading signals (e.g., "BTC", "ETH"). ### Request Example None ### Response #### Success Response (200) - **timestamp** (integer) - The Unix timestamp when the signal was generated. - **trade_decision** (object or null) - Contains the trading decision details if a trade is recommended. Can be null if no trade is recommended. - **action** (string) - The type of trade action (e.g., "open", "close"). - **direction** (string) - The trading direction (e.g., "long", "short"). - **confidence** (float) - The confidence level of the trade decision. - **coin** (string) - The cryptocurrency symbol for the trade. - **strategy** (object) - The parameters of the trading strategy. - **position_size_coin** (float) - The calculated position size in cryptocurrency units. - **leverage** (float) - The leverage applied to the trade. - **stop_loss** (float) - The stop-loss price level. - **take_profit** (float) - The take-profit price level. - **current_position** (object) - Information about the current open position for the specified coin. - **size** (float) - The size of the current position. - **direction** (string) - The direction of the current position (e.g., "LONG", "SHORT", "NONE"). - **entry_price** (float or null) - The entry price of the current position, or null if no position is open. #### Response Example ```json { "timestamp": 1703001234, "trade_decision": { "action": "open", "direction": "long", "confidence": 0.85, "coin": "BTC", "strategy": { "position_size_coin": 0.1, "leverage": 2.0, "stop_loss": 42000.0, "take_profit": 46000.0 } }, "current_position": { "size": 0.0, "direction": "NONE", "entry_price": null } } ``` #### Response Example (with existing position) ```json { "timestamp": 1703001234, "trade_decision": null, "current_position": { "size": 0.1, "direction": "LONG", "entry_price": 43000.0 } } ``` ``` -------------------------------- ### Create .env File for Local Development Configuration Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Creates a `.env` file to store configuration variables for local development, including private keys and API keys for various services like Grok and Twitter. ```bash # Private key for local development (use a test key, never real funds!) PRIVATE_KEY=0xYOUR_PRIVATE_KEY_HERE # Signal Service URL SIGNAL_SERVICE_URL=http://localhost:8001 # API Keys GROK_API_KEY=your_grok_api_key TWITTER_BEARER_TOKEN=your_twitter_bearer_token TWITTER_API_KEY=your_twitter_api_key TWITTER_API_SECRET=your_twitter_api_secret TWITTER_ACCESS_TOKEN=your_twitter_access_token TWITTER_ACCESS_TOKEN_SECRET=your_twitter_access_token_secret ``` -------------------------------- ### Initialize Oasis ROFL Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Initializes the Oasis ROFL (Remote Attestation) framework. This command sets up the necessary configuration for secure enclaves and trusted execution. ```bash oasis rofl init ``` -------------------------------- ### Initialize and Connect Signal Client (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt Initializes a signal client to retrieve trading predictions from the signal service with automatic fallback support. This Python script demonstrates connecting to the signal service, waiting for it to become healthy, fetching predictions with retry logic, and processing the trade decision if available. It includes cleanup of client resources. ```python import asyncio from wt3.clients.signal import SignalClient async def main(): # Initialize client with automatic service discovery client = SignalClient() # Wait for signal service to become healthy is_healthy = await client.wait_for_health(timeout=30) if not is_healthy: raise Exception("Signal service unavailable") # Get trading prediction with retry logic prediction = await client.get_prediction(max_retries=3) if prediction: trade_decision = prediction.get('trade_decision') if trade_decision: print(f"Action: {trade_decision['action']}") print(f"Coin: {trade_decision['coin']}") print(f"Direction: {trade_decision['direction']}") print(f"Confidence: {trade_decision['confidence']}") # Clean up await client.close() asyncio.run(main()) ``` -------------------------------- ### Execute Trading Cycle with WT3 Agent (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt This Python script demonstrates the execution of a complete trading cycle using the WT3Agent. It includes fetching trading signals, executing trades, and managing the trading state. The script also shows how to retrieve and display recent trading activities. Dependencies include 'wt3.__main__.WT3Agent' and 'wt3.core.orchestration.trading_cycle'. ```python import asyncio from wt3.__main__ import WT3Agent from wt3.core.orchestration.trading_cycle import trading_cycle async def main(): # Initialize trading agent agent = WT3Agent() # Execute single trading cycle # 1. Fetches signal from signal service # 2. Executes trade if decision is made # 3. Updates trading state with results await trading_cycle(agent) # Check recent activities activities = agent.trading_state.get_recent_activities(limit=5) for activity in activities: print(f"{activity['timestamp']}: {activity['coin']} - {activity['action']}") if 'current_price' in activity['data']: print(f" Price: ${activity['data']['current_price']:,.2f}") if 'position_size' in activity['data']: print(f" Position: {activity['data']['position_size']}") # Output: # 2024-01-15T14:30:00: BTC - executed # Price: $43,500.00 # Position: 0.05 # 2024-01-15T14:15:00: ETH - hold # Price: $2,300.00 # Position: 0.0 asyncio.run(main()) ``` -------------------------------- ### Load Environment Variables from .env File Source: https://context7.com/oasisprotocol/wt3/llms.txt This command loads environment variables from a '.env' file into the current shell session. It is essential for configuring the application with necessary API keys and settings. ```bash export $(cat .env | xargs) ``` -------------------------------- ### Create Oasis ROFL App Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Creates a new Oasis ROFL application. This step registers the application within the ROFL framework, preparing it for building and deployment. ```bash oasis rofl create ``` -------------------------------- ### Clone WT3 Repository Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Clones the WT3 project repository from GitHub and navigates into the project directory. This is the first step in setting up the local development environment. ```bash git clone https://github.com/oasisprotocol/wt3.git cd wt3 ``` -------------------------------- ### Build Oasis ROFL App Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Builds the Oasis ROFL application. This process compiles the application code and generates the necessary artifacts for deployment to a ROFL node. ```bash oasis rofl build ``` -------------------------------- ### Build WT3 Signal Service Docker Image Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Builds the Docker image for the WT3 signal service. This is part of the production deployment process, creating a containerized version of the signal generation component. ```bash docker build -t yourusername/wt3-signal:latest -f Dockerfile.signal . ``` -------------------------------- ### Build WT3 Docker Image Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Builds the Docker image for the main WT3 agent. This is part of the production deployment process, creating a containerized version of the application. ```bash docker build -t yourusername/wt3:latest . ``` -------------------------------- ### Run Complete WT3 System Main Agent (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt This Python script launches the complete WT3 autonomous trading agent, enabling all its features. It includes functionalities such as signal polling, trading recaps, social media monitoring, and PnL reporting. The script also handles graceful shutdown on interruption. It requires the 'wt3.__main__.main' function and standard Python logging. ```python import asyncio import logging from wt3.__main__ import main # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) # Run the complete WT3 agent # - Polls for signals every 15 seconds # - Posts hourly trading recaps # - Checks social media mentions every 30 minutes # - Posts daily/weekly/monthly PnL recaps # - Handles graceful shutdown on interruption if __name__ == "__main__": try: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) result = loop.run_until_complete(main()) loop.close() if result: print("WT3 agent completed successfully") else: print("WT3 agent completed with errors") except KeyboardInterrupt: print("WT3 agent interrupted by user") except Exception as e: print(f"Fatal error: {e}") ``` -------------------------------- ### Run Local WT3 Main Agent Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Runs the main WT3 agent for local development using uv. This agent executes trades on Hyperliquid, manages positions, and interacts with social media. ```bash uv run python -m src.wt3 ``` -------------------------------- ### Execute Trades with Multiple Stop Loss Levels (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt Demonstrates how to use the SignalExecutor to execute a trade with multiple stop-loss levels for partial position exits. This allows for dynamic risk management by closing parts of a position at different price points. Dependencies include core trading components like ExchangeClient, OrderManager, and MarketDataProvider. ```python import asyncio from wt3.core.trading.signal_execution import SignalExecutor from wt3.core.trading.exchange_client import ExchangeClient from wt3.core.trading.order_management import OrderManager from wt3.core.trading.market_data import MarketDataProvider async def main(): # Initialize components exchange_client = ExchangeClient() market_data = MarketDataProvider(exchange_client) order_manager = OrderManager(exchange_client, market_data) executor = SignalExecutor(exchange_client, order_manager) # Signal with multiple stop-loss levels signal = { 'timestamp': 1703001234, 'trade_decision': { 'action': 'buy', 'coin': 'ETH', 'strategy': { 'position_size_coin': 3.0, 'leverage': 3.0, 'stop_loss_levels': [2200.0, 2150.0, 2100.0], # Three levels 'signal_id': 'multi_stop_001' } } } # Execute with multiple stops # Position will be partially closed at each level: # 1.0 ETH at $2200, 1.0 ETH at $2150, 1.0 ETH at $2100 result = await executor.execute_trade_signal(signal) print(result) # Output: Opened long position in ETH: Successfully opened LONG position: 3.0 ETH (market order) with SL: $2200.00 # Note: Multiple stop-loss levels configured. Position will be partially closed at each level. asyncio.run(main()) ``` -------------------------------- ### Manage Hyperliquid Account and Positions (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt Provides functions to interact with the Hyperliquid exchange for querying account balances and current positions. It uses a HyperliquidClient initialized with private keys for authentication. The client supports fetching the total account balance and the specific position size for any given coin. ```python from signal_service_example.clients.hl_client import HyperliquidClient from signal_service_example.clients.rofl import get_keypair # Initialize client with secure key management private_key, public_address = get_keypair() client = HyperliquidClient(private_key) print(f"Trading with address: {public_address}") # Get account balance balance = client.get_account_balance() print(f"Account Balance: ${balance:,.2f}") # Output: Account Balance: $5,432.10 # Check position for specific coin btc_position = client.get_current_position('BTC') if btc_position > 0: print(f"BTC Position: LONG {btc_position}") elif btc_position < 0: print(f"BTC Position: SHORT {abs(btc_position)}") else: print("BTC Position: No position") # Output: BTC Position: LONG 0.05 # Check multiple positions coins = ['BTC', 'ETH', 'SOL'] for coin in coins: position = client.get_current_position(coin) if position != 0: direction = "LONG" if position > 0 else "SHORT" print(f"{coin}: {direction} {abs(position)}") ``` -------------------------------- ### Modify ROFL Client for Local Keypair Access Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Modifies the ROFL client's `get_keypair` function to retrieve the private key from the `PRIVATE_KEY` environment variable. This is required for local development to bypass TEE key management. ```python import os def get_keypair(key_id: str = WT3_TRADING_KEY): private_key = os.getenv("PRIVATE_KEY") if not private_key: raise ValueError("PRIVATE_KEY environment variable not set") account = Account.from_key(private_key) return private_key, account.address ``` -------------------------------- ### Update Oasis ROFL Deployment Source: https://github.com/oasisprotocol/wt3/blob/master/README.md Updates the Oasis ROFL deployment with the newly built application artifacts. This command ensures that the ROFL node is running the latest version of the application. ```bash oasis rofl update ``` -------------------------------- ### Monitor and Reply to Twitter Mentions with Social Client (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt This Python script uses the SocialClient to check for Twitter mentions within a specified time frame and generate automated replies. It also demonstrates how to run periodic tasks for continuous monitoring and handling whitelisted accounts. Dependencies include the 'wt3.clients.social' module. ```python import asyncio from wt3.clients.social import SocialClient async def main(): # Initialize social client client = SocialClient() # Check mentions from last hour mentions_processed = await client.check_and_reply_to_mentions(hours=1) print(f"Processed {mentions_processed} mentions") # Output: Processed 3 mentions # Run periodic social media tasks # Checks mentions every 10 minutes and handles whitelist accounts result = await client.run_periodic_tasks(hours=0.1667) print(f"Mentions processed: {result['mentions_processed']}") print(f"Execution time: {result['execution_time_seconds']}s") print(f"Completed at: {result['completed_at']}") # Output: # Mentions processed: 2 # Execution time: 4.2s # Completed at: 2024-01-15T14:30:00.123456 asyncio.run(main()) ``` -------------------------------- ### Generate Momentum Trading Signals (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt Generates trading signals using Relative Strength Index (RSI) and moving average indicators with automatic risk management. This Python code allows configuration of risk parameters like risk per trade, reward-risk ratio, maximum leverage, and minimum trade size. It then fetches a trading signal for a specified coin and prints the trade decision and current position details. ```python import asyncio from signal_service_example.core.momentum_strategy import MomentumStrategy async def main(): # Initialize strategy with default parameters strategy = MomentumStrategy() # Configure strategy parameters (optional) strategy.risk_per_trade = 0.02 # Risk 2% per trade strategy.reward_risk_ratio = 3.0 # Target 3:1 reward:risk strategy.max_leverage = 5.0 # Maximum 5x leverage strategy.min_trade_size_usd = 100.0 # Minimum $100 trade # Get signal for specific coin signal = await strategy.get_signal('ETH') # Process signal if signal['trade_decision']: decision = signal['trade_decision'] print(f"Trade Action: {decision['action']}") print(f"Direction: {decision['direction']}") print(f"Confidence: {decision['confidence']}") print(f"Position Size: {decision['strategy']['position_size_coin']} ETH") print(f"Leverage: {decision['strategy']['leverage']}x") print(f"Stop Loss: ${decision['strategy']['stop_loss']}") print(f"Take Profit: ${decision['strategy']['take_profit']}") # Check current position if signal['current_position']: position = signal['current_position'] print(f"Current Position: {position['direction']} {position['size']}") asyncio.run(main()) ``` -------------------------------- ### Post Hourly Trading Recap to Twitter (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt Enables the generation and posting of AI-powered hourly trading recaps to Twitter. The SocialClient, initialized with API credentials from environment variables, formats trading data including positions, recent activities, and market session information into a tweet. It returns a success status and the tweet ID or an error message. ```python import asyncio from wt3.clients.social import SocialClient async def main(): # Initialize social client with API credentials from environment client = SocialClient() # Prepare recap data summary_data = { 'positions': [ { 'coin': 'BTC', 'direction': 'LONG', 'size': 0.05, 'entry_price': 43000.0, 'price': 43500.0, 'unrealized_pnl': 25.0 } ], 'recent_activities': [ {'coin': 'BTC', 'action': 'open_order_placed'}, {'coin': 'ETH', 'action': 'hold'} ], 'market_session': 'US', 'total_value': 2175.0 } # Generate and post recap result = await client.post_hourly_recap(summary_data) if result['success']: print(f"Posted recap: {result['result']}") # Output: Successfully posted tweet with ID: 1234567890123456789 else: print(f"Error: {result['error']}") asyncio.run(main()) ``` -------------------------------- ### Open Trading Position with Stop Loss (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt Opens a trading position (long or short) for a specified cryptocurrency with an automatic stop-loss order. This function requires initialized `ExchangeClient`, `MarketDataProvider`, and `OrderManager`. It takes the coin symbol, position direction (long/short), size, and stop-loss price as input, returning the execution result. ```python import asyncio from wt3.core.trading.order_management import OrderManager from wt3.core.trading.exchange_client import ExchangeClient from wt3.core.trading.market_data import MarketDataProvider async def main(): # Initialize components exchange_client = ExchangeClient() market_data = MarketDataProvider(exchange_client) order_manager = OrderManager(exchange_client, market_data) # Open long position with stop loss result = await order_manager.open_position( coin='BTC', is_long=True, size=0.05, # 0.05 BTC stop_loss=42000.0 # Stop loss at $42,000 ) print(result) # Output: Successfully opened LONG position: 0.05 BTC (market order) with SL: $42000.00 # Open short position result = await order_manager.open_position( coin='ETH', is_long=False, size=1.5, # 1.5 ETH stop_loss=2100.0 # Stop loss at $2,100 ) print(result) # Output: Successfully opened SHORT position: 1.5 ETH (market order) with SL: $2100.00 asyncio.run(main()) ``` -------------------------------- ### Execute Trade Signal (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt Executes trading signals received from an external service, handling both opening and closing of positions. This function requires initialized `ExchangeClient`, `OrderManager`, `MarketDataProvider`, and `SignalExecutor`. It processes a signal dictionary containing trade decisions and strategy details, returning the result of the executed trade. ```python import asyncio from wt3.core.trading.signal_execution import SignalExecutor from wt3.core.trading.exchange_client import ExchangeClient from wt3.core.trading.order_management import OrderManager from wt3.core.trading.market_data import MarketDataProvider async def main(): # Initialize components exchange_client = ExchangeClient() market_data = MarketDataProvider(exchange_client) order_manager = OrderManager(exchange_client, market_data) executor = SignalExecutor(exchange_client, order_manager) # Example signal from signal service signal = { 'timestamp': 1703001234, 'trade_decision': { 'action': 'buy', 'coin': 'BTC', 'strategy': { 'position_size_coin': 0.1, 'leverage': 2.5, 'stop_loss': 42000.0, 'signal_id': 'momentum_2024_001' } } } # Execute trade signal result = await executor.execute_trade_signal(signal) print(result) # Output: Opened long position in BTC: Successfully opened LONG position: 0.1 BTC (market order) with SL: $42000.00 # Execute close signal close_signal = { 'timestamp': 1703002000, 'trade_decision': { 'action': 'close', 'coin': 'BTC', 'strategy': {} } } result = await executor.execute_trade_signal(close_signal) print(result) # Output: Closed position in BTC: Successfully closed LONG position: 0.1 BTC (MARKET order) asyncio.run(main()) ``` -------------------------------- ### Signal Service Endpoints Source: https://github.com/oasisprotocol/wt3/blob/master/README.md This section details the API endpoints for the Signal Service, including a health check and an endpoint to retrieve trading signals. ```APIDOC ## GET /health ### Description Returns the current status of the Signal Service. ### Method GET ### Endpoint /health ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The current status of the service. #### Response Example ```json { "status": "ok" } ``` ``` ```APIDOC ## GET /signal ### Description Retrieves a trading signal for a specified cryptocurrency. ### Method GET ### Endpoint /signal ### Parameters #### Query Parameters - **cryptocurrency** (string) - Required - The cryptocurrency for which to retrieve the trading signal (e.g., BTC). ### Request Example None (GET request, parameters are in the URL) ### Response #### Success Response (200) - **timestamp** (integer) - The Unix timestamp of the signal. - **trade_decision** (object) - Details about the trading decision. - **action** (string) - The trading action (e.g., "open"). - **direction** (string) - The direction of the trade (e.g., "long"). - **confidence** (float) - The confidence level of the decision. - **coin** (string) - The cryptocurrency symbol. - **strategy** (object) - Details of the trading strategy. - **position_size_coin** (float) - The size of the position in coin units. - **leverage** (float) - The leverage applied to the trade. - **stop_loss** (float) - The stop-loss price. - **take_profit** (float) - The take-profit price. - **current_position** (object) - Details about the current open position. - **size** (float) - The current size of the position. - **direction** (string) - The current direction of the position. - **entry_price** (float) - The entry price of the current position. #### Response Example ```json { "timestamp": 1234567890, "trade_decision": { "action": "open", "direction": "long", "confidence": 0.85, "coin": "BTC", "strategy": { "position_size_coin": 0.1, "leverage": 2.0, "stop_loss": 50000.0, "take_profit": 55000.0 } }, "current_position": { "size": 0.1, "direction": "LONG", "entry_price": 50000.0 } } ``` ``` -------------------------------- ### Close Trading Position (Python) Source: https://context7.com/oasisprotocol/wt3/llms.txt Closes an existing open trading position for a specified cryptocurrency using a market order for immediate execution. It can also cancel all pending orders for a coin before closing and has functionality to close all open positions across all coins. Requires initialized `ExchangeClient`, `MarketDataProvider`, and `OrderManager`. ```python import asyncio from wt3.core.trading.order_management import OrderManager from wt3.core.trading.exchange_client import ExchangeClient from wt3.core.trading.market_data import MarketDataProvider async def main(): # Initialize components exchange_client = ExchangeClient() market_data = MarketDataProvider(exchange_client) order_manager = OrderManager(exchange_client, market_data) # Close position for specific coin result = await order_manager.close_position('BTC') print(result) # Output: Successfully closed LONG position: 0.05 BTC (MARKET order) # Cancel all orders before closing cancel_result = await order_manager.cancel_all_orders('ETH') print(cancel_result) # Output: Successfully cancelled 2 orders for ETH # Close all positions across all coins result = await order_manager.close_all_positions() print(result) # Output: Closed 3 positions asyncio.run(main()) ``` -------------------------------- ### Check Signal Service Health (Bash) Source: https://context7.com/oasisprotocol/wt3/llms.txt Verifies if the signal service is operational and ready to provide trading signals. This is a basic health check endpoint typically used for monitoring service availability. It expects a 'healthy' status in the JSON response. ```bash curl -X GET http://localhost:8001/health # Response { "status": "healthy" } ``` -------------------------------- ### Signal Service - Health Check Source: https://context7.com/oasisprotocol/wt3/llms.txt Checks if the signal service is operational and ready to provide trading signals. This endpoint is essential for monitoring the service's availability. ```APIDOC ## GET /health ### Description Checks if the signal service is operational and ready to provide trading signals. ### Method GET ### Endpoint `/health` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Indicates the health status of the service (e.g., "healthy"). #### Response Example ```json { "status": "healthy" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.