AlgoTraderAlgoTrader Documentation
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:
Table 7.1. Entities
Entity | Description |
---|---|
Strategy | Each object of this class represents a running strategy within the system |
Security | This is the base class of all securities in the system |
SecurityFamily | A group of Securities (e.g. all S&P 500 Futures) |
Subscription | Market Data Subscriptions of a Strategy for a particular Security are represented by this class. For every Subscription the Strategy will receive Live Market Data for the corresponding Security |
MarketDataEvent | Represents any type of market data related to a particular Security |
Order | An Order for a particular Security |
Account | An account held with an external Broker or Exchange |
Transaction | Each Fill is recorded as a transaction in the database using this entity. In addition the table transaction also stores transactions like interest, debit, credit & fees |
Position | Represents an exposure to a certain Security on the Market |
Exchange | An electronic exchange or venue |
Quote_Request | Represents a request for quote sent to a broker/exchange |
Quote | A quote response for a Quote_Request |
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:
Represent static referential data like:
Strategy
, Security
,
SecurityFamily
,
SecurityReference
,
Account
, Property
,
OrderPreference
and related Entities
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
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 static inner Converter class can be used to automatically convert the Entity to its corresponding Value Object, see Section 7.3, “Value Object”
The static inner Factory class can be used to create new instances of an Entity
The strategy entity represents an individual strategy running inside AlgoTrader.
Regarding the question "what is a 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. This is useful in distributed mode when strategies and
the server run in different processes. If you restart the server in this
scenario, subscriptions for the strategies are automatically loaded again
(without having to restart the strategies).
There are several classes that are directly related to the strategy
Table 7.2. Strategy Classes
Class | Description |
---|---|
PortfolioValue | On regular time intervals certain portfolio values (e.g.
NetLiqValue ,
CashBalance , etc.) are saved to the
database for every strategy. |
Measurement | Custom Measurements (e.g. current value of a custom indicator) related to a strategy can be saved using this class |
CashBalance | A CashBalance represents the current cash
amount of a particular strategy in a particular currency |
Table 7.3. Portfolio Value Details
Attribute | Description |
---|---|
cashBalance | Market value of all open forex positions + cash amount available to the strategy |
marketValue | Market value of all open (non-forex) positions |
netLiqValue | Cash balance + market value |
realizedPL | Realized P&L of all positions |
unrealizedPL | Unrealized P&L of all positions |
All valuations (strategy and position level) can be queried via the
PortfolioService
. Fees are considered in the
calculations if properly configured.
The above UML Class diagram shows all available Security classes
Table 7.4. Security Types
Entity | Description |
---|---|
Option |
A tradable Option |
Future | A tradable Future |
Forex | A Foreign Exchange Currency (FX) or Crypto Currency |
Stock | A Single Stock |
Fund | An ETF, Mutual Fund, etc. |
Index |
An Index (e.g. Equity, Volatility, Commodity) |
GenericFuture | A virtual Future with a fixed duration |
IntrestRate | Any type of Interest Rate |
Bond | A corporate or government Bond |
Commodity | A physical Commodity (e.g. Energy, Metals, Agriculture or Livestock). For Commodity Futures use Future. |
PerpetualSwap | A perpetual swap contract supported by various crypto derivatives exchanges (e.g. BitMEX) |
Combination | A synthetic security composed of one or many Components (see Chapter 24, Synthetic Securities and Derivative Spreads) |
SecurityReference | A generic link between one security and another |
The Security class provides the following two important methods:
getValue
which calculates the current
(market) value of the instrument based on a quantity and a price
parameter
getPrice
which calculates the current
price of the instrument based on a (market) value and a quantity
parameter
For most instruments the formula is:
value
= quantity
x
contractSize
x
price
price
= value
/
quantity
/
contractSize
However for PerpetualSwaps
the formulas
are different:
value
= quantity
x
contractSize
/ price
price
= quantity
*
contractSize
/ value
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 MIN_QTY
,
MAX_QTY
and MIN_PRICE
. This
information is used by ReferenceDataService
when
downloading new future and option changes, values from Security Family will then
be copied onto the newly created Futures and/or Options. In regular operation
mode (i.e. simulation of live trading) the information from Security Families
are not used but only the information contained within Securities.
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.
Market Data Events are available as Value Objects only but not as Entities. There are three different kinds of Market Data Events:
Table 7.5. Market Data Types
Entity | Description |
---|---|
BarVO | Open-High-Low-Close Price Bars, also containing volumes and volume weighted average prices |
TickVO | Snapshot of the market at a particular point in time, containing information like last price, last time, bid, ask, volume, etc.. |
QuoteVO | Its subclasses represent the current best bid and offer
BidVO and
AskVO |
TradeVO | An actual order that was executed on the market, containing information like last price, last size and volume |
GenericTickVO | Represents additional price information made available by market data providers (e.g. open price, close price, vwap price) |
For simulation purposes Bars and Ticks can be supplied through CSV files (see
Section 18.9, “Market Data File Format”) or through InfluxDB (see Chapter 18, Historical Data). In live trading Trades, Bids and Asks are
received by the broker / exchange specific
MarketDataService
.
For conversion between Ticks and Bars please see Section 17.1, “Creation of Bars based on Ticks”.
The following UML Class diagram shows the Order and its related subclasses.
Table 7.6. Order Classes
Entity | Description |
---|---|
Order | Base Class for all Order Types |
OrderStatus | Order Status changes received back from the Broker / Exchange
(e.g. PARTIALLY_EXECUTED or
CANCELLED ) are represented by this class |
OrderCompletion | Similar to Order Status but only gets created once an order is fully executed or cancelled and all corresponding database activity has been completed. |
OrderProperty | An 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. |
Fill | Filled orders are represented by this Class |
Transaction | Each 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 |
SimpleOrder | An Order that can be sent directly to the market |
MarketOrder | Predefined SimpleOrder
types |
LimitOrder | |
StopOrder | |
StopLimitOrder | |
AlgoOrder | A composite order that will generate multiple
SimpleOrders . An
AlgoOrder cannot be sent directly to
the market. AlgoOrders are also called
"Execution Algos", see Chapter 23, Execution Algos |
TWAPOrder | This algorithm aims to match the Time-Weighted Average Price |
VWAPOrder | This algorithm aims to match the Volume-Weighted Average Price |
TargetPositionOrder | This algorithm automatically manages orders to reach the specified target quantity. |
TrailingLimitOrder | This algorithm submits an order directly to the broker/exchange, with a limit price set a fixed distance from the current market price. |
SlicingOrder | An AlgoOrder , that will split a large
order into multiple child orders. The size of the child order,
time in the market and delay between orders are randomized
within the specified range. |
AlgoOrder
s and Order parent/child associations are
persisted to the database. After a system restart, pending
AlgoOrder
will be visible but it will not continue execution
automatically - it will not create new child orders. Execution reports for existing child orders will be processed.
An Account represents either an actual account, an account group (IB
specific) or an allocation profile (IB specific). An account is assigned to a
particular adapterType
(e.g.
IB_NATIVE
or FXCM_FIX
) which
identifies the OrderService
to use for this account. In
addition the field sessionQualifier
which is needed to define
the actual session in place (for FIX Connections). With this setup, it is
possible to have multiple Sessions (session qualifiers) per
AdapterType
and to have multiple Accounts per
Session. If the field active
is set to true a potential
corresponding Fix session will be activated.
Optionally an accountServiceType
(e.g.
IB_NATIVE
or BFX
) can be added which
identifies the AccountService
to use for this account.
Accounts have an optional dependency to Exchange for cases when an account can only be used to trade on one single Exchange (typical for Crypto Currency Exchanges).
Orders sent to the market will always contain Account related information in an adequate way (e.g. as a FIX Tag 1). Also Transactions which are based on an actual order will have an association with a particular Account. However Positions do not hold any information regarding Accounts. It is thus possible that a Position holds aggregated Quantities from several external Accounts. Also it is possible to open a position through on account but then close it through another (i.e. when using separate execution and clearing brokers). With this setup Strategies do not have to worry about the actual Accounts the funds are located in. This way, a strategy will always only see one Position per Security.
Each Fill is recorded as a transaction in the database using this
entity. In addition the table transaction also stores transactions like
INTREST
, DEBIT
,
CREDIT
& FEES
. A transaction is
immutable and contains all relevant information like
dateTime
, quantity
,
price
, executionCommissions
,
clearingCommissions
and fees
as well
as references to Account, Strategy, Security and Position.
Depending on the type of transaction the field quantity
has
the following values:
BUY: > 0
SELL: < 0
EXPIRATION: any value
TRANSFER : any value
CREDIT: 1
EXCHANGE_CREDIT: 1
INTREST_RECEIVED: 1
REFUND : 1
DIVIDEND : 1
DEBIT: -1
EXCHANGE_DEBIT: -1
INTREST_PAID: -1
FEES: -1 (+1 for maker FEES paid)
As the sign of the transaction is defined by the quantity
the fields
executionCommissions
,clearingCommissions
and fees
will always be positive for fees/commissions charged
(they will be negative for fees/commissions paid, e.g. maker rebates).
Some crypto exchanges provide fee information. If the fees are in the currency
of the transaction, they are stored in the fee
attribute of
the transaction. In case the fees are charged in another currency (for example
Binance charges in its own currency - BNB), a new transaction is created with
transactionType
= FEES, quantity
= -1
for fees paid (and quantity
= -1 for fees received, e.g.
maker rebates), price
= fee value and
currency
= fee currency.
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
Table 7.7. Position Valuation Details
Attribute | Description |
---|---|
realizedPL | Total profit of closed parts of a position (parts of a position might still be open) |
unrealizedPL | Profit of the currently open part of a position |
cost | Total cost incurred to open the current position (potentially through multiple orders). These values are based on the fee configurations |
All valuations (strategy and position level) are available through the Section 7.2.12, “Portfolio Service”.
A CashBalance
represents the current cash amount of a
particular strategy in a particular currency.
Cash Balances are derived by taking all Transactions of the given Security and Strategy into account. It is therefore important not to modify Cash Balance entries directly in the database. In case transactions are added or modified manually to the database, please the management action reset position and cash balances in the Figure 10.3, “AlgoTrader UI Management”
Market Data Subscriptions of a Strategy for particular Securities are
represented by this class. For every Subscription the Strategy will receive Live
Market Data for the corresponding Security
Exchanges around the world have different trading hours. Quit often there are different trading hours even for different securities trading on the same exchange. In addition each exchange typically has different holidays or days where trading starts late or trading stops early. Especially for futures trading there are often small gaps between different trading periods of the same trading date. FX trading is often available 24 hours a day without any gaps.
All of these scenarios are captured and maintained through the Entities
Exchange
, TradingHours
and
Holiday
:
Table 7.8. Exchange
Entity | Description |
---|---|
Exchange | Represents an individual Security, a group of Securities or an entire Exchange (if all Securities have the same trading hours). An Exchange has a name, a code (typically MIC) as well as a time zone. |
TradingHours | Defines an individual trading period (e.g. 09:00am to
16:30pm). In addition TradingHours
identify the weekdays they are valid for. |
Holiday | Identifies a holiday of a specific exchange. In addition a
Holiday can identify a late opening
or early closing of trading on a particular trading day. |
Table 7.9. Order Preference
Class | Description |
---|---|
OrderPreference | This class allows definition of order default values (e.g. account, order type, delays, etc.). Except for the order type, all values have to be defined through Properties. |
for further details see Section 16.2.1, “Order Preferences”
A request for quote (RfQ) is a process in which a company requests a quote from broker/exchange for the purchase or sale of a specific security.
Table 7.10. Quote Request and Quote
Class | Description |
---|---|
Quote_Request | This class allows definition of request sent to broker/exchange for the purchase or sale of specific security. |
Quote | This class represents response provided by broker/exchange for the quote request. |
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:
Main Services, are available to both the AlgoTrader Server and Strategies
Client Services, which will be instantiated by each Strategy (and the AlgoTrader Server itself)
Private Services, which are only used by the AlgoTrader Server
For a full list of all Services please visit our JavaDoc
Inside strategies all services are injected by the Spring Framework and can be accessed as follows withing the strategy service:
// subscribe for live market data
getSubscriptionService().subscribeMarketDataEvent(strategyName, securityId, adapterType);
// lookup a instrument by symbol
getLookupService().getSecurityBySymbol(symbol);
// send an order to the broker or exchange
getOrderService().sendOrder(order);
Table 7.11. Main Services
Service | Description |
---|---|
AccountService | Responsible for retrieval of account balances and initiation of withdrawals |
CalendarService | Responsible for information about Exchange trading hours and holidays |
CombinationService | Responsible for handling all Combination / Component related DB-Operations. |
FutureService | Responsible for all future specific operations |
HistoricalDataService | Responsible for the retrieval of historical data from Historical Data Providers |
MarketDataService | Responsible for the retrieval of market data as well as Subscription Management. |
MeasurementService | Responsible for persistence and retrieval of Measurements related to Strategy |
OptionService | Responsible for all option specific operations |
OrderService | Responsible for sending orders to the Broker / Exchange |
PortfolioService | Responsible for providing portfolio values |
PositionService | Responsible for management of positions, e.g. close position and reduce position |
PropertyService | Responsible for persistence of Properties related to a
PropertyHolder |
ReferenceDataService | Responsible for the download of option and future chains |
RfqService | Responsible for sending requests for quotes to the Broker / Exchange |
Table 7.12. Client Services
Service | Description |
---|---|
MarketDataCacheService | Provides a strategy local cache of market data and FX conversion rates |
LookupService | Provides general data lookup operations to other services |
ConfigAwareStrategyService | Base class for all strategy services which has references to all necessary services and implements all event listener interfaces. In addition the service receives a reference to the strategy config |
StrategyService | Base class for all strategy services which has references to all necessary services and implements all event listener interfaces |
SubscriptionService | This service is used by the strategy for subscription
management. The actual DB related operations are carried out by
the MarketDataService . The
MarketDataService should not be
called directly by strategies. |
The AccountService
interface defines a method for
retrieving account balances as well as the initiation of crypto withdrawals for
crypto exchanges. For further details see Chapter 20, Account Data.
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:
isOpen
(is the specified exchange open at the
current time or at the specified date time). Will return true if no
TradingHours
are defined
isTradingDay
(is the current day or the
specified day a trading day at the specified exchange)
getOpenTime
(gets the open time of the
specified exchange on the current day or the specified day)
getCloseTime
(gets the close time of the
specified exchange on the current day or the specified day)
getNextOpenTime
(gets the next open time of
the specified exchange after the current date time or the specified date
time)
getNextCloseTime
(gets the close open time of
the specified exchange after the current date time or the specified date
time)
In addition the Calendar service provides methods to identify a particular
trading day, which will be important to associate a particular order for
clearing. 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.
All dates and times in the CalendarService
are
converted to the system time, e.g. the market opens at 09:30 EST but the
system time zone is CET then the market opening time in the
CalendarService
will be 15:30.
When trading one single exchange it is usually easiest to set the system time to the same time zone of the exchange.
When trading exchanges in different time zones one has the choice of setting the system to clock to the same time zone as one of the exchanges or leave the system time set to the local time zone.
AlgoTrader supports Synthetic Securities & Derivative Spreads. A Combination consists of one or many Components. For further details see Chapter 24, Synthetic Securities and Derivative Spreads.
AlgoTrader has full support for Future based trading strategies. For further details see Chapter 14, Options & Futures
AlgoTrader provides several Historical Data Interfaces out-of-the-box. The system can store historical data in the integrated Section 18.1, “InfluxDB” and feed stored or recorded historical data to strategies during back tests. The system also integrates a feature for live data recording as well as live tick-to-bar aggregation. For further details please see Chapter 18, Historical Data
AlgoTrader provides several Market Data Interfaces out-of-the-box. Live market data is available to trading strategies running within the system. For further details please see Chapter 17, Market Data
The MeasurementService
allows storage of arbitrary
measurements in the database. Measurements contain a name, a time stamp and a
value of type Integer
, Double
,
Money
(BigDecimal
),
Text
(String
) or
Boolean
. Only one value is allowed per measurement (i.e. one record cannot
store both Integer and String values for example. In addition a Measurement also needs to have a
reference to a strategy.
A Measurement can be created as follows whereas the time stamp will be set according to the current system time:
getMeasurementService().createMeasurement(strategyName, "myMeasurement", 12.12345);
In addition a Measurement can also be created by providing an explicit time stamp:
ZoneDateTime zonedDateTime = ZonedDateTime.of(2019, 4, 1, 0, 0, 0, 0, ZoneId.of("UTC")); getMeasurementService().createMeasurement(strategyName, "myMeasurement", zonedDateTime, 12.12345);
A Measurement can be deleted by using the following method:
getMeasurementService().deleteMeasurement(measurementId);
To read Measurements from the database the Section 7.2.18, “Lookup Service”
has to be used which provides various Measurement lookup methods, e.g.
getMeasurementByMaxDate
or
getAllMeasurementsByMaxDate
.
Only one measurement entry per strategy and name is allowed for a given time stamp. If there is an existing measurement with matching strategy, name and time stamp then creating a new measurement with new value will overwrite the previous value.
Only one value per
AlgoTrader has full support for Option based trading strategies including an Option pricing engine. For further details see Chapter 14, Options & Futures
The OrderService
is responsible for sending orders to
brokers and exchanges in live trading as well as sending orders to the internal
Section 5.1, “Exchange Simulator” during back tests. For further details
please see Chapter 16, Order Management
Financial valuations (strategy and position level) are available through the
PortfolioService
.
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:
Security: VIX Dec 2012
Current Bid: 16.50
Current Ask: 16.60
Strategy A: quantity +10 -> market value: 10 * 1000 * 16.50 = 165'000
Strategy B: quantity -10 -> market value: 10 * 1000 * 16.60 = -166'000
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
).
Positions are derived by taking all Transactions of the given Security and Strategy into account. It is therefore important not to modify Position entries directly in the database. In case transactions are added or modified manually to the database, please the management action reset position and cash balances in the Figure 10.3, “AlgoTrader UI Management”
The PositionService
provides the following position
related methods:
closePosition
closes a single position
closeAllPositions
closes all positions in the
system
reducePosition
reduces a position by the
specified quantity
transferPosition
transfers a position from
one strategy to another
resetPositions
calculates all Position based
on Transactions in the database and makes adjustments if
necessary.
Closing and Reducing a position through the
PositionService
requires the definition of an
order_preference
with the name
DEFAULT
. Fur further details see Section 16.2.1, “Order Preferences”
The default order preference also includes an account, which means this feature is typically only usable with one account/adapter. If more than one account is in use, positions should be closes through the Section 7.2.11, “Order Service” by sending an order with a quantity that will offset the current position.
The PropertyService
can be used to assign arbitrary
properties to the following classes:
Account
Exchange
Order
OrderPreference
Position
Security
SecurityFamily
Strategy
Subscription
Transaction
These classes are derived from the abstract class
PropertyHolder
. One or more Properties can be
assigned to them. A Property can be any Java type (including
Integer
, Double
,
BigDecimal
, String
,
Date
, Boolean
, etc.) but also
arbitrary Java objects as long as the type implements
Serializable
Using the PropertyService
a Property can be added as
follows.:
getPropertyService().addProperty(StrategyImpl.class, 12, "myPropertyName", 12.12345);
The above example will add a Property named myPropertyName
and value = 12.12345 to Strategy with id = 12.
Adding a custom object (implementing Serializable) is possible also:
MyObject myObject = new MyObject("abc", 123, 22.44); getPropertyService().addProperty(StrategyImpl.class, 12, "myPropertyName", myObject);
A Property can be deleted by using the following method:
getPropertyService().removeProperty(StrategyImpl.class, 12, "myPropertyName");
Properties are available on the corresponding
PropertyHolder
objects as follows:
double value = strategy.getProperty("myDoubleProperty", Double.class);
// or
double value = (Double)strategy.getProperty("myTextProperty");
All properties assigned to a particular PropertyHolder
can be retrieved as follows:
Map<String, Object> properties = strategy.getProperties();
Amongst others reference Data consists of static data like
Security
, SecurityFamily
,
SecurityReference
, Account
Entities. Reference Data can either be configured in the database directly
through the corresponding tables, one can use the
ReferenceDataService
and corresponding
ReferenceDataStarter
, or conveniently the Reference Data Manager UI. For further details see Chapter 19, Reference Data
AlgoTrader supports Request for Quote process. The RfqService
provides the following methods:
sendRfq
sends a request for quote
getQuote
retrieves a quote if it hasn't expired
discardQuotes
discard quotes.
Accepting quote / placing order is possible with Order Service
similarly like in
Chapter 16, Order Management. Use PreviouslyIndicatedOrderVOBuilder
and method setQuoteId
to link the order to the received quote.
The MarketDataCacheService
is intended to
provide current market data and exchange rates to the strategy. the
MarketDataCacheService
keeps a local copy of
each subscribed Security.
To access the last traded price of an instrument one can use the following code inside strategies:
TickVO tick = (TickVO)getMarketDataCacheService().getCurrentMarketDataEvent(securityId);
BigDecimal lastPrice = tick.getLast();
To access the access the current exchange rate between USD and EUR one can use the following code inside strategies:
double rate = getMarketDataCacheService().getForexRate(Currency.USD, Currency.EUR);
the LookupService
provides a large number of lookup
methods for all objects available in the database. Examples:
getSecurityBySymbol
gets a security by its
symbol
getExchangeByCode
gets an Exchange by its
exchange code
getPositionBySecurityAndStrategy
gets a
Position by Security and Strategy
getOpenPositionsByStrategy
gets open
Positions for the specified Strategy
getAccountByName
gets an Account by its
name
In addition to standard lookup methods above the
LookupService
also provides the following the generic
lookup methods find
and
findUnique
that can be used in situations where a
standard lookup method is not available. These methods can be used as
follows:
String query = "from StrategyImpl where name = :strategyName"; NamedParam param = new NamedParam("strategyName", "ABC"); Strategy strategy = getLookupService().find(Strategy.class, query, QueryType.HQL, false, param);
Please consult the JavaDoc for a full list of available methods.
In order to minimize the number of hits to the database the
LookupService
uses various levels of caching when
reading from the database.
All strategy main classes need to either extend
StrategyService
or
ConfigAwareStrategyService
. The
ConfigAwareStrategyService
provides the same
functionality as the StrategyService
but in addition also
provides a reference to the strategy config object. For further details see
Chapter 4, Strategy Development.
The Subscription service allows a strategy to subscribe for market data. For that purpose the service provides several methods:
To subscribe for market data use the following method:
getSubscriptionService().subscribeMarketDataEvent(strategyName, securityId, adapterType);
The adapterType
specifies the adapter to use when
subscribing for market data (e.g. IB_NATIVE
specifies the
InteractiveBrokers native API adapter)
Upon subscription market data will be feed to the trading strategy that
initiated the market data subscription. Market data will be feed to the
corresponding Section 4.3.1.2, “Event Handler Methods” (e.g.
onBar
and onTick
) and also
into the Esper Engine (if using Esper) where they are available as
Bar
and Tick
events.
To unsubscribe market data use the following method:
getSubscriptionService().unsubscribeMarketDataEvent(strategyName, securityId, adapterType);
The SubscriptionService
also supports the subscription
for GenericEvents
, see Section 17.6, “Generic Events”
The ResetService
can be used to reset the state of the
database to a pre-defined state either before a simulation or if a reset of live
trading is required.
To reset a live trading system multiple types of resets can be specified to
the reset
method using the Enumeration
ResetType
deletes all transactions (except the initial CREDIT)
resets all cash balances (except the one associated with the initial CREDIT)
deletes all non-persistent positions and resets all persistent ones
delete all orders, order stats as well as order properties
deletes non-persistent subscriptions
deletes non-persistent combinations and components
deletes non-persistent properties
deletes measurements
deletes portfolio values
deletes all options
deletes all futures
deletes all bar and tick data
The method resetSimulation
will reset the following
items before each Simulation: Trades, Subscriptions, Combinations/Components,
Properties, Options (if option prices are simulated) and Futures (if future
prices are simulated).
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();
For a full list of all Value Objects please visit our JavaDoc
For selectable items with a fixed number of choices AlgoTrader contains Java 5 Enumerations. For a full list of all Enumerations please visit our JavaDoc