All posts by Neeraj Kaushik

Code Snippet: string split in c++ (c syntax)

Below code snippet useful while splitting string (char*) .


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

int split (const char *str, char c, char ***arr)
 int count = 1;
 int token_len = 1;
 int i = 0;
 char *p;
 char *t;

 p = str;
 while (*p != '\0')
 if (*p == c)

 *arr = (char**) malloc(sizeof(char*) * count);
 if (*arr == NULL)

 p = str;
 while (*p != '\0')
 if (*p == c)
 (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
 if ((*arr)[i] == NULL)

 token_len = 0;
 (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
 if ((*arr)[i] == NULL)

 i = 0;
 p = str;
 t = ((*arr)[i]);
 while (*p != '\0')
 if (*p != c && *p != '\0')
 *t = *p;
 *t = '\0';
 t = ((*arr)[i]);
 return count;

int main(void) {
 char* strToSplit ="REPLY id, login, cmd, volume, symbol, price, bid/ask, rate-id, status, message";
 int i;
 int c = 0;
 char **splittedarr = NULL;
 c = split(strToSplit, ',', ;&splittedarr)

 printf("found %d occurrence.\n", c);

 for (i = 0; i < c; i++)
 printf("string #%d:%s\n", i, splittedarr[i]);
 return 0;

found 10 occurence.
string #0:REPLY id
string #1: login
string #2: cmd
string #3: volume
string #4: symbol
string #5: price
string #6: bid/ask
string #7: rate-id
string #8: status
string #9: message

How to place Order via FIX message?


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 topics mentioned above:

This post will cover 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 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 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 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







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


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










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


// 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






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,                    

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

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);
 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);
 // 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());

// 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());

// 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?
 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())

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

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

Source code can be downloaded from github repository. Executable files are placed in separate folder.


How to link reference libraries in git repository?

I have been looking into solution that how can I link my pre-compiled dlls into different projects in git repositories, and, I don’t want to copy dependencies code always in each repository. 



This can be achieved by creating Git sub-module in repository where you want to use it.

Following steps need to be done:


Step 1: Go on top level directory where sub module needs to link:


$ cd <local path of git repo> 

cd c:/bitbucket/mylocalrepository 

Step 2: Create submodule in repository:

git submodule add path_to_repo path_where_you_want_it
$git submodule add http:/githubrepo/repository.git Repositories

This will create submodule in lib folder of my local repository.

When you want to update to a newer version of one of the libraries, cd into the submodule and send pull request:

cd Repositories
git pull

Troubleshooting: Windows 10 stuck at log in screen after upgrade

Last night, I upgraded my windows 7 to windows 10 on my desktop. Everything was going smooth, but after restarting machine, login screen was stuck when click on Next button (at right bottom). There was no error message pop-up and computer was restarting after 10-15 minutes. This was weird behavior and there was no clue, what was going behind the scene.

IMG-20160109-WA0001 [3564180]

After searching on google, I found a discussion forum, where somebody suggested click “Next” button from keyboard only, which didn’t work for me. Finally, another suggestion about disabling WiFi adapter and restart the machine worked for me.

I removed USB WiFi adaptor and after click on Next button, it continues.

If you end up with similar situation, then it is worthwhile to try this trick.

Screen after Next buttonWP_20160109_002 [3564192]


Forum link: my-windows-10-update-stuck-welcome-back-screen-how-can-i-fix


NoSql (It’s “Not only SQL” not “No to Sql”)

This is my first post on NoSql database technologies. There have been drastic changes in database technologies over the few years. Increase in user’s requests, high availability of applications, real time performance forced to think on different database technologies. We have traditional RDBMS, memory and NoSql databases available in market to suffice particular business needs. Here I’ll illustrate some of key aspects of NoSql databases like what is NoSql, why we need it, advantages and disadvantages of NoSql.

What is NoSql Movement?

It’s a different way of thinking in database technologies. It is unlike relational database management system where we have tables, procedures, functions, normalization concepts. NoSql databases are not built primarily on tables and don’t use sql for manipulation or querying database.

NoSql databases have specific purpose to achieve, that means NoSql database might not support all the features like in relational databases.

NoSql databases are based on CAP Theorem.

  • Consistency: Most of the applications or services attempt to provide strong consistent data. Interactions with applications/services are expected to behave in transactional manner ie. Operation should be atomic (succeed or failure entirely), uncommitted transactions should be isolated from each other and transaction once committed should be permanent.
  • Availability: Load on services /applications are increasing and eventually services should be highly available to users. Every request should be succeed.
  • Partition tolerant: Your services should provide some amount of fault tolerance in case of crash, failure or heavy load. It is important that in case of these circumstances your services should still perform as expected. Partition tolerant is one of desirable property of service. Services can serve request from multiple nodes

Why NoSql?

Since NoSql databases are using for specific purpose. They are normally using for huge data where performance matters. Relational database systems are hard to scale out in case of write operation. We can load balance database servers by replicating on multiple servers, in this case read operation can be load balance but write operation needs consistency across multiple servers. Writes can be scaled only by partitioning the data. This affects reads as distributed joins are usually slow and hard to implement. We can support increase in no. of users or requests by scaling up relational databases which means we need more hardware support, licensing, increase in costs etc.

Relational databases are not good option on heavy load which are doing read and write operations simultaneously like Facebook, Google, Amazon, Twitter etc.

A NoSQL implementation, on the other hand, can scale out, i.e. distribute the database load across more servers.



Common characteristic in NoSql databases

· Aggregating (supported by column databases): Aggregation usage to calculate aggregated values like Count, Max, Avg, Min etc. Some of NoSql provides support for aggregation framework which have inbuilt aggregation of values. Approach in column databases is to store values in columns instead rows (de-normalized data). This kind of data mainly used in data analytics and business intelligence. Google’s BigTable and Apache’s Cassandra supports some feature of column databases.

· Relationships (support by graph databases): A graph database uses graph structures with nodes, edges and properties. Every element contains a direct pointer to adjacent element; in this case it doesn’t need to lookup indexes or scanning whole data. Graph databases are mostly use in relational or social data where elements are connected. Eg. Neo4j, BigData, OrientDB.



Source: wikipaedia


· Document based. Document databases are considered by many as the next logical step from simple key-/value-stores to slightly more complex and meaningful data structures as they at least allow encapsulating key-/value-pairs in documents. Eg. CouchDb, MongoDb.

Mapping of document based db vs relational db


Document Based Databases Relational databases
Collections Table
Document Row


· Key- Value Store: Values are stored as simply key-value pairs. Values only stored like blob object and doesn’t care about data content. Eg. Dynamo DB, LevelDB, RaptorDB.

· Databases Scale out: When the load increases on databases, database administrators were scaling up tradition databases by increasing hardware, buying bigger databases- instead of scale out i.e. distributing databases on multiple nodes /servers to balance load. Because of increase in transactions rates and availability requirements and availability of databases on cloud or virtual machine, scaling out is not economic pain in increasing cost anymore.

On the other hand, NoSql databases can scale out by distributing on multiple servers. NoSQL databases typically use clusters of cheap commodity servers to manage the exploding and transaction volumes.  The result is that the cost per gigabyte or transaction/second for NoSQL can be many times less than the cost for RDBMS, allowing you to store and process more data at a much lower price;

Now question here is why scaling out in RDBMS is hard to implement. Traditional databases support ACID properties that guarantee that database transactions are processed reliably. A transaction can have write operations for multiple records, so to keep consistency across multiple nodes is slow and complex process, because multiple servers would need to communicate back and forth to keep data integrity and synchronize transactions while preventing deadlock. On the other hand NoSql databases supports single record transaction and data is partitioned on multiple nodes to process transactions fast.

· Auto Sharding (Elasticity): NoSql databases support automatic data sharding (horizontal partitioning of data), where database breaks down into smaller chunks (called shard) and can be shared across distributed servers or cluster. This feature provides faster responses to transactions and data requests.


· Data Replication: Most of NoSql supports data-replication like relational databases to support same data-availability across distributed servers.


· No schema required (Flexible data model): Data can be inserted in a NoSQL DB without first defining a rigid database schema. The format of the data being inserted can be changed at any time, without application disruption. This provides greater application flexibility, which ultimately delivers significant business flexibility.


· Caching: Most of NoSql databases supports integrated caching to support low latency and high throughput. This behavior is contrast with traditional database management systems where it needs separate configuration or development to support.

Challenges of No-SQL

Till now we have seen significant advantages of NoSql over RDBMS, however there are many challenges to implement NoSql.

Maturity: Most of the NoSql databases are in open source or in pre-production stage. In this case it might be risk to adopt these databases on enterprise level. For small business or use case it might be better to consider. On the other hand RDBMS databases are matured, providing many features and having good documentations or resources.

Support: Most of RDBMS are not open source that means they come with commitment and assurance in case of failure. They are reliable products and properly tested. Most of NoSql databases are open source and not widely adopted by organizations. It is very hard to get effective support from open sources databases. Some of NoSql databases created by small startups for specific needs, not for global reach.

Tools: RDBMS databases have lot of tools to monitor databases, queries analyzing, optimizations, performance profiling, analytics and Business Intelligence. Objective of NoSql databases are to minimize use of admin tools which has not achieved fully yet, still there are certain things which need skills and tools to monitor database activities.

When to consider NoSql

Following are some of indicators you can consider while choosing NoSql database for your application:

· If your application needs high performance databases.

· Need less or zero administration of databases.

· You want flexible data model. Minor of major changes should not impact whole system.

· Application that needs less complex transactions.

· High availability.

· Not or less consideration on Business Intelligence and analytics.






Enhanced by Zemanta

General tips: How to run Visual Studio as administrator always

Some times it is needed to run visual studio as administrator for system level activities like if you want to setup IIS virtual directory in your visual studio project, To setup IIS settings etc.

If you want to run visual studio as administrator once, you can right click devenv.exe and select “Run As Administrator”.

But sometimes there are requirement to run visual studio always as admin then you can set privilege level to administrator. Here are the steps:

Step 1 : Goto to executable of Visual studio IDE in “C:Program Files(x86)Microsoft Visual Studio 9.0Common7IDE”, Right click on devenv.exe -> Properties -> Compatibility-> And Select “Run as Administrator” check box.

You will also need to setup for visual studio launcher.

Step 2: Go to executable of Visual Studio Launcher on “C:Program Files (x86)Common Filesmicrosoft sharedMSEnvVsLauncher.exe” and follow same steps like step 1.

Colorize negative number using jquery in html table

Recently I was working on creating reports for clients on web portal. We are developing web portabl in MVC3 and using jquery utility functions.

One of the UI requirement was to colorize negative numbers. I can implement in server side in chtml pages but it would not be generic for all pages. So I decided to use jquery functions to do this task.

This is my html page:

<table class=”list”>
<td class=”right”>Amount</td>
<td class=”right”>-5.156</td>
<td class=”right”>-8.25</td>

<td class=”right”>55.45</td>

Date Amount
2012-05-01 -5.156
2012-05-01 -8.25
2012-05-01 55.45

Java Script
On Dom Ready


$(“td.right”).filter(function() {
return $.trim($(this).text()).indexOf(“-“) == 0;


border: 1px solid;
border: 1px solid;

Jquery filter function applied on td element which has class name “right”. this function find index of ‘-‘ and if it on first place it will return true. In case of true, css class “negative” will be applied to td tag.

we can also use contains functions to applied color.


Problem with this approach is it will apply negative class to any value which contains ‘-‘ on any place.

You can see live example at JFiddle.