Created
September 30, 2013 15:46
-
-
Save AndrewWDeane/6765800 to your computer and use it in GitHub Desktop.
Order / Price matching with bullhorn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bullhorn" | |
"fmt" | |
"math/rand" | |
"runtime" | |
"time" | |
) | |
type bs_ind int | |
const ( | |
buy bs_ind = iota | |
sell | |
) | |
type TouchPrice struct { | |
Epic string | |
BuyQty float64 | |
BuyPrice float64 | |
SellPrice float64 | |
SellQty float64 | |
} | |
func (t TouchPrice) String() string { | |
return fmt.Sprintf("%v: %5.0f %5.4f %5.4f %5.0f", t.Epic, t.BuyQty, t.BuyPrice, t.SellPrice, t.SellQty) | |
} | |
type LimitOrder struct { | |
Epic string | |
Ind bs_ind | |
Price float64 | |
Qty float64 | |
} | |
func main() { | |
runtime.GOMAXPROCS(2) | |
rand.Seed(time.Now().Unix()) | |
// start the processing loop | |
bullhorn.Start(1024, 1024) | |
orders := make(chan interface{}, 1024) | |
// start order listener | |
go func() { | |
for order := range orders { | |
switch order := order.(type) { | |
case LimitOrder: | |
fmt.Printf("Got order:%v\n", order) | |
// spawn a price listener to monitor the order | |
go func(order LimitOrder) { | |
prices := make(chan interface{}, 1024) | |
// subscribe to price feed | |
bullhorn.Add(bullhorn.Subscription{fmt.Sprintf("%v", order.Epic), prices}) | |
for price := range prices { | |
switch price := price.(type) { | |
case TouchPrice: | |
fmt.Printf("Matching:%v against:%v", order, price) | |
if (order.Ind == buy && order.Price >= price.SellPrice) || (order.Ind == sell && order.Price <= price.BuyPrice) { | |
fmt.Printf(" - Execute Order!\n") | |
// unsubscribe and kill goroutine | |
bullhorn.Delete(bullhorn.Subscription{fmt.Sprintf("%v", order.Epic), prices}) | |
return | |
} | |
fmt.Printf("\n") | |
} | |
} | |
}(order) | |
} | |
} | |
}() | |
// subscribe the order listener to the order feed | |
bullhorn.Add(bullhorn.Subscription{"orders", orders}) | |
// start the random price producer | |
go func() { | |
for { | |
price := TouchPrice{"CBG", 10000 * rand.Float64(), 1.10 - rand.Float64(), 1.00 + rand.Float64(), 15000 * rand.Float64()} | |
bullhorn.Publish(bullhorn.Event{"CBG", price}) | |
time.Sleep(5e8) | |
} | |
}() | |
// Add a buy order | |
bullhorn.Publish(bullhorn.Event{"orders", LimitOrder{Epic: "CBG", Ind: buy, Price: 1.05, Qty: 100}}) | |
// and a sell | |
bullhorn.Publish(bullhorn.Event{"orders", LimitOrder{Epic: "CBG", Ind: sell, Price: 1.05, Qty: 200}}) | |
select {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment