Bitcoin Forum

Bitcoin => Bitcoin Discussion => Topic started by: helloworld on August 19, 2011, 03:06:07 PM



Title: Exchange algorithm specifics
Post by: helloworld on August 19, 2011, 03:06:07 PM
Trying to work out in my head how an exchange works, specifically how the database tables are designed and what happens internally in the database when someone places an order.

Maybe there's open-source code out there already, but it's kind of fun to do this kind of math/problem solving with just pen and paper (or notepad.exe!)


So, let's say the db has the following orders:

bid, 2.00000000, 10.70000000
bid, 1.00000000, 10.80000000
ask, 2.00000000, 11.00000000
ask, 3.00000000, 11.20000000     <- let's call this order X

Now what happens when these hypothetical orders are placed:

bid, 3.00000000, 10.70000000
check the lowest ask -> 11.
This bid is less than the lowest ask, so no trade occurs, the order it simply gets added to the db.

bid, 3.00000000, 11.50000000
check the lowest ask -> 11.
This bid is above the lowest ask, so check how many coins are available at that lowest price -> 2.
This only fills part of the order, so check the next lowest ask -> 11.2.
Check how many coins are available at that price -> 3.
This is more than enough to fill the order, so the order is complete, however this ask also has 2 btc left to fill.

Question: In this scenario, when order X is only partially filled, would it be best to mark the row as complete and add a new entry with the remaining amount, or just edit the row to show the new amount?

eg.

insert method:
db before:
ask, 3.00000000, 11.20000000
db after:
ask, 3.00000000, 11.20000000, complete
ask, 2.00000000, 11.20000000

or edit method:
db before:
ask, 3.00000000, 11.20000000
db after:
ask, 2.00000000, 11.20000000


Title: Re: Exchange algorithm specifics
Post by: davout on August 19, 2011, 03:23:23 PM
Both approaches work.

On bitcoin-central.net, rows are edited. I'm thinking this should change at some point since you end up losing information, not information that is useful for performing the trading, but history that could be interesting for a trader to have.

Source code is here : https://github.com/davout/bitcoin-central/blob/master/app/models/trade_order.rb

Line 138 is where the magic starts to happen.


Title: Re: Exchange algorithm specifics
Post by: helloworld on August 19, 2011, 03:31:32 PM
Great, thanks!

Please excuse my ignorance, but what language is that code?

I wonder what language and what database is most common for an exchange too... I'm sure you need to bundle your sql statements into transactions to be safe.


Title: Re: Exchange algorithm specifics
Post by: davout on August 19, 2011, 03:36:05 PM
Please excuse my ignorance, but what language is that code?
Ruby

I'm sure you need to bundle your sql statements into transactions to be safe.
They are. And you better make use of the serializable isolation level.