Skip to content

Design

The diagram below gives a very high-level overview of the way the A2PB application interacts with the broker’s software and the stock exchanges.

IB stands for Interactive Brokers – the broker and it’s trading API the A2PB system is built against. The A2PB application communicates via IB’s proprietary socket interface with the locally running IB Trader Workstation (TWS). The TWS in turn communicates with the IB Server which holds the user’s trading account and which executes trades against the various stock markets IB is connected with.

There are two types of application views (called perspectives). First, there’s the dashboard, and then there’s the perspective called Portfolio View. The Portfolio View comes in two variations – one with a focus on the portfolio group and one with the focus on a single portfolio.

The Dashboard View

The dashboard is used to show your total account value and exposure diagrams for all of your portfolios. In addition, the dashboard view is where you configure your account, portfolio group and portfolio structure.

Portfolio Group View

The portfolio group view, as shown in the following example, and the portfolio view, as shown in the next diagram are similar. In the left-top area, they show the current exposure while in the center to right area, they show the monitors for the various securities that are active within the portfolio group or portfolio respectively.

The portfolio View

Here, the exposure diagram in the top-left area shows the current and target exposure of the various positions in the selected portfolio (SMI).

The A2PB balancing algorithm proposes and continuously updates a list of trading propositions. The goal of the trading propositions is, if the user chooses to execute them, to move the portfolio from a potentially un-balanced state to a balanced state. If a portfolio is in a balanced state, no trading propositions are suggested. The balancer works by generating trading suggestions which, if executed, move securities from the pool of candidates to the pool of portfolio positions and vice versa).

Portfolio and portfolio position properties that define a balanced state

On the portfolio

  • The target position count (i.e. size) of the portfolio.
  • The target weight of the portfolio (i.e. the target exposure — the amount of money invested in the portfolio). Short positions in the portfolio (if any) are, in terms of exposure, counted like long positions (i.e. with a positive value).
  • The target percentage of hedge positions in the portfolio. This is expressed as a percent value of the target weight of the portfolio. For example, given a portfolio with a total exposure of $100’000 and a target hedge percentage of 30%, the porfolio’s is considered balanced (in terms of hedging) if there are $30’000 worth of positions in the portfolio that have a negative correlation with respect to the expected price movement of the other 70% of the positions in the portfolio.

On a single security

  • A rating, 7 levels going from “Strong sell” up to “Strong buy” (see Key Concepts)
  • A target weight (small, medium, large, with a possible +/- fine-adjustment option) see Key Concepts)
  • A hedge attribute (wheather or not the security is considered a possible hedge)

The balancer

The balancer is triggered whenever the user adjusts one of the parameters above or makes some other relevant adjustment like adding a new security to the candidates pool of a portfolio.

The balancer is also triggered whenever there is a relevant event happening in the connected trading account (like an update of the overall account value, or a trade confirmation for an open order).

As mentione above, the goal of the balancer is to generate trade suggestions which, when executed, will put the portfolio into a balanced state. When run, the balancing algorithm considers all of the portfolio’s current positions on one side and all of the portfolio’s candidate positions on the other side. There are the following cycles the balancer runs through in order:

1. Honor “Strong buy” and “Strong sell” ratings

Strong buys and strong sells are basically manual overrides. They will always be honored with priority one, bypassing any balancing logic and potentially worsening the current balancing state of the portfolio.

Positions poolCandidates pool
ConditionResultConditionResult
A position is long and has a “Strong sell” ratingThe position is closed (prio I)A candidate has a “Strong buy” ratingThe candidate is bought (prio I)
A position is short and has a “Strong buy” ratingThe position is closed (prio I)A candidate has a “Strong sell” rating and the candidate’s hedge-mode is “If short”The candidate is sold short (prio I)
Note: swinging from a long position into a short position or vice versa in one transaction not yet supported.

Cancelling a generated trade suggestion of this type:

If the user opts to reject a generated trade suggestion of this type, the trade suggestion record is deleted and the rating of the associated security is adjusted to hold.

2. Meet target portfolio size

Once any Strong Buy or Strong Sell ratings are processed, the balancer tries to meet the target size of a portfolio. If the portfolio’s current size is smaller than the target size, one or more candidates will be proposed for buying. If the portfolio’s current size is bigger than the target size, existing positions are proposed for selling.

Positions poolCandidates pool
ConditionResultConditionResult
Portfolio is over target size by more than one and there’s one or more position with a “Sell” rating.The position(s) with a “Sell” rating are sold (prio II). The positions are taken in the order in which they appear in the positions list (bottom up).Portfolio is under target size by more than one and there’s one or more candidate with a “Buy” rating.The candidate(s) with a “Buy” rating are bought (prio II). The candidates are taken in the order in which they appear in the candidates list (top down).
Portfolio is over target size by exactly one and there’s one or more position with a “Sell” rating.A suitable position with a “Sell” rating is sold (prio II). The position is selected according to the rule in Picking securities to buy/sell, below.Portfolio is under target size by exactly one and there’s one or more candidate with a “Buy” rating.A suitable candidate with a “Buy” rating is bought (prio II). The candidate is selected according to the rule in Picking securities to buy/sell, below.
Portfolio is over target size by more than one and there’s one or more position with a “Sell/Adjust” rating.The position(s) with a “Sell/adjust” rating are sold (prio III). The positions are taken in the order in which they appear in the candidates list (bottom up).Portfolio is under target size by more than one and there’s one or more candidate with a “Buy/Adjust” rating.The candidate(s) with a “Buy/adjust” rating are bought (prio III). The candidates are taken in the order in which they appear in the candidates list (top down).
Portfolio is over target size by exactly one and there’s one or more position with a “Sell/Adjust” rating.A suitable position with a “Sell/Adjust” rating is sold (prio II). The position is selected according to the rule in Picking securities to buy/sell, below.Portfolio is under target size by exactly one and there’s one or more candidate with a “Buy/Adjust” rating.A suitable candidate with a “Buy/adjust” rating is bought (prio II). The candidate is selected according to the rule in Picking securities to buy/sell, below.

Important: The above table only explains the handling for long positions. The handling for short positions is symmetrical. For example, take the top-left cell: In order to get the condition for the short position case, the condition would have to be rephrased from:

  • Portfolio is over target size by more than one and there’s one or more position with a “Sell” rating

to

  • Portfolio is over target size by more than one and there’s one or more short position with a “Buy” rating

Picking securities to buy/sell

Consider this example: we have a portfolio with 3 positions and a target size of 4. The portfolio’s weight is currently under its target weight. We also have 2 candidates with a rating of “Buy”. At this point, the balancer will only pick one of the candidates for buying (only one is needed to reach the target of 4 positions in the portfolio). If the two candidates have differing target weights, the balancer will pick the one which, as a result of the completed buy transaction, will move the portfolio closer to its intended target weight.

Since there are multiple targets to be reached, the algorithm is slightly more complicated than that. As mentioned above, there’s the overall target exposure of the portfolio. But there’s also the target hedge percentage of the portfolio. An example: Lets say we have a

  • target exposure, Et, of 100, a
  • current exposure, Ec, of 80, a
  • hedge target exposure, HEt, of 20, i.e. 20% (HEPt = 20%), and a
  • current hedge exposure, HEc, of 10, i.e. 10%, and some candidate to be picked, C, having a
  • candidate target exposure value CEt and a
  • candidate hedge target exposure value CHEt

The goal is to pick the candidate C that minimizes the following formula:

| Ec + CEtEt | + HEPt * | HEc + CHEtHEt |

And satisfies the condition that if HEPt = 0, the Candidate is not a hedge position.

Conversely, when selling a position P in order to reduce the position count of a portfolio, we minimize the formula

| EcPEc – Et | + (100% – HEPt) * | HEcPHEcHEt |

Cancelling a generated trade suggestion of this type

If the user opts to reject a generated trade suggestion of this type, the trade suggestion record is deleted and the rating of the associated security is adjusted to hold.

3. Meet target weight

Finally, the balancer turns to the target weight. In this step, incremental buy or sell trade orders are suggested in order to move individual positions, portfolios and portfolio groups towards their intended target weight.

Positions pool
ConditionResult
Position is under weight and has any type of buy ratingThe position is expanded to meet the target weight.
Priority I if strong buy, II if buy, III if buy/adjust.
Position is over weight and has any type of sell ratingThe position is reduced to meet the target weight.
Priority I if strong sell, II if sell, III if sell/adjust.

Note: Trading suggestions that move a position’s exposure towards its target exposure, while worsening the portfolio’s exposure (compared to its target exposure), are visually marked (e.g. via an exclamation mark and text remark).

Cancelling a generated trade suggestion of this type

If the user opts to reject a generated trade suggestion of this type, the trade suggestion record is deleted and the target exposure of the associated security is adjusted such that it matches the current exposure.

Trading Suggestions

Zero or more trading suggestions are generated as a result of a balancer run. The balancer marks any generated trading suggestions with a priority from one to three:

  • Prio I – Manually triggered trading suggestions because of a “strong” buy or sell rating.
  • Prio II – Automatically generated trading suggestions because of a buy or sell rating.
  • Prio III – Automatically generated trading suggestions because of a buy/adjust or sell/adjust rating.

The trading suggestions are sorted by these priorities and help the user when he/she goes through the list of trading suggestions in order to either accept or reject them. By accepting a trading suggestion, an order is generated and submitted to the connected Interactive Brokers account. By rejecting a trading suggestion, the trading suggestion is deleted and, by default, the security or portfolio parameter that caused the trading suggestion will be adjusted to avoid generating the trading suggestion in future balancing cycles.

The architecture of the software is designed from the ground up to be able to be deployed as a WAR to an application server or container environment. However, at the time of this writing (May 2022), A2PB’s Maven build is geared towards building a stand-alone Java application to be run on Windows and Mac operating systems.

The reason for the current build to focus on building a Windows/Mac executable lies in the fact that A2PB requires a connection to the Interactive Broker’s Trader Workstation for real-time stock quote data feeds and for trading. The Trader Workstation, TWS, is only available as a locally running Java application.

The following list outlines some of the most important design principles and technologies in use:

  • Built entirely in Java using OpenJDK 16.
  • Strict separation between server and presentation code. Separation enforced via Java modules.
  • DB persistence implemented using a custom, light-weight DB access layer employing Spring’s JDBC Template. Tested for use with MySQL and H2 databases. The latter supports embedded mode allowing to install the application as a self-contained executable.
  • DB schema/version management using Liquibase.
  • All GUI components like dialogs, controls, viewers and tables are defined in a declarative fashion based on an XML-based data dictionary and layout description.
  • All business logic, including all non-trivial validation, is implemented in the server module using JSON data structures for communication between the client and the server.
  • The technology in use to build the running Windows/Mac GUI is based on Eclipse RCP/SWT 4. However, because of the server-centric, declarative design of A2PB’s GUI elements, front-ends can just as easily be built based on alternative GUI technologies, including JavaScript/HTML. A Vue.js based proof-of-concept is in the works.
  • Every user interaction in the GUI is recorded to an audit-log and can be extracted in text-script form to be re-played, faceless, on the server.
  • JUnit based test suites are executed as part of the maven build process. Apart from basic unit tests, JUnit is also used to run test scripts for all business use-cases (these test scripts can be recorded out of the running application – see bullet point above).
  • All service modules used throughout the application are wired up using dependency injection.
  • The application currently runs against Interactive Broker’s TWS API 9.8.
  • The TWS API is accessed using a custom developed, provider agnostic broker API abstraction layer. Besides the TWS implementation, there currently exists one additional implementation of the broker access interface: a Mock Provider used for unit testing.