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. Subscription
8.1.9. Exchange
8.1.10. Property
8.1.11. 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

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

These Entities are typically immutable and represent the foundation for every trading strategy. The Section 13.5, “Reference Data Manager” provides a GUI to manage reference data.

Market Data

MarketDataEvent and its subclasses Tick and Bar as well as any type of GenericEvent

These Entities represent external events (Tick and Bar) coming from market data providers or internal events (Generic Events) coming from another trading strategy and provide the basis for the signal logic within trading strategies. Market Data is typically immutable and of only momentary interest to the trading strategies.

Transaction Data

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

These Entities represent or influence 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.

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

VO Converter

The static inner Converter class can be used to automatically convert the Entity to its corresponding Value Object, see Section 8.4, “Value Object”

Factory

The static inner Factory class can be used to create new instances of an Entity


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


To update Securities and SecurityFamilies one can either use the Section 13.5, “Reference Data Manager” or add necessary information directly into the database.

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.SecurityVisitor which must be implemented by all Security Visitors. Each Security 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.PolymorphicSecurityVisitor 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 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

The AlgoTrader DAO framework of consists of several main components

It is possible to add custom DAO's 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 // Required for exception translation

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));
    }
}

HL and SQL queries used by Alogtrader 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:

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, ValueObjects are typically used for transmitting objects (e.g. via JMS or RMI). For each Entity a corresponding ValueObject is generated. ValueObjects 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 ValueObject.

In addition to ValueObjects ValueObjectBuilders exist which help creating ValueObjects. Example:

MarketOrderVO order = MarketOrderVOBuilder.create()

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

The diagrams below shows additional the 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.