### Login and Setup for FXCM Gateway Source: https://github.com/fxcm/javaapi/blob/master/README.md Initializes the FXCM gateway, registers message listeners, and logs in using provided credentials. Ensure you have a valid FXCM account and the necessary login properties. ```java private void setup(IGenericMessageListener aGenericListener, boolean aPrintStatus) { try { // step 1: get an instance of IGateway from the GatewayFactory if (mFxcmGateway == null) { mFxcmGateway = GatewayFactory.createGateway(); } /* step 2: register a generic message listener with the gateway, this listener in particular gets all messages that are related to the trading platform Quote,OrderSingle,ExecutionReport, etc... */ mFxcmGateway.registerGenericMessageListener(aGenericListener); mStatusListener = new DefaultStatusListener(aPrintStatus); mFxcmGateway.registerStatusMessageListener(mStatusListener); if (!mFxcmGateway.isConnected()) { System.out.println("client: login"); FXCMLoginProperties properties = new FXCMLoginProperties(mUsername, mPassword, mStation, mServer, mConfigFile); /* step 3: call login on the gateway, this method takes an instance of FXCMLoginProperties which takes 4 parameters: username,password,terminal and server or path to a Hosts.xml file which it uses for resolving servers. As soon as the login method executes your listeners begin receiving asynch messages from the FXCM servers. */ mFxcmGateway.login(properties); } //after login you must retrieve your trading session status and get accounts to receive messages mFxcmGateway.requestTradingSessionStatus(); mAccountMassID = mFxcmGateway.requestAccounts(); } catch (Exception e) { e.printStackTrace(); } } ``` -------------------------------- ### Get Rollover/Swap Rates Source: https://context7.com/fxcm/javaapi/llms.txt Retrieves the current rollover (swap) rates for holding positions overnight. The rates are provided per BASE_UNIT_SIZE, typically 10k. ```java public void getRolloverRates(TradingSecurity tradingSecurity) { try { // Get rollover rates from TradingSecurity object double buyInterest = tradingSecurity.getFXCMSymInterestBuy(); double sellInterest = tradingSecurity.getFXCMSymInterestSell(); // Interest is per BASE_UNIT_SIZE (typically 10k) System.out.println("Rollover for long positions: $" + buyInterest + " per 10k"); System.out.println("Rollover for short positions: $" + sellInterest + " per 10k"); // Example output: // getFXCMSymInterestBuy() = 0.12 -> you will receive $0.12 per 10k for long // getFXCMSymInterestSell() = -0.39 -> you will pay $0.39 per 10k for short // Get the base unit size from server parameters // FXCMParamValue where FXCMParamName = "BASE_UNIT_SIZE" } catch (Exception e) { System.err.println("Error getting rollover rates: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Retrieve Rollover Interest Rates Source: https://github.com/fxcm/javaapi/blob/master/README.md Demonstrates how to get the current rollover interest rates for a symbol for both long (buy) and short (sell) positions using TradingSecurity class functions. ```java getFXCMSymInterestBuy() = 0.12 you will get $0.12 for 10k getFXCMSymInterestSell() = -0.39 you will pay $0.39 for 10k the 10k in this example is the server default base unit size, it can be found with FXCMParamValue where FXCMParamName = “BASE_UNIT_SIZE” ``` -------------------------------- ### Run QATest Application - Create Market Order Source: https://context7.com/fxcm/javaapi/llms.txt Execute the QATest application with command-line arguments to create a market order. This demonstrates the order placement functionality. ```bash java QATest myusername mypassword Demo http://www.fxcorporate.com/Hosts.jsp CMO ``` -------------------------------- ### Run QATest Application - Listen for Market Messages Source: https://context7.com/fxcm/javaapi/llms.txt Execute the QATest application with specific command-line arguments to listen for market data messages from FXCM servers. Ensure all required parameters are provided. ```bash java QATest myusername mypassword Demo http://www.fxcorporate.com/Hosts.jsp LISTEN ``` -------------------------------- ### Run QATest Application - Retrieve Market Data History Source: https://context7.com/fxcm/javaapi/llms.txt Execute the QATest application with command-line arguments to retrieve historical market data. This is useful for backtesting and analysis. ```bash java QATest myusername mypassword Demo http://www.fxcorporate.com/Hosts.jsp MDH ``` -------------------------------- ### Initialize FXCM Gateway and Login Source: https://context7.com/fxcm/javaapi/llms.txt Initializes the FXCM gateway, registers listeners for trading messages and status updates, and logs into the FXCM trading platform. Ensure your login credentials and server details are correctly configured. ```java import com.fxcm.fix.pretrade.*; import com.fxcm.fix.trade.*; import com.fxcm.external.api.transport.*; import com.fxcm.external.api.util.*; public class FXCMTradingClient { private IGateway mFxcmGateway; private IStatusMessageListener mStatusListener; private String mAccountMassID; // Login credentials private String mUsername = "your_trading_station_username"; private String mPassword = "your_trading_station_password"; private String mStation = "Demo"; // "Demo" or "Real" private String mServer = "http://www.fxcorporate.com/Hosts.jsp"; private String mConfigFile = null; private void setup(IGenericMessageListener aGenericListener, boolean aPrintStatus) { try { // Step 1: Get an instance of IGateway from the GatewayFactory if (mFxcmGateway == null) { mFxcmGateway = GatewayFactory.createGateway(); } // Step 2: Register a generic message listener with the gateway // This listener receives all trading platform messages (Quote, OrderSingle, ExecutionReport, etc.) mFxcmGateway.registerGenericMessageListener(aGenericListener); mStatusListener = new DefaultStatusListener(aPrintStatus); mFxcmGateway.registerStatusMessageListener(mStatusListener); if (!mFxcmGateway.isConnected()) { System.out.println("client: login"); FXCMLoginProperties properties = new FXCMLoginProperties( mUsername, mPassword, mStation, mServer, mConfigFile ); // Step 3: Call login on the gateway // As soon as login executes, listeners begin receiving async messages from FXCM servers mFxcmGateway.login(properties); } // After login, retrieve trading session status and accounts to receive messages mFxcmGateway.requestTradingSessionStatus(); mAccountMassID = mFxcmGateway.requestAccounts(); System.out.println("Successfully connected. Account Mass ID: " + mAccountMassID); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### QATest Available Test Commands Source: https://context7.com/fxcm/javaapi/llms.txt Lists the available test commands that can be used with the QATest application to perform various trading operations and data retrieval tasks. ```bash # Available test commands: # LISTEN - Listen for messages without taking action # CMO - Create market order # SSLMO - Set stop/limit on open position # USLMO - Update stop/limit price on position # DSLMO - Delete stop/limit from position # CEO - Create entry order # SSLEO - Set stop/limit on entry order # USLEO - Update stop/limit on entry order # DSLEO - Remove stop/limit on entry order # DEO - Remove entry order # CLOSEMO - Close position # UREO - Update rate on entry order # MDH - Retrieve market data history # RECONNECT - Reconnect the session ``` -------------------------------- ### QATest Command Line Arguments Format Source: https://context7.com/fxcm/javaapi/llms.txt Defines the expected format for command-line arguments when running the QATest application, including login credentials, connection details, and the specific test command. ```bash # Command line arguments format: # java QATest ``` -------------------------------- ### Create Entry Order Source: https://context7.com/fxcm/javaapi/llms.txt Creates a pending entry order that will be executed when the market reaches a specified price level. ```APIDOC ## Create Entry Order (CEO) ### Description Creates a pending entry order that will be executed when the market reaches a specified price level. ### Method POST (Implied, as it sends messages to the gateway) ### Endpoint N/A (Method call within the Java API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Method parameters are used) - **accountID** (String) - Required - The trading account ID. - **symbol** (String) - Required - The currency pair (e.g., "EUR/USD"). - **amount** (double) - Required - The order amount. - **side** (String) - Required - The order side, either "BUY" or "SELL". - **entryPrice** (double) - Required - The price level at which the entry order should be placed. - **orderType** (String) - Required - The type of entry order, either "LIMIT" or "STOP". ### Request Example ```java createEntryOrder("12345678", "EUR/USD", 10000, "BUY", 1.0850, "LIMIT"); ``` ### Response #### Success Response (200) - **requestID** (String) - The unique identifier for the sent entry order request. #### Response Example ``` Entry order sent. Request ID: req_mno345 ``` #### Error Handling - **Exception** - Catches and prints any errors during the process. ``` -------------------------------- ### Set Stop/Limit on Entry Order (SSLEO) Source: https://context7.com/fxcm/javaapi/llms.txt Attaches stop-loss and take-profit orders to a pending entry order. These contingent orders become active only after the primary entry order is executed. Ensure `mFxcmGateway` is properly initialized. ```java public void setStopLimitOnEntryOrder(String entryOrderID, double stopPrice, double limitPrice) { try { // Attach contingent stop and limit to entry order OrderSingle contingentStop = MessageGenerator.generateContingentOrder( entryOrderID, // Entry order ID stopPrice, // Contingent stop price OrdTypeFactory.STOP // Contingent order type ); OrderSingle contingentLimit = MessageGenerator.generateContingentOrder( entryOrderID, // Entry order ID limitPrice, // Contingent limit price OrdTypeFactory.LIMIT // Contingent order type ); String stopRequestID = mFxcmGateway.sendMessage(contingentStop); String limitRequestID = mFxcmGateway.sendMessage(contingentLimit); System.out.println("Contingent stop set. Request ID: " + stopRequestID); System.out.println("Contingent limit set. Request ID: " + limitRequestID); } catch (Exception e) { System.err.println("Error setting entry order stop/limit: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Create Entry Order Source: https://context7.com/fxcm/javaapi/llms.txt Generates a pending entry order (limit or stop) that executes when the market reaches a specified price. Requires account, symbol, amount, side, entry price, and order type. ```java public void createEntryOrder(String accountID, String symbol, double amount, String side, double entryPrice, String orderType) { try { // Create entry order (limit or stop entry) OrderSingle entryOrder = MessageGenerator.generateEntryOrder( accountID, // Trading account ID amount, // Order amount SideFactory.SIDE_BUY.equals(side) ? SideFactory.BUY : SideFactory.SELL, symbol, // Currency pair entryPrice, // Entry price level orderType.equals("LIMIT") ? OrdTypeFactory.LIMIT : OrdTypeFactory.STOP, "" // Custom order ID (optional) ); // Optionally set Good Til Date (GTD) time-in-force // entryOrder.setTimeInForce(TimeInForceFactory.GOOD_TIL_DATE); // entryOrder.setExpireDate(new UTCDate(expirationDate)); String requestID = mFxcmGateway.sendMessage(entryOrder); System.out.println("Entry order sent. Request ID: " + requestID); } catch (Exception e) { System.err.println("Error creating entry order: " + e.getMessage()); e.printStackTrace(); } } // Usage example - Buy EUR/USD when price drops to 1.0850: // createEntryOrder("12345678", "EUR/USD", 10000, "BUY", 1.0850, "LIMIT"); ``` -------------------------------- ### Set Stop/Limit on Open Position Source: https://context7.com/fxcm/javaapi/llms.txt Attaches stop-loss and/or take-profit orders to an existing open position. Ensure the position ID and prices are valid. ```java public void setStopLimitOnPosition(String positionID, double stopPrice, double limitPrice) { try { // Create stop order for the position OrderSingle stopOrder = MessageGenerator.generateStopLimitOrder( positionID, // Position/Trade ID to attach stop/limit stopPrice, // Stop-loss price OrdTypeFactory.STOP, // Order type: STOP "STOP" // Custom identifier ); // Create limit (take-profit) order for the position OrderSingle limitOrder = MessageGenerator.generateStopLimitOrder( positionID, // Position/Trade ID to attach stop/limit limitPrice, // Take-profit price OrdTypeFactory.LIMIT, // Order type: LIMIT "LIMIT" // Custom identifier ); // Send both orders String stopRequestID = mFxcmGateway.sendMessage(stopOrder); String limitRequestID = mFxcmGateway.sendMessage(limitOrder); System.out.println("Stop order sent. Request ID: " + stopRequestID); System.out.println("Limit order sent. Request ID: " + limitRequestID); } catch (Exception e) { System.err.println("Error setting stop/limit: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Create FXCM Market Order Source: https://context7.com/fxcm/javaapi/llms.txt Creates and sends a market order to the FXCM trading platform. This order will be executed immediately at the best available price. Ensure the account ID, symbol, amount, and side are valid. ```java public void createMarketOrder(String accountID, String symbol, double amount, String side) { try { // Create a new market order OrderSingle orderSingle = MessageGenerator.generateMarketOrder( accountID, // Trading account ID amount, // Order amount (e.g., 10000 for 10k lot) SideFactory.SIDE_BUY.equals(side) ? SideFactory.BUY : SideFactory.SELL, symbol, // Currency pair (e.g., "EUR/USD") "" // Custom order ID (optional) ); // Send the order through the gateway String requestID = mFxcmGateway.sendMessage(orderSingle); System.out.println("Market order sent. Request ID: " + requestID); // The execution report will be received through the IGenericMessageListener } catch (Exception e) { System.err.println("Error creating market order: " + e.getMessage()); e.printStackTrace(); } } // Usage example: // createMarketOrder("12345678", "EUR/USD", 10000, "BUY"); ``` -------------------------------- ### Implement FXCM Message Listener Source: https://context7.com/fxcm/javaapi/llms.txt Implement the IGenericMessageListener interface to process asynchronous trading messages like price quotes, order executions, and position updates. Register this listener with the FXCM Gateway to receive real-time data. ```java public class TradingMessageListener implements IGenericMessageListener { @Override public void messageArrived(ITransportable message) { try { if (message instanceof MarketDataSnapshot) { // Handle price quote updates MarketDataSnapshot snapshot = (MarketDataSnapshot) message; System.out.println("Quote: " + snapshot.getInstrument() + " Bid: " + snapshot.getBidClose() + " Ask: " + snapshot.getAskClose()); } else if (message instanceof ExecutionReport) { // Handle order execution reports ExecutionReport report = (ExecutionReport) message; System.out.println("Execution Report: " + " OrderID: " + report.getOrderID() + " Status: " + report.getOrdStatus() + " Side: " + report.getSide() + " Price: " + report.getPrice()); } else if (message instanceof PositionReport) { // Handle position updates PositionReport posReport = (PositionReport) message; System.out.println("Position: " + " ID: " + posReport.getFXCMPosID() + " Symbol: " + posReport.getInstrument() + " PL: " + posReport.getFXCMPosGrossPL()); } else if (message instanceof CollateralReport) { // Handle account/collateral updates CollateralReport collateral = (CollateralReport) message; System.out.println("Account Equity: " + collateral.getEndCash()); } } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Close Position (CLOSEMO) Source: https://context7.com/fxcm/javaapi/llms.txt Closes an existing open position by creating an offsetting market order. This method requires details of the position to be closed, including its ID, account, symbol, and amount. The `mFxcmGateway` must be initialized. ```java public void closePosition(String positionID, String accountID, String symbol, double amount, String originalSide) { try { // To close a position, create an opposite market order String closeSide = SideFactory.SIDE_BUY.equals(originalSide) ? SideFactory.SIDE_SELL : SideFactory.SIDE_BUY; OrderSingle closeOrder = MessageGenerator.generateCloseMarketOrder( positionID, // Position ID to close accountID, // Trading account ID amount, // Amount to close SideFactory.SIDE_BUY.equals(closeSide) ? SideFactory.BUY : SideFactory.SELL, symbol, // Currency pair "" // Custom order ID (optional) ); String requestID = mFxcmGateway.sendMessage(closeOrder); System.out.println("Close position order sent. Request ID: " + requestID); } catch (Exception e) { System.err.println("Error closing position: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Update Entry Order Rate (UREO) Source: https://context7.com/fxcm/javaapi/llms.txt Modifies the entry price of an existing pending entry order. Use this method when the desired entry price for a pending order needs adjustment. The `mFxcmGateway` must be initialized. ```java public void updateEntryOrderRate(String entryOrderID, double newEntryPrice) { try { // Create replace request for entry order OrderCancelReplaceRequest replaceRequest = MessageGenerator.generateOrderReplaceRequest( entryOrderID, // Entry order ID to modify newEntryPrice, // New entry price 0 // Amount (0 to keep original) ); String requestID = mFxcmGateway.sendMessage(replaceRequest); System.out.println("Entry order rate update sent. Request ID: " + requestID); } catch (Exception e) { System.err.println("Error updating entry order rate: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Set Stop/Limit on Open Position Source: https://context7.com/fxcm/javaapi/llms.txt Sets stop-loss and/or take-profit (limit) orders on an existing open position to manage risk and lock in profits automatically. ```APIDOC ## Set Stop/Limit on Open Position (SSLMO) ### Description Sets stop-loss and/or take-profit (limit) orders on an existing open position to manage risk and lock in profits automatically. ### Method POST (Implied, as it sends messages to the gateway) ### Endpoint N/A (Method call within the Java API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Method parameters are used) - **positionID** (String) - Required - The unique identifier of the open position. - **stopPrice** (double) - Required - The price at which the stop-loss order should be triggered. - **limitPrice** (double) - Required - The price at which the take-profit (limit) order should be triggered. ### Request Example ```java setStopLimitOnPosition("pos123", 1.0800, 1.1000); ``` ### Response #### Success Response (200) - **requestID** (String) - The unique identifier for the sent order request. #### Response Example ``` Stop order sent. Request ID: req_abc123 Limit order sent. Request ID: req_def456 ``` #### Error Handling - **Exception** - Catches and prints any errors during the process. ``` -------------------------------- ### Session Reconnection Source: https://context7.com/fxcm/javaapi/llms.txt Handles reconnection to FXCM servers using existing login properties if the gateway is not connected. It also re-requests session status and accounts. ```java public void reconnectSession() { try { if (mFxcmGateway != null && !mFxcmGateway.isConnected()) { System.out.println("Attempting to reconnect..."); // Relogin with existing credentials FXCMLoginProperties properties = new FXCMLoginProperties( mUsername, mPassword, mStation, mServer, mConfigFile ); mFxcmGateway.login(properties); // Re-request session status and accounts after reconnection mFxcmGateway.requestTradingSessionStatus(); mAccountMassID = mFxcmGateway.requestAccounts(); System.out.println("Reconnection successful."); } } catch (Exception e) { System.err.println("Reconnection failed: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Delete Entry Order (DEO) Source: https://context7.com/fxcm/javaapi/llms.txt Cancels and removes a pending entry order from the system. This is used when an entry order is no longer desired. Ensure `mFxcmGateway` is initialized before calling. ```java public void deleteEntryOrder(String entryOrderID) { try { // Create cancel request for entry order OrderCancelRequest cancelRequest = MessageGenerator.generateOrderCancelRequest( entryOrderID // Entry order ID to cancel ); String requestID = mFxcmGateway.sendMessage(cancelRequest); System.out.println("Entry order deletion sent. Request ID: " + requestID); } catch (Exception e) { System.err.println("Error deleting entry order: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Retrieve Market Data History Source: https://context7.com/fxcm/javaapi/llms.txt Use this method to fetch historical candlestick data for a given symbol and timeframe. Ensure the date range and timeframe are correctly specified. ```java public void retrieveMarketDataHistory(String symbol, String timeframe, Date startDate, Date endDate) { try { // Create market data request MarketDataRequest mdRequest = new MarketDataRequest(); mdRequest.setMDReqID(mFxcmGateway.getNextRequestID()); mdRequest.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SNAPSHOT); mdRequest.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL); // Add instrument mdRequest.addRelatedSymbol( new TradingSessionID(symbol) // Currency pair ); // Set date range for historical data mdRequest.setFXCMStartDate(new UTCDate(startDate)); mdRequest.setFXCMEndDate(new UTCDate(endDate)); // Set timeframe (m1, m5, m15, m30, H1, H2, H4, D1, W1, M1) mdRequest.setFXCMTimingInterval( FXCMTimingIntervalFactory.getInstance(timeframe) ); String requestID = mFxcmGateway.sendMessage(mdRequest); System.out.println("Market data history request sent. Request ID: " + requestID); // Historical data will be received through the IGenericMessageListener } catch (Exception e) { System.err.println("Error retrieving market data: " + e.getMessage()); e.printStackTrace(); } } // Usage example - Get hourly EUR/USD data: // retrieveMarketDataHistory("EUR/USD", "H1", startDate, endDate); ``` -------------------------------- ### Update Stop/Limit Price Source: https://context7.com/fxcm/javaapi/llms.txt Updates the price of an existing stop-loss or take-profit order attached to an open position. ```APIDOC ## Update Stop/Limit Price (USLMO) ### Description Updates the price of an existing stop-loss or take-profit order attached to an open position. ### Method POST (Implied, as it sends messages to the gateway) ### Endpoint N/A (Method call within the Java API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Method parameters are used) - **orderID** (String) - Required - The unique identifier of the stop or limit order to modify. - **newPrice** (double) - Required - The new price for the stop or limit order. ### Request Example ```java updateStopLimitPrice("order789", 1.0950); ``` ### Response #### Success Response (200) - **requestID** (String) - The unique identifier for the sent order update request. #### Response Example ``` Stop/Limit update sent. Request ID: req_ghi789 ``` #### Error Handling - **Exception** - Catches and prints any errors during the process. ``` -------------------------------- ### Update Stop/Limit Price Source: https://context7.com/fxcm/javaapi/llms.txt Modifies the price of an existing stop-loss or take-profit order associated with an open position. Use order ID and the new price. ```java public void updateStopLimitPrice(String orderID, double newPrice) { try { // Create an order cancel/replace request to update the price OrderCancelReplaceRequest replaceRequest = MessageGenerator.generateOrderReplaceRequest( orderID, // Original order ID to modify newPrice, // New price for the stop or limit 0 // Amount (0 to keep original amount) ); String requestID = mFxcmGateway.sendMessage(replaceRequest); System.out.println("Stop/Limit update sent. Request ID: " + requestID); } catch (Exception e) { System.err.println("Error updating stop/limit: " + e.getMessage()); e.printStackTrace(); } } ``` -------------------------------- ### Delete Stop/Limit from Position Source: https://context7.com/fxcm/javaapi/llms.txt Removes an existing stop-loss or take-profit order from an open position. ```APIDOC ## Delete Stop/Limit from Position (DSLMO) ### Description Removes an existing stop-loss or take-profit order from an open position. ### Method POST (Implied, as it sends messages to the gateway) ### Endpoint N/A (Method call within the Java API) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Method parameters are used) - **orderID** (String) - Required - The unique identifier of the stop or limit order to delete. ### Request Example ```java deleteStopLimit("order789"); ``` ### Response #### Success Response (200) - **requestID** (String) - The unique identifier for the sent order deletion request. #### Response Example ``` Stop/Limit deletion sent. Request ID: req_jkl012 ``` #### Error Handling - **Exception** - Catches and prints any errors during the process. ``` -------------------------------- ### Delete Stop/Limit from Position Source: https://context7.com/fxcm/javaapi/llms.txt Removes a stop-loss or take-profit order from an open position using its order ID. This action is irreversible. ```java public void deleteStopLimit(String orderID) { try { // Create an order cancel request OrderCancelRequest cancelRequest = MessageGenerator.generateOrderCancelRequest( orderID // Order ID of the stop or limit to delete ); String requestID = mFxcmGateway.sendMessage(cancelRequest); System.out.println("Stop/Limit deletion sent. Request ID: " + requestID); } catch (Exception e) { System.err.println("Error deleting stop/limit: " + e.getMessage()); e.printStackTrace(); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.