Buy and sell bitcoin through nodejs

Time:2019-11-4

Buy and sell bitcoin through nodejs
The previous chapter introduced exincore, where you can buy and sell assets at market price in one second. You need oceanone if you want to limit price trading, or buy and sell assets that are not supported by exincore.

Scheme II: ocean.one exchange

Ocean.one is a decentralized exchange based on mixin network, with first-class performance.
You can trade any asset on oceanone. Just transfer your currency to oceanone and write the transaction information in the memo of the transaction. Oceanone will list your transaction needs in the market,
After the transaction is successful, the target currency will be transferred to your mixin network account, which has three major features and advantages:

  • No need to register with oceanone
  • No need to deposit money to the exchange
  • Support all assets that can be transferred on mixin network and all erc20 EOS tokens.

Preparatory knowledge:

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

Install dependency packages

We need to rely onmsgpack5 and mixin-node-client, Chapter 4 has been introduced. You should have installed it first

Charge it to mixin network and read out its balance

Here is a demonstration of buying BTC with usdt or buying usdt with BTC. Check your wallet address before you trade.
The complete steps are as follows:

  • Check the balance and wallet address of bitcoin or usdt. And write down the address of the wallet.
  • From a third-party exchange or your cold wallet, charge the money to the wallet address above.
  • Check the balance of the currency again to see whether the account is good or not. (bitcoin’s arrival time is the height of five blocks, about 100 minutes).

Bitcoin and usdt have the same recharge address.

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);
}

Obtain market price information of ocean.one

How to query the price information of ocean.one market? You should first understand what the base currency you are trading is. If you want to buy bitcoin and sell usdt, the base currency is usdt; if you want to buy usdt and sell bitcoin, the base currency is bitcoin

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);
  });
}

Create a memo before trading!

In the second chapter, nodejs bitcoin development tutorial based on mixin network: robots accept bitcoin and return it to users immediately. We have learned how to transfer accounts. Here we introduce how to tell ocean.one what we want to transfer accounts for and put all information in memo

  • SideDirection, “B” or “a”, “B” is purchase, and “a” is sale
  • AssetUuidUUID of the target virtual asset
  • PricePrice: if the operation direction is “B”, the price is the price of assetuuid; if the operation direction is “B”, the price is the price transferred to 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;
}

The code to buy Xin is as follows:

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!");
  }
}

Example of Xin sold

Transfer the Xin you plan to sell to ocean. One (ocean one? BOT), and put the UUID of the target virtual asset you plan to exchange back into memo

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!");
  }
}

A successful list is as follows:

? 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!

Cancel the list

Ocean.one uses trace Ou ID as an order, such as the above example,d34f881b-4460-42d3-af91-551f97b20f74It’s the order number. We use him to cancel the order.

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!");
  }
}

Confirm receipt by reading asset balance

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
             );
 });

Source code execution

Compile and execute to start the transaction

Source code execution

Compile and execute to start the transaction

  • [x] node bitcoin-wallet-nodejs.jsFunction.

Command list when this code is executed:

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

Complete code

Recommended Today

Details of multi-path and large capacity hard disk mount under CentOS

I. application environment and requirementsBlade servers connect HP storage through fiber switches, forming a 2×2 link The storage capacity of the operating system for CentOS 6.4 64 bit mount is 2.5t Based on this application environment, two problems need to be solved: In order to ensure the stability and transmission performance of the link, multi-path […]