start a bunch of boost threads

   boost::thread_group grp;

   for (int i = 0; i < 90; ++i){

      grp.create_thread(worker_func);
// worker_func is a regular function name, implicitly converted to a func ptr
   }

   grp.join_all( );

Advertisements

smart ptr ^ weak reference ^ atomic ref

There’s some interesting resemblance between sptr and weakref. (Will address atomic ref later ..)Background — dominant construct in both c++ and java is the 32-bit pointer, assuming 32-bit address bus.

sptr and weakref
– both “wrap” the raw ptr
– both occupy more than 32 bits
– both introduce an extra level of indirection when accessing pointee
– both were designed for clever heap memory de-allocation
– when you need a raw ptr, you can’t pass in such a super ptr.
– in each case, 2 addresses are involved –
** pointee address and sptr’s own address
** pointee address and the weakref’s own address. When you pass the weakref, you don’t clone the weakref but you clone the 32-bit address of the weakref object.

$dbproc in PWM perl database programs

Now I know where the $dbproc came from. It’s a common variable name in sybase DB-library programs. Note DB-library is the older of the 2 open-client libraries, and still used in many wall street banks.

http://manuals.sybase.com/onlinebooks/group-cnarc/cng1110e/dblib/@Generic__BookTextView/503;pt=505#X — shows a standard DB-library program

http://manuals.sybase.com/onlinebooks/group-cnarc/cng1110e/dblib/@Generic__BookTextView/34250;pt=39614
http://manuals.sybase.com/onlinebooks/group-cnarc/cng1110e/dblib/@ebt-link;pt=34250?target=%25N%15_34741_START_RESTART_N%25

sybase open client, open server, DB-library

http://manuals.sybase.com/onlinebooks/group-cnarc/cng1110e/ctref/@Generic__BookTextView/292;pt=294#X explains

The Sybase product line includes 1) servers and 2) tools for building servers:

  • SQL Server is a database server. SQL Servers manage information stored in one or more databases.
  • Open Server provides the tools and interfaces needed to create a custom server application.

SQL Server and Open Server applications are similar in some ways …But they also differ:

  • An application programmer must create an Open Server application, using Server-Library's building blocks and supplying custom code. SQL Server is complete and does not require custom code.

Open Client provides two core programming interfaces: Client-Library and DB-Library

  • Open Client Client-Library supports server-managed cursors and other new features that were added to the System 10 product line.
  • Open Client DB-Library provides support for older Open Client applications, and is a completely separate programming interface from Client-Library. DB-Library is documented in the Open Client DB-Library/C Reference Manual.

Client-Library programs also depend on CS-Library, which provides routines that are used in both Client-Library and Server-Library applications.

linux named pipe – simple experiment – inode, mtime…

Copied from http://linuxprograms.wordpress.com/2008/02/14/fifo-named-pipes-mkfifo-mknod/

Reading/ Writing data from/to a FIFO
Let’s open two terminals
In the first terminal

$ cat > fifo

we are experimenting with the FIFOThis is second line.

After opening the fifo in the second terminal for reading using cat, you will notice the above two lines displayed there.
Now open the second terminal and go to the directory containing the FIFO ‘fifo’

$ cat fifo

we are experimenting with the FIFOThis is second line.

Now keep on writing to the first terminal. You will notice that every time you press enter, the corresponding line appears in the second terminal.

Pressing CTRL+D in the first terminal terminates writing to the fifo. This also terminates the second process because reading from the fifo now generates a “BROKEN PIPE” signal. The default action for this is to terminate the process.

Let us now see the details of the file ‘fifo’

$ ls -l fifo
prw-r--r-- 1 user user 0 Feb 14 10:05 fifo

The p in the beginning denotes that it is a pipe.

Let’s see more details about the pipe using stat

$ stat fifo
File: `fifo'Size: 0 Blocks: 0 IO Block: 4096 fifo
Device: fd00h/64768d Inode: 1145493 Links: 1
Access: (0644/prw-r--r--) Uid: ( 0/ user) Gid: ( 0/ user)
Access: 2008-02-14 10:05:49.000000000 +0530
Modify: 2008-02-14 10:05:49.000000000 +0530
Change: 2008-02-14 10:05:49.000000000 +0530

If you notice carefully, FIFOs just like a normal file possess all the details like inode number, the number of links to it, the access, modification times, size and the access permissions.

As in the case of pipes, there can be multiple readers and writers to a pipe. Try opening multiple terminals to read from and write to a pipe.

3 differences – perl vs c++

Someone asked me this questions.

My answer: strongly typed vs dynamically typed. strings and numbers.. You can have an array of mixed data types. Not practical in c++ — a subversion of strict type control.

My answer: not compiled but interpreted — run-time performance

My answer: no pointers in perl, no direct access to hardware

–other key differences I should have included
– c++ can leverage lots of legacy C code, and call C system functions directly
– c++ is  memory efficient.
– c++ object code is platforms-specific
– class-support, vtbl,
– OO supports larger projects. Somehow OO perl isn’t catching on

Thread.java methods – 2+1+1 types

For a novice, It's instructive to classify Thread.java methods —

1) Methods affecting the executing jvm thread, always static methods – sleep, yield
2) Methods affecting “this” which is a Thread object linked to a jvm thread. Always non-static methods – targetThread.set/getUncaughtExceptionHandler(), targetThread.isDaemon()

Those are the 2 most common types of Thread.java methods, but there are also —

3) Methods (very special) affecting b_o_t_h — targetThread.join(), targetThread.interrupt()

4) Methods affecting no particular thread, but entire JVM — getAllStackTraces(), set/getDefaultUncaughtExceptionHandler()

threadA triggering immediate reaction on blocked threadB

Note this write-up is about _immediate_ reaction in a _blocking_ thread B.

If B is not blocking, then reaction can’t be immediate.

1) If executing thread A calls “threadB.interrupt()”, B sometimes gets an immediate exception. This is the original “simple thread communication”, before JDK 5 added …

1b) throwing an exception in a Callable task (on Thread A) will cause the blocking thread B to throw exception while blocking on futureA.get()

2) threadA.join() will cause the host thread B to block until A exits. When the operation in A exits, the exit will release ThreadB immediately.

I believe all of them rely on
3) wait/notify

msg overflow ] JMS^tibrv #60sec

Message overflow is a frequent headache in MOM. Basically consumption rate (possibly 0) is slower than production rate, eating up storage capacity, either in memory or on disk.

  • eg: JMS Topic with NDS (non-durable-subscriber) only — almost free of overflow. Bonnie said broker will discard. Jerry said broker keeps track of alive subscribers. Every incoming message is guaranteed to be delivered (by retry) to each. Broker must persist pending messages. When a subscribe disconnects gracefully, broker no longer needs to keep any pending message for her.
  • eg: chatrooms don’t persist data but what type of MOM is that? probably NDS topic
  • eg: JMS queue. While any number of producers can send messages to the queue, each message is guaranteed to be delivered, and consumed by one consumer. If no consumers are registered to consume the messages, the queue holds (on disk) them until a consumer registers to consume them.
  • eg: JMS temp queue??
  • eg: regular queue? In SIM upfront, unread messages –persist–
  • eg: mailing list (topic with durable subscribers)? –Persist–
  • eg: JMS topic without durable subscriber? see post on message retention
  • eg: tibrv CM? Storage is the ledger file. –persist–
  • eg: tibrv non-CM? market data feed? Discarded but how soon? 60 sec by default? Yes, in slow consume and fast producer scenario message lost will be possible — http://arun-tibco.blogspot.com/2010/09/tibco-rv-faqs.html

 

indexing hashmap-based cache for real time query (UBS

There might be other posts in this blog, but take this as a refresher…

UBS (Stamford, not JC team) equity system has large data set in memory. Perhaps a hell lot of market data. I was told the system was so well-tuned that it needs just one full GC run each day (See 2 other posts on “1 GC/day”). It’s presumably based on hashmaps or a key/value noSQL DB

What if I want all the IBM trades over the past 5 days, but hashmap key is something like confirm-ID or trade-ID but not stock symbol? This requires a full scan of the entire universe of trades.

Gemfire suggests that an index is much faster than a full scan. (Probably same in SecDB and Sandra) an index is a separate map of (stockSymbol -} confirm-ID) or a simpler map of (sotckSymbol -} tradeObject) [1]. If you want a range select like “stock symbols starting with IB”, then you need a RB tree, or a skip list tree.

[1] I feel confirm-ID is more flexible. You can easily make the cache distributed.

A radical approach keeps everything in DB, and front it with a DB-cache. Full scan scenario? You hit the DB index. However, b+tree index is optimized for disk, sub-optimal for in-memory. A more serious penalty is network/IPC latency, even if you run the entire DB in the same Unix box. Admire the _single_ JVM solution !

simple JMS publisher (windows) + timer thread

import java.util.Date;

import java.util.Properties;

import java.util.Timer;

import java.util.TimerTask;

import javax.jms.JMSException;

import javax.jms.ObjectMessage;

import javax.jms.Session;

import javax.jms.Topic;

import javax.jms.TopicConnection;

import javax.jms.TopicConnectionFactory;

import javax.jms.TopicPublisher;

import javax.jms.TopicSession;

import javax.naming.Context;

import javax.naming.InitialContext;

/**

 * can run in Windows!

 *

 * @author bt62935

 *

 */

public class SimpleRunAnywherePublisher extends TimerTask {

 

      public static final String INITIAL_CONTEXT_FACTORY = “weblogic.jndi.WLInitialContextFactory”;

      public static final String PROVIDER_URL = “t3://…..”;

      public static final String TOPIC_CONNECTION_FACTORY = “ArbPad.TopicFactory”;

      public static final String TOPIC = “ArbPad.Topic.ETF.BondPrice”;

 

      public static final String TEST_MSG = “Test message “;

 

      public static void main(String[] args) {

            Timer timer = new Timer();

            timer.schedule(new SimpleRunAnywherePublisher(),1*1000, 1*1000);

      }

 

      public void run() {

            Properties prop = new Properties();

            prop.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);

            prop.put(Context.PROVIDER_URL, PROVIDER_URL);

 

            TopicConnection conn = null;

            try {

                  Context ctx = new InitialContext(prop);

                  TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup(TOPIC_CONNECTION_FACTORY);

                  System.out.println(tcf.toString());

                  conn = tcf.createTopicConnection();

                  System.out.println(conn.toString());

                  conn.start();

                  TopicSession session = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

                  System.out.println(session.toString());

                  Topic topic = (Topic) ctx.lookup(TOPIC);

                  System.out.println(topic.getTopicName());

                  TopicPublisher tPub = session.createPublisher(topic);

                  System.out.println(tPub.toString());

                  ObjectMessage msg = session.createObjectMessage(TEST_MSG + new Date());

                  tPub.publish(msg);

            } catch (Exception e) {

                  e.printStackTrace();

            } finally {

                  if (conn != null)

                        try {

                              conn.stop();

                              conn.close();

                        } catch (JMSException e1) {

                              e1.printStackTrace();

                        }

            }

      }

}

 

wealth management is !! technology intensive

(Blog post)

 

In terms of technology sophistication and criticality, trading is way ahead of investment banking, portfolio management, wealth management, private banking, and traditional banking sectors such as loans, cards and trade financing.

 

(Incidentally, I think profit margin follows a similar pattern. Trading, investment banking and fund management including private equity have higher margins. Note these are entirely institutional. Nothing on the retail side is comparable margin-wise, but high net worth wealth management still offers higher margin than other retail businesses.)

 

Back to technology, investment banking (M&A, fund raising…) and fund management have far lower trading volumes (unless a hedge fund engages in HFT). They generate big profits not through technology but other means. Hiring managers in IB and asset management undoubtedly claim technology is critical but it’s not as critical as in trading.

 

One of the smartest colleagues in GS wealth management IT once asked in a town hall whether technology is a competitive advantage in the private wealth business. He was asking the business representatives on the stage. I remember answer was vague. Business said the most important feature they are still praying for is quick retrieval of any client’s full portfolio and its current market value on demand. Note there are (up to) millions of clients in UBS and each client could have hundreds (if not thousands) of positions held in their private accounts, and these positions could change any time as clients trade.

 

Nevertheless, these challenges pale against the technical challenges in high-volume electronic trading. Within the trading space, FI and commodities are behind eq and FX, except interest rate futures. Equity has the reputation of leading-edge technology.

unspoken assumptions about a Libor value

By default, Libor refer to the USD lending rate. Other currencies are actually covered by Libor too.

Usually people refer to overnight rate or 3-month rate, but actually Libor covers other maturities.

Libor is inter-bank lending. Borrower is a big bank and has the best credit rating but lower credit than US government. That’s why TED spread is always above 0.

CDS basics

Background: Many speculators trade “credit products [1]” for a quick profit. In terms of hedgers, I guess bond underwriters may keep some of the new bonds during the bond issue, in which case they would later trade these bonds as part and parcel of the investment banking (underwriting) business.

At the lowest level of the product hierarchy, the underlying product is probably a corporate bond. Since there’s default risk, a common hedge is a CDS.

In fact, CDS is about the only hedge there is. You can also trade the issuer’s preferred stock, commercial papers etc as these are correlated to the bond in your portfolio. I feel shorting the stock is practical only if you intend to hold the bond for a few days.

[1] corporate bonds, CDS etc

Exchanges bring bids and offers together – price discovery through the open order book. In contrast, a pure-play clearing house leaves buyer/sellers alone negotiating trade price over phone/email, but once trade executes, real money is maintained at the margin accounts in clearing house. Clearing house recalculates mark-to-market (not PnL) and margin ratio.

If a counterparty (like Lehman) collapses, clearing house acts as a shock buffer, to break the chain reaction of defaults.

Someone said CDS is like an insurance on a corporate bond.

I guess counterparties leave their security deposit in the clearing house for the duration of the CDS.

Margin risk in CDS is tricky. Scenario testing is required. Concentration risk is the most obvious risk — if an account holds most of the securities about a particular issuer, and the issuer defaults, then no one wants to buy those securities.

FI desk — how long to hold a FI position

See also post on repo-based automatic financing for treasury trades.

A typical FI trading desk holds cash positions only for a few days, but could hold derivative positions till expiry.

A typical cash bond position ties up much higher capital than equity positions, so even the biggest banks don’t have so much working capital to hold many big FI positions for long. Even if a big FI position is profitable, it might take up too much capital so we can’t do enough other trades. Holding big positions indefinitely — is prop trading.

Margin account allows the desk to trade much larger volumes of securities. Common in options, futures, even FX spot, but I don’t think it’s common for cash bonds.

In this context, most common (and effective) derivative is a fixed-floating IR swap. It doesn’t tie up massive capital.

OODB indexing inside memory (java and c++

We understand how indexing helps disk-based query, but large in-memory DB also need indexing. Gemfire is one example. A query without the aid of an index iterates through every object in the collection. If an index is available that matches the where-clause, the query iterates only over the indexed set, thus reducing the query processing time.

Best example is a point query “where trade.cusip=IBM”. Suppose we have a gigantic hash map of 4GB with millions of {tradeId, trade} pairs. With index you iterate over a subset. Perhaps the index is a sorted map of {cusip, tradeId}. It’s sorted to provide range queries, and index field must implement Comparable.

How large can a hash map grow? I once put 200MB into a hash map, easily.

In practice, to keep 100GB data in one machine is too expensive hardware-wise. When such a big server become obsolete, it’s probably useless. Most people prefer the more economical server farm, where data is distributed.

The VMware book [[Virtualizing and Tuning Large Scale Java Platforms]] explains JVM memory size limits.

For a modest machine, the index itself could be too large to fit into one machine. Since in-memory index is usually a red-black tree (or skip list, but not a hash table), we need to split the index tree among physical machines. Beware b+tree is suitable for disk-based indexing only.

leverage entails margin re-calculation, collateral re-valuation

Leverage is buzzword. It's behind the 2008 GFC, which leads to de-leverage. It's behind futures, options, CDS

Leverage means buy/sell on margin. Margin needs to be revalued daily. Margin calls are used to protect the margin-providers i.e. lender or clearing house.

Margin calculation depends on the same valuation methodologies as pricing and PnL. Most cash products are easy to value. Many derivatives require complex valuation.

Q: What specific “modules” of math are involved?
A: margin ratio for long and short
A: CVA
A: collateral credit risk if it's a corporate bond.
A: valuation formulas

http://thismatter.com/money/forex/leverage-margin-pips.htm

price of futures^options; demystifying MV^PnL

Commodity future is the simplest example.

If a 2022 futures contract is traded today at a price of $1k, it’s not a present market-value, and it’s not an amount to be transferred from the buyer to the seller TODAY. The $1k is the amount to be transferred in 2022 — scheduled payment.

Unlike stocks and bonds, Futures prices are not pinned to current market-value, but are actually forward prices, or scheduled-payments. However, the scheduled payment affects cash flow immediately – end of today. Introducing margin mark-to-market rule of the clearing house! This rule converts[1] the scheduled payment due 2022 into a cash transfer EOD _today_ between the long and the short accounts.

[1] using discount factor 1 !

Q: So what’s the current valuation of a long futures position?
%%A: wrong terminology
%%A: a security has a valuation. Based on the valuation, a position has an unrealized-PnL
%%A: PnL = current MV (ie mid-market price) – trade price.

Option current prices are pinned to current market value, which is not same as the payoff on expiry. If an option is traded at $1k, this price is computed from a formula using expected payoff.

Note a holder of a Call/Put option owns a never-negative valued security. A short seller of any option “owns” a security of always-negative value. If you understand that option is an insurance, then Insurance company can only pay (excluding the one-time premium) and the insured can only receive.

[11]Cantor/eSpeed c++ #manyQ

Mostly knowledge-based QQ questions. I need to be selective what to study.

Q1: The reverse is common but when do we provide c wrapper around c++ classes?
A: internal implementation is c++ but clients need C API

Q1b: can c call c++ # <—— very common question
%%A: at compile time, c++ code may be uncompilable by a c compiler. CFRONT converts c++ code into c source code until exceptions were added to the c++ language. At run time, if I have object code precompiled from c++, can c call it? I think it’s often possible.
A: check out the C Application Binary Interface. If your C and C++ code are interoperable, it is because your C and C++ compilers also conform to the same ABI.
A: yes that’s what extern “C” is for.

Q: tool for binary code dependency? (I guess the dependencies are dynamic libraries, rather than static libs linked in.)
AA: ldd or objdump. See http://ask.xmodulo.com/check-library-dependency-program-process-linux.html

Q9: call java from c++, what’re the c++ function(s)?
A: create_vm(), CallStaticVoidMethod(), CallVoidMethod() etc

Q9b: How do I access an int field of a java class?
%%A: if I have a pointer to the java object, I should be able to directly access the int field

Q: how do u implement a singleton

Q: semaphore(1) == mutex?
%%A: no since semaphore in most implementations uses a mutex internally. Functionally they are identical
%%A: semaphore is often cross process. Mutex can also be used on shared memory.

Q: for a const method getAge(), can it return a ptr to a non-const int which is a field?
%%A: i have seen sample code, so probably compilable
A: tricky. P215 effSTL says that inside a const method, all non-static fields become const.

Q3a: what’s the return type of operator*()?
%%A: can be anything, just like operator[], but not void not empty

Q3b: How about qq[ operator T*() ] ?
A(now): is it the OOC to a ptr? Correct. See http://en.cppreference.com/w/cpp/language/cast_operator

Q: if Base class has a virtual method f(int), and Derived class has an overload virtual method f(float, char), is the Base f() accessible via a D object?
%%A: the D f() hides the base f(), but base f() may still be accessible using A::f()

Q: 1 process, 30 threads vs 10 processes * 3 threads each? Assuming there’s data sharing among the threads
%%A: avoid ITC and serialization
%%A (Now): I feel single-process has a single point of failure without redundancy.
A: depends on the IPC cost. If non-trivial cost then favor 30-threads.

Q: how do u change the default fair-share scheduling among threads? #<— uncommon
%%A: I can make some threads sleep or wait. I can control thread-lib-level priorities, but the kernel thread priority levels could be very coarse
%%A(now): if userland thread, then scheduling is done in the thrd lib.

Q: unix performance monitoring?
%%A: jconsole; top; vmstat; perfmeter

 

Q: Dynamic loadable library. How do we configure the system to load a new version of the library?
%%A: $LD_LIBRARY_PATH
%%A: just overwrite the existing *.so file??

Q: how to convert a ptr-to-non-const to a ptr-to-const?
AA: just assign it. The reverse assignment needs const_cast. Tested in g++. I feel this is an obscure technicality.

— communication layer
Q: how do I see syscalls and sockets open by a process?
%%A: truss; lsof; snoop/tcpdump; netstat

Q: practical use of signals?
%%A: kill, core dump, thread dump, suspend,..
A: I used q(trap) to install my signal handler in my bash

Q: what are named pipe? #<—– uncommon
%%A: I think they exist in the file system as fake files. “cat | more” uses an unnamed pipe I believe.
A: now I think I should just say “never used it”.

how bell+hockey stick move when vol drops or expiry nears

Q: how the bell and the hockey stick move when vol drops or expiration approaches?

Not complicated, but we need to Develop quick intuitions about these graphs. I feel these graphs are the keys to the mathematics.

Anyway, here are My Answers —

The Lognormal bell [1] Tightens as ttl [2] drops, assuming
– constant annualized vol therefore
– falling stdev (i.e. vol scaled-down for the shrinking TTL).

“Lognormal bell tightening” indicates lower stdev. stdev is basically the “scaled-down” vol.

Also, when ttl drops, the PnL graph drops towards the hockey stick. The hockey stick means 0 vol OR 0 ttl.

[1] the bell shape is skewed because lognormal isn’t symmetrical.
[2] TimeToLive, aka time to maturity or time to expiration.

operator << must be a friend function #tested

P 331 [[absolute c++]] gives the standard signatures of operator <<

— sound bytes —
friend — It has to be a friend function. Without “friend” keyword, compiler complains.
free function — required
method — is not possible. For a method, host object must be on the LHS of the operator, but q[ operator<< ] needs cout on LHS

listed stock option creation

Let's focus on a call option on a new stock symbol named “TYX”.

There'll be a seller and a buyer of the option. Initially, the option writer is the seller.

Is the exchange the counter party to every seller and every buyer? yes

Does the options exchange always create a buy and sell transactions at the same time? yes

Must a put option be created at the same time? No. Early option exchanges list only calls.

learning topics in options

A few loose “topics” —
a) option valuation at expiration and before
b) PCP
) log normal
) std dev
1) basic long/short positions => strategies like collar, condor, butterfly…
2) volatility and 1)
3) delta (and other greeks) and1)2)
4) hedging with 1)2)3)
) skew
) random variable
) binomial pricing tree

First realize that options are more complex than futures (which is more complex than forward contracts) —

* There are 2 prices — exercise and premium (bid/offer).
* There’s call and put, which are often related.
* option prices are sensitive to (the 3 Greeks)
** vol swings
** underlying asset price swings
** expiration date approaching

Next, focus —

– Focus on OTC. I feel listed options are more complex. Exchange must create a pair and maintain margins.
– Focus on American options. All listed options are American style.
– Focus on stock. Avoid index options as they involve cash settlement. FI options are way too complex. Currency option is also more complex as there’s no clear distinction between what we pay (premium and strike) vs what we get — both are “money”.
– Focus on long positions. Shorts are less intuitive but still important.
– Focus on calls first but soon you must deal with puts

reply-to — JMS vs email

If you see a JMSReplyTo header in a message, it may mean a forwarding address.

Think of email. Alice sends Bob an email with a reply-to header set to Casper. When Bob replies it goes to Casper. Same in a JMS work-flow.

That's a special use case. In standard scenarios, reply-to is an essential feature of the JMS request-reply model.

non-exchange-guaranteed drv

Background — Futures (and LISTED options!) are guaranteed by the exchange. Investor confidence. Now there are several important classes of securities not guaranteed by exchange.

* stocks – backed not by exchange but by the exchange members (biggest dealers), who assume the risk of renegade clients.
* Treasuries? need no exchange to guarantee it?
* muni – a dealer market. TMC is like espeed, just connects counter parties.
* corp bond

(^^^^^^ everything so far is transferable)

* IRS – non-transferable i.e. no secondary market. I don’t know how you can trade this instrument.
* CDS
* OTC stock/FX options – non-transferable
* FRA
* currency swaps (not sure about FX swaps though)

callback object – called by which thread@@

(See also post on generic callback in generic OO)

A novice developer first encounters callback functions. 2 years later she realize it’s actually a function pointer i.e. address of a function. For the callback to be registered with some Hollywood, we must use and understand function pointers.

Then the developer encounters the (anonymous) callback object, typically implementing a callback interface. This trivial idiom is extremely widespread but non-trivial in a concurrent OO context. Examples —

– the simplest observer in [[head first design patterns]]
– swing event listener  — always Objects
– onMsg / onMessage listener
– gemfire callback object and listener object – i can never remember the difference

In the simplest form, a callback object is a stateless wrapper over a function pointer.

Q: called on which call stack?
A: Long answer. The thread creating the callback object is not relevant. The thread registering the callback object with Hollywood is relevant but not the answer. Once the callback object’s address (not the naked function address, thanks to the wrapper) is saved in the framework, many threads can access it. Often it’s an internal framework thread.

[16] keep interviewing; leadership track record #XR

XR,

I feel someone like us might work towards 2 goals simultaneously —
1) I like your tip on “keep interviewing” so as to keep ourselves marketable. Aim for 4 interviews a year?
2) move up in some wall street firm. Perhaps more achievable by job-hopping.

More developers seem to follow the 2nd goal than the 1st goal. (Doesn’t necessarily mean 1st goal is less practical.) Perhaps such a corporate guy is an ostrich hiding her head in the sand, or a villager building a home below the huge Huang-He levee, where river bed is above her roof level

My wife doesn’t understand why I keep interviewing. She feels I should focus on my job and try to meet manager’s expectation.

I agree promotion is primarily decided by immediate manager. Still, some leadership track record and deliverable is often needed. Manager could give you such a project (as happened to me in 2009), or you might be lucky to get such an opportunity, which might happen to a consultant. If you delivery but don’t get promotion, you could change job (internally or quit) to move up.

Sometimes I like the opportunity to coordinate a complex joint effort with users and external teams. I did it in GS and quickly earned some trust and reputation. If you happen to know a system better than others, then you could play that role — Leadership track record in the simplest form.

Actually this track record might be more _visible_ than leading a team of developers on a small implementation. Managers, users and other teams may not really appreciate the challenges of implementations, but if they participate in your “joint effort” they sure understand its complexity. It’s probably unfair that some people do a bit but get lots of visibility; others do a lot but behind the scenes.

2 Hibernate IV questions

My hasty summary, to be validated —

* table per class hierarchy — just one table for entire class hierarchy

* table per subclass — one table per subclass + a “super” table for the super-class
** defining feature is the one-to-one mapping between the super-table-rows and sub-table-rows

* table per concrete class — one table per concrete (sub)class. No “super” table if the super class is abstract — base scenario.
** defining feature is the union query
—-

Q1: I have a table holding 2 types of rows. Half the rows are CashPayments, the others CreditCardPayments. I have 2 java bean classes CashPaymentBean.java and CreditCardPaymentBean.java. How do I configure hibernate mapping to map each CashPayment row to a CashPaymentBean and a CreditCardPayment row to a CreditCardPaymentBean?

Answer: This is about the 3 mapping strategies. Table per class hierarchy, per subclass, per concrete class.
For this case, need to use “table per class hierarchy”.
key words for this specific question: “discriminator column”,
<– this is interface

<discriminator column=”PAYMENT_TYPE” type=”string”/>

….

….

Q2: I have a lot of price data on IBM stock prices. I keep every price in the current month in main table, and older prices in history table. How do I configure hibernate to map a PriceBean.java to both tables, so I can load any price data into a PriceBean?
Answer: This question is also about one of the 3 mappings. It’s “table per concrete class”. This is the first time I look into the details about what the “table per concrete class” mean.


<union-subclass name=”PriceBeanCurrentMonth” table=”MAIN“>

<union-subclass name=”PriceBeanHistory” table=”HISTORY“>

On web service —

Q3: A web service client must authenticate with a web service, and then calls method1, then authenticate again, then calls method2. How can we avoid the 2nd authentication, which is unnecessary?
I have no idea about this.

On JDBC —

Q4: how is driver registered with driver manager when you do a Class.forName(…)?
%A: I remember there’s some magic in Class.forName(). Class.forName() dynamically loads the driver’s class file into memory, which automatically registers it with the driver manager

demo transform,for_each,operator()() with arg,pair,hash_set #10gen

Other features
– transform() with a home-made functor
– many for_each calls
– erase-remove idiom

——————
#include
#include
#include
#include
#include
#include
using namespace std;
using namespace __gnu_cxx;

hash_set uniqueChars(256); // only 256 characters exist in ascii
list abbreviations;

class suffixAdder {
    const char suffix;
public:
    suffixAdder(const char c) :
        suffix(c) {
    }
    // This operator() actually requires an argument!
    const string & operator()(const string & original) {
        return *(new string(original + this->suffix));
    }
};

void dumpList(const list & list) {
    copy(list.begin(), list.end(), ostream_iterator (cout, “n”));
}

void insertNewNodes(char c) {
    cout
            << "entering makeNewNodes() with a character in the original input — "
            << c << "n";
    transform(abbreviations.begin(), abbreviations.end(), front_inserter(
            abbreviations), suffixAdder(c));
    //dumpList(abbreviations);
}
void checkDupe(char c) {
    if (!uniqueChars.insert(c).second) {
        // insert returns a pair, whose second field indicates whether insert happened
        cout <<"Error: duplicate character : "<<c; // insert skipped due to dupe
        cin.get();
        exit(0);
    }
}
/* first pass scans in O(n) input array for duplicate characters.

* 2nd pass re-scans the input array and generates new abbreviations based on the existing population of abbreviations.

Suppose our 2nd scan is on the 4th character “x”
** Pre-condition: all existing abbrevations don't contain “x”
** Post-condition: all new abbreviations generated end in “x”

Number of abbreviations is 2 to the power of n (actually 1 fewer), therefore O(2 to the power of n)

This algorithm is iterative and more efficient than recursion. For a 200-character string, recursion would build a 200-frame stack.

*/
int main(int argc, char *argv[]) {
    //string input = “gfedba21”; // testing
    string input = string(argv[1]);
    for_each(input.begin(), input.end(), checkDupe);
    cout << "—no dupe found. Now generating abbreviations—n";
    abbreviations.push_back(“”);
    for_each(input.begin(), input.end(), insertNewNodes);
    abbreviations.erase(remove(abbreviations.begin(), abbreviations.end(), “”),
            abbreviations.end());
    dumpList(abbreviations);
    cout << "Total # of abbreviations = " << abbreviations.size();
    cin.get();
}

self-management: Part 2: demonstrate@ CV+interview

Tip: See blog on [[vague vs normal vs specific answers]], but in this case, be specific if you want to demonstrate these qualities.

Tip: you don’t need to prove anything if you already have convincing team-lead experience on your CV.
Tip: Tell stories
Tip: show your familiarity with the typical front office culture.
Tip: demonstrate you know how to work with QA team – give them the docs on build/deploy, DB deployment
Tip: demonstrate your documentation best practices – wiki (GS), jira (GS, ML), cheatsheet/runbook

Tip: Humor? If you are 100% sure about side effects, then I think it can help demonstrate communication effectiveness, but I feel a lot of good self-running developers aren’t humorous.

self-management: Part 1: managers’ negative xp

If you ask Wall St IT hiring managers for important personality traits, the most frequent answer is “can get things done on his own”, “less hand-holding”, “low maintenance”, “won’t get stuck”, “…. which is why we want senior, experienced developers”.

Maybe I’m wrong but i assume they are speaking from experience.

Q: what are the negative signs and examples managers have seen in their experience?
A: (see blog on know when to depend on others and when to master a subject) always asking for colleague’s help.
A: inability to summarize issues in writing.
A: inability to generate presentable reports for upper management.
A: can’t get to the point quickly
A: can’t take control of a crisis situation
A: some developers can’t effortlessly, confidently chair a meeting.
A: asking the wrong question, esp. in a mass email. Wrong Like wrong phrases, __indecent_exposure__,
A: problem interfacing with other teams, and esp. teams under rival managers.
A: some developers need manager to remind her over and again some details of the deployment/testing process
A: it could be a good habit to let your mgr proof read your important email to users, but that’s often a sign of hand-holding.

busiest drv markets

Q: Most important types of option contracts?
A: stock options, FX options (mostly OTC, but also on Philly exchange)

Q:Simplest types of option contracts?
A: stock options, clearly simpler than FI options

Q: Most important types of futures contracts?
A: IR futures — including the Bund / Tr futures (long term IR) and (short term IR) eurodollar futures

Q:Simplest types of futures contracts?
A: commodity futures

Q: Most important types of forward contracts?
A: FRA

Q:Simplest types of forward contracts?
A: equity forward

Q: Most important types of swap contracts?
A: IRS, FX swaps

Q:Simplest types of swap contracts?
A: IRS itself. IRS is a distinct type of swap, in a class of its own.

typical FRA scenario, inspired by CFA Reading 71

Today Jan 1 end user (say a top-rated borrower like IBM) anticipates it needs to borrow $xxxx in 3 months (i.e. 1 Apr), for a term of 6 months. A dealer bank (say GS) quotes 550 bps/year. IBM agrees.

Q: what is the quotation about, specifically?
A: GS offers to lend IBM $xxxx for a 6-month term from 1 Apr to 30 Sep [1]. Rate is 550 bps, regardless of the fluctuating 6-month Libor rate.

[1] more likely to be a fixed 180 days. I feel this way Libor rate is more comparable.

Q3: Locking — IBM effectively locks its borrowing cost at 550. Why?
A3: IBM will inevitably borrow from open market comes 1 Apr. If that becomes 600 bps, IBM pays 600 but _receives_ the difference (from FRA contract). If that becomes 500, IBM pays 500 but _pays_ the difference to GS.

Q3b: why “inevitable”? Why not borrow from the FRA dealer.
%%A: I guess GS may not have enough fund to lend; IBM may borrow from multiple banks; IBM may cancel its project. IBM just wants to lock down the borrowing cost in case it needs to borrow on 1 Apr.
%%A: the contract doesn’t require both parties to physically /close/ the 3-month loan. The contract stipulates cash settlement as in A3 above. Therefore IBM doesn’t have to take the loan or take it from GS.

If Libor becomes 600 bps on 1 Apr, then IBM is lucky to lock its borrowing cost at 550 bps. It receives a sum from GS equal to the difference.

Q5: Why lucky?
A: without the FRA, IBM is likely to end up paying 600 bps 😦
A: withe the FRA, IBM gets to borrow at a pre-agreed lower rate of 550 bps, or IBM could cancel the project and pocket the FRA profit as a windfall.

Q5b: what if it turns to be 500 bps?
A: IBM will end up paying 500 on the physical loan, but on 1 Jan, as a borrower IBM needs predictable borrowing cost, so it can plan long term.

Therefore IBM wants Libor to rise i.e. it is long Libor, but IBM doesn’t get unlimited profit as it probably still needs to borrow at the high Libor rate.

Q8: in a commodity (similarly stock / bond / FX) forward contract, there’s a physical item to be delivered at expiration. What’s the “item” in FRA?
A: At expiration on 1 Apr, IBM receives the right to the 6-month deposit interest at prevailing Libor rate. At the same time it must pay the 550 bps to GS. Net payment is not on 1 Jan, not 30 Sep, but on 1 Apr.
A: The “item” is the 6-month deposit interest at prevailing Libor rate, be it 600 or 500. IBM pays 550 bps (times notionally, and prorated 6-month) to receive this item.

Q8b: how is this similar to a commodity forward?
A: At expiry, IBM receives the commodity, and pays a pre-agreed contract price, not the prevailing price. In FRA, the physical deliverable is … a piece of paper for the interest on a CD, 6-month CD at the prevailing Libor rate at, say, 600 bps / year.

popular FI drv in Asia and in muni trading desks

According to a FI professional in Singapore…
Structured/exotic FI derivatives are much less liquid in Asia than in US.
MBS/ABS? —- People trade US MBS.
Credit Default Swaps — this is main credit product, so popular.
Collateralized Debt Obligations — CDO was very hot before 2008 financial crisis but seems dead after financial crisis
interest rate swaps — this is main rates product, so popular.
swaptions — main rates product, popular.
—-
Citi muni trades a lot of swaptions, caps/floors, treasury futures and also CDS. IRS is the cheapest and most basic derivative, and probably the most widely used.

As of 2012 in US, most common IR derivatives after IRS are 1) Swaption and 2)caps/floors

euro dollar deposit, spot, forward, FRA, IRS

Eurodollar (without “futures”) is a monolithic (non-derivative) CD with a term always from _today_ for 1 day (overnight), or 7 days, 14 days … 3 months, .. up to 12 months.
* Eurodollar deposit rate is a always spot rate, not a forward rate.
* Libor 11am announced rate is always a spot rate, not a forward rate.

In contrast,
– an ED futures price is always a forward rate, not a spot rate.
– the rate in an ED “contract” is always a forward rate

An Eurodollar futures contract is a loan with a 3 month term always starting on an IMM date (never today).

In the interest rate business, “Spot rate” has broader, more generic meanings but here we focus on USD short-term spot rate. The libor eurodollar deposit rate is exactly that. Zeros (STRIPS) are also relevant. Example below is a Zero with semi-annual compounding.

Suppose spot rate == 250 bps/6months for a 2 year term (ie 4 x 6 months), it means on the present market, people are willing to close deals like “Take my $1M today. Repay in 2 years (1.025*1.025*1.025*1.025)*$1m=$1,103,800”

When studying IRS or FRA, always always bear in mind eurodollar is nothing but a simple time deposit but depositor is a lending bank and interest payer is a corporate borrower.

FRA is an contract or agreement referencing “tomorrow’s [2] published libor rate” for eurodollar deposit rates.

[2] In reality, “tomorrow” is more likely months away.

financial jargon: forward rate

Forward rate values are derived (from bond prices over different maturities). Forward rates are a useful way to uncover the expected interest rate movements in, say, 5 months. If you believe interest rate will exceed that [1], then invest in short-term bonds so you can reinvest in 6 months at the higher rate you foresee. The above was based on a FI math text book, but the spot rate (underlying instrument of FRA) is also quoted in Libor as eurodollar deposit rates.

[1] “that” being the market’s expectation. Market prices of STRIPS (of various maturities) collectively reveal something [2] to the trained professional — investor community’s expected interest rate movement over the next x years. In other words, forward rates. Therefore, forward rates (over various periods) is yet another measure of sentiment, yet another characterization of the current market.

[2] Suppose the revelation is a series of 6-month forward rates, 6 months forward, 1 year forward, 1.5 year forward, 2 years forward… Now, a 5-year c-strips is an instrument locking in all those forward rates…

forward contract: my”invention”in 1997

I once told an NUS classmate (Liu Ning?) that after market close a buyer and seller can agree to trade a stock. Over the weekend they agree on a price. Whether it’s higher or lower than the Monday opening price, they execute regardless. This is a forward contract !!

CFA covers 4 major derivatives, and forward is the basis of 3 of them —

– forward is basis of IRS
– forward is basis of futures.

FRA is the most important type of forward.

equity forward is the simplest forward, followed by bond forward.

what exactly is traded@@ the RIGHT to demand…cash or asset@@

A tradable bond is a transferable “right to demand coupon+principal payments”. Was a paper certificate.
-} An MBS is a transferable “right to receive part of monthly installment by borrower”

A stock is the most intuitive tradable instrument as it represents part ownership of a company. Was a paper certificate.

A tradable call option is a transferable “right to buy the underlying”. However, when the underlying is a bond, concept is less intuitive.

A tradable put option is a transferable “right to cash in the underlying instrument at a preset sky-high price”. This is less intuitive. A right to sell IBM at $999,000 a share is valuable provided counter-party guarantees to buy it from us.

A basic forward contract is probably not tradable or transferable as it’s a bilateral agreement. Is a swap tradable? I don’t think so.

A copper futures contract is a transferable “right to demand delivery at the specified date, at the trade price[1]” but I think this is like a “call future”. How about a put …..? No need to go into that for the purpose of the post. Here we just want to get to the bottom of what’s traded in a copper futures contract. Now we know.

[1] which is NOT specified in the contract. A futures contract specifies everything but the price.

another basic difference iterator^container^algo

(Why bother? Well, you need to know these when you debug STL or extend STL.)

– Containers — are class templates. 100%
– Algorithms — are function templates. 100%

– iterators? A beginner can safely assume that Most of the time iterators are defined inside each container template as a Member type. Since a container has a dummy type T, the iterator must be a class template of T (or a typedef thereof), a Nested class template of T, presumably, inferred from the syntax :

vector<int>::iterator

– The container/algo/iterator adapters are typically class templates
– functor are typically class templates

A trivial consequence — the declarations of containers and iterators are complicated by the templates. Algorithm declarations are simpler in comparison.

%%jargon — describing c# enums

Consider public enum Weekday{Mon=1, Tue, Wed, Thu,Fri,Sat,Sun} This declares an enum TYPE.

Since these aren’t singletons, we would get many INSTANCES of Weekday.Wed (being value type), but only 7 MEMBERs in this Type. At runtime, we generally work with (pass and receive) INSTANCES, not MEMBERS. Members are a more theoretical concepts.

Each MEMBER has a name and an Integer value. Only 7 names and 7 integer values in this Type. (Warning – Names are unique but not integer values.)

We can get name or integer value from an INSTANCE.

4 ways to characterize MOM

A beginner should internalize these characteristics until they become 2nd nature.

* queue ie point-to-point –vs– unicast topic ie pub/sub [1] –vs– multicast. This is the most important difference.

* guaranteed (reliable) vs non-guaranteed. Multicast can be reliable too.

* Within the pub/sub unicast topic modle,
** there is durable sub vs non-durable sub
** there is persistent delivery vs non-persistent. Note this only applies to unicast, and only covers producer->broker leg, NOT broker->subscriber

* simultaneous broadcast like radio –vs– individual delivery like mail. P2P is always mail style.

* tcpip vs multicast over udp

— the well known
* sync vs async. Only relevant to unicast receivers. Multicast is always async. Sender is always sync.

* server push or client pull. I think client pull is synchronous as polling client usually blocks.

bond duration(n KeyRateDuration) #learning notes 2

Jargon warning: yield is best written in bps/year, like 545bps/year. If you say 5.45% it gets ambiguous in some contexts such as modified duration. “1% rise in yield” could mean 2 things

– 5.45% —-> 6.45%,
– 5.45% –x-> 5.50% is a misunderstanding

This is not academic; this is real. Portfolio sensitivity to yield fluctuations is a key concern of banks on Wall St or Main St. It’s all about x bps change in yield. (From now on, always use bps to describe yield; avoid percentage.)

DV01 is dollar value of a “basis point”, free of any ambiguity.

DV01 and modified duration are 2 of the most widely used bond math numbers. Both are derived from bond cash flow.

Mac duration — definition — weighted average of wait time for the cash flows.
Mac duration — usage — not much in real world trading

Modified duration — definition — Mac duration modified “slightly”, by a tiny factor. REDUCED by (1+r)
Modified duration — usage — more useful than Mac duration. It measures price sensitivity to a yield shift, on a given bond.

For a simple example of a bond with modified duration of 5 years. 100 bps yield change results in a 5% dollar price change.

Key Rate Duration is an natural (and intuitive) extension of the duration concept, useful in MBS etc.

stl pair template #briefly

In java, the map entry inner class is seldom used by developers, but stl pair is different. See [[STL tutorial and ref guide]] large and realistic example.

I believe all experienced STL users will sooner or later memorize some basic operations on pair. Here are the top 5 —
– cvctor  ie conversion ctor
– OOC ie operator-overload converters
– less-than operator — java's Comparable is more clean and simple

A concrete pair class can be subclassed.

IRS pricing <- forward <- spot rate

I don’t think this needs a real trading system. low volume, simple math

Pricing a swap is all about predicting actual floating payments or future libor[4] rates or forward rates at each quarterly reset date.

[4] For muni, libor is replaced by the SIFMA muni swap index

http://www.bionicturtle.com/learn/article/forward_rates_and_spot_rates/ illustrates derivation of a single forward rate from a series of spot rates. “forward rate is a prediction about future spot rates.”

Given
1) all the spot rates of ED deposits (not futures)
2) market (forward) rates of ED futures,
those future libor rates on each quarterly reset date are solvable. This is the basis of floating payment estimation.

In fact, “expected” 3m libor rate on each quarter boundary date (IMM date) is published in eurodollar futures  market[1]. Therefore the derivation is IRS pricing <- forward rates <- ED CD rates + ED futures rates. Note the floating leg comprises periods (aka coupon period). Pay at end of period but payment amount reset at onset of period. See also post on discount curve.

[1] ED futrures rates are very different from the deposit rates announced by BBA. There’s no “market” for deposit rate.

What If I am convinced 3m USD libor will hit 120 bps/yr on 1/1/2020 but the derived libor is 200 bps/yr? How do i lock in the 1.2%? Well, the relevant eurodollar futures contract is trading at 98. I would buy it and hope it becomes 99.

What Wall St xp valued in Singapore

(blog post)

If an IT veteran comes to Singapore job market from silicon valley, he is welcome by Singapore employers, but if he comes from Wall Street, he is more valued.

Singapore positions itself more as a financial center than a technology hotbed. In many arenas, Singapore is playing catch-up with world leaders. Singapore is more successful pushing to the forefront in oil, air transportation, freight logistics (best sea port), medical services, and financial services, esp. commodities trading.

Singapore is somewhat less successful in electronics (once successful), life science, research, telecom…

A technology hotbed requires more resources — more talent, more research, more funding … than city state Singapore has.

One of the wall st experiences/know-hows needed most is real experience in trading system architecture.

what is a cap (and floor) — a few points

Jargon warning — a bond has an _issuer_ and a _lender_ who receives coupons
Jargon warning — an option in Eq/FI has a _holder_ and a _writer_
Jargon warning — Don't worry about the concepts of “caplet” or “cap”. First understand the basics of call option.

A cap is an instrument combining a floating bond + an option, Specifically, a cap models “paying-capped-floating-coupon” using “holding a call option”. This sounds a mouthful, but in plain English, “I pay you a floating coupon but you write me a call option”

A call option's payoff has infinite upside. A floating coupon is also unlimited. A floating bond issuer has unlimited cost, so he needs an equally unlimited protection.

As a bond issuer, I issue a floating bond but hold a call option (as protection).

y Singapore IBanks pay on-par with Wall St #tech

The higher the position, the more on-par.

* these international (not local) investment banks (not commercial banks) have budget.

* Most trading systems have a tiny elite team of super developers, whereas other industries employ armies of developers. An ibank would rather get 1 rock star than 10 mediocre.
* Yes an ibank could hire experienced java developers at $5k but they aren’t battle tested in trading systems.
* recruiters would only send in experienced candidates.

I don’t know how, but gov can probably influence private sector hiring. If this is the case, then Singapore gov is probably encouraging the “on-par” situation. Singapore public sector has the tradition of paying top salary for top talent.

Look at the GIC guys. Even a young graduate can earn S$120k. It’s obvious to me that they aren’t really different from their peers in “ordinary” sectors, but the vacancy simply comes with that price tag. Singapore employers (private or public) willingly pay the premium.

S’pore is in constant competition (and battle) with Hongkong, while rising up to London and New York. They compete for big banks, for hedge funds, for ECNs, for IPOs, and ultimately for talents. Singapore gov is more serious (takes more actions) than many governments to attract high-caliber talents in upstream sectors such as high-finance. The higher your value-add, the more they want you. Sadly, they can only measure your value-add by your income.

pipe, stream, pesudo file, tcp-socket#xLang

* Java has a family of IO classes;
* c++ has a family of stream classes derived from class ios;
* unix has various file-like things.

“pipe” and “stream” are 2 general terminologies for an input/output destination with sequential[1] access. A file is one subtype of stream. Therefore java and c++ access files using their family of classes above.

[1] c++ gives each sequential stream a get-ptr and a put-ptr.
A named pipe is an entity in the file system….

TCP (not UDP) socket is a stream-oriented protocol. Sockets, either unix domain or TCP (not udp), is also like a pipe/stream. In fact, Unix treats any socket as a file so you can read and write to a it like a file. Perl liberally “confuses” file handles and sockets, just as C uses the same type of file-descriptor-number for files and sockets.

TCP (not UDP) is ordered — if two messages are sent over a connection in sequence, the first message will reach the receiving application first. When data segments arrive in the wrong order, TCP buffers the out-of-order data until all data can be properly re-ordered and delivered to the application.

Python wraps the socket descriptor number in a socket object, but you can still get the underlying descriptor number by mySocket.fileno()–

import socket
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print mySocket.fileno()

y sybase still popular on Wall Street

Reason: years ago, sybase made sure it had the fastest insert performance, targeting market data feed. However, the fastest market data feed uses flat files, according to a 2sigma engineer.

Reason: for smaller databases, sybase outperforms DB2
Reason: oracle is not a friendly company.
Reason: As of 2011, MSSQL is still quite similar to sybase
Reason: bcp is supposed to be the fastest way to store large amounts of data
Reason: mssql is not optimized for unix but most wall st database servers run unix.

A few answers from veterans
1) Miao did data warehousing for more than 10 years. Sybase is the most “memorable” RDBMS, mostly due to performance. Miao summaraized “Oracle — marketing, Sybase — performance”. I mentioned that sybase runs on unix and windows — one size fit all, whereas Oracle is mostly used on unix, with more opportunity for customization and optimization. However, Miao shook his head and said sybase performance wins. BCP (“Bulk CoPy”), the sybase Bulk loader was singled out as high performance.

2) my Wall St. DB2/sybase trainer said sybase performs better for small tables (up to 100 mil rows) but favored DB2 for large tables.

3) another Wall St. veteran told me sybase syntax is convenient. Personally, I feel sybase is no inferior than Oracle, but with convenient syntax.

These are the sybase users I know — GS, MS, ML, Citi, Barc

y sybase still popular on Wall Street, again

Despite many people complaining and predicting the decline of sybase on Wall St, sybase continues to be the database of choice in everyday decisions.

Protection — Sybase was built for Wall Street. It doesn’t have major shortcomings for Wall St.
Protection — sybase is considered robust enough.
Protection — sybase tuning is much easier than Oracle, according to an Oracle employee
Protection: performance — One veteran, a data warehousing expert, found bcp much faster than Oracle or others. My DB2 trainer said for small tables (below 100 mil rows) sybase outperforms Oracle/DB2

Protection: legacy — As explained in my blog, a lot of Wall St banks prefer stored procedures rather than embedded SQL in java/c/c#. They go to extreme lengths to externalize all embedded queries into stored proc. As a Wall St veteran puts it, to convert Sybase stored proc to Oracle is such a big effort it’s like rewriting the app. I feel it’s like rewriting from C to java

Unlike java/dotnet code, SQL is dense in business logic. About 99% SQL source code is pure business logic, but less than 25% of java code is business logic. To rewrite a single SQL from Sybase syntax to Oracle is often equivalent to rewriting a few java classes. Risky, test-intensive, fearful, complicated. Backward compatibility is hard to prove. Even embedded SQL use Sybase features, so converting to DB2 will require backward compatibility assurance as well.
 
New applications might use Oracle, DB2 or MSSQL.

swing/wpf #1 primary design pattern@@

Someone asked me to name the single most important design pattern in swing. I feel a number of design patterns are equally fundamental and widespread in swing

* producer/consumer — main pattern in thread communication including task/event processing among threads. Low-level.
* observable — main pattern in communication between UI components
* MVC/MVVM — main pattern in component object composition or each UI component

Other patterns —
Pattern command — as wpf commands and in the form of runnables like invokeLater()
Pattern singleton — not strictly, but a lot of swing objects are singletons by nature.
Pattern Composite
Pattern Builder
Pattern factory
Pattern mediator — http://www.howdoicode.net/2012/07/wpf-view-model-communication.html
Pattern visitor — to visit a family of visual components

prevent heap instantiation4my class #part2

[[C++FAQ]] and [[More Eff C++]] both cover related topics.

I feel it’s very useful to have classes that can only be instantiated on stack, because stack-variables are automatically reclaimed.

With these classes, no double-delete, no dangling pointer, and most importantly, no memory leak. Remember memory leak is the most hidden — hardest to identify.

straddle – basics

* put/call simultaneously
* Buy only — for long straddle [1]
** max loss is the 2 premiums we pay

* payoff looks like a “V”
** losing if too quiet
** Profitable in both extremes
*** obviously long vega

Straddle is the most basic among all “strategies”. Quite common.

[1] short straddle is also common

prevent heap instantiation4my class#Part 1

(Much of this write-up is based on http://www.cprogramming.com/tutorial/operator_new.html) It’s useful if we can restrict a special class’s instantiation to the stack only, and disallow heap allocation. Overload op-new for your class, and make it throw exception unconditionally? Alternatively, can we declare it but leave it unimplemented like —

class Myclass {
public:
void* operator new(size_t);
void operator delete(void*);
};

Both of them are by default static members. Overloading can be used for many purposes. For example, we may need to alter the exception thrown in case of failure–std::bad_alloc–and throw something else:

The relationship between Operator New and the New Keyword

Don’t be confused by the fact that there is both a new keyword and an operator new. When you write:

MyClass *x = new MyClass;

there are actually two things that happen–memory allocation and object construction; the new keyword is responsible for both. One step in the process is to call operator new in order to allocate memory; the other step is to actually invoke the constructor. Operator new lets you change the memory allocation method, but does not have any responsibility for calling the constructor. That’s the job of the new keyword.

It is possible to invoke the constructor without calling operator new. That’s the job of placement new