Skip to content

Instantly share code, notes, and snippets.

@mafshin
Created December 10, 2022 07:15
Show Gist options
  • Save mafshin/8ef602a61f019d67233c326305b37f85 to your computer and use it in GitHub Desktop.
Save mafshin/8ef602a61f019d67233c326305b37f85 to your computer and use it in GitHub Desktop.
Order Book Implementation by Chat GPT
using System;
using System.Collections.Generic;
using System.Linq;
namespace Trading
{
// A class representing a single order in the order book
public class Order
{
public int Id { get; set; }
public string Side { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
public Order(int id, string side, int quantity, decimal price)
{
Id = id;
Side = side;
Quantity = quantity;
Price = price;
}
}
// A class representing the order book
public class OrderBook
{
// A dictionary to hold the orders in the book, indexed by their ID
private Dictionary<int, Order> orders = new Dictionary<int, Order>();
// Add a new order to the book
public void AddOrder(Order order)
{
orders[order.Id] = order;
}
// Cancel an order with the given ID
public void CancelOrder(int id)
{
orders.Remove(id);
}
// Get the best bid and ask prices in the order book
public (decimal? bid, decimal? ask) GetBestPrices()
{
// Find the highest bid and lowest ask prices in the book
var bid = orders.Values.Where(o => o.Side == "B").Max(o => o.Price);
var ask = orders.Values.Where(o => o.Side == "A").Min(o => o.Price);
// Return the best bid and ask prices as a tuple
return (bid, ask);
}
}
class Program
{
static void Main(string[] args)
{
// Create an order book
var book = new OrderBook();
// Add some orders to the book
book.AddOrder(new Order(1, "B", 100, 10.50m));
book.AddOrder(new Order(2, "A", 200, 10.75m));
book.AddOrder(new Order(3, "B", 300, 10.25m));
book.AddOrder(new Order(4, "A", 400, 10.80m));
// Cancel an order
book.CancelOrder(1);
// Get the best bid and ask prices in the book
var (bid, ask) = book.GetBestPrices();
// Print the best prices
Console.WriteLine($"Best bid: {bid}");
Console.WriteLine($"Best ask: {ask}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment