{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Import Libaries" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import mplfinance as mpf\n", "import keyring as kr\n", "import MetaTrader5 as mt\n", "import requests\n", "import re\n", "from time import sleep\n", "import sqlite3 as db\n", "import matplotlib.pyplot as plt\n", "import pandas_ta as ta\n", "\n", "from scipy.signal import savgol_filter\n", "from scipy.signal import find_peaks\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Login" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# login to your Trading Account - sign up in the description\n", "mt.initialize()\n", " \n", "login = 10800246\n", "server = 'VantageInternational-Demo'\n", "password = kr.get_password(server, str(login))\n", "\n", "\n", "mt.login(login, password, server)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "project = \"trading-\" + server[-4::1]\n", "project = project.lower()\n", "project" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Set symbol and volume" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pause_trading = 0\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "symbols = ['XAUUSD']\n", "\n", "#'BTCUSD', 'ETHUSD', \n", " #'XRPUSD', , 'EURNZD', 'EURUSD'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "volume_dict = {\n", " 'BTCUSD' : 0.1,\n", " 'BTCUSD_short' : 0.1,\n", "\n", " 'ETHUSD' : 1.0,\n", " 'ETHUSD_short' : 1.0,\n", " \n", " 'XRPUSD': 0.1,\n", " 'XRPUSD_short': 0.1,\n", "\n", " 'XAUUSD': 0.1,\n", " 'XAUUSD_short': 0.1,\n", "\n", " 'EURUSD': 0.1,\n", " 'EURUSD_short': 0.1,\n", "\n", " 'EURNZD': 0.1,\n", " 'EURNZD_short': 0.1,\n", "\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "periods_dict = {\n", " 'BTCUSD' : ['h1', 'm30', 'm15', 'm5', 'm1'],\n", " \n", " 'ETHUSD' : ['h1', 'm30', 'm15', 'm5', 'm1'],\n", "\n", " \n", " 'XRPUSD': ['h1', 'm30', 'm15', 'm5', 'm1'],\n", " \n", " 'XAUUSD': [ 'm15'],\n", "\n", " \n", " 'EURUSD': ['h1', 'm30', 'm15', 'm5', 'm1'],\n", "\n", "\n", " 'EURNZD': ['m5', 'm2', 'm1'],\n", "\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_symbol():\n", " global symbols, pause_trading, periods_dict\n", " pricemovement = {}\n", "\n", " for s in symbols:\n", " items = mt.symbol_info(s)\n", " pricemovement[s] = round(items.price_change,2)\n", " #print(s, round(items.price_change,2))\n", "\n", " #percentage = pricemovement[max(pricemovement, key=pricemovement.get)]\n", " #symbol = max(pricemovement, key=pricemovement.get)\n", " #volume = volume_dict[symbol]\n", "\n", " sorted_pricemovement = sorted(pricemovement.items(), key=lambda x:x[1], reverse=True)\n", " converted_dict = dict(sorted_pricemovement)\n", "\n", " print(converted_dict)\n", "\n", " percentage = converted_dict[max(converted_dict, key=converted_dict.get)]\n", " symbol = max(converted_dict, key=converted_dict.get)\n", " volume = volume_dict[symbol]\n", "\n", "\n", " print(symbol, percentage, volume)\n", " # if percentage > 0: # and percentage < 0.8:\n", " # periods_dict[symbol] = ['m15', 'm5', 'm2', 'm1']\n", " # elif percentage > 0.8:\n", " # periods_dict[symbol] = ['h1', 'm30', 'm15', 'm5', 'm1']\n", "\n", " #\n", "\n", " #print(periods_dict)\n", "\n", " # if percentage > 0 and mt.positions_total() == 0:\n", " # pause_trading = 0 #0 no puase\n", " # return symbol, percentage, volume, periods_dict\n", " # elif percentage < 0.1 and mt.positions_total() == 0:\n", " # print(\"aktuell kein neues Symbol, pause Trading\")\n", " # pause_trading = 1 #1 pause\n", " # return None\n", "\n", " return symbol, percentage, volume, periods_dict" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "get_symbol()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def set_symbol():\n", " global symbol, volume, volume_dict\n", " symb = get_symbol()\n", " if symb != None:\n", " symbol = symb[0]\n", " volume = volume_dict[symb[0]]\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## set volume manuell" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "get_symbol()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "set_symbol()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pause_trading = 0\n", "symbol, volume, pause_trading" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "symbol = 'XAUUSD'\n", "volume = 0.1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions to place Orders on Market" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pos = mt.positions_get()\n", "for i in pos:\n", " #if i.comment == 'Retracement Bot':\n", " # print(i.ticket)\n", "\n", " if bool(re.search('^BuyStop[0-9]{2}', i.comment)):\n", " print(i.ticket)\n", "\n", "mt.positions_total()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "strategy_name = 'Retracement Bot'\n", "pos = mt.positions_get()\n", "for p in pos:\n", " if p.comment == strategy_name:\n", " print(p.comment)\n", "print(pos)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "buypos = ['True', 'False', 'False']\n", "'True' not in buypos\n", "\n", "buypos.count('True')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Market Order Function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#market_order(symbol, volume_dict[symbol], 'buy')\n", "request = {\n", " \"action\": mt.TRADE_ACTION_DEAL,\n", " \"symbol\": symbol,\n", " \"volume\": volume, # FLOAT\n", " \"type\": mt.ORDER_TYPE_BUY,\n", " \"price\": mt.symbol_info_tick(symbol).ask,\n", " \"sl\": 0.0, # FLOAT\n", " \"tp\": 0.0, # FLOAT\n", " \"deviation\": 20, # INTERGER\n", " \"magic\": 30, # INTERGER\n", " \"comment\": 'Retracement Bot',\n", " \"type_time\": mt.ORDER_TIME_GTC,\n", " \"type_filling\": mt.ORDER_FILLING_IOC, # mt.ORDER_FILLING_FOK if IOC does not work\n", " }\n", "\n", "order_result = mt.order_send(request)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def market_order(symbol, volume, order_type, deviation=20, magic=30, stoploss=0.0, take_profit=0.0,\n", " strategy_name='Retracement Bot'):\n", "\n", " global project, pause_trading\n", "\n", " project_id_dict = {\n", " 'trading-demo': 'a3f3ae',\n", " 'trading-live': '747543'\n", " }\n", "\n", " order_type_dict = {\n", " 'buy': mt.ORDER_TYPE_BUY,\n", " 'sell': mt.ORDER_TYPE_SELL\n", " }\n", "\n", " price_dict = {\n", " 'buy': mt.symbol_info_tick(symbol).ask,\n", " 'sell': mt.symbol_info_tick(symbol).bid\n", " }\n", "\n", " buypos = []\n", "\n", " pos = mt.positions_get()\n", " for p in pos:\n", " if p.comment == strategy_name:\n", " buypos.append('true')\n", " \n", " activepos = buypos.count('true')\n", "\n", " if order_type == 'buy' and activepos == 0 and pause_trading == 0: # and mt.positions_total() == 0:\n", " \n", " request = {\n", " \"action\": mt.TRADE_ACTION_DEAL,\n", " \"symbol\": symbol,\n", " \"volume\": volume, # FLOAT\n", " \"type\": order_type_dict[order_type],\n", " \"price\": price_dict[order_type],\n", " \"sl\": stoploss, # FLOAT\n", " \"tp\": take_profit, # FLOAT\n", " \"deviation\": deviation, # INTERGER\n", " \"magic\": magic, # INTERGER\n", " \"comment\": strategy_name,\n", " \"type_time\": mt.ORDER_TIME_GTC,\n", " \"type_filling\": mt.ORDER_FILLING_IOC, # mt.ORDER_FILLING_FOK if IOC does not work\n", " }\n", "\n", " requests.post('https://api.mynotifier.app', {\n", " \"apiKey\": 'beafb52e-3cb6-477a-92ef-2f10bff50e20',\n", " \"message\": \"Es wrude ein Handel eröffnet!\",\n", " \"description\": \"Bitte kontrolliere die Position\",\n", " \"type\": \"info\",#\"info\", # info, error, warning or success\n", " \"project\": project_id_dict[project]\n", " })\n", "\n", " order_result = mt.order_send(request)\n", " #return (order_result)\n", " \n", " elif order_type == 'sell' and mt.positions_total() > 0:\n", " pos = mt.positions_get()\n", " for p in pos:\n", " if p.comment == strategy_name:\n", " # while schleife ?\n", " positions = mt.positions_get()\n", " ticket = p.ticket\n", " request = {\n", " \"action\": mt.TRADE_ACTION_DEAL,\n", " \"symbol\": symbol,\n", " \"volume\": volume, # FLOAT\n", " \"type\": order_type_dict[order_type],\n", " \"price\": price_dict[order_type],\n", " \"position\": ticket,\n", " \"sl\": stoploss, # FLOAT\n", " \"tp\": take_profit, # FLOAT\n", " \"deviation\": deviation, # INTERGER\n", " \"magic\": magic, # INTERGER\n", " \"comment\": strategy_name,\n", " \"type_time\": mt.ORDER_TIME_GTC,\n", " \"type_filling\": mt.ORDER_FILLING_IOC, # mt.ORDER_FILLING_FOK if IOC does not work\n", " }\n", "\n", " requests.post('https://api.mynotifier.app', {\n", " \"apiKey\": 'beafb52e-3cb6-477a-92ef-2f10bff50e20',\n", " \"message\": \"Es wrude ein Handel geschlossen!\",\n", " \"description\": \"Bitte prüfe die Position\",\n", " \"type\": \"info\",#\"info\", # info, error, warning or success\n", " \"project\": project_id_dict[project]\n", " })\n", "\n", " order_result = mt.order_send(request)\n", " #return (order_result)\n", "\n", "\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Retracement - SL TP Function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_sltp():\n", " ohlc = mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_M5, 0, 50)\n", " df = pd.DataFrame(ohlc)\n", " df['time']=pd.to_datetime(df['time'], unit='s')\n", "\n", " support = df[df.low == df.low.rolling(5, center=True).min()].low\n", " resistance = df[df.high == df.high.rolling(5, center=True).max()].high\n", " df['resistance'] = resistance\n", " df['support'] = support\n", " df.support.fillna(0, inplace=True)\n", " df.resistance.fillna(0, inplace=True)\n", " df = df[(df.support != 0) | (df.resistance != 0)]\n", "\n", " tp = df.resistance.loc[df['resistance'] != 0]\n", " tp = round(tp.mean(), 2)\n", "\n", " sl = df.support.loc[df['support'] != 0]\n", " sl = round (sl.mean(), 2)\n", "\n", " return tp, sl\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Manuell TPSL" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tpsl = get_sltp()\n", "tpsl[0] - tpsl[1] " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Support Resistance Buy Sell Function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_supres_signal(period: str):\n", "\n", "\n", " ohlc = mt.copy_rates_from_pos(symbol, timeframes_dict[period], 0, 50)\n", " df = pd.DataFrame(ohlc)\n", " df['time']=pd.to_datetime(df['time'], unit='s')\n", "\n", " support = df[df.low == df.low.rolling(5, center=True).min()].low\n", " resistance = df[df.high == df.high.rolling(5, center=True).max()].high\n", " df['ma3'] = df['close'].rolling(3).mean()\n", " df['resistance'] = resistance\n", " df['support'] = support\n", " df.support.fillna(0, inplace=True)\n", " df.resistance.fillna(0, inplace=True)\n", " df = df[(df.support != 0) | (df.resistance != 0)]\n", "\n", " if df.resistance.iloc[-1] != 0:\n", " signal = 'sell'\n", " print(f'sell at: {df.resistance.iloc[-1]}')\n", " elif df.support.iloc[-1] !=0:\n", " signal = 'buy'\n", " print(f'buy at: {df.support.iloc[-1]}')\n", "\n", " return signal\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "get_supres_signal('m30')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get SMA Buy Sell Function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Versions 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_sma_signal():\n", " sma = mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_M5, 0, 120)\n", " df = pd.DataFrame(sma)\n", " df['time']=pd.to_datetime(df['time'], unit='s')\n", " df['ma5'] = df['close'].rolling(3).mean()\n", " df['ma10'] = df['close'].rolling(15).mean()\n", " df['diff5'] = df['ma5'].diff()\n", "\n", " support = df[df.low == df.low.rolling(5, center=True).min()].low\n", " resistance = df[df.high == df.high.rolling(5, center=True).max()].high\n", " df['resistance'] = resistance\n", " df['support'] = support\n", " df.support.fillna(0, inplace=True)\n", " df.resistance.fillna(0, inplace=True)\n", " df.dropna()\n", " df = df[['time','open', 'close', 'low', 'ma5', 'ma10', 'diff5', 'resistance', 'support']]\n", "\n", " buy = []\n", " sell = []\n", "\n", " for i in range (len(df)):\n", " if df.ma5.iloc[i] > df.ma10.iloc[i]: #and df.ma5[i-1] < df.ma10.iloc[i-1]:\n", " buy.append(i)\n", " elif df.ma5.iloc[i] < df.ma10.iloc[i]: #and df.ma5[i-1] > df.ma10.iloc[i-1]:\n", " sell.append(i)\n", "\n", " buy, sell\n", "\n", " df['buy'] = 0\n", " df['sell'] = 0\n", "\n", " for b in buy:\n", " df.at[b,'buy'] = 1\n", "\n", " for s in sell:\n", " df.at[s,'sell'] = 1\n", "\n", " # if df.buy.iloc[-1] == 1:\n", " # signal = 'buy'\n", " \n", " # elif df.sell.iloc[-1] == 1:\n", " # signal = 'sell'\n", " # else:\n", " # signal = 'none'\n", "\n", " if df.diff5.tail(12).sum() > 0 and df.buy.iloc[-1] == 1:\n", " #print('buy', df.diff5.tail(12).sum())\n", " signal = 'buy'\n", " else:\n", " #print('sell')\n", " signal = 'sell'\n", " if df.diff5.tail(5).sum() > 0 and df.buy.iloc[-1] == 1:\n", " #print('buy', df.diff5.tail(5).sum())\n", " signal = 'buy'\n", " else:\n", " #print('sell')\n", " signal = 'sell'\n", " if df.diff5.tail(3).sum() > 0 and df.buy.iloc[-1] == 1:\n", " #print('buy', df.diff5.tail(3).sum())\n", " signal = 'buy'\n", " else:\n", " #print('sell')\n", " signal = 'sell'\n", " if df.diff5.tail(2).sum() > 0 and df.buy.iloc[-1] == 1:\n", " #print('buy', df.diff5.tail(2).sum())\n", " signal = 'buy'\n", " else:\n", " print('sell')\n", " signal = 'sell'\n", "\n", " return signal\n", "\n", " \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### get SMA manuell" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "signal = get_sma_signal()\n", "signal" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plot SMA Function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def sma_plot():\n", " plt.figure(figsize=(12,5))\n", " plt.plot(df['close'], label='Asset Price', c='blue', alpha=0.5)\n", " plt.plot(df['ma5'], label='MA5', c='r', alpha=0.9)\n", " plt.plot(df['ma10'], label='MA10', c='y', alpha=0.9)\n", " plt.scatter(df[df.buy == 1].index, df[df.buy == 1]['close'], marker='^', color='g', s=100)\n", " plt.scatter(df[df.sell == 1].index, df[df.sell == 1]['close'], marker='v', color='r', s=100)\n", " plt.legend()\n", " plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sma_plot()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Version 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sma = mt.copy_rates_from_pos(symbol,mt.TIMEFRAME_M1, 0, 60)\n", "df = pd.DataFrame(sma)\n", "#df = df[:-1]\n", "# Identify rows with out of bounds datetime values using errors='coerce'\n", "#nvalid_dates = df[pd.to_datetime(df['time'], errors='coerce')]\n", "# print(invalid_dates)\n", "df['time'] = pd.to_datetime(df['time'], unit='s')\n", "#df = df.head(58)\n", "#df['time']=pd.to_datetime(df['time'], unit='s')\n", "df.tail()\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_sma(period: str):\n", "\n", " global timeframes_dict\n", " sma = mt.copy_rates_from_pos(symbol,timeframes_dict[period] , 0, 120)\n", " df = pd.DataFrame(sma)\n", " #df = df[:-1]\n", " df['time']=pd.to_datetime(df['time'], unit='s')\n", " df['ma5'] = df['close'].rolling(3).mean()\n", " df['ma10'] = df['close'].rolling(15).mean()\n", " df['diff5'] = df['ma5'].diff()\n", " df['diff10'] = df['ma10'].diff()\n", " df['ema'] = df['close'].ewm(span=14, adjust=False).mean()\n", "\n", "\n", " # support = df[df.low == df.low.rolling(5, center=True).min()].low\n", " # resistance = df[df.high == df.high.rolling(5, center=True).max()].high\n", " # df['resistance'] = resistance\n", " # df['support'] = support\n", " # df.support.fillna(0, inplace=True)\n", " # df.resistance.fillna(0, inplace=True)\n", " # df.dropna()\n", " df = df[['time','open', 'close', 'low', 'ma5', 'ma10', 'ema','diff5', 'diff10']]\n", " # 'resistance', 'support'\n", "\n", " buy = []\n", " sell = []\n", "\n", " for i in range (len(df)):\n", " if df.ma5.iloc[i] > df.ema.iloc[i]: #and df.ma5[i-1] < df.ema.iloc[i-1]:\n", " buy.append(i)\n", " elif df.ma5.iloc[i] < df.ema.iloc[i]: #and df.ma5[i-1] > df.ma10.iloc[i-1]:\n", " sell.append(i)\n", "\n", " buy, sell\n", "\n", " df['buy'] = 0\n", " df['sell'] = 0\n", "\n", " for b in buy:\n", " df.at[b,'buy'] = 1\n", "\n", " for s in sell:\n", " df.at[s,'sell'] = 1\n", "\n", "\n", " #df = df.head(26)\n", " return df\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "get_sma('m15')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Daily Movement" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df_daily = mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_D1, 0, 30)\n", "df_days = pd.DataFrame(df_daily)\n", "df_days['time'] = pd.to_datetime(df_days['time'], unit='s')\n", "round(df_days.close.iloc[-1] / df_days.open.iloc[-1],2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "periods_dict[symbol]\n", "get_sma('m15')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Decide Order Function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "periods_dict[symbol]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def decide_order():\n", "\n", " global symbol, volume_dict, periods_dict\n", " \n", "\n", " ## SMA Version 2\n", " tsignals = periods_dict[symbol]\n", " signals = []\n", "\n", " for ts in tsignals:\n", " sma_signals = get_sma(ts)\n", "\n", " supress_signal = get_supres_signal(ts)\n", " print(f\"surpress Signal: {supress_signal}\")\n", " signals.append(supress_signal)\n", " \n", " if sma_signals.buy.iloc[-1] == 1: #sma_signals.diff5.tail(2).sum() > 0: \n", " print(ts, 'buy', sma_signals.diff5.tail(2).sum(), sma_signals.diff10.tail(2).sum())\n", " signals.append('buy')\n", " else:\n", " print(ts, 'sell', sma_signals.diff5.tail(2).sum(), sma_signals.diff10.tail(2).sum())\n", " signals.append('sell')\n", "\n", " \n", "\n", " cbuy = signals.count('buy')\n", " csell = signals.count('sell')\n", " print(f\"Buy: {cbuy} | Sell: {csell}\")\n", "\n", " if cbuy > csell:\n", " signal = 'buy'\n", " print(signal)\n", " else:\n", " signal = 'sell'\n", " print(signal)\n", "\n", "\n", "\n", " if signal == 'buy':\n", " market_order(symbol, volume_dict[symbol], \"buy\") #, stoploss=sl, take_profit=tp)\n", " #print(\"buy at {} am {} \".format(df.support.iloc[-1], df.time.iloc[-1]))\n", " elif signal == 'sell':\n", " market_order(symbol, volume_dict[symbol], \"sell\")\n", " # print(\"sell at {} am {}\".format(df.resistance.iloc[-1], df.time.iloc[-1]))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "symbol" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "market_order(symbol, 0.1, \"buy\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Manuelle Ausführung" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "decide_order()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#if df['support'].iloc[-1] != 0:\n", "#market_order(symbol, volume, \"buy\")\n", "# print(\"buy at {} am {} \".format(df['support'].iloc[-1], df['time'].iloc[-1]))\n", "# elif df['resistance'].iloc[-1] != 0:\n", "#market_order(symbol, volume, \"sell\")\n", "# print(\"sell at {} am {}\".format(df['resistance'].iloc[-1], df['time'].iloc[-1]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Pause Trading" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pause_trading" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pause_trading = 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Trend Detection" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trend_dict = {\n", " 'm5': '',\n", " 'm15': '',\n", " #'m30': '',\n", "}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "timeframes_dict = {\n", " 'm1': mt.TIMEFRAME_M1,\n", " 'm2': mt.TIMEFRAME_M2,\n", " 'm3': mt.TIMEFRAME_M3,\n", " 'm5': mt.TIMEFRAME_M5,\n", " 'm15': mt.TIMEFRAME_M15,\n", " 'm20': mt.TIMEFRAME_M20,\n", " 'm30': mt.TIMEFRAME_M30,\n", " 'h1': mt.TIMEFRAME_H1,\n", "}\n", "\n", "\n", "# timeframes = {\n", "# 'm1': mt.TIMEFRAME_M1,\n", "# 'm2': mt.TIMEFRAME_M2,\n", "# 'm3': mt.TIMEFRAME_M3,\n", "# 'm5': mt.TIMEFRAME_M5,\n", "# 'm15': mt.TIMEFRAME_M15,\n", "# 'm20': mt.TIMEFRAME_M20,\n", "# 'm30': mt.TIMEFRAME_M30,\n", "# 'h1': mt.TIMEFRAME_H1,\n", "# }" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(trend_dict)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_rates(periode):\n", "\n", " global symbol\n", "\n", " ohlc = mt.copy_rates_from_pos(symbol, timeframes_dict[periode], 0, 200)\n", " df = pd.DataFrame(ohlc)\n", " df['time']=pd.to_datetime(df['time'], unit='s')\n", "\n", " #df = df[[\"time\",\"open\",\"high\",\"low\",\"close\"]]\n", "\n", " df[\"open\"] = df.open.astype(float)\n", " df[\"high\"] = df.high.astype(float)\n", " df[\"low\"] = df.low.astype(float)\n", " df[\"close\"] = df.close.astype(float)\n", "\n", " ## Take the rolling atr so the yaxis doesn't shake too much \n", " df[\"atr\"] = ta.atr(high=df.high, low=df.low, close=df.close)\n", " df[\"atr\"] = df.atr.rolling(window=30).mean()\n", "\n", "\n", " df.set_index(\"time\", inplace = True)\n", "\n", " return df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_trend(period):\n", "\n", " global trend_dict, periods_dict, symbol\n", "\n", " #current_periods = periods_dict[symbol][0]\n", "\n", " df2 = get_rates(period)\n", "\n", " df2[\"close_smooth\"] = savgol_filter(df2.close, 49, 5)\n", "\n", " fig, ax = plt.subplots()\n", " plt.xticks(rotation=-30)\n", " price, = ax.plot(df2.index, df2.close, c='grey', lw=2, alpha=0.5, zorder=5)\n", " price_smooth, = ax.plot(df2.index, df2.close_smooth, c='b', lw=2, zorder=5)\n", "\n", " atr = df2.atr.iloc[-1] # all the first atrs are NaN\n", "\n", " peaks_idx, _ = find_peaks(df2.close_smooth, distance = 15, \n", " width = 3, prominence=atr)\n", "\n", " troughs_idx, _ = find_peaks(-1*df2.close_smooth, distance = 15, \n", " width = 3, prominence=atr)\n", "\n", " peaks, = ax.plot(df2.index[peaks_idx], df2.close_smooth.iloc[peaks_idx], \\\n", " c=\"r\", linestyle='None', markersize = 10.0, marker = \"o\", zorder=10)\n", "\n", " troughs, = ax.plot(df2.index[troughs_idx], df2.close_smooth.iloc[troughs_idx], \\\n", " c=\"g\", linestyle='None', markersize = 10.0, marker = \"o\", zorder=10)\n", "\n", " plt.show()\n", "\n", " #print(peaks_idx[-1], troughs_idx[-1])\n", "\n", " if peaks_idx[-1] > troughs_idx[-1]:\n", " print(\"downtrend\")\n", "\n", " trend_dict[period] = 'downtrend'\n", " else:\n", " print(\"uptrend\")\n", "\n", " trend_dict[period] = 'uptrend'\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def set_trend():\n", "\n", " global pause_trading, periods_dict, trend_dict\n", "\n", " for k,v in trend_dict.items():\n", " get_trend(k) \n", " print(k)\n", " \n", " for k,v in reversed(trend_dict.items()):\n", "\n", " if v == 'uptrend':\n", " print(k,v)\n", " periods_dict[symbol] = [k]\n", " pause_trading = 0\n", " break\n", " elif v == 'downtrend':\n", " periods_dict[symbol] = [k] #['m15']\n", " pause_trading = 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Set Trend manually" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pause_trading, trend_dict, periods_dict" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "set_trend()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trend_dict" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "periods_dict[symbol], pause_trading" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Job-Scheduler\n", "\n", "[Doku Appscheduler Cronjob](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/cron.html#id0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from apscheduler.schedulers.background import BackgroundScheduler\n", "import time\n", "\n", "\n", "scheduler = BackgroundScheduler()\n", "#scheduler.add_job(main, 'date', run_date='2025-03-07 14:29:50')\n", "\n", "#scheduler.add_job(decide_order, 'interval', minutes=1) #intervall\n", "scheduler.add_job(set_symbol, 'interval', minutes=30)\n", "scheduler.add_job(set_trend, 'interval', minutes=1)\n", "\n", "scheduler.add_job(decide_order, 'cron', year=\"*\", month=\"*\", day_of_week=\"mon, tue, wed, thu, fri\", hour='0-23', minute='*') #cron\n", "\n", "#scheduler.add_job(export_marketview, 'cron', year=\"*\", month='*', day_of_week='mon, tue, wed; thu, fri', hour='8-22', minute=00)\n", "\n", "#scheduler.add_job(pause_trading, 'cron', year=\"*\", month=\"*\", day_of_week=\"mon, tue, wed, thu, fri\", hour=22, minute=00) #cron\n", "scheduler.start()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Get Jobs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scheduler.get_jobs()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Remove all Jobs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scheduler.remove_all_jobs()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Shutdown AppScheduler" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scheduler.shutdown()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Development Stuff" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## SMA 5 and 10" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def get_sma_dev(period: str):\n", "\n", " timeframes = {\n", " 'm1': mt.TIMEFRAME_M1,\n", " 'm2': mt.TIMEFRAME_M2,\n", " 'm3': mt.TIMEFRAME_M3,\n", " 'm5': mt.TIMEFRAME_M5,\n", " 'm15': mt.TIMEFRAME_M15,\n", " 'm20': mt.TIMEFRAME_M20,\n", " 'm30': mt.TIMEFRAME_M30\n", " }\n", "\n", "\n", " sma = mt.copy_rates_from_pos(symbol,timeframes[period] , 0, 120)\n", " df = pd.DataFrame(sma)\n", " df['time']=pd.to_datetime(df['time'], unit='s')\n", " df['ma5'] = df['close'].rolling(3).mean()\n", " df['ma10'] = df['close'].rolling(15).mean()\n", " df['diffclose'] = df['close'].diff()\n", " df['diff5'] = df['ma5'].diff()\n", " df['diff10'] = df['ma10'].diff()\n", " df['ema'] = df['close'].ewm(span=14, adjust=False).mean()\n", "\n", "\n", " support = df[df.low == df.low.rolling(5, center=True).min()].low\n", " resistance = df[df.high == df.high.rolling(5, center=True).max()].high\n", " df['resistance'] = resistance\n", " df['support'] = support\n", " df.support.fillna(0, inplace=True)\n", " df.resistance.fillna(0, inplace=True)\n", " df.dropna()\n", " df = df[['time','open', 'close', 'low', 'ma5', 'ma10', 'diffclose','diff5', 'diff10', 'ema', 'resistance', 'support']]\n", "\n", " buy = []\n", " sell = []\n", "\n", " for i in range (len(df)):\n", " if df.ma5.iloc[i] > df.ema.iloc[i]: #and df.ma5[i-1] < df.ma10.iloc[i-1]:\n", " buy.append(i)\n", " elif df.ma5.iloc[i] < df.ema.iloc[i]: #and df.ma5[i-1] > df.ma10.iloc[i-1]:\n", " sell.append(i)\n", "\n", " buy, sell\n", "\n", " df['buy'] = 0\n", " df['sell'] = 0\n", "\n", " for b in buy:\n", " df.at[b,'buy'] = 1\n", "\n", " for s in sell:\n", " df.at[s,'sell'] = 1\n", "\n", "\n", " #df = df.head(26)\n", " return df\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sma = get_sma_dev('m15')\n", "sma.tail(50)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "periods_dict['XAUUSD']\n", "sma.close.tail(10)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tsignals = ['m30', 'm15', 'm5', 'm1']\n", "signals = []\n", "\n", "for ts in tsignals:\n", " sma_signals = get_sma(ts)\n", " if sma_signals.diff5.tail(2).sum() > 0: # and sma_signals.buy.iloc[-1] == 1:\n", " print(ts, 'buy', sma_signals.diff5.tail(2).sum(), sma_signals.diff10.tail(2).sum())\n", " signals.append('buy')\n", " else:\n", " print(ts, 'sell', sma_signals.diff5.tail(2).sum(), sma_signals.diff10.tail(2).sum())\n", " signals.append('sell')\n", "\n", "cbuy = signals.count('buy')\n", "csell = signals.count('sell')\n", "\n", "if cbuy > csell:\n", " signal = 'buy'\n", " print(cbuy)\n", "\n", "else:\n", " signal = 'sell'\n", " print(csell)\n", "\n", "\n", "signal\n", "# sma_signals = get_sma('m15')\n", "# df = sma_signals" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if df.diff5.tail(12).sum() > 0 and df.diff10.tail(12).sum() > 0 and df.buy.iloc[-1] == 1:\n", " print('buy', df.diff5.tail(12).sum(), df.diff10.tail(12).sum())\n", "else:\n", " print('sell', df.diff5.tail(12).sum(), df.diff10.tail(12).sum())\n", "if df.diff5.tail(6).sum() > 0 and df.diff10.tail(6).sum() > 0 and df.buy.iloc[-1] == 1:\n", " print('buy', df.diff5.tail(6).sum(), df.diff10.tail(6).sum())\n", "else:\n", " print('sell', df.diff5.tail(6).sum(), df.diff10.tail(6).sum())\n", "if df.diff5.tail(3).sum() > 0 and df.diff10.tail(3).sum() > 0 and df.buy.iloc[-1] == 1:\n", " print('buy', df.diff5.tail(3).sum(), df.diff10.tail(3).sum())\n", "else:\n", " print('sell', df.diff5.tail(3).sum(), df.diff10.tail(3).sum())\n", "if df.diff5.tail(2).sum() > 0 and df.diff10.tail(2).sum() > 0 and df.buy.iloc[-1] == 1:\n", " print('buy', df.diff5.tail(2).sum(), df.diff10.tail(2).sum())\n", "else:\n", " print('sell', df.diff5.tail(2).sum(), df.diff10.tail(2).sum())\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = sma\n", "plt.figure(figsize=(12,5))\n", "plt.plot(df['close'], label='Asset Price', c='blue', alpha=0.5)\n", "plt.plot(df['ma5'], label='MA5', c='r', alpha=0.9)\n", "plt.plot(df['ma10'], label='MA10', c='y', alpha=0.9)\n", "plt.plot(df['ema'], label='EMA', c='green', alpha=0.9)\n", "plt.scatter(df[df.buy == 1].index, df[df.buy == 1]['close'], marker='^', color='g', s=100)\n", "plt.scatter(df[df.sell == 1].index, df[df.sell == 1]['close'], marker='v', color='r', s=100)\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "close_diff = df.close.loc[df['close'] != 0]\n", "close_diff.diff().max(), close_diff.diff().min()\n", "close_diff.diff()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### get Signal from SMA" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if df.buy.iloc[-1] == 1:\n", " signal = 'buy'\n", "elif df.sell.iloc[-1] == 1:\n", " signal = 'sell'\n", "else:\n", " signal = 'none'\n", "\n", "signal" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Support Resistance Timeframe" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ohlc = mt.copy_rates_from_pos(symbol, mt.TIMEFRAME_M15, 0, 120)\n", "df = pd.DataFrame(ohlc)\n", "df['time']=pd.to_datetime(df['time'], unit='s')\n", "\n", "support = df[df.low == df.low.rolling(5, center=True).min()].low\n", "resistance = df[df.high == df.high.rolling(5, center=True).max()].high\n", "df['ma3'] = df['close'].rolling(3).mean()\n", "df['resistance'] = resistance\n", "df['support'] = support\n", "df.support.fillna(0, inplace=True)\n", "df.resistance.fillna(0, inplace=True)\n", "df = df[(df.support != 0) | (df.resistance != 0)]\n", "df\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if df.resistance.iloc[-1] != 0:\n", " signal = 'sell'\n", " print(f'sell at: {df.resistance.iloc[-1]}')\n", "elif df.support.iloc[-1] !=0:\n", " signal = 'buy'\n", " print(f'buy at: {df.support.iloc[-1]}')\n", "else:\n", " signal = 'none'\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### plot resistance" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(12,5))\n", "plt.plot(df['close'], label='Asset Price', c='blue', alpha=0.5)\n", "plt.plot(df['ma3'], label='MA3', c='r', alpha=0.9)\n", "#plt.plot(df['ma10'], label='MA10', c='y', alpha=0.9)\n", "plt.scatter(df[df.support != 0].index, df[df.support != 0]['close'], marker='^', color='g', s=100)\n", "plt.scatter(df[df.resistance != 0].index, df[df.resistance != 0]['close'], marker='v', color='r', s=100)\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tp = df.resistance.loc[df['resistance'] != 0]\n", "tp = tp.mean()\n", "\n", "sl = df.support.loc[df['support'] != 0]\n", "sl = sl.mean()\n", "\n", "round(tp), (sl)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Get Trend from resistance" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# trend\n", "r = df.resistance.loc[df['resistance'] != 0]\n", "rlen = len(list(r)) -1\n", "rlast_value = list(r)[rlen]\n", "rfirst_value = list(r)[0]\n", "\n", "s = df.support.loc[df['support'] != 0]\n", "slen = len(list(s)) -1\n", "slast_value = list(s)[slen]\n", "sfirst_value = list(s)[0]\n", "\n", "\n", "if rfirst_value > rlast_value and sfirst_value > slast_value:\n", " print('Down Trend')\n", " trend = 'down'\n", "else:\n", " print('Up Trend')\n", " trend = 'up'\n", "\n", "abs(rfirst_value - rlast_value)\n", "abs(sfirst_value - slast_value)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#take profit\n", "\n", "levels = pd.concat([support, resistance])\n", "lmax = levels.diff().max()\n", "lmin = levels.diff().min()\n", "tp = round((lmax + lmin)/ 2,2)\n", "if tp < 1:\n", " tp = 1\n", "\n", "sl = tp\n", "\n", "tp, sl" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "levels = pd.concat([support, resistance])\n", "lmax = levels.diff().max()\n", "lmin = levels.diff().min()\n", "tp = round((lmax + lmin)/ 2,2)\n", "sl = tp\n", "\n", "tp, sl" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "lv_max = resistance\n", "lv_max.diff()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "diff_r = df.resistance.loc[df['resistance'] != 0]\n", "diff_r.diff().mean()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "last_resistance = df.resistance.loc[df['resistance'] != 0]\n", "llr = len(list(last_resistance)) - 1\n", "llr_value = list(last_resistance)[llr]\n", "\n", "last_support = df.support.loc[df['support'] != 0]\n", "lls = len(list(last_support)) - 1\n", "lls_value = list(last_support)[lls]\n", "\n", "tp = round(llr_value - lls_value)\n", "tp" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if df.support.iloc[-1] != 0:\n", " print(df.support.iloc[-1], \"Buy\")\n", "elif df.resistance.iloc[-1] != 0:\n", " print(df.resistance.iloc[-1], \"Sell\")\n", " # Minuszahen sollen sich alle auf die letzte Nummer -1 beziehen, das ist nur ein Beispiel, abhängig vom Datensatz\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "support = df.loc[df['support'] != 0]\n", "resistance = df.loc[df['resistance'] != 0]\n", "levels = pd.concat([support, resistance])\n", "#lv_max = levels.diff().max()\n", "#lv_min = abs(levels.diff().min())\n", "levels.diff()\n", "#levels = levels[abs(levels.diff()) > 4]\n", "#levels\n", "#print(lv_max - lv_min)\n", "#levels" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mpf.plot(df, type='candle', style='charles')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df.close.plot()\n", "df.high.plot()\n", "df.low.plot()\n", "plt.hlines(df, xmin=df.support, xmax=df.resistance,\n", " colors='red')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 2 }