利用Warensoft Stock Service編寫高頻交易軟體

来源:http://www.cnblogs.com/warensoft/archive/2017/01/10/6267764.html
-Advertisement-
Play Games

無論是哪種交易軟體,對於程式員來講,最麻煩的就是去實現各種演算法。本文以SAR演算法的實現過程為例,為大家說明如何使用Warensoft Stock Service來實現高頻交易軟體的快速開發。 目前WarensoftStockService已經實現了C# 版本的客戶端驅動,可以直接在Nuget上搜索... ...


利用Warensoft Stock Service編寫高頻交易軟體

 

無論是哪種交易軟體,對於程式員來講,最麻煩的就是去實現各種演算法。本文以SAR演算法的實現過程為例,為大家說明如何使用Warensoft Stock Service來實現高頻交易軟體的快速開發。

目前WarensoftStockService已經實現了C# 版本的客戶端驅動,可以直接在Nuget上搜索Warensoft並安裝。客戶端驅動已經編譯為跨平臺.net standard1.6版本,可以在桌面應用(WPFWinform)、Xamarin手機應用(WPAndroidIOS)、Webasp.net,asp.net core)中應用,操作系統可以是WindowAndroidIOSIMACLinux

下麵將以Android為例(註:本Demo可以直接平移到WPF中),說明SAR指標的實現過程,其他指標計算的綜合應用,在其他文章中會專門講解。

 

  1. 軟體環境說明

 

 

IDE

VS2017 RC

客戶端

Android4.4

伺服器環境

Ubuntu16

客戶端運行環境

Xamarin.Forms

客戶端圖形組件

Oxyplot

 

  1. 建立一個Xamarin.Forms手機App

 這裡選擇基於XAMLApp,註意共用庫使用PCL

 

 

 

 

 工程目錄下圖所示:

 

 

  1. 添加Nuget引用包

 

首先,為Warensoft.StockApp共用庫添加Oxyplot引用(此處可能需要科學上網),如下圖所示:

 

 

 

 

然後再分別安裝Warensoft.EntLib.Common,Warensoft.EntLib.StockServiceClient,如下圖所示:

 

 

 

然後為Warensoft.StockApp.Droid添加OxyPlotNuGet引用,如下所示:

 

 

然後在AndroidMainActivity中加入平臺註冊代碼:

OxyPlot.Xamarin.Forms.Platform.Android.PlotViewRenderer.Init();

 

MainActivity.cs的代碼如下所示:

 

protected override void OnCreate(Bundle bundle)

        {

            TabLayoutResource = Resource.Layout.Tabbar;

            ToolbarResource = Resource.Layout.Toolbar;

            OxyPlot.Xamarin.Forms.Platform.Android.PlotViewRenderer.Init();

            base.OnCreate(bundle);

 

            global::Xamarin.Forms.Forms.Init(this, bundle);

            LoadApplication(new App());

        }

 

 

  1. 實現主視窗

 

主界面的實現採用MVVM模式來實現,關於MVVM的講解,網上應該有很多了,後面的文章中,我會把我自己的理解寫出來,讓大家分享。本DEMOMVVM框架已經集成在了Warensoft.EntLib.Common中,使用起來很簡單。

 

第一步:

編寫主界面(需要瞭解XAML語法),並修改MainPage.xaml,如代碼如下:

<?xml version="1.0" encoding="utf-8" ?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

             xmlns:local="clr-namespace:Warensoft.StockApp"

             xmlns:oxy="clr-namespace:OxyPlot.Xamarin.Forms;assembly=OxyPlot.Xamarin.Forms"

             x:Class="Warensoft.StockApp.MainPage">

    <!--

    此處要註意在頭中註冊OxyPlot的命名空間

    xmlns:oxy="clr-namespace:OxyPlot.Xamarin.Forms;assembly=OxyPlot.Xamarin.Forms"-->

    <Grid>

        <!--此處添加圖形組件-->

        <oxy:PlotView Model="{Binding Model}" VerticalOptions="Center" HorizontalOptions="Center" />

    </Grid>

 

</ContentPage>

 

第二步:

打開MainPage.xaml.cs併為視圖(圖面)添加其對應的模型,代碼如下(註意要引入Warensoft.EntLib.Common):

public partial class MainPage : ContentPage

    {

        public MainPage()

        {

            InitializeComponent();

            //此處註冊ViewModel

            this.BindingContext = new MainPageViewModel();

        }

    }

    public class MainPageViewModel : ViewModelBase

    {

        public override Task ShowCancel(string title, string message)

        {

            throw new NotImplementedException();

        }

 

        public override Task<bool> ShowConfirm(string title, string message)

        {

            throw new NotImplementedException();

        }

 

        public override void ShowMessage(string message)

        {

            Application.Current.MainPage.DisplayAlert("提示",message,"OK");

        }

 

        protected override void InitBindingProperties()

        {

            

        }

}

 

第三步:

定義圖像組件的模型,併為圖像添加XY坐標軸,添加一個K線和一條直線,代碼如下所示:

      

  public PlotModel Model

        {

            get { return this.GetProperty<PlotModel>("Model"); }

            set { this.SetProperty("Model", value); }

        }

 

        protected override void InitBindingProperties()

        {

            this.Model = new PlotModel();

            //添加X、Y軸

            this.Model.Axes.Add(new OxyPlot.Axes.DateTimeAxis()

            {

                Position = AxisPosition.Bottom,

                StringFormat = "HH:mm",

                MajorGridlineStyle = LineStyle.Solid,

                IntervalType = DateTimeIntervalType.Minutes,

                IntervalLength = 30,

 

                MinorIntervalType = DateTimeIntervalType.Minutes,

                Key = "Time",

 

            });

 

            this.Model.Axes.Add(new OxyPlot.Axes.LinearAxis()

            {

                Position = AxisPosition.Right,

                MajorGridlineStyle = LineStyle.Solid,

                MinorGridlineStyle = LineStyle.Dot,

                IntervalLength = 30,

                IsPanEnabled = false,

                IsZoomEnabled = false,

                TickStyle = TickStyle.Inside,

            });

            //添加K線和直線

            this.candle = new OxyPlot.Series.CandleStickSeries();

            this.line = new OxyPlot.Series.LineSeries() { Color = OxyColors.Blue };

            this.Model.Series.Add(this.candle);

            this.Model.Series.Add(this.line);

        }

 

第四步:

添加獲取K線函數(以OKCoin為例),代碼如下:

/// <summary>

        /// 讀取OKCoin的15分鐘K線

        /// </summary>

        /// <returns></returns>

        public async Task<List<Kline>> LoadKline()

        {

            var url = $"https://www.okcoin.cn/api/v1/kline.do?symbol=btc_cny&type=15min&size=100";

            HttpClient client = new HttpClient();

            var result = await client.GetStringAsync(url);

 

            dynamic k = Newtonsoft.Json.JsonConvert.DeserializeObject(result);

            List<Kline> lines = new List<Kline>();

            int index = 0;

            foreach (var item in k)

            {

                List<double> d = new List<double>();

                foreach (var dd in item)

                {

                    d.Add((double)((dynamic)dd).Value);

                }

                lines.Add(new Kline() { Data = d.ToArray()});

                index++;

            }

            return lines;

        }

 

第五步:

添加定時刷新並繪製圖像的函數,代碼如下所示:

private StockServiceDriver driver;

        public async Task UpdateData()

        {

            //初始化WarensoftSocketService客戶端驅動,此處使用的是測試用AppKey和SecretKey

            this.driver = new StockServiceDriver("C6651783-A3B9-4B72-8B02-A2E67A59C5A6", "6C442B3AF58D4DDA81BB03B353C0D7D8");

            await Task.Run(async()=>

            {

                while (true)

                {

                    try

                    {

                        //讀取K線

                        var kline =await this.LoadKline();

                        //遠程Warensoft Stock Service 分析SAR曲線

                        var sar = await this.driver.GetSAR(kline);

 

                        //繪圖,註意辦為需要更新UI,因此需要在主線程中執行更新代碼

                        this.SafeInvoke(()=> {

                            //每次更新前,需要將舊數據清空

                            this.candle.Items.Clear();

                            this.line.Points.Clear();

 

                            foreach (var item in kline.OrderBy(k=>k.Time))

                            {

                                //註意將時間改為OxyPlot能識別的格式

                                var time = OxyPlot.Axes.DateTimeAxis.ToDouble(item.Time);

                                this.candle.Items.Add(new HighLowItem(time,item.High,item.Low,item.Open,item.Close));

                            }

                            if (sar.OperationDone)

                            {

                                foreach (var item in sar.AdditionalData.OrderBy(s=>s.DateTime))

                                {

                                    var time= OxyPlot.Axes.DateTimeAxis.ToDouble(item.DateTime);

                                    this.line.Points.Add(new DataPoint(time, item.Value));

                                }

                            }

                            //更新UI

                            this.Model.InvalidatePlot(true);

                        });

                    }

                    catch (Exception ex)

                    {

 

                         

                    }

                    await Task.Delay(5000);

                }

            });

        }

 

完整的ViewModel代碼如下:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Xamarin.Forms;

using Warensoft.EntLib.Common;

using Warensoft.EntLib.StockServiceClient;

using OxyPlot;

using OxyPlot.Axes;

using OxyPlot.Series;

using Warensoft.EntLib.StockServiceClient.Models;

using System.Net.Http;

 

namespace Warensoft.StockApp

{

    public partial class MainPage : ContentPage

    {

        public MainPage()

        {

            InitializeComponent();

            this.BindingContext = new MainPageViewModel();

        }

    }

    public class MainPageViewModel : ViewModelBase

    {

        private CandleStickSeries candle;

        private LineSeries line;

 

        public override Task ShowCancel(string title, string message)

        {

            throw new NotImplementedException();

        }

 

        public override Task<bool> ShowConfirm(string title, string message)

        {

            throw new NotImplementedException();

        }

 

        public override void ShowMessage(string message)

        {

            Application.Current.MainPage.DisplayAlert("提示",message,"OK");

        }

 

 

        public PlotModel Model

        {

            get { return this.GetProperty<PlotModel>("Model"); }

            set { this.SetProperty("Model", value); }

        }

 

        protected override void InitBindingProperties()

        {

            this.Model = new PlotModel();

            //添加X、Y軸

            this.Model.Axes.Add(new OxyPlot.Axes.DateTimeAxis()

            {

                Position = AxisPosition.Bottom,

                StringFormat = "HH:mm",

                MajorGridlineStyle = LineStyle.Solid,

                IntervalType = DateTimeIntervalType.Minutes,

                IntervalLength = 30,

 

                MinorIntervalType = DateTimeIntervalType.Minutes,

                Key = "Time",

 

            });

 

            this.Model.Axes.Add(new OxyPlot.Axes.LinearAxis()

            {

                Position = AxisPosition.Right,

                MajorGridlineStyle = LineStyle.Solid,

                MinorGridlineStyle = LineStyle.Dot,

                IntervalLength = 30,

                IsPanEnabled = false,

                IsZoomEnabled = false,

                TickStyle = TickStyle.Inside,

            });

            //添加K線和直線

            this.candle = new OxyPlot.Series.CandleStickSeries();

            this.line = new OxyPlot.Series.LineSeries() { Color = OxyColors.Blue };

            this.Model.Series.Add(this.candle);

            this.Model.Series.Add(this.line);

            this.UpdateData();

        }

 

        /// <summary>

        /// 讀取OKCoin的15分鐘K線

        /// </summary>

        /// <returns></returns>

        public async Task<List<Kline>> LoadKline()

        {

            var url = $"https://www.okcoin.cn/api/v1/kline.do?symbol=btc_cny&type=15min&size=100";

            HttpClient client = new HttpClient();

            var result = await client.GetStringAsync(url);

 

            dynamic k = Newtonsoft.Json.JsonConvert.DeserializeObject(result);

            List<Kline> lines = new List<Kline>();

            int index = 0;

            foreach (var item in k)

            {

                List<double> d = new List<double>();

                foreach (var dd in item)

                {

                    d.Add((double)((dynamic)dd).Value);

                }

                lines.Add(new Kline() { Data = d.ToArray()});

                index++;

            }

            return lines;

        }

        private StockServiceDriver driver;

        public async Task UpdateData()

        {

            //初始化WarensoftSocketService客戶端驅動,此處使用的是測試用AppKey和SecretKey

            this.driver = new StockServiceDriver("C6651783-A3B9-4B72-8B02-A2E67A59C5A6", "6C442B3AF58D4DDA81BB03B353C0D7D8");

            await Task.Run(async()=>

            {

                while (true)

                {

                    try

                    {

                        //讀取K線

                        var kline =await this.LoadKline();

                        //遠程Warensoft Stock Service 分析SAR曲線

                        var sar = await this.driver.GetSAR(kline);

 

                        //繪圖,註意辦為需要更新UI,因此需要在主線程中執行更新代碼

                        this.SafeInvoke(()=> {

                            //每次更新前,需要將舊數據清空

                            this.candle.Items.Clear();

                            this.line.Points.Clear();

 

                            foreach (var item in kline.OrderBy(k=>k.Time))

                            {

                                //註意將時間改為OxyPlot能識別的格式

                                var time = OxyPlot.Axes.DateTimeAxis.ToDouble(item.Time);

                                this.candle.Items.Add(new HighLowItem(time,item.High,item.Low,item.Open,item.Close));

                            }

                            if (sar.OperationDone)

                            {

                                foreach (var item in sar.AdditionalData.OrderBy(s=>s.DateTime))

                                {

                                    var time= OxyPlot.Axes.DateTimeAxis.ToDouble(item.DateTime);

                                    this.line.Points.Add(new DataPoint(time, item.Value));

                                }

                            }

                            //更新UI

                            this.Model.InvalidatePlot(true);

                        });

                    }

                    catch (Exception ex)

                    {

 

                         

                    }

                    await Task.Delay(5000);

                }

            });

        }

    }

}

 

最後編譯,並部署到手機上,最終運行效果如下:

 

 

最終編譯完畢的APK文件(下載)。

 

 作者:科學家

                                                    Email[email protected]

                                                    微信:43175692


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 之前的博文中有介紹關於圖片輪播的實現方式,分別為(含超鏈接): 1、《Android中使用ViewFlipper實現屏幕切換》 2、《Android中使用ViewPager實現屏幕頁面切換和頁面輪播效果》 3、《Android中使用ImageViewSwitcher實現圖片切換輪播導航效果》 今天通 ...
  • 輪播圖是很常用的一個效果 核心功能已經實現 沒有什麼特殊需求 自己沒事研究的 所以封裝的不太好 一些地方還比較糙 為想要研究輪播圖的同學提供個參考 目前測試圖片為mipmap中的圖片 沒有寫從網路載入圖片 可自行根據需求在getShowView()方法中修改 1.定時切換 通過handle延時發送通 ...
  • 一、簡述 最近項目組打算引入weex,並選定了一個頁面進行試水。頁面很簡單,主要是獲取數據渲染頁面,並可以跳轉到指定的頁面。跟之前使用RN 相比,weex 確實要簡單很多。從下圖中我們可以看到,weex 頁面需要跳轉到原生頁面,並且跳轉到哪個頁面我們可能並不能寫死。也就是說只要原生頁面之前項目中寫過 ...
  • 360手機助手使用的 DroidPlugin,它是360手機助手團隊在Android系統上實現了一種插件機制。它可以在無需安裝、修改的情況下運行APK文件,此機制對改進大型APP的架構,實現多團隊協作開發具有一定的好處。 它是一種新的插件機制,一種免安裝的運行機制 github地址: https:/ ...
  • 昨天1月9日微信小程式發佈,頓時被朋友圈刷爆,今天看了一下官方文檔,自己開始一步一步搭建環境體驗小程式開發。 常見問題: 1.微信小程式開發是否需要重新創建開發者賬號? 需要,即使之前申請了微信服務號,並認證過,也需要重新申請小程式。 在微信公眾平臺官網首頁(mp.weixin.qq.com)點擊右 ...
  • 1. #import導入頭文件,即:導入頭文件中的內容到當前類 2. #import “”導⼊自定義類,#import <>導入類庫中的頭文件。 3.功能類似C語言中的#include,但是可以避免頭文件被重覆導 入。(也即可以自動避免) 4. 容易出現迴圈導入頭文件問題。 針對上面4的迴圈導入頭文 ...
  • 一、錯誤提示 今天在開發的時候遇到一個崩潰問題,“This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird c ...
  • 前言 最近項目集成了Tinker,開始認為集成會比較簡單,但是在實際操作的過程中還是遇到了一些問題,本文就會介紹在集成過程大家基本會遇到的主要問題。 考慮一:後臺的選取 目前後臺功能可以通過三種方式實現: 1、自己搭建後臺布丁下發系統2、第三方提供的服務,目前如原微信simsun大神的個人tinke ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...