Need Help with coding in Python

profiletimtimnbebe
csc559_-__price_generator_-_2014___3.ppt

by

Mark Goetsch

*

The Pieces

Arbitrage

Quotes

Order Matching

STP

*

*

*

*

“I enter orders[1] in an order book[2] for a specific market[3]. The orders are matched at discrete time time intervals that are controlled by a heartbeat[4]. The orders can be either buy[5] or sell[6] orders[1]. The order matcher will will check whenever a new order[1] is entered into the market. The time will be marked by the heartbeat[4]. If there is a match[7] then the order matcher will either fully match the order[8] or partially match the order[9].”

Patterns Used

Orders

Orderbook

Market

Heartbeat

Buy Order

Sell Order

Match

Full Match

Partial Match

*

*

*

Time Beat

Invalid Order

Match

Match Rules

Sell Orders

Buy Orders

Full Match

Partial Match

Orders

*

*

*

A customer authenticates[1] to a particular contract[2] which belongs to a market[3]. An order[5] is then presented to the orderbook[4] but not before checking the order[5] against the customers margin[6] which is different for every contract[2].

Gateway Analysis Pattern

Patterns Used

Authenticate

Contract

Market

Orderbook

Order

Margin

*

*

*

Authentication

Margin

Contract

Order

Market

Order Book

*

*

*

Rules that are used for every matching possibility.

*

*

*

*

*

Opening Rules =>

How are orders entered before the opening

Closing Rules =>

How are orders handled at the end

Trading Rules =>

How are orders matched

*

*

*

Limit Order

Against

Limit Order

Buy Limit in book >= incoming sell Limit

Sell Limit in book <= incoming buy Limit

Match buy quantity

Best Buy Limit

Match sell quantity

Best Sell Limit

“The incoming order is a limit order. It matches against the best limit in the book (bid price >= ask price) for the incoming limit order. The best limit in the book determines the price”

Remaining buy quantity

Remaining sell quantity

*

*

*

Three Stages to Opening the Market

Staging Period – Orders are entered and a countdown begins which calculates the Indicative Opening Price (IOP) is possible (see table below).

Non-Cancel Period – Can enter new orders but not cancel orders. The final IOP is calculated.

Opening – Orders that can be matched are matched.

Pre-Opening State of Book Conditions Settle Exists No Settle Exists
No Entries --nothing-- Settle --nothing--
Bids Only Bid > Settle Bid = Settle Bid < Settle Bid Bid Settle Bid Bid Bid
Offers Only Offer > Settle Offer = Settle Offer < Settle Settle Offer Offer Offer Offer Offer
Bids and Offers No Trades Possible Settle = Offer Settle = Offer Bid < Settle < Offer Bid = Settle Bid > Settle Offer Offer Settle Bid Bid Bid Bid Bid Bid Bid
Bids and Offers Trades Possible Bid > Offer IOP (Indicative Opening Price) IOP (Indicative Opening Price)

*

*

*

*

Order Matcher

Front End Connectivity

CME GLOBEX API

CBOEdirect API

CBOE Trade Match

CME GLOBEX

Trade Match

Trade Processing and Clearing

*

*

CMI

FIX 4.2

Ilink FIX 4.2

FIX 4.2

FIX 2.3 Express

Confirm Record

CMTA/

Allocation

Trade Correction

Confirm Record

GUS/

Allocation

Trade Correction

Firm Back Office Systems

FCM Back Office Systems

OCC

CME Clearing

*

*

*

*

95.00

95.05

95.10

95.15

95.20

95.25

Orders

Price Generator

Timer++

Limit Orders

Add Order

[Array List]

Match

[FIFO Doubly Linked List]

Matched Orders

[Queue]

[Queue]

Knowing financial theory

How to Test the Engine

Testing Engine

Trading Engine

Sample Buy and Sell Transactions

Various prices above and below the book are generated according to a random distribution.

https://www.khanacademy.org/economics-finance-domain/core-finance/derivative-securities/Black-Scholes/v/introduction-to-the-black-scholes-formula

https://www.khanacademy.org/economics-finance-domain/core-finance/derivative-securities/forward-futures-contracts/v/motivation-for-the-futures-exchange

Random Walk

public static double SimulateAsset(double s0, double mu, double sigma,double tau, double delta_t,MCG g)

{

//Purpose: Simulates an Asset Price run using a random walk and returns a final asset price.

// so = Price of the asset at time 0 (current time)

// mu = Historical Mean

// sigma = Historical Volatility (variance)

// delta_t = period of time (% of a year or a day)

// g = Random variable

double s = s0;

// Made the steps = to the number of days which is the same as daily changes.

double nSteps =tau;

for (int i=0; i < (int)nSteps; i++)

{

// s = s0 * (1 + mean + standard deviation * gaussian random number * squareRoot of the time period.

s= s * (1 + mu * delta_t + sigma * g.gaussian() * Math.sqrt(delta_t));

}

//Returns the final Price

return s;

}

Simulating an Asset as a Random Walk (or drunkards walk)

*

public static double MeasureVolatilityFromHistoric(double[] historic, double delta_t, int length)

{

// Purpose: Measures the Volatility for scaled prices.

double sum = 0;

double variance = 0;

double volatility = 0;

// length - 1 instead of length since n prices generates n-1 returns

for (int i=0; i< length -1; i++)

{

//Random variable X^2

sum = sum + Math.pow((historic[i+1]-historic[i])/historic[i],2);

}

// E[X^2] - E[X]^2

variance =

sum / (length -1) - Math.pow(MeasureMeanFromHistoric( historic, delta_t,length) * delta_t,2);

// Volatility = SquareRoot(variance/ dt) which is the standard deviation scaled for a time increment

volatility = Math.sqrt(variance/delta_t);

return volatility;

}

Measuring the Volatility Associated with the Trade

*

public static double MeasureMeanFromHistoric(double[] historic, double delta_t, int length)

{

//Purpose: Measures the mean of the scaled prices. (Scaled indicates that the level of the

// Prices is not important.

double sum = 0;

double average = 0;

double waverage = 0;

double returns = 0;

//length-1 because the scaling requires n prices to generate a sequence of n-1 scaled returns.

for (int i=0;i < (length-1); i++)

{

// Scales the returns and sums them

returns = (historic[i+1]-historic[i])/historic[i];

sum = sum + returns;

}

//computes the average of the returns

average = sum/(length-1);

// divides the average by dt so that the average applies to each time increment

waverage = average/delta_t;

return waverage;

}

Measuring the averages

*

Defining your engine

Patterns Used

Quote

Instrument, bid, offer, number, spread (bid-offer), mid (bid+offer / 2), one-way quote, two-way quote.

Board Exercise

“To understand the value of a contract, we need to understand the price of the goods being traded. Goods are often priced differently depending on whether they are bought or sold. This two-way pricing behavior can be captured by a quote[1]”

Martin Fowler, Analysis Patterns 1997

*

Patterns Used

Scenario

Instrument, Quote, Timepoint, Price, Quote, Party, Information Source, Market Indicator

Board Exercise

“In volatile markets, prices can change rapidly. Traders need to value goods against a range of possible changes. The scenario[1] puts together a combination of conditions that can act as a single state for the market for valuation. Scenarios can be complex, and we need a way to define their construction so we can use the same scenario construction at different times in a consistent manner. Scenarios are useful for any domain with complex price changes.”

Martin Fowler, Analysis Patterns 1997

*

ud Use Case Model

OrderMatcher

Order

Enter an

Order

Delete Order

Modify Order

Check Order

Validate

Order

Order

Matched

Clearing System

Account System

Margin System

«include»

«include»

«include»

«include»

«include»

95.0095.0595.1095.1595.2095.25

Orders

Price

Generator

Timer++

Limit Orders

Add OrderMatch

Matched

Orders

[Array List]

[FIFO Doubly Linked List]

[Queue]

[Queue]