We'll be building a really robust application that's architected extremely nicely and is written extremely cleanly what is up my disciples if you're new to this channel my name is coding jesus if you're old to this channel my name is still coding jesus in today's video we're going to be looking at building a trading platform from scratch now what does that involve Coding jesus but what that involves will really change over the course of time but to give you a general idea what that currently involves and what i envision that looking like is a client and
a server the server acts as a matching engine that takes in orders and responds with fills if there is indeed a fill and if there is no fill it might respond with an acknowledgement now at the very Beginning guys we're going to make this simple we're going to start with a command line application for the trading client and a general server to handle all these requests slowly but surely as we progress in this series that command line trading console is going to turn into some sort of wpf application or some sort of winforms application that
we will have maybe an order ladder that we can see The trades coming in we can see kind of what's currently on the order book uh we can also submit orders that we'd like to maybe cancel orders that are currently on the order book that are ours and so that's what it's kind of going to look like over the course of time now i'm not looking to build a production tier application it's going to be able to handle a million concurrent connections Okay i'm one person exchanges have teams of hundreds of software engineers working on
that that's not really the point here the point here or the end goal is to build an application or to build a trading platform rather where you can have two to three connections maybe more maybe 10 who knows but you can have around two to three connections and you can trade alongside your friends in this little environment that you're Going to be building yourself all right that's really the goal that we're working towards now a lot of people ask me you know why c sharp they ask me questions like um you know what am i
going to get out of this and let's first answer that before we actually jump into the code because this first episode is going to be kind of setting the expectations so you guys understand what we're jumping Into before we actually write a lot of the code itself and and in fact in today's video there won't be many design decisions we're going to be going over it's primarily going to be understanding what we're getting ourselves into and then writing some code writing the frame of the actual trading engine all right guys The first thing i get
is y c sharp and there is really two ways to answer this why i like c sharp and why i don't want to use another language like c plus or python now at work i write c plus plus 50 of the time the thing is c plus plus has a very high learning curve and that's going to turn off a lot of people that just want to learn how to write this c is a strongly typed language it is a general purpose programming language It has a low barrier to entry and so i decided to
use it not only because i'm comfortable with it but because i think it will attract as many people as possible to this actual series all right now why not python people ask me why not python well i see python all over the internet and personally i'm not a fan of python the reason being is because i like a strongly typed language now i do write python sometimes At work i might read somebody's code they've written in python so i am familiar with python but i'm not as familiar with python as i am with a language
like c sharp or c plus plus okay i have my qualms with python i think python's great if you want to iterate over things quickly but in terms of robustness i'm much more comfortable with c-sharp that doesn't mean that python is not a Robust programming language it is indeed but i'm just more comfortable with c sharp all right guys another thing i want to address before we jump into the code guys is what are you going to get out of this series well you will learn how to write a order book class for example and
have a matching algorithm that works based off fifo you will understand kind of the nitty-gritty implications in terms of Order submission uh what a client should expect to get back how market data is disseminated which forms of market data are disseminated how fills are sent back to users what is contained in a fill now we won't be copying for example the cme spec entirely of course i'm one person i can't build by myself a trading engine that supports 100 000 or a million concurrent Connections okay that's not practical but the goal that we're really heading
at here guys is to have one server and have multiple clients that are all going to be connecting to the server submitting orders and the actual trader will be consuming that market data and acting on that market data to either maybe cancel an order submit a new order etc etc Now um in terms of who can be actually or who is the audience for this well obviously you're watching this if you're a coder but even if you're not a coder i think you're going to enjoy my commentary in terms of the nitty gritty inner workings
of an exchange and um you know that sort of discussion or conversation because this isn't scripted i mean i have notes Down but i'm really talking to you guys as though this is a live stream so i hope that you guys uh enjoyed that now currently it's 1 am so it's actually 12 a.m cst 1 a.m est and most of my viewers are actually in the est time zone so it's most likely 1am where you are right now and and i'm doing this at 12 a.m where i am right now because i work during the
day and i really want to make this series so i'm doing it Late so if you like it make sure to give me a thumbs up and subscribe to show that you appreciate this alrighty the last thing i want to talk about guys before we get into the code or the second last thing rather is the costs and trade-offs like i said i am one developer okay i'm one developer and i'm doing this at 12 a.m so the trading engine that i build will not be as robust as a trading engine being built by 30
developers in the cme Or ice or the new york stock exchange now of course if you're a software engineer you understand this you take this as a given but if you're not a software engineer i don't want you to come into this understand or thinking rather that i'm going to be building some massive production based uh trading engine because as one person that is nearly impossible it will take up so much time that i won't Be producing any other videos or any other content so this is going to be a trading engine that while robust
is not going to be production tier to the point where it could support a million different people trading now at the same time i'm going to be making cost benefit decisions when it comes to little things in terms of uh which type of for example api i want to use in grpc do i want to use a Unary api where i submit an order and i expect some sort of response backward i want to use a streaming based api right those little decisions are things that i'm going to be talking about throughout the series and
things that are going to be relevant for you as a developer watching this or potentially as a layman person just interested in trading now guys another thing that's important To mention is i don't have all the answers so if you see me writing a piece of code that you might have a question about or comment or maybe you think it could be done better all this code is going to be online so you can either contribute or you can ask a question or make a comment in the comment section below and hey maybe if i
think that what you said is you know really way Better than for example what i did then maybe in another video or a follow-up video i will go ahead and implement what you have suggested in replacing what i have written all right i'm not the type of developer that has a massive ego if somebody did something that's much better than what i did or has a way better direction i will go ahead and adopt that direction because i owe that to my viewers right i Owe that to my viewers to produce the best sort of
trading engine series out there all right guys and the last thing is in terms of the layout before we jump into the code i swear we're about to jump into the code before we get into the code guys i'm always a week ahead of you guys so you're going to be watching this video and i've already written the code for this video right so what i'm going To be doing is on the right side of my screen i have two monitors on the right monitor i will have my completed version for this episode and on
the left hand side i will have a completely blank in this case it's going to be a blank solution file in c sharp so i will be starting from where i previously began a week prior okay so if you guys are watching this at the second week the second You know the second video rather of this uh trading engine series i will already be on the you know writing code for the actual uh third video right so i'll be walking you through what i've previously already built okay i think that's the best way to go
about doing so it's the cleanest and quickest way and it allows me to think of the design decisions beforehand so i can explain them to you as easily As possible alrighty guys let's now jump into the code let's jus now jump into the code let's get into it alrighty here so let's see i want to share my screen with you guys i want to share my screen so i am now sharing my screen and you probably can't see me you probably can't see me and now you can see me and i'm just going to check
If you can hear me as well so like i said guys we're kind of building this plane as we're flying it so hopefully you can see me and my screen alrighty i'm pretty confident you can let me move this and adjust my screen real quick and i will put timestamps down below guys in case you just want to skip over some of these things okay so what i have in front of me is Creating a new project a new c-sharp project now visual studio it comes with c plus python and c-sharp and so this video
is not going to assume that i need to walk you through how to download visual studio okay i will include a tutorial in the description box below and it's actually quite simple so as you can see here when i open visual studio the first thing that it asks me is what you want To do i have a list of previous projects that i've worked on and i also have the option to create a new project so that's what we're going to click on to start here guys i click on it and ask me what do
i want to build well i want to build a c-sharp console application and that's actually the first thing up here c sharp console application so i'm going to click on this now Our c sharp console application we're going to write it in windows but we're going to be using dot net standard 2.1 and the server is going to be written in net core 3.1 now if you don't know what that means it simply means it's portable to linux all right so let's select this now let's actually now go ahead and give our application a name
so we will call it trading engine this is going to be the trading engine Server so we will be writing a separate project for the client this is simply the server now i'm going to go ahead and browse to where i want to save this so i will save this solution under this folder trading engine source trading engine i'm going to select that folder awesome so i'm going to call this trading engine server next okay we're going to be selecting c C sharp.net core 3.1 long term support create alrighty guys we are now creating this
project ba-bam as you can see here we have our project in front of us and this is the beginning of your journey this is your hello world journey all right guys before we begin we're going to start off by just setting some ground rules here so we're going to set our root name space our assembly namespace As well as our c sharp language version so we're going to go ahead here alrighty and we're going to do the following so i double clicked on this little cs proj file over here and i'm going to set some
parameters for us so i want the language version that we're going to be using c sharp nine c sharp nine is the latest language version of c sharp and it's a language version that i like using because i like using the latest and greatest so let's Go ahead and do that and we're going to set our root name space to trading engine dot core now you're asking you're asking yourself coding jesus what the hell did you just do i don't know what that means and that's okay i'm going to tell you what this means as
you can see when we go to program we have namespace trading engine server i don't want it to be called trading engine server i want to be called Let's call it actually trading server engine server dot core so that's going to be our root name space so let's go ahead and do this now if you're familiar with java i believe everything in java needs to be in a class um you can't just have a free function just standing in the middle of nowhere but because of c sharp nine we have the ability i believe it's
called something something entry uh single line Entry something along those lines i don't exactly remember what it's called what i'm going to do is i'm going to get rid of this whole class program thing i think it's really annoying we're just going to have this we're just going to use this namespace because this namespace will be everywhere now currently we don't actually have a file that Defines anything in this namespace so we're going to see an error but don't worry about that alrighty guys well what are we going to be using for this trading engine
well this is going to be a server-side application and we're so so we're going to be using a lot of tools that microsoft provides us in terms of both dependency injection hosting and logging now a lot of you are probably asking what are we going to be Using for logging coding jesus but we will be using microsoft's own logging library here it's on i logger library i'm not looking to write my whole login class here for you guys we want to get into the actual code we want to get into the actual body of this
so let's go ahead and add the using directives i need to access both dependency injection and hosting now if you don't know what Dependency injection is we'll get there in a second okay so let's just first add those two so using microsoft we want to use extensions dependency injection okay and we'll add those nougat packages to our c-sharp project in a second extension start hosting now you're probably asking what's a nougat package coding jesus i'm new to c sharp well if you're familiar with Python that's like the what do they call it the cheese store
and the store where you can actually go ahead and you know pip install whatever that you need so that you can import those libraries into your project alrighty guys let's see here uh they doesn't understand what what extensions is okay and we'll get to actually importing those in a second the first thing i wanted to find guys is A file okay we're gonna define a file that is going to be our app settings file this is where the configuration for our server is going to live so let's right click here on trading engine server let's
go to add let's go to new item we want to add a json app config file so let's go ahead and do a json configuration file let's just call it app settings Now i don't want to have any of these things in here we're going to define our own things in a second but guys you are going to have a very very bad time if you don't click on app settings dot here app settings here so if you don't right click on it go to properties and in this pane that opens for you down here
always copy this to the output directory all right always copy and what this is Going to do is it's going to copy it to the location where the binary of this compile or the binary is going to live which is the output of this compiled program such that when the application is executing it can access this appsettings.json file we're going to see that in just a second okeydokes guys so before we even get to the actual trading engine body or using any of these dependency injection Libraries etc let's go ahead and create our interface to
our trading engine so i'm going to go ahead and i'm using ctrl alt c it's a hotkey that i have what you can do is you can right click here go to add class and we're going to go ahead and add where is it loading loading we're going to add an interface and we're going to call it i trading engine server okay Our interface for our trading engine server as you can see here now we have our trading engine dot core i believe i called it trading server dot core so that's what it should be
called let's go ahead and add assembly name let's add that as well let's call it trading engine server.core alrighty let's just make sure these line up and let's go back here so server dot core all right this is our Interface this is what we are going to be programming our trading engine server against right so let's go ahead and now add a class called trading engine so we are going to go ahead and add a class called trading engine server now trading engine server is in this namespace and it's going to inherit from i trading
engine server now as you can see here my interface is not Public it's default internal now i don't want to get to the nitty-gritty about that but pretty much what i'm saying when i'm saying that this is not public is i'm saying i don't expect to use it in some other libraries and indeed this is not a library it's an application we were going to be adding libraries in just a second or not in a second in another video And but this is currently internal so this is what we have so far now the next
thing that i want to do guys is now i want to start making sure that trading engine server is indeed a server so it is a background service now how do i go about doing this well how i go about doing this guys is i need to now start using some of microsoft's hosting all right so i'm going to make This i'm going to make this a background service and you're probably asking coding jesus where the hell are you getting background service from service well background service is in microsoft's hosting nougat package here right so
i'm going to find and install do i want the latest version uh i believe i want 5.0 so where where the heck is this is it 5.0 or maybe i'm thinking of the wrong thing so let's go ahead and look for hosting here browse hosting yep and the latest is indeed 5.0 so let's go ahead and install that all right that is currently being installed so i need to click okay and yes i know that i'm missing background service i need to add the namespace so what i do here is control and dot that will
allow me to Place this using directive right here at the top and i'm not using any of these so let's get rid of it okay now this is going to put a constraint on our trading engine server because it inherits from background service it needs to override background service is key method and that is i believe execute async yes execute async so execute async needs to do something now anytime you have a service or you Have some sort of game engine you're going to always see this concept of a loop like a game loop right
even a server server has a server loop now my server may not need a loop but i'm going to include it regardless right just for completion sake so while our server is not cancelled so why a cancellation request is not requested we are going to do something with this actual trading engine Alrighty the next thing guys that i want to have in this actual trading engine is i want to have a logger so i want to be able to log when i do something x y or z okay now where am i going to get
this logger from well i'm going to dependency inject this logger into my trading server now what this logger is going to look like is it's going to be part of microsoft's Logging utilities or logging library or whatever you want to call it it's going to be ilogger all right and where do i get i logger well i got it from the exact same location or the exact same nougat package rather that i downloaded when i installed this hosting this background service class when i saw this hosting package so that's available and this is going to
this is a template type so it's going to Take in a a given um class so the class that i want to log is called trading engine server i'm going to call it logger and in this constructor i am simply going to have a private read-only class ilogger that's going to be of type trading engine server i'm going to call it logger all right when i get this logger what am i going to do well first of all i'm going to Make sure that it is not null and if it is null i'm going to
throw a new in uh argument null exception where the hell is this hiding where is my intelligence for this well my intellisense for this is not here because i don't have system import you're not using system so there we go using system alrighty so i'm going to throw if logger Is null all right that's going to be a nice sanity check for me now what i also want to do is i want to dependency inject the settings that i'm going to define for this training engine server as you can see here guys this is where
i'm going to be including my actual training engine server configuration and i want to dependency inject that into this trading engine server now what does that mean Well it means that i don't want to have to write code to read from this file to format it the way i want to do it i just want microsoft to take care of that for me their library to take care of that for me rather so i'm going to include i options and we'll get into what that is in a second and this is going to be of
type trading engine server configuration so i'm going to make another class here trading engine server configuration Trading engine server and i'm actually going to have it in a separate folder so i'm going to have a configuration folder so i'm going to go here add new folder trading engine server configuration alrighty so i'm going to go in here and add a new item i'm going to go ahead and add a new class so new class i will go ahead and add Trading engine server configuration alrighty now you can see something that's actually interesting so i have
a folder in here because i liked or added a folder in here because i like to be able to have a distinct understanding of what lives where so i have my data objects in some sort of data folder i have my configuration object in some sort of configuration folder as you can see here what this did was it Added a namespace it changed the namespace from dot core and it appended this dot core dot trading engine server configuration all right um what i'm actually going to do here is i don't like that this is so
long so i'm just going to have it as dot configuration alrighty so what's going to be in this trading server configuration well heck i Don't know yet we're not there yet but what i do want is i want this available to me in my trading engine server because i want this dependency injected into my actual trading engine server so i options was or microsoft extension options was installed when i installed the hosting nougat package just like the logging or the logger or the i logger class rather is made available to me when i installed That
nougat package so i will go ahead and now take advantage of this eye options by using the namespace now what is i options doing well i options is saying that we have this item and it may be null it may not be null so we might have actually uh properly configured this configuration object or maybe we haven't and that's still okay all right so It's not going to give us any sort of problems here it's just an option to have this or not have this now i'm going to be using this configuration namespace because i
need this configuration object here so i'm going to call it um config very simple and i don't want this to run off the screen so i'm going to have it like this now i also want to store this config here so what i'm going to do is I'm going to say that i actually want this configuration so i want this trading engine server configuration object and i'm going to call this config or trading engine server config rather okay now i have this eye options object here how do i get the actual configuration out of it
so what i'm going to do is i'm going to say something like trading engine Configuration service so if config.value which will actually return the value of this option is null then i want to throw but if it's not null then i want to actually take what it is so argument null exception name of config i believe this is called the null coalescing operator there's like 100 null operators um i believe that's what it's called i Will put a correction if it's not in this actual video so i don't know the actual name null coalescing blah
blah blah blah blah indexing k but what this is pretty much doing which is what's important out of this point here is that it's saying that i want this value if it's not null but if it is null then i want to do what's on the right hand side of this operator which is i want to throw an Exception because i don't want to have any null settings i want to use this settings object i want to be confident in using the settings object throughout the course of this actual presentation here alrighty guys alrighty now
we're already running into a problem but it's a problem we have a solution for see background service is a protected abstract has a protected abstract method Called execute async which we need to override in order to actually use this server now this is protected meaning i can't just call trading engine server dot whatever on the class we instantiate of trading engine server i need to make this available in a public method on trading engine server this is where we have our first method that we are going to be adding to our Interface we're going to
be adding a method called run it's going to take in a cancellation token and we're going to have it as a default value we don't need to put default here we're going to actually include it in our implementation now am i going to be explaining in this series what a task is no all right so i'm not going to be explaining what a task is because that's A whole 15 minute video alrighty so i have this trading engine server and i'm going to now actually implement this uh method run and all i'm going to really
do here is i'm going to forward task run i'm going to forward the cancellation token to execute async right this is how i'm getting that execute async to become public for me to actually call later down the road all righty Um that is perfectly fine uh task represents a long running operation now why is this giving me this problem oh well because we're not actually returning a task now we're going to return a completed task here so task dot complete a task at the end because we need to return some sort of value alrighty guys
now as you're going to see this doesn't actually need to take place I don't need a public run method i'm adding it for completion but the actual when microsoft library for hosting this server as a background service will call execute async for us okay so we don't actually need to have this method here i want to have it for completion in case you know maybe down the road we want to do something by actually calling run explicitly as opposed to having the Microsoft hosting library call execute async for us and it is able to do
so even though this method is protected alrighty guys okay the next thing we actually want to do is now focus on being able to run this trading engine server by by hosting it by having it run asynchronously asynchronously for us how are we going to do that well we are going to first build a a host builder so we are going to build A host that will host this application for us and run this application as a background service so let's go ahead and create a class called host builder or trading engine server host builder
trading engine server host builder alrighty and this is going to be a public sealed class meaning nobody can override The contents of the methods in this class and we're also going to make our trading engine server here sealed as well because we don't want anybody overriding this execute async method alrighty let's go to this host builder all right so what are we going to have here well we need a static method that returns a host for us and this host builder Is going to add this trading engine server as its hosted service so that it
can call this background service is execute async operation all right so we're going to have public static ihost and this ihost lives in a namespace that we want to use because we don't want to fully qualified what we can do if we wanted to is do something like this but that looks ugly So instead i'm going to defer to a using directive here all right so it's going to be called build trading engine server alrighty what i am going to do here is i am going to say you know i want to call host dot
create default builder what i can do is i can forward any command line arguments to this i don't need to so i'm not going to Do that dot configure services so this is where things get real real real interesting so whenever we configure a service guys and i'm not a super pro at the inner workings of this library but whenever we configure a service what we do have here is we are going to be taking in both a context in which this service will be built which will which will include um various configuration objects we
will be Able to call our actual app settings configuration objects or set them rather in our services in our service here and we're also going to have access to various services that we would like to add for example we want to add a singleton service or we like to add options or we like to add a hosted service so that's going to take the form of our context and our services and this is a lambda expression guys Okay so uh this is what this is doing so this is a lambda so we're going to be
you know taking in a context and a service a collection of services and we are going to want to do something to them in order to configure our host and add our trading engine server as our hosted service so hopefully that doesn't sound uh too confusing you'll get to look see how that looks like in a second so We want to return an instance of i host so we need to call build here at the very end but now let's look at the actual contents of this configure services call the first thing we want to
do guys is we want to start with allowing ourselves to inject the dependencies that we need to from the actual app settings file and how we're going to do that well we are going to rely on this context object Because this constant context object is going to allow us to index into our configuration which is a representation of this app settings.json file so let's take a look at that so the first thing we're going to do is we're going to start with configuration and we want to be able to add the ability to have options
in our services right so what do i mean by options well Let's go back to trading engine server as you can see here we want to be able to have an optional configuration object in here and we need to enable options in this actual um in this actual uh configuration services method or this in these actual hosts so what we're going to do is in our services we're going to go ahead and do add options And i believe this is an extension method on services so yes i need to add this using declaration up here
add these options and now what i want to do is i want to add a potential class to our configuration okay and that class is going to be this trading engine server configuration but this class is empty right we're going to flush it out soon but we want it available to us in our Actual host object in our actual background service so in order to do so we need to go ahead and configure our services to recognize that this trading engine server configuration object actually exists so we will call configure what we're going to do
with this is we're going to index into the context and what we're going to do is index now to the configuration and we are going to Get a section of the configuration what is this configuration object here well this configuration you can think of it as a representation of this app settings.json file which is empty and we want to get a section of this file so we're going to call get section this section is going to be the section called we're going to call it literally trading engine uh trading engine server Configuration and that is
in our namespace dot core dot configuration right we want to map the values in this appsettings.json file into our trading server configuration object now there's nothing in here yet but that's the next thing we're actually going to take a look at all right so do i need an extra bracket here no i don't so why is this giving me this problem here oh yes because it needs to actually take Any type we want to configure we want to configure this exact same type so that is what we are going to have here alrighty guys so
it's going a little bit off the page but i think we can live with it here now let's actually take a look at what i meant by configuring this eye options parameters so this trading engine server configuration well guys i don't want to need to write All this code to read from this file and then set the fields etc dot configure on services will do all of that for me so let's say for example that i want to add a section to this configuration and like i said guys this section is going to be called
what's it going to be called well it's going to be called name off trading engine server configuration so we're going to call it Trading engine server configuration so this is going to be called trading engine server configuration now what do i want in this configuration right we're not going to get into the nitty gritty just yet but i want to show you guys an example of how this works what i want in here is i'm eventually going to have a server that's going to be accepting requests from clients so i'm going to want to have
a trading engine server Object right so part of this configuration is i'm going to have a trading engine server settings and one of those settings is going to be a port so i'm going to have here port and let's just say for the sake of this example it's going to be port 12 000 all right so now i've kind of mapped out or laid out how my actual trading engine server configuration should look like so how Should it look like well it should have an object inside of it called trading engine server settings right that's
what i had here trading engine server settings and that inside of it is going to have a port so this is going to have a public integer called port and it's kind of a getter and a setter And this is going to be as i mentioned part of the actual trading editor configuration so we're going to have let's call this this and we're going to have a getter and a center we're going to take a look at how these get filled for us without doing any code or writing any code on our end above and
beyond the two lines of code that we wrote in this host builder okay the next thing guys i want to add is i want to add our singleton objects To this actual host so i want to register singleton objects in this dependency injection a little lambda that we have here so we're going to call we're just going to say add our singleton objects so any association so website services uh at singleton so any association with our i trading engine server should be associated with a concrete Instance of trading engine server of course there might be
other implementations of i trading engine server but if i were to add one for example and then add another services.add singleton here i trading engine server and for example i have you know coding jesus trading engine server let's just say this existed right then what this call would do Straight after the call before it so line 23 would override this the object the singleton object associated with this interface right so it would pretty much make this line totally useless there's not going to be multiple implementations of a trading engine server at least i don't foresee
there being in this series so i'm not going to need to worry about that Now i'm going to actually add the hosted service so i'm going to register the hosted service in this dependency injection container here so add hosted service it's going to be called so what we're going to do is call services.add hosted service and it's going to be the type that we want to host so this is going to be the type that that microsoft's hosting library that we have imported Here is going to rely on being or inheriting from background service this
is going to be trading engine server and guys i'm hoping as i'm talking through this video and as i'm going through this series and as i'm developing on youtube i'll be much more fluent in the way i explain things i'm hoping that i'm explaining this properly and that you guys aren't too confused just yet or aren't confused At all which is the ideal and but if i am if you i am confusing because you might might not have explained something properly make sure to leave that in the description of this video below guys or not
the description in the comment section i've been talking for way too long i'm tripping over my words all right guys so we have built our entire trading engine or the instantiation of this trading engine Rather in this one method here this will be our background service that's going to run indefinitely as a trading engine all right so how is that going to look like oh i just remembered what this is in c sharp so what this feature where i don't have to have class program public static this is called i believe a top level statement
in c sharp you can only have one top level statement so i can't have another Cs file that doesn't have any classes in it okay this is my entry point so what i'm going to do is i'm going to do trading engine host builder and i'm going to call build training engine server now i'm going to say using or using var host or engine rather equals this this is going to build my entire uh dependency injection container and hosted service for me in one line Okay so it's very clean very easy to understand what's going
on here now i'm using using here because i want to dispose of this engine when the program terminates if you're not sure what a using statement is in the context of an eye disposable object i will leave a link in the description box below you can take a look at that it's actually quite important it gets rid of managed resources That you need to get rid of so that there is no leak in resources rather the next thing i want to do guys is i want to make sure that these services that i am adding
over here to the iservice collection is available to me throughout the entire application now i don't know currently if i i'm going to need the objects that i will add to this service collection later on down the road or some in some In some sort of globally accessible class but i'm just going to add that currently in case i do need that later down the road if i need these services somewhere later down the road so i'm going to add another class here called trading engine server service provider add class trading engine server service provider
alrighty now this is going to be a a public Static class so public static class and you can read what a static class does and pretty much a static class will be instantiated at the beginning of the program or wherever it's called or whenever the program determines that it needs to actually be created so it's really not deterministic whether this is created when the program starts or whether a Method in this actual class is called and but you can read more about that simply uh online so what we're going to have here is a public
static method called i service that will return an eye service provider so we're going to have we are going to have this i service provider accessible to us throughout the entire application in case we need it somewhere because This class is static and because this member variable is static we're going to call it service provider we have a getter and a setter for it now where are we going to set this guys well we're going to set it after building this host so we're going to say trading engine service provider dot service provider equals engine
dot services guys this object this engine is now an ihost It is no longer of type trading engine server we've registered trading engine server as a service we'd like to host the main application that we'd like hosted in this host and therefore when we call build trading engine server we're not getting back our server we're getting back an object of type i host and that has this uh iservice provider attached to it so we're going to store This i service provider which is a collection of all the services that we registered right over here in
this you know public globally accessible class globally accessible static class called trading engine server service provider now what we're going to do guys is we're going to create some scope in case later down the road we're going to be adding scoped services To this trading engine you can read more about what a scope is i will link documentation below damn i need to write all this documentation that i want to link to you guys task static class i options and i'm also going to add what i just mentioned scope so creating scope which will include
what the difference between a singleton object or a scoped Object or a transient object is so what i'm going to do here is i'm going to do something like using var scope equals trading engine service provider services dot create scope you can read more about what this is doing online it creates a scope in which scope services will exist for us all right now what i'm going to do is i'm going to run our actual engine so i will say await And this is obviously asynchronous programming so i will also link a link to what
asynchronous programming is in the description box below async programming there's so many links i'm going to pick two or three for you guys in case you're interested in really diving into this if you're not familiar with c sharp so engine dot run async now i can pass in some sort of token but It takes in a default cancellation token i'm going to also talk a link to what a cancellation token is in general a cancellation token will allow you to cancel a task it will allow you to cancel a long running task that might be
done by the main thread a background thread that that's not important c sharp is going to take care of that for us we don't need to care about threads when we're talking about Async and wait and tasks so we're going to run it async whether or not that's done by the main thread or some other worker thread that's not up for that's not up for us to decide that's up for the uh that's up for c-sharp to decide right so now we're going to call configure await and because we don't care about returning after this
uh awaited call on the original context That we called this run async with and i'll probably include a link on what the heck can figure away it is if i took time to explain every single one of these things this would be like a four hour video so part of the series guys is going to be reliant on you to understand what some of this is and i will include all the resources you need to learn about it At the beginning and the earlier you learn about this stuff the more clear it will be when
i start using more of these concepts later down the road now i don't suspect that i'm ever going to need to actually create a service that is scoped i don't think i'll ever need to create that for this actual series but i'm simply adding this here to create it just for the sake of fullness if i ever do decide To go in here and say for example you know services dot scoped a scoped service right so if i ever want to whatever add like let's say i trading engine server you know for whatever reason this
is a scope service and it's not a singleton service you know now i added a scope service and i created a scope for the scope service okay but we're not going to be adding any scoped Services at least i don't think we are currently alrighty guys well we really have everything we need to run our trading engine server this trading entrance server is run is gonna run but it won't actually do anything all right it's not going to do anything because we didn't ask it to do anything in the execute async method of this trading
engine server but what i do want to show you guys as We wrap up this video is what's actually going on here so when i'm calling run async and when i'm building this host what's going on here so where exactly is trading engine server being created because obviously here we don't see anything trading engine server right this is i host this is of type you know my service provider this is of type I service scope this is of type i host so where the hell is the trading engine server being created so let's go ahead
and click here we're going to put a break point here all right you're going to see how this is being created now i'm actually before i before we actually take a look at that i'm just going to call logger here so we're going to say i logger log information we're going to pass the message to here So starting i want to say name of trading engine server and we're also going to say at the end here uh stops so we're going to say started right so this while loop is going to run just like any
game loop might run and then once we break out of this loop because we are done running this application it's terminated we've closed it Then we are going to get this stop this application alrighty now let's actually give it a run and what you're going to see is beforehand let me just talk what you want to see this configuration object will have an instance of trading engine server configuration which will be filled out for us so we didn't write any code to fill it out for us okay all that filling out all That's happening because
we in our host builder here we registered this section of the configuration so this section of the app settings.json as this object so we are registering the section as this object and by calling.configure behind the scenes it'll fill all that out for us and it will create an instance of this trading server configuration for us As an instance of eye options available to us anywhere we want to call eye options in the constructor of an object all right so let's give it a go now i'm going to run this hopefully there's no build errors here
building building building alrighty so i'm going to move this to the side a bit here i'm going to bring it back when it's important so as you can see here we have an instance of i logger it's not null So we're going to step through this with just f10 and let's check do we have a value yes we do indeed have a value what's in the value well the value is our trading engine configuration which has an object of type trading engine server settings which has a port of 1200 or 12 000. amazing magic all
right we didn't need to write any code to set the port or Whatever it took it directly from this file right here and it simply dependency injected it by using i options here so it is an optional item that we can dependency inject into any class that we want and by it being optional it doesn't actually have to have a value it can be null for example alrighty let's just click continue i'm Going to bring this back right here as you can see here the i logger call so what happened was uh as part of
building this host and calling run async on it execute async was called and therefore this line was called as you can see we have our little login here started trading engine server now i believe i can click control c and it should cancel the stopping token meaning it will cancel The running of this server and it should print stopped i believe that's what will happen i may be wrong so if i do control c here let's see what happens here so yes i did indeed click control c application is shutting down and yes application is
shutting down will cancel this stopping token so what will happen is stopping token dot cancel oh no we can can't call cancel on the Token we can call it on the cancellation source so we will have something so when this host is built it'll pass in this cancellation token where is this cancellation token coming from well it's coming from cancellation token source so there's an object called cancellation token source and what's actually going on is i'm assuming that this hosting library is storing a reference To this cancellation token source somewhere and when i do control
c it's calling token.cancel token.dispose and it's cancelling the underlying token of this token cancellation source well what is the underlying token well it is cancellation tokens token source dot token and this dot token is what's being passed into my execute Async method so when i do control and control dot c uh control plus c what's happening is while this while loops running a call to dot cancel on the cancellation token source is being called that cancels the token so this token is returning a true for is cancellation requested and this while loop is therefore ending
this while loop is Ending and this dot log information is being called and it call and it writes to the console stopped trading engine server as you can see here we have that line right here stopped trading engine server alrighty guys so we have built our trading server as a background service using microsoft's hosting library we have logging working already we are Dependency injecting uh this you know configuration into the actual training engine server as an eye optional and everything is fine and dandy we're gonna stop here guys i believe i'm half an hour in
or more hopefully you've enjoyed this introduction you've enjoyed kind of me running through what you can expect with this series If you have any questions guys make sure to leave it in the comment section below and guys it's 1am here so please give me a like and subscribe if you have enjoyed this content i do enjoy making this for you guys and i'm excited to see where this develops i hope this will be a long running series we'll be building on this application we'll be going back and forth maybe in the comment section we'll be
building a Really robust application that's architected extremely nicely and is written extremely cleanly if you guys want to support this channel i have a patreon link in the description box below you can also become a channel member by clicking join you should see it right below the video so thanks for watching this video guys i really appreciate it make sure to share it far and wide cheers