Samples :: Reconnector
Reconnector Sell Side
Description
This application acts as a simple FIX acceptor.
Must be started first.
Directory Structure
Item | Description |
---|---|
conf/sample/ReconnectorSellSide.properties | sample configuration |
conf/logback.xml | logger configuration |
Usage
- Run the sample:
- win: 1-ReconnectorSellSide.bat
- linux: 1-ReconnectorSellSide.sh
- Clean everything:
- win: clean.bat
- linux: clean.sh
Source Code
import biz.onixs.fix.dictionary.Version;
import biz.onixs.fix.engine.Engine;
import biz.onixs.fix.engine.Session;
import biz.onixs.fix.engine.SessionState;
import biz.onixs.util.settings.PropertyBasedSettings;
import biz.onixs.util.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Semaphore;
public class ReconnectorSellSide implements Session.StateChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(ReconnectorSellSide.class);
private static final String SETTINGS_RESOURCE = "sample/ReconnectorSellSide.properties";
private final Semaphore sessionIsDisconnected = new Semaphore(0);
private final Semaphore sessionIsEstablished = new Semaphore(0);
private Settings settings = null;
private Session session = null;
private void run() throws InterruptedException {
LOG.info("Loading settings from: {}", SETTINGS_RESOURCE);
settings = new PropertyBasedSettings(SETTINGS_RESOURCE);
//
LOG.info("Starting the Engine...");
final Engine engine = Engine.init(settings);
//
createSession();
session.logonAsAcceptor();
sessionIsDisconnected.acquire();
//
LOG.info("Waiting for connection...");
sessionIsEstablished.acquire();
//
LOG.info("Waiting for disconnection...");
sessionIsDisconnected.acquire();
session.logout();
session.dispose();
//
LOG.info("Engine shutdown...");
engine.shutdown();
}
private void createSession() {
final Version fixVersion = Version.getByNumber(settings.getString("FIXVersion"));
session = new Session(settings.getString("SenderCompID"),
settings.getString("TargetCompID"),
fixVersion, false);
//
session.addStateChangeListener(this);
}
@Override
public void onStateChange(final Object sender, final Session.StateChangeArgs args) {
final SessionState newState = args.getNewState();
if (SessionState.AWAIT_LOGON == newState) {
sessionIsDisconnected.release();
} else if (SessionState.ESTABLISHED == newState) {
sessionIsEstablished.release();
}
}
public static void main(final String[] args) {
try {
LOG.info("ReconnectorSellSide");
LOG.info("The application is starting...");
final ReconnectorSellSide sellSide = new ReconnectorSellSide();
sellSide.run();
} catch (final Throwable throwable) {
LOG.error(throwable.getMessage(), throwable);
} finally {
LOG.info("The application is stopped.");
}
}
}
Reconnector Buy Side
Description
This application acts as a FIX initiator. It demonstrates how different reconnection logic can be implemented. This reconnection logic is especially helpful when initial connection is not established during the first connection attempt.
Can be run with the “ReconnectorSellSide”. The “ReconnectorBuySide” must be started after “ReconnectorSellSide”.
Directory Structure
Item | Description |
---|---|
conf/sample/ReconnectorBuySide.properties | sample configuration |
conf/logback.xml | logger configuration |
Usage
- Run the sample:
- win: 2-ReconnectorBuySide.bat
- linux: 2-ReconnectorBuySide.sh
- Clean everything:
- win: clean.bat
- linux: clean.sh
Source Code
import biz.onixs.fix.dictionary.Version;
import biz.onixs.fix.engine.Engine;
import biz.onixs.fix.engine.Session;
import biz.onixs.fix.engine.SessionState;
import biz.onixs.util.settings.PropertyBasedSettings;
import biz.onixs.util.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Semaphore;
public class ReconnectorBuySide implements Session.StateChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(ReconnectorBuySide.class);
private static final String SETTINGS_RESOURCE = "sample/ReconnectorBuySide.properties";
private final Semaphore sessionIsEstablished = new Semaphore(0);
private Session session = null;
private Settings settings = null;
private void run() throws InterruptedException {
LOG.info("Loading settings from: {}", SETTINGS_RESOURCE);
settings = new PropertyBasedSettings(SETTINGS_RESOURCE);
//
LOG.info("Starting the Engine...");
final Engine engine = Engine.init(settings);
//
createSession();
//
final Reconnector reconnector = new Reconnector();
//reconnector.setAttemptCounter(new GrowingIntervalAttemptCounter());
reconnector.setSession(session);
reconnector.setHost(settings.getString("CounterpartyHost"));
reconnector.setPort(settings.getInteger("CounterpartyPort"));
reconnector.start();
//
sessionIsEstablished.acquire();
//
reconnector.stop();
//
session.logout("The session is disconnected by SimpleBuySide");
session.dispose();
//
LOG.info("Engine shutdown...");
engine.shutdown();
}
private void createSession() {
final Version fixVersion = Version.getByNumber(settings.getString("FIXVersion"));
session = new Session(settings.getString("SenderCompID"), settings.getString("TargetCompID"),
fixVersion, false);
//
session.setSenderSubID("SenderSubID (50) field")
.addStateChangeListener(this);
}
@Override
public void onStateChange(final Object sender, final Session.StateChangeArgs args) {
final SessionState newState = args.getNewState();
if (SessionState.ESTABLISHED == newState) {
sessionIsEstablished.release();
}
}
public static void main(final String[] args) {
try {
LOG.info("ReconnectorBuySide");
LOG.info("The application is starting...");
final ReconnectorBuySide buySide = new ReconnectorBuySide();
buySide.run();
} catch (final Throwable throwable) {
LOG.error(throwable.getMessage(), throwable);
} finally {
LOG.info("The application is stopped.");
}
}
}
The following classes are used in the sample:
import biz.onixs.fix.engine.Session;
import biz.onixs.fix.engine.SessionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Reconnector implements Runnable, Session.StateChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(Reconnector.class);
private AttemptCounter attemptCounter = new FixedIntervalAttemptCounter();
private String host = null;
private int port = 0;
private Session session = null;
private boolean reconnect = false;
private boolean running = false;
private boolean active = true;
private ExecutorService executorService = null;
public Reconnector() {
}
public AttemptCounter getAttemptCounter() {
return attemptCounter;
}
public void setAttemptCounter(final AttemptCounter attemptCounter) {
Objects.requireNonNull(attemptCounter, "null == attemptCounter");
this.attemptCounter = attemptCounter;
}
public String getHost() {
return host;
}
public void setHost(final String host) {
Objects.requireNonNull(host, "null == host");
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(final int port) {
this.port = port;
}
public Session getSession() {
return session;
}
public void setSession(final Session session) {
Objects.requireNonNull(session, "null == session");
this.session = session;
}
public boolean isReconnect() {
return reconnect;
}
/**
* Sets whether to connect after graceful disconnection.
*
* @param reconnect flag to connect after graceful disconnection
*/
public void setReconnect(final boolean reconnect) {
this.reconnect = reconnect;
}
public boolean isRunning() {
return running;
}
public boolean isActive() {
return active;
}
public void start() {
session.addStateChangeListener(this);
attemptCounter.reset();
executorService = Executors.newSingleThreadExecutor();
active = true;
executorService.submit(this);
}
public void stop() {
session.removeStateChangeListener(this);
active = false;
executorService.shutdownNow();
}
@Override
public synchronized void run() {
while (attemptCounter.hasNextAttempt()) {
final int interval = attemptCounter.getNextInterval();
if ((!active) || (session.getState() != SessionState.DISCONNECTED)) {
return;
}
try {
running = true;
LOG.info("Connect attempt #{} to {}:{}", attemptCounter.getAttemptNumber(), host, port);
LOG.info("Logon started");
session.logonAsInitiator(host, port);
LOG.info("Logon finished");
running = false;
return;
} catch (final RuntimeException e) {
LOG.info("Connect attempt #{} failed", attemptCounter.getAttemptNumber(), e);
if (attemptCounter.hasNextAttempt()) {
session.resetLocalSequenceNumbers();
LOG.info("Next connect attempt in {} msecs.", interval);
try {
Thread.sleep((long) interval);
} catch (final InterruptedException ignored) {
}
} else {
LOG.info("Connect attempt limit reached.");
}
}
}
running = false;
}
@Override
public void onStateChange(final Object sender, final Session.StateChangeArgs args) {
if ((!running) && (active) && (reconnect) && (args.getNewState() == SessionState.DISCONNECTED)) {
executorService.submit(this);
}
}
}
public interface AttemptCounter {
int getAttemptNumber();
void incrementAttemptNumber();
boolean hasNextAttempt();
int getNextInterval();
void reset();
}
public abstract class AbstractAttemptCounter implements AttemptCounter {
private int attemptNumber = 0;
@Override
public int getAttemptNumber() {
return attemptNumber;
}
@Override
public void incrementAttemptNumber() {
attemptNumber++;
}
@Override
public void reset() {
attemptNumber = 0;
}
}
import biz.onixs.fix.engine.Engine;
import biz.onixs.fix.engine.EngineSettings;
public class FixedIntervalAttemptCounter extends AbstractAttemptCounter {
private int maxAttemptNumber = 0;
private int attemptInterval = 0;
public FixedIntervalAttemptCounter() {
if (Engine.isInited()) {
final EngineSettings engineSettings = Engine.getInstance().getSettings();
maxAttemptNumber = engineSettings.getConnectionRetriesNumber();
attemptInterval = engineSettings.getConnectionRetriesInterval();
}
}
public int getMaxAttemptNumber() {
return maxAttemptNumber;
}
public void setMaxAttemptNumber(final int maxAttemptNumber) {
if (0 >= maxAttemptNumber) throw new IllegalArgumentException("maxAttemptNumber <= 0");
this.maxAttemptNumber = maxAttemptNumber;
}
public int getAttemptInterval() {
return attemptInterval;
}
public void setAttemptInterval(final int attemptInterval) {
if (0 >= attemptInterval) throw new IllegalArgumentException("attemptInterval <= 0");
this.attemptInterval = attemptInterval;
}
@Override
public boolean hasNextAttempt() {
return (getAttemptNumber() < maxAttemptNumber);
}
@Override
public int getNextInterval() {
if (!hasNextAttempt()) throw new IllegalStateException("No more attempts left.");
incrementAttemptNumber();
return attemptInterval;
}
}
public class GrowingIntervalAttemptCounter extends AbstractAttemptCounter {
private int minInterval = 5000;
private int maxInterval = 60000;
private int growthFactor = 2;
private int currentInterval;
public int getMinInterval() {
return minInterval;
}
public void setMinInterval(final int minInterval) {
this.minInterval = minInterval;
}
public int getMaxInterval() {
return maxInterval;
}
public void setMaxInterval(final int maxInterval) {
this.maxInterval = maxInterval;
}
public int getGrowthFactor() {
return growthFactor;
}
public void setGrowthFactor(final int growthFactor) {
if (0 >= growthFactor) throw new IllegalArgumentException("");
this.growthFactor = growthFactor;
}
@Override
public boolean hasNextAttempt() {
return true;
}
@Override
public int getNextInterval() {
incrementAttemptNumber();
if (1 == getAttemptNumber()) {
currentInterval = minInterval;
} else if (currentInterval < maxInterval) {
currentInterval *= growthFactor;
}
return Math.min(currentInterval, maxInterval);
}
}