Skip to content

Instantly share code, notes, and snippets.

@DhavalDalal
Last active March 1, 2022 21:08
Show Gist options
  • Save DhavalDalal/80d8f58123c1bfc6d6ce07be02f4e9ff to your computer and use it in GitHub Desktop.
Save DhavalDalal/80d8f58123c1bfc6d6ce07be02f4e9ff to your computer and use it in GitHub Desktop.
Portfolio Tracker in C#

Portfolio Tracker (C#)

  • Track individual stocks worth and
  • Net worth of the portfolio.

Pre-Requisites

  • It requires JSON.NET. You can download it from http://www.newtonsoft.com/json
  • If you are within a proxy, you can do it programmatically like this:
    System.Net.WebRequest.DefaultWebProxy = new WebProxy(ip,port); 
    
using System.Net;
using Newtonsoft.Json.Linq;
namespace Com.Tsys.Trading
{
public class NationalStockService
{
private void BypassAllCertificates()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain,error) => true;
}
public virtual double GetPrice(string ticker)
{
using (WebClient wc = new WebClient())
{
BypassAllCertificates();
var url = string.Format("https://national-stock-service.herokuapp.com/stocks/{0}", ticker);
var json = wc.DownloadString(url);
JObject stockDetails = JObject.Parse(json);
return stockDetails["price"].ToObject<double>(); }
}
}
}
using System.Collections.Generic;
namespace Com.Tsys.Trading
{
public class Portfolio
{
private NationalStockService stockService;
public Portfolio()
{
stockService = new NationalStockService();
}
public IList<double> Track(params string[] tickers)
{
IList<double> prices = new List<double>();
foreach (string ticker in tickers)
{
prices.Add(stockService.GetPrice(ticker));
}
return prices;
}
}
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Com.Tsys.Trading
{
public class PortfolioRunner
{
public static void Main(string[] args)
{
Portfolio portfolio = new Portfolio();
IList<double> prices = portfolio.Track("GOOG", "AAPL", "AMZN");
foreach (double price in prices)
{
Console.WriteLine(price);
}
}
}
}
@DhavalDalal
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment