0% found this document useful (0 votes)
50 views

Using Java Messagingjng

Yako Fain presented on using JMS and message-oriented middleware for financial trading systems. Key points included: - JMS allows applications to connect in a loosely coupled way using message queues and topics. This is useful for integrating different trading applications. - A trading order's lifecycle involves creating the order, sending it to an exchange, processing executions/cancellations, and reporting the trade. JMS supports this asynchronous workflow. - MOM servers like WebSphere MQ, Tibco, and Sonic MQ can reliably store and deliver messages to integrate applications written in different languages. This improves performance, availability, and scalability over direct integration.

Uploaded by

gajugg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Using Java Messagingjng

Yako Fain presented on using JMS and message-oriented middleware for financial trading systems. Key points included: - JMS allows applications to connect in a loosely coupled way using message queues and topics. This is useful for integrating different trading applications. - A trading order's lifecycle involves creating the order, sending it to an exchange, processing executions/cancellations, and reporting the trade. JMS supports this asynchronous workflow. - MOM servers like WebSphere MQ, Tibco, and Sonic MQ can reliably store and deliver messages to integrate applications written in different languages. This improves performance, availability, and scalability over direct integration.

Uploaded by

gajugg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

www.weekendwithexperts.

com
Financial Trading Systems Using JMS
and Message-Oriented Middleware

by Yako Fain

www.weekendwithexperts.com
!hilly JU"# October $%# $&&%
www.weekendwithexperts.com
'bo(t Mysel)

J$** 'rchitect and deeloper

+reator o) the seminars ,-eekend -ith


*xperts.

*nterprise Jaa editor at Jaa /eeloper0s


Jo(rnal

'(thor o) Jaa books and articles

!art-time pro)essor at 1ew York Uniersity


www.weekendwithexperts.com
'genda

' brie) oeriew o) the stock trading process

Message Oriented Middleware 2MOM3

4asics o) Jaa Messaging Serice

Jaa JMS clients and Message-/rien 4eans 2M/43

M(ltithreading

5ntrod(cing 6/'! serers

!otential iss(es
www.weekendwithexperts.com
' Trading System
www.weekendwithexperts.com
-all Street

Stock *xchanges
21YS*# 1'S/'7#
'merican Stock
*xchange83

4rokerage ho(ses#
trading )loor#
specialists
www.weekendwithexperts.com
Stock !(rchase Order

-ho can place an order to b(y9sell a stock: '


broker# a day trader8 50e done that as well .

"U59-eb inter)ace

Market# 6imit# "T+ orders

1ew# Mod# +ancel orders. Slicing

'sk and 4id prices

Front9Middle94ack O))ice systems; trading9pro)it <


loss# risk management9 settlements# record keeping#
reg(latory compliance
www.weekendwithexperts.com
Order0s 6i)e +ycle

+reate a new order in yo(r database

Send an order to the stock exchange

=eceie exec(tion2s3 or re>ection2s3

!rocess modi)ications9cancels o) some orders

=eport a trade to middle9back o))ice applications

The order has to go thro(gh seeral applications on


written in di))erent lang(ages on di))erent plat)orms.
www.weekendwithexperts.com
Faster, Faster, Faster!

=o(nd-trip metrics

' st(ck message is a liability

?igh 'ailability

Scalability

5ntegration with other 2legacy3 systems


www.weekendwithexperts.com
MOM Serers
www.weekendwithexperts.com
Message-Oriented Middleware

MOM allows to connect ario(s applications in a


loosely co(pled )ashion with minim(m
programming re@(ired.

MOM is similar to a post o))ice.

"(aranteed deliery 2is not always needed3.

'synchrono(s processing; applications do not rely


on aailability o) other applications.

Messaging helps in b(ilding open ended# serice-


oriented and loosely co(pled systems.
www.weekendwithexperts.com
Ma>or MOM !roiders

-ebSphere M7 2)ormer M7 Series3# 54M

Tibco =endeAo(s# Tibco

FioranoM7# Fiorano So)tware

Sonic M7# Sonic So)tware

MSM7# Microso)t
Messaging bridges come handy in cases like mergers of two companies,
i.e.: A trading system that uses WebSphere MQ can arrange money
transfer from a banking application that uses Tibco.
Webogic has a concept of foreign !MS ser"ers.
Sonic MQ has a bridge to WebSphere MQ#
www.weekendwithexperts.com
+onnecting 'pplications with MOM
www.weekendwithexperts.com
More MOM bene)its

Yo( do not need to write a c(stom so)tware


to connect two applications.

5) one o) the applications is not aailable#


MOM stores messages.

MOM proides cl(stering# load balancing


and )ail-oer witho(t additional
programming.
www.weekendwithexperts.com
Messaging 4(AAwords

Message prod(cers and cons(mers# simple clients

!oint-to-!oint 2!$!3# 7(e(es# Senders

+hannels# 7(e(e Managers

!(blish-S(bscribe 2!(b9S(b3# Topics# !(blishers#


S(bscribers# /(rable S(bscribers

!ersisted messages are stored on disks while non-


persisted messages stay in memory.
www.weekendwithexperts.com
!oint-to-!oint Model

There is only one receier )or


any partic(lar message 2i.e. a
sender places an order and a
receier gets it3.

' sender is called a message


producer and a receier is a
message consumer.

The message is remoed )rom a


@(e(e as soon as the receier
s(ccess)(lly gets it.
www.weekendwithexperts.com
!(blish-S(bsribe Model

' message is published to


a topic and m(ltiple
receiers can get it 2i.e.
stock price @(otes3

=eceiers subscribe to a
topic.

!(blishers and s(bscribers


are connected by a
message broker.
www.weekendwithexperts.com
J$** Serers
www.weekendwithexperts.com
Jaa Messaging Serice 2JMS3

JMS is an '!5 to MOM. Message prod(cers and cons(mers


can (se non-JMS '!5s.

Synchrono(s message retrieal.

JMS 6isteners.

J$** senders; Session 4eans.


$oncurrency, transaction support, easy configuration, they can send messages
to any topic or %ueue

J$** receiers; Message-/rien 4eans 2M/43.


$oncurrency, transaction support, easy configuration, they are mapped to a
particular topic
www.weekendwithexperts.com
Message-/rien 4eans

M/4 are stateless# no remote and home inter)aces


public class OrderListener implements
MessageDrivenBean, MessageListener{

MessageDrivenContext ctx;
public OrderListener() {}
public void onMessage(Message message){
// our business code goes !ere"
}
// Bean Life supporting methods go here
}
www.weekendwithexperts.com
M/4 descriptor; e>b->ar.xml
#message$driven%
#e&b$name%OrderListener#/e&b$name%
#e&b$class%com"x'("OrderListener#/e&b$class%
#transaction$t'pe%Container#/transaction$t'pe%
#transaction$scope%Local#/transaction$scope%
#message$driven$destination%
#&ms$destination$t'pe%&avax"&ms"Topic
#/&ms$destination$t'pe%
#&ms$subscription$durabilit'%nondurable
#/&ms$subscription$durabilit'%
8
www.weekendwithexperts.com
weblogic-e>b->ar.xml
Mapping of an MDB to a topic:
#)eblogic$enterprise$bean%
#e&b$name%OrderListener#/e&b$name%
#message$driven$descriptor%
#destination$&ndi$name%
OrderTopic
#/destination$&ndi$name%
#/message$driven$descriptor%
#/)eblogic$enterprise$bean%
www.weekendwithexperts.com
Simpli)ied Order =o(nd Trip
www.weekendwithexperts.com
Synch s. 'synch
www.weekendwithexperts.com
Synch s. 'synch 2cont.3
www.weekendwithexperts.com
JMS +lasses From >aa.>ms

Message

7(e(e# 7(e(e+onnection# 7(e(e+onnectionFactory#


7(e(eSession# 7(e(eSender# 7(e(e=eceier

Topic# Topic+onnection# Topic+onnectionFactory#


TopicSession# Topic!(blisher# TopicS(bscriber
www.weekendwithexperts.com
JMS Message Types

TextMessage B any Jaa String

Ob>ectMessage B any serialiAable Jaa Ob>ect

4ytesMessage B a stream o) bytes

StreamMessage B a stream o) Jaa primities

MapMessage B any key9al(e pair


An &b'ectMessage or a MapMessage are good
choices for a trading S&A application.
www.weekendwithexperts.com
?ow to Send a Message
*ueueConnection+actor' ,actor' - ne)
*ueueConnection+actor'();
//*ueueConnection+actor' ,actor'-
//(*ueueConnection+actor') ctx"loo.up(/Order*C+0);
*ueueConnection connection -
,actor'"createQueueConnection();
connection"start();
1ession session - connection"createQueueSession(
,alse2 1ession"345O63C78O9L:D;:);
*ueue io*ueue - session"createQueue( /Order*ueue0 );
*ueue1ender <ueue1ender -session"createSender(io*ueue);
5extMessage outMsg - session"createTextMessage();
outMsg"setText(/=>M ?@@ M.t0); // >u' ?@@ s!ares o, =>M
<ueue1ender"send(outMsg);
<ueue1ender"close();
www.weekendwithexperts.com
?ow to =etriee a Message
class M'Aeceiver implements MessageListener{
M'Aeceiver(){
*ueueConnection+actor' ,actor' - ne) *ueueConnection+actor'();
// *ueueConnection+actor' ,actor' -
// (*ueueConnection+actor') ctx"loo.up(/Order*C+0);
*ueueConnection connection - ,actor'"createQueueConnection();
connection"start();
1ession session - connection"createQueueSession(
,alse2 1ession"345O63C78O9L:D;:);
*ueue io*ueue - session"createQueue( /Order*ueue0 );
*ueueAeceiver <ueueAeceiver - session"createeceiver(io*ueue);
*ueueAeceiver"setMessageListener(t!is);
}
public void onMessage(Message msg){
1tring msg5ext;
tr'{ i, (msg instanceo, 5extMessage){
msg5ext - ((5extMessage) msg)"get5ext();
1'stem"out"println(/;ot / B msg5ext);
}else 1'stem"out"println(/;ot a non$text message0);
}
C
www.weekendwithexperts.com
?ow to !(blish a Message
5opicConnection+actor' con+actor' -
(5opicConnection+actor') ctx"loo.up(/ipo5C+D);
5opicConnection connection -
con+actor'"create5opicConnection();
5opic1ession pub1ession -
connection"create5opic1ession(,alse21ession"345O63C78O9L:D;:);
5opic ipo5opic - (5opic)ctx"loo.up(/=EO63lerts0);
5opicEublis!er publis!er-pub1ession"createEublis!er(ipo5opic);
connection"start();
5extMessage message - pub1ession"create5extMessage();
message"set5ext(/;oogleFs =EO is sc!eduled ,or tomorro)0);
publis!er"publis!(message);
www.weekendwithexperts.com
?ow to S(bscribe )or a Topic
5opic1ession sub1ession-connection"create5opic1ession(,alse2


1ession"345O63C78O9L:D;:);
5opic topic - (5opic) ctx"loo.up(/=EO63lerts0);
5opic1ubscriber subscriber-sub1ession"create1ubscriber(topic);

connection"start();
subscriber"setMessageListener(t!is);

public void onMessage!Message message" {


1tring msg5ext;
tr'{
i, (msg instanceo, 5extMessage){
msg5ext - ((5extMessage) msg)"get5ext();
1'stem"out"println(/;ot / B msg5ext);
}else 1'stem"out"println(/;ot a non$text message0);
}
8
www.weekendwithexperts.com
Message Str(ct(re

The header describes the message# i.e.


msg id, routing, correlation id (!MSMessage)*, !MS+elyTo,
!MS$orrelation)*,

The body contains the application data 2(p to C&&Mb3


te-t, bytes, key."alue pairs, etc.

Optional properties and selectors.


Application specific parameters. Support customi/ed
message selection. Allows sharing %ueues for different types
of messages.
www.weekendwithexperts.com
Message Selectors
5) yo( hae to share a @(e(e )or di))erent types o) messages (se selectors 2)ilters3
to aoid DstealingD somebody else0s messages;
1tring selector - D1:-831D3*D;
session"createAeceiver(<ueue2 selector);
S(ch a listener will de-@(e(e only those messages that hae a String property S*
with the al(e ,1'S/'7..

Message prod(cers hae to set this property;
5extMessage outMsg - session"create5extMessage();
outMsg"set5ext(/G@@ **** M0);
outMsg"set1tringEropert'(D1:D2 D831D3*D);
For better per)ormance (se n(meric selectors
www.weekendwithexperts.com
Message 'cknowledgement

Use o) transactions and a message acknowledgement mode


are speci)ied d(ring creation o) a JMS session ;
Connection+actor' con+act- ne) Connection+actor'();
Connection con-con+act"createConnection();
1ession session - con"create1ession(false2
Session#$%TO&$C'(O)L*D+*);
The other choices are $)01T2A$31&W040 and
*56S2&32A$31&W0*40

5) the )irst arg(ment is true# the session will (se


transactions and the second arg is ignored. 'n explicit
commit() is re@(ired in this case.
www.weekendwithexperts.com
M(ltithreading

M/4 allow yo( create a pool o) message listeners witho(t thread


programming. 'nother choice; instantiate Jaa listener-classes on
the app serer start(p.

J$** spec disco(rages (se o) m(ltithreading in containers# b(t8

Using threads to send messages )rom session beans is OF.

+ontrol threads by (sing thread pools. 's o) Jaa %.& they are part
o) J$S* 2see &ava"util"concurrent"5!readEool:xecutor3.

The Jakarta +ommons pro>ect has a Thread!ool component


www.weekendwithexperts.com
6/'! Serers
www.weekendwithexperts.com
6/'! Serers )or +orp /irectories

6/'! directory serers are highly optimiAed )or data


retrieal.

/ata in memory are stored in a tree str(ct(re;


oGxyA.com
o(Ggro(ps
cnGacco(nting
cnG?=
cnG=iskTechnology
cnGYako

The address o) the ob>ect that0s bo(nd (nder the node Yako is ;
cnGYako# cnG=iskTechnology# o(Ggro(ps# oGxyA.com

www.weekendwithexperts.com
6/'! Serer )or JMS Ob>ects

Storing 7(e(e Managers and 7(e(es in 6/'! directory


serers;
oGxyA.com
o(GTrading
cnGOrder7+F
cnGOrder7(e(e
cnG'ck7+F
cnG'ck7(e(e
cnG+ompliance7(e(e

?ere0s the J1/5 look(p parameter;


cnG+ompliance7(e(e# o(GTrading# oGxyA.com
www.weekendwithexperts.com
6/'! and J1/5 look(p

Set JNDI properties, connect to the LDAP server, and find the
object called rder!"F# a J$S %ueue connection factor&'

Has!table env - ne) Has!table();


env"put(Context"=8=5=3L6CO85:I56+3C5OA2
/com"sun"&ndi"ldap"LdapCtx+actor'0);
env"put(Context"EAOJ=D:A64AL2 /ldap:,,m-ldapserver#x-.#com:/010);
env"put(Context"1:C4A=56345H:85=C35=O820simple0);
env"put(Context"1:C4A=56EA=8C=E3L2 /cn-Director' Manager0);
env"put(Context"1:C4A=56CA:D:85=3L120m'Eass)ord0);

DirContext ctx - ne) =nitialDirContext(env);
*ueueConnection+actor' ,actor' - (*ueueConnection+actor')
ctx#loo2up!3cn4OrderQC5, ou4Trading, o4x-.#com6";
*ueue order*ueue - (*ueue)
ctx#loo2up!3cn4OrderQueue, ou4Trading, o4x-.#com6";
www.weekendwithexperts.com
4inding Ob>ects to an 6/'! Tree

'n example o) binding a -ebSphere M7 @(e(e ob>ect. ' @(e(e


connection )actory can be bo(nd to 6/'! similarly.
DirContext ctx-ne) =nitialDirContext(env);// see previous slide
8
M**ueue <ueue - ne) M**ueue();
<ueue"setEersistence(KM1C"M*KM16E:A68O8);
// =, on t!e ot!er end o, t!e <ueue is a non$&ms readerL
// <ueue"set5argetClient(KM1C"M*KM16CL=:8568O8KM16M*);
1tring ldap8ame - Dcn-Order*ueue2 ou-5rading2 o-x'("comD;
ctx"rebind(ldap8ame2 <ueue);

'n app does not know i) yo(0re (sing -ebSphere M7 or other


proider;
*ueue order*ueue - (*ueue)
ctx#loo2up!3cn4OrderQueue, ou4Trading, o4x-.#com6";
www.weekendwithexperts.com
' @(iA
The data center with the MOM serer is down.
Yo(r trading application (ses seeral @(e(e
managers# topics and doAens o) @(e(es.
?ow do yo( @(ickly re-con)ig(re yo(r trading
system to (se a di))erent MOM serer:
www.weekendwithexperts.com
7(iA Sol(tion
=(n an 6/'! binder program that will rebind
the /isaster =ecoery site0s MOM serers#
@(e(e managers# @(e(es and topics.
Yo(r trading system may stay alie een
witho(t bo(ncing J$** serers.
www.weekendwithexperts.com
=eporting and +ompliance
www.weekendwithexperts.com
Trade =eporting and +ompliance

1'S/'7 H&-seconds r(le

Trading !re-+learance

5nsider Trading

Use o) 4(siness 5ntelligence *ngines

'nti-Money 6a(ndering
Using real-time messaging helps in preenting iolations;
re>ect a trade i) it iolates any reg(lations.
www.weekendwithexperts.com
SO'# */' and Messaging
Serices;

Orders# 'cco(nts

+redit =ating 2+=3. 5nstead o) checking )or eery order# s(bscribe )or
modi)ications o) += 2!(b9S(b3.

Trades. +heck )or and p(blish iolations. +ompliance department


s(bscribes )or iolations 2!oint-to-!oint3.

!ositions

Market data. S(bscribe )or partic(lar stock in)o and initiate trades when
conditions are met 2!(b9S(b3.

Tibco 4(siness-orks o))ers an easy way to integrate serices by


connecting them to the same message b(s and creating serice adapters.
Watch for WS.1otifications spec (&AS)S, that won7t re%uire e"ery ser"ice to
be written in !a"a.
www.weekendwithexperts.com
!otential 5ss(es

Se@(encing. Messages may arrie o(t o) order 2i.e. mod


comes be)ore create3.

5) yo( know in adance how many slices are being sent# >(st
add a se@(ence n(mber to a the header property.

+reate a re-se@(encer that will p(t a message with high


se@(ence n(mbers aside (ntil the preio(s message arries.

=eceier can also can also not accept a message i) a


preio(s one does not exist in the database 2modi)ication o)
a non-existing order3.

JMS!riority header )ield 2&-C&3 might help in deliering


expedited messages 2%-H3 ahead o) normal ones.
www.weekendwithexperts.com
!otential 5ss(es 2cont.3

!oisoned Messages 2any type o) corr(ption3. They ca(se an


application to rollback and retry.

The n(mber o) re-tries sho(ld be con)ig(rable.

!oisoned messages sho(ld be placed into a separate @(e(e


and re@(ire examination by people.
www.weekendwithexperts.com
!otential 5ss(es 2cont.3

The connection to the MOM proider is lost


5) yo( set a &avax"&ms":xceptionListener to
yo(r +onnection ob>ect# it0ll be noti)ied o) connectiity
problems.

This inter)ace has the only method ;


on:xception(KM1:xeption e){
// tr' to reconnect}.

5) yo(r MOM proider s(pports logical 5!s# arrange


some wait in this method to allow )ailoer to a /= site.
conn"set:xceptionListener(
:xceptionListener listener)
www.weekendwithexperts.com
Scalability in Messaging

Systems need to accommodate more conc(rrent (sers or


increased ol(me.

MOM +l(sters with the messages persisted on the Storage


'rea 1etworks 2S'13 deices based on ='5/ disks.

5) yo( can not a))ord S'1# yo(0ll hae to arrange a


replication o) the persisted messages.

5s the price o) persisting messages too high: Yo( can easily


increase the message thro(ghp(t C& times or more by
switching to a non-persistent mode.
www.weekendwithexperts.com
*nterprise 5ntegration !atterns
www.eaipatterns.com has a good and growing
collection o) *5 patterns that are not tied to a speci)ic
implementation# )or example;

Message =o(ting; /ynamic =o(ter# 'ggregator#


=ese@(encer# Splitter

Messaging *ndpoints; *ent-/rien +ons(mer# !olling


+ons(mer# Transactional +lient
www.weekendwithexperts.com
Thank yo(I
7 < '
email; yakoJweekendwithexperts.com

You might also like