經過 Node.js 買賣Bitcoin

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

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

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

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

預備知識:

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

安裝依賴包

咱們須要依賴 msgpack5 and mixin-node-client ,第四章 已經作過介紹, 你應該先安裝過它了.github

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

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

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

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

if ( args.type === TYPE_WALLET_ASSETS_INFO ) {
  const assetsInfo = await newUserClient.getUserAssets();
  console.log("-AssetID--Asset--Balance--public_key--");
  assetsInfo.forEach(function(element) {
     console.log(element.asset_id + " " +
                 element.symbol + " " +
                 element.balance + " " +
                 element.public_key + " " +
                 element.account_name + " " +
                 element.account_tag
               );
   });
  // console.log(assetsInfo);
}
複製代碼

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

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

if ( args.type === TYPE_OO_FETCH_BTC_USDT ) {
  FetchOceanOneMarketInfos(BTC_ASSET_ID, USDT_ASSET_ID);
}
function FetchOceanOneMarketInfos(asset_id, base_asset) {
  var instance = axios.create({
  baseURL: "https://events.ocean.one/markets/" + asset_id + "-" + base_asset + "/book",
  timeout: 3000,
  headers: {'X-Custom-Header': 'foobar'}
  });
  instance.get()
  .then(function(response) {
    console.log("--Price--Amount--Funds--Side")
    response.data.data.data.asks.forEach(function(element) {
       console.log(element.price + " " +
                   element.amount + " " +
                   element.funds + " " +
                   element.side);
     });
     response.data.data.data.bids.forEach(function(element) {
        console.log(element.price + " " +
                    element.amount + " " +
                    element.funds + " " +
                    element.side);
      });
    // console.log(response.data.data.data.asks);
  });
}
複製代碼

交易前,建立一個Memo!

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

  • Side 方向,"B" 或者 "A", "B"是購買, "A"是出售.
  • AssetUuid 目標虛擬資產的UUID.
  • Price 價格,若是操做方向是"B", 價格就是AssetUUID的價格; 若是操做方向是"B", 價格就是轉給Ocean.one幣的價格.
function GenerateOceanMemo(targetAsset,side,price) {
  const bytes = Buffer.from(
    targetAsset.replace(/-/g, ''),
    'hex'
  );
  const memo = msgpack
    .encode({
      S: side,
      A: bytes,
      P: price,
      T: "L",
    })
    .toString('base64');
  console.log(memo);
  return memo;
}
複製代碼

買入XIN的代碼以下:學習

else if ( args.type === TYPE_OO_BUY_XIN_USDT ) {
  var prompts = [
    {
      name: 'price',
      type: 'input',
      message: "Input the price of XIN/USDT: ",
    },
  ];
  price = await inquirer.prompt(prompts);
  var prompts = [
    {
      name: 'amount',
      type: 'input',
      message: "Input the amount of USDT: ",
    },
  ];
  amount = await inquirer.prompt(prompts);
  console.log(price);
  console.log(amount);
  const memo = GenerateOceanMemo(XIN_ASSET_ID,"B",price.price);
  const assetInfo = await newUserClient.getUserAsset(USDT_ASSET_ID);
  console.log("The Wallet 's USDT balance is ", assetInfo.balance);
  if ( assetInfo.balance >= amount.amount && assetInfo.balance >= 1 ) {
    const Obj = {
      assetId: USDT_ASSET_ID,
      recipientId: OCEANONE_BOT,
        traceId: newUserClient.getUUID(),
        amount: amount.amount,
        memo: memo,
      }
      const transInfo = await newUserClient.transferFromBot(Obj);
      console.log(transInfo);
      console.log("The Order id is " + transInfo.trace_id + " It is needed to cancel the order!");
  } else {
    console.log("Not enough USDT!");
  }
}
複製代碼

出售XIN的例子

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

else if ( args.type === TYPE_OO_SELL_XIN_USDT ) {
  var prompts = [
    {
      name: 'price',
      type: 'input',
      message: "Input the price of XIN/USDT: ",
    },
  ];
  price = await inquirer.prompt(prompts);
  var prompts = [
    {
      name: 'amount',
      type: 'input',
      message: "Input the amount of XIN: ",
    },
  ];
  amount = await inquirer.prompt(prompts);
  console.log(price);
  console.log(amount);
  const memo = GenerateOceanMemo(XIN_ASSET_ID,"A",price.price);
  const assetInfo = await newUserClient.getUserAsset(BTC_ASSET_ID);
  console.log("The Wallet 's USDT balance is ", assetInfo.balance);
  if ( assetInfo.balance >= amount.amount ) {
    const Obj = {
      assetId: XIN_ASSET_ID,
      recipientId: OCEANONE_BOT,
        traceId: newUserClient.getUUID(),
        amount: amount.amount,
        memo: memo,
      }
      const transInfo = await newUserClient.transferFromBot(Obj);
      console.log(transInfo);
      console.log("The Order id is " + transInfo.trace_id + " It is needed to cancel the order!");
  } else {
    console.log("Not enough XIN!");
  }
}
複製代碼

一個成功的掛單以下:

? Input the price of XIN/USDT:  160
? Input the amount of USDT:  1
{ price: '160' }
{ amount: '1' }
hKFToUKhQcQQgVsLGidkNzaPqkLWlPpiCqFQozE2MKFUoUw=
The Wallet 's USDT balance is 1.995101 { type: 'transfer', snapshot_id: '14f144e4-0bd5-43aa-a7d4-70e7d5c695b0', opponent_id: 'aaff5bef-42fb-4c9f-90e0-29f69176b7d4', asset_id: '815b0b1a-2764-3736-8faa-42d694fa620a', amount: '-1', trace_id: 'd34f881b-4460-42d3-af91-551f97b20f74', memo: 'hKFToUKhQcQQgVsLGidkNzaPqkLWlPpiCqFQozE2MKFUoUw=', created_at: '2019-05-10T07:18:21.130357698Z', counter_user_id: 'aaff5bef-42fb-4c9f-90e0-29f69176b7d4' } The Order id is d34f881b-4460-42d3-af91-551f97b20f74 It is needed to cancel the order! 複製代碼

取消掛單

Ocean.one將trace_id當作訂單,好比上面的例子, d34f881b-4460-42d3-af91-551f97b20f74 就是訂單號,咱們用他來取消訂單。

else if ( args.type === TYPE_OO_CANCEL_ORDER ) {
  const prompts = [
    {
      name: 'order_id',
      type: 'input',
      message: "Input iso8601 datetime: ",
    },
  ];
  answers = await inquirer.prompt(prompts);
  const memo = GenerateOceanCancelMemo(answers.order_id);
  const assetInfo = await newUserClient.getUserAsset(CNB_ASSET_ID);
  console.log("The Wallet 's USDT balance is ", assetInfo.balance);
  if ( assetInfo.balance >= 0.00000001 ) {
    const Obj = {
      assetId: CNB_ASSET_ID,
      recipientId: OCEANONE_BOT,
        traceId: newUserClient.getUUID(),
        amount: "0.00000001",
        memo: memo,
      }
      const transInfo = await newUserClient.transferFromBot(Obj);
      console.log(transInfo);
  } else {
    console.log("Not enough CNB!");
  }
}
複製代碼

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

const assetsInfo = await newUserClient.getUserAssets();
console.log("-AssetID--Asset--Balance--public_key--");
assetsInfo.forEach(function(element) {
   console.log(element.asset_id + " " +
               element.symbol + " " +
               element.balance + " " +
               element.public_key + " " +
               element.account_name + " " +
               element.account_tag
             );
 });
複製代碼

源代碼執行

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

源代碼執行

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

  • node bitcoin-wallet-nodejs.js 運行.

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

Make your choose(select the uuid for open the specified wallet): 0b10471b-1aed-3944-9eda-5ab947562761 You select the : 0b10471b-1aed-3944-9eda-5ab947562761 You select the wallet 0b10471b-1aed-3944-9eda-5ab947562761 ? Make your choose (Use arrow keys)

  • ❯ aw: Read Wallet All Asssets Information
  • ab: Read Bot All Asssets Information
  • --------------OCean.One-------------------------
  • 19: Fetch BTC/USDT order book
  • 20: Fetch XIN/USDT order book
  • 21: Fetch ERC20/USDT order book
  • 22: Sell BTC/USDT
  • 23: Sell XIN/USDT
  • 24: Sell ERC20/USDT
  • 25: Buy BTC/USDT
  • 26: Buy XIN/USDT
  • 27: Buy ERC20/USDT
  • 28: Cancel the order
  • Exit

完整代碼

相關文章
相關標籤/搜索