<<

UPTEC F15 034 Examensarbete 30 hp 16 Juni 2015

An Asynchronous Meta-Data Driven Web UI for Pricing of Structured Products

Anders Lindström Abstract An Asynchronous Meta-Data Driven Web UI for Pricing of Structured Products Anders Lindström

Teknisk- naturvetenskaplig fakultet UTH-enheten In the process of building maintainable and customizable software used and displayed in different mediums, a user interface (UI) that is auto-generated from meta-data can Besöksadress: be built. That way minimal effort can be made when customizing the software. This Ångströmlaboratoriet Lägerhyddsvägen 1 thesis took place at the financial software company SunGard. Traders have requested Hus 4, Plan 0 a web based solution to one of SunGard's financial softwares, and will be used for managing structured products. The solution had to work with some already defined Postadress: web and server components that SunGard is using. The web tool used for making a Box 536 751 21 Uppsala prototype and evaluating the suitability was AngularJS. As a result it was found that it was possible to create a meta-data driven UI. Some programmatic design issues when Telefon: generating the UI are discussed. 018 – 471 30 03

Telefax: 018 – 471 30 00

Hemsida: http://www.teknat.uu.se/student

Handledare: Anders Möller Ämnesgranskare: Josef Höök Examinator: Tomas Nyberg ISSN: 1401-5757, UPTEC F15 034 Popul¨arvetenskaplig Sammanfattning Det h¨arexamensarbetet beskriver uppbyggnaden av ett grafiskt webbgr¨anssnitt f¨oratt prisa strukturerade produkter. Komponenterna som ska visas i webbgr¨anssnittetinnehar sj¨alvbeskrivande information, s˚akallat meta-data, som bland annat beskriver hur komponenten ska visas. Exempel p˚ameta- data ¨arkomponentens titel och dom¨an(flyttal, lista, datum etc.). Den sj¨alvbeskrivande informationen g¨ordet m¨ojlighetatt automatisera skapan- det av gr¨anssnittet.Arbetet tog plats p˚af¨oretagetSunGard, ett f¨oretagsom bland annat utvecklar finansiella mjukvaror f¨orbanker. Mjukvaran detta ex- amensarbete har arbetat med ¨arFront Arena.

N¨arman bygger en mjukvara med grafiskt gr¨anssnittkr¨avsdet ofta att man l¨aggertid och arbete p˚aatt modifiera det grafiska gr¨anssnittetd˚a¨andringar och utbyggnader av mjukvaran sker. Som ett steg i riktningen mot att utveckla flexibel mjukvara har SunGard skapat ett ramverk kallat Deal- Package f¨oratt programmatiskt definiera strukturerade produkter i Front Arena. I ramverket specificerar man meta-data som kan anv¨andas till att autogenerera ett grafiskt gr¨anssnitt,vilket ¨arimplementerat i Front Arena.

Handlare har nu efterfr˚agatm¨ojlighetentill att ¨aven autogenerera grafiska gr¨anssnittp˚awebben. Ramverket som testats och diskuterats i detta ex- amensarbete har varit AngularJS, ett JavaScript-baserat ramverk utveck- lat av . I rapporten beskrivs uppbyggnaden SunGards programma- tiska anv¨andargr¨anssnittDealPackage och implementationen p˚awebben. D¨arefterdiskuteras varf¨orAngularJS inte ¨aroptimalt f¨ordenna uppgift, dock fullt m¨ojligtatt anv¨anda,samt vilka problem som st¨ottsp˚aunder v¨agen. Contents

1 Introduction 1 1.1 SunGard ...... 1 1.2 Purpose ...... 4 1.3 Limitations ...... 4 1.4 Problem Definition ...... 4

2 Meta-Data Objects 5 2.1 Variable Dependencies ...... 5 2.2 Meta-Data ...... 6 2.3 Modification ...... 7

3 Front Arena DealPackage 8

4 Front Arena - Browser 8 4.1 PACE ...... 8 4.2 Browser to PACE ...... 9

5 A Structured Product 11 5.1 Bond ...... 12 5.2 Put Option ...... 12 5.3 Reverse Convertible Note ...... 14

6 Defining an RCN using DealPackage 15

7 Building a Prototype with AngularJS 18 7.1 Overview of Final Prototype ...... 18 7.2 Index Page ...... 20 7.3 Factory: DealPackageService ...... 21 7.4 Service: faProductGeneral ...... 23 7.5 Directive: faInput ...... 25

8 Discussion 29 8.1 Placement of Directive Logic ...... 29 8.2 ’s $filter-service ...... 30 8.3 The Absence of a Standard onChange ...... 31

9 Conclusion 31 9.1 Further work ...... 31 1 INTRODUCTION

1 Introduction

The scope of this thesis is to look into how a meta-data driven user inter- face (UI) on the web can be built using AngularJS[1]. It took place at the financial software company SunGard[2] in Stockholm. They are providers of a financial software called Front Arena[3], which is a software with a large variety of financial services where one of them is structured products.

1.1 SunGard SunGard is a leading global provider of financial software. They build sys- tems for financial trading, risk management and position control. Their system enable banks, hedge funds and other financial institutions to make critical decisions with confidence, execute their orders and follow up their positions. They make solutions independent of what asset class that is being traded, and their product takes care of the whole process from sell-side to buy-side.

A structured product in Front Arena is assembled by first creating each individual component of the structured product, for example a bond and an option as in figure 1 and 2, and then adding them to a combination instru- ment to be traded with customers, as in figure 3.

One of the problems when trading structured products this way in Front Arena is that the traders are subject to operational risks. For example if the currency of the structured product is to be changed, the trader is re- sponsible for changing the currency on all components of the structured products and the combination, hence the trader might accidentally end up having diverging currencies on the components. Due to these operational risks banks may choose other systems to sell structured products.

In 2013 SunGard implemented a new feature called DealPackage in Front Arena to reduce the operational risks. DealPackage is an application pro- gramming interface (API) that allows users of Front Arena to build struc- tured products in a more intuitive way than before possible. Common fields can be defined so that the trader can be sure that for example the curren- cies are the same for all components of the structured product at all times, leading to greatly reduced operational risk.

1 1 INTRODUCTION

Figure 1: UI to create a bond instrument in Front Arena, where the trader can define issuer, currency, rate etc.

Figure 2: UI to create an option instrument in Front Arena, where the trader can define underlying, currency, contract size etc.

2 1 INTRODUCTION

Figure 3: The combination instrument where a bond and an option has been added. In the upper part the trader can define contract currency, issuer, contract size etc. The lower part is where the trade information is entered. There are no connection between the fields in the combination and the fields in the components of the combination, so changing currency on the combination for example will not affect neither the bond nor the option.

On top of this new DealPackage API, SunGard has built support for au- tomatic UI generation within Front Arena. This enables traders to handle their structured product in one single GUI, which greatly enhances the work flow for the trader. Now there is an ambition to extend the support for dis- playing and building these structured products by making it possible to auto-generate UI’s on the web in addition to the UI support available today.

3 1 INTRODUCTION

The web tool of interest is the JavaScript-based framework AngularJS. Sun- Gard wants to know if AngularJS is a suitable choice for building a meta- data driven UI web application that can work together with their server components.

1.2 Purpose Traders have requested a web based solution where parts of the complexity of the full software Front Arena can be bypassed, yet maintaining the power of this new DealPackage API. The purpose of this thesis is to evaluate if the JavaScript-based AngularJS framework is suitable for auto-generating a web UI from meta-data and managing changes to the structured product.

1.3 Limitations These are the limitations defined for this thesis:

• SunGard is interested in evaluating AngularJS, and although there are many competitors, only AngularJS is considered. This implies that JavaScript and jQuery[4] are used. • SunGard has DealPackage already set up and working in their soft- ware. For this reason, solutions in this thesis have to work with this API in order to build the meta-data driven web UI. • Due to time limitations the main focus is on the client side of the solution, i.e. the browser. • A mock-up is built to test the functionality of AngularJS. This result is presented and discussed. There is still lots of work to be done in the back-end of the application before it will be possible to make a fully functional application.

1.4 Problem Definition The result and reflections are based on my own experiences when learn- ing and using JavaScript, jQuery and AngularJS. The questions that I will answer and discuss in this thesis are:

• Is AngularJS a good tool given the problem description? • What should be kept in mind when working with AngularJS? • In what ways are AngularJS not suitable for this particular task?

4 2 META-DATA OBJECTS

2 Meta-Data Objects

A meta-data driven UI can be used in many different domains. For this reason, a general introduction to meta-data objects, that has nothing to do with financial products, will be explained in this section. The financial products can be seen as a specific application to this general explanation. This will be the foundation from where the specific case of SunGard will begin.

Let A, B and C be building components used to construct objects. The components could be bicycle parts and the object is the components put to- gether, i.e. the bicycle. Each of these components has different attributes, these could be the diameter of the tire, material for the handlebar etc. For simplicity, imagine that these components have two attributes as illustrated in figure 4.

Components: A B C

Attributes: a1 b1 c1 a2 b2 c2

Figure 4: Three components (A,B,C) holding two attributes each.

Now say that the object is to be sold. What has to be done is to assemble these components into one single object, lets call this object ABC (built by A, B and C). The customer do not want to worry about the different components, they should see it as if it was only one single object all along, the ABC. In the case of a bicycle, the customer should not have to look for all the parts themselves to put together. Rather, they should be presented with a bicycle and some preferences to choose from. The object ABC now has six attributes as illustrated in figure 5.

Object: ABC

Attributes: a1 b2 a2 c1 b1 c2

Figure 5: The three components from figure 4 combined into an object called ABC. The object holds six attributes coming from the components A,B and C.

2.1 Variable Dependencies However, it is very likely that there are attributes that are dependent on each other. For example, if one component is the tire and another the rim,

5 2 META-DATA OBJECTS then the diameter of these two has to match each other in order for the wheel to work. It is not desirable to have to specify the size of the tire and the rim, and risking to miss changing one of them and end up with a wheel that is not working.

In the ABC example, instead of having to work with three different compo- nents, it is desirable to handle them as one object. Say that the attributes b1 and c1 are directly dependent of each other, meaning that if a modification is made to b1, the exact same modification should always be applied to c1. Then these could be combined into one single attribute in the ABC object, lets call this attribute d1.

d1 Object: ABC

Attributes: a1 b2 a2 c2 b1 c1 d1

(a) (b)

Figure 6: (a) A new attribute d1 is introduced and maps its value to b1 and c1. (b) The object ABC uses attribute d1 to make sure the value of b1 and c1 always are equal.

Now this d1 is rather an attribute of the object ABC, and this combined attribute is connected to the underlying objects B and C. A modification of d1 will now map to b1 and c1.

2.2 Meta-Data Assume for now that it is desired to display the product ABC to the customer in some kind of application that has a GUI. Lets say a GUI is built for the ABC product. But after some time it is desired to start selling XYZ and ASD etc. Then a new GUI has to be made for these products to be shown in the application. It would be better if the GUI could build itself given an object that can describe itself. To be able to do this, the object’s attributes needs information that describes them. Some meta-data is added to each of these attributes, so that each attribute contains the following: Attribute = [Name, Domain, Value].

Here Name is simply the name of the attribute, Domain is what kind of attribute it is (such as integer, double, list etc.), and Value is simply the current value of the attribute. This could of course be extended to include limitations, selection lists and so on, but for now these three will be consider.

To be able to build a GUI using this structure, the meta-data has to be

6 2 META-DATA OBJECTS translated into GUI components to display to the customer. To go from meta-data to a GUI there is a need for a method getAttributes() that returns the attributes of the object. Then it is possible to iterate over the attributes and the meta-data of each attribute as: for attribute in Object.getAttributes(): for metaData in attribute: ... Render GUI component depending on metaData ... end end

Now the application can be fed with self-describing objects and, given that the objects are described correctly, this application does not really care what is being displayed in the GUI. It could be bicycles, computers, flowers or anything else, as long as it is able to describe what name, domain and value its attributes have.

2.3 Modification In an application it is usually not enough to just be able to display the object to the user. It is also desired to interact with the object and modify its values. Similar attributes can already be combined into one attribute, so changing a value will modify the underlying components. But what if changing one attributes value affects another attribute in other ways? For example, imagine that one type of tire is only compatible with a variety of breaks, and an other type of tire is only compatible to a completely different selection of breaks. Then changing tire will affect the possible choices of breaks. Given that the changes happen without delay, this will not be a problem. Changing tire will directly affect the list of choices of breaks. However, it will be shown later in the thesis how this might be a problem if there is a delay.

7 4 FRONT ARENA - BROWSER

3 Front Arena DealPackage

DealPackage is an API for creating templates of structured products, ex- plained in section 5, in Front Arena. The process of setting up a structured product in Front Arena was earlier only possible through a multiple step process, as described in the introduction. First the instruments had to be defined and then combined into a combination trade. The operational risk of making mistakes when setting up a structured product the old way is too high for a trader which main responsibility is to set up and sell structured products.

What is described in section 2 is a general explanation of what type of API that SunGard has built with their new DealPackage. With the new DealPackage it is possible for users of Front Arena to set up a template for their structured products. The template defines what financial contracts that should be part of the package, what parameters that should be possible to modify and the relations between different components of the product. For example if two components of a structured product needs to have the same end date, these could be connected in the definition of the structured product as in figure 6(a). The resulting template of the whole structured product can then be displayed in one single UI. Front Arena comes with some already defined templates of some structured products, but the power of the DealPackage API lies in the possibility for the user to define and modify their own templates for structured products.

As of today, the logic and support for auto-generating the UI for Front Arena is already done. When a structured product has been defined as a DealPackage in Front Arena it can not only be managed programmatically, but also be displayed and managed instantly within Front Arenas GUI.

4 Front Arena - Browser

As mentioned in the introduction there is now a customer request to display and manage these structured products also on the web. The browser will have to be able to request and receive data from Front Arena’s server side. Requested data will be received in an unknown amount of time in the future making the communication asynchronous. This section will show how the communication between Front Arena and the browser is supposed to work.

4.1 PACE PACE stands for Parallel Asynchronous Capacity Engine and is developed by SunGard in the product Front Arena. In a nutshell, it is a server side solution that improves performance by the use of parallelization and the

8 4 FRONT ARENA - BROWSER ability to distribute advanced calculations.

In order for the web application to be able to request data from and send modifications to the server side, a PACE producer and a PACE consumer will be used. A simplified explanation of how these work together is that the consumer requests some task, and the producer will execute the task and notify the consumer with a result when the task has been handled. From here on the PACE producer will simply be called PACE.

4.2 Browser to PACE This part will describe the process of requesting information or manipulating data from the client side, i.e. the browser. The types of requests are for example; opening an existing structured product from the database, making a new structured product, modify a value in an open product, save the product etc. The whole process is visualized in figure 7, followed by a step- by-step explanation of the process.

Web Server PACE Browser (Java) APS (C#, Java, (JavaScript) PACE Consumer Python, C++)

Figure 7: The process of accessing the data from browser to PACE. The process starts with the browser where a request is sent to the web server. The web server communicates with the APS (ARENA PACE Server) which works as a cache memory. If the request is not found in cache, it requests the data from the PACE. After that the data is sent back to the web server to then be transmitted to the browser.

Browser - Web Server

Web Server Browser (Java) (JavaScript) PACE Consumer

In the first step, there is the web browser. It uses the programming or scripting language JavaScript to dynamically interact with the user, without the need of reloading the whole page each time it wants to react to some interaction. From the browser, different types of tasks can be requested, such as opening a reverse convertible note, saving it, or modifying it and so on. These are set up on the form: var myTask = new PaceTask(’Pace.Object.theTask’, { x : 1, y : "foo" });

9 4 FRONT ARENA - BROWSER

Where PaceTask is an JavaScript-object set up to handle requests to the web server. The constructor takes two inputs where one of them is the name of the task, and the other a JavaScript Object Notation (JSON[5])-object with the information about or input of the request. For example if the task is to modify an attribute, the JSON-object would consist of the attributes name and the value it should be set to.

When the request is then sent to the web server via a WebSocket[6] connec- tion, the browser immediately continues with other work until some kind of callback has been fired. Such callback could be for example myTask.onResult- Updated, which is fired when the web server has got the information that the object has been updated in the database. What action the browser will take depends on its implementation of the onResultUpdated function of that object, which is set up by the .

Web Server - ARENA PACE Server (APS)

Web Server (Java) APS PACE Consumer

The web server is set up in Java-code and will take the JSON-object of the request and transform it into a Protocol Buffer[8]. Protocol Buffer is basically a more compact way of storing data which is suitable for sending it over networks.

APS The ARENA PACE Server can be seen as a big cache and work load dis- tributer. If the requested data or operation has recently been requested, it will have the result of the request in memory. Then, instead of having to calculate or request the data from the database again, the APS will simply return that result to the WebSocket. In the other case where it is not found in the cache, it will send the request to the PACE.

APS - PACE

PACE APS (C#, Java, Python, C++)

In the PACE the Protocol Buffer will be translated to a suitable form of one of the programming languages C#, C++, Python or Java. After that, the request will be executed and when the result is done, the PACE will transform the data back to Protocol Buffer to be returned to the APS.

10 5 A STRUCTURED PRODUCT

APS - Web Server

Web Server (Java) APS PACE Consumer

The data is sent back to the web server which will transform the data from Protocol Buffer into JSON and call the callback methods that are affected, for example onResultUpdated, and provide it with proper inputs, such as for example a result key and the result.

Web Server - Browser

Web Server Browser (Java) (JavaScript) PACE Consumer

The browser will get the call from the callback method and take the actions defined to that callback, for example displaying the new data. Following is a section describing what type of structured product that will be sent and modified from and to the browser.

5 A Structured Product

Structured products is a broad investment category that became popular around the 1980s in the U.S. and in Europe. It is basically a contract con- taining a combination of traditional contracts sold as a package. They are investment contracts where the outcome normally depends on one or several underlying assets such as currencies, stocks, interest rates etc. The ability to combine different contracts gives the issuer the flexibility to construct a product with various risk-return-profiles that are suitable for the particular market or customer. One of the benefits with this product category com- pared to individual trades is lower transactions costs, especially for private investors.

As mentioned in the introduction, although the focus is not on the financial aspects, this meta-data driven UI will be tested with one type of structured product. This section will give the financial background to the structured product template, a reverse convertible note, that will be set up in Front Arena and later used as example when building the logic for the meta-data driven UI. As a reverse convertible note consists of a bond and a put option the first two sections will briefly describe these two financial contracts. This will be followed by an explanation of the reverse convertible note. It should

11 5 A STRUCTURED PRODUCT be kept in mind when talking about different types of instruments, such as bonds and options, that they come in many different variations and it is beyond the scope of this thesis to cover even a few of them.[9] [10]

5.1 Bond A bond can be described as a loan where a corporation or government is the issuer, and financial institutions or private persons are the investors. Cor- porations, governments and such are, as well as private persons, sometimes in need of extra money during some period of time to be able to finance projects or expand into new territories. What they can do is to issue what is called a bond. It is a contract where the issuer will receive an amount money from the investor at day zero of the contract, and the investor will get back an agreed-upon amount of money, called face value, at maturity. The face value is in most cases the same amount as the invested amount.

To compensate the investor for the risk, loss of interest etc., the issuer will in addition to pay back the face value, pay an agreed-upon rate of interest. This interest is usually payed out either annually, semi-annually or quarterly and is what is called coupons. An example of this can be seen in figure 8 where an amount of X has been invested at day zero with an interest rate , a maturity of 12 months and coupons payed out quarterly. At the time of maturity, the investor has received a total amount of X + R, where R is the rate of interest r of the face value X. In total the investor has made a profit of R from the investment.

X + R/4

R/4 R/4 R/4 0 m Time 3 m 6 m 9 m 12 m

X

Figure 8: A bond from an investor’s point of view with a face value of X, maturity of 12 months, rolling of 3 months, annual rate of r giving a coupon payout of R = rX per year. At maturity, the investor has made a total profit of R.

5.2 Put Option A put option is a contract that gives the purchaser the right, but not obli- gation, to sell an asset to an agreed-upon price at an agreed-upon time of maturity. In return, the issuer will receive a payment to cover the risk, a

12 5 A STRUCTURED PRODUCT

fixed amount of money called the sell price of the contract. That means that the purchaser’s worst case scenario is to loose the amount of the sell price if the stock would be worth more than or equal to the agreed-upon price at the time of maturity. On the other hand, if the stock would be worth less, the issuer would have to buy the stock to a price higher than the market price at the time of maturity, and thereby loose money. Of course, the underlying is not restricted to just stocks, it could as well be for example commodities such as gold, oil etc.

Sometimes when put options are traded a barrier is used. There are dif- ferent ways a barrier can be set up, with different number of barriers, but for simplicity of this thesis, only a single barrier will be considered. A down-and-in barrier, used for example in Reverse Convertible Notes, can be described as an if-statement stating ”if price of underlying goes below p percent during any time of the contract then give the issuer the right to sell underlying at the time of maturity to the agreed-upon price”. In the example it is implied that the option is an European option, meaning that it can only be exercised at maturity. There are basically three different types of scenarios that could happen with this setting. The three scenarios are displayed in figure 9-11 where the agreed-upon price is 100 and the barrier is set to 80 percent of the agreed-upon price.

In the first case, figure 9, the closing price at the time of maturity is lower than the agreed-upon price, however above the down-and-in barrier. But due to the fact that the stock at least once during the contract passed below the barrier, the purchaser has the right to sell the stock to the investor at the price of 100.

Price per share

100 Closing price (96)

80 Down & in level

Time

Figure 9: If the closing price of the stock is lower than the original price of 100, and the stock at some point during the contract has passed below the down-and-in level, the put option holder is allowed to exercise the contract.

In the second case, figure 10, the closing price is again below the agreed- upon price. But this time the stock has never passed below the barrier, so the purchaser does not have the right to sell the stock.

13 5 A STRUCTURED PRODUCT

Price per share

100 Closing price (96)

80 Down & in level

Time

Figure 10: If the stock never passes the down-and-in level during the contract, the holder of the put option is not allowed to exercise the contract. This means that even though the closing price of the stock is lower than the strike price, the holder of the put option can not sell the stocks at the strike price.

In the last case, figure 11, the closing price is above the agreed-upon price, so it does not really matter if the stock passed the barrier or not. The purchaser will of course not sell the stock to the agreed-upon price of 100 when the stocks are worth 104, and is neither obliged to do so, thereby the name; option.

Price per share

Closing price (104) 100

80 Down & in level

Time

Figure 11: If the closing price of the stock is higher than strike price it will not matter if the stock has passed below the down-and-in level or not. The holder of the put option will not exercise the contract, due to the fact that the strike price is lower than the spot price.

5.3 Reverse Convertible Note A reverse convertible note (RCN) is a type of structured product. It is a short-term investment idea which consists of a coupon-bearing bond, and a put option. The contract usually has a maturity of around 6 to 18 months and is issued by banks. It is a relatively commonly sold structured product on at least the swiss market.

At time zero, the investor pays the issuer an amount of money, say 1’000’000 CU (Currency Units), with the promise of an agreed-upon rate (usually around 10%) and to get the 1’000’000 CU back or stocks worth less than 1’000’000 CU. I.e the payout at maturity would be, ( 100000000, tˆ > T f(S ) = (1) T 100000000 ˆ K min(ST ,K), t ≤ T,

14 6 DEFINING AN RCN USING DEALPACKAGE where tˆis the point in time the underlying asset price for the first time since day zero falls below the down-and-in barrier, and T is the time of maturity. K is the agreed-upon strike price. Figure 12 shows the transactions of the contract and figure 13 shows an example of the payoff graph related to this structured product.

Issuer Investor

Time 1M CU 0 m N Put Options with total strike worth 1M CU

Bond (10%, 1Y, 6m rolling)

Coupon (50’000 CU) 6 m Coupon (50’000 CU) 12 m 1M CU or N stocks worth < 1M

Figure 12: Transactions between issuer and investor during the contract with maturity of one year and a rolling of six months. M stands for million. Profit

Down & In Underlying

0 Price of Underlying Strike at Maturity

Figure 13: The profit profile for the investor. The loss is bound to -investment + coupon. The profit is bound to the coupons.

6 Defining an RCN using DealPackage

Now that we have learned about structured products and the DealPackage framework it is time to put them together. This section will explain the pro- cess of setting up a reverse convertible note in the DealPackage framework provided by SunGard. This is a simplified version of a reverse convertible note, and I want to emphasize that the focus is not on the correctness of this structured product, but rather how a structured product template built in Front Arena, with its components, later can map to a web based meta-data driven UI.

15 6 DEFINING AN RCN USING DEALPACKAGE

The structured product that will be built will have eleven attributes, namely:

startDate The start date of the contract endDate The end date and time of the contract underlying The underlying asset to the option bondFixedRate The fixed rate of the bond optionStrikePrice The strike price of the option curr The leading currency portfolio The portfolio of the trade acquirer The acquirer of the contract status The trade status of the contract (Simulated etc.) counterparty The counter party to the contract barrier The barrier value of the option investedAm The invested amount of the contract

Table 1: Attributes used for the reverse convertible note.

These attributes are not simple variables which only holds a single value. In accordance to what is described in section 2.2 these attributes contain meta-data about how to describe themselves, as well as mapping to e.g. transformations of the data and validation of the data before storing the value etc. Here is an example of how such an attribute is defined: startDate = Object(value="2014-09-13", label="Start Date", toolTip="The start date of the Bond", objMapping="Bond.StartDate", domain="Date" )

Here label and toolTip takes a string as input, which will be the label of the control and the description shown when hovering the control in the UI. The objMapping will map the value of startDate to the bonds start date, so whenever startDate is set it will propagate to the bond’s class instance as well. The domain of the startDate is Date.

The process of when a new instance of a reverse convertible is being created will now be explained. The first thing that happens is that an initialization function (OnNew) is being called. The OnNew-function does the following:

1. Create a new instrument of type Option. 1.1. Set type to ”Put”. 1.2. Add a barrier to the option of type Down & In. 2. Create a new instrument of type Bond.

16 6 DEFINING AN RCN USING DEALPACKAGE

3. Create a combination (an object that contain instruments). 3.1. Set the default contact size to 1000000. 4. Create a new trade from the combination. 4.1. Add the option. 4.2. Add the bond. 5. Set some default values to the structured product 5.1. Set a default underlying. 5.2. Set invested amount to 1000000. 5.3. Set start day to today. 5.4. Set end day to 1 year from today. 5.5. Set a default currency. 5.6. Set a default value of the barrier 5.7. Set weights to the trades (explained below). 5.8. Set a fair fixed rate depending values above.

The weights in 5.7 are weights that will be calculated depending on the price of the underlying and so on, so that the contract will have a value matching the invested amount. The fair rate in 5.8 is then calculated depending on all these factors, especially dependent of the length of the contract and the value of the barrier. The final UI displayed in the Front Arena application can be seen in figure 14.

17 7 BUILDING A PROTOTYPE WITH ANGULARJS

Figure 14: The UI built with the DealPackage framework. The left part contains a selection of the attributes from table 1, and the right part is a payoff graph of this reverse convertible note. It is assumed that the contract size is for 1,000,000. The lower part is trading information that updates every time new prices of the underlying is available.

7 Building a Prototype with AngularJS

We have now learned about meta-data objects, structured products and how a structured product template can be defined with DealPacke, and it is time to build a web prototype. This section will go through the logic for auto-generating a UI on the web. First off is a brief overview of the final prototype built, followed by the details about the code and implementation of the prototype.

7.1 Overview of Final Prototype When first entering the index page of the web application, there are four buttons present. When clicking the New-button, a prompt dialog is shown where the user can enter what type of structured product that should be created.

18 7 BUILDING A PROTOTYPE WITH ANGULARJS

Figure 15: The prompt dialog.

A request gets sent, and when a response is received the page will instantly build the appropriate fields, and populate them with values.

Figure 16: The structured product shown on the web. This is the same layout as seen in figure 14, except the status field is removed.

As seen in figure 16, the status field has been removed. The reason is that the enum values for the status field were not possible to request from the server side at the time. The different data fields in the layout are date-time

19 7 BUILDING A PROTOTYPE WITH ANGULARJS

fields, choice list fields and floating point number fields.

Figure 17: The date-time, choice list, and floating point numbers fields

If the attribute has a tool tip it will be shown when hovering the label of the field.

Figure 18: The tool tip is shown when hovering the label.

This was a brief overview of the prototype built, now the details of the implementation will be explained, starting with the index page.

7.2 Index Page The index page of the application contains very little code. The head of the index page consists of imports of important JavaScript files. The files that are imported are presented and explained below.

20 7 BUILDING A PROTOTYPE WITH ANGULARJS

jQuery The jQuery library version 2.1.1. jQueryUI[11] A relatively new library containing some jQuery gadgets that can be used to en- hance the web page. This also contains some CSS. Pace A class to handle communication with PACE through websockets. Angular The AngularJS library. Angular Bootstrap UI[12] An Angular library containing some de- fined directives. Twitter Bootstrap CSS[13] A CSS library used for buttons and lay- out. Angular Services User defined Angular services used. Angular Controllers User defined Angular controllers used. Angular Directives User defined Angular directives used. xml2json A converter from XML to JSON, used in processing data from PACE which is received as XML.

Table 2: The index page’s imports. The necessary information about Angular services, controllers and directives will be explained later on.

The Document Object Model (DOM)[7] of the body of the page was set up on the following form:

div

div div

btn btn btn btn fa-product-general

Figure 19: A DOM tree showing the structure of the index page. A div is a container to group sections of HTML elements together.

Where the fa-product-general is an Angular directive that will be explained in section 7.4. The div above the four buttons uses a controller named ButtonController, which holds the logic of these buttons. The buttons are Open, New, Save, and Save as.

7.3 Factory: DealPackageService To encapsulate communication with the server side it is good to use an Angular service. This way, communication with server side only has to go through one single API, and if the API on the server side changes over time modifications has to be made in only one place of the web application code. The Angular service can be seen as the ”database” of the web application

21 7 BUILDING A PROTOTYPE WITH ANGULARJS holding the data of the structured product, and communicating with the server side. The service I built was called DealPackageService, and the API looks as follows:

openProduct(id) Will open a structured product with this id if found. newProduct(productType) Will open a structured product of type productType. In this case, we will only consider ”Reverse Convert- ible” as input. editProduct(attribute, value) Will set the value of attribute to value. If it does not succeed, it will reset the structured product to the last successful instance of the struc- tured product. saveProduct() Will save the instance of the struc- tured product to the database on server side. getAttributes() Returns the attributes that will be displayed in the GUI as a list in the order to be shown. resetProduct() Resets the structured product to the last successful instance. getValueByName(name) Will return the value of the attribute with the name name

Table 3: The API of the DealPackageService.

The three first methods (openProduct, newProduct, and editProduct) will send an asynchronous request to the web server. If everything goes well a response will be received later on. The response is a JSON object that will contain the following three keys:

name The name of the structured product instance. attributes A list containing all attributes for this structured product instance. In this case, all the attributes from table 1. graphCoorinates An empty list at the moment. Sometime in the future there will be an implementation containing data points in order to be able to plot the payoff graph.

Table 4: Meta-data keys for the JSON response received from PACE.

Each attribute in the attribute list will contain the following six keys:

22 7 BUILDING A PROTOTYPE WITH ANGULARJS

name The name of the attribute, e.g. ”startDate”. label The label of the attribute, e.g. ”Start Date”. type The type of the attribute, e.g. ”Object”. domain The domain of the attribute, e.g. ”date”. value The value of the attribute, e.g. ”2014-10-03”. toolTip The tool tip to be displayed when the label is hovered, e.g. ”The start date of the Bond”.

Table 5: The meta-data of each attribute.

Object is a class defined by SunGard which basically says that it is an attribute that has an object mapping, like explained in figure 6(a), and is one case where the domain has to be taken into account to figure out what type of UI component to be used for the attribute.

7.4 Service: faProductGeneral One way to auto-generate UI components in the web UI is using what is called an Angular directive. When Angular processes the DOM it will look for certain indications in the DOM. For example, in this case if Angular would find a DOM element named it would ei- ther replace or insert some new HyperText Markup Language (HTML)[14] code within that DOM element. In the example below the product-general.html will be inserted, which will be explained later on. The directive will also have a controller, which controls how the directive and its elements should behave, and what data should be accessible. The directive looks like this:

23 7 BUILDING A PROTOTYPE WITH ANGULARJS

1 app.directive( ’faProductGeneral’ , function () { 2 return { 3 restrict: ’E’ , 4 templateUrl: ’product-general.html’ , 5 scope: {} , 6 controller: function ($scope, DealPackageService) { 7 $scope.attributes= {} ; 8 $scope.service= DealPackageService; 9 $scope.$watch( ’service.getAttributes()’ , function (newVal) { 10 $scope.attributes= newVal; 11 }); 12 $scope.setAttribute= function (attr, val) { 13 DealPackageService.setAttribute(attr,val) 14 } ; 15 } 16 } ; 17 });

Listing 1: The faProductGeneral directive.

The directive’s controller will make use of the DealPackageService that was explained in section 7.3. It will be watching for changes in the getAttribute- function, and whenever the getAttribute-function returns something dif- ferent it will put the new data on the scope to make it accessible within the directive used in the HTML template. It will also put a setAttribute- function on the scope, which will call the setAttribute-function of the DealPackageService. As HTML template, the product-general.html is being used.

1

2

General

3
4
5
6 7
8 9

Listing 2: The HTML template, product-general.html, for the faProductGeneral directive.

On line 5 in listing 2 there is a built in Angular directive used called ng-repeat which is an iterative directive that will use the attributes put on the scope and loop over them, where the loop variable is called attr. For each attr the directive will insert a new Angular directive that I have called faInput. attr will be put on the the directive faInput’s scope as attribute.

24 7 BUILDING A PROTOTYPE WITH ANGULARJS

7.5 Directive: faInput The faInput directive is the main component of this thesis. In this directive lies the logic that decides which UI component that should be displayed given the meta-data of the attribute. It will be explained bit by bit, starting with which building blocks are present in this directive seen in listing 3, and then explaining each of them separately.

1 app.directive( "faInput" , 2 function ($compile, $http, $templateCache) { 3 . . . 4 return { 5 restrict: ’E’ , 6 scope: { 7 attribute: ’=’ 8 } , 9 link: linker, 10 controller: ctrl 11 } 12 })

Listing 3: Return statement of the faInput directive.

The restrict:’E’ only signalize that the directive should be an HTML element, i.e. on the form . The scope, contain- ing a two way binding to attribute, means that it will be an isolated scope containing a single attribute. The attribute, as explained in section 7.3, will contain the attributes found in table 5. The link and controller needs a little more explaining.

linker Because it is not known beforehand what type of UI component that will be used, it is not possible to use one single HTML template for a UI control. For this reason the Angular code has to be able to dynamically choose what HTML code that should be used depending on the meta-data of the attribute. Here is where a linker can be very useful. The linker gets called when Angular is processing the HTML, and making it possible to fetch some HTML code to be inserted or manipulated in the DOM element of the directive. In short, it makes it possible to render different UI components for different kinds of meta-data.

25 7 BUILDING A PROTOTYPE WITH ANGULARJS

1 app.directive( "faInput" , 2 function ($compile, $http, $templateCache) { 3 . . . 4 var l i n k e r= function (scope, element, attrs) { 5 var attrType= getType(scope.attribute.type, 6 scope.attribute.domain) 7 var l o a d e r= getTemplate(attrType) 8 9 var promise= loader.success( function (html) { 10 element.html(html) 11 }) 12 .then( function (response) { 13 element. replaceWith( 14 $compile(element.html())(scope) 15 ) 16 }) 17 } 18 . . . 19 })

Listing 4: The linker-function of the faInput directive.

Into the linker comes the scope, from which the attribute can be accessed, the element, which is the DOM element of the directive, i.e. the faInput, and the attrs which are not of interest nor importance in this case. Here getType(type,domain) will return one of three defined GUI attribute types; faFloat, faChoice or faDate. This type will be sent as argument to getTemplate(attrType), which is a function as follows:

1 app.directive( "faInput" , 2 function ($compile, $http, $templateCache) { 3 . . . 4 var getTemplate= function (type) { 5 var baseUrl= ’/angular/templates/’ 6 var templateMap= 7 { 8 faDate: ’faInputDate.html’ , 9 faFloat: ’faInputFloat.html’ , 10 faChoice: ’faInputChoice.html’ 11 } 12 13 var templateUrl= baseUrl+ templateMap[type] 14 var templateLoader= $http.get(templateUrl, 15 { cache: $templateCache }) 16 17 return templateLoader 18 } 19 . . . 20 })

Listing 5: The getTemplate-method of the faInput directive.

26 7 BUILDING A PROTOTYPE WITH ANGULARJS

The getTemplate(type) function will make an HTTP request for the correct template depending on which type is being asked for. The template is fetched from the template cache on the client side. The function returns this HTTP request object.

When the linker gets back this object it will add a success callback that will be invoked when the request has been executed successfully. In this case the callback will set the inner HTML of the faInput-element to the HTML template returned by the request. The template however will con- tain Angular expressions which Angular unfortunately is not aware that it should compile. Because of this, a manual compile has to be invoked in order to show the correct data.

ctrl The three different GUI attribute type will have one controller each. The controller ctrl is like a bridge controller that will figure out which controller that should be used, and will use Angular’s $injector-service to inject the services needed for the different controllers.

1 app.directive( "faInput" , 2 function ($compile, $http, $templateCache) { 3 . . . 4 var c t r l= function ($scope, $injector, DealPackageService) 5 { 6 var attributeType= getType($scope.attribute.type, $scope. a t t r i b u t e.domain) 7 switch (attributeType) 8 { 9 case ’faDate’ : 10 faDateCtrl($scope, DealPackageService) 11 break 12 case ’faFloat’ : 13 faFloatCtrl($scope, DealPackageService) 14 break 15 case ’faChoice’ : 16 var dataFactory= $injector.get( ’dataFactory’ ), 17 $filter= $injector.get( ’$filter’ ) 18 faChoiceCtrl($scope, $filter, DealPackageService, dataFactory) 19 break 20 } 21 } ; 22 . . . 23 })

Listing 6: The ctrl-controller of the faInput directive.

As an example, a small part of the choice list controller is shown here:

27 7 BUILDING A PROTOTYPE WITH ANGULARJS

1 app.directive( "faInput" , 2 function ($compile, $http, $templateCache) { 3 var faChoiceCtrl= function ($scope, $filter, DealPackageService, dataFactory) 4 { 5 dataFactory.get( ’../rest/acm/’+$scope.attribute.domain).then ( function (data) 6 { 7 $scope.items= $filter( ’orderBy’ )(data, ’+name’ , f a l s e ); 8 }); 9 . . . 10 } 11 . . . 12 })

Listing 7: The choice list controller of the faInput directive.

This controller will have to make an HTTP request to the server in order to get the element that will populate the choice list depending on in which do- main the attribute is in. When the result is received, the data is sorted with the $filter service, and put on the scope as items. The dataFactory service is shown here:

1 app.factory( ’dataFactory’ , function ($http) { 2 return { 3 get: function (url) { 4 return $http.get(url, 5 { 6 transformResponse: function (data) { 7 // convert the data toJSON 8 var x 2 j s= new X2JS(); 9 var j s o n= x2js. s t r 2 j s o n( data); 10 return j s o n; 11 } , 12 cache: true 13 }) 14 .then( 15 // Success 16 function (resp) { 17 return resp.data.MESSAGE.ELEMENT; 18 } , 19 // Fail 20 function (resp) { 21 console.log( ’From dataFactory: The data could not be loaded correctly’ ) 22 return null ; 23 }); 24 } 25 } ; 26 });

Listing 8: The dataFactory service.

28 8 DISCUSSION

It will make a request for data which will be received as XML. If the data has already been requested before, or if multiple requests are done for the same data, the data will be taken from the cache. The data will be transformed into JSON, and the whole HTTP request will be returned, and from there the then statement in the choice list controller will take over as soon as the request has been successfully executed.

8 Discussion

Since the result of this thesis in fact is a discussion, I have decided to name this section discussion. Over all I did not find any major issues with the AngularJS framework, but I did find some issues that I would like to discuss further. The following three topics regards the suitability of using Angu- larJS when building a meta-data driven web UI which I found during the development of the prototype.

8.1 Placement of Directive Logic In the final solution I did, there is an ng-repeat to iterate over the different attributes in the structured product.

Here fa-input refers to a custom directive named faInput. It is within this directive the business logic is placed to figure out what type of com- ponent it is and what actions that should be taken in order to display it correctly. The directive will dynamically assign a controller to the faInput- component and then load the correct HTML-template from cache and com- pile it to display the correct data. There is one controller and one HTML- template for each core UI component.

I had some problems figuring out where to put the logic when using An- gular to handle the meta-data logic. In one of my more naive approaches, I did three different directives which had their own built in controllers to handle the component. But the logic to handle this was put in the HTML- template, with the use of ng-if I was able to show the correct component at the correct place.

29 8 DISCUSSION

Although this solves the issue, it does add some problems when maintaining the application. I figured that this can not be the best place to place it, and it goes against the best practice of Angular of not putting business logic in the markup. Then I figured, I need to have some kind of directive in order to handle this matter, and as described in section 7.5, the first step was to make one directive to start with as:

This was however a lot harder than I first expected when using Angular. This is one of the key points that made me doubt that Angular was the right framework for the job. I had read and seen so many examples where Angular so beautifully solves many design problems and is able to separate markup from business logic. But in my case, when it is not really know beforehand what and how to display the structured product, this becomes harder.

8.2 Angular’s $filter-service To filter the choices by a string it is really convenient to use Angular’s built in service for filters, namely $filters. One of the most interesting points that I observed was that Angular will look through the scope to detect changes with each keystroke, and this also applies to filters. If the filter is applied naively this means that with each change or keystroke anywhere in the scope, Angular will re-filter all lists. In most cases, when there are small lists, this approach is not a problem at all, but for really large lists, as in the case of this type of application where there can be thousands of options, this approach really cripples the application and makes it really slow.

If an auto-complete field is to be created in the future, there is a need for filtering the options depending on a text field. To make this possible with Angular, what I have thought about is to not apply the filter to the text field directly. Rather, a custom function should be applied watching for changes (key strokes), and injecting the $filter-service into that function. In the function the filtering should be applied with a delay, meaning that if a change has been done to the text field, then wait say 100 milliseconds before filtering, and if another change is being applied to the text field within the time of this delay, the delay should be reset to 100 milliseconds again. This approach has the benefit that it handles the problem of having Angular filter the whole list with every change within the scope, which leads to a better user experience in the sense that it does not filter with every keystroke when using the auto-complete select fields which would appear slow.

30 9 CONCLUSION

8.3 The Absence of a Standard onChange Angular comes with a directive for input elements called onChange. If a function is assigned to the onChange directive, this function will be called every time the element’s input is changed. In most scripting languages for the web, this will be called when the input element looses focus, and usually only if the data in fact has been modified. However, in Angular, there is no such directive. This onChange directive will be called for every keystroke in this input field. In the case of this structured product, where requests are sent to server and a response is received, this approach will not be possible. The request should only be sent if the user leaves the input element or presses enter, and the input in fact has been changed. Hopefully this will be implemented in a later version of Angular, but as of this version, I had to implement a custom function that keeps track of the latest value of the input element and, when it looses focus, can validate that there has been a change and call the setAttribute-method of the DealPackageService.

9 Conclusion

To conclude, I would say that using AngularJS as framework for building this meta-data driven UI is possible, but I would not say that it is optimal. AngularJS is a rather young framework, and is still under constant improve- ment and development, and I do not see how this can be the best framework of choice at this stage. However, there might not be any other framework found to be optimal either, and a suboptimal framework might be the best option at hand.

AngularJS is a good choice in the sense that it is developed by Google, and thereby is financed, meaning that the development will most likely con- tinue for a long time, and not stop because the developers loose interest, as the case with many open source frameworks and libraries. There is a good chance that this might be one of the greater frameworks of tomorrow, and as of today, the limitations found in this thesis are all possible to work around, even though I have not been able to find any scalable way of working around them.

9.1 Further work The development of the DealPackage framework is still under progress, and it is evolving rather fast, implementing new features. Features newly imple- mented, or to be implemented are for example:

Visible The possibility for controls to be shown/hide depending on condi- tions or callbacks.

31 9 CONCLUSION

Enabled The possibility for controls to be enabled/disabled depending on conditions or callbacks.

Payoff The possibility to show graphs of the payoff.

Coloring Dynamic coloring of labels and fields, used for example to visually indicate a positive (green) or negative (red) quantity of a financial instrument.

Dialogs Displaying dialogs of various kinds and purposes. For example asking the user to adjust a date if an entered date falls on a non- business day.

SunGard decided not to proceed with AngularJS. They will be using a frame- work called Ext JS[16], developed by Sencha[17]. It is not an open source framework, but well established and has been around since 2007.

32 REFERENCES

References

[1] Google 2015, accessed 21 april 2015,

[2] SunGard 2015, accessed 21 april 2015,

[3] SunGard 2015, Front Arena, accessed 21 april 2015,

[4] The jQuery Foundation 2015, accessed 21 april 2015,

[5] Ecma International, ECMA-404 The JSON Data Interchange Standard, October 2013.

[6] I. Fette & A. Melnikov, The WebSocket Protocol, December 2011.

[7] Jeremy Keith, DOM Scripting - Web Design with JavaScript and the Document Object Model, published by Apress, 2005.

[8] Google 2015, accessed 21 april 2015,

[9] Thomas Lindauer & Ralf Seiz, Pricing (Multi-) Barrier Reverse Con- vertibles, University of St. Gallen, 2008.

[10] John C. Hull, Options, Futures, and other Derivatives, Eighth edition, published by Pearson, 2012.

[11] The jQuery Foundation 2015, accessed 21 april 2015,

[12] Angular-UI team 2015, accessed 21 april 2015,

[13] GitHub Repository 2015, accessed 21 april 2015,

[14] Phil Ballard & Michael Moncur, Teach Yourself JavaScript in 24 Hours, Fifth edition, published by Sams, 2013.

[15] Brad Green & Shyam Seshadri, AngularJS, published by O’Reilly, 2013.

[16] Sencha Inc. 2015, Ext JS, accessed 21 april 2015,

[17] Sencha Inc. 2015, accessed 21 april 2015,

33