About‎ > ‎

Using IBController from .NET code

 

AFL code

_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g {{VALUES}}", O, H, L, C));
Plot(Close, "", colorBlack, styleNoTitle | GetPriceStyle());

RequestTimedRefresh(5);

GetAccountBalance();
 

.NET code

using System;
using AmiBroker;
using AmiBroker.PlugIn;
using AmiBroker.Utils;
using AmiBroker.BrokerIB;

namespace AmiBroker.Samples
{
    // This sample presents how to use IBController from .Net code.
    // It queries and presents the account balace and positions on the chart pane.
    // It handles connection issues and IBController installation issues gracefully.
    public static class IbcSample1
    {
        [ABMethod]
        public static void GetAccountBalance()
        {
            IBController ibc;

            // get the only IBController instance
            try
            {
                // get the single instance of IBController using GetInstance() static method.
                // if ActiveX server (BrokerIB.exe) is not running yet, then GetInstance() starts it up first.
                // if ActiveX server is already running, it returns the single IBController instance that connects to the server.
                // if GetInstance() throws an exception, then ActiveX server exe is not properly installed or is not working.
                ibc = IBController.GetInstance();
            }
            catch
            {
                YTrace.PrintMessage("IBController is not installed or is not working correctly.", 20, Color.Red);
                return;
            }

            // if not connected...
            if (ibc.IsConnected() < ConnectionStatus.Connected)
            {
                YTrace.PrintMessage("IBController is not connected to TWS", 20, Color.Red);
            }
            else
            {
                // get the account balance
                // note: it returns a string! You have to use float.Parse() if you need to use float value!
                string accountBalance = ibc.GetAccountValue(AccountField.TotalCashBalance);
                YTrace.PrintMessage("Total cash balance:" + accountBalance, 10, Color.Green);

                // present the list of the current positions
                string positions = ibc.GetPositionList();
                if (positions.Length == 0)
                    YTrace.PrintMessage("There is no open position.", 10, Color.Green);
                else
                    YTrace.PrintMessage("Currently open positions:" + positions, 10, Color.Green);
            }
        }
    }
}