經過 C# 買賣Bitcoin

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

方案二: 在去中心化交易所OceanOne上掛單買賣Bitcoin

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

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

預備知識:

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

安裝依賴包

咱們須要依賴 MsgPack.Cli and mixin-csharp-sdk ,第四章 已經作過介紹, 你應該先安裝過它了.bash

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

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

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

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

if (cmd == "aw" ) {
    // Console.WriteLine(mixinApi.VerifyPIN(USRCONFIG.PinCode.ToString()).ToString());
    MixinApi mixinApiNewUser = GetWalletSDK();
    var assets = mixinApiNewUser.ReadAssets();
    string wuuid = GetWalletUUID();
    Console.WriteLine("Current wallet uuid is " + wuuid);
    foreach (Asset asset in assets)
    {
      if (asset.symbol == "EOS") {
       Console.WriteLine(asset.symbol + " Public Address is: " +
                         asset.account_name + " " +
                         asset.account_tag +
                         " Balance is: " + asset.balance);
     } else Console.WriteLine(asset.symbol + " Public Address is: " +
                              asset.public_key + " Balance is: " +
                              asset.balance);
    Console.WriteLine();
    }
}
複製代碼

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

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

public class MarketInfoOcean
{
    public Omarket data { get; set; }
}
public class Omarket {
  public string market { get; set; }
  public string timestamp  { get; set; }
  public Side data { get; set; }
}
public class Side {
  public List<order> asks  { get; set; }
  public List<order> bids  { get; set; }
}
public class order {
  public string amount { get; set; }
  public string funds { get; set; }
  public string price { get; set; }
  public string side { get; set; }
}

if (cmdo == "1") {
  string jsonData = FetchOceanMarketPrice(USRCONFIG.XIN_ASSET_ID,USRCONFIG.ASSET_ID_USDT);
  // string jsonData = FetchMarketPrice("c6d0c728-2624-429b-8e0d-d9d19b6592fa");
  var marketObj = JsonConvert.DeserializeObject<MarketInfoOcean>(jsonData);
  Console.WriteLine("--Price--Amount---Funds---Side----");
  foreach (order value in marketObj.data.data.asks)
  {
      Console.WriteLine(value.price + " " + value.amount + " " + value.funds + " " + value.side);
  }
  foreach (order value in marketObj.data.data.bids)
  {
      Console.WriteLine(value.price + " " + value.amount + " " + value.funds + " " + value.side);
  }
}
public static string FetchOceanMarketPrice(string asset_id, string base_asset) {
    return FetchOceanMarketPriceAsync(asset_id,base_asset).Result;
}
public static async Task<string> FetchOceanMarketPriceAsync(string asset_id, string base_asset) {
  HttpClient client = new HttpClient();
  string baseUrl = "https://events.ocean.one/markets/" + asset_id + "-" + base_asset + "/book";
  try
  {
     HttpResponseMessage response = await client.GetAsync(baseUrl);
     response.EnsureSuccessStatusCode();
     string responseBody = await response.Content.ReadAsStringAsync();
     // Above three lines can be replaced with new helper method below
     // string responseBody = await client.GetStringAsync(uri);
     Console.WriteLine(responseBody);
     return responseBody;
  }
  catch(HttpRequestException e)
  {
     Console.WriteLine("\nException Caught!");
     Console.WriteLine("Message :{0} ",e.Message);
  }
  return null;
}
複製代碼

交易前,建立一個Memo!

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

  • Side 方向,"B" 或者 "A", "B"是購買, "A"是出售.
  • AssetUuid 目標虛擬資產的UUID.
  • Price 價格,若是操做方向是"B", 價格就是AssetUUID的價格; 若是操做方向是"B", 價格就是轉給Ocean.one幣的價格.
private static string GenerateOrderMemo(string Side, string AssetUuid, string Price) {
  Hashtable temp = new Hashtable();
  temp.Add("S","A");
  temp.Add("A",StringGuid2Bytes(AssetUuid));
  temp.Add("P",Price);
  temp.Add("T","L");
  var serializer3 = MessagePackSerializer.Get<Hashtable>();
  var stream3 = new MemoryStream();
  serializer3.Pack(stream3, temp);
  string memo = Convert.ToBase64String(stream3.ToArray());
  return memo;
}
複製代碼

買入XIN的代碼以下:學習

public static string  OCEANONE_BOT   = "aaff5bef-42fb-4c9f-90e0-29f69176b7d4";
public static string  ASSET_ID_BTC   = "c6d0c728-2624-429b-8e0d-d9d19b6592fa";
public static string  ASSET_ID_EOS   = "6cfe566e-4aad-470b-8c9a-2fd35b49c68d";
public static string  ASSET_ID_USDT  = "815b0b1a-2764-3736-8faa-42d694fa620a";

public static string  XIN_ASSET_ID   = "c94ac88f-4671-3976-b60a-09064f1811e8";

if ( cmdo == "b1") {
  Console.WriteLine("Please input the price of XIN/USDT: ");
  var pinput = Console.ReadLine();
  Console.WriteLine("Please input the amount of USDT: ");
  var ainput = Console.ReadLine();

  string memo = GenerateOrderMemo("A",USRCONFIG.ASSET_ID_USDT,pinput);
  Console.WriteLine(memo);
  MixinApi mixinApiNewUser = GetWalletSDK();
  var assets = mixinApiNewUser.ReadAsset(USRCONFIG.ASSET_ID_USDT);
  Console.WriteLine(assets.balance);
  float balance = float.Parse(assets.balance);
  float amount  = float.Parse(ainput);
  if ( ( balance >= 1.0 ) && ( balance >= amount ) ) {
    Transfer reqInfo = mixinApiNewUser.Transfer(USRCONFIG.ASSET_ID_USDT,
                            USRCONFIG.OCEANONE_BOT,
                            ainput,
                            GetWalletPinCode(),
                            System.Guid.NewGuid().ToString(),
                            memo);
    Console.WriteLine(reqInfo);
    Console.WriteLine("Order id is " + reqInfo.trace_id);
  } else Console.WriteLine("Not enough USDT!");
}

複製代碼

出售XIN的例子

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

if ( cmdo == "s1") {
  Console.WriteLine("Please input the price of XIN/USDT: ");
  var pinput = Console.ReadLine();
  Console.WriteLine("Please input the amount of XIN: ");
  var ainput = Console.ReadLine();
  string memo = GenerateOrderMemo("B",USRCONFIG.XIN_ASSET_ID,pinput);
  Console.WriteLine(memo);
  // Console.WriteLine(Convert.ToBase64String(stream3.ToArray()));
  MixinApi mixinApiNewUser = GetWalletSDK();
  var assets = mixinApiNewUser.ReadAsset(USRCONFIG.XIN_ASSET_ID);
  float balance = float.Parse(assets.balance);
  float amount  = float.Parse(ainput);
  if ( ( balance >= 0 ) && ( balance >= amount ) ) {
    Transfer reqInfo = mixinApiNewUser.Transfer(USRCONFIG.XIN_ASSET_ID,
                            USRCONFIG.OCEANONE_BOT,
                            ainput,
                            GetWalletPinCode(),
                            System.Guid.NewGuid().ToString(),
                            memo);
    Console.WriteLine(reqInfo);
    Console.WriteLine("Order id is " + reqInfo.trace_id);
  } else Console.WriteLine("Not enough XIN!");
}
複製代碼

一個成功的掛單以下:

Please input the price of XIN/USDT:
110
Please input the amount of USDT:
1
hKFBxBDJSsiPRnE5drYKCQZPGBHooVShTKFToUKhUKMxMTA=
1
{"type":"transfer","snapshot_id":"fe04c667-3ad9-4f2b-b205-ba2cef3733ea",
"opponent_id":"aaff5bef-42fb-4c9f-90e0-29f69176b7d4",
"asset_id":"815b0b1a-2764-3736-8faa-42d694fa620a","amount":"-1",
"trace_id":"12cd76aa-e953-4897-bef0-18123a5e69dc",
"memo":"hKFBxBDJSsiPRnE5drYKCQZPGBHooVShTKFToUKhUKMxMTA=",
"created_at":"2019-05-06T06:43:13.488971627Z"}
Order id is 12cd76aa-e953-4897-bef0-18123a5e69dc
複製代碼

取消掛單

Ocean.one將trace_id當作訂單,好比上面的例子, 12cd76aa-e953-4897-bef0-18123a5e69dc 就是訂單號,咱們用他來取消訂單。

if ( cmdo == "c") {
  Console.WriteLine("Please input the Order id: ");
  var oinput = Console.ReadLine();
  Hashtable temp = new Hashtable();
  temp.Add("O",StringGuid2Bytes(oinput));
  var serializer3 = MessagePackSerializer.Get<Hashtable>();
  var stream3 = new MemoryStream();
  serializer3.Pack(stream3, temp);
  string memo = Convert.ToBase64String(stream3.ToArray());
  MixinApi mixinApiNewUser = GetWalletSDK();
  var assets = mixinApiNewUser.ReadAsset(USRCONFIG.CNB_ASSET_ID);
  Console.WriteLine(assets.balance);
  float balance = float.Parse(assets.balance);
  if (  balance >= 0  ) {
    Transfer reqInfo = mixinApiNewUser.Transfer(USRCONFIG.CNB_ASSET_ID,
                            USRCONFIG.OCEANONE_BOT,
                            "0.0000001",
                            GetWalletPinCode(),
                            System.Guid.NewGuid().ToString(),
                            memo);
    Console.WriteLine(reqInfo);
  } else Console.WriteLine("Not enough CNB!");
  }
複製代碼

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

MixinApi mixinApiNewUser = GetWalletSDK();
var assets = mixinApiNewUser.ReadAssets();
複製代碼

源代碼執行

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

源代碼執行

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

  • dotnet build 編譯項目.
  • dotnet bin/Debug/netcoreapp2.2/bitcoin_wallet.dll 運行它.

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

Commands list of this source code:

  • 1: Create Bitcoin Wallet and update PIN
  • 2: Read Bitcoin balance & address
  • 3: Read USDT balance & address
  • 4: Read EOS balance & address
  • tub: Transfer USDT from Bot to Wallet
  • tum: Transfer USDT from Wallet to Master
  • tcb: Transfer CNB from Bot to Wallet
  • tcm: Transfer CNB from Wallet to Master
  • txb: Transfer XIN from Bot to Wallet
  • txm: Transfer XIN from Wallet to Master
  • 5: pay 0.0001 BTC buy USDT
  • 6: pay $1 USDT buy BTC
  • 7: Read Snapshots
  • 8: Fetch market price(USDT)
  • 9: Fetch market price(BTC)
  • v: Verify Wallet Pin
  • ab: Read Bot Assets
  • aw: Read Wallet Assets
  • o: OceanOne Trading
  • q: Exit Make your choose:

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

Make your choose: o

  • 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
  • c: Cancel Order
  • q: Exit

完整代碼

相關文章
相關標籤/搜索