-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtemplate.py
More file actions
117 lines (99 loc) · 4.81 KB
/
Copy pathtemplate.py
File metadata and controls
117 lines (99 loc) · 4.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
from algorizer import ta
from algorizer import trade
from algorizer import constants as c
from algorizer import stream_c, timeframe_c, generatedSeries_c, marker_c, line_c, candle_c
# from algorizer import pivots_c, pivot_c # only needed if you use ta.pivots
from algorizer import plot, histogram, createMarker, removeMarker, createLine, removeLine
def runCloseCandle( timeframe:timeframe_c, open, high, low, close, volume, top, bottom ):
'''
A candle was closed. Execute the strategy logic
'''
barindex = timeframe.barindex
ta.SMA(close, 200).plot()
ta.RSI(close, 14).plot('subpanel')
def event( stream:stream_c, event:str, param, numparams ):
'''
Handle events generated by the framework
'''
if event == "tick":
'''
A realtime price update was received.
candle : a cancle_c containing the OHLCV values of the latest price.
'''
if not stream.running: # is backtesting
return
candle:candle_c = param
## Show remaining candle time and open position info on the console status line.
## You can remove this if you don't want it.
candle.updateRemainingTime()
message = f"{stream.symbol.split(':')[0]} [{candle.remainingTimeStr()}]"
longpos = trade.getActivePosition(c.LONG)
if longpos:
moreMsg = f" long:{longpos.collateral:.1f}({longpos.get_unrealized_pnl_percentage():.1f}%)"
message += moreMsg
shortpos = trade.getActivePosition(c.SHORT)
if shortpos:
moreMsg = f" short:{shortpos.collateral:.1f}({shortpos.get_unrealized_pnl_percentage():.1f}%)"
message += moreMsg
stream.setStatusLineMsg(message)
return
elif event == "broker_event":
'''
info = {
"order_type": order_type, # c.BUY / c.SELL (1/-1)
"order_quantity": quantity, # Notional. Already scaled by leverage
"order_quantity_dollars": quantity_dollars, # Notional. Already scaled by leverage
"position_type": self.type, # c.LONG / c.SHORT (1/-1)
"position_size": position_size_base, # Notional. Already scaled by leverage
"position_size_dollars": position_size_dollars, # Notional. Already scaled by leverage
"leverage": leverage,
"price": price,
"source": [ 'order', 'liquidation_trigger', 'takeprofit_trigger', 'stoploss_trigger', 'takeprofit_create', 'stoploss_create' ]
}
'''
if not stream.running: # is backtesting
return
source = param['source']
if source == 'takeprofit_create' or source == 'stoploss_create':
return
order_type = param['order_type']
position_size = param['position_size'] * param['position_type']
leverage = param['leverage']
order_quantity_dollars = param['order_quantity_dollars'] / leverage # whook by default expects unleveraged collateral in the order
# Example of an alert for my webhook 'whook': https://github.com/germangar/whook
account = ""
url = 'http://localhost:80/whook'
if position_size == 0:
message = f"{account} {stream.symbol} close"
else:
order = 'buy' if order_type == c.LONG else 'sell'
message = f"{account} {stream.symbol} {order} {order_quantity_dollars:.4f}$ {leverage}x"
if url and message:
import requests
req = requests.post( url, data=message.encode('utf-8'), headers={'Content-Type': 'text/plain; charset=utf-8'} )
print( f"Alert sent: Status: {req.status_code} Response: {req.text}" )
elif event == "cli_command":
'''
Handle custom console commands.
'''
assert( isinstance(param, tuple) and len(param) == numparams)
cmd, args = param
# command "chart [timeframe] opens the chart window"
if cmd == 'chart' or cmd == 'c':
stream.createWindow( args )
if __name__ == '__main__':
# configure the strategy before creating the stream
# the backtest will happen at stream initialization
trade.strategy.hedged = False
trade.strategy.currency_mode = 'USD' # 'BASE' for base currency mode
trade.strategy.order_size = 1000
trade.strategy.max_position_size = 2000
trade.strategy.liquidity = 10000
trade.strategy.leverage_long = 1
trade.strategy.leverage_short = 1
stream = stream_c( 'BTC/USDT:USDT', 'binance', ['1h'], [runCloseCandle], event, 25000 )
stream.registerPanel('subpanel', 1.0, 0.2, background_color="#313131ac" )
stream.createWindow( '1h' )
trade.print_summary_stats()
trade.print_pnl_by_period_summary()
stream.run()