Frequently Asked Questions

Get answer to some of the most common NJ4X API questions

Configuration

"Could not establish connection to terminal server: 127.0.0.1:7788" ? I have that problem in my JFXExample.java.
You need to start NJ4X Terminal Server. One way to do that is to use run_terminal_server.bat (from [jfx_dir]\bin\)

.Net users can start NJ4X Terminal Server from a Windows "Start>All Programs>NJ4X API" menu.
"No connection to server" ..? Ok, I started Terminal Server. So now the message has changed: Exception in thread "main" MT4 Terminal client disconnect... java.io.IOException: No connection to server: com.jfx.net.TerminalServer$ClientWorkerThread$NoSrvConnection: :443
Now you are experiencing MT4 Server connection problem, which is due to the expired/wrong MT4 configs.

Here is how to update MT4 config files into the Terminal Server or how to configure an additional Broker to work with:

  • 1. Start your MT4 terminal and select "File"->"Open Data Folder" menu item.

  • 2. Copy all *.srv files from the "config" dir to the Terminal Server "srv" directory (e.g. C:\Users\[USER]\jfx_term\srv)

  • 3. Use name of the srv file as an argument to the Broker() constructor:
    If it is "ATCBrokers-Demo.srv" then connection string would look like

    jfxExample.connect("127.0.0.1", 7788, new Broker("ATCBrokers-Demo"), "12345678", "abcdef"); 
Can another EA written in MQL be loaded at startup by specifying it in a config file somewhere?
Sure. There are ea and chr Terminal Server directories (i.e. C:\Users\[USER]\jfx_term\ea and C:\Users\[USER]\jfx_term\chr)

You can put additional ex4 EA files to ...\jfx_term\ea dir and they will be copied to JFX-managed MT4 directories.

...\jfx_term\chr should be used for chart templates instantiating custom Expert Advisors.
Can the terminal when executed be visible?
There is a -DSW_HIDE=false parameter (to start Terminal Server with) in order to show all app-managed terminals. To set this parameter you need to modify run_terminal_server.bat, which already contains commented lines for different configurations.
Do you know why some brokers won't allow us to connect through NJ4X? We have seen some brokers that give us invalid user/password combination errors with perfectly valid credentials.
Be sure that your *.srv files for those brokers are up to date. They should be located under the c:\Users\[USER]\jfx_term\srv directory.

Note: the minimal Windows version supported by NJ4X is Windows XP SP3.
How can I debug a strategy? -Xdebug?
Like any other java/.Net code: use your favorite IDE to put breakpoints
How can I test my strategy in java with MT4 ?
Testing of JFX EA goes much in the same way as testing of any other Expert Advisor.

You may find "MT4 Java trading strategy testing" and "MT4 .Net trading strategy testing" videos at http://nj4x.com/video for details.

Here are the steps:

  • 1. Start MT4 terminal of your choice. Copy jfx.ex4 and libraries\mt4if.dll from [jfx_path]\examples\experts to respective experts dir of your MT4 terminal installation. Follow meta_trader_config_1.jpg - meta_trader_config_3.jpg screenshots (found in examples/experts directory) to configure your MT4 terminal.
  • 2. At MT4 terminal open "Tester" window from the toolbar. You may also contact built-in MT4 terminal help, section "Auto Trading>Strategy Testing" for details.
  • 3. Meanwhile you should start your java application to listen to the JFX EA connections, it is described in examples\README.TXT#4.
  • 4. Follow JFX EA setup screenshots jfx_test_2.jpg - jfx_test_5.jpg (the "strategy" parameter of the EA should be your JFX strategy fully qualified class name)
How have you gotten around the issue of storing a client's logon details?  I can imagine this is a security issue and not sure if there is an innovative way to handle it.
NJ4X API does not keep any client's logon details. You just need to provide them at runtime to Connect() method, afterwards NJ4X Terminal Server starts MT4 terminal.exe, which takes care about authentication.
I was confused in thinking that jfx instantiated the TradeIt class defined in the parameters of the jfx EA.  What parameter is used for that?
"strategy" parameter of jfx EA is used to specify the name of java class, inherited from the basic Strategy class, and implementing your own trading algorithms. 
Where does the class file for my strategy need to be located or does it use the machine class path?
It should be located in the classpath of your java application, which is usually started as a separate (from mt4 terminal) java process.

Deployment

Does the Terminal Server need to be running if JFX Expert Advisor attached to client terminal symbol manually?
No, it does not. in this case Terminal Server is not required.
I assume that each broker connection would require a separate terminal instance, is that correct? Say I have 100 clients with one broker, but 50 with another?
Right, for each connected user/broker we need separate MT4 terminal.exe process. In your case it is 150 terminals.
Is it possible to run the MT4 terminal on some Windows host, an the Java (.Net) API client application on some other Linux host?
You are absolutely right. It is possible because the communication between NJ4X API client and terminal.exe runs via TCP/IP (one can additionaly configure UDP protocol layer to increases the performance).
Is there a method to get the directory where the terminal is run from? The directory where you call below as .jfx_terminal directory.
It is {WindowsUserHome}\.jfx_terminal\{Broker}[space]{mt4_user}

For example "D:\Users\roman\.jfx_terminals\AlpariUS-Demo 982388"
Where do all the class files, jar files etc need to be located?
In any place of any machine accessible over TCP/IP from the MT4 terminal running machine.

How it works

Can JFX EA reference a class within a jar file directly?
MQL JFX EA has a number of parameters, one of them is called "strategy", and it should be filled with a fully qualified java class name of your Strategy (inheritor) java class, which in turn can reference any other class within a jar file. In case you write .Net nj4x application, jfx.ex4 EA "strategy" parameter should contain .Net class name and assembly name, e.g. "my.trading.Strategy,trader.exe"
Can NJ4X framework execute the java (.Net) program more than once a second or longer than a second?
Yes, you can take complete control once you are inside the Coordinate() method, and there are no time restrictions for your business logic. Additionally, you can override CoordinationIntervalMillis() method in order to define any suitable period NJ4X framework will call Coordinate() at.
Can it determine what other EA's (not Java/.Net based) are doing?
NJ4X Java/.Net application can get list of orders (market or historical), get current account equity - this is the only way to determine what other EA's are doing. Check the nj4x forum for the PositionListener functionality.
Do I have to load an EA into the terminal.exe as the API server part? Is it just an ex4, or do you also require DLLs?
There are two options (mt4if.dll is required in both cases as it is part of JFX EA):

1 - when MT4 terminal is driving: You start MT4 terminal and manually drop jfx.ex4 expert advisor to the chart. Expert Advisor connects then to your java application. This process is detailed in "NJ4X - Metatrader Java and .NET API - readme.pdf" document, available for download.

2 - when Java/.Net application is driving: You are coding your application to connect to the broker(s) using MT4 account credentials. It is as simple as

demoJfx.connect("127.0.0.1", 7788, Broker.AlpariUS_Demo, "982388", "gtx8TCo");

NJ4X Terminal Server starts MT4 terminal.exe application in background to serve market requests from NJ4X application. It keeps separate MT4 terminal directory structure at your computer under the current user home directory (e.g. c:\Users\brian\.jfx_terminals or C:\Documents and Settings\brian\.jfx_terminals).
Does this java api send trades directly to the MT4 server or through the MT4 client?
It is trading through the standard MT4 client terminal.

Does this perform MT4 Client Terminal emulation?
Yes. NJ4X API allows java/.Net application  to use almost all MQL functionality available to the MT4 EA. Strategy class descendants override Coordinate() method which is called periodically by NJ4X framework in order to perform trading tasks. This is similar to how MT4 client terminal is calling EA's start() method on each new tick.
How are arrays passed between java strategy class and EA in MetaTrader Client Terminal?
There is no need to pass Bid, Ask, High, Low etc. arrays to java application. Instead one can use MT4.marketInfo() method to get current  data or methods like iOpen, iClose, iHigh, iLow - to retrieve historical data. JFXStreamerExample.java class contains history fetching example (there is also StrategyTest.sc / LoadHistoryTest in tests project of NJ4X for .Net).
I understood that if attaching jfx EA to the symbol chart manually then a main method is not required. JFX expert advisor calls the init java method and MT4 start calls the coordinate java method of the Strategy class I have created. Is that correct?
No, it is not. JFX EA does not start any java (.Net) application itself, it just connects to the existing up-and-running one over the network.
I've found that when it calls coordinate(), it never returns until I am done processing.
You can stay in the Coordinate method as long as you need. Normally lifecycle of the coordination is short, and you return from Coordinate as soon as possible. NJ4X framework will execute Coordinate again in a configured period (see coordinationIntervalMillis method) afterwards.
Is an MT4 Client Terminal required?
Yes, it is, you do not need to install it though. MT4 client terminal is included into the NJ4X api distribution and NJ4X Terminal Server installs and runs MT4 client terminals in background.
What is the purpose of the Strategy.coordinate() method? When is it called by the NJ4X framework?
Strategy.coordinate() is called by NJ4X framework once per coordinationIntervalMillis()-defined period. It is 60 seconds by default.

Initially it was an analog of the "start" method of MT4 Terminal's Expert Advisor - so it was called when new tick arrives.

Now its purpose is to do your main trading strategy tasks, like monitoring existing positions, rising new market orders etc.

To get real-time ticks use TickListener functionality (more details are in examples and at http://nj4x.com/forum page)
What is the relationship between the Terminal Server and the generated MT4 client terminal(s)?
Terminal Server manages MT4 terminals in terms of creating installation directories (i.e. c:\Users\[USER]\.jfx_terminals\[BROKER]_[ACCOUNT]), starts or stops MT4 terminals according to the NJ4X (Java or .Net) application requests.

Performance

I forgot to ask what is the latency of the communication protocol? How long (latency) does it take to submit a trade request and get a response?
It takes 0.2 millisecond in average for a single round trip between jfx application and mt4 terminal (JFXExampl.java contains sample code used to get latency figures below)

21:48:30.438> Latency test...
21:50:03.225> total latency test duration: 92787 millis for 300000 requests
21:50:03.225> Total Req Error Req Min_Req Time Max_Req Time Avg_Req Time cnt: <5ms 10 25 50 100
21:50:03.225> Cnt 300000 ErrCnt 0 Min 0 Max 30 Avg 1 cnt: 299993 2 3 2 0
I have a problem with strategy tester performance - it is extremely bad. Do you have any suggestions what it can be connected with?
NJ4X enables 5000 calls per second between app and a single mt4 terminal, its more than enough for real-time trading, but tests can suffer as long as native mt4 experts are working about 100 times faster.

This is because of network communication between terminal and NJ4X app.

My suggestions:
  • 1. For tests put all staff (Java/.Net and terminal) to the same machine
  • 2. If you do not need to debug your strategy, UDP transport can be used (-Djfx_use_udp=true (.Net/App.config: "nj4x_use_udp"), see examples)
  • 3. Remove redundant MT4 calls, optimize your code.
  • 4. Temporarily enable extended traces by (-Djfx_server_port=17342 (.Net/App.config: "nj4x_server_port")) and check out [MT4_Dir]/logs/socket.log and [MT4_Dir]/experts/logs

You can also run Java strategies inside of MT4 terminal, which increases performance about 12 times.

You may configure CLASSPATH environment variable (all jar files located in [MT4_Dir]\experts\libraries will be used automatically) and set jfxPort jfx.ex4 EA parameter to zero ("0").
What research have you done on resources required to run significant number of MT4 terminals?
Single terminal takes about 10-20MB of RAM, 5MB+cumulative history size on HD and 0.01-1.00% of CPU after the start.

The research has been performed to run normally 40 terminals on the minimalistic configuration virtual box of 1GB+1CPU. 40 terminals consumed 80% of RAM and 10% of CPU.

Update: Test run of 100 MT4 terminals (build 432)

One of the customers have used another configuration for its tests, and it was really hard to reach the limits (~1500 terminals):

ProcessorIntel Xeon X5650 @ 2.67GHz 2 processors
Memory36GB
HDDell Perc SCSI H7001.80 TB
NetBroadcom BCM5709C NeteXtreme II GigE
OSWindows Server 2008 Standard SP264bit

Note that JFX API allows easy horisontal scaling, i.e. adding new Terminal Server nodes.

Programming

Can I control multiple MT4 terminals connecting to multiple brokers from the same Java (.Net) API client application?
Of course, this is basic "feature" of NJ4X API.
Can I open multi symbol for a single terminal? (I don't care about ticks from the market)
Sure, you can have multiple orders opened for any symbol. Please test all functionality you need before making a purchase. Demo version has no limitations except api call delays.
Can my strategy java class be a jar file?
Sure, you can build a jar file with your strategy and accompanying classes and point java.exe to use a classpath containing that jar file, e.g. if it is tradeit.jar, then run your java application using something like 

java.exe -cp %CLASSPATH%;c:\[path]\tradeit.jar Main
Does the NJ4X Client support multiple brokers in a single JVM?
Yes, it does. Please see examples\README.TXT [multi] and JFXExample.java for more details.

.Net users may find it interesting to download nj4x_copier_demo.msi, which contains account copier demo C# source project.
How to shutdown terminal session ? I meant to shutdown/exit the terminal application - thus stopping all EA's in that terminal. I don't see any way to exit the NJ4X api from user input. Just ctrl-c to stop the application.
You can use Strategy.disconnect() method.

a) You can call Strategy.Disconnect(true/*immediately*/) in order for the mt4 terminal to be disposed from memory.

b) There is JFX_TERM_IDLE_TMOUT_SECONDS environment variable you can define on the Terminal Server machine.

It is number of seconds the MT4 terminal remains in memory after nj4x client disconnection. You can set JFX_TERM_IDLE_TMOUT_SECONDS to e.g. 10, in order terminal.exe to be kept in memory for 10 seconds (by default it is set to 6 hours).
Questions? Send me an e-mail