#twitter-follow { border: 0;position: fixed; top: 240px; left:0;} #live-support { border: 0;position: fixed; top: 370px; left:0;} #knowledge-base { border: 0;position: fixed; top: 170px; left:0;}

### How to Calculate and Display the Bid/Ask Spread on a Chart

Updated on 2014-03-29

A new function introduced in version 3.0.1 of QuantShare allows you to create custom functions/indicators based on bid/ask data.
This function cannot be accessed directly from the QuantShare programming language but we can use it in the custom functions tool to create new functions (C# based) that can be referenced later by the QuantShare programming language.

The indicator we are going to implement now, calculates the average ask price for a specific bar then subtracts it to the average bid price for that same bar. If you are displaying a one-minute chart then the average ask/bid is calculated based on all ask/bid updates that occurred during that bar.

- Select "Tools -> Create Function"

In the formula editor, type the following code:

// Get the bid vector (history) for the current symbol
// Get the bid vector (history) for the current symbol
// Check if we have bid/ask data the current symbol
if(bid.Length > 0 && ask.Length > 0)
{
// Loop through each bar (we can also replace result.Length by ask.Length or bid.Length)
for(int i=0;i<result.Length;i++)
{
// Initialize the average ask variable
{
// Loop thought each ask update that occurred within the bar i
{
}
// Calculate the average by dividing the sum by the number of ask updates
}
else
{
}

// Perform the same logic for bid
double avgBid = 0;
if(bid[i].Length > 0)
{
for(int j=0;j<bid[i].Length;j++)
{
avgBid += bid[i][j];
}
avgBid = avgBid / bid[i].Length;
}
else
{
avgBid = 0;
}

// Calculate spread and add it to result vector (this vector is returned by the function)
}
}

NB:
- The description of each instruction is included in the code.
- This indicator is available in the sharing server: Average Bid/Ask Spread

- Open a new chart
- Right click on it then select "Create New Pane"
- Right click on the new pane then select "Edit Formula"

Since the name of the custom function we created previously is "AvgBidAskSpread", we can reference it in QS programming language just by typing it. Example:

plot(a, "", colorGreen);