Exincore, introduced in the previous chapter, allows you to buy and sell assets at market prices in 1 second. If you want to buy and sell at a limited price, or buy and sell some assets that Exincore doesn’t support, you need OceanOne.

Plan 2: Order Ocean.One exchange

Ocean. One is a decentralized exchange based on the Mixin Network, and its performance is superb. You can trade any asset on OceanOne. You only need to transfer your currency to OceanOne and write the transaction information in the memo of the transaction. OceanOne will list your trading requirements in the market.

  • No registration with OceanOne is required
  • There is no need to deposit money in the exchange
  • Support all Mixin Network transferable assets, all ERC20 EOS tokens.

Preliminary knowledge:

You first need to create a robot, the method in tutorial 1.

Installing dependency packages

Lesson 4, which was already installed in the last lesson.

Charge coins into the Mixin Network and read out its balance.

This demonstrates buying BTC with USDT or buying USDT with BTC. Check your wallet address before making a transaction. The complete steps are as follows:

  • Check bitcoin or USDT balance, wallet address. And write down the address of the wallet.
  • From a third party exchange or your cold wallet, charge the coins to the above wallet address.
  • Check the balance of currency again to see whether the account is accounted. (Bitcoin’s arrival time is about 100 minutes at a height of five blocks).

Bitcoin and USDT recharge address is the same.

userInfo, userID := ReadAssetInfo("USDT")
fmt.Println("User ID ",userID, "'s USDT Address is: ",
           userInfo["data"]. (map[string]interface{})"public_key"])
fmt.Println("Balance is: ",
           userInfo["data"]. (map[string]interface{})"balance"])

func ReadAssetInfo(asset_id string) ( map[string]interface{}, string) {
 var UserInfoMap map[string]interface{}
 csvFile, err := os.Open("mybitcoin_wallet.csv")
 iferr ! =nil {
   log.Fatal(err)
 }
 reader := csv.NewReader(bufio.NewReader(csvFile))
 record, err := reader.Read()
 iferr ! =nil {
   log.Fatal(err)
 }
 fmt.Println(record[3])
 PrivateKey2           := record[0]
 SessionID2      		  := record[2]
 UserID2               := record[3]
 UserInfoBytes, err    := mixin.ReadAsset(mixin.GetAssetId(asset_id),
                                        UserID2,SessionID2,PrivateKey2)
 iferr ! =nil {
         log.Fatal(err)
 }
 fmt.Println(string(UserInfoBytes))
 iferr := json.Unmarshal(UserInfoBytes, &UserInfoMap); err ! =nil {
     panic(err)
 }
 csvFile.Close()
 return UserInfoMap, UserID2
}
Copy the code

Get market price information for Ocean. One

How to check the price information of Ocean. One market? If you want to buy bitcoin and sell USDT, the base currency is USDT. If you want to buy USDT and sell Bitcoin, then the base currency is bitcoin.

if cmd == "1" {
   FormatOceanOneMarketPrice(mixin.GetAssetId("XIN"),mixin.GetAssetId("USDT"))}func FormatOceanOneMarketPrice(asset_id string, base_asset string) {
  priceInfo, err := GetOceanOneMarketPrice(asset_id, base_asset)
  iferr ! =nil {
    log.Fatal(err)
  }

  var marketInfo map[string]interface{}
  err = json.Unmarshal([]byte(priceInfo), &marketInfo)
   fmt.Println("Price | Amount | Funds | Side")
  for _, v := range (marketInfo["data"].
                    (map[string]interface{})"data"].
                    (map[string]interface{})"asks"([]].interface{})) {
    fmt.Println(v.(map[string]interface{})"price"],
                v.(map[string]interface{})"amount"],
                v.(map[string]interface{})"funds"],
                v.(map[string]interface{})"side"],)}for _, v := range (marketInfo["data"].
                    (map[string]interface{})"data"].
                    (map[string]interface{})"bids"([]].interface{})) {
    fmt.Println(v.(map[string]interface{})"price"],
                v.(map[string]interface{})"amount"],
                v.(map[string]interface{})"funds"],
                v.(map[string]interface{})"side"],)}}func GetOceanOneMarketPrice(asset_id string, base_asset string) ([]byte, error)  {
	var body []byte
	req, err := http.NewRequest("GET"."https://events.ocean.one/markets/" + asset_id + "-" + base_asset + "/book",
                              bytes.NewReader(body))
	iferr ! =nil {
		return nil, err
	}
	req.Header.Set("Content-Type"."application/json")

	resp, err := httpClient.Do(req)
	iferr ! =nil {
		return nil, err
	}
	defer resp.Body.Close()
  // fmt.Println(resp.Body)
	bt, err := ioutil.ReadAll(resp.Body)
	ifresp.StatusCode ! = http.StatusOK {var resp struct {
			Error Error `json:"error"`
		}
		err = json.Unmarshal(bt, &resp)
		if err == nil {
			err = resp.Error
		}
	}
	return bt, err
}
Copy the code

Before trading, create a Memo!

In chapter 2, Go Bitcoin development tutorial based on Mixin Network: The robot accepts bitcoin and immediately returns it to the user. We have learned how to transfer money. Here we explain how to tell Ocean.

  • Side,”B” or “A”, “B” is buy,” A” is sell.
  • AssetUUID UUID of the target virtual asset.
  • Price is the Price of AssetUUID if the operation direction is “B”; If the direction of operation is “B”, the price is the price transferred to Ocean. One coin.
func generateOceanOrderMemo(TargetAsset, Side, Price string) (string) {
  packUuid, _ := uuid.FromString(TargetAsset)
  memoOcean,_ :=
    msgpack.Marshal(OceanOrderAction{
      T: "L",
      P: Price,
      S: Side,
      A: packUuid,
    })
  return  base64.StdEncoding.EncodeToString(memoOcean)
}
Copy the code

Example of selling sex

Transfer the XIN you want to sell to Ocean. One (OCEANONE_BOT) and put the UUID of the target virtual asset you want to trade back into the Memo.

if cmd == "s1" {
  fmt.Print("Please input the price of XIN/USDT: ")
  var pcmd string
  var acmd string
  scanner.Scan()
  pcmd = scanner.Text()
  fmt.Println(pcmd)
  fmt.Print("Please input the amount of XIN: ")
  scanner.Scan()
  acmd = scanner.Text()
  fmt.Println(acmd)
  omemo := generateOceanOrderMemo(mixin.GetAssetId("USDT"),"A",pcmd)
  priKey, pToken, sID, userID, uPIN := GetWalletInfo()
  balance := ReadAssetBalance("XIN",userID,sID,priKey)
  fmt.Println(balance)
  fbalance, _ := strconv.ParseFloat(balance,64)
  abalance, _ := strconv.ParseFloat(acmd,64)
  if fbalance > 0 && fbalance >= abalance {
    fmt.Println(omemo)
    transInfo, _ := mixin.Transfer(OCEANONE_BOT,
                                   acmd,
                                   mixin.GetAssetId("XIN"),
                                   omemo,
                                   messenger.UuidNewV4().String(),
                                   uPIN,pToken,userID,sID,priKey)
    fmt.Println(string(transInfo))
    var jsTransInfo map[string]interface{}
    err := json.Unmarshal([]byte(transInfo), &jsTransInfo)
    iferr ! =nil {
        log.Fatal(err)
    }
    fmt.Println("The Order id is " + jsTransInfo["data"]. (map[string]interface{})"trace_id"]. (string) +
               " it is needed to cancel the order!")}else { fmt.Println("Not enough XIN!")}}Copy the code

If you are planning to buy sex, do the following:

if cmd == "b1" {
  fmt.Print("Please input the price of XIN/USDT: ")
  var pcmd string
  var acmd string
  scanner.Scan()
  pcmd = scanner.Text()
  fmt.Println(pcmd)
  fmt.Print("Please input the amount of USDT: ")
  scanner.Scan()
  acmd = scanner.Text()
  fmt.Println(acmd)
  omemo := generateOceanOrderMemo(mixin.GetAssetId("XIN"),"B",pcmd)
  priKey, pToken, sID, userID, uPIN := GetWalletInfo()
  balance := ReadAssetBalance("USDT",userID,sID,priKey)
  fmt.Println(balance)
  fbalance, _ := strconv.ParseFloat(balance,64)
  abalance, _ := strconv.ParseFloat(acmd,64)
  if fbalance > 0 && fbalance >= abalance {
    fmt.Println(omemo)
    transInfo, _ := mixin.Transfer(OCEANONE_BOT,
                                   acmd,
                                   mixin.GetAssetId("USDT"),
                                   omemo,
                                   messenger.UuidNewV4().String(),
                                   uPIN,pToken,userID,sID,priKey)
    fmt.Println(string(transInfo))
    var jsTransInfo map[string]interface{}
    err := json.Unmarshal([]byte(transInfo), &jsTransInfo)
    iferr ! =nil {
        log.Fatal(err)
    }
    fmt.Println("The Order id is " + jsTransInfo["data"]. (map[string]interface{})"trace_id"]. (string) +
               " it is needed to cancel the order!")}else { fmt.Println("Not enough USDT!")}}//end of b1
Copy the code

A successful listing is as follows:

Please input the price of BTC/USDT: 5666
5666
Please input the amount of USDT: 1
1
1
hKFToUKhQcQQxtDHKCYkQpuODdnRm2WS+qFQpDU2NjahVKFM
{"data": {"type":"transfer"."snapshot_id":"c1518f2c-c2e8-4d2d-b7c3-a42770f2bdab"."opponent_id":"aaff5bef-42fb-4c9f-90e0-29f69176b7d4"."asset_id":"815b0b1a-2764-3736-8faa-42d694fa620a"."amount":"1"."trace_id":"26ef0ec1-a60c-4702-b8ca-4bd40330e120"."memo":"hKFToUKhQcQQxtDHKCYkQpuODdnRm2WS+qFQpDU2NjahVKFM"."created_at":"The 2019-05-08 T06:48:42. 919216755 z"."counter_user_id":"aaff5bef-42fb-4c9f-90e0-29f69176b7d4"}}
The Order id is 26ef0ec1-a60c-4702-b8ca-4bd40330e120 it is needed to cancel the order!
Copy the code

Cancel the deity

Ocean. One takes trace_id as an order, for example in the example above, 26EF0EC1-A60C-4702-b8CA-4bD40330E120 is the order number and we use it to cancel the order.

if cmd == "c" {
  fmt.Print("Please input the Order id: ")
  var ocmd string
  scanner.Scan()
  ocmd = scanner.Text()
  fmt.Println(ocmd)
  orderid, _ := uuid.FromString(ocmd)
  memoOcean,_ :=
    msgpack.Marshal(OceanOrderCancel{
      O: orderid,
    })
  omemoCancel := base64.StdEncoding.EncodeToString(memoOcean)
  priKey, pToken, sID, userID, uPIN := GetWalletInfo()
  balance := ReadAssetBalance("CNB",userID,sID,priKey)
  fmt.Println(balance)
  fbalance, _ := strconv.ParseFloat(balance,64)
  // abalance, _ := strconv.ParseFloat(acmd,64)
  if fbalance > 0 && fbalance >= 0.0000001 {
    fmt.Println(omemoCancel)
    transInfo, _ := mixin.Transfer(OCEANONE_BOT,
                                   "0.00000001",
                                   mixin.GetAssetId("CNB"),
                                   omemoCancel,
                                   messenger.UuidNewV4().String(),
                                   uPIN,pToken,userID,sID,priKey)
    fmt.Println(string(transInfo))
  } else { fmt.Println("Not enough CNB!")}}Copy the code

By reading the balance of assets, to confirm the arrival of the account

if cmd == "aw" {
  priKey, _, sID, userID, _ := GetWalletInfo()
  assets, err := mixin.ReadAssets(userID,sID,priKey)
  iferr ! =nil {
      log.Fatal(err)
  }
  var AssetsInfo map[string]interface{}
  err = json.Unmarshal(assets, &AssetsInfo)
  iferr ! =nil {
      log.Fatal(err)
  }
  // fmt.Println("Data is: ",AssetsInfo["data"].(map[string]interface{})["public_key"])
  for _, v := range (AssetsInfo["data"([]].interface{{}))if v.(map[string]interface{})"symbol"] = ="EOS" {
      fmt.Println(v.(map[string]interface{})"symbol"]."",
                  v.(map[string]interface{})"account_name"]."",
                  v.(map[string]interface{})"account_tag"]."",
                  v.(map[string]interface{})"balance"])}else {
      fmt.Println(v.(map[string]interface{})"symbol"]."",
                  v.(map[string]interface{})"public_key"]."",
                  v.(map[string]interface{})"balance"])}}}Copy the code

Source code execution

Compile and execute, then start trading.

  • Go run coin_exchange.go compile project.

List of commands when this code is executed:

Commands list of this source code:

  • aw: Read Wallet Assets
  • o: Ocean.One Exchange
  • q: Exit Make your choose:

Make your choose(eg: q for Exit!) :

  • 1: Fetch XIN/USDT orders
  • s1: Sell XIN/USDT
  • b1: Buy XIN/USDT
  • 2: Fetch ERC20(Benz)/USDT orders
  • s2: Sell Benz/USDT
  • b2: Buy Benz/USDT
  • 3: Fetch BTC/USDT orders
  • s3: Sell BTC/USDT
  • b3: Buy BTC/USDT
  • c: Cancel Order
  • q: Exit

The complete code