B2BITS FIX Antenna C++  2.28.0
Basic Concepts

Table of Contents

Main components

The main FIX Antenna components are:

Engine description

The engine is represented by the Engine::FixEngine class. This class is responsible for:

Engine initialization is performed using the void Engine::FixEngine::init() method. This method must be called before any other FIX Antenna methods. At the end of the process void Engine::FixEngine::destroy() method must be called to deallocate the consumed resources.

For example:

#include <iostream>
#include <B2BITS_V12.h>
using namespace std;
int main(int argc, char* argv[]) {
try {
// initialization
// ... - main functionality
// destruction
}
catch(const Utils::Exception& ex) {
cout << "EXCEPTION: " << ex.what() << endl;
}
return 0;
}

The Engine::FixEngine class, as well as several other FIX Antenna C++ API classes, implements the Singleton Design Pattern. Therefore you should, first of all, get a pointer to the instance of the class, using the FixEngine* Engine::FixEngine::singleton() static method to access non-static methods of the class.

For example:

FixEngine::singleton()->createSession(...)

Sessions Manager

The Sessions Manager manages the creation of unregistered acceptor sessions. When CreateUnregisteredAcceptorSession is set to true, engine accepts all incoming logons and creates session acceptors. It is possible though to implement custom logic and introduce more sophisticated criteria of accepting such sessions. To do this, you need to create and register your own instance of Sessions Manager.

Create a class derived from the Engine::SessionsManager class and override the Engine::SessionsManager::onUnregisteredAcceptor() method to control acceptor session creation. Return "true" if you agree with the creation of unregistered acceptor; otherwise return "false".

Use Engine::FixEngine::registerSessionsManager() method to register custom Sessions Manager. Only one Sessions Manager can be registered to the FIX Engine.

For example:

class SsnManager : public Engine::SessionsManager{
public:
virtual bool onUnregisteredAcceptor(Session* pSn, const FIXMessage& logonMsg) {
clog << "Incoming logon: " << *logonMsg.toString() << endl;
return true;
}
};
// The FixEngine initialization
FixEngine::init("engine.properties");
// create and register SessionsManager
SsnManager *g_mySM = new SsnManager();
FixEngine::singleton()->registerSessionsManager(g_mySM);
...
// unregister and destroy SessionsManager
FixEngine::singleton()->registerSessionsManager(NULL);
delete g_mySM;
// destruct FixEngine
FixEngine::destroy();
Warning
Do not delete the registered sessions’ manager until you unregister it.

Session description

The FIX session is represented by the Engine::Session class. This class is responsible for:

In earlier versions of FIX Antenna (2.10.14 and earlier) Session object could be uniquely identified by SenderCompId/TargetCompId pair. Starting from version 2.10.15.5 extra string identifier - SessionQualifier has been introduced in addition to SenderCompId/TargetCompId pair. The idea is to give user ability to create several sessions with the same SenderCompId and TargetCompId and to give ability to address these sessions by unique ID. See Session identifier for more details.

Each session encapsulates message storage that is used to store the sent and received messages. There are two types of storages:

Unregistered acceptors

When engine receives FIX logon message it extracts SenderCompID and TargetCompID fields from the message and tries to find previously created acceptor with corresponding session ID (i.e. session SenderCompID equal to TargetCompID extracted from message and session TargetCompID equal to the SenderCompID extracted from messages). Refer to the FIX Session Acceptor for more information about how to create session acceptor. If engine cannot find corresponding acceptor the incoming logon is declined and connection is not established.

Engine though can also work in "trusted mode" i.e. if corresponding session acceptor cannot be found then session is created automatically. To enable this mode set CreateUnregisteredAcceptorSession property to "true" (refer to the section Common parameters for more details about property).

Application description

The Application class is responsible for:

Create a new class derived from the Application class and override the Application::process method in this class to process incoming messages. Then pass the instance of your class to the session to start receiving incoming messages.

Engine delivers incoming messages to the Application by calling Application::process method and analyzing its return value to make sure that incoming message was processed and Application is ready to process next incoming message.

If the Engine::Application::process method does not return "true" (i.e. returns "false" or throws an exception), the engine passes the same incoming message to the Application::process again and again until either Application::process returns "true" or number of attempts is exceeded (DelayedProcessing.MaxDeliveryTries, refer to Common parameters for more information). The interval between attempts is specified by property DelayedProcessing.DeliveryTriesInterval (refer to Common parameters for more information). If the number of unsuccessful attempts exceeds the MaxDeliveryTries, a Logout message with the reason "Application is not available" is sent to the counterparty and session is closed.

Other useful methods to override are: onLogonEvent, onLogoutEvent, onSequenceGapEvent, onSessionLevelRejectEvent, etc. These are the call-back methods called to notify about the corresponding session-level events. Note that all pure virtual methods of Application must be overridden (implementation can be just empty body).

The Engine::Application::process method is called only when application-level message is received. All session-level messages (Heartbeats, Test Requests, Resend Requests, etc.) are handled by FIX Antenna. However you can modify default behavior overriding call-back methods in Application and providing your own logic.

Note
if you need to keep FIX message for future processing create a copy of the message and save a copy instead of saving original message (refer to the Engine::FIXMsgProcessor::clone method).

Below is an example of custom implementation of Application interface:

class Appl : public Engine::Application{
public:
virtual bool process(const FIXMessage & aMsg, const Engine::Session& aSn) {
clog << "aMsg: " << *aMsg.toString() << endl;
return true;
}
virtual void onLogonEvent(const LogonEvent* apEvent, const Session& aSn) {
clog << "LogonEvent, the Logon message was received: " << apEvent->m_pLogonMsg->toString() << endl;
}
virtual void onLogoutEvent(const LogoutEvent* apEvent, const Session& aSn) {
clog << "LogoutEvent, the Logout message was received: " << apEvent->m_pLogoutMsg->toString() << endl;
}
virtual void onSequenceGapEvent(const SequenceGapEvent* apEvent, const Session& aSn) {
clog << "SequenceGapEvent" << endl;
}
virtual void onSessionLevelRejectEvent(const SessionLevelRejectEvent* apEvent, const Session& aSn) {
clog << "SessionLevelRejectEvent" << endl;
}
virtual void onMsgRejectEvent(const MsgRejectEvent* event, const Session& sn){
clog << "MsgRejectEvent" << endl;
}
virtual void onResendRequestEvent(const ResendRequestEvent &,const Session &) {
clog << "ResendRequestEvent" << endl;
}
virtual void onNewStateEvent(const NewStateEvent &,const Session &) {
clog << "NewStateEvent" << endl;
}
virtual void onUnableToRouteMessage(const UnableToRouteMessageEvent &,const Session &) {
clog << "UnableToRouteMessage" << endl;
}
virtual bool onResend(const FIXMessage &,const Session &) {
clog << "Resend" << endl;
return true;
}
virtual void onHeartbeatWithTestReqIDEvent(const HeartbeatWithTestReqIDEvent &,const Session &) {
clog << "HeartbeatWithTestReqIDEvent" << endl;
}
};
Note
It is not recommended to put lock inside the Application::process, synchronize different call-back methods unless you are absolutely confident in what you are doing. Also it is not recommended to perform time-consuming operations inside Application::process as it blocks receiving following messages.
If a pointer to the same Application is sent to several sessions, being established, synchronize the Application::process() method.
Warning
Do not delete the registered Application until you unregister it.

Message description

The FIX message (specified by the FIX protocol) is represented by the Engine::FIXMessage class.

The Engine::FIXMessage class provides the following functionality:

Repeating Groups description

Please read the FIX Protocol explanation of the Repeating group first (refer to the section About FIX messages).

The FIX message may contain repeating groups. Each group contains:

Repeating groups are usually referred by the leading tag.

To add new group to the message you simply should add leading field to the message. In the result the new group will be added with the number of entries according to the value of leading field.

To access fields inside a repeating group you should

To resize group simply modify the value of leading tag. Pay attention that this operation re-creates the group so you should populate values again.

To remove group simply remove leading tag from the message.

Session Controller

Engine::SessionsController class introduces interface to abstract basic session management operations like start/stop/connect/disconnect. It easies sessions management implementation and can be used as general sessions owner in application.

FixAntenna provides built-in default implementation (FixEngineSessionsController) that uses FixEngine as underlying layer to control sessions. See Scheduler for samples.

Scheduler

Basic concept

FIX Antenna-based applications are widely used to connect to venues and trading platforms. The built-in scheduling functionality is designed to deal with the periodic nature of these venues, for example, the trading day or trading week. To provide maximum flexibility for customers, the generic scheduler that is implemented in FIX Antenna (hereafter Scheduler) allows customers to use it for actions that are initiated by time-dependent events. Customers can use it together with the FIX Antenna Engine (to schedule sessions) or for other purposes.

When using the Scheduler together with FIX Antenna (to schedule sessions), a Scheduler instance is created by the Engine if no Scheduler instance is provided by the user via the FixEngine::InitParams::pScheduler_ member.

Note
Scheduler state after engine initialization: After Engine initialization, regardless of whether a Scheduler instance was created by the Engine or provided by the user, the Scheduler instance is in the stopped state and the user has to start it explicitly.

To use the Scheduler, the user must create schedules (usually periodic ones, for example, every day at 9:30 AM), that define the timeline of events. The user can create schedules by defining them in the engine.properties file or via API (refer to subsection Scheduler API examples for more details). If the engine.properties file is used to configure schedules, the Engine creates the schedules defined during initialization and puts them onto the Scheduler but sessions are not added to the schedules. The user must add sessions to particular schedules with her/his own code after the Engine starts, and start the Scheduler explicitly. The reason behind this is that every session requires the Engine::Application callback sink to be defined to serve business needs that are not feasible for the Engine to have during initialization.

To see how to bind sessions to schedules using the schedule property, see the FA Scheduler documentation QuickStart Guide.

General design

There are 4 major types of objects that define the Scheduler feature:

  1. Scheduler - a main events execution component. It schedules events as required and notifies schedules when needed about events that have occurred.
  2. Schedule - an integral object that represents the schedule. It maintains schedule configuration along with other objects required for the schedule to operate like a session controller and timeline event generator.
  3. Session controller - the owner of one or multiple sessions. The session controller allows users to start, stop, connect, and disconnect sessions via ID. In order to add a session to a schedule, the session should be added to the session controller that corresponds to the desired schedule. By default, the session controller has ownership over the sessions that it starts. If a user starts a session and then registers it with the session controller, the user delegates ownership over the session to the session controller, in which case the controller manages the session, including stopping the session. In both of these cases, the user can request the active session pointer from the session controller when needed.
  4. Timeline generator - an object that generates next or previous events for the schedule. The schedule object maintains the timeline generator instance for the schedule. The Scheduler requests this instance from the schedule object as needed and requests the next event.

All these objects are defined as abstract interfaces. FIX Antenna C++ provides default implementation for all of these objects as follows:

One can define his/her own implementations, for example, a generator that defines timeline events that uses something other than the cron format, and use them along with those provided in FIX Antenna C++.

Engine::SessionsSchedule allows a user to set up an events callback sink (an instance derived from Engine::SessionsScheduleManager, see the API Guide for details) whose methods are invoked when TradePeriodBegin/TradePeriodEnd events happen or an exception was raised while events were being executed.

The user can modify an execution plan for every event to change the default Engine::SessionsSchedule behavior, see the details below.

The provided implementations define two types of time events and the session schedule's reactions to them:

  1. TradePeriodBegin - Defines the point in time indicating the beginning of the trading period. The Engine::SessionsSchedule reacts to this event with the following actions:
    • a. Gets a session list from the corresponding Engine::SessionsController.
    • b. Forms an execution plan as follows: puts the Start action to every session in the execution plan list, then puts the Connect action to every session in the execution plan list.
    • c. Calls the onTradePeriodBegin method of the instance derived from the corresponding Engine::SessionsScheduleManager, if so set by the user.
    • d. Executes the execution plan (whether modified in the previous step or not) and invokes the methods of the corresponding Engine::SessionsController instance.
  2. TradePeriodEnd - Defines the point in time indicating the end of the trading period. Engine::SessionsSchedule reacts to this event with the following actions:
    • a. Gets a Sessions list from the corresponding Engine::SessionsController.
    • b. Forms an execution plan as follows: adds the Disconnect action to every session in the execution plan list, then adds the Stop action to every session in the execution plan list.
    • c. Calls the onTradePeriodEnd method of the instance derived from the corresponding Engine::SessionsScheduleManager, if so set by the user.
    • d. Executes the execution plan (whether modified in the previous step or not) and invokes the methods of the coresponding Engine::SessionsController instance.

After the above is complete, the System::SchedulerImpl retrieves the timeline generator instance from the schedule, asks it for the next event, and schedules the event it received. After the scheduled event time passes, everything repeats.

Configuration

There are two ways to configure the session schedule: by using the engine.properties file or by using an API.

Configuring by engine.properties file

To create a schedule from engine.properties, the user must define the parameters as represented in the table below::

Parameter Description
TimezoneDB Timeline CSV file where all valid time zones are defined. Generic name of timeline file: date_time_zonespec.csv
Note
Path to the timeline file in the FIX Antenna package: <Package>/data/date_time_zonespec.csv
No, Scheduler works in UTC only
Schedule.<schedule_name>.TradePeriodBegin Timetable for the beginning of the trade day. Defined in the cron format.
<schedule_name> is the schedule name.
Yes
Schedule.<schedule_name>.TradePeriodEnd Timetable for the ending of the trade day. Defined in the cron format.
<schedule_name> is the schedule name.
Yes
Schedule.<schedule_name>.Timezone Selects a time zone defined in the TimezoneDB property pointing file to use with the schedule.
<schedule_name> is the schedule name.
Note
All possible values can be found in the file that the TimezoneDB property points to. See <Package>/data/date_time_zonespec.csv in the FIX Antenna package.
No, UTC by default
Schedule.<schedule_name>.LateExecution Set to 'true' to forcefully trigger the TradePeriodBegin event or to 'false' to avoid forceful triggering of the TradePeriodBegin event.
When set to true, forcefully triggers the trade period begin event when the application's start occurred inside the trading period (between TradePeriodBegin and TradePeriodEnd).
No, false by default
Schedule.<schedule_name>.DayOffs Defines a cron expression when events are not triggered (for example, holidays when the venue does not work). Defined in the cron format.
<schedule_name> is the schedule name.
Note
dayoffs - is a cron expression like others. If the following event matches the dayoffs expression, it is considered to be a day off, and the schedule is not notified about the event. When this occurs, the Scheduler asks the timeline generator for the next event.
No, no day-offs then

Example of a schedule defined within the engine.properties file:

Schedule.sch1.TradePeriodBegin = 0 0 1 ? * *
Schedule.sch1.TradePeriodEnd = 0 0 23 ? * *
Schedule.sch1.DayOffs = * * * ? * SUN,SAT
Schedule.sch1.Timezone = Europe/Samara
Schedule.sch1.LateExecution = true
Session.ESVR/GTF.Schedule = sch1
TimezoneDB = date_time_zonespec.csv

Example of a timeline file with available time zones. Location:<Package>/data/date_time_zonespec.csv in the FIX Antenna package.

ID,STD ABBR,STD NAME,DST ABBR,DST NAME,GMT offset,DST adjustment,DST Start Date rule,Start time,DST End date rule,End time
Africa/Abidjan,GMT,GMT,,,+00:00:00,+00:00:00,,,,+00:00:00
Africa/Accra,GMT,GMT,,,+00:00:00,+00:00:00,,,,+00:00:00
Africa/Addis_Ababa,EAT,EAT,,,+03:00:00,+00:00:00,,,,+00:00:00
Africa/Algiers,CET,CET,,,+01:00:00,+00:00:00,,,,+00:00:00
Africa/Asmara,EAT,EAT,,,+03:00:00,+00:00:00,,,,+00:00:00
Africa/Asmera,EAT,EAT,,,+03:00:00,+00:00:00,,,,+00:00:00
Africa/Bamako,GMT,GMT,,,+00:00:00,+00:00:00,,,,+00:00:00
Africa/Bangui,WAT,WAT,,,+01:00:00,+00:00:00,,,,+00:00:00
Africa/Banjul,GMT,GMT,,,+00:00:00,+00:00:00,,,,+00:00:00
Africa/Bissau,GMT,GMT,,,+00:00:00,+00:00:00,,,,+00:00:00
Africa/Blantyre,CAT,CAT,,,+02:00:00,+00:00:00,,,,+00:00:00
Africa/Brazzaville,WAT,WAT,,,+01:00:00,+00:00:00,,,,+00:00:00
Africa/Bujumbura,CAT,CAT,,,+02:00:00,+00:00:00,,,,+00:00:00
Africa/Cairo,EET,EET,,,+02:00:00,+00:00:00,,,,+00:00:00
...

Scheduler API examples

The user can create a schedule from the application by using an API:

Engine::CronSessionsScheduleParameters timeGeneratorParams( "0 30 7 ? * *", "0 30 18 ? * *", "* * * ? * SUN,SAT", "Europe/Warsaw", false, FixEngine::singleton()->getProperties()->getTimezoneConverter() );
System::SchedulePtr pSchedule( new Engine::SessionsSchedule( "1", pCronGenerator, pController ) );

To attach a schedule to the Scheduler use:

pScheduler->registerSchedule( pScheduler );

To remove a schedule from the Scheduler use:

pScheduler->unregisterSchedule( "1" );
// Remove all schedules at once
pScheduler->unregisterAll();
// Remove schedule if having it instance pointer
pScheduler->unregisterSchedule( pSchedule->getScheduleId() );

To get a list of schedules use:

System::Scheduler::Schedules schedules = pScheduler->getSchedules();
// Iterate over schedules list
for(System::Scheduler::Schedules::const_iterator it = schedules.begin(); it != schedules.end(); ++it)
{
// Do whatever you need here.
it->second->getScheduleId();
}

Sessions Schedule Manager

Engine::SessionsScheduleManager is an interface that introduces API contract of Sessions Schedule Manager which is integrated into the schedule object.

Sessions Schedule Manager is defined by the user and is passed to the schedule to receive notifications about TradePeriodBegin and TradePeriodEndevent events, and to get the execution plan.

class MySessionsScheduleManager: public Engine::SessionsScheduleManager, public Utils::ReferenceCounter
{
public:
MySessionsScheduleManager(const std::set<Engine::SessionId>& bannedSessons, const std::set<Engine::SessionId>& noTerminateSessons)
:bannedSessons_(bannedSessons)
,noTerminateSessons_(noTerminateSessons)
{
}
bool checkBanned(const std::pair<Engine::SessionId, ScheduleSessionActions>& pair)
{
return bannedSessons_.find(pair.first) != bannedSessons_.end();
}
bool checkNoTerminate(const std::pair<Engine::SessionId, ScheduleSessionActions>& pair)
{
std::set<Engine::SessionId>::const_iterator item = noTerminateSessons_.find(pair.first);
return noTerminateSessons_.find(pair.first)!= noTerminateSessons_.end() && pair.second == ScheduleSessionActions_Terminate;
}
{
std::remove_if(executionPlan.begin(), executionPlan.end(), boost::bind(&MySessionsScheduleManager::checkBanned, this, _1));
};
virtual void onTradePeriodEnd(Engine::ScheduleExecutionPlan& executionPlan)
{
std::remove_if(executionPlan.begin(), executionPlan.end(), boost::bind(&MySessionsScheduleManager::checkBanned, this,_1));
std::remove_if(executionPlan.begin(), executionPlan.end(),boost::bind(&MySessionsScheduleManager::checkNoTerminate, this,_1));
};
private:
std::set<Engine::SessionId> bannedSessons_;
std::set<Engine::SessionId> noTerminateSessons_;
};
void applicationMain(std::string const& aPropertiesFileName)
{
// Initialize FE
FixEngine::init( aPropertiesFileName );
// Get Scheduler instance
// Create FixEngine based SessionsController instance
// Create Cron based timeline generator instance
System::ScheduleTimelinePtr pTimeLine(new Engine::CronSessionScheduleTimeline(Engine::CronSessionsScheduleParameters("0 0 7 * * *", "0 0 18 * * *", "", "Europe/Warsaw", true, FixEngine::singleton()->getProperties()->getTimezoneConverter())));
// Create SessionsSchedule instance
Engine::SessionsSchedule* pSessionsSchedule = new Engine::SessionsSchedule("sch1", pTimeLine, pSessionController);
// Populate data for MySessionsScheduleManager configuration
std::set<Engine::SessionId> banned;
banned.insert(Engine::SessionId("Sender3", "Target3"));
banned.insert(Engine::SessionId("Sender4", "Target4"));
std::set<Engine::SessionId> noTerminate;
noTerminate.insert(Engine::SessionId("Sender5", "Target5"));
noTerminate.insert(Engine::SessionId("Sender6", "Target6"));
// Create MySessionsScheduleManager instance
pMyManager.reset(new MySessionsScheduleManager(banned, noTerminate));
// Attach MySessionsScheduleManager to the schedule used.
pSessionsSchedule->attachScheduleManager(pMyManager.get());
// Register the schedule within Scheduler.
scheduler.registerSchedule(SchedulePtr(pSessionsSchedule));
// The schedule is placed onto the scheduler now.
}

ConnectToGateway sample

The example of using the scheduling functionality can be found in the ConnectToGateway sample which is part of the FIX Antenna C++ package.

The sample demonstrates how a FIX Antenna C++ user can connect to the FIX Gateway (venue) and send pre-loaded messages.

The features implemented in the sample:

Troubleshooting

If the schedule configured via the engine.properties file can't be created, engine initialization will fail with the exception of describing the issue.

For example, Schedule sch1 parameter TradePeriodBegin is mandatory!

If the schedule is created via API, an exception is raised if anything goes wrong while describing the issue happened.

All exceptions have self-describing text along with the error code attached. Refer to: System::SchedulerException::ErrorCode

Here are some examples:

If an error in cron format is detected, an exception is raised describing the issue. This scenario will result in the same behavior that would occur if a schedule couldn't be created.

Samples:

If there are errors in the engine.properties configuration, engine initialization will fail with the exception of describing the issue.

If there are issues while binding sessions to the schedule (sessions controller to be more precise), the exception is thrown describing the issue happened.

All error texts are self-describing, see some samples below: