QuickFIX/J: Not receiving ExecutionReport messages - fix-protocol

After opening an order with our brokerage firm, we desire to obtain the fill price from the ExecutionReport messages. Below you will find the callback code used.
The MarketDataSnapshotFullRefresh messages are received properly, but the second if block is never triggered. Strangely, the corresponding messages.log file does contain multiple 35=8 messages.
We use QuickFIX/J as FIX engine.
#Override
public void fromApp(Message message, SessionID sessionID) throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType {
if (message instanceof MarketDataSnapshotFullRefresh) {
// do stuff with MarketDataSnapshotFullRefresh
}
if(message instanceof ExecutionReport) {
// do stuff with ExecutionReport
}

Message handling is ideally done by a quickfix.MessageCracker, though sometimes handling them in fromApp is the way to go.
You can read more about message cracking here: QuickFIX/J User Manual - Receiving Messages.
I'll outline both ways:
In fromApp
Messages coming in fromApp are not of specific message types as defined in the QuickFIX/J library, but are of type quickfix.Message. If you wanted to process them the way you are doing now (from fromApp), you would have to inspect the MsgType manually:
MsgType msgType = (MsgType) message.getHeader( ).getField( new MsgType( ) );
Based on the type retrieved, you would call a handler method for the specific message type:
if( msgType.valueEquals( MsgType.MARKET_DATA_SNAPSHOT_FULL_REFRESH ) )
handleMarketDataSnapshotFullRefresh( message, sessionID );
else if ...
...
private void handleMarketDataSnapshotFullRefresh( quickfix.Message msg, SessionID sessionID ) {
// handler implementation
}
Using MessageCracker
Another way to handle incoming messages as mentioned before, is through a MessageCracker. You would e.g. extend the class that implements quickfix.Application with quickfix.MessageCracker.
Add an onMessage method with two parameters, first being the message type, second a SessionID. Call crack from the fromApp method which will route to the appropriate handler.
import quickfix.*;
public class MyApplication extends MessageCracker implements Application
{
public void fromApp(Message message, SessionID sessionID)
throws FieldNotFound, UnsupportedMessageType, IncorrectTagValue {
crack(message, sessionID);
}
#Handler
public void onMessage(quickfix.fix44.MarketDataSnapshotFullRefresh mdsfr, SessionID sessionID) {
// handler implementation
}
}

Why are you doing the message processing in the wrong place ? If you check what is recommended by Quickfix you will see they recommend message processing happens in onMessage (which you might not have implemented). And there should only exist a message cracker in fromApp method.
Or else your fromApp method is going to be a hotchpotch of code and the next person handling your code is not going to be a happy soul.

Related

Rx .net subject OnNext exception is losing downstream observers

Dislaimer: I am newbie to Rx.Net.
I want to understand the best way to consume events from the server using Rx.Net. Currently, I have a consumer class that contains a rx Subject, to delegate the consumed update to downstream consumers as :
Event Listener/Processor:
public IObservable<IUpdate> UpdateStream => _subject?.AsObservable();
try
{
// ... processing ...
_subject.OnNext(update); // update is the variable
}
catch (Exception ex)
{
_subject.OnError(ex);
}
Downstream-subscribers:
public void Subscribe()
{
_eventListener.UpdateStream.Subscribe(update =>
{
_fooProcessor.Process(update);
},
ex =>
{
// log
Subscribe(); // an effort to resubscribe lost subscription
},
() => { // log completion (optional)...}
}
I have noticed that subject throws exception onNext (an item with the same key has already been added), wherein, the subject.HasObservers property is false (in other words, the downstream subscription list is lost). The OnError code line does hit, but the downstream subscribers do not get notified (because of lost subscription).
I tried using Observer.EventPattern to listen to the consuming event and create the observable to be consumed by downstream-subscribers; but that did not work as well (I could not evaluate the point of failure in this case).
Is there a pattern to resubscribe from downstream consumers (on different dlls), in such cases?
Appreciate any help.
Thanks!
I found that the downstream-subscriber was throwing an exception, resulting in dropping the subscription. This is not an issue now.
Thanks - How to handle exceptions in OnNext when using ObserveOn?

"QuickFix.UnsupportedMessageType" exception was thrown, when the "onMessage" crack was present

I'm not quite sure why it happened. I request Market Data Request (with 263=1) and the counterparty gave response with (absolutely) MarketDataSnapshotFullRefresh (35=W). I've included the onMessage(QuickFix.FIX42.MarketDataSnapshotFullRefresh ...) on my message's cracker.. But the app has thrown the exception "QuickFix.UnsupportedMessageType"...
So, I tried to capture the SnapshotMarketData directly from "FromApp" (without Message Cracker) and it successfully done. So what's the matter with my message's cracker? Any idea?
This is the "FromApp" currently..
public void FromApp(QuickFix.Message msg, SessionID sessionID) //every inbound Application-level message
{
if (msg.Header.GetField(Tags.MsgType) == MsgType.MARKET_DATA_SNAPSHOT_FULL_REFRESH)
Homepage._homepage.GetFixMessage(msg.ToString());
else
Crack(msg, sessionID);
}
And this is the Message Cracker previously (before I capture directly from "FromApp"
#region MessageCracker handlers
public void onMessage(QuickFix.FIX42.MarketDataSnapshotFullRefresh mdsnapshot, SessionID s)
{
Homepage._homepage.GetFixMessage(mdsnapshot.ToString());
}
#endregion
OnMessage needs to start with a capital "O".
QF/n uses the C# convention of capitalizing method names.

Verticles and uncaught exceptions

Considering the scenario that one of the verticles throws an uncaught exception.
What happens next?
If the verticle state is removed from the system is there some mechanism similar to erlang supervisors to restart the verticle?
Documentation is not very clear about this aspect.
Update based on comments:
What interest me the most is the situation when an exception is thrown from the processing handlers of a received message (through the bus)
Regards
I have answered part of my own question (with the help of a test program)
When exception is thrown in a event handler then the exception is caught by vert.x and swallowed (ignored). The event handler will process the next message.
Update: The app can register an exception handler and have all the uncaught Throwable delivered to this handler. There you can perform additional general processing
Update2: Use Vertx.exceptionHandler to register the handler
Vert.x is all about the same style, asynchronous programming, which is mainly highlighted by callback handlers.
To handle the deployment failure case, you have first to go the programmatic way, i.e. you have to deploy your verticle programmatically through let's say a deployment verticle providing a completion handler that will be populated with deployment result, here down a sample using Java (since your haven't opt for a specific language, I will go with my best) where:
MainVerticle: is your deployment verticle (used mainly to deploy other verticles)
some.package.MyVerticle: is your real verticle, note that I used the id here and not an instance.
public class MainVerticle extends AbstractVerticle {
public void start() {
vertx.deployVerticle("some.package.MyVerticle", res -> {
if (res.succeeded()) {
// Do whatever if deployment succeeded
} else {
// Handle deployment failure here...
}
});
}
}
Now when it comes to 'messaging failures', it would be harder to highlight a specific case since it can occur at many places and on behalf of both messaging ends.
If you want to register a failure case handler when sending a message, you can instantiate a MessageProducer<T> representing the stream it can be written to, then register an exception handler on it:
EventBus eb = vertx.eventBus();
MessageProducer<String> sender = eb.sender("someAddress");
sender.exceptionHandler(e -> {
System.out.println("An error occured" + e.getCause());
});
sender.write("Hello...");
On the other side, you can handle failure case when reading the received messages pretty much the same way, but using a MessageConsumer<T> this time:
EventBus eb = vertx.eventBus();
MessageConsumer<String> receiver = eb.consumer("someAddress");
receiver.exceptionHandler(e -> {
System.out.println("An error occured while readeing data" + e.getCause());
}).handler(msg -> {
System.out.println("A message has been received: " + msg.body());
});
To add a bit to the previous answer, if you want to react to all uncaught exceptions, register handler on vertx object, as follows:
vertx.exceptionHandler(new Handler<Throwable>() {
#Override
public void handle(Throwable event) {
// do what you meant to do on uncaught exception, e.g.:
System.err.println("Error");
someLogger.error(event + " throws exception: " + event.getStackTrace());
}
});
I ran into something similar to this. When an exception happens as part of processing a message in a Verticle, I just wanted to reply with the Exception.
The idea is to just bubble up the exceptions all the way back to the entry point in the app where a decision can be made about what to do with the failure, while capturing the entire stack along the way.
To accomplish it I wrote this function:
protected ReplyException buildReplyException(Throwable cause, String message)
{
ReplyException ex = new ReplyException(ReplyFailure.RECIPIENT_FAILURE, -1, message);
ex.initCause(cause);
return ex;
}
Which I then use to build handlers, or reply handlers, like this:
reply -> {
if (reply.succeeded()) {
message.reply(true);
} else {
message.reply(buildReplyException(reply.cause(), ""));
}
});
This way the guy that sent the original message will get a failed response which contains a cause that's an exception which has a full stack trace populated on it.
This approach worked very well for me to handle errors while processing messages.

How to send email to registered user in Java EE

I want to send an email activation link to a registered user. I already set up my Sendmail.class which work` perfectly.
Here is the scenario:
the user request for registration by providing information via a restful client
the restful endpoint gets the request to do some business operation and sends a computed code to the email of the registered user and returns a response saying 'successfully registered'
The problem is that I don't want to wait for the Sendmail.class to finish the sending process (it may fail) to return the 'successfully registered message
How can I handle this process using Java EE?
Put the code that sends the email in an #Asynchronous method.
Example:
#Stateless
public class EmailSender {
#Asynchronous
public void sendMail(...) {
// send mail here
}
}
From the place where you do your business logic:
#Inject
private EmailSender emailSender;
public Foo myBusiness() {
// Compute stuff
emailSender.sendMail(stuff); // returns immediately
// do other stuff if needed
}
See the Oracle tutorial for some extra info.
Put your e-mail sending code in a thread. Even you can easily use SwingWorker:
SwingWorker worker = new SwingWorker() {
#Override
protected void done() {
}
#Override
protected Object doInBackground() throws Exception {
// Send your e-mail here.
}
};
worker.execute();

GWT requestfactory: How to catch the exception i thrown in Locator at server side?

At client side:
factory.find(proxyId).fire(new Receiver<P>()
{
#Override
public void onSuccess( P response )
{
proxy = response;
...
}
#Override
public void onFailure( com.google.web.bindery.requestfactory.shared.ServerFailure error )
{
Window.alert( error.getMessage() );
}
}
at server side i use an Locator like below:
public class myLocator extends Locator<T, String>
{
#Injector LocatorHook hook;
#Override
public T find( Class<? extends T> clazz, String id )
{
T result = ...;
hook.run( result );
return result;
}
....
}
The hook.run() method may throwRunTimeException("validation exception") there, i expect to catch the
exception at client side in onFailure(), however, i did catch the exception, but the message is "Internal Server Error",
not the exception i thrown in hook.run():"validation exception".
Any ideas to let client catch the exception i throw at server side?
Updation:
As Thomas said it's weird that validating objects that come fresh from data store, but i encounter a
situation that i don't know how to use service method:
At client i get EntityProxyId object, through the factory.find( proxyId ).fire(...) i can get the entity
from datastore, but the entity may not suitable for the user to access, in this situation i need to check it at server side, but i can't find a suitable place to do the
validation, Any ideas about this?
RequestFactory doesn't expect exceptions to be thrown by locators. Exceptions should only be thrown by service methods, and will be directed to the appropriate Receiver on the client-side (the one attached to the service method that threw).
Outside service methods, the only exceptions that gets routed to the client are ReportableExceptions, that can only be thrown from a ServiceLocatorDecorator's report() methods. That means you could hook your own ServiceLocatorDecorator that catches exceptions from your locators and report()s them.
That said, validating objects that come fresh from your data store seems weird. You might want to provide a ServiceLocatorDecorator that overrides validate() (that'll validate the objects after the changes coming from the client have been applied). The errors will go back to the client in the Receiver's onConstraintViolations, and the RequestContext will be unfrozen so you can further edit your proxies and fire() again.