虚拟货币(比特币,以太坊)价值预测

缘由:好友开发了一个程序化交易虚拟货币的助手软件。卖的火热(想购买的朋友请加微信: endpang )。出于对土豪的敬意,抽时间做一个时序预测的东西。

财富自由之路开始。。。。

首先得获得实时的价格数据,

火币网的接口:https://github.com/huobiapi/API_Docs/wiki/REST_introduction

websocket 获得实时数据并将价格写入文本文件

from websocket import create_connection
import gzip
import time
import json




if __name__ == '__main__':
    while(1):
        try:
            ws = create_connection("wss://api.huobipro.com/ws")
            break
        except:
            print('connect ws error,retry...')
            time.sleep(5)

    # 订阅 KLine 数据
    tradeStr="""{"sub": "market.ethusdt.kline.1min","id": "id10"}"""

    # 请求 KLine 数据
    # tradeStr="""{"req": "market.ethusdt.kline.1min","id": "id10", "from": 1513391453, "to": 1513392453}"""

    #订阅 Market Depth 数据
    # tradeStr="""{"sub": "market.ethusdt.depth.step5", "id": "id10"}"""

    #请求 Market Depth 数据
    # tradeStr="""{"req": "market.ethusdt.depth.step5", "id": "id10"}"""

    #订阅 Trade Detail 数据
    # tradeStr="""{"sub": "market.ethusdt.trade.detail", "id": "id10"}"""

    #请求 Trade Detail 数据
    # tradeStr="""{"req": "market.ethusdt.trade.detail", "id": "id10"}"""

    #请求 Market Detail 数据
    # tradeStr="""{"req": "market.ethusdt.detail", "id": "id12"}"""

    ws.send(tradeStr)
    old = {"vol": 0,"count":0,"close":0}
    i = 0
    with open('test_csv.csv',"w") as csv:
        #csv.write("lines\n")
        while(1):

            compressData=ws.recv()
            result=gzip.decompress(compressData).decode('utf-8')
            if result[:7] == '{"ping"':

                ts=result[8:21]
                pong='{"pong":'+ts+'}'
                ws.send(pong)
                ws.send(tradeStr)
            elif result[:5] == '{"ch"':
                arr = json.loads(result)
                #print("arr",arr)

                if arr['tick']['count'] < old["count"]:
                    i = i+1
                    csv.write(format(old['close'])+"\n")
                    print('count',old)
                else:
                    delta = arr['tick']['vol'] - old['vol']
                    print("delta:",delta)
                    if delta > 0:
                        deltap = arr['tick']['close'] -  old["close"]

                        print("deltap",deltap)
                old = arr['tick']

基于tensorflow  lstm 的预测模型。

import lstm
import time
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

def plot_results(predicted_data, true_data):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    plt.plot(predicted_data, label='Prediction')
    plt.legend()
    plt.show()

def plot_results_multiple(predicted_data, true_data, prediction_len):
    fig = plt.figure(facecolor='white')
    ax = fig.add_subplot(111)
    ax.plot(true_data, label='True Data')
    #Pad the list of predictions to shift it in the graph to it's correct start
    for i, data in enumerate(predicted_data):
        padding = [None for p in range(i * prediction_len)]
        plt.plot(padding + data, label='Prediction')
        plt.legend()
    plt.show()

#Main Run Thread
if __name__=='__main__':
	global_start_time = time.time()
	epochs  = 1
	seq_len = 50

	print('> Loading data... ')

	X_train, y_train, X_test, y_test = lstm.load_data('test_csv.csv', seq_len, True)

	print('> Data Loaded. Compiling...')

	model = lstm.build_model([1, 50, 100, 1])

	model.fit(
	    X_train,
	    y_train,
	    batch_size=512,
	    nb_epoch=epochs,
	    validation_split=0.05)

	predictions = lstm.predict_sequences_multiple(model, X_test, seq_len, 50)
	#predicted = lstm.predict_sequence_full(model, X_test, seq_len)
	#predicted = lstm.predict_point_by_point(model, X_test)        

	print('Training duration (s) : ', time.time() - global_start_time)
	plot_results_multiple(predictions, y_test, 50)

市场有风险,交易需谨慎。不准莫怪我,预测准的,写出来也不会开放代码的。。。 : P

以太币私有链搭建教程

sudo apt-get update

sudo apt-get install software-properties-common

sudo add-apt-repository -y ppa:ethereum/ethereum

sudo add-apt-repository -y ppa:ethereum/ethereum-dev

sudo apt-get update

sudo apt-get install ethereum

geth #启动

创始块配置文件 piccgenesis.json

{
  "config": {
        "chainId": 10,
        "homesteadBlock": 0,
        "eip155Block": 0,
        "eip158Block": 0
    },
  "alloc"      : {},
  "coinbase"   : "0x0000000000000000000000000000000000000000",
  "difficulty" : "0x02000000",
  "extraData"  : "",
  "gasLimit"   : "0x2fefd8",
  "nonce"      : "0x0000000000000042",
  "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
  "timestamp"  : "0x00"
}

mixhash

与nonce配合用于挖矿,由上一个区块的一部分生成的hash。注意他和nonce的设置需要满足以太坊的Yellow paper, 4.3.4. Block Header Validity, (44)章节所描述的条件。.
nonce nonce就是一个64位随机数,用于挖矿,注意他和mixhash的设置需要满足以太坊的Yellow paper, 4.3.4. Block Header Validity, (44)章节所描述的条件。
difficulty 设置当前区块的难度,如果难度过大,cpu挖矿就很难,这里设置较小难度
alloc 用来预置账号以及账号的以太币数量,因为私有链挖矿比较容易,所以我们不需要预置有币的账号,需要的时候自己创建即可以。
coinbase 矿工的账号,随便填
timestamp 设置创世块的时间戳
parentHash 上一个区块的hash值,因为是创世块,所以这个值是0
extraData 附加信息,随便填,可以填你的个性信息
gasLimit 该值设置对GAS的消耗总量限制,用来限制区块能包含的交易信息总和,因为我们是私有链,所以填最大。
geth  --datadir "Your/Path" init piccgenesis.json

创建数据存放地址并初始化创世块

geth --identity "YourName"  --rpc  --rpccorsdomain "*" --datadir "Your/Path" --port "30303"  --rpcapi "db,eth,net,web3" --networkid  95518  console

#如果nohup 请去掉 console

从第二个节点连接。创建目录并将piccgenesis.json拷贝进去。

geth --datadir . init ./piccgenesis.json  #初始化目录
geth --datadir . --networkid 95518 --ipcdisable --port 61911 --rpcport 8101 --bootnodes "enode://8a0127669dc890530d868aa2a08efaff12933c885da21882ed935f563b7cdb7aa3497aa24807bc348c143017dba4c4433d97e64571a1962e257726a7c0725ed8@172.18.100.205:8888" console

创建账号

personal.newAccount()

#启动挖矿
miner.start()

#查看账户余额,不为零即已经在挖矿了
eth.getBalance(eth.accounts[0])

显卡挖矿

下载二进制安装包

https://github.com/ethereum-mining/ethminer/releases

或(注意两种安装方式的命令不一样,请  -h 查看)

apt-get install ethminer
ethminer -G

解锁账户

personal.unlockAccount("0x00530bc8552639fd8479c22f403e84fe5e98896f","===pwd===")

转账3以太币

eth.sendTransaction({from:"0x00530bc8552639fd8479c22f403e84fe5e98896f",to:"0xa6993059b5a31e53f4df0e84a59ccf13abf86b86",value:web3.toWei(3,"ether")})

矿池挖矿

./ethminer --farm-recheck 2000 -G -S us2.ethpool.org:3333 -FS us1.ethpool.org:3333 -O 0x550ce8f9cacae8d5137feb704fbfa45e213bcd30

 

CBB(抄币币)的创世节点:enode://3251729f9c8622826f9a94c40c6f8566505ffd2f34771f77468797858cae8f16b7e7b923a694431f14815b7460c910349d981801a2637a30a8bc503eedee781d@13.115.164.167:30303

配置文件:

 
{
        "config": {
                "chainId": 10,
                        "homesteadBlock": 0,
                        "eip155Block": 0,
                        "eip158Block": 0
        },
                "alloc"      : {},
                "coinbase"   : "0x0000000000000000000000000000000000000000",
                "difficulty" : "0x020000",
                "extraData"  : "",
                "gasLimit"   : "0x2fefd8",
                "nonce"      : "0x0000000000000042",
                "mixhash"    : "0x0000000000000000000000000000000000000000000000000000000000000000",
                "parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
                "timestamp"  : "0x00"
}