Friday, March 10, 2017

DIY Game Financial System Part 1: Intro and Accounts

picture of commerce on river banks in the evening

I'm quite interested in finance as can be seen on my other blog dreamstateliving, and thus I decided to start working on a small but powerful in game financial system that can be used in my future games.
The goal for this system is to allow for
  • trading at a marketplace, much like the stock market
  • buying and selling stuff from vendors
Note that the code provided with this post is intended to be used in games, a lot of shortcuts have been taken. This is not a fool-proof system, more like a base to start building your own in game financial system on.

In this part we will introduce the scenario and go through the Account and TradeAccount classes.

This is part of my series on DIY Game Financial System
For other posts in this series check out the following links:
DIY Game Financial System Part 1: Intro and Accounts
DIY Game Financial System Part 2: Trade Algorithm

Introduction, a textual description

Every player, vendor etc. has their private TradeAccount consisting of a BalanceAccount and a list of Securities (items, shares whatever) owned at his current state.
Each TradeAccount is able to generate a BuyOrder based on a name of the Security to buy, the Quantity of Securities we are shopping for and the PricePerItem we are willing to pay. The BuyOrder  also contains a BalanceAccount with the amount of money needed to make the purchase. It is not possible to generate a BuyOrder if the TradeAccounts' BalanceAccount does not hold the amount of money needed to close the transaction.
In a similar fashion, each TradeAccount is able to generate a SellOrder for Securities currently held by that TradeAccount. The SellOrder also consists of the PricePerItem, Quantity and the Security for sale.

Both the SellOrder and the BuyOrder are sent to the Marketplace where the trade should be made. The Marketplace should be possible to instance as many times as needed. For example each vendor would have their own with things for sale, but the global Marketplace would allow for players to trade.

If there is an exact match on Security, Quantity and PricePerItem we will Execute the BuyOrder and transfer the money to the sellers TradeAccount and the securities to the buyers TradeAccount.
This will be our first naive algorithm to match orders.

Lets look at some code.


BalanceAccount

This is just a holder of money. Lets look at the interface.
public interface IAccount
{
    Guid Id { get; }
    ulong Balance { get; }
    bool CanAfford(ulong x);
    bool DepositInto(IAccount dest, ulong amount);
    void AddBalance(ulong amount);
}
So first we have an identifier, Id, just so that we can identify this account uniquely. Then we will store the actual current Balance of the account. I chose an unsigned long to store because of three reasons:

  • I don't really want to handle negative numbers, i.e. if you cannot afford it you can't buy it.
  • to be able to handle very large sums, I don't really know the applications for this yet, but don't want to limit someone for buying something for a ridiculous amount of money (18,446,744,073,709,551,615 to be exact)
  • I don't want to handle decimal numbers. Keep it simple, its a game :)
After that we have some functions, CanAfford checks if the account could afford to buy something costing x. 
public bool CanAfford(ulong x)
{
    return Balance >= x;
}
DepositInto withdraws money from this account and inserts it into the destination account.
public bool DepositInto(IAccount dest, ulong amount)
{
    lock (this)
    {
        if (!CanAfford(amount))
            return false;
        SubtractBalance(amount);
    }
    lock (dest)
    {
        dest.AddBalance(amount);
    }
    return true;
}
And lastly AddBalance creates money out of the blue (or you handle it somewhere else) and inserts into this account.
public void AddBalance(ulong amount)
{
    lock (this)
    {
        Balance += amount;
    }
}
private void SubtractBalance(ulong amount)
{
    Balance -= amount;
}
As you can see we add an extra lock in the AddBalance function as it is a public one and could be called from outside the DepositInto lock. For the private SubtractBalance method, we have full control and don't need the additional lock overhead.
There is a number of unit tests to verify this implementation in the source code in the repository. It gets quite long and thus not included in the post.

TradeAccount

public interface ITradeAccount
{
    event EventHandler<TradeAccount> Updated;
    IAccount BalanceAccount { get; }
    ulong ValueOfActiveBuyOrders { get; }
    Dictionary<string, Security> Securities { get; }
    List<BuyOrder> BuyOrders { get; }
    List<SellOrder> SellOrders { get; }

    SellOrder CreateSellOrder(string name, ulong quantity, ulong pricePerItem);
    BuyOrder CreateBuyOrder(string name, ulong quantity, ulong pricePerItem);
}

First off, we will expose an event, Updated, that will be triggered whenever the contents of this Trade Account change. This to be able to create event based updates of GUI elements at a later stage.
After that we have the BalanceAccount associated with this TradeAccount, for storage of money that can be used to buy stuff.
ValueOfActiveBuyOrders will return the amount of money bound in buy orders created by this TradeAccount.
public ulong ValueOfActiveBuyOrders
{
    get
    {
        ulong sum = 0;
        foreach (var item in BuyOrders)
        {
            sum += item.OrderAccount.Balance;
        }
        return sum;
    }
}
Securities is a dictionary of securities held by this account followed bu the currently active BuyOrders and SellOrders.

Lastly we expose functions to create both Sell and Buy orders.

CreateSellOrder

public SellOrder CreateSellOrder(string name, ulong quantity, ulong pricePerItem)
{
    Security security; 
    if (!Securities.TryGetValue(name, out security))
        return null;
    var split = security.Split(quantity);
    if (split == null)
        return null;
    var order = new SellOrder(split, pricePerItem);
    order.AddCancelAction(CancelSellOrder);
    order.AddExecuteAction(ExecuteSellOrder);
    lock (SellOrders)
    {
        SellOrders.Add(order);
    }
    Updated?.Invoke(this, this);
    return order;
}
To createa a SellOrder we first need to check if we actually own any securities with the name provided, if we don't we will stop directly. After that we split our owned security into a new one with the quantity we want to sell. We expect the Split method to return null if the split is invalid (tries to sell more then owned) and we stop there as well. If all is well, we setup the SellOrder, connect both Cancel and Execute handlers to this TradeAccount so that it will know its way home when the mission is accomplished or canceled. Lastly, we add it to the list of active SellOrders and invoke the Updated event.
private void ExecuteSellOrder(SellOrder order)
{
    order.OrderAccount.DepositInto(BalanceAccount, order.OrderAccount.Balance);
    lock (SellOrders)
    {
        SellOrders.Remove(order);
    }
    Updated?.Invoke(this, this);
}
The ExecuteSellOrder is responsible to transfer money to the selling TradeAccount when a trade is completing. As seen, the SellOrder has already received the money from the buying account so this is just a final put the money where it belongs and cleanup things handler.
private void CancelSellOrder(SellOrder order)
{
    Security security;
    if (!Securities.TryGetValue(order.SecurityName, out security))
    {
        Securities.Add(order.SecurityName, order.ForSale);
    }
    else
    {
        Securities[order.SecurityName].Merge(order.ForSale);
    }
    lock (SellOrders)
    {
        SellOrders.Remove(order);
    }
    Updated?.Invoke(this, this);
}
The CancelSellOrder is a little more complicated. We are not receiving any money here but we need to put the Securities back where they belong. So find the security we were trying to sell and either merge with the existing one or create a new entry (if it has been cleaned up for any reason). After that some cleanup and update event invoking.

CreateBuyOrder

The CreateBuyOrder basically follows the same pattern as the sell order creator but here we check that we have enough money to make the purchase that we want to.
We do this by creating a new account and trying to deposit the needed amount of money into it. If it fails, we stop there. If all is good, we create the BuyOrder and supply it the just created account and what to look for in the marketplace. Just as for the SellOrder, we connect handlers for both the Execute and Cancel outcomes and add it to the list of active buy orders.
public BuyOrder CreateBuyOrder(string name, ulong quantity, ulong pricePerItem)
{
    var orderAccount = new Account(0);
    if (!BalanceAccount.DepositInto(orderAccount, quantity*pricePerItem))
        return null;
    var order = new BuyOrder(name, pricePerItem, quantity, orderAccount);
    order.AddCancelAction(CancelBuyOrder);
    order.AddExecuteAction(ExecuteBuyOrder);
    lock (BuyOrders)
    {
        BuyOrders.Add(order);
    }
    Updated?.Invoke(this, this);
    return order;
}
The ExecuteBuyOrder looks very similar to the CancelSellOrder above, instead of putting back a canceled sell order, we will put in a newly purchased Security. It needs to find the already owned security and merge with it if it exists or create a new entry in the owned Securites dictionary. After that a cleanup is done.
private void ExecuteBuyOrder(BuyOrder order)
{
    Security security;
    if (!Securities.TryGetValue(order.SecurityName, out security))
    {
        Securities.Add(order.SecurityName, order.Security);
    }
    else
    {
        Securities[order.SecurityName].Merge(order.Security);
    }
    lock (BuyOrders)
    {
        BuyOrders.Remove(order);
    }
    Updated?.Invoke(this, this);
}
And surprise, surprise the CancelBuyOrder is similar to the ExecuteSellOrder. Here we put back the pocket-money we received when going to the market and then cleaning up.
private void CancelBuyOrder(BuyOrder order)
{
    order.OrderAccount.DepositInto(BalanceAccount, order.OrderAccount.Balance);
    lock (BuyOrders)
    {
        BuyOrders.Remove(order);
    }
    Updated?.Invoke(this, this);
}

So just like with the Account, there are a number of unit tests in the repository  that I will not cover here. Actually the repository contains the code for the first working version with a test GUI. We will cover the rest of the code in future posts in this series, but if you are interested you can look at the code already now :)

So there, thank you for reading. Hope this helps someone out there : )