AlgoTraderAlgoTrader Documentation

Chapter 8. Domain Model

8.1. Entities
8.1.1. Strategy
8.1.2. Security
8.1.3. Market Data Events
8.1.4. Order
8.1.5. Account
8.1.6. Transaction
8.1.7. Position
8.1.8. Cash Balance
8.1.9. Subscription
8.1.10. Exchange
8.1.11. Property
8.1.12. Order Preference
8.2. Data access objects (DAOs)
8.3. Services
8.3.1. Main Services
8.3.2. Private Services
8.3.3. Client Services
8.3.4. Order Services
8.3.5. Market Data Services
8.3.6. Historical Data Services
8.3.7. Reference Data Services
8.3.8. Calendar Service
8.3.9. Reconciliation Services
8.3.10. Reset Service
8.4. Value Object
8.5. Enumerations

The following sections describe the Domain Model of the system using UML (unified modeling language).


The Main Entities of the system are specified within the following table:


A full list of all Entities of the system will be discussed throughout the next sections. Entities of the system can be categorized into the following three areas:

Reference Data

Represent static referential data like:

Strategy, Security, SecurityFamily, SecurityReference, Account, BrokerParameter, Property, OrderPreference and related Entities

Market Data

Represent external events (Tick and Bar) coming from market data providers or internal events (Generic Events) coming from another trading strategy. Market Data is typically immutable and of only momentary interest to the trading strategies. Market Data Events are available as Value Objects only (but not as Entities):

MarketDataEventVO and its subclasses TickVO, BarVO, QuoteVO, BidVO, AskVO, TradeVO and GenericTickVO as well as any type of GenericEventVO

Transaction Data

Represent the financial state of trading strategies. Some of them (e.g. Transactions and Measurements) are immutable whereas others (e.g. Positions and Balances) are mutable and change their values while Orders are getting executed:

Order, Transaction, Position, CashBalance, Measurement, PortfolioValue and related Entities

Besides providing Getters and Setters all Entities provide the following common features:


The strategy entity represents an individual strategy running inside AlgoTrader.

Regarding the question "what is 1 productive strategy?". It essentially up to the user, what he would like to consider as one strategy. A strategy can have one or multiple instruments. And also regarding trading logic there is no limitation.

However please note that the entire performance and reporting functionality of AlgoTrader happens on the strategy level. So if one would like to see performance metrics on an instrument level one would have to instantiate multiple strategies. Also, if it is a requirement to start and stop individual functions separately, it is best to put them into two separate strategies.

On the technical side each separate strategy allocates a certain amount of overhead (memory and CPU). For that reason it is best to combine functionality into as few strategies as possible if there are no good reasons not to separate them.

The field autoActivate means that if a strategy is set to active corresponding market data subscriptions are initiated automatically upon startup of the system

There are several classes that are directly related to the strategy



The above UML Class diagram shows all available Security classes


A Security Family contains common information about an entire family of securities (i.e. all general information about options on S&P500 are stored using this class). The class provides fields like exchange, currency, and tick size.


The above UML Class diagram shows all available SecurityFamily classes


The definition of the attributes of the classes Security and SecurityFamily are documented in the AlgoTrader JavaDoc

The class EasyToBorrow Contains information about how many contracts of a particular Stock can be shorted through a specific Broker.

SecurityReference Is a generic link between one security the owner and another the target. Using this class it is possible for a Security to have links to multiple other Securities.

The Visitor Pattern is a way of separating an algorithm from an object structure on which it operates. Using this pattern it is possible to implement custom Logic per Entity without polluting the Entity code itself.

AlgoTrader provides the interface ch.algotrader.visitor.EntityVisitor which must be implemented by all Entity Visitors. Each Entity Visitor has two generic type parameters R and P. R is the return type (or java.lang.Void) returned by all visit methods and P is an arbitrary parameter object that can be added to the visit methods.

In addition there is the ch.algotrader.visitor.PolymorphicEntityVisitor which reflects the entire inheritance tree of all Securities. For example if there is no visitFuture method the PolymorphicEntityVisitor will automatically invoke the visitSecurity method.

The accept method of each Entity can be used to process an arbitrary Visitor like this:

entity.accept(MyVisitor.INSTANCE);

In AlgoTrader there are two Visitors available which are used by the AlgoTrader Server

InitializingVisitor

Is used to make sure certain Hibernate Entity References are initialized / loaded.

TickValidationVisitor

Used to validate a Tick by rules defined per Security


The following UML Class diagram shows the Order and its related subclasses.

Table 8.6. Order Classes

EntityDescription
OrderBase Class for all Order Types
OrderStatusOrder Status changes received back from the Broker (e.g. PARTIALLY_EXECUTED or CANCELLED) are represented by this class
OrderCompletitionSimilar to Order Status but only gets created once an order is fully executed or cancelled and all corresponding database activity has been completed.
OrderPropertyAn arbitrary property that can be attached to an Order. Through the type attribute the OrderProperty can be marked as internal only or as fix property or as IB property.
FillFilled orders are represented by this Class
TransactionEach Fill is recorded as a transaction in the database using this entity. In addition the table transaction also carries transactions like INTREST, DEBIT, CREDIT & FEES
SimpleOrderAn Order that can be sent directly to the market
MarketOrder Predefined SimpleOrder types
LimitOrder
StopOrder
StopLimitOrder
AlgoOrderA composite order that will generate multiple SimpleOrders. An AlgoOrder cannot be sent directly to the market
VWAPOrderThis algorithm determines the Volume-Weighted Average Price
TargetPositionOrderThis algorithm automatically manages orders to reach the specified target quantity.
TrailingLimitOrderThis algorithm submits an order directly to the exchange, with a limit price set a fixed distance from the current market price.
SlicingOrderAn AlgoOrder, that will split a large order into multiple "slices". The size of the slice, time in the market and delay between orders are randomized within the specified range.
IncrementalLimitOrderAlgoOrder that will "step through" the spread using LimitOrders with incremental limits
TickwiseIncrementalLimitOrderWill step through the spread Tick-by-Tick
VariableIncrementalLimitOrderWill step through the spread by a specified percentage of the spread


For any Strategy holding a particular Security a Position is created in the database. Even if this position is later on closed (i.e. quantity = 0) the position will still remain in the database, because the associated Transactions still have references to it.

In general, position values (e.g. marketPrice, marketValue, averagePrice, cost, unrealizedPL & realizedPL) are calculated per actual strategy related position and show the price that would need to payed if the position was closed at this moment

Since some values (e.g. market value) depend on whether the position is long or short, aggregated position values of different strategies for the same security cannot be retrieved just by adding position values from the corresponding strategies. Example:

The sum of above market values would be -1'000 which is obviously wrong.

As a consequence the PortfolioDAO provides lookup-methods that aggregate positions from the same security (of different strategies) in the correct manner (e.g. findOpenPositionsAggregated).

The AlgoTrader DAO framework of consists of several main components

It is possible to add custom DAOs to the platform. To accomplish this one needs to create a DAO interface extending either ReadOnlyDao or ReadWriteDao, add custom operations such as entity specific finders and then create a custom DAO class extending AbstractDao and implementing the custom DAO interface.

public class MyEntity implements BaseEntityI {


    private long id;
    private String name;
    @Override
    public long getId() {
        return this.id;
    }
    protected void setId(final long id) {
        this.id = id;
    }
    @Override
    public boolean isInitialized() {
        return true;
    }
    public String getName() {
        return this.name;
    }
    public void setName(final String name) {
        this.name = name;
    }
}
public interface MyEntityDao extends ReadWriteDao<MyEntity> {


    public MyEntity findByName(String name);
}
@Repository 

public class MyEntityDaoImpl extends AbstractDao<MyEntity> implements MyEntityDao {
    public MyEntityDaoImpl(final SessionFactory sessionFactory) {
        super(MyEntity.class, sessionFactory);
    }
    @Override
    public Strategy findByName(final String name) {
        return findUniqueCaching(
            "from MyEntity where name = :name", QueryType.HQL, new NamedParam("name", name));
    }
}

HQL and SQL queries used by Algotrader DAO components are externalized and stored in Hibernate.hbm.xml file. This allows for better management and for easier re-use of queries.



<query name='Strategy.findByName'>
<![CDATA[
    from StrategyImpl 
    where name = :name 
]]>
</query>
            

Queries can be accessed from DAO classes or custom components by their names



public class StrategyDaoImpl extends AbstractDao<Strategy> implements StrategyDao {
    ...
    @Override
    public Strategy findByName(final String name) {
        return findUniqueCaching(
            "Strategy.findByName", QueryType.BY_NAME, new NamedParam("name", name));
    }
            

The system is based on a Service Oriented Architecture (SOA). All operations of the system are provided as Spring Services / Beans. The following groups of services exist:

Table 8.10. Private Services

ServiceDescription
AlgoOrderServiceOrder Services responsible for handling of AlgoOrders (delegates to AlgoOrderExecServices)
AlgoOrderExecServiceAbstract Base Class for all Algo Execution Order Services
ExternalMarketDataServiceAbstract Base Class for all external Market Data Interfaces
FixSessionServiceExposes properties of FIX sessions
ForexServiceResponsible for the FX Hedging functionality
GenericOrderServiceParent Class for all Order Services
MarketDataPersistenceServiceResponsible for persisting Market Data to the database
OrderExecutionServiceResponsible for handling of persistence and propagation various trading events such as order status update and order fills as well as maintaining order execution status in the order book.
OrderPersistenceServiceResponsible for persisting Orders and OrderStatus to the database
ReconciliationServiceResponsible for reconciliation of reports provided by the broker
ResetServiceResponsible for resetting the DB state (e.g. before the start of a simulation)
ServerLookupServiceProvides internal data lookup operations to other server side services
SimpleOrderServiceOrder Service responsible for handling of Simple Orders (delegates to SimpleOrderExecServices)
SimpleOrderExecServiceAbstract Base Class for all Simple Order Execution Services
StrategyPersistenceServiceHandles persistence of Strategy Entities
TransactionPersistenceServiceResponsible for the persistence of Transactions, Positions updates and Cash Balance updates to the database
TransactionServiceResponsible for handling of incoming Fills

The CalendarService is responsible for providing information about Exchange trading hours and holidays.

Especially when trading multiple exchanges around the globe the CalendarService becomes very useful. It provides convenient methods like:

In addition the Calendar service provides methods to identify a particular trading day, which will be important to associate a particular order for clearing and reconciliation. If a trading session overlaps from one day to another (e.g. starts on Sunday 23:00pm), the trading day will be considered the day when the session ends (e.g. Monday). However in this example Monday would need to be set to true in the corresponding TradingHours object.

In contrast to Entities which are used to persist information, Value Objects are typically used for transmitting objects (e.g. via JMS or RMI). For each Entity a corresponding Value Object is generated. Value Objects are immutable (i.e. all fields are final and need to be set through the constructor)

Each Entity contains an inner Converter class that can be used to convert the Entity to its corresponding Value Object.

In addition to Value Objects ValueObjectBuilders exist which help creating Value Objects. Example:

MarketOrderVO order = MarketOrderVOBuilder.create()

.setStrategyId(strategyId)
.setAccountId(accountId)
.setSecurityId(securityId)
.setQuantity(quantity)
.setSide(side)
.build();

The diagrams below shows additional value objects provided by the system. Server Side Value Objects are in use by the AlgoTrader Server only.



For selectable items with a fixed number of choices AlgoTrader contains the following Enumerations.