### Running Full Example Script - Bash Source: https://github.com/clensh/capital-library/blob/main/README.md This command executes the comprehensive example script library.py, which is located in the CapitalA subfolder, from the project's root directory in the terminal. This is the standard way to run the provided full example. ```Bash python CapitalA/library.py ``` -------------------------------- ### Installing Dependencies for Capital.com API Client (Bash) Source: https://github.com/clensh/capital-library/blob/main/README.md This command installs the necessary Python packages, `requests` and `websocket-client`, which are required dependencies for the Capital.com API client library to handle HTTP requests and WebSocket communication respectively. ```bash pip install requests websocket-client ``` -------------------------------- ### Switching Active Trading Account - Python Source: https://github.com/clensh/capital-library/blob/main/README.md This snippet provides an example of how to programmatically switch the active trading account if multiple accounts are available, using the `switch_account` method. It's commented out, indicating it's for illustrative purposes. ```Python # To switch the active account if multiple exist: # if len(accounts) > 1: # if client.switch_account(accounts[1]['accountId']): ``` -------------------------------- ### Retrieving Historical Market Data with CapitalA (Python) Source: https://github.com/clensh/capital-library/blob/main/README.md This example illustrates how to fetch historical price data for a given EPIC and resolution using the CapitalA library. It retrieves a specified number of data points and then iterates through them to print snapshot time and open bid price. ```Python from CapitalA import HistoricalPriceResolution example_epic = "IX.D.SPTRD.CFD.IP" prices_data = client.get_historical_prices( epic=example_epic, resolution=HistoricalPriceResolution.HOUR_4, num_points=50 ) if prices_data and prices_data.get("prices"): for candle in prices_data["prices"]: print(f"Time: {candle['snapshotTimeUTC']}, Open Bid: {candle['openPrice']['bid']}") else: print(f"Could not fetch historical prices for {example_epic}") ``` -------------------------------- ### Opening Trades with CapitalA (Python) Source: https://github.com/clensh/capital-library/blob/main/README.md This snippet demonstrates how to open a trade using the CapitalA library. It shows how to define an EPIC, trade size, and set stop and profit distances. It also includes commented-out code for calculating trade size based on margin and hints at managing positions after opening. ```Python from CapitalA import TradeDirection example_epic = "IX.D.EURUSD.CFD.IP" trade_size = 0.01 try: # You can calculate trade size based on desired margin: # calculated_size = client.calculate_trade_size_for_margin( # epic=example_epic, # margin_amount_in_quote_currency=20.0, # direction=TradeDirection.BUY # ) # if calculated_size > 0: # trade_size = calculated_size # else: # print(f"Could not calculate valid trade size for {example_epic}.") open_response = client.open_trade( epic=example_epic, direction=TradeDirection.BUY, size=trade_size, stop_distance=15, profit_distance=30 ) if open_response and open_response.get("dealReference"): deal_ref = open_response["dealReference"] print(f"Trade opened with reference: {deal_ref}") # To manage the position (update/close), you'll need its 'dealId'. # This is typically found by fetching open positions after opening the trade. # Example (simplified): # import time # time.sleep(2) # positions = client.get_open_positions() # my_deal_id = None # for p in positions: # if p.get("position",{}).get("epic") == example_epic: # my_deal_id = p.get("position",{}).get("dealId") # break # if my_deal_id: # client.update_trade(deal_id=my_deal_id, stop_level=new_stop_price) # client.close_trade(deal_id=my_deal_id) else: print(f"Failed to open trade: {open_response}") except CapitalComAPIError as e: print(f"Trading Error: {e}") ``` -------------------------------- ### Initializing CapitalComAPI Client and Performing Basic Operations - Python Source: https://github.com/clensh/capital-library/blob/main/README.md This snippet demonstrates how to initialize the CapitalComAPI client using environment variables for credentials, log in, retrieve the current account balance, and fetch market details for a specific instrument. It includes error handling for API-specific and general exceptions. ```Python import os from CapitalA import CapitalComAPI, Environment, TradeDirection, CapitalComAPIError API_KEY = os.environ.get("CAPITALCOM_API_KEY") IDENTIFIER = os.environ.get("CAPITALCOM_IDENTIFIER") PASSWORD = os.environ.get("CAPITALCOM_PASSWORD") ENVIRONMENT_TO_USE = Environment.DEMO if not all([API_KEY, IDENTIFIER, PASSWORD]): print("Error: Please set CAPITALCOM_API_KEY, CAPITALCOM_IDENTIFIER, and CAPITALCOM_PASSWORD environment variables.") exit() try: with CapitalComAPI(api_key=API_KEY, identifier=IDENTIFIER, password=PASSWORD, environment=ENVIRONMENT_TO_USE) as client: print(f"Successfully logged in to {client.environment.value} environment.") print(f"Active Account ID: {client.active_account_id}") balance = client.get_balance() print(f"Current Balance: {balance}") example_epic = "IX.D.EURUSD.CFD.IP" market_info = client.get_market_details(epic=example_epic) if market_info: print(f"Market: {market_info.get('instrument', {}).get('name')}") print(f"Current Offer Price: {market_info.get('snapshot', {}).get('offer')}") else: print(f"Could not retrieve market info for {example_epic}") except CapitalComAPIError as e: print(f"API Error: {e.message} (Status: {e.status_code}, Response: {e.response_data})") except Exception as e: print(f"An unexpected error occurred: {e}") print("Program finished.") ``` -------------------------------- ### Listing All Available Accounts - Python Source: https://github.com/clensh/capital-library/blob/main/README.md This snippet illustrates how to retrieve a list of all associated trading accounts using `client.get_accounts()` and then iterates through them to print each account's ID and status. ```Python accounts = client.get_accounts() for acc in accounts: print(f"Account ID: {acc['accountId']}, Status: {acc['status']}") ``` -------------------------------- ### Subscribing to Real-time Market Data via WebSockets (Python) Source: https://github.com/clensh/capital-library/blob/main/README.md This snippet shows how to subscribe to real-time market updates (quotes and OHLC bars) using CapitalA's WebSocket functionality. It defines callback functions to process incoming data and demonstrates how to subscribe to different data types and resolutions. The script then waits for a period to receive updates. ```Python from CapitalA import WebsocketDataType, HistoricalPriceResolution, OhlcBarType import time def my_market_update_handler(data: dict): print(f"MARKET Update for {data.get('epic')}: Bid={data.get('bid')}, Ask={data.get('offer')}") def my_ohlc_update_handler(data: dict): print(f"OHLC Update for {data.get('epic')} ({data.get('resolution')}): O={data.get('openPrice')}, C={data.get('closePrice')}") market_epic = "IX.D.EURUSD.CFD.IP" ohlc_epic = "IX.D.DAX.IFD.IP" client.subscribe_to_epic_data( epic=market_epic, data_type=WebsocketDataType.MARKET, callback=my_market_update_handler ) client.subscribe_to_epic_data( epic=ohlc_epic, data_type=WebsocketDataType.OHLC, callback=my_ohlc_update_handler, resolution=HistoricalPriceResolution.MINUTE_5, bar_type=OhlcBarType.CLASSIC ) print("Subscribed to WebSocket streams. Waiting for updates for 30 seconds...") time.sleep(30) # Keep the main script alive to receive messages # Unsubscribing (logout/context exit also stops WebSockets): # client.unsubscribe_from_epic_data(epic=market_epic, data_type=WebsocketDataType.MARKET) ``` -------------------------------- ### Retrieving Active Account Details - Python Source: https://github.com/clensh/capital-library/blob/main/README.md This snippet shows how to fetch and display details of the currently active trading account, specifically its currency, using the `get_active_account_details` method. It includes a check to ensure details were successfully retrieved. ```Python details = client.get_active_account_details() if details: print(f"Account Currency: {details.get('currency')}") ``` -------------------------------- ### Manually Authenticating CapitalComAPI Client - Python Source: https://github.com/clensh/capital-library/blob/main/README.md This snippet demonstrates how to manually log in and out of the CapitalComAPI client, providing an alternative to the context manager for authentication control. It checks for successful login before proceeding with operations and ensures a clean logout. ```Python client = CapitalComAPI(api_key=API_KEY, identifier=IDENTIFIER, password=PASSWORD, environment=Environment.DEMO) if client.login(): print("Login successful manually.") # ... perform operations ... client.logout() else: print("Login failed.") ``` -------------------------------- ### Handling API and Network Errors - Python Source: https://github.com/clensh/capital-library/blob/main/README.md This code illustrates robust error handling for API calls. It catches CapitalComAPIError for API-specific issues, providing details like message, status code, and response data, and requests.exceptions.RequestException for network-related problems, ensuring application resilience. ```Python import requests # Import for requests.exceptions try: client.get_balance() except CapitalComAPIError as e: print(f"API Error occurred: {e.message}") print(f"Status Code: {e.status_code}") print(f"Response Data: {e.response_data}") except requests.exceptions.RequestException as e: print(f"Network error: {e}") ``` -------------------------------- ### Stopping All WebSocket Subscriptions - Python Source: https://github.com/clensh/capital-library/blob/main/README.md This snippet demonstrates how to stop all active WebSocket subscriptions using the client.stop_all_websocket_subscriptions() method and confirms the completion of updates. It's typically used to gracefully shut down WebSocket connections. ```Python client.stop_all_websocket_subscriptions() # To stop all active subscriptions print("Finished receiving WebSocket updates.") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.