decorating a c++ class to add converters

In java, i usually extend a bean class B to add data fields.

When using STL (P203 [[STL tutorial and ref]]), we often subclass a basic data class just to add conversion features. You can do the same using has-a decoration.

In STL, data classes need converters more often than in java. Java is more strict, more orthogonal — there’s often just one right way to do something. Perl, javascript and c++ data manipulation is more flexible. —————-}  Therefore more conversion is needed and implicit.

adapters for STL 1) container 2) iterator and 3) functor

You know the STL planet has (at least) 3 continents — containers + iterators + algorithm. Now, most of these have adapters.
1) Container adapter? Obvious!
2) iterator adapter? simplest example is back_inserter.
(How about reverse_iterator? I think so.)

3) functor adapter? simplest example is bind1st() and bind2nd()
The adapter not2() is actually quite simple but understand not1() first.

4) algorithms? I don’t think algorithms have adapters because
…algorithms aren’t objects!

5) allocators? I don’t think so.

OutOfMemory retry loop of "new" #c++

We know c++ keeps retrying when a “new” operation encounters OOM condition (no such exception in c++ actually)

Q: what are the very few (therefore important) ways to break out of the loop?
A1: more memory becomes available and retry succeeds
A1a: new-handler releases a secret “stash” of memory
A1b: install a more resourceful new-handler, which releases some special memory block

A2: new-handler turns out null -> std::bad_alloc -> abort()
A2a: set new-handler to null
A2b: directly throw bad_alloc and pass on the hot potato
A2c: directly call abort()

short term influences on FX rate – ML perspective

* (Above all, IR has the most direct impact on FX rate, at least in the short/mid term.)

* Positions in the FX futures and options market — For eg, high volumes around contract expiry dates can move FX rates
* Activities in the FX options market — for eg, large orders as a result of option excise can move spot prices.
* Fund manager activities — they can move in/out of Euro zone or America. Look at international portfolio managers, not small investors. If these managers want to trade and hedge globally and diversify the portfolio, then they need to invest not only in the domestic market but markets denominated in other currencies. They need FX as a means to an end. They must pay the FX transaction fee. In this sense, I believe FX importance and value-add is smaller than Eq and FI, but it does grow.
* Stock market — a country’s currency rises with its stock market
* commodity prices

What drv might be curtailed by post-2008 regulations

(A foolhardy prediction by a greenhorn…)

These are the potential casualty but in reality, i don’t know if any of these were curtailed.

CDS
MBS
IRS – set to grow further, across continents. I don’t think will be curtailed.

Listed derivatives — are all safe and may grow further.

Reasons/justifications for the tighter regulation include —
– systemic failure
– contagion of default, domino effect
– [tv] obstacle to risk assessment
– [v] poor liquidity
– [t] unreliable credit rating

Underlying “defects” in the product set-up —
[t = poor transparency]
[v = opaque pricing, disparate valuations]

ifstream /with-f/ and istream — typedef specializations revealed

Background — “cin” is an instance of istream (no “f”); whereas ifstream is the most common file input utility.

“istream is a specialization (not a template instantiation) of the class template basic_istream” — many people say that but if the generic template is named “basic_istream” a specialization can’t have a different name! When you look at the code you realize it’s yet another typedef —

typedef basic_istream istream

Therefore, istream is an alias to a specialized basic_istream.

Now back to basics. Stripping layers of typedef and template specialization, the core structure is

———> basic_ifstream extends basic_istream extends ….

-) ifstream is a typedef of a specialization of basic_ifstream
-) istream is a typedef of a specialization of basic_istream

typedef basic_istream istream;
typedef basic_ifstream ifstream;

stronger]Perl than java though I spent more years]java (theory^GTD)

Q: what elements make me Feel strong in c# or c++ or perl…?
A21: passing a large number of non-trivial interviews
A36: discussion with veterans. Can follow. Can contribute.
A78: help veterans solve problems
A96: independently solve non-trivial problems (colleagues couldn’t help you solve)
A01: hands-on skill with the tough and core parts of the language, like threading, generics, Reflection …
A10: tools, tools and tools

Q: what elements make me Look strong in c# or c++ or perl…?
A63: track record – a wide range of non-trivial mainstream projects, often with substantial (or impressive) volume and performance
A81: certification or the type of knowledge therein
A56: insight into strange errors that other veterans don’t dig into

For c#, I have A36, A01, A96
For java, I can improve A78, A10
——-
In any programming language there’s a body of abstract theory (including design principles, language features…) on one hand, and practical how-to on the other hand. I’m a theory guy meaning I understand theory faster. Practical on-the-ground problem solving skill is ….mediocre.

Now, Why am I stronger in Perl than java even though I spent more years writing java? Here’s my new answer — I understand java fundamentals better than Perl fundamentals; but I know more Perl how-to than java how-to. Most practical Perl problems I can resolve faster than others. (Well, not many people spent that many years using Perl.) I have worked with many Perl developers and many of them tell me I know a lot of little tricks.

Here’s one example of a killer java skill — Multithreading is the most complex part of java (followed by generics and reflection, IMO). Complex in the JVM ie “theory”. In practice, app developers stick to code idioms and proven constructs. These “best practices” shield programmers from the underlying complexities. If you know some of these “best practices”, then you don’t need a deep understanding of the JVM internals. What I just said is all within my comfort zone. However, when threads meet swing, messaging, distributed cache, app servers…, we are challenged. Not much theory. Just a lot of code on the ground. You need resourceful, quick problem solvers. Good understanding of java fundamentals can help to some extent.

Another example – eclipse IDE. Never tested in interviews. No theory. But can really make a programmer so much faster or slower.

new-expression calls op-new and then ctor

See also post on 3-stepper “new” and double-checked locking.

Simple rules
* always — new-expression always includes a constructor call, even for placement new expressions [3]
* never — explicit op-new function call never calls constructor [2]

More rules
* new-expression calls op-new (to grab raw memory), and then ctor (to initialize raw memory), then returns a pointer of the requested type, in one thread
* placement new-expression calls placement op-new, then ctor
* placement op-new doesn’t grab raw memory

http://www.cplusplus.com/reference/std/new/operator%20new/
An expression with the new operator, first calls function “operator new” with the size of its type specifier as first argument, it then automatically constructs the object.

Note [1] some of the steps above could be skipped — Placement version of operator-new (we didn’t say “placement version of new“) does not allocate memory – it simply returns the given ptr. Notice though that the constructor for the object (if any) will still be called by the operator expression i.e. the new-expression [3].

Note [2] operator-new function call PRECEDES (not includes) constructor call. If you call operator-new explicitly, no constructor called!

   myclass * p3 = (myclass*) operator new (sizeof(myclass));
// (!) not the same as: myclass * p3 = new myclass;
// (constructor not called by explicit operator-new call)

Note [3] op-new can include a 2nd argument --
new (p3) myclass; // placement-new-expression, calls constructor
// similar to --
operator new (sizeof(myclass),p3)
// placement-op-new. no constructor call


http://www.cplusplus.com/reference/std/new/operator%20new%5B%5D/ shows simple examples of operator-new[] including the placement version

operator new[] can be called explicitly as a regular function, but in C++, new[] is an operator with a very specific behavior: An expression with new and an array type specifier is an operator new[] expression. This first calls function operator new[] with the size of its array type specifier as first argument (plus any array overhead storage to keep track of the size, if any), and if this is successful, it then automatically initializes or constructs each of the objects in the array (if needed). The expression evaluates as a pointer to the appropriate type pointing to the first element of the array.

— jargon warning
ARM says
“the new operator will call the function operator new()”. it means
The new expression will call the function operator new()

usage@custom subclass of STL binary_function

customized subclass of binary_function can be used in several *distinct* use cases —

1) as 3rd argument to STL sort(). See P205 [[stl tutorial]] for complete example.
2) as optional template argument when *specializing* a sorted map class TEMPLATE in STL. Note your custom subclass feeds into the template, NOT to the constructor —

– A constructor usually takes an object as argument, not a class.
– A template specialization usually takes a class or a derived type[1] as argument, not an object.

[1] like a ptr, ref or typedef based on the class

pair up new/delete — usually impractical@@

Update — Best way to manage the delete is probably RAII. There’s a post on that
—————————

A simple [2] technique — make sure for every “new” operation at run time [1], there’s exactly one “delete” operation. RAII is a similar solution.

[1] One challenge is how to ensure this runtime rule using compile-time coding rules. Some runtime rules are enforceable at compile time. Consider const, final, finally, synchronized, private, abstract keywords

Q: Analyzing source code, you might see multiple deletes in a branch/loop, but is the delete operation ever implicit (ie absent in source code)?
A: Never. “new” only gives you a ptr. You can pass that ptr around or assign the pointee address to a field, but c++ never automatically, implicitly calls delete on a ptr.

[2] Many situations are too complex for this technique. As pointed out on [[nitty gritty]] P194, sometimes delete is placed into another function than the “birth place” function.

java thread pool(phrasebook

* Runnable.java — the tasks/jobs lined up are objects implementing Runnable.java. It’s counter intuitive to me that the threads in the pool by definition implement Runnable.java, and the jobs also implement Runnable.java — see blog post [[ wrapper object of “me” as a field in me ]]

* queues — i think thread pools need a FIFO queue to hold the jobs/tasks. Usually it’s a blocking queue.

compared to calls, put are more like insurance (barrier option

Compared to a call, a put is more like traditional insurance. (Barrier option is a cheaper insurance than vanilla options. Down-and-in European Put is a common barrier option.)

Having an ITM call is like a shopping _coupon_ ” buy a beer at $1 with this coupon “.
* you can resell the coupon or use as gift voucher

An OTM call (more common than ITM) is like an above-market airticket offer for those affluent travelers who need last minute booking.

For puts, Commodity puts are more intuitive than equity puts. FX options and swaptions are less intuitive. Here’s an illustration —

Suppose a farmer receives guarantee from Walmart to buy his 2019 produce at a pre-set fairly low price whenever he wants within the harvest season.

  • * OTM — pre-set price is low because Walmart is providing a “distress assistance” price
  • * farmer has to pay a “membership” for this guarantee
  • * membership can be traded
  • * put writer is typically a wholesaler like Walmart who needs to regularly source the product in bulk.
    • My friend Trevor Tang is also a put writer, who doesn’t mind receiving the underlyer

Commodity option is the most intuitive. When you write a put on wheat, you advertise to take IN wheat that’s PUT OUT by the option holder. Incidentally, the strike price is typically below the current underlier price (OTM), but the take-in-PUT-out actions happen when underlier drops below the strike.

ITM call/put are more intuitive, but OTM are more important in practice.

essential trading server arch QnA #tibrv,gemfire

Every trading server invariably uses some non-http network daemon. There’s always more than 1 process (JVM, C# or c++) on the server side. In FI/commodities (not low-latency eq) There’s often some MOM daemon such as JMS, tibrv and gemfire notification daemon. Here are some Fundamental questions:

Q22: on top of tcp/udp, what specific network protocol between the server-side and GUI?
A: I have seen rmi and protobuf over tib ems.

Q22a: how about JMS between server and swing? Did we see 160 subscribers on a given topic, due to that many swing installations?

Q33: on top of tcp/udp, what specific network protocol among the server-side processes?
A: I have see tibrv, JMS, RMI, gemfire data distribution protocols …

Q44: since most trading servers must avoid DB latency, where does the trading data live? In memory?
A: i have seen gemfire, rttp,

Q45: in case of distributed cache (not replicated), how does one cache listener update another node?

Q55: how does the daemon stay alive after main() exits?
A: Look at ion, gemfire, activemq. There’s often at least 1 (1 enough) non-daemon thread that’s stuck in wait()

c++ in finance is mostly C code@@

My friend told me a lot of c++ apps in finance is 80% C code. How about yours?
He said most of today’s c++ systems were created in C days. When c++ became mature, people didn’t decide to create brand-new modules in c++ (contrast java). Instead, they decided to evolve slowly from c to c++. Result is, they still write mostly in C, and not c++.
Java is a different story. People did feel the justification to create brand-new apps in java, perhaps because there’s no “evolutionary” approach. They either stick to c or make a clean break using java.
I still wonder why people didn’t create new components in c++. C++ could coexist with C very, very easily. Any insight?