OnixS C++ FIX Engine 4.14.0
Users' manual and API documentation
Loading...
Searching...
No Matches
Common Sample Files

Common source code for samples.

Source code

Helpers.h

#include <OnixS/FIXEngine/FIX/FIX44.h>
#include <stdio.h>
#include <cerrno>
#include <cstdlib>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <exception>
#include <stdexcept>
#include <cassert>
#include <string>
#include <cstdarg>
#ifdef _WIN32
# include <conio.h>
# include <ctype.h>
# include <io.h>
#else
# include <pthread.h>
# include <csignal>
# include <cstdlib>
# include <termios.h>
# include <unistd.h>
# include <vector>
#endif
#ifndef _WIN32
#include <sys/poll.h>
#endif
#ifndef _WIN32
// The code below illustrates how to manage signals:
// - Mask signals in all threads;
// - Start a separate thread to catch signals;
class SignalHelper
{
public:
using SuppressedSignals = std::vector<int>;
static void manageLinuxSignals()
{
SuppressedSignals suppressedSignals;
// Add signals we are waiting for.
suppressedSignals.push_back(SIGPIPE);
pthread_t signalThreadId;
int status;
// Mask signals in the primary thread.
// Child threads will inherit this signal mask.
sigemptyset(&signalSet());
for(const auto signal : suppressedSignals)
sigaddset(&signalSet(), signal);
status = pthread_sigmask(SIG_BLOCK, &signalSet(), nullptr);
if (status != 0)
errorAbort(status, "Set signal mask");
// Create the sigwait thread.
status = pthread_create(&signalThreadId, nullptr, signalWaiter, nullptr);
if (status != 0)
errorAbort(status, "Create signalWaiter");
}
private:
[[noreturn]]
static void errorAbort(int status, const char* reason)
{
printf("Aborted due to status %d: %s\n", status, reason ? reason : "no error message");
exit(1);
}
[[noreturn]]
static void* signalWaiter(void*)
{
int signalNumber;
while (true)
{
sigwait(&signalSet(), &signalNumber);
printf("Signal %d received and suppressed.\n", signalNumber);
}
}
static sigset_t& signalSet()
{
static sigset_t set;
return set;
}
};
#endif
inline
void manageLinuxSignals()
{
#ifndef _WIN32
SignalHelper::manageLinuxSignals();
#endif
}
class EngineShutdownGuard
{
public:
explicit EngineShutdownGuard(OnixS::FIX::ISessionReactor * reactor = nullptr) :
reactor_(reactor)
{
}
~EngineShutdownGuard() noexcept
{
const CleanupMode cleanupMode = currentCleanupMode();
shutdownEngine(cleanupMode);
quiesceReactor(cleanupMode);
}
private:
enum CleanupMode
{
NormalExit,
ExceptionExit
};
enum
{
ReactorShutdownTimeoutSeconds = 30
};
static CleanupMode currentCleanupMode() noexcept
{
#if defined(__cpp_lib_uncaught_exceptions)
return std::uncaught_exceptions() > 0 ? ExceptionExit : NormalExit;
#else
return std::uncaught_exception() ? ExceptionExit : NormalExit;
#endif
}
static void failCleanup(CleanupMode cleanupMode) noexcept
{
if(cleanupMode == NormalExit)
std::_Exit(EXIT_FAILURE);
}
static void shutdownEngine(CleanupMode cleanupMode) noexcept
{
try
{
}
catch(const std::exception & ex)
{
std::clog << "Engine shutdown failed during cleanup: " << ex.what() << std::endl;
failCleanup(cleanupMode);
}
catch(...)
{
std::clog << "Engine shutdown failed during cleanup with an unknown error." << std::endl;
failCleanup(cleanupMode);
}
}
void quiesceReactor(CleanupMode cleanupMode) noexcept
{
if(reactor_ == nullptr)
return;
try
{
const OnixS::FIX::SecondSpan timeoutSpan(ReactorShutdownTimeoutSeconds);
OnixS::FIX::TimeoutTimer timeout(timeoutSpan);
while(!reactor_->isQuiescent() && !timeout.elapsed())
reactor_->dispatchEvents();
if(!reactor_->isQuiescent())
{
std::clog << "Reactor did not become quiescent during cleanup." << std::endl;
failCleanup(cleanupMode);
}
}
catch(const std::exception & ex)
{
std::clog << "Reactor cleanup failed: " << ex.what() << std::endl;
failCleanup(cleanupMode);
}
catch(...)
{
std::clog << "Reactor cleanup failed with an unknown error." << std::endl;
failCleanup(cleanupMode);
}
}
OnixS::FIX::ISessionReactor * reactor_;
EngineShutdownGuard(const EngineShutdownGuard &);
EngineShutdownGuard & operator=(const EngineShutdownGuard &);
};
#ifdef _WIN32
inline
HANDLE redirectedInputHandle(DWORD& inputType)
{
HANDLE inputHandle = reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(stdin)));
if(inputHandle == INVALID_HANDLE_VALUE)
return INVALID_HANDLE_VALUE;
inputType = GetFileType(inputHandle);
if(inputType == FILE_TYPE_UNKNOWN && GetLastError() != NO_ERROR)
return INVALID_HANDLE_VALUE;
return inputHandle;
}
inline
void readRedirectedPipeByte(HANDLE inputHandle)
{
char input;
DWORD readByteCount = 0;
const DWORD inputSize = sizeof(input);
// Keep pipe reads on the Win32 layer so the CRT cannot hide buffered bytes.
ReadFile(inputHandle, &input, inputSize, &readByteCount, nullptr);
}
#endif
inline
void waitForAnyKey(const std::string& waitText = std::string())
{
const unsigned int inputSettleDelayMilliseconds = 1000;
OnixS::Threading::ThisThread::sleep(inputSettleDelayMilliseconds);
if(!waitText.empty())
std::clog << std::endl << waitText << std::endl;
#ifdef _WIN32
if(!_isatty(_fileno(stdin)))
{
DWORD inputType = FILE_TYPE_UNKNOWN;
HANDLE inputHandle = redirectedInputHandle(inputType);
if(inputHandle == INVALID_HANDLE_VALUE)
return;
if(inputType == FILE_TYPE_PIPE)
{
readRedirectedPipeByte(inputHandle);
return;
}
std::getchar();
return;
}
_getch();
// Discard bytes already queued by an extended or repeated keypress.
while(_kbhit())
_getch();
#else
if(!isatty(STDIN_FILENO))
{
std::getchar();
return;
}
class TerminalModeGuard
{
public:
explicit TerminalModeGuard(int descriptor) :
descriptor_(descriptor)
{
if(tcgetattr(descriptor_, &originalAttributes_) != 0)
throw std::runtime_error("Cannot read terminal attributes.");
termios singleKeyAttributes = originalAttributes_;
singleKeyAttributes.c_lflag &= static_cast<tcflag_t>(~(ICANON | ECHO));
singleKeyAttributes.c_cc[VMIN] = 1;
singleKeyAttributes.c_cc[VTIME] = 0;
if(tcsetattr(descriptor_, TCSANOW, &singleKeyAttributes) != 0)
throw std::runtime_error("Cannot enable single-key terminal input.");
}
~TerminalModeGuard()
{
tcsetattr(descriptor_, TCSANOW, &originalAttributes_);
}
private:
int descriptor_;
termios originalAttributes_;
};
TerminalModeGuard terminalMode(STDIN_FILENO);
char input;
const size_t inputSize = sizeof(input);
ssize_t readResult;
do
{
readResult = read(STDIN_FILENO, &input, inputSize);
}
while(readResult < 0 && errno == EINTR);
// Match the previous getchar() behavior when the terminal reaches a real EOF.
if(readResult == 0)
return;
if(readResult != static_cast<ssize_t>(inputSize))
throw std::runtime_error("Cannot read terminal input.");
// Best-effort cleanup: sequence bytes that have not arrived yet cannot be discarded.
tcflush(STDIN_FILENO, TCIFLUSH);
#endif
}
inline
bool keyPressed()
{
#ifdef _WIN32
if(_isatty(_fileno(stdin)))
return _kbhit() != 0 ? _getch(), true : false;
DWORD inputType = FILE_TYPE_UNKNOWN;
HANDLE inputHandle = redirectedInputHandle(inputType);
// Closed or unavailable redirected input is equivalent to a request to continue.
if(inputHandle == INVALID_HANDLE_VALUE)
return true;
if(inputType == FILE_TYPE_PIPE)
{
DWORD availableByteCount = 0;
if(!PeekNamedPipe(inputHandle, nullptr, 0, nullptr, &availableByteCount, nullptr))
return true;
if(availableByteCount == 0)
return false;
// A character, EOF, or a concurrent pipe closure releases a non-interactive sample.
readRedirectedPipeByte(inputHandle);
return true;
}
// A character or EOF both release a non-interactive sample.
std::getchar();
return true;
#else
pollfd pfd = { STDIN_FILENO, POLLIN, 0 };
if(poll(&pfd, 1, 0) <= 0)
return false;
if(pfd.revents & (POLLHUP | POLLERR | POLLNVAL))
return true;
if(!(pfd.revents & POLLIN))
return false;
std::getchar();
return true;
#endif
}
inline
void setOrderFields(OnixS::FIX::Message* order)
{
order->set(OnixS::FIX::FIX44::Tags::HandlInst, OnixS::FIX::FIX44::Values::HandlInst::AutoExecPriv)
.set(OnixS::FIX::FIX44::Tags::ClOrdID, "Unique identifier for Order")
.set(OnixS::FIX::FIX44::Tags::Symbol, "IBM")
.set(OnixS::FIX::FIX44::Tags::Side, OnixS::FIX::FIX44::Values::Side::Buy)
.set(OnixS::FIX::FIX44::Tags::OrderQty, 1000)
.set(OnixS::FIX::FIX44::Tags::OrdType, OnixS::FIX::FIX44::Values::OrdType::Market)
}
inline
void processSampleException(const std::string & exceptionText)
{
std::cerr << "EXCEPTION: " << exceptionText << std::endl;
#ifdef _WIN32
if(exceptionText.find("System error code = 10013") != std::string::npos)
{
std::clog << "The socket is already in use, or access to the port is restricted on this OS. Please try to change the listen port in 'Settings.h' to another one." << std::endl;
std::clog << "You can view a list of which ports are excluded from your user by running this command: 'netsh interface ipv4 show excludedportrange protocol=tcp'" << std::endl;
}
#endif
}
inline
std::string readBinaryFile(const std::string & path)
{
std::ifstream in (path.c_str(), std::ios_base::binary);
assert(in);
return std::string((std::istreambuf_iterator< char > (in)), std::istreambuf_iterator< char >()) ;
}
inline
std::string readTextFile(const std::string & path, bool skipEol = false)
{
std::ifstream in (path.c_str());
assert(in);
std::string str((std::istreambuf_iterator< char > (in)), std::istreambuf_iterator< char >());
if(skipEol)
{
while(str.length() && (*str.rbegin() == '\r' || *str.rbegin() == '\n'))
str.erase(str.length() - 1);
}
return str;
}
inline
int xsnprintf(char * buffer, size_t size, const char * format, ...)
{
va_list list;
va_start(list, format);
#ifdef _MSC_VER
return _vsnprintf_s(buffer, size, size ? size - 1 : 0, format, list);
#else
return snprintf(buffer, size, format, list);
#endif
}

SampleArguments.h

The getting-started samples use Sample::Arguments to carry the selected execution mode and process-local port. The remaining support functions keep automation details out of the primary sample flow:

  • waitForUser() waits for any key during an interactive run and returns immediately during an automated run.
  • waitForUserOrEvent() waits for any key during an interactive run or for completion during an automated run.
  • shutdownAcceptor() preserves interactive logout behavior while allowing automated shutdown.
  • runSample() validates command-line arguments before invoking the sample flow.
enum ExecutionMode
{
InteractiveExecution,
NonInteractiveExecution
};
struct Arguments
{
Arguments(ExecutionMode executionModeValue, int portValue) :
executionMode(executionModeValue),
port(portValue)
{}
ExecutionMode executionMode;
int port;
};
using SampleRunner = int (*)(const Arguments & arguments);
inline void waitForUser(const Arguments & arguments, const char * prompt);
inline void waitForUserOrEvent(
const Arguments & arguments,
const char * prompt,
OnixS::Threading::Semaphore & event);
inline void shutdownAcceptor(const Arguments & arguments, OnixS::FIX::Session & session);
inline int runSample(
int argc,
const char * const argv[],
int defaultPort,
SampleRunner sampleRunner);

Settings.h

#include <string>
namespace Settings
{
constexpr int ListenPort = 4500;
constexpr int SslListenPort = 2442;
const std::string LicenseStore = "../../license|../../../license|../../../../license";
const std::string SenderCompId = "BuySide";
const std::string TargetCompId = "SellSide";
}

PrecisionTimer.h

#ifdef _WIN32
#include <Windows.h>
#endif
#ifndef _WIN32
#include <unistd.h>
# include <ctime>
#ifndef _POSIX_TIMERS
#error NEED_POSIX_TIMERS
#endif
#endif // #ifndef _WIN32
#include <cmath>
#include <cstdio>
#include <stdexcept>
#include <iostream>
class PrecisionTimer
{
public:
PrecisionTimer();
void start();
unsigned long stop();
unsigned long elapsed();
long itemsPerSecond(size_t nItems);
private:
#ifdef _WIN32
using Timespec = LARGE_INTEGER;
#endif
#ifndef _WIN32
using Timespec = timespec;
#endif
Timespec frequency_;
Timespec counter_;
};
inline
PrecisionTimer::PrecisionTimer()
{
#ifdef _WIN32
::QueryPerformanceFrequency(&frequency_);
#endif
#ifndef _WIN32
if(0 != ::clock_getres(CLOCK_REALTIME, &frequency_))
throw std::domain_error("PrecisionTimer(),clock_getres() failed");
#endif
start();
}
inline
void PrecisionTimer::start()
{
#ifdef _WIN32
::QueryPerformanceCounter(&counter_);
#endif
#ifndef _WIN32
if(0 != ::clock_gettime(CLOCK_REALTIME, &counter_))
throw std::domain_error("PrecisionTimer::start(),clock_gettime() failed");
#endif
}
inline
unsigned long PrecisionTimer::stop()
{
#ifdef _WIN32
LARGE_INTEGER current;
QueryPerformanceCounter(&current);
current.QuadPart -= counter_.QuadPart;
counter_.QuadPart = current.QuadPart;
return elapsed();
#endif
#ifndef _WIN32
Timespec current;
if(0 != ::clock_gettime(CLOCK_REALTIME, &current))
throw std::domain_error("PrecisionTimer::stop(),clock_gettime() failed");
current.tv_sec -= counter_.tv_sec;
current.tv_nsec -= counter_.tv_nsec;
counter_.tv_sec = current.tv_sec;
counter_.tv_nsec = current.tv_nsec;
return elapsed();
#endif
}
inline
unsigned long PrecisionTimer::elapsed()
{
#ifdef _WIN32
double elapsed = (double)(counter_.QuadPart) * 1000 / (double) frequency_.QuadPart;
return (unsigned long) elapsed;
#endif
#ifndef _WIN32
return (counter_.tv_sec * 1000 + counter_.tv_nsec / 1000000);
#endif
}
inline
long PrecisionTimer::itemsPerSecond(size_t nItems)
{
double rv = (elapsed() > 0) ? std::floor(nItems * 1000.0 / elapsed()) : 0;
return static_cast<long>(rv);
}