forked from namuan/trading-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto_strat_bot.py
181 lines (154 loc) · 5.12 KB
/
crypto_strat_bot.py
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""
Crypto Bot running based on a given strategy
"""
import logging
import mplfinance as mpf
from common.analyst import resample_candles
from common.logger import init_logging
from common.steps import (
SetupDatabase,
ReadConfiguration,
FetchDataFromExchange,
LoadDataInDataFrame,
TradeSignal,
parse_args,
PublishStrategyChartOnTelegram,
)
from common.steps_runner import run_forever_with
class ReSampleData:
def run(self, context):
df = context["df"]
context["resample_map"] = {
"fifteen_df": "15T",
"hourly_df": "1H",
"two_hourly_df": "2H",
"four_hourly_df": "4H",
}
for rk, rv in context["resample_map"].items():
context[rk] = resample_candles(df, rv)
class CalculateIndicators(object):
@staticmethod
def calc_strat_n(first_candle, second_candle):
strat_n = "0"
if (
first_candle.high > second_candle.high
and first_candle.low > second_candle.low
):
strat_n = "2u"
if (
first_candle.low < second_candle.low
and first_candle.high < second_candle.high
):
strat_n = "2d"
if (
first_candle.high > second_candle.high
and first_candle.low < second_candle.low
):
strat_n = "3"
if (
first_candle.high < second_candle.high
and first_candle.low > second_candle.low
):
strat_n = "1"
return strat_n
def calculate_strat(self, ticker_df):
try:
last_candle = ticker_df.iloc[-1]
candle_2 = ticker_df.iloc[-2]
candle_3 = ticker_df.iloc[-3]
candle_4 = ticker_df.iloc[-4]
first_level_strat_n = self.calc_strat_n(last_candle, candle_2)
second_level_strat_n = self.calc_strat_n(candle_2, candle_3)
third_level_strat_n = self.calc_strat_n(candle_3, candle_4)
if last_candle.close > last_candle.open:
last_candle_direction = "green"
else:
last_candle_direction = "red"
return (
f"{third_level_strat_n}-{second_level_strat_n}-{first_level_strat_n}",
last_candle_direction,
)
except Exception:
logging.warning(f"Unable to calculate strat: {ticker_df}")
return "na", "na"
def run(self, context):
df = context["df"]
context["close"] = df["close"].iloc[-1]
indicators = {}
for rk, rv in context["resample_map"].items():
strat, strat_candle = self.calculate_strat(context[rk])
indicators[f"strat_{rv}"] = strat
indicators[f"strat_candle_{rv}_direction"] = strat_candle
context["indicators"] = indicators
logging.info(f"Close {context['close']} -> Indicators => {indicators}")
class IdentifyBuySellSignal(object):
def run(self, context):
indicators = context["indicators"]
strat_60m: str = indicators["strat_1H"]
strat_candle_60m = indicators["strat_candle_1H_direction"]
strat_conditions = strat_60m.endswith("2d-2d") or strat_60m.endswith("2u-2u")
if strat_conditions and strat_candle_60m == "green":
context["signal"] = TradeSignal.BUY
context["trade_done"] = True
logging.info(f"Identified signal => {context.get('signal')}")
class GenerateChart:
def run(self, context):
df_1 = context["fifteen_df"]
df_2 = context["hourly_df"]
df_3 = context["two_hourly_df"]
df_4 = context["four_hourly_df"]
args = context["args"]
chart_title = f"{args.coin}_{args.stable_coin}_60m"
context["chart_name"] = chart_title
context[
"chart_file_path"
] = chart_file_path = f"output/{chart_title.lower()}-strat.png"
save = dict(fname=chart_file_path)
fig = mpf.figure(style="yahoo", figsize=(20, 10))
ax1 = fig.add_subplot(3, 2, 1)
ax2 = fig.add_subplot(3, 2, 2)
ax3 = fig.add_subplot(3, 2, 5)
ax4 = fig.add_subplot(3, 2, 6)
mpf.plot(
df_1[-160:],
ax=ax1,
type="candle",
)
mpf.plot(
df_2[-40:],
ax=ax2,
type="candle",
)
mpf.plot(
df_3[-20:],
ax=ax3,
type="candle",
)
mpf.plot(
df_4[-10:],
ax=ax4,
type="candle",
)
ax1.set_title("15T")
ax2.set_title("1H")
ax3.set_title("2H")
ax4.set_title("4H")
fig.suptitle(chart_title, fontsize=12)
fig.savefig(save["fname"])
def main(args):
init_logging()
procedure = [
SetupDatabase(),
ReadConfiguration(),
FetchDataFromExchange(),
LoadDataInDataFrame(),
ReSampleData(),
CalculateIndicators(),
GenerateChart(),
IdentifyBuySellSignal(),
PublishStrategyChartOnTelegram(),
]
run_forever_with(procedure, args)
if __name__ == "__main__":
args = parse_args(__doc__)
main(args)