Friday, August 21, 2009

Pricing European Options by using Monte Carlo Simulation


In my previous article, price of european option (put and call) is estimated by using binomial model (Cox-Ross-Rubinstein (CRR) approach [1]). In this article, i provide java and Scilab (similar to Matlab)
source code to estimate these option prices by Monte Carlo simulation.

In binomial model, intrinsic value of an asset (S_T) at expiry t
ime (T) is estimated with a sequence of discrete time steps, at each step, stock price is estimated with a probability (either down or up probability. In monte carlo simulation, intrinsic value of an asset (S_T) at expiry time (T) is obtained from a normal distribution such as [2]:
where, r is annual interest rate S_t asset price at time t and sigma is volatility and x is normal distribution variable.

Having estimated S_T, option's payoff can be estimated easily (max (0, X-S_T) or max (0, S_T-X) for call and put options respectively, where X is options strike, exercise price). Based on expected values of pay off functions which generated with monte carlo simulation, option prices can be calculated as follows for european call option:


Source code of this estimation in java and
Scilab is listed


1:  // SciLab (Matlab) Source code
2: // Estimate European Option price by Monte Carlo Simulation
3: // denizstij (http://denizstij.blogspot.com/),
4: // Aug-2009
5: asset=230; //S
6: strike=210;//X
7: volatility=0.25; //sigma
8: r=0.04545;
9: time=0.5;
10: num_sims=10000;
11: R= (r-0.5*volatility^2)*time;
12: SD=volatility*sqrt(time);
13: sum_call_payoffs=0.0;
14: sum_put_payoffs=0.0;
15: for i=0:num_sims,
16: S_T= asset*exp(R+SD*rand(1,'normal'));
17: sum_call_payoffs=sum_call_payoffs+max([0,S_T-strike]);
18: sum_put_payoffs=sum_put_payoffs+max([0,strike-S_T]);
19: end
20: eu_call_option_price= exp(-r*time)*(sum_call_payoffs/double(num_sims))
21: eu_put_option_price= exp(-r*time)*(sum_put_payoffs/double(num_sims))


1:  package com.denizstij.finance.pricing;
2: import java.util.ArrayList;
3: import java.util.List;
4: import java.util.Random;
5: /**
6: *
7: * Estimate European Option price by Monte Carlo Simulation
8: * @author denizstij (http://denizstij.blogspot.com/)
9: * Aug-2009
10: *
11: */
12: public class EuropeanOptionPricingByMonteCarlo {
13: /**
14: * Estimate European Option price by Monte Carlo Simulation
15: *
16: * @param asset Current Asset Price
17: * @param strike Exercise Price
18: * @param volatility Annual volatility
19: * @param intRate Annual interest rate
20: * @param expiry: Time to maturity (in terms of year)
21: * @param num_sim : Number of simulations
22: * @return Put and call price of european options based on
23: * Monte Carlo Simulation
24: */
25: public strictfp List<Double> estimatePrice(double asset,
26: double strike,
27: double volatility,
28: double intRate,
29: double time,
30: int num_sim) {
31: List<Double> results = new ArrayList<Double>();
32: double R = (intRate - 0.5 *Math.pow(volatility,2))*time;
33: double SD = volatility * Math.sqrt(time);
34: double dF = Math.exp(-intRate*time); // discount Factor
35: double sumCallPayoffs=0.0;
36: double sumPutPayoffs=0.0;
37: Random random= new Random();
38: for (int i = 0; i <= num_sim; i++) {
39: double nextGaussian = random.nextGaussian();
40: double S_T= asset*Math.exp(R+SD*nextGaussian);
41: sumCallPayoffs+=callPayOff(S_T,strike);
42: sumPutPayoffs+=putPayOff(S_T,strike);
43: }
44: double callOptionPrices= dF*sumCallPayoffs/num_sim;
45: double putOptionPrices= dF*sumPutPayoffs/num_sim;
46: results.add(callOptionPrices);
47: results.add(putOptionPrices);
48: return results;
49: }
50: // Pay off method for put options
51: private double putPayOff(double stockPrice, double strike) {
52: return Math.max(strike - stockPrice, 0);
53: }
54: // Pay off method for call options
55: private double callPayOff(double stockPrice, double strike) {
56: return Math.max(stockPrice - strike, 0);
57: }
58: public static void main(String args[]) {
59: EuropeanOptionPricingByMonteCarlo euOptionPricing = new EuropeanOptionPricingByMonteCarlo();
60: List<Double> results = euOptionPricing.estimatePrice(
61: 230,
62: 210,
63: 0.25,
64: 0.04545,
65: 0.5, // In terms of year
66: 10000);
67: Double callOptionPrice = results.get(0);
68: Double putOptionPrice = results.get(1);
69: System.out.println("call Option Price:" + callOptionPrice);
70: System.out.println("put Option Price:" + putOptionPrice);
71: }
72: }

Wednesday, August 19, 2009

Pricing European Options by using Binomial Model

Binomial Model is one of the simplest pricing model for European options. Below you can find an implementation of Cox-Ross-Rubinstein (CRR) approach [1] in java for pricing of put and call European options.

With following parameters, sensitivity of the binomial pricing model as function of number of time steps can be seen in figure 1. With high number of time steps, binomial model with CRR approach converges with optimal Black-Scholes formula (e.x: 30.741 for call option)

Figure 1: Option price as a function of number of time steps.

1:  package com.denizstij.finance.pricing;
2:
3: import java.util.ArrayList;
4: import java.util.List;
5:
6: /**
7: *
8: * Estimate European Option price based on Cox, Ross and Rubinstein model
9: * @author denizstij (http://denizstij.blogspot.com/)
10: *
11: */
12: public strictfp class EuropeanOptionPricingByBinomial {
13:
14: /**
15: * Estimate European Option price based on Cox, Ross and Rubinstein model
16: *
17: * @param asset Current Asset Price
18: * @param strike Exercise Price
19: * @param volatility Annual volatility
20: * @param intRate Annual interest rate
21: * @param expiry: Time to maturity (in terms of year)
22: * @param steps : Number of steps
23: * @return Put and call price of european options based on Cox, Ross and Rubinstein model
24: */
25: public List<Double> estimatePrice(double asset,
26: double strike,
27: double volatility,
28: double intRate,
29: double expiry,
30: int steps) {
31: List<Double> results = new ArrayList<Double>();
32:
33: List<Double> stockPrices = new ArrayList<Double>();
34: List<Double> callOptionPrices = new ArrayList<Double>();
35: List<Double> putOptionPrices = new ArrayList<Double>();
36:
37: double time_step = (expiry) / steps;
38: double R = Math.exp(intRate * time_step);
39: double dF = 1 / R; // discount Factor
40:
41: double u = Math.exp(volatility * Math.sqrt(time_step)); // up boundary
42: double d = 1 / u; // down boundary (Cox, Ross and Rubinstein constraint)
43: // at leaf node, price difference factor between each node
44: double uu = u * u; // (u*d)
45: double p_up = (R - d) / (u - d); // up probability
46: double p_down = 1 - p_up; // down probability
47:
48: // initiliaze stock prices
49: for (int i = 0; i <= steps; i++) {
50: stockPrices.add(i, 0.0d);
51: }
52:
53: double sDown = asset * Math.pow(d, steps);
54: stockPrices.set(0, sDown);
55:
56: // Estimate stock prices in leaf nodes
57: for (int i = 1; i <= steps; i++) {
58: double sD = uu * stockPrices.get(i - 1);
59: stockPrices.set(i, sD);
60: }
61:
62: // estimate option's intrinsic values at leaf nodes
63: for (int i = 0; i <= steps; i++) {
64: double callOptionPrice = callPayOff(stockPrices.get(i), strike);
65: callOptionPrices.add(i, callOptionPrice);
66: double putOptionPrice = putPayOff(stockPrices.get(i), strike);
67: putOptionPrices.add(i, putOptionPrice);
68: }
69:
70: // and lets estimate option prices
71: for (int i = steps; i > 0; i--) {
72: for (int j = 0; j <= i - 1; j++) {
73: double callV = dF*(p_up * callOptionPrices.get(j + 1) +
74: p_down* callOptionPrices.get(j));
75: callOptionPrices.set(j, callV);
76: double putV = dF*(p_up * putOptionPrices.get(j + 1) +
77: p_down * putOptionPrices.get(j));
78: putOptionPrices.set(j, putV);
79: }
80: }
81:
82: // first elements holds option's price
83: results.add(callOptionPrices.get(0));
84: results.add(putOptionPrices.get(0));
85: return results;
86: }
87:
88: // Pay off method for put options
89: private double putPayOff(double stockPrice, double strike) {
90: return Math.max(strike - stockPrice, 0);
91: }
92:
93: // Pay off method for call options
94: private double callPayOff(double stockPrice, double strike) {
95: return Math.max(stockPrice - strike, 0);
96: }
97:
98: public static void main(String args[]) {
99:
100: EuropeanOptionPricingByBinomial euOptionPricing = new EuropeanOptionPricingByBinomial();
101: List<Double> results = euOptionPricing.estimatePrice(
102: 230,
103: 210,
104: 0.25,
105: 0.04545,
106: 0.5, // In terms of year
107: 10);
108: Double callOptionPrice = results.get(0);
109: Double putOptionPrice = results.get(1);
110: System.out.println("call Option Price:" + callOptionPrice);
111: System.out.println("put Option Price:" + putOptionPrice);
112: }
113: }
114:

Tuesday, August 11, 2009

Volume Weighted Average Price (VWAP)

Recently i was skimming through an ebook about electronic trading (Electronic and Algorithmic Trading Technology) after reading this news article. This ebook outlines algorithmic trading in a concise way. According to this book and wikipedia entry, more than half of the orders in London Stock Exchange in the last year were entered by algo traders.

According to the ebook, one of the fundamental and basic algo trading is Volume Weighted Average Price (VWAP). VWAP is the ratio of value traded to total quantity of trades in a time period. It is average price of an security in terms of quantity. It is calculated as follows:



VWAP algorithm implies that at a given time if VWAP is greater than the price of share, then the share is under valued and it is a good candidate for buying. But if VWAP is lesser than the price of share, then it should be considered for selling. Even though, it is a very simple algorithm, it and its variations are commonly used in electronic trading.

I have implemented a sample java application (algo trading) which estimates VWAP of an equity by fetching real time (15 min delayed) financial quotes from Yahoo Finance, UK. Equity quotes (15 min delated) can be downloaded free of charge from yahoo finance pages in CSV format. The sample application periodically downloads predetermined quotes (for example VODAFONE GRP --VOD.L) in CSV format and estimates VWAP. Unfortonately, since downloaded data do not consists of trade quantity values (CSV files has following data: symbol, mid trade, time, date, change, lowest trade, highest trade and volume), quantity value for each quote is estimated based on the volume and mid price.

The sample application has multi layered architecture with observer design pattern. It uses Apache HTTPClient to download CVS files periodically from yahoo finance pages. After quotes are extracted from CSV files, they are appended to a linkedlist based time series and then observers (VWAP estimator and then VWAP clients(UI layer)) are notified for the latest updates.

Click here to download source code of the sample application (algo trading) in java.

Friday, July 31, 2009

Customized ClassPath Contributor- An Eclipse Plug-in

When i first started using java (JDK 1.1), classpath management was an issue for me. Setting up a classpath in command line and then running a java program was so error-prone. Luckily, IDE's, such such as eclipse and netbeans, make a developer's life is more happier. Eclipse (actually eclipse framework) provides various functionalities for fast, productive, efficent, and happy programming, not just for Java, but also many other langues (C/C++, Php, Flex, ...)

Classpath management for java in eclipse , of course, is more easer than bare command line. But it still lacks of some functionalities. Profile based shared repository is one of these missing functionalities. So often in my current work, in eclipse, i find myself arranging classpaths after SVN branching or merging or changing workspace or checking out from SVN. My personal settings during these operations conflicts with other developers settings. There is not any profile (indiviual) based mechanism for settings and classpath ( I am awera that maven provides profile and central reposisty based but our projects has legacy ant scripts)

Therefore, We decided to create a central setting project (Settings) wh
ich contributes automatically and independently to our projects (for example, Beee & Booo) based on developer's profiles. Figure 1 depicts a sample workspace which contains two sample projects (Beee & Booo) and a setting project (Settings) which contains profiles (/Settings/profiles) and central shared libraries (/Settings/libs)


Figure 1: Settings projects and Sample projects (Beee & Booo ) in workspace

Let me talk a bit about Settings project. Setting project is a centralized configuration project and holds shared and indivual settings and libraries for each developer. Therefore, structure of the settings project would vary. But a setting project has following main directories:
  • Settings/libs: Contains common, share libraries
  • Settings/profiles: Holds indivual profiles.
Each profile (ex: deniz.turan) directory under "Settings/profiles" directory holds developer specific settings. Name of profiles directories are same as user's system (windows or linux) login names in order to discover automaticly profiles for developer.

Each profile has following subdirectories which would have specific or custom sub directories (such ants, libs)

  • Settings/profiles/deniz.turan/ants: Holds ant script related indivual properties and custom build scrtips: There are two important file here:
  • Settings/profiles/deniz.turan/libs: Holds profile based libraries. User can create sub library directories (with prefiex "lib_", ex: lib_1, lib_2, lib_3 ....) to arrange class path orders. Library class path order is natural order of String Class such as : lib_1 >lib_2> lib_3> ... > Settings/profiles/deniz.turan/libs (See figure 4 and 5)

Imprtant note: Profiles' libraries are in higher order in class path as demonstrated in below

Having a central setting project is not enough alone, unless the content of profiles (/Settings/profiles) and central common libraries (/Settings/libs) are automatically contributed to main projects for each developer independently. Therefore, i decided to develop an eclipse plug-in to contribute to classpath of a project from a setting project and profile, with a automatic manner. Of course, it is possible to add libraries or folders to project's build path in eclipse, but as i pointed out above, it causes conflicts during merges, branches or in new workspace or on other machines.

To develop plug-in, following two extension points from eclipse rcp framework are used:
  • org.eclipse.jdt.core.classpathContainerInitializer : Initialize and manage class path container (ex: "Deniz's Classpath", in sample source project, Figure 2 , 4 and 5)
  • org.eclipse.jdt.ui.classpathContainerPage : Configuration page for classpath container (Figure 3)
For an overview of JDT in eclipse, please click here

Below you can see some screen shots from Classpath Manager project and a sample workspace.

Figure 2: Classpath Container ("Deniz's Classpath Manager")


Figure 3: Classpath Container Page


Figure 4: After Classpath Manager contributes to a project's build path


Figure 5: Final workspace after Classpath Manager contributes resources from Settings project and profile (deniz.turan)


As figure 5 illustrates, content of deniz.turan profile in Settings project (/Settings/profiles/deniz.turan) and common libraries (/Settings/libs) are contributed to sample "Booo" project. As explained above, order of contributed libraries in classpath are based on first profile sub libraries (/Settings/profiles/deniz.turan/libs/lib_1), and then profiles libraray (/Settings/profile/deniz.turan/libs) and finally common libraries (/Settings/libs)

You can download source code of Classpath Manager eclipse plugin project with sample setting project. The source code is a prototype and implements basic idea of the classpathContainerInitializer and classpathContainerPage extensions. It is tested with eclipse 3.4 and 3.5.

Click here to download ource code.


Saturday, July 25, 2009

Fooled by Randomness, Nassim Nicholas Taleb

Think a book, whose author offends, mocks and bores its readers while he pretends he is the most clever, smart, intellectual and scientific guy in the world in each page of the book. It is not only written in a chaotic structure-- chapters, sections are not related to each other or very mixed up in terms of concepts and structure, the author also uses lots of buzzwords, redundant and wrong examples.

I am talking about
"Fooled by Randomness, The hidden Role of Chance in Life and in the Market", by Nassim Nicholas Taleb. Have a look at following quote from the book:

"What has more value? (a) a contract that pays you $1 million if the stock market goes down 10% on any given day in the next year; (b)a contract that pays you $1 million if the stock market goes down 10% on any given day in the next year due to a terrorist act. "

What is your answer? a or b ? Taleb claims:"I expect most people to select (b)." I am not sure IQ level of people around Taleb, but i reckon, most people would go option a. (I know that, in a normal distrubuted financial world, %10 changes in stock market is so low probability -- once every 73 to 603 trillion billion years-- , but in last 80 years, that incident happened over 2 times and five sigma deviation is over 73 times, which happens once in 7000 years if finance data is normally distrubuted. More info is here).

Taleb is a trader and scholar, works in a fixed income (bonds) financial company. He has background in science (PhD) and like many other PhD graduate, he bored in academia after some time and started to work in finance sector. In his book, he claims that probability theory is not a natural or trivial concepts for many people to comprehend. I do agree with him in this claim. But he takes his claims further and try to establish a theory and life style based on randomness (rare events) . He claims that he is expert on random events and he takes advantages of these random events in his life and business.

He exemplifies his ideas with "fictitious" characters who works as traders in finance (fixed income or equity markets). These characters are generally quite extreme and opposite of each other. For example, he kicks off the book with stock and bond market traders. The stock market trader, Steve, does not have any sound education and a risk taker and get successful so quickly. On the other hand, the bond market trader, Bob, has a degree in probability and he does not take much risk in his business (to be honest, there is not much risk in fixed income market compare to stock market). Because of calculated and not risk taking style, Bob is not rich as much as Steve.

Taleb claims that the success of the stock market trader, Steve, is based on randomness, in another words just "luck". He claims that even if you put 10.000 monkeys in stock market as trader, and monkeys trade randomly, by the end of 5 years, there will be at least a rich monkey. He also claims that after some lengthy time (10 years), all of these monkeys will disappear (The clever one would run away when he has some money, but most of them lose all of their money before they are kicked out). Taleb has a point in analogy, i think. Similar to many aspect of life, randomness also has a part in stock market. But i think, his claims that without proper analysis, research and hard work in stock market, someone would get rich randomly is just ridiculous. He dismisses that the participant of stock markets are intelligent, agile and very adaptive people. Stock market has chaotic aspects, but not totally random. It responses a deterministic way to some events (for example, if a small company merges or bought by a big company, it's share will surge). And the job of traders is to predict (or to speculate) these events in order to make profit.

I found many so-called scientific or intellectual ideas of Talebs, especially in probability theory is very mixed up. For example, he ignores the main reason of filters in statistics or engineering (filtering outliners and noise). While he claims that he takes advantages of these outliners (randomness, noise) in his real life and business, he complaints about the source of the noise for example, media and journalist (He has issue with media, TV, papers too). He contradicts himself, and gives mixed messages in different part of the book.

In brief, in his book, Taleb comes cross as an arrogant, geek person who claims 'if you disagree with me, you're an idiot and I will ignore and laugh at you.' He wrote the book for just sake of writing a book, and before clearing and organising the ideas in his mind. His writing style and personality kills the some of his nice ideas. By the end of book, i felt big disappointment. It was worst ever book i read in a long time. Luckily, the current book in my hand ("The Ascent of Money: A Financial History of the World") , is making me to forget yucky taste of this book.

Saturday, July 18, 2009

Better Annotation in Java Around a Testing Framework

Recently in a pet project, i got involved extensively with annotation in java. I wanted to create a testing framework in which unit tests are created based on given methods level annotations. The testing concept is similar to EasyMock, but rather than creating mock objects, i wanted to capture real objects during "runtime" and then create tests cases based on annotation and output/input parameters. By the way, with "Runtime" i don't mean production environment. When a QA or developer run (tests) the product, tests cases and its inputs are created and stored.

After clearing the concept in my mind, i decided to do a prototype. In the first prototype, i wanted to implement @AssertNotNull unit test case for method's input parameters and output value.

By deploying method level java byte code injection with javassist and a simple annotation (@AssertNotNull), unit tests are create for methods and inputs and outputs of methods are serialized. Once i catch the input objects (parameters of the method) with injected byte code at the beginning and end of methods, i serialized them in XML format with XStream . Injected byte codes also call a TestGenerator service to generate unit tests based on the defined annotation and serialized input/outputs. In unit test phrase, I was planning to deserialize these input objects and uses as input to automatically created tests. First prototype was successful. Unit tests (@AssertNotNull) are created for output object and input parameters of a given annotated method. It was a big step to create unit tests automatically with real object rather than mock objects like EasyMock.

As a next step, i decided to implement a prototype for more complex test cases which has two inputs, for example @AssertEquals. When i was prototyping @AssertEquals annotation, i noticed that annotation in java are really so basic. They do not provide so much functionalities for advance usage such as:

  • Hierarchy: One of the main concept in OO is missing in annotation creation.You are not allowed to extend an annotation. For example, i would like to create a base annotation type (let say @Test) and many sub annotation types (@AssertTrue, @AssertNotNull, @AssertEquals) which extend @Tests. This approach, Hierarchy in annotation, would save lots of computation and coding time if reflection is used to probe which methods are annotated with a type of annotation (@Test) rather than a specific annotation (@AssertTrue). Of course, as a solution to lack of Hierarchy in annotation, methods or classes can be annotated both with super type and specific type annotation (both for example, @AssertNotNull and @Test). But isn't it an ugly code ?
  • Multiple annotation: A method or class can be annotated only once with a specific annotation. Even it is not much common in real life, as in my test framework, it should be possible to annotate a method with different parameters. For example, i would like to annotate a method with multiple @AssertNotEqual each of which uses different parameters. People who comes cross that issue, generally creates a container annotation For example in JPA, If you would like to annotate an entity with multiple @NamedQuery, you have to declare these annotations in @NamedQueries.
  • Simple Type : Types of fields in annotation are so restricted. Only primitive, String and Class types are allowed.
I think annotation in java should be revised. Similar to enums they should to be enhanced for a versatile and advanced usage. I am aware that these issues can be resolved with some other ways as i mentioned above, and it is not trivial to implement comprehensive annotation, but i still think that java deserves better annotation design.

By the way, i am still working on this pet project, test framework! Once i finished it, i will create a blog here with more detail.

Thursday, May 07, 2009

JNDI & EclipseLink in GWT 1.6.x


New version of GWT (1.6.x) comes with a new embedded web server, Jetty, rather than Tomcat. When GWT team was determining 1.6 milestone, they started this issue to discussion (here) Finally, cons and pro's of Jetty overcome Tomcat, and GWT 1.6 is shipped with a new embedded web server.

Among other sturctural changes, this change cause some issues. JNDI issue is one of them. In our legacy project we were using Tomcat and our JNDI settings was defined in context.xml. With a new jetty server, JNDI settings has to be defined in web-jetty.xml. But there is a undocumented (actually misdocumented) point, which should be kept in mind. When defining JNDI variable in jetty-web.xml, you should use full qualified name, unlike in Tomcat.

For example, in our old legacy code, Tomcat setting for our data source was defined as :
jdbc/SybaseIQ. But jetty expect full path such as: (java:comp/env/jdbc/SybaseIQ). Please note but you still need to use shorter name jdbc/SybaseIQ in your code or persistence.xml.
Otherwise you would get
"javax.naming.NameNotFoundException" exception and even lost yourself in complex advises from discussion groups.


Another point should be kept in mind, if you use another JPA implementation rather than Datanucleus, which comes with Google Application Engine, when you create your GWT project, do not select Google Application Engine option.


Friday, April 03, 2009

Hover Help (HH) Plug-in for Carbide c++ v2.0

Those of you, who use Eclipse IDE for development, know how much Eclipse IDE makes coding easier for developers. Among many other functionality, Eclipse IDE provides refactoring, skeleton project creation, automatic building, easy launching, template source generation, code completion and various and quickest way to access help contents. For example, by hovering mouse over an API or pressing F2 key on a keyword, javadoc of the keyword/API can be displayed in a pop-up browser in java source editors. In my last work, as an eclipse plug-in developer at Symbian/Nokia, London, I participated in a project to develop a plug-in for similar help functionality for Carbide c++.

There are many open source products and IDE based on Eclipse framework.
Carbide c++ from Nokia is one of them. “Carbide.c++ is a family of IDEs for the creation of C++ and C applications for Symbian OS devices. Carbide.c++ is based on the Eclipse IDE and the C/C++ development tools from the Eclipse CDT Project.”

Upon several open source mobile framework such as Google's Andriod and Apple's iPhone, last year Nokia decided to go open source too and acquired Symbian in Dec, 2008 and set up Symbian Foundation. By the end of this month (April, 2009), Symbian Foundation will kick off. One of the biggest task at Symbian nowadays is to prepare Symbian SDK to open source community. A good and easy accessible documentation is one of these tasks. My role in Symbian as eclipse plug-in developer was to prepare a Carbide c++ plug-in (Hover Help plug-in) to provide Symbian OS API documentation seamlessly in a c++ editor, similar to Javadoc display functionality in eclipse with F2 key or hovering by mouse.

Below you can find an overview of Hover Help plug-in. It is extracted from help of the HH plug-in. In this text, i wont go in technical details. But if you need more technical information (such as CDT, API binding, plug-ins, hover extension points, direct access to jar content without extracting), please contact me via email.

Hover Help (HH)


The Hover Help Plug-in is an Eclipse plug-in that provides a link between the Carbide IDE and the C++ Developer Library. When installed, it provides developers with easy access to the API reference documentation. When a user hovers over a C++ API, the editor shows the documentation for this API reference.




The Hover Help Plug-in uses the The Developer Library Plug-in. This is an Eclipse documentation plug-in that contains the information displayed when an API reference item is hovered over.
You can download the Developer Library Plug-in from the
Symbian Foundation website.

Prerequisites for installation


The following software package is required for the Developer Library Hover Help Plug-in to work:

  • Carbide 2.0 Note: The Hover Plug-in does not work with Carbide 1.3.
  • Hover Help Plug-in Dependencies: com.nokia.carbide.cpp.sysdoc.hover.dependencies
  • Hover Help Plug-in version 1.0 or higher: com.nokia.carbide.cpp.sysdoc.hover

You must also you have installed the other programs that are required to do Symbian OS C++ development in Carbide, such as Active Perl and an SDK. Refer to the readme documentation of Carbide for further information.

Installing the Hover Help Plug-in

You can install the Hover Help Plug-in in the same way as other Eclipse plug-ins:

  1. Place the Hover Help Plug-in and its dependency plug-in into Carbide’s plugins directory.
  2. Restart Carbide.

Set Up

This section describes the initial set up of the Hover Help Plug-in and how you can add the Developer Library plug-in.

After installation

After installation of all the components, the Hover Help Plug-in prepares itself for its first use by reading of the interchange file (hover_help.xml).

This process will take a few seconds and progress is displayed in Progress view.

You can cancel the indexing process, the hover help plug-in will be deactivated. You can re-activate the hover help plug-in using

the preference panel, the indexing will start again.

Adding a new Developer Library Plug-in

New versions of the Developer Library Plug-in are published regularly. You can configure the Hover Help Plug-in to use a new version as follows:

  1. Obtain the latest Developer Library Plug-in from the Symbian Foundation website, and copy the new plug-in into Carbide’s plugins directory.
  2. Restart Carbide.
  3. From Developer Library Hover Help Preference panel, make sure new added Developer library is selected. If not select it from plug-in drop-down box.

Activating the Hover Help Plug-in

If the Hover Help Plug-in has been de-activated, you can activate it by following the steps:

  1. Go to the Developer Library Hover Help Preferences and un-check the check box deactivate the plug-in. When you reactivate the Hover Help Plug-in, the plug-in will initialise to "Automatically select latest Developer Library". See automatically select the latest Developer Library for more information
  2. Select the plug-in from the Developer Libraries Help Files plug-in drop-down box.

Hover Help Preferences

This section describes the preferences panel that you can use to configure and change the Developer Library Plug-ins used by the Hover Help Plug-in.


With the preference panel I can:

  • Let the Hover Help plug-in automatically choose for me the right Developer Library Plug-in.
  • Select a Developer Library plug-in using the drop-down box.
  • Deactivate the Hover Help plug-in.
  • Restore the plug-in configuration to default.
  • Apply, confirm or cancel the changes.

Automatically select the Developer Library plug-in

When you check the check box "Automatically select the latest Developer Library" the Developer Library is automatically selected for you. The name of the selected library is displayed in the greyed field.

If you want to select a particular Developer Library Plug-in, you can uncheck the checkbox "Automatically select latest Developer Library".

The right Developer library is chosen using the following heuristic. To be noted that the items are ordered by importance.

  • Audience and license of the Developer Library. The choice is between platform and public development. For example: "DL for platform" will be chosen rather then "DL for public"
  • Publication date of the Developer Library For example: "DL published 15/02/2009" will be chosen rather then "DL published 01/01/2009"

Select a Developer Library

The selected Developer Library is shown in the drop-down box.
To be able to change the Developer Library, the
"Automatically select latest Developer Library" checkbox should not be checked. To change the active Developer Library, select the Developer Library Help Plug-ins drop-down box.

Deactivate Hovering check box

The Deactivate Hovering check box enables or disables the hovering feature in the Eclipse IDE.
When you reactivate the Hover Help plug-in, the plug-in is set to
"Automatically select latest Developer Library".

Apply, confirm, cancel

These buttons have the common Carbide behaviour.

Defaults

If “Restore Default” button is clicked, the plug-in will automatic reset to "Automatically select latest Developer Library".

Wednesday, February 18, 2009

King Rat by James Clavell

I am one of those guys who can not read any book any time. My mind set has to be in right mood to read a book. Otherwise how many times i start a book, i can not finish it. But once my mind set is right, i may finish a book in a day. I remember very well many times i tried to read The New Life by Orhan Pamuk and could not finish it, when it is first published . Whenever i opened the book, after 5-10 pages, i could not read further. I used to find myself lost among pages, sentences. But couple of years later, i finished it in a day, when my mind set was ready for it.

Fate of a book, King Rat by James Clavell was not much different than The New Life until last week. I felt a bit guilty not reading it becuase it was a gift from my girl friend. But whenever i opened it, i could not go more than a couple of pages, even though i saw its movie version. With its blue cover, it was on my book shelf for a long time, until my hungar to reading a non-technical text surged again. (I was not reading any novel, non-technical text last couple of months, due to busy work and mind set).

But last time, it was different. Once i started reading it, i could not stop myself. I did enjoy every pages, every word of it. Its affect on me was comparable to one of my favourite book, The Grapes of Wrath by John Steinbeck.

This book is based on a real life story of British pilot, Peter Marlowe, who surrendered to Japanese soldiers in WW II and his time with fellow English speaking people (American, British, Austrilian) as POW in a Japanese camp in Singapore. To survive in the camp with ethic and integrity against hunger, disease and primitive human and society rules and needs is the subject of the book.

I strongly advise this book to anybody who would like to meet real characters with their basic needs in tough circumstances. This book is a mirror to human nature and society.

Friday, October 17, 2008

PI approximation with Monte Carlo Simulation

/**
*
* PI approximation using Monte Carlo Simulation. Draw a square of
* unit area on the ground, then inscribe a circle within it. Now, scatter some
* small objects (for example, grains of rice or sand) throughout the square. If
* the objects are scattered uniformly, then the proportion of objects within
* the circle vs objects within the square should be approximately PI/4, which
* is the ratio of the circle's area to the square's area. Thus, if we count the
* number of objects in the circle, multiply by four, and divide by the total
* number of objects in the square (including those in the circle), we get an
* approximation to PI. (
http://en.wikipedia.org/wiki/Monte_Carlo_method)
*
*/
public class PiEstimationWithMonteCarlo {

public double estimatePI(long numberSample) {
long numberInCircle = 0;
double pi = 0.0;

for (int i = 0; i < numberSample; i++) {
double x = generateRandomNumber();
double y = generateRandomNumber();
if (insideCircle(x, y))
numberInCircle++;
}
pi = (numberInCircle * 4) / ((double) numberSample);
return pi;
}

private boolean insideCircle(double x, double y) {
double distance = x * x + y * y;
if (distance > 1) {
// out of circle
return false;
}
return true;
}

private double generateRandomNumber() {
// between -1 and 1
return Math.random() * 2 - 1;
}

public static void main(String args[]) {
PiEstimationWithMonteCarlo piEstimator = new PiEstimationWithMonteCarlo();
double pi = piEstimator.estimatePI(5000000);
System.out.println("PI=" + pi);
}
}

Tuesday, October 14, 2008

Bets and the City: Sally Nicoll's Spread Betting Diary

One of my friend started to work in a leading spread betting company recently. It was the first time i heard spread betting. It came cross to me as gambling at first but my friend tried to convince me that it is trading more than betting and many trader uses it to hedge their investment.

With these are in my mind, i bought a spread betting and a stock market books to get some beginner information about this sector. Let me be clear first, i don't like gambling, i never heard or seen anybody gains from gambling, apart from casino or gambling saloon owners. Besides, i saw from some of people around me how gambling dramatically effects people's life.

Spread betting book i purchased is
Bets and the City: Sally Nicoll's Spread Betting Diary. It has good review rate on Amazon and i think it is a good book to get some starting information on learning phrase of a spread better or gambler.

Nothing can explain this book more than "Bridget Jones meets Wall Street", i think. As a middle age, single lady with tendency to gambling, Sally decides to play on spread betting after reading an article on a magazine. She is also a full-time writer, struggling to finish her first novel. While she learns and gamble rather than trade on spread betting, she writes her spread betting experience or dairies on a spread betting company's website.

She puts together a genuine dairy. In her blog/dairy, she writes all her mistakes, losses, gains and lessons with a hilarious way with her daily life. Like many beginner, she is not much successful, in many trades she loses, but each time she strikes back with new methodologies. And she explains in a clean way her mistakes, as much as she can.

When she published her spread betting dairy as book, after a year, she was still a learner and not millionaire yet. She does not reveal her final account figures in the end of the book, but i think, she lost big chunk of her initial money. But she still claims that spread betting (especially binary betting) is a trade rather than a gambling, which i doubt very much, especially in this financial crisis (even in normal conditions, in the medium and long term). Maybe Sally should try also arbitrage sport betting which a friend of mine claims that he earned decent amount with his pocket money when he was in university. When i heard these, i can not help myself thinking motto of BBC3's The Real Hustle TV program: "These bets are very tempting to take part in but you can guess which way the bet always goes - the hustler's way!"


Wednesday, October 01, 2008

Sample Address Book

Here is a sample address book application based on 3-tier architecture and with various frameworks and toolkits such as :

Presentation layer
  • GWT
  • EXT GXT
Logic layer
  • Spring
  • Hibernate
Database layer
  • HSQLDB (or MySQL)

Source code as eclipse project is available here . Please note, in order to run project in eclipse, a maven 2 plugin must be installed. I suggest m2eclipse (http://m2eclipse.codehaus.org/).

Requirements for the address books are as follows:

  • A simple address book with three separate pages.
  • The first page should allow the user to input up to 50 names and phone numbers at a time. The user can input between one and fifty name/numbers at a time.Each name must be unique and have only one phone number.Both the name and the phone number must not be blank.The names and phone numbers should be stored in memory. Phone numbers should be validated to contain only numbers, with an optional + prefix and possibly one pair of brackets with at least one number in them. The phone number must start either with a + or a 0 - if it starts with a +, it cannot be followed by a 0.

  • The second page should list all stored numbers and names, sorted alphabetically.

  • The third page should allow a user to search the address book by phone number (exact number, not substrings) and also by full name or part of a name (case insensitive). It should display all matching names and related phone numbers for the search criteria.

Saturday, September 06, 2008

Spring in Finance eXchange

There is a full day free event SPRING IN FINANCE EXCHANGE on 10-10-08 by Spring Source. It seems interesting. Click here see the programme and register before it is too late.

Patterns of Enterprise Application Architecture by Martin Fowler

In this text, I will share my thoughts and some of the important points from Martin Fowler's book Patterns of Enterprise Application Architecture. Similar to some of my other texts, this is an ongoing text, i will try to update it regularly while i read the book.



Enterprise Applications

Followings are the important aspects of an Enterprise Applications:

  • Persistent Data
  • Huge Volume of Data
  • Concurrent Access to Data and Resources
  • Multiple User Interfaces
  • Integration with other Enterprise Applications
  • Same data with various syntax and semantics format
  • Complex Business Logic/Illogic

In the light of these, we can say that, for example, following applications are not of enterprise applications: web browser, word/image /video processor, games, OS, compilers, digital TV software... And followings can be given as examples to enterprise applications: " ... payroll, patient records, shipping tracking, cost analysis, credit scoring, insurance, supply chain, accounting, customer service, and foreign exchange tradin."

Performance of an Enterprise Application is one of the vital factor in its success. Following has to be kept in mind during design in terms of performance:

  • Response Time: Amount of time it takes to process an request
  • Responsiveness: How quick the system acknowledge back that a request is received. Generall, responsiveness is more shorter than response time.
  • Latency: Minimum time to get a response from a remote system for a given existing or non existing task or request. Remote calls tends to increase latency therefore they should kept minimum.
  • Throughput: The amount of work/task done in a given time.
  • Load: How much system is under stress due to concurrent requests on a time point.
  • Load Sensetivity: Under a specific load or stress quickness of response time
  • Efficiency: Performance (response or throughput) per by resource
  • Capacity: Maximum effective load or throughput of a sytem
  • Scability: How performance is affected if resources are added or removed. Especially, hardware resources must be kept in mind when considering scability.

In terms of performance, the ultimate target in enterprise applications is to maximize the throughput or minimizing the repsonse time. Obviously, there is a trade-off between throughput and response time, therefore, ratio between throughput and response time has to be decided based on the constraints and requirements of application domain.

Chapter 1- Layering

Layering is one of the fundemantal pattern in enterprise applications. Layering is representing an application with loose coupled and highly coherent components, each of which sits on top of a lower components. Each layer only aware of the lower layer and it provides an interface to communicate with upper layers. Layering provides:

  • Abstraction: Each layer is responsible of a set of task and does not has to know detail implementation of other layers
  • Substitute: Without effecting much other layers, a layer's implementation can be changed.
  • Minimize dependencies
  • Standardization: By providing interface each layer make some sort of de-facto standardization, contract for other layers.
  • Reusability: Layer can be used with other high level layers.

On the other hand, extra layering would degrade performance since in each layer data or inputs has to be transferred into the layer specific format.

The Three Principal Layers

There are three principle layers:

  • Presentation: Displaying or providing information to user. Generally sits on client side
  • Domain: Business logic which generally sits on server side.
  • Data Source : Communication with database, messaging system, transaction again generally on server side.

Chapter 2. Organizing Domain Logic

Three separated pattern to organize domain logic:

  • Transaction Script: Based on simple procedural approach
  • Domain Model: Based on Object Oriented modelling
  • Table Module: Hybrid of transaction and domain model

A common approach is to put a Service Layer on top of above patterns in domain logic. A service layer provides clear API and placeholds for transaction control and security.

Chapter 3. Mapping to Relational Databases

This chapter elaborates mapping patterns and issues between domain layer and datasource layer such as architectural, behavioral, structural, decorative, connections and schemas. Fortunately, many of these concerns and patterns are implemented and addressed with latest OMR frameworks (such as hibernate) unless if you dont want to create your own OMR layer or framework.

Chapter 4. Web Presentation

Most important aspect in Web presentation is separation of business logic from web presentation by using patterns similar to MVC (Model, View, Input Controller). In case of a web application, MVC works as follows:

  1. A request comes to controller which extract required information from the request.
  2. Controller forwards it to business logic for an appropriate model object
  3. The model object fetch persistent data via data access objects and aggregate/format data for response object
  4. Returns to controller to decide which view will be used to display the response.
  5. Controller passes the response data to the view
  6. View is prepared and return back to client

Separating model from presentation is also a good practice in terms of testing. Each section, especially business model, can be tested independently without dealing with presentation issues.

View Patterns

  • Transform View: Similar to XSLT, it deploys a transformation schema which applied to inputs.
  • Template View: With structured page which has embed markers indicating where dynamic content to go. Server page technologies such as ASP, PHP, JSP implement this pattern. While this pattern provides a flexible and powerful coding, unfortunately, it also leads to a messy presentation code.

In addition to these patterns, view is generated either with a single step(stage) or two step view. In single step view generation, there is a one view module for each user interface, display and presentation decisions are taken only in this module. But in two step view, each view module responsible of a specific view and then this view is passed to second stage where global, common view is created. This is a vital advantage of two step view cos of it provides highly coherent view modules.

Input Controller Patterns

Input controller handles HTTP request and analyse it and then decide what to do with the request. There are two patterns for input controller :

  • Page Controller: For every page there is a input controller which create models and process it and then create a view object and returns it.
  • Front Controller: A centralized single object intercepts all requests and upon analyse them, it creates separate handlers to process each request.

Chapter 5. Concurrency

Concurrency Issues

  • Lost Updates
  • Inconsistent read
  • DeadLocks/LiveLocks

Execution Contexts

  • Request
  • Session
  • Process
  • Thread
  • Transaction

Isolation and Immutability

Isolation and immutability are among two solutions for concurrency problems. In isolation, shared resource is isolated for only an active agents such as process in operation systems. Other approach is to make shared resource is immutable. If no active agent tries to change the shared resource, then there wont be lost update or inconsistent read problem.

Optimistic and Pessimistic Concurrency Control

If we can not enable a isolated or immutable shared resource, then we have to carry out either an optimistic or pessimistic concurrency control.

In optimistic concurrency control, shared resource is allowed by two or more active agent and then a conflicts are detected. If there is a conflict, it is asked user to make decision (to merge, or cancel) similar to source control system such as CVS or SVN.

In pessimistic concurrency control, once an active agents starts to work on a shared resource, agent locks it, and other agents can not access it until the active agent unlock the shared resource. Unlike optimistic approach, while this approach maximise the concurrency, it suffers from low availability as a shared resource is accessed by only one agents at a time.

Severity of conflict and frequency of changes are the two major factor deciding which approach to use. If change frequency is high and severity of conflict is low then optimistic approach can be chosen. But if conflict is major factor then pessimistic approach is the answer. But these two approach comes along with additional problems such as deadlocks and livelocks.

Transaction

Transaction is one of the primary technique for concurrency control. A transacation is a sequence of work with consistent states and well defined start and end points. All works in transacation are carried out completely nor neither of them if one fails (rollback). Transaction can be defined with following four properties (ACID)

  • Atomicity: Transaction as a whole is an atomic process. Namely, if a step in the transaction fails, then all other steps will be rolled back. Transaction finishes successfuly with an commit statement.
  • Consistency: During all step of transaction, system state must be consistent and noncorrupt.
  • Isolation: Results of each internal steps in a transaction is not visible to other transaction until it finishes with a commit statement.
  • Durability: Commit statement must do result of transaction persistent.

Databases, message queues, ATM, printers are the sample transactional resources. A transaction should be short as much as possible. If a transaction takes more than a request, then it is called long transaction. And if a transaction' s lifeycle is bound to only a request's, then it is called request transaction, in other words, it starts and finishes with requests. Another variation is late transaction which works for only updates. It does not prevent inconsistent reads.

Transaction Isolation Levels

Isolation levels are defined in terms of three factor:

  • Dirty Read: You are permitted to read uncommitted or dirty data. Data integrity is compromised, foreign keys violated and unique keys ingored.
  • Non-Repeatable Read: It means a row can be updated at two different time, T1 and T2 and each time, you would get a different updated data.
  • Phantom Read: If you read a row at time T1 and then later T2, data will be same on the row but more related row data is added to table.

ISO 92 standard defines four transaction levels (from low to high):

  • Read Uncommitted
  • Read Committed
  • Repeatable Read
  • Serializable
Isolation LevelDirty Read Unrepeatable ReadPhantom
Read Uncommitted YES YES YES
Read CommittedNOYESYES
Repeatable ReadNONOYES
SerializableNONONO


Chapter 6. Session State

A session in a distributed environment system can either be:


  • Statelessness: System does not retain state between requests. When a request invoke a method, the state of the objects used by the method are not known. As default, HTTP protocol is stateless.
  • Stateful: System stores or keep track of states or information between requests.

Stateful system requires more resource as each stateful object has to to store all its states. On the other hand, a stateless object can be other requests too. But in real life problems, we need to store states. Therefore, best approach would be to store states on a stateless server.

Session States

Session state are the states that they are bound to session and isolated from other concurrent sessions. Lifecycle of a session state is limited with session's, so if you want to persist states further than business transaction, they should be persisted on other medium such as on databases.

Session states in business transaction has to obey fundemantal rules of transaction (ACID) when business transaction finished. For example. during business transaction, session states maybe be in invalid or inconsistent, but before commit, they have to be consistent with the rest of the data. But more important concern is the isolation between session states. Operations in business transaction must not cause an inconsistent data cos of multiple concurrent read and updates. Session states must be kept isolated from other sessions.

For performance reason, some data can be stored in sessions as part of a cache mechanism between requests. But this data is not a session state.

Methods to Store Session State

  • Client Session State: Storing data on client side. Most common methods: encoding data on URL, cookies or hidden form variables in html. Often these session data has to converted to right format in server side. If the amount of data is large and frequent, that approach suffers bandwith problem. It also exposes security and data integrity issues, unless data encryption is applied.
  • Server Session States: For example stroring data on server's memory or more for further persistence, serialized object can be stored on filesystem or database table where session id would be primary key and serialized object would be value. In case of session migration, transfering session to another server, session states have to stored in a shared resource or memory. That approach is good when session states are continouosly proccessed.
  • Database Session States: It is also server side but object's states are mapped to columns in a table for a longer persistence. Special attention has to be paid to secure isolation of session data in databases. In terms of performance, this approach is appropriate when session data is idle most of the time, for example in a public retail system.

Session data has to be cleared after some timeout or if request is cancelled. In case of client session state approach, this is not big concern as much others. A timeout has to be put place in server and database session states.

These three approaches can be used all together. But generally Server and Client session states are mostly used in practice. As pointed out above, if data is small and not complex, client session states is a good candidate. If you need failover, clustering and isolation between session is not problem, then Database session states can be used.