how to place orders through fix message

10
How to place Order via FIX message? Purpose The purpose of this post is to walk-through implementation to “Place an Order on via FIX message channel”. In my previous posts, I have shown basic implementation of FIX messages like connect/disconnect and Consume Market Feeds. You can read previous posts to know more about FIX message implementation. Fix Message Implementation using QuickFix Consume Market feeds on FIX Protocol from Fix enabled broker/exchange using QuickFix/n Topics to be covered I will cover following topics with example code in this post: Different types of Orders. Orders Validity Order workflow. Place Order What is Execution Report? Process Execution Report. Order Types: Market Order: This is basic type of order; wherein, trader buy or sell at market price without specifying desired buy or sell price. Limit Order: It is an order to buy or sell at a specified price. A limit buy order can execute at specified buy price or lower. A limit sell order can execute at specified price or higher. In this order, trader has to specify price before placing an order. Stop Order: It is similar to market order which execute when specific price triggers. For example, if the market price is

Upload: neeraj-kaushik

Post on 12-Apr-2017

151 views

Category:

Software


3 download

TRANSCRIPT

Page 1: How to place orders through FIX Message

How to place Order via FIX message?

Purpose

The purpose of this post is to walk-through implementation to “Place an Order on via FIX message channel”.

In my previous posts, I have shown basic implementation of FIX messages like connect/disconnect and Consume Market Feeds.

You can read previous posts to know more about FIX message implementation.

Fix Message Implementation using QuickFix Consume Market feeds on FIX Protocol from Fix enabled broker/exchange using QuickFix/n

Topics to be covered

I will cover following topics with example code in this post:

Different types of Orders. Orders Validity Order workflow. Place Order What is Execution Report? Process Execution Report.

Order Types:

Market Order: This is basic type of order; wherein, trader buy or sell at market price without specifying desired buy or sell price.

Limit Order: It is an order to buy or sell at a specified price. A limit buy order can execute at specified buy price or lower. A limit sell order can execute at specified price or higher. In this order, trader has to specify price before placing an order.

Stop Order: It is similar to market order which execute when specific price triggers. For example, if the market price is $150, a trader places a buy stop order with a price of $160, when price would move 160 or above, this order will become market order and execute at best available price. This type order can be used for Take-Profit and Stop-Loss.

Stop Limit Order: This is a combination of stop order and limit order, like stop order, it is only processed if the market reaches a specific price, but it is executed limit order, therefore it will only get filled at the chosen or a better price. For example, if the current price is 150, a trader might place a buy stop limit order with a price of 160. If the market trades at 160 or above, this order will execute as limit order to get filled at 160. However, it might happen that this order may not fill if there is not depth available.

Page 2: How to place orders through FIX Message

Execution Report <8> (Pending New)

Execution Report <8> (New)

Execution Report <8> (Partially Fill / Filled)

Single Order –New <D>

Detail description of each order types can be read on investopedia.

Order Validity

In addition to specify order types, trades can also specify validity of an order for how long particular order is valid. Order would be cancelled after expiry.

Traders can specify following validity of an order:

Day: Order is only valid till end of the market session. GTC (Good till Cancel): Order is valid till trader manually cancels it. However, brokers might

have max timeline to cancel orders automatically if order is beyond certain days, typically 30, 60 or 90 days.

GTD (Good till Date): Order is valid till end of the market session of specified date mention in this order.

IOC (Immediate or Cancel): Order should be partially/filled immediately while placing order; otherwise, it would be cancelled.

FOK (Fill or Kill): Either order would be fully filled or cancelled. This type of order would not allow any partial fills.

FIX Order workflow (Fills)

What is Execution Report?

It is FIX message which broker side sent for an order. Broker side relays status of an order, and there can be multiple Execution Reports for a single order message. Execution reports can have following status and information:

Order Status

Order Status

Description

Done for Day

Order did not fully or partially filled; no further executions are pending for the trading day.

Fix Client FIX Broker Side

Page 3: How to place orders through FIX Message

Filled Order completely filled; no remaining quantity.Suspended Order has been placed in suspended state at the request of the client.Canceled Canceled order with or without executions.Expired Order has been canceled in broker's system due to order validity (Time In Force)

instructions.Partially Filled

Outstanding order with executions and remaining quantity.

Replaced Replaced order with or without executionsNew Outstanding order with no executionsRejected Order has been rejected by broker. NOTE: An order can be rejected subsequent to order

acknowledgment, i.e. an order can pass from New to Rejected status.Pending New

Order has been received by brokers system but not yet accepted for execution. An execution message with this status will only be sent in response to a Status Request message.

Accepted Order has been received and is being evaluated for pricing.

Important Fields

Field DescriptionClOrderId Unique key of an order requested by client.

OrderId Unique key generated by broker/exchange for an order.

ExecID Unique key of each execution report message.

Account Account number on which order was placed.

OrdType Type of Order e.g. Market , LimitPrice Ordered Price specified to buy or sell

Side Side of an order (buy or Sell)Symbol Symbol name of instrument on which order placed.

SecurityId InstrumentIDLastPx Orderd executed on this price.LastQty Traded quantity in each fillLeavesQty Remaining Qty of an order. It is zero when order is fully filled.CumQty Total Traded Quantity

Technology/Tools Used:

Examples are written in C#.

Fix message parser Library: QuickFix/n

Online Fix Log tool: http://FixHawk.Terebrum.com

Page 4: How to place orders through FIX Message

Implementation

I have downloaded FIX UI Demo code from QuickFix/n Git hub location to save some time. This sample code already has connection and order routines. I will do further changes to show various use cases of order work flow with FIX 4.4 specification. I have also added FIXAcceptor component to process FIX messages locally.

Connect with FIX Acceptor

Click on connect button. Fix Initiator will send Logon message, which will be received by FIX acceptor and acknowledge it in reverse sending logon message.

Application is ready to place an order after connection is established.

Placing Order

Fix 4.4 supports “NewOrderSingle (D)” to place any single order by the client. You can find standard specification this message on any fix dictionary available online. However, message specification might differ from broker to broker.

You can see standard FIX messages/tags specification on FIXIMATE .

Page 5: How to place orders through FIX Message

Create an object of “NewOrderSingle” class and set values to properties of class:

Code:

// hard-coded fieldsQuickFix.Fields.HandlInst fHandlInst = new QuickFix.Fields.HandlInst(QuickFix.Fields.HandlInst.AUTOMATED_EXECUTION_ORDER_PRIVATE);

// from paramsQuickFix.Fields.OrdType fOrdType = FixEnumTranslator.ToField(orderType);QuickFix.Fields.Side fSide = FixEnumTranslator.ToField(side);QuickFix.Fields.Symbol fSymbol = new QuickFix.Fields.Symbol(symbol);QuickFix.Fields.TransactTime fTransactTime = new QuickFix.Fields.TransactTime(DateTime.Now);

QuickFix.Fields.ClOrdID fClOrdID = GenerateClOrdID();

QuickFix.FIX44.NewOrderSingle nos = new QuickFix.FIX44.NewOrderSingle( fClOrdID, fSymbol, fSide, fTransactTime, fOrdType);

nos.HandlInst = fHandlInst; nos.OrderQty = new QuickFix.Fields.OrderQty(orderQty); nos.TimeInForce = FixEnumTranslator.ToField(tif);

Page 6: How to place orders through FIX Message

if (orderType == OrderType.Limit) nos.Price = new QuickFix.Fields.Price(price);

Process Execution Report

public void HandleExecutionReport(QuickFix.FIX44.ExecutionReport msg) {

string execId = msg.ExecID.Obj; string execType = FixEnumTranslator.Translate(msg.ExecType);

Trace.WriteLine("EVM: Handling ExecutionReport: " + execId + " / " + execType);

ExecutionRecord exRec = new ExecutionRecord( msg.ExecID.Obj, msg.OrderID.Obj, string.Empty, execType, msg.Symbol.Obj, FixEnumTranslator.Translate(msg.Side));

exRec.LeavesQty = msg.LeavesQty.getValue(); exRec.TotalFilledQty = msg.CumQty.getValue(); exRec.LastQty = msg.LastQty.getValue(); }

FIX Acceptor

This is server side component which process messages from FIX clients and send response back to them.

Executor Class

Page 7: How to place orders through FIX Message

This class is getting various methods callbacks once received FIX message from FIX Client.

public void OnMessage(QuickFix.FIX44.NewOrderSingle n, SessionID s)

This method will be called every time when “NewOrderSingle” message received.

I am simulating different status of an execution report. I have added 1 sec sleep time between each status change and can be clearly seen in UI.

public void OnMessage(QuickFix.FIX44.NewOrderSingle n, SessionID s) { Symbol symbol = n.Symbol; Side side = n.Side; OrdType ordType = n.OrdType; OrderQty orderQty = n.OrderQty; Price price = new Price(DEFAULT_MARKET_PRICE); ClOrdID clOrdID = n.ClOrdID;

switch (ordType.getValue()) { case OrdType.LIMIT: price = n.Price; if (price.Obj == 0) throw new IncorrectTagValue(price.Tag); break; case OrdType.MARKET: break; default: throw new IncorrectTagValue(ordType.Tag); }

// Send Status New SendExecution(s, OrdStatus.NEW, ExecType.NEW, n, n.OrderQty.getValue(), 0, 0, 0, 0); Thread.Sleep(1000);

// Send Status Partially Filled decimal filledQty = Math.Abs(Math.Round(n.OrderQty.getValue() / 4, 2)); decimal cumQty = filledQty; SendExecution(s, OrdStatus.PARTIALLY_FILLED, ExecType.PARTIAL_FILL, n, filledQty, filledQty, price.getValue(), filledQty, price.getValue()); Thread.Sleep(1000);

// Send Status Partially Filled filledQty = Math.Abs(Math.Round(n.OrderQty.getValue() / 4, 2)); cumQty += filledQty; SendExecution(s, OrdStatus.PARTIALLY_FILLED, ExecType.PARTIAL_FILL, n, n.OrderQty.getValue() - cumQty, cumQty, price.getValue(), filledQty, price.getValue()); Thread.Sleep(1000);

// Send Status Fully Filled filledQty = n.OrderQty.getValue() - cumQty; cumQty += filledQty; SendExecution(s, OrdStatus.FILLED, ExecType.FILL, n, 0, cumQty, price.getValue(), filledQty, price.getValue()); }

Page 8: How to place orders through FIX Message

private void SendExecution(SessionID s, char ordStatus, char execType, QuickFix.FIX44.NewOrderSingle n, decimal leavesQty, decimal cumQty, decimal avgPx, decimal lastQty, decimal lastPrice) {

QuickFix.FIX44.ExecutionReport exReport = new QuickFix.FIX44.ExecutionReport( new OrderID(GenOrderID()), new ExecID(GenExecID()), new ExecType(execType), new OrdStatus(ordStatus), n.Symbol, //shouldn't be here? n.Side, new LeavesQty(leavesQty), new CumQty(cumQty), new AvgPx(avgPx));

exReport.ClOrdID = new ClOrdID(n.ClOrdID.getValue()); exReport.Set(new LastQty(lastQty)); exReport.Set(new LastPx(lastPrice));

if (n.IsSetAccount()) exReport.SetField(n.Account);

try { Session.SendToTarget(exReport, s); } catch (SessionNotFound ex) { Console.WriteLine("==session not found exception!=="); Console.WriteLine(ex.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }

This post exhibits standard way of handling FIX messages; however, implementation can vary from broker to broker.

I hope, this post will give you good understanding of how order can be placed via FIX channel. I will cover order cancel and replace scenario in next post.

Source Code

Github Downloadable Zip file