Skip to content

Commit

Permalink
Merge pull request ethereum#641 from thanhnguyennguyen/update-matched…
Browse files Browse the repository at this point in the history
…-price

Update matched price
  • Loading branch information
ngtuna authored Aug 26, 2019
2 parents fb6e40a + 8d06207 commit dedfc14
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 40 deletions.
17 changes: 10 additions & 7 deletions core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,15 +300,19 @@ func ApplyTomoXMatchedTransaction(config *params.ChainConfig, statedb *state.Sta
takerExfee := GetExRelayerFee(orderItem.ExchangeAddress, statedb)
baseFee := common.TomoXBaseFee

price := orderItem.Price
for i := 0; i < len(txMatch.Trades); i++ {
log.Debug("ApplyTomoXMatchedTransaction : trades quantityString", "i", i, "trade", txMatch.Trades[i], "price", price)
quantityString := txMatch.Trades[i]["quantity"]
makerExAddr := common.HexToAddress(txMatch.Trades[i]["exAddr"])
price := tomox.ToBigInt(txMatch.Trades[i][tomox.TradedPrice])
quantityString := txMatch.Trades[i][tomox.TradedQuantity]
quantity := tomox.ToBigInt(quantityString)
if price.Cmp(big.NewInt(0)) <= 0 || quantity.Cmp(big.NewInt(0)) <= 0 {
return nil, 0, fmt.Errorf("trade misses important information. tradedPrice %v, tradedQuantity %v", price, quantity), false
}
makerExAddr := common.HexToAddress(txMatch.Trades[i][tomox.TradedMakerExchangeAddress])
makerExfee := GetExRelayerFee(makerExAddr, statedb)
makerExOwner := GetRelayerOwner(makerExAddr, statedb)
makerAddr := common.HexToAddress(txMatch.Trades[i]["uAddr"])
if quantityString != "" && makerExAddr != (common.Address{}) && makerAddr != (common.Address{}) {
makerAddr := common.HexToAddress(txMatch.Trades[i][tomox.TradedMaker])
log.Debug("ApplyTomoXMatchedTransaction : trades quantityString", "i", i, "trade", txMatch.Trades[i], "price", price)
if makerExAddr != (common.Address{}) && makerAddr != (common.Address{}) {
// take relayer fee
err := SubRelayerFee(takerExAddr, common.RelayerFee, statedb)
if err != nil {
Expand All @@ -323,7 +327,6 @@ func ApplyTomoXMatchedTransaction(config *params.ChainConfig, statedb *state.Sta
gasUsed = gasUsed.Add(gasUsed, common.RelayerFee)
gasUsed = gasUsed.Add(gasUsed, common.RelayerFee)

quantity := tomox.ToBigInt(quantityString)
log.Debug("ApplyTomoXMatchedTransaction quantity check", "i", i, "trade", txMatch.Trades[i], "price", price, "quantity", quantity)

isTakerBuy := orderItem.Side == tomox.Bid
Expand Down
57 changes: 37 additions & 20 deletions tomox/orderbook.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,19 @@ const (

// we use a big number as segment for storing order, order list from order tree slot.
// as sequential id
SlotSegment = common.AddressLength
SlotSegment = common.AddressLength
orderbookItemPrefix = "OB"

// trade struct field
TradedTakerOrderHash = "takerOrderHash"
TradedMakerOrderHash = "makerOrderHash"
TradedTimestamp = "timestamp"
TradedQuantity = "quantity"
TradedMakerExchangeAddress = "makerExAddr"
TradedMaker = "uAddr"
TradedBaseToken = "bToken"
TradedQuoteToken = "qToken"
TradedPrice = "tradedPrice"
)

var ErrDoesNotExist = errors.New("order doesn't exist in ordertree")
Expand Down Expand Up @@ -53,11 +64,11 @@ type OrderBookItemRecordBSON struct {

// OrderBook : list of orders
type OrderBook struct {
db OrderDao // this is for orderBook
Bids *OrderTree `json:"bids"`
Asks *OrderTree `json:"asks"`
Item *OrderBookItem
Timestamp uint64 `json:"time"`
db OrderDao // this is for orderBook
Bids *OrderTree `json:"bids"`
Asks *OrderTree `json:"asks"`
Item *OrderBookItem
Timestamp uint64 `json:"time"`

Key []byte
Slot *big.Int
Expand Down Expand Up @@ -173,7 +184,7 @@ func (orderBook *OrderBook) GetOrder(storedKey, key []byte, dryrun bool) *Order
}
orderItem := &OrderItem{}
val, err := orderBook.db.Get(storedKey, orderItem, dryrun)
if err != nil || val == nil {
if err != nil || val == nil {
log.Error("Key not found", "key", storedKey, "err", err)
return nil
}
Expand Down Expand Up @@ -214,10 +225,10 @@ func (orderBook *OrderBook) WorstAsk(dryrun bool) (value *big.Int) {
// processMarketOrder : process the market order
func (orderBook *OrderBook) processMarketOrder(order *OrderItem, verbose bool, dryrun bool) ([]map[string]string, *OrderItem, error) {
var (
trades []map[string]string
newTrades []map[string]string
trades []map[string]string
newTrades []map[string]string
orderInBook *OrderItem
err error
err error
)
quantityToTrade := order.Quantity
side := order.Side
Expand Down Expand Up @@ -357,7 +368,7 @@ func (orderBook *OrderBook) processOrderList(side string, orderList *OrderList,
log.Debug("Process matching between order and orderlist")
quantityToTrade := CloneBigInt(quantityStillToTrade)
var (
trades []map[string]string
trades []map[string]string
orderInBook *OrderItem
)
// speedup the comparison, do not assign because it is pointer
Expand All @@ -374,7 +385,7 @@ func (orderBook *OrderBook) processOrderList(side string, orderList *OrderList,

var (
newBookQuantity *big.Int
tradedQuantity *big.Int
tradedQuantity *big.Int
)

if IsStrictlySmallerThan(quantityToTrade, headOrder.Item.Quantity) {
Expand Down Expand Up @@ -423,14 +434,20 @@ func (orderBook *OrderBook) processOrderList(side string, orderList *OrderList,
}

transactionRecord := make(map[string]string)
transactionRecord["takerOrderHash"] = hex.EncodeToString(order.Hash.Bytes())
transactionRecord["makerOrderHash"] = hex.EncodeToString(headOrder.Item.Hash.Bytes())
transactionRecord["timestamp"] = strconv.FormatUint(orderBook.Timestamp, 10)
transactionRecord["quantity"] = tradedQuantity.String()
transactionRecord["exAddr"] = headOrder.Item.ExchangeAddress.String()
transactionRecord["uAddr"] = headOrder.Item.UserAddress.String()
transactionRecord["bToken"] = headOrder.Item.BaseToken.String()
transactionRecord["qToken"] = headOrder.Item.QuoteToken.String()
transactionRecord[TradedTakerOrderHash] = hex.EncodeToString(order.Hash.Bytes())
transactionRecord[TradedMakerOrderHash] = hex.EncodeToString(headOrder.Item.Hash.Bytes())
transactionRecord[TradedTimestamp] = strconv.FormatUint(orderBook.Timestamp, 10)
transactionRecord[TradedQuantity] = tradedQuantity.String()
transactionRecord[TradedMakerExchangeAddress] = headOrder.Item.ExchangeAddress.String()
transactionRecord[TradedMaker] = headOrder.Item.UserAddress.String()
transactionRecord[TradedBaseToken] = headOrder.Item.BaseToken.String()
transactionRecord[TradedQuoteToken] = headOrder.Item.QuoteToken.String()
// matched price should be the better price
if order.Price.Cmp(headOrder.Item.Price) < 0 {
transactionRecord[TradedPrice] = order.Price.String()
} else {
transactionRecord[TradedPrice] = headOrder.Item.Price.String()
}

trades = append(trades, transactionRecord)
}
Expand Down
25 changes: 12 additions & 13 deletions tomox/tomox.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ type TxDataMatch struct {
}

type TxMatchBatch struct {
Data []TxDataMatch
Data []TxDataMatch
Timestamp uint64
}

Expand Down Expand Up @@ -1274,19 +1274,21 @@ func (tomox *TomoX) SyncDataToSDKNode(txDataMatch TxDataMatch, txHash common.Has

// 2.a. put to trades
tradeSDK := &sdktypes.Trade{}
if q, ok := trade["quantity"]; ok {
tradeSDK.Amount = new(big.Int)
tradeSDK.Amount.SetString(q, 10)
quantity := ToBigInt(trade[TradedQuantity])
price := ToBigInt(trade[TradedPrice])
if price.Cmp(big.NewInt(0)) <= 0 || quantity.Cmp(big.NewInt(0)) <= 0 {
return fmt.Errorf("trade misses important information. tradedPrice %v, tradedQuantity %v", price, quantity)
}
tradeSDK.PricePoint = order.Price
tradeSDK.Amount = quantity
tradeSDK.PricePoint = price
tradeSDK.PairName = order.PairName
tradeSDK.BaseToken = order.BaseToken
tradeSDK.QuoteToken = order.QuoteToken
tradeSDK.Status = sdktypes.TradeStatusSuccess
tradeSDK.Taker = order.UserAddress
tradeSDK.Maker = common.HexToAddress(trade["uAddr"])
tradeSDK.Maker = common.HexToAddress(trade[TradedMakerExchangeAddress])
tradeSDK.TakerOrderHash = order.Hash
tradeSDK.MakerOrderHash = common.HexToHash(trade["makerOrderHash"])
tradeSDK.MakerOrderHash = common.HexToHash(trade[TradedMakerOrderHash])
tradeSDK.TxHash = txHash
tradeSDK.Hash = tradeSDK.ComputeHash()
log.Debug("TRADE history", "order", order, "trade", tradeSDK)
Expand All @@ -1295,15 +1297,12 @@ func (tomox *TomoX) SyncDataToSDKNode(txDataMatch TxDataMatch, txHash common.Has
}

// 2.b. update status and filledAmount
filledAmount, ok := new(big.Int).SetString(trade["quantity"], 10)
if !ok {
return fmt.Errorf("failed to get tradedQuantity. QuantityString: %s", trade["quantity"])
}
filledAmount := quantity
// update order status of relating orders
if err := tomox.updateStatusOfMatchedOrder(trade["makerOrderHash"], filledAmount); err != nil {
if err := tomox.updateStatusOfMatchedOrder(trade[TradedMakerOrderHash], filledAmount); err != nil {
return err
}
if err := tomox.updateStatusOfMatchedOrder(trade["takerOrderHash"], filledAmount); err != nil {
if err := tomox.updateStatusOfMatchedOrder(trade[TradedTakerOrderHash], filledAmount); err != nil {
return err
}
}
Expand Down

0 comments on commit dedfc14

Please sign in to comment.