46 KiB
46 KiB
In [ ]:
import pandas as pd
import matplotlib.pyplot as plt
import mplfinance as mpf
import keyring as kr
import MetaTrader5 as mt
import requests
import re
from time import sleep
import sqlite3 as db
import matplotlib.pyplot as plt
import pandas_ta as ta
from scipy.signal import savgol_filter
from scipy.signal import find_peaks
In [ ]:
# login to your Trading Account - sign up in the description
mt.initialize()
login = 10800246
server = 'VantageInternational-Demo'
password = kr.get_password(server, str(login))
mt.login(login, password, server)In [ ]:
project = "trading-" + server[-4::1]
project = project.lower()
projectIn [ ]:
pause_trading = 0
In [ ]:
symbols = ['XAUUSD']
#'BTCUSD', 'ETHUSD',
#'XRPUSD', , 'EURNZD', 'EURUSD'In [ ]:
volume_dict = {
'BTCUSD' : 0.1,
'BTCUSD_short' : 0.1,
'ETHUSD' : 1.0,
'ETHUSD_short' : 1.0,
'XRPUSD': 0.1,
'XRPUSD_short': 0.1,
'XAUUSD': 0.1,
'XAUUSD_short': 0.1,
'EURUSD': 0.1,
'EURUSD_short': 0.1,
'EURNZD': 0.1,
'EURNZD_short': 0.1,
}In [ ]:
periods_dict = {
'BTCUSD' : ['h1', 'm30', 'm15', 'm5', 'm1'],
'ETHUSD' : ['h1', 'm30', 'm15', 'm5', 'm1'],
'XRPUSD': ['h1', 'm30', 'm15', 'm5', 'm1'],
'XAUUSD': [ 'm15'],
'EURUSD': ['h1', 'm30', 'm15', 'm5', 'm1'],
'EURNZD': ['m5', 'm2', 'm1'],
}In [ ]:
def get_symbol():
global symbols, pause_trading, periods_dict
pricemovement = {}
for s in symbols:
items = mt.symbol_info(s)
pricemovement[s] = round(items.price_change,2)
#print(s, round(items.price_change,2))
#percentage = pricemovement[max(pricemovement, key=pricemovement.get)]
#symbol = max(pricemovement, key=pricemovement.get)
#volume = volume_dict[symbol]
sorted_pricemovement = sorted(pricemovement.items(), key=lambda x:x[1], reverse=True)
converted_dict = dict(sorted_pricemovement)
print(converted_dict)
percentage = converted_dict[max(converted_dict, key=converted_dict.get)]
symbol = max(converted_dict, key=converted_dict.get)
volume = volume_dict[symbol]
print(symbol, percentage, volume)
# if percentage > 0: # and percentage < 0.8:
# periods_dict[symbol] = ['m15', 'm5', 'm2', 'm1']
# elif percentage > 0.8:
# periods_dict[symbol] = ['h1', 'm30', 'm15', 'm5', 'm1']
#
#print(periods_dict)
# if percentage > 0 and mt.positions_total() == 0:
# pause_trading = 0 #0 no puase
# return symbol, percentage, volume, periods_dict
# elif percentage < 0.1 and mt.positions_total() == 0:
# print("aktuell kein neues Symbol, pause Trading")
# pause_trading = 1 #1 pause
# return None
return symbol, percentage, volume, periods_dictIn [ ]:
get_symbol()In [ ]:
def set_symbol():
global symbol, volume, volume_dict
symb = get_symbol()
if symb != None:
symbol = symb[0]
volume = volume_dict[symb[0]]
In [ ]:
get_symbol()In [ ]:
set_symbol()
In [ ]:
pause_trading = 0
symbol, volume, pause_tradingIn [ ]:
symbol = 'XAUUSD'
volume = 0.1In [ ]:
pos = mt.positions_get()
for i in pos:
#if i.comment == 'Retracement Bot':
# print(i.ticket)
if bool(re.search('^BuyStop[0-9]{2}', i.comment)):
print(i.ticket)
mt.positions_total()In [ ]:
strategy_name = 'Retracement Bot'
pos = mt.positions_get()
for p in pos:
if p.comment == strategy_name:
print(p.comment)
print(pos)In [ ]:
buypos = ['True', 'False', 'False']
'True' not in buypos
buypos.count('True')In [ ]:
#market_order(symbol, volume_dict[symbol], 'buy')
request = {
"action": mt.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": volume, # FLOAT
"type": mt.ORDER_TYPE_BUY,
"price": mt.symbol_info_tick(symbol).ask,
"sl": 0.0, # FLOAT
"tp": 0.0, # FLOAT
"deviation": 20, # INTERGER
"magic": 30, # INTERGER
"comment": 'Retracement Bot',
"type_time": mt.ORDER_TIME_GTC,
"type_filling": mt.ORDER_FILLING_IOC, # mt.ORDER_FILLING_FOK if IOC does not work
}
order_result = mt.order_send(request)In [ ]:
def market_order(symbol, volume, order_type, deviation=20, magic=30, stoploss=0.0, take_profit=0.0,
strategy_name='Retracement Bot'):
global project, pause_trading
project_id_dict = {
'trading-demo': 'a3f3ae',
'trading-live': '747543'
}
order_type_dict = {
'buy': mt.ORDER_TYPE_BUY,
'sell': mt.ORDER_TYPE_SELL
}
price_dict = {
'buy': mt.symbol_info_tick(symbol).ask,
'sell': mt.symbol_info_tick(symbol).bid
}
buypos = []
pos = mt.positions_get()
for p in pos:
if p.comment == strategy_name:
buypos.append('true')
activepos = buypos.count('true')
if order_type == 'buy' and activepos == 0 and pause_trading == 0: # and mt.positions_total() == 0:
request = {
"action": mt.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": volume, # FLOAT
"type": order_type_dict[order_type],
"price": price_dict[order_type],
"sl": stoploss, # FLOAT
"tp": take_profit, # FLOAT
"deviation": deviation, # INTERGER
"magic": magic, # INTERGER
"comment": strategy_name,
"type_time": mt.ORDER_TIME_GTC,
"type_filling": mt.ORDER_FILLING_IOC, # mt.ORDER_FILLING_FOK if IOC does not work
}
requests.post('https://api.mynotifier.app', {
"apiKey": 'beafb52e-3cb6-477a-92ef-2f10bff50e20',
"message": "Es wrude ein Handel eröffnet!",
"description": "Bitte kontrolliere die Position",
"type": "info",#"info", # info, error, warning or success
"project": project_id_dict[project]
})
order_result = mt.order_send(request)
#return (order_result)
elif order_type == 'sell' and mt.positions_total() > 0:
pos = mt.positions_get()
for p in pos:
if p.comment == strategy_name:
# while schleife ?
positions = mt.positions_get()
ticket = p.ticket
request = {
"action": mt.TRADE_ACTION_DEAL,
"symbol": symbol,
"volume": volume, # FLOAT
"type": order_type_dict[order_type],
"price": price_dict[order_type],
"position": ticket,
"sl": stoploss, # FLOAT
"tp": take_profit, # FLOAT
"deviation": deviation, # INTERGER
"magic": magic, # INTERGER
"comment": strategy_name,
"type_time": mt.ORDER_TIME_GTC,
"type_filling": mt.ORDER_FILLING_IOC, # mt.ORDER_FILLING_FOK if IOC does not work
}
requests.post('https://api.mynotifier.app', {
"apiKey": 'beafb52e-3cb6-477a-92ef-2f10bff50e20',
"message": "Es wrude ein Handel geschlossen!",
"description": "Bitte prüfe die Position",
"type": "info",#"info", # info, error, warning or success
"project": project_id_dict[project]
})
order_result = mt.order_send(request)
#return (order_result)
In [ ]:
def get_sltp():
ohlc = mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_M5, 0, 50)
df = pd.DataFrame(ohlc)
df['time']=pd.to_datetime(df['time'], unit='s')
support = df[df.low == df.low.rolling(5, center=True).min()].low
resistance = df[df.high == df.high.rolling(5, center=True).max()].high
df['resistance'] = resistance
df['support'] = support
df.support.fillna(0, inplace=True)
df.resistance.fillna(0, inplace=True)
df = df[(df.support != 0) | (df.resistance != 0)]
tp = df.resistance.loc[df['resistance'] != 0]
tp = round(tp.mean(), 2)
sl = df.support.loc[df['support'] != 0]
sl = round (sl.mean(), 2)
return tp, sl
In [ ]:
tpsl = get_sltp()
tpsl[0] - tpsl[1] In [ ]:
def get_supres_signal(period: str):
ohlc = mt.copy_rates_from_pos(symbol, timeframes_dict[period], 0, 50)
df = pd.DataFrame(ohlc)
df['time']=pd.to_datetime(df['time'], unit='s')
support = df[df.low == df.low.rolling(5, center=True).min()].low
resistance = df[df.high == df.high.rolling(5, center=True).max()].high
df['ma3'] = df['close'].rolling(3).mean()
df['resistance'] = resistance
df['support'] = support
df.support.fillna(0, inplace=True)
df.resistance.fillna(0, inplace=True)
df = df[(df.support != 0) | (df.resistance != 0)]
if df.resistance.iloc[-1] != 0:
signal = 'sell'
print(f'sell at: {df.resistance.iloc[-1]}')
elif df.support.iloc[-1] !=0:
signal = 'buy'
print(f'buy at: {df.support.iloc[-1]}')
return signal
In [ ]:
get_supres_signal('m30')In [ ]:
def get_sma_signal():
sma = mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_M5, 0, 120)
df = pd.DataFrame(sma)
df['time']=pd.to_datetime(df['time'], unit='s')
df['ma5'] = df['close'].rolling(3).mean()
df['ma10'] = df['close'].rolling(15).mean()
df['diff5'] = df['ma5'].diff()
support = df[df.low == df.low.rolling(5, center=True).min()].low
resistance = df[df.high == df.high.rolling(5, center=True).max()].high
df['resistance'] = resistance
df['support'] = support
df.support.fillna(0, inplace=True)
df.resistance.fillna(0, inplace=True)
df.dropna()
df = df[['time','open', 'close', 'low', 'ma5', 'ma10', 'diff5', 'resistance', 'support']]
buy = []
sell = []
for i in range (len(df)):
if df.ma5.iloc[i] > df.ma10.iloc[i]: #and df.ma5[i-1] < df.ma10.iloc[i-1]:
buy.append(i)
elif df.ma5.iloc[i] < df.ma10.iloc[i]: #and df.ma5[i-1] > df.ma10.iloc[i-1]:
sell.append(i)
buy, sell
df['buy'] = 0
df['sell'] = 0
for b in buy:
df.at[b,'buy'] = 1
for s in sell:
df.at[s,'sell'] = 1
# if df.buy.iloc[-1] == 1:
# signal = 'buy'
# elif df.sell.iloc[-1] == 1:
# signal = 'sell'
# else:
# signal = 'none'
if df.diff5.tail(12).sum() > 0 and df.buy.iloc[-1] == 1:
#print('buy', df.diff5.tail(12).sum())
signal = 'buy'
else:
#print('sell')
signal = 'sell'
if df.diff5.tail(5).sum() > 0 and df.buy.iloc[-1] == 1:
#print('buy', df.diff5.tail(5).sum())
signal = 'buy'
else:
#print('sell')
signal = 'sell'
if df.diff5.tail(3).sum() > 0 and df.buy.iloc[-1] == 1:
#print('buy', df.diff5.tail(3).sum())
signal = 'buy'
else:
#print('sell')
signal = 'sell'
if df.diff5.tail(2).sum() > 0 and df.buy.iloc[-1] == 1:
#print('buy', df.diff5.tail(2).sum())
signal = 'buy'
else:
print('sell')
signal = 'sell'
return signal
In [ ]:
signal = get_sma_signal()
signalIn [ ]:
def sma_plot():
plt.figure(figsize=(12,5))
plt.plot(df['close'], label='Asset Price', c='blue', alpha=0.5)
plt.plot(df['ma5'], label='MA5', c='r', alpha=0.9)
plt.plot(df['ma10'], label='MA10', c='y', alpha=0.9)
plt.scatter(df[df.buy == 1].index, df[df.buy == 1]['close'], marker='^', color='g', s=100)
plt.scatter(df[df.sell == 1].index, df[df.sell == 1]['close'], marker='v', color='r', s=100)
plt.legend()
plt.show()In [ ]:
sma_plot()In [ ]:
sma = mt.copy_rates_from_pos(symbol,mt.TIMEFRAME_M1, 0, 60)
df = pd.DataFrame(sma)
#df = df[:-1]
# Identify rows with out of bounds datetime values using errors='coerce'
#nvalid_dates = df[pd.to_datetime(df['time'], errors='coerce')]
# print(invalid_dates)
df['time'] = pd.to_datetime(df['time'], unit='s')
#df = df.head(58)
#df['time']=pd.to_datetime(df['time'], unit='s')
df.tail()
In [ ]:
def get_sma(period: str):
global timeframes_dict
sma = mt.copy_rates_from_pos(symbol,timeframes_dict[period] , 0, 120)
df = pd.DataFrame(sma)
#df = df[:-1]
df['time']=pd.to_datetime(df['time'], unit='s')
df['ma5'] = df['close'].rolling(3).mean()
df['ma10'] = df['close'].rolling(15).mean()
df['diff5'] = df['ma5'].diff()
df['diff10'] = df['ma10'].diff()
df['ema'] = df['close'].ewm(span=14, adjust=False).mean()
# support = df[df.low == df.low.rolling(5, center=True).min()].low
# resistance = df[df.high == df.high.rolling(5, center=True).max()].high
# df['resistance'] = resistance
# df['support'] = support
# df.support.fillna(0, inplace=True)
# df.resistance.fillna(0, inplace=True)
# df.dropna()
df = df[['time','open', 'close', 'low', 'ma5', 'ma10', 'ema','diff5', 'diff10']]
# 'resistance', 'support'
buy = []
sell = []
for i in range (len(df)):
if df.ma5.iloc[i] > df.ema.iloc[i]: #and df.ma5[i-1] < df.ema.iloc[i-1]:
buy.append(i)
elif df.ma5.iloc[i] < df.ema.iloc[i]: #and df.ma5[i-1] > df.ma10.iloc[i-1]:
sell.append(i)
buy, sell
df['buy'] = 0
df['sell'] = 0
for b in buy:
df.at[b,'buy'] = 1
for s in sell:
df.at[s,'sell'] = 1
#df = df.head(26)
return df
In [ ]:
get_sma('m15')In [ ]:
df_daily = mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_D1, 0, 30)
df_days = pd.DataFrame(df_daily)
df_days['time'] = pd.to_datetime(df_days['time'], unit='s')
round(df_days.close.iloc[-1] / df_days.open.iloc[-1],2)In [ ]:
periods_dict[symbol]
get_sma('m15')In [ ]:
periods_dict[symbol]In [ ]:
def decide_order():
global symbol, volume_dict, periods_dict
## SMA Version 2
tsignals = periods_dict[symbol]
signals = []
for ts in tsignals:
sma_signals = get_sma(ts)
supress_signal = get_supres_signal(ts)
print(f"surpress Signal: {supress_signal}")
signals.append(supress_signal)
if sma_signals.buy.iloc[-1] == 1: #sma_signals.diff5.tail(2).sum() > 0:
print(ts, 'buy', sma_signals.diff5.tail(2).sum(), sma_signals.diff10.tail(2).sum())
signals.append('buy')
else:
print(ts, 'sell', sma_signals.diff5.tail(2).sum(), sma_signals.diff10.tail(2).sum())
signals.append('sell')
cbuy = signals.count('buy')
csell = signals.count('sell')
print(f"Buy: {cbuy} | Sell: {csell}")
if cbuy > csell:
signal = 'buy'
print(signal)
else:
signal = 'sell'
print(signal)
if signal == 'buy':
market_order(symbol, volume_dict[symbol], "buy") #, stoploss=sl, take_profit=tp)
#print("buy at {} am {} ".format(df.support.iloc[-1], df.time.iloc[-1]))
elif signal == 'sell':
market_order(symbol, volume_dict[symbol], "sell")
# print("sell at {} am {}".format(df.resistance.iloc[-1], df.time.iloc[-1]))
In [ ]:
symbolIn [ ]:
market_order(symbol, 0.1, "buy")In [ ]:
decide_order()In [ ]:
#if df['support'].iloc[-1] != 0:
#market_order(symbol, volume, "buy")
# print("buy at {} am {} ".format(df['support'].iloc[-1], df['time'].iloc[-1]))
# elif df['resistance'].iloc[-1] != 0:
#market_order(symbol, volume, "sell")
# print("sell at {} am {}".format(df['resistance'].iloc[-1], df['time'].iloc[-1]))In [ ]:
pause_tradingIn [ ]:
pause_trading = 0In [ ]:
trend_dict = {
'm5': '',
'm15': '',
#'m30': '',
}In [ ]:
timeframes_dict = {
'm1': mt.TIMEFRAME_M1,
'm2': mt.TIMEFRAME_M2,
'm3': mt.TIMEFRAME_M3,
'm5': mt.TIMEFRAME_M5,
'm15': mt.TIMEFRAME_M15,
'm20': mt.TIMEFRAME_M20,
'm30': mt.TIMEFRAME_M30,
'h1': mt.TIMEFRAME_H1,
}
# timeframes = {
# 'm1': mt.TIMEFRAME_M1,
# 'm2': mt.TIMEFRAME_M2,
# 'm3': mt.TIMEFRAME_M3,
# 'm5': mt.TIMEFRAME_M5,
# 'm15': mt.TIMEFRAME_M15,
# 'm20': mt.TIMEFRAME_M20,
# 'm30': mt.TIMEFRAME_M30,
# 'h1': mt.TIMEFRAME_H1,
# }In [ ]:
print(trend_dict)In [ ]:
def get_rates(periode):
global symbol
ohlc = mt.copy_rates_from_pos(symbol, timeframes_dict[periode], 0, 200)
df = pd.DataFrame(ohlc)
df['time']=pd.to_datetime(df['time'], unit='s')
#df = df[["time","open","high","low","close"]]
df["open"] = df.open.astype(float)
df["high"] = df.high.astype(float)
df["low"] = df.low.astype(float)
df["close"] = df.close.astype(float)
## Take the rolling atr so the yaxis doesn't shake too much
df["atr"] = ta.atr(high=df.high, low=df.low, close=df.close)
df["atr"] = df.atr.rolling(window=30).mean()
df.set_index("time", inplace = True)
return dfIn [ ]:
def get_trend(period):
global trend_dict, periods_dict, symbol
#current_periods = periods_dict[symbol][0]
df2 = get_rates(period)
df2["close_smooth"] = savgol_filter(df2.close, 49, 5)
fig, ax = plt.subplots()
plt.xticks(rotation=-30)
price, = ax.plot(df2.index, df2.close, c='grey', lw=2, alpha=0.5, zorder=5)
price_smooth, = ax.plot(df2.index, df2.close_smooth, c='b', lw=2, zorder=5)
atr = df2.atr.iloc[-1] # all the first atrs are NaN
peaks_idx, _ = find_peaks(df2.close_smooth, distance = 15,
width = 3, prominence=atr)
troughs_idx, _ = find_peaks(-1*df2.close_smooth, distance = 15,
width = 3, prominence=atr)
peaks, = ax.plot(df2.index[peaks_idx], df2.close_smooth.iloc[peaks_idx], \
c="r", linestyle='None', markersize = 10.0, marker = "o", zorder=10)
troughs, = ax.plot(df2.index[troughs_idx], df2.close_smooth.iloc[troughs_idx], \
c="g", linestyle='None', markersize = 10.0, marker = "o", zorder=10)
plt.show()
#print(peaks_idx[-1], troughs_idx[-1])
if peaks_idx[-1] > troughs_idx[-1]:
print("downtrend")
trend_dict[period] = 'downtrend'
else:
print("uptrend")
trend_dict[period] = 'uptrend'
In [ ]:
def set_trend():
global pause_trading, periods_dict, trend_dict
for k,v in trend_dict.items():
get_trend(k)
print(k)
for k,v in reversed(trend_dict.items()):
if v == 'uptrend':
print(k,v)
periods_dict[symbol] = [k]
pause_trading = 0
break
elif v == 'downtrend':
periods_dict[symbol] = [k] #['m15']
pause_trading = 1In [ ]:
pause_trading, trend_dict, periods_dictIn [ ]:
set_trend()In [ ]:
trend_dictIn [ ]:
periods_dict[symbol], pause_tradingIn [ ]:
from apscheduler.schedulers.background import BackgroundScheduler
import time
scheduler = BackgroundScheduler()
#scheduler.add_job(main, 'date', run_date='2025-03-07 14:29:50')
#scheduler.add_job(decide_order, 'interval', minutes=1) #intervall
scheduler.add_job(set_symbol, 'interval', minutes=30)
scheduler.add_job(set_trend, 'interval', minutes=1)
scheduler.add_job(decide_order, 'cron', year="*", month="*", day_of_week="mon, tue, wed, thu, fri", hour='0-23', minute='*') #cron
#scheduler.add_job(export_marketview, 'cron', year="*", month='*', day_of_week='mon, tue, wed; thu, fri', hour='8-22', minute=00)
#scheduler.add_job(pause_trading, 'cron', year="*", month="*", day_of_week="mon, tue, wed, thu, fri", hour=22, minute=00) #cron
scheduler.start()
In [ ]:
scheduler.get_jobs()In [ ]:
scheduler.remove_all_jobs()In [ ]:
scheduler.shutdown()In [ ]:
def get_sma_dev(period: str):
timeframes = {
'm1': mt.TIMEFRAME_M1,
'm2': mt.TIMEFRAME_M2,
'm3': mt.TIMEFRAME_M3,
'm5': mt.TIMEFRAME_M5,
'm15': mt.TIMEFRAME_M15,
'm20': mt.TIMEFRAME_M20,
'm30': mt.TIMEFRAME_M30
}
sma = mt.copy_rates_from_pos(symbol,timeframes[period] , 0, 120)
df = pd.DataFrame(sma)
df['time']=pd.to_datetime(df['time'], unit='s')
df['ma5'] = df['close'].rolling(3).mean()
df['ma10'] = df['close'].rolling(15).mean()
df['diffclose'] = df['close'].diff()
df['diff5'] = df['ma5'].diff()
df['diff10'] = df['ma10'].diff()
df['ema'] = df['close'].ewm(span=14, adjust=False).mean()
support = df[df.low == df.low.rolling(5, center=True).min()].low
resistance = df[df.high == df.high.rolling(5, center=True).max()].high
df['resistance'] = resistance
df['support'] = support
df.support.fillna(0, inplace=True)
df.resistance.fillna(0, inplace=True)
df.dropna()
df = df[['time','open', 'close', 'low', 'ma5', 'ma10', 'diffclose','diff5', 'diff10', 'ema', 'resistance', 'support']]
buy = []
sell = []
for i in range (len(df)):
if df.ma5.iloc[i] > df.ema.iloc[i]: #and df.ma5[i-1] < df.ma10.iloc[i-1]:
buy.append(i)
elif df.ma5.iloc[i] < df.ema.iloc[i]: #and df.ma5[i-1] > df.ma10.iloc[i-1]:
sell.append(i)
buy, sell
df['buy'] = 0
df['sell'] = 0
for b in buy:
df.at[b,'buy'] = 1
for s in sell:
df.at[s,'sell'] = 1
#df = df.head(26)
return df
In [ ]:
sma = get_sma_dev('m15')
sma.tail(50)
In [ ]:
periods_dict['XAUUSD']
sma.close.tail(10)In [ ]:
tsignals = ['m30', 'm15', 'm5', 'm1']
signals = []
for ts in tsignals:
sma_signals = get_sma(ts)
if sma_signals.diff5.tail(2).sum() > 0: # and sma_signals.buy.iloc[-1] == 1:
print(ts, 'buy', sma_signals.diff5.tail(2).sum(), sma_signals.diff10.tail(2).sum())
signals.append('buy')
else:
print(ts, 'sell', sma_signals.diff5.tail(2).sum(), sma_signals.diff10.tail(2).sum())
signals.append('sell')
cbuy = signals.count('buy')
csell = signals.count('sell')
if cbuy > csell:
signal = 'buy'
print(cbuy)
else:
signal = 'sell'
print(csell)
signal
# sma_signals = get_sma('m15')
# df = sma_signalsIn [ ]:
if df.diff5.tail(12).sum() > 0 and df.diff10.tail(12).sum() > 0 and df.buy.iloc[-1] == 1:
print('buy', df.diff5.tail(12).sum(), df.diff10.tail(12).sum())
else:
print('sell', df.diff5.tail(12).sum(), df.diff10.tail(12).sum())
if df.diff5.tail(6).sum() > 0 and df.diff10.tail(6).sum() > 0 and df.buy.iloc[-1] == 1:
print('buy', df.diff5.tail(6).sum(), df.diff10.tail(6).sum())
else:
print('sell', df.diff5.tail(6).sum(), df.diff10.tail(6).sum())
if df.diff5.tail(3).sum() > 0 and df.diff10.tail(3).sum() > 0 and df.buy.iloc[-1] == 1:
print('buy', df.diff5.tail(3).sum(), df.diff10.tail(3).sum())
else:
print('sell', df.diff5.tail(3).sum(), df.diff10.tail(3).sum())
if df.diff5.tail(2).sum() > 0 and df.diff10.tail(2).sum() > 0 and df.buy.iloc[-1] == 1:
print('buy', df.diff5.tail(2).sum(), df.diff10.tail(2).sum())
else:
print('sell', df.diff5.tail(2).sum(), df.diff10.tail(2).sum())
In [ ]:
df = sma
plt.figure(figsize=(12,5))
plt.plot(df['close'], label='Asset Price', c='blue', alpha=0.5)
plt.plot(df['ma5'], label='MA5', c='r', alpha=0.9)
plt.plot(df['ma10'], label='MA10', c='y', alpha=0.9)
plt.plot(df['ema'], label='EMA', c='green', alpha=0.9)
plt.scatter(df[df.buy == 1].index, df[df.buy == 1]['close'], marker='^', color='g', s=100)
plt.scatter(df[df.sell == 1].index, df[df.sell == 1]['close'], marker='v', color='r', s=100)
plt.legend()
plt.show()In [ ]:
close_diff = df.close.loc[df['close'] != 0]
close_diff.diff().max(), close_diff.diff().min()
close_diff.diff()In [ ]:
if df.buy.iloc[-1] == 1:
signal = 'buy'
elif df.sell.iloc[-1] == 1:
signal = 'sell'
else:
signal = 'none'
signalIn [ ]:
ohlc = mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_M15, 0, 120)
df = pd.DataFrame(ohlc)
df['time']=pd.to_datetime(df['time'], unit='s')
support = df[df.low == df.low.rolling(5, center=True).min()].low
resistance = df[df.high == df.high.rolling(5, center=True).max()].high
df['ma3'] = df['close'].rolling(3).mean()
df['resistance'] = resistance
df['support'] = support
df.support.fillna(0, inplace=True)
df.resistance.fillna(0, inplace=True)
df = df[(df.support != 0) | (df.resistance != 0)]
df
In [ ]:
if df.resistance.iloc[-1] != 0:
signal = 'sell'
print(f'sell at: {df.resistance.iloc[-1]}')
elif df.support.iloc[-1] !=0:
signal = 'buy'
print(f'buy at: {df.support.iloc[-1]}')
else:
signal = 'none'
In [ ]:
plt.figure(figsize=(12,5))
plt.plot(df['close'], label='Asset Price', c='blue', alpha=0.5)
plt.plot(df['ma3'], label='MA3', c='r', alpha=0.9)
#plt.plot(df['ma10'], label='MA10', c='y', alpha=0.9)
plt.scatter(df[df.support != 0].index, df[df.support != 0]['close'], marker='^', color='g', s=100)
plt.scatter(df[df.resistance != 0].index, df[df.resistance != 0]['close'], marker='v', color='r', s=100)
plt.legend()
plt.show()In [ ]:
tp = df.resistance.loc[df['resistance'] != 0]
tp = tp.mean()
sl = df.support.loc[df['support'] != 0]
sl = sl.mean()
round(tp), (sl)In [ ]:
# trend
r = df.resistance.loc[df['resistance'] != 0]
rlen = len(list(r)) -1
rlast_value = list(r)[rlen]
rfirst_value = list(r)[0]
s = df.support.loc[df['support'] != 0]
slen = len(list(s)) -1
slast_value = list(s)[slen]
sfirst_value = list(s)[0]
if rfirst_value > rlast_value and sfirst_value > slast_value:
print('Down Trend')
trend = 'down'
else:
print('Up Trend')
trend = 'up'
abs(rfirst_value - rlast_value)
abs(sfirst_value - slast_value)
In [ ]:
#take profit
levels = pd.concat([support, resistance])
lmax = levels.diff().max()
lmin = levels.diff().min()
tp = round((lmax + lmin)/ 2,2)
if tp < 1:
tp = 1
sl = tp
tp, slIn [ ]:
levels = pd.concat([support, resistance])
lmax = levels.diff().max()
lmin = levels.diff().min()
tp = round((lmax + lmin)/ 2,2)
sl = tp
tp, slIn [ ]:
lv_max = resistance
lv_max.diff()Warning:
Output truncated. This notebook contains too many cells to display efficiently.