![]()
FX Trading Platform API Release 2·8
|
Document Version: |
2.8.2 |
|
Date of last revision: |
June 27, 2008 |
|
Date |
Change |
|
June 27, 2008
March 14, 2008
December 27, 2006 |
Note: Alphatoken can be multicharacter Page 9. Examples updated, referenced on Page 6
Added the Deal/Order BUP messages, Trading Enabled/Suspended messages, and Update Subscription message Pages 10-11.
Added new WebService Function reflecting the Subscription Model called ‘SaveUserProductSubscriptionSettings’ with more details for many of the functions Pages 12-16.
Added example code for SaveUserProductSubscripitionSettings Page 25.
Change to rates dictionary message on page 8-9 to include “Close” from prior day session for each pair. |
FX Trading Platform API Release 2·8.
What trading platforms are available?
Two business functions, two technologies
Trade requests and data - Web Services
Location of the Web Services API Server
For those unfamiliar with web services
Many clients have asked for a mechanism by which they can access the FX Trading Platform directly from their systems. With the release of the Rate Data Server and the Web Services interface, this is now available via a standards based XML interface.
The API exposed here is compatible with the GAIN Capital Group of companies and branding partners.
The GAIN Capital Group of companies includes:
· GAIN Capital
· FOREX.com
Please check with your FCM to confirm availability of this interface to their platform.
This API is provided by GAIN Capital as a free to use service and as such is open to all programmers from novice to seasoned professional. In order for this service to remain free it is important to remember that the servers here at GAIN are not an inexhaustible source of computing power… though close, and we ask that you respect them and make use of them in a fashion that you would expect others to use your resources. We ultimately must reserve the right to revoke access to the API from users that we consider to be abusing the service. Such abuse might be:
· Re-transmitting GAIN derived Rates for any purpose other than to facilitate the execution of trades through GAIN Capital without the express permission of GAIN Capital
· Repeatedly calling functions in an unending and unreasonable loop
· Polling the GetRatesDataSet function when streaming rates are available
· Loading our order processing system with huge volumes of orders that are not expected to be met
· Ignoring error messages and continuing to trade when your account has either run out of funds or has been locked out
· Repeating to connect to Rates Service without sending a valid key
· Excessive parallel calls to the service
· Re-transmitting our rates to other parties
· Anything else that we simply don’t like the look of
The provision of this service is intended to help you trade with us and we will of course take all reasonable steps to ensure high availability of the API.
Use of the service accepts these rules.
|
Current API Version |
|
|
Changes |
|
|
Example code |
|
|
This Document in MS Word format |
The provision of the service is divided into two distinct technologies, each suitable for the business function that is asked of it.
Rate data represents the tradable prices published to the client. They can be categorized as ‘Real Time’ meaning that they are changing in real-time and need to be pushed out to the client. For this role we use a direct TCP/IP socket interface to the price publication system. The same socket is used by our trading client. To assist with programming in Visual Studio.NET and JAVA we provide native components that handle the connection and link management. Each component creates events through delegates or call backs as appropriate.
The trading functions are initiated by the client in the form of a request. This logic is implemented using Web Services; an XML based SOAP interface.
The rate data interface is implemented as a TCP/IP socket connection. The client connects to the interface and following a sign-on handshake will receive a stream of market rates as and when they are updated.
The Programming interface is provided via components written for the .NET Framework (one in VB.NET and one in C#) and for the JAVA 1.2 environments. The documentation for the interface for those components is provided within the examples sub-folder (See ‘Links to associated documents’ on page 6).
For those programmers looking to interface directly with the rate data feed, the following describes the message construct; please be aware that the rates interface is more susceptible to change than the abstracted API interface.
The data is transmitted in a proprietary format and therefore requires a full explanation of the protocol.
Note: Data sent by the client is in Green, data sent from the server is in Yellow
On connect:
Client sends initial logon key followed by [Carriage Return [cr]]:
{Key obtained from WebServices[1]}\COMPACT[cr]
Please note that the string \COMPACT is required to produce the correct output.
Server returns initial response ‘Dictionary message’, this is a message listing a token table for all CCY pairs and includes the High/Low prices for the pair since 5pm EST in the form:
SA\AUD/USD\Bid\Ask\High\Low\D\A\4\Close\$B\AUD/JPY\Bid\Ask\High\Low\A\2\Close\... …\N\USD/JPY\Bid\Ask\High\Low\E\2\Close\$
Where:
S=Message type SUR or ‘Dictionary’
A=first Alpha CCY token (Note: the Alpha token is not limited to be only one
character)
AUD/USD = first CCY pair which will hereon in be referred to as ‘A’
Bid\Ask\High\Low = Bid\Ask\High\Low values for the CCY pair
D=Status, Dealable or Referred
A=A for American, E for European
4=Decimals for the CCYPair (typically 2, 4, or 5)
Close=Close price from prior day’s session at 17:00 ET (New York) (12/27/2006
update)
$=delimiter
On rate change:
Periodically (typically no more than four times a second, the rates server will send out an updated rate message. It will send multiple rates but transmit them from the server as a single message ‘hit’ in the form:
RF\0.6530\0.6535\D…RN\119.09\119.14\D
Where:
R=Message type RATE
F=CCYPair, in this case EUR/GBP
Bid\Ask = Bid\Ask
D=Status, Dealable or Referred
Resend dictionary information request:
In the event that the client feels that it needs a fresh dictionary message with CCY and High/Low information;
Client sends:
S[cr]
Where:
S=Resend a SUR message.
On high/low reset or on server receipt of a ‘Resend Dictionary Message:
Server sends a fresh, complete dictionary message as per above.
Rates filter instruction:
For lightweight clients that wish to reduce bandwidth to the bare minimum, the client can optionally send a filter to prevent all rates from being sent; the filter will indicate which pair should be send. The choice is between all pairs or one specific pair, at this time it is not possible to build a group of filtered pairs:
Client sends:
FAUD/JPY[cr]
Where:
F=Message Type FILTER
AUD/JPY=CCY pair, in this case AUD/JPY
Or:
FALL/ALL[cr]
Where:
F=Message Type FILTER
ALL/ALL=all, i.e. filter off
Note: In the absence of the filter, all CCY’s will be sent.
Other Messages
There are other messages available through the Rates Socket feed that will act as notification.
Deal Messages
On execution of a deal on the back-end a deal message is sent. A deal message will be sent regardless of how the deal was entered.
BUP\DEAL\EUR/USD\300000\300000\57321.47\-90\3084\58807154\23211905\456560\1.52186667\
BUP\DEAL\PRODUCT\POSITIONCONTRACT\POSITIONCCY\POSTEDMARGIN\REALIZEDMARGININUSD\REALIZEDMARGININBASECCY\DEALREFERENCENUMBER\CONFIRMATIONNUMBER\POSITIONINUSD\POSITIONAVERAGERATE
Where:
BUP\DEAL=Message type Deal
Product=Currency Pair
Position Contract=Current Net Position in Pair
Position CCY=Please ignore this value
Posted Margin=Current Account Balance
Realized Margin in USD=Realized P/L since prior day’s close 17:00 ET (New York)
Realized Margin in Base CCY=Same as above only in base Currency
Deal Reference Number=Ref. Number
Confirmation Number=Conf. Number
Position in USD=Current Net Position in Pair (in USD)
Position Average Rate=Average Rate of Current Position
Use this event to trigger a request for a refresh to deal blotter, position blotter and margin blotter from the server.
Order Messages
On placement or modification of an order on the back-end an order message is sent. An order message will be sent regardless of how the order was entered or modified.
BUP\ORD\EUR/USD\58813100\PLACED\
BUP\ORD\PRODUCT\ORDERREFERENCE\ORDERSTATUS
Where:
BUP\ORD=Message type Order
Product=Currency Pair
Order Reference=Reference Number of Order
Order Status=Status of Order. The following values are valid:
a. PLACED
b. MODIFIED
c. CANCELLED
d. EXPIRED
e. DEALT
f. PENDING
g. FAILEDMARGIN
Use this event to trigger a request for a refresh to deal blotter, position blotter, margin blotter and order blotter from the server.
Trading Enabled/Disabled Messages
Messages are sent indicating when trading has been set to enabled or suspended. This typically happens each day around 17:00 ET when daily maintenance is performed. The maintenance typically lasts no more than a few minutes. The messages are sent as follows:
E\Trading Enabled\
E\Trading Suspended\
Rate Subscription
The Rate Updates were designed so that clients only see pairs which they have selected. Clients may choose to edit their selected pairs multiple times; there are no restrictions in place to limit the revisions. As a result, the front-end platforms need to respond when the settings are changed. Whenever a client updates their selection, a notification message is sent via the rate feed:
MSG\SUB\CHANGE\
The server will send a keep-alive ‘carriage-return’ character on a regular basis if rate-data is not sent. The client should send a return keep-alive character once a minute if it does not receive any data. This is to ensure that the socket connection is valid without swamping the rates server with keep-alive messages. Typically, the socket interface will throw a ‘reset by peer’ message if the socket fails to deliver the keep-alive. Additionally, if you, the client does not receive a message, send a keep-alive to test the link.
The rates server is located on IP port 443 at the following addresses:
Live trading accounts:
LiveRates.efxnow.com
Demo and test accounts:
DemoRates.efxnow.com
Rates servers are distributed across multiple data centers to provide high availability.
The remainder of the system functions are implemented as web service requests. The current list of supported requests is listed below, note, you may click on each link to access the demo version of the web services interface:
The following operations are supported. For a formal definition, please review the following operations are supported. For a formal definition, please review the Service Description.
·
PlaceOCOOrder
Place OCO1 trade order. This
function enables you to create an order in which one part of the order is
cancelled if the other part is executed. Pair as
GBP/USD, Expiry2 as EOD or GTC, BuySell as B or S, Amount as
multiple of 10,000 or 100,000 depending upon account, Order Basis as S or T for
Stop loss or LimiT. Warning: Trade Order can take up to 60 seconds to be placed
into the order process. Use DealRequest for immediate execution. To
place an OCO[2]
order associated with current open positions please refer to the
PlaceOCOASSPOrder function.
·
PlaceSingleOrder
Place single trade order. Allows you to create a simple order
to be executed in the future through which a position can be opened.
Pair as GBP/USD, Expiry2 as EOD or GTC, BuySell as B or
S, Amount as multiple of 10,000 or 100,000 depending upon account, Order Basis
as S or T for Stop loss or LimiT. Warning: Trade Order can take up to 60
seconds to be placed into the order process. Use DealRequest for immediate
execution. (See example on page 24)
·
ModifySingleOrder
Modify single trade order. This allows you to modify an order
which has already been created. “OrderReference” is a parameter that identifies
which particular order is to be modified and can be retrieved from many order
functions. The order functions return “CustomerOrderReference” which
corresponds to the “OrderReference” parameter. Expiry2
as EOD or GTC, BuySell as B or S, Amount as multiple of 10,000 or 100,000
depending upon account, Order Basis as S or T for Stop loss or LimiT. Warning:
Trade Order can take up to 60 seconds to be placed into the order process. Use
DealRequest for immediate execution.
·
GetPositionBlotter
User Position blotter. Returns the current open positions as
displayed in position management. The input, Key, can be retrieved from the
GetRatesServerAuth function.
·
GetTime
Returns the server time (UTC), can be used as a connection keep-alive if you so
wish. (See example on page 21)
·
GetSymbolBlotterDataSet
Symbol Blotter DataSet. Returns all the possible currency
pairs to trade in their respective currency symbols. The parameters are your UserID
and password.
·
GetEconomicCalendar
Economic Calendar
·
ModifySingleASSPOrder
Modify Single Associated Position2 Trade order. This
allows you to modify an associated position2
order which has already been created. “OrderReference” is a parameter to
identify which particular order is to be modified. “OrderReference” can be
retrieved when creating the order through the PlaceSingleASSOrder or the
PlaceSingleOrder function. “CustomerOrderReference”, returned from these
functions, can be used as the “OrderReference”. Pair as
GBP/USD, Order Basis as S or T for Stop loss or LimiT. Warning: Trade Order can
take up to 60 seconds to be placed into the order process. Use DealRequest for
immediate execution.
·
GetNewsDataSet
News DataSet
·
DealRequest
Place trade deal request. Here the function is intended to be
used when you wish to enter the market at a specified rate. If the specified
rate is the current market rate the request is processed else it will get
rejected (in other words, a fill or kill scenario). Pair as
GBP/USD, BuySell as B or S, Amount as multiple of 10,000 or 100,000 depending
upon account.
·
GetPositionBlotterDataSet
Position Blotter DataSet which relates to all the details for any current open
positions associated to the account.
·
GetDelayedRatesDataSet
Delayed Rates DataSet
·
GetDealBlotterWithFilter
User Deal blotter with Filter
·
PlaceIfThenOrder
Place If Then Trade order. The If/Then order is a conditional
order providing that if the first order ("If" order) is executed, the
second order ("Then" order) is activated as a live, single order. In
cases where the If order does not execute, the Then single order will remain
dormant. When either part of an If / Then order is cancelled, all parts of the
order are cancelled as well. Pair as GBP/USD, Expiry[3] as EOD or GTC, BuySell as B or S,
Amount as multiple of 10,000 or 100,000 depending upon account, Order Basis as
S or T for Stop loss or LimiT. Warning: Trade Order can take up to 60 seconds
to be placed into the order process. Use DealRequest for immediate execution.
·
GetOrderBlotterDataSet
Order Blotter DataSet which Returns any open
orders in the account.
·
GetOrderBlotter
User Order blotter
·
GetComment
GAIN Commentary. Returns top three GAIN Commentary items.
·
GetRatesDataSet
Rates Snapshot DataSet. Returns the rates and timestamps for
all the currency pairs. The required parameter is a ‘Key’ which can be
retrieved from the GetRatesServerAuth function.
·
GetMarginBlotterDataSet
Margin Blotter DataSet. Returns account specific balance
information such as Margin Balance, Account Balance, P/L, and more.
·
GetAccountServices
Account Services
·
GetRatesServerAuth
This
function is primarily to authenticate your account. Returns
the 'key' string valid for 24hrs used to authenticate with the Rates Server and
the blotter functions. This must be called prior to connecting with the rates server
or the blotters each day. Please contact Customer Service with any questions
regarding Brand Code. (See example on page 23)
·
GetDealBlotterDataSetWithFilter
Deal Blotter DataSet with filter
·
ModifyIfThenOCOOrder
Modify If Then OCO1 Trade order. Pair as GBP/USD, Expiry2
as EOD or GTC, BuySell as B or S, Amount as multiple of 10,000 or 100,000
depending upon account, Order Basis as S or T for Stop loss or LimiT. Warning:
Trade Order can take up to 60 seconds to be placed into the order process. Use
DealRequest for immediate execution.
·
GetNews
Market News. Returns top three News items.
·
Echo
Returns string that you sent as a literal and as a list of ASCII char codes.
Use this routine if you wish to test the WebService process or check
connectivity.
·
ModifyOCOOrder
Modify OCO1 trade order. Expiry2 as EOD or GTC, BuySell
as B or S, Amount as multiple of 10,000 or 100,000 depending upon account,
Order Basis as S or T for Stop loss or LimiT. Warning: Trade Order can take up
to 60 seconds to be placed into the order process. Use DealRequest for
immediate execution.
·
DealRequestByDealId
This
function is like the "point and shoot" option in position management
on the platform. It is used when multiple lots are in exposure for a specified
currency pair. You can choose which position you want to trade. This function
is not used when only one position is open. A DealID will be requested, which
is the ITID returned from the GetDealBlotter function. GetDealBlotter should be
called after you enter the position due to the DealBlotter being reset each day
at 5 pm EST. Place trade deal request by DealId as the ID of the deal that you
want to close, Pair as GBP/USD, BuySell as B or S, Amount as multiple of 10,000
or 100,000 depending upon account.
·
PlaceIfThenOCOOrder
If/Then
OCO[4]
order is a conditional order providing that if the first order ("If"
order) is executed, the second order ("Then" order) is activated as a
live, One Cancels Other (OCO) order. Full description of an OCO1
order. The execution of either one of the two 'Then' orders automatically
cancels the other. In cases where the 'If' single order does not execute, the
'Then' OCO1 order will remain dormant. When any part of an If / Then
OCO1 order is cancelled, including either leg of the OCO1
order, all parts of the order are cancelled as well. Place
If Then OCO1 Trade order. Pair as GBP/USD, Expiry2 as EOD
or GTC, BuySell as B or S, Amount as multiple of 10,000 or 100,000 depending
upon account, Order Basis as S or T for Stop loss or LimiT. Warning: Trade
Order can take up to 60 seconds to be placed into the order process. Use
DealRequest for immediate execution.
·
GetSubAccountAuthenticationKey
Returns the Sub Account 'Key' string valid for 24hrs used to authenticate with
the Rates Server and the blotter functions. This must be called prior to
connecting with the rates server or the blotters each day.
·
GetSymbolBlotter
List of traded symbols
·
CancelOrder
Cancel trade order. OrderConfirmation as reference number provided for original
order; note: in the case of an OCO1, both legs should be cancelled.
·
DealRequestAtBest
This
function is used to deal at market at the best rate available. he DealRequest
function may take longer to enter the market, especially in a fast moving
market if the deal is rejected. Place trade deal request with
Rate at Best. Pair as GBP/USD, BuySell as B or S, Amount as multiple of 10,000
or 100,000 depending upon account.
·
GetDealBlotterDataSet
Deal Blotter DataSet
·
GetAccount
Account parameters
·
ModifyOCOASSPOrder
Modify OCO[5]
Associated Position3 Trade order. Pair as GBP/USD. Warning: Trade
Order can take up to 60 seconds to be placed into the order process. Use
DealRequest for immediate execution.
·
GetMarginBlotter
User Margin blotter
·
GetHistoricRatesDataSet
DataSet of historic market rates up to 24 hours maximum. Quote is in the form
CCY/CCY i.e. GBP/USD. The required parameter is a Key, Quote,
StartDateTime, and EndDateTime. ‘Key’ can be retrieved from the
GetRatesServerAuth function. Quote is in the form CCY/CCY i.e. GBP/USD.
StartDateTime and EndDateTime is in the form YYYY-MM-DD HH:MM:SS i.e. 2006-08-16
11:03:25. (See example on page 21)
·
PlaceSingleASSPOrder
Place Single Associated Position3 Trade order. This
is an order to create the stop loss or limit to an open position. Pair as
GBP/USD, Order Basis as S or T for Stop loss or LimiT. Warning: Trade Order can
take up to 60 seconds to be placed into the order process. Use DealRequest for
immediate execution.
·
GetCommentDataSet
Comment DataSet
·
GetDealBlotter
User Deal blotter
·
PlaceOCOASSPOrder
Place OCO[6]
Associated Position2 Trade order. Pair as GBP/USD. Warning: Trade
Order can take up to 60 seconds to be placed into the order process. Use
DealRequest for immediate execution.
·
SaveUserProductSubscriptionSettings
Updates the Subscribed Product List based on the comma separated Pairs listed
in SubscribedPairs String. (See example on page 25)
·
GetAccountObject
Account parameters. Notes field may be used to describe the client. Use 'GAIN'
as the default value for brand.
·
GetTicker
Ticker
·
ModifyIfThenOrder
Modify If Then Trade order. Pair as GBP/USD, Expiry as EOD or GTC, BuySell as B
or S, Amount as multiple of 10,000 or 100,000 depending upon account, Order
Basis as S or T for Stop loss or LimiT. Warning: Trade Order can take up to 60
seconds to be placed into the order process. Use DealRequest for immediate
execution.
·
CancelOrderByOrderID
Cancel trade Order. Please provide Order Reference Number for
the Reference Number. The Order Reference Number can be retrieved from
GetOrderBlotterDataSet. All the legs of the Order will be removed. Please
provide Order Reference Number for the Reference Number. All the legs of the
Order will get removed.
The full details of each of the requests can be found by inspecting each of the methods using a web browser at http://api.efxnow.com/DEMOWebServices2.8/Service.asmx
The web services are available in Demo and Live versions at the following addresses:
Live trading accounts:
https://api.efxnow.com/WebServices2.x/service.asmx
Demo and test accounts:
http://api.efxnow.com/DemoWebServices2.x/service.asmx
Web Services offer a mechanism by which programmers can perform remote procedure calls over the Internet in a language and platform agnostic manor using protocols such as Simple Object Access Protocol (SOAP). Web Services are not a Microsoft technology but a rapidly stabilizing global standard. For a quick introduction to web services we recommend the following article:
http://msdn.microsoft.com/webservices/webservices/understanding/
There is a wealth of information available on the Internet regarding using Web Services so we will not go into great detail here.
Web services revolve around IIS in our implementation and in their simplest form can be invoked using an http GET or POST method and the returning stream can be interpreted by parsing the output. To aid in development we have enabled the ‘test feature’ that allows you to test the web service response using a regular web browser at http://api.efxnow.com/DEMOWebServices2.8/Service.asmx. Here you can launch any of the requests to explore the responses. The self-documenting nature of web services ensures that the latest information is always available.
As the web services themselves are essentially self-documenting, there will not be a repeat of that documentation in these notes. However, there are a number of statements that should be made clear regarding our use of Web Services:
Supported protocols
Though Web Services are intended to be used with SOAP, we also intend to support the simple GET and POST methods of invocation; this opens the door to web services programming with little more than an http web request and a text parser.
Supported transports
For the purposes of testing against the demo servers we support http and https over IP ports 80 and 443 respectively though for production we will only support https over port 443. This is to ensure transport level data encryption.
Data returned
The data returned will comprise an XML encoded string, strings or an XML encoded representation of a dataset. Typically in the case of a data set there will be a single table contained within that set.
Session persistence
There is no concept of session state however; http keep-alive requests are allowed and recommended to maintain a fast and responsive connection, this is the default in VS.NET applications.
Programming environment
The nature of Web Services should permit a truly language and platform agnostic approach. However, as the SOAP protocol develops there are certain compatibility specific issues that will inevitably crop up as a result of Microsoft’s (or any vendor for that matter) interpretation of the SOAP specification. We recommend Microsoft Visual Studio .NET for its usability and productivity, especially with web services where most tasks can be represented in a single line of code. The examples given below are shown in Visual Basic .NET.
Versioning
The interface to Web Services is versioned through the url, i.e. the current release version is 2.8 hence the reference in the url, i.e. http://...Webservices2.8/service.asmx. As new versions are built the old version will remain operational for as long as is feasible. There is often no requirement to drop previous versions. However, we reserve the right to withdraw a version of the interface in the event that a flaw is found that could harm us or our customers.
Authentication
The web services calls will sometimes call for authentication in the form of a UserID, Password and Brand. The UserID and password are clear. However, the brand is a value that is specific to the account in question and is usually a function of the origin of the signup i.e. GAINCapital, FOREX.com, etc. The brand should be obtained by calling client services.
Example code – VB.NET
In the documentation pack you will find a compressed archive containing the sample code for the ‘ExampleClient’ project. The project is written using Visual Basic.NET but we are sure that C# and JAVA programmers will find the code sufficiently readable.
The project comprises a simple form ‘Form1’ with code behind in Form1.vb. Visually, the form is laid out as:

Also in the project is the auto-generated Web Services proxy code, this can be found in ‘Reference.vb’. The code is automatically generated and referenced by using the solution function ‘Add Web Reference’ (Right click on the project). Then, key in the URL to the web services file into the web reference wizard.

http://api.efxnow.com/DEMOWebServices2.8/Service.asmx . Once added, the URL property of the web reference can be changed and refreshed in the designer or in code.
Once the Web Reference has been created; the web services can be referred to using their default namespace ‘com.efxnow.api’. If this is name is considered unsuitable, it can be changed in the Web Reference properties.

In the code examples we could have chosen to Import the namespace into the designer to ease programming with the statement:
Imports ExampleClient.com.efxnow.api.Service
However, in the example we have created a class level object to represent the Web Reference:
Dim myWebService As New com.efxnow.secure.Service
From this point forward we can refer to the Web Services using the object.
The first example of using the web services is triggered when we start the application. In the Form_Load event we have added code to request the servers time and then display it on a label on the form. The code to complete that is:
Me.lblStatus.Text = "Connected, server time " & myWebService.GetTime & " (GMT)"
Here the .GetTime method is invoked as though the code were local to our machine. The returned data is in the form of a STRING object encoded in the XML response; with VS.NET we can simply pass the STRING object directly to the forms label object.
This function returns a dataset representing the market rates for a given CCY pair for a given time period. In the example the datasets’ first data table is passed to a data grid object for rendering.
'Verbose code example of Rate history:
'This code could be contracted to a single composite statement!
' Set up string variables in preparation for call:
Dim Key As String = "{the key obtained from GetRatesServerAuth}"
Dim Quote As String = Me.ComboBoxCCY.SelectedItem
' Set the start time to be 10 mins before NOW:
Dim StartDateTime As String = DateAdd(DateInterval.Second, -600, Now).ToShortDateString & " " & DateAdd(DateInterval.Second, -600, Now).ToLongTimeString
Dim EndDateTime As String = ""
'Create DataSet object as container for the result set
Dim myResponse As New DataSet
'Fill dataset:
myResponse = myWebService.GetHistoricRatesDataSet(Key, Quote, StartDateTime, EndDateTime)
'Bind the resulting DataSet table to a grid for display
Me.DataGridRates.DataSource = myResponse.Tables(0)
Note that the key is obtained from the function ‘GetRatesServerAuth’. Use this function to obtain a key from your account details.
Note also that the EndDateTime string is left blank; this will be interpreted as being NOW. In web service methods there is no concept of overloading therefore optional parameters must be passed in, i.e. there is no concept of optional parameters!
The returned dataset contains a single table and as this is a zero based array environment we can refer to it by the index 0.
We use the change event raised by the CCY combo box to trigger the request to GetHistoricRatesDataset, the result from this looks like:

Note that these rates are not streaming; the purpose of this call is to supply ‘backfill’ rates in the event that the live feed is interrupted or, it is decided by the client that live rates are not required. Be aware that the volume of data returned by this request can be vast!
In order to execute a trade there exists the DealRequest function. This function takes authentication information along with the trade request and submits this to the trading system for execution. Upon completion the client is returned a dataset containing a data table with a single row. The row contains the Reference field and the Message field.
The reference will be a positive numeric value representing the Deal Reference if the request is successful or false (-1) if not. The message contains a text description of the event, successful or not.
'Verbose code example of Trade Execution:
' Set up string variables in preparation for call:
Dim UserID As String = "myUserID"
Dim PWD As String = "myPassword"
Dim Pair As String = Me.ComboBoxCCY.SelectedItem
Dim BuySell As String = Me.ComboBoxBuySell.SelectedItem
Dim Amount As String = txtAmount.Text
Dim Rate As String = txtRate.Text
'Create DealResponse object as container for the result set
Dim myResponse As New com.efxnow.api.objDealResponse()
'Fill Return Object:
myResponse = myWebService.DealRequest(UserID, PWD, Pair, BuySell, Amount, Rate)
'Pull items back from Object:
Dim Message As String
If myResponse.Success Then
Message = myResponse.Confirmation
Else
Message = myResponse.ErrorDescription
End If
'Display Message
Me.txtResponse.Text = Message
Be aware that the request contains the user id and the password; this is transmitted over the Internet and, unless an SSL connection is used, it will be visible in clear text.
As mentioned previously in a footnote, one requirement that must be met to receive streaming rates is that a key must be sent to the rates server on initial connection. This key can be obtained following a call to the function GetRatesServerAuth.
'Verbose code example of GetRatesServerAuth:
' Set up string variables in preparation for call:
Dim UserID As String = "myUserID"
Dim PWD As String = "myPassword"
Dim BrandCode As String = "myBrandCode"
'Create String object as container for the result
Dim myResponse As String
'Get:
myResponse = myWebService.GetRatesServerAuth(UserID, PWD, BrandCode)
'Display Message
Me.txtResponse.Text = myResponse
The response can then be passed to the rates server to start a session.
The response is valid for a limited time therefore, it is recommended that a call to GetRatesServerAuth be made prior to each connection attempt to the rates server.
In order to execute an order, there exists the PlaceSingleOrder function. Similarly, there are also functions available to place OCO Orders, If/Then OCO orders, associated single orders, and associated OCO orders. Upon completion, a dataset is returned. The first row indicates success – true or false. The second row contains an error code reference number, which will be 0 if successful. The third row contains a confirmation number, which will be -1 if the order is unsuccessful.
'Verbose code example of Order Execution:
' Set up string variables in preparation for call:
Dim UserID As String = "myUserID"
Dim PWD As String = "myPassword"
Dim Pair As String = Me.ComboBoxCCY.SelectedItem
Dim Expiry As String = Me.ComboBoxExp.SelectedItem 'EOD or GTC
Dim BuySell As String = Me.ComboBoxBuySell.SelectedItem 'B or S
Dim Amount As String = txtAmount.Text
Dim Rate As String = txtRate.Text
Dim OrderBasis As String = Me.ComboBoxOrderBasis.SelectedItem ' S = Stop Loss T = Limit Order
'Create OrderResponse object as container for the result set
Dim myResponse As New com.efxnow.api.objOrderResponse
'Fill Return Object:
myResponse = myWebService.PlaceSingleOrder(UserID, PWD, Pair, Expiry, BuySell, Amount, Rate, OrderBasis)
'Pull items back from Object:
Dim Message As String
If myResponse.Success Then
Message = myResponse.Confirmation
Else
Message = myResponse.ErrorDescription
End If
'Display Message
Me.txtResponse.Text = Message
This function allows a client to select the pairs that will appear in their rate feed. There are no restrictions in place to limit the revisions. There are certain restrictions that limit the pairs that can be selected or deselected:
· A pair cannot be deselected if it has an open position, active order or is the base pair for a pair that has an open position or order. It will be a required pair until the position is removed or the order is closed.
· If a cross currency pair is selected, the base pairs that comprise the cross must also be selected. For example, if EUR/JPY is selected, then USD/JPY and EUR/USD must also be selected.
· There are maximum and minimum requirements. Currently, the max value is set to 25 and the min value is set to 4. These are subject to change at any time.
Upon the receipt of the confirmation for this function, you will receive a message via the rate feed (please see ‘Other Messages’ on page 10 for details). You must disconnect and reconnect to the rate feed in order for this change to reflect on you end. Upon completion, a dataset is returned. The first row indicates the error message if there was any error. The second row contains an error code reference number, which will be blank if successful. The third row indicates success—true or false.
'Verbose code example of Rate Subscription:
'Set up string variables in preparation for call:
Dim UserID As String = "myUserID"
Dim PWD As String = "myPassword"
Dim BrandCode As String = “myBrandCode”
Dim ProductList As String = “EUR/USD,JPY/USD,GBP/USD,USD/CHF,AUD/NZD,AUD/USD,EUR/AUD,NZD/USD”
'Create SaveUserProductSubscriptionSettings object as container for the result set
Dim myResponse As New com.efxnow.api.objProductSubscriptionResponse()
‘Fill Return Object:
myResponse = myWebService.SaveUserProductSubscriptionSettings(UserID, PWD, BrandCode, ProductList)
'Pull items back from Object:
Dim Message As String
If myResponse.Success Then
Message = myResponse.Confirmation
Else
Message = myResponse.ErrorDescription
End If
'Display Message
Me.txtResponse.Text = Message
Also, the examples package includes some examples of programming against the Web Services using the JAVA language. These examples offer a simplistic way to program against Web Services illustrating the simplicity of the text based XML model. There are however, tools that will generate proxy objects to do all of this automatically given a WSDL file. We would recommend this approach, as it simplifies the maintenance/support if and when the WSDL file changes. However, these are offered as pointers and are supplied ‘as-is’.
This class provided a static method to call an ASP.NET WebService via a PUT/GET method.
This class uses the WebService Util class to execute the Margin Trader 1.0 Webservices. Webserivces are exposed as standard functions and this class calls the appropriate webservice via the util class, parses the results and returns the results as java classes.
This class provides simple XML parsing functions for XML. It only understands the concepts of tags <TAG></TAG> and how to extract the content. Used correctly is can effectively parse well structured XML which is returned from ASP.NET Web Services.
This provides an example of the usage of the Simple Parser, note the last function in the class. The caller must know the order and the structure of the XML nodes expected to work correctly, and all expected nodes must appear in the xml.
These error numbers relate to responses from DealRequest, Order placement and Order Cancellation response objects and are new as of version 2.8.
0 = No Error
1 = General input parameter error
2 = Authentication error
3 = Stop Loss Order rate must be > current offer rate
4 = Limit Order rate must be < current offer rate
5 = Over maximum order amount
6 = Order rate must be within 1000 points
7 = Record not found
8 = Unable to complete request, the trading system is down for maintenance
9 = Rate changed (That rate is not acceptable / off market)
10 = Insufficient Margin
11 = A fatal error occurred processing your request; please check all positions and or contact the trading desk to confirm or deny the execution of this trade.
These error numbers related to responses from SaveUserProductSubscriptionSettings response object.
3 = Authentication Problem
2001= Invalid Product
2029 = Additional Products are required. The list of required products will be returned in the Message field.
4001 = Request Failed
9100 = Invalid Credentials
9101 = Empty Subscription Product Collection
9102 = Subscription Product Collection cannot exceed [max pairs]
9103 = Subscription Product Collection cannot be less than [min pairs]
The API Forum is the best method of getting help and support for the API. The Forum is actively monitored during business hours 9am to 5pm EST. Support can also be obtained by emailing APISupport@GAINCapital.com
The latest version and url can be found on the website.
{end of document}
[1] GetRatesServerAuth is used to obtain the key for the session. See the Web Services detailed description later in this document.
[2] OCO stands for One Cancels Other
2 Expiry EOD stands for End Of Day means 5:00 pm EST. GTC stands for Good Till Cancel
[3] Expiry EOD stands for End Of Day means 5:00 pm EST. GTC stands for Good Till Cancel
2 Associated Position refers to an open position. Orders can be place to an associated open position through any functions with ASSP. Unassociated positions are referred to when you do not have a respective open position.
[4] OCO stands for One Cancels Other
2 Expiry EOD stands for End Of Day means 5:00 pm EST. GTC stands for Good Till Cancel
[5] OCO stands for One Cancels Other
2 Expiry EOD stands for End Of Day means 5:00 pm EST. GTC stands for Good Till Cancel.
3 Associated Position refers to an open position. Orders can be place to an associated open position through any functions with ASSP. Unassociated positions are referred to when you do not have a respective open position.
[6] OCO stands for One Cancels Other
2 Associated Position refers to an open position. Orders can be place to an associated open position through any functions with ASSP. Unassociated positions are referred to when you do not have a respective open position.
3 Expiry EOD stands for End Of Day means 5:00 pm EST. GTC stands for Good Till Cancel.