Click here to Skip to main content
15,885,872 members
Articles / Programming Languages / C#

How to Place Order via FIX Message?

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
1 Apr 2016CPOL6 min read 19K   3   2   4
Walk-through implementation to “Place an Order on via FIX message channel”

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 Establish connection with broker/exchange Fix End points, Consume Market Feeds, etc.

You can read my previous posts about the topics mentioned above:

This post will cover the following topics:

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

Order Types

  • Market Order: This is a basic type of order; wherein, trader buys or sells 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 executes when specific price triggers. For example, if the market price is 150, a trader places a buy stop order with a price of 60, 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.

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 canceled after expiry.

Traders can specify the 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 canceled.
  • FOK (Fill or Kill): Either order would be fully filled or canceled. This type of order would not allow any partial fills.

FIX Order Workflow

OrderFlow

What is Execution Report?

It is FIX message which broker side sent in response to order request. Broker side relays status of an order, and there can be multiple Execution Reports for a single order. Execution reports can have the 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
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 executions
New Outstanding order with no executions
Rejected 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 Description
ClOrderId 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, Limit
Price 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 InstrumentID
LastPx Orderd executed on this price
LastQty Traded quantity in each fill
LeavesQty Remaining Qty of an order. It is zero when order is fully filled
CumQty Total Traded Quantity

Implementation

Technology/Tools Used

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 make 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.

Connect

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

Placing Order

Fix 4.4 supports “Single Order – New <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.

OrderTicket

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

Code

C#
// hard-coded fields
QuickFix.Fields.HandlInst fHandlInst = new QuickFix.Fields.HandlInst
(QuickFix.Fields.HandlInst.AUTOMATED_EXECUTION_ORDER_PRIVATE);
// from params
QuickFix.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);
if (orderType == OrderType.Limit)
    nos.Price = new QuickFix.Fields.Price(price);

Process Execution Report

ExecutionReport

C#
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 processes messages from FIX clients and sends response back to them.

Executor Class

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

C#
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.

C#
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());
 }

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 a standard way of handling FIX messages; however, implementation can vary from broker to broker.

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

Source Code

The source code can be downloaded from github repository. Executable files are placed in a separate folder.

Image 5 Image 6

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Saxo Bank A/S
Denmark Denmark
• Solution Architect /Principle Lead Developer with 12 years of IT experience with more emphasize on Capital Domain and Investment banking domain.
• Strong experience in Continuous Integration, Delivery and DevOps solutions.
• Strong experience in drafting solutions, stakeholder communications and risk management.
• Proved strong coding and designing skills with agile approaches (TDD, XP framework, Pair Programming).
• Delivered many projects with involvement from inception to delivery phase.
• Strong experience in high performance, multithreaded, low latency applications.
• Ability to communicate with the business and technical stake holders effectively.
• Have extensive experience in Capital Market Domain: Front Office & BackOffice (Algorithm Trading tools, messaging framework, Enterprise bus, integration of FIX APIs and many trading APIs).
• Functional knowledge of Portfolio/Wealth Management, Equities, Fixed Income, Derivatives, Forex.
• Practical knowledge of building and practicing agile delivery methodologies (SCRUM, TDD, Kanban).

Technical Skills

• Architectural: Solution Design, Architectural Presentations (Logical, Component, Physical, UML diagrams)
• Languages: C#, C++
• Server Technologies: WCF, Web API,
• Middle Ware: ActiveMQ, RabbitMQ, Enterprise Service Bus
• UI Technologies: Winforms and WPF
• Web Technologies: Asp.Net Mvc, KnockOutJS, JQuery, Advance Java Scripts Concepts
• Databases: Sql Server 2008 +, MySQL
• Tools/Frameworks: TFS, SVN, NUnit, Rhino Mocks, Unity, NAnt, QuickFix/n, Nhibernate, LINQ, JIRA,

Functional Skills

• Wealth Management System, Trade Life Cycle, Trading Components and their integrations
• Working knowledge of Stocks, Bonds, CFDs,Forex, Futures and Options
• Pricing Systems, Market Data Management,
• BackOffice Processes : Settlement Processes, Netting, Tax, Commissions, Corporate Actions Handling,
• Reporting Solutions : OLTP and OLAP Data model designing
• FIX Engine implementation and integration

Comments and Discussions

 
QuestionQuickfix rate in mvc application Pin
Member 117176576-Aug-18 20:30
Member 117176576-Aug-18 20:30 
Generalmy vote of 5 Pin
Southmountain2-Apr-16 10:13
Southmountain2-Apr-16 10:13 
GeneralRe: my vote of 5 Pin
Neeraj Kaushik19804-Apr-16 7:07
Neeraj Kaushik19804-Apr-16 7:07 
GeneralRe: my vote of 5 Pin
Neeraj Kaushik19804-Apr-16 7:10
Neeraj Kaushik19804-Apr-16 7:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.