webcab options and futures for .net v3€¦ · techniques for european, asian, american, lookback,...

153
WebCab Options and Futures for .NET v3.0

Upload: others

Post on 13-Jun-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

WebCab Options and Futures for .NET v3.0

Page 2: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Preface

This documentation accompanies the WebCab Options and Futures .NET Service. Thepurpose of this documentation is to provide a clear and concise description of all aspectsthat are likely to be encountered in real life applications by developers and users of thisenterprise Application. This class allows the use of quantitative and risk managementtechniques for European, Asian, American, Lookback, Bermuda and Binary Options; wealso cover futures and forward contracts. We apply the Black-Scholes-Merton Optionspricing model using Analytic, Monte Carlo and Finite Difference techniques. We also offerestimates of implied and historical volatility, futures account management and market riskmonitoring techniques.

The first chapter of this documentation contains a brief introduction to the most im-portant implemented features and related system requirements. In chapter two we let thedeveloper quickly get started with deploying the component by detailing deployment tech-niques on the most widely used application servers. The third, fourth and fifth chapterscontains the financial and mathematical documentation, which represents the theoreticalbackground of this Applications implemented features. Chapters six until ten, contains theprogrammer’s guide, giving a road map for developers to take advantage of every featureand capability. In chapter ten we provide some examples to illustrate how features detailedwithin the programmer’s guide can be applied in practice. Finally, we introduce WebCabComponents, its philosophy and approach to serving the .NETTM development communitywith robust and powerful .NET Services.

Good luck with your project and thank you for your interest in our components.

The WebCab Components Team

i

Page 3: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Contents

Preface i

1 Introduction 11.1 Product Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.1.2 Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.2 Prerequisites and Compatibility . . . . . . . . . . . . . . . . . . . . . . . . 51.2.1 System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2.2 Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Where do I Start? 72.1 What Type of User Are You? . . . . . . . . . . . . . . . . . . . . . . . . . 72.2 What Do I Need to Install and Where Can I Get It? . . . . . . . . . . . . 8

2.2.1 Installing the IIS Web server . . . . . . . . . . . . . . . . . . . . . . 92.2.2 What Do I Need if I am Using Windows 2003? . . . . . . . . . . . . 10

2.3 Deploying the .NET Service . . . . . . . . . . . . . . . . . . . . . . . . . . 122.3.1 Deploying a Component . . . . . . . . . . . . . . . . . . . . . . . . 122.3.2 Deploying an XML Web Service . . . . . . . . . . . . . . . . . . . . 13

2.4 Using the DLLs inside an IDE . . . . . . . . . . . . . . . . . . . . . . 152.4.1 Using the DLL within a Visual Studio .NET project . . . . . . . . . 152.4.2 Using the DLL within a Borland’s C# Builder project . . . . . . . . 15

2.5 Client Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.5.1 Running the Console Client Example . . . . . . . . . . . . . . . . . 162.5.2 ASP.NET Client Example . . . . . . . . . . . . . . . . . . . . . . . 172.5.3 XML Web service examples . . . . . . . . . . . . . . . . . . . . . . 17

2.6 Testing the Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.6.1 Accessing the Online ASP.NET Demo . . . . . . . . . . . . . . . . 192.6.2 Online XML Web service examples . . . . . . . . . . . . . . . . . . 202.6.3 Using .NET Web Service Studio . . . . . . . . . . . . . . . . . . . . 21

3 Options Documentation 243.1 European and Binary Options . . . . . . . . . . . . . . . . . . . . . . . . . 24

3.1.1 Payoff functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.1.2 Put-Call Parity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

ii

Page 4: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

CONTENTS CONTENTS

3.2 Trading Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253.2.1 Spreads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263.2.2 Combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

3.3 Volatility and how to estimate it . . . . . . . . . . . . . . . . . . . . . . . . 263.3.1 Standard Historical Estimate . . . . . . . . . . . . . . . . . . . . . 273.3.2 ARCH, EWMA and GARCH models . . . . . . . . . . . . . . . . . 283.3.3 GARCH(1,1) Model . . . . . . . . . . . . . . . . . . . . . . . . . . 29

3.4 Black-Scholes Model for European Options . . . . . . . . . . . . . . . . . . 293.4.1 Options on Indexes, Currencies and Futures . . . . . . . . . . . . . 30

3.5 Greeks for European Options . . . . . . . . . . . . . . . . . . . . . . . . . 303.5.1 Risk Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.5.2 Delta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.5.3 Theta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313.5.4 Gamma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323.5.5 Vega . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323.5.6 Rho . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

3.6 Implied volatility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4 Futures Documentation 344.1 Futures Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

4.1.1 Forward Contract Pay Off . . . . . . . . . . . . . . . . . . . . . . . 344.2 Using Futures contracts to hedge . . . . . . . . . . . . . . . . . . . . . . . 34

4.2.1 Hedging a portfolio using index futures . . . . . . . . . . . . . . . . 344.2.2 Optimal Hedge Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . 35

4.3 Interest Bearing Investments . . . . . . . . . . . . . . . . . . . . . . . . . . 354.4 Pricing of Futures Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . 35

4.4.1 Assumptions underlying the pricing model . . . . . . . . . . . . . . 354.4.2 Futures and Forwards on Stocks, Bonds and Indexes . . . . . . . . 36

4.5 Futures on Commodities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

5 Exotic Options Documentation 395.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395.2 Types of Option Contract . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

5.2.1 Contracts with different Payoff Functions . . . . . . . . . . . . . . . 395.2.2 Weak Path Dependence and American Options . . . . . . . . . . . 405.2.3 Strong Path Dependence - Asian and Lookback Options . . . . . . 415.2.4 Time dependence - Bermudan options . . . . . . . . . . . . . . . . 41

5.3 The Black-Scholes Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415.4 General Methods of Pricing Options in the Black-Scholes World . . . . . . 42

5.4.1 The Black-Scholes Equation . . . . . . . . . . . . . . . . . . . . . . 425.4.2 Boundary and initial / final conditions . . . . . . . . . . . . . . . . 435.4.3 Methods of solving Black-Scholes PDE . . . . . . . . . . . . . . . . 43

5.5 Finite Differencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445.5.1 Single-Asset Options . . . . . . . . . . . . . . . . . . . . . . . . . . 44

iii

Page 5: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

CONTENTS CONTENTS

5.5.2 Multi-Asset Options . . . . . . . . . . . . . . . . . . . . . . . . . . 465.5.3 Modifications for American Options . . . . . . . . . . . . . . . . . . 475.5.4 Modifications for Strongly Path Dependent Options . . . . . . . . . 48

5.6 Monte Carlo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495.6.1 Random walks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495.6.2 Generating normal variables . . . . . . . . . . . . . . . . . . . . . . 515.6.3 Options on many underlying assets: Higher dimensions . . . . . . . 515.6.4 Advantages of Monte Carlo simulations . . . . . . . . . . . . . . . . 52

5.7 Sources of Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525.7.1 Errors determined by algorithm instability . . . . . . . . . . . . . . 535.7.2 Monte Carlo errors due to number of simulations used . . . . . . . 545.7.3 Finite Differencing errors due to wrong boundary conditions . . . . 545.7.4 Finite Differencing errors due to the size of the price step . . . . . . 555.7.5 Errors due to the size of the time step . . . . . . . . . . . . . . . . 55

5.8 Greeks of Exotic Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565.8.1 Finding Greeks of Exotic Options using Monte-Carlo . . . . . . . . 57

5.9 Employee Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575.9.1 Details and Assumptions of the Enhanced FASB 123 Model . . . . 585.9.2 Brenchmark Results . . . . . . . . . . . . . . . . . . . . . . . . . . 58

5.10 Scenario Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605.10.1 Scenario Grids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615.10.2 Scenario Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

6 Programmer’s Guide for Microsoft Office 656.1 Developing with VBA from Office . . . . . . . . . . . . . . . . . . . . . . . 65

6.1.1 Open the Visual Basic Editor . . . . . . . . . . . . . . . . . . . . . 666.1.2 Add a Code Module . . . . . . . . . . . . . . . . . . . . . . . . . . 666.1.3 Declare a Subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . 666.1.4 Add a Reference to This Product . . . . . . . . . . . . . . . . . . . 676.1.5 Declare a Class Instance Variable . . . . . . . . . . . . . . . . . . . 696.1.6 Create a Class Instance . . . . . . . . . . . . . . . . . . . . . . . . . 696.1.7 Call a Class Method . . . . . . . . . . . . . . . . . . . . . . . . . . 706.1.8 Display the Method Result . . . . . . . . . . . . . . . . . . . . . . . 706.1.9 Run the Subroutine . . . . . . . . . . . . . . . . . . . . . . . . . . . 706.1.10 A Generic VBA Example for Office . . . . . . . . . . . . . . . . . . 73

6.2 Integrating with Microsoft Excel . . . . . . . . . . . . . . . . . . . . . . . . 746.2.1 Open the Visual Basic Editor . . . . . . . . . . . . . . . . . . . . . 746.2.2 Add a Code Module . . . . . . . . . . . . . . . . . . . . . . . . . . 746.2.3 Declare a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . 756.2.4 Add a Reference to This Product . . . . . . . . . . . . . . . . . . . 756.2.5 Declare a Class Instance Variable . . . . . . . . . . . . . . . . . . . 756.2.6 Create a Class Instance . . . . . . . . . . . . . . . . . . . . . . . . . 766.2.7 Call a Class Method . . . . . . . . . . . . . . . . . . . . . . . . . . 766.2.8 Store the Method Result as a Function Return Value . . . . . . . . 76

iv

Page 6: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

CONTENTS CONTENTS

6.2.9 Insert the Function in your Worksheet . . . . . . . . . . . . . . . . 77

7 Programmer’s Guide for Visual Studio 6 817.1 Developing with Visual Basic 6 . . . . . . . . . . . . . . . . . . . . . . . . 81

7.1.1 Add a Reference to This Product . . . . . . . . . . . . . . . . . . . 817.1.2 Declare a Class Instance Variable . . . . . . . . . . . . . . . . . . . 827.1.3 Create a Class Instance . . . . . . . . . . . . . . . . . . . . . . . . . 837.1.4 Call a Class Method . . . . . . . . . . . . . . . . . . . . . . . . . . 84

7.2 Illustrating Visual Basic Examples . . . . . . . . . . . . . . . . . . . . . . 847.2.1 Calling the CallDelta method which takes and returns doubles . . . 867.2.2 Calling the HistoricalEstimateWithDividends method which takes

two double arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877.3 Developing with Visual C++ 6 . . . . . . . . . . . . . . . . . . . . . . . . 89

7.3.1 Open a New or Existing Project . . . . . . . . . . . . . . . . . . . . 897.3.2 Add All COM Specific ’include’ Declarations . . . . . . . . . . . . . 937.3.3 Call ”CoInitialize” . . . . . . . . . . . . . . . . . . . . . . . . . . . 937.3.4 Import the Type Library for this Product . . . . . . . . . . . . . . 947.3.5 Connect to a COM Server . . . . . . . . . . . . . . . . . . . . . . . 947.3.6 Declare the Parameter Types and Values . . . . . . . . . . . . . . . 957.3.7 Declare the Return Type . . . . . . . . . . . . . . . . . . . . . . . . 977.3.8 Call the Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 977.3.9 Call ”CoUninitialize” . . . . . . . . . . . . . . . . . . . . . . . . . . 987.3.10 A Generic Visual C++ Example . . . . . . . . . . . . . . . . . . . . 99

8 Programmer’s Guide for Borland C++ Builder 1028.1 Developing with Borland C++ Builder . . . . . . . . . . . . . . . . . . . . 102

8.1.1 Open a New or Existing Project . . . . . . . . . . . . . . . . . . . . 1038.1.2 Add all COM Specific ”Include” Declarations . . . . . . . . . . . . 1058.1.3 Call ”CoInitialize” . . . . . . . . . . . . . . . . . . . . . . . . . . . 1058.1.4 Create a Class Instance . . . . . . . . . . . . . . . . . . . . . . . . . 1068.1.5 Obtain a Method ID . . . . . . . . . . . . . . . . . . . . . . . . . . 1078.1.6 Declare the Parameter Values and Types . . . . . . . . . . . . . . . 1078.1.7 Declare the Return Type . . . . . . . . . . . . . . . . . . . . . . . . 1088.1.8 Call the Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1088.1.9 Call ”CoUninitialize” . . . . . . . . . . . . . . . . . . . . . . . . . . 1098.1.10 A Generic Borland C++ Builder Example . . . . . . . . . . . . . . 109

9 Programmer’s Guide for .NET 1129.1 Developing with .NET Class Libraries . . . . . . . . . . . . . . . . . . . . . 112

9.1.1 Stand-alone C# .NET Applications . . . . . . . . . . . . . . . . . . 1129.2 Developing with XML Web Services . . . . . . . . . . . . . . . . . . . . . . 114

9.2.1 Deploying the XML Web Services . . . . . . . . . . . . . . . . . . . 1149.2.2 Writing XML Web Service Clients . . . . . . . . . . . . . . . . . . . 1149.2.3 Writing Console XML Web Service Clients . . . . . . . . . . . . . . 115

v

Page 7: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

CONTENTS CONTENTS

9.2.4 Importing Web services into Visual Studio .NET projects . . . . . . 1179.3 Connecting to a Database with our .NET Libraries . . . . . . . . . . . . . 118

9.3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1189.3.2 The ADO Mediator . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

9.4 Programmers Guide for Implementing Custom Contracts and BoundaryConditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1239.4.1 Specifying the Contract to be Priced . . . . . . . . . . . . . . . . . 1249.4.2 Boundary conditions . . . . . . . . . . . . . . . . . . . . . . . . . . 125

10 Examples 12910.1 Question and Answer (QA) Client Examples . . . . . . . . . . . . . . . . . 129

10.1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12910.1.2 Structure of QA Examples Directory . . . . . . . . . . . . . . . . . 12910.1.3 Quick Start Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . 13110.1.4 Explanation of the QA Directory Structure and its files . . . . . . . 13110.1.5 Remarks on .NET compilers . . . . . . . . . . . . . . . . . . . . . . 13310.1.6 Database Example with JDBC Mediator . . . . . . . . . . . . . . . 133

10.2 Exotic Options Custom Examples . . . . . . . . . . . . . . . . . . . . . . . 13410.2.1 About the examples . . . . . . . . . . . . . . . . . . . . . . . . . . 13510.2.2 Testing procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13510.2.3 Example 1 - European vanilla options . . . . . . . . . . . . . . . . . 13510.2.4 Example 2 - Supplying your own payoff function and boundaries . . 13610.2.5 Example 3 - Supplying your own payoff function for multi-asset

boundaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13710.2.6 Example 4 - Thorough comparison between finite differencing and

Monte Carlo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13810.2.7 Example 5 - American options . . . . . . . . . . . . . . . . . . . . . 13810.2.8 Example 6 - American multi-asset options . . . . . . . . . . . . . . 13910.2.9 Example 7 - Example of Bermudan options . . . . . . . . . . . . . . 14010.2.10Example 8 - Example of Binary options . . . . . . . . . . . . . . . . 14110.2.11Example 9 - Example of Asian options . . . . . . . . . . . . . . . . 14110.2.12Example 10 - Example of Lookback options . . . . . . . . . . . . . 14210.2.13Example 11 - Example of Monte Carlo with error control . . . . . . 142

11 Guide to WebCab Components 14411.1 The Company . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14411.2 Presentation of Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14411.3 Supported Clients, IDEs, Containers and DBMSs . . . . . . . . . . . . . . 14411.4 Transparent Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . 14511.5 Company Culture and Activity . . . . . . . . . . . . . . . . . . . . . . . . 14511.6 Product Life cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14511.7 Support, Warranty and Upgrades . . . . . . . . . . . . . . . . . . . . . . . 145

vi

Page 8: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 1

Introduction

1.1 Product Description

1.1.1 Overview

Price a broad range of option and futures contracts using a range of price/vol/interest ratemodels. Includes in addition to the general pricing framework a detailed Black-Scholes-MertonModel API for European, Asian, American, Lookback, Bermuda and Binary Options usingAnalytic, Monte Carlo and Finite Difference techniques. We also offer a flexible implementationof a binomial and trinomial trees based pricing engine for the evaluation of employee options inaccordance within the Enhanced FASB 123 model.

1.1.2 Details

WebCab Options and Future implements the following functionality:

General Equity Derivatives Pricing Framework

General Pricing Framework offers the following predefined Models and Contracts:

� Contracts: Asian Option, Binary Option, Cap, Coupon Bond, Floor, Forward Startstock option, Lookback Option, Ladder Option, Vanilla Swap, Vanilla Stock Option,Zero Coupon Bond, Barrier Option, Parisian Option, Parasian Option, Forward andFuture.

� Interest Rate Models: Constant Spot Rate, Constant (in time) Yield curve,One factor stochastic models (Vasicek, Black-Derman-Toty (BDT), Ho & Lee, Hulland White), Two factor stochastic models (Breman & Schwartz, Fong & Vasicek,Longstaff & Schwartz), Cox-Ingersoll-Ross Equilibrium model, Spot rate model withautomatic yield (Ho & Lee, Hull & White), Heath-Jarrow-Morton forward rate model,Brace-Gatarek-Musiela (BGM) LIBOR market model.

� Price Models: Constant price model, General deterministic price model, Lognormalprice model, Poisson price model.

1

Page 9: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Introduction Chapter 1

� Volatility Models: Constant Volatility Models, General Deterministic Volatilitymodel, Hull & White Stochastic model of the Variance, Hoston Stochastic Volatilitymodel.

Once the contract and the price/interest/vol model combination has been set you able torun the Monte Carlo Pricing Engine which allows:

� Evaluate Price: Evaluate price estimate accordance to number of iterations ormaximum expected error

� Estimate Error: Evaluate the standard deviation of the price estimate, and theminimum/maximum expected price for a given confidence level.

Exotic Options Module

The Exotic Options module implements the following functionality:

� Types of Options - Within this module we show explicitly how-to and offer prac-tical advice on the valuation of Asian, American (single and multi-asset), Lookback,Bermuda, European (single and multi asset) and binary options using the MonteCarlo and Finite Difference techniques.

� Finite Difference Methods - powerful method for finding solutions of the Black-Scholes Equations.

– Single Asset Options - We provide an explicit and fully implicit algorithmsincluding a framework in which to measure stability issues under differing sce-narios.

– Crank-Nicholson - is a fast and stable method for evaluating single assetoption contracts.

– Multi-Asset - Implement a general multidimensional finite-difference algo-rithm.

– American, Bermuda Options Modification - we apply the ‘SuccessiveOver-relaxation’ technique in order to value American and Bermuda options.

– Asian and Lookback - examples of how strongly path dependent options canbe evaluated using Finite Difference methods is given.

– Implied Volatility - Evaluate the implied volatility of a number of Exoticoptions including American, Asian, Lookback and Binary in accordance withthe Black-Scholes model.

� Monte Carlo - can be effectively applied to value a large range of option contracts.

– Flow implementation - including generation of normal variables and the sim-ulation of the random walk and corresponding cash flows ensures that our imple-mentation of this technique can be applied to value almost any option contract.

2

Page 10: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Introduction Chapter 1

– Options on many underlying assets - Generate correlation random variableusing Cholesky factorization in order to value options contract of European typewhich depend on many underlying assets.

– Control Structure - the user has full control over the number of simulationsand/or the required precision.

Trees Module

The Trees module implements the following functionality:

� Employee Options - A binomial and trinomial trees based pricing engine for theevaluation of employee options in accordance within the Enhanced FASB 123 modelas detailed within the paper, ’How to value Employee Stock Options’, by John Hulland Alan White (September 2002).

� Volatility models - Constant volatility model, and determinist volatility modelsprovided by using interpolation points or user define function of time.

� Interest Rate Models - Constant interest rate model or Yield Curve Model deducedfrom bond prices, forward rates, zero rates, forward rate curve can be used.

Options Module

The Options module offers the following functionality:

� European and Binary Options - The (Analytic) Black-Scholes model is fullyimplemented for European and Binary Options on stocks, currencies and indexes.We also include the Black-76 model for the evaluation of options on futures contracts.

� ‘The Greeks’ - We offer methods for the evaluation of ‘the Greeks’ (delta, gamma,rho, theta, vega) for European options on stocks, indexes and currencies accordingto the Black-Scholes model.

� Volatility Estimates - the volatility may to estimated directly from historical valuesor from one of the following models:

– ARCH - Autoregressive Conditional Heteroscedasticity model.

– EWMA - Exponentially Weighted Moving Average model.

– GARCH(1,1) - Generalized Autoregressive Heteroscedasticity model.

� Implied Volatility - Calculates the implied volatility for dividend and non-dividendpaying stocks from the Black-Scholes formulae.

� Payoff Functions - Pay off functions at expiry for European and Binary Optionsare implemented.

� Put - Call Parity relations

3

Page 11: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Introduction Chapter 1

– Put - call parity relations for European options on an asset with no yield ora continuous yield.

– Put - call parity relations for Binary options on an asset with no yield.

– Implied risk-free interest - the implied risk free interest rate is calculatedwhen either the prices of put/call European or put/pull Binary option is known.

� Trading Strategies - the following pay-off functions for the following option tradingstrategies are implemented.

– Spread Option Strategies - Bull Spreads, Bear Spreads and Butterfly Spreads.

– Combination Option Strategies - Straddles and Strangles.

Futures Module

The Futures module implements the following methods and procedures:

� Pricing on investment and consumption assets - Pricing of futures contractson stocks, bonds, indexes, currencies and commodities.

– Futures on stocks, bonds, indexes - evaluation for assets with or withoutincome, effective gearing.

– Futures on commodities - cost of carry, utility yield.

� Hedging - Portfolio hedging using index futures, optimal hedge ratio.

– Portfolio Hedging - delta hedge a portfolio using the beta coefficient.

– Optimal Hedge Ratio - the optimal ratio of the size of the position taken infutures contracts and the size of the exposure.

� Future Account management - margin, daily P&L, total equity, excess margin.

� Interest calculations - return, compound interest, compounding periods conver-sion.

The Risk Management functionality included within this Component:

� Delta Limit Monitoring - For a portfolio (which may include Futures, Options,etc) the delta limit can be assigned and checked.

� Scenario Analysis - Allows for an asset or portfolio to be stressed and for theresulting behavior to be analyzed. We offer methods which stress the asset in anyone or two of the underlying market variables.

4

Page 12: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Introduction Chapter 1

Technology Aspects

This product also has the following technology aspects:

� 3-in-1: .NET, COM, and XML Web services - Three DLLs, Three API Docs,Three Sets of Client Examples all in 1 product. Offering a 1st class .NET, COM,and XML Web service product implementation.

� Extensive Client Examples - Multiple client examples including .NET (C#, VB.NET,C++.NET), COM and XML Web services (C#, VB.NET)

� ADO Mediator - The ADO Mediator assists the .NET developer in writing DBMSenabled applications by transparently combining the financial and mathematicalfunctionality of our .NET components with the ADO.NET Database Connectivitymodel.

� Compatible Containers - Visual Studio 6 (incl. Visual Basic 6, Visual C++ 6), Vi-sual Studio .NET (incl. Visual Basic .NET, Visual C#.NET, and Visual C++.NET),Borland’s C++ Builder (incl. C++Builder, C++BuilderX, C++ 2005), BorlandDelphi 3 - 2005, Office 97/2000/XP/2003.

� ASP.NET Web Application Examples - We provide an ASP.NET Web Appli-cation example which enables you to quickly test the functionality within this .NETService.

� ASP.NET Examples with Synthetic ADO.NET - we use a ASP.NET service toperform component calculations on SQL database columns from a remote DBMS. Weapply a component’s function to certain rows from the database and list the output inHTML format. This is a powerful feature since it allows you to perform calculationsin a DBMS manner without having to code the C# to SQL database transactionyourself as it is all done by the ASP within the .NET Framework managed serverside environment.

1.2 Prerequisites and Compatibility

1.2.1 System Requirements

� Microsoft Windowsr

XP/2000/2003 family

� Pentium III 500 MHz

� 64MB RAM

� .NET Framework 1.0 (or higher)

5

Page 13: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Introduction Chapter 1

1.2.2 Compatibility

Component Type

� ASP.NET XML Web service

� .NET Class Library

� COM Component

Built Using

� Microsoft .NET Framework SDK

6

Page 14: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 2

Where do I Start?

Start using the Options and Futures for .NET v3.0 .NET Service right away by following thefew quick and simple steps described in this chapter. If you require additional information orhave problems with the installation and use of this .NET Service then please do not hesitate tocontact us via our support forum at: http://www.webcabcomponents.com/support/index.php

2.1 What Type of User Are You?

.NET Components or XML Web Services

The prerequisite Windows operating system components you will need to have installed onyour local machine will depend on the way in which you intend to use our .NET Service.In particular, there are two distinct deployment architectures in which our product can beused:

� Class Library - those wishing the use our .NET Components functionality directlywithin there .NET Applications. This category includes those who wish to use ourcomponent within Microsoft’s Visual Studio .NET or Borland’s C#Builder projects,or those who simply want to register the DLL class library onto there local machinefor consumption by local or remote applications.

� XML Web service/ASP.NET - those wishing to deploy either an ASP.NET basedClient server application and an XML Web service.

Chapter Overview

Within the remainder of this chapter we will detail how to install and configure the nec-essary Windows components, deploy the .NET Components or XML Web Services andfinally how to run examples associated within these two deployment scenarios1.

1Later within this PDF documentation within the Programmers Guide we will cover developmenttechniques which can be employed for either composing larger applications or building clients for thesedeployed components and Web services

7

Page 15: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

The remainder of this chapter is structured in the following way, please feel free to skipany sections which are not relevant to you:

1. Configuration - Describes how to configure the Windows deployment/developmentplatform for .NET based applications, including Web Services.

2. Deployment - Details the deployment of the .NET Service as a .NET Componentor as a XML Web Service.

3. Using the DLLs inside an IDE - We detail here how to import the .NET ClassLibraries DLLs into Microsoft’s Visual Studio .NET and Borland’s C# Builder.

4. Clients - Explains client examples provided with this .NET Service

5. Live Demos - Details the functionality of the Online Web Application Demos.

2.2 What Do I Need to Install and Where Can I Get

It?

In order to deploy and then use a .NET Component within your applications you are re-quired to have (or install) the following Windows component onto your Windows operatingsystem:

� .NET Framework

If you wish to deploy either ASP.NET or XML Web services then you will also be requiredto install:

� Microsoft’s Internet Information Server (IIS)

In order to develop .NET based applications (i.e. compile C#.NET source code) you willalso need to have the following Windows Components installed:

� .NET Framework SDK

Getting the .NET Platform

The .NET Framework’s installation package comes in the following two flavors:

� .NET Framework SDK (approx. 110MB)

� .NET Framework, Redistribution package (approx. 23MB)

Those wishing to develop applications using the .NET Framework will require the .NETFramework and the .NET Framework SDK installed onto the development machine. Whereasthose who only wishing to deploy .NET Applications and Services will require only the.NET Framework (also known as the .NET Framework Redistribution package). The latestversion of these packages can be downloaded from http://msdn.microsoft.com/downloads.

In order to run our ASP.NET and Web service demos you are also required to have Mi-crosoft’s IIS Web server installed and started.

8

Page 16: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

Installing the .NET Framework

Through the Add/Remove Programs feature of the Control Panel you are able to dis-cover which version (if any) of the .NET Framework you are currently running. If youintend to upgrade to a later version of the .NET Framework then you are presently run-ning then we strongly suggest that you first uninstall all previous versions of the .NETFramework first. This is due to the fact that some applications will use the earliest in-stalled version of the .NET Framework rather than the latest edition.

You can then proceed to install the latest version of the .NET Framework by just exe-cuting the .NET Framework installation package by following through the dialog withinthe installation program.

Remark Please note that Microsoft will ensure backward compatibility of the .NETFramework. That is, application developed under v1.0 for example will run and behave ina similar fashion under later releases of the .NET Framework.

2.2.1 Installing the IIS Web server

In order to deploy and run ASP.NET or XML Web services you are required to have therelevant pieces of the “Applications Server” stack installed onto the deployment Windowsmachine. The key piece of this infrastructure stack is Microsoft’s IIS Web server.

On any Windows machine you can check to see whether the IIS Web server is installed andrunning by opening the following page within a web browser http://localhost. If the IISWeb server is installed and running then you will be presented with either a placeholderpage similar to the following:

9

Page 17: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

If you already have a web site deployed into the root directory of the IIS Web server thenthe home page of this web site will be displayed.

Remark By requesting the page http://localhost, the local IIS Web server will be auto-matically restarted if it is not already running.

Installation Process

If the IIS Web server is not installed onto your local machine then you may install itthrough using the Windows Program installation tool. To access this tool select:

Settings > Control Panel > Add or Remove Programs

Now click on the button, Add\Remove Windows Components. A window should pop-up in which a number of Windows components are listed, one of these items should readInternet Information Services (IIS). You should select the click box for this serviceand install it by clicking the Next button.

2.2.2 What Do I Need if I am Using Windows 2003?

Microsoft’s Windows 2003 is the first Windows operating system that has been designed ex-plicitly to host .NET Applications. Though, Windows 2003 has the .NET Framework v1.1embedded within the operating system you will still need to configure the IIS Web serveror the .NET Framework SDK if you intend to either deploy ASP.NET based Applicationsor use the Windows 2003 machine to develop .NET based Applications and Services.

10

Page 18: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

Installing the IIS Web server onto Windows 2003

The IIS Web server for the Windows 2003 operating system is not installed by default.Therefore, if you did not explicitly request the deployment of the system component knownas ‘Application Server’ during the installation of Windows 2003. You will need to manu-ally install this Windows 2003, component if you wish to deploy ASP.NET or XML Webservices to your local machine. For all Windows platforms the deployment process of theIIS Web server proceeds in a similar fashion via the control panel interface.

In order to deploy the ‘Applications Server’ components first select Add/Remove Win-dows Components from the Add/Remove Programs control panel interface.

Once the ‘Application Server’ is selected by clicking on the Details button you will bepresented with:

11

Page 19: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

Remarks

� As you can see from the above screen shot by default the ASP.NET, Enable net-work COM+ access and Internet Information Services (IIS) have been se-lected which is sufficient for the deployment of nearly all .NET Framework basedApplications and Services.

� The Windows 2003 platform contains a thoroughly updated infrastructure stack con-cerning the delivery of ASP.NET and XML Web services. This includes a newASP.NET container which is closely integrated with the IIS Web server. This updatecontains several enterprise level .NET related features concerning the managementof services (automatic startup, shutdown of services and the server itself), security(lockdown of ports and unused services), scalability (load balancing) and easier man-agement (Component services and IIS management console). In our opinion theWindows 2003 platform offers a significantly more robust platform than early ver-sions of the Windows platform in which to deploy .NET Applications and Services.

2.3 Deploying the .NET Service

If you installed this product using the MSI installer then the .NET Class Libraries DLLsshould already be registered within your global assembly cache. In order to use the corre-sponding XML Web Service implementation you will need to follow the deployment guidebelow.

In case you installed using a Zip package or wish to install the .NET Class Librariesonto another Windows machine we explain below how to manually deploy our .NET ClassLibraries.

2.3.1 Deploying a Component

Once the .NET Framework has been installed onto the deployment machine the component(i.e. the DLL), can be deployed and registered. By registering the component it will becomeavailable to local and remote .NET Applications and Services.

Making your components (locally) available

The easiest and quickest means to deploy the DLL component files, is to simply copy themto one of the following two directories on your Windows machine:

� WINDOWS\System

� Application directory - the directory in which the .NET Application which willconsume the component is located.

When your Application is executed Windows will automatically look in one of these loca-tions for the DLL file with it wishes to import.

12

Page 20: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

Making the Components Globally available?

The above deployment technique is straightforward but has the restriction that is does notallow for any custom configuration of the deployment environment which may be requiredby the .NET Application which will consume the component. Moreover, such deploymenttechniques do not allow the components (i.e. DLL’s) to be effectively shared between twoor more applications. In order to allow the components to be used by several applicationsyou must deploy the components within the Global Assembly Cache.

Remark The Global Assembly Cache within the .NET Framework plays a similarrole to that of the CLASSPATH environment variable within the Sun Java platform.

A Component can be deployed to the Global Assembly Cache in one of two ways:

� Microsoft Windows Installer 2.0 - Recommended for use on production servers.

� Global Assembly Cache tool (Gacutil.exe) - Recommended only for use on develop-ment or test servers.

Please note, in order to use the Assembly Cache tool you are required to have the .NETFramework SDK installed and to create a Windows installer you will need the WindowsInstaller SDK v2.0. For further details concerning the Windows Installer technology werefer the interested reader to the Visual Studio .NET documentation or the MSDN sectionof Microsoft’s website.

The Global Assembly Cache Tool is run from the DOS command prompt. In order todeploy the assembly WebCab.Libraries.OptionsDemo.dll, contained within the present di-rectory you must input the command:

Gacutil.exe /i WebCab.Libraries.OptionsDemo.dll

Using the DLL within your own Applications

Within the Library directory of the installation package you will find the class libraryassembly (DLL) for Options and Futures. There are several ways you may choose to usethis DLL within your applications.

2.3.2 Deploying an XML Web Service

Once the .NET Framework and the IIS related infrastructure is installed the actual deploy-ment of an ASP.NET Application or an XML Web service just involves copying a DLL fileand several ASMX files into given directories within the IIS Web server root file directory.

Installation Process

13

Page 21: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

Within the XML Web service folder within this installation package are the resourcesfor deploying the Web service of the Options and Futures. In order to install and startusing the XML Web service functionality you will need to perform the following steps:

� Deploy the XML Web service assembly (DLL) onto your local IIS Web server. Thisis accomplished by copying the contents of the ‘bin’ folder of the current directoryto the ‘bin’ folder of the local IIS root directory, which under the default installationis C:\Inetpub\wwwroot.

� Deploy all .asmx pages inside the IIS Web server, by copying all the folders locatedunder the XML Web service folder located under the current directory to the IISroot directory.

� Run the WSDL tool in order to generate all XML Web service proxies. This is doneby running the following line at the command prompt:

wsdl http://localhost/<directory name>/<XML Web service>.asmx

where <directory name> is the name of the subdirectory of the IIS root in whichthe XML Web service is deployed and <XML Web service> is the name of the Webservice which you wish to generate a proxy for.

Remarks

� All generated proxies are used as described in the CHM documentation of this prod-uct.

� If the Web service is not being locally run then the ‘localhost’ should be replacedwith the host name of the computer where the Web service is deployed and running.

� You may be using another equivalent ASP.NET Web server, in which case the abovedeployment procedure may differ slightly in detail but will still involve the same basicsteps.

Testing the Deployment

You can easily test an XML Web service deployment by using any compatible web browser.That is, to test the deployment open a compatible web browser (for example Internet Ex-plorer) and open the following page:

http://localhost/<directory name>/<filename>.asmx

where <directory name> is the name of the subdirectory of the IIS directory root wherethe Web services are located and <filename> is the name of one of the .asmx files locatedinside the <directory name> folder. As soon as the browser displays the page correctlyyou are sure that the corresponding XML Web service has been properly installed.

14

Page 22: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

2.4 Using the DLLs inside an IDE

2.4.1 Using the DLL within a Visual Studio .NET project

If you are developing a Visual Studio .NET project and wish to use our DLLs componentsfunctionality then you may add the DLL to the project reference. This is performed byusing the Project > Add Reference... menu item.

2.4.2 Using the DLL within a Borland’s C# Builder project

If you are developing a C#Builder project and wish to use our DLLs components function-ality then you may deploy and then add the assembly to your project solely from withinC# Builder.

To deploy the DLL select from the menu, Component > Installed .NET Components Thenclick on the ‘Select an Assembly’, to select the DLL from the file system.

Once the DLL component is deployed you may add the DLL to your C# project by rightclicking on your project within the “Project Manager” and selecting “Add reference” asshow below:

15

Page 23: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

Alternatively, you could use the equivalent link with the menu, Project > Add Reference.

Now an ‘Add reference’ window will pop-up, in which you should select the assemblyyou wish to add to your project and then click OK.

2.5 Client Examples

Within this section we describe the clients which have been provided with this .NETService. In particular, we will describe:

1. Console Client Examples

2. ASP.NET Client Examples

3. Web Service Client Examples

2.5.1 Running the Console Client Example

In order to run the console demonstration examples you must start a DOS CommandPrompt. On a Windows XP machine this can be achieved by:

START > Programs > Accessories > Command Prompt

Once the command prompt is started you should navigate to the Librares\Client sub-directory of the installation directory2 using the cd command. The Client subdirectoryis structured into subdirectories corresponding to client examples. Every client exampleshould be accompanied by a compile.cmd file, which when run will compile its corre-sponding client. After compilation, the only thing left to do is launch into execution thegenerated executable file(s).

For further technical details you should read the README.TXT files located insidethe Client subdirectories.

2Usually C:\Program Files\WebCab Components\Options and Futures.

16

Page 24: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

2.5.2 ASP.NET Client Example

Within the \NET Libraries\ASP.NET Examples, folder of this package we have pro-vided a set of tailor made ASP.NET examples for the WebCab Options and Futures for.NET v3.0 .NET Service.

In order to start using these ASP.NET examples, please go through the following steps:

1. Deploy the ASP.NET Pages and Resources

(a) Copy the contents of the ‘Options ASP.NET Examples’ folder located in thecurrent directory to a location under your IIS (or another compatible ASP.NETweb server) root directory. This is usually ‘C:\Inetpub\wwwroot’ or a similarpath with a different drive letter.

(b) Secondly, copy the contents of the ‘bin’ subfolder of the current directory to the‘bin’ subfolder of your IIS root directory. If the ‘bin’ directory does not existinside the IIS root directory, you will be required to create it.

2. Run the ASP.NET Examples

(a) Open an Internet browser3 and type in the following address:

http://localhost/Options ASP.NET Examples/index.html

In case you chose to copy the ‘Options ASP.NET Examples’ directory to asubdirectory of your IIS root directory, you will need to include the full path toit inside the above URL. Also, if you have deployed these ASP.NET examplesto another .NET machine, you should replace ‘localhost’ with the name of thatmachine.

Remark An online version of these ASP.NET examples can be found at:

webcabcomponents.com/dotNET

Using the Example

Further explanation regarding the use of this example can be found within the ‘Accessingthe Online Demo’, section of this guide which details the use of the online version of thisASP.NET example.

2.5.3 XML Web service examples

Within the directory \XML Web Services\Client\, you will find C# application clientexamples which make use of the financial and mathematical functionality provided by theXML Web services implementation of the WebCab Options and Futures .NET Service.

3E.g. Internet Explorer, Opera, Mozilla.

17

Page 25: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

Remark In order to run and access the Web service examples it is necessary to havethe IIS web server and a compatible internet browser (for example Internet Explorer 5 orhigher) installed onto your local machine.

Please go through the following steps in order to test these client examples:

1. Before running or even compiling these XML Web service client examples you willhave to deploy all Options and Futures XML Web services located one directorylevel above to your local IIS server or an IIS server your machine can connect to.This is accomplished by copying the contents of the ‘bin’ folder, located one levelabove in the directory structure, to the ‘bin’ folder of the IIS root directory, usuallyC:\Inetpubwwwroot. You will also need to copy the ‘OptionsDemo’ folder to the IISroot directory.

2. Browse through each subfolder of the current directory and locate every ‘compile.cmd’compilation script file. There is one compilation script for every client example. Everyclient example requires certain XML Web services to connect to, which you maydetermine by running the compilation script. The reported errors should correspondto the XML Web services the client example requires.

3. Run the WSDL tool in order to generate XML Web service proxies for every XMLWeb service required by each client example. This is done by running the followingline at command prompt:

wsdl http://localhost/OptionsDemo/<XMLWebservice>.asmx

where <XMLWebservice> is the name of the required XML Web service and ‘localhost’should is the host name of the computer where the IIS server is running, in case it’snot this machine.

Make sure you are running this command from directory containing the compila-tion script.

4. Run the ‘compile.cmd’ compilation script file again. If the right XML Web serviceproxies have been generated for its client examples, the compilation script will com-pile all source code files and generate a .NET executable file (.exe). If the script stillresults in an error, please go through the previous step again, making sure you gener-ate the XML Web service proxy classes required by the client example correspondingto this compilation script.

5. Run the generated executable files. Running the executable files will allow you totest the client examples.

You may compile the client examples (after having generated the XML Web service prox-ies) and run their executable files as you go through each subfolder, since every client

18

Page 26: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

example is independent of each other.

If you wish to customize a particular client example after having run it, please feel free toadapt its source code files accordingly and run the compilation script again. Note that youwill not need to regenerate the XML Web service proxy classes.

2.6 Testing the Component

2.6.1 Accessing the Online ASP.NET Demo

By far the easiest way to test the functionality of this .NET Service is to view the on-line demo. The online demo can be accessed from our .NET Homepage by clicking the‘[ASP.NET]’ link corresponding to this Application. Once you click on the link the follow-ing pop-up Window will appear:

Fig: Interface of the ASP.NET online Web Application

Compatible Web Containers

This demo runs inside an online web container and demonstrates the ASP.NET technology.The demo can be accessed through a web browser and is compatible with Internet Explorer

19

Page 27: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

5, Netscape Navigator 4, Netscape 6, Opera 5 and higher.

Selecting a method to test

After clicking on the ‘[ASP.NET]’ link for this application from our home page the Webdemo will launch within a new browser window. To order to select a method from thisapplication use the drop-down menu on the left hand side of the screen to navigate throughall implemented functions. The menu lists all the components on the first level and theircorresponding functions on the second and third level. Click on the plus icon in order toexpand the component menu and then click a function item to select it.

Inputting data

The selected function will be displayed on the right hand panel of the new window accom-panied by its description and parameter characterization. Once the nature of the method isclear you may test the method by inputting the parameters within the text boxes providedor associating a database table field using our database management tool.

Running the demo using text boxes

Please input the value of each parameters in to the corresponding text box while payingattention to each parameter description. When all the parameters has been input, pressthe “Get Result” button on the right-hand side and towards the bottom of the screen inorder to request the solution from the server-side component. If by chance any parametersare out of range you will be prompted to enter a correct value before proceeding.

2.6.2 Online XML Web service examples

The XML Web Services contained within this package have also been deployed online. TheWeb service demo is accessed through our .NET Homepage by clicking on the ‘[WSDL]’link corresponding to this Service. Once you click on the link the following pop-up Windowwill appear:

20

Page 28: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

Fig: Interface of the Online Web Services

Remark In order to view the online demos you will require a compatible internet browser(for example Internet Explorer 5 or higher) with JavaScript enabled.

2.6.3 Using .NET Web Service Studio

You may wish to test the functionality of our XML Web services by using one of Mi-crosoft’s .NET tools made for testing XML Web services, .NET Web Service Studio2.0. A link to where you can directly download this tool is available on our onlineweb site at webcabcomponents.com/dotNET. Download and unzip the pack and run theWebServiceStudio\build.bat file. In order to start up the tool double-click the generatedWebServiceStudio.exe .NET executable file.

Deciding on an XML Web service

Click here in order to open the .NET Homepage of our web site. At the bottom of thepage you will notice a list of Online .NET Web Services with their corresponding ASP.NETExample page and their WSDL description page links. Click on the WSDL link next to:fullnamewithoutdotnet:. Move your mouse pointer above the left hand SIDE MENU andclick on an XML Web service name.

21

Page 29: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

A new browser window will open and present you with the default IIS 6.0 ASP.NETXML Web service page. Inside the ‘Address’ bar of your browser you will be able to seethe fully qualified URL to the online WSDL for the corresponding XML Web service.

Connecting to an XML Web service

Copy from your browser’s Address bar the WSDL URL to the XML Web service you havechosen to test and paste it into the WSDL EndPoint text field inside WebService Studio.Click the Get button next to this text field and wait for the tool to establish a connectionto the XML Web service.

As soon as the connection has been established, you can start going through every availablewebmethod our XML Web service has to offer by clicking on the items in the left hand sideof the tool’s window. After clicking a web method’s name, look inside the Input panel forrequired parameters. You may recognize these parameters from the available API CHMdocumentation we have included inside this package4.

Sending in Web Method Parameters

Inside the Body tree of the Input panel you may click on every parameter type and thenset its value inside the Value panel to its right. This is accomplished by editing the rightside of the Value column in the right hand side Value panel.

If you are dealing with parameters of an array type (say a Double[] array), you will firstset its Length in the Value panel and then go through every of its tree children inside theInput panel and set their Value field back into the Value panel. The following two screenshots explain this process.

WebService Studio: Setting the Length of a Double Array to 4

4Browse the API Reference by double-clicking the CHM file located inside the Documentation direc-tory of this Package.

22

Page 30: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Where do I Start? Chapter 2

WebService Studio: Setting the Value of its First Element to 12

Invoking a Web Method

After having sent in the right parameter values5 click the Invoke button right below theValue panel on the right hand side of the window.

The Output panel below the Input panel will present you with the results of invokingthe corresponding Web Method of our online XML Web service over the Internet.

5You should refer to the corresponding API HTML Help documentation even when running this testtool. You could however send in some arbitrary values just to try out some of our simpler Web Methods.

23

Page 31: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 3

Options Documentation

An option is the right to trade a particular asset at some time or interval in the futureat an agreed price. The mechanism for determining the agreed price and the variety withwhich the option can be exercised leads to the large range of options which exist withinfinancial markets.

Within Options theory there are a number of terms which are repeated used. Belowwe define the use of these terms once and for all so that they can be used within the restof this documentation and within the JavaDocs without confusion.

� Premium - the amount paid for the option contract

� Underlying (asset) - the financial instrument which the options depends upon, de-noted by S

� Strike (or exercise) price - the amount with which the underlying can be brought(call) or sold (put) during the period when the option can be exercised, denoted byEc, Ep, respectively

� Expiration date - the date of expiry of the option contract, denoted by T

� Intrinsic value - the payoff that would be received if the underlying is at its currentlevel when the option expires

� Time value - the value in excess of the intrinsic value

3.1 European and Binary Options

A European (or Vanilla) option is one of the following two types:

� Call option: a call option is the right to buy an asset Sc, at an agreed price Ec, at afixed time Tc

� Put option: a put option is the right to sell an asset Sp, at an agreed price Ep, at afixed time Tp

24

Page 32: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

We will also consider binary options (or digitals) which are contracts which have a payoffat expiry which is discontinuous in the underlying asset price. We consider a binary calloption which has a given fixed payoff if the underlying asset is greater or equal to thestrike price at expiry. The binary put option is similarly defined to have a fixed payout ifthe underlying asset is less than the strike price at expiry.

3.1.1 Payoff functions

The payoff function of an option contract is the cash (or equivalent) settlement which theinvestor receives at expiry. The payoff functions for an European option at expiry are givenby:

Call Option payoff function = max(Sc − Ec, 0)

Put Option payoff function = max(Ep − Sp, 0)

respectively.

We also provide the payoff functions for put and call Binary options.

3.1.2 Put-Call Parity

By arbitrage arguments one is able to derive what is generally referred to as put-call parityrelations. This allows for example the European call option price to be derived from theEuropean put option price when the two options act on the same underlying asset with thesame strike and expiry date. Similarly the European put option price can also be derivedfrom the European call option. The case when the underlying assets pay no dividend andpays a continuous dividend are treated for European options. In a similar fashion we alsooffer parity relations for binary options on assets which do not pay a dividend during thelife of the option.

In order to derive the call (or put) options value for a put (respectively call) option withthe use of parity relations we need to know the (fixed or average) risk free interest rateduring the life of the option contract. Within our component we allow the user to derivethe implied risk-free interest rate when the put and call option values are known in thefollowing instances:

� European options on an asset with zero yield

� European options on an asset with continuous yield

� Binary options on an asset with zero yield

3.2 Trading Strategies

An option trading strategy generally involves the use of more than one option which dis-plays a preferred payoff function characteristic from the investors stand point. Here we

25

Page 33: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

discuss a number of trading strategies which have become widely used within various fi-nancial markets.

3.2.1 Spreads

A spread trading strategy involves taking a position in two or more options on the sameunderlying asset and with the same expiry date. Procedures for the evaluation of the payoff functions at maturity of the following spreads are given:

� Bull Spreads - Buying a call option with strike x1, and selling a call option on thesame asset but with a strike x2, where x1 ≤ x2. The individual entering into thiscontract will gain if the underlying asset rises in value.

� Bear Spread - Buying a call option with strike x1, and selling a call option on thesame asset but with a strike x2, where x1 ≥ x2. The individual entering into thiscontract will gain if the underlying asset falls in value.

� Butterfly Spread - This trading strategy involves the use of three options with dif-ferent strikes. To construct the spread the investor must buy a call option with arelatively high strike x1, and a relatively low strike price x2, and sell two options witha strike midway i.e. at (x1 + x2)/2. Generally, the butterfly spread is constructedwith the midpoint close to the present market value. In this case the investor willgain if the price at expiry is close to its present price and will take a small loss if theprice moves significantly in either direction.

3.2.2 Combinations

A combination is an option trading strategy which involves taking positions in both putand call options on the same underlying asset. Methods for the evaluation of the payoff ofthe following strategies an given:

� Straddle Combination - involves taking a long position in a call option and a longposition in a put option with the same strike price and expiration date.

� Strangle Combination - consists of a long position in a call option and a put optionwith different strike prices and the same expiry date.

3.3 Volatility and how to estimate it

The volatility is a measure of the degree to which a given quantity fluctuates, which is in asense the amount of randomness of that parameter. The volatility is most commonly firstencountered in the context of the volatility of an assets price in order to be applied to thepricing of European options in the context of the Black-Scholes model (see below). Evenin the context of European options and the Black-Scholes model that is the (constant)volatility of the underlying asset price there are a number of senses in which the volatilitywill be referred to, namely:

26

Page 34: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

� Historical Volatility - Measure of the past fluctuations of the underlying assetprice. Below we describe the most common historical measure of the volatility usedwhich is the standard deviation of the log of the price returns.

� Implied Volatility - The volatility implied from the price of the European option inaccordance with the Black-Scholes model. However, in general the implied volatilitycould be deduced from any option price in accordance with any (volatility based)option pricing model.

� Forecast Volatility - An estimate of the future volatility of the underlying assetprice over some period. This is a required parameter within option pricing models.

It is important to point out that there is no one true measure of volatility. Moreover,the measure should be tailored to take into account its application. For example, withinthe Black-Scholes model we which to know as a model parameter the average volatilityover a given period, whereas when evaluating value-at-risk (VaR) or performed portfoliooptimization (CAPM) we are interested in the present value of the volatility of the assetswithin the portfolio.

3.3.1 Standard Historical Estimate

The historical volatility (as mentioned above) is most commonly estimated as the standarddeviation of the log of the asset returns. That is, if

� Si = the asset price at the end of the ith day

� Di = the interest payment (or dividend) from the asset on the ith day

� n = the number of days over which the historical data is taken

Then the log of the return on the ith day is given by:

ui = ln

(Si + Di

Si

)for i = 1, 2, . . . , n, and the historical daily volatility estimate, using the past n daysobservations of the asset price is given by:

Daily Volatility =

√√√√ 1

n− 1

n∑i=1

(ui − u)2 (3.3.1)

where u is the arithmetic average of the returns ui’s, over the n days.

Remarks If we had considered the returns on the underlying asset over the past nmonths then the corresponding formula for (3.3.1) would express the historical volatilityper month. Similar remarks hold if other time periods are used.

27

Page 35: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

We are able to express the historical volatility derived from the n asset prices with re-spect to another time period. In particular, we are able to derive the annual volatility.

The standard error per annum of the (annual) volatility historical volatility estimate isgiven by:

s∗√2n

where s∗ is the annual volatility.

Our Implementation

This estimation procedure has been implemented within the class as the following twomethods:

� Volatility.historicalEstimate - Estimates the historical volatility of an asset whichdoes not pay dividends or interest payments.

� Volatility.historicalEstimateWithDividends - Estimates the historical volatility of anasset which does pay dividends or interest payments.

The volatility evaluated by the historical procedure can be rescaled by the procedures:

� Volatility.yearDaysRescaling - Rescaling annual volatility to volatility over a givennumber of days.

� Volatility.daysYearRescaling - Rescaling the volatility over a number of days to theannual volatility.

We also provide to following error estimate:

� Volatility.historicalEstimateStandardError - The standard error of the historical an-nual volatility estimate.

3.3.2 ARCH, EWMA and GARCH models

These models where introduced to produce more accurate estimates of the present volatil-ity from historical data. With these more refined models more weight is give to recentmeasurements and an aspect of reversion to mean is incorporated which is displayed byvolatility in real world situations is incorporated within the models.

Within the volatility class we implement all of these models offering more refined meansby which to estimate and predict the volatility. The full names for these models are:

� ARCH - autoregressive conditional Heteroscedasticity

� EWMA - exponentially weighted moving average

� GARCH - generalized autoregression conditional heteroscedasticity

28

Page 36: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

ARCH Model

The ARCH model was first suggested by R.Engle, see ‘Autoregressive Conditional Het-eroscedasticity with Estimates of the Variance of UK Inflation,’ Econometrica, 50 (1982),987-1008. This estimate is based on the long term volatility (v) and historical observations(si).

EWMA Model

This model is a special case of the ARCH model. The weights assigned to the historical val-ues decrease exponentially. J.P.Morgan uses the EWMA model for updating daily volatilityestimates in its RiskMetrics database. In particular, if the weights are {αi : i ∈ 1, . . . , n},then the relation between the weights is given by αi+1 = λαi, where λ is a constant be-tween zero and one. J.P.Morgan found that across a range of market variable, by takingλ = 0.94, the forecasts of the volatility rate came closest to the realized volatility.

3.3.3 GARCH(1,1) Model

The GARCH(1,1) model was introduced by Bollerslev in 1986, see ‘Generalized Autore-gressive Conditional Heteroscedasticity’, Journal of Econometrics, 31(1986),307-27. TheEWMA model is a special case of the GARCH(1,1) model. The GARCH model exhibitsmean reversion whereas the EWMA model does not and hence the GARCH model istheoretically more appealing than the EWMA model.

3.4 Black-Scholes Model for European Options

We consider the Black-Scholes model for the evaluation of European put and call optionsat time zero on assets with or without interest payments. In particular, for the Europeanput (denoted by ‘p’) and call (denoted by ‘c’) options there exists closed formulae givenby:

c = S0N(d1)−Xe−rT N(d2)

p = Xe−rT N(−d2)− S0N(−d1)

where

d1 =ln(S0/X) + (r + σ2/2)T

σ√

T

d2 = d1 − σ√

T

and N(x) is the normal probability distribution with zero mean and standard deviation of1. The constant S0 is the stock price at time zero, X is the strike of the options, r is thecontinuously compounded risk free interest rate, σ is the volatility and T is the time tomaturity of the option.

The case when there exists dividends is handled by assuming that the stock price con-sists of a riskless component of the known dividend payments during the option period

29

Page 37: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

and a risky component which accounts for the remainder of the option price. By discount-ing the dividend payments by the risk free interest rate we can deduce the present valueof the option taking into account the effect of dividend payments which will decrease thevalue of the underlying asset. Strictly speaking the volatility used for this method shouldbe the volatility of the stock price net the present value of the assets dividend.

3.4.1 Options on Indexes, Currencies and Futures

European options on indexes, currencies and futures contracts are also traded on exchangesand within the over-the-counter market. By extending the classical Black-Scholes modelfor stocks we are able to evaluate options on this wider range of underlying assets.

These methods cover the evaluation of the following contracts:

� Index options on the S&P100 and S&P500 which are traded on the Chicago BoardOptions Exchange

� Currency Options trading on the Philadelphia exchange including Dollar-Yen calland put with have expiration dates in the nearest three months

� Futures options of Brent Crude Futures traded on the International Petroleum Ex-change (IPE)

3.5 Greeks for European Options

The Greeks describe the rate of change of the option price with respect to various marketvariables. These include the underlying stock price (delta), time (theta), rate of changeof the delta with respect to the underlying stock price (gamma), volatility (vega) and theinterest rate (rho). We will consider the Greeks for European options where the underlyingasset may yield a continuous dividend. We use the Black-Scholes model for the derivationof all the Greeks which is based upon following assumptions:

� An asset price follows a Markov stochastic process known as geometric Brownianmotion

� The short selling of securities with full use of proceeds is permitted

� There are no transaction costs or taxes. All securities are perfectly divisible

� There are no riskless arbitrage opportunities

� Security trading is continuous

� The risk-free interest rate is constant and the same for all maturities

Remark The Black - Scholes model can be extended in a number of directions by weak-ening these assumptions. In particular, we will consider the case when the asset has acontinuous yield.

30

Page 38: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

3.5.1 Risk Management

The Greeks provide a convenient mechanism for financial institutions to monitor and con-trol the risk they are exposed to from outstanding options contracts. Options can alsobe an important tool for the hedging of risk associated with stock (or other types of)portfolios. One of the most popular techniques is known as Delta hedging which involvestaking an options position with a delta which is the negation of the portfolios delta. Thenthe collection of assets consisting of the portfolio and the options will have zero delta or adelta-neutral position. The delta function is a linear functional which mean that the deltaof a portfolio is the sum and the deltas of the individual components. In particular, if anoptions portfolio has a delta of ∆, and consists of the wi options αi, for i = 1, . . . , n, then:

∆ =n∑

i=1

wi∆i

where ∆i, is the delta of the option αi.

Once a portfolio has been made delta neutral, the next stage is to consider its gammaand by taking an off setting position try to attain gamma neutrality. In a similar way atrader may wish to hedge a portfolio against volatility changes and may taken an optionposition which create an overall vega neutral position. In practice, options traders usuallyrebalance their portfolios at least once a day to maintain delta neutrality. It is usually notfeasible to maintain gamma and vega neutrality on a regular basis due to the trading costswhich would be incurred. Typically, a trader monitors these measures, and if they get toolarge, either some of this excess is hedged away or trading is curtailed.

3.5.2 Delta

Within our component we offer methods for the calculation of the delta of a European calland put option on an asset with or without a continuous yield. These methods can notonly be applied to the calculation of the delta of options on stocks but also to options onindexes, currencies and futures. We offer methods for each of these situations.

3.5.3 Theta

The theta of a portfolio or asset is the rate of change of its value with respect to the de-crease in the time to maturity. We calculate theta in time measured in years. Usually, whentheta is quoted time is measure in days. Theta can be converted to a per day measure-ment from a per year measurement by dividend by 252 the number of trading days in a year.

We consider the theta of a stock which may or may not pay of continuous dividend. Wealso provide methods for the evaluation of the theta of a European option on currencies,indexes and futures contracts.

31

Page 39: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

3.5.4 Gamma

The gamma of an portfolio of derivatives on an underlying asset is the rate of change ofthe portfolios delta with respect to the price of the underlying asset. In short, it is thesecond derivative of the portfolio value with respect to the asset price. Gamma is usefulfor determining the sensitivity of delta to changes in the underlying asset and hence therelative frequency in which the portfolio will need to be rebalanced in order to stay ap-proximately delta neutral.

We provide methods for calculating the gamma of options on stocks, indexes, currenciesand futures.

3.5.5 Vega

Vega is a measure of the sensitivity of the portfolio to changes in the volatility. If mayseem strange to use the Black - Scholes model to calculate vega since within this modelthe volatility is assumed to be constant. Ideally it would be better to develop a modelwhere the volatility is assumed to follow a stochastic process. However, it turns out thatthe vega calculated form a stochastic volatility model is very similar to the Black - Scholesvega so the practice of calculating vega from a model where volatility is constant worksreasonably well.

3.5.6 Rho

The Rho of a portfolio of derivatives is the rate of change of the portfolio value withrespect to the risk free interest rate. In the case of options on currencies where there aretwo interest rates there are two ‘rho’s’, one for the base currency interest rate and theother for the foreign currencies interest rate.

3.6 Implied volatility

The one parameter within the Black-Scholes pricing formulae that cannot be directly ob-served is the volatility of an asset. We showed above how the volatility can be estimatedfrom an assets historical price data. An alternative approach is to derive the volatilityof an asset from the market value of options on that given asset. The estimate for thevolatility derived by this method is referred to as the implied volatility.

Unfortunately, it is not possible to invert the Black-Scholes equations so that σ is ex-pressed as a function of S0, X, r, T and c. However an iterative search procedure can beused to find the implied σ. In our component we use Ridders method (see our componentWebCab Equation Solver for more details) in order to find the implied volatility with aprecision to six decimal places (i.e. 10e− 6).

32

Page 40: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Options Documentation Chapter 3

Implied volatilities can be used to monitor the market’s aggregate view of the volatil-ity of a particular quoted asset. Analysts will often calculate implied volatilities fromactively traded options on a given asset and use these results to calculate the price of lessactively traded options on the same underlying asset.

It is important to note that the prices of deep-in-the-money and deep-out-of-the-moneyoptions are relatively insensitive to volatility. Therefore the implied volatility calculatedfrom these options tends to be unreliable.

33

Page 41: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 4

Futures Documentation

Within is chapter we detail the type and nature of the implemented models within theFutures module. We will deal with quantitative and risk management techniques withfutures and forward contracts on stocks, indexes, commodities and currencies.

4.1 Futures Contracts

A futures contract is an agreement to buy or sell an asset at a certain future time for anfixed price. Futures contracts are usually traded through an exchange with the profit orloss from the futures contract held through a broker calculated every day and the accordingcash flows paid from one party (or account) to the other.

Futures contracts have become standardized for different markets. We will consider withinthe section futures contracts on stocks, bonds, commodities, currencies and indexes.

4.1.1 Forward Contract Pay Off

A forward contract is closely related to a futures contract the main difference being thatno money changes hands between the parties until the expiry date. We provide the payofffunction which calculates the cash flow between the parties on the expiry date.

4.2 Using Futures contracts to hedge

All methods related to the use of futures contracts to hedge positions can be found withinthe bean FuturesHedgingBean.

4.2.1 Hedging a portfolio using index futures

Stock index futures can be used to hedge the risk in a well diversified stock portfolio. Sinceby the Capital Asset Pricing model we know that the relationship between the expectedreturn on a well diversified portfolio of stocks and the return on the stock market as a

34

Page 42: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Futures Documentation Chapter 4

whole is described by the parameter β (beta). The beta is the slope of the line of best fitwhen the excess return of the portfolio is regressed against the excess return on the marketover the risk free rate. That is, when β = 1, the returns from the portfolio tend to matchthe return from the index. If β = n ∈ (0, +∞), then the returns from the portfolio tendto be n times the return from the index.

Within this component we include methods which allow the beta of a portfolio to beestimated and the calculation of the number of index futures contracts necessary to hedgea well diversified portfolio. We also offer a method which returns the number of indexfutures contracts which need to be brought or sold in order for the β, of the portfolioconstructed portfolio to be modified to any value we choose.

4.2.2 Optimal Hedge Ratio

The optimal hedge ratio is the ratio of the size of the position taken in futures contractsto the size of the exposure in order to have a perfectly hedged portfolio. Practically itmay not be possible to perfectly hedge a physical position with futures contracts since theexposure may not be equal to an integer multiple of the contract size. A method whichcalculates the number of futures contracts which offers the best hedge is given.

4.3 Interest Bearing Investments

The evaluation of futures contract is closely related to the analysis of interest bearinginvestments. For this reason we include basic methods related to fixed interest payingdeposits with compound and continuously compounded interest.

Later we will consider more delicate interest rate models which allows the interest ratecurve to be non-constant.

4.4 Pricing of Futures Contracts

With the pricing of futures contracts it is important to distinguish between futures oninvestment assets and futures on consumption assets. This distinction is necessary be-cause the holder of consumption asset utility may depend mainly on issues completelyindependent from the actually profit and loss realized from holding the contracts. For thisreason for consumption assets a non-arbitrage argument cannot be used in order to derivea pricing methodology.

4.4.1 Assumptions underlying the pricing model

In order to construct a pricing model we need to assume that there exists some marketparticipants for which the following is true:

� These market participants are not subject to transaction costs when they trade

35

Page 43: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Futures Documentation Chapter 4

� These market participants are subject to the same tax rate on all net trading profits

� The market participants can borrow money at the same risk-free rate of interest asthey can lend money

� The market participants take advantage of arbitrage opportunities as they occur

These assumptions are not so unreasonable since their exists the set of large investmentbanks which broadly speaking satisfy these requirements. In particular, investment bankswill often have in-house arbitrage trading desks or specialists covering all the markets inwhich they have significant customer flow. Hence since these investment banks will takeadvantage of these arbitrage opportunities almost as soon as they arise means that inpractice arbitrage opportunities disappear almost as soon as they arise. An implicationof these assumptions is therefore that market prices are such that there is no arbitrageopportunities.

4.4.2 Futures and Forwards on Stocks, Bonds and Indexes

We provide the following methods for the evaluation of future contracts on stocks andbonds:

� futurePriceNoIncome - this method returns the value of a futures contract on anunderlying asset which does not pay an income

� futurePriceWithIncome - evaluates the futures price today on an asset which pays aknown income during the life of the contract. This could be a futures contract on abond or dividend paying stock.

� futuresPricesWithDividend - evaluates the future price today on an asset which hasa continuous yield.

� shortForward (longForward) - evaluates the value of an short (respectively long)forward contracts residual value

� futureOnIndex - returns the price today of a futures contract on an index

� futureOnCurrencies - returns the price today of a futures contract on currencies

� gearing - we also include a method which calculates the effective gearing of a futuresposition

� costOfCarry - we calculate the cost of carry for an investment asset

Because an exchange traded futures contract is marked to market on a daily basis it cannotaccrue a residual value.

Within an environment of constant interest rates the value of a futures contract and thevalue of a forward contract are the same. When interest rates are allowed to vary as happenin the real world these to contract will generally have different values.

36

Page 44: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Futures Documentation Chapter 4

4.5 Futures on Commodities

Futures on commodities have a number of different features. These features are related tothe fact that a holder of a futures contract of a commodity may not hold the contract forinvestment purposes. That is, certain individuals may wish to continue to hold a futurescontract (or the underlying commodity) even if there are arbitration opportunities. If thereis not a significantly large number of market participants who will arbitrate then arbitragearguments to evaluate these futures will produce misleading results.

With futures on commodities the settlement of the contract is generally in the under-lying physical asset and hence the seller of a futures should hold the physical commodityin order to be certain that they can settle the contract at expiry. Hence storage costs ofthe underlying commodity, and its availability will effect the futures prices.

We consider commodities which are held primarily for investment purposes for examplegold and commodities which are held mainly because of these consumption value for exam-ple oil. We assume that for commodities of investment type that a section of the holders(for example investment banks) of the futures contracts and underlying assets will alwaysarbitrage if the opportunity arises. We also assume that these investors have the followingproperties:

� These market participants are not subject to transaction costs when they trade

� These market participants are subject to the same tax rate on all net trading profits

� The market participants can borrow money at the same risk-free rate of interest asthey can lend money

We refer to commodities which do not satisfy these conditions as consumption commodi-ties. Though large investment banks still operate within these markets it may not bepossible to short the underlying assets and go long on a futures contract. This is becauseholders of the underlying commodity hold the asset for reasons of consumption and may bereluctant to sell the commodity and buy futures contracts because futures contracts cannotbe consumed. Alternatively, if an investment bank holds the underlying commodity theycan always sell this asset and buy futures contracts.

We will also use the two related notions of convenience yield and cost of carry. Theconvenience yield measures to markets implied benefit from holding the physical commod-ity. The convenience yield can be viewed as the yield over the risk free interest rate whichthe market is prepared of pay for the convenience of holding the physical commodity. Thecost of carry measures the storage cost plus the interest that is paid to finance the assetless the income earned on the asset.

We provide methods which return a value of a futures contract on an investment com-modity and give an inequality which the price of a future on a consumption commodity

37

Page 45: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Futures Documentation Chapter 4

must satisfy. We also provide methods for the calculation of the cost of carry and conve-nience yield for investments and consumption commodities. Further, for an consumptioncommodity we offer methods which relate the cost of carry and the convenience yield.

Remark With most commodity markets the notion of the spot price does not reallyexist because the delivery of the physical commodity always takes some time, usually anumber of weeks. Hence within our methods what we are really doing is deriving relation-ships between two futures prices. In particular, within our methods I refer to the rathervague notion of “commodity price” rather than the spot price of the commodity so thatno confusion arises and we do not give a force impression of the way in which commoditymarkets work.

38

Page 46: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 5

Exotic Options Documentation

5.1 Introduction

Within this chapter we discuss firstly the definition of various exotic options and then showhow one can go about pricing and analyzing such option contracts. We cover American,Bermuda, Asian, Loopback and multi-asset options using Finite Differencing and Monte-Carlo techniques.

5.2 Types of Option Contract

An option is a contract between two parties in which one party buys the option contractwhich the other party creates (also known as writing an option contract). The option itselfis the right to obtain a pay-off as defined within the option contract at a single or rangeof future dates.

Example: The first and simplest type of options introduced is known as a European(Vanilla) Option which gives the holder the (optional) right to trade (either buy or sell)an asset at an agreed future time at an agreed price (known as the exercise price or strikeprice). The issuer of the European Option has the obligation to take the other side of thetrade (to the holder of the option) on the asset at the agreed price, when the holder decidesto exercise the option.

Options are traded on exchanges and regulated OTC markets throughout the world. Todate option contracts have been written on stocks, stock indices, currencies, debt instru-ments, commodities, futures contracts and even options on options.

5.2.1 Contracts with different Payoff Functions

Within this subsection we give three examples of types of option contracts which differonly in there payoff function.

39

Page 47: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

Vanilla or European Options

The payoff function on a Vanilla option is given by:

� Vanilla call option payoff: max(asset price at expiry − strike price, 0)

� Vanilla put option payoff: max(strike price− asset price at expiry, 0)

Binary or digital Options

An increasingly important type of option is the binary or digital options. These contractshave a payoff that is discontinuous in the underlying asset price.

Option strategies

Standard combinations are option contracts are traded, and are known as option strategies.Commonly used strategies include:

� Spread is an option strategy consisting of a long position and a short position.

� Bull spread is a spread where the long position has a smaller strike price than theshort position. It benefits from a rising (bull) market.

� Bear spread is a spread where the long position has a greater strike price than theshort position. It benefits from a falling (bear) market.

� Strangle is an option strategy consisting of one call and one put option.

� Straddle is a special kind of strangle, where the strike prices for the call and the putare equal.

5.2.2 Weak Path Dependence and American Options

As mentioned before an option contract can have the property that it can only be exercisedon a given date or a range of dates. Option which can only be exercised on a given dateare known as European whereas options which can be exercised on a range of dates areknown as American options. American options allow the holder the option of choosingto exercise the options early before the final expiry date.

American type options will depend on the path of the underlying asset and this dependencyis known as weak. This refers to the fact that the partial differential equation derived fromthe Black-Scholes model has the same independent variables as the corresponding Euro-pean contract. That is, there are no more variables which depend on the path taken bythe underlying asset.

40

Page 48: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

5.2.3 Strong Path Dependence - Asian and Lookback Options

Strongly path dependent options such as Asian and Loopback options have a payoff functionwhich explicitly uses a new path dependent variable. For example the payoff in the caseof Asian options is the dependent on the average of the underlying asset over a certainperiod. In this cases the following new path dependent variable will be introduced:

I =1

T

∫ T

0

Sdτ (5.2.1)

where T is the time to expiry and τ is the time from inception. And the payoff functionwill take the following form:

payoff = P (S, I) (5.2.2)

where P is some function of the underlying asset price S and the introduced variable I.

Options with a payoff dependent on the average of the asset price are called Asian op-tions. Options where the payoff function is dependent on the maximum or minimumreached by the underlying asset price are called Lookback options.

Remark A characteristic of strongly path dependent options is that the partial dif-ferential equations resulting from the Black-Scholes model can only be solved with theintroduction of a new independent variable corresponding to a path dependent value.

5.2.4 Time dependence - Bermudan options

Another variation of an option contract is when the payoff of the contract can vary withtime. A typical example of such an option is a Bermudan option. A Bermuda optioncontract permits early exercise (as in American options) but it restricts this possibility tocertain dates or certain periods.

Such options are strongly path dependent and there payoff function will take the followingform:

payoff = P (S, I, t) (5.2.3)

where P is some function of the underlying asset price S, I is the introduced variabledepending on the path of the asset (see prior subsection) and t is the time.

5.3 The Black-Scholes Model

The payoff function is the value of the option at expiry whereas we require to know theoption value now, that is, the value before expiry. Clearly any option pricing model willneed to make assumptions concerning the future evolution of the price. The Black-Scholesmodel assumes that price evolve in accordance with the following Brownian motion knowas a lognormal random walk:

dS = µSdt + σSdX (5.3.4)

41

Page 49: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

where dS is the ‘infinitesimal’ change in the underlying assets price, µ is the known as thedrift of the asset, dt is the time variation, σ is the volatility of the underlying asset anddX is a random variable drawn from a Normal distribution with mean zero and variance dt.

Simply knowing that the price has a lognormal evolution is not sufficient in being ableto value option contracts. In order to be able to achieve this we need to introduce afurther assumption which allow us to assign a fair value to any option contract (at leastin principle). This principle is known as the ‘principle of no arbitrage’ and said thefollowing:

In the absence of arbitrage opportunities (which is assumed to be the casewithin efficient markets), the return from a risk free portfolio must be the riskfree interest rate.

5.4 General Methods of Pricing Options in the Black-

Scholes World

5.4.1 The Black-Scholes Equation

If we assume the validity of the two principles:

� lognormal evolution

� no arbitrage

then it follows that the price evolution must obey the following partial differential equation(PDE):

∂V

∂t+

1

2σ2S2∂2V

∂S2+ rS

∂V

∂S− rV = 0, (5.4.5)

where σ is the volatility, r is the risk-free interest rate and S is the asset price.

The linear parabolic PDE (5.4.5) is known as the Black-Scholes Equation and is the basisfrom which we will price option contracts. To price an option contract involves finding thesolution of this equation for some given initial conditions.

Remark The unknown within the equation is not a value, but a function: V (S, t) whichstands for the value of the option at a time t, with the current asset price being S.

The Black-Scholes equation knows nothing about what kind of option we are valuing,whether it is a call or a put, American or Asian, nor what strike price is. These pointsare dealt with by the following final condition which with boundary conditions (see below)will ensures that we have one and only one solution to the corresponding Black-Scholesequations:

42

Page 50: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

We must specify the option value V as a function of the underlying at theexpiry date: final(S) = V (S, 0).

This function is of course the payoff function which as mentioned above is the one thingwhich specifies many different types of option contracts.

5.4.2 Boundary and initial / final conditions

Knowing the Black-Scholes equation and the payoff function is generally not enough infor-mation to determine the price of an option contract. In order to select the unique pricingfunction we must prescribe boundary conditions and an initial or final condition of theBlack-Scholes Equation.

The boundary conditions which are required in order to select the pricing function usingthe Black-Scholes Equations will naturally be the functions which describe the (expected)behavior of the pricing function. The only problem is to select boundary conditions of thepricing function which are sufficient to uniquely determine the pricing function and yetones which we are confident will not select the ‘wrong’ function from the solution set.

Using Extreme Values to provide boundary conditions

The asset values at which the pricing function is estimated from which we are able toprovide boundary conditions are usually ‘extreme values’ with respect to the option con-tract. That is, the pricing function is estimated when the underlying asset price is eithersignificantly above the strike price (for a call option this is referred to as being deep inthe money) or is significantly below the strike price (for a call option this is referred to asbeing deep out of the money).

At ‘extreme values’ the pricing function will either be approximately zero in the caseof deep out of the money, or approximately the difference between the price and the strikecompounded at the risk free rate until maturity in the case of deep in the money. Since inthe case of deep out of the money the option is very unlikely to be exercised whereas deepin the money options are very unlikely to expiry worthless.

In particular, within financial applications it is usually possible to specify the behaviorof the pricing function (or solution) at S = 0 and as S → ∞. We must also describe theinitial conditions (i.e. when t = 0) that is the price for which the equation evolves. Ifthe final condition is required then the payoff function at expiry for differing values of theunderlying asset can be evaluated. By specifying these boundary conditions we will insurethat the Black-Scholes equation yield a unique solution which will be the pricing function.

5.4.3 Methods of solving Black-Scholes PDE

We now have a well posed PDE problem for which there exists a unique solution. Theproblem now is to find this solution.

43

Page 51: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

The Black-Scholes PDE is a parabolic partial differential equation (also referred to asequations of heat or diffusion type). Though there exist approaches which attempt to solvethe Black-Scholes equations analytically, such as1:

� Transformation to Constant Coefficient Diffusion Equation

� Use of Green’s Functions

� Series Solution

� Fourier Transform

� Laplace Transform

For most option contracts the resulting Black-Scholes equation does not exhibit an analyticsolution. In these cases you are forced to use numerical techniques in order to find thepricing function.

The two most widely used and successful numerical approaches to finding solutions of theBlack-Scholes equations are Finite Differencing and Monte-Carlo techniques which wedescribe in the following sections.

5.5 Finite Differencing

The finite difference algorithm essentially relies on a discretization of the continuous PDE.The difference equations resulted from this process are used to generate a mesh or a gridwhich contains the discrete version of the solution. You are then able to interpolate the(discrete) solution at the grid nodes in order to find a solution over the whole region.

5.5.1 Single-Asset Options

The Explicit Algorithm

When there is only one asset involved, the Black-Scholes PDE has exactly the form pre-sented in the section above. This can be immediately translated into a finite differenceequation:

V n+1j − V n

j

∆t+ rj∆S

V n+1j+1 − V n+1

j−1

2∆S+

1

2σ2j2∆S2

V n+1j+1 − 2V n+1

j + V n+1j−1

∆S2= rV n+1

j (5.5.6)

where ∆t is the time step, ∆S is the asset price step and where V αβ ’s denote the function

values at points of the grid, where the superscripts indices α = n, n + 1, denotes the cor-responding time axis value and the subscripts β = j − 1, j, j + 1, denote the grid point onthe asset price axis.

1A detailed presentation of these methods can be found in Cranck, JC: Mathematics of Diffusion,Oxford, 1989; or Carslaw, HS & Jaeger, JC: Conduction of Heat in Solids, Oxford, 1989

44

Page 52: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

Remark The grid in this case is bidimensional. Where one axis represents the timeand the other axis represents the underlying asset price.

We still have the final condition which we can use since we already know V time stepsj for

all 1 ≤ j ≤ asset price steps. From the equation we can immediately find the value ofV time steps−1

j for all 2 ≤ j ≤ asset price steps−1, the values V time steps−11 and V time steps−1

asset price steps

being known from the boundary conditions. In the same manner we can compute the valuesfor time step− 2, then for time step− 3 and so on, until the whole grid is evaluated.

General stability issues

The problem with the explicit algorithm approach is that it tends to amplify errors, that isit tends to be unstable. Very small and unavoidable errors caused by the limited precisionof the floating point format can become exponentially larger in subsequent iterations andcompletely compromise the results.

It can be deduced that in order to endure the stability of the explicit algorithm, thefollowing relationship between the time step and the asset price step must hold:

∆t ≤ ∆S2

2a(5.5.7)

where a is some constant.

Moreover, this relationship is tight meaning that if this inequality is not satisfied thenthe algorithm is unstable. A consequence of this relationship is that if we want to im-prove the accuracy by halving the asset step size within the grid, then we must reduce thetime step by a factor of four. Resulting in the computation time required to complete thecomputation being increased by a factor of eight. The improvement in accuracy we wouldget from such a reduction in step sizes is a factor of four since the explicit finite-differencemethod is accurate to O(∆t, ∆S2).

Remark There is also a lower bound for the asset price step, but this usually doesnot make much difference in practice unless the volatility is very small.

To conclude, the explicit algorithm is unstable if the value of ∆t is too large in relationwith the value of ∆S, and if ∆S itself is too small.

Fully implicit

The implicit algorithm which we will cover in this section solves the problem of stabilitywhich effected the explicit algorithm above. The fully implicit algorithm, uses the followingdifference equation (equivalent with the first in the sense that they both can be used to

45

Page 53: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

represent the Black-Scholes PDE):

V n+1j − V n

j

∆t+ rj∆S

V nj+1 − V n

j−1

2∆S+

1

2σ2j2∆S2

V nj+1 − 2V n

j + V nj−1

∆S2= rV n

j (5.5.8)

using the notation defined above.

Unlike the explicit case, the solution here is not so straightforward. We cannot simplysolve one equation at each iteration, starting from the final condition to complete the grid.Here we must solve a full set of asset price steps equations, which can be computationallyintensive. But the implicit algorithm also has the advantage that it is unconditionallystable. This allows us the apply the algorithm without any restriction on the time step.For example, the asset price step can be small and the time step large without the methodrunning into stability problems.

Cranck-Nicholson

The main advantage of the explicit method (see above) is that it’s fast, but it also hasthe disadvantage that it can be unstable. In the case of the implicit method (see abovesection), its main advantage is that it is stable, but with the drawback that is can beslow. The Crank-Nicholson method is a hybrid of these two approaches and actuallymanages to combine the speed of the explicit method whilst keep the stability of theimplicit algorithm. In fact, the Cranck-Nicholson algorithm is stable and yet it is alsofaster than the fully implicit method. Key extra ingredient is in the way it takes the finitedifference approximation of the partial derivatives: which can be viewed as the averagebetween the explicit approximation and the implicit one. The finite difference equation forCranck-Nicholson is given by:

V n+1j −V n

j

∆t+ 1

2rj∆S

V n+1j+1 −V n+1

j−1

2∆S+ 1

2rj∆S

V nj+1−V n

j−1

2∆S+

+12σ2j2∆S2 V n+1

j+1 −2V n+1j +V n+1

j−1

∆S2 + 12σ2j2∆S2 V n

j+1−2V nj +V n

j−1

∆S2 = rV n+1j

(5.5.9)

using the notation defined above.

Which results in the Cranck-Nicholson method having an accuracy of O(∆t2, ∆S2). Forfurther details concerning the Crank-Nicholson method we refer the interested reader to:

Cranck, J. & Nicholson, P.: A practical method for numerical evaluationof solutions of partial differential equations of the heat conduction type. Pro-ceedings of the Cambridge Philosophical Society 43 50-67, 1947.

5.5.2 Multi-Asset Options

If the option contract involves more than one asset, then the original single asset Black-Scholes theory is modified with the use of concept of correlated lognormal random walks :

dSi = µiSidt + σiSidX (5.5.10)

46

Page 54: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

where Si is the price of the i-th asset, 1 ≤ i ≤ n assets, µi and σi are the drift and volatilityof that asset respectively and dXi is a random number drawn from a Normal distributionwith mean 0 and variance dt. From the definition of the Normal distribution we knownthat:

E[dXi] = 0 and E[dX2i ] = dt (5.5.11)

where E is the expectation. An extra parameter (which is in fact a matrix) in the multi-asset case is the correlation matrix between the underlying assets which the option dependson.

Correlation Matrix

The correlation matrix can be constructed from the set of pairs of historical times seriesof the underlying assets. This can be expressed by stating that the random numbers dXi

and dXj are correlated. Hence:

E[dXidXj] = ρijdt (5.5.12)

where ρij is the correlation coefficient between the i-th and the j-th random walks. Thesymmetric matrix defined by the entries ρij, which represent the entry in the i-th row andj-th column is called the correlation matrix.

Black-Scholes Equation for Multi-asset options

In this case the Black-Scholes equation for multi-asset options is give by:

∂V

∂t+

1

2

n assets∑i=1

n assets∑j=1

σiσjρijSiSj∂2V

∂Si∂Sj

+n assets∑

i=1

(r −Di)Si∂V

∂Si

− rV = 0 (5.5.13)

How these equations are solved?

The numerical algorithm used to solve such an equation is a generalization of the explicitmethod presented above. The difference is that now the grid is not bidimensional butmultidimensional. So the storage space required and the computational power neededgrows correspondingly. In practice the multidimensional finite-difference algorithm cannotbe used for more than three assets. In cases with more than three assets you shoulduse instead Monte-Carlo methods which are much faster when the number of assets (i.e.dimensions) is higher than three.

5.5.3 Modifications for American Options

Finding the price of an American option, that is an option which allows early expiry, viathe Black-Scholes equations is an example of what is known as a free boundary problem.With free boundary problems we are required to solve partial differential equations wherethe value of the solution at the boundary is not fixed by a boundary condition.

47

Page 55: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

With American options price evaluation we can assume that both the options value andits delta (∂V

∂S) are continuous with respect to the payoff function, this is the called smooth

pasting principle2. Since the smooth pasting condition is satisfied whatever pricing mech-anisms of American Option we use, it must be satisfied by the finite-differencing approach.Therefore, when applying finite differencing techniques to American options we modify theformula that generates the next line of the pricing grid in the explicit algorithm so thatit guarantees the solution will be continuous with respect to the payoff and moreover thatthe continuous delta constraint will also be satisfied and so on...

Note: American options should only be priced using finite-difference methods, sinceMonte-Carlo techniques are inappropriate for this type of option.

5.5.4 Modifications for Strongly Path Dependent Options

Since an asset’s path cannot be continuously measured, resulting option contracts whichare strongly path dependent only require measurement of path dependent quantities atdiscrete time intervals. In particular, there is a minimum time step between sampling ofpath dependent quantities such as the price.

After each time step, the path dependent value must be updated to reflect the changesin the state of the asset’s price path. The path dependent quantity is updated at eachsampling date ti and takes the value Ii for ti ≤ t ≤ ti+1, where:

Ii = F (S(ti, Ii−1, i)) (5.5.14)

This updating rule can be generalized as the new value of I, is determined by only theold value of I, the value of the underlying at the sampling date and the date itself. If weconsider for example Asian options using an arithmetic average, the updating formula willbecome:

Ii =1

iS(ti) +

i− 1

iIi−1 (5.5.15)

For max-type lookback options the updating formula will be:

Ii = max(S(ti), Ii−1) (5.5.16)

As we said in the definition of strongly path dependent options, the option value V (S, I, t);is now a function of three variables:

V (S, I, t) (5.5.17)

where S is the value in the underlying asset, I is the value of path dependent variable andt is the time.

2This principle states that the value of an American Option is maximized by an exercise strategy thatmakes the option pricing function and and its derivative with respect to the price (i.e. the option delta)continuous.

48

Page 56: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

Remarks

1. The stochastic differential equation for I is degenerate (i.e. dI = 0) at t 6= ti forany i, because it is only updated on the discrete set of dates ti. Therefore, providedwe are not on a sampling date, the quantity I is constant and the pricing equationis simply the basic Black-Scholes equation. Though the pricing function V (S, I, t),is still a function of three variables, the I variable can be effectively treated as aparameter.

2. Since the options value across a sampling date is continuous we impose at each ti,the following condition:

V (S, Ii−1, t−i ) = V (S, Ii, t

+i ) (5.5.18)

where the left hand side of the expression represents the limit of V (S, Ii−1, t), ast approaches ti, from below; and the right hand side of the expression representsthe limit of V (S, Ii, t), as t approaches ti, from above. This condition is known asthe jump condition, and roughly saids that V cannot have discontinuities in the ‘t’direction at the grid points.

5.6 Monte Carlo

The Monte Carlo technique can be effectively and easily applied to model a large rangeof derivative contracts. The generality and easy of use results from the fact that in orderto specuify a given contract we are only require to supply the contracts payoff. Therfore,we are able applied this technique to standard exotic options contracts is means that thisapproach certainly applies

readily carries over to exotic and path dependent option contracts (e.g. Asian, Americanand Loopback Options). The Monte Carlo method applied to the pricing of an optioncontract will need to make the following steps:

� Simulate the random walk and the corresponding cash flows

� Estimate the average payoff and calculate its present value

5.6.1 Random walks

The fair value of an option in the Black-Scholes world is the present value of the expectedpayoff at expiry under a risk-neutral random walk of the underlying asset.

dS = rSdt + σSdX (5.6.19)

where r is the drift rate, S is the stock price, t is a time variable, σ is the volatility and Xis the random variable with respect to the standard normal distribution.

We can therefore write:

OptionValue = exp(−r(T − t))E[payoff(S)] (5.6.20)

49

Page 57: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

where r is the drift rate (as before), T is the time to expiry of the option, t is the presenttime, E is the expectation with respect to the risk-neutral random walk of a given payoff(i.e. payoff(S)) being achieved at the expiry of the option contract.

Hence, we can estimate the value of an option contract by the following steps:

1. Simulate the risk-neutral random walk as discussed below, starting at today’s valueof the asset S0, over the required time horizon. This time period starts today andcontinues until the expiry of the option. This gives one realization of the underlyingprice path.

2. For this realization calculate the option payoff.

3. Perform many more such realizations over the time horizon.

4. Calculate the average payoff over all realizations.

5. Take the present value of this average which gives the option value.

The initial part of the algorithm requires first of all the generation of random numbersfrom a standardized Normal distribution. This will be discussed in the next section. Thenone has to update the asset price at each time step using these random increments.

For the lognormal random walk we have the following simple and exact time-steppingalgorithm. We write down the risk-neutral stochastic differential equation for S in theform:

d (logS) =

(r − 1

2σ2

)dt + σdX (5.6.21)

When by integrating this equation we find:

S(t) = S(0) exp

((r − 1

2σ2

)t + σ

∫ t

0

dX

)(5.6.22)

So over the time step δt, we have:

S(t + δt) = S(t) + δS = S(0) exp

((r − 1

2σ2

)δt + σ

√δtφ

)(5.6.23)

The critical issue in this approach in that we can approximate cases where the optionspayoff function depends on the historical price of the underlying asset and possibly otherparameters. This is because in such cases for a small δt, the above ‘equality’ approximatelyholds and so we can split the time interval in to small periods and generate estimates ofthe options contract price.

In the case when the option only depends on the data at expiry then the payoff func-tion will not depend on the time and other variables and the above expression will hold forall δt. In such cases we can simulate the final asset price in one giant leap to expiry, usingthe time step T . European options are such an instance and if we apply the Monte Carlomethod then we will obtain estimates which will converge to the corresponding value givenby the Black-Scholes formulae as the number of approximations is increased.

50

Page 58: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

5.6.2 Generating normal variables

Most programming languages (including Java and C#) incorporate routines for samplingrandom numbers between zero and one. An approximate sample from a univariate stan-dardized normal distribution φ(0, 1), can be obtained using the formula:

ε =12∑i=1

Ri − 6 (5.6.24)

where the Ri are independent random numbers between zero and one where ε is the requiredsample from φ(0, 1). This approximation is satisfactory for most purposes since it has amean of zero, a standard deviation of one, and a third moment of zero.

5.6.3 Options on many underlying assets: Higher dimensions

Monte Carlo is a natural method for the pricing of European-style contracts that dependon many underlying assets. Supposing that we have an option with a payoff functionwhich depends on the prices of several underlying assets S1, S2, . . . , Sd. Instead of usingthe Black-Scholes methods which require us to solve a PDE in d+1 variables we could usethe simulation methods provided by Monte Carlo procedures. In order to use Monte Carloall we need to do is simulate:

Si(t + δt) = Si(0) exp

((r − 1

2σ2

i

)δt + σi

√δtφi

)(5.6.25)

The catch is that the φi are correlated, that is:

E[φiφj] = ρij (5.6.26)

Generating correlated random variables

Let us suppose that we can generate d uncorrelated Normally distributed variables ε1, ε2,. . . ,εd. We can use these variables to get correlated variables with the transformation

φ = Mε (5.6.27)

where φ and ε are the column vectors with φi and εi in the i-th row. The matrix M isspecial and must satisfy:

MMT = Σ (5.6.28)

with Σ being the correlation matrix.

The decomposition of the correlation matrix into the product of two matrices is not unique.One solution is the Cholesky factorization which produces a matrix M that is lowertriangular.

51

Page 59: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

5.6.4 Advantages of Monte Carlo simulations

The Monte Carlo technique is very powerful and general. All you need to do is to simulatethe random walk and the corresponding cash flows, estimate the average payoff and takeits present value.

However this method has also disadvantages. One of them is that it is slower compared withthe finite-differencing solution of a partial differential equation. Generally speaking this istrue for problems up to three or four dimensions. When there are four or more stochasticor path dependent variables the Monte Carlo method becomes relatively more efficient. An-other disadvantage is that it is time consuming to apply this method to American options.

Because Monte Carlo simulation is based on the generation of a finite number of real-izations using series of random numbers, the value of an option derived in this way willvary each time the simulations are run. If the standard deviation in the option using asingle simulation is ε then the standard deviation of the error after N simulations is ε/

√N .

In other words to improve the accuracy by a factor of 10 we must perform 100 times asmany simulations.

5.7 Sources of Error

All numerical algorithms including the ones used here (i.e. Monte-Carlo, Finite Differenc-ing, Binomial Trees) produce by definition an approximation of the real “correct” result.In practice, we are forced to apply a numerical procedure to a class of problems where theaccuracy of the procedure used within this class will vary from case to case. Therefore,when we speak about the accuracy of an algorithm, we are actually talking about theconfidence level that we can have in an algorithm when it is applied to a class of prob-lems. For example, we could say that for a given amount of computational resources weare more confident in the accuracy of the pricing of Asian options carried out with theFinite-Differencing approach than when Monte Carlo is applied.

More precisely, when we refer to the accuracy of an algorithm it should be understoodin the following sense:

Two algorithms have the same accuracy if, having the parameters adjustedso that they run at equal speeds, produce results characterized by the sameuncertainty interval.

Thus an algorithm is characterized by the degree of confidence (or certainty) in the ap-proximations produced. That is, it can be characterized by the degree of confidence wehave in its accuracy. The accuracy which an algorithm may have can vary from very high(for example, when we apply analytical formulae), to very low (for example, for unstablefinite differencing algorithms).

The error within an algorithm is said to be controllable if we are able to eliminate (or

52

Page 60: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

at least minimize) the error of an algorithm by carefully adjusting this parameters. Inmost instances errors are controllable, so the algorithms parameters can be adjusted inorder to produce better results.

In some cases, the interval of uncertainty for a given confidence level can be explicitlyestimated for a large class of problems (for example Monte Carlo pricing of option con-tracts). But in other cases the uncertainty interval could depend on either the parameterused or the particular problem considered (for example, in the case the finite differencingthe accuracy of the result will depend on the payoff function, or equivalently the particularoption contract considered).

Remark In many cases the speed of an algorithm is directly related to the accuracyof the algorithm. Within the Monte-Carlo and Finite Differencing as applied to optionstheory if the error of the algorithm is controllable then the accuracy of the algorithm isequivalent to the speed of the algorithm.

In the subsections below we describe in order of importance several factors related to ourimplementation of options pricing algorithms3 which can produce errors in the analysis ofderivative securities.

5.7.1 Errors determined by algorithm instability

An algorithm is said to be unstable if it amplifies any other error source, for examplefloating point errors. Iterative algorithms are the most susceptible to instability as verysmall errors can grow at an exponential rate.

Finite Differencing

In Finite Differencing algorithms this error appears when the time step is too large relativeto the price step. Instability errors are usually easily detectable as they tend to be verylarge, compared with other sources of errors. Each algorithm has its own threshold whereit becomes unstable, in the case of finite differencing this is the ratio between time andprice step. The explicit finite differencing algorithm is the most vulnerable to instability.The fully-implicit algorithm is much more robust but is not as accurate. Cranck-Nicholsonis a compromise between robustness and accuracy.

Monte Carlo and Analytic Formulae

The best general algorithm when we refer to stability is, by far, Monte Carlo which isalso the slowest. Even better is the analytical derivative pricing as applied opt the evalu-ation of European Vanilla options.

3There also exists a number of errors which can result from general computing issues such as roundingerrors.

53

Page 61: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

Remark Within the application of Finite Differencing and Monte Carlo to options theoryit is almost always possible to eliminate instability by increasing the number of time steps.

5.7.2 Monte Carlo errors due to number of simulations used

Ideally in Monte Carlo you should perform an arbitrarily large number of simulations.Which we result in a confidence interval which is arbitrarily small. For a finite numberof simulation the confidence level will have a definite positive size. Moreover, the confi-dence level generally will be larger than the correspond confidence interval for the finitedifferencing and analytic formulae. And hence the Monte Carlo procedure is slower (orless accurate) than either finite differencing or analytic formulae.

A significant advantage of the Monte Carlo procedure is that is does admit an explicit esti-mate of the error, or equivalently the confidence interval. For a confidence level 0 ≤ c ≤ 1,the confidence interval is:

µ− erf(c)ω√N

< x < µ− erf(c)ω√N

(5.7.29)

where,

� µ - is the average of all simulation results, or the returned value of the algorithm

� ω - is the standard deviation of the simulation results

� N - is the number of simulations

� erf - the error function

See the Monte Carlo section for further detail concerning the Monte Carlo procedure.

5.7.3 Finite Differencing errors due to wrong boundary condi-tions

In order to use finite differencing techniques to price derivative contracts you must setappropriate boundary conditions. As below in the section on boundary conditions withinfinite differencing, first you should try the general boundary condition, implemented bythe SecondOrderBoundaries class. Even if this works for a large class of contracts, thereis no guarantee that it will work in every situation. In fact, it always introduces a certainerror in the final result.

Usually this error is small but there are circumstances when it can be significant. Youcan identify such an error by comparing the result of a finite differencing method withMonte Carlo (which does not require any boundary conditions, therefore is not affected bysuch an error).

54

Page 62: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

The only way of eliminating such errors is by implementing the correct Dirichlet-typeboundary conditions for the specific option contract you are pricing.

Remark In most cases boundary errors grow when the maturity time increases, so theycan be spotted more easily by using contract with a long time until expiry, for example 5or 10 years.

5.7.4 Finite Differencing errors due to the size of the price step

Solving a PDE numerically will always mean that some approximations will be used. Inparticular, the partial derivative of a function will be replaced by an approximation of it,using differences computed over the grid considered. Ideally the number of points withinthis grid should be arbitrarily large, or equivalently the grid should be arbitrarily dense. Inreality though only a small number of points can be used due to computational restrictions.Again, comparison with Monte-Carlo can aid in identifying such errors.

Identify the step size error

In practice it can be quite difficult to discern between step size errors and errors resultingfrom the choice of boundary conditions. One difference between the two is that in manycases the former causes a shift of the prices for all maturities in one direction (while theboundary error is larger when the time to maturity increase). Hence, the algorithm willtend to underprice or overprice a given contract, no matter what maturity is used.

Controlling the Step size error

Fortunately the step size error is controllable. It can be minimized by increasing thenumber of points used to tabulate the price axis. If this number is too high comparedto the number of time steps, the algorithms can become unstable. In particular, as thenumber of price steps increase the various implementations of the finite differencing willbecame unstable in the following order: explicit, Crank-Nicholson, fully implicit. There-fore, you may have to increase the number of time steps in order to maintain an algorithmsstability.

5.7.5 Errors due to the size of the time step

This error is unlikely to generate a significant error in comparison to the stability errorswhen the finite differencing algorithms are applied. In the case of Monte Carlo which isvery robust and hence in most cases stable, this error can have a significant influence.Saying this, such an error if it where to occur can be minimized by increasing the numberof timesteps.

55

Page 63: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

5.8 Greeks of Exotic Options

Recall that the Greeks describe the rate of change of an option’s price with respect tovarious market variables. The Greeks can also be thought of as corresponding to variouscoefficients of the Taylor expansion of the price function with regard to the various marketvariables which it depends on. In short, the Greeks measure the sensitivity of an option(or portfolio of options) to various market variables in the following ways:

� Delta (∆) - The rate of change of the option price to changes in the underlying assetprice.

� Theta (Θ) - The rate of change of the option price to changes in the time remaininguntil the expiry of the option.

� Gamma (Γ) - The rate of change of the option delta, or equivalently the rate ofchange of the rate of change of the option price.

� Vega - The rate of change of the option price to changes in the volatility. Naturally,Vega will be measured with respect to the measure used within the option modelunder consideration.

� Rho - The rate of change of the option price to changes in the interest rates, inparticular the risk free interest rate.

The definition of the Greeks in the case of Vanilla Options which where treated earlier andExotic Options is identical. The differences lie in the way in which the Greeks in thesetwo cases can be evaluated. In the case of Vanilla options via the Black-Scholes modelwe are able to derive analytic formulae for the price function and the Greeks (i.e. thederivative of the price function). In the case of Exotic options since the Black-Scholesmodel does not exhibit an analytic solution we are forced to use numerical procedures inorder to estimate the price function and its corresponding derivatives (a.k.a. the Greeks).Within the previous sections to have discussed how the price function in accordance withthe Black-Scholes model may be evaluated at a given point using one of the followinggeneric approaches:

� Finite Differencing Techniques

� Monte-Carlo

Each of these pricing mechanisms can be used to estimate the Greeks of an Exotic Op-tion and the correspond values given for the Greeks may naturally differ. In the followingsections we detail how we may estimate the value of the Greeks using these pricing mech-anisms.

56

Page 64: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

5.8.1 Finding Greeks of Exotic Options using Monte-Carlo

Evaluating one of the Greeks (excluding Gamma) is the equivalent to evaluating the deriva-tive of the price function which respect to one of its variables. In the case of the Delta thisvariable is the underlying asset price, for vega the variable is the volatility and so on... Inorder to evaluate a given Greek which depends on the rate of change with respect to thevariable η (say), at a given point in time t = T , we evaluate the price function:

f(T, η, . . .),

using Monte-Carlo approximation at the point t = T , η = η(T ), where . . . corresponds tothe other variables. We also evaluate the price function at the same point in time but wherethe η variable has been perturbed. That is, we set η = η(T )+, where ε is a small positivenumber of modulus δη, and evaluate the function f(T, η + ε, . . .), using the Monte-Carloapproach. Then ‘the Greek’ with represents the rate of change with respect to the variableη, can be estimate by:

f(T, η(T ), . . .)− f(T, η(T ) + ε, . . .)

δη

Remarks

� If in the above procedure η, is taken to be the underlying asset price then we willevaluate the Delta of the option, if η is taken to be the volatility then we will evaluateVega, and so on...

� In order to minimize standard errors the number of trials used for the evaluation ofthe price function and its perturbation should be the same.

Evaluating the Gamma using Monte-Carlo

In order to evaluate the Gamma of an option using Monte-Carlo, you will need to evaluatethe Delta using the above procedure at the evaluation point (i.e. ∆(T, α(T ), . . .)), and foranother point where the underlying asset’s price has been perturbed (i.e. ∆(T, α(T )+ε, . . .).Then Gamma at the point (T, α(T ), . . .), is given by:

∆(T, α(T ), . . .)− f(T, α(T ) + ε, . . .)

δx

where δx is the modulus of the perturbation ε.

5.9 Employee Options

Within the Tree module we offer the pricing of employee options in accordance with theEnhanced FASB 123 model. That is, we provide a binomial and trinomial trees basedpricing engine for the evaluation of employee options in accordance with the EnhancedFASB 123 model as detailed within the paper, ’How to value Employee Stock Options’, byJohn Hull and Alan White (September 2002). This fair-based approach is in accordance

57

Page 65: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

with the advice laid out within the publication, ’Accounting for Stock Based Compensa-tion’ (October 1995), which first details the FASB 123 model. For a formal statementon the FASB 123 Accounting Standard we refer the reader to Summary of StatementNo. 123 (revised 2004), Financial Accounting Standards Board which is available athttp://www.fasb.org/st/summary/stsum123r.shtml.

5.9.1 Details and Assumptions of the Enhanced FASB 123 Model

Employee stock options are issued to employees of a company of the stock of that company.Therefore, these options can be viewed as a component of renumeration and hence it isbecoming increasing accepted that these options should be reflected on a companies in-come statement. However, due to the special features of these options (as described below)standard pricing models as applied to traded products cannot be applied in this case. Herewe provide a custom binomial and trinomial trees pricing engine based as suggested withinthe article of Hull and White which presents a theoretically sound approach to the pricingof such options.

The FASB 123 model takes into account the following special features of an employeeStock Option:

� Non-traded: The employee option cannot be traded and moreover can only beexercised during the period of employment.

� Vesting Period: Often the option will stipulate a period before which it can beexercise. If the employee leaves the company before the end of the vesting periodthen the options for forfeited. If the employee leaves after the vesting period thenthe option are exercised if they are in the money, otherwise they are forfeited.

� Dilution: When the option are exercised they are settled with shares held in Trea-sury, hence new shares are issued and dilution of the share capital takes place.

The Enhanced FASB 123 model dealt with differs from the basic FASB 123 model inthat:

� Employee Exit Rate: Explicitly includes to possibility that the employee leave thecompany during or after the vesting period. This allows the company to use actualemployee turnover rates with the pricing model.

� Early Exercise Policy: Allows the employee in incorporate an pre-determinedpolicy towards to early exercise of the options. That is, it allows the employee tospecify the level as a multiple of the exercise price which the underlying stock mustreach when the employee will exercise the option.

5.9.2 Brenchmark Results

Here we compare the results which can be found using our implementation of the Hull/Whitemodel (2004) with the results which can be those found using John Hull’s implementation

58

Page 66: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

which can be downloaded from http://www.rotman.utoronto.ca/ hull/esops/. The sourcecode for these examples are provided as a QA example which can be found within the/client directory of the installation directory.

Key for the Results Table

� pr. = Stock Price

� ex. = Execise Price

� life = Total Life

� time = Time to Vest

� pre = Employee Exit Rate pre-vesting

� post = Employee Exit Rate post-vesting

� multi = Exercise Multiple

� vol = Expected Volatility

� rate = Risk-free rate

� yield = Dividend yield

� WC Bin = WebCab Binomial model results

� WC Tri = WebCab Trinomial model results

Selection of Benchmark Results

In the following table we provide the results from four examples corresponding to each ofthe four rows. Within each row we define an Employee Option pricing problem and providethe results of the Employee Option Evaluation in accordance with the FASB 123 modelusing our Binomial and Trinomial implementations and the implementation of John Hull.

pr. ex. life time pre post multi vol rate yield WC Bin WC Tri Hull50 50 10 5 5% 5% 1.0 30% 7.5% 2.5% 12.35 12.27 12.2350 50 10 3 6% 6% 1.0 20% 7.5% 2.5% 8.116 8.0597 8.0312 12 4 2 4% 4% 1.9 35% 10% 12% 1.9675 1.9603 1.9614 15 15 10 6% 6% 2 20% 8% 3% 2.6981 2.654 2.65

Conclusions: As you can see from the table above the results using our implementationare almost exactly the same as the results which are returned by John Hull’s implementa-tion.

59

Page 67: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

5.10 Scenario Analysis

Scenario analysis allows for an asset (or portfolio of assets) to be stressed and for the result-ing behavior to be analyzed. Such analysis is necessary within a Greek/VaR based marketrisk methodology to capture the risks due to outsized market moves. Though the standardGreek/VAR4 methodology is adequate for the majority of market dynamics it generallywill fail to reflect market risks due to shocks such as major geopolitical elements or marketcrashes. Examples of outsized market moves include the October 1987 stock market crashor the swings in the Treasury bond market in 1998 after the Russian government effectivelydefaulted on its national debt.

Applications to Risk Management and Trading

The major reason why the Greek/VaR methodology is insufficient lies in the fact thatit under estimates the probability of outsized market moves. In theory such major out-sized moves (for example of 3 standard deviation move in one day) will occur a few timesevery thousand years but in practice such outsized market moves have been observed totake place every ten years or so. That is, the historical distribution of assets prices has“fatter” tails than the tail implied from the normal distribution of asset prices which isone of the assumptions in the Black-Scholes model.

Though Scenario Analysis forms an important ingredient within most risk frameworksit is also a useful trading tool. Whether you wish to flatten out the exposure of a portfolioor take directional positions with particular characteristics a scenario grid representationwill quickly communicate the directional exposure of the portfolio with respect to the mar-ket variables being considered. Moreover, if you wish to analyze the particular risk/rewardprofile of a particular trade before entering the position you can carrying out ScenarioTesting on a number of scenario which you anticipate occurring. It this way you will knowa prior the profit and loss implications of various differing scenario playing out. In thisway you are will be able to construct an optimal trading approach according from yourinterpretation of the possible scenarios and there estimated probabilities.

What we will cover

Within this section we will consider the following two approaches to Scenario Analysis:

� Scenario Grid - The Profit/Loss of a portfolio after various shifts of two marketvariables from there present values. This gives a complete picture of the implicationsin terms of valuation (and hence profit and loss) of various market scenarios takingplace.

4The Value at Risk (or VaR) is a framework for producing a global risk parameter of a portfolio ofassets. In particular, the n-day m% VaR of a portfolio of assets is the maximum expected lose with m% ofconfidence over a period of n days. The 5-day 95% VaR is the greatest loss expected over a 5-day periodwhen the worst 5% of cases are excluded.

60

Page 68: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

� Scenario Testing - The Profit or Loss resulting from the a one off shift of all themarket variables. Using this type of analysis you can analyze the effect on a portfolioif it underwent a similar major market shift to one which occurred in the past.

Remarks

� The VaR measure only captures information concerning the 99% (or 95%) leastvolatile days (at least in terms of the profit and loss). Hence, the VaR metric does nottake into account the days which result in the most volatile portfolio value swings.

� The Greeks can be viewed as the leading coefficients of the Taylor expansion withrespect to the market variables (price, interest rates, volatility, time etc) of the pricingfunction of the underlying asset. For small shifts in the market variables the leadingterms of the Taylor expansion will offer a good approximation to the pricing functionitself shifted. But as the shifts become larger to lower order terms will become lessinsignificant and sum of the leading terms of the Taylor expansion (i.e. the Greeks)will diverge from the pricing function itself. On the other hand, scenario analysiscan cope equally well with large shifts in the underlying market variables since thepricing function (i.e. the entire Taylor expansion) is re-evaluated after the shift inthe market variables has taken place.

5.10.1 Scenario Grids

A Scenario Grid with respect to two market variables either displayed as a grid of numericalvalues, or as a surface plot representing the values of a portfolio (or the resulting profit orloss) after each (scenario) shift, offers a quick and effective means to assess the type anddegree of risk which a portfolio of assets is carrying.

Evaluation of the Absolute Scenario Grid

A scenario grid is a grid of numerical values, say with α × β elements where the (a, b)entry is defined to represent the market value of the portfolio evaluated with the referencemarket variables. This value in practice is usually taken to be today’s portfolio and marketvariables values.

Remark If we are considering the profit and loss resulting from various market movesthen the value at a reference point (a, b), will be zero.

The remaining points of the scenario grid are populated in the following fashion. Once thetwo market variables which are to be shifted and the degree to which each of these shiftswill be (including whether the shift is a percentage or an absolute value) is decided theremaining scenario grid members can be evaluated as follow. The (x, y) element which isp, shifts in the first variable and q, shifts in the second variable is given by:

price(x + qs, y + pf)

61

Page 69: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

where s (respectively f) are the number of shifts in the first (respectively second) marketvariable and price represents the re-evaluation of the portfolio after the shifts to the twomarket variables whilst keeping the other market variables fixed. That is, the scenariogrid will display the absolute value of the portfolio under various shifts of the two mar-ket variables with respect to a reference value associated with a reference market condition.

Example of Absolute Scenario Grid

Below we give an example of a absolute Scenario grid where the initial value of the port-folio is 256, 488, as stated in the grid element D4. The portfolio consider is made up ofassets which depend on the price of the precious metal gold. The top axis represents corre-sponding shifts of the volatility of the underlying asset gold and the axis on the right handside represent changes in the underlying price of gold. As you can see below the volatilityand market price is shifted between −2 and +2, and the corresponding value of the goldportfolio is evaluated and the grid point is populated.

Fig. The ‘Volatility vs Underlying’ Absolute Scenario Grid of the Gold Portfolio

Evaluation of Relative (or P/L Change) Scenario Grid

In the case of the relative (or P/L Change) scenario grid, where we consider the profitand loss implications of various market moves the scenario grid can be evaluated by justsubtracting the value of the reference market value from the other values associated withvarious shifts in the market variables. That is, in the notion used above the (x, y) elementwithin the relative (or P/L change) scenario grid is given by:

price(x + qs, y + pf)−R

where R is the reference market value of the portfolio being considered. In the goldportfolio example considered above the reference market value of 256, 488 (see grid elementD4 above).

5.10.2 Scenario Testing

Scenario Testing (also know as back testing) is another technique which allows the portfolioto be put under various stresses and to measure the implications in terms of the portfoliosprofit and loss. Scenario Testing is generally applied in two instances:

62

Page 70: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

� Trading Tool - Test a trading idea against various future scenarios.

� Risk Management (Back Testing) - Stress a portfolio according to past (extreme)market dynamics.

Mechanics of Scenario Testing

Whether you intend to use Scenario Testing as a trade or risk management tool to ba-sic mechanics of its use are the same. The general procedure is to re-evaluate an asset (orportfolio) under a shift of all the market variables which the asset (or portfolio) dependson. For an asset this will involve performing the following steps:

� Identify the market variables which an asset depends. Since the Scenario Analysisdepends on a pricing model this will involve going back to the pricing models beingused for the given asset and identifying the models market variables.

� Shift the market variables according to the market scenario which you wish to analyze.

� Re-evaluate the asset according to the shifted market variables using the same model.

In order to undertake Scenario Testing of a Portfolio, we should perform to following:

� Identify all the market variables which the Portfolio is exposed to. Will we involveidentifying the variables involved in the pricing models of the assets within the port-folio.

� Shift the market variables according to the market scenario which you wish to analyze.

� Re-evaluate the assets of the portfolio according to the shifted market variables.

By re-evaluating the asset (or portfolio) after a shift in the market variables has takenplace we can see the effect on the value of an asset (or portfolio) which a given supposedmarket dynamics will have on the assets (or portfolios) value.

Using Scenario Testing as a Trading Tool

Once a trading idea has been identified and the possible future scenarios classified, thevarious ways in which to express a trading idea can be analyzed against the various futurescenarios considered. By analyzing the possible scenarios against the original trading ideawill help in assessing where to put stops and how to adjust the trading strategy as thetrade evolves.

For example, say you take a directional position on the underlying asset price througha trading approach which hedges most of the volatility and interest rate risk at the pointwhen the trade is entered. Further, you decide that you ideally do not wish to be exposedto excessive interest rate or volatility risk. Now, one of the envisaged scenarios plays outand from your a prior analysis you know that your exposure to volatility will grow larger

63

Page 71: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Exotic Options Documentation Chapter 5

than you feel happy with. At this point you hedge the volatility according to a pre-decidedstrategy, which you analyzed apriori within your original scenario analysis before enteringthe trade. Hence, through Scenario Testing you are able to build a robust trading approachwhich can manage the plan the whole trade life cycle under various scenarios.

Using Scenario (or Back) Testing within a Risk Management Framework

The application of Scenario (or Back) Testing within a VaR/Greek risk methodology isparticularly important since extreme market moves (i.e. the worst 1of 99stock marketcrash of October 1987, taken place significantly more often than would be expected fromthe lognormal distribution of asset prices.

Scenario Testing within a risk management framework involves the following steps:

� Observe the market variables which a given portfolio being considered is exposed to.

� Record the historical market events for which the moves in the market variableswhich the portfolio under consideration is exposed to where particularly large.

� Re-evaluate the portfolio as if the extreme market variable shifts which occurred inthe past happened to the present value of the market variables.

By performing the above procedure the effect that an extreme historical market movewould have on the considered portfolio if that market move would re-occur. In this wayyou can ascertain to what degree a given portfolio is “hedged” against extreme marketmoves. Since in times of market turmoil liquidity often dries up, and hence the hedging ofrisk during extreme market moves is usually impossible.

64

Page 72: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 6

Programmer’s Guide for Microsoftr

Office

This chapter describes the steps to take in order to integrate WebCab Options and Futures withmost Office documents, such as Excel worksheets, and Access documents. The integration isachieved both through VBA (Visual Basic for Application) code and features specific to theOffice Application you are using to write your documents. The information in this chapterapplies equally to Microsoft Office 2000, XP, and 2003 Applications and documents.

6.1 Developing with VBA from Office

This section describes how to write a VBA client for a business class documented in theAPI Reference for this product. The steps below are the same across all Microsoft OfficeApplications (Word, Excel, Access etc.) and involve using the Visual Basic Editor andwriting several lines of code:

1. Open the Visual Basic Editor

2. Add a Code Module

3. Declare a Subroutine

4. Add a Reference to This Product

5. Declare a Class Instance Variable

6. Create a Class Instance

7. Call a Class Method

8. Display the Method Result

9. Run the Subroutine

65

Page 73: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.1: Starting the Visual Basic Editor in Excel

6.1.1 Open the Visual Basic Editor

In order to add VBA code to your Office document, you will first need to open the VisualBasic Editor, by going to the Tools | Macro | Visual Basic Editor menu, as shown in figure6.1.

6.1.2 Add a Code Module

In the upper-left corner of the Visual Basic Editor window, you can find all Office objectsassociated with your document. Right click any of the objects and select Insert | Module,as shown in Fig. 6.2 in order to add a new VBA module to your project. A code windowwill appear, where you will be writing the code that will enable you to use this product’sfunctionality.

6.1.3 Declare a Subroutine

The first step in writing the code, which makes use of the functionality provided by thisproduct is to declare a subroutine, which can then be run directly from your Office Appli-cation. To declare a subroutine, use the Sub and End Sub keywords and the name you wishto assign to this subroutine. For example, in order to declare a subroutine named run, youwould write the code displayed in Fig. 6.3.

66

Page 74: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.2: Adding a module to a VBAProject

Fig. 6.3: Declaring a subroutine named run in VBA

6.1.4 Add a Reference to This Product

Adding a reference to this product is required only once for every Office document that usesfunctionality provided by this product. This step will enable VBA code auto-completionfor all business clases and methods that belong to this product, saving you time typingand browsing the API Reference. Also, it will speed up all calls to this product’s methods,increasing the overall performance of your project.

67

Page 75: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.4: Opening the “References” window in the Visual Basic Editor for Office

Fig. 6.5: Selecting a reference to a WebCab product, here ‘Functions’

To add a reference to this product, go to the Tools | References... menu as shown inFig. 6.4 in order to open the “References” dialog window. Scroll down and select theentry named WebCab Options and Futures Demo from the list of available references inthe dialog window and then click OK. Figure 6.5 shows how to add a reference to WebCabFunctions Demo.

68

Page 76: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.6: Creating a new instance of a class named “Interpolation”

6.1.5 Declare a Class Instance Variable

The API Reference for this product describes all business classes, their methods and prop-erties, and offers advice on how to use each of them. You can browse the API Referencefrom the Start Menu at Programs | WebCab Components | Options and Futures for .NET| COM | API Reference. In order to call methods of a business class listed in the APIReference, you need to declare a variable to hold a reference to its instance.

Write a Dim statement to declare a variable of the same type as the business class that youwish to make calls to. For example, if you wish to call methods belonging to a businessclass named “Interpolation” and declare a variable of this type named instance, you wouldwrite the following:

Dim instance As Interpolation

6.1.6 Create a Class Instance

In order to create an instance of a business class listed in the API Reference, you will haveto write code that connects to its corresponding COM server1.

Use the Set keyword in order to assign the class instance to the variable you have de-clared in the previous step. The Set keyword is required in class instance assignments,as omitting this keyword would result in a run-time error. The reference assigned to thisinstance is created by writing the New keyword, followed by the name of the same businessclass you used to declare the variable.

1“COM server” is a generic term used to describe a COM interface, which provides functionality to VBand VBA applications.

69

Page 77: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

For example, assume you wish to create an instance of a business class named Interpola-tion, which is located in the WebCab Functions for .NET product. Figure 6.6 shows howto create an instance of this class and how to assign it to the instance variable declaredin the step above.

6.1.7 Call a Class Method

In order to call a method belonging to a business class for which you have created aninstance, you can use the name of the method as listed in the API Reference and appendit to the name of the variable that holds the class instance, separating it with a period.For example, in order to call a method named MyMethod, you could write the followingline of code:

result = instance.MyMethod (parameter-values)

where parameter-values are the ordered values of the parameters separated by a comma.The actual type of these parameters and that of the results variable depends on the signa-ture (i.e. the return type and parameter types) of the MyMethod method.

Remark For a more detailed Visual Basic example of how to invoke a method, seesection 6.1.10.

6.1.8 Display the Method Result

To see what the result of the method call was, you can display it inside a window by callingthe MsgBox function, as shown below:

MsgBox "The result of the method call was " & result

This line of code will display a small dialog window containing the result of the methodcall.

6.1.9 Run the Subroutine

After having finished writing the subroutine code as described in the steps below, you canrun the subroutine. There are several ways to run a subroutine, two of which are describedbelow:

1. Type F5 in the Visual Basic EditorYou can run your subroutine by placing the editing cursor within its body (i.e.between the Sub and End Sub keywords) and pressing the F5 key. This will instantlyexecute the subroutine, bringing up the result window.

70

Page 78: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.7: Opening the “Macro” window from the menu in Excel.

2. Run the Soubroutine as a MacroYou can run the subroutine even after having closed the Visual Basic Editor, directlyfrom the Office Application you are using. Go to the Tools | Macro | Macros... menu,as shown in Fig. 6.7 to open the “Macro” dialog window. Select the macro, whichhas the same name as your subroutine and click Run (see Fig. 6.8).

71

Page 79: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.8: Running a subroutine macro named run from Office.

72

Page 80: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

' Declaring a subroutine named `run'Sub run()

Dim instance As Interpolation' Creating an new `Interpolation' instanceSet instance = New Interpolation

' Declaring the first parameter (a double array)Dim x(0 To 4) As Doublex(0) = 1x(1) = 2x(2) = 3x(3) = 4x(4) = 5

' Declaring the second parameter (a double array)Dim y(0 To 4) As Doubley(0) = 3y(1) = 2.4y(2) = 1.7y(3) = 1.4y(4) = 0.7

' Declaring the variable to hold the method resultDim result As Double

' Calling the `CubicSplinePointwise' method. All other' parameter values are being written here. The result' is stored in the `result' variable.result = instance.CubicSplinePointwise(x, y, -0.6, -0.7, 1.2)

' Printing the result inside a dialog windowMsgBox "The result of the method call was " & result

End Sub

Table 6.1: Generic Office VBA Example

6.1.10 A Generic VBA Example for Office

In this section we provide the complete VBA source code for a subroutine named run,which makes a call to a method in a business class and prints the result of the method callinside a window. The same steps mentioned above are being followed in this example.

The code in table 6.1 calls a method named CubicSplinePointwise, belonging to the Interpo-lation business class in the WebCab Functions product. This method takes five parameters,of which the first two are one-dimensional arrays and the last three are double values. The

73

Page 81: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

method returns a double value.

6.2 Integrating with Microsoft Excel

This section is dedicated exclusively to Microsoft Excel users, who wish to tightly andseamlessly integrate the functionality provided by this product directly into Excel. At theend of this section, you will have learned how to create your own user-defined functions,which you can call directly from your worksheets as formulas or from the Insert | Function...menu. The following steps describe completely how to achieve integration of this product’sfunctionality within Excel:

1. Open the Visual Basic Editor

2. Add a Code Module

3. Declare a Function

4. Add a Reference to This Product

5. Declare a Class Instance Variable

6. Create a Class Instance

7. Call a Class Method

8. Store the Method Result as a Function Return Value

9. Insert the Function in your Worksheet

6.2.1 Open the Visual Basic Editor

First you will need to open the Visual Basic Editor, by going to the Tools | Macro | VisualBasic Editor menu, as shown in figure 6.1. The Visual Basic Editor will allow you to writethe necessary VBA code that uses the functionality provide by this product.

6.2.2 Add a Code Module

In the upper-left corner of the Visual Basic Editor window, you can find all Microsoft Excelobjects associated with your workbook. Right click any of the objects and select Insert |Module, as shown in Fig. 6.2 in order to add a new VBA module to the existing VisualBasic project. A code window will appear, where you will be writing the code that willenable you to use this product’s functionality.

74

Page 82: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.9: Declaring a function named “MyFunction” in VBA

6.2.3 Declare a Function

In the source code window, declare a function using the Function and End Function key-words. You can pick any name you wish for this function, as you will be able to call itdirectly from a worksheet, like a regular Excel formula. You can change the name of thefunction at any later time, by simply editing the function declaration. Figure 6.9 showshow to declare a function named MyFunction.

6.2.4 Add a Reference to This Product

As described in section 6.1.4, in order to add a reference to this product, you will need togo to the Tools | References... menu as shown in Fig. 6.4. This will open the “References”dialog window. Scroll down and select the entry named WebCab Options and FuturesDemo from the list of available references in the dialog window and then click OK. Figure6.5 shows how to add a reference to WebCab Functions Demo.

6.2.5 Declare a Class Instance Variable

The API Reference for this product details all business classes, their methods and proper-ties, and gives advice on how to use each of them. You can browse the API Reference fromthe Start Menu at Programs | WebCab Components | Options and Futures for .NET | COM| API Reference. In order to call methods of a business class listed in the API Reference,you need to create a variable to hold a reference to its instance.

Write a Dim statement to declare a variable of the same type as the business class that youwish to make calls to. For example, if you wish to call methods belonging to a businessclass named “Interpolation” and declare a variable of this type named instance, you wouldwrite the following:

75

Page 83: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Dim instance As Interpolation

6.2.6 Create a Class Instance

Use the Set keyword in order to assign the class instance to the variable you have declaredin the previous step. The Set keyword is required in class instance assignments, as omittingthis keyword would result in a run-time error. The reference assigned to this instance iscreated by writing the New keyword, followed by the name of the same business class youused to declare the variable.

For example, the Interpolation business class inside the WebCab.COM.Math.Interpolationnamespace has the following full name: WebCab.COM.Math.Interpolation.Interpolation.In order to create an instance of this class and assign it to the variable we have declaredin the previous step, we would write the following VBA code:

Set instance = New Interpolation

6.2.7 Call a Class Method

In order to call a method belonging to a business class for which you have created aninstance, you can use the name of the method as listed in the API Reference and appendit to the name of the variable that holds the class instance, separating it with a period.For example, in order to call a method named MyMethod, you would write the followingline of code:

instance.MyMethod (parameter-values)

where parameter-values are the ordered values of the parameters separated by a comma.The actual type of these parameters and that of the results variable depends on the signa-ture (i.e. the return type and parameter types) of the MyMethod method.

Remark For a more detailed Visual Basic example of how to invoke a method, seethe next section, 6.2.8.

6.2.8 Store the Method Result as a Function Return Value

The result of the method call must be stored as the method’s return value, by assigningthe method’s result to the the the name of the function itself, as shown below:

MyFunction = instance.MyMethod (parameter-values)

76

Page 84: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

' Declaring a function named `MyFunction'Function MyFunction()

Dim instance As Interpolation' Creating an instance of the `Interpolation' business classSet instance = New Interpolation

' Declaring the first parameter (a double array)Dim x(0 To 4) As Doublex(0) = 1x(1) = 2x(2) = 3x(3) = 4x(4) = 5

' Declaring the second parameter (a double array)Dim y(0 To 4) As Doubley(0) = 3y(1) = 2.4y(2) = 1.7y(3) = 1.4y(4) = 0.7

' Calling the `CubicSplinePointwise' method. All other' parameter values are being written here. The result' is stored as a return value for this function.MyFunction = instance.CubicSplinePointwise(x, y, -0.6, -0.7, 1.2)

End Function

Table 6.2: The VBA code for a user-defined function in Excel

The complete source code of a function named MyFunction is shown in table 6.2. Theexample calls the same method as the generic VBA example in section 6.1.10.

6.2.9 Insert the Function in your Worksheet

Switch back to the worksheet window and open the “Insert Function” window from theInsert | Function... menu (see Fig. 6.10). From the dialog window, click the drop-down listthat lists all the categories, and select the category named “User Defined”, as shown infigure 6.11.

The name of your function will appear in the list of user-defined functions. Select itand click the OK button (Fig. 6.12). A window named “Function Arguments” will appear,asking for values for the arguments. In case your function takes no arguments, as in ourexample above, simply click OK, as shown in figure 6.13.

77

Page 85: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.10: How to open the “Insert Function” window in Excel

Fig. 6.11: Selecting the “User Defined” category

The current cell value will contain the value of a formula, which calls the “MyFunction”function with no parameters. The result of the formula, listed in the fx formula bar, willbe printed inside the cell, as shown in figure 6.14. You can change the formula directlyfrom the formula bar, or by opening again the “Insert Function” window.

You can also add a reference to the formula directly from the worksheet, by typing thevalue of the formula directly into the cell, without opening the “Insert Function” window,

78

Page 86: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

Fig. 6.12: Selecting the “MyFunction” user-defined function

Fig. 6.13: Inserting the “MyFunction” user-defined function into the worksheet

Fig. 6.14: The value returned by the “MyFunction” formula in an Excel worksheet

79

Page 87: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Microsoft Office Chapter 6

the same way you would call a standard Excel formula.

80

Page 88: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 7

Programmer’s Guide for VisualStudio 6

This chapter is dedicated to Visual Studio 6 developers, programming with either or both of theVisual Basic 6 and Visual C++ 6 languages. Using WebCab Options and Futures from theselanguages comes down to connecting to a COM server and making calls to it. The first sectionis for Visual Basic 6 developers, while the second section is for Visual C++ 6 developers.

7.1 Developing with Visual Basic 6

This section describes the steps required to use this product from VB6. These steps arealways the same, irrespective of the type of project you are developing. In an example atthe end of this section, we also provide a generic Visual Basic example of how to connectto our components from a “Standard EXE” Project.

Assuming you have already started a new project or opened an existing project, hereare the steps required to connect and use a WebCab Options and Futures COM server:

1. Add a Reference to This Product

2. Declare a Class Instance Variable

3. Create a Class Instance

4. Call a Class Method

7.1.1 Add a Reference to This Product

Adding a reference to this product is required only once for every VB Project that usesfunctionality provided by this product. This step will enable VB code auto-completion forall business clases and methods that belong to this product, saving you time typing andbrowsing the API Reference. Also, it will speed up all calls to this product’s methods,increasing the overall performance of your project.

81

Page 89: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.1: Opening the “References” window in Visual Basic 6

To add a reference to this product, go to the Project | References... menu as shown inFig. 7.1 in order to open the “References” dialog window. Scroll down and select theentry named WebCab Options and Futures Demo from the list of available references inthe dialog window and then click OK. Figure 7.2 shows how to add a reference to WebCabFunctions Demo.

7.1.2 Declare a Class Instance Variable

The API Reference for this product details all business classes, their methods and proper-ties, and gives advice on how to use each of them. You can browse the API Reference fromthe Start Menu at Programs | WebCab Components | Options and Futures for .NET | COM| API Reference. In order to call methods of a business class listed in the API Reference,you need to create a variable to hold a reference to its instance.

Write a Dim statement to declare a variable of the same type as the business class that youwish to make calls to. For example, if you wish to call methods belonging to a businessclass named “Interpolation” and declare a variable of this type named instance, you wouldwrite the following:

Dim instance As Interpolation

To avoid name clashing with other classes that may be named the same as the businessclass you are instantiating, you can prefix the name of the business class with the name

82

Page 90: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.2: Selecting a reference to a WebCab product, here WebCab Functions

VB6 assigns to the COM reference to this product. Assuming the name of this referenceis WebCab_COM_FunctionsDemo, the complete business class name would be referenced asfollows:

Dim instance As WebCab_COM_FunctionsDemo.Interpolation

7.1.3 Create a Class Instance

In order to create an instance of a business class listed in the API Reference, you will haveto write code that connects to its corresponding COM server. Use the Set keyword in orderto assign the class instance to the variable you have declared in the previous step. The Set

keyword is required in class instance assignments, as omitting this keyword would resultin a run-time error. The reference assigned to this instance is created by writing the New

keyword, followed by the name of the same business class you used to declare the variable.

For example, assume you wish to create an instance of a business class named Inter-polation, which is located in the WebCab Functions for .NET product. The following lineof code will create an instance of this class and assign it to the instance variable declaredin the step above:

83

Page 91: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Set instance = New Interpolation

To avoid name clashing with other classes that may be named the same as the busi-ness class you are instantiating, you would use the complete name of the business class, asshown below:

Set instance = New WebCab_COM_FunctionsDemo.Interpolation

7.1.4 Call a Class Method

In order to call a method belonging to a business class for which you have created aninstance, you can use the name of the method as listed in the API Reference and appendit to the name of the variable that holds the class instance, the same way you would calla method or property in Visual Basic. For example, in order to call a method namedMyMethod, you could write the following line of code:

result = instance.MyMethod (parameter-values)

where parameter-values are the ordered values of the parameters separated by a comma.The actual type of these parameters and that of the results variable depends on the signa-ture (i.e. the return type and parameter types) of the MyMethod method.

Remark For a more detailed Visual Basic example of how to invoke a method see thefollowing section, 7.2.

7.2 Illustrating Visual Basic Examples

Within this section we provide a number of source code examples which demonstrate how touse our Options product inside a Visual Basic 6 application. These examples will illustratehow to use a variety of methods from different classes within the Options product whichtake a variety of parameter and return types.

Examples Provided

In particular we provide source code examples for the following methods:

� CallDelta(double, double, double, double, date, date, Enumeration) from within Eu-ropeanDelta class.

� HistoricalEstimateWithDividends(double[], double[]) from within Volatility class.

84

Page 92: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Aim of Examples

The aim of these examples is to provide practical hands-on instruction as to exactly whatyou are required to input in order to use our Options product inside a Visual Basic project.Each example will invoke a method from a business class and return the result within amessage box. These examples will cover the full range of parameter and return typeswhich you may encounter within the application of this component. Therefore, by re-usingthese template code examples you should be able to construct clients which use any of themethods from within this component.

For a detailed description of the nature of each one of the methods within the Optionsproduct please consult our API documentation at: WebCab Options API Documentation

Structure of each Example

Each of these source code examples have the same structure and perform the followingsteps:

Start Visual Basic Project - Within our examples we use a Form project in which weillustrate the method call.

Declaring an instance of the class - In order to use the methods from a given classyou must first create an instance of that class.

Initializing the instance of the class

Declaring the Parameters - Create the types which will be used within the methodcall.

Declaring the variable to hold the returned method result

Invoke the Method

Print the result within a message box Remark: We assume that the Optionscomponent has been registered and is available within the Visual Basic project. For furtherdetails on how this is performed please see the previous section.

Obtaining the Source code

We provide an implementation of this example with associated project files within thedirectory:

home/Libraries/Client/Optimization/VBExamples/FutureEvaluation

where home refers to the directory where the product is installed which will generallybe: C:/Program Files/WebCab Components/Option for .NET

This folder can also be access via the START menu by selecting: START > Programs >

WebCab Components > Option for .NET > .NET > Tools > Option > VBExamples Custom Example

85

Page 93: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Within this folder you will find the following files:

1. FutureEvaluation.frm - The Visual Basic source code file.

2. FutureEvaluation.vbp - The Visual Basic project file.

3. FutureEvaluation.vbw - The Visual Basic Project Workplace

In order to run this example you will need to:

1. Open VB Project file - Double click on the .vbp file which will open the projectwithin Visual Basic 6. We assume that you have Visual Basic 6 installed and thatVisual Basic project files (i.e. .vbs file) are associated with this IDE.

2. Add a WebCab Option Reference - Select from the VB6 menu Project >

Reference which will bring up the ’References’ dialog box. With the text area listplease select the item ’WebCab Option’ and then click ’OK’.

3. Run the example - After the Component has been registered you are able to runthe examples by pressing F5.

7.2.1 Calling the CallDelta method which takes and returns dou-bles

This example shows how to use the CallDelta method from the EuropeanDelta businessclass which takes four doubles, two data and one enumeration types as parameters andreturns a double.

To reuse this Visual Basic example contained within the table 7.2.1 just copy and pasteto code within any of your subroutines or functions. In our example, we placed the codeinside the Form_Load subroutine, which is been triggered at the time the Application Formis first executed.

Private Sub Form_Load()' Declaring an instance of class EuropeanDeltaDim instance As EuropeanDelta' Initializing the instance of the class EuropeanDeltaSet instance = New EuropeanDelta

' Declaring a variable of type double which will hold the asset priceDim stockPrice As DoublestockPrice = 250

86

Page 94: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

' Declare a variable of type double which will hold the value of' strikeDim strike As Doublestrike = 210' Declare a variable of type double which will hold the value of' risk free interest rateDim riskFreeRate As DoubleriskFreeRate = 0.04' Declare a variable of type double which will hold the value of' volatilityDim volatility As Doublevolatility = 0.1' Declare a variable of type Date which will hold the date when' the futures contract is evaluatedDim evaluationDate As DateevaluationDate = #9/5/1998#' Declare a variable of type Date which will hold the date when' the futures contract maturesDim maturityDate As DatematurityDate = #9/5/2002#' Declaring the variable to hold the method resultDim result As Double

' Calling the `CallDelta' method which calculates the delta of' an asset bearing investment over a given period when the asset' price, strike, risk free rate and volatility are knownresult = instance.CallDelta(stockPrice, strike, riskFreeRate, _volatility, evaluationDate, maturityDate, ''London'')

' Printing the result in a Message BoxMsgBox "The European delta is:" & result

End Sub

A specific Visual Basic client example using EuropeanDelta class.

7.2.2 Calling the HistoricalEstimateWithDividends method whichtakes two double arrays

This example shows how to use the HistoricalEstimateWithDividends method from theEuropeanDelta business class which takes four doubles, two date types and one enumera-tion type as parameters and returns a double.

To reuse this Visual Basic example contained within the table 7.2.2 just copy and pasteto code within any of your subroutines or functions. In our example, we placed the codeinside the Form_Load subroutine, which is been triggered at the time the Application Form

87

Page 95: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

is first executed.

Private Sub Form_Load()' Declaring an instance of Volatility classDim volatility As WebCab_COM_OptionsDemo.volatility' Initializing the instance of the class EuropeanDeltaSet volatility = New WebCab_COM_OptionsDemo.volatility

'Declaring a double array which will hold the prices of the asset'IMPORTANT NOTE: The double array index must start with 0Dim assetPrices(0 To 11) As DoubleassetPrices(0) = 23.4assetPrices(1) = 24.1assetPrices(2) = 24.5assetPrices(3) = 23.9assetPrices(4) = 24.5assetPrices(5) = 24.9assetPrices(6) = 25.0assetPrices(7) = 24.8assetPrices(8) = 25.1assetPrices(9) = 25.7assetPrices(10) = 26.0assetPrices(11) = 25.8

'Declaring a double array which will hold dividends of the assetDim dividends(0 To 11) As Doubledividends(0) = 1For i = 1 To 11 Step 1

dividends(i) = 0Next

'Declaring a variable which will hold the method result Dim resultAs Double

'Calling the `HistoricalEstimateWithDividends ' methodresult = volatility.HistoricalEstimateWithDividends(assetPrices,_

dividends)'Printing the result in a Message BoxMsgBox "The historical estimate is: " & result

End Sub

A specific Visual Basic client example using Volatility class.

88

Page 96: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

7.3 Developing with Visual C++ 6

Using this product from Visual C++ 6 involves two major steps: importing the TypeLibrary for this product and passing parameters to the COM methods according to COMstandards. All the other steps are rather straightforward and involve basic C++ codewriting:

The steps are as follows:

1. Open a New or Existing Project

2. Add All COM Specific ‘include’ Declarations

3. Import the Type Library for this Product

4. Call “CoInitialize”

5. Connect to a COM Server

6. Declare the Parameter Types and Values

7. Declare the Return Type

8. Call the Method

9. Call “CoUninitialize”

7.3.1 Open a New or Existing Project

You can start a new Visual C++ Project by going to the File | New... menu (see Fig. 7.3),which will bring up the “New” dialog window. From this window, choose the “Projects”tab and select the Win32 Console Application. Type in the name of your project in theProject name text box (for example, Project1) and click OK, as shown in Fig. 7.4.

In the next window, select “A simple application” (see Fig. 7.5), click the Finish but-ton, and click OK in the next window as well. From the left hand side of the screen, switchto “FileView” and select the .cpp file with the same name as your project – as seen in Fig.7.6. Note that the source code snippets in this section apply both to a new project and toone of your existing projects.

89

Page 97: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.3: Starting a new project

90

Page 98: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.4: Starting a Console Application named “Project1”

91

Page 99: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.5: Creating a simple Console Application

92

Page 100: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

Fig. 7.6: Location of the main C++ source code file, Project1.cpp

7.3.2 Add All COM Specific ‘include’ Declarations

COM specific calls will require that the header file objbase.h is included within your project.This header offers functionality to enable C++ to interoperate with COM servers. To in-clude this header file within your project you will need to add at the top of your mainsource code file the following line:

#include "objbase.h"

7.3.3 Call “CoInitialize”

In order to allow Visual C++ clients to connect to a COM server, you need to make a callto a function named CoInitialize, which belongs to the objbase.h header file, mentionedabove. The call to the function must be made as shown below:

CoInitialize(NULL);

93

Page 101: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

7.3.4 Import the Type Library for this Product

The name of all COM interfaces and their methods are described by a Type Library filewith a .tlb extension. These methods are automatically exposed to your Visual C++ 6client by the IDE, if you import this .tlb file into your project.

In order to import the Type Library for this product, add an #import declaration (rightafter the #include declarations in your main source code file) followed by the complete pathto the COM .tlb file, which is located in the COM Libraries subdirectory of the instalationpath for this product. The default installation path for users with Administrator privi-leges is C:\Program Files\WebCab Components\Options and Futures for .NET, while thedefault installation path for a user without Administrator privileges is C:\Documents andSettings\User-Name\Local Settings\Application Data\WebCab Components\Options andFutures for .NET.

If you add no_namespace at the end of the #import statement, the COM interfaces willbe placed within the default namespace, so you can access them directly without prefixingthem with the namespace name.

For example, if you installed with Administrator privileges, you can import the TypeLibrary for this product by writing the following statement:

#import "C:\Program Files\WebCab Components\Options and Futures for .NET\\COM Libraries\WebCab.COM.OptionsDemo.tlb" no_namespace

If you omit the no_namespace parameter, the COM methods will be exposed as part ofa namespace called WebCab_COM_OptionsDemo.

7.3.5 Connect to a COM Server

For every COM server described in the COM API Reference, the previous step defines atype with the same name prefixed by “COM_” and followed by “Ptr”. Declare a variable ofthis type and invoke its method named CreateInstance with the GUID of the COM serveritself as a parameter.

For example, in order to connect to the Interpolation COM server, part of the WebCabFunctions for .NET product, you would write the following C++ code:

COM_InterpolationPtr instance = NULLinstance.CreateInstance(__uuidof(Interpolation));

The variable named “instance” will hold the connection to the “Interpolation” COM server

94

Page 102: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

in all subsequent calls.

7.3.6 Declare the Parameter Types and Values

Passing non-array parameters to the COM methods is as straightforward as passing pa-rameters to a C++ method. You can declare a parameter to hold the value, pass the valuedirectly, or pass the result of another method call.

When it comes to passing one-dimensional or two-dimensional arrays as parameters toCOM methods, you will need to perform some additional COM specific steps. First of all,all COM arrays are typed as SAFEARRAY. The SAFEARRAY type holds a pointer to a standardC++ array, but has some extra fields that describe the type of the array, its number ofdimensions, and most importantly its lower and upper bounds. Handling arrays of thistype can be done fairly easy using standard SAFEARRAY manipulation functions, such asSafeArrayCreate, SafeArrayRedim, and SafeArrayDestroy.

You will need to pass either one-dimensional or two-dimensional safe arrays to any ofthe COM methods within this product. Here is how you can accomplish this from VisualC++ 6:

� Declaring a One-Dimensional Safe ArrayUse the SafeArrayCreateVector function to create a one-dimensional safe array,by passing the element type, the lower bound and the number of elements the arrayhas. The element type is one of the types declared by the VARENUM enumeration type.Of the most common types, you will be using the VT_R8 constant (corresponding tothe double type in the API Reference), VT_I4 (corresponding to the integer type),VT_DATE (the DateTime type), and VT_BOOL for boolean types.

After making the call to this function, you will need to copy the values referenced bya C++ one-dimensional array to the memory location referenced by the pvData fieldof the safe array structure. This C++ array must hold the values that you wish tosend across to the COM method as a parameter value.

For example, in order to create a one-dimensional array of 4 double elements, hereis how you could define the corresponding safe array and the underlying C++ one-dimensional array:

int noElements = 4;double pvData_myOneDimensionalArray[] = {1, 2, 3, 4};SAFEARRAY *psa_myOneDimensionalArray = SafeArrayCreateVector(

VT_R8, 0, noElements);memcpy(psa_myOneDimensionalArray->pvData,

pvData_myOneDimensionalArray, noElements * sizeof(double));

95

Page 103: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

� Declaring a Two-Dimensional Safe ArrayIn order to declare a two-dimensional array, you will first declare the correspond-ing C++ two-dimensional array. However, the C++ array needs to be transposed,such that the number of rows becomes the number of columns and vice-versa. Thisis due to the transposed memory layout of safe arrays, opposed to that of C++ arrays.

For example, if to declare an n by m safe array, you will need to declare an mby n C++ array, and lay the elements in this reversed order.

Also, you will need to make sure that the number of elements of all sub-arrays isthe same, because the two-dimensional safe array is a rectangular array, which as-sumes fixed number of elements on each dimension.

The safe array structure can be initialized using the SafeArrayCreate function,which takes the following parameters: the element type, the number of dimensions(two in our case), and the lower bound and number of elements on each dimension.The lower bound and number of elements is declared using a SAFEARRAYBOUND struc-ture, one for every dimension.

Assuming a two-dimensional array of 2 by 4 double elements, its corresponding safearray and C++ two-dimensional array must be 4 by 2 and its elements must be laidout as follows:

int noRows = 2;int noColumns = 4;double pvData_myTwoDimensionalArray[4][2] = {

{ 1, 5 },{ 2, 6 },{ 3, 7 },{ 4, 8 },

};

SAFEARRAYBOUND myTwoDimensionalArrayBounds[2];myTwoDimensionalArrayBounds[0].lLbound = 0;myTwoDimensionalArrayBounds[0].cElements = noRows;myTwoDimensionalArrayBounds[1].lLbound = 0;myTwoDimensionalArrayBounds[1].cElements = noColumns;

SAFEARRAY *psa_myTwoDimensionalArray = SafeArrayCreate(VT_R8, 2, myTwoDimensionalArrayBounds);

memcpy(psa_myTwoDimensionalArray->pvData,pvData_myTwoDimensionalArray, noRows * noColumns *

sizeof(double));

96

Page 104: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

The actual values in the safe array are { 1, 2, 3, 4 } on the first row, and { 5, 6,

7, 8 } on the second row.

Before sending a safe array to a COM method, you will also need to perform one last step– wrap it within a VARIANT type. The VARIANT structure is a generic type that can wraparound any other COM type. Define a variable of type VARIANT, and use its fields to specifythe type of the safe array and the reference to the safe array structure. To describe thetype of the safe array, use the VT_ARRAY constant and the constant corresponding to theelement type of the array.

For example, a variant corresponding to the two dimensional safe array declared abovewill look as follows:

VARIANT myTwoDimensionalArray;myTwoDimensionalArray.vt = VT_ARRAY | VT_R8;myTwoDimensionalArray.parray = psa_myTwoDimensionalArray;

A complete list of VARENUM constants corresponding to all COM types that might be re-quired by this product can be found at this MSDN link.

7.3.7 Declare the Return Type

COM methods that return arrays require special attention. Instead of declaring a C++array pointer, you will need to declare a pointer to a SAFEARRAY structure, and assign toit the result of the method call. Here is how you would declare a variable to hold a safearray returned by a COM method:

SAFEARRAY *arrayResult;

COM methods that return non-array types can be used like regular C++ methods, bydeclaring a variable of the corresponding type and assigning to it the result of the methodcall.

7.3.8 Call the Method

You can call a COM method by using the variable that holds the connection to the COMserver and the name of the method, as listed in the COM API Reference. For example,assuming you wish to call a method named ComMethod, which takes two double values forparameters and returns a third double value, here is how you could perform this call fromC++:

double result = instance->ComMethod (10, 20);

97

Page 105: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

SAFEARRAY *twoDimArray;// A fictive call is made to the COM methodtwoDimArray = instance->ComMethod (paramValue1, paramValue2 etc.);

// We read off the lower and upper bounds on each dimensionlong l1, u1, l2, u2;SafeArrayGetLBound(twoDimArray, 1, &l1);SafeArrayGetUBound(twoDimArray, 1, &u1);SafeArrayGetLBound(twoDimArray, 2, &l2);SafeArrayGetUBound(twoDimArray, 2, &u2);

// We read through all elements and print them to the screenlong indices[2]; // the indices for every dimensionfor (indices[0] = l1; indices[0] <= u1; indices[0]++) {

for (indices[1] = l2; indices[1] <= u2; indices[1]++) {double element;SafeArrayGetElement(twoDimArray, indices, &element);printf ("twoDimArray[%d,%d] = %lf", indices[0], indices[1],

element);}

}

Table 7.1: Handling a two-dimensional safe array in C++

Any other COM method calls can be made the same way, by using a different methodname, a different set of parameter values, and maybe a different return type.

Special care must be taken when processing the result of COM methods, which returna one or two-dimensional array. Since, as described above in section 7.3.7, the type of thevariable to hold the result is a pointer to a SAFEARRAY structure, you will need to use safearray specific methods, in order to inspect all element values, and reuse them in C++.

Table 7.1 gives an example of how to handle a two-dimensional array, covering most ofthe operations you are likely to perform in your C++ applications with safe arrays re-turned by COM methods.

7.3.9 Call “CoUninitialize”

In order to free generic COM related resources held by a C++ client, you must make acall to the CoUninitialize function. The call to this function can be made right before theend of your application or when your client no longer requires to use COM resources. Theline of code which releases all COM resources is:

98

Page 106: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

CoUninitialize();

7.3.10 A Generic Visual C++ Example

In this section we provide a generic Visual C++ example of a simple Console Application,which connects to one of our business classes, invokes one of its methods and prints the re-sult in a window. This source code example works with a new Win32 Console Application,which can be created as described in section 7.3.1. Since this example’s structure in notspecific to the method being invoked, you may adapt this example to whatever businessclass, product, and method you wish to call.

This C++ application calls a method named RelativeToAbsolute, belonging to the As-setParameters business class in the WebCab Portfolio for .NET product. This methodtakes one two-dimensional double array parameter and returns another two-dimensionaldouble array.

99

Page 107: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

// Project1.cpp, a Simple Win32 Console Application//

#include "stdafx.h"#include "objbase.h"#include "stdio.h"

// Adding a reference to the Portfolio COM Type Library#import "C:\Program Files\WebCab Components\Portfolio for .NET\\COM Libraries\WebCab.COM.PortfolioDemo.tlb" no_namespace

int main(int argc, char* argv[]){

CoInitialize(NULL); // Enable C++ to COM interoperability

/** Declare a variable to hold the connection to the* `AssetParameters' COM server and establish* the connection using its GUID.*/

COM_AssetParametersPtr instance = NULL;instance.CreateInstance(__uuidof(AssetParameters));

int noRows = 2;int noColumns = 4;// Reverse the dimensions for the C++ array, by declaring first// the number of columns and then the number of rows.double pvData_absoluteValues[4][2] = {

{ 100, 140 },{ 120, 135 },{ 125, 135 },{ 115, 140 },

};SAFEARRAYBOUND bounds[2];bounds[0].lLbound = 0;bounds[0].cElements = noRows;bounds[1].lLbound = 0;bounds[1].cElements = noColumns;SAFEARRAY *psa_absoluteValues = SafeArrayCreate(VT_R8, 2, bounds);memcpy(psa_absoluteValues->pvData,

pvData_absoluteValues, noRows * noColumns * sizeof(double);

Table 7.2: Generic VC++ example (continued on the next page)

100

Page 108: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Visual Studio 6 Chapter 7

VARIANT absoluteValues;absoluteValues.vt = VT_ARRAY | VT_R8;absoluteValues.parray = psa_absoluteValues;

// Call the `AbsoluteToRelative' COM methodSAFEARRAY *relativeValues;relativeValues = instance->AbsoluteToRelative(absoluteValues);

// Print the result inside a MessageBoxchar text[200] = "";long indices[2];long l1, u1, l2, u2;SafeArrayGetLBound(relativeValues, 1, &l1);SafeArrayGetUBound(relativeValues, 1, &u1);SafeArrayGetLBound(relativeValues, 2, &l2);SafeArrayGetUBound(relativeValues, 2, &u2);for (indices[0] = l1; indices[0] <= u1; indices[0]++) {

sprintf (text, "%s{ ", text);for (indices[1] = l2; indices[1] <= u2; indices[1]++) {

double element;SafeArrayGetElement(relativeValues, indices, &element);sprintf (text, "%s%lf ", text, element);

}sprintf (text, "%s}\n", text);

}

MessageBox(NULL, text, "The Relative Values", MB_OK);

CoUninitialize(); // Free all COM specific resourcesreturn 0;

}

Table 7.3: Generic VC++ example (continued)

101

Page 109: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 8

Programmer’s Guide for BorlandC++ Builder

This chapter contains information concerning the use of this Component product from Borland’sC++ Builder product lines; include Borland C++ 2005, Borland C++BuilderX and BorlandC++Builder; on the Windows development platform. The principles and code examples pro-vided here can be applied verbatim in order to use this component with the C++ languageon the Windows development platform. Though the use of the different IDE products lineswill differ slightly, the same Windows client code can be used verbatim within any of the C++Builder product lines.

8.1 Developing with Borland C++ Builder

In order to connect and make calls to our COM servers from Borland C++ Builder, youwill need to write late-binding code.

The steps are as follows:

1. Open a New or Existing Project

2. Add all COM Specific ‘Include’ Declarations

3. Call “CoInitialize”

4. Create a Class Instance

5. Obtain a Method ID

6. Declare the Parameter Values and Types

7. Declare the Return Type

8. Call the Method

9. Call “CoUninitialize”

102

Page 110: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

Fig. 8.1: Starting a new project

8.1.1 Open a New or Existing Project

You can start a new Borland C++ Builder Project by going to the File | New... menu (seeFig. 8.1), which will bring up the “Object Gallery” dialog window. From this window,choose the “Project” left-hand item, select the New Console project and click OK, as shownin Fig. 8.2.

Type in the name of your project in the next dialog window and click Next (see fig. 8.3). Inthe next window (figure 8.4) simply click Next, and in the last window, select the checkboxnext to the untitled entry and click the Finish button, as shown in figure 8.5.

103

Page 111: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

Fig. 8.2: Starting a Console Application

Fig. 8.3: Choosing a name for a new Borland C++ Console Application

104

Page 112: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

Fig. 8.4: Selecting platforms and tools sets for a new Borland C++ Console Application

8.1.2 Add all COM Specific ‘Include’ Declarations

COM specific calls will require that the header file objbase.h is included within your project.This header offers functionality to enable C++ to interoperate with COM servers. To in-clude this header file within your project you will need to add at the top of your mainsource code file the following line:

#include "objbase.h"

8.1.3 Call “CoInitialize”

In order to allow Borland C++ Builder clients to connect to a COM server, you need tomake a call to a function named CoInitialize, which belongs to the objbase.h header file,mentioned above. The call to the function must be made as shown below:

CoInitialize(NULL);

105

Page 113: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

Fig. 8.5: Specifying the project files for a new Borland C++ Console Application

8.1.4 Create a Class Instance

In order to create an instance of a WebCab Options and Futures business class, you willneed to provide the full name (i.e. the ProgId) of the business class, as declared withinthe API Reference. The full name of a business class contains the namespace, followed bya period and the name of the class itself.

The C++ code below returns an instance of the Interpolation business class, located insideWebCab Functions for .NET. Its namespace is WebCab.COM.Math.Interpolation, meaningits full name is WebCab.COM.Math.Interpolation.Interpolation. You can easily adapt thecode below to create an instance of another business class, by replacing the ProgId belowwith the full name of the class you wish to use.

106

Page 114: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

CLSID clsid;CLSIDFromProgID(OLESTR( // Get the CLSID of the ProgId

"WebCab.COM.Math.Interpolation.Interpolation"),&clsid);

LPDISPATCH instance = NULL; // the COM `instance'LPUNKNOWN punk = NULL;

CoCreateInstance (clsid, NULL, CLSCTX_INPROC_SERVER,IID_IUnknown, (void**) &punk);

punk->QueryInterface(IID_IDispatch, (void**) &instance);punk->Release();

The variable named “instance” will hold the connection to the “Interpolation” COM server.

8.1.5 Obtain a Method ID

In order to call a method using the instance created above, you will need to obtain a ref-erence to its ID. Use the code below to obtain the ID of the method you wish to call, byreplacing the generic method name “MyMethod” with the name of the method you wishto call. The variable “methodID” will hold the reference to the method.

DISPID methodID; // The ID of the method

/** Replace `MyMethod ' with the name of the method you wish to call*/

wchar_t *methodName = L"MyMethod";instance->GetIDsOfNames(IID_NULL, &methodName, 1, LOCALE_USER_DEFAULT,

&methodID);

8.1.6 Declare the Parameter Values and Types

For every parameter, you will need to declare a variable of type VARIANT, whose type willbe set to the type of the parameter, and its value will correspond to the value you wishthe parameter to take. The code listed in table 8.1 shows how to declare the parametervalues for a method that takes two double parameters.

For information about how to set other types of parameters, such as integers, booleanvalues, and arrays; we refer the reader to this ‘IDispatch Data Types and Structures’article on Microsoft’s MSDN site.

107

Page 115: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

int noParameters = 2; // the number of parameters// 1st parameterVARIANTARG parameter1;parameter1.vt = VT_R8; // 8-bit real typeparameter1.dblVal = 100.0; // 100.0// 2nd parameterVARIANTARG parameter2;parameter2.vt = VT_R8; // 8-bit real typeparameter2.dblVal = 95.0; // 95.0

DISPPARAMS parameters; // the list of parametersmemset(&parameters, 0, sizeof(DISPPARAMS));parameters.cArgs = noParameters;parameters.rgvarg = new VARIANTARG[noParameters];memset(parameters.rgvarg, 0, sizeof(VARIANT) * noParameters);

// Add the parameters in reverse orderparameters.rgvarg[1] = parameter1;parameters.rgvarg[0] = parameter2;

Table 8.1: Declaring parameter types and values for a COM method

8.1.7 Declare the Return Type

A VARIANT variable needs to be declared for the return value of the method as well. Thetype of the VARIANT will be automatically set by the method invocation, so you will onlyneed to initialize its type to VT_EMPTY by calling the VariantInit function.

VARIANTARG result; // Variable to hold the resultVariantInit(&result);

8.1.8 Call the Method

Calling the method comes down to using all the variables declared in the previous steps (theinstance, the method ID, the parameters, and the return value) in one call, as shown below:

// Call the underlying methodinstance->Invoke(methodID, IID_NULL, LOCALE_SYSTEM_DEFAULT,

DISPATCH_METHOD, &parameters, &result, 0, NULL);

The return value of the method is stored in the result variable, in the field correspondingto the method’s return type. For example, if the method returns a double, you will writethe following code in order to store the result in a double variable named “resultAsDouble”:

108

Page 116: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

// Get the result as doubledouble resultAsDouble = result.dblVal;

8.1.9 Call “CoUninitialize”

In order to free generic COM related resources held by a C++ client, you must make acall to the CoUninitialize function. The call to this function can be made right before theend of your application or when your client no longer requires to use COM resources. Theline of code which releases all COM resources is:

CoUninitialize();

8.1.10 A Generic Borland C++ Builder Example

In this section (tables 8.2 and 8.3) we provide a generic Borland C++ Builder example ofa simple Console Application, which connects to one of our business classes, invokes oneof its methods and prints the result in a window. The source code below works with anew Win32 Console Application, which can be created as described in section 8.1.1. Sincethis example’s structure in not specific to the method being invoked, you may adapt thisexample to whatever business class, product, and method you wish to call.

This C++ application calls a method named Kairi, belonging to the MovingAverage busi-ness class in the WebCab Technical Analysis for .NET product. This method takes twodouble parameters and returns a double value.

109

Page 117: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

// Project1.cpp, a Simple Win32 Console Application//

#include "objbase.h"#include "stdio.h"

int main(int argc, char* argv[]){

CoInitialize(NULL); // Enable C++ to COM interoperability

CLSID clsid;CLSIDFromProgID(OLESTR( // Get the CLSID of the ProgId

"WebCab.COM.Finance.Trading.Indicators.MovingAverage"),&clsid);

LPDISPATCH instance = NULL; // the COM `instance'LPUNKNOWN punk = NULL;

CoCreateInstance (clsid, NULL, CLSCTX_INPROC_SERVER,IID_IUnknown, (void**) &punk);

punk->QueryInterface(IID_IDispatch, (void**) &instance);punk->Release();

DISPID methodID; // The ID of the method

// The method name is `Kairi'wchar_t *methodName = L"Kairi";instance->GetIDsOfNames(IID_NULL, &methodName, 1, LOCALE_USER_DEFAULT,

&methodID);

int noParameters = 2; // the number of parameters// 1st parameterVARIANTARG parameter1;parameter1.vt = VT_R8; // 8-bit real typeparameter1.dblVal = 100.0; // 100.0// 2nd parameterVARIANTARG parameter2;parameter2.vt = VT_R8; // 8-bit real typeparameter2.dblVal = 95.0; // 95.0

Table 8.2: Generic VC++ example – Part 1

110

Page 118: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for Borland C++ Builder Chapter 8

DISPPARAMS parameters; // the list of parametersmemset(&parameters, 0, sizeof(DISPPARAMS));parameters.cArgs = noParameters;parameters.rgvarg = new VARIANTARG[noParameters];memset(parameters.rgvarg, 0, sizeof(VARIANT) * noParameters);

// Add the parameters in reverse orderparameters.rgvarg[1] = parameter1;parameters.rgvarg[0] = parameter2;

VARIANTARG result; // Variable to hold the resultVariantInit(&result);

// Call the `Kairi' methodinstance->Invoke(methodID, IID_NULL, LOCALE_SYSTEM_DEFAULT,

DISPATCH_METHOD, &parameters, &result, 0, NULL);delete [] parameters.rgvarg;

// Get the result as doubledouble percentage = result.dblVal;// Print the result inside a MessageBoxchar text[200];sprintf(text, "The percentage is %lf", percentage);MessageBox(NULL, text, "Method result", MB_OK);

CoUninitialize(); // Free all COM specific resourcesreturn 0;

}

Table 8.3: Generic VC++ example – Part 2

111

Page 119: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 9

Programmer’s Guide for .NET

This chapter describes development techniques for various business solutions that make useof the functionality provided by our .NET Service. We analyze both standard and enterprisesolutions, including stand-alone applications, ASP.NET pages, and XML Web services.

9.1 Developing with .NET Class Libraries

The .NET Edition of this product offers core-level functionality to the .NET developerallowing the implementation of fully personalized components and applications for specificbusiness problems on a variety of deployment environments. Irrespective of the complexityof the project a programmer may be working on, this .NET Service can be integrated inan equally straightforward manner by providing the needed functionality in a compact andprecise way.

The Options and Futures for .NET v3.0 component comes as a collection of DLL files.Each DLL is a packed collection of classes that provide the functionality offered by this.NET Service as documented inside the API reference directory of this package. Dependingon the type of .NET solution you are developing, you will be using these DLL files in aspecific way. Once you have chosen a particular implementation of a deployment frame-work, the structure of your source code will need to adapt accordingly. In the followingdiscussion we describe several basic .NET implementation examples that can be used tomake use of our product’s functionality.

9.1.1 Stand-alone C# .NET Applications

A stand-alone C# application is a C# class which acts as a client for the deployed .NETcomponents (i.e. DLLs). The source code listed below defines a standard stand-aloneapplication skeleton which communicates with a class within a .NET Component. By cre-ating an instance, calling a method, sending in a set of parameters and then retrieving thereturned result of the method call. As soon as the method call has gone through success-fully the method continues by displaying its result on the screen.

112

Page 120: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

/*

* The class we are is located inside the WebCab.Libraries.NetService

* namespace.*/

using System;

using WebCab.Libraries.NetService;

public class StandAloneExample {

public static void Main () {

/*

* Creates an instance of the NetClass class*/

NetClass instance = new NetClass ();

/*

* Defines the method parameter.*/

double parameter = 25;

/*

* Invokes a method with the specified parameter* and puts the result in the result variable.*/

double result = instance.ComputeResult (parameter);

/*

* Prints out the retrieved result.*/

Console.WriteLine ("Method ’ComputeResult’ in class NetClass

returned " + result + ".");

}

}

If the method ComputeResult of the NetClass class returned 100, this stand-alone appli-cation would print the following:

Method ’ComputeResult’ in class NetClass returned 100.

113

Page 121: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

9.2 Developing with XML Web Services

This component has been XML Web service enabled and the relevant deployment files canbe deployed which means that you may deploy the Application as a web service and makethe methods contained therein available as XML Web service methods.

9.2.1 Deploying the XML Web Services

Using Windows XP with .NET Framework and IIS installed

In order to deploy this .NET Service as an XML Web service you will need to go throughthe following steps:

� Copy DLL Files - copy the DLL files provide into the bin directory of the IIS serversdirectory. On the standard install this is located at:

C:\Inetpub\wwwroot\bin

� Copy asmx Files - now copy the asmx files included into the folder:

C:\Inetpub\wwwroot\

Now the web service can be accessed through the URL:

http://localhost/WebServices/filename.asmx

Remarks

1. If you prefer to change the URL in which the XML Web service can be accessedthen just create and then copy the asmx files into another subfolder of the ‘wwwroot’directory, in which case the corresponding URL of the web service will correspondingchange.

2. In order to copy the installation files to your IIS location you will need to haveappropriate read and write access to the folder under question.

9.2.2 Writing XML Web Service Clients

The building of an XML Web service client will require the following steps:

� Create a proxy class for the XML Web service.

114

Page 122: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

� Reference the proxy class in the client code.

� Create an instance of the proxy class in the client code.

� Call the method on the proxy class corresponding to the XML Web service methodyou want to communicate with.

For most clients, these steps differ only on how the proxy class is referenced and how theXML Web services are deployed.

9.2.3 Writing Console XML Web Service Clients

An XML Web service client may take a number of forms including a console application,ASP.NET page, HTML page, Windows Form, Java Applet/Frame and any other XMLWeb service enabled client technology.

Here in order to illustrate the core step involved in making a client we describe the stepsrequired to build a console application. Creating other types of clients will involve similarsteps. We assume that you have the .NET Framework installed (on the client and server)and that the IIS server has (been installed and) started on the server.

To create a console XML Web service client application you must:

� Deploy the DLL provided into a bin which you need to create somewhere in a subdi-rectory of the IIS web server you plan to use. The default location for this web serveron your local machine is ‘C:\Inetpub\wwwroot’. The DDL is the required XML Webservice .NET assembly file.

� Deploy the web service descriptor ‘Classname.asmx’ provided, into a IIS web-serversubdirectory.1 Note that we will assume below that the URL of the deployed Class-name.asmx file is:

http://yourserver/Webservices/Classname.asmx

� Create a XML Web service proxy by using the WDLS command line tool. Enter aDOS prompt in the directory where you intend to (develop and) run your consoleapplication from and type at the command line:

Wsdl.exe http://yourserver/Webservices/Classname.asmx

1The purpose of the asmx file is to tell the server that the XML Web service exists so that it may startsearching for the relevant classes within the DLL files in the bin directory. Hence, the asmx file is verysimple and consists of the one line:

<%@ WebService language="C# " class="Classname" %>

and is saved as a TXT file with an extension .asmx.

115

Page 123: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

That is ‘Wsdl’ followed by the URL of the asmx file for the XML Web service. Thisutility will generate a C# file which will be written to the present directory (whichshould be the clients directory)2. The WSDL file is an interface (in OOP terminology)or proxy for the DLL C# implementation of the XML Web service.

� Write a console application in the standard way and instantiate the WebService meth-ods (as if the DLL is hosting locally) using the WSDL proxy. See the below template:

using System;

public class ClassnameClient {/// <remarks>

/// The Main method ensures that the console will run.

/// </remarks>

static void Main() {/*

* We instantiate the "object" represented by

* the proxy class.

*/

Classname classnameObject = new Classname();

/*

* We invoke the ‘Compose’ method of the

* Classname XML Web service

*/

Console.WriteLine("XML Web service method Compose

applied to 7.0 and 3.9 is " +

classnameObject.Compose(7, 3.9));

}}

2WSDL is a standard by which all XML Web services are described. See http://www.w3.org/TR/wsdl

116

Page 124: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

9.2.4 Importing Web services into Visual Studio .NET projects

Fig: Adding a Web reference.

Fig: Adding a Web reference.

117

Page 125: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

9.3 Connecting to a Database with our .NET Libraries

9.3.1 Overview

Most of the financial and mathematical functionality provided by this .NET Service is in-tended for use within a multi-tier environment where the back-end role is taken by an SQLDatabase server. By packaging this functionality within .NET components such as XMLWeb services and .NET Class Libraries we separate the business logic from the databaselogic, allowing you to customize the way you access the database and the way the retrieveddata is sent to the business methods.

In order to assist you in developing DBMS based .NET solutions, we provide the ADOMediator as a standardized way of using our .NET components with an SQL Databaseserver. The ADO Mediator is also a .NET component, which sits on the same level as theother financial and mathematical .NET components and is a seamlessly integrated compo-nent of this .NET Service. While reducing the amount of DBMS code you have to type, itallows you to concentrate on the SQL queries and procedure calls to the Database serverand map the stored data directly to the business methods of this .NET Service.

The ADO Mediator’s functionality has been enabled for use with the following modulescontained within the WebCab Options and Futures for .NET v3.0:

� The “Exotic Options” Module

� The “Options” Module

� The “Equity Derivatives” Module

� The “Futures” Module

9.3.2 The ADO Mediator

There is one ADOMediator class for every module in this .NET Service. You will use thecorresponding ADOMediator class for performing Database operations with classes of a cer-tain module. The ADO Mediator class is located inside the ‘ADO’ subnamespace of itscorresponding module. For example if a module contains the:

WebCab.Libraries.Finance.Trading

namespace, its ADOMediator class will be found under:

WebCab.Libraries.Finance.Trading.ADO.ADOMediator.

Configuring the ADO Mediator

There are three steps to perform in order to start using an ADO Mediator class:

118

Page 126: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

1. Specify the ADO.NET DriverThe constructor accepts an input connection and an output connection. There is norestriction that you should provide both an input and an output connection. Youmay choose to read data and display it inside your Application, compute data andwrite it into the database, or read and write to and from the database, and specifyonly the input or output database connection.

Connecting to your database requires an ADO.NET Driver. This driver is a .NETclass which is part of a DLL file provided by your Database vendor. You specifythe driver you wish to use by sending in to the ADOMediator constructor its run-timetype. That is, if your driver class name is System.Data.SqlClient.SqlConnection3,its run-time type under C# is specified by typing inside your source code:

typeof (System.Data.SqlClient.SqlConnection)

2. Provide the input/output ConnectionString propertyThe ConnectionString property is a piece of text which describes the Database servermachine address, the credentials, and additional information required in order toobtain access to certain parts of your Database server. This piece of text is alwaysdocumented by the provider of the ADO.NET Driver and should be used as suchwhen submitting it to an ADOMediator constructor. An example for the previousADO.NET SQL Server driver would be:

"Initial Catalog=Northwind;Data Source=localhost;Integrated Security=true;"

You may easily notice that the string above describes the machine name and theinitial catalog to connect to. The Integrated Security=true bit enables you toconnect to the SQL Server 2000 by using the current Windows login username andpassword.

3. Assign a business .NET componentThe previous two steps are part of creating an instance of an ADOMediator class andtaking care of the Database connections. This third step involves specifying the busi-ness class belonging to this module which deals with the financial and mathematicalfunctionality. Choose a class of the corresponding module and assign an instance ofthis class to the UnderlyingInstance property of the previously created ADOMediator

instance.

For example, if the name of the class you choose is TradingClass, you could writethe following C# code4:

TradingClass aTradingClassInstance = new TradingClass ();adoInstance.UnderlyingInstance = aTradingClassInstance;

3The built-in ADO.NET driver class name for connecting to the MS SQL Server4We assume adoInstance is the name of the previously created ADOMediator instance.

119

Page 127: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

Using the ADO Mediator

Once these three steps have been performed, you may use the created ADOMediator instanceto perform Database related calculations using the assigned .NET business class. Thereare several methods which you may use with your ADO Mediator instance. Some methodsallow you to read from the database and perform calculations for every retrieved row, andthen store the result in a .NET variable. Other methods allow you to specify the inputvalues and write the result in the database. There are also methods which allow you toread the input parameters from the database and write the method results back into thedatabase in one go.

The basic methods of the ADO mediator are:

� Select Method - Allows you to retrieve the results of a method of your choice be-longing to the underlying business class instance, applied to every row of an SQLSELECT query.

� Update Method - Directly updates values inside your database, as returned by amethod belonging to the underlying business class instance.

� SelectAndUpdate Method - Allows you to combine the two methods mentioned aboveby selecting the data, computing the results and writing it back to the database,according to your own criteria.

A complete API reference for these methods is found inside the Documentation folder ofthis pack. The Windows Installer (MSI) for this .NET Service has also created a short cutto this documentation from the Start Menu.

How the ADO Mediator Works

The way the ADO Mediator processes requests from the client and transfers them to the.NET components and the Database is shown in the diagram below.

120

Page 128: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

Fig: This diagram describes how the ADO Mediator passes onto the Database andthe .NET components its client requests.

C# Source Code Example

The following C# source code makes use of the ADO Mediator’s functionality in order toread and update the database according to a known algorithm. We use the standard SQLServer ADO.NET Driver to connect to a fictitious table named TRADES, and invoke theTradingMethod method of the TradingClass business class.

121

Page 129: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

using System;using System.Data.SqlClient;using WebCab.Libraries.Finance.Trading;using WebCab.Libraries.Finance.Trading.ADO;...try {.../** We specify the same driver and connection string for both the input and output* connections to the SQL Server 2000 Database server.*/

ADOMediator adoInstance = new ADOMediator (typeof (SqlConnection), // Input

"Initial Catalog=Northwind;Data Source=localhost;Integrated Security=true;",typeof (SqlConnection), // Output

"Initial Catalog=Northwind;Data Source=localhost;Integrated Security=true;");

/** We assign an instance of the TradingClass business class to the newly created* instance of this ADO Mediator.*/

adoInstance.UnderlyingInstance = new TradingClass ();

/** We invoke the SelectAndUpdate method which will populate the table according to* the result of the method and the position of the input values in the database.*/

adoInstance.SelectAndUpdate ("TradingMethod","SELECT C ID, SHARES, VALUE FROM TRADES", // Select"UPDATE CUSTOMER SET MONEY=@MONEY WHERE C ID=@C ID", // Update"@MONEY", // Maps the ‘TradingMethod’ method result to @MONEY{new Object[] {"@C ID", "C ID"}}, // Maps C ID to @C IDfalse); // True when updating with a stored procedure

}catch (ADOMediatorException e) {Console.WriteLine (e);

}

Using ADO Mediator with SQL Server 2000

The ADO Mediator instance above requires the same information as in the case of writingyour own ADO.NET source code. The difference lies in the fact that you do not have tomanually control the driver specific operations such as opening and closing a connection,and only concentrate on your SQL queries and the functionality of our business classes.You start by following the three steps mentioned above5 and continue by making calls toany ADOMediator methods.

5Specifying the input and/or output ADO.NET drivers and their connection strings and assigning aninstance of the fictitious TradingClass business class.

122

Page 130: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

As you may notice, the SelectAndUpdate method above follows a logical pattern of de-scribing how the data should be read from the database, computed, and written back,with special care to the use of named parameters. You do not require previous experiencein dealing with named parameters, as they are basically a way to substitute real values withnames inside SQL queries. You may have spotted the @MONEY and @C ID named parametersin our UPDATE statement above. These named parameters will be replaced with real values,taken either from the TradingMethod’s result, or directly from a column returned by theSELECT query.

In our case, we replace @MONEY with the result of applying the TradingMethod method6

to the values of the SHARES and VALUE columns returned by the SELECT query. The sec-ond named parameter (@C ID) is replaced directly by the value of the C ID column of theSELECT query. For more information about named parameters you may wish to consult yourADO.NET driver’s manual. Most special cases are related to the use of named parametersand have been covered by the current version of the ADO Mediator.

9.4 Programmers Guide for Implementing Custom Con-

tracts and Boundary Conditions

The Exotic Options and Equity Derivatives modules within the WebCab Options andFutures Component provides methods for the evaluation of a wide range of exotic options.In particular, these modules offer the following features:

� Exotic Options Module - Evaluation of Option Contracts using Monte Carlo orFinite Differencing techniques in accordance with the Black-Scholes Model.

� Equity Derivative Module - Evaluation of a wide range of Equity derivativesusing a Monte Carlo technique in accordance with various volatility, interest andprice evolution models.

Besides offering a set of predefined option contracts we also allow users of both of thesemodules to provide a custom pay-off function. This allows the user in principle at least toprice any option contract for which the value of the pay-off at expiry can be implementedwithin a method of a class. For both the Exotic Options and Equity Derivatives moduleswe are able to provide a custom pay-off function.

For the Exotic Options module in addition to providing the ability the set a custom pay-offfunction we also allow within the context of the application of finite differencing techniquesto set arbitrary boundary conditions of Dirichlet type. For further, details please see thesection below entitled ‘Boundary Conditions’.

6Which in our example belongs to the fictitious TradingClass business class.

123

Page 131: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

9.4.1 Specifying the Contract to be Priced

As mentioned above you are able to provide a custom derivative contract for example anoption contract by implementing the pay-off function for that contract. In the following dis-cussion we first detail Payoff functions, before moving on to the Payoff function’s interfaceand then finally providing some references to implementations within our component.

Payoff Function

As observed before the most important item which defines and differentiates an option orany other derivative contract is their payoff function. For example, in the most generalform a Bermudan strongly path-dependent option has a payoff function of the followingform:

payoff = P (S, I, t) (9.4.1)

where S is the price of the underlying, I is the path dependent value which depends onthe path of the underlying and t is the time.

In instances where we have more than one asset, the price of the underlying S, and thepath dependent value I, are arrays where the i-th term corresponds to the correspondingvalue of the i-th asset. That is, in the case where the payoff function depends on morethan one asset the variables S and I, will become arrays.

Examples: In the case of both Asian and Loopback options the values given for S (seebelow), will correspond to the market price of the underlying asset at some time T , onwhich the option is defined. The path dependent variables will depend on the way in whichthe option is defined. In particular, for Asian and Loopback options we have:

� Asian - I = ‘Average of the price over a specified period evaluated at a given pointin time’

� Loopback - I = ‘Maximum of the price over a specified period evaluated at a givenpoint in time’

The Payoff Function Interface

Before being able to price a derivative contract you will naturally need to provide itsdefinition which is performed by providing its payoff function. In order to allow thepayoff function to be provided within our framework you are required to implement thePayoffFunction interface within the exotic options module. In order to implement thisinterface requires the user to provide an implementation of the method:

GetValueAt(double time, double[] assetPrices, double[] pathDependentValues)

which returns the pay-off of the contract at a given point in time.

124

Page 132: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

Whenever we which to implement another derivative contract we are required to pro-vide an implementation for the GetValueAt method such that it returns the value of thepayoff function, given the current asset prices (i.e. double[] (Multi-asset) or double (Sin-gle asset)) and the path dependent values (i.e. double[] (Multi-Asset) or double (singleasset)); and the current time time.

Providing Strategy Implementations

To illustrate the use of the payoff interface we include within our product implementationcommon options and option trading strategies as implementations of this interface. Belowwe list these implementations of options and option strategies along with the name of theclass in which they can be found:

� Options with only one asset

– Simple Vanilla options payoff implemented within the SimplePayoff class.

– Binary options payoff implemented within the BinaryPayoff class.

– Standard strongly path dependent options implemented within theStronglyPathDependentPayoff class.

� Standard Option Strategies

– Spread strategy implemented within the SpreadStrategyPayoff class.

– Strangle strategy implemented within the StrangleStrategyPayoff class.

– Straddle strategy implemented within the StraddleStrategyPayoff class.

Please note that in addition to these implementations we also provide client exampleswhich illustrate how custom payoff (and boundary conditions) can be implemented andthen used with the pricing procedures.

9.4.2 Boundary conditions

Whenever wishing to apply a finite differencing PDE based approach to the pricing ofderivative contracts you will be required to either provide custom boundary conditions oruse a pre-defined set of boundary conditions for the pricing problem in question. The reasonwhy boundary conditions are required when applying the finite differencing PDE approachis to ensure that the PDE problem which in this instance is a pricing problem has a uniquesolution (i.e. yields a unique price). That is, in the case of the Black-Scholes model theboundary conditions within the finite differencing PDE approach as implemented withinthe class WebCab.Finance.Options.Exotic.FiniteDifference, are used to select the uniquesolution (i.e. price) from the range of solutions of the Black-Scholes equations themselves.

125

Page 133: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

Types of Boundary Conditions

Within our implementation we allow the use of two types of boundary conditions, namely:

� Dirichlet Conditions - These boundary conditions consist of the value of the solu-tion (i.e. price function) on the boundary of the finite differencing grid. In order touse Dirichlet Boundary Conditions you will need to provide the boundary conditionsby implementing the interface DirichletBoundaries.

� Default Second Order Boundary Conditions - The second order boundaryconditions work very well when the maximum and minimum values of the underlyingasset price on the grid are deep in (or out) of the money. These boundary conditionsare given as follows: Set the value of the second order derivative at the boundarywith the maximum value of the underlying asset on the finite differencing grid tobe zero and take the lower bound to be the axis where the asset price is zero to beset in accordance with the assumption that the asset price will stay at zero (i.e. thediffusion and drift term from this point have no effect).

Selecting which type of Boundary Condition to use

Within the application of finite differencing PDE methods to derivatives pricing the selec-tion of appropriate Dirichlet boundary conditions can become quite complex, particular formulti-asset contracts. Even for single-asset contracts the setting of appropriate boundaryconditions can be rather awkward to achieve in such a way as to express the true financialbehavior of the contracts values on the boundary over the entire range of values of theboundary of the finite differencing grid.

Ideally within the application of the class Options.Exotic.FiniteDifference, you should beable to tailor custom Dirichlet boundary conditions for the option at hand. However, asnoted above this can often be a difficult task and for this reason we provide the SecondOrder Boundary Conditions within Options.Exotic.SecondOrderBoundaries, which havethe distinct advantage of working well for a broad range of contracts and can be usedessentially as the ‘default boundary conditions’. Moreover, even if you are using a customset of Dirichlet boundary conditions then often it is a good idea to compare the resultsfound using the Second Order Boundary Conditions in order to approximately validate thesolution found.

Remark Please note that if you are considering a standard option (for example, Asian,Lookback, Barrier, Parisian, Parasian) then we provide within the class Options.Exotic.BlackScholesseveral methods which price standard contracts using a finite differencing approach using(good) Dirichlet boundary conditions which have internally been set.

Setting Custom Dirichlet Boundary Conditions

We give the user the choice of supplying the boundary conditions of Dirichlet type. This isdone by providing an implementation of the interface Options.Exotic.DirichletBoundaries,

126

Page 134: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

in particular providing an implementation for the method:

GetValueAt(double time, int indexOfAsset, boolean underlyingMax, double[]variableAssets, int noAssets)

The question as to the exact logic of this method should be decided by the user, andshould ideally attempt to capture the nature of the contract being considered.

Contracts depending on one underlying Asset: In the case of a one-asset optionthe corresponding PDE will have two variables: t (time) and S (price). In this case thefinite difference grid (within the time-price plain) will be determined by being the rect-angular region bounded by four lines determined by the present time, the expiry time,the minimum asset price and the maximum asset price considered within the grid. Theboundary condition corresponding to the expiry is clearly a function only of the price S(since the time is equal to the expiry time), and hence the boundary here is a function ofone variable. Similarly, the boundary for fixed values of the asset price (i.e. maximum andminimum values) only depends on the time variable, and the boundary corresponding tothe present point in time only depends on the asset price. Hence, in the case of an contracton one underlying the corresponding boundary conditions are all function of one variable.

Contracts depending on many underlying Assets: Now, if the contract dependson many assets (i.e. is multi-asset), then providing the boundaries gets much more com-plicated. This is because corresponding finite differencing grid is over a multi-dimensionalcube which is spanned by the time axis and an axis for each of the underlying assets con-sidered. Here the boundaries are no more functions of just one variable on the boundary,since in general if the contract is on N assets, then the pricing function will depend onN + 1 assets (i.e. assets and time variable) and the boundary functions once one of theprice function variables has been fixed (in a corresponding way to the single asset case) itwill depend on N variables.

Notes on Implementation: The interface DirichletBoundaries extends a more generalinterface Boundaries, which has only one method: int type(), which informs the finite dif-ferencing algorithm the type of boundary conditions which are to be used. In the currentimplementation only Dirichlet boundaries can be supplied by the user, so, when implement-ing the DirichletBoundaries interface, the method type must return the predefined constantBT DIRICHLET. To avoid the task of always writing this method, an abstract class, namedDirichlet, which provides type and leaves getValueAt unimplemented, was included. Thatis, you simply have to extend this class instead of implementing the interface.

Using the Default Second Order Boundary Condition

In addition to the Dirichlet Boundary we also provide a set of boundary conditions knownas the Default Second Order Boundary Conditions which is contained within the class,SecondOrderBoundaries, contained within the ExoticOptions module.

127

Page 135: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Programmer’s Guide for .NET Chapter 9

These Boundary conditions as mentioned above are particularly useful since they can beapplied to a wide range of options contracts with good results. These boundary conditionsare not Dirichlet in type and rely on the following assumptions being made:

� At S = 0 (the low boundary), for most contracts (including calls and puts) the diffu-sion and drift terms switch off. This means that on S = 0 the payoff is guaranteed,resulting in the condition:

∂V

∂t(0, t)− rV (0, t) = 0 (9.4.2)

� At S →∞ (the high boundary), the payoff is at most linear in the underlying, whichimplies the condition that:

∂2V

∂S2(S, t) → 0 as S →∞ (9.4.3)

Pre-defined Boundaries for Vanilla Put and Call Options

In the special instance of Vanilla Put and Call options we provide custom Dirichlet Bound-ary conditions. Though for these options there exists closed analytic formulae we pro-vide these custom Dirichlet Boundary in order to ascertain the accuracy of the finitedifferencing approach. These custom boundaries conditions are contained within the classSimpleBoundaries and extend the Dirichlet boundaries.

128

Page 136: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 10

Examples

Within this chapter we detail the examples provided with this .NET Service. We providewith this Component examples of two types:

1. QA Examples

2. Custom Examples

10.1 Question and Answer (QA) Client Examples

10.1.1 Overview

Within this folder we offer client examples written using a number of .NET compliantlanguages for the .NET Business Components provided within this package. In particular,for each business method contained within each business Component we provide an exampleimplemented within C# , VB.NET and C++.NET; which illustrates how functionalitycontained within this component can be applied to solve real world problems. In addition,to these examples we also include custom applications which solve some of the genericproblems which this Component is designed to address.

10.1.2 Structure of QA Examples Directory

By drilling down the QA Client directory structurr you will find the following six directorylevels:

1. Client Level2. Language Level3. Business Module Level4. Business Class Level5. Example Level6. Custom Example Level

which have the structure as shown in the following diagrams.

129

Page 137: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

Top Three levels of the QA Directory Structure

(Client Level) (Language Level) (Business Module Level)

QAClients +

|

+ C# ------------------------+

| |

+ VB.NET --+... + ‘Business Module 1’ ----------

| |

+ C++.NET --+... + ‘Business Module 2’ --+...

| |

+ QALibrary.dll + ...

|

+ QALibraryModule.netmodule

|

+ Readme.txt

Bottom Three levels of the QA Directory Structure

(Business Class Level) (Example Level) (Custom Example Level)

--+

|

+ ‘Business Class 1’ --------+

| |

+ ‘Business Class 2’ --+... + ‘BusinessClass’.exe.conf

| |

+ ... + ‘BusinessClass’.cs

|

+ compile.bat

|

+ run.bat

|

+ run_gui.bat

|

+ ‘CustomClient’ -------+ ‘CustomClient’.cs

| |

+ ... + compile.bat

|

+ run.bat

130

Page 138: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

10.1.3 Quick Start Guide

Browse down to the particular client within the business module for the given .NET com-patible language which you are interested in. Run the compile.bat, script in order tocompile the example and then run the run.bat, script in order to run the example.

10.1.4 Explanation of the QA Directory Structure and its files

1. Client Level

The directory containing the Questions and Answer Examples is named ‘QAClients’.This directory can be located by using the Readme.html file, which is presented atthe end of the installation process, by selecting:

Run Examples > Run .NET Class Library Examples

The Readme.html file can also be opened from the shortcut:

Start > Programs > WebCab Components > ‘Name of Components Package’ > Readme.html

2. Language Level

Within the ‘QAClients’ folder is the Language level of the QA directory structure.Within this folder you will find 3 sub-directories: C# , VB.NET and C++.NET;which contain examples written in each of the .NET languages C# , VB.NET andC++.NET respectively. Within this folder you will also find the following three files:

� QALibrary and QALibraryModule.netmodule - contain utility function-ality necessary for running the clients. If you wish to run these examples fromwithin Visual Studio .NET (for example) then you will need to register this DLLwithin your VS.NET project.

� Readme.txt - this Readme file.

As mentioned above within the overview we provide an implementation of each ‘Ques-tion and Answer’ example as three eqivalent implementations, namely: a C# client,a VB.NET client and a C++.NET client. Selecting one of the three folders C# ,VB.NET or C++.NET; in order to view the client implementated within the corre-sponding language.

3. Business Module Level

After selecting one of the sub-folders C# , VB.NET, C++.NET at the ‘LanguageLevel’ (see (2) above) you will enter a folder which contains a sub-folder for each ofthe modules contained within this component package. The modules are convenientcollections of business classes containing the business functionality offered by thiscomponent. Each module has a sub-folder which contains the ‘Question and Answer’examples of each method of the classes which it contains.

131

Page 139: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

4. Business Class Level

At the business class level under the module level we are presented with one sub-folderfor each of the classes within the business module. Each of these folders contains thefiles of the examples for each of the methods contained with the respective class.

5. Example Level

At the Example level you will be presented with the files which allow you to compileand then run the examples of the application of the Business methods of the respec-tive class. The files within this directory which constitute the Client example are asfollows:

� Source Code File(s) - Depending on the .NET compatible language selectedat the ‘Language Level’ this folder will contain a source code file(s) with theextension .cs, .vb or .cpp corresponding respectively to the C# , VB.NET orC++.NET client.

� Configuration File - Apart from the main source code file the folder willalso contain a configuration file with the extension .conf, this file contains theinformation concerning the location of the DLLs which the example will require.You may add more references as needed but you should not remove the referencesalready contained within this file.

� Compile Batch File - Assuming that you have access to the relevant C# ,VB.NET or C++.NET compiler the compile batch file (compile.bat) once runwill compile the client example from the folders source code file. Below weinclude some remarks on how to obtaining suitable .NET compilers in order tobe able to compile and then run these C# , VB.NET and C++.NET examples.

� Run Batch File - The run batch file (run.bat) will run the examples executablefile (exe) which is generated from the compilation of the source code file. If theexample over runs your console screenful then press space in order to page down.

6. Custom Example Level

At the Custom Example level you will find a source code file containing the im-plementation of the Application which addresses a typical question for which theComponent is designed. The source code has a linear structure with full inline com-mentary. By just running the compile and then run scripts contained within thisdirectory you will be able to solve to given problems view the results obtained. Thefiles contained within each Custom Client Example directory are as follows:

� Source Code File(s) - Depending on the .NET compatible language selectedat the ‘Language Level’ this folder will contain a source code file(s) with theextension .cs, .vb or .cpp corresponding respectively to the C# , VB.NET orC++.NET client.

132

Page 140: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

� Compile Batch File - Assuming that you have access to the relevant C# ,VB.NET or C++.NET compiler the compile batch file (compile.bat) once runwill compile the client example from the folders source code file. Below weinclude some remarks on how to obtaining suitable .NET compilers in order tobe able to compile and then run these C, VB.NET and C++.NET examples.

� Run Batch File - The run batch file (run.bat) will run the examples executablefile (exe) which is generated from the compilation of the source code file. If theexample over runs your console screenful then press space in order to page down.

10.1.5 Remarks on .NET compilers

1. Required compilers and how to test for them

In order to compile the C# , VB.NET or C++.NET examples you will require foreach of these .NET languages a suitable compiler. The easiest way in which to testwhether you have access to the three main .NET language compilers at your com-mand prompt is to type the follow commands at the command line:

csc - Invokes the C# compilervbc - Invokes the VB.NET compilercl - Invokes the C++.NET compiler

2. How to obtain the required compilers

Compilers for the C# and VB.NET .NET compatible languages are provided withinthe .NET SDK v1.0 (or higher). At the time of writing within the standard Microsoft.NET SDK the C++ compiler is enabled only as a C compiler.

In order to obtain the C# and VB.NET command line compilers you simply needto download and install the .NET SDK available from the Micrsoft site. In orderto obtain a fully functional C++.NET compiler you can either download and installMicrosoft’s feeely available and fully functional Visual C++ Toolkit 2003, availablefrom: http://msdn.microsoft.com/visualc/vctoolkit2003/; or use the C++ compilerwhich is provided with Microsoft’s Visual Studio .NET IDE.

10.1.6 Database Example with JDBC Mediator

The Database Example is located inside the Client/Options/DatabaseExample directory.The following steps are required before running the Database example.

1. Installing our Tables (MySQL Only)In order to create the database structure from which you are able to load the outputresults, you will need to run the ‘create.sql’ scripts in the ‘Data’ subdirectory. Openthe MySQL prompt from the ‘Data’ subdirectory and:

133

Page 141: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

� Select (or create and then select) a database you can spare for tables namedAMD, BEAS, DELL, IBM, MSFT, ORCL, and RATE. For example, if you havedecided using the ‘test’ database, you would optinally type the SQL commandto create it (unless it already exists):

CREATE DATABASE test;

and then, you would type the following to select it:

USE DATABASE

� Run the ‘create.sql’ SQL script located in the ‘Data’ subdirectory of the currentdirectory by typing at the same MySQL prompt the following:

source create.sql

If this fails, make sure you have started the MySQL prompt from the ‘Data’subdirectory (this is where the database files for this example are stored).

2. Configuring the Database ConnectionEdit the Java source code file by filling out JDBC information about your database,such as:

(a) Driver Name (e.g. com.jdbc.mysql.Driver)

(b) JDBC Url (e.g. jdbc:mysql://localhost/test)

(c) Username and Password

If you are unsure whether you have a JDBC Driver for your Database, skip this stepand try running the example with the predefined values. If that fails, you will needto probably download the latest driver.

3. Running the example

Run the ‘compile’ script (compile.sh for Linux, compile.bat for Windows) to compilethe Java source code, and then the ‘run’ script to see the results.

Uninstalling the Source Data

To delete all the tables used in this example, open the MySQL prompt from the ‘Data’subdirectory, select the database where you created the tables, and run the following:

source delete.sql

10.2 Exotic Options Custom Examples

This section provides examples of using option pricing methods (in particular Monti-Carlo andFinite Differencing) implemented within the Exotic Options module of the WebCab Optionsand Futures J2EE Application. For the below listed examples we built working applications sothat you may see how the component can be used and then how it performs.

134

Page 142: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

10.2.1 About the examples

There are seven examples included for the Exotic Options module. We designed them withthe intention of covering a broad range of possible user scenarios.

10.2.2 Testing procedure

In all our examples of options on one asset the following financial parameters were used:

� interest rate = 0.1

� no dividend (dividend yield = 0)

Also note that all the results are displayed with five digit precision.

Monte Carlo results will differ with each subsequent method call using identical parame-ters, because the Monte Carlo algorithm contains a fundamental random selection element.Therefore a comparison between MonteCarlo and finite differencing cannot be relevant un-less seen in a statistical manner. You should run our examples many times before makingany conclusions regarding the differences between Monte Carlo and finite differencing.

In some of the examples we use a formula to estimate the magnitude of the differencein relation with the magnitude of the results. That is, we calculate:

relative difference =|fd result−mc result||fd result|+ |mc result|

(10.2.1)

10.2.3 Example 1 - European vanilla options

Motivation and Problem

This example compares finite differencing with Monte Carlo for very simple option typeswith known boundaries. We use the SimplePayoff and SimpleBoundaries classes to specifyour option type. The contract stipulates that we have an European call option with strikeprice equal to 50 and that it will be exercised after one year.

Suppose that the current asset price is 40 and we wish to find out the present optionvalue.

The Parameters

In this instance the following parameters should be used within the finite differencingalgorithm:

� algorithm = Cranck-Nicholson

135

Page 143: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

� time steps = 1000

� maximum asset price = 150

� asset price steps = 150

Results

According to the finite difference procedure the present option price is 4.44724.

For Monte Carlo, the number of random walks is set to 1000.

Almost 90% of the tests runs with this example show a relative difference between MonteCarlo and finite differencing less than 5%.

Source Files

The source file for this example is EuropeanVanilla/EuropeanVanilla.java and it can befound in the /Client/ExoticOptions directory within the Applications package.

10.2.4 Example 2 - Supplying your own payoff function and bound-aries

Motivation and Problem

This example shows you how to supply your own payoff function and boundaries. Thepayoff function used here is actually the square root of the payoff from a Vanilla put option.

We compared the results obtained using the generic SecondOrderBoundaries class withthe results obtained when we have set the boundaries by implementing Dirichlet abstractclass.

The Parameters

The algorithm parameters are exactly the same as those used in the previous example.

Results

The results are:

� generic boundaries - 2.3347

� user designed boundaries - 2.34563

The Monte Carlo method returns similar results.

136

Page 144: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

Source Files

The source files for this example is SupplyingPayoffFunction/SupplyingPayoffFunction.java.It can be found in the /Client/ExoticOptions directory within the Applications package.

10.2.5 Example 3 - Supplying your own payoff function for multi-asset boundaries

The Problem This example is similar to the previous one, the only difference being thatnow we have a two-asset option to be priced.

The Parameters

The financial parameters are:

� interest rate = 0.1

� volatility of first asset = 0.4

� volatility of second asset = 0.3

� no dividend (dividend yield = 0)

� correlation matrix =

(1 0.15

0.15 1

)As there is more than one asset, we do not have the possibility of choosing the algorithmtype. The only algorithm which can be used is the explicit algorithm.

The (explicit) algorithm parameters are:

� time steps = 200

� maximum asset price = 150

� asset price steps = 50

The strike price for the first asset is 50 and for the second asset it is 40.

Results

The results are:

� generic boundaries - 2.19603

� user designed boundaries - 2.19578

137

Page 145: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

Remark If you are using the J2EE platform and local delivery then you can see thatthe finite differencing algorithm is slower in combination with the generic boundaries. Thereason for this is that the computations required by the client MyBoundaries class arefewer than those performed by SecondOrderBoundaries. Quite the opposite happens whenusing remote delivery. In this case, with generic boundaries, the algorithm finishes muchfaster. Indeed, the server using client boundaries must now call the getValueAt methodremotely while all processing for general boundaries still takes place on the server. In thisinstance you can see the huge speed difference which can occur between the two deliverymethods. Here in this example there are 40000 calls to the boundary evaluation methodwhich needs 40000 network connections and greatly infringes performance.

Source Files

The source files for this example is MultiAssetOptions/MultiAssetOptions.java and it canbe found in the /Client/ExoticOptions directory within the Applications package.

10.2.6 Example 4 - Thorough comparison between finite differ-encing and Monte Carlo

Motivation and Problem

In this example we call the Cranck-Nicholson finite differencing algorithm and Monte Carlosuccessively for 6 types of options each having 10 different maturity dates. This meansthat we have a total of 60 option contract to value. For each contract the absolute and therelative difference between the results are also displayed.

Remark There exist some results that are evidently wrong (for example the negativevalue which appears when evaluating Lookback strike put option with 10 years to matu-rity). The most probable cause of these and of other very large differences is simply thatthe boundaries are wrong (the general” boundaries we use here are based on two assump-tions that are not necessarily applicable to all option types). In such cases you shouldconstruct your own boundaries. For further discussion of this issue please see boundaryconditions section of the Exotic Options Programmers Guide. Also see other possible errorsources in Mathematical Documentation.

Source Files

The source file for this example is ComparisonFDMC/ComparisonFDMC.javaanditcanbefoundinthe/Client/ExoticOptionsdirectorywithintheApplicationspackage.

10.2.7 Example 5 - American options

Motivation and Examples

This example compares the three finite differencing algorithms: explicit, implicit and Cranck-Nicholson. American options cannot be priced with Monte Carlo, so no such results are

138

Page 146: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

displayed. When evaluated with an implicit algorithm (fully implicit or Cranck-Nicholson)the tolerance parameter must be set. In our example the tolerance was set to 0.001. Gen-erally it is not worth trying to set this to a lower value in the hope that precision willincrease.

The Parameters

Algorithm parameters are:

� time steps = 2000

� maximum asset price = 150

� asset price steps = 150

The current price was considered to be 75, the strike price 50 and the time to maturity ofone year.

Results

The results are:

� explicit algorithm - 0

� fully implicit algorithm - 30.07861

� Cranck Nicholson algorithm - 30.51493

The explicit algorithm returns 0, because it is unstable in the current configuration of al-gorithm parameters. If you increase the number of time-steps to, say 10000, you will seethat it will return a correct result. The same thing happens if you decrease the asset pricestep to 50 (for example).

Remark Zero is not the only result possible when the algorithm is unstable. Oftenvery large results are returned (for example 1E100).

Source Files

The source file for this example is AmericanOptions/AmericanOptions.java and it can befound in the /Client/ExoticOptions directory within the components package.

10.2.8 Example 6 - American multi-asset options

Motivation and Problem

This example shows you how to evaluate American multi-asset options. For this purposewe use two standard option strategies: the spread and the strangle.

139

Page 147: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

The Parameters

The financial parameters are the same as in the European multi-asset example.

The algorithm parameters are:

� time steps = 1000

� maximum asset price = 100

� asset price steps = 50

The contract specifies that the strike price for the first asset is 50 and for the second asset40. The expiry time is one year and the current asset prices are 40 and 90 respectively.

Results

The results are:

� American bull spread - 4.60251

� American bear spread - 10

� American strangle - 12.5145

� American straddle strategy - 10.09196

Source Files

The source file for this example is AmericanMultiAssetOptions/AmericanMultiAssetOptions.javaand it can be found in the /Client/ExoticOptions directory within the Applications pack-age.

10.2.9 Example 7 - Example of Bermudan options

Motivation and Problem

This is an example of a simple put option with expiry time of one year and early exercisepermitted only during an interval of six month beginning with the third month of the year.All these restrictions are set in the payoff function, which is, in this case, time dependent.That means we have a Bermudan-type option.

The Parameters

The current price is 40 and the strike price is 50. Cranck-Nicholson algorithm is used withgeneric boundaries.

Results

The result returned are 10.91813.

140

Page 148: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

Source Files

The source files for this example is BermudanOptions/BermudanOptions.java. It can befound in the /Client/ExoticOptions directory within the Applications package.

10.2.10 Example 8 - Example of Binary options

Motivation and Problem

This is an example of a binary option, which pays off 1 currency unit if the price after oneyear is above the strike price.

Results

The result of the Crank-Nicholson algorithm is 0.28462.

Source Files

The source files for this example is BinaryOptions/BinaryOptions.java. It can be found inthe /Client/ExoticOptions directory within the Application package.

10.2.11 Example 9 - Example of Asian options

Motivation and Problem

This example shows you how to use the pricing methods for strongly path dependentoptions. Specifically a Asian option with daily arithmetic averaging is used. It is a rate(price) call option. This means that the payoff is max(average− strike, 0). The followingparameters were used:

� interest rate = 0.1

� volatility = 0.3

� time to maturity = 1

� current price = 40

� strike price = 50

� dividend = 0

� price steps = averagesteps = 150

� maximum price = maximumaverage = 150

� time steps for finite differencing = 5 ∗ 260 = 1300

� sampling period = 5(dailyupdatingoftheaverage)

141

Page 149: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

� time stepsforMonteCarlo = 260

� random walks = 9000

Results

The result of the Cranck-Nicholson algorithm is 0.74908.

Source Files

The source files for this example is AsianOptions/AsianOptions.java. It can be found inthe /Client/ExoticOptions directory within the Application package.

10.2.12 Example 10 - Example of Lookback options

Motivation and Problem

This example is very similar to the previous one, except that we are now pricing lookbackoptions instead of Asian options (which are also strongly path dependent). The differenceis that the path dependent variable is now the maximum value of the price registered fromthe beginning of the contract. The payoff is max(max− strike, 0). The same parametersas in the previous example were used.

Results

The result of the Cranck-Nicholson algorithm is 4.94097.

Source Files

The source files for this example is LookbackOptions/LookbackOptions.java. It can be foundin the /Client/LookbackOptions directory within the Application package.

10.2.13 Example 11 - Example of Monte Carlo with error control

Motivation and Problem

This example shows you how to use error control for Monte Carlo. It is identical withthe first example (European vanilla options), except that now we require that the relativeerror of Monte Carlo is less than 5%, with 95% certainty. So the confidence level is 0.95and max relative error is 0.05.

Results

If you run the example multiple times, you can notice that in the large majority of casesthe relative error is below 5%. On the average, only 1 in 20 runs should have a biggererror.

142

Page 150: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Examples Chapter 10

Source Files

The source files for this example is ErrorControl/ErrorControl.java. It can be found in the/Client/LookbackOptions directory within the Application package.

143

Page 151: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Chapter 11

Guide to WebCab Components

11.1 The Company

WebCab is a privately owned British company that has built business solutions since itsinception in 1999. We continue to refine and develop our Mathematical and FinancialFramework which we have implemented on the Office, J2SE, J2EE, Delphi, COM and.NET platforms.

11.2 Presentation of Products

Our aim is to provide good quality, useful information to help you decide which componentbest suits your development needs. WebCab is committed to honesty and realism whenpresenting our products. In order to achieve this a detailed, clear and factual style forpresentation is adopted within our documentation and marketing material.

11.3 Supported Clients, IDEs, Containers and DBMSs

By supporting all major development, server and client side technologies we preserve thedevelopers flexibility in making tool and architecture decisions. In particular, each productcontains detailed examples and advice concerning the integration and use of our moduleswithin existing development tool and infrastructure platforms. In short, our documenta-tion provides the information that the developer needs to get their applications up andrunning as quickly and as easily as possible.

We detail exactly how the developer can use the .NET Component, COM Componentand XML Web service contained within this product with the following technologies:

� Client containers - Internet Explorer, Mozilla, Microsoft Office

� IDEs - Microsoft’s Visual Studio .NET (incl. Visual C.NET, Visual Basic .NET,Visual C++.NET), Microsoft’s Visual Studio 6 (incl. Visual C++, Visual Basic),

144

Page 152: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Guide to WebCab Components Chapter 11

Borland’s C++ Builder (incl. C++ 2005, C++BuildX), .NET Framework SDK,Office’s Visual Basic Editor

� Client Side Technologies - Application Clients, ASP.NET, C#, VB.NET, C++.NET

� XML Web services - Implemented in C#, VB.NET

� DBMS - Oracle, IBM DB2, SQL Server, Sybase, MySQL

� Platforms - Windows 2003/XP/2000/NT/9x

For these technologies we include all installation scripts and template examples which willhelp the developer quickly and easily assemble their multi-tier enterprise application.

11.4 Transparent Functionality

All technical and business intelligence incorporated within our products is described withinthe associated documentation. This allows the developer to see the nature of the method-ology implemented within our proprietary algorithms.

11.5 Company Culture and Activity

WebCab Components is focused solely on the production of high quality software moduleswithin our Financial and Mathematical Framework. The WebCab team contains a widerange of expertise and experience from the academic, investment banking and softwaredevelopment worlds.

Within the company there exists significant internal competitive pressures with constantpeer review and evaluation, resulting in higher quality products, which adhere to highprofessional standards and offer extended functionality.

11.6 Product Life cycle

We continuously add value to our products by evolving them according to new .NETFramework specifications, customer feedback and market demands. We give particularemphasis to incorporating our clients suggested modifications and additions into our prod-uct development cycle.

11.7 Support, Warranty and Upgrades

WebCab warrants that each component will perform substantially in accordance with theaccompanying written material. We provide with all our products without charge sixty(60) days product support services including fixing bugs, compatibility issues and other

145

Page 153: WebCab Options and Futures for .NET v3€¦ · techniques for European, Asian, American, Lookback, Bermuda and Binary Options; we also cover futures and forward contracts. We apply

Guide to WebCab Components Chapter 11

technical support issues.

All maintenance updates (including service packs) will be distributed free of additionallicense cost.

Dr Ben Fairfax

Founder and CEO

WebCab Components - From Developer, To Developer

.NET and all .NET-based marks are trademarks or registered trademarks of Microsoft Corporation,

Inc. in the U.S. and other countries.

146