Skip to content

Commit

Permalink
example
Browse files Browse the repository at this point in the history
  • Loading branch information
51bitquant committed Jun 28, 2022
1 parent 2a789d3 commit 3f08751
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 94 deletions.
75 changes: 41 additions & 34 deletions examples/download_data_demo1.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,71 +7,76 @@
from howtrader.trader.setting import SETTINGS
from howtrader.trader.engine import MainEngine

from howtrader.gateway.binances import BinancesGateway
from howtrader.gateway.binance import BinanceGateway
from howtrader.gateway.binances.binances_gateway import BinancesRestApi
from howtrader.gateway.binance import BinanceSpotGateway,BinanceUsdtGateway, BinanceInverseGateway
from howtrader.gateway.binance.binance_usdt_gateway import BinanceUsdtRestApi
from howtrader.trader.object import Exchange, Interval
from tzlocal import get_localzone
from tzlocal import get_localzone_name
from howtrader.trader.object import HistoryRequest
from howtrader.trader.database import database_manager
from howtrader.trader.database import BaseDatabase, get_database

database: BaseDatabase = get_database()

from threading import Thread

SETTINGS["log.active"] = True
SETTINGS["log.level"] = INFO
SETTINGS["log.console"] = True

binances_setting = {
spot_gateway_setting = {
"key": "",
"secret": "",
"proxy_host": "",
"proxy_port": 0,
}

usdt_gateway_setting = {
"key": "",
"secret": "",
"会话数": 3,
"服务器": "REAL",
"合约模式": "正向",
"代理地址": "",
"代理端口": 0,
"proxy_host": "",
"proxy_port": 0
}

binance_setting = {
inverse_gateway_setting = {
"key": "",
"secret": "",
"session_number": 3,
"proxy_host": "",
"proxy_port": 0
}


def request1():
start = datetime(2020, 10, 1, tzinfo=get_localzone())
end = datetime(2020, 10, 2, tzinfo=get_localzone())
start = datetime(2020, 10, 1, tzinfo=get_localzone_name())
end = datetime(2020, 10, 2, tzinfo=get_localzone_name())
req = HistoryRequest(
symbol=symbol,
exchange=exchange,
interval=Interval(interval),
interval=interval,
start=start,
end=end
)

data = gate_way.query_history(req)

print(data)

if data:
database_manager.save_bar_data(data)
bars = gate_way.query_history(req)

print(bars)
if bars:
database.save_bar_data(bars)

def request2():
print("start2")
start = datetime(2020, 11, 12, tzinfo=get_localzone())
end = datetime(2020, 11, 13, tzinfo=get_localzone())
start = datetime(2020, 11, 12, tzinfo=get_localzone_name())
end = datetime(2020, 11, 13, tzinfo=get_localzone_name())
req = HistoryRequest(
symbol=symbol,
exchange=exchange,
interval=Interval(interval),
interval=interval,
start=start,
end=end
)

data = gate_way.query_history(req)
print("start12_end13", data)
bars = gate_way.query_history(req)
print("start2_end", bars)
if bars:
database.save_bar_data(bars)


if __name__ == "__main__":
Expand All @@ -82,15 +87,17 @@ def request2():

event_engine = EventEngine()
main_engine = MainEngine(event_engine)
main_engine.add_gateway(BinanceGateway) # spot
# main_engine.add_gateway(BinancesGateway) # future
main_engine.connect(binance_setting, "BINANCE") # spot
# main_engine.connect(binances_setting, "BINANCES") # future

main_engine.add_gateway(BinanceSpotGateway) # spot
main_engine.add_gateway(BinanceUsdtGateway) # future
main_engine.add_gateway(BinanceInverseGateway) # future
main_engine.connect(spot_gateway_setting, "BINANCE_SPOT") # spot
main_engine.connect(usdt_gateway_setting, "BINANCE_USDT") # future
main_engine.connect(inverse_gateway_setting, "BINANCE_INVERSE") # Inverse future.
sleep(3)

main_engine.write_log("连接BINANCE接口") # spot
# main_engine.write_log("连接BINANCES接口") # future
main_engine.write_log("connect binance spot gateway") # spot
main_engine.write_log("connect binance future gateway") # future
main_engine.write_log("connect binance inverse gateway") # inverse
gate_way = main_engine.get_gateway("BINANCE") # spot
# gate_way = main_engine.get_gateway("BINANCES") # future
print(gate_way)
Expand Down
67 changes: 37 additions & 30 deletions examples/download_data_demo2.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
"""
我们使用币安原生的api进行数据爬取.
use binance api to get the kline datas.
author: 51bitquant
discord: 51bitquant#8078
"""

import pandas as pd
import time
from datetime import datetime
import requests
import pytz
from howtrader.trader.database import database_manager
from howtrader.trader.database import BaseDatabase, get_database

pd.set_option('expand_frame_repr', False) #
from howtrader.trader.object import BarData, Interval, Exchange
Expand All @@ -20,6 +22,9 @@
from threading import Thread


database: BaseDatabase = get_database()


def generate_datetime(timestamp: float) -> datetime:
"""
:param timestamp:
Expand All @@ -30,39 +35,40 @@ def generate_datetime(timestamp: float) -> datetime:
return dt


def get_binance_data(symbol: str, exchanges: str, start_time: str, end_time: str):
def get_binance_data(symbol: str, exchange: str, start_time: str, end_time: str, gate_way: str="BINANCE_USDT"):
"""
爬取币安交易所的数据
crawl binance exchange data
:param symbol: BTCUSDT.
:param exchanges: 现货、USDT合约, 或者币币合约.
:param start_time: 格式如下:2020-1-1 或者2020-01-01
:param end_time: 格式如下:2020-1-1 或者2020-01-01
:param exchange: spot、usdt_future, inverse_future.
:param start_time: format :2020-1-1 or 2020-01-01 year-month-day
:param end_time: format: 2020-1-1 or 2020-01-01 year-month-day
:param gate_way the gateway name for binance is:BINANCE_SPOT, BINANCE_USDT, BINANCE_INVERSE
:return:
"""

api_url = ''
save_symbol = symbol
gate_way = 'BINANCES'

if exchanges == 'spot':

if exchange == 'spot':
print("spot")
limit = BINANCE_SPOT_LIMIT
save_symbol = symbol.lower()
gate_way = 'BINANCE'
api_url = f'https://api.binance.com/api/v3/klines?symbol={symbol}&interval=1m&limit={limit}'

elif exchanges == 'future':
print('future')
elif exchange == 'usdt_future':
print('usdt_future')
limit = BINANCE_FUTURE_LIMIT
api_url = f'https://fapi.binance.com/fapi/v1/klines?symbol={symbol}&interval=1m&limit={limit}'

elif exchanges == 'coin_future':
print("coin_future")
elif exchange == 'inverse_future':
print("inverse_future")
limit = BINANCE_FUTURE_LIMIT
f'https://dapi.binance.com/dapi/v1/klines?symbol={symbol}&interval=1m&limit={limit}'

else:
raise Exception('交易所名称请输入以下其中一个:spot, future, coin_future')
raise Exception('the exchange name should be one of :spot, usdt_future, inverse_future')

start_time = int(datetime.strptime(start_time, '%Y-%m-%d').timestamp() * 1000)
end_time = int(datetime.strptime(end_time, '%Y-%m-%d').timestamp() * 1000)
Expand All @@ -72,7 +78,7 @@ def get_binance_data(symbol: str, exchanges: str, start_time: str, end_time: str
print(start_time)
url = f'{api_url}&startTime={start_time}'
print(url)
data = requests.get(url=url, timeout=10, proxies=proxies).json()
datas = requests.get(url=url, timeout=10, proxies=proxies).json()

"""
[
Expand All @@ -95,28 +101,29 @@ def get_binance_data(symbol: str, exchanges: str, start_time: str, end_time: str

buf = []

for l in data:
bar = BarData(
for row in datas:
bar: BarData = BarData(
symbol=save_symbol,
exchange=Exchange.BINANCE,
datetime=generate_datetime(l[0]),
datetime=generate_datetime(row[0]),
interval=Interval.MINUTE,
volume=float(l[5]),
open_price=float(l[1]),
high_price=float(l[2]),
low_price=float(l[3]),
close_price=float(l[4]),
volume=float(row[5]),
turnover=float(row[7]),
open_price=float(row[1]),
high_price=float(row[2]),
low_price=float(row[3]),
close_price=float(row[4]),
gateway_name=gate_way
)
buf.append(bar)

database_manager.save_bar_data(buf)
database.save_bar_data(buf)

# 到结束时间就退出, 后者收盘价大于当前的时间.
if (data[-1][0] > end_time) or data[-1][6] >= (int(time.time() * 1000) - 60 * 1000):
if (datas[-1][0] > end_time) or datas[-1][6] >= (int(time.time() * 1000) - 60 * 1000):
break

start_time = data[-1][0]
start_time = datas[-1][0]

except Exception as error:
print(error)
Expand All @@ -143,13 +150,13 @@ def download_spot(symbol):
t3.join()


def download_future(symbol):
def download_usdt_future(symbol):
"""
下载合约数据的方法。
:return:
"""
t1 = Thread(target=get_binance_data, args=(symbol, 'future', "2019-9-10", "2020-3-1"))
t2 = Thread(target=get_binance_data, args=(symbol, 'future', "2019-3-1", "2020-11-16"))
t1 = Thread(target=get_binance_data, args=(symbol, 'usdt_future', "2019-9-10", "2020-3-1"))
t2 = Thread(target=get_binance_data, args=(symbol, 'usdt_future', "2019-3-1", "2020-11-16"))

t1.start()
t2.start()
Expand All @@ -174,4 +181,4 @@ def download_future(symbol):

# download_spot(symbol) # 下载现货的数据.

download_future(symbol) # 下载合约的数据
download_usdt_future(symbol) # 下载合约的数据
9 changes: 4 additions & 5 deletions examples/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
from howtrader.trader.engine import MainEngine
from howtrader.trader.ui import MainWindow, create_qapp

from howtrader.gateway.binance import BinanceGateway
from howtrader.gateway.binances import BinancesGateway

from howtrader.gateway.binance import BinanceSpotGateway, BinanceUsdtGateway, BinanceInverseGateway

from howtrader.app.cta_strategy import CtaStrategyApp
from howtrader.app.data_manager import DataManagerApp
Expand All @@ -25,8 +23,9 @@ def main():

main_engine = MainEngine(event_engine)

main_engine.add_gateway(BinanceGateway)
main_engine.add_gateway(BinancesGateway)
main_engine.add_gateway(BinanceSpotGateway)
main_engine.add_gateway(BinanceUsdtGateway)
main_engine.add_gateway(BinanceInverseGateway)
main_engine.add_app(CtaStrategyApp)
main_engine.add_app(CtaBacktesterApp)
main_engine.add_app(DataManagerApp)
Expand Down
38 changes: 17 additions & 21 deletions examples/no_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@

from howtrader.event import EventEngine
from howtrader.trader.setting import SETTINGS
from howtrader.trader.engine import MainEngine
from howtrader.trader.engine import MainEngine, LogEngine

from howtrader.gateway.binances import BinancesGateway
from howtrader.app.cta_strategy import CtaStrategyApp
from howtrader.gateway.binance import BinanceSpotGateway, BinanceUsdtGateway
from howtrader.app.cta_strategy import CtaStrategyApp, CtaEngine
from howtrader.app.cta_strategy.base import EVENT_CTA_LOG


Expand All @@ -17,47 +17,43 @@
SETTINGS["log.console"] = True


binances_setting = {
usdt_gateway_setting = {
"key": "",
"secret": "",
"会话数": 3,
"服务器": "REAL",
"合约模式": "正向",
"代理地址": "",
"代理端口": 0,
"proxy_host": "",
"proxy_port": 0,
}


def run():
"""
Running in the child process.
"""
SETTINGS["log.file"] = True

event_engine = EventEngine()
main_engine = MainEngine(event_engine)
main_engine.add_gateway(BinancesGateway)
cta_engine = main_engine.add_app(CtaStrategyApp)
main_engine.write_log("主引擎创建成功")
main_engine: MainEngine = MainEngine(event_engine)
main_engine.add_gateway(BinanceUsdtGateway)
cta_engine: CtaEngine = main_engine.add_app(CtaStrategyApp)
main_engine.write_log("setup main engine")

log_engine = main_engine.get_engine("log")
log_engine: LogEngine = main_engine.get_engine("log")
event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event)
main_engine.write_log("注册日志事件监听")
main_engine.write_log("register event listener")

main_engine.connect(binances_setting, "BINANCES")
main_engine.write_log("连接BINANCES接口")
main_engine.connect(usdt_gateway_setting, "BINANCE_USDT")
main_engine.write_log("connect binance usdt gate way")

sleep(10)

cta_engine.init_engine()
main_engine.write_log("CTA策略初始化完成")
main_engine.write_log("set up cta engine")

cta_engine.init_all_strategies()
sleep(60) # Leave enough time to complete strategy initialization
main_engine.write_log("CTA策略全部初始化")
main_engine.write_log("init cta strategies")

cta_engine.start_all_strategies()
main_engine.write_log("CTA策略全部启动")
main_engine.write_log("start cta strategies")

while True:
sleep(10)
Expand Down
4 changes: 2 additions & 2 deletions examples/portfolio_backtesting.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

from howtrader.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
from howtrader.app.cta_strategy.strategies.atr_rsi_strategy import AtrRsiStrategy
from howtrader.app.cta_strategy.strategies.boll_channel_strategy import BollChannelStrategy
from .strategies.atr_rsi_strategy import AtrRsiStrategy
from .strategies.boll_channel_strategy import BollChannelStrategy
from datetime import datetime


Expand Down
Loading

0 comments on commit 3f08751

Please sign in to comment.