what appear af keyword q[OPERATOR] in c++src code

new
delete
()
[]
->
>> and the opposite (hard to type in blogger)
*
&
double
char
char*  // yes you can
string
MyClass1 // name of any class you created — i believe it’s usually unambiguous to the compiler.

Q: how about qq(vector)?
A: yes tested. No return type please!

generic callback in a concurrent java/c++ sys

(Note OO is a development-time concept. Once compiled, an OO program looks no different from a C program with tons of structs and function pointers.)

Most financial systems today are concurrent OO systems. The lowly callback pattern is extremely common but actually requires a thorough understanding of both thread and object interaction. Let’s examine some. Note just about every player in the callback scenarios is a pointer, including function pointers.

In the simplest 1-thread case, an observer pointee registers interest with a subject object, by giving its own address. After subject state changes in Thr 1, the same thread loops through the list of observers and invokes the callback method on each observer. Note the observer object must not be deallocated.

For onMsg() in tibrv or onMessage() in JMS, there’s a remote “upstream” thread in the message broker’s PID/runtime, and there’s a separate downstream thread in the listener’s PID. I believe this thread starts out blocking for messages. Upon receiving a msg, the runtime somehow wakes up this blocking thread and this thread invokes onMsg() on the listener pointee. Meanwhile what’s the remote upstream thread doing? Simplest design is synchronous — upstream thread waits for the listener thread to finish. This means the upstream thread can only dispatch the message to remote listeners sequentially. I feel it’s much better to get the upstream thread to return right away after sending the one-way-message[3] (see Doug Lea’s book) so this thread can contact the 2nd listener in the list. Rewind to registration time — Any thread could register the listener with “Hollywood”. This thread could terminate immediately but the listener pointee must live.

[3] in classic Reo, we actually send one-way messages to the market-facing gateway. We get the status message on a separate thread via onMessage().

In C/C++, you can also register into “Hollywood” a ptr to a free func. No object, usually no state (unless the free func uses stateful static objects). Free functions are free of destruction. Hollywood could save the (function) ptr in any collection. When there’s an event, Hollywood calls us back, in any thread.

c++function entities — 2nd class citizens@@

Compared to java, I feel c++ is more flexible, “creative” and “loose” with functions; c++ weaves functions more into its rich syntax; and c++ apps rely more heavily on passable function entities. Any algorithm (any trivial body of code) can be passed around like a variable or object.

Inside the computer, a function (like objects) occupies a chunk of memory in “text” section, so it’s reasonable to pass its address to where it’s needed. C++ lets your *package* algorithms into passable function entities. These function entities are often stateless[2]. Consider functional programming. I call these 2nd-class citizen objects because they normally do not have state, variables, virtuals etc.

(Java Threads also should not but often have state.)

Java has interfaces and Method objects. C++ has func pointers and functor objects. Both designs are powerful, widespread and proven.

[2] functors are almost always pbclone in STL. Some functors are stateful — (beside generators) Dinkumware’s hash tables have hashing traits/policies as state in the hashing functors. See separate blog post.

http://www.newty.de/fpt/fpt.html#callconv shows some func ptr syntax examples —

someObject.someMethodReturningAFunctor()(arg1, arg2); // not the number of () pairs
(instance1.*pt2Member)(12, ‘a’, ‘b’);

(*this.*pt2Member)(12, 'a', 'b');     
(instance2->*pt2Member)(12, 'a', 'b');  

(*(someComplexExpressionReturningFuncPtr))(arg1, arg2)

struts self-quiz

Q: what kind of obj is returned by execute()? How is it related to the httpRequest’s forward() call?
Q: how does execute() get the form input data? P741
Q: how many servlets are there in a typical web app? how many are there in a struts app? P743
Q: a session is for one web app only?
Q: how 2 share a session obj btw 2 web apps?

SureStop and Thread.stop()

SureStop.java from Paul Hyde seems to be fairly professional[1] and robust. But I wonder how it avoids the deadly pitfalls of Thread.stop()? Answer is in the post on unlock@thread death

[1] Paul even included a test.

Sometimes we do want to forcibly kill a runaway thread. Look at Pushmail. Also,

* a thread stuck in an infinite loop
* a thread blocked in IO
* a thread trying to acquire a lock
* deadlock

Many useful implementation techniques
– SureStop.java is Based on the simple self-running object. In fact SureStop is an extremely simple implementation of a simple idea, given the power it has. Simplicity is power.
– uses highest thread priority to avoid starvation.
– daemon thread

option-related jargon encountered recently

You asked what option-related jargon I learned recently. Here are some
(“vol” and “volatility” intermixed)

greeks of common spread portfolios like straddle, strangle, condor, butterfly… ?

Put-call parity
synthetic put, synthetic call, synthetic long/short underlier. WHY would traders prefer the synthetic forms to the simpler forms?

variance swap? Why is it so popular?
barrier options?

how does dividend announcement affect options
how do people forecast dividends many years into the future?
How is libor curve affect option pricing
forward curve bootstrapping
forward price and how is it estimated
ex-dividend day and how it affects option exercise
repo curve used in option pricing?
dividend blending in forward curve bootstrap?

local volatility?
Historical vol
Realized vol
implied vol
volatility cone

volatility skew — why
volatility smile — why
How is fat tail related to skew/smile
higher moments of the price distribution function

VIX – most important index on options
typical values of VIX values
typical values of stock volatility values

arctan surface – for what underliers
taylor surface – for what underliers

price relative
What is the expected daily price relative for a stock with expected volatility of 20%

vol of ETF, indices and single stocks
vol of currency pairs
vol of interest rates

what applications do option traders need
what market data do option traders need
How up-to-date and live do option traders need their market data to be
How are vol surfaces calibrated, finalized and published
What types of users rely on vol surfaces and why

Greeks represent exposures. Which exposures do traders want to avoid by hedging, and which ones they don’t want to avoid
European/American/Bermuda options
among ATM / ITM / OTM what type of options are most popular and why
log-normal distribution vs normal distribution
How do traders price OTC options from listed option prices
What risks do long-term option contracts create and how to reduce those risks
how many underliers have listed options
wings of the volatility surface
Basic techniques to remove outliers during volatility fitting
cost of vol fitting
basic steps to fit an entire surface from a bunch of option quotes on different expirations and different strikes
precisely when would an option holder want to exercise an option?
assignment process upon option exercise
typical values of delta for ATM options, OTM and ITM options
when would delta exceed 1
option decay
Basically, how is historical vol measured
Can you compare implied vol against historical vol

Mockito partial mock #googlemock@@

partial mock using thenCallRealMethod()

First understand the norm — full mock. Usually your MethodUnderTest is on Object A, which depends on Object B. Object B is hard to
instantiate => mock up B. ALLLLL the methods in B will mock using thenReturn().

Now what if MUT in A depends on A.m2() which depends on external/infrastructure, => hard to run during test => mockup m2() using
thenReturn(). => A must be a mock object. To test MUT, you have to register MUT with thenCallRealMethod.

Not sure how googlemock (c++) does…

rule based margin calc + stress test (GS prime brokerage@@)

Start with basic margin calc used in my 1997 investment, or as described in http://thismatter.com/money/stocks/margin.htm.

Then apply rules. Rule-based calculator recognizes known hedge strategies and picks out each pair (or 3-some …) of positions in a hedge. These tend to reduce the margin requirement. Known as margin release??

Lastly, apply stress test to simulate worst cases. One of the worst cases is the worst worst. In the worst worst, price can be 5%  worse then normal, so investor’s margin requirement should increase 5% to cover that.

JTable update – upward^downward (editingStopped()

Upward — update table Model from SQL, MOM (mkt data), or timer (overwhelming mkt data), then fire events.
Downward — mouse/keyb — user editing a cell, then propagate to DB or other UI components.
(–> Here you see the threading issue.)

Q1: How many ways are there to read/write data in jtable?
%%A: i guess 1 — via the table model.

Q1b: is there a separate copy of the model data in the JTable instance?
%%A: i don’t think so.
A: My tests confirm that user edits directly hit the underlying table model (eg 2D array). See also P 449 [[java cookbook]].

   /** Invoked on EDT, when editing is finished.
     * @param  e  the event received
     */
JTable.editingStopped(ChangeEvent e) invokes on EDT —

JTable.getModel.setValueAt(). This method should be customized in your own table model. Your setValueAt() should modify your own data structure (2D array etc) and then fire events
     public void setValueAt(Object value, int row, int col) {
        data[row][col] = …
        fireTableDataChanged();
    }

iterators – what go into "<>" and "()"

motivation — i find declarations too complicated when iterators are involved.

* in a template definition’s , people put iterator categories like InputIterator. I think these are just suggestive dummy typenames. If you rename to “input_iterator” through out that class, nothing will break. In fact, when you write template , Animal cannot be a real class name.

* in function prototypes, you use those fake types declared earlier. See [[essential c++]]
* in concrete function calls, you feed in variables representing iterators. You need to follow the suggestions in the iterator category. Otherwise, things break, though Compiler can’t detect, i think.

Now let’s extend the question
Q2: what do u put into vs () for a function template [1] using iterators?
[1] such as those STL algorithms

A: i think iterator is an atypical example. See [[java interface as a replacement for c++ templates]] for background.
* in prototypes’ you can put anything silly like T, S, V
* in prototypes’ (), you can use those same type param, or a ptr/ref to it. An iterator argument can be derived from these fake types or standalone.
* in concrete function calls, you can feed a specific iterator type into , and arguments into (). Usually you can omit the stuff because compiler can infer.

AbstractAction – brief intro

(Outdated. See other posts.)
A typical Action instance is a combination of
+ a stateless action listener
+ a stateful lookup table of _instance_ properties for a toolbar button. Properties include text label, icon, tooltip, shortcut key binding… [2]

Action instance gets wrapped [1] in the toolbar button instance. At the same time, a menu item instance can be another wrapper over the same Action instance. Those properties become shared, effectively[4].

Therefore, our Action instance becomes _master_ of 2 slaves. When you putValue(somePropName, someNewVal), you update master lookup table[3]. This lets you centrally control the button/menu item that must perform the same action.

The official java tutorial http://download.oracle.com/javase/tutorial/uiswing/misc/action.html has sample code.

[1] How do you wrap the Action instance in a toolbar button instance?
+ call ctor new JButton(myAction) or new JMenuItem(myAction)
+ As a shortcut, When you call add(myActionInstance) on a JToolBar, the toolbar button instance is instantiated as a wrapper object. Same thing when adding to a JMenuBar.

[2] You can add your own properties
[3] Exactly one property has its own setter/getter — setEnabled().
[4] actually the button (or menuItem) instance has its fields “mastered” by the Action properties. Achieved by PropertyChangeListeners. P47 [[Zukowski]]

Another analysis of a vanilla swing event listener

See also http://bigblog.tanbin.com/2011/02/deeper-look-at-swing-event-handlers.html

Case study — http://download.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

Be crystal clear about
* registration time — could happen hours before
* produce-time
* consume-time

How many threads?
– EDT is the consumer thread
– producer thread
– registration thread? less relevant. can be any thread.

Data shared among these threads at these different TIMES?
+ (singleton) jcomponent object
+ (singleton) action listener object
+ event-queue-task objects.

Before registration time, action listener is instantiated. At registration time, address of the listener object is saved in jcomponent object — like a subscriber mailing list (or spam list:)

At produce-time, system instantiates event-queue-task object (different from EventObject), injecting the jcomponent (as event source) + Listener object addresses therein, then enqueues the task object to the EDT event-queue. If 5 listeners registered, then 5 distinct task objects enqueued.

At consume-time (shortly but possibly much later [1]), EDT picks up the task object and finds the listener object, and calls listener.actionPerformed() passing in EventObjectt. As a non-static method, this CALL’s host object is the listener object but it executes on EDT. At consume-time, all instance fields of the source object (typically a jcomponent), instance fields of the listener (and, if a nested class within a jcomponent, private fields of the enclosing jcomponent) are accessible.

Listener OBJECT is often of an inner class –> Complicating. You need to be very clear that registration time and listener creation time are rather less relevant since they could be well before the event. Enclosing class’s fields all become accessible to actionPerformed().

If inner class is local, then local variables of the enclosing METHOD are also accessible, if FINAL. This last FINAL scenario is more tricky. The local vars are created at registration time but (because FINAL) remain accessible at consume-time.

[1] that’s why async always needs buffer — see http://bigblog.tanbin.com/2011/05/asynchronous-always-requires-buffer-and.html