經過 Go 在去中心化交易所OceanOne上掛單買賣Bitcoin

上一章介紹了Exincore,你能夠1秒完成資產的市價買賣。若是你想限訂價格買賣,或者買賣一些exincore不支持的資產,你須要OceanOne。git

方案二: 掛單Ocean.One交易所

Ocean.one是基於Mixin Network的去中心化交易所,它性能一流。 你能夠在OceanOne上交易任何資產,只須要將你的幣轉給OceanOne, 將交易信息寫在交易的memo裏,OceanOne會在市場裏列出你的交易需求, 交易成功後,會將目標幣轉入到你的MixinNetwork賬上,它有三大特色與優點:github

  • 不須要在OceanOne註冊
  • 不須要存幣到交易所
  • 支持全部Mixin Network上可以轉帳的資產,全部的ERC20 EOS代幣。

預備知識:

你先須要建立一個機器人, 方法在 教程一.json

安裝依賴包

第四課, 在上一課中已經安裝好了.bash

充幣到 Mixin Network, 並讀出它的餘額.

此處演示用 USDT購買BTC 或者 用BTC購買USDT。交易前,先檢查一下錢包地址。 完整的步驟以下:app

  • 檢查比特幣或USDT的餘額,錢包地址。並記下錢包地址。
  • 從第三方交易所或者你的冷錢包中,將幣充到上述錢包地址。
  • 再檢查一下幣的餘額,看到賬與否。(比特幣的到賬時間是5個區塊的高度,約100分鐘)。

比特幣與USDT的充值地址是同樣的。ide

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")
 if err != nil {
   log.Fatal(err)
 }
 reader := csv.NewReader(bufio.NewReader(csvFile))
 record, err := reader.Read()
 if err != 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)
 if err != nil {
         log.Fatal(err)
 }
 fmt.Println(string(UserInfoBytes))
 if err := json.Unmarshal(UserInfoBytes, &UserInfoMap); err != nil {
     panic(err)
 }
 csvFile.Close()
 return UserInfoMap, UserID2
}
複製代碼

取得Ocean.one的市場價格信息

如何來查詢Ocean.one市場的價格信息呢?你要先了解你交易的基礎幣是什麼,若是你想買比特幣,賣出USDT,那麼基礎貨幣就是USDT;若是你想買USDT,賣出比特幣,那麼基礎貨幣就是比特幣.性能

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)
  if err != 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))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")

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

交易前,建立一個Memo!

在第二章裏,基於Mixin Network的 Go 比特幣開發教程: 機器人接受比特幣並當即退還用戶, 咱們學習過轉賬,這兒咱們介紹如何告訴Ocean.one,咱們給它轉賬的目的是什麼,信息所有放在memo裏.學習

  • Side 方向,"B" 或者 "A", "B"是購買, "A"是出售.
  • AssetUUID 目標虛擬資產的UUID.
  • Price 價格,若是操做方向是"B", 價格就是AssetUUID的價格; 若是操做方向是"B", 價格就是轉給Ocean.one幣的價格.
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)
}
複製代碼

出售XIN的例子

轉打算出售的 XIN 給Ocean.one(OCEANONE_BOT),將你打算換回來的目標虛擬資產的UUID放入memo.ui

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)
    if err != 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!") }
}
複製代碼

若是你是打算買XIN,操做以下:this

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)
    if err != 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
複製代碼

一個成功的掛單以下:

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":"2019-05-08T06:48:42.919216755Z",
"counter_user_id":"aaff5bef-42fb-4c9f-90e0-29f69176b7d4"}}
The Order id is 26ef0ec1-a60c-4702-b8ca-4bd40330e120 it is needed to cancel the order!
複製代碼

取消掛單

Ocean.one將trace_id當作訂單,好比上面的例子, 26ef0ec1-a60c-4702-b8ca-4bd40330e120 就是訂單號,咱們用他來取消訂單。

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!") }
}
複製代碼

經過讀取資產餘額,來確認到賬狀況

if cmd == "aw" {
  priKey, _, sID, userID, _ := GetWalletInfo()
  assets, err := mixin.ReadAssets(userID,sID,priKey)
  if err != nil {
      log.Fatal(err)
  }
  var AssetsInfo map[string]interface{}
  err = json.Unmarshal(assets, &AssetsInfo)
  if err != 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"])
    }
  }
}
複製代碼

源代碼執行

編譯執行,便可開始交易了.

  • go run coin_exchange.go 編譯項目.

本代碼執行時的命令列表:

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

完整代碼

相關文章
相關標籤/搜索