Skip to content

Commit

Permalink
remove triggered orders
Browse files Browse the repository at this point in the history
  • Loading branch information
codchen committed May 11, 2023
1 parent 4c2cf12 commit efabc4f
Show file tree
Hide file tree
Showing 12 changed files with 7 additions and 583 deletions.
12 changes: 0 additions & 12 deletions x/dex/cache/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,18 +119,6 @@ func (o *BlockOrders) GetLimitOrders(direction types.PositionDirection) []*types
return o.getOrdersByCriteria(types.OrderType_LIMIT, direction)
}

func (o *BlockOrders) GetTriggeredOrders() []*types.Order {
return o.getOrdersByCriteriaMap(
map[types.OrderType]bool{
types.OrderType_STOPLOSS: true,
types.OrderType_STOPLIMIT: true,
},
map[types.PositionDirection]bool{
types.PositionDirection_LONG: true,
types.PositionDirection_SHORT: true,
})
}

func (o *BlockOrders) getOrdersByCriteria(orderType types.OrderType, direction types.PositionDirection) []*types.Order {
res := []*types.Order{}
iterator := sdk.KVStorePrefixIterator(o.orderStore, []byte{})
Expand Down
42 changes: 0 additions & 42 deletions x/dex/cache/order_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,45 +255,3 @@ func TestGetSortedMarketOrders(t *testing.T) {
require.Equal(t, uint64(13), marketSells[7].Id)
require.Equal(t, uint64(19), marketSells[8].Id)
}

func TestGetTriggeredOrders(t *testing.T) {
keeper, ctx := keepertest.DexKeeper(t)
stateOne := dex.NewMemState(keeper.GetMemStoreKey())
stateOne.GetBlockOrders(ctx, types.ContractAddress(TEST_CONTRACT), types.PairString(TEST_PAIR)).Add(&types.Order{
Id: 1,
Account: "test",
ContractAddr: TEST_CONTRACT,
PositionDirection: types.PositionDirection_LONG,
OrderType: types.OrderType_STOPLOSS,
Price: sdk.MustNewDecFromStr("150"),
TriggerPrice: sdk.MustNewDecFromStr("100"),
TriggerStatus: false,
})
stateOne.GetBlockOrders(ctx, types.ContractAddress(TEST_CONTRACT), types.PairString(TEST_PAIR)).Add(&types.Order{
Id: 2,
Account: "test",
ContractAddr: TEST_CONTRACT,
PositionDirection: types.PositionDirection_SHORT,
OrderType: types.OrderType_STOPLIMIT,
Price: sdk.MustNewDecFromStr("150"),
TriggerPrice: sdk.MustNewDecFromStr("200"),
TriggerStatus: false,
})
stateOne.GetBlockOrders(ctx, types.ContractAddress(TEST_CONTRACT), types.PairString(TEST_PAIR)).Add(&types.Order{
Id: 3,
Account: "test",
ContractAddr: TEST_CONTRACT,
PositionDirection: types.PositionDirection_LONG,
OrderType: types.OrderType_LIMIT,
Price: sdk.MustNewDecFromStr("100"),
})

triggeredOrders := stateOne.GetBlockOrders(ctx, types.ContractAddress(TEST_CONTRACT), types.PairString(TEST_PAIR)).GetTriggeredOrders()
var orderIds []uint64
for _, order := range triggeredOrders {
orderIds = append(orderIds, order.Id)
}

require.Equal(t, len(triggeredOrders), 2)
require.ElementsMatch(t, orderIds, []uint64{1, 2})
}
13 changes: 0 additions & 13 deletions x/dex/client/cli/tx/tx_place_orders.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,6 @@ func CmdPlaceOrders() *cobra.Command {
}
newOrder.Nominal = argNominal
}
if newOrder.OrderType == types.OrderType_STOPLOSS || newOrder.OrderType == types.OrderType_STOPLIMIT {
triggerPrice, err := sdk.NewDecFromStr(orderDetails[7])
if err != nil {
return err
}
triggerStatus, err := strconv.ParseBool(orderDetails[8])
if err != nil {
return err
}

newOrder.TriggerPrice = triggerPrice
newOrder.TriggerStatus = triggerStatus
}
orders = append(orders, &newOrder)
}

Expand Down
56 changes: 0 additions & 56 deletions x/dex/contract/execution.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ func ExecutePair(
// Fill limit orders
limitOrderOutcome := exchange.MatchLimitOrders(ctx, orderbook)
totalOutcome := marketOrderOutcome.Merge(&limitOrderOutcome)
UpdateTriggeredOrderForPair(ctx, typedContractAddr, typedPairStr, dexkeeper, totalOutcome)

dexkeeperutils.SetPriceStateFromExecutionOutcome(ctx, dexkeeper, typedContractAddr, pair, totalOutcome)

Expand Down Expand Up @@ -108,60 +107,6 @@ func matchMarketOrderForPair(
return marketBuyOutcome.Merge(&marketSellOutcome)
}

func MoveTriggeredOrderForPair(
ctx sdk.Context,
typedContractAddr types.ContractAddress,
typedPairStr types.PairString,
dexkeeper *keeper.Keeper,
) {
priceDenom, assetDenom := types.GetPriceAssetString(typedPairStr)
triggeredOrders := dexkeeper.GetAllTriggeredOrdersForPair(ctx, string(typedContractAddr), priceDenom, assetDenom)
for i, order := range triggeredOrders {
if order.TriggerStatus {
if order.OrderType == types.OrderType_STOPLOSS {
triggeredOrders[i].OrderType = types.OrderType_MARKET
} else if order.OrderType == types.OrderType_STOPLIMIT {
triggeredOrders[i].OrderType = types.OrderType_LIMIT
}
dexutils.GetMemState(ctx.Context()).GetBlockOrders(ctx, typedContractAddr, typedPairStr).Add(&triggeredOrders[i])
dexkeeper.RemoveTriggeredOrder(ctx, string(typedContractAddr), order.Id, priceDenom, assetDenom)
}
}
}

func UpdateTriggeredOrderForPair(
ctx sdk.Context,
typedContractAddr types.ContractAddress,
typedPairStr types.PairString,
dexkeeper *keeper.Keeper,
totalOutcome exchange.ExecutionOutcome,
) {
// update existing trigger orders
priceDenom, assetDenom := types.GetPriceAssetString(typedPairStr)
triggeredOrders := dexkeeper.GetAllTriggeredOrdersForPair(ctx, string(typedContractAddr), priceDenom, assetDenom)
for i, order := range triggeredOrders {
if order.PositionDirection == types.PositionDirection_LONG && order.TriggerPrice.LTE(totalOutcome.MaxPrice) {
triggeredOrders[i].TriggerStatus = true
dexkeeper.SetTriggeredOrder(ctx, string(typedContractAddr), triggeredOrders[i], priceDenom, assetDenom)
} else if order.PositionDirection == types.PositionDirection_SHORT && order.TriggerPrice.GTE(totalOutcome.MinPrice) {
triggeredOrders[i].TriggerStatus = true
dexkeeper.SetTriggeredOrder(ctx, string(typedContractAddr), triggeredOrders[i], priceDenom, assetDenom)
}
}

// update triggered orders in cache
orders := dexutils.GetMemState(ctx.Context()).GetBlockOrders(ctx, typedContractAddr, typedPairStr)
cacheTriggeredOrders := orders.GetTriggeredOrders()
for i, order := range cacheTriggeredOrders {
if order.PositionDirection == types.PositionDirection_LONG && order.TriggerPrice.LTE(totalOutcome.MaxPrice) {
cacheTriggeredOrders[i].TriggerStatus = true
} else if order.PositionDirection == types.PositionDirection_SHORT && order.TriggerPrice.GTE(totalOutcome.MinPrice) {
cacheTriggeredOrders[i].TriggerStatus = true
}
dexkeeper.SetTriggeredOrder(ctx, string(typedContractAddr), *cacheTriggeredOrders[i], priceDenom, assetDenom)
}
}

func GetMatchResults(
ctx sdk.Context,
typedContractAddr types.ContractAddress,
Expand Down Expand Up @@ -201,7 +146,6 @@ func ExecutePairsInParallel(ctx sdk.Context, contractAddr string, dexkeeper *kee
defer wg.Done()
pairCopy := pair
pairStr := types.GetPairString(&pairCopy)
MoveTriggeredOrderForPair(ctx, typedContractAddr, pairStr, dexkeeper)
orderbook, found := orderBooks.Load(pairStr)
if !found {
panic(fmt.Sprintf("Orderbook not found for %s", pairStr))
Expand Down
133 changes: 0 additions & 133 deletions x/dex/contract/execution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
keepertest "github.com/sei-protocol/sei-chain/testutil/keeper"
"github.com/sei-protocol/sei-chain/x/dex/contract"
"github.com/sei-protocol/sei-chain/x/dex/exchange"
keeperutil "github.com/sei-protocol/sei-chain/x/dex/keeper/utils"
"github.com/sei-protocol/sei-chain/x/dex/types"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -372,135 +371,3 @@ func TestEmitSettlementMetrics(t *testing.T) {

contract.EmitSettlementMetrics(settlements)
}

func TestMoveTriggeredOrderIntoMemState(t *testing.T) {
pair := TEST_PAIR()
dexkeeper, ctx := keepertest.DexKeeper(t)
ctx = ctx.WithBlockHeight(int64(TestHeight)).WithBlockTime(time.Unix(int64(TestTimestamp), 0))
triggeredOrder := types.Order{
Id: 8,
Price: sdk.MustNewDecFromStr("20"),
Quantity: sdk.MustNewDecFromStr("5"),
Data: "",
PositionDirection: types.PositionDirection_LONG,
OrderType: types.OrderType_STOPLOSS,
PriceDenom: TEST_PAIR().PriceDenom,
AssetDenom: TEST_PAIR().AssetDenom,
TriggerPrice: sdk.MustNewDecFromStr("10"),
TriggerStatus: true,
}

dexkeeper.SetTriggeredOrder(ctx, TEST_CONTRACT, triggeredOrder, TEST_PAIR().PriceDenom, TEST_PAIR().AssetDenom)
contract.MoveTriggeredOrderForPair(
ctx,
types.ContractAddress(TEST_CONTRACT),
types.GetPairString(&pair),
dexkeeper,
)
orders := dexutil.GetMemState(ctx.Context()).GetBlockOrders(ctx, TEST_CONTRACT, types.GetPairString(&pair))
cacheMarketOrders := orders.GetSortedMarketOrders(types.PositionDirection_LONG)
cacheTriggeredOrders := orders.GetTriggeredOrders()

triggeredBookOrders := dexkeeper.GetAllTriggeredOrdersForPair(ctx, TEST_CONTRACT, TEST_PAIR().PriceDenom, TEST_PAIR().AssetDenom)

require.Equal(t, len(triggeredBookOrders), 0)
require.Equal(t, len(cacheTriggeredOrders), 0)
require.Equal(t, len(cacheMarketOrders), 1)
require.Equal(t, cacheMarketOrders[0].Id, uint64(8))
require.Equal(t, cacheMarketOrders[0].OrderType, types.OrderType_MARKET)
require.Equal(t, cacheMarketOrders[0].PositionDirection, types.PositionDirection_LONG)
}

func TestUpdateTriggeredOrders(t *testing.T) {
pair := TEST_PAIR()
dexkeeper, ctx := keepertest.DexKeeper(t)
ctx = ctx.WithBlockHeight(int64(TestHeight)).WithBlockTime(time.Unix(int64(TestTimestamp), 0))
shortTriggeredOrder := types.Order{
Id: 1,
Price: sdk.MustNewDecFromStr("20"),
Quantity: sdk.MustNewDecFromStr("5"),
Data: "",
PositionDirection: types.PositionDirection_SHORT,
OrderType: types.OrderType_STOPLIMIT,
PriceDenom: TEST_PAIR().PriceDenom,
AssetDenom: TEST_PAIR().AssetDenom,
TriggerPrice: sdk.MustNewDecFromStr("6"),
TriggerStatus: false,
}
longTriggeredOrder := types.Order{
Id: 2,
Price: sdk.MustNewDecFromStr("20"),
Quantity: sdk.MustNewDecFromStr("5"),
Data: "",
PositionDirection: types.PositionDirection_LONG,
OrderType: types.OrderType_STOPLOSS,
PriceDenom: TEST_PAIR().PriceDenom,
AssetDenom: TEST_PAIR().AssetDenom,
TriggerPrice: sdk.MustNewDecFromStr("19"),
TriggerStatus: false,
}
shortNotTriggeredOrder := types.Order{
Id: 3,
Price: sdk.MustNewDecFromStr("20"),
Quantity: sdk.MustNewDecFromStr("5"),
Data: "",
PositionDirection: types.PositionDirection_SHORT,
OrderType: types.OrderType_STOPLOSS,
PriceDenom: TEST_PAIR().PriceDenom,
AssetDenom: TEST_PAIR().AssetDenom,
TriggerPrice: sdk.MustNewDecFromStr("4"),
TriggerStatus: false,
}
longNotTriggeredOrder := types.Order{
Id: 4,
Price: sdk.MustNewDecFromStr("20"),
Quantity: sdk.MustNewDecFromStr("5"),
Data: "",
PositionDirection: types.PositionDirection_LONG,
OrderType: types.OrderType_STOPLIMIT,
PriceDenom: TEST_PAIR().PriceDenom,
AssetDenom: TEST_PAIR().AssetDenom,
TriggerPrice: sdk.MustNewDecFromStr("21"),
TriggerStatus: false,
}

totalOutcome := exchange.ExecutionOutcome{
TotalNotional: sdk.MustNewDecFromStr("10"),
TotalQuantity: sdk.MustNewDecFromStr("10"),
Settlements: []*types.SettlementEntry{},
MinPrice: sdk.MustNewDecFromStr("5"),
MaxPrice: sdk.MustNewDecFromStr("20"),
}

dexkeeper.SetTriggeredOrder(ctx, TEST_CONTRACT, shortTriggeredOrder, TEST_PAIR().PriceDenom, TEST_PAIR().AssetDenom)
dexkeeper.SetTriggeredOrder(ctx, TEST_CONTRACT, longNotTriggeredOrder, TEST_PAIR().PriceDenom, TEST_PAIR().AssetDenom)
orders := dexutil.GetMemState(ctx.Context()).GetBlockOrders(ctx, TEST_CONTRACT, types.GetPairString(&pair))
orders.Add(&shortNotTriggeredOrder)
orders.Add(&longTriggeredOrder)

contract.UpdateTriggeredOrderForPair(
ctx,
types.ContractAddress(TEST_CONTRACT),
types.GetPairString(&pair),
dexkeeper,
totalOutcome,
)

triggeredBookOrders := dexkeeper.GetAllTriggeredOrdersForPair(ctx, TEST_CONTRACT, TEST_PAIR().PriceDenom, TEST_PAIR().AssetDenom)

require.Equal(t, len(triggeredBookOrders), 4)
triggerStatusMap := map[uint64]bool{}

for _, order := range triggeredBookOrders {
triggerStatusMap[order.Id] = order.TriggerStatus
}
require.Contains(t, triggerStatusMap, uint64(1))
require.Contains(t, triggerStatusMap, uint64(2))
require.Contains(t, triggerStatusMap, uint64(3))
require.Contains(t, triggerStatusMap, uint64(4))

require.Equal(t, triggerStatusMap[uint64(1)], true)
require.Equal(t, triggerStatusMap[uint64(2)], true)
require.Equal(t, triggerStatusMap[uint64(3)], false)
require.Equal(t, triggerStatusMap[uint64(4)], false)
}
16 changes: 5 additions & 11 deletions x/dex/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState)
k.SetShortBook(ctx, contractState.ContractInfo.ContractAddr, elem)
}

for _, elem := range contractState.TriggeredOrdersList {
// not sure if it's guaranteed that the Order has the correct Price/Asset/Contract details...
k.SetTriggeredOrder(ctx, contractState.ContractInfo.ContractAddr, elem, elem.PriceDenom, elem.AssetDenom)
}

for _, elem := range contractState.PriceList {
for _, priceElem := range elem.Prices {
k.SetPriceState(ctx, *priceElem, contractState.ContractInfo.ContractAddr)
Expand Down Expand Up @@ -70,12 +65,11 @@ func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState {
})
}
contractStates[i] = types.ContractState{
ContractInfo: contractInfo,
LongBookList: k.GetAllLongBook(ctx, contractAddr),
ShortBookList: k.GetAllShortBook(ctx, contractAddr),
TriggeredOrdersList: k.GetAllTriggeredOrders(ctx, contractAddr),
PairList: registeredPairs,
PriceList: contractPrices,
ContractInfo: contractInfo,
LongBookList: k.GetAllLongBook(ctx, contractAddr),
ShortBookList: k.GetAllShortBook(ctx, contractAddr),
PairList: registeredPairs,
PriceList: contractPrices,
}
}
genesis.ContractState = contractStates
Expand Down
1 change: 0 additions & 1 deletion x/dex/keeper/contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ func (k Keeper) DoUnregisterContract(ctx sdk.Context, contract types.ContractInf
k.DeleteMatchResultState(ctx, contract.ContractAddr)
k.DeleteNextOrderID(ctx, contract.ContractAddr)
k.DeleteAllRegisteredPairsForContract(ctx, contract.ContractAddr)
k.RemoveAllTriggeredOrders(ctx, contract.ContractAddr)
}

func (k Keeper) SuspendContract(ctx sdk.Context, contractAddress string, reason string) error {
Expand Down
13 changes: 0 additions & 13 deletions x/dex/keeper/query/grpc_query_order.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,6 @@ func (k KeeperWrapper) GetOrder(c context.Context, req *types.QueryGetOrderByIDR
}
}

triggeredOrders := k.GetAllTriggeredOrders(ctx, req.ContractAddr)
for i, order := range triggeredOrders {
if order.Id == req.Id {
return &types.QueryGetOrderByIDResponse{
Order: &triggeredOrders[i],
}, nil
}
}

return &types.QueryGetOrderByIDResponse{}, types.ErrInvalidOrderID
}

Expand Down Expand Up @@ -107,10 +98,6 @@ func (k KeeperWrapper) GetOrders(c context.Context, req *types.QueryGetOrdersReq
}
}
}
triggeredOrders := k.GetAllTriggeredOrders(ctx, req.ContractAddr)
for i := range triggeredOrders {
orders = append(orders, &triggeredOrders[i])
}

return &types.QueryGetOrdersResponse{Orders: orders}, nil
}
Loading

0 comments on commit efabc4f

Please sign in to comment.