Category Archives: General

Next generation MetaTrader – Interactive Brokers Interface: IBPlugin

IBplugin is a general Windows component that can be used in Windows applications or script- and programming languages.  It is a further development of TWSLink with a focus on MetaTrader.
IBPlugin can be used by coders, as well as endusers who get software based on IBPlugin.  Such a sample is the IB Trade Panel:  This expert advisor for the MetaTrader platform makes it easy to
place orders for an Interactive Brokers account on MetaTrader charts.  Orders are only executed on your Interactive Brokers account.

 

 

Coders can write their own experts and sell them.  They can use all open sources that are shippted with IBPlugin. This includes the IB Trader Panel.
You can use it, change it and sell it in closedcommercial applications.  The only thing you and your customers need is an IBPlugin license.
This will be below EUR 100 per year for Interactive Brokers single accounts.

 

MatLab script for TWSLink

A new short example for using TWSLink with the actual version of MatLab (MatLab 2017a) is available.

The old example may not compiled in current MatLab script editor as the header declaration for TWSLink exported function was not compatible. This has been changed. So the new example comes with modified headers and a minimal example how to load TWSLink, connect, register and place a trade.

Please use the example as follows:

  1. Make sure TWSLink is installed ([ddownload id=”281″ style=”link” text=”TWSLink setup”])
  2. Download MatLab example and unzip in a folder of your choice.
  3. Open MatLab (tested with MatLab 2017a).
  4. In the script editor open twslink.m file from MatLab example folder.
  5. Run the script. You might get asked to add this folder to path or to change folder for execution. Select “Change Folder“.

[ddownload id=”413″ style=”link” text=”Download MatLab example”]

 

% load twslink dll
loadlibrary('twslink2.dll','twslinkimp.h','alias','twslink');

% uid of contract
uid=0;
% uid of order
uid_order=0;

% register EUR.USD CASH 
uid = calllib('twslink', 'REGISTER_CONTRACT','EUR','CASH','USD','IDEALPRO','','','',0.0,'',0,0.0);

% connect to API (running TWS or gateway)
calllib('twslink', 'CONNECT','127.0.0.1',7496,1,10000);

% SEL 25.000 EUR.USD CASH
uid_order=calllib('twslink', 'PLACE_ORDER',uid,0,'SELL','MKT',25000,0.0,0.0,'GTC',1,0);

% unload twslink
unloadlibrary('twslink');

 

 

 

 

Disable TWS automatic Logoff

Attention:
Method described below is deprecated.  It is recommended to checkout TWS version >= 978 which allows to set a restart time. Login is just required once per week. (Nov. 26, 2019)

Hello,

this is a quick tutorial how to prevent Interactive Brokers Traders Workstation (TWS) from automatic logoff. It also allows TWS to be started with a double click on a batch (Windows)- or shell (Linux) file.

This tutorial refers to Windows. On Linux just edit .sh files instead of .bat files.Steps to create automatic startup and autologoff preventions are:

  1. Download free open source IBController
  2. Unzip IBController into a folder of your choice
  3. For each TWS login, create a subfolder below IBController folder
  4. Copy files IBController/IBController.ini and IBController/IBControllerStart.bat (.sh on Linux) to this subfolder
  5. Edit IBController.ini to set login name and password and to set a flag to prevent autlogoff
  6. Edit IBControllerStart.bat to set TWS-Version and path to your IBController.ini
  7. Test it

 

We tested auto startup with TWS 952, TWS 964 and IBController 3.2.0. Before you start, make sure to have a TWS >= version 952 installed. You can check this,  by looking in folder.
c:\jts. You should see something like c:\jts\952 or c:\jts\959

1– Download IBController

Visit Github to get the latest stable version. In this case, it is version 3.2.0. Scroll down to file IBController-3.2.0.zip.

2– Unzip IBController

to C:\IBController. So in C:\IBController you can see  files: README.txt, version, userguide.pdf, etc…

3– Create configuration subfolder

for all your configurations (different IB logins (paper, real) and/or TWS startup), let’s call it: configs. So you finally have a folder

c:\IBController\configs

Now in this folder, create a subfolder for a specific configuration. In our case, this is to start TWS version 952 with the public demo login credentials.
Create folder:

         c:\IBController\configs\demo_952.

and create another folder in this subfolder, call it TWS. (This is used by TWS to store some setup.)

        c:\IBController\configs\demo_952\TWS.

 

4–Copy files

C:\IBcontroller\IBController.ini and c:\IBController\IBControllerStart.bat to config folder

          c:\IBController\configs\demo_952.

Also copy [ddownload id="1405" text="our jts.ini default file"] into this config folder.

5–Edit INI file

c:\IBController\configs\demo_952\IBController.ini.
Scroll to attribute
IbLoginId

and set the username of your account. In this case with public demo user:
IbLoginId=edemo

Scroll to attribute
IbPassword

and set the password to the password of your login. This case the password for public demo:
IbPassword=demouser

(You could also set an encryped password...)
     PasswordEncrypted=yes

To encrypt your password in this file. BUT then, you need to put the encrypted password for IbPassword parameter.

To encrypt password, open file c:\IBController\IBControllerEncrypt.bat and follow instructions. (replace ‘deomuser’ by your password,
run file in a cmd window, copy encrypted password and put behind IbPassword=.

Define the folder, where TWS is storing settings and logfiles. Use the TWS subfolder for this as argument for
attribute IbDir.

     IbDir= c:\IBController\configs\demo_952\TWS

Set the trading mode flag. For livetrading to live , for paper trading to paper. So real accounts should have this set to live. Paper accounts to paper.

TradingMode=live

Finally, set the attrib IbAutoClosedown to no. This prevents TWS from autologoff.

     IbAutoClosedown=no

 

6– Edit BAT file

c:\IBController\configs\demo_952\IBControllerStart.bat.
Set parameter TWS_MAJOR_VRSN to a version which is installed in c:\jts. In this case 952.

     TWS_MAJOR_VRSN=952

Set the path of the file IBController.ini.

     IBC_INI=c:\IBController\configs\demo_952\IBController.ini

 

7– Test it

Doubleclick on file c:\IBController\configs\demo_952\IBControllerStart.bat.. This should start TWS, do an automatic login and prevent

TWS from automatic logoff. To test this feature, in TWS open Settings/Lock and Exit

and set the time 5 Minutes to future. !Close this dialog and settings. Wait for logoff time. TWS should NOT be closed. If you reopen logsettings, you will see logoff time shifted.

 

Hopefully this tutorial can help you to run TWS more convenient and to stop it from logoff. The setup in this tutorial slightly differs from what the IBController makes recommend.
Basically, the recommend to store the config files in the users document folder and to set this folder for encryption. Of course you can do it this way. Just follow the guid, which can
be found in folder

c:\ibcontroller\userguide.pdf

 

 

 

 

MQL Code Snippet for random number generation

This post is a suggestion how to generate an integer random number with the same randomness as the market itself. It is assumed, that market data series are more or less random. The function suggested below can be used in MetaTrader 4/5 Expert Advisors,Scripts or Indicators. The trick is simple: Just build the sum over a series of bars of the past, like:

s=sum(n,close-open)

 

, where n is the # of bars. Then divide the sum by minimal price movement to get a number which can be converted to an integer. Now scale this integer sum down buy the module of random number range.

s = s mod range

That’s it. This random number has the same distribution as the market itself (scaled to its range).

        

Function Code:

int random_int(MqlRates& rates[], double symbol_point,int range=2, bool use_tickcount=true)
{
     if(range > 0)
     {
        int len=ArraySize(rates);
        if(len > 0)
        {
           double bar_sum=0.0;
           for(int i=0;i < len;++i)
               bar_sum +=(rates[i].high - rates[i].low + MathAbs(rates[i].close - rates[i].open));
           // bar_sum has the same randomness as the market
           
           // make it integer convertable
           bar_sum /= symbol_point;
                      
           // add tickcount, to put random behaviour on backtest (where always the same rates selected)
           if(use_tickcount == true)
               bar_sum += GetTickCount();
               
           // scale random number to range
           int rnd=((int) bar_sum % range);
           
           //PrintFormat("rnd=%d bs=%.2f tc=%d dt=%s",rnd,bar_sum,GetTickCount(),TimeToStr(__rates_dyn[0].time));
           return rnd;
        }
     }
     return 0;
}

An application could be be to create random buy/sell orders for test purpose.

void test_random(void)
{
   int rnd=00;
   string sb_sequence;
   double point;
   MqlRates         rates_array[];
   
   // get point for symbol
   SymbolInfoDouble(_Symbol,SYMBOL_POINT,point);

   // make 100 random runs
   for(int i=0;i < 100;++i)
   {
      // get 10 bars in the past, with a moving offset 
      // (the order is not importent here)
      if(CopyRates(_Symbol ,PERIOD_CURRENT,i,10,rates_array) > 0)
      {
         // get a random number 0 or 1.
         // 0=OP_BUY,1=OP_SELL
         rnd=random_int(rates_array,point, 2,false);
         if(rnd == OP_BUY)
            sb_sequence += " buy";
         else
            sb_sequence += " sell";
            
      }
   }
   
   // print out sequence to Experts log
   Print(sb_sequence);
}