1
+ from ccxtbt import CCXTStore
2
+ import backtrader as bt
3
+ from datetime import datetime , timedelta
4
+ from strategies .bollema import BollEMA
5
+ from strategies .boll import Boll
6
+ from utils .helper import init_env , get_env
7
+
8
+
9
+ class TestStrategy (bt .Strategy ):
10
+
11
+ def __init__ (self ):
12
+
13
+ self .sma = bt .indicators .SMA (self .data , period = 21 )
14
+
15
+ def next (self ):
16
+
17
+ # Get cash and balance
18
+ # New broker method that will let you get the cash and balance for
19
+ # any wallet. It also means we can disable the getcash() and getvalue()
20
+ # rest calls before and after next which slows things down.
21
+
22
+ # NOTE: If you try to get the wallet balance from a wallet you have
23
+ # never funded, a KeyError will be raised! Change LTC below as approriate
24
+ if self .live_data :
25
+ cash , value = self .broker .get_wallet_balance ('USDT' )
26
+ else :
27
+ # Avoid checking the balance during a backfill. Otherwise, it will
28
+ # Slow things down.
29
+ cash = 'NA'
30
+ # return # 仍然处于历史数据回填阶段,不执行逻辑,返回
31
+
32
+ for data in self .datas :
33
+
34
+ print ('{} - {} | Cash {} | O: {} H: {} L: {} C: {} V:{} SMA:{}' .format (data .datetime .datetime (), data ._name , cash , data .open [0 ], data .high [0 ],
35
+ data .low [0 ], data .close [0 ], data .volume [0 ], self .sma [0 ]))
36
+
37
+ def notify_data (self , data , status , * args , ** kwargs ):
38
+ dn = data ._name
39
+ dt = datetime .utcnow ()
40
+ msg = 'Data Status: {}' .format (data ._getstatusname (status ))
41
+ print (dt , dn , msg )
42
+ if data ._getstatusname (status ) == 'LIVE' :
43
+ self .live_data = True
44
+ else :
45
+ self .live_data = False
46
+
47
+
48
+ if __name__ == '__main__' :
49
+ init_env ()
50
+ cerebro = bt .Cerebro (quicknotify = True )
51
+
52
+ # Add the strategy
53
+ # cerebro.addstrategy(TestStrategy)
54
+ # cerebro.addstrategy(BollEMA, period_boll=200, period_ema=99, production=True)
55
+ cerebro .addstrategy (Boll )
56
+
57
+ # Create our store
58
+ config = { 'apiKey' : get_env ('B_APIKEY' ), 'secret' : get_env ('B_SECRET' ), 'enableRateLimit' : True }
59
+ if get_env ("PROXY" ) == '1' :
60
+ config ['proxies' ] = { 'https' : "http://127.0.0.1:8001" , 'http' : "http://127.0.0.1:8001" }
61
+
62
+ # IMPORTANT NOTE - Kraken (and some other exchanges) will not return any values
63
+ # for get cash or value if You have never held any BNB coins in your account.
64
+ # So switch BNB to a coin you have funded previously if you get errors
65
+ store = CCXTStore (exchange = 'binanceusdm' , currency = 'USDT' , config = config , retries = 5 , debug = False )
66
+
67
+ # Get the broker and pass any kwargs if needed.
68
+ # ----------------------------------------------
69
+ # Broker mappings have been added since some exchanges expect different values
70
+ # to the defaults. Case in point, Kraken vs Bitmex. NOTE: Broker mappings are not
71
+ # required if the broker uses the same values as the defaults in CCXTBroker.
72
+ broker_mapping = {
73
+ 'order_types' : {
74
+ bt .Order .Market : 'market' ,
75
+ bt .Order .Limit : 'limit' ,
76
+ bt .Order .Stop : 'stop-loss' , #stop-loss for kraken, stop for bitmex
77
+ bt .Order .StopLimit : 'stop limit'
78
+ },
79
+ 'mappings' : {
80
+ 'closed_order' : {
81
+ 'key' : 'status' ,
82
+ 'value' : 'closed'
83
+ },
84
+ 'canceled_order' : {
85
+ 'key' : 'status' ,
86
+ 'value' : 'canceled'
87
+ }
88
+ }
89
+ }
90
+
91
+ broker = store .getbroker (broker_mapping = broker_mapping )
92
+ cerebro .setbroker (broker )
93
+
94
+ # Get our data
95
+ # Drop newest will prevent us from loading partial data from incomplete candles
96
+ hist_start_date = datetime .utcnow () - timedelta (minutes = 1600 )
97
+ data = store .getdata (
98
+ dataname = 'ETH/USDT' ,
99
+ name = "ETHUSDT" ,
100
+ timeframe = bt .TimeFrame .Minutes ,
101
+ fromdate = hist_start_date ,
102
+ compression = 5 ,
103
+ ohlcv_limit = 99999 ,
104
+ drop_newest = True ,
105
+ # historical=True
106
+ )
107
+
108
+ # Add the feed
109
+ cerebro .adddata (data )
110
+
111
+ cerebro .broker .setcommission (commission = 0.0004 , margin = 0.1 , mult = 1.0 )
112
+ cerebro .addsizer (bt .sizers .FixedSize , stake = 1 )
113
+
114
+ # Run the strategy
115
+ cerebro .run ()
0 commit comments